@oxy.so/federation 2.16.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/cjs/apUri.js +0 -16
  2. package/dist/cjs/apValue.js +164 -0
  3. package/dist/cjs/index.js +17 -2
  4. package/dist/cjs/networkIdentity.js +2 -3
  5. package/dist/cjs/node/actorResolver.js +81 -110
  6. package/dist/cjs/node/actorRouter.js +2 -1
  7. package/dist/cjs/node/boundedBody.js +44 -0
  8. package/dist/cjs/node/inboundDispatch.js +6 -15
  9. package/dist/cjs/node/index.js +11 -1
  10. package/dist/cjs/node/signedFetch.js +15 -5
  11. package/dist/esm/apUri.js +0 -15
  12. package/dist/esm/apValue.js +155 -0
  13. package/dist/esm/index.js +10 -1
  14. package/dist/esm/networkIdentity.js +2 -3
  15. package/dist/esm/node/actorResolver.js +72 -101
  16. package/dist/esm/node/actorRouter.js +2 -1
  17. package/dist/esm/node/boundedBody.js +42 -0
  18. package/dist/esm/node/inboundDispatch.js +6 -15
  19. package/dist/esm/node/index.js +6 -1
  20. package/dist/esm/node/signedFetch.js +14 -5
  21. package/dist/types/apUri.d.ts +0 -7
  22. package/dist/types/apValue.d.ts +75 -0
  23. package/dist/types/index.d.ts +15 -16
  24. package/dist/types/node/actorResolver.d.ts +53 -11
  25. package/dist/types/node/boundedBody.d.ts +19 -0
  26. package/dist/types/node/inboundDispatch.d.ts +1 -0
  27. package/dist/types/node/index.d.ts +7 -2
  28. package/dist/types/node/signedFetch.d.ts +23 -2
  29. package/package.json +1 -1
  30. package/src/__tests__/actorResolver.test.ts +90 -2
  31. package/src/__tests__/apValue.test.ts +93 -0
  32. package/src/__tests__/networkIdentity.test.ts +4 -2
  33. package/src/__tests__/signedFetch.test.ts +26 -3
  34. package/src/apUri.ts +0 -15
  35. package/src/apValue.ts +153 -0
  36. package/src/index.ts +23 -17
  37. package/src/networkIdentity.ts +2 -2
  38. package/src/node/actorResolver.ts +139 -123
  39. package/src/node/actorRouter.ts +2 -2
  40. package/src/node/boundedBody.ts +62 -0
  41. package/src/node/inboundDispatch.ts +6 -14
  42. package/src/node/index.ts +18 -0
  43. package/src/node/signedFetch.ts +44 -6
@@ -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
+ }
@@ -22,6 +22,7 @@
22
22
  * dispatcher + `handleIncomingFollow` / `handleUndo(Follow)` / `handleAccept` /
23
23
  * `handleReject`.
24
24
  */
25
+ import { apIri } from '../apValue.js';
25
26
  import { normalizeActorUsername } from '../urls.js';
26
27
  /**
27
28
  * Thrown when a federated follow is about to be bridged but the FOLLOWER actor
@@ -56,13 +57,13 @@ function parseInboundMove(activity, verifiedActorUri) {
56
57
  const activityId = typeof activity.id === 'string' ? activity.id : undefined;
57
58
  if (!activityId)
58
59
  return { ok: false, reason: 'missing id' };
59
- const actor = objectTargetUri(activity.actor);
60
+ const actor = apIri(activity.actor);
60
61
  if (actor !== verifiedActorUri)
61
62
  return { ok: false, reason: 'actor is not the signer' };
62
- const object = objectTargetUri(activity.object);
63
+ const object = apIri(activity.object);
63
64
  if (object !== verifiedActorUri)
64
65
  return { ok: false, reason: 'object is not the moving actor' };
65
- const target = objectTargetUri(activity.target);
66
+ const target = apIri(activity.target);
66
67
  if (!target)
67
68
  return { ok: false, reason: 'missing target' };
68
69
  try {
@@ -90,21 +91,11 @@ function actorUriHost(actorUri) {
90
91
  }
91
92
  }
92
93
  /** Read the `object`'s referenced actor/target uri (a string, or an embedded `{ id }`). */
93
- function objectTargetUri(object) {
94
- if (typeof object === 'string')
95
- return object;
96
- if (object && typeof object === 'object') {
97
- const id = object.id;
98
- if (typeof id === 'string')
99
- return id;
100
- }
101
- return undefined;
102
- }
103
94
  /** Build the inbound-activity dispatcher from an app's adapters + content handlers. */
104
95
  export function createInboundDispatcher(config) {
105
96
  const { logger } = config;
106
97
  async function handleIncomingFollow(activity, actorUri) {
107
- const targetActorUri = objectTargetUri(activity.object);
98
+ const targetActorUri = apIri(activity.object);
108
99
  if (!targetActorUri)
109
100
  return;
110
101
  // Extract username from our actor URL
@@ -169,7 +160,7 @@ export function createInboundDispatcher(config) {
169
160
  logger.info(`Accepted follow from ${actorUri} to ${username}`);
170
161
  }
171
162
  async function handleUndoFollow(object, actorUri) {
172
- const targetActorUri = objectTargetUri(object.object);
163
+ const targetActorUri = apIri(object.object);
173
164
  const match = targetActorUri?.match(/\/ap\/users\/([^/]+)$/);
174
165
  let localUserId;
175
166
  if (match) {
@@ -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.
@@ -60,6 +60,11 @@ function requestInitHeaders(init) {
60
60
  * (see {@link SignedFetchInit.keyId}); such a request is never retried unsigned.
61
61
  */
62
62
  export function createSignedFetch(config) {
63
+ const fetcher = createSignedFetcher(config);
64
+ return async (url, accept, init) => (await fetcher(url, accept, init)).response;
65
+ }
66
+ /** {@link createSignedFetch}, answering with the final URL as well ({@link SignedFetcher}). */
67
+ export function createSignedFetcher(config) {
63
68
  return async function signedFetch(url, accept, init = {}) {
64
69
  const acceptHeader = `${accept}, application/ld+json; profile="https://www.w3.org/ns/activitystreams"`;
65
70
  const actorSigned = init.keyId !== undefined;
@@ -94,6 +99,7 @@ export function createSignedFetch(config) {
94
99
  if (hop === SIGNED_FETCH_MAX_REDIRECTS || !location) {
95
100
  return { res, finalUrl: currentUrl };
96
101
  }
102
+ await res.body?.cancel().catch(() => { });
97
103
  currentUrl = new URL(location, currentUrl).toString();
98
104
  }
99
105
  throw new Error('redirect loop exhausted');
@@ -102,14 +108,17 @@ export function createSignedFetch(config) {
102
108
  // An actor-signed answer is the remote's verdict for THAT actor (a follower or
103
109
  // recipient): an unsigned retry asks a different question, so it never runs.
104
110
  if (actorSigned)
105
- return res;
111
+ return { response: res, finalUrl };
106
112
  // If the remote server returns a 5xx (e.g. it can't resolve our keyId to
107
113
  // verify the signature), retry without the signature as a fallback for public
108
114
  // resources. Retry from the post-redirect URL so we don't restart a chain that
109
115
  // already landed on the failing hop.
110
116
  if (res.status >= 500) {
111
- config.logger?.info(`[FedSync] signedFetch got ${res.status} for ${finalUrl}, retrying unsigned`);
112
- return fetchFollowingRedirects(finalUrl, false).then(({ res: unsignedRes }) => unsignedRes);
117
+ config.logger?.info(`[FedSync] signedFetch got ${res.status} for ${finalUrl}, retrying unsigned`, { status: res.status, url: finalUrl });
118
+ // The failed signed answer's body is never read; release its stream.
119
+ await res.body?.cancel().catch(() => { });
120
+ const unsigned = await fetchFollowingRedirects(finalUrl, false);
121
+ return { response: unsigned.res, finalUrl: unsigned.finalUrl };
113
122
  }
114
123
  // A 401/403 on a signed request means the remote rejected OUR signature (e.g.
115
124
  // it could not resolve/verify our keyId, or our instance key pair is
@@ -118,8 +127,8 @@ export function createSignedFetch(config) {
118
127
  // observable in production. The caller still receives the response and decides
119
128
  // how to proceed; we do not change control flow here.
120
129
  if (res.status === 401 || res.status === 403) {
121
- 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`);
130
+ 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 });
122
131
  }
123
- return res;
132
+ return { response: res, finalUrl };
124
133
  };
125
134
  }
@@ -59,13 +59,6 @@ export declare function canonicalFederationHost(host: string): string;
59
59
  * that is not named is not in any set.
60
60
  */
61
61
  export declare function isSameFederationHost(a: string, b: string): boolean;
62
- /**
63
- * The IRI a JSON-LD node reference names: the string itself, or the `id` of an
64
- * embedded object. ActivityStreams lets a server embed a referenced node (an
65
- * actor's `followers` collection with its `totalItems`, an `endpoints` value)
66
- * instead of linking it, and both mean the same node. Anything else names none.
67
- */
68
- export declare function apIri(value: unknown): string | undefined;
69
62
  /**
70
63
  * Given an ActivityPub activity/object ID (URL), extract the actor URI by
71
64
  * trimming everything from the first recognised post-path segment onward.
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The ONE way to read an ActivityStreams value whose JSON-LD shape varies.
3
+ *
4
+ * JSON-LD lets the same statement arrive in several shapes, and every one of
5
+ * them is valid ActivityPub:
6
+ *
7
+ * - compaction turns a one-element array into the value itself, so `tag`,
8
+ * `attachment`, `alsoKnownAs`, `to` or `icon` may be one object or a list
9
+ * (GoToSocial sends single values; Mastodon sends arrays);
10
+ * - a reference may be the IRI string, an embedded object naming it by `id`,
11
+ * or a `Link` naming it by `href`;
12
+ * - an image may be a URL string, an `Image` whose `url` is a string, a `Link`
13
+ * or a list of them, or a list of `Image`s (PeerTube 6+ sends icon sizes);
14
+ * - a media type may carry parameters (`application/ld+json; profile="…"`),
15
+ * spaced or quoted however the server likes;
16
+ * - a date may use any ISO 8601 offset spelling (`Z`, `+00:00`, `+0000`, `+00`).
17
+ *
18
+ * A reader that assumes one shape loses the others SILENTLY: the mention, tag,
19
+ * alias or avatar is simply not there, and nothing logs. These helpers accept
20
+ * every shape, so readers never re-derive the rule. They are pure and
21
+ * dependency-free (browser-safe).
22
+ */
23
+ /**
24
+ * A one-or-many ActivityStreams property as a list. A single value becomes a
25
+ * one-element list, an absent (`undefined` / `null`) value an empty one, and the
26
+ * `null` / `undefined` entries of a list are dropped.
27
+ */
28
+ export declare function apList(value: unknown): unknown[];
29
+ /**
30
+ * The IRI a JSON-LD node reference names: the string itself, the `id` of an
31
+ * embedded object, or the `href` of a `Link` (a `Mention` tag, a `Link` `url`).
32
+ * ActivityStreams lets a server embed a referenced node (an actor's `followers`
33
+ * collection with its `totalItems`, an `endpoints` value) instead of linking it,
34
+ * and all of these mean the same node. Anything else, a list included, names none;
35
+ * read a list through {@link apIriList}.
36
+ */
37
+ export declare function apIri(value: unknown): string | undefined;
38
+ /**
39
+ * Every IRI a one-or-many reference property names (`to`, `cc`, `audience`,
40
+ * `alsoKnownAs`, `attributedTo`), in order: {@link apList} read through
41
+ * {@link apIri}, dropping the entries that name none.
42
+ */
43
+ export declare function apIriList(value: unknown): string[];
44
+ /**
45
+ * The first absolute http(s) URL an image-valued property (`icon`, `image`, an
46
+ * `Image` attachment's `url`) names: a URL string, an object's `url` or `href`
47
+ * (an `Image` whose `url` is a string, a `Link` or a list of them), or the
48
+ * first entry of a list that names one.
49
+ */
50
+ export declare function apImageUrl(value: unknown): string | undefined;
51
+ /**
52
+ * The base of a media type, lowercased and without parameters:
53
+ * `application/ld+json; profile="https://www.w3.org/ns/activitystreams"` and
54
+ * `Application/LD+JSON;profile=…` are both `application/ld+json`. Empty for a
55
+ * value that is not a string.
56
+ */
57
+ export declare function apMediaTypeBase(value: unknown): string;
58
+ /**
59
+ * Whether a media type is an ActivityStreams document's (`application/activity+json`
60
+ * or `application/ld+json`, with any parameters): what a WebFinger `self` link or
61
+ * an actor response names.
62
+ */
63
+ export declare function isActivityPubMediaType(value: unknown): boolean;
64
+ /**
65
+ * A date an ActivityStreams document asserts (`published`, `updated`, a field's
66
+ * `verifiedAt`), parsed leniently, or `undefined` when it names no date.
67
+ *
68
+ * ISO 8601 is read in every offset spelling servers send (`Z`, `+00:00`, `+0000`,
69
+ * `+00`), with a space for the `T`, a comma for the decimal point and a missing
70
+ * offset (read as UTC), so the result does not depend on the JavaScript engine's
71
+ * own `Date` parser. Another string is accepted when it names a four-digit year
72
+ * and that parser reads it (an RFC 2822 date). A `Date` passes through when
73
+ * valid. It never clamps: a caller that must bound future dates does so itself.
74
+ */
75
+ export declare function apDate(value: unknown): Date | undefined;
@@ -56,7 +56,16 @@ export { FEDERATION_NETWORKS, BSKY_NETWORK_DOMAIN, blueskyUsernameFromHandle, bl
56
56
  * built from — not a parallel implementation that agrees today.
57
57
  */
58
58
  export { AP_CONTEXT } from './apContext';
59
- export { canonicalFederationHost, isSameFederationHost, extractActorUriFromActivityId, apIri, createDomainPolicy, type DomainPolicy, type DomainPolicyConfig, } from './apUri';
59
+ export { canonicalFederationHost, isSameFederationHost, extractActorUriFromActivityId, createDomainPolicy, type DomainPolicy, type DomainPolicyConfig, } from './apUri';
60
+ /**
61
+ * The one way to read an ActivityStreams value whose JSON-LD shape varies: a
62
+ * one-or-many property ({@link apList}), a reference by IRI, `id` or `href`
63
+ * ({@link apIri} / {@link apIriList}), an image ({@link apImageUrl}), a media
64
+ * type with parameters ({@link apMediaTypeBase} / {@link isActivityPubMediaType})
65
+ * and a date in any ISO 8601 offset spelling ({@link apDate}). A reader that
66
+ * assumes one shape silently loses the others.
67
+ */
68
+ export { apList, apIri, apIriList, apImageUrl, apMediaTypeBase, isActivityPubMediaType, apDate, } from './apValue';
60
69
  /**
61
70
  * The single builder of a LOCAL user's ActivityPub actor document —
62
71
  * byte-identical across apps, with media resolution injected. The actor `type`
@@ -78,9 +87,8 @@ export { GROUP_OUTBOX_SIZE, isGroupActorKind, groupOutboxCollection, groupFollow
78
87
  export type NetworkId = 'activitypub' | 'atproto' | 'instagram-graph';
79
88
  /**
80
89
  * A remote actor normalized into a network-neutral shape. Built by a connector
81
- * from its protocol's profile representation, and consumed by the identity
82
- * bridge ({@link NetworkConnector.mapIdentity}) to resolve/mint the federated
83
- * Oxy user the actor maps to.
90
+ * from its protocol's profile representation; `oxyUserId` carries the Oxy user
91
+ * the identity authority resolved it to.
84
92
  */
85
93
  export interface NormalizedExternalActor {
86
94
  network: NetworkId;
@@ -318,15 +326,12 @@ export type LocalNetworkEvent<TContent = unknown> = {
318
326
  localUsername: string;
319
327
  targetActorUri: string;
320
328
  };
321
- /** Context passed alongside an inbound payload to {@link NetworkConnector.receive}. */
322
- export interface ReceiveContext {
323
- /** The remote actor URI/DID whose signature was already verified by the transport. */
324
- verifiedActorUri: string;
325
- }
326
329
  /**
327
330
  * The common contract every external network speaks behind. A connector owns all
328
331
  * protocol specifics; the registry and the app's content core only ever see this
329
- * surface.
332
+ * surface. Identity is not part of it: the identity authority (Oxy) resolves
333
+ * and verifies every external account, and inbound payloads reach the protocol's
334
+ * own inbox handler, never a connector-generic `receive`.
330
335
  *
331
336
  * Generic over the app's post-content type `TContent`, which flows through
332
337
  * {@link NetworkConnector.deliver} on `post.create` / `post.update` events.
@@ -338,16 +343,10 @@ export interface NetworkConnector<TContent = unknown> {
338
343
  readonly enabled: boolean;
339
344
  /** True when `subject` (a handle / URI / DID) belongs to this network. */
340
345
  matches(subject: string): boolean;
341
- /** Resolve a handle to a normalized actor (webfinger for AP, handle→DID for atproto). */
342
- resolve(handle: string): Promise<NormalizedExternalActor | null>;
343
346
  /** Fetch + normalize an actor profile by its protocol id. */
344
347
  fetchProfile(externalId: string): Promise<NormalizedExternalActor | null>;
345
348
  /** Backfill + normalize an actor's recent posts. */
346
349
  fetchPosts(externalId: string, opts?: FetchPostsOptions): Promise<FetchPostsResult>;
347
350
  /** Deliver a local domain event outbound (federate to followers / write a record). */
348
351
  deliver(event: LocalNetworkEvent<TContent>): Promise<void>;
349
- /** Process an inbound payload (already actor-verified by the transport). */
350
- receive(payload: unknown, ctx: ReceiveContext): Promise<void>;
351
- /** Resolve/mint the Oxy user this external actor maps to; null when unresolvable. */
352
- mapIdentity(actor: NormalizedExternalActor): Promise<string | null>;
353
352
  }
@@ -112,11 +112,15 @@ export interface FederatedActorUpsert {
112
112
  */
113
113
  export type CollectionCount = number | null | undefined;
114
114
  /** Bring-your-own-store: the AP actor cache stays in the app DB behind this adapter. */
115
- export interface FederatedActorStore<TActor extends FederatedActorRecordBase> {
115
+ export interface FederatedActorStore<TActor extends FederatedActorRecordBase, TSource = undefined> {
116
116
  /** Look up a cached actor by its protocol URI. */
117
117
  findActorByUri(uri: string): Promise<TActor | null>;
118
- /** Upsert (create-or-update) the actor cache row keyed by `uri`. */
119
- upsertActor(uri: string, update: FederatedActorUpsert): Promise<TActor | null>;
118
+ /**
119
+ * Upsert (create-or-update) the actor cache row keyed by `uri`. `source` is
120
+ * what {@link ActorResolverConfig.fetchActorDocument} returned beside the
121
+ * document this update was parsed from (absent with the default fetch).
122
+ */
123
+ upsertActor(uri: string, update: FederatedActorUpsert, source?: TSource): Promise<TActor | null>;
120
124
  /** Look up a cached actor by its `publicKey.id` (HTTP-signature key resolution). */
121
125
  findActorByPublicKeyId(keyId: string): Promise<Pick<TActor, 'uri' | 'publicKeyPem'> | null>;
122
126
  /** Stamp the resolved Oxy user id onto an actor row (identified by its `_id`). */
@@ -170,6 +174,29 @@ export interface ActorTextAdapter {
170
174
  */
171
175
  qualifyHandles?(text: string, instanceDomain: string): string;
172
176
  }
177
+ /**
178
+ * One read of a remote actor document, as {@link ActorResolver.fetchRemoteActor}
179
+ * consumes it.
180
+ */
181
+ export interface ActorDocumentFetchResult<TSource = undefined> {
182
+ /** The HTTP status the actor's server answered. Only a 2xx carries `document`. */
183
+ status: number;
184
+ /** The actor document, present when the read succeeded. */
185
+ document?: Record<string, unknown>;
186
+ /** A short description of a failure for the resolver's log line. */
187
+ detail?: string;
188
+ /**
189
+ * What the fetcher learned beside the document (Mention: Oxy's verified
190
+ * identity answer), handed to {@link FederatedActorStore.upsertActor} so the
191
+ * store does not ask for it a second time.
192
+ */
193
+ source?: TSource;
194
+ }
195
+ /**
196
+ * Where actor documents come from: the actor URI, and the canonical acct the
197
+ * caller knows it by (a hint, never an identity claim).
198
+ */
199
+ export type ActorDocumentFetch<TSource = undefined> = (actorUri: string, acctHint?: string) => Promise<ActorDocumentFetchResult<TSource>>;
173
200
  /** A parsed WebFinger JRD (only the `links` we read). */
174
201
  export interface WebFingerJrd {
175
202
  links?: Array<{
@@ -190,11 +217,21 @@ export interface ActorResolverLogger {
190
217
  warn(message: string, detail?: unknown): void;
191
218
  }
192
219
  /** Adapters + config an {@link ActorResolver} is built from. */
193
- export interface ActorResolverConfig<TActor extends FederatedActorRecordBase> {
220
+ export interface ActorResolverConfig<TActor extends FederatedActorRecordBase, TSource = undefined> {
194
221
  /** Whether federation is enabled (gates background refreshes). */
195
222
  federationEnabled: boolean;
196
- /** Signed AP GET (actor + collection-count fetches). */
223
+ /** Signed AP GET (collection-count fetches, and actor documents by default). */
197
224
  signedFetch: SignedFetch;
225
+ /**
226
+ * Where actor documents come from. Default: {@link signedFetch} of the actor
227
+ * URI. An app whose identity authority already fetches and verifies the actor
228
+ * reads the document from that answer instead, so one refresh fetches the
229
+ * actor once: Mention reads it from Oxy's `/federation/identities/resolve`,
230
+ * which returns the document it verified. Every guard below (same origin,
231
+ * self-consistent key, blocked domains, 410 tombstone, WebFinger fallback)
232
+ * applies to the document whichever way it arrived.
233
+ */
234
+ fetchActorDocument?: ActorDocumentFetch<TSource>;
198
235
  /** SSRF-safe bounded WebFinger fetch. */
199
236
  fetchWebFinger: WebFingerFetch;
200
237
  /** Per-instance blocked-domain check (own domains + identity apex + configured blocks). */
@@ -203,15 +240,18 @@ export interface ActorResolverConfig<TActor extends FederatedActorRecordBase> {
203
240
  normalizeFederatedAcct: (acct: string | undefined) => string | undefined;
204
241
  /** Extract the domain from a canonical acct. */
205
242
  domainFromAcct: (acct: string) => string | undefined;
206
- /** Recursively find the first absolute http(s) URL in a value (icon/image). */
207
- firstStringUrl: (value: unknown) => string | undefined;
243
+ /**
244
+ * The first absolute http(s) URL in an `icon` / `image` value. Optional: the
245
+ * default is {@link apImageUrl}, which reads every image shape.
246
+ */
247
+ firstStringUrl?: (value: unknown) => string | undefined;
208
248
  /**
209
249
  * Optional re-labelling of a bridged actor onto its real network. Absent means
210
250
  * every actor keeps the identity of the host it was fetched from.
211
251
  */
212
252
  deriveNetworkIdentity?: DeriveNetworkIdentity;
213
253
  /** The app's actor cache store. */
214
- store: FederatedActorStore<TActor>;
254
+ store: FederatedActorStore<TActor, TSource>;
215
255
  /** The actor↔Oxy-user identity bridge. */
216
256
  identity: ActorResolverIdentity;
217
257
  /** Remote-text normalization. */
@@ -225,13 +265,15 @@ export interface ActorResolverConfig<TActor extends FederatedActorRecordBase> {
225
265
  * through the instance (e.g. `fetchRemoteActor` → `this.tombstoneGoneActor`),
226
266
  * which keeps them spy-able and overridable in tests.
227
267
  */
228
- export declare class ActorResolver<TActor extends FederatedActorRecordBase> {
268
+ export declare class ActorResolver<TActor extends FederatedActorRecordBase, TSource = undefined> {
229
269
  private readonly config;
230
270
  /** Actor URIs with an in-flight background refresh (guards against refresh storms). */
231
271
  private readonly inFlightActorRefreshes;
232
272
  /** Actor key refetches in flight, by actor URI: concurrent failed signatures share one. */
233
273
  private readonly inFlightKeyRefetches;
234
- constructor(config: ActorResolverConfig<TActor>);
274
+ constructor(config: ActorResolverConfig<TActor, TSource>);
275
+ /** One read of an actor document: the app's {@link ActorResolverConfig.fetchActorDocument}, or a signed GET. */
276
+ private readActorDocument;
235
277
  /**
236
278
  * Whether an actor URI's host is refused by the instance domain policy. An
237
279
  * unparseable URI has no host to check, so it is refused too — the policy is a
@@ -339,4 +381,4 @@ export declare class ActorResolver<TActor extends FederatedActorRecordBase> {
339
381
  private refetchActorKey;
340
382
  }
341
383
  /** Build the remote-actor resolver from an app's storage + identity + transports. */
342
- export declare function createActorResolver<TActor extends FederatedActorRecordBase>(config: ActorResolverConfig<TActor>): ActorResolver<TActor>;
384
+ export declare function createActorResolver<TActor extends FederatedActorRecordBase, TSource = undefined>(config: ActorResolverConfig<TActor, TSource>): ActorResolver<TActor, TSource>;
@@ -47,4 +47,23 @@ export declare class ResponseBodyTimeoutError extends Error {
47
47
  * cap, a deadline, a read error, or a truncated preview.
48
48
  */
49
49
  export declare function readBodyChunks(source: BodyChunkSource, limits: BodyReadLimits): Promise<Buffer>;
50
+ /** Limits for {@link readBoundedResponseText} / {@link readBoundedResponseJson}. */
51
+ export interface ResponseBodyLimits {
52
+ /** Largest body accepted, in bytes; a larger declared or actual body throws. */
53
+ maxBytes: number;
54
+ /** Deadline for the whole body, in milliseconds (default 10 s). */
55
+ timeoutMs?: number;
56
+ }
57
+ /**
58
+ * A WHATWG `Response` body as UTF-8 text, within {@link ResponseBodyLimits}.
59
+ * A fetch's own timeout ends at the headers, so without the body deadline a
60
+ * remote that stalls mid-body would hold the reader open. A declared
61
+ * `Content-Length` over the cap is refused before any byte is read.
62
+ */
63
+ export declare function readBoundedResponseText(res: Response, limits: ResponseBodyLimits): Promise<string>;
64
+ /**
65
+ * A WHATWG `Response` body as a JSON object, within {@link ResponseBodyLimits}.
66
+ * Throws when the body is empty, is not JSON, or is JSON but not an object.
67
+ */
68
+ export declare function readBoundedResponseJson(res: Response, limits: ResponseBodyLimits): Promise<Record<string, unknown>>;
50
69
  export {};
@@ -186,5 +186,6 @@ export interface InboundDispatcher {
186
186
  /** Process one already-actor-verified inbound activity. */
187
187
  processInboxActivity(activity: Record<string, unknown>, verifiedActorUri: string): Promise<void>;
188
188
  }
189
+ /** Read the `object`'s referenced actor/target uri (a string, or an embedded `{ id }`). */
189
190
  /** Build the inbound-activity dispatcher from an app's adapters + content handlers. */
190
191
  export declare function createInboundDispatcher(config: InboundDispatcherConfig): InboundDispatcher;
@@ -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, type SignedFetch, type SignedFetchInit, type CreateSignedFetchConfig, type SingleHopFetch, type SingleHopFetchInit, type SignedFetchLogger, } from './signedFetch';
19
+ export { createSignedFetch, createSignedFetcher, type SignedFetch, type SignedFetcher, type SignedFetchResult, type SignedFetchLogDetail, type SignedFetchInit, type CreateSignedFetchConfig, type SingleHopFetch, type SingleHopFetchInit, type SignedFetchLogger, } from './signedFetch';
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, type ResponseBodyLimits, } from './boundedBody';
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.
@@ -33,7 +38,7 @@ export { createIdentityBridge, type IdentityBridge, type IdentityBridgeConfig, t
33
38
  * 410-Gone tombstone) over a bring-your-own-store adapter, the identity bridge,
34
39
  * and injected transports + text normalization.
35
40
  */
36
- export { createActorResolver, ActorResolver, type ActorResolverConfig, type ActorResolverIdentity, type ActorResolverLogger, type ActorTextAdapter, type FederatedActorStore, type CollectionCount, type FederatedActorRecordBase, type FederatedActorUpsert, type FederatedActorField, type WebFingerFetch, type WebFingerJrd, } from './actorResolver';
41
+ export { createActorResolver, ActorResolver, type ActorDocumentFetch, type ActorDocumentFetchResult, type ActorResolverConfig, type ActorResolverIdentity, type ActorResolverLogger, type ActorTextAdapter, type FederatedActorStore, type CollectionCount, type FederatedActorRecordBase, type FederatedActorUpsert, type FederatedActorField, type WebFingerFetch, type WebFingerJrd, } from './actorResolver';
37
42
  /**
38
43
  * Outbound activity delivery + the follow lifecycle (Follow / Undo(Follow) /
39
44
  * Accept(Follow)) + the `Update(Person)` actor rebroadcast, over injected key
@@ -34,10 +34,17 @@ export interface SingleHopFetchInit {
34
34
  * `fetchUpstreamSingleHop` into this shape.
35
35
  */
36
36
  export type SingleHopFetch = (url: string, init: SingleHopFetchInit) => Promise<Response>;
37
+ /** What a {@link SignedFetchLogger} line is about, for a sink that formats its own. */
38
+ export interface SignedFetchLogDetail {
39
+ /** The status that prompted the line. */
40
+ status: number;
41
+ /** The URL the answer came from (after redirects). */
42
+ url: string;
43
+ }
37
44
  /** Non-fatal diagnostics sink for signed fetches. */
38
45
  export interface SignedFetchLogger {
39
- info(message: string): void;
40
- warn(message: string): void;
46
+ info(message: string, detail?: SignedFetchLogDetail): void;
47
+ warn(message: string, detail?: SignedFetchLogDetail): void;
41
48
  }
42
49
  /** Adapters + config a {@link SignedFetch} is built from. */
43
50
  export interface CreateSignedFetchConfig {
@@ -67,6 +74,18 @@ export interface SignedFetchInit extends RequestInit {
67
74
  }
68
75
  /** A signed ActivityPub GET, returning the standard WHATWG {@link Response}. */
69
76
  export type SignedFetch = (url: string, accept: string, init?: SignedFetchInit) => Promise<Response>;
77
+ /** A {@link SignedFetch} answer with the URL it came from, after redirects. */
78
+ export interface SignedFetchResult {
79
+ response: Response;
80
+ /** The URL that answered: the request URL, or the last redirect hop followed. */
81
+ finalUrl: string;
82
+ }
83
+ /**
84
+ * A signed ActivityPub GET that also reports the URL that answered — for a
85
+ * caller that binds a document to where it was served from (an actor whose `id`
86
+ * may name the redirect target rather than the URL asked for).
87
+ */
88
+ export type SignedFetcher = (url: string, accept: string, init?: SignedFetchInit) => Promise<SignedFetchResult>;
70
89
  /**
71
90
  * Build a `signedFetch(url, accept, init?)`:
72
91
  *
@@ -86,3 +105,5 @@ export type SignedFetch = (url: string, accept: string, init?: SignedFetchInit)
86
105
  * (see {@link SignedFetchInit.keyId}); such a request is never retried unsigned.
87
106
  */
88
107
  export declare function createSignedFetch(config: CreateSignedFetchConfig): SignedFetch;
108
+ /** {@link createSignedFetch}, answering with the final URL as well ({@link SignedFetcher}). */
109
+ export declare function createSignedFetcher(config: CreateSignedFetchConfig): SignedFetcher;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxy.so/federation",
3
- "version": "2.16.0",
3
+ "version": "3.0.0",
4
4
  "description": "Oxy Federation — the app-agnostic ActivityPub identity + follow engine substrate: the network-connector contract, normalized cross-network DTOs, HTTP signatures, actor resolution, the outbound delivery transport + follow lifecycle, the inbound dispatcher, and the webfinger/actor/inbox Express routers. Domain-parameterized so every Oxy app backend federates under its own domain.",
5
5
  "main": "dist/cjs/index.js",
6
6
  "module": "dist/esm/index.js",