@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.
@@ -0,0 +1,164 @@
1
+ "use strict";
2
+ /**
3
+ * The ONE way to read an ActivityStreams value whose JSON-LD shape varies.
4
+ *
5
+ * JSON-LD lets the same statement arrive in several shapes, and every one of
6
+ * them is valid ActivityPub:
7
+ *
8
+ * - compaction turns a one-element array into the value itself, so `tag`,
9
+ * `attachment`, `alsoKnownAs`, `to` or `icon` may be one object or a list
10
+ * (GoToSocial sends single values; Mastodon sends arrays);
11
+ * - a reference may be the IRI string, an embedded object naming it by `id`,
12
+ * or a `Link` naming it by `href`;
13
+ * - an image may be a URL string, an `Image` whose `url` is a string, a `Link`
14
+ * or a list of them, or a list of `Image`s (PeerTube 6+ sends icon sizes);
15
+ * - a media type may carry parameters (`application/ld+json; profile="…"`),
16
+ * spaced or quoted however the server likes;
17
+ * - a date may use any ISO 8601 offset spelling (`Z`, `+00:00`, `+0000`, `+00`).
18
+ *
19
+ * A reader that assumes one shape loses the others SILENTLY: the mention, tag,
20
+ * alias or avatar is simply not there, and nothing logs. These helpers accept
21
+ * every shape, so readers never re-derive the rule. They are pure and
22
+ * dependency-free (browser-safe).
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.apList = apList;
26
+ exports.apIri = apIri;
27
+ exports.apIriList = apIriList;
28
+ exports.apImageUrl = apImageUrl;
29
+ exports.apMediaTypeBase = apMediaTypeBase;
30
+ exports.isActivityPubMediaType = isActivityPubMediaType;
31
+ exports.apDate = apDate;
32
+ /**
33
+ * A one-or-many ActivityStreams property as a list. A single value becomes a
34
+ * one-element list, an absent (`undefined` / `null`) value an empty one, and the
35
+ * `null` / `undefined` entries of a list are dropped.
36
+ */
37
+ function apList(value) {
38
+ if (value === undefined || value === null)
39
+ return [];
40
+ if (!Array.isArray(value))
41
+ return [value];
42
+ return value.filter((entry) => entry !== undefined && entry !== null);
43
+ }
44
+ /**
45
+ * The IRI a JSON-LD node reference names: the string itself, the `id` of an
46
+ * embedded object, or the `href` of a `Link` (a `Mention` tag, a `Link` `url`).
47
+ * ActivityStreams lets a server embed a referenced node (an actor's `followers`
48
+ * collection with its `totalItems`, an `endpoints` value) instead of linking it,
49
+ * and all of these mean the same node. Anything else, a list included, names none;
50
+ * read a list through {@link apIriList}.
51
+ */
52
+ function apIri(value) {
53
+ if (typeof value === 'string')
54
+ return value || undefined;
55
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
56
+ const { id, href } = value;
57
+ if (typeof id === 'string' && id)
58
+ return id;
59
+ if (typeof href === 'string' && href)
60
+ return href;
61
+ }
62
+ return undefined;
63
+ }
64
+ /**
65
+ * Every IRI a one-or-many reference property names (`to`, `cc`, `audience`,
66
+ * `alsoKnownAs`, `attributedTo`), in order: {@link apList} read through
67
+ * {@link apIri}, dropping the entries that name none.
68
+ */
69
+ function apIriList(value) {
70
+ const iris = [];
71
+ for (const entry of apList(value)) {
72
+ const iri = apIri(entry);
73
+ if (iri)
74
+ iris.push(iri);
75
+ }
76
+ return iris;
77
+ }
78
+ function isAbsoluteHttpUrl(value) {
79
+ return /^https?:\/\/[^\s/]/i.test(value);
80
+ }
81
+ /** Nesting a real image value needs: icon list → Image → url list → Link. */
82
+ const AP_IMAGE_MAX_DEPTH = 4;
83
+ /**
84
+ * The first absolute http(s) URL an image-valued property (`icon`, `image`, an
85
+ * `Image` attachment's `url`) names: a URL string, an object's `url` or `href`
86
+ * (an `Image` whose `url` is a string, a `Link` or a list of them), or the
87
+ * first entry of a list that names one.
88
+ */
89
+ function apImageUrl(value) {
90
+ return imageUrlAt(value, 0);
91
+ }
92
+ function imageUrlAt(value, depth) {
93
+ if (typeof value === 'string')
94
+ return isAbsoluteHttpUrl(value) ? value : undefined;
95
+ if (depth >= AP_IMAGE_MAX_DEPTH || !value || typeof value !== 'object')
96
+ return undefined;
97
+ if (Array.isArray(value)) {
98
+ for (const entry of value) {
99
+ const url = imageUrlAt(entry, depth + 1);
100
+ if (url)
101
+ return url;
102
+ }
103
+ return undefined;
104
+ }
105
+ const record = value;
106
+ return imageUrlAt(record.url, depth + 1) ?? imageUrlAt(record.href, depth + 1);
107
+ }
108
+ /**
109
+ * The base of a media type, lowercased and without parameters:
110
+ * `application/ld+json; profile="https://www.w3.org/ns/activitystreams"` and
111
+ * `Application/LD+JSON;profile=…` are both `application/ld+json`. Empty for a
112
+ * value that is not a string.
113
+ */
114
+ function apMediaTypeBase(value) {
115
+ if (typeof value !== 'string')
116
+ return '';
117
+ return (value.split(';')[0] ?? '').trim().toLowerCase();
118
+ }
119
+ /**
120
+ * Whether a media type is an ActivityStreams document's (`application/activity+json`
121
+ * or `application/ld+json`, with any parameters): what a WebFinger `self` link or
122
+ * an actor response names.
123
+ */
124
+ function isActivityPubMediaType(value) {
125
+ const base = apMediaTypeBase(value);
126
+ return base === 'application/activity+json' || base === 'application/ld+json';
127
+ }
128
+ const ISO_DATE_TIME = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2}(?::\d{2}(?:[.,]\d+)?)?)\s*(Z|z|[+-]\d{2}(?::?\d{2})?)?)?$/;
129
+ /**
130
+ * A date an ActivityStreams document asserts (`published`, `updated`, a field's
131
+ * `verifiedAt`), parsed leniently, or `undefined` when it names no date.
132
+ *
133
+ * ISO 8601 is read in every offset spelling servers send (`Z`, `+00:00`, `+0000`,
134
+ * `+00`), with a space for the `T`, a comma for the decimal point and a missing
135
+ * offset (read as UTC), so the result does not depend on the JavaScript engine's
136
+ * own `Date` parser. Another string is accepted when it names a four-digit year
137
+ * and that parser reads it (an RFC 2822 date). A `Date` passes through when
138
+ * valid. It never clamps: a caller that must bound future dates does so itself.
139
+ */
140
+ function apDate(value) {
141
+ if (value instanceof Date)
142
+ return Number.isNaN(value.getTime()) ? undefined : value;
143
+ if (typeof value !== 'string')
144
+ return undefined;
145
+ const text = value.trim();
146
+ if (!text)
147
+ return undefined;
148
+ const iso = ISO_DATE_TIME.exec(text);
149
+ if (iso) {
150
+ const [, day, time = '00:00:00', offset = 'Z'] = iso;
151
+ const parsed = new Date(`${day}T${time.replace(',', '.')}${isoOffset(offset)}`);
152
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed;
153
+ }
154
+ if (!/\b\d{4}\b/.test(text))
155
+ return undefined;
156
+ const parsed = new Date(text);
157
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed;
158
+ }
159
+ function isoOffset(offset) {
160
+ if (offset === 'Z' || offset === 'z')
161
+ return 'Z';
162
+ const digits = offset.slice(1).replace(':', '');
163
+ return `${offset[0]}${digits.slice(0, 2)}:${digits.slice(2, 4) || '00'}`;
164
+ }
package/dist/cjs/index.js CHANGED
@@ -22,7 +22,7 @@
22
22
  * knowledge of any app's post shape.
23
23
  */
24
24
  Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.groupFollowersCollection = exports.groupOutboxCollection = exports.isGroupActorKind = exports.GROUP_OUTBOX_SIZE = exports.LOCAL_ACTOR_TYPE_BY_ACCOUNT_KIND = exports.AP_ACTOR_TYPES = exports.isApActorType = exports.accountKindForActor = exports.localActorTypeForAccountKind = exports.normalizeAlsoKnownAs = exports.createLocalActorBuilder = exports.createDomainPolicy = exports.extractActorUriFromActivityId = exports.isSameFederationHost = exports.canonicalFederationHost = exports.AP_CONTEXT = exports.readProxyDeclarations = exports.upstreamHandleFromProxyOf = exports.upstreamHandleFromPreferredUsername = exports.upstreamHandleFromAutomatedActor = exports.upstreamHandleFromAlsoKnownAs = exports.upstreamHandleFromProfileField = exports.federatedUsernameFromUpstreamUrl = exports.parseUpstreamProfileUrl = exports.upstreamProfileUrl = exports.stripBridgeBoilerplate = exports.createBridgeRelabeller = exports.atprotoIdentityHandle = exports.isUnresolvedAtprotoHandle = exports.UNRESOLVED_ATPROTO_HANDLE = exports.blueskyHandleFromUsername = exports.blueskyUsernameFromHandle = exports.BSKY_NETWORK_DOMAIN = exports.FEDERATION_NETWORKS = exports.INSTANCE_ACTOR_USERNAME = exports.normalizeActorUsername = exports.createUrlBuilders = exports.DEFAULT_SIGNED_CONTENT_TYPE = exports.HTTP_SIGNATURE_ALGORITHM = exports.verifyHttpSignature = exports.signRequest = void 0;
25
+ exports.groupFollowersCollection = exports.groupOutboxCollection = exports.isGroupActorKind = exports.GROUP_OUTBOX_SIZE = exports.LOCAL_ACTOR_TYPE_BY_ACCOUNT_KIND = exports.AP_ACTOR_TYPES = exports.isApActorType = exports.accountKindForActor = exports.localActorTypeForAccountKind = exports.normalizeAlsoKnownAs = exports.createLocalActorBuilder = exports.apDate = exports.isActivityPubMediaType = exports.apMediaTypeBase = exports.apImageUrl = exports.apIriList = exports.apIri = exports.apList = exports.createDomainPolicy = exports.extractActorUriFromActivityId = exports.isSameFederationHost = exports.canonicalFederationHost = exports.AP_CONTEXT = exports.readProxyDeclarations = exports.upstreamHandleFromProxyOf = exports.upstreamHandleFromPreferredUsername = exports.upstreamHandleFromAutomatedActor = exports.upstreamHandleFromAlsoKnownAs = exports.upstreamHandleFromProfileField = exports.federatedUsernameFromUpstreamUrl = exports.parseUpstreamProfileUrl = exports.upstreamProfileUrl = exports.stripBridgeBoilerplate = exports.createBridgeRelabeller = exports.atprotoIdentityHandle = exports.isUnresolvedAtprotoHandle = exports.UNRESOLVED_ATPROTO_HANDLE = exports.blueskyHandleFromUsername = exports.blueskyUsernameFromHandle = exports.BSKY_NETWORK_DOMAIN = exports.FEDERATION_NETWORKS = exports.INSTANCE_ACTOR_USERNAME = exports.normalizeActorUsername = exports.createUrlBuilders = exports.DEFAULT_SIGNED_CONTENT_TYPE = exports.HTTP_SIGNATURE_ALGORITHM = exports.verifyHttpSignature = exports.signRequest = void 0;
26
26
  /**
27
27
  * HTTP Signatures (draft-cavage) — the pure sign/verify crypto every Oxy app's
28
28
  * ActivityPub federation shares. Private-key custody is injected; the key never
@@ -90,6 +90,22 @@ Object.defineProperty(exports, "canonicalFederationHost", { enumerable: true, ge
90
90
  Object.defineProperty(exports, "isSameFederationHost", { enumerable: true, get: function () { return apUri_1.isSameFederationHost; } });
91
91
  Object.defineProperty(exports, "extractActorUriFromActivityId", { enumerable: true, get: function () { return apUri_1.extractActorUriFromActivityId; } });
92
92
  Object.defineProperty(exports, "createDomainPolicy", { enumerable: true, get: function () { return apUri_1.createDomainPolicy; } });
93
+ /**
94
+ * The one way to read an ActivityStreams value whose JSON-LD shape varies: a
95
+ * one-or-many property ({@link apList}), a reference by IRI, `id` or `href`
96
+ * ({@link apIri} / {@link apIriList}), an image ({@link apImageUrl}), a media
97
+ * type with parameters ({@link apMediaTypeBase} / {@link isActivityPubMediaType})
98
+ * and a date in any ISO 8601 offset spelling ({@link apDate}). A reader that
99
+ * assumes one shape silently loses the others.
100
+ */
101
+ var apValue_1 = require("./apValue");
102
+ Object.defineProperty(exports, "apList", { enumerable: true, get: function () { return apValue_1.apList; } });
103
+ Object.defineProperty(exports, "apIri", { enumerable: true, get: function () { return apValue_1.apIri; } });
104
+ Object.defineProperty(exports, "apIriList", { enumerable: true, get: function () { return apValue_1.apIriList; } });
105
+ Object.defineProperty(exports, "apImageUrl", { enumerable: true, get: function () { return apValue_1.apImageUrl; } });
106
+ Object.defineProperty(exports, "apMediaTypeBase", { enumerable: true, get: function () { return apValue_1.apMediaTypeBase; } });
107
+ Object.defineProperty(exports, "isActivityPubMediaType", { enumerable: true, get: function () { return apValue_1.isActivityPubMediaType; } });
108
+ Object.defineProperty(exports, "apDate", { enumerable: true, get: function () { return apValue_1.apDate; } });
93
109
  /**
94
110
  * The single builder of a LOCAL user's ActivityPub actor document —
95
111
  * byte-identical across apps, with media resolution injected. The actor `type`
@@ -65,6 +65,7 @@ exports.atprotoIdentityHandle = atprotoIdentityHandle;
65
65
  exports.createBridgeRelabeller = createBridgeRelabeller;
66
66
  exports.stripBridgeBoilerplate = stripBridgeBoilerplate;
67
67
  exports.federatedUsernameFromUpstreamUrl = federatedUsernameFromUpstreamUrl;
68
+ const apValue_1 = require("./apValue");
68
69
  const apUri_1 = require("./apUri");
69
70
  /**
70
71
  * The networks Oxy re-labels accounts onto.
@@ -159,10 +160,8 @@ exports.BSKY_NETWORK_DOMAIN = exports.FEDERATION_NETWORKS.bluesky.domain;
159
160
  * copy of it", and only the former could ever justify moving an identity.
160
161
  */
161
162
  function readProxyDeclarations(value) {
162
- if (!Array.isArray(value))
163
- return [];
164
163
  const declarations = [];
165
- for (const raw of value) {
164
+ for (const raw of (0, apValue_1.apList)(value)) {
166
165
  if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
167
166
  continue;
168
167
  const entry = raw;
@@ -23,6 +23,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
23
23
  exports.ActorResolver = void 0;
24
24
  exports.createActorResolver = createActorResolver;
25
25
  const apUri_1 = require("../apUri");
26
+ const apValue_1 = require("../apValue");
26
27
  const networkIdentity_1 = require("../networkIdentity");
27
28
  const boundedBody_1 = require("./boundedBody");
28
29
  /**
@@ -86,12 +87,6 @@ async function readBoundedJson(res, maxBytes) {
86
87
  throw new Error('Remote response is not a JSON object');
87
88
  return record;
88
89
  }
89
- function isApActorContentType(type) {
90
- if (!type)
91
- return false;
92
- const base = type.split(';')[0]?.trim().toLowerCase();
93
- return base === 'application/activity+json' || base === 'application/ld+json';
94
- }
95
90
  function asRecord(value) {
96
91
  return value && typeof value === 'object' && !Array.isArray(value)
97
92
  ? value
@@ -180,7 +175,7 @@ class ActorResolver {
180
175
  const data = await this.config.fetchWebFinger(url);
181
176
  if (!data)
182
177
  return null;
183
- const link = data.links?.find((l) => l.rel === 'self' && isApActorContentType(l.type));
178
+ const link = data.links?.find((l) => l.rel === 'self' && (0, apValue_1.isActivityPubMediaType)(l.type));
184
179
  return link?.href || null;
185
180
  }
186
181
  catch (err) {
@@ -265,7 +260,7 @@ class ActorResolver {
265
260
  }
266
261
  const actor = await readBoundedJson(res, ACTOR_BODY_MAX_BYTES);
267
262
  const actorId = asString(actor.id);
268
- const actorInbox = asString(actor.inbox);
263
+ const actorInbox = (0, apValue_1.apIri)(actor.inbox);
269
264
  if (!actorId || !actorInbox) {
270
265
  this.config.logger.info(`[FedSync] fetchRemoteActor missing fields for ${currentUri}: id=${!!actor.id} inbox=${!!actor.inbox} type=${String(actor.type)} keys=${Object.keys(actor).join(',')}`);
271
266
  return null;
@@ -306,34 +301,33 @@ class ActorResolver {
306
301
  const actorPublicKey = asRecord(actor.publicKey);
307
302
  // Fetch collection counts (followers, following, posts) in parallel
308
303
  const [followersCount, followingCount, postsCount] = await Promise.all([
309
- this.fetchCollectionCount(asString(actor.followers)),
310
- this.fetchCollectionCount(asString(actor.following)),
311
- this.fetchCollectionCount(asString(actor.outbox)),
304
+ this.fetchCollectionCount((0, apValue_1.apIri)(actor.followers)),
305
+ this.fetchCollectionCount((0, apValue_1.apIri)(actor.following)),
306
+ this.fetchCollectionCount((0, apValue_1.apIri)(actor.outbox)),
312
307
  ]);
313
308
  // Extract profile fields (PropertyValue attachments). Sanitize BEFORE
314
309
  // normalizing: the canonical normalizer collapses whitespace, it never
315
310
  // strips markup — so the sanitizer must run first, on the raw value.
316
311
  const fields = [];
317
- if (Array.isArray(actor.attachment)) {
318
- for (const att of actor.attachment) {
319
- const attRecord = asRecord(att);
320
- if (!attRecord || attRecord.type !== 'PropertyValue')
321
- continue;
322
- const fieldName = this.config.text.inlineField(attRecord.name);
323
- const fieldValue = typeof attRecord.value === 'string'
324
- ? this.config.text.sanitizeFieldValue(attRecord.value)
325
- : '';
326
- if (!fieldName || !fieldValue)
327
- continue;
328
- fields.push({
329
- name: fieldName,
330
- value: fieldValue,
331
- verifiedAt: attRecord.verifiedAt ? new Date(String(attRecord.verifiedAt)) : undefined,
332
- });
333
- }
312
+ for (const att of (0, apValue_1.apList)(actor.attachment)) {
313
+ const attRecord = asRecord(att);
314
+ if (!attRecord || attRecord.type !== 'PropertyValue')
315
+ continue;
316
+ const fieldName = this.config.text.inlineField(attRecord.name);
317
+ const fieldValue = typeof attRecord.value === 'string'
318
+ ? this.config.text.sanitizeFieldValue(attRecord.value)
319
+ : '';
320
+ if (!fieldName || !fieldValue)
321
+ continue;
322
+ fields.push({
323
+ name: fieldName,
324
+ value: fieldValue,
325
+ verifiedAt: (0, apValue_1.apDate)(attRecord.verifiedAt),
326
+ });
334
327
  }
335
- const avatarUrl = this.config.firstStringUrl(actor.icon);
336
- const headerUrl = this.config.firstStringUrl(actor.image);
328
+ const imageUrl = this.config.firstStringUrl ?? apValue_1.apImageUrl;
329
+ const avatarUrl = imageUrl(actor.icon);
330
+ const headerUrl = imageUrl(actor.image);
337
331
  // `summary` is the actor's bio — a BODY, so its line breaks are the author's
338
332
  // and must survive; `htmlToPlainText` normalizes it as multiline.
339
333
  const summary = typeof actor.summary === 'string' ? this.config.text.htmlToPlainText(actor.summary) : '';
@@ -341,11 +335,13 @@ class ActorResolver {
341
335
  // ` ` only becomes whitespace once decoded), THEN collapse.
342
336
  const rawDisplayName = typeof actor.name === 'string' ? actor.name : '';
343
337
  const displayName = this.config.text.inlineDisplayName(rawDisplayName) || username;
344
- const alsoKnownAs = Array.isArray(actor.alsoKnownAs)
345
- ? actor.alsoKnownAs.filter((v) => typeof v === 'string')
346
- : undefined;
338
+ // Absent stays absent (the store keeps what it has); one alias or a list
339
+ // of them is the list.
340
+ const alsoKnownAs = actor.alsoKnownAs === undefined || actor.alsoKnownAs === null
341
+ ? undefined
342
+ : (0, apValue_1.apIriList)(actor.alsoKnownAs);
347
343
  // A move target is an actor URL; anything else is not one.
348
- const movedToValue = asString(actor.movedTo);
344
+ const movedToValue = (0, apValue_1.apIri)(actor.movedTo);
349
345
  const movedTo = movedToValue && /^https?:\/\//.test(movedToValue) ? movedToValue : undefined;
350
346
  // The IDENTITY the actor is stored under in Oxy, which is not necessarily the
351
347
  // host it was fetched from — see `DeriveNetworkIdentity`. Everything below
@@ -385,10 +381,10 @@ class ActorResolver {
385
381
  avatarUrl,
386
382
  headerUrl,
387
383
  inboxUrl: actorInbox,
388
- outboxUrl: asString(actor.outbox) || undefined,
389
- sharedInboxUrl: asString(actorEndpoints?.sharedInbox) || undefined,
390
- followersUrl: asString(actor.followers) || undefined,
391
- followingUrl: asString(actor.following) || undefined,
384
+ outboxUrl: (0, apValue_1.apIri)(actor.outbox),
385
+ sharedInboxUrl: (0, apValue_1.apIri)(actorEndpoints?.sharedInbox),
386
+ followersUrl: (0, apValue_1.apIri)(actor.followers),
387
+ followingUrl: (0, apValue_1.apIri)(actor.following),
392
388
  publicKeyPem: asString(actorPublicKey?.publicKeyPem) || undefined,
393
389
  publicKeyId: asString(actorPublicKey?.id) || undefined,
394
390
  type: asString(actor.type) || 'Person',
@@ -398,12 +394,12 @@ class ActorResolver {
398
394
  memorial: actor.memorial === true,
399
395
  suspended: actor.suspended === true,
400
396
  fields,
401
- featuredUrl: asString(actor.featured) || undefined,
402
- featuredTagsUrl: asString(actor.featuredTags) || undefined,
397
+ featuredUrl: (0, apValue_1.apIri)(actor.featured),
398
+ featuredTagsUrl: (0, apValue_1.apIri)(actor.featuredTags),
403
399
  alsoKnownAs,
404
400
  ...(movedTo && { movedTo }),
405
401
  networkAcct: networkIdentity?.federatedUsername,
406
- remoteCreatedAt: typeof actor.published === 'string' ? new Date(actor.published) : undefined,
402
+ remoteCreatedAt: (0, apValue_1.apDate)(actor.published),
407
403
  // Omitted, not written as `undefined`, when this refresh could not tell:
408
404
  // an absent key is what tells the store to keep the value it has.
409
405
  ...(followersCount !== undefined && { followersCount }),
@@ -25,6 +25,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
25
25
  exports.createActorRouter = createActorRouter;
26
26
  const express_1 = require("express");
27
27
  const apContext_1 = require("../apContext");
28
+ const apValue_1 = require("../apValue");
28
29
  const httpCacheControl_1 = require("./httpCacheControl");
29
30
  const httpSignature_1 = require("../httpSignature");
30
31
  const urls_1 = require("../urls");
@@ -100,7 +101,7 @@ function createActorRouter(config) {
100
101
  return res.status(400).json({ error: 'Invalid activity' });
101
102
  }
102
103
  // Verify the actor in the activity matches the signature.
103
- const activityActor = typeof activity.actor === 'string' ? activity.actor : activity.actor?.id;
104
+ const activityActor = (0, apValue_1.apIri)(activity.actor);
104
105
  if (activityActor !== actorUri) {
105
106
  logger.debug(`Inbox: Actor mismatch. Signed: ${actorUri}, Activity: ${activityActor}`);
106
107
  return res.status(403).json({ error: 'Actor mismatch' });
@@ -26,6 +26,7 @@
26
26
  Object.defineProperty(exports, "__esModule", { value: true });
27
27
  exports.ActorResolutionPendingError = void 0;
28
28
  exports.createInboundDispatcher = createInboundDispatcher;
29
+ const apValue_1 = require("../apValue");
29
30
  const urls_1 = require("../urls");
30
31
  /**
31
32
  * Thrown when a federated follow is about to be bridged but the FOLLOWER actor
@@ -61,13 +62,13 @@ function parseInboundMove(activity, verifiedActorUri) {
61
62
  const activityId = typeof activity.id === 'string' ? activity.id : undefined;
62
63
  if (!activityId)
63
64
  return { ok: false, reason: 'missing id' };
64
- const actor = objectTargetUri(activity.actor);
65
+ const actor = (0, apValue_1.apIri)(activity.actor);
65
66
  if (actor !== verifiedActorUri)
66
67
  return { ok: false, reason: 'actor is not the signer' };
67
- const object = objectTargetUri(activity.object);
68
+ const object = (0, apValue_1.apIri)(activity.object);
68
69
  if (object !== verifiedActorUri)
69
70
  return { ok: false, reason: 'object is not the moving actor' };
70
- const target = objectTargetUri(activity.target);
71
+ const target = (0, apValue_1.apIri)(activity.target);
71
72
  if (!target)
72
73
  return { ok: false, reason: 'missing target' };
73
74
  try {
@@ -95,21 +96,11 @@ function actorUriHost(actorUri) {
95
96
  }
96
97
  }
97
98
  /** Read the `object`'s referenced actor/target uri (a string, or an embedded `{ id }`). */
98
- function objectTargetUri(object) {
99
- if (typeof object === 'string')
100
- return object;
101
- if (object && typeof object === 'object') {
102
- const id = object.id;
103
- if (typeof id === 'string')
104
- return id;
105
- }
106
- return undefined;
107
- }
108
99
  /** Build the inbound-activity dispatcher from an app's adapters + content handlers. */
109
100
  function createInboundDispatcher(config) {
110
101
  const { logger } = config;
111
102
  async function handleIncomingFollow(activity, actorUri) {
112
- const targetActorUri = objectTargetUri(activity.object);
103
+ const targetActorUri = (0, apValue_1.apIri)(activity.object);
113
104
  if (!targetActorUri)
114
105
  return;
115
106
  // Extract username from our actor URL
@@ -174,7 +165,7 @@ function createInboundDispatcher(config) {
174
165
  logger.info(`Accepted follow from ${actorUri} to ${username}`);
175
166
  }
176
167
  async function handleUndoFollow(object, actorUri) {
177
- const targetActorUri = objectTargetUri(object.object);
168
+ const targetActorUri = (0, apValue_1.apIri)(object.object);
178
169
  const match = targetActorUri?.match(/\/ap\/users\/([^/]+)$/);
179
170
  let localUserId;
180
171
  if (match) {
@@ -0,0 +1,155 @@
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 function apList(value) {
29
+ if (value === undefined || value === null)
30
+ return [];
31
+ if (!Array.isArray(value))
32
+ return [value];
33
+ return value.filter((entry) => entry !== undefined && entry !== null);
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) {
44
+ if (typeof value === 'string')
45
+ return value || undefined;
46
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
47
+ const { id, href } = value;
48
+ if (typeof id === 'string' && id)
49
+ return id;
50
+ if (typeof href === 'string' && href)
51
+ return href;
52
+ }
53
+ return undefined;
54
+ }
55
+ /**
56
+ * Every IRI a one-or-many reference property names (`to`, `cc`, `audience`,
57
+ * `alsoKnownAs`, `attributedTo`), in order: {@link apList} read through
58
+ * {@link apIri}, dropping the entries that name none.
59
+ */
60
+ export function apIriList(value) {
61
+ const iris = [];
62
+ for (const entry of apList(value)) {
63
+ const iri = apIri(entry);
64
+ if (iri)
65
+ iris.push(iri);
66
+ }
67
+ return iris;
68
+ }
69
+ function isAbsoluteHttpUrl(value) {
70
+ return /^https?:\/\/[^\s/]/i.test(value);
71
+ }
72
+ /** Nesting a real image value needs: icon list → Image → url list → Link. */
73
+ const AP_IMAGE_MAX_DEPTH = 4;
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) {
81
+ return imageUrlAt(value, 0);
82
+ }
83
+ function imageUrlAt(value, depth) {
84
+ if (typeof value === 'string')
85
+ return isAbsoluteHttpUrl(value) ? value : undefined;
86
+ if (depth >= AP_IMAGE_MAX_DEPTH || !value || typeof value !== 'object')
87
+ return undefined;
88
+ if (Array.isArray(value)) {
89
+ for (const entry of value) {
90
+ const url = imageUrlAt(entry, depth + 1);
91
+ if (url)
92
+ return url;
93
+ }
94
+ return undefined;
95
+ }
96
+ const record = value;
97
+ return imageUrlAt(record.url, depth + 1) ?? imageUrlAt(record.href, depth + 1);
98
+ }
99
+ /**
100
+ * The base of a media type, lowercased and without parameters:
101
+ * `application/ld+json; profile="https://www.w3.org/ns/activitystreams"` and
102
+ * `Application/LD+JSON;profile=…` are both `application/ld+json`. Empty for a
103
+ * value that is not a string.
104
+ */
105
+ export function apMediaTypeBase(value) {
106
+ if (typeof value !== 'string')
107
+ return '';
108
+ return (value.split(';')[0] ?? '').trim().toLowerCase();
109
+ }
110
+ /**
111
+ * Whether a media type is an ActivityStreams document's (`application/activity+json`
112
+ * or `application/ld+json`, with any parameters): what a WebFinger `self` link or
113
+ * an actor response names.
114
+ */
115
+ export function isActivityPubMediaType(value) {
116
+ const base = apMediaTypeBase(value);
117
+ return base === 'application/activity+json' || base === 'application/ld+json';
118
+ }
119
+ const ISO_DATE_TIME = /^(\d{4}-\d{2}-\d{2})(?:[Tt ](\d{2}:\d{2}(?::\d{2}(?:[.,]\d+)?)?)\s*(Z|z|[+-]\d{2}(?::?\d{2})?)?)?$/;
120
+ /**
121
+ * A date an ActivityStreams document asserts (`published`, `updated`, a field's
122
+ * `verifiedAt`), parsed leniently, or `undefined` when it names no date.
123
+ *
124
+ * ISO 8601 is read in every offset spelling servers send (`Z`, `+00:00`, `+0000`,
125
+ * `+00`), with a space for the `T`, a comma for the decimal point and a missing
126
+ * offset (read as UTC), so the result does not depend on the JavaScript engine's
127
+ * own `Date` parser. Another string is accepted when it names a four-digit year
128
+ * and that parser reads it (an RFC 2822 date). A `Date` passes through when
129
+ * valid. It never clamps: a caller that must bound future dates does so itself.
130
+ */
131
+ export function apDate(value) {
132
+ if (value instanceof Date)
133
+ return Number.isNaN(value.getTime()) ? undefined : value;
134
+ if (typeof value !== 'string')
135
+ return undefined;
136
+ const text = value.trim();
137
+ if (!text)
138
+ return undefined;
139
+ const iso = ISO_DATE_TIME.exec(text);
140
+ if (iso) {
141
+ const [, day, time = '00:00:00', offset = 'Z'] = iso;
142
+ const parsed = new Date(`${day}T${time.replace(',', '.')}${isoOffset(offset)}`);
143
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed;
144
+ }
145
+ if (!/\b\d{4}\b/.test(text))
146
+ return undefined;
147
+ const parsed = new Date(text);
148
+ return Number.isNaN(parsed.getTime()) ? undefined : parsed;
149
+ }
150
+ function isoOffset(offset) {
151
+ if (offset === 'Z' || offset === 'z')
152
+ return 'Z';
153
+ const digits = offset.slice(1).replace(':', '');
154
+ return `${offset[0]}${digits.slice(0, 2)}:${digits.slice(2, 4) || '00'}`;
155
+ }
package/dist/esm/index.js CHANGED
@@ -57,6 +57,15 @@ export { FEDERATION_NETWORKS, BSKY_NETWORK_DOMAIN, blueskyUsernameFromHandle, bl
57
57
  */
58
58
  export { AP_CONTEXT } from './apContext.js';
59
59
  export { canonicalFederationHost, isSameFederationHost, extractActorUriFromActivityId, createDomainPolicy, } from './apUri.js';
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.js';
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`
@@ -47,6 +47,7 @@
47
47
  * built, so no relabel can resurrect it. Keeping them in separate structures
48
48
  * means neither can be edited into the other by accident.
49
49
  */
50
+ import { apList } from './apValue.js';
50
51
  import { canonicalFederationHost } from './apUri.js';
51
52
  /**
52
53
  * The networks Oxy re-labels accounts onto.
@@ -141,10 +142,8 @@ export const BSKY_NETWORK_DOMAIN = FEDERATION_NETWORKS.bluesky.domain;
141
142
  * copy of it", and only the former could ever justify moving an identity.
142
143
  */
143
144
  export function readProxyDeclarations(value) {
144
- if (!Array.isArray(value))
145
- return [];
146
145
  const declarations = [];
147
- for (const raw of value) {
146
+ for (const raw of apList(value)) {
148
147
  if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
149
148
  continue;
150
149
  const entry = raw;