@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
|
@@ -28,7 +28,7 @@ import {
|
|
|
28
28
|
type NetworkIdentityCandidate,
|
|
29
29
|
} from '../networkIdentity';
|
|
30
30
|
import type { NormalizedExternalActor } from '../index';
|
|
31
|
-
import {
|
|
31
|
+
import { readBoundedResponseJson, readBoundedResponseText } from './boundedBody';
|
|
32
32
|
import type { SignedFetch } from './signedFetch';
|
|
33
33
|
import type { ReportActorGoneOutcome } from './identityBridge';
|
|
34
34
|
import type { FetchPublicKeyOptions } from '../httpSignature';
|
|
@@ -64,46 +64,6 @@ const COLLECTION_BODY_MAX_BYTES = 64 * 1024;
|
|
|
64
64
|
const COLLECTION_WITHHELD_STATUSES: ReadonlySet<number> = new Set([401, 403, 404, 410]);
|
|
65
65
|
const ERROR_BODY_MAX_BYTES = 4 * 1024;
|
|
66
66
|
|
|
67
|
-
/**
|
|
68
|
-
* Deadline for reading a whole actor/collection/error body once its headers
|
|
69
|
-
* arrived. `signedFetch`'s timeout ends at the headers, so without this a remote
|
|
70
|
-
* that stalls mid-body would hold the resolver open.
|
|
71
|
-
*/
|
|
72
|
-
const BODY_TIMEOUT_MS = 10_000;
|
|
73
|
-
|
|
74
|
-
async function readBoundedResponseBody(res: Response, maxBytes: number): Promise<string> {
|
|
75
|
-
const contentLength = res.headers.get('content-length');
|
|
76
|
-
if (contentLength) {
|
|
77
|
-
const declaredBytes = Number(contentLength);
|
|
78
|
-
if (Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {
|
|
79
|
-
await res.body?.cancel().catch(() => {});
|
|
80
|
-
throw new ResponseBodyTooLargeError(maxBytes);
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
if (!res.body) return '';
|
|
85
|
-
|
|
86
|
-
const reader = res.body.getReader();
|
|
87
|
-
const body = await readBodyChunks(
|
|
88
|
-
{ read: () => reader.read(), cancel: () => void reader.cancel().catch(() => {}) },
|
|
89
|
-
{ maxBytes, timeoutMs: BODY_TIMEOUT_MS },
|
|
90
|
-
);
|
|
91
|
-
return new TextDecoder('utf-8', { fatal: true }).decode(body);
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
async function readBoundedJson(res: Response, maxBytes: number): Promise<Record<string, unknown>> {
|
|
95
|
-
const body = await readBoundedResponseBody(res, maxBytes);
|
|
96
|
-
// An empty body is a REMOTE's answer, not a parser error. Without this,
|
|
97
|
-
// `JSON.parse('')` throws a SyntaxError whose message names a column number,
|
|
98
|
-
// which is a worse thing to find in a federation log than the fact that the
|
|
99
|
-
// instance sent nothing.
|
|
100
|
-
if (body.length === 0) throw new Error('Remote response has no body');
|
|
101
|
-
const value: unknown = JSON.parse(body);
|
|
102
|
-
const record = asRecord(value);
|
|
103
|
-
if (!record) throw new Error('Remote response is not a JSON object');
|
|
104
|
-
return record;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
67
|
/** The minimal fields the resolver reads off / writes to a stored actor record. */
|
|
108
68
|
export interface FederatedActorRecordBase {
|
|
109
69
|
_id?: unknown;
|
|
@@ -197,11 +157,15 @@ export interface FederatedActorUpsert {
|
|
|
197
157
|
export type CollectionCount = number | null | undefined;
|
|
198
158
|
|
|
199
159
|
/** Bring-your-own-store: the AP actor cache stays in the app DB behind this adapter. */
|
|
200
|
-
export interface FederatedActorStore<TActor extends FederatedActorRecordBase> {
|
|
160
|
+
export interface FederatedActorStore<TActor extends FederatedActorRecordBase, TSource = undefined> {
|
|
201
161
|
/** Look up a cached actor by its protocol URI. */
|
|
202
162
|
findActorByUri(uri: string): Promise<TActor | null>;
|
|
203
|
-
/**
|
|
204
|
-
|
|
163
|
+
/**
|
|
164
|
+
* Upsert (create-or-update) the actor cache row keyed by `uri`. `source` is
|
|
165
|
+
* what {@link ActorResolverConfig.fetchActorDocument} returned beside the
|
|
166
|
+
* document this update was parsed from (absent with the default fetch).
|
|
167
|
+
*/
|
|
168
|
+
upsertActor(uri: string, update: FederatedActorUpsert, source?: TSource): Promise<TActor | null>;
|
|
205
169
|
/** Look up a cached actor by its `publicKey.id` (HTTP-signature key resolution). */
|
|
206
170
|
findActorByPublicKeyId(keyId: string): Promise<Pick<TActor, 'uri' | 'publicKeyPem'> | null>;
|
|
207
171
|
/** Stamp the resolved Oxy user id onto an actor row (identified by its `_id`). */
|
|
@@ -257,6 +221,41 @@ export interface ActorTextAdapter {
|
|
|
257
221
|
qualifyHandles?(text: string, instanceDomain: string): string;
|
|
258
222
|
}
|
|
259
223
|
|
|
224
|
+
/**
|
|
225
|
+
* One read of a remote actor document, as {@link ActorResolver.fetchRemoteActor}
|
|
226
|
+
* consumes it.
|
|
227
|
+
*/
|
|
228
|
+
export interface ActorDocumentFetchResult<TSource = undefined> {
|
|
229
|
+
/** The HTTP status the actor's server answered. Only a 2xx carries `document`. */
|
|
230
|
+
status: number;
|
|
231
|
+
/** The actor document, present when the read succeeded. */
|
|
232
|
+
document?: Record<string, unknown>;
|
|
233
|
+
/** A short description of a failure for the resolver's log line. */
|
|
234
|
+
detail?: string;
|
|
235
|
+
/**
|
|
236
|
+
* What the fetcher learned beside the document (Mention: Oxy's verified
|
|
237
|
+
* identity answer), handed to {@link FederatedActorStore.upsertActor} so the
|
|
238
|
+
* store does not ask for it a second time.
|
|
239
|
+
*/
|
|
240
|
+
source?: TSource;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Where actor documents come from: the actor URI, and the canonical acct the
|
|
245
|
+
* caller knows it by (a hint, never an identity claim).
|
|
246
|
+
*/
|
|
247
|
+
export type ActorDocumentFetch<TSource = undefined> = (
|
|
248
|
+
actorUri: string,
|
|
249
|
+
acctHint?: string,
|
|
250
|
+
) => Promise<ActorDocumentFetchResult<TSource>>;
|
|
251
|
+
|
|
252
|
+
/** Whether a read produced a document the resolver can parse. */
|
|
253
|
+
function hasActorDocument<TSource>(
|
|
254
|
+
fetched: ActorDocumentFetchResult<TSource>,
|
|
255
|
+
): fetched is ActorDocumentFetchResult<TSource> & { document: Record<string, unknown> } {
|
|
256
|
+
return fetched.status >= 200 && fetched.status < 300 && fetched.document !== undefined;
|
|
257
|
+
}
|
|
258
|
+
|
|
260
259
|
/** A parsed WebFinger JRD (only the `links` we read). */
|
|
261
260
|
export interface WebFingerJrd {
|
|
262
261
|
links?: Array<{ rel?: string; type?: string; href?: string }>;
|
|
@@ -276,11 +275,21 @@ export interface ActorResolverLogger {
|
|
|
276
275
|
}
|
|
277
276
|
|
|
278
277
|
/** Adapters + config an {@link ActorResolver} is built from. */
|
|
279
|
-
export interface ActorResolverConfig<TActor extends FederatedActorRecordBase> {
|
|
278
|
+
export interface ActorResolverConfig<TActor extends FederatedActorRecordBase, TSource = undefined> {
|
|
280
279
|
/** Whether federation is enabled (gates background refreshes). */
|
|
281
280
|
federationEnabled: boolean;
|
|
282
|
-
/** Signed AP GET (
|
|
281
|
+
/** Signed AP GET (collection-count fetches, and actor documents by default). */
|
|
283
282
|
signedFetch: SignedFetch;
|
|
283
|
+
/**
|
|
284
|
+
* Where actor documents come from. Default: {@link signedFetch} of the actor
|
|
285
|
+
* URI. An app whose identity authority already fetches and verifies the actor
|
|
286
|
+
* reads the document from that answer instead, so one refresh fetches the
|
|
287
|
+
* actor once: Mention reads it from Oxy's `/federation/identities/resolve`,
|
|
288
|
+
* which returns the document it verified. Every guard below (same origin,
|
|
289
|
+
* self-consistent key, blocked domains, 410 tombstone, WebFinger fallback)
|
|
290
|
+
* applies to the document whichever way it arrived.
|
|
291
|
+
*/
|
|
292
|
+
fetchActorDocument?: ActorDocumentFetch<TSource>;
|
|
284
293
|
/** SSRF-safe bounded WebFinger fetch. */
|
|
285
294
|
fetchWebFinger: WebFingerFetch;
|
|
286
295
|
/** Per-instance blocked-domain check (own domains + identity apex + configured blocks). */
|
|
@@ -300,7 +309,7 @@ export interface ActorResolverConfig<TActor extends FederatedActorRecordBase> {
|
|
|
300
309
|
*/
|
|
301
310
|
deriveNetworkIdentity?: DeriveNetworkIdentity;
|
|
302
311
|
/** The app's actor cache store. */
|
|
303
|
-
store: FederatedActorStore<TActor>;
|
|
312
|
+
store: FederatedActorStore<TActor, TSource>;
|
|
304
313
|
/** The actor↔Oxy-user identity bridge. */
|
|
305
314
|
identity: ActorResolverIdentity;
|
|
306
315
|
/** Remote-text normalization. */
|
|
@@ -352,14 +361,34 @@ function actorPublicKeyIsSelfConsistent(actor: Record<string, unknown>, actorId:
|
|
|
352
361
|
* through the instance (e.g. `fetchRemoteActor` → `this.tombstoneGoneActor`),
|
|
353
362
|
* which keeps them spy-able and overridable in tests.
|
|
354
363
|
*/
|
|
355
|
-
export class ActorResolver<TActor extends FederatedActorRecordBase> {
|
|
364
|
+
export class ActorResolver<TActor extends FederatedActorRecordBase, TSource = undefined> {
|
|
356
365
|
/** Actor URIs with an in-flight background refresh (guards against refresh storms). */
|
|
357
366
|
private readonly inFlightActorRefreshes = new Set<string>();
|
|
358
367
|
|
|
359
368
|
/** Actor key refetches in flight, by actor URI: concurrent failed signatures share one. */
|
|
360
369
|
private readonly inFlightKeyRefetches = new Map<string, Promise<TActor | null>>();
|
|
361
370
|
|
|
362
|
-
constructor(private readonly config: ActorResolverConfig<TActor>) {}
|
|
371
|
+
constructor(private readonly config: ActorResolverConfig<TActor, TSource>) {}
|
|
372
|
+
|
|
373
|
+
/** One read of an actor document: the app's {@link ActorResolverConfig.fetchActorDocument}, or a signed GET. */
|
|
374
|
+
private async readActorDocument(
|
|
375
|
+
actorUri: string,
|
|
376
|
+
acctHint?: string,
|
|
377
|
+
): Promise<ActorDocumentFetchResult<TSource>> {
|
|
378
|
+
if (this.config.fetchActorDocument) return this.config.fetchActorDocument(actorUri, acctHint);
|
|
379
|
+
const res = await this.config.signedFetch(actorUri, AP_CONTENT_TYPE);
|
|
380
|
+
if (res.ok) {
|
|
381
|
+
return {
|
|
382
|
+
status: res.status,
|
|
383
|
+
document: await readBoundedResponseJson(res, { maxBytes: ACTOR_BODY_MAX_BYTES }),
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
if (res.status === 410) return { status: res.status };
|
|
387
|
+
const body = await readBoundedResponseText(res, { maxBytes: ERROR_BODY_MAX_BYTES }).catch(
|
|
388
|
+
() => '',
|
|
389
|
+
);
|
|
390
|
+
return { status: res.status, detail: `${res.statusText} body=${body.slice(0, 500)}`.trim() };
|
|
391
|
+
}
|
|
363
392
|
|
|
364
393
|
/**
|
|
365
394
|
* Whether an actor URI's host is refused by the instance domain policy. An
|
|
@@ -438,22 +467,20 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
|
|
|
438
467
|
}
|
|
439
468
|
|
|
440
469
|
const canonicalAcctHint = this.config.normalizeFederatedAcct(acctHint);
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
if (!res.ok) {
|
|
470
|
+
let fetched = await this.readActorDocument(currentUri, canonicalAcctHint);
|
|
471
|
+
if (!hasActorDocument(fetched)) {
|
|
444
472
|
// A definitive 410 Gone is authoritative: tombstone and stop — do NOT fall
|
|
445
473
|
// through to the WebFinger fallback (which recovers a STALE/wrong URI on a
|
|
446
474
|
// transient failure, not a permanent removal). Only 410 does this.
|
|
447
|
-
if (
|
|
475
|
+
if (fetched.status === 410) {
|
|
448
476
|
this.config.logger.info(
|
|
449
477
|
`[FedSync] fetchRemoteActor 410 Gone for ${currentUri} — tombstoning actor`,
|
|
450
478
|
);
|
|
451
479
|
await this.tombstoneGoneActor(currentUri);
|
|
452
480
|
return null;
|
|
453
481
|
}
|
|
454
|
-
const body = await readBoundedResponseBody(res, ERROR_BODY_MAX_BYTES).catch(() => '');
|
|
455
482
|
this.config.logger.info(
|
|
456
|
-
`[FedSync] fetchRemoteActor HTTP ${
|
|
483
|
+
`[FedSync] fetchRemoteActor HTTP ${fetched.status}${fetched.detail ? ` ${fetched.detail}` : ''} for ${currentUri}`,
|
|
457
484
|
);
|
|
458
485
|
|
|
459
486
|
// If direct fetch failed, try WebFinger to resolve the canonical actor URI.
|
|
@@ -466,44 +493,34 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
|
|
|
466
493
|
(pathUsername
|
|
467
494
|
? this.config.normalizeFederatedAcct(`${pathUsername}@${parsed.hostname}`)
|
|
468
495
|
: undefined);
|
|
469
|
-
if (acct)
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
`[FedSync] fetchRemoteActor 410 Gone for resolved ${resolved} — tombstoning actor ${currentUri}`,
|
|
483
|
-
);
|
|
484
|
-
await this.tombstoneGoneActor(currentUri);
|
|
485
|
-
return null;
|
|
486
|
-
}
|
|
487
|
-
const body2 = await readBoundedResponseBody(res, ERROR_BODY_MAX_BYTES).catch(
|
|
488
|
-
() => '',
|
|
489
|
-
);
|
|
490
|
-
this.config.logger.info(
|
|
491
|
-
`[FedSync] fetchRemoteActor HTTP ${res.status} for resolved ${resolved} body=${body2.slice(0, 500)}`,
|
|
492
|
-
);
|
|
493
|
-
return null;
|
|
494
|
-
}
|
|
495
|
-
} else {
|
|
496
|
+
if (!acct) return null;
|
|
497
|
+
this.config.logger.info(`[FedSync] attempting WebFinger fallback for ${acct}`);
|
|
498
|
+
const resolved = await this.resolveWebFinger(acct);
|
|
499
|
+
if (!resolved || resolved === currentUri) {
|
|
500
|
+
this.config.logger.info(`[FedSync] WebFinger returned ${resolved ?? 'null'} for ${acct}`);
|
|
501
|
+
return null;
|
|
502
|
+
}
|
|
503
|
+
this.config.logger.info(`[FedSync] WebFinger resolved ${acct} → ${resolved}`);
|
|
504
|
+
fetched = await this.readActorDocument(resolved, acct);
|
|
505
|
+
if (!hasActorDocument(fetched)) {
|
|
506
|
+
// A 410 on the WebFinger-RESOLVED URI is just as definitive. Tombstone
|
|
507
|
+
// against the stored URI.
|
|
508
|
+
if (fetched.status === 410) {
|
|
496
509
|
this.config.logger.info(
|
|
497
|
-
`[FedSync]
|
|
510
|
+
`[FedSync] fetchRemoteActor 410 Gone for resolved ${resolved} — tombstoning actor ${currentUri}`,
|
|
498
511
|
);
|
|
512
|
+
await this.tombstoneGoneActor(currentUri);
|
|
499
513
|
return null;
|
|
500
514
|
}
|
|
501
|
-
|
|
515
|
+
this.config.logger.info(
|
|
516
|
+
`[FedSync] fetchRemoteActor HTTP ${fetched.status}${fetched.detail ? ` ${fetched.detail}` : ''} for resolved ${resolved}`,
|
|
517
|
+
);
|
|
502
518
|
return null;
|
|
503
519
|
}
|
|
520
|
+
currentUri = resolved;
|
|
504
521
|
}
|
|
505
522
|
|
|
506
|
-
const actor =
|
|
523
|
+
const actor = fetched.document;
|
|
507
524
|
const actorId = asString(actor.id);
|
|
508
525
|
const actorInbox = apIri(actor.inbox);
|
|
509
526
|
if (!actorId || !actorInbox) {
|
|
@@ -675,7 +692,7 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
|
|
|
675
692
|
lastFetchedAt: new Date(),
|
|
676
693
|
};
|
|
677
694
|
|
|
678
|
-
const fedActor = await this.config.store.upsertActor(actorId, update);
|
|
695
|
+
const fedActor = await this.config.store.upsertActor(actorId, update, fetched.source);
|
|
679
696
|
|
|
680
697
|
// Always upsert into Oxy so profile changes (avatar, name, bio) are synced.
|
|
681
698
|
// The identity bridge creates the federated Oxy user if it does not exist,
|
|
@@ -824,7 +841,7 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
|
|
|
824
841
|
if (!res.ok) {
|
|
825
842
|
return COLLECTION_WITHHELD_STATUSES.has(res.status) ? null : undefined;
|
|
826
843
|
}
|
|
827
|
-
const col = await
|
|
844
|
+
const col = await readBoundedResponseJson(res, { maxBytes: COLLECTION_BODY_MAX_BYTES });
|
|
828
845
|
const total = col.totalItems;
|
|
829
846
|
return typeof total === 'number' && Number.isSafeInteger(total) && total >= 0 ? total : null;
|
|
830
847
|
} catch {
|
|
@@ -974,8 +991,8 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
|
|
|
974
991
|
}
|
|
975
992
|
|
|
976
993
|
/** Build the remote-actor resolver from an app's storage + identity + transports. */
|
|
977
|
-
export function createActorResolver<TActor extends FederatedActorRecordBase>(
|
|
978
|
-
config: ActorResolverConfig<TActor>,
|
|
979
|
-
): ActorResolver<TActor> {
|
|
994
|
+
export function createActorResolver<TActor extends FederatedActorRecordBase, TSource = undefined>(
|
|
995
|
+
config: ActorResolverConfig<TActor, TSource>,
|
|
996
|
+
): ActorResolver<TActor, TSource> {
|
|
980
997
|
return new ActorResolver(config);
|
|
981
998
|
}
|
package/src/node/boundedBody.ts
CHANGED
|
@@ -94,3 +94,65 @@ export async function readBodyChunks(
|
|
|
94
94
|
}
|
|
95
95
|
return Buffer.concat(chunks, total);
|
|
96
96
|
}
|
|
97
|
+
|
|
98
|
+
/** Deadline for a whole response body once its headers arrived, by default. */
|
|
99
|
+
const RESPONSE_BODY_TIMEOUT_MS = 10_000;
|
|
100
|
+
|
|
101
|
+
/** Limits for {@link readBoundedResponseText} / {@link readBoundedResponseJson}. */
|
|
102
|
+
export interface ResponseBodyLimits {
|
|
103
|
+
/** Largest body accepted, in bytes; a larger declared or actual body throws. */
|
|
104
|
+
maxBytes: number;
|
|
105
|
+
/** Deadline for the whole body, in milliseconds (default 10 s). */
|
|
106
|
+
timeoutMs?: number;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* A WHATWG `Response` body as UTF-8 text, within {@link ResponseBodyLimits}.
|
|
111
|
+
* A fetch's own timeout ends at the headers, so without the body deadline a
|
|
112
|
+
* remote that stalls mid-body would hold the reader open. A declared
|
|
113
|
+
* `Content-Length` over the cap is refused before any byte is read.
|
|
114
|
+
*/
|
|
115
|
+
export async function readBoundedResponseText(
|
|
116
|
+
res: Response,
|
|
117
|
+
limits: ResponseBodyLimits,
|
|
118
|
+
): Promise<string> {
|
|
119
|
+
const { maxBytes, timeoutMs = RESPONSE_BODY_TIMEOUT_MS } = limits;
|
|
120
|
+
const contentLength = res.headers.get('content-length');
|
|
121
|
+
if (contentLength) {
|
|
122
|
+
const declaredBytes = Number(contentLength);
|
|
123
|
+
if (Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {
|
|
124
|
+
await res.body?.cancel().catch(() => {});
|
|
125
|
+
throw new ResponseBodyTooLargeError(maxBytes);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (!res.body) return '';
|
|
130
|
+
|
|
131
|
+
const reader = res.body.getReader();
|
|
132
|
+
const body = await readBodyChunks(
|
|
133
|
+
{ read: () => reader.read(), cancel: () => void reader.cancel().catch(() => {}) },
|
|
134
|
+
{ maxBytes, timeoutMs },
|
|
135
|
+
);
|
|
136
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(body);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* A WHATWG `Response` body as a JSON object, within {@link ResponseBodyLimits}.
|
|
141
|
+
* Throws when the body is empty, is not JSON, or is JSON but not an object.
|
|
142
|
+
*/
|
|
143
|
+
export async function readBoundedResponseJson(
|
|
144
|
+
res: Response,
|
|
145
|
+
limits: ResponseBodyLimits,
|
|
146
|
+
): Promise<Record<string, unknown>> {
|
|
147
|
+
const body = await readBoundedResponseText(res, limits);
|
|
148
|
+
// An empty body is a REMOTE's answer, not a parser error. Without this,
|
|
149
|
+
// `JSON.parse('')` throws a SyntaxError whose message names a column number,
|
|
150
|
+
// which is a worse thing to find in a federation log than the fact that the
|
|
151
|
+
// instance sent nothing.
|
|
152
|
+
if (body.length === 0) throw new Error('Remote response has no body');
|
|
153
|
+
const value: unknown = JSON.parse(body);
|
|
154
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
155
|
+
throw new Error('Remote response is not a JSON object');
|
|
156
|
+
}
|
|
157
|
+
return value as Record<string, unknown>;
|
|
158
|
+
}
|
package/src/node/delivery.ts
CHANGED
|
@@ -330,11 +330,18 @@ export interface DeliveryService {
|
|
|
330
330
|
senderUsername: string,
|
|
331
331
|
options?: { extraInboxes?: string[] },
|
|
332
332
|
): Promise<void>;
|
|
333
|
-
/**
|
|
333
|
+
/**
|
|
334
|
+
* Send a Follow activity to a remote actor (records the outbound follow, delivers/queues).
|
|
335
|
+
* By default the delivery runs in the background, so a request never waits on
|
|
336
|
+
* the remote. `durable` hands it to the delivery queue BEFORE resolving
|
|
337
|
+
* (resolving the actor's inbox first, and throwing when it has none), for a
|
|
338
|
+
* caller that may exit right after — a one-shot script.
|
|
339
|
+
*/
|
|
334
340
|
sendFollow(
|
|
335
341
|
localOxyUserId: string,
|
|
336
342
|
localUsername: string,
|
|
337
343
|
remoteActorUri: string,
|
|
344
|
+
options?: { durable?: boolean },
|
|
338
345
|
): Promise<{ success: boolean; pending: boolean }>;
|
|
339
346
|
/**
|
|
340
347
|
* Remove the local follow and attempt Undo delivery. True means the local
|
|
@@ -619,6 +626,7 @@ export function createDeliveryService<TActor extends DeliveryActorFields>(
|
|
|
619
626
|
localOxyUserId: string,
|
|
620
627
|
localUsername: string,
|
|
621
628
|
remoteActorUri: string,
|
|
629
|
+
options: { durable?: boolean } = {},
|
|
622
630
|
): Promise<{ success: boolean; pending: boolean }> {
|
|
623
631
|
if (!config.federationEnabled) return { success: false, pending: false };
|
|
624
632
|
if (isBlockedUrl(remoteActorUri)) {
|
|
@@ -648,6 +656,24 @@ export function createDeliveryService<TActor extends DeliveryActorFields>(
|
|
|
648
656
|
|
|
649
657
|
// Refuse before committing an outbound follow or reporting success.
|
|
650
658
|
await authorizeDelivery(activity, localOxyUserId);
|
|
659
|
+
|
|
660
|
+
if (options.durable) {
|
|
661
|
+
// The caller may exit as soon as this resolves, so nothing is left to the
|
|
662
|
+
// background: the inbox is resolved now, and the Follow is in the delivery
|
|
663
|
+
// queue (whose worker retries it) before the follow is reported.
|
|
664
|
+
const actor =
|
|
665
|
+
cached?.sharedInboxUrl || cached?.inboxUrl
|
|
666
|
+
? cached
|
|
667
|
+
: await config.actorRefresh.fetchRemoteActor(remoteActorUri);
|
|
668
|
+
const inbox = actor?.sharedInboxUrl ?? actor?.inboxUrl;
|
|
669
|
+
if (!inbox || isBlockedUrl(inbox)) {
|
|
670
|
+
throw new Error(`No inbox to deliver the Follow to ${remoteActorUri}`);
|
|
671
|
+
}
|
|
672
|
+
await config.follows.upsertOutboundPending(localOxyUserId, canonicalUri, activityId);
|
|
673
|
+
await queueDelivery(activity, inbox, localOxyUserId);
|
|
674
|
+
return { success: true, pending: actor?.manuallyApprovesFollowers ?? false };
|
|
675
|
+
}
|
|
676
|
+
|
|
651
677
|
// A refused follow must not start remote actor discovery either.
|
|
652
678
|
config.actorRefresh.refreshActorInBackground(remoteActorUri, cached ?? undefined);
|
|
653
679
|
await config.follows.upsertOutboundPending(localOxyUserId, canonicalUri, activityId);
|
package/src/node/index.ts
CHANGED
|
@@ -19,7 +19,11 @@
|
|
|
19
19
|
|
|
20
20
|
export {
|
|
21
21
|
createSignedFetch,
|
|
22
|
+
createSignedFetcher,
|
|
22
23
|
type SignedFetch,
|
|
24
|
+
type SignedFetcher,
|
|
25
|
+
type SignedFetchResult,
|
|
26
|
+
type SignedFetchLogDetail,
|
|
23
27
|
type SignedFetchInit,
|
|
24
28
|
type CreateSignedFetchConfig,
|
|
25
29
|
type SingleHopFetch,
|
|
@@ -27,6 +31,18 @@ export {
|
|
|
27
31
|
type SignedFetchLogger,
|
|
28
32
|
} from './signedFetch';
|
|
29
33
|
|
|
34
|
+
/**
|
|
35
|
+
* Bounded, deadlined reads of a remote `Response` body (the one reader behind
|
|
36
|
+
* every federation document read).
|
|
37
|
+
*/
|
|
38
|
+
export {
|
|
39
|
+
readBoundedResponseJson,
|
|
40
|
+
readBoundedResponseText,
|
|
41
|
+
ResponseBodyTooLargeError,
|
|
42
|
+
ResponseBodyTimeoutError,
|
|
43
|
+
type ResponseBodyLimits,
|
|
44
|
+
} from './boundedBody';
|
|
45
|
+
|
|
30
46
|
/**
|
|
31
47
|
* X's `t.co` wrapper unwrapped into the link the author posted, over the same
|
|
32
48
|
* injected single-hop transport — for bridged X bios and posts.
|
|
@@ -62,6 +78,8 @@ export {
|
|
|
62
78
|
export {
|
|
63
79
|
createActorResolver,
|
|
64
80
|
ActorResolver,
|
|
81
|
+
type ActorDocumentFetch,
|
|
82
|
+
type ActorDocumentFetchResult,
|
|
65
83
|
type ActorResolverConfig,
|
|
66
84
|
type ActorResolverIdentity,
|
|
67
85
|
type ActorResolverLogger,
|
package/src/node/signedFetch.ts
CHANGED
|
@@ -44,10 +44,18 @@ export interface SingleHopFetchInit {
|
|
|
44
44
|
*/
|
|
45
45
|
export type SingleHopFetch = (url: string, init: SingleHopFetchInit) => Promise<Response>;
|
|
46
46
|
|
|
47
|
+
/** What a {@link SignedFetchLogger} line is about, for a sink that formats its own. */
|
|
48
|
+
export interface SignedFetchLogDetail {
|
|
49
|
+
/** The status that prompted the line. */
|
|
50
|
+
status: number;
|
|
51
|
+
/** The URL the answer came from (after redirects). */
|
|
52
|
+
url: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
47
55
|
/** Non-fatal diagnostics sink for signed fetches. */
|
|
48
56
|
export interface SignedFetchLogger {
|
|
49
|
-
info(message: string): void;
|
|
50
|
-
warn(message: string): void;
|
|
57
|
+
info(message: string, detail?: SignedFetchLogDetail): void;
|
|
58
|
+
warn(message: string, detail?: SignedFetchLogDetail): void;
|
|
51
59
|
}
|
|
52
60
|
|
|
53
61
|
/** Adapters + config a {@link SignedFetch} is built from. */
|
|
@@ -85,6 +93,24 @@ export type SignedFetch = (
|
|
|
85
93
|
init?: SignedFetchInit,
|
|
86
94
|
) => Promise<Response>;
|
|
87
95
|
|
|
96
|
+
/** A {@link SignedFetch} answer with the URL it came from, after redirects. */
|
|
97
|
+
export interface SignedFetchResult {
|
|
98
|
+
response: Response;
|
|
99
|
+
/** The URL that answered: the request URL, or the last redirect hop followed. */
|
|
100
|
+
finalUrl: string;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* A signed ActivityPub GET that also reports the URL that answered — for a
|
|
105
|
+
* caller that binds a document to where it was served from (an actor whose `id`
|
|
106
|
+
* may name the redirect target rather than the URL asked for).
|
|
107
|
+
*/
|
|
108
|
+
export type SignedFetcher = (
|
|
109
|
+
url: string,
|
|
110
|
+
accept: string,
|
|
111
|
+
init?: SignedFetchInit,
|
|
112
|
+
) => Promise<SignedFetchResult>;
|
|
113
|
+
|
|
88
114
|
function requestInitHeaders(init: RequestInit): Record<string, string> {
|
|
89
115
|
if (!init.headers) return {};
|
|
90
116
|
if (init.headers instanceof Headers) {
|
|
@@ -121,11 +147,17 @@ function requestInitHeaders(init: RequestInit): Record<string, string> {
|
|
|
121
147
|
* (see {@link SignedFetchInit.keyId}); such a request is never retried unsigned.
|
|
122
148
|
*/
|
|
123
149
|
export function createSignedFetch(config: CreateSignedFetchConfig): SignedFetch {
|
|
150
|
+
const fetcher = createSignedFetcher(config);
|
|
151
|
+
return async (url, accept, init) => (await fetcher(url, accept, init)).response;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** {@link createSignedFetch}, answering with the final URL as well ({@link SignedFetcher}). */
|
|
155
|
+
export function createSignedFetcher(config: CreateSignedFetchConfig): SignedFetcher {
|
|
124
156
|
return async function signedFetch(
|
|
125
157
|
url: string,
|
|
126
158
|
accept: string,
|
|
127
159
|
init: SignedFetchInit = {},
|
|
128
|
-
): Promise<
|
|
160
|
+
): Promise<SignedFetchResult> {
|
|
129
161
|
const acceptHeader = `${accept}, application/ld+json; profile="https://www.w3.org/ns/activitystreams"`;
|
|
130
162
|
const actorSigned = init.keyId !== undefined;
|
|
131
163
|
const keyId = init.keyId ?? (await config.getInstanceKeyId());
|
|
@@ -164,6 +196,7 @@ export function createSignedFetch(config: CreateSignedFetchConfig): SignedFetch
|
|
|
164
196
|
if (hop === SIGNED_FETCH_MAX_REDIRECTS || !location) {
|
|
165
197
|
return { res, finalUrl: currentUrl };
|
|
166
198
|
}
|
|
199
|
+
await res.body?.cancel().catch(() => {});
|
|
167
200
|
currentUrl = new URL(location, currentUrl).toString();
|
|
168
201
|
}
|
|
169
202
|
throw new Error('redirect loop exhausted');
|
|
@@ -173,7 +206,7 @@ export function createSignedFetch(config: CreateSignedFetchConfig): SignedFetch
|
|
|
173
206
|
|
|
174
207
|
// An actor-signed answer is the remote's verdict for THAT actor (a follower or
|
|
175
208
|
// recipient): an unsigned retry asks a different question, so it never runs.
|
|
176
|
-
if (actorSigned) return res;
|
|
209
|
+
if (actorSigned) return { response: res, finalUrl };
|
|
177
210
|
|
|
178
211
|
// If the remote server returns a 5xx (e.g. it can't resolve our keyId to
|
|
179
212
|
// verify the signature), retry without the signature as a fallback for public
|
|
@@ -182,8 +215,12 @@ export function createSignedFetch(config: CreateSignedFetchConfig): SignedFetch
|
|
|
182
215
|
if (res.status >= 500) {
|
|
183
216
|
config.logger?.info(
|
|
184
217
|
`[FedSync] signedFetch got ${res.status} for ${finalUrl}, retrying unsigned`,
|
|
218
|
+
{ status: res.status, url: finalUrl },
|
|
185
219
|
);
|
|
186
|
-
|
|
220
|
+
// The failed signed answer's body is never read; release its stream.
|
|
221
|
+
await res.body?.cancel().catch(() => {});
|
|
222
|
+
const unsigned = await fetchFollowingRedirects(finalUrl, false);
|
|
223
|
+
return { response: unsigned.res, finalUrl: unsigned.finalUrl };
|
|
187
224
|
}
|
|
188
225
|
|
|
189
226
|
// A 401/403 on a signed request means the remote rejected OUR signature (e.g.
|
|
@@ -195,9 +232,10 @@ export function createSignedFetch(config: CreateSignedFetchConfig): SignedFetch
|
|
|
195
232
|
if (res.status === 401 || res.status === 403) {
|
|
196
233
|
config.logger?.warn(
|
|
197
234
|
`[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`,
|
|
235
|
+
{ status: res.status, url: finalUrl },
|
|
198
236
|
);
|
|
199
237
|
}
|
|
200
238
|
|
|
201
|
-
return res;
|
|
239
|
+
return { response: res, finalUrl };
|
|
202
240
|
};
|
|
203
241
|
}
|