@oxy.so/federation 2.16.0 → 3.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.
- package/dist/cjs/apUri.js +0 -16
- package/dist/cjs/apValue.js +164 -0
- package/dist/cjs/index.js +17 -2
- package/dist/cjs/networkIdentity.js +2 -3
- package/dist/cjs/node/actorResolver.js +81 -110
- package/dist/cjs/node/actorRouter.js +2 -1
- package/dist/cjs/node/boundedBody.js +44 -0
- package/dist/cjs/node/inboundDispatch.js +6 -15
- package/dist/cjs/node/index.js +11 -1
- package/dist/cjs/node/signedFetch.js +15 -5
- package/dist/esm/apUri.js +0 -15
- package/dist/esm/apValue.js +155 -0
- package/dist/esm/index.js +10 -1
- package/dist/esm/networkIdentity.js +2 -3
- package/dist/esm/node/actorResolver.js +72 -101
- package/dist/esm/node/actorRouter.js +2 -1
- package/dist/esm/node/boundedBody.js +42 -0
- package/dist/esm/node/inboundDispatch.js +6 -15
- package/dist/esm/node/index.js +6 -1
- package/dist/esm/node/signedFetch.js +14 -5
- package/dist/types/apUri.d.ts +0 -7
- package/dist/types/apValue.d.ts +75 -0
- package/dist/types/index.d.ts +15 -16
- package/dist/types/node/actorResolver.d.ts +53 -11
- package/dist/types/node/boundedBody.d.ts +19 -0
- package/dist/types/node/inboundDispatch.d.ts +1 -0
- package/dist/types/node/index.d.ts +7 -2
- package/dist/types/node/signedFetch.d.ts +23 -2
- package/package.json +1 -1
- package/src/__tests__/actorResolver.test.ts +90 -2
- package/src/__tests__/apValue.test.ts +93 -0
- package/src/__tests__/networkIdentity.test.ts +4 -2
- package/src/__tests__/signedFetch.test.ts +26 -3
- package/src/apUri.ts +0 -15
- package/src/apValue.ts +153 -0
- package/src/index.ts +23 -17
- package/src/networkIdentity.ts +2 -2
- package/src/node/actorResolver.ts +139 -123
- package/src/node/actorRouter.ts +2 -2
- package/src/node/boundedBody.ts +62 -0
- package/src/node/inboundDispatch.ts +6 -14
- package/src/node/index.ts +18 -0
- package/src/node/signedFetch.ts +44 -6
|
@@ -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 () =>
|
|
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' } });
|
|
@@ -285,3 +321,55 @@ describe('fetchRemoteActor — bounded remote bodies', () => {
|
|
|
285
321
|
expect(oversized.pulls()).toBeLessThan(15);
|
|
286
322
|
});
|
|
287
323
|
});
|
|
324
|
+
|
|
325
|
+
describe('fetchRemoteActor — an injected actor document source', () => {
|
|
326
|
+
it('reads the actor once from the source, hands its context to the store, and fetches only collections', async () => {
|
|
327
|
+
const signedFetchCalls: string[] = [];
|
|
328
|
+
const upserts: Array<{ uri: string; source: unknown }> = [];
|
|
329
|
+
const document = {
|
|
330
|
+
id: ALLOWED_ACTOR,
|
|
331
|
+
type: 'Person',
|
|
332
|
+
preferredUsername: 'bob',
|
|
333
|
+
inbox: `${ALLOWED_ACTOR}/inbox`,
|
|
334
|
+
followers: `${ALLOWED_ACTOR}/followers`,
|
|
335
|
+
};
|
|
336
|
+
const resolver = createActorResolver<TestActor, { verifiedBy: string }>({
|
|
337
|
+
federationEnabled: true,
|
|
338
|
+
signedFetch: async (url) => {
|
|
339
|
+
signedFetchCalls.push(url);
|
|
340
|
+
return new Response(JSON.stringify({ totalItems: 3 }), { status: 200 });
|
|
341
|
+
},
|
|
342
|
+
fetchActorDocument: async (uri) =>
|
|
343
|
+
uri === ALLOWED_ACTOR
|
|
344
|
+
? { status: 200, document, source: { verifiedBy: 'authority' } }
|
|
345
|
+
: { status: 404 },
|
|
346
|
+
fetchWebFinger: async () => null,
|
|
347
|
+
isBlockedDomain: () => false,
|
|
348
|
+
normalizeFederatedAcct: (acct) => acct,
|
|
349
|
+
domainFromAcct: (acct) => acct.split('@')[1],
|
|
350
|
+
store: {
|
|
351
|
+
findActorByUri: async () => null,
|
|
352
|
+
upsertActor: async (uri, update, source) => {
|
|
353
|
+
upserts.push({ uri, source });
|
|
354
|
+
expect(update.followersCount).toBe(3);
|
|
355
|
+
return { uri };
|
|
356
|
+
},
|
|
357
|
+
findActorByPublicKeyId: async () => null,
|
|
358
|
+
setActorOxyUserId: async () => {},
|
|
359
|
+
tombstoneActor: async () => null,
|
|
360
|
+
},
|
|
361
|
+
identity: { resolveExternalUser: async () => null, reportActorGone: async () => 'archived' },
|
|
362
|
+
text: {
|
|
363
|
+
inlineField: (value) => (typeof value === 'string' ? value : ''),
|
|
364
|
+
inlineDisplayName: (raw) => raw,
|
|
365
|
+
sanitizeFieldValue: (html) => html,
|
|
366
|
+
htmlToPlainText: (html) => html,
|
|
367
|
+
},
|
|
368
|
+
logger: { info: () => {}, warn: () => {} },
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
await expect(resolver.fetchRemoteActor(ALLOWED_ACTOR)).resolves.toEqual({ uri: ALLOWED_ACTOR });
|
|
372
|
+
expect(upserts).toEqual([{ uri: ALLOWED_ACTOR, source: { verifiedBy: 'authority' } }]);
|
|
373
|
+
expect(signedFetchCalls).toEqual([`${ALLOWED_ACTOR}/followers`]);
|
|
374
|
+
});
|
|
375
|
+
});
|
|
@@ -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
|
|
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
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createSignedFetcher, type SingleHopFetchInit } from '../node/signedFetch';
|
|
2
2
|
|
|
3
3
|
const INSTANCE_KEY = 'https://app.example/actor#main-key';
|
|
4
4
|
const ALICE_KEY = 'https://app.example/ap/users/alice#main-key';
|
|
@@ -6,7 +6,7 @@ const ALICE_KEY = 'https://app.example/ap/users/alice#main-key';
|
|
|
6
6
|
/** A signed fetch over a scripted transport, recording each hop's URL and signing keyId. */
|
|
7
7
|
function rig(responses: Response[]) {
|
|
8
8
|
const hops: Array<{ url: string; keyId: string | null }> = [];
|
|
9
|
-
const
|
|
9
|
+
const fetcher = createSignedFetcher({
|
|
10
10
|
sign: async () => 'sig',
|
|
11
11
|
getInstanceKeyId: async () => INSTANCE_KEY,
|
|
12
12
|
fetchSingleHop: async (url: string, init: SingleHopFetchInit) => {
|
|
@@ -17,7 +17,9 @@ function rig(responses: Response[]) {
|
|
|
17
17
|
},
|
|
18
18
|
userAgent: 'test',
|
|
19
19
|
});
|
|
20
|
-
|
|
20
|
+
const signedFetch = async (...args: Parameters<typeof fetcher>) =>
|
|
21
|
+
(await fetcher(...args)).response;
|
|
22
|
+
return { signedFetch, fetcher, hops };
|
|
21
23
|
}
|
|
22
24
|
|
|
23
25
|
it('signs as the instance and retries a 5xx unsigned', async () => {
|
|
@@ -57,3 +59,24 @@ it('signs every hop as the given actor and never retries an actor-signed request
|
|
|
57
59
|
expect(res.status).toBe(503);
|
|
58
60
|
expect(failing.hops).toHaveLength(1);
|
|
59
61
|
});
|
|
62
|
+
|
|
63
|
+
it('retries a redirected 5xx unsigned from where the redirect landed, and reports that URL', async () => {
|
|
64
|
+
const { fetcher, hops } = rig([
|
|
65
|
+
new Response(null, { status: 302, headers: { location: '/users/bob' } }),
|
|
66
|
+
new Response(null, { status: 502 }),
|
|
67
|
+
new Response('{}'),
|
|
68
|
+
]);
|
|
69
|
+
|
|
70
|
+
const { response, finalUrl } = await fetcher(
|
|
71
|
+
'https://remote.example/@bob',
|
|
72
|
+
'application/activity+json',
|
|
73
|
+
);
|
|
74
|
+
|
|
75
|
+
expect(response.status).toBe(200);
|
|
76
|
+
expect(finalUrl).toBe('https://remote.example/users/bob');
|
|
77
|
+
expect(hops).toEqual([
|
|
78
|
+
{ url: 'https://remote.example/@bob', keyId: INSTANCE_KEY },
|
|
79
|
+
{ url: 'https://remote.example/users/bob', keyId: INSTANCE_KEY },
|
|
80
|
+
{ url: 'https://remote.example/users/bob', keyId: null },
|
|
81
|
+
]);
|
|
82
|
+
});
|
package/src/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.
|
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
|
@@ -110,12 +110,29 @@ export {
|
|
|
110
110
|
canonicalFederationHost,
|
|
111
111
|
isSameFederationHost,
|
|
112
112
|
extractActorUriFromActivityId,
|
|
113
|
-
apIri,
|
|
114
113
|
createDomainPolicy,
|
|
115
114
|
type DomainPolicy,
|
|
116
115
|
type DomainPolicyConfig,
|
|
117
116
|
} from './apUri';
|
|
118
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
|
+
|
|
119
136
|
/**
|
|
120
137
|
* The single builder of a LOCAL user's ActivityPub actor document —
|
|
121
138
|
* byte-identical across apps, with media resolution injected. The actor `type`
|
|
@@ -160,9 +177,8 @@ export type NetworkId = 'activitypub' | 'atproto' | 'instagram-graph';
|
|
|
160
177
|
|
|
161
178
|
/**
|
|
162
179
|
* A remote actor normalized into a network-neutral shape. Built by a connector
|
|
163
|
-
* from its protocol's profile representation
|
|
164
|
-
*
|
|
165
|
-
* Oxy user the actor maps to.
|
|
180
|
+
* from its protocol's profile representation; `oxyUserId` carries the Oxy user
|
|
181
|
+
* the identity authority resolved it to.
|
|
166
182
|
*/
|
|
167
183
|
export interface NormalizedExternalActor {
|
|
168
184
|
network: NetworkId;
|
|
@@ -420,16 +436,12 @@ export type LocalNetworkEvent<TContent = unknown> =
|
|
|
420
436
|
targetActorUri: string;
|
|
421
437
|
};
|
|
422
438
|
|
|
423
|
-
/** Context passed alongside an inbound payload to {@link NetworkConnector.receive}. */
|
|
424
|
-
export interface ReceiveContext {
|
|
425
|
-
/** The remote actor URI/DID whose signature was already verified by the transport. */
|
|
426
|
-
verifiedActorUri: string;
|
|
427
|
-
}
|
|
428
|
-
|
|
429
439
|
/**
|
|
430
440
|
* The common contract every external network speaks behind. A connector owns all
|
|
431
441
|
* protocol specifics; the registry and the app's content core only ever see this
|
|
432
|
-
* surface.
|
|
442
|
+
* surface. Identity is not part of it: the identity authority (Oxy) resolves
|
|
443
|
+
* and verifies every external account, and inbound payloads reach the protocol's
|
|
444
|
+
* own inbox handler, never a connector-generic `receive`.
|
|
433
445
|
*
|
|
434
446
|
* Generic over the app's post-content type `TContent`, which flows through
|
|
435
447
|
* {@link NetworkConnector.deliver} on `post.create` / `post.update` events.
|
|
@@ -441,16 +453,10 @@ export interface NetworkConnector<TContent = unknown> {
|
|
|
441
453
|
readonly enabled: boolean;
|
|
442
454
|
/** True when `subject` (a handle / URI / DID) belongs to this network. */
|
|
443
455
|
matches(subject: string): boolean;
|
|
444
|
-
/** Resolve a handle to a normalized actor (webfinger for AP, handle→DID for atproto). */
|
|
445
|
-
resolve(handle: string): Promise<NormalizedExternalActor | null>;
|
|
446
456
|
/** Fetch + normalize an actor profile by its protocol id. */
|
|
447
457
|
fetchProfile(externalId: string): Promise<NormalizedExternalActor | null>;
|
|
448
458
|
/** Backfill + normalize an actor's recent posts. */
|
|
449
459
|
fetchPosts(externalId: string, opts?: FetchPostsOptions): Promise<FetchPostsResult>;
|
|
450
460
|
/** Deliver a local domain event outbound (federate to followers / write a record). */
|
|
451
461
|
deliver(event: LocalNetworkEvent<TContent>): Promise<void>;
|
|
452
|
-
/** Process an inbound payload (already actor-verified by the transport). */
|
|
453
|
-
receive(payload: unknown, ctx: ReceiveContext): Promise<void>;
|
|
454
|
-
/** Resolve/mint the Oxy user this external actor maps to; null when unresolvable. */
|
|
455
|
-
mapIdentity(actor: NormalizedExternalActor): Promise<string | null>;
|
|
456
462
|
}
|
package/src/networkIdentity.ts
CHANGED
|
@@ -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() : '';
|