@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.
- package/dist/cjs/apUri.js +0 -16
- package/dist/cjs/apValue.js +164 -0
- package/dist/cjs/index.js +17 -2
- package/dist/cjs/networkIdentity.js +2 -3
- package/dist/cjs/node/actorResolver.js +81 -110
- package/dist/cjs/node/actorRouter.js +2 -1
- package/dist/cjs/node/boundedBody.js +44 -0
- package/dist/cjs/node/inboundDispatch.js +6 -15
- package/dist/cjs/node/index.js +11 -1
- package/dist/cjs/node/signedFetch.js +15 -5
- package/dist/esm/apUri.js +0 -15
- package/dist/esm/apValue.js +155 -0
- package/dist/esm/index.js +10 -1
- package/dist/esm/networkIdentity.js +2 -3
- package/dist/esm/node/actorResolver.js +72 -101
- package/dist/esm/node/actorRouter.js +2 -1
- package/dist/esm/node/boundedBody.js +42 -0
- package/dist/esm/node/inboundDispatch.js +6 -15
- package/dist/esm/node/index.js +6 -1
- package/dist/esm/node/signedFetch.js +14 -5
- package/dist/types/apUri.d.ts +0 -7
- package/dist/types/apValue.d.ts +75 -0
- package/dist/types/index.d.ts +15 -16
- package/dist/types/node/actorResolver.d.ts +53 -11
- package/dist/types/node/boundedBody.d.ts +19 -0
- package/dist/types/node/inboundDispatch.d.ts +1 -0
- 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 +90 -2
- package/src/__tests__/apValue.test.ts +93 -0
- package/src/__tests__/networkIdentity.test.ts +4 -2
- package/src/__tests__/signedFetch.test.ts +26 -3
- package/src/apUri.ts +0 -15
- package/src/apValue.ts +153 -0
- package/src/index.ts +23 -17
- package/src/networkIdentity.ts +2 -2
- package/src/node/actorResolver.ts +139 -123
- package/src/node/actorRouter.ts +2 -2
- package/src/node/boundedBody.ts +62 -0
- package/src/node/inboundDispatch.ts +6 -14
- package/src/node/index.ts +18 -0
- package/src/node/signedFetch.ts +44 -6
|
@@ -19,7 +19,8 @@
|
|
|
19
19
|
* document.
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
|
-
import {
|
|
22
|
+
import { canonicalFederationHost, isSameFederationHost } from '../apUri';
|
|
23
|
+
import { apDate, apImageUrl, apIri, apIriList, apList, isActivityPubMediaType } from '../apValue';
|
|
23
24
|
import {
|
|
24
25
|
readProxyDeclarations,
|
|
25
26
|
type DeriveNetworkIdentity,
|
|
@@ -27,7 +28,7 @@ import {
|
|
|
27
28
|
type NetworkIdentityCandidate,
|
|
28
29
|
} from '../networkIdentity';
|
|
29
30
|
import type { NormalizedExternalActor } from '../index';
|
|
30
|
-
import {
|
|
31
|
+
import { readBoundedResponseJson, readBoundedResponseText } from './boundedBody';
|
|
31
32
|
import type { SignedFetch } from './signedFetch';
|
|
32
33
|
import type { ReportActorGoneOutcome } from './identityBridge';
|
|
33
34
|
import type { FetchPublicKeyOptions } from '../httpSignature';
|
|
@@ -63,52 +64,6 @@ const COLLECTION_BODY_MAX_BYTES = 64 * 1024;
|
|
|
63
64
|
const COLLECTION_WITHHELD_STATUSES: ReadonlySet<number> = new Set([401, 403, 404, 410]);
|
|
64
65
|
const ERROR_BODY_MAX_BYTES = 4 * 1024;
|
|
65
66
|
|
|
66
|
-
/**
|
|
67
|
-
* Deadline for reading a whole actor/collection/error body once its headers
|
|
68
|
-
* arrived. `signedFetch`'s timeout ends at the headers, so without this a remote
|
|
69
|
-
* that stalls mid-body would hold the resolver open.
|
|
70
|
-
*/
|
|
71
|
-
const BODY_TIMEOUT_MS = 10_000;
|
|
72
|
-
|
|
73
|
-
async function readBoundedResponseBody(res: Response, maxBytes: number): Promise<string> {
|
|
74
|
-
const contentLength = res.headers.get('content-length');
|
|
75
|
-
if (contentLength) {
|
|
76
|
-
const declaredBytes = Number(contentLength);
|
|
77
|
-
if (Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {
|
|
78
|
-
await res.body?.cancel().catch(() => {});
|
|
79
|
-
throw new ResponseBodyTooLargeError(maxBytes);
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
if (!res.body) return '';
|
|
84
|
-
|
|
85
|
-
const reader = res.body.getReader();
|
|
86
|
-
const body = await readBodyChunks(
|
|
87
|
-
{ read: () => reader.read(), cancel: () => void reader.cancel().catch(() => {}) },
|
|
88
|
-
{ maxBytes, timeoutMs: BODY_TIMEOUT_MS },
|
|
89
|
-
);
|
|
90
|
-
return new TextDecoder('utf-8', { fatal: true }).decode(body);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
async function readBoundedJson(res: Response, maxBytes: number): Promise<Record<string, unknown>> {
|
|
94
|
-
const body = await readBoundedResponseBody(res, maxBytes);
|
|
95
|
-
// An empty body is a REMOTE's answer, not a parser error. Without this,
|
|
96
|
-
// `JSON.parse('')` throws a SyntaxError whose message names a column number,
|
|
97
|
-
// which is a worse thing to find in a federation log than the fact that the
|
|
98
|
-
// instance sent nothing.
|
|
99
|
-
if (body.length === 0) throw new Error('Remote response has no body');
|
|
100
|
-
const value: unknown = JSON.parse(body);
|
|
101
|
-
const record = asRecord(value);
|
|
102
|
-
if (!record) throw new Error('Remote response is not a JSON object');
|
|
103
|
-
return record;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
function isApActorContentType(type: string | undefined): boolean {
|
|
107
|
-
if (!type) return false;
|
|
108
|
-
const base = type.split(';')[0]?.trim().toLowerCase();
|
|
109
|
-
return base === 'application/activity+json' || base === 'application/ld+json';
|
|
110
|
-
}
|
|
111
|
-
|
|
112
67
|
/** The minimal fields the resolver reads off / writes to a stored actor record. */
|
|
113
68
|
export interface FederatedActorRecordBase {
|
|
114
69
|
_id?: unknown;
|
|
@@ -202,11 +157,15 @@ export interface FederatedActorUpsert {
|
|
|
202
157
|
export type CollectionCount = number | null | undefined;
|
|
203
158
|
|
|
204
159
|
/** Bring-your-own-store: the AP actor cache stays in the app DB behind this adapter. */
|
|
205
|
-
export interface FederatedActorStore<TActor extends FederatedActorRecordBase> {
|
|
160
|
+
export interface FederatedActorStore<TActor extends FederatedActorRecordBase, TSource = undefined> {
|
|
206
161
|
/** Look up a cached actor by its protocol URI. */
|
|
207
162
|
findActorByUri(uri: string): Promise<TActor | null>;
|
|
208
|
-
/**
|
|
209
|
-
|
|
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>;
|
|
210
169
|
/** Look up a cached actor by its `publicKey.id` (HTTP-signature key resolution). */
|
|
211
170
|
findActorByPublicKeyId(keyId: string): Promise<Pick<TActor, 'uri' | 'publicKeyPem'> | null>;
|
|
212
171
|
/** Stamp the resolved Oxy user id onto an actor row (identified by its `_id`). */
|
|
@@ -262,6 +221,41 @@ export interface ActorTextAdapter {
|
|
|
262
221
|
qualifyHandles?(text: string, instanceDomain: string): string;
|
|
263
222
|
}
|
|
264
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
|
+
|
|
265
259
|
/** A parsed WebFinger JRD (only the `links` we read). */
|
|
266
260
|
export interface WebFingerJrd {
|
|
267
261
|
links?: Array<{ rel?: string; type?: string; href?: string }>;
|
|
@@ -281,11 +275,21 @@ export interface ActorResolverLogger {
|
|
|
281
275
|
}
|
|
282
276
|
|
|
283
277
|
/** Adapters + config an {@link ActorResolver} is built from. */
|
|
284
|
-
export interface ActorResolverConfig<TActor extends FederatedActorRecordBase> {
|
|
278
|
+
export interface ActorResolverConfig<TActor extends FederatedActorRecordBase, TSource = undefined> {
|
|
285
279
|
/** Whether federation is enabled (gates background refreshes). */
|
|
286
280
|
federationEnabled: boolean;
|
|
287
|
-
/** Signed AP GET (
|
|
281
|
+
/** Signed AP GET (collection-count fetches, and actor documents by default). */
|
|
288
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>;
|
|
289
293
|
/** SSRF-safe bounded WebFinger fetch. */
|
|
290
294
|
fetchWebFinger: WebFingerFetch;
|
|
291
295
|
/** Per-instance blocked-domain check (own domains + identity apex + configured blocks). */
|
|
@@ -294,15 +298,18 @@ export interface ActorResolverConfig<TActor extends FederatedActorRecordBase> {
|
|
|
294
298
|
normalizeFederatedAcct: (acct: string | undefined) => string | undefined;
|
|
295
299
|
/** Extract the domain from a canonical acct. */
|
|
296
300
|
domainFromAcct: (acct: string) => string | undefined;
|
|
297
|
-
/**
|
|
298
|
-
|
|
301
|
+
/**
|
|
302
|
+
* The first absolute http(s) URL in an `icon` / `image` value. Optional: the
|
|
303
|
+
* default is {@link apImageUrl}, which reads every image shape.
|
|
304
|
+
*/
|
|
305
|
+
firstStringUrl?: (value: unknown) => string | undefined;
|
|
299
306
|
/**
|
|
300
307
|
* Optional re-labelling of a bridged actor onto its real network. Absent means
|
|
301
308
|
* every actor keeps the identity of the host it was fetched from.
|
|
302
309
|
*/
|
|
303
310
|
deriveNetworkIdentity?: DeriveNetworkIdentity;
|
|
304
311
|
/** The app's actor cache store. */
|
|
305
|
-
store: FederatedActorStore<TActor>;
|
|
312
|
+
store: FederatedActorStore<TActor, TSource>;
|
|
306
313
|
/** The actor↔Oxy-user identity bridge. */
|
|
307
314
|
identity: ActorResolverIdentity;
|
|
308
315
|
/** Remote-text normalization. */
|
|
@@ -354,14 +361,34 @@ function actorPublicKeyIsSelfConsistent(actor: Record<string, unknown>, actorId:
|
|
|
354
361
|
* through the instance (e.g. `fetchRemoteActor` → `this.tombstoneGoneActor`),
|
|
355
362
|
* which keeps them spy-able and overridable in tests.
|
|
356
363
|
*/
|
|
357
|
-
export class ActorResolver<TActor extends FederatedActorRecordBase> {
|
|
364
|
+
export class ActorResolver<TActor extends FederatedActorRecordBase, TSource = undefined> {
|
|
358
365
|
/** Actor URIs with an in-flight background refresh (guards against refresh storms). */
|
|
359
366
|
private readonly inFlightActorRefreshes = new Set<string>();
|
|
360
367
|
|
|
361
368
|
/** Actor key refetches in flight, by actor URI: concurrent failed signatures share one. */
|
|
362
369
|
private readonly inFlightKeyRefetches = new Map<string, Promise<TActor | null>>();
|
|
363
370
|
|
|
364
|
-
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
|
+
}
|
|
365
392
|
|
|
366
393
|
/**
|
|
367
394
|
* Whether an actor URI's host is refused by the instance domain policy. An
|
|
@@ -403,7 +430,7 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
|
|
|
403
430
|
try {
|
|
404
431
|
const data = await this.config.fetchWebFinger(url);
|
|
405
432
|
if (!data) return null;
|
|
406
|
-
const link = data.links?.find((l) => l.rel === 'self' &&
|
|
433
|
+
const link = data.links?.find((l) => l.rel === 'self' && isActivityPubMediaType(l.type));
|
|
407
434
|
return link?.href || null;
|
|
408
435
|
} catch (err) {
|
|
409
436
|
this.config.logger.warn(`WebFinger resolution failed for ${acct}:`, err);
|
|
@@ -440,22 +467,20 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
|
|
|
440
467
|
}
|
|
441
468
|
|
|
442
469
|
const canonicalAcctHint = this.config.normalizeFederatedAcct(acctHint);
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
if (!res.ok) {
|
|
470
|
+
let fetched = await this.readActorDocument(currentUri, canonicalAcctHint);
|
|
471
|
+
if (!hasActorDocument(fetched)) {
|
|
446
472
|
// A definitive 410 Gone is authoritative: tombstone and stop — do NOT fall
|
|
447
473
|
// through to the WebFinger fallback (which recovers a STALE/wrong URI on a
|
|
448
474
|
// transient failure, not a permanent removal). Only 410 does this.
|
|
449
|
-
if (
|
|
475
|
+
if (fetched.status === 410) {
|
|
450
476
|
this.config.logger.info(
|
|
451
477
|
`[FedSync] fetchRemoteActor 410 Gone for ${currentUri} — tombstoning actor`,
|
|
452
478
|
);
|
|
453
479
|
await this.tombstoneGoneActor(currentUri);
|
|
454
480
|
return null;
|
|
455
481
|
}
|
|
456
|
-
const body = await readBoundedResponseBody(res, ERROR_BODY_MAX_BYTES).catch(() => '');
|
|
457
482
|
this.config.logger.info(
|
|
458
|
-
`[FedSync] fetchRemoteActor HTTP ${
|
|
483
|
+
`[FedSync] fetchRemoteActor HTTP ${fetched.status}${fetched.detail ? ` ${fetched.detail}` : ''} for ${currentUri}`,
|
|
459
484
|
);
|
|
460
485
|
|
|
461
486
|
// If direct fetch failed, try WebFinger to resolve the canonical actor URI.
|
|
@@ -468,44 +493,34 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
|
|
|
468
493
|
(pathUsername
|
|
469
494
|
? this.config.normalizeFederatedAcct(`${pathUsername}@${parsed.hostname}`)
|
|
470
495
|
: undefined);
|
|
471
|
-
if (acct)
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
`[FedSync] fetchRemoteActor 410 Gone for resolved ${resolved} — tombstoning actor ${currentUri}`,
|
|
485
|
-
);
|
|
486
|
-
await this.tombstoneGoneActor(currentUri);
|
|
487
|
-
return null;
|
|
488
|
-
}
|
|
489
|
-
const body2 = await readBoundedResponseBody(res, ERROR_BODY_MAX_BYTES).catch(
|
|
490
|
-
() => '',
|
|
491
|
-
);
|
|
492
|
-
this.config.logger.info(
|
|
493
|
-
`[FedSync] fetchRemoteActor HTTP ${res.status} for resolved ${resolved} body=${body2.slice(0, 500)}`,
|
|
494
|
-
);
|
|
495
|
-
return null;
|
|
496
|
-
}
|
|
497
|
-
} 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) {
|
|
498
509
|
this.config.logger.info(
|
|
499
|
-
`[FedSync]
|
|
510
|
+
`[FedSync] fetchRemoteActor 410 Gone for resolved ${resolved} — tombstoning actor ${currentUri}`,
|
|
500
511
|
);
|
|
512
|
+
await this.tombstoneGoneActor(currentUri);
|
|
501
513
|
return null;
|
|
502
514
|
}
|
|
503
|
-
|
|
515
|
+
this.config.logger.info(
|
|
516
|
+
`[FedSync] fetchRemoteActor HTTP ${fetched.status}${fetched.detail ? ` ${fetched.detail}` : ''} for resolved ${resolved}`,
|
|
517
|
+
);
|
|
504
518
|
return null;
|
|
505
519
|
}
|
|
520
|
+
currentUri = resolved;
|
|
506
521
|
}
|
|
507
522
|
|
|
508
|
-
const actor =
|
|
523
|
+
const actor = fetched.document;
|
|
509
524
|
const actorId = asString(actor.id);
|
|
510
525
|
const actorInbox = apIri(actor.inbox);
|
|
511
526
|
if (!actorId || !actorInbox) {
|
|
@@ -573,26 +588,25 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
|
|
|
573
588
|
// normalizing: the canonical normalizer collapses whitespace, it never
|
|
574
589
|
// strips markup — so the sanitizer must run first, on the raw value.
|
|
575
590
|
const fields: FederatedActorField[] = [];
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
});
|
|
591
|
-
}
|
|
591
|
+
for (const att of apList(actor.attachment)) {
|
|
592
|
+
const attRecord = asRecord(att);
|
|
593
|
+
if (!attRecord || attRecord.type !== 'PropertyValue') continue;
|
|
594
|
+
const fieldName = this.config.text.inlineField(attRecord.name);
|
|
595
|
+
const fieldValue =
|
|
596
|
+
typeof attRecord.value === 'string'
|
|
597
|
+
? this.config.text.sanitizeFieldValue(attRecord.value)
|
|
598
|
+
: '';
|
|
599
|
+
if (!fieldName || !fieldValue) continue;
|
|
600
|
+
fields.push({
|
|
601
|
+
name: fieldName,
|
|
602
|
+
value: fieldValue,
|
|
603
|
+
verifiedAt: apDate(attRecord.verifiedAt),
|
|
604
|
+
});
|
|
592
605
|
}
|
|
593
606
|
|
|
594
|
-
const
|
|
595
|
-
const
|
|
607
|
+
const imageUrl = this.config.firstStringUrl ?? apImageUrl;
|
|
608
|
+
const avatarUrl = imageUrl(actor.icon);
|
|
609
|
+
const headerUrl = imageUrl(actor.image);
|
|
596
610
|
// `summary` is the actor's bio — a BODY, so its line breaks are the author's
|
|
597
611
|
// and must survive; `htmlToPlainText` normalizes it as multiline.
|
|
598
612
|
const summary =
|
|
@@ -602,9 +616,12 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
|
|
|
602
616
|
const rawDisplayName = typeof actor.name === 'string' ? actor.name : '';
|
|
603
617
|
const displayName = this.config.text.inlineDisplayName(rawDisplayName) || username;
|
|
604
618
|
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
619
|
+
// Absent stays absent (the store keeps what it has); one alias or a list
|
|
620
|
+
// of them is the list.
|
|
621
|
+
const alsoKnownAs =
|
|
622
|
+
actor.alsoKnownAs === undefined || actor.alsoKnownAs === null
|
|
623
|
+
? undefined
|
|
624
|
+
: apIriList(actor.alsoKnownAs);
|
|
608
625
|
// A move target is an actor URL; anything else is not one.
|
|
609
626
|
const movedToValue = apIri(actor.movedTo);
|
|
610
627
|
const movedTo = movedToValue && /^https?:\/\//.test(movedToValue) ? movedToValue : undefined;
|
|
@@ -666,8 +683,7 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
|
|
|
666
683
|
alsoKnownAs,
|
|
667
684
|
...(movedTo && { movedTo }),
|
|
668
685
|
networkAcct: networkIdentity?.federatedUsername,
|
|
669
|
-
remoteCreatedAt:
|
|
670
|
-
typeof actor.published === 'string' ? new Date(actor.published) : undefined,
|
|
686
|
+
remoteCreatedAt: apDate(actor.published),
|
|
671
687
|
// Omitted, not written as `undefined`, when this refresh could not tell:
|
|
672
688
|
// an absent key is what tells the store to keep the value it has.
|
|
673
689
|
...(followersCount !== undefined && { followersCount }),
|
|
@@ -676,7 +692,7 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
|
|
|
676
692
|
lastFetchedAt: new Date(),
|
|
677
693
|
};
|
|
678
694
|
|
|
679
|
-
const fedActor = await this.config.store.upsertActor(actorId, update);
|
|
695
|
+
const fedActor = await this.config.store.upsertActor(actorId, update, fetched.source);
|
|
680
696
|
|
|
681
697
|
// Always upsert into Oxy so profile changes (avatar, name, bio) are synced.
|
|
682
698
|
// The identity bridge creates the federated Oxy user if it does not exist,
|
|
@@ -825,7 +841,7 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
|
|
|
825
841
|
if (!res.ok) {
|
|
826
842
|
return COLLECTION_WITHHELD_STATUSES.has(res.status) ? null : undefined;
|
|
827
843
|
}
|
|
828
|
-
const col = await
|
|
844
|
+
const col = await readBoundedResponseJson(res, { maxBytes: COLLECTION_BODY_MAX_BYTES });
|
|
829
845
|
const total = col.totalItems;
|
|
830
846
|
return typeof total === 'number' && Number.isSafeInteger(total) && total >= 0 ? total : null;
|
|
831
847
|
} catch {
|
|
@@ -975,8 +991,8 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
|
|
|
975
991
|
}
|
|
976
992
|
|
|
977
993
|
/** Build the remote-actor resolver from an app's storage + identity + transports. */
|
|
978
|
-
export function createActorResolver<TActor extends FederatedActorRecordBase>(
|
|
979
|
-
config: ActorResolverConfig<TActor>,
|
|
980
|
-
): ActorResolver<TActor> {
|
|
994
|
+
export function createActorResolver<TActor extends FederatedActorRecordBase, TSource = undefined>(
|
|
995
|
+
config: ActorResolverConfig<TActor, TSource>,
|
|
996
|
+
): ActorResolver<TActor, TSource> {
|
|
981
997
|
return new ActorResolver(config);
|
|
982
998
|
}
|
package/src/node/actorRouter.ts
CHANGED
|
@@ -25,6 +25,7 @@ import { Router, type Request, type Response } from 'express';
|
|
|
25
25
|
import type { AccountKind } from '@oxy.so/contracts';
|
|
26
26
|
import type { User } from '@oxy.so/core';
|
|
27
27
|
import { AP_CONTEXT } from '../apContext';
|
|
28
|
+
import { apIri } from '../apValue';
|
|
28
29
|
import { discoveryCacheControl } from './httpCacheControl';
|
|
29
30
|
import { type FetchPublicKey, verifyHttpSignature } from '../httpSignature';
|
|
30
31
|
import type { UrlBuilders } from '../urls';
|
|
@@ -233,8 +234,7 @@ export function createActorRouter(config: ActorRouterConfig): Router {
|
|
|
233
234
|
}
|
|
234
235
|
|
|
235
236
|
// Verify the actor in the activity matches the signature.
|
|
236
|
-
const activityActor =
|
|
237
|
-
typeof activity.actor === 'string' ? activity.actor : activity.actor?.id;
|
|
237
|
+
const activityActor = apIri(activity.actor);
|
|
238
238
|
if (activityActor !== actorUri) {
|
|
239
239
|
logger.debug(`Inbox: Actor mismatch. Signed: ${actorUri}, Activity: ${activityActor}`);
|
|
240
240
|
return res.status(403).json({ error: 'Actor mismatch' });
|
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
|
+
}
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
* `handleReject`.
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
|
+
import { apIri } from '../apValue';
|
|
26
27
|
import { normalizeActorUsername } from '../urls';
|
|
27
28
|
|
|
28
29
|
/**
|
|
@@ -226,11 +227,11 @@ function parseInboundMove(
|
|
|
226
227
|
): { ok: true; move: InboundMove } | { ok: false; reason: string } {
|
|
227
228
|
const activityId = typeof activity.id === 'string' ? activity.id : undefined;
|
|
228
229
|
if (!activityId) return { ok: false, reason: 'missing id' };
|
|
229
|
-
const actor =
|
|
230
|
+
const actor = apIri(activity.actor);
|
|
230
231
|
if (actor !== verifiedActorUri) return { ok: false, reason: 'actor is not the signer' };
|
|
231
|
-
const object =
|
|
232
|
+
const object = apIri(activity.object);
|
|
232
233
|
if (object !== verifiedActorUri) return { ok: false, reason: 'object is not the moving actor' };
|
|
233
|
-
const target =
|
|
234
|
+
const target = apIri(activity.target);
|
|
234
235
|
if (!target) return { ok: false, reason: 'missing target' };
|
|
235
236
|
try {
|
|
236
237
|
if (new URL(target).protocol !== 'https:') return { ok: false, reason: 'target is not https' };
|
|
@@ -261,15 +262,6 @@ function actorUriHost(actorUri: string): string | null {
|
|
|
261
262
|
}
|
|
262
263
|
|
|
263
264
|
/** Read the `object`'s referenced actor/target uri (a string, or an embedded `{ id }`). */
|
|
264
|
-
function objectTargetUri(object: unknown): string | undefined {
|
|
265
|
-
if (typeof object === 'string') return object;
|
|
266
|
-
if (object && typeof object === 'object') {
|
|
267
|
-
const id = (object as { id?: unknown }).id;
|
|
268
|
-
if (typeof id === 'string') return id;
|
|
269
|
-
}
|
|
270
|
-
return undefined;
|
|
271
|
-
}
|
|
272
|
-
|
|
273
265
|
/** Build the inbound-activity dispatcher from an app's adapters + content handlers. */
|
|
274
266
|
export function createInboundDispatcher(config: InboundDispatcherConfig): InboundDispatcher {
|
|
275
267
|
const { logger } = config;
|
|
@@ -278,7 +270,7 @@ export function createInboundDispatcher(config: InboundDispatcherConfig): Inboun
|
|
|
278
270
|
activity: Record<string, unknown>,
|
|
279
271
|
actorUri: string,
|
|
280
272
|
): Promise<void> {
|
|
281
|
-
const targetActorUri =
|
|
273
|
+
const targetActorUri = apIri(activity.object);
|
|
282
274
|
if (!targetActorUri) return;
|
|
283
275
|
|
|
284
276
|
// Extract username from our actor URL
|
|
@@ -356,7 +348,7 @@ export function createInboundDispatcher(config: InboundDispatcherConfig): Inboun
|
|
|
356
348
|
object: Record<string, unknown>,
|
|
357
349
|
actorUri: string,
|
|
358
350
|
): Promise<void> {
|
|
359
|
-
const targetActorUri =
|
|
351
|
+
const targetActorUri = apIri(object.object);
|
|
360
352
|
const match = targetActorUri?.match(/\/ap\/users\/([^/]+)$/);
|
|
361
353
|
let localUserId: string | undefined;
|
|
362
354
|
if (match) {
|
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,
|