@oxy.so/federation 1.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 (78) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +16 -0
  3. package/dist/cjs/.tsbuildinfo +1 -0
  4. package/dist/cjs/actorObject.js +216 -0
  5. package/dist/cjs/apContext.js +48 -0
  6. package/dist/cjs/apUri.js +132 -0
  7. package/dist/cjs/httpSignature.js +187 -0
  8. package/dist/cjs/index.js +99 -0
  9. package/dist/cjs/networkIdentity.js +487 -0
  10. package/dist/cjs/node/actorResolver.js +625 -0
  11. package/dist/cjs/node/actorRouter.js +307 -0
  12. package/dist/cjs/node/delivery.js +415 -0
  13. package/dist/cjs/node/identityBridge.js +133 -0
  14. package/dist/cjs/node/inboundDispatch.js +268 -0
  15. package/dist/cjs/node/index.js +63 -0
  16. package/dist/cjs/node/signedFetch.js +122 -0
  17. package/dist/cjs/node/webfingerRouter.js +166 -0
  18. package/dist/cjs/urls.js +55 -0
  19. package/dist/esm/.tsbuildinfo +1 -0
  20. package/dist/esm/actorObject.js +210 -0
  21. package/dist/esm/apContext.js +45 -0
  22. package/dist/esm/apUri.js +126 -0
  23. package/dist/esm/httpSignature.js +179 -0
  24. package/dist/esm/index.js +65 -0
  25. package/dist/esm/networkIdentity.js +472 -0
  26. package/dist/esm/node/actorResolver.js +620 -0
  27. package/dist/esm/node/actorRouter.js +304 -0
  28. package/dist/esm/node/delivery.js +412 -0
  29. package/dist/esm/node/identityBridge.js +130 -0
  30. package/dist/esm/node/inboundDispatch.js +263 -0
  31. package/dist/esm/node/index.js +51 -0
  32. package/dist/esm/node/signedFetch.js +119 -0
  33. package/dist/esm/node/webfingerRouter.js +163 -0
  34. package/dist/esm/urls.js +50 -0
  35. package/dist/types/.tsbuildinfo +1 -0
  36. package/dist/types/actorObject.d.ts +182 -0
  37. package/dist/types/apContext.d.ts +35 -0
  38. package/dist/types/apUri.d.ts +107 -0
  39. package/dist/types/httpSignature.d.ts +113 -0
  40. package/dist/types/index.d.ts +336 -0
  41. package/dist/types/networkIdentity.d.ts +509 -0
  42. package/dist/types/node/actorResolver.d.ts +287 -0
  43. package/dist/types/node/actorRouter.d.ts +108 -0
  44. package/dist/types/node/delivery.d.ts +248 -0
  45. package/dist/types/node/identityBridge.d.ts +84 -0
  46. package/dist/types/node/inboundDispatch.d.ts +156 -0
  47. package/dist/types/node/index.d.ts +51 -0
  48. package/dist/types/node/signedFetch.d.ts +74 -0
  49. package/dist/types/node/webfingerRouter.d.ts +62 -0
  50. package/dist/types/urls.d.ts +55 -0
  51. package/package.json +119 -0
  52. package/src/__tests__/actorObject.test.ts +258 -0
  53. package/src/__tests__/actorResolver.test.ts +252 -0
  54. package/src/__tests__/actorResolverNetworkIdentity.test.ts +297 -0
  55. package/src/__tests__/apUri.test.ts +53 -0
  56. package/src/__tests__/delivery.test.ts +432 -0
  57. package/src/__tests__/federationHost.test.ts +281 -0
  58. package/src/__tests__/httpSignature.test.ts +343 -0
  59. package/src/__tests__/inboundDispatch.test.ts +381 -0
  60. package/src/__tests__/index.test.ts +8 -0
  61. package/src/__tests__/networkIdentity.test.ts +525 -0
  62. package/src/__tests__/routers.test.ts +460 -0
  63. package/src/__tests__/urls.test.ts +26 -0
  64. package/src/actorObject.ts +313 -0
  65. package/src/apContext.ts +45 -0
  66. package/src/apUri.ts +161 -0
  67. package/src/httpSignature.ts +282 -0
  68. package/src/index.ts +419 -0
  69. package/src/networkIdentity.ts +731 -0
  70. package/src/node/actorResolver.ts +839 -0
  71. package/src/node/actorRouter.ts +438 -0
  72. package/src/node/delivery.ts +729 -0
  73. package/src/node/identityBridge.ts +230 -0
  74. package/src/node/inboundDispatch.ts +420 -0
  75. package/src/node/index.ts +136 -0
  76. package/src/node/signedFetch.ts +177 -0
  77. package/src/node/webfingerRouter.ts +226 -0
  78. package/src/urls.ts +71 -0
@@ -0,0 +1,472 @@
1
+ /**
2
+ * WHICH HOSTS REPUBLISH ANOTHER NETWORK'S ACCOUNTS, AND HOW TO READ THE REAL
3
+ * IDENTITY BACK OUT OF THEM.
4
+ *
5
+ * A BRIDGE is a fediverse host that mirrors accounts from somewhere else. The
6
+ * account it publishes as `@WIRED@mastox.eu` is not a person on mastox.eu — it is
7
+ * WIRED, on X, copied. Naming that account after the bridge tells a reader
8
+ * nothing they can act on: the hostname is an implementation detail of how the
9
+ * post reached us, and the thing they actually want to know is which account on
10
+ * which network wrote it. So an actor from a listed bridge is stored and rendered
11
+ * under the NETWORK it came from — `@wired@x.com` — exactly as an atproto actor
12
+ * with a custom-domain handle is stored under `bsky.social` rather than under the
13
+ * domain the handle happens to spell.
14
+ *
15
+ * WHY THE MECHANISM LIVES HERE BUT THE ENTRIES DO NOT
16
+ *
17
+ * Two different questions must stay separate. An app's connector DERIVES the
18
+ * identity at ingest (`createBridgeRelabeller(entries)` with entries the app
19
+ * commits and answers for), and oxy-api's `PUT /users/resolve` DECIDES
20
+ * WHETHER TO BELIEVE IT — that endpoint binds an actor URI's hostname to the
21
+ * domain the caller asserts, precisely so a service cannot claim to vouch for
22
+ * a user on a host it does not own. A bridged identity is the one case where
23
+ * those legitimately differ. The shared package ships the derivation machinery
24
+ * and network vocabulary; each side keeps its own reviewed list and they fail
25
+ * CLOSED in both directions — an app that derives for a bridge the API does
26
+ * not trust simply has its resolve refused, and a host the API trusts that no
27
+ * app derives for does nothing at all.
28
+ *
29
+ * A WRONG ENTRY HERE MISATTRIBUTES SOMEBODY'S WRITING
30
+ *
31
+ * That is a heavier failure than the blocklist's. A wrong block loses content
32
+ * and somebody complains; a wrong bridge entry silently publishes one person's
33
+ * posts under another person's name, on a network they may not even use. So
34
+ * every entry records what was actually VERIFIED against a live actor
35
+ * ({@link FederationBridgeEntry.evidence}) separately from what is merely
36
+ * ASSUMED ({@link FederationBridgeEntry.assumption}), and every entry an app
37
+ * ships should carry a stored fixture and a test that fails if its rule stops
38
+ * round-tripping. Derivation is per-ACTOR and fails closed: an actor that does
39
+ * not satisfy its bridge's rule keeps the bridge hostname, because a bridge's
40
+ * own admin and service accounts are real accounts on that host and relabelling
41
+ * them would invent an upstream person who does not exist.
42
+ *
43
+ * THIS IS NOT THE BLOCKLIST, AND MUST NEVER BE MERGED WITH IT
44
+ *
45
+ * Blocking and bridge-trust are opposite decisions about a host, and the
46
+ * blocklist wins: a blocked host is refused before any actor from it is ever
47
+ * built, so no relabel can resurrect it. Keeping them in separate structures
48
+ * means neither can be edited into the other by accident.
49
+ */
50
+ import { canonicalFederationHost } from './apUri.js';
51
+ /**
52
+ * The networks Oxy re-labels accounts onto.
53
+ *
54
+ * Bluesky is here for a reason beyond bridging: it is the network the atproto
55
+ * connector ingests DIRECTLY, and its domain used to be a constant private to
56
+ * that connector. Both readers now take it from here, so a Bluesky account
57
+ * reaching us over atproto and the same account reaching us over ActivityPub
58
+ * through Bridgy Fed cannot end up under two different domains — which is what
59
+ * would happen if the two paths each named the network themselves.
60
+ */
61
+ export const FEDERATION_NETWORKS = {
62
+ x: {
63
+ id: 'x',
64
+ name: 'X',
65
+ domain: 'x.com',
66
+ profileHosts: ['x.com', 'twitter.com', 'mobile.twitter.com', 'mobile.x.com'],
67
+ profilePathPrefix: [],
68
+ storedUsername: (handle) => handle.trim().toLowerCase(),
69
+ },
70
+ instagram: {
71
+ id: 'instagram',
72
+ name: 'Instagram',
73
+ domain: 'instagram.com',
74
+ profileHosts: ['instagram.com'],
75
+ profilePathPrefix: [],
76
+ storedUsername: (handle) => handle.trim().toLowerCase(),
77
+ },
78
+ bluesky: {
79
+ id: 'bluesky',
80
+ name: 'Bluesky',
81
+ domain: 'bsky.social',
82
+ profileHosts: ['bsky.app'],
83
+ profilePathPrefix: ['profile'],
84
+ storedUsername: (handle) => blueskyUsernameFromHandle(handle.trim()),
85
+ },
86
+ };
87
+ /**
88
+ * The upstream profile URL for a handle on a network.
89
+ *
90
+ * Deliberately the SAME declaration {@link parseUpstreamProfileUrl} reads
91
+ * backwards. Rendering a link and recognising a pasted one are the same fact
92
+ * stated in two directions, and holding them as two independent tables is how
93
+ * they drift — with the failure landing on the parsing side, where a search that
94
+ * silently finds nothing is indistinguishable from "we do not have that account"
95
+ * and so nobody ever reports it.
96
+ */
97
+ export function upstreamProfileUrl(network, handle) {
98
+ const path = [...network.profilePathPrefix, encodeURIComponent(handle)].join('/');
99
+ return `https://${network.profileHosts[0]}/${path}`;
100
+ }
101
+ /**
102
+ * The network and handle a pasted upstream profile URL names, or `undefined` when
103
+ * it is not one.
104
+ *
105
+ * Query strings and fragments are dropped (a pasted URL usually carries tracking
106
+ * parameters) and a trailing slash is tolerated. Purely syntactic: it never
107
+ * fetches the URL — resolving a user-supplied URL by fetching it would be an SSRF
108
+ * surface, and there is nothing here that needs the network.
109
+ */
110
+ export function parseUpstreamProfileUrl(candidateUrl, networks = Object.values(FEDERATION_NETWORKS)) {
111
+ let url;
112
+ try {
113
+ url = new URL(candidateUrl.trim());
114
+ }
115
+ catch {
116
+ return undefined;
117
+ }
118
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
119
+ return undefined;
120
+ const host = canonicalFederationHost(url.hostname);
121
+ for (const network of networks) {
122
+ if (!network.profileHosts.some((allowed) => canonicalFederationHost(allowed) === host))
123
+ continue;
124
+ const handle = profileUrlHandle(url.href, network.profileHosts, network.profilePathPrefix);
125
+ if (handle !== undefined && handle.length > 0)
126
+ return { network, handle };
127
+ }
128
+ return undefined;
129
+ }
130
+ /** The Bluesky network's canonical identity domain — see {@link FEDERATION_NETWORKS}. */
131
+ export const BSKY_NETWORK_DOMAIN = FEDERATION_NETWORKS.bluesky.domain;
132
+ /**
133
+ * Parse an actor's `proxyOf` into well-formed declarations, dropping anything
134
+ * malformed. Pure; accepts `unknown` because it reads an untrusted document.
135
+ *
136
+ * `authoritative` DEFAULTS TO FALSE when absent. FEP-fffd leaves it optional, and
137
+ * the conservative reading is the only safe one here: the flag is what
138
+ * distinguishes "this actor IS that upstream account" from "this actor is one
139
+ * copy of it", and only the former could ever justify moving an identity.
140
+ */
141
+ export function readProxyDeclarations(value) {
142
+ if (!Array.isArray(value))
143
+ return [];
144
+ const declarations = [];
145
+ for (const raw of value) {
146
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
147
+ continue;
148
+ const entry = raw;
149
+ const protocol = typeof entry.protocol === 'string' ? entry.protocol.trim() : '';
150
+ const proxied = typeof entry.proxied === 'string' ? entry.proxied.trim() : '';
151
+ if (protocol.length === 0 || proxied.length === 0)
152
+ continue;
153
+ declarations.push({ protocol, proxied, authoritative: entry.authoritative === true });
154
+ }
155
+ return declarations;
156
+ }
157
+ /**
158
+ * The handle a profile URL addresses: the single path segment that follows the
159
+ * network's fixed profile prefix (`x.com/<handle>` has none, `bsky.app` uses
160
+ * `profile/`), on one of the network's own hosts.
161
+ *
162
+ * Exact — one segment after the prefix and nothing more — so a link to some other
163
+ * page on the same host (`x.com/i/status/123`) yields nothing rather than a
164
+ * plausible-looking wrong handle.
165
+ */
166
+ function profileUrlHandle(href, allowedHosts, pathPrefix) {
167
+ let url;
168
+ try {
169
+ url = new URL(href);
170
+ }
171
+ catch {
172
+ return undefined;
173
+ }
174
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
175
+ return undefined;
176
+ const host = canonicalFederationHost(url.hostname);
177
+ if (!allowedHosts.some((allowed) => canonicalFederationHost(allowed) === host))
178
+ return undefined;
179
+ const segments = url.pathname.split('/').filter((s) => s.length > 0);
180
+ if (segments.length !== pathPrefix.length + 1)
181
+ return undefined;
182
+ for (let i = 0; i < pathPrefix.length; i += 1) {
183
+ if (segments[i].toLowerCase() !== pathPrefix[i])
184
+ return undefined;
185
+ }
186
+ return decodeURIComponent(segments[pathPrefix.length]);
187
+ }
188
+ /** Every `href="…"` in a sanitized field value, in document order. */
189
+ function fieldHrefs(value) {
190
+ const hrefs = [];
191
+ const pattern = /href="([^"]*)"/gi;
192
+ let match = pattern.exec(value);
193
+ while (match !== null) {
194
+ hrefs.push(match[1]);
195
+ match = pattern.exec(value);
196
+ }
197
+ return hrefs;
198
+ }
199
+ /**
200
+ * Read the upstream handle out of a named profile field that links to the
201
+ * upstream profile — the STRONGEST rule available, because the bridge is
202
+ * publishing a machine-readable assertion of which account this mirrors rather
203
+ * than leaving us to infer it from the username.
204
+ */
205
+ export function upstreamHandleFromProfileField(options) {
206
+ const wanted = options.fieldName.toLowerCase();
207
+ const prefix = options.pathPrefix ?? [];
208
+ return (candidate) => {
209
+ for (const field of candidate.fields) {
210
+ if (field.name.trim().toLowerCase() !== wanted)
211
+ continue;
212
+ for (const href of fieldHrefs(field.value)) {
213
+ const handle = profileUrlHandle(href, options.hosts, prefix);
214
+ if (handle !== undefined && handle.length > 0)
215
+ return handle;
216
+ }
217
+ }
218
+ return undefined;
219
+ };
220
+ }
221
+ /**
222
+ * Read the upstream handle out of `alsoKnownAs` profile URLs — the shape where an
223
+ * actor publishes a profile link there rather than in a named profile field.
224
+ *
225
+ * ⚠ UNMATCHED BY ANY ACTOR WE ACTUALLY HOLD. On all three Bridgy Fed actors
226
+ * captured from production, `alsoKnownAs` contains ONLY the atproto DID
227
+ * (`["did:plc:…"]`) and no `bsky.app` URL, so this returns `undefined` for the
228
+ * entire real corpus; the shipped Bridgy entry reads the `Web site` profile
229
+ * field, which every one of them does carry. Written against the documented
230
+ * shape rather than an observed one — so verify against a live actor before
231
+ * building on it, and do not read a green test suite as evidence that it fires.
232
+ *
233
+ * `alsoKnownAs` is also NOT a generic upstream backlink. It is one on Bridgy,
234
+ * but on the stock-Mastodon mirror farms it is a Mastodon MIGRATION pointer at a
235
+ * sibling farm domain — following it there would attribute an account to
236
+ * whatever that pointer happens to name. Only use this where a reviewed entry
237
+ * states that the bridge publishes an upstream link in that field.
238
+ */
239
+ export function upstreamHandleFromAlsoKnownAs(options) {
240
+ const prefix = options.pathPrefix ?? [];
241
+ return (candidate) => {
242
+ for (const href of candidate.alsoKnownAs) {
243
+ const handle = profileUrlHandle(href, options.hosts, prefix);
244
+ if (handle !== undefined && handle.length > 0)
245
+ return handle;
246
+ }
247
+ return undefined;
248
+ };
249
+ }
250
+ /**
251
+ * Read the upstream identifier out of an actor's FEP-fffd `proxyOf` declaration.
252
+ *
253
+ * THIS IS A STRATEGY A REVIEWED ENTRY OPTS INTO — NOT A REGISTRY-FREE LANE, AND
254
+ * THE DIFFERENCE IS THE WHOLE SECURITY ARGUMENT.
255
+ *
256
+ * `proxyOf` is attractive precisely because it is self-describing: the actor
257
+ * states what it proxies, in a ratified format, with no list to maintain. That
258
+ * is exactly why it cannot be believed on its own. It is a claim made by an
259
+ * UNTRUSTED REMOTE ACTOR about its own identity, and every field in it is
260
+ * attacker-controlled. Honouring it wherever it appears would mean any actor on
261
+ * any instance could publish
262
+ *
263
+ * "proxyOf": [{ "protocol": "…", "proxied": "elonmusk", "authoritative": true }]
264
+ *
265
+ * and be stored, rendered and searchable as that person on that network. The
266
+ * reviewed bridge list is not bureaucracy around this; it IS the thing that
267
+ * makes a re-attribution believable, because we checked who runs the host.
268
+ *
269
+ * Inside an entry the claim is safe for the same reason the entry's other rules
270
+ * are: we already decided we believe this operator about who it mirrors. So the
271
+ * strategy exists, it is tested, and it is reachable only from a host somebody
272
+ * reviewed.
273
+ *
274
+ * `authoritative` must be true — a non-authoritative proxy says the actor is one
275
+ * copy of the upstream object, not that it stands in for it.
276
+ *
277
+ * NOTHING WE INGEST USES THIS YET. The only actors in our corpus that publish
278
+ * `proxyOf` are the two Nostr bridges, and Nostr identities are npubs with no
279
+ * `@handle@domain` form to re-label onto, so no shipped entry names it. It is
280
+ * here so a bridge that adopts FEP-fffd needs an entry rather than new code —
281
+ * do not read its passing tests as evidence that it fires in production.
282
+ */
283
+ export function upstreamHandleFromProxyOf(options) {
284
+ const accepted = new Set(options.protocols.map((protocol) => protocol.trim().toLowerCase()));
285
+ const toHandle = options.handleFromProxied ?? ((proxied) => proxied);
286
+ return (candidate) => {
287
+ for (const declaration of candidate.proxyOf) {
288
+ if (!declaration.authoritative)
289
+ continue;
290
+ if (!accepted.has(declaration.protocol.trim().toLowerCase()))
291
+ continue;
292
+ const handle = toHandle(declaration.proxied);
293
+ if (handle !== undefined && handle.length > 0)
294
+ return handle;
295
+ }
296
+ return undefined;
297
+ };
298
+ }
299
+ /**
300
+ * Use the actor's own `preferredUsername` as the upstream handle, but ONLY for an
301
+ * actor that carries one of the bridge's mirror notices.
302
+ *
303
+ * The notice is what distinguishes a mirrored account from a real account on the
304
+ * bridge host: the operator's own admin account lives there too and is not a
305
+ * mirror of anything. Without the marker requirement this rule would relabel that
306
+ * person onto a network they may not even be on.
307
+ */
308
+ /**
309
+ * A mirror identified by the actor DECLARING ITSELF AUTOMATED, with the handle
310
+ * read from `preferredUsername`.
311
+ *
312
+ * For a bridge that runs stock server software there is nothing to fingerprint:
313
+ * somebody points a mirror bot at an ordinary instance and the result is
314
+ * indistinguishable from any other server. The tempting fallback is to match the
315
+ * per-account notice such a bridge writes into each bio — and that fails, because
316
+ * a notice is free text with LANGUAGES. One deployment served the same sentence
317
+ * in English, French and Spanish; an entry listing two of them silently left
318
+ * every account of the third under the bridge's own hostname, with the notice
319
+ * still in its bio, looking exactly like an ordinary account.
320
+ *
321
+ * `type` is the same claim without the prose. ActivityPub already distinguishes
322
+ * an automated actor (`Service`/`Application`) from a `Person`, every mirror is
323
+ * published as one, and the operator's own account is not — so the bridge's
324
+ * machine-readable declaration replaces a guess about wording. It is still a
325
+ * per-ACTOR proof, which is what keeps a human on that host from being
326
+ * re-attributed to another network.
327
+ *
328
+ * NOT a general "this actor is a bot" rule: it is only ever consulted for a host
329
+ * already reviewed into a bridge policy. Plenty of ordinary fediverse accounts
330
+ * are `Service`, and none of them are on a listed bridge.
331
+ */
332
+ export function upstreamHandleFromAutomatedActor() {
333
+ return (candidate) => {
334
+ // `Service` ONLY. `Application` is by convention the SERVER'S OWN actor —
335
+ // Mastodon publishes `https://<host>/actor` as an `Application` named
336
+ // `mastodon.internal` — so accepting it would re-label the instance actor
337
+ // itself onto the upstream network. Caught by an existing guard rather than
338
+ // by review, which is the whole reason that guard is there.
339
+ if (candidate.actorType.trim().toLowerCase() !== 'service')
340
+ return undefined;
341
+ const handle = candidate.preferredUsername.trim();
342
+ return handle.length > 0 ? handle : undefined;
343
+ };
344
+ }
345
+ export function upstreamHandleFromPreferredUsername(markers) {
346
+ return (candidate) => {
347
+ if (!markers.some((marker) => marker.test(candidate.bio)))
348
+ return undefined;
349
+ const handle = candidate.preferredUsername.trim();
350
+ return handle.length > 0 ? handle : undefined;
351
+ };
352
+ }
353
+ /**
354
+ * The username a Bluesky handle is stored under, given that the instance domain
355
+ * is ALWAYS `bsky.social`.
356
+ *
357
+ * A Bluesky handle is a whole DNS name identifying the account, not a `local@host`
358
+ * address, so the account is on the Bluesky network however many labels the handle
359
+ * has. Once the instance domain is already `bsky.social`, the `.bsky.social`
360
+ * suffix on a DEFAULT handle is redundant and is dropped — otherwise the handle
361
+ * renders as the doubled `@skylee1.bsky.social@bsky.social`. A CUSTOM domain
362
+ * handle is not a `.bsky.social` handle, so it is kept whole:
363
+ *
364
+ * - `skylee1.bsky.social` → `skylee1`
365
+ * - `gothamist.com` → `gothamist.com`
366
+ * - `mayor.nyc.gov` → `mayor.nyc.gov` (never the bogus `nyc.gov` instance)
367
+ * - `jay.bsky.team` → `jay.bsky.team` (`.bsky.team` is not `.bsky.social`)
368
+ *
369
+ * Exported, and used by BOTH paths a Bluesky account can reach us by — the atproto
370
+ * connector reading it directly, and the Bridgy Fed entry below reading it over
371
+ * ActivityPub. That is the point: the same account arriving by two protocols has
372
+ * to produce the same username or the two rows are two people.
373
+ *
374
+ * `bsky.social` itself is guarded: stripping would leave an empty username, so the
375
+ * whole handle is kept.
376
+ */
377
+ export function blueskyUsernameFromHandle(handle) {
378
+ const suffix = `.${FEDERATION_NETWORKS.bluesky.domain}`;
379
+ return handle !== FEDERATION_NETWORKS.bluesky.domain && handle.endsWith(suffix)
380
+ ? handle.slice(0, -suffix.length)
381
+ : handle;
382
+ }
383
+ /**
384
+ * Build the readers for a set of reviewed bridge entries.
385
+ *
386
+ * The entries are a PARAMETER and this package ships none. Deciding that a given
387
+ * operator may be trusted to re-attribute somebody's account is a moderation
388
+ * judgement, not a platform fact — bake one app's list in here and every Oxy app
389
+ * silently inherits it, including consent calls their owners never made. Oxy holds
390
+ * the capability; the app holds the policy, commits it, and answers for it.
391
+ *
392
+ * A blocked host must be refused by the caller's domain policy BEFORE this is
393
+ * consulted: blocking and bridge-trust are opposite decisions about a host and the
394
+ * block wins. No blocklist is accepted here, so this can never be mistaken for the
395
+ * place that decision is made.
396
+ */
397
+ export function createBridgeRelabeller(entries) {
398
+ const byHost = new Map(entries.map((entry) => [canonicalFederationHost(entry.host), entry]));
399
+ const findBridge = (host) => byHost.get(canonicalFederationHost(host));
400
+ return {
401
+ findBridge,
402
+ vouchesForNetwork: (actorHost, networkDomain) => {
403
+ const bridge = findBridge(actorHost);
404
+ if (!bridge)
405
+ return false;
406
+ return canonicalFederationHost(bridge.network.domain) === canonicalFederationHost(networkDomain);
407
+ },
408
+ deriveNetworkIdentity: (candidate) => {
409
+ const entry = findBridge(candidate.host);
410
+ if (!entry)
411
+ return undefined;
412
+ // A `pending_dedup` entry is committed, reviewed and deliberately inert:
413
+ // re-labelling it would manufacture visible twins of accounts we already
414
+ // hold under the same derived handle.
415
+ if (entry.relabel !== 'enabled')
416
+ return undefined;
417
+ const derived = entry.derive(candidate);
418
+ if (derived === undefined)
419
+ return undefined;
420
+ const handle = entry.caseRule === 'lowercase' ? derived.trim().toLowerCase() : derived.trim();
421
+ // An empty handle is the signature of a BROKEN derivation, not of an
422
+ // unusual account — and it is the most destructive possible outcome, since
423
+ // every actor on the domain would collapse onto one identity. We hold
424
+ // federated actors with no `preferredUsername` at all, so this is reachable
425
+ // rather than theoretical. An `@` or `/` would likewise produce an identity
426
+ // that reads as a different account than it addresses.
427
+ if (handle.length === 0 || handle.includes('@') || handle.includes('/'))
428
+ return undefined;
429
+ const instanceDomain = canonicalFederationHost(entry.network.domain);
430
+ if (instanceDomain.length === 0)
431
+ return undefined;
432
+ return {
433
+ federatedUsername: `${handle}@${instanceDomain}`,
434
+ instanceDomain,
435
+ bio: stripBridgeBoilerplate(candidate.bio, entry),
436
+ };
437
+ },
438
+ };
439
+ }
440
+ /** Strip a bridge's own boilerplate, leaving anything it does not match untouched. */
441
+ export function stripBridgeBoilerplate(bio, entry) {
442
+ let result = bio;
443
+ for (const pattern of entry.boilerplate) {
444
+ result = result.replace(pattern, '');
445
+ }
446
+ return result.trim();
447
+ }
448
+ /**
449
+ * The exact federated username Oxy stores for a pasted upstream profile URL —
450
+ * `https://x.com/NASA` → `nasa@x.com`, `https://bsky.app/profile/alice.bsky.social`
451
+ * → `alice@bsky.social` — or `undefined` when the URL names no known network.
452
+ *
453
+ * This is the SEARCH direction of the same declaration the ingest path reads
454
+ * forwards, and it deliberately routes through `network.storedUsername` rather
455
+ * than reimplementing the normalisation. A search built on a second, parallel
456
+ * rule would work for X (where the rule is just lowercasing) and fail silently
457
+ * for Bluesky (where a default handle's `.bsky.social` suffix is dropped),
458
+ * returning nothing for an account we hold — a result indistinguishable from
459
+ * "we do not have that account", which is why nobody would ever report it.
460
+ *
461
+ * Purely syntactic: it never fetches the URL. Resolving a user-supplied URL by
462
+ * fetching it would be an SSRF surface, and nothing here needs the network.
463
+ */
464
+ export function federatedUsernameFromUpstreamUrl(candidateUrl, networks = Object.values(FEDERATION_NETWORKS)) {
465
+ const parsed = parseUpstreamProfileUrl(candidateUrl, networks);
466
+ if (!parsed)
467
+ return undefined;
468
+ const local = parsed.network.storedUsername(parsed.handle);
469
+ if (local.length === 0 || local.includes('@') || local.includes('/'))
470
+ return undefined;
471
+ return `${local}@${canonicalFederationHost(parsed.network.domain)}`;
472
+ }