@oxy.so/federation 3.2.0 → 3.2.2
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.
|
@@ -40,6 +40,22 @@ const ACTOR_STALE_MS = 24 * 60 * 60 * 1000; // 24 hours
|
|
|
40
40
|
* send a bad signature naming a real actor's keyId.
|
|
41
41
|
*/
|
|
42
42
|
const KEY_REFETCH_MIN_INTERVAL_MS = 60 * 1000; // 1 minute
|
|
43
|
+
/**
|
|
44
|
+
* How long a keyId's owner, once confirmed, is remembered in memory: the stored
|
|
45
|
+
* actor's `publicKeyId` is the durable record, this only spares a second fetch of
|
|
46
|
+
* the key document while that write lands or when the store does not keep it.
|
|
47
|
+
*/
|
|
48
|
+
const KEY_OWNER_TTL_MS = 60 * 60 * 1000; // 1 hour
|
|
49
|
+
/**
|
|
50
|
+
* How long a keyId whose owner could not be established is not asked again. A
|
|
51
|
+
* server delivering a burst of activities would otherwise have its key document
|
|
52
|
+
* fetched once per activity.
|
|
53
|
+
*/
|
|
54
|
+
const KEY_OWNER_FAILURE_TTL_MS = 60 * 1000; // 1 minute
|
|
55
|
+
/** Bound on the in-memory keyId → owner memory. */
|
|
56
|
+
const KEY_OWNER_CACHE_MAX = 2000;
|
|
57
|
+
/** Maximum decompressed size of a key document (a stub actor or a bare `Key`). */
|
|
58
|
+
const KEY_BODY_MAX_BYTES = 64 * 1024;
|
|
43
59
|
/** The AP content type asked for on signed actor/collection fetches. */
|
|
44
60
|
const AP_CONTENT_TYPE = 'application/activity+json';
|
|
45
61
|
/** Maximum decompressed response sizes accepted from untrusted federation hosts. */
|
|
@@ -88,6 +104,46 @@ function actorPublicKeyIsSelfConsistent(actor, actorId) {
|
|
|
88
104
|
return false;
|
|
89
105
|
return true;
|
|
90
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* The owner a key document names for `keyId`, or undefined when it names none.
|
|
109
|
+
*
|
|
110
|
+
* The document is either an actor (or GoToSocial's stub of one) whose `publicKey`
|
|
111
|
+
* is the key, a bare key object (`Key`, `CryptographicKey`) with an `owner`, or
|
|
112
|
+
* the actor itself, when it signs with its own URI as the keyId. Whatever it is, the key it
|
|
113
|
+
* describes must be `keyId`; a document about some other key names no owner of
|
|
114
|
+
* this one.
|
|
115
|
+
*/
|
|
116
|
+
function keyDocumentOwner(document, keyId) {
|
|
117
|
+
const publicKey = asRecord(document.publicKey);
|
|
118
|
+
if (publicKey && (0, apValue_1.apIri)(publicKey.id) === keyId) {
|
|
119
|
+
return (0, apValue_1.apIri)(publicKey.owner) ?? asString(document.id);
|
|
120
|
+
}
|
|
121
|
+
const documentId = asString(document.id);
|
|
122
|
+
if (documentId !== keyId)
|
|
123
|
+
return undefined;
|
|
124
|
+
// A bare key: it describes itself and names its owner.
|
|
125
|
+
const bareOwner = (0, apValue_1.apIri)(document.owner);
|
|
126
|
+
if (bareOwner)
|
|
127
|
+
return bareOwner;
|
|
128
|
+
// The actor itself, at the keyId (a server signing with the actor URI).
|
|
129
|
+
return publicKey ? documentId : undefined;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Whether an actor holds `keyId`, so its PEM may verify signatures naming it.
|
|
133
|
+
*
|
|
134
|
+
* A keyId that is a fragment (`<actor>#main-key`) names the document it is a
|
|
135
|
+
* fragment of: the actor was read from that very document, so the key it
|
|
136
|
+
* publishes is the one meant, and nothing more is asked (as before key documents
|
|
137
|
+
* were read at all). Any other keyId was resolved through a document of its own,
|
|
138
|
+
* which anyone on that origin can write; the owner it named holds the key only if
|
|
139
|
+
* the owner says so: its `publicKey.id` is the keyId, or the keyId is the actor's
|
|
140
|
+
* own URI.
|
|
141
|
+
*/
|
|
142
|
+
function actorClaimsKey(actor, keyId) {
|
|
143
|
+
if (keyId.includes('#'))
|
|
144
|
+
return true;
|
|
145
|
+
return actor.publicKeyId === keyId || actor.uri === keyId;
|
|
146
|
+
}
|
|
91
147
|
/**
|
|
92
148
|
* Resolution, caching and refresh of remote ActivityPub actors, over app-provided
|
|
93
149
|
* storage + identity + transports. A class so that internal cross-calls dispatch
|
|
@@ -101,6 +157,10 @@ class ActorResolver {
|
|
|
101
157
|
this.inFlightActorRefreshes = new Set();
|
|
102
158
|
/** Actor key refetches in flight, by actor URI: concurrent failed signatures share one. */
|
|
103
159
|
this.inFlightKeyRefetches = new Map();
|
|
160
|
+
/** Owners of keyIds resolved through their key document, remembered briefly. */
|
|
161
|
+
this.keyOwners = new Map();
|
|
162
|
+
/** Key documents being fetched, by keyId: concurrent signatures share one fetch. */
|
|
163
|
+
this.inFlightKeyOwners = new Map();
|
|
104
164
|
}
|
|
105
165
|
/** One read of an actor document: the app's {@link ActorResolverConfig.fetchActorDocument}, or a signed GET. */
|
|
106
166
|
async readActorDocument(actorUri, acctHint) {
|
|
@@ -614,21 +674,136 @@ class ActorResolver {
|
|
|
614
674
|
*/
|
|
615
675
|
async fetchPublicKey(keyId, options = {}) {
|
|
616
676
|
const stored = await this.config.store.findActorByPublicKeyId(keyId);
|
|
617
|
-
|
|
618
|
-
|
|
677
|
+
const actorUri = stored?.uri ?? (await this.resolveKeyOwner(keyId));
|
|
678
|
+
if (!actorUri)
|
|
679
|
+
return null;
|
|
619
680
|
if (options.refresh) {
|
|
620
681
|
const actor = await this.refetchActorKey(actorUri);
|
|
621
|
-
return actor?.publicKeyPem
|
|
682
|
+
return actor?.publicKeyPem && actorClaimsKey(actor, keyId)
|
|
683
|
+
? { publicKeyPem: actor.publicKeyPem, actorUri: actor.uri }
|
|
684
|
+
: null;
|
|
622
685
|
}
|
|
623
686
|
if (stored?.publicKeyPem) {
|
|
624
687
|
return { publicKeyPem: stored.publicKeyPem, actorUri: stored.uri };
|
|
625
688
|
}
|
|
626
|
-
// Fetch the actor to get the public key (uses 24h cache)
|
|
627
|
-
|
|
628
|
-
|
|
689
|
+
// Fetch the actor to get the public key (uses 24h cache). A cached actor that
|
|
690
|
+
// does not claim the key may be one that rotated to a new keyId since it was
|
|
691
|
+
// stored: it is read again, once, before the key is refused.
|
|
692
|
+
let actor = await this.getOrFetchActor(actorUri);
|
|
693
|
+
if (actor && !actorClaimsKey(actor, keyId))
|
|
694
|
+
actor = await this.refetchActorKey(actorUri);
|
|
695
|
+
if (!actor?.publicKeyPem || !actorClaimsKey(actor, keyId)) {
|
|
696
|
+
if (actor) {
|
|
697
|
+
this.config.logger.warn(`[FedSync] refusing key ${keyId}: its owner ${actor.uri} does not publish it`);
|
|
698
|
+
}
|
|
629
699
|
return null;
|
|
700
|
+
}
|
|
630
701
|
return { publicKeyPem: actor.publicKeyPem, actorUri: actor.uri };
|
|
631
702
|
}
|
|
703
|
+
/**
|
|
704
|
+
* The URI of the actor that owns `keyId`, or null when it cannot be told.
|
|
705
|
+
*
|
|
706
|
+
* A keyId that is a FRAGMENT of a document names that document as its owner:
|
|
707
|
+
* Mastodon, Misskey/Sharkey, Pleroma/Akkoma, PeerTube, Lemmy, Pixelfed and
|
|
708
|
+
* Threads all sign with `<actor>#main-key`, and the actor is the URI without
|
|
709
|
+
* the fragment. No key document is fetched.
|
|
710
|
+
*
|
|
711
|
+
* Any other keyId is a document of its own, and its owner is whatever that
|
|
712
|
+
* document names (Mastodon's `FetchRemoteKeyService` does the same):
|
|
713
|
+
* - GoToSocial: `<actor>/main-key`, a stub `Person` whose `publicKey`
|
|
714
|
+
* carries `{ id: keyId, owner: <actor> }` and no inbox;
|
|
715
|
+
* - a bare `Key`/`CryptographicKey` with `{ id: keyId, owner }`;
|
|
716
|
+
* - a server that signs with the actor URI itself: the
|
|
717
|
+
* document is the actor.
|
|
718
|
+
*
|
|
719
|
+
* The owner named here is only a candidate: it must be on the keyId's own
|
|
720
|
+
* origin, and {@link fetchPublicKey} uses it only once the owner's actor
|
|
721
|
+
* document publishes `keyId` as its key ({@link actorClaimsKey}). The PEM is
|
|
722
|
+
* always the owner's, never the key document's.
|
|
723
|
+
*/
|
|
724
|
+
async resolveKeyOwner(keyId) {
|
|
725
|
+
let parsed;
|
|
726
|
+
try {
|
|
727
|
+
parsed = new URL(keyId);
|
|
728
|
+
}
|
|
729
|
+
catch {
|
|
730
|
+
return null;
|
|
731
|
+
}
|
|
732
|
+
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:')
|
|
733
|
+
return null;
|
|
734
|
+
const hash = keyId.indexOf('#');
|
|
735
|
+
if (hash !== -1)
|
|
736
|
+
return keyId.slice(0, hash);
|
|
737
|
+
const remembered = this.keyOwners.get(keyId);
|
|
738
|
+
if (remembered && remembered.expiresAt > Date.now())
|
|
739
|
+
return remembered.owner;
|
|
740
|
+
// The keyId may already be a stored actor's own URI.
|
|
741
|
+
if (await this.config.store.findActorByUri(keyId))
|
|
742
|
+
return keyId;
|
|
743
|
+
// A blocked host is not asked for its key document, as `getOrFetchActor` would not
|
|
744
|
+
// be asked for its actor.
|
|
745
|
+
if (this.isBlockedActorUri(keyId))
|
|
746
|
+
return null;
|
|
747
|
+
let inFlight = this.inFlightKeyOwners.get(keyId);
|
|
748
|
+
if (!inFlight) {
|
|
749
|
+
inFlight = this.readKeyOwner(keyId)
|
|
750
|
+
.then((owner) => {
|
|
751
|
+
this.rememberKeyOwner(keyId, owner);
|
|
752
|
+
return owner;
|
|
753
|
+
})
|
|
754
|
+
.finally(() => {
|
|
755
|
+
this.inFlightKeyOwners.delete(keyId);
|
|
756
|
+
});
|
|
757
|
+
this.inFlightKeyOwners.set(keyId, inFlight);
|
|
758
|
+
}
|
|
759
|
+
return inFlight;
|
|
760
|
+
}
|
|
761
|
+
rememberKeyOwner(keyId, owner) {
|
|
762
|
+
if (this.keyOwners.size >= KEY_OWNER_CACHE_MAX) {
|
|
763
|
+
const now = Date.now();
|
|
764
|
+
for (const [id, entry] of this.keyOwners) {
|
|
765
|
+
if (entry.expiresAt <= now)
|
|
766
|
+
this.keyOwners.delete(id);
|
|
767
|
+
}
|
|
768
|
+
// Still full of live entries: drop the oldest (Map keeps insertion order).
|
|
769
|
+
if (this.keyOwners.size >= KEY_OWNER_CACHE_MAX) {
|
|
770
|
+
const oldest = this.keyOwners.keys().next().value;
|
|
771
|
+
if (oldest !== undefined)
|
|
772
|
+
this.keyOwners.delete(oldest);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
this.keyOwners.delete(keyId);
|
|
776
|
+
this.keyOwners.set(keyId, {
|
|
777
|
+
owner,
|
|
778
|
+
expiresAt: Date.now() + (owner ? KEY_OWNER_TTL_MS : KEY_OWNER_FAILURE_TTL_MS),
|
|
779
|
+
});
|
|
780
|
+
}
|
|
781
|
+
/** Fetch the key document at `keyId` and read the owner it names (see {@link resolveKeyOwner}). */
|
|
782
|
+
async readKeyOwner(keyId) {
|
|
783
|
+
let document;
|
|
784
|
+
try {
|
|
785
|
+
const res = await this.config.signedFetch(keyId, AP_CONTENT_TYPE);
|
|
786
|
+
if (!res.ok) {
|
|
787
|
+
this.config.logger.info(`[FedSync] key document ${keyId} answered HTTP ${res.status}`);
|
|
788
|
+
return null;
|
|
789
|
+
}
|
|
790
|
+
document = await (0, boundedBody_1.readBoundedResponseJson)(res, { maxBytes: KEY_BODY_MAX_BYTES });
|
|
791
|
+
}
|
|
792
|
+
catch (err) {
|
|
793
|
+
this.config.logger.warn(`[FedSync] could not fetch key document ${keyId}:`, err);
|
|
794
|
+
return null;
|
|
795
|
+
}
|
|
796
|
+
const owner = keyDocumentOwner(document, keyId);
|
|
797
|
+
if (!owner) {
|
|
798
|
+
this.config.logger.info(`[FedSync] key document ${keyId} names no owner for that key`);
|
|
799
|
+
return null;
|
|
800
|
+
}
|
|
801
|
+
if (!sameOriginUrl(owner, keyId)) {
|
|
802
|
+
this.config.logger.warn(`[FedSync] refusing key ${keyId}: its document names an owner on another origin, ${owner}`);
|
|
803
|
+
return null;
|
|
804
|
+
}
|
|
805
|
+
return owner;
|
|
806
|
+
}
|
|
632
807
|
/**
|
|
633
808
|
* Fetch `actorUri` again for its current key, or null when it was fetched too
|
|
634
809
|
* recently for that to tell anything new (see {@link KEY_REFETCH_MIN_INTERVAL_MS})
|
|
@@ -36,6 +36,22 @@ const ACTOR_STALE_MS = 24 * 60 * 60 * 1000; // 24 hours
|
|
|
36
36
|
* send a bad signature naming a real actor's keyId.
|
|
37
37
|
*/
|
|
38
38
|
const KEY_REFETCH_MIN_INTERVAL_MS = 60 * 1000; // 1 minute
|
|
39
|
+
/**
|
|
40
|
+
* How long a keyId's owner, once confirmed, is remembered in memory: the stored
|
|
41
|
+
* actor's `publicKeyId` is the durable record, this only spares a second fetch of
|
|
42
|
+
* the key document while that write lands or when the store does not keep it.
|
|
43
|
+
*/
|
|
44
|
+
const KEY_OWNER_TTL_MS = 60 * 60 * 1000; // 1 hour
|
|
45
|
+
/**
|
|
46
|
+
* How long a keyId whose owner could not be established is not asked again. A
|
|
47
|
+
* server delivering a burst of activities would otherwise have its key document
|
|
48
|
+
* fetched once per activity.
|
|
49
|
+
*/
|
|
50
|
+
const KEY_OWNER_FAILURE_TTL_MS = 60 * 1000; // 1 minute
|
|
51
|
+
/** Bound on the in-memory keyId → owner memory. */
|
|
52
|
+
const KEY_OWNER_CACHE_MAX = 2000;
|
|
53
|
+
/** Maximum decompressed size of a key document (a stub actor or a bare `Key`). */
|
|
54
|
+
const KEY_BODY_MAX_BYTES = 64 * 1024;
|
|
39
55
|
/** The AP content type asked for on signed actor/collection fetches. */
|
|
40
56
|
const AP_CONTENT_TYPE = 'application/activity+json';
|
|
41
57
|
/** Maximum decompressed response sizes accepted from untrusted federation hosts. */
|
|
@@ -84,6 +100,46 @@ function actorPublicKeyIsSelfConsistent(actor, actorId) {
|
|
|
84
100
|
return false;
|
|
85
101
|
return true;
|
|
86
102
|
}
|
|
103
|
+
/**
|
|
104
|
+
* The owner a key document names for `keyId`, or undefined when it names none.
|
|
105
|
+
*
|
|
106
|
+
* The document is either an actor (or GoToSocial's stub of one) whose `publicKey`
|
|
107
|
+
* is the key, a bare key object (`Key`, `CryptographicKey`) with an `owner`, or
|
|
108
|
+
* the actor itself, when it signs with its own URI as the keyId. Whatever it is, the key it
|
|
109
|
+
* describes must be `keyId`; a document about some other key names no owner of
|
|
110
|
+
* this one.
|
|
111
|
+
*/
|
|
112
|
+
function keyDocumentOwner(document, keyId) {
|
|
113
|
+
const publicKey = asRecord(document.publicKey);
|
|
114
|
+
if (publicKey && apIri(publicKey.id) === keyId) {
|
|
115
|
+
return apIri(publicKey.owner) ?? asString(document.id);
|
|
116
|
+
}
|
|
117
|
+
const documentId = asString(document.id);
|
|
118
|
+
if (documentId !== keyId)
|
|
119
|
+
return undefined;
|
|
120
|
+
// A bare key: it describes itself and names its owner.
|
|
121
|
+
const bareOwner = apIri(document.owner);
|
|
122
|
+
if (bareOwner)
|
|
123
|
+
return bareOwner;
|
|
124
|
+
// The actor itself, at the keyId (a server signing with the actor URI).
|
|
125
|
+
return publicKey ? documentId : undefined;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Whether an actor holds `keyId`, so its PEM may verify signatures naming it.
|
|
129
|
+
*
|
|
130
|
+
* A keyId that is a fragment (`<actor>#main-key`) names the document it is a
|
|
131
|
+
* fragment of: the actor was read from that very document, so the key it
|
|
132
|
+
* publishes is the one meant, and nothing more is asked (as before key documents
|
|
133
|
+
* were read at all). Any other keyId was resolved through a document of its own,
|
|
134
|
+
* which anyone on that origin can write; the owner it named holds the key only if
|
|
135
|
+
* the owner says so: its `publicKey.id` is the keyId, or the keyId is the actor's
|
|
136
|
+
* own URI.
|
|
137
|
+
*/
|
|
138
|
+
function actorClaimsKey(actor, keyId) {
|
|
139
|
+
if (keyId.includes('#'))
|
|
140
|
+
return true;
|
|
141
|
+
return actor.publicKeyId === keyId || actor.uri === keyId;
|
|
142
|
+
}
|
|
87
143
|
/**
|
|
88
144
|
* Resolution, caching and refresh of remote ActivityPub actors, over app-provided
|
|
89
145
|
* storage + identity + transports. A class so that internal cross-calls dispatch
|
|
@@ -97,6 +153,10 @@ export class ActorResolver {
|
|
|
97
153
|
this.inFlightActorRefreshes = new Set();
|
|
98
154
|
/** Actor key refetches in flight, by actor URI: concurrent failed signatures share one. */
|
|
99
155
|
this.inFlightKeyRefetches = new Map();
|
|
156
|
+
/** Owners of keyIds resolved through their key document, remembered briefly. */
|
|
157
|
+
this.keyOwners = new Map();
|
|
158
|
+
/** Key documents being fetched, by keyId: concurrent signatures share one fetch. */
|
|
159
|
+
this.inFlightKeyOwners = new Map();
|
|
100
160
|
}
|
|
101
161
|
/** One read of an actor document: the app's {@link ActorResolverConfig.fetchActorDocument}, or a signed GET. */
|
|
102
162
|
async readActorDocument(actorUri, acctHint) {
|
|
@@ -610,21 +670,136 @@ export class ActorResolver {
|
|
|
610
670
|
*/
|
|
611
671
|
async fetchPublicKey(keyId, options = {}) {
|
|
612
672
|
const stored = await this.config.store.findActorByPublicKeyId(keyId);
|
|
613
|
-
|
|
614
|
-
|
|
673
|
+
const actorUri = stored?.uri ?? (await this.resolveKeyOwner(keyId));
|
|
674
|
+
if (!actorUri)
|
|
675
|
+
return null;
|
|
615
676
|
if (options.refresh) {
|
|
616
677
|
const actor = await this.refetchActorKey(actorUri);
|
|
617
|
-
return actor?.publicKeyPem
|
|
678
|
+
return actor?.publicKeyPem && actorClaimsKey(actor, keyId)
|
|
679
|
+
? { publicKeyPem: actor.publicKeyPem, actorUri: actor.uri }
|
|
680
|
+
: null;
|
|
618
681
|
}
|
|
619
682
|
if (stored?.publicKeyPem) {
|
|
620
683
|
return { publicKeyPem: stored.publicKeyPem, actorUri: stored.uri };
|
|
621
684
|
}
|
|
622
|
-
// Fetch the actor to get the public key (uses 24h cache)
|
|
623
|
-
|
|
624
|
-
|
|
685
|
+
// Fetch the actor to get the public key (uses 24h cache). A cached actor that
|
|
686
|
+
// does not claim the key may be one that rotated to a new keyId since it was
|
|
687
|
+
// stored: it is read again, once, before the key is refused.
|
|
688
|
+
let actor = await this.getOrFetchActor(actorUri);
|
|
689
|
+
if (actor && !actorClaimsKey(actor, keyId))
|
|
690
|
+
actor = await this.refetchActorKey(actorUri);
|
|
691
|
+
if (!actor?.publicKeyPem || !actorClaimsKey(actor, keyId)) {
|
|
692
|
+
if (actor) {
|
|
693
|
+
this.config.logger.warn(`[FedSync] refusing key ${keyId}: its owner ${actor.uri} does not publish it`);
|
|
694
|
+
}
|
|
625
695
|
return null;
|
|
696
|
+
}
|
|
626
697
|
return { publicKeyPem: actor.publicKeyPem, actorUri: actor.uri };
|
|
627
698
|
}
|
|
699
|
+
/**
|
|
700
|
+
* The URI of the actor that owns `keyId`, or null when it cannot be told.
|
|
701
|
+
*
|
|
702
|
+
* A keyId that is a FRAGMENT of a document names that document as its owner:
|
|
703
|
+
* Mastodon, Misskey/Sharkey, Pleroma/Akkoma, PeerTube, Lemmy, Pixelfed and
|
|
704
|
+
* Threads all sign with `<actor>#main-key`, and the actor is the URI without
|
|
705
|
+
* the fragment. No key document is fetched.
|
|
706
|
+
*
|
|
707
|
+
* Any other keyId is a document of its own, and its owner is whatever that
|
|
708
|
+
* document names (Mastodon's `FetchRemoteKeyService` does the same):
|
|
709
|
+
* - GoToSocial: `<actor>/main-key`, a stub `Person` whose `publicKey`
|
|
710
|
+
* carries `{ id: keyId, owner: <actor> }` and no inbox;
|
|
711
|
+
* - a bare `Key`/`CryptographicKey` with `{ id: keyId, owner }`;
|
|
712
|
+
* - a server that signs with the actor URI itself: the
|
|
713
|
+
* document is the actor.
|
|
714
|
+
*
|
|
715
|
+
* The owner named here is only a candidate: it must be on the keyId's own
|
|
716
|
+
* origin, and {@link fetchPublicKey} uses it only once the owner's actor
|
|
717
|
+
* document publishes `keyId` as its key ({@link actorClaimsKey}). The PEM is
|
|
718
|
+
* always the owner's, never the key document's.
|
|
719
|
+
*/
|
|
720
|
+
async resolveKeyOwner(keyId) {
|
|
721
|
+
let parsed;
|
|
722
|
+
try {
|
|
723
|
+
parsed = new URL(keyId);
|
|
724
|
+
}
|
|
725
|
+
catch {
|
|
726
|
+
return null;
|
|
727
|
+
}
|
|
728
|
+
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:')
|
|
729
|
+
return null;
|
|
730
|
+
const hash = keyId.indexOf('#');
|
|
731
|
+
if (hash !== -1)
|
|
732
|
+
return keyId.slice(0, hash);
|
|
733
|
+
const remembered = this.keyOwners.get(keyId);
|
|
734
|
+
if (remembered && remembered.expiresAt > Date.now())
|
|
735
|
+
return remembered.owner;
|
|
736
|
+
// The keyId may already be a stored actor's own URI.
|
|
737
|
+
if (await this.config.store.findActorByUri(keyId))
|
|
738
|
+
return keyId;
|
|
739
|
+
// A blocked host is not asked for its key document, as `getOrFetchActor` would not
|
|
740
|
+
// be asked for its actor.
|
|
741
|
+
if (this.isBlockedActorUri(keyId))
|
|
742
|
+
return null;
|
|
743
|
+
let inFlight = this.inFlightKeyOwners.get(keyId);
|
|
744
|
+
if (!inFlight) {
|
|
745
|
+
inFlight = this.readKeyOwner(keyId)
|
|
746
|
+
.then((owner) => {
|
|
747
|
+
this.rememberKeyOwner(keyId, owner);
|
|
748
|
+
return owner;
|
|
749
|
+
})
|
|
750
|
+
.finally(() => {
|
|
751
|
+
this.inFlightKeyOwners.delete(keyId);
|
|
752
|
+
});
|
|
753
|
+
this.inFlightKeyOwners.set(keyId, inFlight);
|
|
754
|
+
}
|
|
755
|
+
return inFlight;
|
|
756
|
+
}
|
|
757
|
+
rememberKeyOwner(keyId, owner) {
|
|
758
|
+
if (this.keyOwners.size >= KEY_OWNER_CACHE_MAX) {
|
|
759
|
+
const now = Date.now();
|
|
760
|
+
for (const [id, entry] of this.keyOwners) {
|
|
761
|
+
if (entry.expiresAt <= now)
|
|
762
|
+
this.keyOwners.delete(id);
|
|
763
|
+
}
|
|
764
|
+
// Still full of live entries: drop the oldest (Map keeps insertion order).
|
|
765
|
+
if (this.keyOwners.size >= KEY_OWNER_CACHE_MAX) {
|
|
766
|
+
const oldest = this.keyOwners.keys().next().value;
|
|
767
|
+
if (oldest !== undefined)
|
|
768
|
+
this.keyOwners.delete(oldest);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
this.keyOwners.delete(keyId);
|
|
772
|
+
this.keyOwners.set(keyId, {
|
|
773
|
+
owner,
|
|
774
|
+
expiresAt: Date.now() + (owner ? KEY_OWNER_TTL_MS : KEY_OWNER_FAILURE_TTL_MS),
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
/** Fetch the key document at `keyId` and read the owner it names (see {@link resolveKeyOwner}). */
|
|
778
|
+
async readKeyOwner(keyId) {
|
|
779
|
+
let document;
|
|
780
|
+
try {
|
|
781
|
+
const res = await this.config.signedFetch(keyId, AP_CONTENT_TYPE);
|
|
782
|
+
if (!res.ok) {
|
|
783
|
+
this.config.logger.info(`[FedSync] key document ${keyId} answered HTTP ${res.status}`);
|
|
784
|
+
return null;
|
|
785
|
+
}
|
|
786
|
+
document = await readBoundedResponseJson(res, { maxBytes: KEY_BODY_MAX_BYTES });
|
|
787
|
+
}
|
|
788
|
+
catch (err) {
|
|
789
|
+
this.config.logger.warn(`[FedSync] could not fetch key document ${keyId}:`, err);
|
|
790
|
+
return null;
|
|
791
|
+
}
|
|
792
|
+
const owner = keyDocumentOwner(document, keyId);
|
|
793
|
+
if (!owner) {
|
|
794
|
+
this.config.logger.info(`[FedSync] key document ${keyId} names no owner for that key`);
|
|
795
|
+
return null;
|
|
796
|
+
}
|
|
797
|
+
if (!sameOriginUrl(owner, keyId)) {
|
|
798
|
+
this.config.logger.warn(`[FedSync] refusing key ${keyId}: its document names an owner on another origin, ${owner}`);
|
|
799
|
+
return null;
|
|
800
|
+
}
|
|
801
|
+
return owner;
|
|
802
|
+
}
|
|
628
803
|
/**
|
|
629
804
|
* Fetch `actorUri` again for its current key, or null when it was fetched too
|
|
630
805
|
* recently for that to tell anything new (see {@link KEY_REFETCH_MIN_INTERVAL_MS})
|
|
@@ -32,6 +32,12 @@ export interface FederatedActorRecordBase {
|
|
|
32
32
|
avatarUrl?: string;
|
|
33
33
|
headerUrl?: string;
|
|
34
34
|
publicKeyPem?: string;
|
|
35
|
+
/**
|
|
36
|
+
* The `publicKey.id` the actor published, which is the keyId its signatures
|
|
37
|
+
* name. Read to confirm that an actor claims a key whose id is not a fragment
|
|
38
|
+
* of the actor URI (GoToSocial's `…/users/x/main-key`).
|
|
39
|
+
*/
|
|
40
|
+
publicKeyId?: string;
|
|
35
41
|
lastFetchedAt?: Date | null;
|
|
36
42
|
}
|
|
37
43
|
/** A verified profile field (PropertyValue) stored on the actor cache. */
|
|
@@ -373,6 +379,35 @@ export declare class ActorResolver<TActor extends FederatedActorRecordBase, TSou
|
|
|
373
379
|
publicKeyPem: string;
|
|
374
380
|
actorUri: string;
|
|
375
381
|
} | null>;
|
|
382
|
+
/** Owners of keyIds resolved through their key document, remembered briefly. */
|
|
383
|
+
private readonly keyOwners;
|
|
384
|
+
/** Key documents being fetched, by keyId: concurrent signatures share one fetch. */
|
|
385
|
+
private readonly inFlightKeyOwners;
|
|
386
|
+
/**
|
|
387
|
+
* The URI of the actor that owns `keyId`, or null when it cannot be told.
|
|
388
|
+
*
|
|
389
|
+
* A keyId that is a FRAGMENT of a document names that document as its owner:
|
|
390
|
+
* Mastodon, Misskey/Sharkey, Pleroma/Akkoma, PeerTube, Lemmy, Pixelfed and
|
|
391
|
+
* Threads all sign with `<actor>#main-key`, and the actor is the URI without
|
|
392
|
+
* the fragment. No key document is fetched.
|
|
393
|
+
*
|
|
394
|
+
* Any other keyId is a document of its own, and its owner is whatever that
|
|
395
|
+
* document names (Mastodon's `FetchRemoteKeyService` does the same):
|
|
396
|
+
* - GoToSocial: `<actor>/main-key`, a stub `Person` whose `publicKey`
|
|
397
|
+
* carries `{ id: keyId, owner: <actor> }` and no inbox;
|
|
398
|
+
* - a bare `Key`/`CryptographicKey` with `{ id: keyId, owner }`;
|
|
399
|
+
* - a server that signs with the actor URI itself: the
|
|
400
|
+
* document is the actor.
|
|
401
|
+
*
|
|
402
|
+
* The owner named here is only a candidate: it must be on the keyId's own
|
|
403
|
+
* origin, and {@link fetchPublicKey} uses it only once the owner's actor
|
|
404
|
+
* document publishes `keyId` as its key ({@link actorClaimsKey}). The PEM is
|
|
405
|
+
* always the owner's, never the key document's.
|
|
406
|
+
*/
|
|
407
|
+
private resolveKeyOwner;
|
|
408
|
+
private rememberKeyOwner;
|
|
409
|
+
/** Fetch the key document at `keyId` and read the owner it names (see {@link resolveKeyOwner}). */
|
|
410
|
+
private readKeyOwner;
|
|
376
411
|
/**
|
|
377
412
|
* Fetch `actorUri` again for its current key, or null when it was fetched too
|
|
378
413
|
* recently for that to tell anything new (see {@link KEY_REFETCH_MIN_INTERVAL_MS})
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oxy.so/federation",
|
|
3
|
-
"version": "3.2.
|
|
3
|
+
"version": "3.2.2",
|
|
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",
|
|
@@ -89,7 +89,7 @@
|
|
|
89
89
|
"lint": "biome lint --error-on-warnings ./src"
|
|
90
90
|
},
|
|
91
91
|
"dependencies": {
|
|
92
|
-
"@oxy.so/contracts": "^1.0.0 || ^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || 4.11.0-oxy-one.0",
|
|
92
|
+
"@oxy.so/contracts": "^1.0.0 || ^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || 4.11.0-oxy-one.0",
|
|
93
93
|
"@oxy.so/core": "^6.14.0 || ^7.0.0"
|
|
94
94
|
},
|
|
95
95
|
"peerDependencies": {
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { signRequest, verifyHttpSignature } from '../httpSignature';
|
|
3
|
+
import {
|
|
4
|
+
createActorResolver,
|
|
5
|
+
type FederatedActorRecordBase,
|
|
6
|
+
type FederatedActorUpsert,
|
|
7
|
+
} from '../node/actorResolver';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Which actor owns a keyId (OxyHQ/oxy#2366).
|
|
11
|
+
*
|
|
12
|
+
* The resolver used to take the keyId minus its `#fragment` as the actor. That is
|
|
13
|
+
* Mastodon's shape and most servers copy it, but GoToSocial's keyId is a PATH,
|
|
14
|
+
* `<actor>/main-key`: the "actor" fetched was the key document, a stub with no
|
|
15
|
+
* inbox, so every GoToSocial activity was refused with a 401. The key document
|
|
16
|
+
* is now read for its owner, and the owner is believed only when its own actor
|
|
17
|
+
* document publishes the key.
|
|
18
|
+
*
|
|
19
|
+
* Each fixture is the shape the server really serves (keyId + documents).
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
interface TestActor extends FederatedActorRecordBase {
|
|
23
|
+
uri: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface Rig {
|
|
27
|
+
resolver: ReturnType<typeof createActorResolver<TestActor>>;
|
|
28
|
+
fetched: string[];
|
|
29
|
+
actors: Map<string, TestActor>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function actorDocument(id: string, keyId: string, pem: string): Record<string, unknown> {
|
|
33
|
+
return {
|
|
34
|
+
'@context': ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1'],
|
|
35
|
+
id,
|
|
36
|
+
type: 'Person',
|
|
37
|
+
preferredUsername: id.split('/').filter(Boolean).pop(),
|
|
38
|
+
inbox: `${id.replace(/\/$/, '')}/inbox`,
|
|
39
|
+
publicKey: { id: keyId, owner: id, publicKeyPem: pem },
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function makeRig(documents: Record<string, Record<string, unknown>>): Rig {
|
|
44
|
+
const fetched: string[] = [];
|
|
45
|
+
const actors = new Map<string, TestActor>();
|
|
46
|
+
const resolver = createActorResolver<TestActor>({
|
|
47
|
+
federationEnabled: true,
|
|
48
|
+
signedFetch: async (url) => {
|
|
49
|
+
fetched.push(url);
|
|
50
|
+
// A fragment never reaches the wire.
|
|
51
|
+
const document = documents[url.replace(/#.*$/, '')];
|
|
52
|
+
return document
|
|
53
|
+
? new Response(JSON.stringify(document), { status: 200 })
|
|
54
|
+
: new Response('not found', { status: 404 });
|
|
55
|
+
},
|
|
56
|
+
fetchWebFinger: async () => null,
|
|
57
|
+
isBlockedDomain: (host) => host === 'blocked.example',
|
|
58
|
+
normalizeFederatedAcct: (acct) => acct,
|
|
59
|
+
domainFromAcct: (acct) => acct.split('@')[1],
|
|
60
|
+
firstStringUrl: () => undefined,
|
|
61
|
+
store: {
|
|
62
|
+
findActorByUri: async (uri) => actors.get(uri) ?? null,
|
|
63
|
+
upsertActor: async (uri, update: FederatedActorUpsert) => {
|
|
64
|
+
const row: TestActor = {
|
|
65
|
+
uri,
|
|
66
|
+
acct: update.acct,
|
|
67
|
+
publicKeyPem: update.publicKeyPem,
|
|
68
|
+
publicKeyId: update.publicKeyId,
|
|
69
|
+
lastFetchedAt: update.lastFetchedAt,
|
|
70
|
+
};
|
|
71
|
+
actors.set(uri, row);
|
|
72
|
+
return row;
|
|
73
|
+
},
|
|
74
|
+
findActorByPublicKeyId: async (keyId) =>
|
|
75
|
+
[...actors.values()].find((actor) => actor.publicKeyId === keyId) ?? null,
|
|
76
|
+
setActorOxyUserId: async () => {},
|
|
77
|
+
tombstoneActor: async () => null,
|
|
78
|
+
},
|
|
79
|
+
identity: { resolveExternalUser: async () => null, reportActorGone: async () => 'archived' },
|
|
80
|
+
text: {
|
|
81
|
+
inlineField: (value) => (typeof value === 'string' ? value : ''),
|
|
82
|
+
inlineDisplayName: (raw) => raw,
|
|
83
|
+
sanitizeFieldValue: (html) => html,
|
|
84
|
+
htmlToPlainText: (html) => html,
|
|
85
|
+
},
|
|
86
|
+
logger: { info: () => {}, warn: () => {} },
|
|
87
|
+
});
|
|
88
|
+
return { resolver, fetched, actors };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Servers whose keyId is `<actor>#<fragment>`: the actor is read, nothing else. */
|
|
92
|
+
const FRAGMENT_SHAPES: Array<{ server: string; actor: string; keyId: string }> = [
|
|
93
|
+
{
|
|
94
|
+
server: 'Mastodon',
|
|
95
|
+
actor: 'https://mastodon.example/users/alice',
|
|
96
|
+
keyId: 'https://mastodon.example/users/alice#main-key',
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
server: 'Misskey / Sharkey',
|
|
100
|
+
actor: 'https://misskey.example/users/9x2k7q1abc',
|
|
101
|
+
keyId: 'https://misskey.example/users/9x2k7q1abc#main-key',
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
server: 'Pleroma / Akkoma',
|
|
105
|
+
actor: 'https://akkoma.example/users/alice',
|
|
106
|
+
keyId: 'https://akkoma.example/users/alice#main-key',
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
server: 'PeerTube',
|
|
110
|
+
actor: 'https://peertube.example/accounts/alice',
|
|
111
|
+
keyId: 'https://peertube.example/accounts/alice#main-key',
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
server: 'Lemmy',
|
|
115
|
+
actor: 'https://lemmy.example/u/alice',
|
|
116
|
+
keyId: 'https://lemmy.example/u/alice#main-key',
|
|
117
|
+
},
|
|
118
|
+
{
|
|
119
|
+
server: 'Threads',
|
|
120
|
+
actor: 'https://threads.example/ap/users/17841400000000000/',
|
|
121
|
+
keyId: 'https://threads.example/ap/users/17841400000000000/#main-key',
|
|
122
|
+
},
|
|
123
|
+
];
|
|
124
|
+
|
|
125
|
+
describe('fetchPublicKey — the owner of every real keyId shape', () => {
|
|
126
|
+
it.each(FRAGMENT_SHAPES)(
|
|
127
|
+
'$server: the keyId is a fragment of the actor, which is read directly',
|
|
128
|
+
async ({ actor, keyId }) => {
|
|
129
|
+
const rig = makeRig({ [actor]: actorDocument(actor, keyId, `PEM ${actor}`) });
|
|
130
|
+
await expect(rig.resolver.fetchPublicKey(keyId)).resolves.toEqual({
|
|
131
|
+
publicKeyPem: `PEM ${actor}`,
|
|
132
|
+
actorUri: actor,
|
|
133
|
+
});
|
|
134
|
+
expect(rig.fetched).toEqual([actor]);
|
|
135
|
+
},
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
it('GoToSocial: the keyId is a path, so the key document names the owner', async () => {
|
|
139
|
+
const actor = 'https://gts.example/users/fedqa';
|
|
140
|
+
const keyId = `${actor}/main-key`;
|
|
141
|
+
const rig = makeRig({
|
|
142
|
+
// What GoToSocial serves at the keyId: a stub `Person` with the key and no inbox.
|
|
143
|
+
[keyId]: {
|
|
144
|
+
'@context': ['https://w3id.org/security/v1', 'https://www.w3.org/ns/activitystreams'],
|
|
145
|
+
id: actor,
|
|
146
|
+
type: 'Person',
|
|
147
|
+
preferredUsername: 'fedqa',
|
|
148
|
+
publicKey: { id: keyId, owner: actor, publicKeyPem: 'STUB PEM' },
|
|
149
|
+
},
|
|
150
|
+
[actor]: actorDocument(actor, keyId, 'GTS PEM'),
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
await expect(rig.resolver.fetchPublicKey(keyId)).resolves.toEqual({
|
|
154
|
+
publicKeyPem: 'GTS PEM',
|
|
155
|
+
actorUri: actor,
|
|
156
|
+
});
|
|
157
|
+
expect(rig.fetched).toEqual([keyId, actor]);
|
|
158
|
+
|
|
159
|
+
// The stored actor now answers for the keyId: nothing is fetched again.
|
|
160
|
+
rig.fetched.length = 0;
|
|
161
|
+
await expect(rig.resolver.fetchPublicKey(keyId)).resolves.toEqual({
|
|
162
|
+
publicKeyPem: 'GTS PEM',
|
|
163
|
+
actorUri: actor,
|
|
164
|
+
});
|
|
165
|
+
expect(rig.fetched).toEqual([]);
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
it('a bare Key document names its owner', async () => {
|
|
169
|
+
const actor = 'https://keys.example/people/alice';
|
|
170
|
+
const keyId = 'https://keys.example/keys/alice-1';
|
|
171
|
+
const rig = makeRig({
|
|
172
|
+
[keyId]: { id: keyId, type: 'CryptographicKey', owner: actor, publicKeyPem: 'KEY PEM' },
|
|
173
|
+
[actor]: actorDocument(actor, keyId, 'ACTOR PEM'),
|
|
174
|
+
});
|
|
175
|
+
await expect(rig.resolver.fetchPublicKey(keyId)).resolves.toEqual({
|
|
176
|
+
publicKeyPem: 'ACTOR PEM',
|
|
177
|
+
actorUri: actor,
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
it('a keyId that is the actor URI itself is that actor', async () => {
|
|
182
|
+
const actor = 'https://plain.example/accounts/alice';
|
|
183
|
+
const rig = makeRig({ [actor]: actorDocument(actor, `${actor}#main-key`, 'PEM') });
|
|
184
|
+
await expect(rig.resolver.fetchPublicKey(actor)).resolves.toEqual({
|
|
185
|
+
publicKeyPem: 'PEM',
|
|
186
|
+
actorUri: actor,
|
|
187
|
+
});
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it('concurrent signatures with one keyId fetch its key document once', async () => {
|
|
191
|
+
const actor = 'https://gts.example/users/busy';
|
|
192
|
+
const keyId = `${actor}/main-key`;
|
|
193
|
+
const rig = makeRig({
|
|
194
|
+
[keyId]: { id: actor, type: 'Person', publicKey: { id: keyId, owner: actor } },
|
|
195
|
+
[actor]: actorDocument(actor, keyId, 'PEM'),
|
|
196
|
+
});
|
|
197
|
+
await Promise.all([rig.resolver.fetchPublicKey(keyId), rig.resolver.fetchPublicKey(keyId)]);
|
|
198
|
+
expect(rig.fetched.filter((url) => url === keyId)).toHaveLength(1);
|
|
199
|
+
});
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
describe('fetchPublicKey — a key is never believed without its owner', () => {
|
|
203
|
+
it('refuses a key whose named owner publishes a different key (forged owner)', async () => {
|
|
204
|
+
const victim = 'https://gts.example/users/alice';
|
|
205
|
+
const keyId = 'https://gts.example/users/mallory/main-key';
|
|
206
|
+
const rig = makeRig({
|
|
207
|
+
// Mallory's key document claims Alice as its owner...
|
|
208
|
+
[keyId]: {
|
|
209
|
+
id: 'https://gts.example/users/mallory',
|
|
210
|
+
type: 'Person',
|
|
211
|
+
publicKey: { id: keyId, owner: victim, publicKeyPem: 'MALLORY PEM' },
|
|
212
|
+
},
|
|
213
|
+
// ...but Alice publishes her own key, not Mallory's.
|
|
214
|
+
[victim]: actorDocument(victim, `${victim}/main-key`, 'ALICE PEM'),
|
|
215
|
+
});
|
|
216
|
+
await expect(rig.resolver.fetchPublicKey(keyId)).resolves.toBeNull();
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it('refuses an owner on another origin without fetching it', async () => {
|
|
220
|
+
const victim = 'https://victim.example/users/alice';
|
|
221
|
+
const keyId = 'https://evil.example/users/x/main-key';
|
|
222
|
+
const rig = makeRig({
|
|
223
|
+
[keyId]: { id: 'https://evil.example/users/x', publicKey: { id: keyId, owner: victim } },
|
|
224
|
+
[victim]: actorDocument(victim, keyId, 'ALICE PEM'),
|
|
225
|
+
});
|
|
226
|
+
await expect(rig.resolver.fetchPublicKey(keyId)).resolves.toBeNull();
|
|
227
|
+
expect(rig.fetched).toEqual([keyId]);
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
it('refuses a key document that describes some other key', async () => {
|
|
231
|
+
const actor = 'https://gts.example/users/alice';
|
|
232
|
+
const keyId = `${actor}/main-key`;
|
|
233
|
+
const rig = makeRig({
|
|
234
|
+
[keyId]: { id: actor, publicKey: { id: `${actor}/other-key`, owner: actor } },
|
|
235
|
+
[actor]: actorDocument(actor, keyId, 'PEM'),
|
|
236
|
+
});
|
|
237
|
+
await expect(rig.resolver.fetchPublicKey(keyId)).resolves.toBeNull();
|
|
238
|
+
expect(rig.fetched).toEqual([keyId]);
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
it('refuses a key document that cannot be fetched, and does not ask again at once', async () => {
|
|
242
|
+
const keyId = 'https://gone.example/users/alice/main-key';
|
|
243
|
+
const rig = makeRig({});
|
|
244
|
+
await expect(rig.resolver.fetchPublicKey(keyId)).resolves.toBeNull();
|
|
245
|
+
await expect(rig.resolver.fetchPublicKey(keyId)).resolves.toBeNull();
|
|
246
|
+
expect(rig.fetched).toEqual([keyId]);
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
it('does not fetch a key document on a blocked host', async () => {
|
|
250
|
+
const rig = makeRig({});
|
|
251
|
+
await expect(
|
|
252
|
+
rig.resolver.fetchPublicKey('https://blocked.example/users/x/main-key'),
|
|
253
|
+
).resolves.toBeNull();
|
|
254
|
+
expect(rig.fetched).toEqual([]);
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
it('on refresh, refuses an owner that no longer publishes the key', async () => {
|
|
258
|
+
const actor = 'https://gts.example/users/rotated';
|
|
259
|
+
const keyId = `${actor}/main-key`;
|
|
260
|
+
const documents: Record<string, Record<string, unknown>> = {
|
|
261
|
+
[keyId]: { id: actor, publicKey: { id: keyId, owner: actor } },
|
|
262
|
+
[actor]: actorDocument(actor, keyId, 'OLD PEM'),
|
|
263
|
+
};
|
|
264
|
+
const rig = makeRig(documents);
|
|
265
|
+
await expect(rig.resolver.fetchPublicKey(keyId)).resolves.toMatchObject({
|
|
266
|
+
publicKeyPem: 'OLD PEM',
|
|
267
|
+
});
|
|
268
|
+
// The actor moves to a new keyId; the old one must stop verifying.
|
|
269
|
+
documents[actor] = actorDocument(actor, `${actor}/main-key-2`, 'NEW PEM');
|
|
270
|
+
const stored = rig.actors.get(actor);
|
|
271
|
+
if (stored) stored.lastFetchedAt = new Date(0);
|
|
272
|
+
await expect(rig.resolver.fetchPublicKey(keyId, { refresh: true })).resolves.toBeNull();
|
|
273
|
+
});
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
describe('verifyHttpSignature — a GoToSocial delivery end to end', () => {
|
|
277
|
+
it('accepts a POST signed with a path keyId and attributes it to the owner', async () => {
|
|
278
|
+
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 });
|
|
279
|
+
const pem = publicKey.export({ type: 'spki', format: 'pem' }).toString();
|
|
280
|
+
const actor = 'https://gts.example/users/fedqa';
|
|
281
|
+
const keyId = `${actor}/main-key`;
|
|
282
|
+
const rig = makeRig({
|
|
283
|
+
[keyId]: {
|
|
284
|
+
id: actor,
|
|
285
|
+
type: 'Person',
|
|
286
|
+
publicKey: { id: keyId, owner: actor, publicKeyPem: pem },
|
|
287
|
+
},
|
|
288
|
+
[actor]: actorDocument(actor, keyId, pem),
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
const body = JSON.stringify({
|
|
292
|
+
type: 'Follow',
|
|
293
|
+
actor,
|
|
294
|
+
object: 'https://mention.earth/ap/users/qa',
|
|
295
|
+
});
|
|
296
|
+
const headers = await signRequest(
|
|
297
|
+
async (_keyId, signingString) =>
|
|
298
|
+
crypto.createSign('sha256').update(signingString).sign(privateKey, 'base64'),
|
|
299
|
+
keyId,
|
|
300
|
+
'POST',
|
|
301
|
+
'https://mention.earth/ap/inbox',
|
|
302
|
+
body,
|
|
303
|
+
);
|
|
304
|
+
const request = {
|
|
305
|
+
method: 'POST',
|
|
306
|
+
path: '/ap/inbox',
|
|
307
|
+
headers: {
|
|
308
|
+
...Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v])),
|
|
309
|
+
'content-type': 'application/activity+json',
|
|
310
|
+
},
|
|
311
|
+
body,
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
await expect(
|
|
315
|
+
verifyHttpSignature(request, (id, options) => rig.resolver.fetchPublicKey(id, options)),
|
|
316
|
+
).resolves.toEqual({ verified: true, actorUri: actor });
|
|
317
|
+
|
|
318
|
+
// The date and digest checks still apply to it.
|
|
319
|
+
await expect(
|
|
320
|
+
verifyHttpSignature({ ...request, body: `${body} ` }, (id) =>
|
|
321
|
+
rig.resolver.fetchPublicKey(id),
|
|
322
|
+
),
|
|
323
|
+
).resolves.toMatchObject({ verified: false, reason: 'digest-mismatch' });
|
|
324
|
+
});
|
|
325
|
+
});
|
|
@@ -50,6 +50,26 @@ const ACTOR_STALE_MS = 24 * 60 * 60 * 1000; // 24 hours
|
|
|
50
50
|
*/
|
|
51
51
|
const KEY_REFETCH_MIN_INTERVAL_MS = 60 * 1000; // 1 minute
|
|
52
52
|
|
|
53
|
+
/**
|
|
54
|
+
* How long a keyId's owner, once confirmed, is remembered in memory: the stored
|
|
55
|
+
* actor's `publicKeyId` is the durable record, this only spares a second fetch of
|
|
56
|
+
* the key document while that write lands or when the store does not keep it.
|
|
57
|
+
*/
|
|
58
|
+
const KEY_OWNER_TTL_MS = 60 * 60 * 1000; // 1 hour
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* How long a keyId whose owner could not be established is not asked again. A
|
|
62
|
+
* server delivering a burst of activities would otherwise have its key document
|
|
63
|
+
* fetched once per activity.
|
|
64
|
+
*/
|
|
65
|
+
const KEY_OWNER_FAILURE_TTL_MS = 60 * 1000; // 1 minute
|
|
66
|
+
|
|
67
|
+
/** Bound on the in-memory keyId → owner memory. */
|
|
68
|
+
const KEY_OWNER_CACHE_MAX = 2000;
|
|
69
|
+
|
|
70
|
+
/** Maximum decompressed size of a key document (a stub actor or a bare `Key`). */
|
|
71
|
+
const KEY_BODY_MAX_BYTES = 64 * 1024;
|
|
72
|
+
|
|
53
73
|
/** The AP content type asked for on signed actor/collection fetches. */
|
|
54
74
|
const AP_CONTENT_TYPE = 'application/activity+json';
|
|
55
75
|
|
|
@@ -73,6 +93,12 @@ export interface FederatedActorRecordBase {
|
|
|
73
93
|
avatarUrl?: string;
|
|
74
94
|
headerUrl?: string;
|
|
75
95
|
publicKeyPem?: string;
|
|
96
|
+
/**
|
|
97
|
+
* The `publicKey.id` the actor published, which is the keyId its signatures
|
|
98
|
+
* name. Read to confirm that an actor claims a key whose id is not a fragment
|
|
99
|
+
* of the actor URI (GoToSocial's `…/users/x/main-key`).
|
|
100
|
+
*/
|
|
101
|
+
publicKeyId?: string;
|
|
76
102
|
lastFetchedAt?: Date | null;
|
|
77
103
|
}
|
|
78
104
|
|
|
@@ -355,6 +381,48 @@ function actorPublicKeyIsSelfConsistent(actor: Record<string, unknown>, actorId:
|
|
|
355
381
|
return true;
|
|
356
382
|
}
|
|
357
383
|
|
|
384
|
+
/**
|
|
385
|
+
* The owner a key document names for `keyId`, or undefined when it names none.
|
|
386
|
+
*
|
|
387
|
+
* The document is either an actor (or GoToSocial's stub of one) whose `publicKey`
|
|
388
|
+
* is the key, a bare key object (`Key`, `CryptographicKey`) with an `owner`, or
|
|
389
|
+
* the actor itself, when it signs with its own URI as the keyId. Whatever it is, the key it
|
|
390
|
+
* describes must be `keyId`; a document about some other key names no owner of
|
|
391
|
+
* this one.
|
|
392
|
+
*/
|
|
393
|
+
function keyDocumentOwner(document: Record<string, unknown>, keyId: string): string | undefined {
|
|
394
|
+
const publicKey = asRecord(document.publicKey);
|
|
395
|
+
if (publicKey && apIri(publicKey.id) === keyId) {
|
|
396
|
+
return apIri(publicKey.owner) ?? asString(document.id);
|
|
397
|
+
}
|
|
398
|
+
const documentId = asString(document.id);
|
|
399
|
+
if (documentId !== keyId) return undefined;
|
|
400
|
+
// A bare key: it describes itself and names its owner.
|
|
401
|
+
const bareOwner = apIri(document.owner);
|
|
402
|
+
if (bareOwner) return bareOwner;
|
|
403
|
+
// The actor itself, at the keyId (a server signing with the actor URI).
|
|
404
|
+
return publicKey ? documentId : undefined;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Whether an actor holds `keyId`, so its PEM may verify signatures naming it.
|
|
409
|
+
*
|
|
410
|
+
* A keyId that is a fragment (`<actor>#main-key`) names the document it is a
|
|
411
|
+
* fragment of: the actor was read from that very document, so the key it
|
|
412
|
+
* publishes is the one meant, and nothing more is asked (as before key documents
|
|
413
|
+
* were read at all). Any other keyId was resolved through a document of its own,
|
|
414
|
+
* which anyone on that origin can write; the owner it named holds the key only if
|
|
415
|
+
* the owner says so: its `publicKey.id` is the keyId, or the keyId is the actor's
|
|
416
|
+
* own URI.
|
|
417
|
+
*/
|
|
418
|
+
function actorClaimsKey(
|
|
419
|
+
actor: Pick<FederatedActorRecordBase, 'uri' | 'publicKeyId'>,
|
|
420
|
+
keyId: string,
|
|
421
|
+
): boolean {
|
|
422
|
+
if (keyId.includes('#')) return true;
|
|
423
|
+
return actor.publicKeyId === keyId || actor.uri === keyId;
|
|
424
|
+
}
|
|
425
|
+
|
|
358
426
|
/**
|
|
359
427
|
* Resolution, caching and refresh of remote ActivityPub actors, over app-provided
|
|
360
428
|
* storage + identity + transports. A class so that internal cross-calls dispatch
|
|
@@ -947,25 +1015,148 @@ export class ActorResolver<TActor extends FederatedActorRecordBase, TSource = un
|
|
|
947
1015
|
options: FetchPublicKeyOptions = {},
|
|
948
1016
|
): Promise<{ publicKeyPem: string; actorUri: string } | null> {
|
|
949
1017
|
const stored = await this.config.store.findActorByPublicKeyId(keyId);
|
|
950
|
-
|
|
951
|
-
|
|
1018
|
+
const actorUri = stored?.uri ?? (await this.resolveKeyOwner(keyId));
|
|
1019
|
+
if (!actorUri) return null;
|
|
952
1020
|
|
|
953
1021
|
if (options.refresh) {
|
|
954
1022
|
const actor = await this.refetchActorKey(actorUri);
|
|
955
|
-
return actor?.publicKeyPem
|
|
1023
|
+
return actor?.publicKeyPem && actorClaimsKey(actor, keyId)
|
|
1024
|
+
? { publicKeyPem: actor.publicKeyPem, actorUri: actor.uri }
|
|
1025
|
+
: null;
|
|
956
1026
|
}
|
|
957
1027
|
|
|
958
1028
|
if (stored?.publicKeyPem) {
|
|
959
1029
|
return { publicKeyPem: stored.publicKeyPem, actorUri: stored.uri };
|
|
960
1030
|
}
|
|
961
1031
|
|
|
962
|
-
// Fetch the actor to get the public key (uses 24h cache)
|
|
963
|
-
|
|
964
|
-
|
|
1032
|
+
// Fetch the actor to get the public key (uses 24h cache). A cached actor that
|
|
1033
|
+
// does not claim the key may be one that rotated to a new keyId since it was
|
|
1034
|
+
// stored: it is read again, once, before the key is refused.
|
|
1035
|
+
let actor = await this.getOrFetchActor(actorUri);
|
|
1036
|
+
if (actor && !actorClaimsKey(actor, keyId)) actor = await this.refetchActorKey(actorUri);
|
|
1037
|
+
if (!actor?.publicKeyPem || !actorClaimsKey(actor, keyId)) {
|
|
1038
|
+
if (actor) {
|
|
1039
|
+
this.config.logger.warn(
|
|
1040
|
+
`[FedSync] refusing key ${keyId}: its owner ${actor.uri} does not publish it`,
|
|
1041
|
+
);
|
|
1042
|
+
}
|
|
1043
|
+
return null;
|
|
1044
|
+
}
|
|
965
1045
|
|
|
966
1046
|
return { publicKeyPem: actor.publicKeyPem, actorUri: actor.uri };
|
|
967
1047
|
}
|
|
968
1048
|
|
|
1049
|
+
/** Owners of keyIds resolved through their key document, remembered briefly. */
|
|
1050
|
+
private readonly keyOwners = new Map<string, { owner: string | null; expiresAt: number }>();
|
|
1051
|
+
|
|
1052
|
+
/** Key documents being fetched, by keyId: concurrent signatures share one fetch. */
|
|
1053
|
+
private readonly inFlightKeyOwners = new Map<string, Promise<string | null>>();
|
|
1054
|
+
|
|
1055
|
+
/**
|
|
1056
|
+
* The URI of the actor that owns `keyId`, or null when it cannot be told.
|
|
1057
|
+
*
|
|
1058
|
+
* A keyId that is a FRAGMENT of a document names that document as its owner:
|
|
1059
|
+
* Mastodon, Misskey/Sharkey, Pleroma/Akkoma, PeerTube, Lemmy, Pixelfed and
|
|
1060
|
+
* Threads all sign with `<actor>#main-key`, and the actor is the URI without
|
|
1061
|
+
* the fragment. No key document is fetched.
|
|
1062
|
+
*
|
|
1063
|
+
* Any other keyId is a document of its own, and its owner is whatever that
|
|
1064
|
+
* document names (Mastodon's `FetchRemoteKeyService` does the same):
|
|
1065
|
+
* - GoToSocial: `<actor>/main-key`, a stub `Person` whose `publicKey`
|
|
1066
|
+
* carries `{ id: keyId, owner: <actor> }` and no inbox;
|
|
1067
|
+
* - a bare `Key`/`CryptographicKey` with `{ id: keyId, owner }`;
|
|
1068
|
+
* - a server that signs with the actor URI itself: the
|
|
1069
|
+
* document is the actor.
|
|
1070
|
+
*
|
|
1071
|
+
* The owner named here is only a candidate: it must be on the keyId's own
|
|
1072
|
+
* origin, and {@link fetchPublicKey} uses it only once the owner's actor
|
|
1073
|
+
* document publishes `keyId` as its key ({@link actorClaimsKey}). The PEM is
|
|
1074
|
+
* always the owner's, never the key document's.
|
|
1075
|
+
*/
|
|
1076
|
+
private async resolveKeyOwner(keyId: string): Promise<string | null> {
|
|
1077
|
+
let parsed: URL;
|
|
1078
|
+
try {
|
|
1079
|
+
parsed = new URL(keyId);
|
|
1080
|
+
} catch {
|
|
1081
|
+
return null;
|
|
1082
|
+
}
|
|
1083
|
+
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return null;
|
|
1084
|
+
const hash = keyId.indexOf('#');
|
|
1085
|
+
if (hash !== -1) return keyId.slice(0, hash);
|
|
1086
|
+
|
|
1087
|
+
const remembered = this.keyOwners.get(keyId);
|
|
1088
|
+
if (remembered && remembered.expiresAt > Date.now()) return remembered.owner;
|
|
1089
|
+
|
|
1090
|
+
// The keyId may already be a stored actor's own URI.
|
|
1091
|
+
if (await this.config.store.findActorByUri(keyId)) return keyId;
|
|
1092
|
+
|
|
1093
|
+
// A blocked host is not asked for its key document, as `getOrFetchActor` would not
|
|
1094
|
+
// be asked for its actor.
|
|
1095
|
+
if (this.isBlockedActorUri(keyId)) return null;
|
|
1096
|
+
|
|
1097
|
+
let inFlight = this.inFlightKeyOwners.get(keyId);
|
|
1098
|
+
if (!inFlight) {
|
|
1099
|
+
inFlight = this.readKeyOwner(keyId)
|
|
1100
|
+
.then((owner) => {
|
|
1101
|
+
this.rememberKeyOwner(keyId, owner);
|
|
1102
|
+
return owner;
|
|
1103
|
+
})
|
|
1104
|
+
.finally(() => {
|
|
1105
|
+
this.inFlightKeyOwners.delete(keyId);
|
|
1106
|
+
});
|
|
1107
|
+
this.inFlightKeyOwners.set(keyId, inFlight);
|
|
1108
|
+
}
|
|
1109
|
+
return inFlight;
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
private rememberKeyOwner(keyId: string, owner: string | null): void {
|
|
1113
|
+
if (this.keyOwners.size >= KEY_OWNER_CACHE_MAX) {
|
|
1114
|
+
const now = Date.now();
|
|
1115
|
+
for (const [id, entry] of this.keyOwners) {
|
|
1116
|
+
if (entry.expiresAt <= now) this.keyOwners.delete(id);
|
|
1117
|
+
}
|
|
1118
|
+
// Still full of live entries: drop the oldest (Map keeps insertion order).
|
|
1119
|
+
if (this.keyOwners.size >= KEY_OWNER_CACHE_MAX) {
|
|
1120
|
+
const oldest = this.keyOwners.keys().next().value;
|
|
1121
|
+
if (oldest !== undefined) this.keyOwners.delete(oldest);
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
this.keyOwners.delete(keyId);
|
|
1125
|
+
this.keyOwners.set(keyId, {
|
|
1126
|
+
owner,
|
|
1127
|
+
expiresAt: Date.now() + (owner ? KEY_OWNER_TTL_MS : KEY_OWNER_FAILURE_TTL_MS),
|
|
1128
|
+
});
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
/** Fetch the key document at `keyId` and read the owner it names (see {@link resolveKeyOwner}). */
|
|
1132
|
+
private async readKeyOwner(keyId: string): Promise<string | null> {
|
|
1133
|
+
let document: Record<string, unknown>;
|
|
1134
|
+
try {
|
|
1135
|
+
const res = await this.config.signedFetch(keyId, AP_CONTENT_TYPE);
|
|
1136
|
+
if (!res.ok) {
|
|
1137
|
+
this.config.logger.info(`[FedSync] key document ${keyId} answered HTTP ${res.status}`);
|
|
1138
|
+
return null;
|
|
1139
|
+
}
|
|
1140
|
+
document = await readBoundedResponseJson(res, { maxBytes: KEY_BODY_MAX_BYTES });
|
|
1141
|
+
} catch (err) {
|
|
1142
|
+
this.config.logger.warn(`[FedSync] could not fetch key document ${keyId}:`, err);
|
|
1143
|
+
return null;
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
const owner = keyDocumentOwner(document, keyId);
|
|
1147
|
+
if (!owner) {
|
|
1148
|
+
this.config.logger.info(`[FedSync] key document ${keyId} names no owner for that key`);
|
|
1149
|
+
return null;
|
|
1150
|
+
}
|
|
1151
|
+
if (!sameOriginUrl(owner, keyId)) {
|
|
1152
|
+
this.config.logger.warn(
|
|
1153
|
+
`[FedSync] refusing key ${keyId}: its document names an owner on another origin, ${owner}`,
|
|
1154
|
+
);
|
|
1155
|
+
return null;
|
|
1156
|
+
}
|
|
1157
|
+
return owner;
|
|
1158
|
+
}
|
|
1159
|
+
|
|
969
1160
|
/**
|
|
970
1161
|
* Fetch `actorUri` again for its current key, or null when it was fetched too
|
|
971
1162
|
* recently for that to tell anything new (see {@link KEY_REFETCH_MIN_INTERVAL_MS})
|