@atproto/pds 0.5.33 → 0.5.34

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 CHANGED
@@ -1,5 +1,24 @@
1
1
  # @atproto/pds
2
2
 
3
+ ## 0.5.34
4
+
5
+ ### Patch Changes
6
+
7
+ - [#5501](https://github.com/bluesky-social/atproto/pull/5501) [`09d0932`](https://github.com/bluesky-social/atproto/commit/09d09322f31947b1f559ca47047bca3da127e301) Thanks [@devinivy](https://github.com/devinivy)! - `registerPush`, `unregisterPush` and `createReport` now issue their outbound
8
+ call through the PDS's default `safeFetch`
9
+
10
+ - [#5504](https://github.com/bluesky-social/atproto/pull/5504) [`1ff43e6`](https://github.com/bluesky-social/atproto/commit/1ff43e6e592b1c3ac44e9cd5585370063035a90d) Thanks [@devinivy](https://github.com/devinivy)! - Resolve identities through the PDS's existing `safeFetch`.
11
+
12
+ - [#5502](https://github.com/bluesky-social/atproto/pull/5502) [`ac0989b`](https://github.com/bluesky-social/atproto/commit/ac0989bf9e16affd4aa919df8609b12f4ee8cd65) Thanks [@devinivy](https://github.com/devinivy)! - Bound the decoded size of the upstream responses that the proxy buffers — error
13
+ bodies, and the read-after-write path — at `proxy.maxResponseSize`, which
14
+ previously bounded only the bytes read off the wire. A response that decodes
15
+ past the bound fails as an upstream error.
16
+ - Updated dependencies [[`1ff43e6`](https://github.com/bluesky-social/atproto/commit/1ff43e6e592b1c3ac44e9cd5585370063035a90d), [`ac0989b`](https://github.com/bluesky-social/atproto/commit/ac0989bf9e16affd4aa919df8609b12f4ee8cd65), [`f88aa58`](https://github.com/bluesky-social/atproto/commit/f88aa5842df9aba9f208a6073272b43ef9bd089d)]:
17
+ - @atproto/identity@0.5.13
18
+ - @atproto/oauth-provider@0.22.8
19
+ - @atproto-labs/fetch-node@0.4.0
20
+ - @atproto/lex@0.3.11
21
+
3
22
  ## 0.5.33
4
23
 
5
24
  ### Patch Changes
@@ -1 +1 @@
1
- {"version":3,"file":"registerPush.d.ts","sourceRoot":"","sources":["../../../../../src/api/app/bsky/notification/registerPush.ts"],"names":[],"mappings":"AAEA,OAAO,EAAuB,KAAK,MAAM,EAAE,MAAM,sBAAsB,CAAA;AAEvE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AAIxD,MAAM,CAAC,OAAO,WAAW,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,UAAU,QAmDvD"}
1
+ {"version":3,"file":"registerPush.d.ts","sourceRoot":"","sources":["../../../../../src/api/app/bsky/notification/registerPush.ts"],"names":[],"mappings":"AACA,OAAO,EAAuB,KAAK,MAAM,EAAE,MAAM,sBAAsB,CAAA;AAEvE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AAIxD,MAAM,CAAC,OAAO,WAAW,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,UAAU,QAkDvD"}
@@ -1,5 +1,4 @@
1
1
  import { getNotif } from '@atproto/identity';
2
- import { xrpc } from '@atproto/lex';
3
2
  import { InvalidRequestError } from '@atproto/xrpc-server';
4
3
  import { AuthScope } from '../../../../auth-scope.js';
5
4
  import { app } from '../../../../lexicons/index.js';
@@ -33,10 +32,9 @@ export default function (server, ctx) {
33
32
  return;
34
33
  }
35
34
  const notifEndpoint = await getEndpoint(ctx, serviceDid);
36
- await xrpc(notifEndpoint, app.bsky.notification.registerPush, {
37
- validateRequest: ctx.cfg.service.devMode,
38
- validateResponse: ctx.cfg.service.devMode,
39
- strictResponseProcessing: ctx.cfg.service.devMode,
35
+ await ctx
36
+ .safeClient(notifEndpoint)
37
+ .xrpc(app.bsky.notification.registerPush, {
40
38
  body,
41
39
  headers,
42
40
  });
@@ -1 +1 @@
1
- {"version":3,"file":"registerPush.js","sourceRoot":"","sources":["../../../../../src/api/app/bsky/notification/registerPush.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAC5C,OAAO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EACV,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,YAAY,CAAC,IAAI,CACxC,CAAA;YAED,IAAI,WAAW,CAAC,GAAG,KAAK,UAAU,EAAE,CAAC;gBACnC,MAAM,WAAW,CAAC,MAAM,CAAC,IAAI,CAC3B,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,YAAY,EAClC,IAAI,EACJ,EAAE,OAAO,EAAE,CACZ,CAAA;gBACD,OAAM;YACR,CAAC;YAED,MAAM,aAAa,GAAG,MAAM,WAAW,CAAC,GAAG,EAAE,UAAU,CAAC,CAAA;YAExD,MAAM,IAAI,CAAC,aAAa,EAAE,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,YAAY,EAAE;gBAC5D,eAAe,EAAE,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,OAAO;gBACxC,gBAAgB,EAAE,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,OAAO;gBACzC,wBAAwB,EAAE,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,OAAO;gBACjD,IAAI;gBACJ,OAAO;aACR,CAAC,CAAA;QACJ,CAAC;KACF,CAAC,CAAA;AACJ,CAAC;AAED,MAAM,WAAW,GAAG,KAAK,EAAE,GAAe,EAAE,UAAkB,EAAE,EAAE;IAChE,MAAM,GAAG,GAAG,MAAM,SAAS,CAAC,GAAG,EAAE,UAAU,CAAC,CAAA;IAC5C,MAAM,aAAa,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAA;IACnC,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,IAAI,mBAAmB,CAC3B,yDAAyD,UAAU,EAAE,CACtE,CAAA;IACH,CAAC;IACD,OAAO,aAAa,CAAA;AACtB,CAAC,CAAA","sourcesContent":["import { getNotif } from '@atproto/identity'\nimport { xrpc } from '@atproto/lex'\nimport { InvalidRequestError, type Server } from '@atproto/xrpc-server'\nimport { AuthScope } from '../../../../auth-scope.js'\nimport type { AppContext } from '../../../../context.js'\nimport { app } from '../../../../lexicons/index.js'\nimport { getDidDoc } from '../util/resolver.js'\n\nexport default function (server: Server, ctx: AppContext) {\n const { bskyAppView } = ctx\n if (!bskyAppView) return\n\n server.add(app.bsky.notification.registerPush, {\n auth: ctx.authVerifier.authorization({\n additional: [AuthScope.SignupQueued],\n authorize: () => {\n // @NOTE this endpoint predates generic service proxying but we want to\n // map the permission to the \"RPC\" scope for consistency. However, since\n // the service info is only available in the request body, we can't\n // assert permissions here.\n },\n }),\n handler: async ({ auth, input: { body } }) => {\n const { serviceDid } = body\n const { did } = auth.credentials\n\n if (auth.credentials.type === 'oauth') {\n auth.credentials.permissions.assertRpc({\n aud: `${serviceDid}#bsky_notif`,\n lxm: app.bsky.notification.registerPush.$lxm,\n })\n }\n\n const { headers } = await ctx.serviceAuthHeaders(\n did,\n serviceDid,\n app.bsky.notification.registerPush.$lxm,\n )\n\n if (bskyAppView.did === serviceDid) {\n await bskyAppView.client.call(\n app.bsky.notification.registerPush,\n body,\n { headers },\n )\n return\n }\n\n const notifEndpoint = await getEndpoint(ctx, serviceDid)\n\n await xrpc(notifEndpoint, app.bsky.notification.registerPush, {\n validateRequest: ctx.cfg.service.devMode,\n validateResponse: ctx.cfg.service.devMode,\n strictResponseProcessing: ctx.cfg.service.devMode,\n body,\n headers,\n })\n },\n })\n}\n\nconst getEndpoint = async (ctx: AppContext, serviceDid: string) => {\n const doc = await getDidDoc(ctx, serviceDid)\n const notifEndpoint = getNotif(doc)\n if (!notifEndpoint) {\n throw new InvalidRequestError(\n `invalid notification service details in did document: ${serviceDid}`,\n )\n }\n return notifEndpoint\n}\n"]}
1
+ {"version":3,"file":"registerPush.js","sourceRoot":"","sources":["../../../../../src/api/app/bsky/notification/registerPush.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAC5C,OAAO,EAAE,mBAAmB,EAAe,MAAM,sBAAsB,CAAA;AACvE,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAA;AAEr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AAC,MAAM,CAAC,IAAI,CAC3B,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,YAAY,EAClC,IAAI,EACJ,EAAE,OAAO,EAAE,CACZ,CAAA;gBACD,OAAM;YACR,CAAC;YAED,MAAM,aAAa,GAAG,MAAM,WAAW,CAAC,GAAG,EAAE,UAAU,CAAC,CAAA;YAExD,MAAM,GAAG;iBACN,UAAU,CAAC,aAAa,CAAC;iBACzB,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,YAAY,EAAE;gBACxC,IAAI;gBACJ,OAAO;aACR,CAAC,CAAA;QACN,CAAC;KACF,CAAC,CAAA;AACJ,CAAC;AAED,MAAM,WAAW,GAAG,KAAK,EAAE,GAAe,EAAE,UAAkB,EAAE,EAAE;IAChE,MAAM,GAAG,GAAG,MAAM,SAAS,CAAC,GAAG,EAAE,UAAU,CAAC,CAAA;IAC5C,MAAM,aAAa,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAA;IACnC,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,IAAI,mBAAmB,CAC3B,yDAAyD,UAAU,EAAE,CACtE,CAAA;IACH,CAAC;IACD,OAAO,aAAa,CAAA;AACtB,CAAC,CAAA","sourcesContent":["import { getNotif } from '@atproto/identity'\nimport { InvalidRequestError, type Server } from '@atproto/xrpc-server'\nimport { AuthScope } from '../../../../auth-scope.js'\nimport type { AppContext } from '../../../../context.js'\nimport { app } from '../../../../lexicons/index.js'\nimport { getDidDoc } from '../util/resolver.js'\n\nexport default function (server: Server, ctx: AppContext) {\n const { bskyAppView } = ctx\n if (!bskyAppView) return\n\n server.add(app.bsky.notification.registerPush, {\n auth: ctx.authVerifier.authorization({\n additional: [AuthScope.SignupQueued],\n authorize: () => {\n // @NOTE this endpoint predates generic service proxying but we want to\n // map the permission to the \"RPC\" scope for consistency. However, since\n // the service info is only available in the request body, we can't\n // assert permissions here.\n },\n }),\n handler: async ({ auth, input: { body } }) => {\n const { serviceDid } = body\n const { did } = auth.credentials\n\n if (auth.credentials.type === 'oauth') {\n auth.credentials.permissions.assertRpc({\n aud: `${serviceDid}#bsky_notif`,\n lxm: app.bsky.notification.registerPush.$lxm,\n })\n }\n\n const { headers } = await ctx.serviceAuthHeaders(\n did,\n serviceDid,\n app.bsky.notification.registerPush.$lxm,\n )\n\n if (bskyAppView.did === serviceDid) {\n await bskyAppView.client.call(\n app.bsky.notification.registerPush,\n body,\n { headers },\n )\n return\n }\n\n const notifEndpoint = await getEndpoint(ctx, serviceDid)\n\n await ctx\n .safeClient(notifEndpoint)\n .xrpc(app.bsky.notification.registerPush, {\n body,\n headers,\n })\n },\n })\n}\n\nconst getEndpoint = async (ctx: AppContext, serviceDid: string) => {\n const doc = await getDidDoc(ctx, serviceDid)\n const notifEndpoint = getNotif(doc)\n if (!notifEndpoint) {\n throw new InvalidRequestError(\n `invalid notification service details in did document: ${serviceDid}`,\n )\n }\n return notifEndpoint\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"unregisterPush.d.ts","sourceRoot":"","sources":["../../../../../src/api/app/bsky/notification/unregisterPush.ts"],"names":[],"mappings":"AAEA,OAAO,EAAuB,KAAK,MAAM,EAAE,MAAM,sBAAsB,CAAA;AACvE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AAIxD,MAAM,CAAC,OAAO,WAAW,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,UAAU,QA8CvD"}
1
+ {"version":3,"file":"unregisterPush.d.ts","sourceRoot":"","sources":["../../../../../src/api/app/bsky/notification/unregisterPush.ts"],"names":[],"mappings":"AACA,OAAO,EAAuB,KAAK,MAAM,EAAE,MAAM,sBAAsB,CAAA;AACvE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AAIxD,MAAM,CAAC,OAAO,WAAW,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,UAAU,QA6CvD"}
@@ -1,5 +1,4 @@
1
1
  import { getNotif } from '@atproto/identity';
2
- import { xrpc } from '@atproto/lex';
3
2
  import { InvalidRequestError } from '@atproto/xrpc-server';
4
3
  import { app } from '../../../../lexicons/index.js';
5
4
  import { getDidDoc } from '../util/resolver.js';
@@ -27,10 +26,9 @@ export default function (server, ctx) {
27
26
  return;
28
27
  }
29
28
  const notifEndpoint = await getEndpoint(ctx, serviceDid);
30
- await xrpc(notifEndpoint, app.bsky.notification.unregisterPush, {
31
- validateRequest: ctx.cfg.service.devMode,
32
- validateResponse: ctx.cfg.service.devMode,
33
- strictResponseProcessing: ctx.cfg.service.devMode,
29
+ await ctx
30
+ .safeClient(notifEndpoint)
31
+ .xrpc(app.bsky.notification.unregisterPush, {
34
32
  body,
35
33
  headers,
36
34
  });
@@ -1 +1 @@
1
- {"version":3,"file":"unregisterPush.js","sourceRoot":"","sources":["../../../../../src/api/app/bsky/notification/unregisterPush.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAA;AACnC,OAAO,EAAE,mBAAmB,EAAe,MAAM,sBAAsB,CAAA;AAEvE,OAAO,EAAE,GAAG,EAAE,MAAM,+BAA+B,CAAA;AACnD,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAA;AAE/C,MAAM,CAAC,OAAO,WAAW,MAAc,EAAE,GAAe;IACtD,MAAM,EAAE,WAAW,EAAE,GAAG,GAAG,CAAA;IAC3B,IAAI,CAAC,WAAW;QAAE,OAAM;IAExB,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,cAAc,EAAE;QAC/C,IAAI,EAAE,GAAG,CAAC,YAAY,CAAC,aAAa,CAAC;YACnC,UAAU,EAAE,EAAE;YACd,SAAS,EAAE,GAAG,EAAE,GAAE,CAAC;SACpB,CAAC;QACF,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,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E,GAAe,EAAE,UAAkB,EAAE,EAAE;IAChE,MAAM,GAAG,GAAG,MAAM,SAAS,CAAC,GAAG,EAAE,UAAU,CAAC,CAAA;IAC5C,MAAM,aAAa,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAA;IACnC,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,IAAI,mBAAmB,CAC3B,yDAAyD,UAAU,EAAE,CACtE,CAAA;IACH,CAAC;IACD,OAAO,aAAa,CAAA;AACtB,CAAC,CAAA","sourcesContent":["import { getNotif } from '@atproto/identity'\nimport { xrpc } from '@atproto/lex'\nimport { InvalidRequestError, type Server } from '@atproto/xrpc-server'\nimport type { AppContext } from '../../../../context.js'\nimport { app } from '../../../../lexicons/index.js'\nimport { getDidDoc } from '../util/resolver.js'\n\nexport default function (server: Server, ctx: AppContext) {\n const { bskyAppView } = ctx\n if (!bskyAppView) return\n\n server.add(app.bsky.notification.unregisterPush, {\n auth: ctx.authVerifier.authorization({\n additional: [],\n authorize: () => {},\n }),\n handler: async ({ auth, input: { body } }) => {\n const { serviceDid } = body\n const { did } = auth.credentials\n\n if (auth.credentials.type === 'oauth') {\n auth.credentials.permissions.assertRpc({\n aud: `${serviceDid}#bsky_notif`,\n lxm: app.bsky.notification.unregisterPush.$lxm,\n })\n }\n\n const { headers } = await ctx.serviceAuthHeaders(\n did,\n serviceDid,\n app.bsky.notification.unregisterPush.$lxm,\n )\n\n if (bskyAppView.did === serviceDid) {\n await bskyAppView.client.call(\n app.bsky.notification.unregisterPush,\n body,\n { headers },\n )\n return\n }\n\n const notifEndpoint = await getEndpoint(ctx, serviceDid)\n\n await xrpc(notifEndpoint, app.bsky.notification.unregisterPush, {\n validateRequest: ctx.cfg.service.devMode,\n validateResponse: ctx.cfg.service.devMode,\n strictResponseProcessing: ctx.cfg.service.devMode,\n body,\n headers,\n })\n },\n })\n}\n\nconst getEndpoint = async (ctx: AppContext, serviceDid: string) => {\n const doc = await getDidDoc(ctx, serviceDid)\n const notifEndpoint = getNotif(doc)\n if (!notifEndpoint) {\n throw new InvalidRequestError(\n `invalid notification service details in did document: ${serviceDid}`,\n )\n }\n return notifEndpoint\n}\n"]}
1
+ {"version":3,"file":"unregisterPush.js","sourceRoot":"","sources":["../../../../../src/api/app/bsky/notification/unregisterPush.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAC5C,OAAO,EAAE,mBAAmB,EAAe,MAAM,sBAAsB,CAAA;AAEvE,OAAO,EAAE,GAAG,EAAE,MAAM,+BAA+B,CAAA;AACnD,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAA;AAE/C,MAAM,CAAC,OAAO,WAAW,MAAc,EAAE,GAAe;IACtD,MAAM,EAAE,WAAW,EAAE,GAAG,GAAG,CAAA;IAC3B,IAAI,CAAC,WAAW;QAAE,OAAM;IAExB,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,cAAc,EAAE;QAC/C,IAAI,EAAE,GAAG,CAAC,YAAY,CAAC,aAAa,CAAC;YACnC,UAAU,EAAE,EAAE;YACd,SAAS,EAAE,GAAG,EAAE,GAAE,CAAC;SACpB,CAAC;QACF,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE;YAC3C,MAAM,EAAE,UAAU,EAAE,GAAG,IAAI,CAAA;YAC3B,MAAM,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,WAAW,CAAA;YAEhC,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;gBACtC,IAAI,CAAC,WAAW,CAAC,WAAW,CAAC,SAAS,CAAC;oBACrC,GAAG,EAAE,GAAG,UAAU,aAAa;oBAC/B,GAAG,EAAE,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,cAAc,CAAC,IAAI;iBAC/C,CAAC,CAAA;YACJ,CAAC;YAED,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,GAAG,CAAC,kBAAkB,CAC9C,GAAG,EACH,UAAU,EACV,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,cAAc,CAAC,IAAI,CAC1C,CAAA;YAED,IAAI,WAAW,CAAC,GAAG,KAAK,UAAU,EAAE,CAAC;gBACnC,MAAM,WAAW,CAAC,MAAM,CAAC,IAAI,CAC3B,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,cAAc,EACpC,IAAI,EACJ,EAAE,OAAO,EAAE,CACZ,CAAA;gBACD,OAAM;YACR,CAAC;YAED,MAAM,aAAa,GAAG,MAAM,WAAW,CAAC,GAAG,EAAE,UAAU,CAAC,CAAA;YAExD,MAAM,GAAG;iBACN,UAAU,CAAC,aAAa,CAAC;iBACzB,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,cAAc,EAAE;gBAC1C,IAAI;gBACJ,OAAO;aACR,CAAC,CAAA;QACN,CAAC;KACF,CAAC,CAAA;AACJ,CAAC;AAED,MAAM,WAAW,GAAG,KAAK,EAAE,GAAe,EAAE,UAAkB,EAAE,EAAE;IAChE,MAAM,GAAG,GAAG,MAAM,SAAS,CAAC,GAAG,EAAE,UAAU,CAAC,CAAA;IAC5C,MAAM,aAAa,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAA;IACnC,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,IAAI,mBAAmB,CAC3B,yDAAyD,UAAU,EAAE,CACtE,CAAA;IACH,CAAC;IACD,OAAO,aAAa,CAAA;AACtB,CAAC,CAAA","sourcesContent":["import { getNotif } from '@atproto/identity'\nimport { InvalidRequestError, type Server } from '@atproto/xrpc-server'\nimport type { AppContext } from '../../../../context.js'\nimport { app } from '../../../../lexicons/index.js'\nimport { getDidDoc } from '../util/resolver.js'\n\nexport default function (server: Server, ctx: AppContext) {\n const { bskyAppView } = ctx\n if (!bskyAppView) return\n\n server.add(app.bsky.notification.unregisterPush, {\n auth: ctx.authVerifier.authorization({\n additional: [],\n authorize: () => {},\n }),\n handler: async ({ auth, input: { body } }) => {\n const { serviceDid } = body\n const { did } = auth.credentials\n\n if (auth.credentials.type === 'oauth') {\n auth.credentials.permissions.assertRpc({\n aud: `${serviceDid}#bsky_notif`,\n lxm: app.bsky.notification.unregisterPush.$lxm,\n })\n }\n\n const { headers } = await ctx.serviceAuthHeaders(\n did,\n serviceDid,\n app.bsky.notification.unregisterPush.$lxm,\n )\n\n if (bskyAppView.did === serviceDid) {\n await bskyAppView.client.call(\n app.bsky.notification.unregisterPush,\n body,\n { headers },\n )\n return\n }\n\n const notifEndpoint = await getEndpoint(ctx, serviceDid)\n\n await ctx\n .safeClient(notifEndpoint)\n .xrpc(app.bsky.notification.unregisterPush, {\n body,\n headers,\n })\n },\n })\n}\n\nconst getEndpoint = async (ctx: AppContext, serviceDid: string) => {\n const doc = await getDidDoc(ctx, serviceDid)\n const notifEndpoint = getNotif(doc)\n if (!notifEndpoint) {\n throw new InvalidRequestError(\n `invalid notification service details in did document: ${serviceDid}`,\n )\n }\n return notifEndpoint\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"createReport.d.ts","sourceRoot":"","sources":["../../../../../src/api/com/atproto/moderation/createReport.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAA;AAElD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AAIxD,MAAM,CAAC,OAAO,WAAW,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,UAAU,QAiCvD"}
1
+ {"version":3,"file":"createReport.d.ts","sourceRoot":"","sources":["../../../../../src/api/com/atproto/moderation/createReport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAA;AAElD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AAIxD,MAAM,CAAC,OAAO,WAAW,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,UAAU,QA8BvD"}
@@ -1,4 +1,3 @@
1
- import { xrpc } from '@atproto/lex';
2
1
  import { AuthScope } from '../../../../auth-scope.js';
3
2
  import { com } from '../../../../lexicons/index.js';
4
3
  import { computeProxyTo, parseProxyInfo } from '../../../../pipethrough.js';
@@ -15,10 +14,7 @@ export default function (server, ctx) {
15
14
  handler: async ({ auth, params, input: { body }, req }) => {
16
15
  const { url, did: aud } = await parseProxyInfo(ctx, req, com.atproto.moderation.createReport.$lxm);
17
16
  const { headers } = await ctx.serviceAuthHeaders(auth.credentials.did, aud, com.atproto.moderation.createReport.$lxm);
18
- return xrpc(url, com.atproto.moderation.createReport, {
19
- validateRequest: ctx.cfg.service.devMode,
20
- validateResponse: ctx.cfg.service.devMode,
21
- strictResponseProcessing: ctx.cfg.service.devMode,
17
+ return ctx.safeClient(url).xrpc(com.atproto.moderation.createReport, {
22
18
  headers,
23
19
  params,
24
20
  body,
@@ -1 +1 @@
1
- {"version":3,"file":"createReport.js","sourceRoot":"","sources":["../../../../../src/api/com/atproto/moderation/createReport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAA;AAEnC,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAA;AAErD,OAAO,EAAE,GAAG,EAAE,MAAM,+BAA+B,CAAA;AACnD,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAA;AAE3E,MAAM,CAAC,OAAO,WAAW,MAAc,EAAE,GAAe;IACtD,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,EAAE;QAC9C,IAAI,EAAE,GAAG,CAAC,YAAY,CAAC,aAAa,CAAC;YACnC,UAAU,EAAE,CAAC,SAAS,CAAC,SAAS,CAAC;YACjC,SAAS,EAAE,CAAC,WAAW,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE;gBAClC,MAAM,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,IAAI,CAAA;gBACpD,MAAM,GAAG,GAAG,cAAc,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;gBACzC,WAAW,CAAC,SAAS,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAA;YACrC,CAAC;SACF,CAAC;QACF,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE;YACxD,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,MAAM,cAAc,CAC5C,GAAG,EACH,GAAG,EACH,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,IAAI,CACzC,CAAA;YAED,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,GAAG,CAAC,kBAAkB,CAC9C,IAAI,CAAC,WAAW,CAAC,GAAG,EACpB,GAAG,EACH,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,IAAI,CACzC,CAAA;YAED,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,EAAE;gBACpD,eAAe,EAAE,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,OAAO;gBACxC,gBAAgB,EAAE,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,OAAO;gBACzC,wBAAwB,EAAE,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,OAAO;gBACjD,OAAO;gBACP,MAAM;gBACN,IAAI;aACL,CAAC,CAAA;QACJ,CAAC;KACF,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import { xrpc } from '@atproto/lex'\nimport type { Server } from '@atproto/xrpc-server'\nimport { AuthScope } from '../../../../auth-scope.js'\nimport type { AppContext } from '../../../../context.js'\nimport { com } from '../../../../lexicons/index.js'\nimport { computeProxyTo, parseProxyInfo } from '../../../../pipethrough.js'\n\nexport default function (server: Server, ctx: AppContext) {\n server.add(com.atproto.moderation.createReport, {\n auth: ctx.authVerifier.authorization({\n additional: [AuthScope.Takendown],\n authorize: (permissions, { req }) => {\n const lxm = com.atproto.moderation.createReport.$lxm\n const aud = computeProxyTo(ctx, req, lxm)\n permissions.assertRpc({ aud, lxm })\n },\n }),\n handler: async ({ auth, params, input: { body }, req }) => {\n const { url, did: aud } = await parseProxyInfo(\n ctx,\n req,\n com.atproto.moderation.createReport.$lxm,\n )\n\n const { headers } = await ctx.serviceAuthHeaders(\n auth.credentials.did,\n aud,\n com.atproto.moderation.createReport.$lxm,\n )\n\n return xrpc(url, com.atproto.moderation.createReport, {\n validateRequest: ctx.cfg.service.devMode,\n validateResponse: ctx.cfg.service.devMode,\n strictResponseProcessing: ctx.cfg.service.devMode,\n headers,\n params,\n body,\n })\n },\n })\n}\n"]}
1
+ {"version":3,"file":"createReport.js","sourceRoot":"","sources":["../../../../../src/api/com/atproto/moderation/createReport.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAA;AAErD,OAAO,EAAE,GAAG,EAAE,MAAM,+BAA+B,CAAA;AACnD,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAA;AAE3E,MAAM,CAAC,OAAO,WAAW,MAAc,EAAE,GAAe;IACtD,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,EAAE;QAC9C,IAAI,EAAE,GAAG,CAAC,YAAY,CAAC,aAAa,CAAC;YACnC,UAAU,EAAE,CAAC,SAAS,CAAC,SAAS,CAAC;YACjC,SAAS,EAAE,CAAC,WAAW,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE;gBAClC,MAAM,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,IAAI,CAAA;gBACpD,MAAM,GAAG,GAAG,cAAc,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;gBACzC,WAAW,CAAC,SAAS,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAA;YACrC,CAAC;SACF,CAAC;QACF,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,EAAE,GAAG,EAAE,EAAE,EAAE;YACxD,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,MAAM,cAAc,CAC5C,GAAG,EACH,GAAG,EACH,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,IAAI,CACzC,CAAA;YAED,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,GAAG,CAAC,kBAAkB,CAC9C,IAAI,CAAC,WAAW,CAAC,GAAG,EACpB,GAAG,EACH,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,IAAI,CACzC,CAAA;YAED,OAAO,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,YAAY,EAAE;gBACnE,OAAO;gBACP,MAAM;gBACN,IAAI;aACL,CAAC,CAAA;QACJ,CAAC;KACF,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import type { Server } from '@atproto/xrpc-server'\nimport { AuthScope } from '../../../../auth-scope.js'\nimport type { AppContext } from '../../../../context.js'\nimport { com } from '../../../../lexicons/index.js'\nimport { computeProxyTo, parseProxyInfo } from '../../../../pipethrough.js'\n\nexport default function (server: Server, ctx: AppContext) {\n server.add(com.atproto.moderation.createReport, {\n auth: ctx.authVerifier.authorization({\n additional: [AuthScope.Takendown],\n authorize: (permissions, { req }) => {\n const lxm = com.atproto.moderation.createReport.$lxm\n const aud = computeProxyTo(ctx, req, lxm)\n permissions.assertRpc({ aud, lxm })\n },\n }),\n handler: async ({ auth, params, input: { body }, req }) => {\n const { url, did: aud } = await parseProxyInfo(\n ctx,\n req,\n com.atproto.moderation.createReport.$lxm,\n )\n\n const { headers } = await ctx.serviceAuthHeaders(\n auth.credentials.did,\n aud,\n com.atproto.moderation.createReport.$lxm,\n )\n\n return ctx.safeClient(url).xrpc(com.atproto.moderation.createReport, {\n headers,\n params,\n body,\n })\n },\n })\n}\n"]}
@@ -71,6 +71,11 @@ export type DiskBlobstoreConfig = {
71
71
  };
72
72
  export type IdentityConfig = {
73
73
  plcUrl: string;
74
+ /**
75
+ * Bounds each individual identity resolution attempt. Note that
76
+ * `safeFetch`'s own 10s timeout acts as an upper backstop, so values above
77
+ * 10s are effectively capped.
78
+ */
74
79
  resolverTimeout: number;
75
80
  cacheStaleTTL: number;
76
81
  cacheMaxTTL: number;
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config/config.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,cAAc,EACd,cAAc,EACf,MAAM,kCAAkC,CAAA;AACzC,OAAO,EAAE,KAAK,SAAS,EAA8B,MAAM,iBAAiB,CAAA;AAE5E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAA;AAEjD,YAAY,EAAE,cAAc,EAAE,CAAA;AAK9B,eAAO,MAAM,QAAQ,QAAS,iBAAiB,KAAG,YA8VjD,CAAA;AAED,MAAM,MAAM,YAAY,GAAG;IACzB,OAAO,EAAE,aAAa,CAAA;IACtB,EAAE,EAAE,cAAc,CAAA;IAClB,UAAU,EAAE,gBAAgB,CAAA;IAC5B,SAAS,EAAE,iBAAiB,GAAG,mBAAmB,CAAA;IAClD,QAAQ,EAAE,cAAc,CAAA;IACxB,QAAQ,EAAE,cAAc,GAAG,IAAI,CAAA;IAC/B,OAAO,EAAE,aAAa,CAAA;IACtB,KAAK,EAAE,WAAW,GAAG,IAAI,CAAA;IACzB,eAAe,EAAE,WAAW,GAAG,IAAI,CAAA;IACnC,YAAY,EAAE,kBAAkB,CAAA;IAChC,WAAW,EAAE,iBAA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AQ,EAAE,WAAW;gBACrB,cAAc,EAAE,GAAG,CAAC,mBAAmB;aACxC;SACF,CAAA;IAEL,MAAM,UAAU,GAA0B,EAAE,CAAA;IAE5C,IAAI,GAAG,CAAC,mBAAmB,IAAI,IAAI,EAAE,CAAC;QACpC,cAAc,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAA;QACvC,UAAU,CAAC,YAAY,GAAG,GAAG,CAAC,mBAAmB,CAAA;IACnD,CAAC;IAED,OAAO;QACL,OAAO,EAAE,UAAU;QACnB,EAAE,EAAE,KAAK;QACT,UAAU,EAAE,aAAa;QACzB,SAAS,EAAE,YAAY;QACvB,QAAQ,EAAE,WAAW;QACrB,QAAQ,EAAE,WAAW;QACrB,OAAO,EAAE,UAAU;QACnB,KAAK,EAAE,QAAQ;QACf,eAAe,EAAE,kBAAkB;QACnC,YAAY,EAAE,eAAe;QAC7B,WAAW,EAAE,cAAc;QAC3B,UAAU,EAAE,aAAa;QACzB,aAAa,EAAE,gBAAgB;QAC/B,KAAK,EAAE,QAAQ;QACf,UAAU,EAAE,aAAa;QACzB,QAAQ,EAAE,WAAW;QACrB,KAAK,EAAE,QAAQ;QACf,OAAO,EAAE,UAAU;QACnB,KAAK,EAAE,QAAQ;QACf,QAAQ,EAAE,WAAW;QACrB,KAAK,EAAE,QAAQ;KAChB,CAAA;AACH,CAAC,CAAA","sourcesContent":["import assert from 'node:assert'\nimport path from 'node:path'\nimport { DAY, HOUR, SECOND } from '@atproto/common'\nimport type {\n BrandingConfig,\n HcaptchaConfig,\n} from '@atproto/oauth-provider/provider'\nimport { type DidString, ensureValidDid, isValidDid } from '@atproto/syntax'\nimport pkg from '../../package.json' with { type: 'json' }\nimport type { ServerEnvironment } from './env.js'\n\nexport type { BrandingConfig }\n\n// off-config but still from env:\n// logging: LOG_LEVEL, LOG_SYSTEMS, LOG_ENABLED, LOG_DESTINATION\n\nexport const envToCfg = (env: ServerEnvironment): ServerConfig => {\n const port = env.port ?? 2583\n const hostname = env.hostname ?? 'localhost'\n const publicUrl =\n hostname === 'localhost'\n ? `http://localhost:${port}`\n : `https://${hostname}`\n const did = env.serviceDid ?? `did:web:${hostname}`\n\n if (!isValidDid(did)) {\n throw new Error(`Invalid service DID: ${did}`)\n }\n\n const serviceCfg: ServerConfig['service'] = {\n port,\n hostname,\n publicUrl,\n did,\n version: env.version || pkg.version,\n privacyPolicyUrl: env.privacyPolicyUrl,\n termsOfServiceUrl: env.termsOfServiceUrl,\n contactEmailAddress: env.contactEmailAddress,\n acceptingImports: env.acceptingImports ?? true,\n maxImportSize: env.maxImportSize,\n blobUploadLimit: env.blobUploadLimit ?? 5 * 1024 * 1024, // 5mb\n devMode: env.devMode ?? false,\n }\n\n const dbLoc = (name: string) => {\n return env.dataDirectory ? path.join(env.dataDirectory, name) : name\n }\n\n const disableWalAutoCheckpoint = env.disableWalAutoCheckpoint ?? false\n\n const dbCfg: ServerConfig['db'] = {\n accountDbLoc: env.accountDbLocation ?? dbLoc('account.sqlite'),\n sequencerDbLoc: env.sequencerDbLocation ?? dbLoc('sequencer.sqlite'),\n didCacheDbLoc: env.didCacheDbLocation ?? dbLoc('did_cache.sqlite'),\n disableWalAutoCheckpoint,\n }\n\n const actorStoreCfg: ServerConfig['actorStore'] = {\n directory: env.actorStoreDirectory ?? dbLoc('actors'),\n cacheSize: env.actorStoreCacheSize ?? 100,\n disableWalAutoCheckpoint,\n }\n\n let blobstoreCfg: ServerConfig['blobstore']\n if (env.blobstoreS3Bucket && env.blobstoreDiskLocation) {\n throw new Error('Cannot set both S3 and disk blobstore env vars')\n }\n if (env.blobstoreS3Bucket) {\n blobstoreCfg = {\n provider: 's3',\n bucket: env.blobstoreS3Bucket,\n uploadTimeoutMs: env.blobstoreS3UploadTimeoutMs || 20000,\n requestTimeoutMs: env.blobstoreS3RequestTimeoutMs,\n region: env.blobstoreS3Region,\n endpoint: env.blobstoreS3Endpoint,\n forcePathStyle: env.blobstoreS3ForcePathStyle,\n }\n if (env.blobstoreS3AccessKeyId || env.blobstoreS3SecretAccessKey) {\n if (!env.blobstoreS3AccessKeyId || !env.blobstoreS3SecretAccessKey) {\n throw new Error(\n 'Must specify both S3 access key id and secret access key blobstore env vars',\n )\n }\n blobstoreCfg.credentials = {\n accessKeyId: env.blobstoreS3AccessKeyId,\n secretAccessKey: env.blobstoreS3SecretAccessKey,\n }\n }\n } else if (env.blobstoreDiskLocation) {\n blobstoreCfg = {\n provider: 'disk',\n location: env.blobstoreDiskLocation,\n tempLocation: env.blobstoreDiskTmpLocation,\n }\n } else {\n throw new Error('Must configure either S3 or disk blobstore')\n }\n\n // @NOTE when behind an entryway, this should be configured to match the entryway's domains\n let serviceHandleDomains: string[]\n if (env.serviceHandleDomains && env.serviceHandleDomains.length > 0) {\n serviceHandleDomains = env.serviceHandleDomains\n } else {\n if (hostname === 'localhost') {\n serviceHandleDomains = ['.test']\n } else {\n serviceHandleDomains = [`.${hostname}`]\n }\n }\n const invalidDomain = serviceHandleDomains.find(\n (domain) => domain.length < 1 || !domain.startsWith('.'),\n )\n if (invalidDomain) {\n throw new Error(`Invalid handle domain: ${invalidDomain}`)\n }\n\n const identityCfg: ServerConfig['identity'] = {\n plcUrl: env.didPlcUrl ?? 'https://plc.directory',\n cacheMaxTTL: env.didCacheMaxTTL ?? DAY,\n cacheStaleTTL: env.didCacheStaleTTL ?? HOUR,\n resolverTimeout: env.resolverTimeout ?? 3 * SECOND,\n recoveryDidKey: env.recoveryDidKey ?? null,\n serviceHandleDomains,\n handleBackupNameservers: env.handleBackupNameservers,\n enableDidDocWithSession: !!env.enableDidDocWithSession,\n }\n\n let entrywayCfg: ServerConfig['entryway'] = null\n if (env.entrywayUrl) {\n assert(\n env.entrywayJwtVerifyKeyK256PublicKeyHex &&\n env.entrywayPlcRotationKey &&\n env.entrywayDid,\n 'if entryway url is configured, must include all required entryway configuration',\n )\n entrywayCfg = {\n url: env.entrywayUrl,\n did: env.entrywayDid,\n jwtPublicKeyHex: env.entrywayJwtVerifyKeyK256PublicKeyHex,\n plcRotationKey: env.entrywayPlcRotationKey,\n }\n }\n\n // default to being required if left undefined\n const invitesCfg: ServerConfig['invites'] =\n env.inviteRequired === false\n ? {\n required: false,\n }\n : {\n required: true,\n interval: env.inviteInterval ?? null,\n epoch: env.inviteEpoch ?? 0,\n }\n\n let emailCfg: ServerConfig['email']\n if (!env.emailFromAddress && !env.emailSmtpUrl) {\n emailCfg = null\n } else {\n if (!env.emailFromAddress || !env.emailSmtpUrl) {\n throw new Error(\n 'Partial email config, must set both emailFromAddress and emailSmtpUrl',\n )\n }\n emailCfg = {\n smtpUrl: env.emailSmtpUrl,\n fromAddress: env.emailFromAddress,\n disableConfirmationLink: env.emailDisableConfirmationLink ?? false,\n }\n }\n\n let moderationEmailCfg: ServerConfig['moderationEmail']\n if (!env.moderationEmailAddress && !env.moderationEmailSmtpUrl) {\n moderationEmailCfg = null\n } else {\n if (!env.moderationEmailAddress || !env.moderationEmailSmtpUrl) {\n throw new Error(\n 'Partial moderation email config, must set both emailFromAddress and emailSmtpUrl',\n )\n }\n moderationEmailCfg = {\n smtpUrl: env.moderationEmailSmtpUrl,\n fromAddress: env.moderationEmailAddress,\n disableConfirmationLink: false,\n }\n }\n\n const subscriptionCfg: ServerConfig['subscription'] = {\n maxBuffer: env.maxSubscriptionBuffer ?? 500,\n repoBackfillLimitMs: env.repoBackfillLimitMs ?? DAY,\n }\n\n let bskyAppViewCfg: ServerConfig['bskyAppView'] = null\n if (env.bskyAppViewUrl) {\n assert(\n env.bskyAppViewDid,\n 'if bsky appview service url is configured, must configure its did as well.',\n )\n bskyAppViewCfg = {\n url: env.bskyAppViewUrl,\n did: env.bskyAppViewDid,\n cdnUrlPattern: env.bskyAppViewCdnUrlPattern,\n }\n }\n\n let modServiceCfg: ServerConfig['modService'] = null\n if (env.modServiceUrl) {\n assert(\n env.modServiceDid,\n 'if mod service url is configured, must configure its did as well.',\n )\n modServiceCfg = {\n url: env.modServiceUrl,\n did: env.modServiceDid,\n }\n }\n\n let reportServiceCfg: ServerConfig['reportService'] = null\n if (env.reportServiceUrl) {\n assert(\n env.reportServiceDid,\n 'if report service url is configured, must configure its did as well.',\n )\n reportServiceCfg = {\n url: env.reportServiceUrl,\n did: env.reportServiceDid,\n }\n }\n\n // if there's a mod service, default report service into it\n if (modServiceCfg && !reportServiceCfg) {\n reportServiceCfg = modServiceCfg\n }\n\n const redisCfg: ServerConfig['redis'] = env.redisScratchAddress\n ? {\n address: env.redisScratchAddress,\n password: env.redisScratchPassword,\n }\n : null\n\n const rateLimitsCfg: ServerConfig['rateLimits'] = env.rateLimitsEnabled\n ? {\n enabled: true,\n bypassKey: env.rateLimitBypassKey,\n bypassIps: env.rateLimitBypassIps?.map((ipOrCidr) =>\n ipOrCidr.split('/')[0]?.trim(),\n ),\n }\n : { enabled: false }\n\n const crawlersCfg: ServerConfig['crawlers'] = env.crawlers ?? []\n\n const fetchCfg: ServerConfig['fetch'] = {\n disableSsrfProtection: env.disableSsrfProtection ?? env.devMode ?? false,\n maxResponseSize: env.fetchMaxResponseSize ?? 512 * 1024, // 512kb\n }\n\n const proxyCfg: ServerConfig['proxy'] = {\n disableSsrfProtection: env.disableSsrfProtection ?? env.devMode ?? false,\n allowHTTP2: env.proxyAllowHTTP2 ?? false,\n headersTimeout: env.proxyHeadersTimeout ?? 10e3,\n bodyTimeout: env.proxyBodyTimeout ?? 30e3,\n maxResponseSize: env.proxyMaxResponseSize ?? 10 * 1024 * 1024, // 10mb\n maxRetries:\n env.proxyMaxRetries != null && env.proxyMaxRetries > 0\n ? env.proxyMaxRetries\n : 0,\n preferCompressed: env.proxyPreferCompressed ?? false,\n }\n\n const brandingCfg = {\n name: env.serviceName ?? `${hostname} PDS`,\n logo: env.logoUrl,\n colors: {\n primary: env.primaryColor,\n\n error: env.errorColor,\n warning: env.warningColor,\n info: env.infoColor,\n success: env.successColor,\n },\n background: {\n light: env.backgroundLightUrl,\n dark: env.backgroundDarkUrl,\n },\n links: [\n {\n title: { en: 'Home', fr: 'Accueil' },\n href: env.homeUrl,\n rel: 'canonical' as const, // Prevents login page from being indexed\n },\n {\n title: { en: 'Terms of Service' },\n href: env.termsOfServiceUrl,\n rel: 'terms-of-service' as const,\n },\n {\n title: { en: 'Privacy Policy' },\n href: env.privacyPolicyUrl,\n rel: 'privacy-policy' as const,\n },\n {\n title: { en: 'Support' },\n href: env.supportUrl,\n rel: 'help' as const,\n },\n ].filter(\n <T extends { href?: string }>(f: T): f is T & { href: string } =>\n f.href != null && f.href !== '',\n ),\n }\n\n const oauthCfg: ServerConfig['oauth'] = entrywayCfg\n ? {\n issuer: entrywayCfg.url,\n provider: undefined,\n }\n : {\n issuer: serviceCfg.publicUrl,\n provider: {\n hcaptcha:\n env.hcaptchaSiteKey &&\n env.hcaptchaSecretKey &&\n env.hcaptchaTokenSalt\n ? {\n siteKey: env.hcaptchaSiteKey,\n secretKey: env.hcaptchaSecretKey,\n tokenSalt: env.hcaptchaTokenSalt,\n }\n : undefined,\n branding: brandingCfg,\n trustedClients: env.trustedOAuthClients,\n },\n }\n\n const lexiconCfg: LexiconResolverConfig = {}\n\n if (env.lexiconDidAuthority != null) {\n ensureValidDid(env.lexiconDidAuthority)\n lexiconCfg.didAuthority = env.lexiconDidAuthority\n }\n\n return {\n service: serviceCfg,\n db: dbCfg,\n actorStore: actorStoreCfg,\n blobstore: blobstoreCfg,\n identity: identityCfg,\n entryway: entrywayCfg,\n invites: invitesCfg,\n email: emailCfg,\n moderationEmail: moderationEmailCfg,\n subscription: subscriptionCfg,\n bskyAppView: bskyAppViewCfg,\n modService: modServiceCfg,\n reportService: reportServiceCfg,\n redis: redisCfg,\n rateLimits: rateLimitsCfg,\n crawlers: crawlersCfg,\n fetch: fetchCfg,\n lexicon: lexiconCfg,\n proxy: proxyCfg,\n branding: brandingCfg,\n oauth: oauthCfg,\n }\n}\n\nexport type ServerConfig = {\n service: ServiceConfig\n db: DatabaseConfig\n actorStore: ActorStoreConfig\n blobstore: S3BlobstoreConfig | DiskBlobstoreConfig\n identity: IdentityConfig\n entryway: EntrywayConfig | null\n invites: InvitesConfig\n email: EmailConfig | null\n moderationEmail: EmailConfig | null\n subscription: SubscriptionConfig\n bskyAppView: BksyAppViewConfig | null\n modService: ModServiceConfig | null\n reportService: ReportServiceConfig | null\n redis: RedisScratchConfig | null\n rateLimits: RateLimitsConfig\n crawlers: string[]\n fetch: FetchConfig\n proxy: ProxyConfig\n branding: BrandingConfig\n oauth: OAuthConfig\n lexicon: LexiconResolverConfig\n}\n\nexport type ServiceConfig = {\n port: number\n hostname: string\n publicUrl: string\n did: DidString\n version: string\n privacyPolicyUrl?: string\n termsOfServiceUrl?: string\n acceptingImports: boolean\n maxImportSize?: number\n blobUploadLimit: number\n contactEmailAddress?: string\n devMode: boolean\n}\n\nexport type DatabaseConfig = {\n accountDbLoc: string\n sequencerDbLoc: string\n didCacheDbLoc: string\n disableWalAutoCheckpoint: boolean\n}\n\nexport type ActorStoreConfig = {\n directory: string\n cacheSize: number\n disableWalAutoCheckpoint: boolean\n}\n\nexport type S3BlobstoreConfig = {\n provider: 's3'\n bucket: string\n region?: string\n endpoint?: string\n forcePathStyle?: boolean\n uploadTimeoutMs?: number\n requestTimeoutMs?: number\n credentials?: {\n accessKeyId: string\n secretAccessKey: string\n }\n}\n\nexport type DiskBlobstoreConfig = {\n provider: 'disk'\n location: string\n tempLocation?: string\n}\n\nexport type IdentityConfig = {\n plcUrl: string\n resolverTimeout: number\n cacheStaleTTL: number\n cacheMaxTTL: number\n recoveryDidKey: string | null\n serviceHandleDomains: string[]\n handleBackupNameservers?: string[]\n enableDidDocWithSession: boolean\n}\n\nexport type EntrywayConfig = {\n url: string\n did: string\n jwtPublicKeyHex: string\n plcRotationKey: string\n}\n\nexport type FetchConfig = {\n disableSsrfProtection: boolean\n maxResponseSize: number\n}\n\nexport type ProxyConfig = {\n disableSsrfProtection: boolean\n allowHTTP2: boolean\n headersTimeout: number\n bodyTimeout: number\n maxResponseSize: number\n maxRetries: number\n\n /**\n * When proxying requests that might get intercepted (for read-after-write) we\n * negotiate the encoding based on the client's preferences. We will however\n * use or own weights in order to be able to better control if the PDS will\n * need to perform content decoding. This settings allows to prefer compressed\n * content over uncompressed one.\n */\n preferCompressed: boolean\n}\n\nexport type OAuthConfig = {\n issuer: string\n provider?: {\n hcaptcha?: HcaptchaConfig\n branding: BrandingConfig\n trustedClients?: string[]\n }\n}\n\nexport type LexiconResolverConfig = {\n didAuthority?: `did:${string}:${string}`\n}\n\nexport type InvitesConfig =\n | {\n required: true\n interval: number | null\n epoch: number\n }\n | {\n required: false\n }\n\nexport type EmailConfig = {\n smtpUrl: string\n fromAddress: string\n disableConfirmationLink: boolean\n}\n\nexport type SubscriptionConfig = {\n maxBuffer: number\n repoBackfillLimitMs: number\n}\n\nexport type RedisScratchConfig = {\n address: string\n password?: string\n}\n\nexport type RateLimitsConfig =\n | {\n enabled: true\n bypassKey?: string\n bypassIps?: string[]\n }\n | { enabled: false }\n\nexport type BksyAppViewConfig = {\n url: string\n did: string\n cdnUrlPattern?: string\n}\n\nexport type ModServiceConfig = {\n url: string\n did: string\n}\n\nexport type ReportServiceConfig = {\n url: string\n did: string\n}\n"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config/config.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAA;AAChC,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAKnD,OAAO,EAAkB,cAAc,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAC5E,OAAO,GAAG,MAAM,oBAAoB,CAAC,OAAO,IAAI,EAAE,MAAM,EAAE,CAAA;AAK1D,iCAAiC;AACjC,gEAAgE;AAEhE,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,GAAsB,EAAgB,EAAE;IAC/D,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,IAAI,IAAI,CAAA;IAC7B,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kBAAkB;QACnC,YAAY,EAAE,eAAe;QAC7B,WAAW,EAAE,cAAc;QAC3B,UAAU,EAAE,aAAa;QACzB,aAAa,EAAE,gBAAgB;QAC/B,KAAK,EAAE,QAAQ;QACf,UAAU,EAAE,aAAa;QACzB,QAAQ,EAAE,WAAW;QACrB,KAAK,EAAE,QAAQ;QACf,OAAO,EAAE,UAAU;QACnB,KAAK,EAAE,QAAQ;QACf,QAAQ,EAAE,WAAW;QACrB,KAAK,EAAE,QAAQ;KAChB,CAAA;AACH,CAAC,CAAA","sourcesContent":["import assert from 'node:assert'\nimport path from 'node:path'\nimport { DAY, HOUR, SECOND } from '@atproto/common'\nimport type {\n BrandingConfig,\n HcaptchaConfig,\n} from '@atproto/oauth-provider/provider'\nimport { type DidString, ensureValidDid, isValidDid } from '@atproto/syntax'\nimport pkg from '../../package.json' with { type: 'json' }\nimport type { ServerEnvironment } from './env.js'\n\nexport type { BrandingConfig }\n\n// off-config but still from env:\n// logging: LOG_LEVEL, LOG_SYSTEMS, LOG_ENABLED, LOG_DESTINATION\n\nexport const envToCfg = (env: ServerEnvironment): ServerConfig => {\n const port = env.port ?? 2583\n const hostname = env.hostname ?? 'localhost'\n const publicUrl =\n hostname === 'localhost'\n ? `http://localhost:${port}`\n : `https://${hostname}`\n const did = env.serviceDid ?? `did:web:${hostname}`\n\n if (!isValidDid(did)) {\n throw new Error(`Invalid service DID: ${did}`)\n }\n\n const serviceCfg: ServerConfig['service'] = {\n port,\n hostname,\n publicUrl,\n did,\n version: env.version || pkg.version,\n privacyPolicyUrl: env.privacyPolicyUrl,\n termsOfServiceUrl: env.termsOfServiceUrl,\n contactEmailAddress: env.contactEmailAddress,\n acceptingImports: env.acceptingImports ?? true,\n maxImportSize: env.maxImportSize,\n blobUploadLimit: env.blobUploadLimit ?? 5 * 1024 * 1024, // 5mb\n devMode: env.devMode ?? false,\n }\n\n const dbLoc = (name: string) => {\n return env.dataDirectory ? path.join(env.dataDirectory, name) : name\n }\n\n const disableWalAutoCheckpoint = env.disableWalAutoCheckpoint ?? false\n\n const dbCfg: ServerConfig['db'] = {\n accountDbLoc: env.accountDbLocation ?? dbLoc('account.sqlite'),\n sequencerDbLoc: env.sequencerDbLocation ?? dbLoc('sequencer.sqlite'),\n didCacheDbLoc: env.didCacheDbLocation ?? dbLoc('did_cache.sqlite'),\n disableWalAutoCheckpoint,\n }\n\n const actorStoreCfg: ServerConfig['actorStore'] = {\n directory: env.actorStoreDirectory ?? dbLoc('actors'),\n cacheSize: env.actorStoreCacheSize ?? 100,\n disableWalAutoCheckpoint,\n }\n\n let blobstoreCfg: ServerConfig['blobstore']\n if (env.blobstoreS3Bucket && env.blobstoreDiskLocation) {\n throw new Error('Cannot set both S3 and disk blobstore env vars')\n }\n if (env.blobstoreS3Bucket) {\n blobstoreCfg = {\n provider: 's3',\n bucket: env.blobstoreS3Bucket,\n uploadTimeoutMs: env.blobstoreS3UploadTimeoutMs || 20000,\n requestTimeoutMs: env.blobstoreS3RequestTimeoutMs,\n region: env.blobstoreS3Region,\n endpoint: env.blobstoreS3Endpoint,\n forcePathStyle: env.blobstoreS3ForcePathStyle,\n }\n if (env.blobstoreS3AccessKeyId || env.blobstoreS3SecretAccessKey) {\n if (!env.blobstoreS3AccessKeyId || !env.blobstoreS3SecretAccessKey) {\n throw new Error(\n 'Must specify both S3 access key id and secret access key blobstore env vars',\n )\n }\n blobstoreCfg.credentials = {\n accessKeyId: env.blobstoreS3AccessKeyId,\n secretAccessKey: env.blobstoreS3SecretAccessKey,\n }\n }\n } else if (env.blobstoreDiskLocation) {\n blobstoreCfg = {\n provider: 'disk',\n location: env.blobstoreDiskLocation,\n tempLocation: env.blobstoreDiskTmpLocation,\n }\n } else {\n throw new Error('Must configure either S3 or disk blobstore')\n }\n\n // @NOTE when behind an entryway, this should be configured to match the entryway's domains\n let serviceHandleDomains: string[]\n if (env.serviceHandleDomains && env.serviceHandleDomains.length > 0) {\n serviceHandleDomains = env.serviceHandleDomains\n } else {\n if (hostname === 'localhost') {\n serviceHandleDomains = ['.test']\n } else {\n serviceHandleDomains = [`.${hostname}`]\n }\n }\n const invalidDomain = serviceHandleDomains.find(\n (domain) => domain.length < 1 || !domain.startsWith('.'),\n )\n if (invalidDomain) {\n throw new Error(`Invalid handle domain: ${invalidDomain}`)\n }\n\n const identityCfg: ServerConfig['identity'] = {\n plcUrl: env.didPlcUrl ?? 'https://plc.directory',\n cacheMaxTTL: env.didCacheMaxTTL ?? DAY,\n cacheStaleTTL: env.didCacheStaleTTL ?? HOUR,\n resolverTimeout: env.resolverTimeout ?? 3 * SECOND,\n recoveryDidKey: env.recoveryDidKey ?? null,\n serviceHandleDomains,\n handleBackupNameservers: env.handleBackupNameservers,\n enableDidDocWithSession: !!env.enableDidDocWithSession,\n }\n\n let entrywayCfg: ServerConfig['entryway'] = null\n if (env.entrywayUrl) {\n assert(\n env.entrywayJwtVerifyKeyK256PublicKeyHex &&\n env.entrywayPlcRotationKey &&\n env.entrywayDid,\n 'if entryway url is configured, must include all required entryway configuration',\n )\n entrywayCfg = {\n url: env.entrywayUrl,\n did: env.entrywayDid,\n jwtPublicKeyHex: env.entrywayJwtVerifyKeyK256PublicKeyHex,\n plcRotationKey: env.entrywayPlcRotationKey,\n }\n }\n\n // default to being required if left undefined\n const invitesCfg: ServerConfig['invites'] =\n env.inviteRequired === false\n ? {\n required: false,\n }\n : {\n required: true,\n interval: env.inviteInterval ?? null,\n epoch: env.inviteEpoch ?? 0,\n }\n\n let emailCfg: ServerConfig['email']\n if (!env.emailFromAddress && !env.emailSmtpUrl) {\n emailCfg = null\n } else {\n if (!env.emailFromAddress || !env.emailSmtpUrl) {\n throw new Error(\n 'Partial email config, must set both emailFromAddress and emailSmtpUrl',\n )\n }\n emailCfg = {\n smtpUrl: env.emailSmtpUrl,\n fromAddress: env.emailFromAddress,\n disableConfirmationLink: env.emailDisableConfirmationLink ?? false,\n }\n }\n\n let moderationEmailCfg: ServerConfig['moderationEmail']\n if (!env.moderationEmailAddress && !env.moderationEmailSmtpUrl) {\n moderationEmailCfg = null\n } else {\n if (!env.moderationEmailAddress || !env.moderationEmailSmtpUrl) {\n throw new Error(\n 'Partial moderation email config, must set both emailFromAddress and emailSmtpUrl',\n )\n }\n moderationEmailCfg = {\n smtpUrl: env.moderationEmailSmtpUrl,\n fromAddress: env.moderationEmailAddress,\n disableConfirmationLink: false,\n }\n }\n\n const subscriptionCfg: ServerConfig['subscription'] = {\n maxBuffer: env.maxSubscriptionBuffer ?? 500,\n repoBackfillLimitMs: env.repoBackfillLimitMs ?? DAY,\n }\n\n let bskyAppViewCfg: ServerConfig['bskyAppView'] = null\n if (env.bskyAppViewUrl) {\n assert(\n env.bskyAppViewDid,\n 'if bsky appview service url is configured, must configure its did as well.',\n )\n bskyAppViewCfg = {\n url: env.bskyAppViewUrl,\n did: env.bskyAppViewDid,\n cdnUrlPattern: env.bskyAppViewCdnUrlPattern,\n }\n }\n\n let modServiceCfg: ServerConfig['modService'] = null\n if (env.modServiceUrl) {\n assert(\n env.modServiceDid,\n 'if mod service url is configured, must configure its did as well.',\n )\n modServiceCfg = {\n url: env.modServiceUrl,\n did: env.modServiceDid,\n }\n }\n\n let reportServiceCfg: ServerConfig['reportService'] = null\n if (env.reportServiceUrl) {\n assert(\n env.reportServiceDid,\n 'if report service url is configured, must configure its did as well.',\n )\n reportServiceCfg = {\n url: env.reportServiceUrl,\n did: env.reportServiceDid,\n }\n }\n\n // if there's a mod service, default report service into it\n if (modServiceCfg && !reportServiceCfg) {\n reportServiceCfg = modServiceCfg\n }\n\n const redisCfg: ServerConfig['redis'] = env.redisScratchAddress\n ? {\n address: env.redisScratchAddress,\n password: env.redisScratchPassword,\n }\n : null\n\n const rateLimitsCfg: ServerConfig['rateLimits'] = env.rateLimitsEnabled\n ? {\n enabled: true,\n bypassKey: env.rateLimitBypassKey,\n bypassIps: env.rateLimitBypassIps?.map((ipOrCidr) =>\n ipOrCidr.split('/')[0]?.trim(),\n ),\n }\n : { enabled: false }\n\n const crawlersCfg: ServerConfig['crawlers'] = env.crawlers ?? []\n\n const fetchCfg: ServerConfig['fetch'] = {\n disableSsrfProtection: env.disableSsrfProtection ?? env.devMode ?? false,\n maxResponseSize: env.fetchMaxResponseSize ?? 512 * 1024, // 512kb\n }\n\n const proxyCfg: ServerConfig['proxy'] = {\n disableSsrfProtection: env.disableSsrfProtection ?? env.devMode ?? false,\n allowHTTP2: env.proxyAllowHTTP2 ?? false,\n headersTimeout: env.proxyHeadersTimeout ?? 10e3,\n bodyTimeout: env.proxyBodyTimeout ?? 30e3,\n maxResponseSize: env.proxyMaxResponseSize ?? 10 * 1024 * 1024, // 10mb\n maxRetries:\n env.proxyMaxRetries != null && env.proxyMaxRetries > 0\n ? env.proxyMaxRetries\n : 0,\n preferCompressed: env.proxyPreferCompressed ?? false,\n }\n\n const brandingCfg = {\n name: env.serviceName ?? `${hostname} PDS`,\n logo: env.logoUrl,\n colors: {\n primary: env.primaryColor,\n\n error: env.errorColor,\n warning: env.warningColor,\n info: env.infoColor,\n success: env.successColor,\n },\n background: {\n light: env.backgroundLightUrl,\n dark: env.backgroundDarkUrl,\n },\n links: [\n {\n title: { en: 'Home', fr: 'Accueil' },\n href: env.homeUrl,\n rel: 'canonical' as const, // Prevents login page from being indexed\n },\n {\n title: { en: 'Terms of Service' },\n href: env.termsOfServiceUrl,\n rel: 'terms-of-service' as const,\n },\n {\n title: { en: 'Privacy Policy' },\n href: env.privacyPolicyUrl,\n rel: 'privacy-policy' as const,\n },\n {\n title: { en: 'Support' },\n href: env.supportUrl,\n rel: 'help' as const,\n },\n ].filter(\n <T extends { href?: string }>(f: T): f is T & { href: string } =>\n f.href != null && f.href !== '',\n ),\n }\n\n const oauthCfg: ServerConfig['oauth'] = entrywayCfg\n ? {\n issuer: entrywayCfg.url,\n provider: undefined,\n }\n : {\n issuer: serviceCfg.publicUrl,\n provider: {\n hcaptcha:\n env.hcaptchaSiteKey &&\n env.hcaptchaSecretKey &&\n env.hcaptchaTokenSalt\n ? {\n siteKey: env.hcaptchaSiteKey,\n secretKey: env.hcaptchaSecretKey,\n tokenSalt: env.hcaptchaTokenSalt,\n }\n : undefined,\n branding: brandingCfg,\n trustedClients: env.trustedOAuthClients,\n },\n }\n\n const lexiconCfg: LexiconResolverConfig = {}\n\n if (env.lexiconDidAuthority != null) {\n ensureValidDid(env.lexiconDidAuthority)\n lexiconCfg.didAuthority = env.lexiconDidAuthority\n }\n\n return {\n service: serviceCfg,\n db: dbCfg,\n actorStore: actorStoreCfg,\n blobstore: blobstoreCfg,\n identity: identityCfg,\n entryway: entrywayCfg,\n invites: invitesCfg,\n email: emailCfg,\n moderationEmail: moderationEmailCfg,\n subscription: subscriptionCfg,\n bskyAppView: bskyAppViewCfg,\n modService: modServiceCfg,\n reportService: reportServiceCfg,\n redis: redisCfg,\n rateLimits: rateLimitsCfg,\n crawlers: crawlersCfg,\n fetch: fetchCfg,\n lexicon: lexiconCfg,\n proxy: proxyCfg,\n branding: brandingCfg,\n oauth: oauthCfg,\n }\n}\n\nexport type ServerConfig = {\n service: ServiceConfig\n db: DatabaseConfig\n actorStore: ActorStoreConfig\n blobstore: S3BlobstoreConfig | DiskBlobstoreConfig\n identity: IdentityConfig\n entryway: EntrywayConfig | null\n invites: InvitesConfig\n email: EmailConfig | null\n moderationEmail: EmailConfig | null\n subscription: SubscriptionConfig\n bskyAppView: BksyAppViewConfig | null\n modService: ModServiceConfig | null\n reportService: ReportServiceConfig | null\n redis: RedisScratchConfig | null\n rateLimits: RateLimitsConfig\n crawlers: string[]\n fetch: FetchConfig\n proxy: ProxyConfig\n branding: BrandingConfig\n oauth: OAuthConfig\n lexicon: LexiconResolverConfig\n}\n\nexport type ServiceConfig = {\n port: number\n hostname: string\n publicUrl: string\n did: DidString\n version: string\n privacyPolicyUrl?: string\n termsOfServiceUrl?: string\n acceptingImports: boolean\n maxImportSize?: number\n blobUploadLimit: number\n contactEmailAddress?: string\n devMode: boolean\n}\n\nexport type DatabaseConfig = {\n accountDbLoc: string\n sequencerDbLoc: string\n didCacheDbLoc: string\n disableWalAutoCheckpoint: boolean\n}\n\nexport type ActorStoreConfig = {\n directory: string\n cacheSize: number\n disableWalAutoCheckpoint: boolean\n}\n\nexport type S3BlobstoreConfig = {\n provider: 's3'\n bucket: string\n region?: string\n endpoint?: string\n forcePathStyle?: boolean\n uploadTimeoutMs?: number\n requestTimeoutMs?: number\n credentials?: {\n accessKeyId: string\n secretAccessKey: string\n }\n}\n\nexport type DiskBlobstoreConfig = {\n provider: 'disk'\n location: string\n tempLocation?: string\n}\n\nexport type IdentityConfig = {\n plcUrl: string\n /**\n * Bounds each individual identity resolution attempt. Note that\n * `safeFetch`'s own 10s timeout acts as an upper backstop, so values above\n * 10s are effectively capped.\n */\n resolverTimeout: number\n cacheStaleTTL: number\n cacheMaxTTL: number\n recoveryDidKey: string | null\n serviceHandleDomains: string[]\n handleBackupNameservers?: string[]\n enableDidDocWithSession: boolean\n}\n\nexport type EntrywayConfig = {\n url: string\n did: string\n jwtPublicKeyHex: string\n plcRotationKey: string\n}\n\nexport type FetchConfig = {\n disableSsrfProtection: boolean\n maxResponseSize: number\n}\n\nexport type ProxyConfig = {\n disableSsrfProtection: boolean\n allowHTTP2: boolean\n headersTimeout: number\n bodyTimeout: number\n maxResponseSize: number\n maxRetries: number\n\n /**\n * When proxying requests that might get intercepted (for read-after-write) we\n * negotiate the encoding based on the client's preferences. We will however\n * use or own weights in order to be able to better control if the PDS will\n * need to perform content decoding. This settings allows to prefer compressed\n * content over uncompressed one.\n */\n preferCompressed: boolean\n}\n\nexport type OAuthConfig = {\n issuer: string\n provider?: {\n hcaptcha?: HcaptchaConfig\n branding: BrandingConfig\n trustedClients?: string[]\n }\n}\n\nexport type LexiconResolverConfig = {\n didAuthority?: `did:${string}:${string}`\n}\n\nexport type InvitesConfig =\n | {\n required: true\n interval: number | null\n epoch: number\n }\n | {\n required: false\n }\n\nexport type EmailConfig = {\n smtpUrl: string\n fromAddress: string\n disableConfirmationLink: boolean\n}\n\nexport type SubscriptionConfig = {\n maxBuffer: number\n repoBackfillLimitMs: number\n}\n\nexport type RedisScratchConfig = {\n address: string\n password?: string\n}\n\nexport type RateLimitsConfig =\n | {\n enabled: true\n bypassKey?: string\n bypassIps?: string[]\n }\n | { enabled: false }\n\nexport type BksyAppViewConfig = {\n url: string\n did: string\n cdnUrlPattern?: string\n}\n\nexport type ModServiceConfig = {\n url: string\n did: string\n}\n\nexport type ReportServiceConfig = {\n url: string\n did: string\n}\n"]}
package/dist/context.d.ts CHANGED
@@ -85,6 +85,16 @@ export declare class AppContext implements AsyncDisposable {
85
85
  entrywayPassthruHeaders(req: express.Request): {
86
86
  headers: Record<string, string>;
87
87
  };
88
+ /**
89
+ * A {@link Client} for a service URL that was resolved from a DID document,
90
+ * i.e. a URL the PDS does not control. Routes the request through
91
+ * {@link safeFetch}, which restricts it to https origins that resolve to
92
+ * unicast addresses, and caps the response size. Lexicon validation follows
93
+ * the service's dev mode, as it does for the AppView client.
94
+ *
95
+ * Any call built from a DID document's service endpoint must use this.
96
+ */
97
+ safeClient(service: string | URL): Client;
88
98
  serviceAuthHeaders(did: string, aud: string, lxm: string): Promise<{
89
99
  headers: {
90
100
  authorization: string;
@@ -1 +1 @@
1
- {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AACnC,OAAO,KAAK,OAAO,MAAM,SAAS,CAAA;AAClC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAGpC,OAAO,KAAK,KAAK,MAAM,MAAM,QAAQ,CAAA;AAErC,OAAO,KAAK,MAAM,MAAM,iBAAiB,CAAA;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AACrC,OAAO,EAIL,aAAa,EACd,MAAM,kCAAkC,CAAA;AAEzC,OAAO,KAAK,EAAE,SAAS,EAAE,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Url)
85
85
  : nodemailer.createTransport({ jsonTransport: true });
86
86
  const moderationMailer = new ModerationMailer(modMailTransport, cfg);
87
+ /**
88
+ * A fetch() function that protects against SSRF attacks, large responses &
89
+ * known bad domains. This function can safely be used to fetch user
90
+ * provided URLs (unless "disableSsrfProtection" is true, of course).
91
+ *
92
+ * @note **DO NOT** wrap `safeFetch` with any logging or other transforms as
93
+ * this might prevent the use of explicit `redirect: "follow"` init from
94
+ * working. See {@link safeFetchWrap}.
95
+ */
96
+ const safeFetch = safeFetchWrap({
97
+ allowIpHost: false,
98
+ allowImplicitRedirect: false,
99
+ responseMaxSize: cfg.fetch.maxResponseSize,
100
+ ssrfProtection: !cfg.fetch.disableSsrfProtection,
101
+ fetch: function (input, init) {
102
+ const method = init?.method ?? (input instanceof Request ? input.method : 'GET');
103
+ const uri = input instanceof Request ? input.url : String(input);
104
+ fetchLogger.info({ method, uri }, 'fetch');
105
+ return globalThis.fetch.call(this, input, init);
106
+ },
107
+ });
87
108
  const didCache = new DidSqliteCache(cfg.db.didCacheDbLoc, cfg.identity.cacheStaleTTL, cfg.identity.cacheMaxTTL, cfg.db.disableWalAutoCheckpoint);
88
109
  await didCache.migrateOrThrow();
89
110
  const idResolver = new IdResolver({
@@ -91,6 +112,7 @@ export class AppContext {
91
112
  didCache,
92
113
  timeout: cfg.identity.resolverTimeout,
93
114
  backupNameservers: cfg.identity.handleBackupNameservers,
115
+ fetch: safeFetch,
94
116
  });
95
117
  const plcClient = new plc.Client(cfg.identity.plcUrl);
96
118
  const backgroundQueue = new BackgroundQueue(undefined, { concurrency: 5 });
@@ -157,27 +179,6 @@ export class AppContext {
157
179
  const localViewer = LocalViewer.creator(accountManager, imageUrlBuilder, bskyAppView);
158
180
  // An agent for performing HTTP requests based on user provided URLs.
159
181
  const proxyAgent = buildProxyAgent(cfg.proxy);
160
- /**
161
- * A fetch() function that protects against SSRF attacks, large responses &
162
- * known bad domains. This function can safely be used to fetch user
163
- * provided URLs (unless "disableSsrfProtection" is true, of course).
164
- *
165
- * @note **DO NOT** wrap `safeFetch` with any logging or other transforms as
166
- * this might prevent the use of explicit `redirect: "follow"` init from
167
- * working. See {@link safeFetchWrap}.
168
- */
169
- const safeFetch = safeFetchWrap({
170
- allowIpHost: false,
171
- allowImplicitRedirect: false,
172
- responseMaxSize: cfg.fetch.maxResponseSize,
173
- ssrfProtection: !cfg.fetch.disableSsrfProtection,
174
- fetch: function (input, init) {
175
- const method = init?.method ?? (input instanceof Request ? input.method : 'GET');
176
- const uri = input instanceof Request ? input.url : String(input);
177
- fetchLogger.info({ method, uri }, 'fetch');
178
- return globalThis.fetch.call(this, input, init);
179
- },
180
- });
181
182
  const oauthProvider = cfg.oauth.provider
182
183
  ? new OAuthProvider({
183
184
  issuer: cfg.oauth.issuer,
@@ -338,6 +339,22 @@ export class AppContext {
338
339
  entrywayPassthruHeaders(req) {
339
340
  return forwardedFor(req, authPassthru(req));
340
341
  }
342
+ /**
343
+ * A {@link Client} for a service URL that was resolved from a DID document,
344
+ * i.e. a URL the PDS does not control. Routes the request through
345
+ * {@link safeFetch}, which restricts it to https origins that resolve to
346
+ * unicast addresses, and caps the response size. Lexicon validation follows
347
+ * the service's dev mode, as it does for the AppView client.
348
+ *
349
+ * Any call built from a DID document's service endpoint must use this.
350
+ */
351
+ safeClient(service) {
352
+ return new Client({ service, fetch: this.safeFetch }, {
353
+ validateRequest: this.cfg.service.devMode,
354
+ validateResponse: this.cfg.service.devMode,
355
+ strictResponseProcessing: this.cfg.service.devMode,
356
+ });
357
+ }
341
358
  async serviceAuthHeaders(did, aud, lxm) {
342
359
  const keypair = await this.actorStore.keypair(did);
343
360
  return createServiceAuthHeaders({
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAA;AAChC,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AAGnC,OAAO,KAAK,UAAU,MAAM,YAAY,CAAA;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MAAM,OAAO,GAAG,GAAG,CAAC,QAAQ,CAC1B,GAAG,CAAC,UAAU,CAAC,GAAG,QAAQ,IAAI,QAAQ,EAAE,EAAE,MAAM,CAAC,EACjD,WAAW,CACZ,CAAA;IACD,OAAO,SAAS,OAAO,EAAE,CAAA;AAC3B,CAAC,CAAA;AAED,eAAe,UAAU,CAAA","sourcesContent":["import assert from 'node:assert'\nimport * as plc from '@did-plc/lib'\nimport type express from 'express'\nimport type { Redis } from 'ioredis'\nimport * as nodemailer from 'nodemailer'\nimport * as ui8 from 'uint8arrays'\nimport type * as undici from 'undici'\nimport { KmsKeypair, S3BlobStore } from '@atproto/aws'\nimport * as crypto from '@atproto/crypto'\nimport { IdResolver } from '@atproto/identity'\nimport { Client } from '@atproto/lex'\nimport {\n AccessTokenMode,\n JoseKey,\n LexResolver,\n OAuthProvider,\n} from '@atproto/oauth-provider/provider'\nimport { OAuthVerifier } from '@atproto/oauth-provider/verifier'\nimport type { BlobStore } from '@atproto/repo'\nimport {\n createServiceAuthHeaders,\n createServiceJwt,\n} from '@atproto/xrpc-server'\nimport { type Fetch, safeFetchWrap } from '@atproto-labs/fetch-node'\nimport { AccountManager } from './account-manager/account-manager.js'\nimport { OAuthStore } from './account-manager/oauth-store.js'\nimport { ScopeReferenceGetter } from './account-manager/scope-reference-getter.js'\nimport { ActorStore } from './actor-store/actor-store.js'\nimport { authPassthru, forwardedFor } from './api/proxy.js'\nimport {\n AuthVerifier,\n createPublicKeyObject,\n createSecretKeyObject,\n} from './auth-verifier.js'\nimport { BackgroundQueue } from './background.js'\nimport { BskyAppView } from './bsky-app-view.js'\nimport {\n type ServerConfig,\n type ServerEnvironment,\n type ServerSecrets,\n envToCfg,\n envToSecrets,\n readEnv,\n} from './config/index.js'\nimport { Crawlers } from './crawlers.js'\nimport { DidSqliteCache } from './did-cache/index.js'\nimport { DiskBlobStore } from './disk-blobstore.js'\nimport { events } from './events.js'\nimport { ImageUrlBuilder } from './image/image-url-builder.js'\nimport { fetchLogger, lexiconResolverLogger, oauthLogger } from './logger.js'\nimport { ServerMailer } from './mailer/index.js'\nimport { ModerationMailer } from './mailer/moderation.js'\nimport { buildProxyAgent } from './pipethrough.js'\nimport {\n LocalViewer,\n type LocalViewerCreator,\n} from './read-after-write/viewer.js'\nimport { getRedisClient } from './redis.js'\nimport { Sequencer } from './sequencer/index.js'\n\nexport type AppContextOptions = {\n actorStore: ActorStore\n blobstore: (did: string) => BlobStore\n localViewer: LocalViewerCreator\n mailer: ServerMailer\n moderationMailer: ModerationMailer\n didCache: DidSqliteCache\n idResolver: IdResolver\n plcClient: plc.Client\n accountManager: AccountManager\n sequencer: Sequencer\n backgroundQueue: BackgroundQueue\n redisScratch?: Redis\n crawlers: Crawlers\n bskyAppView?: BskyAppView\n moderationClient?: Client\n reportingClient?: Client\n entrywayClient?: Client\n entrywayAdminClient?: Client\n proxyAgent: undici.Dispatcher\n safeFetch: Fetch\n oauthProvider?: OAuthProvider\n authVerifier: AuthVerifier\n plcRotationKey: crypto.Keypair\n cfg: ServerConfig\n}\n\nexport class AppContext implements AsyncDisposable {\n public actorStore: ActorStore\n public blobstore: (did: string) => BlobStore\n public localViewer: LocalViewerCreator\n public mailer: ServerMailer\n public moderationMailer: ModerationMailer\n public didCache: DidSqliteCache\n public idResolver: IdResolver\n public plcClient: plc.Client\n public accountManager: AccountManager\n public sequencer: Sequencer\n public backgroundQueue: BackgroundQueue\n public redisScratch?: Redis\n public crawlers: Crawlers\n public bskyAppView?: BskyAppView\n public moderationClient: Client | undefined\n public reportingClient: Client | undefined\n public entrywayClient: Client | undefined\n public entrywayAdminClient: Client | undefined\n public proxyAgent: undici.Dispatcher\n public safeFetch: Fetch\n public authVerifier: AuthVerifier\n public oauthProvider?: OAuthProvider\n public plcRotationKey: crypto.Keypair\n public cfg: ServerConfig\n\n constructor(opts: AppContextOptions) {\n this.actorStore = opts.actorStore\n this.blobstore = opts.blobstore\n this.localViewer = opts.localViewer\n this.mailer = opts.mailer\n this.moderationMailer = opts.moderationMailer\n this.didCache = opts.didCache\n this.idResolver = opts.idResolver\n this.plcClient = opts.plcClient\n this.accountManager = opts.accountManager\n this.sequencer = opts.sequencer\n this.backgroundQueue = opts.backgroundQueue\n this.redisScratch = opts.redisScratch\n this.crawlers = opts.crawlers\n this.bskyAppView = opts.bskyAppView\n this.moderationClient = opts.moderationClient\n this.reportingClient = opts.reportingClient\n this.entrywayClient = opts.entrywayClient\n this.entrywayAdminClient = opts.entrywayAdminClient\n this.proxyAgent = opts.proxyAgent\n this.safeFetch = opts.safeFetch\n this.authVerifier = opts.authVerifier\n this.oauthProvider = opts.oauthProvider\n this.plcRotationKey = opts.plcRotationKey\n this.cfg = opts.cfg\n }\n\n static async fromEnv(\n env: ServerEnvironment = readEnv(),\n ): Promise<AppContext> {\n const cfg = envToCfg(env)\n const secrets = envToSecrets(env)\n return AppContext.fromConfig(cfg, secrets)\n }\n\n static async fromConfig(\n cfg: ServerConfig,\n secrets: ServerSecrets,\n overrides?: Partial<AppContextOptions>,\n ): Promise<AppContext> {\n // @TODO Implement using an AsyncDisposableStack\n\n const blobstore =\n cfg.blobstore.provider === 's3'\n ? S3BlobStore.creator({\n bucket: cfg.blobstore.bucket,\n region: cfg.blobstore.region,\n endpoint: cfg.blobstore.endpoint,\n forcePathStyle: cfg.blobstore.forcePathStyle,\n credentials: cfg.blobstore.credentials,\n uploadTimeoutMs: cfg.blobstore.uploadTimeoutMs,\n requestTimeoutMs: cfg.blobstore.requestTimeoutMs,\n })\n : DiskBlobStore.creator(\n cfg.blobstore.location,\n cfg.blobstore.tempLocation,\n )\n\n const mailTransport =\n cfg.email !== null\n ? nodemailer.createTransport(cfg.email.smtpUrl)\n : nodemailer.createTransport({ jsonTransport: true })\n\n const mailer = new ServerMailer(mailTransport, cfg.email, cfg.branding)\n\n const modMailTransport =\n cfg.moderationEmail !== null\n ? nodemailer.createTransport(cfg.moderationEmail.smtpUrl)\n : nodemailer.createTransport({ jsonTransport: true })\n\n const moderationMailer = new ModerationMailer(modMailTransport, cfg)\n\n const didCache = new DidSqliteCache(\n cfg.db.didCacheDbLoc,\n cfg.identity.cacheStaleTTL,\n cfg.identity.cacheMaxTTL,\n cfg.db.disableWalAutoCheckpoint,\n )\n await didCache.migrateOrThrow()\n\n const idResolver = new IdResolver({\n plcUrl: cfg.identity.plcUrl,\n didCache,\n timeout: cfg.identity.resolverTimeout,\n backupNameservers: cfg.identity.handleBackupNameservers,\n })\n const plcClient = new plc.Client(cfg.identity.plcUrl)\n\n const backgroundQueue = new BackgroundQueue(undefined, { concurrency: 5 })\n const crawlers = new Crawlers(\n backgroundQueue,\n cfg.service.hostname,\n cfg.crawlers,\n )\n const sequencer = new Sequencer(\n cfg.db.sequencerDbLoc,\n crawlers,\n undefined,\n cfg.db.disableWalAutoCheckpoint,\n )\n const redisScratch = cfg.redis\n ? getRedisClient(cfg.redis.address, cfg.redis.password)\n : undefined\n\n const bskyAppView = cfg.bskyAppView\n ? new BskyAppView({\n ...cfg.bskyAppView,\n validateResponse: cfg.service.devMode,\n })\n : undefined\n\n const moderationClient = cfg.modService\n ? new Client(\n { service: cfg.modService.url },\n {\n // Trust internal services to send us well-formed responses\n strictResponseProcessing: false,\n validateResponse: cfg.service.devMode,\n },\n )\n : undefined\n const reportingClient = cfg.reportService\n ? new Client(\n { service: cfg.reportService.url },\n {\n // Trust internal services to send us well-formed responses\n strictResponseProcessing: false,\n validateResponse: cfg.service.devMode,\n },\n )\n : undefined\n const entrywayClient = cfg.entryway\n ? new Client(\n { service: cfg.entryway.url },\n {\n // Trust internal services to send us well-formed responses\n strictResponseProcessing: false,\n validateResponse: cfg.service.devMode,\n },\n )\n : undefined\n const entrywayAdminClient =\n cfg.entryway && secrets.entrywayAdminToken\n ? new Client(\n {\n service: cfg.entryway.url,\n headers: {\n authorization: basicAuthHeader(\n 'admin',\n secrets.entrywayAdminToken,\n ),\n },\n },\n {\n // Trust internal services to send us well-formed responses\n strictResponseProcessing: false,\n validateResponse: cfg.service.devMode,\n },\n )\n : undefined\n\n const jwtSecretKey = createSecretKeyObject(secrets.jwtSecret)\n const jwtPublicKey = cfg.entryway\n ? createPublicKeyObject(cfg.entryway.jwtPublicKeyHex)\n : null\n\n const imageUrlBuilder = new ImageUrlBuilder(\n cfg.service.hostname,\n bskyAppView,\n )\n\n const actorStore = new ActorStore(cfg.actorStore, {\n blobstore,\n backgroundQueue,\n })\n\n const plcRotationKey =\n secrets.plcRotationKey.provider === 'kms'\n ? await KmsKeypair.load({\n keyId: secrets.plcRotationKey.keyId,\n })\n : await crypto.Secp256k1Keypair.import(\n secrets.plcRotationKey.privateKeyHex,\n )\n\n const accountManager = new AccountManager(\n cfg,\n actorStore,\n idResolver,\n jwtSecretKey,\n mailer,\n sequencer,\n plcClient,\n plcRotationKey,\n )\n await accountManager.migrateOrThrow()\n\n const localViewer = LocalViewer.creator(\n accountManager,\n imageUrlBuilder,\n bskyAppView,\n )\n\n // An agent for performing HTTP requests based on user provided URLs.\n const proxyAgent = buildProxyAgent(cfg.proxy)\n\n /**\n * A fetch() function that protects against SSRF attacks, large responses &\n * known bad domains. This function can safely be used to fetch user\n * provided URLs (unless \"disableSsrfProtection\" is true, of course).\n *\n * @note **DO NOT** wrap `safeFetch` with any logging or other transforms as\n * this might prevent the use of explicit `redirect: \"follow\"` init from\n * working. See {@link safeFetchWrap}.\n */\n const safeFetch = safeFetchWrap({\n allowIpHost: false,\n allowImplicitRedirect: false,\n responseMaxSize: cfg.fetch.maxResponseSize,\n ssrfProtection: !cfg.fetch.disableSsrfProtection,\n\n fetch: function (input, init) {\n const method =\n init?.method ?? (input instanceof Request ? input.method : 'GET')\n const uri = input instanceof Request ? input.url : String(input)\n\n fetchLogger.info({ method, uri }, 'fetch')\n\n return globalThis.fetch.call(this, input, init)\n },\n })\n\n const oauthProvider = cfg.oauth.provider\n ? new OAuthProvider({\n issuer: cfg.oauth.issuer,\n keyset: [await JoseKey.fromKeyLike(jwtSecretKey, undefined, 'HS256')],\n store: new OAuthStore(\n accountManager,\n actorStore,\n imageUrlBuilder,\n backgroundQueue,\n mailer,\n sequencer,\n plcClient,\n plcRotationKey,\n cfg.service.publicUrl,\n cfg.identity.recoveryDidKey,\n ),\n redis: redisScratch,\n dpopSecret: secrets.dpopSecret,\n inviteCodeRequired: cfg.invites.required,\n availableUserDomains: cfg.identity.serviceHandleDomains,\n hcaptcha: cfg.oauth.provider.hcaptcha,\n branding: cfg.oauth.provider.branding,\n safeFetch,\n lexResolver: new LexResolver({\n fetch: safeFetch,\n plcDirectoryUrl: cfg.identity.plcUrl,\n hooks: {\n onResolveAuthority: ({ nsid }) => {\n lexiconResolverLogger.debug(\n { nsid: nsid.toString() },\n 'Resolving lexicon DID authority',\n )\n // Override the lexicon did resolution to point to a custom PDS\n return cfg.lexicon.didAuthority\n },\n onResolveAuthorityResult({ nsid, did }) {\n lexiconResolverLogger.info(\n { nsid: nsid.toString(), did },\n 'Resolved lexicon DID',\n )\n },\n onResolveAuthorityError({ nsid, err }) {\n lexiconResolverLogger.error(\n { nsid: nsid.toString(), err },\n 'Lexicon DID resolution error',\n )\n },\n onFetchResult({ uri, cid }) {\n lexiconResolverLogger.info(\n { uri: uri.toString(), cid: cid.toString() },\n 'Fetched lexicon',\n )\n },\n onFetchError({ err, uri }) {\n lexiconResolverLogger.error(\n { uri: uri.toString(), err },\n 'Lexicon fetch error',\n )\n },\n },\n }),\n metadata: {\n protected_resources: [new URL(cfg.oauth.issuer).origin],\n },\n // If the PDS is both an authorization server & resource server (no\n // entryway), we can afford to check the token validity on every\n // request. This allows revoked tokens to be rejected immediately.\n // This also allows JWT to be shorter since some claims (notably the\n // \"scope\" claim) do not need to be included in the token.\n accessTokenMode: AccessTokenMode.stateful,\n\n getClientInfo(clientId) {\n return {\n isTrusted: cfg.oauth.provider?.trustedClients?.includes(clientId),\n }\n },\n onSignedUp({ account, data, clientId }) {\n events.accountCreated({\n source: 'oauth',\n did: account.did,\n clientId,\n invited: data.inviteCode != null,\n deactivated: false,\n })\n },\n onSignedIn({ account, clientId }) {\n events.signedIn({\n did: account.did,\n clientId,\n })\n },\n onAuthorized({ account, client }) {\n events.oauthAuthorized({\n did: account.did,\n clientId: client.id,\n clientFirstParty: client.isFirstParty,\n clientTrusted: client.isTrusted,\n clientConfidential: client.isConfidential,\n })\n },\n onTokenCreated({ account, client }) {\n events.sessionCreated({\n source: 'oauth',\n did: account.did,\n clientId: client.id,\n })\n },\n onTokenRefreshed({ account, client }) {\n events.sessionRefreshed({\n source: 'oauth',\n did: account.did,\n clientId: client.id,\n })\n },\n })\n : undefined\n\n const scopeRefGetter = entrywayClient\n ? new ScopeReferenceGetter(entrywayClient, redisScratch)\n : undefined\n\n const oauthVerifier: OAuthVerifier =\n oauthProvider ?? // OAuthProvider extends OAuthVerifier\n new OAuthVerifier({\n issuer: cfg.oauth.issuer,\n keyset: [await JoseKey.fromKeyLike(jwtPublicKey!, undefined, 'ES256K')],\n dpopSecret: secrets.dpopSecret,\n redis: redisScratch,\n onDecodeToken: async ({ payload, dpopProof }) => {\n // @TODO drop this once oauth provider no longer accepts DPoP proof with\n // query or fragment in \"htu\" claim.\n if (dpopProof?.htu.match(/[?#]/)) {\n oauthLogger.info(\n { htu: dpopProof.htu, client_id: payload.client_id },\n 'DPoP proof \"htu\" contains query or fragment',\n )\n }\n\n if (scopeRefGetter) {\n payload.scope = await scopeRefGetter.dereference(payload.scope)\n }\n\n return payload\n },\n })\n\n const authVerifier = new AuthVerifier(\n accountManager,\n idResolver,\n oauthVerifier,\n {\n publicUrl: cfg.service.publicUrl,\n jwtKey: jwtPublicKey ?? jwtSecretKey,\n adminPass: secrets.adminPassword,\n dids: {\n pds: cfg.service.did,\n entryway: cfg.entryway?.did,\n modService: cfg.modService?.did,\n },\n },\n )\n\n return new AppContext({\n actorStore,\n blobstore,\n localViewer,\n mailer,\n moderationMailer,\n didCache,\n idResolver,\n plcClient,\n accountManager,\n sequencer,\n backgroundQueue,\n redisScratch,\n crawlers,\n bskyAppView,\n moderationClient,\n reportingClient,\n entrywayClient,\n entrywayAdminClient,\n proxyAgent,\n safeFetch,\n authVerifier,\n oauthProvider,\n plcRotationKey,\n cfg,\n ...(overrides ?? {}),\n })\n }\n\n async appviewAuthHeaders(did: string, lxm: string) {\n assert(this.bskyAppView)\n return this.serviceAuthHeaders(did, this.bskyAppView.did, lxm)\n }\n\n async entrywayAuthHeaders(req: express.Request, did: string, lxm: string) {\n assert(this.cfg.entryway)\n const headers = await this.serviceAuthHeaders(\n did,\n this.cfg.entryway.did,\n lxm,\n )\n return forwardedFor(req, headers)\n }\n\n entrywayPassthruHeaders(req: express.Request) {\n return forwardedFor(req, authPassthru(req))\n }\n\n async serviceAuthHeaders(did: string, aud: string, lxm: string) {\n const keypair = await this.actorStore.keypair(did)\n return createServiceAuthHeaders({\n iss: did,\n aud,\n lxm,\n keypair,\n })\n }\n\n async serviceAuthJwt(did: string, aud: string, lxm: string) {\n const keypair = await this.actorStore.keypair(did)\n return createServiceJwt({\n iss: did,\n aud,\n lxm,\n keypair,\n })\n }\n\n async destroy(): Promise<void> {\n try {\n await this.backgroundQueue.destroy()\n } finally {\n try {\n await this.sequencer.destroy()\n } finally {\n try {\n await this.accountManager.close()\n } finally {\n try {\n await this.redisScratch?.quit()\n } finally {\n await this.proxyAgent.destroy()\n }\n }\n }\n }\n }\n\n async [Symbol.asyncDispose]() {\n await this.destroy()\n }\n}\n\nconst basicAuthHeader = (username: string, password: string) => {\n const encoded = ui8.toString(\n ui8.fromString(`${username}:${password}`, 'utf8'),\n 'base64pad',\n )\n return `Basic ${encoded}`\n}\n\nexport default AppContext\n"]}
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAA;AAChC,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AAGnC,OAAO,KAAK,UAAU,MAAM,YAAY,CAAA;AACxC,OAAO,KAAK,GAAG,MAAM,aAAa,CAAA;AAElC,OAAO,EAAE,UAAU,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AAC;4BAAS,CAAC;wBACT,MAAM,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,CAAA;oBACjC,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAED,KAAK,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC;QACzB,MAAM,IAAI,CAAC,OAAO,EAAE,CAAA;IACtB,CAAC;CACF;AAED,MAAM,eAAe,GAAG,CAAC,QAAgB,EAAE,QAAgB,EAAE,EAAE;IAC7D,MAAM,OAAO,GAAG,GAAG,CAAC,QAAQ,CAC1B,GAAG,CAAC,UAAU,CAAC,GAAG,QAAQ,IAAI,QAAQ,EAAE,EAAE,MAAM,CAAC,EACjD,WAAW,CACZ,CAAA;IACD,OAAO,SAAS,OAAO,EAAE,CAAA;AAC3B,CAAC,CAAA;AAED,eAAe,UAAU,CAAA","sourcesContent":["import assert from 'node:assert'\nimport * as plc from '@did-plc/lib'\nimport type express from 'express'\nimport type { Redis } from 'ioredis'\nimport * as nodemailer from 'nodemailer'\nimport * as ui8 from 'uint8arrays'\nimport type * as undici from 'undici'\nimport { KmsKeypair, S3BlobStore } from '@atproto/aws'\nimport * as crypto from '@atproto/crypto'\nimport { IdResolver } from '@atproto/identity'\nimport { Client } from '@atproto/lex'\nimport {\n AccessTokenMode,\n JoseKey,\n LexResolver,\n OAuthProvider,\n} from '@atproto/oauth-provider/provider'\nimport { OAuthVerifier } from '@atproto/oauth-provider/verifier'\nimport type { BlobStore } from '@atproto/repo'\nimport {\n createServiceAuthHeaders,\n createServiceJwt,\n} from '@atproto/xrpc-server'\nimport { type Fetch, safeFetchWrap } from '@atproto-labs/fetch-node'\nimport { AccountManager } from './account-manager/account-manager.js'\nimport { OAuthStore } from './account-manager/oauth-store.js'\nimport { ScopeReferenceGetter } from './account-manager/scope-reference-getter.js'\nimport { ActorStore } from './actor-store/actor-store.js'\nimport { authPassthru, forwardedFor } from './api/proxy.js'\nimport {\n AuthVerifier,\n createPublicKeyObject,\n createSecretKeyObject,\n} from './auth-verifier.js'\nimport { BackgroundQueue } from './background.js'\nimport { BskyAppView } from './bsky-app-view.js'\nimport {\n type ServerConfig,\n type ServerEnvironment,\n type ServerSecrets,\n envToCfg,\n envToSecrets,\n readEnv,\n} from './config/index.js'\nimport { Crawlers } from './crawlers.js'\nimport { DidSqliteCache } from './did-cache/index.js'\nimport { DiskBlobStore } from './disk-blobstore.js'\nimport { events } from './events.js'\nimport { ImageUrlBuilder } from './image/image-url-builder.js'\nimport { fetchLogger, lexiconResolverLogger, oauthLogger } from './logger.js'\nimport { ServerMailer } from './mailer/index.js'\nimport { ModerationMailer } from './mailer/moderation.js'\nimport { buildProxyAgent } from './pipethrough.js'\nimport {\n LocalViewer,\n type LocalViewerCreator,\n} from './read-after-write/viewer.js'\nimport { getRedisClient } from './redis.js'\nimport { Sequencer } from './sequencer/index.js'\n\nexport type AppContextOptions = {\n actorStore: ActorStore\n blobstore: (did: string) => BlobStore\n localViewer: LocalViewerCreator\n mailer: ServerMailer\n moderationMailer: ModerationMailer\n didCache: DidSqliteCache\n idResolver: IdResolver\n plcClient: plc.Client\n accountManager: AccountManager\n sequencer: Sequencer\n backgroundQueue: BackgroundQueue\n redisScratch?: Redis\n crawlers: Crawlers\n bskyAppView?: BskyAppView\n moderationClient?: Client\n reportingClient?: Client\n entrywayClient?: Client\n entrywayAdminClient?: Client\n proxyAgent: undici.Dispatcher\n safeFetch: Fetch\n oauthProvider?: OAuthProvider\n authVerifier: AuthVerifier\n plcRotationKey: crypto.Keypair\n cfg: ServerConfig\n}\n\nexport class AppContext implements AsyncDisposable {\n public actorStore: ActorStore\n public blobstore: (did: string) => BlobStore\n public localViewer: LocalViewerCreator\n public mailer: ServerMailer\n public moderationMailer: ModerationMailer\n public didCache: DidSqliteCache\n public idResolver: IdResolver\n public plcClient: plc.Client\n public accountManager: AccountManager\n public sequencer: Sequencer\n public backgroundQueue: BackgroundQueue\n public redisScratch?: Redis\n public crawlers: Crawlers\n public bskyAppView?: BskyAppView\n public moderationClient: Client | undefined\n public reportingClient: Client | undefined\n public entrywayClient: Client | undefined\n public entrywayAdminClient: Client | undefined\n public proxyAgent: undici.Dispatcher\n public safeFetch: Fetch\n public authVerifier: AuthVerifier\n public oauthProvider?: OAuthProvider\n public plcRotationKey: crypto.Keypair\n public cfg: ServerConfig\n\n constructor(opts: AppContextOptions) {\n this.actorStore = opts.actorStore\n this.blobstore = opts.blobstore\n this.localViewer = opts.localViewer\n this.mailer = opts.mailer\n this.moderationMailer = opts.moderationMailer\n this.didCache = opts.didCache\n this.idResolver = opts.idResolver\n this.plcClient = opts.plcClient\n this.accountManager = opts.accountManager\n this.sequencer = opts.sequencer\n this.backgroundQueue = opts.backgroundQueue\n this.redisScratch = opts.redisScratch\n this.crawlers = opts.crawlers\n this.bskyAppView = opts.bskyAppView\n this.moderationClient = opts.moderationClient\n this.reportingClient = opts.reportingClient\n this.entrywayClient = opts.entrywayClient\n this.entrywayAdminClient = opts.entrywayAdminClient\n this.proxyAgent = opts.proxyAgent\n this.safeFetch = opts.safeFetch\n this.authVerifier = opts.authVerifier\n this.oauthProvider = opts.oauthProvider\n this.plcRotationKey = opts.plcRotationKey\n this.cfg = opts.cfg\n }\n\n static async fromEnv(\n env: ServerEnvironment = readEnv(),\n ): Promise<AppContext> {\n const cfg = envToCfg(env)\n const secrets = envToSecrets(env)\n return AppContext.fromConfig(cfg, secrets)\n }\n\n static async fromConfig(\n cfg: ServerConfig,\n secrets: ServerSecrets,\n overrides?: Partial<AppContextOptions>,\n ): Promise<AppContext> {\n // @TODO Implement using an AsyncDisposableStack\n\n const blobstore =\n cfg.blobstore.provider === 's3'\n ? S3BlobStore.creator({\n bucket: cfg.blobstore.bucket,\n region: cfg.blobstore.region,\n endpoint: cfg.blobstore.endpoint,\n forcePathStyle: cfg.blobstore.forcePathStyle,\n credentials: cfg.blobstore.credentials,\n uploadTimeoutMs: cfg.blobstore.uploadTimeoutMs,\n requestTimeoutMs: cfg.blobstore.requestTimeoutMs,\n })\n : DiskBlobStore.creator(\n cfg.blobstore.location,\n cfg.blobstore.tempLocation,\n )\n\n const mailTransport =\n cfg.email !== null\n ? nodemailer.createTransport(cfg.email.smtpUrl)\n : nodemailer.createTransport({ jsonTransport: true })\n\n const mailer = new ServerMailer(mailTransport, cfg.email, cfg.branding)\n\n const modMailTransport =\n cfg.moderationEmail !== null\n ? nodemailer.createTransport(cfg.moderationEmail.smtpUrl)\n : nodemailer.createTransport({ jsonTransport: true })\n\n const moderationMailer = new ModerationMailer(modMailTransport, cfg)\n\n /**\n * A fetch() function that protects against SSRF attacks, large responses &\n * known bad domains. This function can safely be used to fetch user\n * provided URLs (unless \"disableSsrfProtection\" is true, of course).\n *\n * @note **DO NOT** wrap `safeFetch` with any logging or other transforms as\n * this might prevent the use of explicit `redirect: \"follow\"` init from\n * working. See {@link safeFetchWrap}.\n */\n const safeFetch = safeFetchWrap({\n allowIpHost: false,\n allowImplicitRedirect: false,\n responseMaxSize: cfg.fetch.maxResponseSize,\n ssrfProtection: !cfg.fetch.disableSsrfProtection,\n\n fetch: function (input, init) {\n const method =\n init?.method ?? (input instanceof Request ? input.method : 'GET')\n const uri = input instanceof Request ? input.url : String(input)\n\n fetchLogger.info({ method, uri }, 'fetch')\n\n return globalThis.fetch.call(this, input, init)\n },\n })\n\n const didCache = new DidSqliteCache(\n cfg.db.didCacheDbLoc,\n cfg.identity.cacheStaleTTL,\n cfg.identity.cacheMaxTTL,\n cfg.db.disableWalAutoCheckpoint,\n )\n await didCache.migrateOrThrow()\n\n const idResolver = new IdResolver({\n plcUrl: cfg.identity.plcUrl,\n didCache,\n timeout: cfg.identity.resolverTimeout,\n backupNameservers: cfg.identity.handleBackupNameservers,\n fetch: safeFetch,\n })\n const plcClient = new plc.Client(cfg.identity.plcUrl)\n\n const backgroundQueue = new BackgroundQueue(undefined, { concurrency: 5 })\n const crawlers = new Crawlers(\n backgroundQueue,\n cfg.service.hostname,\n cfg.crawlers,\n )\n const sequencer = new Sequencer(\n cfg.db.sequencerDbLoc,\n crawlers,\n undefined,\n cfg.db.disableWalAutoCheckpoint,\n )\n const redisScratch = cfg.redis\n ? getRedisClient(cfg.redis.address, cfg.redis.password)\n : undefined\n\n const bskyAppView = cfg.bskyAppView\n ? new BskyAppView({\n ...cfg.bskyAppView,\n validateResponse: cfg.service.devMode,\n })\n : undefined\n\n const moderationClient = cfg.modService\n ? new Client(\n { service: cfg.modService.url },\n {\n // Trust internal services to send us well-formed responses\n strictResponseProcessing: false,\n validateResponse: cfg.service.devMode,\n },\n )\n : undefined\n const reportingClient = cfg.reportService\n ? new Client(\n { service: cfg.reportService.url },\n {\n // Trust internal services to send us well-formed responses\n strictResponseProcessing: false,\n validateResponse: cfg.service.devMode,\n },\n )\n : undefined\n const entrywayClient = cfg.entryway\n ? new Client(\n { service: cfg.entryway.url },\n {\n // Trust internal services to send us well-formed responses\n strictResponseProcessing: false,\n validateResponse: cfg.service.devMode,\n },\n )\n : undefined\n const entrywayAdminClient =\n cfg.entryway && secrets.entrywayAdminToken\n ? new Client(\n {\n service: cfg.entryway.url,\n headers: {\n authorization: basicAuthHeader(\n 'admin',\n secrets.entrywayAdminToken,\n ),\n },\n },\n {\n // Trust internal services to send us well-formed responses\n strictResponseProcessing: false,\n validateResponse: cfg.service.devMode,\n },\n )\n : undefined\n\n const jwtSecretKey = createSecretKeyObject(secrets.jwtSecret)\n const jwtPublicKey = cfg.entryway\n ? createPublicKeyObject(cfg.entryway.jwtPublicKeyHex)\n : null\n\n const imageUrlBuilder = new ImageUrlBuilder(\n cfg.service.hostname,\n bskyAppView,\n )\n\n const actorStore = new ActorStore(cfg.actorStore, {\n blobstore,\n backgroundQueue,\n })\n\n const plcRotationKey =\n secrets.plcRotationKey.provider === 'kms'\n ? await KmsKeypair.load({\n keyId: secrets.plcRotationKey.keyId,\n })\n : await crypto.Secp256k1Keypair.import(\n secrets.plcRotationKey.privateKeyHex,\n )\n\n const accountManager = new AccountManager(\n cfg,\n actorStore,\n idResolver,\n jwtSecretKey,\n mailer,\n sequencer,\n plcClient,\n plcRotationKey,\n )\n await accountManager.migrateOrThrow()\n\n const localViewer = LocalViewer.creator(\n accountManager,\n imageUrlBuilder,\n bskyAppView,\n )\n\n // An agent for performing HTTP requests based on user provided URLs.\n const proxyAgent = buildProxyAgent(cfg.proxy)\n\n const oauthProvider = cfg.oauth.provider\n ? new OAuthProvider({\n issuer: cfg.oauth.issuer,\n keyset: [await JoseKey.fromKeyLike(jwtSecretKey, undefined, 'HS256')],\n store: new OAuthStore(\n accountManager,\n actorStore,\n imageUrlBuilder,\n backgroundQueue,\n mailer,\n sequencer,\n plcClient,\n plcRotationKey,\n cfg.service.publicUrl,\n cfg.identity.recoveryDidKey,\n ),\n redis: redisScratch,\n dpopSecret: secrets.dpopSecret,\n inviteCodeRequired: cfg.invites.required,\n availableUserDomains: cfg.identity.serviceHandleDomains,\n hcaptcha: cfg.oauth.provider.hcaptcha,\n branding: cfg.oauth.provider.branding,\n safeFetch,\n lexResolver: new LexResolver({\n fetch: safeFetch,\n plcDirectoryUrl: cfg.identity.plcUrl,\n hooks: {\n onResolveAuthority: ({ nsid }) => {\n lexiconResolverLogger.debug(\n { nsid: nsid.toString() },\n 'Resolving lexicon DID authority',\n )\n // Override the lexicon did resolution to point to a custom PDS\n return cfg.lexicon.didAuthority\n },\n onResolveAuthorityResult({ nsid, did }) {\n lexiconResolverLogger.info(\n { nsid: nsid.toString(), did },\n 'Resolved lexicon DID',\n )\n },\n onResolveAuthorityError({ nsid, err }) {\n lexiconResolverLogger.error(\n { nsid: nsid.toString(), err },\n 'Lexicon DID resolution error',\n )\n },\n onFetchResult({ uri, cid }) {\n lexiconResolverLogger.info(\n { uri: uri.toString(), cid: cid.toString() },\n 'Fetched lexicon',\n )\n },\n onFetchError({ err, uri }) {\n lexiconResolverLogger.error(\n { uri: uri.toString(), err },\n 'Lexicon fetch error',\n )\n },\n },\n }),\n metadata: {\n protected_resources: [new URL(cfg.oauth.issuer).origin],\n },\n // If the PDS is both an authorization server & resource server (no\n // entryway), we can afford to check the token validity on every\n // request. This allows revoked tokens to be rejected immediately.\n // This also allows JWT to be shorter since some claims (notably the\n // \"scope\" claim) do not need to be included in the token.\n accessTokenMode: AccessTokenMode.stateful,\n\n getClientInfo(clientId) {\n return {\n isTrusted: cfg.oauth.provider?.trustedClients?.includes(clientId),\n }\n },\n onSignedUp({ account, data, clientId }) {\n events.accountCreated({\n source: 'oauth',\n did: account.did,\n clientId,\n invited: data.inviteCode != null,\n deactivated: false,\n })\n },\n onSignedIn({ account, clientId }) {\n events.signedIn({\n did: account.did,\n clientId,\n })\n },\n onAuthorized({ account, client }) {\n events.oauthAuthorized({\n did: account.did,\n clientId: client.id,\n clientFirstParty: client.isFirstParty,\n clientTrusted: client.isTrusted,\n clientConfidential: client.isConfidential,\n })\n },\n onTokenCreated({ account, client }) {\n events.sessionCreated({\n source: 'oauth',\n did: account.did,\n clientId: client.id,\n })\n },\n onTokenRefreshed({ account, client }) {\n events.sessionRefreshed({\n source: 'oauth',\n did: account.did,\n clientId: client.id,\n })\n },\n })\n : undefined\n\n const scopeRefGetter = entrywayClient\n ? new ScopeReferenceGetter(entrywayClient, redisScratch)\n : undefined\n\n const oauthVerifier: OAuthVerifier =\n oauthProvider ?? // OAuthProvider extends OAuthVerifier\n new OAuthVerifier({\n issuer: cfg.oauth.issuer,\n keyset: [await JoseKey.fromKeyLike(jwtPublicKey!, undefined, 'ES256K')],\n dpopSecret: secrets.dpopSecret,\n redis: redisScratch,\n onDecodeToken: async ({ payload, dpopProof }) => {\n // @TODO drop this once oauth provider no longer accepts DPoP proof with\n // query or fragment in \"htu\" claim.\n if (dpopProof?.htu.match(/[?#]/)) {\n oauthLogger.info(\n { htu: dpopProof.htu, client_id: payload.client_id },\n 'DPoP proof \"htu\" contains query or fragment',\n )\n }\n\n if (scopeRefGetter) {\n payload.scope = await scopeRefGetter.dereference(payload.scope)\n }\n\n return payload\n },\n })\n\n const authVerifier = new AuthVerifier(\n accountManager,\n idResolver,\n oauthVerifier,\n {\n publicUrl: cfg.service.publicUrl,\n jwtKey: jwtPublicKey ?? jwtSecretKey,\n adminPass: secrets.adminPassword,\n dids: {\n pds: cfg.service.did,\n entryway: cfg.entryway?.did,\n modService: cfg.modService?.did,\n },\n },\n )\n\n return new AppContext({\n actorStore,\n blobstore,\n localViewer,\n mailer,\n moderationMailer,\n didCache,\n idResolver,\n plcClient,\n accountManager,\n sequencer,\n backgroundQueue,\n redisScratch,\n crawlers,\n bskyAppView,\n moderationClient,\n reportingClient,\n entrywayClient,\n entrywayAdminClient,\n proxyAgent,\n safeFetch,\n authVerifier,\n oauthProvider,\n plcRotationKey,\n cfg,\n ...(overrides ?? {}),\n })\n }\n\n async appviewAuthHeaders(did: string, lxm: string) {\n assert(this.bskyAppView)\n return this.serviceAuthHeaders(did, this.bskyAppView.did, lxm)\n }\n\n async entrywayAuthHeaders(req: express.Request, did: string, lxm: string) {\n assert(this.cfg.entryway)\n const headers = await this.serviceAuthHeaders(\n did,\n this.cfg.entryway.did,\n lxm,\n )\n return forwardedFor(req, headers)\n }\n\n entrywayPassthruHeaders(req: express.Request) {\n return forwardedFor(req, authPassthru(req))\n }\n\n /**\n * A {@link Client} for a service URL that was resolved from a DID document,\n * i.e. a URL the PDS does not control. Routes the request through\n * {@link safeFetch}, which restricts it to https origins that resolve to\n * unicast addresses, and caps the response size. Lexicon validation follows\n * the service's dev mode, as it does for the AppView client.\n *\n * Any call built from a DID document's service endpoint must use this.\n */\n safeClient(service: string | URL): Client {\n return new Client(\n { service, fetch: this.safeFetch },\n {\n validateRequest: this.cfg.service.devMode,\n validateResponse: this.cfg.service.devMode,\n strictResponseProcessing: this.cfg.service.devMode,\n },\n )\n }\n\n async serviceAuthHeaders(did: string, aud: string, lxm: string) {\n const keypair = await this.actorStore.keypair(did)\n return createServiceAuthHeaders({\n iss: did,\n aud,\n lxm,\n keypair,\n })\n }\n\n async serviceAuthJwt(did: string, aud: string, lxm: string) {\n const keypair = await this.actorStore.keypair(did)\n return createServiceJwt({\n iss: did,\n aud,\n lxm,\n keypair,\n })\n }\n\n async destroy(): Promise<void> {\n try {\n await this.backgroundQueue.destroy()\n } finally {\n try {\n await this.sequencer.destroy()\n } finally {\n try {\n await this.accountManager.close()\n } finally {\n try {\n await this.redisScratch?.quit()\n } finally {\n await this.proxyAgent.destroy()\n }\n }\n }\n }\n }\n\n async [Symbol.asyncDispose]() {\n await this.destroy()\n }\n}\n\nconst basicAuthHeader = (username: string, password: string) => {\n const encoded = ui8.toString(\n ui8.fromString(`${username}:${password}`, 'utf8'),\n 'base64pad',\n )\n return `Basic ${encoded}`\n}\n\nexport default AppContext\n"]}
@@ -42,7 +42,7 @@ export declare const parseProxyHeader: (ctx: Pick<AppContext, 'cfg' | 'idResolve
42
42
  serviceId: string;
43
43
  }>;
44
44
  export declare function isJsonContentType(contentType?: string): boolean | undefined;
45
- export declare function asPipeThroughBuffer(input: HandlerPipeThroughStream): Promise<HandlerPipeThroughBuffer>;
45
+ export declare function asPipeThroughBuffer(input: HandlerPipeThroughStream, maxSize: number): Promise<HandlerPipeThroughBuffer>;
46
46
  /**
47
47
  * Performs lexicon method matching on a set of methods,
48
48
  * taking into account that they are treated case-insensitively.
@@ -1 +1 @@
1
- {"version":3,"file":"pipethrough.d.ts","sourceRoot":"","sources":["../src/pipethrough.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAkB,MAAM,WAAW,CAAA;AACpE,OAAO,EAAe,KAAK,QAAQ,EAAY,MAAM,aAAa,CAAA;AAClE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AACtC,OAAO,EAAS,KAAK,UAAU,EAAsB,MAAM,QAAQ,CAAA;AAQnE,OAAO,EACL,KAAK,eAAe,EACpB,KAAK,wBAAwB,EAC7B,KAAK,wBAAwB,EAI7B,SAAS,IAAI,eAAe,EAG7B,MAAM,sBAAsB,CAAA;AAI7B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,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AAE,mBAAmB,CAAA;KAC7B,EACD,OAAO,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,EAC7C,OAAO,CAAC,EAAE,YAAY,EAQvB;IAED,IAAI,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAEpC;IAED,IAAI,KAAK,uBAER;CACF"}
@@ -1,6 +1,6 @@
1
- import { PassThrough, finished } from 'node:stream';
1
+ import { PassThrough, finished, pipeline, } from 'node:stream';
2
2
  import { Agent, Pool, interceptors } from 'undici';
3
- import { decodeStream, getServiceEndpoint, omit, streamToNodeBuffer, } from '@atproto/common';
3
+ import { MaxSizeChecker, createDecoders, getServiceEndpoint, omit, streamToNodeBuffer, } from '@atproto/common';
4
4
  import { InternalServerError, InvalidRequestError, ResponseType, XRPCError as XRPCServerError, excludeErrorResult, parseReqNsid, } from '@atproto/xrpc-server';
5
5
  import { isUnicastIp, unicastLookup } from '@atproto-labs/fetch-node';
6
6
  import { buildProxiedContentEncoding } from '@atproto-labs/xrpc-utils';
@@ -244,7 +244,7 @@ async function pipethroughStream(ctx, req, dispatchOptions, successStreamFactory
244
244
  .stream(dispatchOptions, (upstream) => {
245
245
  if (upstream.statusCode >= 400) {
246
246
  const passThrough = new PassThrough();
247
- void tryParsingError(upstream.headers, passThrough).then((parsed) => {
247
+ void tryParsingError(upstream.headers, passThrough, ctx.cfg.proxy.maxResponseSize).then((parsed) => {
248
248
  const xrpcError = new PipethroughUpstreamError(upstream, parsed, {
249
249
  cause: dispatchOptions,
250
250
  });
@@ -281,7 +281,7 @@ async function pipethroughRequest(ctx, req, dispatchOptions) {
281
281
  .request(dispatchOptions)
282
282
  .catch(handleUpstreamRequestError.bind(req));
283
283
  if (upstream.statusCode >= 400) {
284
- const parsed = await tryParsingError(upstream.headers, upstream.body);
284
+ const parsed = await tryParsingError(upstream.headers, upstream.body, ctx.cfg.proxy.maxResponseSize);
285
285
  throw new PipethroughUpstreamError(upstream, parsed, {
286
286
  cause: dispatchOptions,
287
287
  });
@@ -305,7 +305,7 @@ export function isJsonContentType(contentType) {
305
305
  return undefined;
306
306
  return /application\/(?:\w+\+)?json/i.test(contentType);
307
307
  }
308
- async function tryParsingError(headers, readable) {
308
+ async function tryParsingError(headers, readable, maxSize) {
309
309
  if (isJsonContentType(headers['content-type']) === false) {
310
310
  // We don't known how to parse non JSON content types so we can discard the
311
311
  // whole response.
@@ -327,7 +327,7 @@ async function tryParsingError(headers, readable) {
327
327
  return {};
328
328
  }
329
329
  try {
330
- const buffer = await bufferUpstreamResponse(readable, headers['content-encoding']);
330
+ const buffer = await bufferUpstreamResponse(readable, headers['content-encoding'], maxSize);
331
331
  const errInfo = JSON.parse(buffer.toString('utf8'));
332
332
  return {
333
333
  error: safeString(errInfo?.['error']),
@@ -339,9 +339,17 @@ async function tryParsingError(headers, readable) {
339
339
  return {};
340
340
  }
341
341
  }
342
- async function bufferUpstreamResponse(readable, contentEncoding) {
342
+ async function bufferUpstreamResponse(readable, contentEncoding, maxSize) {
343
343
  try {
344
- return await streamToNodeBuffer(decodeStream(readable, contentEncoding));
344
+ // @NOTE maxResponseSize bounds the wire stream that undici reads, and
345
+ // decoding it can yield a much larger buffer, so the decoded stream needs
346
+ // its own bound. The checker is applied even when there is no
347
+ // content-encoding, so that an identity-encoded body is bounded too.
348
+ return await streamToNodeBuffer(pipeline([
349
+ readable,
350
+ ...createDecoders(contentEncoding),
351
+ new MaxSizeChecker(maxSize, () => new TypeError('upstream response too large')),
352
+ ], () => { }));
345
353
  }
346
354
  catch (err) {
347
355
  if (!readable.destroyed)
@@ -349,9 +357,9 @@ async function bufferUpstreamResponse(readable, contentEncoding) {
349
357
  throw new XRPCServerError(ResponseType.UpstreamFailure, err instanceof TypeError ? err.message : 'unable to decode request body', undefined, { cause: err });
350
358
  }
351
359
  }
352
- export async function asPipeThroughBuffer(input) {
360
+ export async function asPipeThroughBuffer(input, maxSize) {
353
361
  return {
354
- buffer: await bufferUpstreamResponse(input.stream, input.headers?.['content-encoding']),
362
+ buffer: await bufferUpstreamResponse(input.stream, input.headers?.['content-encoding'], maxSize),
355
363
  headers: omit(input.headers, ['content-encoding', 'content-length']),
356
364
  encoding: input.encoding,
357
365
  };
@@ -1 +1 @@
1
- {"version":3,"file":"pipethrough.js","sourceRoot":"","sources":["../src/pipethrough.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAiB,QAAQ,EAAE,MAAM,aAAa,CAAA;AAElE,OAAO,EAAE,KAAK,EAAmB,IAAI,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAA;AACnE,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,eAAe;QACpC,WAAW,EAAE,GAAG,CAAC,WAAW;QAC5B,OAAO,EAAE,GAAG,CAAC,qBAAqB;YAChC,CAAC,CAAC,SAAS;YACX,CAAC,CAAC,CAAC,MAAM,EAAE,IAAI,E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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,UAAU,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,EAAE,oCAAoC,CAAC,CAAA;AAChE,CAAC;AAED,MAAM,OAAO,wBAAyB,SAAQ,eAAe;IAC3D,YACW,QAGR,EACD,OAA6C,EAC7C,OAAsB;QAEtB,MAAM,MAAM,GACV,QAAQ,CAAC,UAAU,KAAK,GAAG;YACzB,CAAC,CAAC,YAAY,CAAC,eAAe;YAC9B,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAA;QAEzB,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;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 type { IncomingHttpHeaders, ServerResponse } from 'node:http'\nimport { PassThrough, type Readable, finished } from 'node:stream'\nimport type { Request } from 'express'\nimport { Agent, type Dispatcher, Pool, interceptors } from 'undici'\nimport {\n decodeStream,\n getServiceEndpoint,\n omit,\n streamToNodeBuffer,\n} from '@atproto/common'\nimport type { RpcPermissionMatch } from '@atproto/oauth-scopes'\nimport {\n type CatchallHandler,\n type HandlerPipeThroughBuffer,\n type 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 type { ProxyConfig } from './config/config.js'\nimport type { 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 ...getAtprotoPassthroughHeaders(req.headers),\n // @NOTE deprecated; use `x-atproto-bsky-topics`\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 ...getAtprotoPassthroughHeaders(req.headers),\n // @NOTE deprecated; use `x-atproto-bsky-topics`\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\nfunction getAtprotoPassthroughHeaders(\n headers: IncomingHttpHeaders,\n): IncomingHttpHeaders {\n // @NOTE node lower-cases all incoming header names, so a case-sensitive\n // prefix check is sufficient here. This runs on the request hot path, so we\n // build the result imperatively rather than via intermediate arrays.\n const result: IncomingHttpHeaders = {}\n for (const name in headers) {\n if (name.startsWith('x-atproto-')) {\n result[name] = headers[name]\n }\n }\n return result\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,EAEL,WAAW,EAEX,QAAQ,EACR,QAAQ,GACT,MAAM,aAAa,CAAA;AAEpB,OAAO,EAAE,KAAK,EAAmB,IAAI,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAA;AACnE,OAAO,EACL,cAAc,EACd,cAAc,EACd,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,2BAA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AAA;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 type { IncomingHttpHeaders, ServerResponse } from 'node:http'\nimport {\n type Duplex,\n PassThrough,\n type Readable,\n finished,\n pipeline,\n} from 'node:stream'\nimport type { Request } from 'express'\nimport { Agent, type Dispatcher, Pool, interceptors } from 'undici'\nimport {\n MaxSizeChecker,\n createDecoders,\n getServiceEndpoint,\n omit,\n streamToNodeBuffer,\n} from '@atproto/common'\nimport type { RpcPermissionMatch } from '@atproto/oauth-scopes'\nimport {\n type CatchallHandler,\n type HandlerPipeThroughBuffer,\n type 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 type { ProxyConfig } from './config/config.js'\nimport type { 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 ...getAtprotoPassthroughHeaders(req.headers),\n // @NOTE deprecated; use `x-atproto-bsky-topics`\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 ...getAtprotoPassthroughHeaders(req.headers),\n // @NOTE deprecated; use `x-atproto-bsky-topics`\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\nfunction getAtprotoPassthroughHeaders(\n headers: IncomingHttpHeaders,\n): IncomingHttpHeaders {\n // @NOTE node lower-cases all incoming header names, so a case-sensitive\n // prefix check is sufficient here. This runs on the request hot path, so we\n // build the result imperatively rather than via intermediate arrays.\n const result: IncomingHttpHeaders = {}\n for (const name in headers) {\n if (name.startsWith('x-atproto-')) {\n result[name] = headers[name]\n }\n }\n return result\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(\n upstream.headers,\n passThrough,\n ctx.cfg.proxy.maxResponseSize,\n ).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(\n upstream.headers,\n upstream.body,\n ctx.cfg.proxy.maxResponseSize,\n )\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 maxSize: number,\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 maxSize,\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[] | undefined,\n maxSize: number,\n): Promise<Buffer> {\n try {\n // @NOTE maxResponseSize bounds the wire stream that undici reads, and\n // decoding it can yield a much larger buffer, so the decoded stream needs\n // its own bound. The checker is applied even when there is no\n // content-encoding, so that an identity-encoded body is bounded too.\n return await streamToNodeBuffer(\n pipeline(\n [\n readable,\n ...createDecoders(contentEncoding),\n new MaxSizeChecker(\n maxSize,\n () => new TypeError('upstream response too large'),\n ),\n ],\n () => {},\n ) as Duplex,\n )\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 maxSize: number,\n): Promise<HandlerPipeThroughBuffer> {\n return {\n buffer: await bufferUpstreamResponse(\n input.stream,\n input.headers?.['content-encoding'],\n maxSize,\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 +1 @@
1
- {"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../../src/read-after-write/util.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,SAAS,CAAA;AAClC,OAAO,EAAE,KAAK,QAAQ,EAAE,CAAC,EAAE,MAAM,cAAc,CAAA;AAE/C,OAAO,KAAK,EACV,kBAAkB,EAEnB,MAAM,sBAAsB,CAAA;AAC7B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAO/C,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAExE,eAAO,MAAM,WAAW,UAAW,YAAY,KAAG,MAAM,GAAG,SAS1D,CAAA;AAED,eAAO,MAAM,yB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AC,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAA;CAC1D,OAEI,UAAU,UACP;IAAE,GAAG,EAAE,OAAO,CAAC,OAAO,CAAC;IAAC,IAAI,EAAE;QAAE,WAAW,EAAE;YAAE,GAAG,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,CAAA;CAAE,MACpE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SACN,OAAO,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,KACzC,OAAO,CACR,eAAe,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,GAAG,kBAAkB,CAoDjE,CAAA;AAED,eAAO,MAAM,oBAAoB,GAAI,CAAC,QAC9B,CAAC,QACD,MAAM,KACX,eAAe,CAAC,CAAC,CASlB,CAAA"}
@@ -34,7 +34,7 @@ export const pipethroughReadAfterWrite = async (ctx, reqCtx, ns, munge) => {
34
34
  const local = await store.record.getRecordsSinceRev(rev);
35
35
  if (local.count === 0)
36
36
  return streamRes;
37
- const { buffer } = (bufferRes = await asPipeThroughBuffer(streamRes));
37
+ const { buffer } = (bufferRes = await asPipeThroughBuffer(streamRes, ctx.cfg.proxy.maxResponseSize));
38
38
  const lex = lexParse(buffer.toString('utf8'), { strict: false });
39
39
  const result = method.output.schema.safeValidate(lex, { strict: false });
40
40
  // We won't perform munging with invalid upstream data
@@ -1 +1 @@
1
- {"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/read-after-write/util.ts"],"names":[],"mappings":"AACA,OAAO,EAAiB,CAAC,EAAE,MAAM,cAAc,CAAA;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAM5C,OAAO,EAAE,gBAAgB,IAAI,GAAG,EAAE,MAAM,cAAc,CAAA;AACtD,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,WAAW,GACZ,MAAM,mBAAmB,CAAA;AAG1B,MAAM,C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SAAS,IAAI,SAAS,CAAA;IAC/B,CAAC;AACH,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAClC,IAAO,EACP,GAAY,EACQ,EAAE,CAAC,CAAC;IACxB,QAAQ,EAAE,kBAAkB;IAC5B,IAAI;IACJ,OAAO,EACL,GAAG,KAAK,SAAS;QACf,CAAC,CAAC;YACE,sBAAsB,EAAE,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;SACzC;QACH,CAAC,CAAC,SAAS;CAChB,CAAC,CAAA","sourcesContent":["import type express from 'express'\nimport { type LexValue, l } from '@atproto/lex'\nimport { lexParse } from '@atproto/lex-json'\nimport type {\n HandlerPipeThrough,\n HandlerPipeThroughBuffer,\n} from '@atproto/xrpc-server'\nimport type { AppContext } from '../context.js'\nimport { readStickyLogger as log } from '../logger.js'\nimport {\n asPipeThroughBuffer,\n isJsonContentType,\n pipethrough,\n} from '../pipethrough.js'\nimport type { HandlerResponse, LocalRecords, MungeFn } from './types.js'\n\nexport const getLocalLag = (local: LocalRecords): number | undefined => {\n let oldest: string | undefined = local.profile?.indexedAt\n for (const post of local.posts) {\n if (!oldest || post.indexedAt < oldest) {\n oldest = post.indexedAt\n }\n }\n if (!oldest) return undefined\n return Date.now() - new Date(oldest).getTime()\n}\n\nexport const pipethroughReadAfterWrite = async <\n M extends (l.Query | l.Procedure) & {\n output: l.Payload<`application/json`, l.Schema<LexValue>>\n },\n>(\n ctx: AppContext,\n reqCtx: { req: express.Request; auth: { credentials: { did: string } } },\n ns: l.Main<M>,\n munge: MungeFn<l.InferMethodOutputBody<M>>,\n): Promise<\n HandlerResponse<l.InferMethodOutputBody<M>> | HandlerPipeThrough\n> => {\n const { req, auth } = reqCtx\n const requester = auth.credentials.did\n const method = l.getMain(ns)\n\n const streamRes = await pipethrough(ctx, req, { iss: requester })\n\n const rev = streamRes.headers['atproto-repo-rev']\n if (!rev) return streamRes\n\n if (isJsonContentType(streamRes.headers['content-type']) === false) {\n // content-type is present but not JSON, we can't munge this\n return streamRes\n }\n\n // if the munging fails, we can't return the original response because the\n // stream will already have been read. If we end-up buffering the response,\n // we'll return the buffered response in case of an error.\n let bufferRes: HandlerPipeThroughBuffer | undefined\n\n try {\n return await ctx.actorStore.read(requester, async (store) => {\n const local = await store.record.getRecordsSinceRev(rev)\n if (local.count === 0) return streamRes\n\n const { buffer } = (bufferRes = await asPipeThroughBuffer(streamRes))\n\n const lex = lexParse(buffer.toString('utf8'), { strict: false })\n\n const result = method.output.schema.safeValidate(lex, { strict: false })\n\n // We won't perform munging with invalid upstream data\n if (!result.success) return bufferRes\n\n const parsedRes = result.value as l.InferMethodOutputBody<M, never>\n\n const localViewer = ctx.localViewer(store)\n\n const data = await munge(localViewer, parsedRes, local, requester)\n return formatMungedResponse(data, getLocalLag(local))\n })\n } catch (err) {\n // The error occurred while reading the stream, this is non-recoverable\n if (!bufferRes && !streamRes.stream.readable) throw err\n\n log.warn({ err, requester }, 'error in read after write munge')\n return bufferRes ?? streamRes\n }\n}\n\nexport const formatMungedResponse = <T>(\n body: T,\n lag?: number,\n): HandlerResponse<T> => ({\n encoding: 'application/json',\n body,\n headers:\n lag !== undefined\n ? {\n 'Atproto-Upstream-Lag': lag.toString(10),\n }\n : undefined,\n})\n"]}
1
+ {"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/read-after-write/util.ts"],"names":[],"mappings":"AACA,OAAO,EAAiB,CAAC,EAAE,MAAM,cAAc,CAAA;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAM5C,OAAO,EAAE,gBAAgB,IAAI,GAAG,EAAE,MAAM,cAAc,CAAA;AACtD,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,WAAW,GACZ,MAAM,mBAAmB,CAAA;AAG1B,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,KAAmB,EAAsB,EAAE;IACrE,IAAI,MAAM,GAAuB,KAAK,CAAC,OAAO,EAAE,SAAS,CAAA;IACzD,KAA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AAM,oBAAoB,GAAG,CAClC,IAAO,EACP,GAAY,EACQ,EAAE,CAAC,CAAC;IACxB,QAAQ,EAAE,kBAAkB;IAC5B,IAAI;IACJ,OAAO,EACL,GAAG,KAAK,SAAS;QACf,CAAC,CAAC;YACE,sBAAsB,EAAE,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;SACzC;QACH,CAAC,CAAC,SAAS;CAChB,CAAC,CAAA","sourcesContent":["import type express from 'express'\nimport { type LexValue, l } from '@atproto/lex'\nimport { lexParse } from '@atproto/lex-json'\nimport type {\n HandlerPipeThrough,\n HandlerPipeThroughBuffer,\n} from '@atproto/xrpc-server'\nimport type { AppContext } from '../context.js'\nimport { readStickyLogger as log } from '../logger.js'\nimport {\n asPipeThroughBuffer,\n isJsonContentType,\n pipethrough,\n} from '../pipethrough.js'\nimport type { HandlerResponse, LocalRecords, MungeFn } from './types.js'\n\nexport const getLocalLag = (local: LocalRecords): number | undefined => {\n let oldest: string | undefined = local.profile?.indexedAt\n for (const post of local.posts) {\n if (!oldest || post.indexedAt < oldest) {\n oldest = post.indexedAt\n }\n }\n if (!oldest) return undefined\n return Date.now() - new Date(oldest).getTime()\n}\n\nexport const pipethroughReadAfterWrite = async <\n M extends (l.Query | l.Procedure) & {\n output: l.Payload<`application/json`, l.Schema<LexValue>>\n },\n>(\n ctx: AppContext,\n reqCtx: { req: express.Request; auth: { credentials: { did: string } } },\n ns: l.Main<M>,\n munge: MungeFn<l.InferMethodOutputBody<M>>,\n): Promise<\n HandlerResponse<l.InferMethodOutputBody<M>> | HandlerPipeThrough\n> => {\n const { req, auth } = reqCtx\n const requester = auth.credentials.did\n const method = l.getMain(ns)\n\n const streamRes = await pipethrough(ctx, req, { iss: requester })\n\n const rev = streamRes.headers['atproto-repo-rev']\n if (!rev) return streamRes\n\n if (isJsonContentType(streamRes.headers['content-type']) === false) {\n // content-type is present but not JSON, we can't munge this\n return streamRes\n }\n\n // if the munging fails, we can't return the original response because the\n // stream will already have been read. If we end-up buffering the response,\n // we'll return the buffered response in case of an error.\n let bufferRes: HandlerPipeThroughBuffer | undefined\n\n try {\n return await ctx.actorStore.read(requester, async (store) => {\n const local = await store.record.getRecordsSinceRev(rev)\n if (local.count === 0) return streamRes\n\n const { buffer } = (bufferRes = await asPipeThroughBuffer(\n streamRes,\n ctx.cfg.proxy.maxResponseSize,\n ))\n\n const lex = lexParse(buffer.toString('utf8'), { strict: false })\n\n const result = method.output.schema.safeValidate(lex, { strict: false })\n\n // We won't perform munging with invalid upstream data\n if (!result.success) return bufferRes\n\n const parsedRes = result.value as l.InferMethodOutputBody<M, never>\n\n const localViewer = ctx.localViewer(store)\n\n const data = await munge(localViewer, parsedRes, local, requester)\n return formatMungedResponse(data, getLocalLag(local))\n })\n } catch (err) {\n // The error occurred while reading the stream, this is non-recoverable\n if (!bufferRes && !streamRes.stream.readable) throw err\n\n log.warn({ err, requester }, 'error in read after write munge')\n return bufferRes ?? streamRes\n }\n}\n\nexport const formatMungedResponse = <T>(\n body: T,\n lag?: number,\n): HandlerResponse<T> => ({\n encoding: 'application/json',\n body,\n headers:\n lag !== undefined\n ? {\n 'Atproto-Upstream-Lag': lag.toString(10),\n }\n : undefined,\n})\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atproto/pds",
3
- "version": "0.5.33",
3
+ "version": "0.5.34",
4
4
  "license": "MIT",
5
5
  "description": "Reference implementation of atproto Personal Data Server (PDS)",
6
6
  "keywords": [
@@ -64,26 +64,26 @@
64
64
  "uint8arrays": "^5.0.0",
65
65
  "undici": "^8.5.0",
66
66
  "zod": "^3.23.8",
67
- "@atproto-labs/fetch-node": "^0.3.7",
68
- "@atproto-labs/opentelemetry-node": "^0.2.1",
67
+ "@atproto-labs/simple-store": "^0.5.1",
68
+ "@atproto-labs/fetch-node": "^0.4.0",
69
69
  "@atproto-labs/simple-store-memory": "^0.2.6",
70
70
  "@atproto-labs/simple-store-redis": "^0.1.6",
71
+ "@atproto/aws": "^0.3.17",
71
72
  "@atproto/common": "^0.8.3",
72
73
  "@atproto-labs/xrpc-utils": "^0.1.22",
73
- "@atproto-labs/simple-store": "^0.5.1",
74
- "@atproto/aws": "^0.3.17",
75
74
  "@atproto/crypto": "^0.5.5",
76
75
  "@atproto/did": "^0.5.5",
77
- "@atproto/identity": "^0.5.12",
76
+ "@atproto/identity": "^0.5.13",
77
+ "@atproto/lex": "^0.3.11",
78
+ "@atproto-labs/opentelemetry-node": "^0.2.1",
78
79
  "@atproto/lex-cbor": "^0.1.6",
79
- "@atproto/lex": "^0.3.10",
80
- "@atproto/lex-json": "^0.1.6",
81
80
  "@atproto/lex-data": "^0.1.7",
82
- "@atproto/oauth-provider": "^0.22.7",
83
- "@atproto/repo": "^0.10.14",
81
+ "@atproto/lex-json": "^0.1.6",
84
82
  "@atproto/oauth-scopes": "^0.5.12",
85
- "@atproto/syntax": "^0.7.6",
86
- "@atproto/xrpc-server": "^0.13.1"
83
+ "@atproto/oauth-provider": "^0.22.8",
84
+ "@atproto/repo": "^0.10.14",
85
+ "@atproto/xrpc-server": "^0.13.1",
86
+ "@atproto/syntax": "^0.7.6"
87
87
  },
88
88
  "devDependencies": {
89
89
  "@did-plc/server": "^0.0.1",
@@ -98,9 +98,9 @@
98
98
  "jest": "^30.5.1",
99
99
  "puppeteer": "^23.11.1",
100
100
  "ws": "^8.12.0",
101
- "@atproto/oauth-client-browser-example": "^0.1.8",
101
+ "@atproto/lex-document": "^0.1.11",
102
102
  "@atproto/api": "^0.20.44",
103
- "@atproto/lex-document": "^0.1.11"
103
+ "@atproto/oauth-client-browser-example": "^0.1.8"
104
104
  },
105
105
  "scripts": {
106
106
  "codegen:lex": "lex build --clear --indexFile --lexicons ../../lexicons",