@oxy.so/federation 2.16.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/dist/esm/index.js CHANGED
@@ -56,7 +56,16 @@ export { FEDERATION_NETWORKS, BSKY_NETWORK_DOMAIN, blueskyUsernameFromHandle, bl
56
56
  * built from — not a parallel implementation that agrees today.
57
57
  */
58
58
  export { AP_CONTEXT } from './apContext.js';
59
- export { canonicalFederationHost, isSameFederationHost, extractActorUriFromActivityId, apIri, createDomainPolicy, } from './apUri.js';
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;
@@ -18,7 +18,8 @@
18
18
  * e.g. Mention's `IFederatedActor`) so callers keep full typing on the returned
19
19
  * document.
20
20
  */
21
- import { apIri, isSameFederationHost } from '../apUri.js';
21
+ import { isSameFederationHost } from '../apUri.js';
22
+ import { apDate, apImageUrl, apIri, apIriList, apList, isActivityPubMediaType } from '../apValue.js';
22
23
  import { readProxyDeclarations, } from '../networkIdentity.js';
23
24
  import { readBodyChunks, ResponseBodyTooLargeError } from './boundedBody.js';
24
25
  /**
@@ -82,12 +83,6 @@ async function readBoundedJson(res, maxBytes) {
82
83
  throw new Error('Remote response is not a JSON object');
83
84
  return record;
84
85
  }
85
- function isApActorContentType(type) {
86
- if (!type)
87
- return false;
88
- const base = type.split(';')[0]?.trim().toLowerCase();
89
- return base === 'application/activity+json' || base === 'application/ld+json';
90
- }
91
86
  function asRecord(value) {
92
87
  return value && typeof value === 'object' && !Array.isArray(value)
93
88
  ? value
@@ -176,7 +171,7 @@ export class ActorResolver {
176
171
  const data = await this.config.fetchWebFinger(url);
177
172
  if (!data)
178
173
  return null;
179
- const link = data.links?.find((l) => l.rel === 'self' && isApActorContentType(l.type));
174
+ const link = data.links?.find((l) => l.rel === 'self' && isActivityPubMediaType(l.type));
180
175
  return link?.href || null;
181
176
  }
182
177
  catch (err) {
@@ -310,26 +305,25 @@ export class ActorResolver {
310
305
  // normalizing: the canonical normalizer collapses whitespace, it never
311
306
  // strips markup — so the sanitizer must run first, on the raw value.
312
307
  const fields = [];
313
- if (Array.isArray(actor.attachment)) {
314
- for (const att of actor.attachment) {
315
- const attRecord = asRecord(att);
316
- if (!attRecord || attRecord.type !== 'PropertyValue')
317
- continue;
318
- const fieldName = this.config.text.inlineField(attRecord.name);
319
- const fieldValue = typeof attRecord.value === 'string'
320
- ? this.config.text.sanitizeFieldValue(attRecord.value)
321
- : '';
322
- if (!fieldName || !fieldValue)
323
- continue;
324
- fields.push({
325
- name: fieldName,
326
- value: fieldValue,
327
- verifiedAt: attRecord.verifiedAt ? new Date(String(attRecord.verifiedAt)) : undefined,
328
- });
329
- }
308
+ for (const att of apList(actor.attachment)) {
309
+ const attRecord = asRecord(att);
310
+ if (!attRecord || attRecord.type !== 'PropertyValue')
311
+ continue;
312
+ const fieldName = this.config.text.inlineField(attRecord.name);
313
+ const fieldValue = typeof attRecord.value === 'string'
314
+ ? this.config.text.sanitizeFieldValue(attRecord.value)
315
+ : '';
316
+ if (!fieldName || !fieldValue)
317
+ continue;
318
+ fields.push({
319
+ name: fieldName,
320
+ value: fieldValue,
321
+ verifiedAt: apDate(attRecord.verifiedAt),
322
+ });
330
323
  }
331
- const avatarUrl = this.config.firstStringUrl(actor.icon);
332
- const headerUrl = this.config.firstStringUrl(actor.image);
324
+ const imageUrl = this.config.firstStringUrl ?? apImageUrl;
325
+ const avatarUrl = imageUrl(actor.icon);
326
+ const headerUrl = imageUrl(actor.image);
333
327
  // `summary` is the actor's bio — a BODY, so its line breaks are the author's
334
328
  // and must survive; `htmlToPlainText` normalizes it as multiline.
335
329
  const summary = typeof actor.summary === 'string' ? this.config.text.htmlToPlainText(actor.summary) : '';
@@ -337,9 +331,11 @@ export class ActorResolver {
337
331
  // ` ` only becomes whitespace once decoded), THEN collapse.
338
332
  const rawDisplayName = typeof actor.name === 'string' ? actor.name : '';
339
333
  const displayName = this.config.text.inlineDisplayName(rawDisplayName) || username;
340
- const alsoKnownAs = Array.isArray(actor.alsoKnownAs)
341
- ? actor.alsoKnownAs.filter((v) => typeof v === 'string')
342
- : undefined;
334
+ // Absent stays absent (the store keeps what it has); one alias or a list
335
+ // of them is the list.
336
+ const alsoKnownAs = actor.alsoKnownAs === undefined || actor.alsoKnownAs === null
337
+ ? undefined
338
+ : apIriList(actor.alsoKnownAs);
343
339
  // A move target is an actor URL; anything else is not one.
344
340
  const movedToValue = apIri(actor.movedTo);
345
341
  const movedTo = movedToValue && /^https?:\/\//.test(movedToValue) ? movedToValue : undefined;
@@ -399,7 +395,7 @@ export class ActorResolver {
399
395
  alsoKnownAs,
400
396
  ...(movedTo && { movedTo }),
401
397
  networkAcct: networkIdentity?.federatedUsername,
402
- remoteCreatedAt: typeof actor.published === 'string' ? new Date(actor.published) : undefined,
398
+ remoteCreatedAt: apDate(actor.published),
403
399
  // Omitted, not written as `undefined`, when this refresh could not tell:
404
400
  // an absent key is what tells the store to keep the value it has.
405
401
  ...(followersCount !== undefined && { followersCount }),
@@ -22,6 +22,7 @@
22
22
  */
23
23
  import { Router } from 'express';
24
24
  import { AP_CONTEXT } from '../apContext.js';
25
+ import { apIri } from '../apValue.js';
25
26
  import { discoveryCacheControl } from './httpCacheControl.js';
26
27
  import { verifyHttpSignature } from '../httpSignature.js';
27
28
  import { INSTANCE_ACTOR_USERNAME, normalizeActorUsername } from '../urls.js';
@@ -97,7 +98,7 @@ export function createActorRouter(config) {
97
98
  return res.status(400).json({ error: 'Invalid activity' });
98
99
  }
99
100
  // Verify the actor in the activity matches the signature.
100
- const activityActor = typeof activity.actor === 'string' ? activity.actor : activity.actor?.id;
101
+ const activityActor = apIri(activity.actor);
101
102
  if (activityActor !== actorUri) {
102
103
  logger.debug(`Inbox: Actor mismatch. Signed: ${actorUri}, Activity: ${activityActor}`);
103
104
  return res.status(403).json({ error: 'Actor mismatch' });
@@ -22,6 +22,7 @@
22
22
  * dispatcher + `handleIncomingFollow` / `handleUndo(Follow)` / `handleAccept` /
23
23
  * `handleReject`.
24
24
  */
25
+ import { apIri } from '../apValue.js';
25
26
  import { normalizeActorUsername } from '../urls.js';
26
27
  /**
27
28
  * Thrown when a federated follow is about to be bridged but the FOLLOWER actor
@@ -56,13 +57,13 @@ function parseInboundMove(activity, verifiedActorUri) {
56
57
  const activityId = typeof activity.id === 'string' ? activity.id : undefined;
57
58
  if (!activityId)
58
59
  return { ok: false, reason: 'missing id' };
59
- const actor = objectTargetUri(activity.actor);
60
+ const actor = apIri(activity.actor);
60
61
  if (actor !== verifiedActorUri)
61
62
  return { ok: false, reason: 'actor is not the signer' };
62
- const object = objectTargetUri(activity.object);
63
+ const object = apIri(activity.object);
63
64
  if (object !== verifiedActorUri)
64
65
  return { ok: false, reason: 'object is not the moving actor' };
65
- const target = objectTargetUri(activity.target);
66
+ const target = apIri(activity.target);
66
67
  if (!target)
67
68
  return { ok: false, reason: 'missing target' };
68
69
  try {
@@ -90,21 +91,11 @@ function actorUriHost(actorUri) {
90
91
  }
91
92
  }
92
93
  /** Read the `object`'s referenced actor/target uri (a string, or an embedded `{ id }`). */
93
- function objectTargetUri(object) {
94
- if (typeof object === 'string')
95
- return object;
96
- if (object && typeof object === 'object') {
97
- const id = object.id;
98
- if (typeof id === 'string')
99
- return id;
100
- }
101
- return undefined;
102
- }
103
94
  /** Build the inbound-activity dispatcher from an app's adapters + content handlers. */
104
95
  export function createInboundDispatcher(config) {
105
96
  const { logger } = config;
106
97
  async function handleIncomingFollow(activity, actorUri) {
107
- const targetActorUri = objectTargetUri(activity.object);
98
+ const targetActorUri = apIri(activity.object);
108
99
  if (!targetActorUri)
109
100
  return;
110
101
  // Extract username from our actor URL
@@ -169,7 +160,7 @@ export function createInboundDispatcher(config) {
169
160
  logger.info(`Accepted follow from ${actorUri} to ${username}`);
170
161
  }
171
162
  async function handleUndoFollow(object, actorUri) {
172
- const targetActorUri = objectTargetUri(object.object);
163
+ const targetActorUri = apIri(object.object);
173
164
  const match = targetActorUri?.match(/\/ap\/users\/([^/]+)$/);
174
165
  let localUserId;
175
166
  if (match) {
@@ -59,13 +59,6 @@ export declare function canonicalFederationHost(host: string): string;
59
59
  * that is not named is not in any set.
60
60
  */
61
61
  export declare function isSameFederationHost(a: string, b: string): boolean;
62
- /**
63
- * The IRI a JSON-LD node reference names: the string itself, or the `id` of an
64
- * embedded object. ActivityStreams lets a server embed a referenced node (an
65
- * actor's `followers` collection with its `totalItems`, an `endpoints` value)
66
- * instead of linking it, and both mean the same node. Anything else names none.
67
- */
68
- export declare function apIri(value: unknown): string | undefined;
69
62
  /**
70
63
  * Given an ActivityPub activity/object ID (URL), extract the actor URI by
71
64
  * trimming everything from the first recognised post-path segment onward.
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The ONE way to read an ActivityStreams value whose JSON-LD shape varies.
3
+ *
4
+ * JSON-LD lets the same statement arrive in several shapes, and every one of
5
+ * them is valid ActivityPub:
6
+ *
7
+ * - compaction turns a one-element array into the value itself, so `tag`,
8
+ * `attachment`, `alsoKnownAs`, `to` or `icon` may be one object or a list
9
+ * (GoToSocial sends single values; Mastodon sends arrays);
10
+ * - a reference may be the IRI string, an embedded object naming it by `id`,
11
+ * or a `Link` naming it by `href`;
12
+ * - an image may be a URL string, an `Image` whose `url` is a string, a `Link`
13
+ * or a list of them, or a list of `Image`s (PeerTube 6+ sends icon sizes);
14
+ * - a media type may carry parameters (`application/ld+json; profile="…"`),
15
+ * spaced or quoted however the server likes;
16
+ * - a date may use any ISO 8601 offset spelling (`Z`, `+00:00`, `+0000`, `+00`).
17
+ *
18
+ * A reader that assumes one shape loses the others SILENTLY: the mention, tag,
19
+ * alias or avatar is simply not there, and nothing logs. These helpers accept
20
+ * every shape, so readers never re-derive the rule. They are pure and
21
+ * dependency-free (browser-safe).
22
+ */
23
+ /**
24
+ * A one-or-many ActivityStreams property as a list. A single value becomes a
25
+ * one-element list, an absent (`undefined` / `null`) value an empty one, and the
26
+ * `null` / `undefined` entries of a list are dropped.
27
+ */
28
+ export declare function apList(value: unknown): unknown[];
29
+ /**
30
+ * The IRI a JSON-LD node reference names: the string itself, the `id` of an
31
+ * embedded object, or the `href` of a `Link` (a `Mention` tag, a `Link` `url`).
32
+ * ActivityStreams lets a server embed a referenced node (an actor's `followers`
33
+ * collection with its `totalItems`, an `endpoints` value) instead of linking it,
34
+ * and all of these mean the same node. Anything else, a list included, names none;
35
+ * read a list through {@link apIriList}.
36
+ */
37
+ export declare function apIri(value: unknown): string | undefined;
38
+ /**
39
+ * Every IRI a one-or-many reference property names (`to`, `cc`, `audience`,
40
+ * `alsoKnownAs`, `attributedTo`), in order: {@link apList} read through
41
+ * {@link apIri}, dropping the entries that name none.
42
+ */
43
+ export declare function apIriList(value: unknown): string[];
44
+ /**
45
+ * The first absolute http(s) URL an image-valued property (`icon`, `image`, an
46
+ * `Image` attachment's `url`) names: a URL string, an object's `url` or `href`
47
+ * (an `Image` whose `url` is a string, a `Link` or a list of them), or the
48
+ * first entry of a list that names one.
49
+ */
50
+ export declare function apImageUrl(value: unknown): string | undefined;
51
+ /**
52
+ * The base of a media type, lowercased and without parameters:
53
+ * `application/ld+json; profile="https://www.w3.org/ns/activitystreams"` and
54
+ * `Application/LD+JSON;profile=…` are both `application/ld+json`. Empty for a
55
+ * value that is not a string.
56
+ */
57
+ export declare function apMediaTypeBase(value: unknown): string;
58
+ /**
59
+ * Whether a media type is an ActivityStreams document's (`application/activity+json`
60
+ * or `application/ld+json`, with any parameters): what a WebFinger `self` link or
61
+ * an actor response names.
62
+ */
63
+ export declare function isActivityPubMediaType(value: unknown): boolean;
64
+ /**
65
+ * A date an ActivityStreams document asserts (`published`, `updated`, a field's
66
+ * `verifiedAt`), parsed leniently, or `undefined` when it names no date.
67
+ *
68
+ * ISO 8601 is read in every offset spelling servers send (`Z`, `+00:00`, `+0000`,
69
+ * `+00`), with a space for the `T`, a comma for the decimal point and a missing
70
+ * offset (read as UTC), so the result does not depend on the JavaScript engine's
71
+ * own `Date` parser. Another string is accepted when it names a four-digit year
72
+ * and that parser reads it (an RFC 2822 date). A `Date` passes through when
73
+ * valid. It never clamps: a caller that must bound future dates does so itself.
74
+ */
75
+ export declare function apDate(value: unknown): Date | undefined;
@@ -56,7 +56,16 @@ export { FEDERATION_NETWORKS, BSKY_NETWORK_DOMAIN, blueskyUsernameFromHandle, bl
56
56
  * built from — not a parallel implementation that agrees today.
57
57
  */
58
58
  export { AP_CONTEXT } from './apContext';
59
- export { canonicalFederationHost, isSameFederationHost, extractActorUriFromActivityId, apIri, createDomainPolicy, type DomainPolicy, type DomainPolicyConfig, } from './apUri';
59
+ export { canonicalFederationHost, isSameFederationHost, extractActorUriFromActivityId, createDomainPolicy, type DomainPolicy, type DomainPolicyConfig, } from './apUri';
60
+ /**
61
+ * The one way to read an ActivityStreams value whose JSON-LD shape varies: a
62
+ * one-or-many property ({@link apList}), a reference by IRI, `id` or `href`
63
+ * ({@link apIri} / {@link apIriList}), an image ({@link apImageUrl}), a media
64
+ * type with parameters ({@link apMediaTypeBase} / {@link isActivityPubMediaType})
65
+ * and a date in any ISO 8601 offset spelling ({@link apDate}). A reader that
66
+ * assumes one shape silently loses the others.
67
+ */
68
+ export { apList, apIri, apIriList, apImageUrl, apMediaTypeBase, isActivityPubMediaType, apDate, } from './apValue';
60
69
  /**
61
70
  * The single builder of a LOCAL user's ActivityPub actor document —
62
71
  * byte-identical across apps, with media resolution injected. The actor `type`
@@ -203,8 +203,11 @@ export interface ActorResolverConfig<TActor extends FederatedActorRecordBase> {
203
203
  normalizeFederatedAcct: (acct: string | undefined) => string | undefined;
204
204
  /** Extract the domain from a canonical acct. */
205
205
  domainFromAcct: (acct: string) => string | undefined;
206
- /** Recursively find the first absolute http(s) URL in a value (icon/image). */
207
- firstStringUrl: (value: unknown) => string | undefined;
206
+ /**
207
+ * The first absolute http(s) URL in an `icon` / `image` value. Optional: the
208
+ * default is {@link apImageUrl}, which reads every image shape.
209
+ */
210
+ firstStringUrl?: (value: unknown) => string | undefined;
208
211
  /**
209
212
  * Optional re-labelling of a bridged actor onto its real network. Absent means
210
213
  * every actor keeps the identity of the host it was fetched from.
@@ -186,5 +186,6 @@ export interface InboundDispatcher {
186
186
  /** Process one already-actor-verified inbound activity. */
187
187
  processInboxActivity(activity: Record<string, unknown>, verifiedActorUri: string): Promise<void>;
188
188
  }
189
+ /** Read the `object`'s referenced actor/target uri (a string, or an embedded `{ id }`). */
189
190
  /** Build the inbound-activity dispatcher from an app's adapters + content handlers. */
190
191
  export declare function createInboundDispatcher(config: InboundDispatcherConfig): InboundDispatcher;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxy.so/federation",
3
- "version": "2.16.0",
3
+ "version": "2.17.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",
@@ -28,6 +28,8 @@ function makeResolver(
28
28
  cachedKey?: Pick<TestActor, 'uri' | 'publicKeyPem'> | null;
29
29
  blockedHosts?: string[];
30
30
  signedFetch?: (url: string) => Promise<Response>;
31
+ onUpsert?: (update: unknown) => void;
32
+ defaultImageReader?: boolean;
31
33
  } = {},
32
34
  ) {
33
35
  const blockedHosts = overrides.blockedHosts ?? ['spam.example'];
@@ -51,13 +53,16 @@ function makeResolver(
51
53
  isBlockedDomain: domainPolicy.isBlockedDomain,
52
54
  normalizeFederatedAcct: (acct) => acct,
53
55
  domainFromAcct: (acct) => acct.split('@')[1],
54
- firstStringUrl: () => undefined,
56
+ ...(!overrides.defaultImageReader && { firstStringUrl: () => undefined }),
55
57
  store: {
56
58
  findActorByUri: async (uri) => {
57
59
  findActorByUriCalls.push(uri);
58
60
  return overrides.cached ?? null;
59
61
  },
60
- upsertActor: async () => null,
62
+ upsertActor: async (_uri, update) => {
63
+ overrides.onUpsert?.(update);
64
+ return null;
65
+ },
61
66
  findActorByPublicKeyId: async () => overrides.cachedKey ?? null,
62
67
  setActorOxyUserId: async () => {},
63
68
  tombstoneActor: async () => null,
@@ -164,6 +169,37 @@ describe('getOrFetchActor — instance domain policy', () => {
164
169
  });
165
170
  });
166
171
 
172
+ describe('fetchRemoteActor — every JSON-LD shape of a field', () => {
173
+ it('keeps a single alias, a single profile field, an icon list and a +0000 date', async () => {
174
+ const actor = JSON.stringify({
175
+ id: ALLOWED_ACTOR,
176
+ inbox: 'https://remote.example/inbox',
177
+ preferredUsername: 'bob',
178
+ alsoKnownAs: 'https://old.example/users/bob',
179
+ attachment: { type: 'PropertyValue', name: 'Site', value: 'bob.example' },
180
+ icon: [{ type: 'Image', url: { type: 'Link', href: 'https://remote.example/a.png' } }],
181
+ published: '2020-05-01T10:00:00+0000',
182
+ });
183
+ let upserted: Record<string, unknown> | undefined;
184
+ const rig = makeResolver({
185
+ defaultImageReader: true,
186
+ signedFetch: async (url) =>
187
+ url === ALLOWED_ACTOR ? new Response(actor) : new Response(null, { status: 404 }),
188
+ onUpsert: (update) => {
189
+ upserted = update as Record<string, unknown>;
190
+ },
191
+ });
192
+
193
+ await rig.resolver.fetchRemoteActor(ALLOWED_ACTOR);
194
+ expect(upserted).toMatchObject({
195
+ alsoKnownAs: ['https://old.example/users/bob'],
196
+ fields: [{ name: 'Site', value: 'bob.example' }],
197
+ avatarUrl: 'https://remote.example/a.png',
198
+ remoteCreatedAt: new Date('2020-05-01T10:00:00Z'),
199
+ });
200
+ });
201
+ });
202
+
167
203
  describe('fetchPublicKey — signature lookups stay honest', () => {
168
204
  it('serves a cached key for a blocked domain, so its signature is judged on merit', async () => {
169
205
  const rig = makeResolver({ cachedKey: { uri: BLOCKED_ACTOR, publicKeyPem: 'PEM' } });
@@ -0,0 +1,93 @@
1
+ import {
2
+ apDate,
3
+ apImageUrl,
4
+ apIri,
5
+ apIriList,
6
+ apList,
7
+ apMediaTypeBase,
8
+ isActivityPubMediaType,
9
+ } from '../index';
10
+
11
+ describe('apList', () => {
12
+ it('reads a single value, a list and an absent value', () => {
13
+ const tag = { type: 'Mention', href: 'https://a.example/users/b' };
14
+ expect(apList(tag)).toEqual([tag]);
15
+ expect(apList([tag, null])).toEqual([tag]);
16
+ expect(apList(undefined)).toEqual([]);
17
+ expect(apList(null)).toEqual([]);
18
+ });
19
+ });
20
+
21
+ describe('apIri / apIriList', () => {
22
+ it('reads an IRI string, an embedded object id and a Link href', () => {
23
+ expect(apIri('https://a.example/u')).toBe('https://a.example/u');
24
+ expect(apIri({ id: 'https://a.example/f', totalItems: 3 })).toBe('https://a.example/f');
25
+ expect(apIri({ type: 'Link', href: 'https://a.example/l' })).toBe('https://a.example/l');
26
+ expect(apIri(['https://a.example/u'])).toBeUndefined();
27
+ expect(apIri('')).toBeUndefined();
28
+ });
29
+
30
+ it('lists every reference of a one-or-many property', () => {
31
+ expect(apIriList('https://a.example/u')).toEqual(['https://a.example/u']);
32
+ expect(apIriList(['https://a.example/u', { id: 'https://a.example/v' }, 7])).toEqual([
33
+ 'https://a.example/u',
34
+ 'https://a.example/v',
35
+ ]);
36
+ });
37
+ });
38
+
39
+ describe('apImageUrl', () => {
40
+ it('reads every icon shape', () => {
41
+ expect(apImageUrl('https://a.example/i.png')).toBe('https://a.example/i.png');
42
+ expect(apImageUrl({ type: 'Image', url: 'https://a.example/i.png' })).toBe(
43
+ 'https://a.example/i.png',
44
+ );
45
+ expect(
46
+ apImageUrl({ type: 'Image', url: { type: 'Link', href: 'https://a.example/l.png' } }),
47
+ ).toBe('https://a.example/l.png');
48
+ expect(
49
+ apImageUrl([
50
+ { type: 'Image', url: 'not a url' },
51
+ { type: 'Image', url: [{ href: 'https://a.example/big.png' }] },
52
+ ]),
53
+ ).toBe('https://a.example/big.png');
54
+ expect(apImageUrl({ type: 'Image' })).toBeUndefined();
55
+ });
56
+ });
57
+
58
+ describe('apMediaTypeBase / isActivityPubMediaType', () => {
59
+ it('compares the base type whatever the parameters', () => {
60
+ expect(apMediaTypeBase('Application/LD+JSON;profile=x')).toBe('application/ld+json');
61
+ expect(isActivityPubMediaType('application/activity+json')).toBe(true);
62
+ expect(
63
+ isActivityPubMediaType('application/ld+json;profile="https://www.w3.org/ns/activitystreams"'),
64
+ ).toBe(true);
65
+ expect(isActivityPubMediaType('text/html')).toBe(false);
66
+ expect(isActivityPubMediaType(undefined)).toBe(false);
67
+ });
68
+ });
69
+
70
+ describe('apDate', () => {
71
+ it('reads every ISO 8601 offset spelling as the same instant', () => {
72
+ const instant = '2024-01-01T12:00:00.000Z';
73
+ for (const value of [
74
+ '2024-01-01T12:00:00Z',
75
+ '2024-01-01T12:00:00+00:00',
76
+ '2024-01-01T12:00:00+0000',
77
+ '2024-01-01T12:00:00+00',
78
+ '2024-01-01 12:00:00Z',
79
+ '2024-01-01T12:00:00',
80
+ '2024-01-01T14:00:00+02',
81
+ ]) {
82
+ expect(apDate(value)?.toISOString()).toBe(instant);
83
+ }
84
+ });
85
+
86
+ it('names no date for garbage, and passes a valid Date through', () => {
87
+ expect(apDate('garbage')).toBeUndefined();
88
+ expect(apDate('2024-13-01T00:00:00Z')).toBeUndefined();
89
+ expect(apDate(42)).toBeUndefined();
90
+ const date = new Date('2024-01-01T00:00:00Z');
91
+ expect(apDate(date)).toBe(date);
92
+ });
93
+ });
@@ -517,9 +517,11 @@ describe('FEP-fffd proxyOf', () => {
517
517
  ).toEqual([]);
518
518
  });
519
519
 
520
- it('reads a missing or non-array proxyOf as none', () => {
520
+ it('reads a missing proxyOf as none and a single declaration as one', () => {
521
521
  expect(readProxyDeclarations(undefined)).toEqual([]);
522
- expect(readProxyDeclarations({ protocol: 'p', proxied: 'q' })).toEqual([]);
522
+ expect(readProxyDeclarations({ protocol: 'p', proxied: 'q' })).toEqual([
523
+ { protocol: 'p', proxied: 'q', authoritative: false },
524
+ ]);
523
525
  });
524
526
  });
525
527
 
package/src/apUri.ts CHANGED
@@ -72,21 +72,6 @@ export function isSameFederationHost(a: string, b: string): boolean {
72
72
  return canonicalA === canonicalFederationHost(b);
73
73
  }
74
74
 
75
- /**
76
- * The IRI a JSON-LD node reference names: the string itself, or the `id` of an
77
- * embedded object. ActivityStreams lets a server embed a referenced node (an
78
- * actor's `followers` collection with its `totalItems`, an `endpoints` value)
79
- * instead of linking it, and both mean the same node. Anything else names none.
80
- */
81
- export function apIri(value: unknown): string | undefined {
82
- if (typeof value === 'string') return value || undefined;
83
- if (value && typeof value === 'object' && !Array.isArray(value)) {
84
- const id = (value as { id?: unknown }).id;
85
- return typeof id === 'string' && id ? id : undefined;
86
- }
87
- return undefined;
88
- }
89
-
90
75
  /**
91
76
  * Given an ActivityPub activity/object ID (URL), extract the actor URI by
92
77
  * trimming everything from the first recognised post-path segment onward.