@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
package/dist/cjs/apUri.js
CHANGED
|
@@ -13,7 +13,6 @@
|
|
|
13
13
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
14
|
exports.canonicalFederationHost = canonicalFederationHost;
|
|
15
15
|
exports.isSameFederationHost = isSameFederationHost;
|
|
16
|
-
exports.apIri = apIri;
|
|
17
16
|
exports.extractActorUriFromActivityId = extractActorUriFromActivityId;
|
|
18
17
|
exports.createDomainPolicy = createDomainPolicy;
|
|
19
18
|
/** Path segments that typically separate an actor path from a post ID in ActivityPub URIs. */
|
|
@@ -76,21 +75,6 @@ function isSameFederationHost(a, b) {
|
|
|
76
75
|
return false;
|
|
77
76
|
return canonicalA === canonicalFederationHost(b);
|
|
78
77
|
}
|
|
79
|
-
/**
|
|
80
|
-
* The IRI a JSON-LD node reference names: the string itself, or the `id` of an
|
|
81
|
-
* embedded object. ActivityStreams lets a server embed a referenced node (an
|
|
82
|
-
* actor's `followers` collection with its `totalItems`, an `endpoints` value)
|
|
83
|
-
* instead of linking it, and both mean the same node. Anything else names none.
|
|
84
|
-
*/
|
|
85
|
-
function apIri(value) {
|
|
86
|
-
if (typeof value === 'string')
|
|
87
|
-
return value || undefined;
|
|
88
|
-
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
89
|
-
const id = value.id;
|
|
90
|
-
return typeof id === 'string' && id ? id : undefined;
|
|
91
|
-
}
|
|
92
|
-
return undefined;
|
|
93
|
-
}
|
|
94
78
|
/**
|
|
95
79
|
* Given an ActivityPub activity/object ID (URL), extract the actor URI by
|
|
96
80
|
* trimming everything from the first recognised post-path segment onward.
|
|
@@ -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.
|
|
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
|
|
@@ -89,8 +89,23 @@ var apUri_1 = require("./apUri");
|
|
|
89
89
|
Object.defineProperty(exports, "canonicalFederationHost", { enumerable: true, get: function () { return apUri_1.canonicalFederationHost; } });
|
|
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
|
-
Object.defineProperty(exports, "apIri", { enumerable: true, get: function () { return apUri_1.apIri; } });
|
|
93
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; } });
|
|
94
109
|
/**
|
|
95
110
|
* The single builder of a LOCAL user's ActivityPub actor document —
|
|
96
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
|
/**
|
|
@@ -51,46 +52,9 @@ const COLLECTION_BODY_MAX_BYTES = 64 * 1024;
|
|
|
51
52
|
*/
|
|
52
53
|
const COLLECTION_WITHHELD_STATUSES = new Set([401, 403, 404, 410]);
|
|
53
54
|
const ERROR_BODY_MAX_BYTES = 4 * 1024;
|
|
54
|
-
/**
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
* that stalls mid-body would hold the resolver open.
|
|
58
|
-
*/
|
|
59
|
-
const BODY_TIMEOUT_MS = 10000;
|
|
60
|
-
async function readBoundedResponseBody(res, maxBytes) {
|
|
61
|
-
const contentLength = res.headers.get('content-length');
|
|
62
|
-
if (contentLength) {
|
|
63
|
-
const declaredBytes = Number(contentLength);
|
|
64
|
-
if (Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {
|
|
65
|
-
await res.body?.cancel().catch(() => { });
|
|
66
|
-
throw new boundedBody_1.ResponseBodyTooLargeError(maxBytes);
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
if (!res.body)
|
|
70
|
-
return '';
|
|
71
|
-
const reader = res.body.getReader();
|
|
72
|
-
const body = await (0, boundedBody_1.readBodyChunks)({ read: () => reader.read(), cancel: () => void reader.cancel().catch(() => { }) }, { maxBytes, timeoutMs: BODY_TIMEOUT_MS });
|
|
73
|
-
return new TextDecoder('utf-8', { fatal: true }).decode(body);
|
|
74
|
-
}
|
|
75
|
-
async function readBoundedJson(res, maxBytes) {
|
|
76
|
-
const body = await readBoundedResponseBody(res, maxBytes);
|
|
77
|
-
// An empty body is a REMOTE's answer, not a parser error. Without this,
|
|
78
|
-
// `JSON.parse('')` throws a SyntaxError whose message names a column number,
|
|
79
|
-
// which is a worse thing to find in a federation log than the fact that the
|
|
80
|
-
// instance sent nothing.
|
|
81
|
-
if (body.length === 0)
|
|
82
|
-
throw new Error('Remote response has no body');
|
|
83
|
-
const value = JSON.parse(body);
|
|
84
|
-
const record = asRecord(value);
|
|
85
|
-
if (!record)
|
|
86
|
-
throw new Error('Remote response is not a JSON object');
|
|
87
|
-
return record;
|
|
88
|
-
}
|
|
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';
|
|
55
|
+
/** Whether a read produced a document the resolver can parse. */
|
|
56
|
+
function hasActorDocument(fetched) {
|
|
57
|
+
return fetched.status >= 200 && fetched.status < 300 && fetched.document !== undefined;
|
|
94
58
|
}
|
|
95
59
|
function asRecord(value) {
|
|
96
60
|
return value && typeof value === 'object' && !Array.isArray(value)
|
|
@@ -138,6 +102,22 @@ class ActorResolver {
|
|
|
138
102
|
/** Actor key refetches in flight, by actor URI: concurrent failed signatures share one. */
|
|
139
103
|
this.inFlightKeyRefetches = new Map();
|
|
140
104
|
}
|
|
105
|
+
/** One read of an actor document: the app's {@link ActorResolverConfig.fetchActorDocument}, or a signed GET. */
|
|
106
|
+
async readActorDocument(actorUri, acctHint) {
|
|
107
|
+
if (this.config.fetchActorDocument)
|
|
108
|
+
return this.config.fetchActorDocument(actorUri, acctHint);
|
|
109
|
+
const res = await this.config.signedFetch(actorUri, AP_CONTENT_TYPE);
|
|
110
|
+
if (res.ok) {
|
|
111
|
+
return {
|
|
112
|
+
status: res.status,
|
|
113
|
+
document: await (0, boundedBody_1.readBoundedResponseJson)(res, { maxBytes: ACTOR_BODY_MAX_BYTES }),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
if (res.status === 410)
|
|
117
|
+
return { status: res.status };
|
|
118
|
+
const body = await (0, boundedBody_1.readBoundedResponseText)(res, { maxBytes: ERROR_BODY_MAX_BYTES }).catch(() => '');
|
|
119
|
+
return { status: res.status, detail: `${res.statusText} body=${body.slice(0, 500)}`.trim() };
|
|
120
|
+
}
|
|
141
121
|
/**
|
|
142
122
|
* Whether an actor URI's host is refused by the instance domain policy. An
|
|
143
123
|
* unparseable URI has no host to check, so it is refused too — the policy is a
|
|
@@ -180,7 +160,7 @@ class ActorResolver {
|
|
|
180
160
|
const data = await this.config.fetchWebFinger(url);
|
|
181
161
|
if (!data)
|
|
182
162
|
return null;
|
|
183
|
-
const link = data.links?.find((l) => l.rel === 'self' &&
|
|
163
|
+
const link = data.links?.find((l) => l.rel === 'self' && (0, apValue_1.isActivityPubMediaType)(l.type));
|
|
184
164
|
return link?.href || null;
|
|
185
165
|
}
|
|
186
166
|
catch (err) {
|
|
@@ -210,19 +190,17 @@ class ActorResolver {
|
|
|
210
190
|
return null;
|
|
211
191
|
}
|
|
212
192
|
const canonicalAcctHint = this.config.normalizeFederatedAcct(acctHint);
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
if (!res.ok) {
|
|
193
|
+
let fetched = await this.readActorDocument(currentUri, canonicalAcctHint);
|
|
194
|
+
if (!hasActorDocument(fetched)) {
|
|
216
195
|
// A definitive 410 Gone is authoritative: tombstone and stop — do NOT fall
|
|
217
196
|
// through to the WebFinger fallback (which recovers a STALE/wrong URI on a
|
|
218
197
|
// transient failure, not a permanent removal). Only 410 does this.
|
|
219
|
-
if (
|
|
198
|
+
if (fetched.status === 410) {
|
|
220
199
|
this.config.logger.info(`[FedSync] fetchRemoteActor 410 Gone for ${currentUri} — tombstoning actor`);
|
|
221
200
|
await this.tombstoneGoneActor(currentUri);
|
|
222
201
|
return null;
|
|
223
202
|
}
|
|
224
|
-
|
|
225
|
-
this.config.logger.info(`[FedSync] fetchRemoteActor HTTP ${res.status} ${res.statusText} for ${currentUri} body=${body.slice(0, 500)}`);
|
|
203
|
+
this.config.logger.info(`[FedSync] fetchRemoteActor HTTP ${fetched.status}${fetched.detail ? ` ${fetched.detail}` : ''} for ${currentUri}`);
|
|
226
204
|
// If direct fetch failed, try WebFinger to resolve the canonical actor URI.
|
|
227
205
|
// Some servers (e.g., Threads) use numeric IDs in AP URIs that differ from
|
|
228
206
|
// the username-based URI we may have stored.
|
|
@@ -232,40 +210,32 @@ class ActorResolver {
|
|
|
232
210
|
(pathUsername
|
|
233
211
|
? this.config.normalizeFederatedAcct(`${pathUsername}@${parsed.hostname}`)
|
|
234
212
|
: undefined);
|
|
235
|
-
if (acct)
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
}
|
|
252
|
-
const body2 = await readBoundedResponseBody(res, ERROR_BODY_MAX_BYTES).catch(() => '');
|
|
253
|
-
this.config.logger.info(`[FedSync] fetchRemoteActor HTTP ${res.status} for resolved ${resolved} body=${body2.slice(0, 500)}`);
|
|
254
|
-
return null;
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
else {
|
|
258
|
-
this.config.logger.info(`[FedSync] WebFinger returned ${resolved ?? 'null'} for ${acct}`);
|
|
213
|
+
if (!acct)
|
|
214
|
+
return null;
|
|
215
|
+
this.config.logger.info(`[FedSync] attempting WebFinger fallback for ${acct}`);
|
|
216
|
+
const resolved = await this.resolveWebFinger(acct);
|
|
217
|
+
if (!resolved || resolved === currentUri) {
|
|
218
|
+
this.config.logger.info(`[FedSync] WebFinger returned ${resolved ?? 'null'} for ${acct}`);
|
|
219
|
+
return null;
|
|
220
|
+
}
|
|
221
|
+
this.config.logger.info(`[FedSync] WebFinger resolved ${acct} → ${resolved}`);
|
|
222
|
+
fetched = await this.readActorDocument(resolved, acct);
|
|
223
|
+
if (!hasActorDocument(fetched)) {
|
|
224
|
+
// A 410 on the WebFinger-RESOLVED URI is just as definitive. Tombstone
|
|
225
|
+
// against the stored URI.
|
|
226
|
+
if (fetched.status === 410) {
|
|
227
|
+
this.config.logger.info(`[FedSync] fetchRemoteActor 410 Gone for resolved ${resolved} — tombstoning actor ${currentUri}`);
|
|
228
|
+
await this.tombstoneGoneActor(currentUri);
|
|
259
229
|
return null;
|
|
260
230
|
}
|
|
261
|
-
|
|
262
|
-
else {
|
|
231
|
+
this.config.logger.info(`[FedSync] fetchRemoteActor HTTP ${fetched.status}${fetched.detail ? ` ${fetched.detail}` : ''} for resolved ${resolved}`);
|
|
263
232
|
return null;
|
|
264
233
|
}
|
|
234
|
+
currentUri = resolved;
|
|
265
235
|
}
|
|
266
|
-
const actor =
|
|
236
|
+
const actor = fetched.document;
|
|
267
237
|
const actorId = asString(actor.id);
|
|
268
|
-
const actorInbox = (0,
|
|
238
|
+
const actorInbox = (0, apValue_1.apIri)(actor.inbox);
|
|
269
239
|
if (!actorId || !actorInbox) {
|
|
270
240
|
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
241
|
return null;
|
|
@@ -306,34 +276,33 @@ class ActorResolver {
|
|
|
306
276
|
const actorPublicKey = asRecord(actor.publicKey);
|
|
307
277
|
// Fetch collection counts (followers, following, posts) in parallel
|
|
308
278
|
const [followersCount, followingCount, postsCount] = await Promise.all([
|
|
309
|
-
this.fetchCollectionCount((0,
|
|
310
|
-
this.fetchCollectionCount((0,
|
|
311
|
-
this.fetchCollectionCount((0,
|
|
279
|
+
this.fetchCollectionCount((0, apValue_1.apIri)(actor.followers)),
|
|
280
|
+
this.fetchCollectionCount((0, apValue_1.apIri)(actor.following)),
|
|
281
|
+
this.fetchCollectionCount((0, apValue_1.apIri)(actor.outbox)),
|
|
312
282
|
]);
|
|
313
283
|
// Extract profile fields (PropertyValue attachments). Sanitize BEFORE
|
|
314
284
|
// normalizing: the canonical normalizer collapses whitespace, it never
|
|
315
285
|
// strips markup — so the sanitizer must run first, on the raw value.
|
|
316
286
|
const fields = [];
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
});
|
|
333
|
-
}
|
|
287
|
+
for (const att of (0, apValue_1.apList)(actor.attachment)) {
|
|
288
|
+
const attRecord = asRecord(att);
|
|
289
|
+
if (!attRecord || attRecord.type !== 'PropertyValue')
|
|
290
|
+
continue;
|
|
291
|
+
const fieldName = this.config.text.inlineField(attRecord.name);
|
|
292
|
+
const fieldValue = typeof attRecord.value === 'string'
|
|
293
|
+
? this.config.text.sanitizeFieldValue(attRecord.value)
|
|
294
|
+
: '';
|
|
295
|
+
if (!fieldName || !fieldValue)
|
|
296
|
+
continue;
|
|
297
|
+
fields.push({
|
|
298
|
+
name: fieldName,
|
|
299
|
+
value: fieldValue,
|
|
300
|
+
verifiedAt: (0, apValue_1.apDate)(attRecord.verifiedAt),
|
|
301
|
+
});
|
|
334
302
|
}
|
|
335
|
-
const
|
|
336
|
-
const
|
|
303
|
+
const imageUrl = this.config.firstStringUrl ?? apValue_1.apImageUrl;
|
|
304
|
+
const avatarUrl = imageUrl(actor.icon);
|
|
305
|
+
const headerUrl = imageUrl(actor.image);
|
|
337
306
|
// `summary` is the actor's bio — a BODY, so its line breaks are the author's
|
|
338
307
|
// and must survive; `htmlToPlainText` normalizes it as multiline.
|
|
339
308
|
const summary = typeof actor.summary === 'string' ? this.config.text.htmlToPlainText(actor.summary) : '';
|
|
@@ -341,11 +310,13 @@ class ActorResolver {
|
|
|
341
310
|
// ` ` only becomes whitespace once decoded), THEN collapse.
|
|
342
311
|
const rawDisplayName = typeof actor.name === 'string' ? actor.name : '';
|
|
343
312
|
const displayName = this.config.text.inlineDisplayName(rawDisplayName) || username;
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
313
|
+
// Absent stays absent (the store keeps what it has); one alias or a list
|
|
314
|
+
// of them is the list.
|
|
315
|
+
const alsoKnownAs = actor.alsoKnownAs === undefined || actor.alsoKnownAs === null
|
|
316
|
+
? undefined
|
|
317
|
+
: (0, apValue_1.apIriList)(actor.alsoKnownAs);
|
|
347
318
|
// A move target is an actor URL; anything else is not one.
|
|
348
|
-
const movedToValue = (0,
|
|
319
|
+
const movedToValue = (0, apValue_1.apIri)(actor.movedTo);
|
|
349
320
|
const movedTo = movedToValue && /^https?:\/\//.test(movedToValue) ? movedToValue : undefined;
|
|
350
321
|
// The IDENTITY the actor is stored under in Oxy, which is not necessarily the
|
|
351
322
|
// host it was fetched from — see `DeriveNetworkIdentity`. Everything below
|
|
@@ -385,10 +356,10 @@ class ActorResolver {
|
|
|
385
356
|
avatarUrl,
|
|
386
357
|
headerUrl,
|
|
387
358
|
inboxUrl: actorInbox,
|
|
388
|
-
outboxUrl: (0,
|
|
389
|
-
sharedInboxUrl: (0,
|
|
390
|
-
followersUrl: (0,
|
|
391
|
-
followingUrl: (0,
|
|
359
|
+
outboxUrl: (0, apValue_1.apIri)(actor.outbox),
|
|
360
|
+
sharedInboxUrl: (0, apValue_1.apIri)(actorEndpoints?.sharedInbox),
|
|
361
|
+
followersUrl: (0, apValue_1.apIri)(actor.followers),
|
|
362
|
+
followingUrl: (0, apValue_1.apIri)(actor.following),
|
|
392
363
|
publicKeyPem: asString(actorPublicKey?.publicKeyPem) || undefined,
|
|
393
364
|
publicKeyId: asString(actorPublicKey?.id) || undefined,
|
|
394
365
|
type: asString(actor.type) || 'Person',
|
|
@@ -398,12 +369,12 @@ class ActorResolver {
|
|
|
398
369
|
memorial: actor.memorial === true,
|
|
399
370
|
suspended: actor.suspended === true,
|
|
400
371
|
fields,
|
|
401
|
-
featuredUrl: (0,
|
|
402
|
-
featuredTagsUrl: (0,
|
|
372
|
+
featuredUrl: (0, apValue_1.apIri)(actor.featured),
|
|
373
|
+
featuredTagsUrl: (0, apValue_1.apIri)(actor.featuredTags),
|
|
403
374
|
alsoKnownAs,
|
|
404
375
|
...(movedTo && { movedTo }),
|
|
405
376
|
networkAcct: networkIdentity?.federatedUsername,
|
|
406
|
-
remoteCreatedAt:
|
|
377
|
+
remoteCreatedAt: (0, apValue_1.apDate)(actor.published),
|
|
407
378
|
// Omitted, not written as `undefined`, when this refresh could not tell:
|
|
408
379
|
// an absent key is what tells the store to keep the value it has.
|
|
409
380
|
...(followersCount !== undefined && { followersCount }),
|
|
@@ -411,7 +382,7 @@ class ActorResolver {
|
|
|
411
382
|
...(postsCount !== undefined && { postsCount }),
|
|
412
383
|
lastFetchedAt: new Date(),
|
|
413
384
|
};
|
|
414
|
-
const fedActor = await this.config.store.upsertActor(actorId, update);
|
|
385
|
+
const fedActor = await this.config.store.upsertActor(actorId, update, fetched.source);
|
|
415
386
|
// Always upsert into Oxy so profile changes (avatar, name, bio) are synced.
|
|
416
387
|
// The identity bridge creates the federated Oxy user if it does not exist,
|
|
417
388
|
// updates it when changed, and mirrors the banner. This connector then stamps
|
|
@@ -548,7 +519,7 @@ class ActorResolver {
|
|
|
548
519
|
if (!res.ok) {
|
|
549
520
|
return COLLECTION_WITHHELD_STATUSES.has(res.status) ? null : undefined;
|
|
550
521
|
}
|
|
551
|
-
const col = await
|
|
522
|
+
const col = await (0, boundedBody_1.readBoundedResponseJson)(res, { maxBytes: COLLECTION_BODY_MAX_BYTES });
|
|
552
523
|
const total = col.totalItems;
|
|
553
524
|
return typeof total === 'number' && Number.isSafeInteger(total) && total >= 0 ? total : null;
|
|
554
525
|
}
|
|
@@ -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 =
|
|
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' });
|
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
14
|
exports.ResponseBodyTimeoutError = exports.ResponseBodyTooLargeError = void 0;
|
|
15
15
|
exports.readBodyChunks = readBodyChunks;
|
|
16
|
+
exports.readBoundedResponseText = readBoundedResponseText;
|
|
17
|
+
exports.readBoundedResponseJson = readBoundedResponseJson;
|
|
16
18
|
/** Thrown when a body exceeds its byte cap under `overflow: 'reject'`. */
|
|
17
19
|
class ResponseBodyTooLargeError extends Error {
|
|
18
20
|
constructor(maxBytes) {
|
|
@@ -75,3 +77,45 @@ async function readBodyChunks(source, limits) {
|
|
|
75
77
|
}
|
|
76
78
|
return Buffer.concat(chunks, total);
|
|
77
79
|
}
|
|
80
|
+
/** Deadline for a whole response body once its headers arrived, by default. */
|
|
81
|
+
const RESPONSE_BODY_TIMEOUT_MS = 10000;
|
|
82
|
+
/**
|
|
83
|
+
* A WHATWG `Response` body as UTF-8 text, within {@link ResponseBodyLimits}.
|
|
84
|
+
* A fetch's own timeout ends at the headers, so without the body deadline a
|
|
85
|
+
* remote that stalls mid-body would hold the reader open. A declared
|
|
86
|
+
* `Content-Length` over the cap is refused before any byte is read.
|
|
87
|
+
*/
|
|
88
|
+
async function readBoundedResponseText(res, limits) {
|
|
89
|
+
const { maxBytes, timeoutMs = RESPONSE_BODY_TIMEOUT_MS } = limits;
|
|
90
|
+
const contentLength = res.headers.get('content-length');
|
|
91
|
+
if (contentLength) {
|
|
92
|
+
const declaredBytes = Number(contentLength);
|
|
93
|
+
if (Number.isFinite(declaredBytes) && declaredBytes > maxBytes) {
|
|
94
|
+
await res.body?.cancel().catch(() => { });
|
|
95
|
+
throw new ResponseBodyTooLargeError(maxBytes);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (!res.body)
|
|
99
|
+
return '';
|
|
100
|
+
const reader = res.body.getReader();
|
|
101
|
+
const body = await readBodyChunks({ read: () => reader.read(), cancel: () => void reader.cancel().catch(() => { }) }, { maxBytes, timeoutMs });
|
|
102
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(body);
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* A WHATWG `Response` body as a JSON object, within {@link ResponseBodyLimits}.
|
|
106
|
+
* Throws when the body is empty, is not JSON, or is JSON but not an object.
|
|
107
|
+
*/
|
|
108
|
+
async function readBoundedResponseJson(res, limits) {
|
|
109
|
+
const body = await readBoundedResponseText(res, limits);
|
|
110
|
+
// An empty body is a REMOTE's answer, not a parser error. Without this,
|
|
111
|
+
// `JSON.parse('')` throws a SyntaxError whose message names a column number,
|
|
112
|
+
// which is a worse thing to find in a federation log than the fact that the
|
|
113
|
+
// instance sent nothing.
|
|
114
|
+
if (body.length === 0)
|
|
115
|
+
throw new Error('Remote response has no body');
|
|
116
|
+
const value = JSON.parse(body);
|
|
117
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
118
|
+
throw new Error('Remote response is not a JSON object');
|
|
119
|
+
}
|
|
120
|
+
return value;
|
|
121
|
+
}
|