@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.
@@ -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
  }
@@ -87,9 +87,8 @@ export { GROUP_OUTBOX_SIZE, isGroupActorKind, groupOutboxCollection, groupFollow
87
87
  export type NetworkId = 'activitypub' | 'atproto' | 'instagram-graph';
88
88
  /**
89
89
  * A remote actor normalized into a network-neutral shape. Built by a connector
90
- * from its protocol's profile representation, and consumed by the identity
91
- * bridge ({@link NetworkConnector.mapIdentity}) to resolve/mint the federated
92
- * 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.
93
92
  */
94
93
  export interface NormalizedExternalActor {
95
94
  network: NetworkId;
@@ -327,15 +326,12 @@ export type LocalNetworkEvent<TContent = unknown> = {
327
326
  localUsername: string;
328
327
  targetActorUri: string;
329
328
  };
330
- /** Context passed alongside an inbound payload to {@link NetworkConnector.receive}. */
331
- export interface ReceiveContext {
332
- /** The remote actor URI/DID whose signature was already verified by the transport. */
333
- verifiedActorUri: string;
334
- }
335
329
  /**
336
330
  * The common contract every external network speaks behind. A connector owns all
337
331
  * protocol specifics; the registry and the app's content core only ever see this
338
- * 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`.
339
335
  *
340
336
  * Generic over the app's post-content type `TContent`, which flows through
341
337
  * {@link NetworkConnector.deliver} on `post.create` / `post.update` events.
@@ -347,16 +343,10 @@ export interface NetworkConnector<TContent = unknown> {
347
343
  readonly enabled: boolean;
348
344
  /** True when `subject` (a handle / URI / DID) belongs to this network. */
349
345
  matches(subject: string): boolean;
350
- /** Resolve a handle to a normalized actor (webfinger for AP, handle→DID for atproto). */
351
- resolve(handle: string): Promise<NormalizedExternalActor | null>;
352
346
  /** Fetch + normalize an actor profile by its protocol id. */
353
347
  fetchProfile(externalId: string): Promise<NormalizedExternalActor | null>;
354
348
  /** Backfill + normalize an actor's recent posts. */
355
349
  fetchPosts(externalId: string, opts?: FetchPostsOptions): Promise<FetchPostsResult>;
356
350
  /** Deliver a local domain event outbound (federate to followers / write a record). */
357
351
  deliver(event: LocalNetworkEvent<TContent>): Promise<void>;
358
- /** Process an inbound payload (already actor-verified by the transport). */
359
- receive(payload: unknown, ctx: ReceiveContext): Promise<void>;
360
- /** Resolve/mint the Oxy user this external actor maps to; null when unresolvable. */
361
- mapIdentity(actor: NormalizedExternalActor): Promise<string | null>;
362
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). */
@@ -214,7 +251,7 @@ export interface ActorResolverConfig<TActor extends FederatedActorRecordBase> {
214
251
  */
215
252
  deriveNetworkIdentity?: DeriveNetworkIdentity;
216
253
  /** The app's actor cache store. */
217
- store: FederatedActorStore<TActor>;
254
+ store: FederatedActorStore<TActor, TSource>;
218
255
  /** The actor↔Oxy-user identity bridge. */
219
256
  identity: ActorResolverIdentity;
220
257
  /** Remote-text normalization. */
@@ -228,13 +265,15 @@ export interface ActorResolverConfig<TActor extends FederatedActorRecordBase> {
228
265
  * through the instance (e.g. `fetchRemoteActor` → `this.tombstoneGoneActor`),
229
266
  * which keeps them spy-able and overridable in tests.
230
267
  */
231
- export declare class ActorResolver<TActor extends FederatedActorRecordBase> {
268
+ export declare class ActorResolver<TActor extends FederatedActorRecordBase, TSource = undefined> {
232
269
  private readonly config;
233
270
  /** Actor URIs with an in-flight background refresh (guards against refresh storms). */
234
271
  private readonly inFlightActorRefreshes;
235
272
  /** Actor key refetches in flight, by actor URI: concurrent failed signatures share one. */
236
273
  private readonly inFlightKeyRefetches;
237
- 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;
238
277
  /**
239
278
  * Whether an actor URI's host is refused by the instance domain policy. An
240
279
  * unparseable URI has no host to check, so it is refused too — the policy is a
@@ -342,4 +381,4 @@ export declare class ActorResolver<TActor extends FederatedActorRecordBase> {
342
381
  private refetchActorKey;
343
382
  }
344
383
  /** Build the remote-actor resolver from an app's storage + identity + transports. */
345
- 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 {};
@@ -254,8 +254,16 @@ export interface DeliveryService {
254
254
  deliverToFollowers(activity: Record<string, unknown>, senderOxyUserId: string, senderUsername: string, options?: {
255
255
  extraInboxes?: string[];
256
256
  }): Promise<void>;
257
- /** Send a Follow activity to a remote actor (records the outbound follow, delivers/queues). */
258
- sendFollow(localOxyUserId: string, localUsername: string, remoteActorUri: string): Promise<{
257
+ /**
258
+ * Send a Follow activity to a remote actor (records the outbound follow, delivers/queues).
259
+ * By default the delivery runs in the background, so a request never waits on
260
+ * the remote. `durable` hands it to the delivery queue BEFORE resolving
261
+ * (resolving the actor's inbox first, and throwing when it has none), for a
262
+ * caller that may exit right after — a one-shot script.
263
+ */
264
+ sendFollow(localOxyUserId: string, localUsername: string, remoteActorUri: string, options?: {
265
+ durable?: boolean;
266
+ }): Promise<{
259
267
  success: boolean;
260
268
  pending: boolean;
261
269
  }>;
@@ -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.17.0",
3
+ "version": "3.1.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",
@@ -321,3 +321,55 @@ describe('fetchRemoteActor — bounded remote bodies', () => {
321
321
  expect(oversized.pulls()).toBeLessThan(15);
322
322
  });
323
323
  });
324
+
325
+ describe('fetchRemoteActor — an injected actor document source', () => {
326
+ it('reads the actor once from the source, hands its context to the store, and fetches only collections', async () => {
327
+ const signedFetchCalls: string[] = [];
328
+ const upserts: Array<{ uri: string; source: unknown }> = [];
329
+ const document = {
330
+ id: ALLOWED_ACTOR,
331
+ type: 'Person',
332
+ preferredUsername: 'bob',
333
+ inbox: `${ALLOWED_ACTOR}/inbox`,
334
+ followers: `${ALLOWED_ACTOR}/followers`,
335
+ };
336
+ const resolver = createActorResolver<TestActor, { verifiedBy: string }>({
337
+ federationEnabled: true,
338
+ signedFetch: async (url) => {
339
+ signedFetchCalls.push(url);
340
+ return new Response(JSON.stringify({ totalItems: 3 }), { status: 200 });
341
+ },
342
+ fetchActorDocument: async (uri) =>
343
+ uri === ALLOWED_ACTOR
344
+ ? { status: 200, document, source: { verifiedBy: 'authority' } }
345
+ : { status: 404 },
346
+ fetchWebFinger: async () => null,
347
+ isBlockedDomain: () => false,
348
+ normalizeFederatedAcct: (acct) => acct,
349
+ domainFromAcct: (acct) => acct.split('@')[1],
350
+ store: {
351
+ findActorByUri: async () => null,
352
+ upsertActor: async (uri, update, source) => {
353
+ upserts.push({ uri, source });
354
+ expect(update.followersCount).toBe(3);
355
+ return { uri };
356
+ },
357
+ findActorByPublicKeyId: async () => null,
358
+ setActorOxyUserId: async () => {},
359
+ tombstoneActor: async () => null,
360
+ },
361
+ identity: { resolveExternalUser: async () => null, reportActorGone: async () => 'archived' },
362
+ text: {
363
+ inlineField: (value) => (typeof value === 'string' ? value : ''),
364
+ inlineDisplayName: (raw) => raw,
365
+ sanitizeFieldValue: (html) => html,
366
+ htmlToPlainText: (html) => html,
367
+ },
368
+ logger: { info: () => {}, warn: () => {} },
369
+ });
370
+
371
+ await expect(resolver.fetchRemoteActor(ALLOWED_ACTOR)).resolves.toEqual({ uri: ALLOWED_ACTOR });
372
+ expect(upserts).toEqual([{ uri: ALLOWED_ACTOR, source: { verifiedBy: 'authority' } }]);
373
+ expect(signedFetchCalls).toEqual([`${ALLOWED_ACTOR}/followers`]);
374
+ });
375
+ });
@@ -152,6 +152,7 @@ function makeRig(
152
152
 
153
153
  return {
154
154
  service: createDeliveryService(config),
155
+ config,
155
156
  signatures,
156
157
  deliveredBodies,
157
158
  enqueued,
@@ -213,6 +214,32 @@ describe('sendFollow', () => {
213
214
  );
214
215
  });
215
216
 
217
+ it('durable: queues the Follow before resolving, resolving an uncached inbox first', async () => {
218
+ const remote = 'https://remote.example/users/carol';
219
+ const rig = makeRig();
220
+ const fetched = { _id: 'CAROL', uri: remote, inboxUrl: 'https://remote.example/inbox' };
221
+ const service = createDeliveryService({
222
+ ...rig.config,
223
+ actorRefresh: { ...rig.config.actorRefresh, fetchRemoteActor: async () => fetched },
224
+ });
225
+
226
+ expect(await service.sendFollow('u-alice', 'alice', remote, { durable: true })).toEqual({
227
+ success: true,
228
+ pending: false,
229
+ });
230
+ // Nothing left to the background: the job is queued when the call returns.
231
+ expect(rig.enqueued).toEqual([
232
+ expect.objectContaining({ targetInbox: 'https://remote.example/inbox' }),
233
+ ]);
234
+ expect(rig.upsertedFollows).toHaveLength(1);
235
+ await expect(
236
+ createDeliveryService({
237
+ ...rig.config,
238
+ actorRefresh: { ...rig.config.actorRefresh, fetchRemoteActor: async () => null },
239
+ }).sendFollow('u-alice', 'alice', 'https://remote.example/users/nobody', { durable: true }),
240
+ ).rejects.toThrow();
241
+ });
242
+
216
243
  it('short-circuits when federation is disabled', async () => {
217
244
  const rig = makeRig({ federationEnabled: false });
218
245
  const result = await rig.service.sendFollow(
@@ -1,4 +1,4 @@
1
- import { createSignedFetch, type SingleHopFetchInit } from '../node/signedFetch';
1
+ import { createSignedFetcher, type SingleHopFetchInit } from '../node/signedFetch';
2
2
 
3
3
  const INSTANCE_KEY = 'https://app.example/actor#main-key';
4
4
  const ALICE_KEY = 'https://app.example/ap/users/alice#main-key';
@@ -6,7 +6,7 @@ const ALICE_KEY = 'https://app.example/ap/users/alice#main-key';
6
6
  /** A signed fetch over a scripted transport, recording each hop's URL and signing keyId. */
7
7
  function rig(responses: Response[]) {
8
8
  const hops: Array<{ url: string; keyId: string | null }> = [];
9
- const signedFetch = createSignedFetch({
9
+ const fetcher = createSignedFetcher({
10
10
  sign: async () => 'sig',
11
11
  getInstanceKeyId: async () => INSTANCE_KEY,
12
12
  fetchSingleHop: async (url: string, init: SingleHopFetchInit) => {
@@ -17,7 +17,9 @@ function rig(responses: Response[]) {
17
17
  },
18
18
  userAgent: 'test',
19
19
  });
20
- return { signedFetch, hops };
20
+ const signedFetch = async (...args: Parameters<typeof fetcher>) =>
21
+ (await fetcher(...args)).response;
22
+ return { signedFetch, fetcher, hops };
21
23
  }
22
24
 
23
25
  it('signs as the instance and retries a 5xx unsigned', async () => {
@@ -57,3 +59,24 @@ it('signs every hop as the given actor and never retries an actor-signed request
57
59
  expect(res.status).toBe(503);
58
60
  expect(failing.hops).toHaveLength(1);
59
61
  });
62
+
63
+ it('retries a redirected 5xx unsigned from where the redirect landed, and reports that URL', async () => {
64
+ const { fetcher, hops } = rig([
65
+ new Response(null, { status: 302, headers: { location: '/users/bob' } }),
66
+ new Response(null, { status: 502 }),
67
+ new Response('{}'),
68
+ ]);
69
+
70
+ const { response, finalUrl } = await fetcher(
71
+ 'https://remote.example/@bob',
72
+ 'application/activity+json',
73
+ );
74
+
75
+ expect(response.status).toBe(200);
76
+ expect(finalUrl).toBe('https://remote.example/users/bob');
77
+ expect(hops).toEqual([
78
+ { url: 'https://remote.example/@bob', keyId: INSTANCE_KEY },
79
+ { url: 'https://remote.example/users/bob', keyId: INSTANCE_KEY },
80
+ { url: 'https://remote.example/users/bob', keyId: null },
81
+ ]);
82
+ });
package/src/index.ts CHANGED
@@ -177,9 +177,8 @@ export type NetworkId = 'activitypub' | 'atproto' | 'instagram-graph';
177
177
 
178
178
  /**
179
179
  * A remote actor normalized into a network-neutral shape. Built by a connector
180
- * from its protocol's profile representation, and consumed by the identity
181
- * bridge ({@link NetworkConnector.mapIdentity}) to resolve/mint the federated
182
- * Oxy user the actor maps to.
180
+ * from its protocol's profile representation; `oxyUserId` carries the Oxy user
181
+ * the identity authority resolved it to.
183
182
  */
184
183
  export interface NormalizedExternalActor {
185
184
  network: NetworkId;
@@ -437,16 +436,12 @@ export type LocalNetworkEvent<TContent = unknown> =
437
436
  targetActorUri: string;
438
437
  };
439
438
 
440
- /** Context passed alongside an inbound payload to {@link NetworkConnector.receive}. */
441
- export interface ReceiveContext {
442
- /** The remote actor URI/DID whose signature was already verified by the transport. */
443
- verifiedActorUri: string;
444
- }
445
-
446
439
  /**
447
440
  * The common contract every external network speaks behind. A connector owns all
448
441
  * protocol specifics; the registry and the app's content core only ever see this
449
- * surface.
442
+ * surface. Identity is not part of it: the identity authority (Oxy) resolves
443
+ * and verifies every external account, and inbound payloads reach the protocol's
444
+ * own inbox handler, never a connector-generic `receive`.
450
445
  *
451
446
  * Generic over the app's post-content type `TContent`, which flows through
452
447
  * {@link NetworkConnector.deliver} on `post.create` / `post.update` events.
@@ -458,16 +453,10 @@ export interface NetworkConnector<TContent = unknown> {
458
453
  readonly enabled: boolean;
459
454
  /** True when `subject` (a handle / URI / DID) belongs to this network. */
460
455
  matches(subject: string): boolean;
461
- /** Resolve a handle to a normalized actor (webfinger for AP, handle→DID for atproto). */
462
- resolve(handle: string): Promise<NormalizedExternalActor | null>;
463
456
  /** Fetch + normalize an actor profile by its protocol id. */
464
457
  fetchProfile(externalId: string): Promise<NormalizedExternalActor | null>;
465
458
  /** Backfill + normalize an actor's recent posts. */
466
459
  fetchPosts(externalId: string, opts?: FetchPostsOptions): Promise<FetchPostsResult>;
467
460
  /** Deliver a local domain event outbound (federate to followers / write a record). */
468
461
  deliver(event: LocalNetworkEvent<TContent>): Promise<void>;
469
- /** Process an inbound payload (already actor-verified by the transport). */
470
- receive(payload: unknown, ctx: ReceiveContext): Promise<void>;
471
- /** Resolve/mint the Oxy user this external actor maps to; null when unresolvable. */
472
- mapIdentity(actor: NormalizedExternalActor): Promise<string | null>;
473
462
  }