@oxy.so/federation 2.15.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/apValue.ts ADDED
@@ -0,0 +1,153 @@
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
+ /**
25
+ * A one-or-many ActivityStreams property as a list. A single value becomes a
26
+ * one-element list, an absent (`undefined` / `null`) value an empty one, and the
27
+ * `null` / `undefined` entries of a list are dropped.
28
+ */
29
+ export function apList(value: unknown): unknown[] {
30
+ if (value === undefined || value === null) return [];
31
+ if (!Array.isArray(value)) return [value];
32
+ return value.filter((entry) => entry !== undefined && entry !== null);
33
+ }
34
+
35
+ /**
36
+ * The IRI a JSON-LD node reference names: the string itself, the `id` of an
37
+ * embedded object, or the `href` of a `Link` (a `Mention` tag, a `Link` `url`).
38
+ * ActivityStreams lets a server embed a referenced node (an actor's `followers`
39
+ * collection with its `totalItems`, an `endpoints` value) instead of linking it,
40
+ * and all of these mean the same node. Anything else, a list included, names none;
41
+ * read a list through {@link apIriList}.
42
+ */
43
+ export function apIri(value: unknown): string | undefined {
44
+ if (typeof value === 'string') return value || undefined;
45
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
46
+ const { id, href } = value as { id?: unknown; href?: unknown };
47
+ if (typeof id === 'string' && id) return id;
48
+ if (typeof href === 'string' && href) return href;
49
+ }
50
+ return undefined;
51
+ }
52
+
53
+ /**
54
+ * Every IRI a one-or-many reference property names (`to`, `cc`, `audience`,
55
+ * `alsoKnownAs`, `attributedTo`), in order: {@link apList} read through
56
+ * {@link apIri}, dropping the entries that name none.
57
+ */
58
+ export function apIriList(value: unknown): string[] {
59
+ const iris: string[] = [];
60
+ for (const entry of apList(value)) {
61
+ const iri = apIri(entry);
62
+ if (iri) iris.push(iri);
63
+ }
64
+ return iris;
65
+ }
66
+
67
+ function isAbsoluteHttpUrl(value: string): boolean {
68
+ return /^https?:\/\/[^\s/]/i.test(value);
69
+ }
70
+
71
+ /** Nesting a real image value needs: icon list → Image → url list → Link. */
72
+ const AP_IMAGE_MAX_DEPTH = 4;
73
+
74
+ /**
75
+ * The first absolute http(s) URL an image-valued property (`icon`, `image`, an
76
+ * `Image` attachment's `url`) names: a URL string, an object's `url` or `href`
77
+ * (an `Image` whose `url` is a string, a `Link` or a list of them), or the
78
+ * first entry of a list that names one.
79
+ */
80
+ export function apImageUrl(value: unknown): string | undefined {
81
+ return imageUrlAt(value, 0);
82
+ }
83
+
84
+ function imageUrlAt(value: unknown, depth: number): string | undefined {
85
+ if (typeof value === 'string') return isAbsoluteHttpUrl(value) ? value : undefined;
86
+ if (depth >= AP_IMAGE_MAX_DEPTH || !value || typeof value !== 'object') return undefined;
87
+ if (Array.isArray(value)) {
88
+ for (const entry of value) {
89
+ const url = imageUrlAt(entry, depth + 1);
90
+ if (url) return url;
91
+ }
92
+ return undefined;
93
+ }
94
+ const record = value as { url?: unknown; href?: unknown };
95
+ return imageUrlAt(record.url, depth + 1) ?? imageUrlAt(record.href, depth + 1);
96
+ }
97
+
98
+ /**
99
+ * The base of a media type, lowercased and without parameters:
100
+ * `application/ld+json; profile="https://www.w3.org/ns/activitystreams"` and
101
+ * `Application/LD+JSON;profile=…` are both `application/ld+json`. Empty for a
102
+ * value that is not a string.
103
+ */
104
+ export function apMediaTypeBase(value: unknown): string {
105
+ if (typeof value !== 'string') return '';
106
+ return (value.split(';')[0] ?? '').trim().toLowerCase();
107
+ }
108
+
109
+ /**
110
+ * Whether a media type is an ActivityStreams document's (`application/activity+json`
111
+ * or `application/ld+json`, with any parameters): what a WebFinger `self` link or
112
+ * an actor response names.
113
+ */
114
+ export function isActivityPubMediaType(value: unknown): boolean {
115
+ const base = apMediaTypeBase(value);
116
+ return base === 'application/activity+json' || base === 'application/ld+json';
117
+ }
118
+
119
+ const ISO_DATE_TIME =
120
+ /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2}(?::\d{2}(?:[.,]\d+)?)?)\s*(Z|z|[+-]\d{2}(?::?\d{2})?)?)?$/;
121
+
122
+ /**
123
+ * A date an ActivityStreams document asserts (`published`, `updated`, a field's
124
+ * `verifiedAt`), parsed leniently, or `undefined` when it names no date.
125
+ *
126
+ * ISO 8601 is read in every offset spelling servers send (`Z`, `+00:00`, `+0000`,
127
+ * `+00`), with a space for the `T`, a comma for the decimal point and a missing
128
+ * offset (read as UTC), so the result does not depend on the JavaScript engine's
129
+ * own `Date` parser. Another string is accepted when it names a four-digit year
130
+ * and that parser reads it (an RFC 2822 date). A `Date` passes through when
131
+ * valid. It never clamps: a caller that must bound future dates does so itself.
132
+ */
133
+ export function apDate(value: unknown): Date | undefined {
134
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? undefined : value;
135
+ if (typeof value !== 'string') return undefined;
136
+ const text = value.trim();
137
+ if (!text) return undefined;
138
+ const iso = ISO_DATE_TIME.exec(text);
139
+ if (iso) {
140
+ const [, day, time = '00:00:00', offset = 'Z'] = iso;
141
+ const parsed = new Date(`${day}T${time.replace(',', '.')}${isoOffset(offset)}`);
142
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed;
143
+ }
144
+ if (!/\b\d{4}\b/.test(text)) return undefined;
145
+ const parsed = new Date(text);
146
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed;
147
+ }
148
+
149
+ function isoOffset(offset: string): string {
150
+ if (offset === 'Z' || offset === 'z') return 'Z';
151
+ const digits = offset.slice(1).replace(':', '');
152
+ return `${offset[0]}${digits.slice(0, 2)}:${digits.slice(2, 4) || '00'}`;
153
+ }
package/src/index.ts CHANGED
@@ -115,6 +115,24 @@ export {
115
115
  type DomainPolicyConfig,
116
116
  } from './apUri';
117
117
 
118
+ /**
119
+ * The one way to read an ActivityStreams value whose JSON-LD shape varies: a
120
+ * one-or-many property ({@link apList}), a reference by IRI, `id` or `href`
121
+ * ({@link apIri} / {@link apIriList}), an image ({@link apImageUrl}), a media
122
+ * type with parameters ({@link apMediaTypeBase} / {@link isActivityPubMediaType})
123
+ * and a date in any ISO 8601 offset spelling ({@link apDate}). A reader that
124
+ * assumes one shape silently loses the others.
125
+ */
126
+ export {
127
+ apList,
128
+ apIri,
129
+ apIriList,
130
+ apImageUrl,
131
+ apMediaTypeBase,
132
+ isActivityPubMediaType,
133
+ apDate,
134
+ } from './apValue';
135
+
118
136
  /**
119
137
  * The single builder of a LOCAL user's ActivityPub actor document —
120
138
  * byte-identical across apps, with media resolution injected. The actor `type`
@@ -48,6 +48,7 @@
48
48
  * means neither can be edited into the other by accident.
49
49
  */
50
50
 
51
+ import { apList } from './apValue';
51
52
  import { canonicalFederationHost } from './apUri';
52
53
 
53
54
  /**
@@ -217,9 +218,8 @@ export interface ProxyDeclaration {
217
218
  * copy of it", and only the former could ever justify moving an identity.
218
219
  */
219
220
  export function readProxyDeclarations(value: unknown): ProxyDeclaration[] {
220
- if (!Array.isArray(value)) return [];
221
221
  const declarations: ProxyDeclaration[] = [];
222
- for (const raw of value) {
222
+ for (const raw of apList(value)) {
223
223
  if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) continue;
224
224
  const entry = raw as Record<string, unknown>;
225
225
  const protocol = typeof entry.protocol === 'string' ? entry.protocol.trim() : '';
@@ -20,6 +20,7 @@
20
20
  */
21
21
 
22
22
  import { canonicalFederationHost, isSameFederationHost } from '../apUri';
23
+ import { apDate, apImageUrl, apIri, apIriList, apList, isActivityPubMediaType } from '../apValue';
23
24
  import {
24
25
  readProxyDeclarations,
25
26
  type DeriveNetworkIdentity,
@@ -103,12 +104,6 @@ async function readBoundedJson(res: Response, maxBytes: number): Promise<Record<
103
104
  return record;
104
105
  }
105
106
 
106
- function isApActorContentType(type: string | undefined): boolean {
107
- if (!type) return false;
108
- const base = type.split(';')[0]?.trim().toLowerCase();
109
- return base === 'application/activity+json' || base === 'application/ld+json';
110
- }
111
-
112
107
  /** The minimal fields the resolver reads off / writes to a stored actor record. */
113
108
  export interface FederatedActorRecordBase {
114
109
  _id?: unknown;
@@ -294,8 +289,11 @@ export interface ActorResolverConfig<TActor extends FederatedActorRecordBase> {
294
289
  normalizeFederatedAcct: (acct: string | undefined) => string | undefined;
295
290
  /** Extract the domain from a canonical acct. */
296
291
  domainFromAcct: (acct: string) => string | undefined;
297
- /** Recursively find the first absolute http(s) URL in a value (icon/image). */
298
- firstStringUrl: (value: unknown) => string | undefined;
292
+ /**
293
+ * The first absolute http(s) URL in an `icon` / `image` value. Optional: the
294
+ * default is {@link apImageUrl}, which reads every image shape.
295
+ */
296
+ firstStringUrl?: (value: unknown) => string | undefined;
299
297
  /**
300
298
  * Optional re-labelling of a bridged actor onto its real network. Absent means
301
299
  * every actor keeps the identity of the host it was fetched from.
@@ -403,7 +401,7 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
403
401
  try {
404
402
  const data = await this.config.fetchWebFinger(url);
405
403
  if (!data) return null;
406
- const link = data.links?.find((l) => l.rel === 'self' && isApActorContentType(l.type));
404
+ const link = data.links?.find((l) => l.rel === 'self' && isActivityPubMediaType(l.type));
407
405
  return link?.href || null;
408
406
  } catch (err) {
409
407
  this.config.logger.warn(`WebFinger resolution failed for ${acct}:`, err);
@@ -507,7 +505,7 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
507
505
 
508
506
  const actor = await readBoundedJson(res, ACTOR_BODY_MAX_BYTES);
509
507
  const actorId = asString(actor.id);
510
- const actorInbox = asString(actor.inbox);
508
+ const actorInbox = apIri(actor.inbox);
511
509
  if (!actorId || !actorInbox) {
512
510
  this.config.logger.info(
513
511
  `[FedSync] fetchRemoteActor missing fields for ${currentUri}: id=${!!actor.id} inbox=${!!actor.inbox} type=${String(actor.type)} keys=${Object.keys(actor).join(',')}`,
@@ -564,35 +562,34 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
564
562
 
565
563
  // Fetch collection counts (followers, following, posts) in parallel
566
564
  const [followersCount, followingCount, postsCount] = await Promise.all([
567
- this.fetchCollectionCount(asString(actor.followers)),
568
- this.fetchCollectionCount(asString(actor.following)),
569
- this.fetchCollectionCount(asString(actor.outbox)),
565
+ this.fetchCollectionCount(apIri(actor.followers)),
566
+ this.fetchCollectionCount(apIri(actor.following)),
567
+ this.fetchCollectionCount(apIri(actor.outbox)),
570
568
  ]);
571
569
 
572
570
  // Extract profile fields (PropertyValue attachments). Sanitize BEFORE
573
571
  // normalizing: the canonical normalizer collapses whitespace, it never
574
572
  // strips markup — so the sanitizer must run first, on the raw value.
575
573
  const fields: FederatedActorField[] = [];
576
- if (Array.isArray(actor.attachment)) {
577
- for (const att of actor.attachment) {
578
- const attRecord = asRecord(att);
579
- if (!attRecord || attRecord.type !== 'PropertyValue') continue;
580
- const fieldName = this.config.text.inlineField(attRecord.name);
581
- const fieldValue =
582
- typeof attRecord.value === 'string'
583
- ? this.config.text.sanitizeFieldValue(attRecord.value)
584
- : '';
585
- if (!fieldName || !fieldValue) continue;
586
- fields.push({
587
- name: fieldName,
588
- value: fieldValue,
589
- verifiedAt: attRecord.verifiedAt ? new Date(String(attRecord.verifiedAt)) : undefined,
590
- });
591
- }
574
+ for (const att of apList(actor.attachment)) {
575
+ const attRecord = asRecord(att);
576
+ if (!attRecord || attRecord.type !== 'PropertyValue') continue;
577
+ const fieldName = this.config.text.inlineField(attRecord.name);
578
+ const fieldValue =
579
+ typeof attRecord.value === 'string'
580
+ ? this.config.text.sanitizeFieldValue(attRecord.value)
581
+ : '';
582
+ if (!fieldName || !fieldValue) continue;
583
+ fields.push({
584
+ name: fieldName,
585
+ value: fieldValue,
586
+ verifiedAt: apDate(attRecord.verifiedAt),
587
+ });
592
588
  }
593
589
 
594
- const avatarUrl = this.config.firstStringUrl(actor.icon);
595
- const headerUrl = this.config.firstStringUrl(actor.image);
590
+ const imageUrl = this.config.firstStringUrl ?? apImageUrl;
591
+ const avatarUrl = imageUrl(actor.icon);
592
+ const headerUrl = imageUrl(actor.image);
596
593
  // `summary` is the actor's bio — a BODY, so its line breaks are the author's
597
594
  // and must survive; `htmlToPlainText` normalizes it as multiline.
598
595
  const summary =
@@ -602,11 +599,14 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
602
599
  const rawDisplayName = typeof actor.name === 'string' ? actor.name : '';
603
600
  const displayName = this.config.text.inlineDisplayName(rawDisplayName) || username;
604
601
 
605
- const alsoKnownAs = Array.isArray(actor.alsoKnownAs)
606
- ? actor.alsoKnownAs.filter((v): v is string => typeof v === 'string')
607
- : undefined;
602
+ // Absent stays absent (the store keeps what it has); one alias or a list
603
+ // of them is the list.
604
+ const alsoKnownAs =
605
+ actor.alsoKnownAs === undefined || actor.alsoKnownAs === null
606
+ ? undefined
607
+ : apIriList(actor.alsoKnownAs);
608
608
  // A move target is an actor URL; anything else is not one.
609
- const movedToValue = asString(actor.movedTo);
609
+ const movedToValue = apIri(actor.movedTo);
610
610
  const movedTo = movedToValue && /^https?:\/\//.test(movedToValue) ? movedToValue : undefined;
611
611
 
612
612
  // The IDENTITY the actor is stored under in Oxy, which is not necessarily the
@@ -648,10 +648,10 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
648
648
  avatarUrl,
649
649
  headerUrl,
650
650
  inboxUrl: actorInbox,
651
- outboxUrl: asString(actor.outbox) || undefined,
652
- sharedInboxUrl: asString(actorEndpoints?.sharedInbox) || undefined,
653
- followersUrl: asString(actor.followers) || undefined,
654
- followingUrl: asString(actor.following) || undefined,
651
+ outboxUrl: apIri(actor.outbox),
652
+ sharedInboxUrl: apIri(actorEndpoints?.sharedInbox),
653
+ followersUrl: apIri(actor.followers),
654
+ followingUrl: apIri(actor.following),
655
655
  publicKeyPem: asString(actorPublicKey?.publicKeyPem) || undefined,
656
656
  publicKeyId: asString(actorPublicKey?.id) || undefined,
657
657
  type: asString(actor.type) || 'Person',
@@ -661,13 +661,12 @@ export class ActorResolver<TActor extends FederatedActorRecordBase> {
661
661
  memorial: actor.memorial === true,
662
662
  suspended: actor.suspended === true,
663
663
  fields,
664
- featuredUrl: asString(actor.featured) || undefined,
665
- featuredTagsUrl: asString(actor.featuredTags) || undefined,
664
+ featuredUrl: apIri(actor.featured),
665
+ featuredTagsUrl: apIri(actor.featuredTags),
666
666
  alsoKnownAs,
667
667
  ...(movedTo && { movedTo }),
668
668
  networkAcct: networkIdentity?.federatedUsername,
669
- remoteCreatedAt:
670
- typeof actor.published === 'string' ? new Date(actor.published) : undefined,
669
+ remoteCreatedAt: apDate(actor.published),
671
670
  // Omitted, not written as `undefined`, when this refresh could not tell:
672
671
  // an absent key is what tells the store to keep the value it has.
673
672
  ...(followersCount !== undefined && { followersCount }),
@@ -25,6 +25,7 @@ import { Router, type Request, type Response } from 'express';
25
25
  import type { AccountKind } from '@oxy.so/contracts';
26
26
  import type { User } from '@oxy.so/core';
27
27
  import { AP_CONTEXT } from '../apContext';
28
+ import { apIri } from '../apValue';
28
29
  import { discoveryCacheControl } from './httpCacheControl';
29
30
  import { type FetchPublicKey, verifyHttpSignature } from '../httpSignature';
30
31
  import type { UrlBuilders } from '../urls';
@@ -233,8 +234,7 @@ export function createActorRouter(config: ActorRouterConfig): Router {
233
234
  }
234
235
 
235
236
  // Verify the actor in the activity matches the signature.
236
- const activityActor =
237
- typeof activity.actor === 'string' ? activity.actor : activity.actor?.id;
237
+ const activityActor = apIri(activity.actor);
238
238
  if (activityActor !== actorUri) {
239
239
  logger.debug(`Inbox: Actor mismatch. Signed: ${actorUri}, Activity: ${activityActor}`);
240
240
  return res.status(403).json({ error: 'Actor mismatch' });
@@ -23,6 +23,7 @@
23
23
  * `handleReject`.
24
24
  */
25
25
 
26
+ import { apIri } from '../apValue';
26
27
  import { normalizeActorUsername } from '../urls';
27
28
 
28
29
  /**
@@ -226,11 +227,11 @@ function parseInboundMove(
226
227
  ): { ok: true; move: InboundMove } | { ok: false; reason: string } {
227
228
  const activityId = typeof activity.id === 'string' ? activity.id : undefined;
228
229
  if (!activityId) return { ok: false, reason: 'missing id' };
229
- const actor = objectTargetUri(activity.actor);
230
+ const actor = apIri(activity.actor);
230
231
  if (actor !== verifiedActorUri) return { ok: false, reason: 'actor is not the signer' };
231
- const object = objectTargetUri(activity.object);
232
+ const object = apIri(activity.object);
232
233
  if (object !== verifiedActorUri) return { ok: false, reason: 'object is not the moving actor' };
233
- const target = objectTargetUri(activity.target);
234
+ const target = apIri(activity.target);
234
235
  if (!target) return { ok: false, reason: 'missing target' };
235
236
  try {
236
237
  if (new URL(target).protocol !== 'https:') return { ok: false, reason: 'target is not https' };
@@ -261,15 +262,6 @@ function actorUriHost(actorUri: string): string | null {
261
262
  }
262
263
 
263
264
  /** Read the `object`'s referenced actor/target uri (a string, or an embedded `{ id }`). */
264
- function objectTargetUri(object: unknown): string | undefined {
265
- if (typeof object === 'string') return object;
266
- if (object && typeof object === 'object') {
267
- const id = (object as { id?: unknown }).id;
268
- if (typeof id === 'string') return id;
269
- }
270
- return undefined;
271
- }
272
-
273
265
  /** Build the inbound-activity dispatcher from an app's adapters + content handlers. */
274
266
  export function createInboundDispatcher(config: InboundDispatcherConfig): InboundDispatcher {
275
267
  const { logger } = config;
@@ -278,7 +270,7 @@ export function createInboundDispatcher(config: InboundDispatcherConfig): Inboun
278
270
  activity: Record<string, unknown>,
279
271
  actorUri: string,
280
272
  ): Promise<void> {
281
- const targetActorUri = objectTargetUri(activity.object);
273
+ const targetActorUri = apIri(activity.object);
282
274
  if (!targetActorUri) return;
283
275
 
284
276
  // Extract username from our actor URL
@@ -356,7 +348,7 @@ export function createInboundDispatcher(config: InboundDispatcherConfig): Inboun
356
348
  object: Record<string, unknown>,
357
349
  actorUri: string,
358
350
  ): Promise<void> {
359
- const targetActorUri = objectTargetUri(object.object);
351
+ const targetActorUri = apIri(object.object);
360
352
  const match = targetActorUri?.match(/\/ap\/users\/([^/]+)$/);
361
353
  let localUserId: string | undefined;
362
354
  if (match) {