@oxy.so/federation 2.16.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/cjs/apUri.js +0 -16
  2. package/dist/cjs/apValue.js +164 -0
  3. package/dist/cjs/index.js +17 -2
  4. package/dist/cjs/networkIdentity.js +2 -3
  5. package/dist/cjs/node/actorResolver.js +81 -110
  6. package/dist/cjs/node/actorRouter.js +2 -1
  7. package/dist/cjs/node/boundedBody.js +44 -0
  8. package/dist/cjs/node/inboundDispatch.js +6 -15
  9. package/dist/cjs/node/index.js +11 -1
  10. package/dist/cjs/node/signedFetch.js +15 -5
  11. package/dist/esm/apUri.js +0 -15
  12. package/dist/esm/apValue.js +155 -0
  13. package/dist/esm/index.js +10 -1
  14. package/dist/esm/networkIdentity.js +2 -3
  15. package/dist/esm/node/actorResolver.js +72 -101
  16. package/dist/esm/node/actorRouter.js +2 -1
  17. package/dist/esm/node/boundedBody.js +42 -0
  18. package/dist/esm/node/inboundDispatch.js +6 -15
  19. package/dist/esm/node/index.js +6 -1
  20. package/dist/esm/node/signedFetch.js +14 -5
  21. package/dist/types/apUri.d.ts +0 -7
  22. package/dist/types/apValue.d.ts +75 -0
  23. package/dist/types/index.d.ts +15 -16
  24. package/dist/types/node/actorResolver.d.ts +53 -11
  25. package/dist/types/node/boundedBody.d.ts +19 -0
  26. package/dist/types/node/inboundDispatch.d.ts +1 -0
  27. package/dist/types/node/index.d.ts +7 -2
  28. package/dist/types/node/signedFetch.d.ts +23 -2
  29. package/package.json +1 -1
  30. package/src/__tests__/actorResolver.test.ts +90 -2
  31. package/src/__tests__/apValue.test.ts +93 -0
  32. package/src/__tests__/networkIdentity.test.ts +4 -2
  33. package/src/__tests__/signedFetch.test.ts +26 -3
  34. package/src/apUri.ts +0 -15
  35. package/src/apValue.ts +153 -0
  36. package/src/index.ts +23 -17
  37. package/src/networkIdentity.ts +2 -2
  38. package/src/node/actorResolver.ts +139 -123
  39. package/src/node/actorRouter.ts +2 -2
  40. package/src/node/boundedBody.ts +62 -0
  41. package/src/node/inboundDispatch.ts +6 -14
  42. package/src/node/index.ts +18 -0
  43. package/src/node/signedFetch.ts +44 -6
@@ -26,6 +26,7 @@
26
26
  Object.defineProperty(exports, "__esModule", { value: true });
27
27
  exports.ActorResolutionPendingError = void 0;
28
28
  exports.createInboundDispatcher = createInboundDispatcher;
29
+ const apValue_1 = require("../apValue");
29
30
  const urls_1 = require("../urls");
30
31
  /**
31
32
  * Thrown when a federated follow is about to be bridged but the FOLLOWER actor
@@ -61,13 +62,13 @@ function parseInboundMove(activity, verifiedActorUri) {
61
62
  const activityId = typeof activity.id === 'string' ? activity.id : undefined;
62
63
  if (!activityId)
63
64
  return { ok: false, reason: 'missing id' };
64
- const actor = objectTargetUri(activity.actor);
65
+ const actor = (0, apValue_1.apIri)(activity.actor);
65
66
  if (actor !== verifiedActorUri)
66
67
  return { ok: false, reason: 'actor is not the signer' };
67
- const object = objectTargetUri(activity.object);
68
+ const object = (0, apValue_1.apIri)(activity.object);
68
69
  if (object !== verifiedActorUri)
69
70
  return { ok: false, reason: 'object is not the moving actor' };
70
- const target = objectTargetUri(activity.target);
71
+ const target = (0, apValue_1.apIri)(activity.target);
71
72
  if (!target)
72
73
  return { ok: false, reason: 'missing target' };
73
74
  try {
@@ -95,21 +96,11 @@ function actorUriHost(actorUri) {
95
96
  }
96
97
  }
97
98
  /** Read the `object`'s referenced actor/target uri (a string, or an embedded `{ id }`). */
98
- function objectTargetUri(object) {
99
- if (typeof object === 'string')
100
- return object;
101
- if (object && typeof object === 'object') {
102
- const id = object.id;
103
- if (typeof id === 'string')
104
- return id;
105
- }
106
- return undefined;
107
- }
108
99
  /** Build the inbound-activity dispatcher from an app's adapters + content handlers. */
109
100
  function createInboundDispatcher(config) {
110
101
  const { logger } = config;
111
102
  async function handleIncomingFollow(activity, actorUri) {
112
- const targetActorUri = objectTargetUri(activity.object);
103
+ const targetActorUri = (0, apValue_1.apIri)(activity.object);
113
104
  if (!targetActorUri)
114
105
  return;
115
106
  // Extract username from our actor URL
@@ -174,7 +165,7 @@ function createInboundDispatcher(config) {
174
165
  logger.info(`Accepted follow from ${actorUri} to ${username}`);
175
166
  }
176
167
  async function handleUndoFollow(object, actorUri) {
177
- const targetActorUri = objectTargetUri(object.object);
168
+ const targetActorUri = (0, apValue_1.apIri)(object.object);
178
169
  const match = targetActorUri?.match(/\/ap\/users\/([^/]+)$/);
179
170
  let localUserId;
180
171
  if (match) {
@@ -18,9 +18,19 @@
18
18
  * actor + inbox + follow-graph Express routers.
19
19
  */
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
- exports.createActorRouter = exports.goneTombstone = exports.buildActorDeleteActivity = exports.createWebfingerRouter = exports.ActorResolutionPendingError = exports.createInboundDispatcher = exports.DeliveryAuthorizationDeniedError = exports.createDeliveryService = exports.ActorResolver = exports.createActorResolver = exports.createIdentityBridge = exports.createTcoLinkExpander = exports.createSignedFetch = void 0;
21
+ exports.createActorRouter = exports.goneTombstone = exports.buildActorDeleteActivity = exports.createWebfingerRouter = exports.ActorResolutionPendingError = exports.createInboundDispatcher = exports.DeliveryAuthorizationDeniedError = exports.createDeliveryService = exports.ActorResolver = exports.createActorResolver = exports.createIdentityBridge = exports.createTcoLinkExpander = exports.ResponseBodyTimeoutError = exports.ResponseBodyTooLargeError = exports.readBoundedResponseText = exports.readBoundedResponseJson = exports.createSignedFetcher = exports.createSignedFetch = void 0;
22
22
  var signedFetch_1 = require("./signedFetch");
23
23
  Object.defineProperty(exports, "createSignedFetch", { enumerable: true, get: function () { return signedFetch_1.createSignedFetch; } });
24
+ Object.defineProperty(exports, "createSignedFetcher", { enumerable: true, get: function () { return signedFetch_1.createSignedFetcher; } });
25
+ /**
26
+ * Bounded, deadlined reads of a remote `Response` body (the one reader behind
27
+ * every federation document read).
28
+ */
29
+ var boundedBody_1 = require("./boundedBody");
30
+ Object.defineProperty(exports, "readBoundedResponseJson", { enumerable: true, get: function () { return boundedBody_1.readBoundedResponseJson; } });
31
+ Object.defineProperty(exports, "readBoundedResponseText", { enumerable: true, get: function () { return boundedBody_1.readBoundedResponseText; } });
32
+ Object.defineProperty(exports, "ResponseBodyTooLargeError", { enumerable: true, get: function () { return boundedBody_1.ResponseBodyTooLargeError; } });
33
+ Object.defineProperty(exports, "ResponseBodyTimeoutError", { enumerable: true, get: function () { return boundedBody_1.ResponseBodyTimeoutError; } });
24
34
  /**
25
35
  * X's `t.co` wrapper unwrapped into the link the author posted, over the same
26
36
  * injected single-hop transport — for bridged X bios and posts.
@@ -20,6 +20,7 @@
20
20
  */
21
21
  Object.defineProperty(exports, "__esModule", { value: true });
22
22
  exports.createSignedFetch = createSignedFetch;
23
+ exports.createSignedFetcher = createSignedFetcher;
23
24
  const httpSignature_1 = require("../httpSignature");
24
25
  /** Total time budget for a single signed hop (connect + response headers). */
25
26
  const SIGNED_FETCH_TIMEOUT_MS = 10000;
@@ -63,6 +64,11 @@ function requestInitHeaders(init) {
63
64
  * (see {@link SignedFetchInit.keyId}); such a request is never retried unsigned.
64
65
  */
65
66
  function createSignedFetch(config) {
67
+ const fetcher = createSignedFetcher(config);
68
+ return async (url, accept, init) => (await fetcher(url, accept, init)).response;
69
+ }
70
+ /** {@link createSignedFetch}, answering with the final URL as well ({@link SignedFetcher}). */
71
+ function createSignedFetcher(config) {
66
72
  return async function signedFetch(url, accept, init = {}) {
67
73
  const acceptHeader = `${accept}, application/ld+json; profile="https://www.w3.org/ns/activitystreams"`;
68
74
  const actorSigned = init.keyId !== undefined;
@@ -97,6 +103,7 @@ function createSignedFetch(config) {
97
103
  if (hop === SIGNED_FETCH_MAX_REDIRECTS || !location) {
98
104
  return { res, finalUrl: currentUrl };
99
105
  }
106
+ await res.body?.cancel().catch(() => { });
100
107
  currentUrl = new URL(location, currentUrl).toString();
101
108
  }
102
109
  throw new Error('redirect loop exhausted');
@@ -105,14 +112,17 @@ function createSignedFetch(config) {
105
112
  // An actor-signed answer is the remote's verdict for THAT actor (a follower or
106
113
  // recipient): an unsigned retry asks a different question, so it never runs.
107
114
  if (actorSigned)
108
- return res;
115
+ return { response: res, finalUrl };
109
116
  // If the remote server returns a 5xx (e.g. it can't resolve our keyId to
110
117
  // verify the signature), retry without the signature as a fallback for public
111
118
  // resources. Retry from the post-redirect URL so we don't restart a chain that
112
119
  // already landed on the failing hop.
113
120
  if (res.status >= 500) {
114
- config.logger?.info(`[FedSync] signedFetch got ${res.status} for ${finalUrl}, retrying unsigned`);
115
- return fetchFollowingRedirects(finalUrl, false).then(({ res: unsignedRes }) => unsignedRes);
121
+ config.logger?.info(`[FedSync] signedFetch got ${res.status} for ${finalUrl}, retrying unsigned`, { status: res.status, url: finalUrl });
122
+ // The failed signed answer's body is never read; release its stream.
123
+ await res.body?.cancel().catch(() => { });
124
+ const unsigned = await fetchFollowingRedirects(finalUrl, false);
125
+ return { response: unsigned.res, finalUrl: unsigned.finalUrl };
116
126
  }
117
127
  // A 401/403 on a signed request means the remote rejected OUR signature (e.g.
118
128
  // it could not resolve/verify our keyId, or our instance key pair is
@@ -121,8 +131,8 @@ function createSignedFetch(config) {
121
131
  // observable in production. The caller still receives the response and decides
122
132
  // how to proceed; we do not change control flow here.
123
133
  if (res.status === 401 || res.status === 403) {
124
- config.logger?.warn(`[FedSync] signedFetch got ${res.status} ${res.statusText} for ${url} — remote rejected our HTTP signature (check instance key pair / service token); returning the failed response so no posts are imported from this source`);
134
+ config.logger?.warn(`[FedSync] signedFetch got ${res.status} ${res.statusText} for ${url} — remote rejected our HTTP signature (check instance key pair / service token); returning the failed response so no posts are imported from this source`, { status: res.status, url: finalUrl });
125
135
  }
126
- return res;
136
+ return { response: res, finalUrl };
127
137
  };
128
138
  }
package/dist/esm/apUri.js CHANGED
@@ -69,21 +69,6 @@ export function isSameFederationHost(a, b) {
69
69
  return false;
70
70
  return canonicalA === canonicalFederationHost(b);
71
71
  }
72
- /**
73
- * The IRI a JSON-LD node reference names: the string itself, or the `id` of an
74
- * embedded object. ActivityStreams lets a server embed a referenced node (an
75
- * actor's `followers` collection with its `totalItems`, an `endpoints` value)
76
- * instead of linking it, and both mean the same node. Anything else names none.
77
- */
78
- export function apIri(value) {
79
- if (typeof value === 'string')
80
- return value || undefined;
81
- if (value && typeof value === 'object' && !Array.isArray(value)) {
82
- const id = value.id;
83
- return typeof id === 'string' && id ? id : undefined;
84
- }
85
- return undefined;
86
- }
87
72
  /**
88
73
  * Given an ActivityPub activity/object ID (URL), extract the actor URI by
89
74
  * trimming everything from the first recognised post-path segment onward.
@@ -0,0 +1,155 @@
1
+ /**
2
+ * The ONE way to read an ActivityStreams value whose JSON-LD shape varies.
3
+ *
4
+ * JSON-LD lets the same statement arrive in several shapes, and every one of
5
+ * them is valid ActivityPub:
6
+ *
7
+ * - compaction turns a one-element array into the value itself, so `tag`,
8
+ * `attachment`, `alsoKnownAs`, `to` or `icon` may be one object or a list
9
+ * (GoToSocial sends single values; Mastodon sends arrays);
10
+ * - a reference may be the IRI string, an embedded object naming it by `id`,
11
+ * or a `Link` naming it by `href`;
12
+ * - an image may be a URL string, an `Image` whose `url` is a string, a `Link`
13
+ * or a list of them, or a list of `Image`s (PeerTube 6+ sends icon sizes);
14
+ * - a media type may carry parameters (`application/ld+json; profile="…"`),
15
+ * spaced or quoted however the server likes;
16
+ * - a date may use any ISO 8601 offset spelling (`Z`, `+00:00`, `+0000`, `+00`).
17
+ *
18
+ * A reader that assumes one shape loses the others SILENTLY: the mention, tag,
19
+ * alias or avatar is simply not there, and nothing logs. These helpers accept
20
+ * every shape, so readers never re-derive the rule. They are pure and
21
+ * dependency-free (browser-safe).
22
+ */
23
+ /**
24
+ * A one-or-many ActivityStreams property as a list. A single value becomes a
25
+ * one-element list, an absent (`undefined` / `null`) value an empty one, and the
26
+ * `null` / `undefined` entries of a list are dropped.
27
+ */
28
+ export function apList(value) {
29
+ if (value === undefined || value === null)
30
+ return [];
31
+ if (!Array.isArray(value))
32
+ return [value];
33
+ return value.filter((entry) => entry !== undefined && entry !== null);
34
+ }
35
+ /**
36
+ * The IRI a JSON-LD node reference names: the string itself, the `id` of an
37
+ * embedded object, or the `href` of a `Link` (a `Mention` tag, a `Link` `url`).
38
+ * ActivityStreams lets a server embed a referenced node (an actor's `followers`
39
+ * collection with its `totalItems`, an `endpoints` value) instead of linking it,
40
+ * and all of these mean the same node. Anything else, a list included, names none;
41
+ * read a list through {@link apIriList}.
42
+ */
43
+ export function apIri(value) {
44
+ if (typeof value === 'string')
45
+ return value || undefined;
46
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
47
+ const { id, href } = value;
48
+ if (typeof id === 'string' && id)
49
+ return id;
50
+ if (typeof href === 'string' && href)
51
+ return href;
52
+ }
53
+ return undefined;
54
+ }
55
+ /**
56
+ * Every IRI a one-or-many reference property names (`to`, `cc`, `audience`,
57
+ * `alsoKnownAs`, `attributedTo`), in order: {@link apList} read through
58
+ * {@link apIri}, dropping the entries that name none.
59
+ */
60
+ export function apIriList(value) {
61
+ const iris = [];
62
+ for (const entry of apList(value)) {
63
+ const iri = apIri(entry);
64
+ if (iri)
65
+ iris.push(iri);
66
+ }
67
+ return iris;
68
+ }
69
+ function isAbsoluteHttpUrl(value) {
70
+ return /^https?:\/\/[^\s/]/i.test(value);
71
+ }
72
+ /** Nesting a real image value needs: icon list → Image → url list → Link. */
73
+ const AP_IMAGE_MAX_DEPTH = 4;
74
+ /**
75
+ * The first absolute http(s) URL an image-valued property (`icon`, `image`, an
76
+ * `Image` attachment's `url`) names: a URL string, an object's `url` or `href`
77
+ * (an `Image` whose `url` is a string, a `Link` or a list of them), or the
78
+ * first entry of a list that names one.
79
+ */
80
+ export function apImageUrl(value) {
81
+ return imageUrlAt(value, 0);
82
+ }
83
+ function imageUrlAt(value, depth) {
84
+ if (typeof value === 'string')
85
+ return isAbsoluteHttpUrl(value) ? value : undefined;
86
+ if (depth >= AP_IMAGE_MAX_DEPTH || !value || typeof value !== 'object')
87
+ return undefined;
88
+ if (Array.isArray(value)) {
89
+ for (const entry of value) {
90
+ const url = imageUrlAt(entry, depth + 1);
91
+ if (url)
92
+ return url;
93
+ }
94
+ return undefined;
95
+ }
96
+ const record = value;
97
+ return imageUrlAt(record.url, depth + 1) ?? imageUrlAt(record.href, depth + 1);
98
+ }
99
+ /**
100
+ * The base of a media type, lowercased and without parameters:
101
+ * `application/ld+json; profile="https://www.w3.org/ns/activitystreams"` and
102
+ * `Application/LD+JSON;profile=…` are both `application/ld+json`. Empty for a
103
+ * value that is not a string.
104
+ */
105
+ export function apMediaTypeBase(value) {
106
+ if (typeof value !== 'string')
107
+ return '';
108
+ return (value.split(';')[0] ?? '').trim().toLowerCase();
109
+ }
110
+ /**
111
+ * Whether a media type is an ActivityStreams document's (`application/activity+json`
112
+ * or `application/ld+json`, with any parameters): what a WebFinger `self` link or
113
+ * an actor response names.
114
+ */
115
+ export function isActivityPubMediaType(value) {
116
+ const base = apMediaTypeBase(value);
117
+ return base === 'application/activity+json' || base === 'application/ld+json';
118
+ }
119
+ const ISO_DATE_TIME = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2}(?::\d{2}(?:[.,]\d+)?)?)\s*(Z|z|[+-]\d{2}(?::?\d{2})?)?)?$/;
120
+ /**
121
+ * A date an ActivityStreams document asserts (`published`, `updated`, a field's
122
+ * `verifiedAt`), parsed leniently, or `undefined` when it names no date.
123
+ *
124
+ * ISO 8601 is read in every offset spelling servers send (`Z`, `+00:00`, `+0000`,
125
+ * `+00`), with a space for the `T`, a comma for the decimal point and a missing
126
+ * offset (read as UTC), so the result does not depend on the JavaScript engine's
127
+ * own `Date` parser. Another string is accepted when it names a four-digit year
128
+ * and that parser reads it (an RFC 2822 date). A `Date` passes through when
129
+ * valid. It never clamps: a caller that must bound future dates does so itself.
130
+ */
131
+ export function apDate(value) {
132
+ if (value instanceof Date)
133
+ return Number.isNaN(value.getTime()) ? undefined : value;
134
+ if (typeof value !== 'string')
135
+ return undefined;
136
+ const text = value.trim();
137
+ if (!text)
138
+ return undefined;
139
+ const iso = ISO_DATE_TIME.exec(text);
140
+ if (iso) {
141
+ const [, day, time = '00:00:00', offset = 'Z'] = iso;
142
+ const parsed = new Date(`${day}T${time.replace(',', '.')}${isoOffset(offset)}`);
143
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed;
144
+ }
145
+ if (!/\b\d{4}\b/.test(text))
146
+ return undefined;
147
+ const parsed = new Date(text);
148
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed;
149
+ }
150
+ function isoOffset(offset) {
151
+ if (offset === 'Z' || offset === 'z')
152
+ return 'Z';
153
+ const digits = offset.slice(1).replace(':', '');
154
+ return `${offset[0]}${digits.slice(0, 2)}:${digits.slice(2, 4) || '00'}`;
155
+ }
package/dist/esm/index.js CHANGED
@@ -56,7 +56,16 @@ export { FEDERATION_NETWORKS, BSKY_NETWORK_DOMAIN, blueskyUsernameFromHandle, bl
56
56
  * built from — not a parallel implementation that agrees today.
57
57
  */
58
58
  export { AP_CONTEXT } from './apContext.js';
59
- export { canonicalFederationHost, isSameFederationHost, extractActorUriFromActivityId, apIri, createDomainPolicy, } from './apUri.js';
59
+ export { canonicalFederationHost, isSameFederationHost, extractActorUriFromActivityId, createDomainPolicy, } from './apUri.js';
60
+ /**
61
+ * The one way to read an ActivityStreams value whose JSON-LD shape varies: a
62
+ * one-or-many property ({@link apList}), a reference by IRI, `id` or `href`
63
+ * ({@link apIri} / {@link apIriList}), an image ({@link apImageUrl}), a media
64
+ * type with parameters ({@link apMediaTypeBase} / {@link isActivityPubMediaType})
65
+ * and a date in any ISO 8601 offset spelling ({@link apDate}). A reader that
66
+ * assumes one shape silently loses the others.
67
+ */
68
+ export { apList, apIri, apIriList, apImageUrl, apMediaTypeBase, isActivityPubMediaType, apDate, } from './apValue.js';
60
69
  /**
61
70
  * The single builder of a LOCAL user's ActivityPub actor document —
62
71
  * byte-identical across apps, with media resolution injected. The actor `type`
@@ -47,6 +47,7 @@
47
47
  * built, so no relabel can resurrect it. Keeping them in separate structures
48
48
  * means neither can be edited into the other by accident.
49
49
  */
50
+ import { apList } from './apValue.js';
50
51
  import { canonicalFederationHost } from './apUri.js';
51
52
  /**
52
53
  * The networks Oxy re-labels accounts onto.
@@ -141,10 +142,8 @@ export const BSKY_NETWORK_DOMAIN = FEDERATION_NETWORKS.bluesky.domain;
141
142
  * copy of it", and only the former could ever justify moving an identity.
142
143
  */
143
144
  export function readProxyDeclarations(value) {
144
- if (!Array.isArray(value))
145
- return [];
146
145
  const declarations = [];
147
- for (const raw of value) {
146
+ for (const raw of apList(value)) {
148
147
  if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
149
148
  continue;
150
149
  const entry = raw;
@@ -18,9 +18,10 @@
18
18
  * e.g. Mention's `IFederatedActor`) so callers keep full typing on the returned
19
19
  * document.
20
20
  */
21
- import { apIri, isSameFederationHost } from '../apUri.js';
21
+ import { isSameFederationHost } from '../apUri.js';
22
+ import { apDate, apImageUrl, apIri, apIriList, apList, isActivityPubMediaType } from '../apValue.js';
22
23
  import { readProxyDeclarations, } from '../networkIdentity.js';
23
- import { readBodyChunks, ResponseBodyTooLargeError } from './boundedBody.js';
24
+ import { readBoundedResponseJson, readBoundedResponseText } from './boundedBody.js';
24
25
  /**
25
26
  * Minimum interval between background actor refreshes for the same actor.
26
27
  * Prevents refresh storms when a profile is viewed repeatedly in a short window.
@@ -47,46 +48,9 @@ const COLLECTION_BODY_MAX_BYTES = 64 * 1024;
47
48
  */
48
49
  const COLLECTION_WITHHELD_STATUSES = new Set([401, 403, 404, 410]);
49
50
  const ERROR_BODY_MAX_BYTES = 4 * 1024;
50
- /**
51
- * Deadline for reading a whole actor/collection/error body once its headers
52
- * arrived. `signedFetch`'s timeout ends at the headers, so without this a remote
53
- * that stalls mid-body would hold the resolver open.
54
- */
55
- const BODY_TIMEOUT_MS = 10000;
56
- async function readBoundedResponseBody(res, maxBytes) {
57
- const contentLength = res.headers.get('content-length');
58
- if (contentLength) {
59
- const declaredBytes = Number(contentLength);
60
- if (Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {
61
- await res.body?.cancel().catch(() => { });
62
- throw new ResponseBodyTooLargeError(maxBytes);
63
- }
64
- }
65
- if (!res.body)
66
- return '';
67
- const reader = res.body.getReader();
68
- const body = await readBodyChunks({ read: () => reader.read(), cancel: () => void reader.cancel().catch(() => { }) }, { maxBytes, timeoutMs: BODY_TIMEOUT_MS });
69
- return new TextDecoder('utf-8', { fatal: true }).decode(body);
70
- }
71
- async function readBoundedJson(res, maxBytes) {
72
- const body = await readBoundedResponseBody(res, maxBytes);
73
- // An empty body is a REMOTE's answer, not a parser error. Without this,
74
- // `JSON.parse('')` throws a SyntaxError whose message names a column number,
75
- // which is a worse thing to find in a federation log than the fact that the
76
- // instance sent nothing.
77
- if (body.length === 0)
78
- throw new Error('Remote response has no body');
79
- const value = JSON.parse(body);
80
- const record = asRecord(value);
81
- if (!record)
82
- throw new Error('Remote response is not a JSON object');
83
- return record;
84
- }
85
- function isApActorContentType(type) {
86
- if (!type)
87
- return false;
88
- const base = type.split(';')[0]?.trim().toLowerCase();
89
- return base === 'application/activity+json' || base === 'application/ld+json';
51
+ /** Whether a read produced a document the resolver can parse. */
52
+ function hasActorDocument(fetched) {
53
+ return fetched.status >= 200 && fetched.status < 300 && fetched.document !== undefined;
90
54
  }
91
55
  function asRecord(value) {
92
56
  return value && typeof value === 'object' && !Array.isArray(value)
@@ -134,6 +98,22 @@ export class ActorResolver {
134
98
  /** Actor key refetches in flight, by actor URI: concurrent failed signatures share one. */
135
99
  this.inFlightKeyRefetches = new Map();
136
100
  }
101
+ /** One read of an actor document: the app's {@link ActorResolverConfig.fetchActorDocument}, or a signed GET. */
102
+ async readActorDocument(actorUri, acctHint) {
103
+ if (this.config.fetchActorDocument)
104
+ return this.config.fetchActorDocument(actorUri, acctHint);
105
+ const res = await this.config.signedFetch(actorUri, AP_CONTENT_TYPE);
106
+ if (res.ok) {
107
+ return {
108
+ status: res.status,
109
+ document: await readBoundedResponseJson(res, { maxBytes: ACTOR_BODY_MAX_BYTES }),
110
+ };
111
+ }
112
+ if (res.status === 410)
113
+ return { status: res.status };
114
+ const body = await readBoundedResponseText(res, { maxBytes: ERROR_BODY_MAX_BYTES }).catch(() => '');
115
+ return { status: res.status, detail: `${res.statusText} body=${body.slice(0, 500)}`.trim() };
116
+ }
137
117
  /**
138
118
  * Whether an actor URI's host is refused by the instance domain policy. An
139
119
  * unparseable URI has no host to check, so it is refused too — the policy is a
@@ -176,7 +156,7 @@ export class ActorResolver {
176
156
  const data = await this.config.fetchWebFinger(url);
177
157
  if (!data)
178
158
  return null;
179
- const link = data.links?.find((l) => l.rel === 'self' && isApActorContentType(l.type));
159
+ const link = data.links?.find((l) => l.rel === 'self' && isActivityPubMediaType(l.type));
180
160
  return link?.href || null;
181
161
  }
182
162
  catch (err) {
@@ -206,19 +186,17 @@ export class ActorResolver {
206
186
  return null;
207
187
  }
208
188
  const canonicalAcctHint = this.config.normalizeFederatedAcct(acctHint);
209
- // Use signed fetch for servers that enforce authorized fetch (e.g., Threads)
210
- let res = await this.config.signedFetch(currentUri, AP_CONTENT_TYPE);
211
- if (!res.ok) {
189
+ let fetched = await this.readActorDocument(currentUri, canonicalAcctHint);
190
+ if (!hasActorDocument(fetched)) {
212
191
  // A definitive 410 Gone is authoritative: tombstone and stop — do NOT fall
213
192
  // through to the WebFinger fallback (which recovers a STALE/wrong URI on a
214
193
  // transient failure, not a permanent removal). Only 410 does this.
215
- if (res.status === 410) {
194
+ if (fetched.status === 410) {
216
195
  this.config.logger.info(`[FedSync] fetchRemoteActor 410 Gone for ${currentUri} — tombstoning actor`);
217
196
  await this.tombstoneGoneActor(currentUri);
218
197
  return null;
219
198
  }
220
- const body = await readBoundedResponseBody(res, ERROR_BODY_MAX_BYTES).catch(() => '');
221
- this.config.logger.info(`[FedSync] fetchRemoteActor HTTP ${res.status} ${res.statusText} for ${currentUri} body=${body.slice(0, 500)}`);
199
+ this.config.logger.info(`[FedSync] fetchRemoteActor HTTP ${fetched.status}${fetched.detail ? ` ${fetched.detail}` : ''} for ${currentUri}`);
222
200
  // If direct fetch failed, try WebFinger to resolve the canonical actor URI.
223
201
  // Some servers (e.g., Threads) use numeric IDs in AP URIs that differ from
224
202
  // the username-based URI we may have stored.
@@ -228,38 +206,30 @@ export class ActorResolver {
228
206
  (pathUsername
229
207
  ? this.config.normalizeFederatedAcct(`${pathUsername}@${parsed.hostname}`)
230
208
  : undefined);
231
- if (acct) {
232
- this.config.logger.info(`[FedSync] attempting WebFinger fallback for ${acct}`);
233
- const resolved = await this.resolveWebFinger(acct);
234
- if (resolved && resolved !== currentUri) {
235
- this.config.logger.info(`[FedSync] WebFinger resolved ${acct} → ${resolved}`);
236
- res = await this.config.signedFetch(resolved, AP_CONTENT_TYPE);
237
- if (res.ok) {
238
- currentUri = resolved;
239
- }
240
- else {
241
- // A 410 on the WebFinger-RESOLVED URI is just as definitive. Tombstone
242
- // against the stored URI (not reassigned on this branch).
243
- if (res.status === 410) {
244
- this.config.logger.info(`[FedSync] fetchRemoteActor 410 Gone for resolved ${resolved} — tombstoning actor ${currentUri}`);
245
- await this.tombstoneGoneActor(currentUri);
246
- return null;
247
- }
248
- const body2 = await readBoundedResponseBody(res, ERROR_BODY_MAX_BYTES).catch(() => '');
249
- this.config.logger.info(`[FedSync] fetchRemoteActor HTTP ${res.status} for resolved ${resolved} body=${body2.slice(0, 500)}`);
250
- return null;
251
- }
252
- }
253
- else {
254
- this.config.logger.info(`[FedSync] WebFinger returned ${resolved ?? 'null'} for ${acct}`);
209
+ if (!acct)
210
+ return null;
211
+ this.config.logger.info(`[FedSync] attempting WebFinger fallback for ${acct}`);
212
+ const resolved = await this.resolveWebFinger(acct);
213
+ if (!resolved || resolved === currentUri) {
214
+ this.config.logger.info(`[FedSync] WebFinger returned ${resolved ?? 'null'} for ${acct}`);
215
+ return null;
216
+ }
217
+ this.config.logger.info(`[FedSync] WebFinger resolved ${acct} → ${resolved}`);
218
+ fetched = await this.readActorDocument(resolved, acct);
219
+ if (!hasActorDocument(fetched)) {
220
+ // A 410 on the WebFinger-RESOLVED URI is just as definitive. Tombstone
221
+ // against the stored URI.
222
+ if (fetched.status === 410) {
223
+ this.config.logger.info(`[FedSync] fetchRemoteActor 410 Gone for resolved ${resolved} — tombstoning actor ${currentUri}`);
224
+ await this.tombstoneGoneActor(currentUri);
255
225
  return null;
256
226
  }
257
- }
258
- else {
227
+ this.config.logger.info(`[FedSync] fetchRemoteActor HTTP ${fetched.status}${fetched.detail ? ` ${fetched.detail}` : ''} for resolved ${resolved}`);
259
228
  return null;
260
229
  }
230
+ currentUri = resolved;
261
231
  }
262
- const actor = await readBoundedJson(res, ACTOR_BODY_MAX_BYTES);
232
+ const actor = fetched.document;
263
233
  const actorId = asString(actor.id);
264
234
  const actorInbox = apIri(actor.inbox);
265
235
  if (!actorId || !actorInbox) {
@@ -310,26 +280,25 @@ export class ActorResolver {
310
280
  // normalizing: the canonical normalizer collapses whitespace, it never
311
281
  // strips markup — so the sanitizer must run first, on the raw value.
312
282
  const fields = [];
313
- if (Array.isArray(actor.attachment)) {
314
- for (const att of actor.attachment) {
315
- const attRecord = asRecord(att);
316
- if (!attRecord || attRecord.type !== 'PropertyValue')
317
- continue;
318
- const fieldName = this.config.text.inlineField(attRecord.name);
319
- const fieldValue = typeof attRecord.value === 'string'
320
- ? this.config.text.sanitizeFieldValue(attRecord.value)
321
- : '';
322
- if (!fieldName || !fieldValue)
323
- continue;
324
- fields.push({
325
- name: fieldName,
326
- value: fieldValue,
327
- verifiedAt: attRecord.verifiedAt ? new Date(String(attRecord.verifiedAt)) : undefined,
328
- });
329
- }
283
+ for (const att of apList(actor.attachment)) {
284
+ const attRecord = asRecord(att);
285
+ if (!attRecord || attRecord.type !== 'PropertyValue')
286
+ continue;
287
+ const fieldName = this.config.text.inlineField(attRecord.name);
288
+ const fieldValue = typeof attRecord.value === 'string'
289
+ ? this.config.text.sanitizeFieldValue(attRecord.value)
290
+ : '';
291
+ if (!fieldName || !fieldValue)
292
+ continue;
293
+ fields.push({
294
+ name: fieldName,
295
+ value: fieldValue,
296
+ verifiedAt: apDate(attRecord.verifiedAt),
297
+ });
330
298
  }
331
- const avatarUrl = this.config.firstStringUrl(actor.icon);
332
- const headerUrl = this.config.firstStringUrl(actor.image);
299
+ const imageUrl = this.config.firstStringUrl ?? apImageUrl;
300
+ const avatarUrl = imageUrl(actor.icon);
301
+ const headerUrl = imageUrl(actor.image);
333
302
  // `summary` is the actor's bio — a BODY, so its line breaks are the author's
334
303
  // and must survive; `htmlToPlainText` normalizes it as multiline.
335
304
  const summary = typeof actor.summary === 'string' ? this.config.text.htmlToPlainText(actor.summary) : '';
@@ -337,9 +306,11 @@ export class ActorResolver {
337
306
  // `&nbsp;` only becomes whitespace once decoded), THEN collapse.
338
307
  const rawDisplayName = typeof actor.name === 'string' ? actor.name : '';
339
308
  const displayName = this.config.text.inlineDisplayName(rawDisplayName) || username;
340
- const alsoKnownAs = Array.isArray(actor.alsoKnownAs)
341
- ? actor.alsoKnownAs.filter((v) => typeof v === 'string')
342
- : undefined;
309
+ // Absent stays absent (the store keeps what it has); one alias or a list
310
+ // of them is the list.
311
+ const alsoKnownAs = actor.alsoKnownAs === undefined || actor.alsoKnownAs === null
312
+ ? undefined
313
+ : apIriList(actor.alsoKnownAs);
343
314
  // A move target is an actor URL; anything else is not one.
344
315
  const movedToValue = apIri(actor.movedTo);
345
316
  const movedTo = movedToValue && /^https?:\/\//.test(movedToValue) ? movedToValue : undefined;
@@ -399,7 +370,7 @@ export class ActorResolver {
399
370
  alsoKnownAs,
400
371
  ...(movedTo && { movedTo }),
401
372
  networkAcct: networkIdentity?.federatedUsername,
402
- remoteCreatedAt: typeof actor.published === 'string' ? new Date(actor.published) : undefined,
373
+ remoteCreatedAt: apDate(actor.published),
403
374
  // Omitted, not written as `undefined`, when this refresh could not tell:
404
375
  // an absent key is what tells the store to keep the value it has.
405
376
  ...(followersCount !== undefined && { followersCount }),
@@ -407,7 +378,7 @@ export class ActorResolver {
407
378
  ...(postsCount !== undefined && { postsCount }),
408
379
  lastFetchedAt: new Date(),
409
380
  };
410
- const fedActor = await this.config.store.upsertActor(actorId, update);
381
+ const fedActor = await this.config.store.upsertActor(actorId, update, fetched.source);
411
382
  // Always upsert into Oxy so profile changes (avatar, name, bio) are synced.
412
383
  // The identity bridge creates the federated Oxy user if it does not exist,
413
384
  // updates it when changed, and mirrors the banner. This connector then stamps
@@ -544,7 +515,7 @@ export class ActorResolver {
544
515
  if (!res.ok) {
545
516
  return COLLECTION_WITHHELD_STATUSES.has(res.status) ? null : undefined;
546
517
  }
547
- const col = await readBoundedJson(res, COLLECTION_BODY_MAX_BYTES);
518
+ const col = await readBoundedResponseJson(res, { maxBytes: COLLECTION_BODY_MAX_BYTES });
548
519
  const total = col.totalItems;
549
520
  return typeof total === 'number' && Number.isSafeInteger(total) && total >= 0 ? total : null;
550
521
  }
@@ -22,6 +22,7 @@
22
22
  */
23
23
  import { Router } from 'express';
24
24
  import { AP_CONTEXT } from '../apContext.js';
25
+ import { apIri } from '../apValue.js';
25
26
  import { discoveryCacheControl } from './httpCacheControl.js';
26
27
  import { verifyHttpSignature } from '../httpSignature.js';
27
28
  import { INSTANCE_ACTOR_USERNAME, normalizeActorUsername } from '../urls.js';
@@ -97,7 +98,7 @@ export function createActorRouter(config) {
97
98
  return res.status(400).json({ error: 'Invalid activity' });
98
99
  }
99
100
  // Verify the actor in the activity matches the signature.
100
- const activityActor = typeof activity.actor === 'string' ? activity.actor : activity.actor?.id;
101
+ const activityActor = apIri(activity.actor);
101
102
  if (activityActor !== actorUri) {
102
103
  logger.debug(`Inbox: Actor mismatch. Signed: ${actorUri}, Activity: ${activityActor}`);
103
104
  return res.status(403).json({ error: 'Actor mismatch' });