@oxy.so/federation 2.17.0 → 3.1.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.
- package/dist/cjs/node/actorResolver.js +44 -69
- package/dist/cjs/node/boundedBody.js +44 -0
- package/dist/cjs/node/delivery.js +16 -1
- package/dist/cjs/node/index.js +11 -1
- package/dist/cjs/node/signedFetch.js +15 -5
- package/dist/esm/node/actorResolver.js +45 -70
- package/dist/esm/node/boundedBody.js +42 -0
- package/dist/esm/node/delivery.js +16 -1
- package/dist/esm/node/index.js +6 -1
- package/dist/esm/node/signedFetch.js +14 -5
- package/dist/types/index.d.ts +5 -15
- package/dist/types/node/actorResolver.d.ts +48 -9
- package/dist/types/node/boundedBody.d.ts +19 -0
- package/dist/types/node/delivery.d.ts +10 -2
- package/dist/types/node/index.d.ts +7 -2
- package/dist/types/node/signedFetch.d.ts +23 -2
- package/package.json +1 -1
- package/src/__tests__/actorResolver.test.ts +52 -0
- package/src/__tests__/delivery.test.ts +27 -0
- package/src/__tests__/signedFetch.test.ts +26 -3
- package/src/index.ts +5 -16
- package/src/node/actorResolver.ts +107 -90
- package/src/node/boundedBody.ts +62 -0
- package/src/node/delivery.ts +27 -1
- package/src/node/index.ts +18 -0
- package/src/node/signedFetch.ts +44 -6
|
@@ -52,40 +52,9 @@ const COLLECTION_BODY_MAX_BYTES = 64 * 1024;
|
|
|
52
52
|
*/
|
|
53
53
|
const COLLECTION_WITHHELD_STATUSES = new Set([401, 403, 404, 410]);
|
|
54
54
|
const ERROR_BODY_MAX_BYTES = 4 * 1024;
|
|
55
|
-
/**
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
* that stalls mid-body would hold the resolver open.
|
|
59
|
-
*/
|
|
60
|
-
const BODY_TIMEOUT_MS = 10000;
|
|
61
|
-
async function readBoundedResponseBody(res, maxBytes) {
|
|
62
|
-
const contentLength = res.headers.get('content-length');
|
|
63
|
-
if (contentLength) {
|
|
64
|
-
const declaredBytes = Number(contentLength);
|
|
65
|
-
if (Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {
|
|
66
|
-
await res.body?.cancel().catch(() => { });
|
|
67
|
-
throw new boundedBody_1.ResponseBodyTooLargeError(maxBytes);
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
if (!res.body)
|
|
71
|
-
return '';
|
|
72
|
-
const reader = res.body.getReader();
|
|
73
|
-
const body = await (0, boundedBody_1.readBodyChunks)({ read: () => reader.read(), cancel: () => void reader.cancel().catch(() => { }) }, { maxBytes, timeoutMs: BODY_TIMEOUT_MS });
|
|
74
|
-
return new TextDecoder('utf-8', { fatal: true }).decode(body);
|
|
75
|
-
}
|
|
76
|
-
async function readBoundedJson(res, maxBytes) {
|
|
77
|
-
const body = await readBoundedResponseBody(res, maxBytes);
|
|
78
|
-
// An empty body is a REMOTE's answer, not a parser error. Without this,
|
|
79
|
-
// `JSON.parse('')` throws a SyntaxError whose message names a column number,
|
|
80
|
-
// which is a worse thing to find in a federation log than the fact that the
|
|
81
|
-
// instance sent nothing.
|
|
82
|
-
if (body.length === 0)
|
|
83
|
-
throw new Error('Remote response has no body');
|
|
84
|
-
const value = JSON.parse(body);
|
|
85
|
-
const record = asRecord(value);
|
|
86
|
-
if (!record)
|
|
87
|
-
throw new Error('Remote response is not a JSON object');
|
|
88
|
-
return record;
|
|
55
|
+
/** Whether a read produced a document the resolver can parse. */
|
|
56
|
+
function hasActorDocument(fetched) {
|
|
57
|
+
return fetched.status >= 200 && fetched.status < 300 && fetched.document !== undefined;
|
|
89
58
|
}
|
|
90
59
|
function asRecord(value) {
|
|
91
60
|
return value && typeof value === 'object' && !Array.isArray(value)
|
|
@@ -133,6 +102,22 @@ class ActorResolver {
|
|
|
133
102
|
/** Actor key refetches in flight, by actor URI: concurrent failed signatures share one. */
|
|
134
103
|
this.inFlightKeyRefetches = new Map();
|
|
135
104
|
}
|
|
105
|
+
/** One read of an actor document: the app's {@link ActorResolverConfig.fetchActorDocument}, or a signed GET. */
|
|
106
|
+
async readActorDocument(actorUri, acctHint) {
|
|
107
|
+
if (this.config.fetchActorDocument)
|
|
108
|
+
return this.config.fetchActorDocument(actorUri, acctHint);
|
|
109
|
+
const res = await this.config.signedFetch(actorUri, AP_CONTENT_TYPE);
|
|
110
|
+
if (res.ok) {
|
|
111
|
+
return {
|
|
112
|
+
status: res.status,
|
|
113
|
+
document: await (0, boundedBody_1.readBoundedResponseJson)(res, { maxBytes: ACTOR_BODY_MAX_BYTES }),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
if (res.status === 410)
|
|
117
|
+
return { status: res.status };
|
|
118
|
+
const body = await (0, boundedBody_1.readBoundedResponseText)(res, { maxBytes: ERROR_BODY_MAX_BYTES }).catch(() => '');
|
|
119
|
+
return { status: res.status, detail: `${res.statusText} body=${body.slice(0, 500)}`.trim() };
|
|
120
|
+
}
|
|
136
121
|
/**
|
|
137
122
|
* Whether an actor URI's host is refused by the instance domain policy. An
|
|
138
123
|
* unparseable URI has no host to check, so it is refused too — the policy is a
|
|
@@ -205,19 +190,17 @@ class ActorResolver {
|
|
|
205
190
|
return null;
|
|
206
191
|
}
|
|
207
192
|
const canonicalAcctHint = this.config.normalizeFederatedAcct(acctHint);
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
if (!res.ok) {
|
|
193
|
+
let fetched = await this.readActorDocument(currentUri, canonicalAcctHint);
|
|
194
|
+
if (!hasActorDocument(fetched)) {
|
|
211
195
|
// A definitive 410 Gone is authoritative: tombstone and stop — do NOT fall
|
|
212
196
|
// through to the WebFinger fallback (which recovers a STALE/wrong URI on a
|
|
213
197
|
// transient failure, not a permanent removal). Only 410 does this.
|
|
214
|
-
if (
|
|
198
|
+
if (fetched.status === 410) {
|
|
215
199
|
this.config.logger.info(`[FedSync] fetchRemoteActor 410 Gone for ${currentUri} — tombstoning actor`);
|
|
216
200
|
await this.tombstoneGoneActor(currentUri);
|
|
217
201
|
return null;
|
|
218
202
|
}
|
|
219
|
-
|
|
220
|
-
this.config.logger.info(`[FedSync] fetchRemoteActor HTTP ${res.status} ${res.statusText} for ${currentUri} body=${body.slice(0, 500)}`);
|
|
203
|
+
this.config.logger.info(`[FedSync] fetchRemoteActor HTTP ${fetched.status}${fetched.detail ? ` ${fetched.detail}` : ''} for ${currentUri}`);
|
|
221
204
|
// If direct fetch failed, try WebFinger to resolve the canonical actor URI.
|
|
222
205
|
// Some servers (e.g., Threads) use numeric IDs in AP URIs that differ from
|
|
223
206
|
// the username-based URI we may have stored.
|
|
@@ -227,38 +210,30 @@ class ActorResolver {
|
|
|
227
210
|
(pathUsername
|
|
228
211
|
? this.config.normalizeFederatedAcct(`${pathUsername}@${parsed.hostname}`)
|
|
229
212
|
: undefined);
|
|
230
|
-
if (acct)
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
}
|
|
247
|
-
const body2 = await readBoundedResponseBody(res, ERROR_BODY_MAX_BYTES).catch(() => '');
|
|
248
|
-
this.config.logger.info(`[FedSync] fetchRemoteActor HTTP ${res.status} for resolved ${resolved} body=${body2.slice(0, 500)}`);
|
|
249
|
-
return null;
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
else {
|
|
253
|
-
this.config.logger.info(`[FedSync] WebFinger returned ${resolved ?? 'null'} for ${acct}`);
|
|
213
|
+
if (!acct)
|
|
214
|
+
return null;
|
|
215
|
+
this.config.logger.info(`[FedSync] attempting WebFinger fallback for ${acct}`);
|
|
216
|
+
const resolved = await this.resolveWebFinger(acct);
|
|
217
|
+
if (!resolved || resolved === currentUri) {
|
|
218
|
+
this.config.logger.info(`[FedSync] WebFinger returned ${resolved ?? 'null'} for ${acct}`);
|
|
219
|
+
return null;
|
|
220
|
+
}
|
|
221
|
+
this.config.logger.info(`[FedSync] WebFinger resolved ${acct} → ${resolved}`);
|
|
222
|
+
fetched = await this.readActorDocument(resolved, acct);
|
|
223
|
+
if (!hasActorDocument(fetched)) {
|
|
224
|
+
// A 410 on the WebFinger-RESOLVED URI is just as definitive. Tombstone
|
|
225
|
+
// against the stored URI.
|
|
226
|
+
if (fetched.status === 410) {
|
|
227
|
+
this.config.logger.info(`[FedSync] fetchRemoteActor 410 Gone for resolved ${resolved} — tombstoning actor ${currentUri}`);
|
|
228
|
+
await this.tombstoneGoneActor(currentUri);
|
|
254
229
|
return null;
|
|
255
230
|
}
|
|
256
|
-
|
|
257
|
-
else {
|
|
231
|
+
this.config.logger.info(`[FedSync] fetchRemoteActor HTTP ${fetched.status}${fetched.detail ? ` ${fetched.detail}` : ''} for resolved ${resolved}`);
|
|
258
232
|
return null;
|
|
259
233
|
}
|
|
234
|
+
currentUri = resolved;
|
|
260
235
|
}
|
|
261
|
-
const actor =
|
|
236
|
+
const actor = fetched.document;
|
|
262
237
|
const actorId = asString(actor.id);
|
|
263
238
|
const actorInbox = (0, apValue_1.apIri)(actor.inbox);
|
|
264
239
|
if (!actorId || !actorInbox) {
|
|
@@ -407,7 +382,7 @@ class ActorResolver {
|
|
|
407
382
|
...(postsCount !== undefined && { postsCount }),
|
|
408
383
|
lastFetchedAt: new Date(),
|
|
409
384
|
};
|
|
410
|
-
const fedActor = await this.config.store.upsertActor(actorId, update);
|
|
385
|
+
const fedActor = await this.config.store.upsertActor(actorId, update, fetched.source);
|
|
411
386
|
// Always upsert into Oxy so profile changes (avatar, name, bio) are synced.
|
|
412
387
|
// The identity bridge creates the federated Oxy user if it does not exist,
|
|
413
388
|
// updates it when changed, and mirrors the banner. This connector then stamps
|
|
@@ -544,7 +519,7 @@ class ActorResolver {
|
|
|
544
519
|
if (!res.ok) {
|
|
545
520
|
return COLLECTION_WITHHELD_STATUSES.has(res.status) ? null : undefined;
|
|
546
521
|
}
|
|
547
|
-
const col = await
|
|
522
|
+
const col = await (0, boundedBody_1.readBoundedResponseJson)(res, { maxBytes: COLLECTION_BODY_MAX_BYTES });
|
|
548
523
|
const total = col.totalItems;
|
|
549
524
|
return typeof total === 'number' && Number.isSafeInteger(total) && total >= 0 ? total : null;
|
|
550
525
|
}
|
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
14
|
exports.ResponseBodyTimeoutError = exports.ResponseBodyTooLargeError = void 0;
|
|
15
15
|
exports.readBodyChunks = readBodyChunks;
|
|
16
|
+
exports.readBoundedResponseText = readBoundedResponseText;
|
|
17
|
+
exports.readBoundedResponseJson = readBoundedResponseJson;
|
|
16
18
|
/** Thrown when a body exceeds its byte cap under `overflow: 'reject'`. */
|
|
17
19
|
class ResponseBodyTooLargeError extends Error {
|
|
18
20
|
constructor(maxBytes) {
|
|
@@ -75,3 +77,45 @@ async function readBodyChunks(source, limits) {
|
|
|
75
77
|
}
|
|
76
78
|
return Buffer.concat(chunks, total);
|
|
77
79
|
}
|
|
80
|
+
/** Deadline for a whole response body once its headers arrived, by default. */
|
|
81
|
+
const RESPONSE_BODY_TIMEOUT_MS = 10000;
|
|
82
|
+
/**
|
|
83
|
+
* A WHATWG `Response` body as UTF-8 text, within {@link ResponseBodyLimits}.
|
|
84
|
+
* A fetch's own timeout ends at the headers, so without the body deadline a
|
|
85
|
+
* remote that stalls mid-body would hold the reader open. A declared
|
|
86
|
+
* `Content-Length` over the cap is refused before any byte is read.
|
|
87
|
+
*/
|
|
88
|
+
async function readBoundedResponseText(res, limits) {
|
|
89
|
+
const { maxBytes, timeoutMs = RESPONSE_BODY_TIMEOUT_MS } = limits;
|
|
90
|
+
const contentLength = res.headers.get('content-length');
|
|
91
|
+
if (contentLength) {
|
|
92
|
+
const declaredBytes = Number(contentLength);
|
|
93
|
+
if (Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {
|
|
94
|
+
await res.body?.cancel().catch(() => { });
|
|
95
|
+
throw new ResponseBodyTooLargeError(maxBytes);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (!res.body)
|
|
99
|
+
return '';
|
|
100
|
+
const reader = res.body.getReader();
|
|
101
|
+
const body = await readBodyChunks({ read: () => reader.read(), cancel: () => void reader.cancel().catch(() => { }) }, { maxBytes, timeoutMs });
|
|
102
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(body);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* A WHATWG `Response` body as a JSON object, within {@link ResponseBodyLimits}.
|
|
106
|
+
* Throws when the body is empty, is not JSON, or is JSON but not an object.
|
|
107
|
+
*/
|
|
108
|
+
async function readBoundedResponseJson(res, limits) {
|
|
109
|
+
const body = await readBoundedResponseText(res, limits);
|
|
110
|
+
// An empty body is a REMOTE's answer, not a parser error. Without this,
|
|
111
|
+
// `JSON.parse('')` throws a SyntaxError whose message names a column number,
|
|
112
|
+
// which is a worse thing to find in a federation log than the fact that the
|
|
113
|
+
// instance sent nothing.
|
|
114
|
+
if (body.length === 0)
|
|
115
|
+
throw new Error('Remote response has no body');
|
|
116
|
+
const value = JSON.parse(body);
|
|
117
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
118
|
+
throw new Error('Remote response is not a JSON object');
|
|
119
|
+
}
|
|
120
|
+
return value;
|
|
121
|
+
}
|
|
@@ -257,7 +257,7 @@ function createDeliveryService(config) {
|
|
|
257
257
|
}
|
|
258
258
|
})();
|
|
259
259
|
}
|
|
260
|
-
async function sendFollow(localOxyUserId, localUsername, remoteActorUri) {
|
|
260
|
+
async function sendFollow(localOxyUserId, localUsername, remoteActorUri, options = {}) {
|
|
261
261
|
if (!config.federationEnabled)
|
|
262
262
|
return { success: false, pending: false };
|
|
263
263
|
if (isBlockedUrl(remoteActorUri)) {
|
|
@@ -283,6 +283,21 @@ function createDeliveryService(config) {
|
|
|
283
283
|
};
|
|
284
284
|
// Refuse before committing an outbound follow or reporting success.
|
|
285
285
|
await authorizeDelivery(activity, localOxyUserId);
|
|
286
|
+
if (options.durable) {
|
|
287
|
+
// The caller may exit as soon as this resolves, so nothing is left to the
|
|
288
|
+
// background: the inbox is resolved now, and the Follow is in the delivery
|
|
289
|
+
// queue (whose worker retries it) before the follow is reported.
|
|
290
|
+
const actor = cached?.sharedInboxUrl || cached?.inboxUrl
|
|
291
|
+
? cached
|
|
292
|
+
: await config.actorRefresh.fetchRemoteActor(remoteActorUri);
|
|
293
|
+
const inbox = actor?.sharedInboxUrl ?? actor?.inboxUrl;
|
|
294
|
+
if (!inbox || isBlockedUrl(inbox)) {
|
|
295
|
+
throw new Error(`No inbox to deliver the Follow to ${remoteActorUri}`);
|
|
296
|
+
}
|
|
297
|
+
await config.follows.upsertOutboundPending(localOxyUserId, canonicalUri, activityId);
|
|
298
|
+
await queueDelivery(activity, inbox, localOxyUserId);
|
|
299
|
+
return { success: true, pending: actor?.manuallyApprovesFollowers ?? false };
|
|
300
|
+
}
|
|
286
301
|
// A refused follow must not start remote actor discovery either.
|
|
287
302
|
config.actorRefresh.refreshActorInBackground(remoteActorUri, cached ?? undefined);
|
|
288
303
|
await config.follows.upsertOutboundPending(localOxyUserId, canonicalUri, activityId);
|
package/dist/cjs/node/index.js
CHANGED
|
@@ -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
|
-
|
|
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
|
}
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
import { isSameFederationHost } from '../apUri.js';
|
|
22
22
|
import { apDate, apImageUrl, apIri, apIriList, apList, isActivityPubMediaType } from '../apValue.js';
|
|
23
23
|
import { readProxyDeclarations, } from '../networkIdentity.js';
|
|
24
|
-
import {
|
|
24
|
+
import { readBoundedResponseJson, readBoundedResponseText } from './boundedBody.js';
|
|
25
25
|
/**
|
|
26
26
|
* Minimum interval between background actor refreshes for the same actor.
|
|
27
27
|
* Prevents refresh storms when a profile is viewed repeatedly in a short window.
|
|
@@ -48,40 +48,9 @@ const COLLECTION_BODY_MAX_BYTES = 64 * 1024;
|
|
|
48
48
|
*/
|
|
49
49
|
const COLLECTION_WITHHELD_STATUSES = new Set([401, 403, 404, 410]);
|
|
50
50
|
const ERROR_BODY_MAX_BYTES = 4 * 1024;
|
|
51
|
-
/**
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
* that stalls mid-body would hold the resolver open.
|
|
55
|
-
*/
|
|
56
|
-
const BODY_TIMEOUT_MS = 10000;
|
|
57
|
-
async function readBoundedResponseBody(res, maxBytes) {
|
|
58
|
-
const contentLength = res.headers.get('content-length');
|
|
59
|
-
if (contentLength) {
|
|
60
|
-
const declaredBytes = Number(contentLength);
|
|
61
|
-
if (Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {
|
|
62
|
-
await res.body?.cancel().catch(() => { });
|
|
63
|
-
throw new ResponseBodyTooLargeError(maxBytes);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
if (!res.body)
|
|
67
|
-
return '';
|
|
68
|
-
const reader = res.body.getReader();
|
|
69
|
-
const body = await readBodyChunks({ read: () => reader.read(), cancel: () => void reader.cancel().catch(() => { }) }, { maxBytes, timeoutMs: BODY_TIMEOUT_MS });
|
|
70
|
-
return new TextDecoder('utf-8', { fatal: true }).decode(body);
|
|
71
|
-
}
|
|
72
|
-
async function readBoundedJson(res, maxBytes) {
|
|
73
|
-
const body = await readBoundedResponseBody(res, maxBytes);
|
|
74
|
-
// An empty body is a REMOTE's answer, not a parser error. Without this,
|
|
75
|
-
// `JSON.parse('')` throws a SyntaxError whose message names a column number,
|
|
76
|
-
// which is a worse thing to find in a federation log than the fact that the
|
|
77
|
-
// instance sent nothing.
|
|
78
|
-
if (body.length === 0)
|
|
79
|
-
throw new Error('Remote response has no body');
|
|
80
|
-
const value = JSON.parse(body);
|
|
81
|
-
const record = asRecord(value);
|
|
82
|
-
if (!record)
|
|
83
|
-
throw new Error('Remote response is not a JSON object');
|
|
84
|
-
return record;
|
|
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;
|
|
85
54
|
}
|
|
86
55
|
function asRecord(value) {
|
|
87
56
|
return value && typeof value === 'object' && !Array.isArray(value)
|
|
@@ -129,6 +98,22 @@ export class ActorResolver {
|
|
|
129
98
|
/** Actor key refetches in flight, by actor URI: concurrent failed signatures share one. */
|
|
130
99
|
this.inFlightKeyRefetches = new Map();
|
|
131
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
|
+
}
|
|
132
117
|
/**
|
|
133
118
|
* Whether an actor URI's host is refused by the instance domain policy. An
|
|
134
119
|
* unparseable URI has no host to check, so it is refused too — the policy is a
|
|
@@ -201,19 +186,17 @@ export class ActorResolver {
|
|
|
201
186
|
return null;
|
|
202
187
|
}
|
|
203
188
|
const canonicalAcctHint = this.config.normalizeFederatedAcct(acctHint);
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
if (!res.ok) {
|
|
189
|
+
let fetched = await this.readActorDocument(currentUri, canonicalAcctHint);
|
|
190
|
+
if (!hasActorDocument(fetched)) {
|
|
207
191
|
// A definitive 410 Gone is authoritative: tombstone and stop — do NOT fall
|
|
208
192
|
// through to the WebFinger fallback (which recovers a STALE/wrong URI on a
|
|
209
193
|
// transient failure, not a permanent removal). Only 410 does this.
|
|
210
|
-
if (
|
|
194
|
+
if (fetched.status === 410) {
|
|
211
195
|
this.config.logger.info(`[FedSync] fetchRemoteActor 410 Gone for ${currentUri} — tombstoning actor`);
|
|
212
196
|
await this.tombstoneGoneActor(currentUri);
|
|
213
197
|
return null;
|
|
214
198
|
}
|
|
215
|
-
|
|
216
|
-
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}`);
|
|
217
200
|
// If direct fetch failed, try WebFinger to resolve the canonical actor URI.
|
|
218
201
|
// Some servers (e.g., Threads) use numeric IDs in AP URIs that differ from
|
|
219
202
|
// the username-based URI we may have stored.
|
|
@@ -223,38 +206,30 @@ export class ActorResolver {
|
|
|
223
206
|
(pathUsername
|
|
224
207
|
? this.config.normalizeFederatedAcct(`${pathUsername}@${parsed.hostname}`)
|
|
225
208
|
: undefined);
|
|
226
|
-
if (acct)
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
}
|
|
243
|
-
const body2 = await readBoundedResponseBody(res, ERROR_BODY_MAX_BYTES).catch(() => '');
|
|
244
|
-
this.config.logger.info(`[FedSync] fetchRemoteActor HTTP ${res.status} for resolved ${resolved} body=${body2.slice(0, 500)}`);
|
|
245
|
-
return null;
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
else {
|
|
249
|
-
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);
|
|
250
225
|
return null;
|
|
251
226
|
}
|
|
252
|
-
|
|
253
|
-
else {
|
|
227
|
+
this.config.logger.info(`[FedSync] fetchRemoteActor HTTP ${fetched.status}${fetched.detail ? ` ${fetched.detail}` : ''} for resolved ${resolved}`);
|
|
254
228
|
return null;
|
|
255
229
|
}
|
|
230
|
+
currentUri = resolved;
|
|
256
231
|
}
|
|
257
|
-
const actor =
|
|
232
|
+
const actor = fetched.document;
|
|
258
233
|
const actorId = asString(actor.id);
|
|
259
234
|
const actorInbox = apIri(actor.inbox);
|
|
260
235
|
if (!actorId || !actorInbox) {
|
|
@@ -403,7 +378,7 @@ export class ActorResolver {
|
|
|
403
378
|
...(postsCount !== undefined && { postsCount }),
|
|
404
379
|
lastFetchedAt: new Date(),
|
|
405
380
|
};
|
|
406
|
-
const fedActor = await this.config.store.upsertActor(actorId, update);
|
|
381
|
+
const fedActor = await this.config.store.upsertActor(actorId, update, fetched.source);
|
|
407
382
|
// Always upsert into Oxy so profile changes (avatar, name, bio) are synced.
|
|
408
383
|
// The identity bridge creates the federated Oxy user if it does not exist,
|
|
409
384
|
// updates it when changed, and mirrors the banner. This connector then stamps
|
|
@@ -540,7 +515,7 @@ export class ActorResolver {
|
|
|
540
515
|
if (!res.ok) {
|
|
541
516
|
return COLLECTION_WITHHELD_STATUSES.has(res.status) ? null : undefined;
|
|
542
517
|
}
|
|
543
|
-
const col = await
|
|
518
|
+
const col = await readBoundedResponseJson(res, { maxBytes: COLLECTION_BODY_MAX_BYTES });
|
|
544
519
|
const total = col.totalItems;
|
|
545
520
|
return typeof total === 'number' && Number.isSafeInteger(total) && total >= 0 ? total : null;
|
|
546
521
|
}
|
|
@@ -69,3 +69,45 @@ export async function readBodyChunks(source, limits) {
|
|
|
69
69
|
}
|
|
70
70
|
return Buffer.concat(chunks, total);
|
|
71
71
|
}
|
|
72
|
+
/** Deadline for a whole response body once its headers arrived, by default. */
|
|
73
|
+
const RESPONSE_BODY_TIMEOUT_MS = 10000;
|
|
74
|
+
/**
|
|
75
|
+
* A WHATWG `Response` body as UTF-8 text, within {@link ResponseBodyLimits}.
|
|
76
|
+
* A fetch's own timeout ends at the headers, so without the body deadline a
|
|
77
|
+
* remote that stalls mid-body would hold the reader open. A declared
|
|
78
|
+
* `Content-Length` over the cap is refused before any byte is read.
|
|
79
|
+
*/
|
|
80
|
+
export async function readBoundedResponseText(res, limits) {
|
|
81
|
+
const { maxBytes, timeoutMs = RESPONSE_BODY_TIMEOUT_MS } = limits;
|
|
82
|
+
const contentLength = res.headers.get('content-length');
|
|
83
|
+
if (contentLength) {
|
|
84
|
+
const declaredBytes = Number(contentLength);
|
|
85
|
+
if (Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {
|
|
86
|
+
await res.body?.cancel().catch(() => { });
|
|
87
|
+
throw new ResponseBodyTooLargeError(maxBytes);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (!res.body)
|
|
91
|
+
return '';
|
|
92
|
+
const reader = res.body.getReader();
|
|
93
|
+
const body = await readBodyChunks({ read: () => reader.read(), cancel: () => void reader.cancel().catch(() => { }) }, { maxBytes, timeoutMs });
|
|
94
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(body);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* A WHATWG `Response` body as a JSON object, within {@link ResponseBodyLimits}.
|
|
98
|
+
* Throws when the body is empty, is not JSON, or is JSON but not an object.
|
|
99
|
+
*/
|
|
100
|
+
export async function readBoundedResponseJson(res, limits) {
|
|
101
|
+
const body = await readBoundedResponseText(res, limits);
|
|
102
|
+
// An empty body is a REMOTE's answer, not a parser error. Without this,
|
|
103
|
+
// `JSON.parse('')` throws a SyntaxError whose message names a column number,
|
|
104
|
+
// which is a worse thing to find in a federation log than the fact that the
|
|
105
|
+
// instance sent nothing.
|
|
106
|
+
if (body.length === 0)
|
|
107
|
+
throw new Error('Remote response has no body');
|
|
108
|
+
const value = JSON.parse(body);
|
|
109
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
110
|
+
throw new Error('Remote response is not a JSON object');
|
|
111
|
+
}
|
|
112
|
+
return value;
|
|
113
|
+
}
|
|
@@ -252,7 +252,7 @@ export function createDeliveryService(config) {
|
|
|
252
252
|
}
|
|
253
253
|
})();
|
|
254
254
|
}
|
|
255
|
-
async function sendFollow(localOxyUserId, localUsername, remoteActorUri) {
|
|
255
|
+
async function sendFollow(localOxyUserId, localUsername, remoteActorUri, options = {}) {
|
|
256
256
|
if (!config.federationEnabled)
|
|
257
257
|
return { success: false, pending: false };
|
|
258
258
|
if (isBlockedUrl(remoteActorUri)) {
|
|
@@ -278,6 +278,21 @@ export function createDeliveryService(config) {
|
|
|
278
278
|
};
|
|
279
279
|
// Refuse before committing an outbound follow or reporting success.
|
|
280
280
|
await authorizeDelivery(activity, localOxyUserId);
|
|
281
|
+
if (options.durable) {
|
|
282
|
+
// The caller may exit as soon as this resolves, so nothing is left to the
|
|
283
|
+
// background: the inbox is resolved now, and the Follow is in the delivery
|
|
284
|
+
// queue (whose worker retries it) before the follow is reported.
|
|
285
|
+
const actor = cached?.sharedInboxUrl || cached?.inboxUrl
|
|
286
|
+
? cached
|
|
287
|
+
: await config.actorRefresh.fetchRemoteActor(remoteActorUri);
|
|
288
|
+
const inbox = actor?.sharedInboxUrl ?? actor?.inboxUrl;
|
|
289
|
+
if (!inbox || isBlockedUrl(inbox)) {
|
|
290
|
+
throw new Error(`No inbox to deliver the Follow to ${remoteActorUri}`);
|
|
291
|
+
}
|
|
292
|
+
await config.follows.upsertOutboundPending(localOxyUserId, canonicalUri, activityId);
|
|
293
|
+
await queueDelivery(activity, inbox, localOxyUserId);
|
|
294
|
+
return { success: true, pending: actor?.manuallyApprovesFollowers ?? false };
|
|
295
|
+
}
|
|
281
296
|
// A refused follow must not start remote actor discovery either.
|
|
282
297
|
config.actorRefresh.refreshActorInBackground(remoteActorUri, cached ?? undefined);
|
|
283
298
|
await config.follows.upsertOutboundPending(localOxyUserId, canonicalUri, activityId);
|
package/dist/esm/node/index.js
CHANGED
|
@@ -16,7 +16,12 @@
|
|
|
16
16
|
* Undo(Follow)/Reject, delegating content verbs to the app), and the webfinger +
|
|
17
17
|
* actor + inbox + follow-graph Express routers.
|
|
18
18
|
*/
|
|
19
|
-
export { createSignedFetch, } from './signedFetch.js';
|
|
19
|
+
export { createSignedFetch, createSignedFetcher, } from './signedFetch.js';
|
|
20
|
+
/**
|
|
21
|
+
* Bounded, deadlined reads of a remote `Response` body (the one reader behind
|
|
22
|
+
* every federation document read).
|
|
23
|
+
*/
|
|
24
|
+
export { readBoundedResponseJson, readBoundedResponseText, ResponseBodyTooLargeError, ResponseBodyTimeoutError, } from './boundedBody.js';
|
|
20
25
|
/**
|
|
21
26
|
* X's `t.co` wrapper unwrapped into the link the author posted, over the same
|
|
22
27
|
* injected single-hop transport — for bridged X bios and posts.
|