maka-agent 0.2.0-dev.15.20260902 → 0.2.0-dev.16.20260903
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/cli-core.js +0 -1
- package/dist/pi-transcript.js +48 -0
- package/dist/pi-tui-form-interaction.js +497 -0
- package/dist/pi-tui-pickers.js +256 -55
- package/dist/pi-tui-runner.js +215 -12
- package/dist/runtime-host-cli.js +17 -42
- package/dist/runtime-host-lifecycle-transaction.js +31 -13
- package/dist/runtime-host-managed-lifecycle-manager.js +1 -1
- package/dist/runtime-host-onboarding.js +3 -1
- package/dist/runtime-host-openrc-service.js +469 -0
- package/dist/runtime-host-run-command.js +6 -2
- package/dist/runtime-host-service-command.js +3 -3
- package/dist/runtime-host-service-management-command.js +43 -15
- package/dist/runtime-host-session-channel.js +3 -0
- package/dist/runtime-host-session-driver.js +21 -6
- package/dist/runtime-host-setup-command.js +30 -31
- package/dist/tui-context-refresh.js +103 -0
- package/dist/tui-copy-catalog.js +73 -0
- package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
- package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
- package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
- package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
- package/node_modules/@maka/core/dist/chat-model-choice.js +4 -0
- package/node_modules/@maka/core/dist/computer-use.js +27 -92
- package/node_modules/@maka/core/dist/interaction.js +577 -3
- package/node_modules/@maka/core/dist/llm-connections.js +4 -0
- package/node_modules/@maka/core/dist/local-memory.js +2 -2
- package/node_modules/@maka/core/dist/model-call-usage-projection.js +3 -0
- package/node_modules/@maka/core/dist/model-metadata.js +26 -7
- package/node_modules/@maka/core/dist/model-thinking.js +17 -0
- package/node_modules/@maka/core/dist/provider-registry.js +1 -0
- package/node_modules/@maka/core/dist/runtime-event.js +23 -1
- package/node_modules/@maka/core/dist/scheduled-task.js +4 -0
- package/node_modules/@maka/core/dist/session.js +95 -2
- package/node_modules/@maka/core/dist/text-sanitize.js +19 -0
- package/node_modules/@maka/core/dist/usage-ledger-merge.js +3 -0
- package/node_modules/@maka/core/dist/usage-record-schema.js +11 -5
- package/node_modules/@maka/core/dist/workhub-creation-intent.js +75 -9
- package/node_modules/@maka/core/dist/workhub-session-resolver.js +50 -0
- package/node_modules/@maka/core/package.json +2 -0
- package/node_modules/@maka/eval/dist/harbor-external-subject.js +2 -1
- package/node_modules/@maka/eval/dist/harness-executor.js +3 -2
- package/node_modules/@maka/eval/dist/install-preflight.js +39 -10
- package/node_modules/@maka/eval/dist/process-termination.js +83 -0
- package/node_modules/@maka/mcp/dist/sep-2243.js +3 -3
- package/node_modules/@maka/runtime/dist/agent-run.js +6 -3
- package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +332 -118
- package/node_modules/@maka/runtime/dist/ai-sdk-compaction-contract.js +6 -1
- package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +171 -341
- package/node_modules/@maka/runtime/dist/bots/telegram-bridge.js +3 -26
- package/node_modules/@maka/runtime/dist/bundled-skill-catalog.generated.js +1 -1
- package/node_modules/@maka/runtime/dist/computer-use-codec.js +1 -141
- package/node_modules/@maka/runtime/dist/computer-use-tools.js +23 -105
- package/node_modules/@maka/runtime/dist/context-budget-policy.js +20 -26
- package/node_modules/@maka/runtime/dist/context-budget.js +18 -20
- package/node_modules/@maka/runtime/dist/conversation-copy.js +23 -19
- package/node_modules/@maka/runtime/dist/cua-frame-state.js +1 -69
- package/node_modules/@maka/runtime/dist/github-copilot-oauth-enrollment.js +267 -0
- package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +6 -9
- package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +67 -23
- package/node_modules/@maka/runtime/dist/history-compact-summary-validation.js +11 -18
- package/node_modules/@maka/runtime/dist/history-compaction.js +66 -73
- package/node_modules/@maka/runtime/dist/interaction-authority.js +69 -0
- package/node_modules/@maka/runtime/dist/mcp-tools.js +13 -1
- package/node_modules/@maka/runtime/dist/memory-extraction.js +11 -11
- package/node_modules/@maka/runtime/dist/model-adapter.js +24 -6
- package/node_modules/@maka/runtime/dist/model-factory.js +14 -5
- package/node_modules/@maka/runtime/dist/oauth-provider-contracts.js +28 -1
- package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +7 -6
- package/node_modules/@maka/runtime/dist/opencode-session-header.js +29 -0
- package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +11 -1
- package/node_modules/@maka/runtime/dist/runtime-kernel.js +12 -11
- package/node_modules/@maka/runtime/dist/runtime-read-model.js +51 -13
- package/node_modules/@maka/runtime/dist/scheduled-task-tools.js +3 -0
- package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +26 -0
- package/node_modules/@maka/runtime/dist/session-manager.js +1 -0
- package/node_modules/@maka/runtime/dist/session-projection-helpers.js +16 -1
- package/node_modules/@maka/runtime/dist/stream-graph-projection.js +6 -0
- package/node_modules/@maka/runtime/dist/stream-graph-read-model.js +5 -0
- package/node_modules/@maka/runtime/dist/stream-usage-fallback-fetch.js +74 -0
- package/node_modules/@maka/runtime/dist/subscription-credentials.js +51 -4
- package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +47 -3
- package/node_modules/@maka/runtime/dist/system-prompt/main-session-prompt.js +20 -1
- package/node_modules/@maka/runtime/dist/test-connection.js +18 -11
- package/node_modules/@maka/runtime/dist/tool-runtime.js +183 -0
- package/node_modules/@maka/runtime/package.json +1 -0
- package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +14 -0
- package/node_modules/@maka/runtime-host/dist/client/client-capability-channel.js +84 -1
- package/node_modules/@maka/runtime-host/dist/client/host-profile.js +68 -51
- package/node_modules/@maka/runtime-host/dist/client/index.js +1 -1
- package/node_modules/@maka/runtime-host/dist/client/owner-connection-code.js +8 -5
- package/node_modules/@maka/runtime-host/dist/client/peer-client.js +342 -36
- package/node_modules/@maka/runtime-host/dist/client/reconnect-lifecycle.js +60 -4
- package/node_modules/@maka/runtime-host/dist/peer-mesh/index.js +3 -3
- package/node_modules/@maka/runtime-host/dist/peer-mesh/limits.js +1 -1
- package/node_modules/@maka/runtime-host/dist/peer-mesh/model.js +48 -60
- package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +847 -431
- package/node_modules/@maka/runtime-host/dist/peer-mesh/owner.js +33 -74
- package/node_modules/@maka/runtime-host/dist/peer-mesh/store.js +82 -69
- package/node_modules/@maka/runtime-host/dist/peer-reachability/index.js +21 -0
- package/node_modules/@maka/runtime-host/dist/peer-reachability/model.js +202 -0
- package/node_modules/@maka/runtime-host/dist/peer-reachability/owner.js +119 -0
- package/node_modules/@maka/runtime-host/dist/peer-reachability/publisher.js +245 -0
- package/node_modules/@maka/runtime-host/dist/protocol/agent-graph.js +4 -1
- package/node_modules/@maka/runtime-host/dist/protocol/client-capability.js +68 -0
- package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +15 -8
- package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +7 -23
- package/node_modules/@maka/runtime-host/dist/protocol/index.js +47 -1
- package/node_modules/@maka/runtime-host/dist/protocol/oauth.js +25 -1
- package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
- package/node_modules/@maka/runtime-host/dist/protocol/peer-mesh.js +14 -31
- package/node_modules/@maka/runtime-host/dist/protocol/scheduled-task.js +19 -6
- package/node_modules/@maka/runtime-host/dist/protocol/session-collaboration.js +36 -1
- package/node_modules/@maka/runtime-host/dist/protocol/session-revision.js +11 -2
- package/node_modules/@maka/runtime-host/dist/protocol/usage-pricing.js +16 -2
- package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +51 -2
- package/node_modules/@maka/runtime-host/dist/server/access-authority.js +35 -2
- package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +1 -0
- package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +12 -10
- package/node_modules/@maka/runtime-host/dist/server/client-capability-invocation-broker.js +163 -30
- package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +38 -14
- package/node_modules/@maka/runtime-host/dist/server/daily-review-coordinator.js +45 -22
- package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +78 -20
- package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +4 -2
- package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +2 -1
- package/node_modules/@maka/runtime-host/dist/server/execution-service.js +49 -28
- package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +3 -6
- package/node_modules/@maka/runtime-host/dist/server/interaction-coordinator.js +130 -27
- package/node_modules/@maka/runtime-host/dist/server/interaction-projection.js +30 -1
- package/node_modules/@maka/runtime-host/dist/server/listener-set.js +2 -4
- package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +16 -3
- package/node_modules/@maka/runtime-host/dist/server/oauth-coordinator.js +66 -3
- package/node_modules/@maka/runtime-host/dist/server/oauth-execution-authority.js +20 -3
- package/node_modules/@maka/runtime-host/dist/server/peer-listener.js +8 -21
- package/node_modules/@maka/runtime-host/dist/server/peer-mesh-authority.js +1 -1
- package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +6 -3
- package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +72 -12
- package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +48 -18
- package/node_modules/@maka/runtime-host/dist/server/session-turn-access-request-coordinator.js +43 -26
- package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +15 -1
- package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +229 -4
- package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +146 -8
- package/node_modules/@maka/runtime-host/dist/transport/peer-native.js +32 -6
- package/node_modules/@maka/runtime-host/package.json +1 -0
- package/node_modules/@maka/storage/dist/agent-run-store.js +18 -5
- package/node_modules/@maka/storage/dist/codex-session-adapter.js +14 -0
- package/node_modules/@maka/storage/dist/execution-stores.js +5 -0
- package/node_modules/@maka/storage/dist/interaction-store.js +13 -1
- package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +9 -3
- package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +49 -19
- package/node_modules/@maka/storage/dist/runtime-policy/oauth-login-receipt-document.js +3 -1
- package/node_modules/@maka/storage/dist/runtime-policy/onboarding-transaction.js +13 -5
- package/node_modules/@maka/storage/dist/session-copy-cleanup.js +4 -2
- package/node_modules/@maka/storage/dist/session-store.js +39 -6
- package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +16 -9
- package/node_modules/@maka/storage/dist/sqlite-session-metadata-schema.js +30 -3
- package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +117 -0
- package/node_modules/@maka/storage/dist/sqlite-usage-store.js +29 -6
- package/node_modules/@maka/storage/dist/usage-stores.js +3 -1
- package/package.json +1 -1
|
@@ -16,24 +16,23 @@
|
|
|
16
16
|
* specific language governing permissions and limitations
|
|
17
17
|
* under the License.
|
|
18
18
|
*/
|
|
19
|
+
import { createHash } from 'node:crypto';
|
|
19
20
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
20
|
-
import {
|
|
21
|
+
import { performance } from 'node:perf_hooks';
|
|
22
|
+
import { canonicalPeerMeshMemberAdvertisement, canonicalPeerMeshRoster, createPeerMeshInvitationSecret, validatePeerMeshInvitation, decodeSignedPeerMeshMemberAdvertisement, decodeSignedPeerMeshRoster, generatePeerMeshAuthorityKeyPair, matchesPeerMeshInvitationSecret, PEER_MESH_MAX_MEMBERS, PEER_MESH_MAX_MESHES, PEER_MESH_MAX_INVITATION_RECORDS, PEER_MESH_MAX_PENDING_INVITATIONS, PEER_MESH_MAX_TRANSIT_ADDRESSES_PER_RELAY, PEER_MESH_MAX_TRANSIT_RELAY_ADDRESSES, peerMeshMemberAdvertisementSigningBytes, peerMeshId, peerMeshInvitationSecretDigest, signPeerMeshRoster, } from './model.js';
|
|
21
23
|
import { canonicalPeerMeshDisplayName } from './display-name.js';
|
|
24
|
+
import { authenticateSignedPeerReachabilityLease, decodeSignedPeerReachabilityLease, isPeerReachabilityLeaseCurrent, PEER_REACHABILITY_MAX_CLOCK_SKEW_MS, peerReachabilityLeaseSigningBytes, peerReachabilityLeaseReceipt, PEER_REACHABILITY_RECOVERY_HORIZON_MS, verifySignedPeerReachabilityLease, } from '../peer-reachability/index.js';
|
|
22
25
|
import { authorityKeys, isActivePeerMeshMembership as isActiveMembership, isRetiredPeerMeshState as isRetired, openPeerMeshStateStore, } from './store.js';
|
|
23
|
-
const CONTROL_FRAME_MAX_BYTES =
|
|
26
|
+
const CONTROL_FRAME_MAX_BYTES = 128 * 1024;
|
|
24
27
|
const DEFAULT_INVITATION_TTL_MS = 15 * 60 * 1_000;
|
|
25
28
|
const CONNECT_DEADLINE_MS = 30_000;
|
|
26
29
|
const CONTROL_REQUEST_DEADLINE_MS = 10_000;
|
|
27
30
|
const MAX_ACTIVE_CONTROL_STREAMS = 32;
|
|
28
31
|
const MAX_ACTIVE_CONTROL_STREAMS_PER_PEER = 2;
|
|
29
|
-
const
|
|
30
|
-
const ROUTE_REFRESH_LEAD_MS = 60 * 1_000;
|
|
31
|
-
const ROUTE_MAX_FUTURE_MS = 10 * 60 * 1_000;
|
|
32
|
-
const ROUTE_PAGE_SIZE = 8;
|
|
32
|
+
const EVIDENCE_PAGE_SIZE = 2;
|
|
33
33
|
const RECONCILE_CONCURRENCY = 4;
|
|
34
34
|
const RECONCILE_DEADLINE_MS = 60 * 1_000;
|
|
35
|
-
const RECONCILE_INTERVAL_MS =
|
|
36
|
-
const LOCAL_ROUTE_OBSERVATION_INTERVAL_MS = 1_000;
|
|
35
|
+
const RECONCILE_INTERVAL_MS = 5 * 60 * 1_000;
|
|
37
36
|
export async function openPeerMeshNode(input) {
|
|
38
37
|
const store = await openPeerMeshStateStore(input.dataRoot, input.peer.identity().peerId);
|
|
39
38
|
const node = new PeerMeshNodeImpl({ ...input, store });
|
|
@@ -49,28 +48,66 @@ export async function openPeerMeshNode(input) {
|
|
|
49
48
|
class PeerMeshNodeImpl {
|
|
50
49
|
#store;
|
|
51
50
|
#peer;
|
|
51
|
+
#reachability;
|
|
52
52
|
#endpointKind;
|
|
53
53
|
#now;
|
|
54
|
+
#monotonicNow;
|
|
54
55
|
#onBackgroundReconcileError;
|
|
55
56
|
#activeControlStreams = new Set();
|
|
56
57
|
#lifetime = new AbortController();
|
|
57
58
|
#admissionTail = Promise.resolve();
|
|
58
59
|
#reconcileTail = Promise.resolve();
|
|
60
|
+
#transitTail = Promise.resolve();
|
|
59
61
|
#reconcileCursor = 0;
|
|
60
62
|
#gossipCursor = 0;
|
|
61
|
-
#
|
|
63
|
+
#evidenceRefreshTask;
|
|
64
|
+
#unsubscribeReachability;
|
|
65
|
+
#reconcileGeneration = 0;
|
|
66
|
+
#reconcileWaiters = new Set();
|
|
67
|
+
#reachabilityReceipts = new Map();
|
|
68
|
+
#completedRecoverySweeps = new Set();
|
|
69
|
+
#routeResolutionListeners = new Map();
|
|
62
70
|
#serveTask;
|
|
63
71
|
#closeTask;
|
|
64
72
|
constructor(input) {
|
|
65
73
|
this.#store = input.store;
|
|
66
74
|
this.#peer = input.peer;
|
|
75
|
+
this.#reachability = input.reachability;
|
|
67
76
|
this.#endpointKind = input.endpointKind;
|
|
68
77
|
this.#now = input.now ?? Date.now;
|
|
78
|
+
this.#monotonicNow = input.monotonicNow ?? (input.now ? input.now : () => performance.now());
|
|
69
79
|
this.#onBackgroundReconcileError = input.onBackgroundReconcileError;
|
|
70
80
|
}
|
|
71
81
|
async initialize() {
|
|
72
|
-
|
|
73
|
-
|
|
82
|
+
const stored = this.#store.read();
|
|
83
|
+
const now = this.#now();
|
|
84
|
+
for (const lease of stored.reachability) {
|
|
85
|
+
const signed = authenticateSignedPeerReachabilityLease({
|
|
86
|
+
value: lease,
|
|
87
|
+
expectedPeerId: lease.lease.peerId,
|
|
88
|
+
verifyIdentity: this.#peer.verifyIdentity.bind(this.#peer),
|
|
89
|
+
});
|
|
90
|
+
if (usableHistoricalReachability(signed, now) &&
|
|
91
|
+
signed.lease.issuedAt <= now + PEER_REACHABILITY_MAX_CLOCK_SKEW_MS) {
|
|
92
|
+
this.#recordReachabilityReceipt(signed);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
for (const advertisement of stored.advertisements) {
|
|
96
|
+
this.#assertAdvertisementSignature(advertisement);
|
|
97
|
+
}
|
|
98
|
+
if (stored.reachability.some((signed) => !usableHistoricalReachability(signed, now))) {
|
|
99
|
+
await this.#store.mutate((current) => ({
|
|
100
|
+
state: {
|
|
101
|
+
...current,
|
|
102
|
+
reachability: current.reachability.filter((signed) => usableHistoricalReachability(signed, now)),
|
|
103
|
+
},
|
|
104
|
+
result: undefined,
|
|
105
|
+
}));
|
|
106
|
+
}
|
|
107
|
+
await this.#refreshLocalEvidence();
|
|
108
|
+
this.#unsubscribeReachability = this.#reachability.subscribe(() => {
|
|
109
|
+
this.#triggerReconciliation();
|
|
110
|
+
});
|
|
74
111
|
await this.#reconcileTransit();
|
|
75
112
|
}
|
|
76
113
|
localPeerId() {
|
|
@@ -87,21 +124,17 @@ class PeerMeshNodeImpl {
|
|
|
87
124
|
await this.#store.mutate(async (current) => {
|
|
88
125
|
if (current.displayName === canonical)
|
|
89
126
|
return { state: current, result: undefined };
|
|
90
|
-
const
|
|
91
|
-
const
|
|
92
|
-
if (!state.meshes.some((mesh) => isActiveMembership(mesh, localPeerId))) {
|
|
93
|
-
return { state, result: undefined };
|
|
94
|
-
}
|
|
95
|
-
const route = await this.#signLocalRoute(state);
|
|
127
|
+
const next = { ...current, displayName: canonical };
|
|
128
|
+
const advertisements = await this.#localAdvertisementsFor(next);
|
|
96
129
|
return {
|
|
97
130
|
state: {
|
|
98
|
-
...
|
|
99
|
-
|
|
131
|
+
...next,
|
|
132
|
+
advertisements: mergeAdvertisements(current.advertisements, advertisements),
|
|
100
133
|
},
|
|
101
134
|
result: undefined,
|
|
102
135
|
};
|
|
103
136
|
});
|
|
104
|
-
|
|
137
|
+
this.#triggerReconciliation();
|
|
105
138
|
});
|
|
106
139
|
}
|
|
107
140
|
setMeshDisplayName(meshId, displayName) {
|
|
@@ -120,17 +153,20 @@ class PeerMeshNodeImpl {
|
|
|
120
153
|
...(canonical ? { displayName: canonical } : {}),
|
|
121
154
|
}), authorityKeys(state));
|
|
122
155
|
return {
|
|
123
|
-
state: {
|
|
156
|
+
state: {
|
|
157
|
+
...current,
|
|
158
|
+
meshes: replaceMesh(current.meshes, { ...state, roster }),
|
|
159
|
+
},
|
|
124
160
|
result: {
|
|
125
161
|
roster,
|
|
126
|
-
targets: rosterAnnouncementTargets(state.roster.roster.members, current.
|
|
162
|
+
targets: rosterAnnouncementTargets(state.roster.roster.members, current.reachability, this.#peer.identity().peerId, this.#now()),
|
|
127
163
|
},
|
|
128
164
|
};
|
|
129
165
|
});
|
|
130
166
|
if (announcement)
|
|
131
167
|
this.#scheduleRosterAnnouncement(announcement.roster, announcement.targets);
|
|
132
168
|
const stored = this.#store.read();
|
|
133
|
-
return peerMeshStatus(requireAuthority(stored.meshes, meshId), this.#peer.identity(), this.#endpointKind, stored.
|
|
169
|
+
return peerMeshStatus(requireAuthority(stored.meshes, meshId), this.#peer.identity(), this.#endpointKind, stored.reachability, stored.advertisements, this.#now(), (peerId) => this.#peer.isConnected(peerId), (peerId) => this.resolveRoutes(peerId), (signed) => this.#isReachabilityCurrent(signed));
|
|
134
170
|
});
|
|
135
171
|
}
|
|
136
172
|
status() {
|
|
@@ -139,7 +175,7 @@ class PeerMeshNodeImpl {
|
|
|
139
175
|
const stored = this.#store.read();
|
|
140
176
|
return Object.freeze(stored.meshes
|
|
141
177
|
.filter((state) => state.roster.roster.closed || isActiveMembership(state, identity.peerId))
|
|
142
|
-
.map((state) => peerMeshStatus(state, identity, this.#endpointKind, stored.
|
|
178
|
+
.map((state) => peerMeshStatus(state, identity, this.#endpointKind, stored.reachability, stored.advertisements, this.#now(), (peerId) => this.#peer.isConnected(peerId), (peerId) => this.resolveRoutes(peerId), (signed) => this.#isReachabilityCurrent(signed))));
|
|
143
179
|
}
|
|
144
180
|
create() {
|
|
145
181
|
return this.#admitMesh(async () => {
|
|
@@ -148,6 +184,7 @@ class PeerMeshNodeImpl {
|
|
|
148
184
|
const roster = signPeerMeshRoster(canonicalPeerMeshRoster({
|
|
149
185
|
version: 1,
|
|
150
186
|
meshId: peerMeshId(keys.publicKey),
|
|
187
|
+
authorityPeerId: identity.peerId,
|
|
151
188
|
revision: 1,
|
|
152
189
|
members: [identity.peerId],
|
|
153
190
|
closed: false,
|
|
@@ -158,38 +195,34 @@ class PeerMeshNodeImpl {
|
|
|
158
195
|
authorityPrivateKey: keys.privateKey,
|
|
159
196
|
invitations: [],
|
|
160
197
|
};
|
|
161
|
-
const
|
|
198
|
+
const reachability = await this.#reachability.refresh();
|
|
162
199
|
const now = this.#now();
|
|
163
200
|
await this.#store.mutate((current) => {
|
|
164
201
|
assertMeshCapacity(current.meshes, identity.peerId, current.pendingJoins.length);
|
|
165
|
-
const currentLocalRoute = current.routes
|
|
166
|
-
.filter(({ route }) => route.peerId === identity.peerId)
|
|
167
|
-
.sort((left, right) => right.route.sequence - left.route.sequence)[0];
|
|
168
|
-
const localRoute = currentLocalRoute && currentLocalRoute.route.sequence >= signedRoute.route.sequence
|
|
169
|
-
? currentLocalRoute
|
|
170
|
-
: signedRoute;
|
|
171
202
|
return {
|
|
172
203
|
state: {
|
|
173
204
|
...current,
|
|
174
205
|
meshes: appendMesh(current.meshes, state, identity.peerId),
|
|
175
|
-
|
|
206
|
+
reachability: mergeReachability(current.reachability, [reachability], now),
|
|
176
207
|
},
|
|
177
208
|
result: undefined,
|
|
178
209
|
};
|
|
179
210
|
});
|
|
211
|
+
await this.#refreshLocalEvidence();
|
|
180
212
|
const stored = this.#store.read();
|
|
181
|
-
return peerMeshStatus(findMesh(stored.meshes, state.roster.roster.meshId), identity, this.#endpointKind, stored.
|
|
213
|
+
return peerMeshStatus(findMesh(stored.meshes, state.roster.roster.meshId), identity, this.#endpointKind, stored.reachability, stored.advertisements, now, (peerId) => this.#peer.isConnected(peerId), (peerId) => this.resolveRoutes(peerId), (signed) => this.#isReachabilityCurrent(signed));
|
|
182
214
|
});
|
|
183
215
|
}
|
|
184
|
-
invite(meshId, input = {}) {
|
|
216
|
+
async invite(meshId, input = {}) {
|
|
185
217
|
if (this.#lifetime.signal.aborted)
|
|
186
|
-
|
|
218
|
+
throw new Error('Peer Mesh node is closed');
|
|
187
219
|
const now = this.#now();
|
|
188
220
|
const identity = this.#peer.identity();
|
|
189
221
|
const ttlMs = input.ttlMs ?? DEFAULT_INVITATION_TTL_MS;
|
|
190
222
|
if (!Number.isSafeInteger(ttlMs) || ttlMs < 1_000 || ttlMs > 24 * 60 * 60 * 1_000) {
|
|
191
|
-
|
|
223
|
+
throw new Error('Peer Mesh invitation TTL must be between 1 second and 1 day');
|
|
192
224
|
}
|
|
225
|
+
const reachability = await this.#reachability.refresh();
|
|
193
226
|
return this.#store.mutate((current) => {
|
|
194
227
|
const state = requireAuthority(current.meshes, meshId);
|
|
195
228
|
if (state.roster.roster.closed)
|
|
@@ -202,14 +235,13 @@ class PeerMeshNodeImpl {
|
|
|
202
235
|
throw new Error('Peer Mesh has too many recent invitations');
|
|
203
236
|
const secret = createPeerMeshInvitationSecret();
|
|
204
237
|
const expiresAt = now + ttlMs;
|
|
205
|
-
const target = authorityTarget(identity);
|
|
206
238
|
const invitation = {
|
|
207
239
|
version: 1,
|
|
208
240
|
meshId: state.roster.roster.meshId,
|
|
209
241
|
authorityPublicKey: state.roster.authorityPublicKey,
|
|
210
242
|
secret,
|
|
211
243
|
expiresAt,
|
|
212
|
-
|
|
244
|
+
reachability,
|
|
213
245
|
};
|
|
214
246
|
return {
|
|
215
247
|
state: {
|
|
@@ -233,6 +265,7 @@ class PeerMeshNodeImpl {
|
|
|
233
265
|
join(invitationValue, signal) {
|
|
234
266
|
return this.#admitMesh(async () => {
|
|
235
267
|
const invitation = validatePeerMeshInvitation(invitationValue);
|
|
268
|
+
const authorityReachability = this.#authenticateReachability(invitation.reachability, invitation.reachability.lease.peerId, true);
|
|
236
269
|
const current = this.#store.read();
|
|
237
270
|
const existing = findMesh(current.meshes, invitation.meshId);
|
|
238
271
|
const pending = current.pendingJoins.find(({ invitation: candidate }) => candidate.meshId === invitation.meshId);
|
|
@@ -246,6 +279,10 @@ class PeerMeshNodeImpl {
|
|
|
246
279
|
if (existing?.role === 'authority') {
|
|
247
280
|
throw new Error('This peer already belongs to that Peer Mesh');
|
|
248
281
|
}
|
|
282
|
+
if (existing?.role === 'replica' &&
|
|
283
|
+
authorityReachability.lease.peerId !== existing.roster.roster.authorityPeerId) {
|
|
284
|
+
throw new Error('Peer Mesh repair invitation has the wrong authority identity');
|
|
285
|
+
}
|
|
249
286
|
assertRejoinSettled(existing, localPeerId);
|
|
250
287
|
if (pending && pending.invitation.secret !== invitation.secret) {
|
|
251
288
|
throw new Error('This Peer Mesh already has an unresolved join attempt');
|
|
@@ -263,12 +300,14 @@ class PeerMeshNodeImpl {
|
|
|
263
300
|
let joinIntentAdmitted = pending !== undefined;
|
|
264
301
|
try {
|
|
265
302
|
stream = await this.#peer.connectMeshControl({
|
|
266
|
-
|
|
267
|
-
routeHints: invitation.routeHints,
|
|
268
|
-
coordinationRelays: invitation.coordinationRelays,
|
|
303
|
+
...dialTarget(authorityReachability),
|
|
269
304
|
directDeadlineMs: CONNECT_DEADLINE_MS,
|
|
270
305
|
}, operationSignal);
|
|
271
|
-
|
|
306
|
+
if (stream.peerId !== authorityReachability.lease.peerId) {
|
|
307
|
+
throw new Error('Peer Mesh control stream has the wrong peer identity');
|
|
308
|
+
}
|
|
309
|
+
const localReachability = await this.#reachability.refresh();
|
|
310
|
+
const localAdvertisement = await this.#signLocalAdvertisement(invitation.meshId);
|
|
272
311
|
await this.#store.mutate((current) => {
|
|
273
312
|
const existing = findMesh(current.meshes, invitation.meshId);
|
|
274
313
|
if (existing?.role === 'authority') {
|
|
@@ -299,7 +338,7 @@ class PeerMeshNodeImpl {
|
|
|
299
338
|
};
|
|
300
339
|
});
|
|
301
340
|
joinIntentAdmitted = true;
|
|
302
|
-
return await this.#redeemPendingJoin(invitation,
|
|
341
|
+
return await this.#redeemPendingJoin(invitation, localReachability, localAdvertisement, stream, operationSignal);
|
|
303
342
|
}
|
|
304
343
|
catch (error) {
|
|
305
344
|
if (signal?.aborted && joinIntentAdmitted) {
|
|
@@ -314,8 +353,9 @@ class PeerMeshNodeImpl {
|
|
|
314
353
|
}
|
|
315
354
|
});
|
|
316
355
|
}
|
|
317
|
-
async #redeemPendingJoin(invitation,
|
|
356
|
+
async #redeemPendingJoin(invitation, localReachability, localAdvertisement, stream, signal) {
|
|
318
357
|
signal.throwIfAborted();
|
|
358
|
+
const authorityReachability = this.#authenticateReachability(invitation.reachability, invitation.reachability.lease.peerId, true);
|
|
319
359
|
const dispatch = await this.#store.mutate((current) => {
|
|
320
360
|
const pending = current.pendingJoins.find(({ invitation: candidate }) => candidate.meshId === invitation.meshId && candidate.secret === invitation.secret);
|
|
321
361
|
if (!pending) {
|
|
@@ -339,7 +379,8 @@ class PeerMeshNodeImpl {
|
|
|
339
379
|
kind: 'redeem-invitation',
|
|
340
380
|
meshId: invitation.meshId,
|
|
341
381
|
secret: invitation.secret,
|
|
342
|
-
|
|
382
|
+
reachability: localReachability,
|
|
383
|
+
advertisement: localAdvertisement,
|
|
343
384
|
}, decodeRedeemResponse, signal);
|
|
344
385
|
if (response.kind === 'invitation-rejected') {
|
|
345
386
|
await this.#discardPendingJoin(invitation);
|
|
@@ -349,10 +390,14 @@ class PeerMeshNodeImpl {
|
|
|
349
390
|
const identity = this.#peer.identity();
|
|
350
391
|
if (roster.roster.meshId !== invitation.meshId ||
|
|
351
392
|
roster.authorityPublicKey !== invitation.authorityPublicKey ||
|
|
393
|
+
roster.roster.authorityPeerId !== stream.peerId ||
|
|
394
|
+
invitation.reachability.lease.peerId !== stream.peerId ||
|
|
352
395
|
!roster.roster.members.includes(identity.peerId)) {
|
|
396
|
+
await this.#discardPendingJoin(invitation);
|
|
353
397
|
throw new Error('Peer Mesh authority returned an unrelated roster');
|
|
354
398
|
}
|
|
355
|
-
const
|
|
399
|
+
const reachability = this.#validateReachabilityPage(response.reachability, roster, true);
|
|
400
|
+
const advertisements = this.#validateAdvertisementPage(response.advertisements, roster);
|
|
356
401
|
signal.throwIfAborted();
|
|
357
402
|
await this.#store.mutate((current) => {
|
|
358
403
|
const pending = current.pendingJoins.find(({ invitation: candidate }) => candidate.meshId === invitation.meshId && candidate.secret === invitation.secret);
|
|
@@ -369,11 +414,6 @@ class PeerMeshNodeImpl {
|
|
|
369
414
|
}
|
|
370
415
|
const state = {
|
|
371
416
|
role: 'replica',
|
|
372
|
-
authority: {
|
|
373
|
-
peerId: invitation.peerId,
|
|
374
|
-
routeHints: invitation.routeHints,
|
|
375
|
-
coordinationRelays: invitation.coordinationRelays,
|
|
376
|
-
},
|
|
377
417
|
roster: selectedRoster,
|
|
378
418
|
desiredMembership: pending.phase === 'leave_pending' ? 'left' : 'active',
|
|
379
419
|
};
|
|
@@ -384,13 +424,18 @@ class PeerMeshNodeImpl {
|
|
|
384
424
|
? replaceMesh(current.meshes, state)
|
|
385
425
|
: appendMesh(current.meshes, state, identity.peerId),
|
|
386
426
|
pendingJoins: current.pendingJoins.filter((candidate) => candidate !== pending),
|
|
387
|
-
|
|
427
|
+
reachability: mergeReachability(current.reachability, [...reachability, authorityReachability, localReachability], this.#now()),
|
|
428
|
+
advertisements: mergeAdvertisements(current.advertisements, [
|
|
429
|
+
...advertisements,
|
|
430
|
+
localAdvertisement,
|
|
431
|
+
]),
|
|
388
432
|
},
|
|
389
433
|
result: undefined,
|
|
390
434
|
};
|
|
391
435
|
});
|
|
436
|
+
this.#recordReachabilityReceipts([...reachability, authorityReachability, localReachability]);
|
|
392
437
|
signal.throwIfAborted();
|
|
393
|
-
await this.#
|
|
438
|
+
await this.#refreshLocalEvidence();
|
|
394
439
|
signal.throwIfAborted();
|
|
395
440
|
await this.#reconcileTransit();
|
|
396
441
|
signal.throwIfAborted();
|
|
@@ -398,7 +443,7 @@ class PeerMeshNodeImpl {
|
|
|
398
443
|
const state = findMesh(stored.meshes, invitation.meshId);
|
|
399
444
|
if (!state)
|
|
400
445
|
throw new Error('Peer Mesh join was not retained');
|
|
401
|
-
return peerMeshStatus(state, identity, this.#endpointKind, stored.
|
|
446
|
+
return peerMeshStatus(state, identity, this.#endpointKind, stored.reachability, stored.advertisements, this.#now(), (peerId) => this.#peer.isConnected(peerId), (peerId) => this.resolveRoutes(peerId), (signed) => this.#isReachabilityCurrent(signed));
|
|
402
447
|
}
|
|
403
448
|
#discardPendingJoin(invitation) {
|
|
404
449
|
return this.#store.mutate((current) => ({
|
|
@@ -416,7 +461,10 @@ class PeerMeshNodeImpl {
|
|
|
416
461
|
state: {
|
|
417
462
|
...current,
|
|
418
463
|
meshes: existing?.role === 'replica'
|
|
419
|
-
? replaceMesh(current.meshes, {
|
|
464
|
+
? replaceMesh(current.meshes, {
|
|
465
|
+
...existing,
|
|
466
|
+
desiredMembership: 'left',
|
|
467
|
+
})
|
|
420
468
|
: current.meshes,
|
|
421
469
|
pendingJoins: current.pendingJoins.flatMap((pending) => {
|
|
422
470
|
if (pending.invitation.meshId !== meshId)
|
|
@@ -429,15 +477,20 @@ class PeerMeshNodeImpl {
|
|
|
429
477
|
});
|
|
430
478
|
}
|
|
431
479
|
async #resumePendingJoin(pending, signal) {
|
|
480
|
+
const authorityReachability = this.#authenticateReachability(pending.invitation.reachability, pending.invitation.reachability.lease.peerId, true);
|
|
481
|
+
const existing = findMesh(this.#store.read().meshes, pending.invitation.meshId);
|
|
482
|
+
if (existing?.role === 'replica' &&
|
|
483
|
+
authorityReachability.lease.peerId !== existing.roster.roster.authorityPeerId) {
|
|
484
|
+
throw new Error('Peer Mesh repair invitation has the wrong authority identity');
|
|
485
|
+
}
|
|
432
486
|
const stream = await this.#peer.connectMeshControl({
|
|
433
|
-
|
|
434
|
-
routeHints: pending.invitation.routeHints,
|
|
435
|
-
coordinationRelays: pending.invitation.coordinationRelays,
|
|
487
|
+
...dialTarget(authorityReachability),
|
|
436
488
|
directDeadlineMs: CONNECT_DEADLINE_MS,
|
|
437
489
|
}, signal);
|
|
438
490
|
try {
|
|
439
|
-
const
|
|
440
|
-
await this.#
|
|
491
|
+
const localReachability = await this.#reachability.refresh();
|
|
492
|
+
const localAdvertisement = await this.#signLocalAdvertisement(pending.invitation.meshId);
|
|
493
|
+
await this.#redeemPendingJoin(pending.invitation, localReachability, localAdvertisement, stream, signal);
|
|
441
494
|
}
|
|
442
495
|
finally {
|
|
443
496
|
await stream.close().catch(() => undefined);
|
|
@@ -472,7 +525,10 @@ class PeerMeshNodeImpl {
|
|
|
472
525
|
return {
|
|
473
526
|
state: {
|
|
474
527
|
...current,
|
|
475
|
-
meshes: replaceMesh(current.meshes, {
|
|
528
|
+
meshes: replaceMesh(current.meshes, {
|
|
529
|
+
...state,
|
|
530
|
+
desiredMembership: 'left',
|
|
531
|
+
}),
|
|
476
532
|
},
|
|
477
533
|
result: undefined,
|
|
478
534
|
};
|
|
@@ -496,22 +552,28 @@ class PeerMeshNodeImpl {
|
|
|
496
552
|
setTransitMesh(meshId) {
|
|
497
553
|
return this.#admitMesh(async () => {
|
|
498
554
|
const localPeerId = this.#peer.identity().peerId;
|
|
499
|
-
await this.#store.mutate((current) => {
|
|
555
|
+
await this.#store.mutate(async (current) => {
|
|
500
556
|
if (meshId !== null &&
|
|
501
557
|
!current.meshes.some((mesh) => mesh.roster.roster.meshId === meshId && isActiveMembership(mesh, localPeerId))) {
|
|
502
558
|
throw new Error('Transit requires an active Peer Mesh membership');
|
|
503
559
|
}
|
|
560
|
+
if (current.transitMeshId === meshId)
|
|
561
|
+
return { state: current, result: undefined };
|
|
562
|
+
const next = { ...current, transitMeshId: meshId };
|
|
563
|
+
const advertisements = await this.#localAdvertisementsFor(next);
|
|
504
564
|
return {
|
|
505
|
-
state: {
|
|
565
|
+
state: {
|
|
566
|
+
...next,
|
|
567
|
+
advertisements: mergeAdvertisements(current.advertisements, advertisements),
|
|
568
|
+
},
|
|
506
569
|
result: undefined,
|
|
507
570
|
};
|
|
508
571
|
});
|
|
509
572
|
try {
|
|
510
573
|
await this.#reconcileTransit();
|
|
511
|
-
await this.#refreshLocalRoute();
|
|
512
574
|
}
|
|
513
575
|
finally {
|
|
514
|
-
|
|
576
|
+
this.#triggerReconciliation();
|
|
515
577
|
}
|
|
516
578
|
});
|
|
517
579
|
}
|
|
@@ -527,39 +589,40 @@ class PeerMeshNodeImpl {
|
|
|
527
589
|
this.#assertOpen();
|
|
528
590
|
const now = this.#now();
|
|
529
591
|
const stored = this.#store.read();
|
|
592
|
+
const localPeerId = this.#peer.identity().peerId;
|
|
593
|
+
this.#pruneCompletedRecoverySweeps(stored, localPeerId);
|
|
530
594
|
const sharedMeshIds = stored.meshes
|
|
531
|
-
.filter((state) => isActiveMembership(state,
|
|
532
|
-
state.roster.roster.members.includes(peerId))
|
|
595
|
+
.filter((state) => isActiveMembership(state, localPeerId) && state.roster.roster.members.includes(peerId))
|
|
533
596
|
.map(({ roster }) => roster.roster.meshId);
|
|
534
597
|
const visible = sharedMeshIds.length > 0;
|
|
535
598
|
if (!visible)
|
|
536
|
-
return
|
|
537
|
-
const
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
const
|
|
541
|
-
const
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
if (!route && transitRelayPeerIds.length === 0)
|
|
550
|
-
return undefined;
|
|
599
|
+
return emptyRouteResolution('exhausted');
|
|
600
|
+
const reachability = latestReachability(stored.reachability, peerId, now, true)?.lease;
|
|
601
|
+
const transitRelayPeerIds = transitRelayCandidates(eligibleTransitEvidence(stored, localPeerId, now, (signed) => this.#isReachabilityCurrent(signed)).filter(({ meshId, lease }) => lease.lease.peerId !== peerId && sharedMeshIds.includes(meshId))).map(({ peerId: relayPeerId }) => relayPeerId);
|
|
602
|
+
const routeHints = reachability?.directRoutes ?? [];
|
|
603
|
+
const coordinationRelays = reachability?.coordinationRoutes ?? [];
|
|
604
|
+
const hasCandidates = routeHints.length + coordinationRelays.length + transitRelayPeerIds.length > 0;
|
|
605
|
+
const state = hasCandidates
|
|
606
|
+
? 'available'
|
|
607
|
+
: hasPeerRecoverySource(stored, sharedMeshIds, peerId, localPeerId, now)
|
|
608
|
+
? 'recovering'
|
|
609
|
+
: this.#completedRecoverySweeps.has(peerId)
|
|
610
|
+
? 'exhausted'
|
|
611
|
+
: 'recovering';
|
|
551
612
|
return Object.freeze({
|
|
552
|
-
|
|
553
|
-
|
|
613
|
+
state,
|
|
614
|
+
routeHints,
|
|
615
|
+
coordinationRelays,
|
|
554
616
|
transitRelayPeerIds: Object.freeze(transitRelayPeerIds),
|
|
555
617
|
});
|
|
556
618
|
}
|
|
557
619
|
async prepareRoutes(peerId, signal) {
|
|
558
620
|
this.#assertOpen();
|
|
559
621
|
signal.throwIfAborted();
|
|
622
|
+
this.#setRecoverySweepCompleted(peerId, false);
|
|
560
623
|
const localPeerId = this.#peer.identity().peerId;
|
|
561
624
|
const stored = this.#store.read();
|
|
562
|
-
const visible = stored
|
|
625
|
+
const visible = this.#pruneCompletedRecoverySweeps(stored, localPeerId).has(peerId);
|
|
563
626
|
if (!visible)
|
|
564
627
|
return;
|
|
565
628
|
// A signed route can remain within its TTL after a peer restarted or
|
|
@@ -567,9 +630,75 @@ class PeerMeshNodeImpl {
|
|
|
567
630
|
// asks the Mesh control plane for its newest record. Callers with a
|
|
568
631
|
// self-contained invitation run this reconciliation in parallel with the
|
|
569
632
|
// first dial; callers without usable routes wait for it.
|
|
570
|
-
|
|
633
|
+
try {
|
|
634
|
+
await this.#queueReconcile(signal, peerId);
|
|
635
|
+
}
|
|
636
|
+
finally {
|
|
637
|
+
if (!signal.aborted && !this.#lifetime.signal.aborted) {
|
|
638
|
+
this.#setRecoverySweepCompleted(peerId, true);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
#pruneCompletedRecoverySweeps(stored = this.#store.read(), localPeerId = this.#peer.identity().peerId) {
|
|
643
|
+
const visiblePeerIds = new Set();
|
|
644
|
+
for (const state of stored.meshes) {
|
|
645
|
+
if (!isActiveMembership(state, localPeerId))
|
|
646
|
+
continue;
|
|
647
|
+
for (const memberPeerId of state.roster.roster.members) {
|
|
648
|
+
if (memberPeerId !== localPeerId)
|
|
649
|
+
visiblePeerIds.add(memberPeerId);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
for (const peerId of this.#completedRecoverySweeps) {
|
|
653
|
+
if (!visiblePeerIds.has(peerId))
|
|
654
|
+
this.#completedRecoverySweeps.delete(peerId);
|
|
655
|
+
}
|
|
656
|
+
return visiblePeerIds;
|
|
657
|
+
}
|
|
658
|
+
subscribeRoutes(peerId, listener) {
|
|
659
|
+
this.#assertOpen();
|
|
660
|
+
let current = this.resolveRoutes(peerId);
|
|
661
|
+
const observe = () => {
|
|
662
|
+
const next = this.resolveRoutes(peerId);
|
|
663
|
+
if (sameResolvedRoutes(current, next))
|
|
664
|
+
return;
|
|
665
|
+
current = next;
|
|
666
|
+
try {
|
|
667
|
+
listener();
|
|
668
|
+
}
|
|
669
|
+
catch {
|
|
670
|
+
// Route observers cannot control Mesh reconciliation.
|
|
671
|
+
}
|
|
672
|
+
};
|
|
673
|
+
const listeners = this.#routeResolutionListeners.get(peerId) ?? new Set();
|
|
674
|
+
listeners.add(observe);
|
|
675
|
+
this.#routeResolutionListeners.set(peerId, listeners);
|
|
676
|
+
const unsubscribeStore = this.#store.subscribe(observe);
|
|
677
|
+
return () => {
|
|
678
|
+
unsubscribeStore();
|
|
679
|
+
listeners.delete(observe);
|
|
680
|
+
if (listeners.size === 0)
|
|
681
|
+
this.#routeResolutionListeners.delete(peerId);
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
#setRecoverySweepCompleted(peerId, completed) {
|
|
685
|
+
const retain = completed && this.#pruneCompletedRecoverySweeps().has(peerId);
|
|
686
|
+
const changed = retain
|
|
687
|
+
? !this.#completedRecoverySweeps.has(peerId)
|
|
688
|
+
: this.#completedRecoverySweeps.has(peerId);
|
|
689
|
+
if (!changed)
|
|
690
|
+
return;
|
|
691
|
+
if (retain)
|
|
692
|
+
this.#completedRecoverySweeps.add(peerId);
|
|
693
|
+
else
|
|
694
|
+
this.#completedRecoverySweeps.delete(peerId);
|
|
695
|
+
for (const listener of this.#routeResolutionListeners.get(peerId) ?? [])
|
|
696
|
+
listener();
|
|
571
697
|
}
|
|
572
698
|
reconcile(signal) {
|
|
699
|
+
return this.#queueReconcile(signal);
|
|
700
|
+
}
|
|
701
|
+
#queueReconcile(signal, excludedPeerId) {
|
|
573
702
|
if (this.#lifetime.signal.aborted)
|
|
574
703
|
return Promise.reject(new Error('Peer Mesh node is closed'));
|
|
575
704
|
const previous = this.#reconcileTail;
|
|
@@ -579,7 +708,7 @@ class PeerMeshNodeImpl {
|
|
|
579
708
|
});
|
|
580
709
|
this.#reconcileTail = previous.then(() => turn);
|
|
581
710
|
return waitForTurn(previous, signal)
|
|
582
|
-
.then(() => this.#reconcile(signal))
|
|
711
|
+
.then(() => this.#reconcile(signal, excludedPeerId))
|
|
583
712
|
.finally(release);
|
|
584
713
|
}
|
|
585
714
|
async serve() {
|
|
@@ -618,16 +747,23 @@ class PeerMeshNodeImpl {
|
|
|
618
747
|
}
|
|
619
748
|
async #close() {
|
|
620
749
|
this.#lifetime.abort();
|
|
750
|
+
this.#unsubscribeReachability?.();
|
|
751
|
+
this.#unsubscribeReachability = undefined;
|
|
752
|
+
for (const wake of this.#reconcileWaiters)
|
|
753
|
+
wake();
|
|
754
|
+
this.#reconcileWaiters.clear();
|
|
621
755
|
await this.#serveTask?.catch(() => undefined);
|
|
622
756
|
for (const stream of this.#activeControlStreams)
|
|
623
757
|
stream.abort();
|
|
624
758
|
this.#activeControlStreams.clear();
|
|
625
|
-
|
|
759
|
+
this.#routeResolutionListeners.clear();
|
|
760
|
+
await Promise.all([this.#admissionTail, this.#reconcileTail, this.#transitTail]);
|
|
626
761
|
return this.#store.close();
|
|
627
762
|
}
|
|
628
763
|
async #runReconciliation(signal) {
|
|
629
764
|
let failureReported = false;
|
|
630
765
|
while (!signal.aborted) {
|
|
766
|
+
const observedGeneration = this.#reconcileGeneration;
|
|
631
767
|
try {
|
|
632
768
|
await this.reconcile(signal);
|
|
633
769
|
failureReported = false;
|
|
@@ -643,64 +779,80 @@ class PeerMeshNodeImpl {
|
|
|
643
779
|
}
|
|
644
780
|
}
|
|
645
781
|
}
|
|
646
|
-
await this.#waitForReconciliationTrigger(signal).catch(() => undefined);
|
|
782
|
+
await this.#waitForReconciliationTrigger(observedGeneration, signal).catch(() => undefined);
|
|
647
783
|
}
|
|
648
784
|
}
|
|
649
|
-
async #waitForReconciliationTrigger(signal) {
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
785
|
+
async #waitForReconciliationTrigger(observedGeneration, signal) {
|
|
786
|
+
if (this.#reconcileGeneration !== observedGeneration)
|
|
787
|
+
return;
|
|
788
|
+
let wake;
|
|
789
|
+
const triggered = new Promise((resolve) => {
|
|
790
|
+
wake = resolve;
|
|
791
|
+
this.#reconcileWaiters.add(wake);
|
|
792
|
+
});
|
|
793
|
+
if (this.#reconcileGeneration !== observedGeneration)
|
|
794
|
+
wake();
|
|
795
|
+
try {
|
|
796
|
+
await Promise.race([triggered, delay(RECONCILE_INTERVAL_MS, undefined, { signal })]);
|
|
657
797
|
}
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
const identity = this.#peer.identity();
|
|
661
|
-
const current = this.#store.read();
|
|
662
|
-
if (!current.meshes.some((state) => isActiveMembership(state, identity.peerId))) {
|
|
663
|
-
return false;
|
|
798
|
+
finally {
|
|
799
|
+
this.#reconcileWaiters.delete(wake);
|
|
664
800
|
}
|
|
665
|
-
const existing = current.routes
|
|
666
|
-
.filter(({ route }) => route.peerId === identity.peerId)
|
|
667
|
-
.sort((left, right) => right.route.sequence - left.route.sequence)[0];
|
|
668
|
-
return !isCurrentLocalRoute(existing, identity, current, this.#endpointKind, this.#now());
|
|
669
801
|
}
|
|
670
|
-
|
|
802
|
+
#triggerReconciliation() {
|
|
803
|
+
this.#reconcileGeneration += 1;
|
|
804
|
+
for (const wake of this.#reconcileWaiters)
|
|
805
|
+
wake();
|
|
806
|
+
this.#reconcileWaiters.clear();
|
|
807
|
+
}
|
|
808
|
+
async #reconcile(signal, excludedPeerId) {
|
|
671
809
|
const lifetimeSignal = signal
|
|
672
810
|
? AbortSignal.any([signal, this.#lifetime.signal])
|
|
673
811
|
: this.#lifetime.signal;
|
|
674
812
|
lifetimeSignal.throwIfAborted();
|
|
675
813
|
await this.#reconcileTransit();
|
|
676
|
-
await this.#
|
|
814
|
+
await this.#refreshLocalEvidence();
|
|
677
815
|
const identity = this.#peer.identity();
|
|
678
816
|
const stored = this.#store.read();
|
|
679
|
-
const memberships = stored.meshes.filter((state) => state.
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
817
|
+
const memberships = stored.meshes.filter((state) => !state.roster.roster.closed && state.roster.roster.members.includes(identity.peerId));
|
|
818
|
+
const pending = stored.pendingJoins
|
|
819
|
+
.filter(({ invitation }) => invitation.reachability.lease.peerId !== excludedPeerId)
|
|
820
|
+
.map((join) => ({ kind: 'join', join }));
|
|
683
821
|
const gossipCursor = this.#gossipCursor;
|
|
684
822
|
this.#gossipCursor = (this.#gossipCursor + 1) % PEER_MESH_MAX_MEMBERS;
|
|
685
823
|
const now = this.#now();
|
|
686
824
|
for (const [index, state] of memberships.entries()) {
|
|
687
|
-
const
|
|
688
|
-
const
|
|
689
|
-
const
|
|
690
|
-
|
|
825
|
+
const meshId = state.roster.roster.meshId;
|
|
826
|
+
const desiredMembership = state.role === 'replica' ? state.desiredMembership : 'active';
|
|
827
|
+
const authority = state.role === 'replica'
|
|
828
|
+
? currentAuthorityTarget(state, stored.reachability, now)
|
|
829
|
+
: undefined;
|
|
830
|
+
if (authority && authority.lease.peerId !== excludedPeerId) {
|
|
831
|
+
pending.push({
|
|
832
|
+
kind: 'membership',
|
|
833
|
+
meshId,
|
|
834
|
+
target: authority,
|
|
835
|
+
desiredMembership,
|
|
836
|
+
roster: state.roster,
|
|
837
|
+
});
|
|
838
|
+
}
|
|
839
|
+
if (desiredMembership === 'left')
|
|
840
|
+
continue;
|
|
841
|
+
const rotatingTargets = state.roster.roster.members
|
|
842
|
+
.filter((peerId) => peerId !== identity.peerId &&
|
|
843
|
+
peerId !== excludedPeerId &&
|
|
844
|
+
(state.role === 'authority' || peerId !== state.roster.roster.authorityPeerId))
|
|
691
845
|
.flatMap((peerId) => {
|
|
692
|
-
const
|
|
693
|
-
return
|
|
846
|
+
const target = peerTarget(peerId, stored.reachability, now);
|
|
847
|
+
return target ? [target] : [];
|
|
694
848
|
});
|
|
695
|
-
if (
|
|
696
|
-
|
|
697
|
-
}
|
|
849
|
+
if (rotatingTargets.length === 0)
|
|
850
|
+
continue;
|
|
698
851
|
pending.push({
|
|
699
852
|
kind: 'membership',
|
|
700
|
-
meshId
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
desiredMembership: state.desiredMembership,
|
|
853
|
+
meshId,
|
|
854
|
+
target: rotatingTargets[(gossipCursor + index) % rotatingTargets.length],
|
|
855
|
+
desiredMembership,
|
|
704
856
|
roster: state.roster,
|
|
705
857
|
});
|
|
706
858
|
}
|
|
@@ -723,16 +875,18 @@ class PeerMeshNodeImpl {
|
|
|
723
875
|
await this.#resumePendingJoin(operation.join, operationSignal);
|
|
724
876
|
}
|
|
725
877
|
else if (operation.desiredMembership === 'left') {
|
|
726
|
-
await this.#notifyLeave(operation.meshId, operation.
|
|
878
|
+
await this.#notifyLeave(operation.meshId, operation.target, operation.roster, operationSignal);
|
|
727
879
|
}
|
|
728
880
|
else {
|
|
729
|
-
await this.#
|
|
881
|
+
await this.#syncPeer(operation.meshId, operation.target, operationSignal);
|
|
730
882
|
}
|
|
731
883
|
}
|
|
732
884
|
catch (error) {
|
|
733
885
|
if (lifetimeSignal.aborted)
|
|
734
886
|
lifetimeSignal.throwIfAborted();
|
|
735
|
-
|
|
887
|
+
if (operation.kind === 'join' || operation.desiredMembership === 'left') {
|
|
888
|
+
failures.push(error);
|
|
889
|
+
}
|
|
736
890
|
if (deadline.aborted)
|
|
737
891
|
return;
|
|
738
892
|
}
|
|
@@ -747,86 +901,60 @@ class PeerMeshNodeImpl {
|
|
|
747
901
|
}
|
|
748
902
|
}
|
|
749
903
|
async #notifyLeave(meshId, target, roster, signal) {
|
|
750
|
-
const stream = await this.#peer.connectMeshControl({
|
|
904
|
+
const stream = await this.#peer.connectMeshControl({
|
|
905
|
+
...dialTarget(target),
|
|
906
|
+
directDeadlineMs: CONNECT_DEADLINE_MS,
|
|
907
|
+
}, signal);
|
|
751
908
|
try {
|
|
752
909
|
const response = await exchangeControl(stream, { kind: 'leave', meshId, roster }, decodeLeaveResponse, signal);
|
|
753
910
|
if (response.kind === 'leave-rejected') {
|
|
754
911
|
throw new Error('Peer Mesh authority rejected the leave request');
|
|
755
912
|
}
|
|
756
|
-
await this.#applySync(meshId, response.roster, []);
|
|
913
|
+
await this.#applySync(meshId, response.roster, [], []);
|
|
757
914
|
}
|
|
758
915
|
finally {
|
|
759
916
|
await stream.close().catch(() => undefined);
|
|
760
917
|
}
|
|
761
918
|
}
|
|
762
|
-
async #syncTargets(meshId, targets, authorityRouteExpired, signal) {
|
|
763
|
-
if (!authorityRouteExpired || targets.length === 1) {
|
|
764
|
-
try {
|
|
765
|
-
await this.#syncPeer(meshId, targets[0], signal);
|
|
766
|
-
}
|
|
767
|
-
catch (authorityFailure) {
|
|
768
|
-
const fallbackTargets = targets.slice(1);
|
|
769
|
-
if (fallbackTargets.length === 0)
|
|
770
|
-
throw authorityFailure;
|
|
771
|
-
await Promise.any(fallbackTargets.map((target) => this.#syncPeer(meshId, target, signal)));
|
|
772
|
-
}
|
|
773
|
-
return;
|
|
774
|
-
}
|
|
775
|
-
const controllers = targets.map(() => new AbortController());
|
|
776
|
-
const authorityPeerId = targets[0].peerId;
|
|
777
|
-
const attempts = targets.map(async (target, index) => {
|
|
778
|
-
await this.#syncPeer(meshId, target, AbortSignal.any([signal, controllers[index].signal]));
|
|
779
|
-
if (index > 0 && !this.#hasFreshRoute(meshId, authorityPeerId)) {
|
|
780
|
-
throw new Error('Peer Mesh gossip did not recover the authority route');
|
|
781
|
-
}
|
|
782
|
-
});
|
|
783
|
-
try {
|
|
784
|
-
await Promise.any(attempts);
|
|
785
|
-
}
|
|
786
|
-
finally {
|
|
787
|
-
for (const controller of controllers)
|
|
788
|
-
controller.abort();
|
|
789
|
-
await Promise.allSettled(attempts);
|
|
790
|
-
}
|
|
791
|
-
}
|
|
792
|
-
#hasFreshRoute(meshId, peerId) {
|
|
793
|
-
const stored = this.#store.read();
|
|
794
|
-
const mesh = findMesh(stored.meshes, meshId);
|
|
795
|
-
return Boolean(mesh &&
|
|
796
|
-
isActiveMembership(mesh, this.#peer.identity().peerId) &&
|
|
797
|
-
stored.routes.some(({ route }) => route.peerId === peerId && route.expiresAt > this.#now()));
|
|
798
|
-
}
|
|
799
919
|
async #syncPeer(meshId, target, signal) {
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
const localPeerId = this.#peer.identity().peerId;
|
|
805
|
-
if (!state || !isActiveMembership(state, localPeerId))
|
|
920
|
+
const localPeerId = this.#peer.identity().peerId;
|
|
921
|
+
const targetPeerId = target.lease.peerId;
|
|
922
|
+
for (let page = 0; page <= PEER_MESH_MAX_MEMBERS; page += 1) {
|
|
923
|
+
if (!isActiveMeshMember(this.#store.read().meshes, meshId, localPeerId, targetPeerId))
|
|
806
924
|
return;
|
|
807
|
-
const
|
|
808
|
-
|
|
809
|
-
throw new Error('Peer Mesh local route is unavailable');
|
|
810
|
-
const discovered = this.resolveRoutes(target.peerId);
|
|
925
|
+
const discovered = this.resolveRoutes(targetPeerId);
|
|
926
|
+
const targetRoutes = dialTarget(target);
|
|
811
927
|
const stream = await this.#peer.connectMeshControl({
|
|
812
|
-
peerId:
|
|
813
|
-
routeHints: mergeAddresses(discovered?.routeHints ?? [],
|
|
814
|
-
coordinationRelays: mergeAddresses(discovered?.coordinationRelays ?? [],
|
|
928
|
+
peerId: targetPeerId,
|
|
929
|
+
routeHints: mergeAddresses(discovered?.routeHints ?? [], targetRoutes.routeHints),
|
|
930
|
+
coordinationRelays: mergeAddresses(discovered?.coordinationRelays ?? [], targetRoutes.coordinationRelays),
|
|
815
931
|
transitRelayPeerIds: discovered?.transitRelayPeerIds,
|
|
816
932
|
directDeadlineMs: CONNECT_DEADLINE_MS,
|
|
817
933
|
}, signal);
|
|
818
934
|
try {
|
|
935
|
+
await this.#refreshLocalEvidence();
|
|
936
|
+
const stored = this.#store.read();
|
|
937
|
+
if (!isActiveMeshMember(stored.meshes, meshId, localPeerId, targetPeerId))
|
|
938
|
+
return;
|
|
939
|
+
const state = findMesh(stored.meshes, meshId);
|
|
940
|
+
const reachability = latestReachability(stored.reachability, localPeerId, this.#now(), true);
|
|
941
|
+
const advertisement = findAdvertisement(stored.advertisements, meshId, localPeerId);
|
|
942
|
+
if (!reachability || !advertisement) {
|
|
943
|
+
throw new Error('Peer Mesh local evidence is unavailable');
|
|
944
|
+
}
|
|
819
945
|
const response = await exchangeControl(stream, {
|
|
820
946
|
kind: 'sync',
|
|
821
947
|
meshId,
|
|
822
948
|
roster: state.roster,
|
|
823
|
-
|
|
824
|
-
|
|
949
|
+
reachability,
|
|
950
|
+
advertisement,
|
|
951
|
+
knownReachability: reachabilitySummaries(stored.reachability, state.roster, this.#now()),
|
|
952
|
+
knownAdvertisements: advertisementSummaries(stored.advertisements, state.roster),
|
|
825
953
|
}, decodeSyncResponse, signal);
|
|
826
954
|
if (response.kind === 'sync-rejected') {
|
|
827
955
|
throw new Error(`Peer Mesh synchronization was rejected: ${response.reason}`);
|
|
828
956
|
}
|
|
829
|
-
await this.#applySync(meshId, response.roster, response.
|
|
957
|
+
await this.#applySync(meshId, response.roster, response.reachability, response.advertisements);
|
|
830
958
|
if (!response.more)
|
|
831
959
|
return;
|
|
832
960
|
}
|
|
@@ -836,98 +964,191 @@ class PeerMeshNodeImpl {
|
|
|
836
964
|
}
|
|
837
965
|
throw new Error('Peer Mesh synchronization exceeded its page bound');
|
|
838
966
|
}
|
|
839
|
-
#
|
|
840
|
-
this.#
|
|
841
|
-
this.#
|
|
967
|
+
#refreshLocalEvidence() {
|
|
968
|
+
this.#evidenceRefreshTask ??= this.#refreshLocalEvidenceOnce().finally(() => {
|
|
969
|
+
this.#evidenceRefreshTask = undefined;
|
|
842
970
|
});
|
|
843
|
-
return this.#
|
|
971
|
+
return this.#evidenceRefreshTask;
|
|
844
972
|
}
|
|
845
|
-
async #
|
|
973
|
+
async #refreshLocalEvidenceOnce() {
|
|
974
|
+
const reachability = await this.#reachability.refresh();
|
|
846
975
|
const identity = this.#peer.identity();
|
|
847
976
|
const now = this.#now();
|
|
848
977
|
return this.#store.mutate(async (current) => {
|
|
849
|
-
|
|
978
|
+
const active = current.meshes.filter((state) => isActiveMembership(state, identity.peerId));
|
|
979
|
+
if (active.length === 0) {
|
|
850
980
|
return { state: current, result: undefined };
|
|
851
981
|
}
|
|
852
|
-
const
|
|
853
|
-
.filter(({ route }) => route.peerId === identity.peerId)
|
|
854
|
-
.sort((left, right) => right.route.sequence - left.route.sequence)[0];
|
|
855
|
-
if (isCurrentLocalRoute(existing, identity, current, this.#endpointKind, now)) {
|
|
856
|
-
return { state: current, result: existing };
|
|
857
|
-
}
|
|
858
|
-
const route = await this.#signLocalRoute(current);
|
|
982
|
+
const advertisements = await this.#localAdvertisementsFor(current);
|
|
859
983
|
return {
|
|
860
|
-
state: {
|
|
861
|
-
|
|
984
|
+
state: {
|
|
985
|
+
...current,
|
|
986
|
+
reachability: mergeReachability(current.reachability, [reachability], now),
|
|
987
|
+
advertisements: mergeAdvertisements(current.advertisements, advertisements),
|
|
988
|
+
},
|
|
989
|
+
result: Object.freeze({
|
|
990
|
+
reachability,
|
|
991
|
+
advertisements: Object.freeze(advertisements),
|
|
992
|
+
}),
|
|
862
993
|
};
|
|
863
994
|
});
|
|
864
995
|
}
|
|
865
|
-
async #
|
|
996
|
+
async #localAdvertisementsFor(stored) {
|
|
866
997
|
const identity = this.#peer.identity();
|
|
867
|
-
const
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
998
|
+
const advertisements = [];
|
|
999
|
+
for (const state of stored.meshes) {
|
|
1000
|
+
if (!isActiveMembership(state, identity.peerId))
|
|
1001
|
+
continue;
|
|
1002
|
+
const meshId = state.roster.roster.meshId;
|
|
1003
|
+
const existing = findAdvertisement(stored.advertisements, meshId, identity.peerId);
|
|
1004
|
+
advertisements.push(isCurrentLocalAdvertisement(existing, meshId, identity.peerId, stored, this.#endpointKind)
|
|
1005
|
+
? existing
|
|
1006
|
+
: await this.#signLocalAdvertisement(meshId, stored));
|
|
1007
|
+
}
|
|
1008
|
+
return Object.freeze(advertisements);
|
|
1009
|
+
}
|
|
1010
|
+
async #signLocalAdvertisement(meshId, stored = this.#store.read()) {
|
|
1011
|
+
const identity = this.#peer.identity();
|
|
1012
|
+
const maxRevision = stored.advertisements
|
|
1013
|
+
.filter(({ advertisement }) => advertisement.meshId === meshId && advertisement.peerId === identity.peerId)
|
|
1014
|
+
.reduce((maximum, { advertisement }) => Math.max(maximum, advertisement.revision), 0);
|
|
1015
|
+
const advertisement = canonicalPeerMeshMemberAdvertisement({
|
|
871
1016
|
version: 1,
|
|
1017
|
+
meshId,
|
|
872
1018
|
peerId: identity.peerId,
|
|
873
|
-
|
|
874
|
-
expiresAt: this.#now() + ROUTE_TTL_MS,
|
|
875
|
-
routeHints: identity.listenAddresses,
|
|
876
|
-
coordinationRelays: identity.coordinationRelays,
|
|
1019
|
+
revision: maxRevision + 1,
|
|
877
1020
|
...(this.#endpointKind ? { endpointKind: this.#endpointKind } : {}),
|
|
878
1021
|
...(stored.displayName ? { displayName: stored.displayName } : {}),
|
|
879
|
-
|
|
1022
|
+
offersTransit: stored.transitMeshId === meshId,
|
|
880
1023
|
});
|
|
881
|
-
const proof = await this.#peer.signIdentity(
|
|
882
|
-
const signed =
|
|
883
|
-
|
|
1024
|
+
const proof = await this.#peer.signIdentity(peerMeshMemberAdvertisementSigningBytes(advertisement));
|
|
1025
|
+
const signed = decodeSignedPeerMeshMemberAdvertisement({
|
|
1026
|
+
advertisement,
|
|
884
1027
|
publicKey: proof.publicKey.toString('base64url'),
|
|
885
1028
|
signature: proof.signature.toString('base64url'),
|
|
886
1029
|
});
|
|
887
|
-
this.#
|
|
1030
|
+
this.#assertAdvertisementSignature(signed);
|
|
1031
|
+
return signed;
|
|
1032
|
+
}
|
|
1033
|
+
#validateReachabilityPage(values, roster, allowExpired) {
|
|
1034
|
+
if (values.length > EVIDENCE_PAGE_SIZE) {
|
|
1035
|
+
throw new Error('Too many Peer Mesh reachability leases');
|
|
1036
|
+
}
|
|
1037
|
+
const reachability = values.map((value) => {
|
|
1038
|
+
const signed = decodeSignedPeerReachabilityLease(value);
|
|
1039
|
+
if (!roster.roster.members.includes(signed.lease.peerId)) {
|
|
1040
|
+
throw new Error('Peer Mesh reachability is outside the active roster');
|
|
1041
|
+
}
|
|
1042
|
+
return this.#authenticateReachability(signed, signed.lease.peerId, allowExpired);
|
|
1043
|
+
});
|
|
1044
|
+
if (new Set(reachability.map(({ lease }) => lease.peerId)).size !== reachability.length) {
|
|
1045
|
+
throw new Error('Duplicate Peer Mesh reachability leases');
|
|
1046
|
+
}
|
|
1047
|
+
return Object.freeze(reachability);
|
|
1048
|
+
}
|
|
1049
|
+
#authenticateReachability(value, expectedPeerId, allowExpired = false) {
|
|
1050
|
+
const signed = verifySignedPeerReachabilityLease({
|
|
1051
|
+
value,
|
|
1052
|
+
expectedPeerId,
|
|
1053
|
+
now: this.#now(),
|
|
1054
|
+
verifyIdentity: this.#peer.verifyIdentity.bind(this.#peer),
|
|
1055
|
+
...(allowExpired ? { allowExpired: true } : {}),
|
|
1056
|
+
});
|
|
1057
|
+
if (allowExpired &&
|
|
1058
|
+
signed.lease.expiresAt <= this.#now() - PEER_REACHABILITY_RECOVERY_HORIZON_MS) {
|
|
1059
|
+
throw new Error('Peer Mesh reachability is outside the recovery horizon');
|
|
1060
|
+
}
|
|
888
1061
|
return signed;
|
|
889
1062
|
}
|
|
890
|
-
#
|
|
891
|
-
if (values.length >
|
|
892
|
-
throw new Error('Too many Peer Mesh
|
|
893
|
-
const routes = values.map(decodeSignedPeerMeshRouteRecord);
|
|
894
|
-
if (new Set(routes.map(({ route }) => route.peerId)).size !== routes.length) {
|
|
895
|
-
throw new Error('Duplicate Peer Mesh routes');
|
|
1063
|
+
#validateAdvertisementPage(values, roster) {
|
|
1064
|
+
if (values.length > EVIDENCE_PAGE_SIZE) {
|
|
1065
|
+
throw new Error('Too many Peer Mesh member advertisements');
|
|
896
1066
|
}
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
1067
|
+
const advertisements = values.map((value) => {
|
|
1068
|
+
const signed = decodeSignedPeerMeshMemberAdvertisement(value);
|
|
1069
|
+
if (signed.advertisement.meshId !== roster.roster.meshId ||
|
|
1070
|
+
!roster.roster.members.includes(signed.advertisement.peerId)) {
|
|
1071
|
+
throw new Error('Peer Mesh member advertisement is outside the active roster');
|
|
900
1072
|
}
|
|
901
|
-
this.#
|
|
1073
|
+
this.#assertAdvertisementSignature(signed);
|
|
1074
|
+
return signed;
|
|
1075
|
+
});
|
|
1076
|
+
const keys = advertisements.map(({ advertisement }) => advertisement.peerId);
|
|
1077
|
+
if (new Set(keys).size !== keys.length) {
|
|
1078
|
+
throw new Error('Duplicate Peer Mesh member advertisements');
|
|
902
1079
|
}
|
|
903
|
-
return Object.freeze(
|
|
904
|
-
}
|
|
905
|
-
#
|
|
906
|
-
const signed =
|
|
907
|
-
if (signed.
|
|
908
|
-
|
|
909
|
-
signed.route.expiresAt > now + ROUTE_MAX_FUTURE_MS) {
|
|
910
|
-
throw new Error('Peer Mesh route is outside the authenticated peer or lifetime');
|
|
1080
|
+
return Object.freeze(advertisements);
|
|
1081
|
+
}
|
|
1082
|
+
#validateAdvertisementForPeer(value, meshId, peerId) {
|
|
1083
|
+
const signed = decodeSignedPeerMeshMemberAdvertisement(value);
|
|
1084
|
+
if (signed.advertisement.meshId !== meshId || signed.advertisement.peerId !== peerId) {
|
|
1085
|
+
throw new Error('Peer Mesh member advertisement belongs to a different member');
|
|
911
1086
|
}
|
|
912
|
-
this.#
|
|
1087
|
+
this.#assertAdvertisementSignature(signed);
|
|
913
1088
|
return signed;
|
|
914
1089
|
}
|
|
915
|
-
#
|
|
916
|
-
const signed =
|
|
917
|
-
const valid = this.#peer.verifyIdentity(signed.
|
|
1090
|
+
#assertAdvertisementSignature(signedValue) {
|
|
1091
|
+
const signed = decodeSignedPeerMeshMemberAdvertisement(signedValue);
|
|
1092
|
+
const valid = this.#peer.verifyIdentity(signed.advertisement.peerId, peerMeshMemberAdvertisementSigningBytes(signed.advertisement), {
|
|
918
1093
|
publicKey: Buffer.from(signed.publicKey, 'base64url'),
|
|
919
1094
|
signature: Buffer.from(signed.signature, 'base64url'),
|
|
920
1095
|
});
|
|
921
1096
|
if (!valid)
|
|
922
|
-
throw new Error('Peer Mesh
|
|
1097
|
+
throw new Error('Peer Mesh member advertisement signature is invalid');
|
|
1098
|
+
}
|
|
1099
|
+
#recordReachabilityReceipt(signed) {
|
|
1100
|
+
this.#recordReachabilityReceipts([signed]);
|
|
1101
|
+
}
|
|
1102
|
+
#recordReachabilityReceipts(values) {
|
|
1103
|
+
const retained = this.#retainedReachabilityReceiptPeerIds();
|
|
1104
|
+
for (const peerId of this.#reachabilityReceipts.keys()) {
|
|
1105
|
+
if (!retained.has(peerId))
|
|
1106
|
+
this.#reachabilityReceipts.delete(peerId);
|
|
1107
|
+
}
|
|
1108
|
+
for (const signed of values) {
|
|
1109
|
+
if (!retained.has(signed.lease.peerId))
|
|
1110
|
+
continue;
|
|
1111
|
+
const previous = this.#reachabilityReceipts.get(signed.lease.peerId);
|
|
1112
|
+
if (previous && previous.revision > signed.lease.revision)
|
|
1113
|
+
continue;
|
|
1114
|
+
if (previous &&
|
|
1115
|
+
previous.revision === signed.lease.revision &&
|
|
1116
|
+
previous.signature !== signed.signature) {
|
|
1117
|
+
continue;
|
|
1118
|
+
}
|
|
1119
|
+
this.#reachabilityReceipts.set(signed.lease.peerId, peerReachabilityLeaseReceipt({
|
|
1120
|
+
signed,
|
|
1121
|
+
wallNow: this.#now(),
|
|
1122
|
+
monotonicNow: this.#monotonicNow(),
|
|
1123
|
+
...(previous ? { previous } : {}),
|
|
1124
|
+
}));
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
#retainedReachabilityReceiptPeerIds() {
|
|
1128
|
+
const stored = this.#store.read();
|
|
1129
|
+
const localPeerId = this.#peer.identity().peerId;
|
|
1130
|
+
const retained = new Set();
|
|
1131
|
+
for (const state of stored.meshes) {
|
|
1132
|
+
if (!isActiveMembership(state, localPeerId))
|
|
1133
|
+
continue;
|
|
1134
|
+
for (const peerId of state.roster.roster.members) {
|
|
1135
|
+
if (peerId !== localPeerId)
|
|
1136
|
+
retained.add(peerId);
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
return retained;
|
|
923
1140
|
}
|
|
924
|
-
|
|
1141
|
+
#isReachabilityCurrent(signed) {
|
|
1142
|
+
return isPeerReachabilityLeaseCurrent(signed, this.#reachabilityReceipts.get(signed.lease.peerId), this.#monotonicNow());
|
|
1143
|
+
}
|
|
1144
|
+
async #applySync(meshId, rosterValue, reachabilityValues, advertisementValues) {
|
|
925
1145
|
const roster = decodeSignedPeerMeshRoster(rosterValue);
|
|
926
1146
|
if (roster.roster.meshId !== meshId)
|
|
927
1147
|
throw new Error('Peer Mesh synchronization changed Mesh');
|
|
928
|
-
const
|
|
1148
|
+
const reachability = this.#validateReachabilityPage(reachabilityValues, roster, true);
|
|
1149
|
+
const advertisements = this.#validateAdvertisementPage(advertisementValues, roster);
|
|
929
1150
|
const localPeerId = this.#peer.identity().peerId;
|
|
930
|
-
await this.#store.mutate((current) => {
|
|
1151
|
+
const accepted = await this.#store.mutate((current) => {
|
|
931
1152
|
const state = findMesh(current.meshes, meshId);
|
|
932
1153
|
if (!state || state.roster.authorityPublicKey !== roster.authorityPublicKey) {
|
|
933
1154
|
throw new Error('Peer Mesh synchronization has the wrong authority');
|
|
@@ -941,14 +1162,19 @@ class PeerMeshNodeImpl {
|
|
|
941
1162
|
state: {
|
|
942
1163
|
...current,
|
|
943
1164
|
meshes: replaceMesh(current.meshes, next),
|
|
944
|
-
|
|
945
|
-
? current.
|
|
946
|
-
:
|
|
1165
|
+
reachability: !isActiveMembership(next, localPeerId)
|
|
1166
|
+
? current.reachability
|
|
1167
|
+
: mergeReachability(current.reachability, reachability, this.#now()),
|
|
1168
|
+
advertisements: !isActiveMembership(next, localPeerId)
|
|
1169
|
+
? current.advertisements
|
|
1170
|
+
: mergeAdvertisements(current.advertisements, advertisements),
|
|
947
1171
|
},
|
|
948
|
-
result:
|
|
1172
|
+
result: isActiveMembership(next, localPeerId),
|
|
949
1173
|
};
|
|
950
1174
|
});
|
|
951
|
-
|
|
1175
|
+
if (accepted)
|
|
1176
|
+
this.#recordReachabilityReceipts(reachability);
|
|
1177
|
+
await this.#refreshLocalEvidence();
|
|
952
1178
|
await this.#reconcileTransit();
|
|
953
1179
|
}
|
|
954
1180
|
#assertOpen() {
|
|
@@ -971,6 +1197,7 @@ class PeerMeshNodeImpl {
|
|
|
971
1197
|
const roster = signPeerMeshRoster({
|
|
972
1198
|
version: 1,
|
|
973
1199
|
meshId: state.roster.roster.meshId,
|
|
1200
|
+
authorityPeerId: state.roster.roster.authorityPeerId,
|
|
974
1201
|
revision: state.roster.roster.revision + 1,
|
|
975
1202
|
members: next.members,
|
|
976
1203
|
closed: next.closed,
|
|
@@ -989,7 +1216,7 @@ class PeerMeshNodeImpl {
|
|
|
989
1216
|
state: { ...current, meshes: replaceMesh(current.meshes, updated) },
|
|
990
1217
|
result: {
|
|
991
1218
|
roster,
|
|
992
|
-
targets: rosterAnnouncementTargets(state.roster.roster.members, current.
|
|
1219
|
+
targets: rosterAnnouncementTargets(state.roster.roster.members, current.reachability, this.#peer.identity().peerId, this.#now()),
|
|
993
1220
|
},
|
|
994
1221
|
};
|
|
995
1222
|
});
|
|
@@ -1003,14 +1230,17 @@ class PeerMeshNodeImpl {
|
|
|
1003
1230
|
this.#scheduleMaintenance();
|
|
1004
1231
|
}
|
|
1005
1232
|
const stored = this.#store.read();
|
|
1006
|
-
return peerMeshStatus(findMesh(stored.meshes, meshId), this.#peer.identity(), this.#endpointKind, stored.
|
|
1233
|
+
return peerMeshStatus(findMesh(stored.meshes, meshId), this.#peer.identity(), this.#endpointKind, stored.reachability, stored.advertisements, this.#now(), (peerId) => this.#peer.isConnected(peerId), (peerId) => this.resolveRoutes(peerId), (signed) => this.#isReachabilityCurrent(signed));
|
|
1007
1234
|
}
|
|
1008
1235
|
#scheduleRosterAnnouncement(roster, targets) {
|
|
1009
1236
|
if (targets.length === 0 || this.#lifetime.signal.aborted)
|
|
1010
1237
|
return;
|
|
1011
1238
|
const signal = this.#lifetime.signal;
|
|
1012
1239
|
void Promise.allSettled(targets.map(async (target) => {
|
|
1013
|
-
const stream = await this.#peer.connectMeshControl({
|
|
1240
|
+
const stream = await this.#peer.connectMeshControl({
|
|
1241
|
+
...dialTarget(target),
|
|
1242
|
+
directDeadlineMs: CONNECT_DEADLINE_MS,
|
|
1243
|
+
}, signal);
|
|
1014
1244
|
try {
|
|
1015
1245
|
const response = await exchangeControl(stream, {
|
|
1016
1246
|
kind: 'announce-roster',
|
|
@@ -1027,7 +1257,8 @@ class PeerMeshNodeImpl {
|
|
|
1027
1257
|
}));
|
|
1028
1258
|
}
|
|
1029
1259
|
#scheduleMaintenance() {
|
|
1030
|
-
|
|
1260
|
+
this.#triggerReconciliation();
|
|
1261
|
+
void this.#refreshLocalEvidence().catch(() => undefined);
|
|
1031
1262
|
void this.#reconcileTransit().catch(() => undefined);
|
|
1032
1263
|
}
|
|
1033
1264
|
#acceptIncoming(stream) {
|
|
@@ -1064,8 +1295,8 @@ class PeerMeshNodeImpl {
|
|
|
1064
1295
|
const request = decodeControlRequest(await readFrame(stream));
|
|
1065
1296
|
let response;
|
|
1066
1297
|
if (request.kind === 'redeem-invitation') {
|
|
1067
|
-
await this.#
|
|
1068
|
-
response = await this.#redeem(request, stream.peerId, this.#
|
|
1298
|
+
await this.#refreshLocalEvidence();
|
|
1299
|
+
response = await this.#redeem(request, stream.peerId, this.#authenticateReachability(request.reachability, stream.peerId), this.#validateAdvertisementForPeer(request.advertisement, request.meshId, stream.peerId));
|
|
1069
1300
|
}
|
|
1070
1301
|
else if (request.kind === 'sync') {
|
|
1071
1302
|
response = await this.#sync(request, stream.peerId);
|
|
@@ -1109,7 +1340,7 @@ class PeerMeshNodeImpl {
|
|
|
1109
1340
|
await this.#reconcileTransit();
|
|
1110
1341
|
return response;
|
|
1111
1342
|
}
|
|
1112
|
-
async #redeem(request, remotePeerId,
|
|
1343
|
+
async #redeem(request, remotePeerId, remoteReachability, remoteAdvertisement) {
|
|
1113
1344
|
const now = this.#now();
|
|
1114
1345
|
const response = await this.#store.mutate((current) => {
|
|
1115
1346
|
const state = findMesh(current.meshes, request.meshId);
|
|
@@ -1124,16 +1355,15 @@ class PeerMeshNodeImpl {
|
|
|
1124
1355
|
!state.roster.roster.members.includes(remotePeerId)) {
|
|
1125
1356
|
return { state: current, result: rejected('invalid') };
|
|
1126
1357
|
}
|
|
1127
|
-
const
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
const routes = mergeAuthenticatedRoute(current.routes, remoteRoute, now);
|
|
1358
|
+
const reachability = mergeReachability(current.reachability, [remoteReachability], now);
|
|
1359
|
+
const advertisements = mergeAdvertisements(current.advertisements, [remoteAdvertisement]);
|
|
1360
|
+
const evidence = initialEvidence(state, reachability, advertisements, this.#peer.identity().peerId, now);
|
|
1131
1361
|
return {
|
|
1132
|
-
state: { ...current,
|
|
1362
|
+
state: { ...current, reachability, advertisements },
|
|
1133
1363
|
result: {
|
|
1134
1364
|
kind: 'invitation-redeemed',
|
|
1135
|
-
roster:
|
|
1136
|
-
|
|
1365
|
+
roster: state.roster,
|
|
1366
|
+
...evidence,
|
|
1137
1367
|
},
|
|
1138
1368
|
};
|
|
1139
1369
|
}
|
|
@@ -1175,30 +1405,14 @@ class PeerMeshNodeImpl {
|
|
|
1175
1405
|
result: rejected('full'),
|
|
1176
1406
|
};
|
|
1177
1407
|
}
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
],
|
|
1185
|
-
};
|
|
1186
|
-
const routes = mergeAuthenticatedRoute(current.routes, remoteRoute, now);
|
|
1187
|
-
return {
|
|
1188
|
-
state: { ...current, meshes: replaceMesh(current.meshes, updated), routes },
|
|
1189
|
-
result: {
|
|
1190
|
-
kind: 'invitation-redeemed',
|
|
1191
|
-
roster: state.roster,
|
|
1192
|
-
routes: responseRoutes(updated, routes, [{ peerId: remotePeerId, sequence: Number.MAX_SAFE_INTEGER }], now).routes,
|
|
1193
|
-
},
|
|
1194
|
-
};
|
|
1195
|
-
}
|
|
1196
|
-
const members = [...state.roster.roster.members, remotePeerId].sort();
|
|
1197
|
-
const roster = signPeerMeshRoster({
|
|
1198
|
-
...state.roster.roster,
|
|
1199
|
-
revision: state.roster.roster.revision + 1,
|
|
1200
|
-
members,
|
|
1201
|
-
}, authorityKeys(state));
|
|
1408
|
+
const existingMember = state.roster.roster.members.includes(remotePeerId);
|
|
1409
|
+
const roster = existingMember
|
|
1410
|
+
? state.roster
|
|
1411
|
+
: signPeerMeshRoster({
|
|
1412
|
+
...state.roster.roster,
|
|
1413
|
+
revision: state.roster.roster.revision + 1,
|
|
1414
|
+
members: [...state.roster.roster.members, remotePeerId].sort(),
|
|
1415
|
+
}, authorityKeys(state));
|
|
1202
1416
|
const updated = {
|
|
1203
1417
|
...state,
|
|
1204
1418
|
roster,
|
|
@@ -1207,21 +1421,29 @@ class PeerMeshNodeImpl {
|
|
|
1207
1421
|
redeemedInvitation(invitation, remotePeerId),
|
|
1208
1422
|
],
|
|
1209
1423
|
};
|
|
1210
|
-
const
|
|
1424
|
+
const reachability = mergeReachability(current.reachability, [remoteReachability], now);
|
|
1425
|
+
const advertisements = mergeAdvertisements(current.advertisements, [remoteAdvertisement]);
|
|
1426
|
+
const evidence = initialEvidence(updated, reachability, advertisements, this.#peer.identity().peerId, now);
|
|
1211
1427
|
return {
|
|
1212
|
-
state: {
|
|
1428
|
+
state: {
|
|
1429
|
+
...current,
|
|
1430
|
+
meshes: replaceMesh(current.meshes, updated),
|
|
1431
|
+
reachability,
|
|
1432
|
+
advertisements,
|
|
1433
|
+
},
|
|
1213
1434
|
result: {
|
|
1214
1435
|
kind: 'invitation-redeemed',
|
|
1215
1436
|
roster,
|
|
1216
|
-
|
|
1437
|
+
...evidence,
|
|
1217
1438
|
},
|
|
1218
1439
|
};
|
|
1219
1440
|
});
|
|
1220
1441
|
if (response.kind === 'invitation-redeemed') {
|
|
1442
|
+
this.#recordReachabilityReceipt(remoteReachability);
|
|
1221
1443
|
const stored = this.#store.read();
|
|
1222
1444
|
const state = findMesh(stored.meshes, request.meshId);
|
|
1223
1445
|
if (state) {
|
|
1224
|
-
this.#scheduleRosterAnnouncement(state.roster, rosterAnnouncementTargets(state.roster.roster.members, stored.
|
|
1446
|
+
this.#scheduleRosterAnnouncement(state.roster, rosterAnnouncementTargets(state.roster.roster.members, stored.reachability, this.#peer.identity().peerId, this.#now()).filter(({ lease }) => lease.peerId !== remotePeerId));
|
|
1225
1447
|
}
|
|
1226
1448
|
}
|
|
1227
1449
|
return response;
|
|
@@ -1265,14 +1487,15 @@ class PeerMeshNodeImpl {
|
|
|
1265
1487
|
const stored = this.#store.read();
|
|
1266
1488
|
const state = findMesh(stored.meshes, request.meshId);
|
|
1267
1489
|
if (state) {
|
|
1268
|
-
this.#scheduleRosterAnnouncement(state.roster, rosterAnnouncementTargets(state.roster.roster.members, stored.
|
|
1490
|
+
this.#scheduleRosterAnnouncement(state.roster, rosterAnnouncementTargets(state.roster.roster.members, stored.reachability, this.#peer.identity().peerId, this.#now()));
|
|
1269
1491
|
}
|
|
1270
1492
|
}
|
|
1271
1493
|
return response;
|
|
1272
1494
|
}
|
|
1273
1495
|
async #sync(request, remotePeerId) {
|
|
1274
|
-
const
|
|
1275
|
-
|
|
1496
|
+
const remoteReachability = this.#authenticateReachability(request.reachability, remotePeerId);
|
|
1497
|
+
const remoteAdvertisement = this.#validateAdvertisementForPeer(request.advertisement, request.meshId, remotePeerId);
|
|
1498
|
+
await this.#refreshLocalEvidence();
|
|
1276
1499
|
const incomingRoster = decodeSignedPeerMeshRoster(request.roster);
|
|
1277
1500
|
const response = await this.#store.mutate((current) => {
|
|
1278
1501
|
const state = findMesh(current.meshes, request.meshId);
|
|
@@ -1290,51 +1513,66 @@ class PeerMeshNodeImpl {
|
|
|
1290
1513
|
};
|
|
1291
1514
|
const localMember = isActiveMembership(updated, localPeerId);
|
|
1292
1515
|
const remoteMember = !roster.roster.closed && roster.roster.members.includes(remotePeerId);
|
|
1293
|
-
const
|
|
1294
|
-
?
|
|
1295
|
-
: current.
|
|
1516
|
+
const reachability = localMember && remoteMember
|
|
1517
|
+
? mergeReachability(current.reachability, [remoteReachability], this.#now())
|
|
1518
|
+
: current.reachability;
|
|
1519
|
+
const advertisements = localMember && remoteMember
|
|
1520
|
+
? mergeAdvertisements(current.advertisements, [remoteAdvertisement])
|
|
1521
|
+
: current.advertisements;
|
|
1296
1522
|
if (!localMember || !remoteMember) {
|
|
1297
1523
|
return {
|
|
1298
|
-
state: {
|
|
1524
|
+
state: {
|
|
1525
|
+
...current,
|
|
1526
|
+
meshes: replaceMesh(current.meshes, updated),
|
|
1527
|
+
reachability,
|
|
1528
|
+
advertisements,
|
|
1529
|
+
},
|
|
1299
1530
|
result: {
|
|
1300
1531
|
kind: 'sync-result',
|
|
1301
1532
|
roster,
|
|
1302
|
-
|
|
1533
|
+
reachability: [],
|
|
1534
|
+
advertisements: [],
|
|
1303
1535
|
more: false,
|
|
1304
1536
|
},
|
|
1305
1537
|
};
|
|
1306
1538
|
}
|
|
1307
|
-
const page =
|
|
1539
|
+
const page = responseEvidence(updated, reachability, advertisements, request.knownReachability, request.knownAdvertisements, this.#now());
|
|
1308
1540
|
return {
|
|
1309
|
-
state: {
|
|
1541
|
+
state: {
|
|
1542
|
+
...current,
|
|
1543
|
+
meshes: replaceMesh(current.meshes, updated),
|
|
1544
|
+
reachability,
|
|
1545
|
+
advertisements,
|
|
1546
|
+
},
|
|
1310
1547
|
result: {
|
|
1311
1548
|
kind: 'sync-result',
|
|
1312
1549
|
roster,
|
|
1313
|
-
|
|
1314
|
-
more: page.more,
|
|
1550
|
+
...page,
|
|
1315
1551
|
},
|
|
1316
1552
|
};
|
|
1317
1553
|
});
|
|
1318
|
-
if (response.kind === 'sync-result')
|
|
1554
|
+
if (response.kind === 'sync-result') {
|
|
1555
|
+
const localPeerId = this.#peer.identity().peerId;
|
|
1556
|
+
if (!response.roster.roster.closed &&
|
|
1557
|
+
response.roster.roster.members.includes(localPeerId) &&
|
|
1558
|
+
response.roster.roster.members.includes(remotePeerId)) {
|
|
1559
|
+
this.#recordReachabilityReceipt(remoteReachability);
|
|
1560
|
+
}
|
|
1319
1561
|
await this.#reconcileTransit();
|
|
1562
|
+
}
|
|
1320
1563
|
return response;
|
|
1321
1564
|
}
|
|
1322
|
-
|
|
1565
|
+
#reconcileTransit() {
|
|
1566
|
+
const task = this.#transitTail.then(() => this.#applyTransitSnapshot());
|
|
1567
|
+
this.#transitTail = task.then(() => undefined, () => undefined);
|
|
1568
|
+
return task;
|
|
1569
|
+
}
|
|
1570
|
+
async #applyTransitSnapshot() {
|
|
1323
1571
|
const stored = this.#store.read();
|
|
1324
1572
|
const localPeerId = this.#peer.identity().peerId;
|
|
1325
1573
|
const now = this.#now();
|
|
1326
1574
|
const selected = stored.meshes.find((mesh) => mesh.roster.roster.meshId === stored.transitMeshId && isActiveMembership(mesh, localPeerId));
|
|
1327
|
-
const eligibleRelays = stored
|
|
1328
|
-
.filter(({ route }) => {
|
|
1329
|
-
if (route.peerId === localPeerId ||
|
|
1330
|
-
route.expiresAt <= now ||
|
|
1331
|
-
route.transitMeshId === undefined ||
|
|
1332
|
-
route.routeHints.length + route.coordinationRelays.length === 0) {
|
|
1333
|
-
return false;
|
|
1334
|
-
}
|
|
1335
|
-
return isActiveMeshMember(stored.meshes, route.transitMeshId, localPeerId, route.peerId);
|
|
1336
|
-
})
|
|
1337
|
-
.sort((left, right) => left.route.peerId.localeCompare(right.route.peerId));
|
|
1575
|
+
const eligibleRelays = eligibleTransitEvidence(stored, localPeerId, now, (signed) => this.#isReachabilityCurrent(signed));
|
|
1338
1576
|
const relayCandidates = transitRelayCandidates(eligibleRelays);
|
|
1339
1577
|
const approvedRelayPeerIds = [
|
|
1340
1578
|
...new Set(stored.meshes
|
|
@@ -1351,20 +1589,50 @@ class PeerMeshNodeImpl {
|
|
|
1351
1589
|
});
|
|
1352
1590
|
}
|
|
1353
1591
|
}
|
|
1354
|
-
function
|
|
1592
|
+
function sameResolvedRoutes(left, right) {
|
|
1593
|
+
return (left.state === right.state &&
|
|
1594
|
+
sameStringValues(left.routeHints, right.routeHints) &&
|
|
1595
|
+
sameStringValues(left.coordinationRelays, right.coordinationRelays) &&
|
|
1596
|
+
sameStringValues(left.transitRelayPeerIds, right.transitRelayPeerIds));
|
|
1597
|
+
}
|
|
1598
|
+
function sameStringValues(left, right) {
|
|
1599
|
+
return left.length === right.length && left.every((value, index) => value === right[index]);
|
|
1600
|
+
}
|
|
1601
|
+
function eligibleTransitEvidence(stored, localPeerId, now, isCurrent) {
|
|
1602
|
+
const evidence = new Map();
|
|
1603
|
+
for (const { advertisement } of stored.advertisements) {
|
|
1604
|
+
if (advertisement.peerId === localPeerId ||
|
|
1605
|
+
!advertisement.offersTransit ||
|
|
1606
|
+
!isActiveMeshMember(stored.meshes, advertisement.meshId, localPeerId, advertisement.peerId)) {
|
|
1607
|
+
continue;
|
|
1608
|
+
}
|
|
1609
|
+
const lease = latestReachability(stored.reachability, advertisement.peerId, now, true);
|
|
1610
|
+
if (!lease ||
|
|
1611
|
+
!isCurrent(lease) ||
|
|
1612
|
+
lease.lease.directRoutes.length + lease.lease.coordinationRoutes.length === 0) {
|
|
1613
|
+
continue;
|
|
1614
|
+
}
|
|
1615
|
+
evidence.set(advertisement.peerId, {
|
|
1616
|
+
meshId: advertisement.meshId,
|
|
1617
|
+
lease,
|
|
1618
|
+
});
|
|
1619
|
+
}
|
|
1620
|
+
return Object.freeze([...evidence.values()].sort((left, right) => left.lease.lease.peerId.localeCompare(right.lease.lease.peerId)));
|
|
1621
|
+
}
|
|
1622
|
+
function transitRelayCandidates(evidence) {
|
|
1355
1623
|
let remaining = PEER_MESH_MAX_TRANSIT_RELAY_ADDRESSES;
|
|
1356
1624
|
const candidates = [];
|
|
1357
|
-
for (const {
|
|
1625
|
+
for (const { lease: { lease }, } of evidence) {
|
|
1358
1626
|
if (remaining === 0)
|
|
1359
1627
|
break;
|
|
1360
1628
|
const routeHints = [
|
|
1361
|
-
...new Set(
|
|
1629
|
+
...new Set(lease.directRoutes.filter((address) => isBaseRelayFor(address, lease.peerId))),
|
|
1362
1630
|
].slice(0, Math.min(PEER_MESH_MAX_TRANSIT_ADDRESSES_PER_RELAY, remaining));
|
|
1363
|
-
const coordinationRelays = [...new Set(
|
|
1631
|
+
const coordinationRelays = [...new Set(lease.coordinationRoutes)].slice(0, Math.min(PEER_MESH_MAX_TRANSIT_ADDRESSES_PER_RELAY - routeHints.length, remaining - routeHints.length));
|
|
1364
1632
|
if (routeHints.length + coordinationRelays.length === 0)
|
|
1365
1633
|
continue;
|
|
1366
1634
|
candidates.push(Object.freeze({
|
|
1367
|
-
peerId:
|
|
1635
|
+
peerId: lease.peerId,
|
|
1368
1636
|
addresses: Object.freeze(routeHints),
|
|
1369
1637
|
coordinationRelays: Object.freeze(coordinationRelays),
|
|
1370
1638
|
}));
|
|
@@ -1385,12 +1653,12 @@ function isActiveMeshMember(meshes, meshId, localPeerId, peerId) {
|
|
|
1385
1653
|
isActiveMembership(mesh, localPeerId) &&
|
|
1386
1654
|
mesh.roster.roster.members.includes(peerId));
|
|
1387
1655
|
}
|
|
1388
|
-
function peerMeshStatus(state, identity, endpointKind,
|
|
1389
|
-
const
|
|
1390
|
-
|
|
1656
|
+
function peerMeshStatus(state, identity, endpointKind, reachability, advertisements, now, isConnected, resolveRoutes, isCurrent) {
|
|
1657
|
+
const meshId = state.roster.roster.meshId;
|
|
1658
|
+
const localAdvertisement = findAdvertisement(advertisements, meshId, identity.peerId);
|
|
1391
1659
|
return Object.freeze({
|
|
1392
1660
|
role: state.role === 'authority' ? 'authority' : 'member',
|
|
1393
|
-
|
|
1661
|
+
authorityPeerId: state.roster.roster.authorityPeerId,
|
|
1394
1662
|
roster: state.roster,
|
|
1395
1663
|
pendingInvitationCount: state.role === 'authority'
|
|
1396
1664
|
? state.invitations.filter((invitation) => invitation.status === 'pending' && invitation.expiresAt > now).length
|
|
@@ -1400,47 +1668,46 @@ function peerMeshStatus(state, identity, endpointKind, routes = [], now = Date.n
|
|
|
1400
1668
|
return Object.freeze({
|
|
1401
1669
|
peerId,
|
|
1402
1670
|
...(endpointKind ? { endpointKind } : {}),
|
|
1403
|
-
...(
|
|
1671
|
+
...(localAdvertisement?.advertisement.displayName
|
|
1672
|
+
? { displayName: localAdvertisement.advertisement.displayName }
|
|
1673
|
+
: {}),
|
|
1404
1674
|
state: 'local',
|
|
1405
1675
|
});
|
|
1406
1676
|
}
|
|
1407
|
-
const
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1677
|
+
const advertisement = findAdvertisement(advertisements, meshId, peerId)?.advertisement;
|
|
1678
|
+
const signed = latestReachability(reachability, peerId, now, true);
|
|
1679
|
+
const lease = signed?.lease;
|
|
1680
|
+
const resolution = resolveRoutes(peerId);
|
|
1681
|
+
const current = Boolean(signed && isCurrent(signed));
|
|
1682
|
+
const memberState = isConnected(peerId)
|
|
1683
|
+
? 'reachable'
|
|
1684
|
+
: resolution.state === 'exhausted'
|
|
1685
|
+
? 'needs_repair'
|
|
1686
|
+
: resolution.state === 'recovering'
|
|
1687
|
+
? signed
|
|
1688
|
+
? 'reconnecting'
|
|
1689
|
+
: 'connecting'
|
|
1690
|
+
: current
|
|
1691
|
+
? 'connecting'
|
|
1692
|
+
: 'reconnecting';
|
|
1419
1693
|
return Object.freeze({
|
|
1420
1694
|
peerId,
|
|
1421
|
-
...(
|
|
1422
|
-
...(
|
|
1423
|
-
state:
|
|
1424
|
-
|
|
1425
|
-
: 'coordination_only',
|
|
1426
|
-
expiresAt: route.expiresAt,
|
|
1695
|
+
...(advertisement?.endpointKind ? { endpointKind: advertisement.endpointKind } : {}),
|
|
1696
|
+
...(advertisement?.displayName ? { displayName: advertisement.displayName } : {}),
|
|
1697
|
+
state: memberState,
|
|
1698
|
+
...(lease ? { expiresAt: lease.expiresAt } : {}),
|
|
1427
1699
|
});
|
|
1428
1700
|
})),
|
|
1429
1701
|
});
|
|
1430
1702
|
}
|
|
1431
|
-
function currentAuthorityTarget(state,
|
|
1432
|
-
|
|
1433
|
-
return learned ? mergeTargets(learned, state.authority) : state.authority;
|
|
1703
|
+
function currentAuthorityTarget(state, reachability, now) {
|
|
1704
|
+
return latestReachability(reachability, state.roster.roster.authorityPeerId, now, true);
|
|
1434
1705
|
}
|
|
1435
|
-
function rosterAnnouncementTargets(memberPeerIds,
|
|
1706
|
+
function rosterAnnouncementTargets(memberPeerIds, reachability, localPeerId, now) {
|
|
1436
1707
|
const members = new Set(memberPeerIds);
|
|
1437
|
-
return Object.freeze(
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
peerId: route.peerId,
|
|
1441
|
-
routeHints: route.routeHints,
|
|
1442
|
-
coordinationRelays: route.coordinationRelays,
|
|
1443
|
-
})));
|
|
1708
|
+
return Object.freeze(reachability.filter((signed) => signed.lease.peerId !== localPeerId &&
|
|
1709
|
+
members.has(signed.lease.peerId) &&
|
|
1710
|
+
usableHistoricalReachability(signed, now)));
|
|
1444
1711
|
}
|
|
1445
1712
|
function requireAuthority(states, meshId) {
|
|
1446
1713
|
const state = findMesh(states, meshId);
|
|
@@ -1464,13 +1731,6 @@ function redeemedInvitation(invitation, peerId) {
|
|
|
1464
1731
|
peerId,
|
|
1465
1732
|
};
|
|
1466
1733
|
}
|
|
1467
|
-
function authorityTarget(identity) {
|
|
1468
|
-
return Object.freeze({
|
|
1469
|
-
peerId: identity.peerId,
|
|
1470
|
-
routeHints: identity.listenAddresses,
|
|
1471
|
-
coordinationRelays: identity.coordinationRelays,
|
|
1472
|
-
});
|
|
1473
|
-
}
|
|
1474
1734
|
function assertMeshCapacity(states, localPeerId, pendingJoinCount = 0) {
|
|
1475
1735
|
if (states.filter((state) => !isRetired(state, localPeerId)).length + pendingJoinCount >=
|
|
1476
1736
|
PEER_MESH_MAX_MESHES) {
|
|
@@ -1494,7 +1754,8 @@ function assertRejoinSettled(state, localPeerId) {
|
|
|
1494
1754
|
}
|
|
1495
1755
|
function selectRoster(current, candidate) {
|
|
1496
1756
|
if (current.roster.meshId !== candidate.roster.meshId ||
|
|
1497
|
-
current.authorityPublicKey !== candidate.authorityPublicKey
|
|
1757
|
+
current.authorityPublicKey !== candidate.authorityPublicKey ||
|
|
1758
|
+
current.roster.authorityPeerId !== candidate.roster.authorityPeerId) {
|
|
1498
1759
|
throw new Error('Peer Mesh roster has the wrong authority');
|
|
1499
1760
|
}
|
|
1500
1761
|
if (candidate.roster.revision < current.roster.revision)
|
|
@@ -1507,61 +1768,190 @@ function selectRoster(current, candidate) {
|
|
|
1507
1768
|
}
|
|
1508
1769
|
return candidate;
|
|
1509
1770
|
}
|
|
1510
|
-
function
|
|
1511
|
-
const
|
|
1771
|
+
function mergeReachability(current, candidates, now) {
|
|
1772
|
+
const leases = new Map(current
|
|
1773
|
+
.filter((signed) => usableHistoricalReachability(signed, now))
|
|
1774
|
+
.map((signed) => [signed.lease.peerId, signed]));
|
|
1512
1775
|
for (const candidate of candidates) {
|
|
1513
|
-
if (candidate
|
|
1776
|
+
if (!usableHistoricalReachability(candidate, now))
|
|
1514
1777
|
continue;
|
|
1515
|
-
const existing =
|
|
1516
|
-
if (!existing ||
|
|
1517
|
-
|
|
1518
|
-
candidate.route.sequence > existing.route.sequence) {
|
|
1519
|
-
routes.set(candidate.route.peerId, candidate);
|
|
1778
|
+
const existing = leases.get(candidate.lease.peerId);
|
|
1779
|
+
if (!existing || candidate.lease.revision > existing.lease.revision) {
|
|
1780
|
+
leases.set(candidate.lease.peerId, candidate);
|
|
1520
1781
|
continue;
|
|
1521
1782
|
}
|
|
1522
|
-
if (candidate.
|
|
1523
|
-
|
|
1524
|
-
throw new Error('Peer
|
|
1783
|
+
if (candidate.lease.revision === existing.lease.revision &&
|
|
1784
|
+
reachabilityFactDigest(candidate) !== reachabilityFactDigest(existing)) {
|
|
1785
|
+
throw new Error('Peer reachability revision identifies conflicting facts');
|
|
1525
1786
|
}
|
|
1526
1787
|
}
|
|
1527
|
-
return Object.freeze([...
|
|
1788
|
+
return Object.freeze([...leases.values()].sort((left, right) => left.lease.peerId.localeCompare(right.lease.peerId)));
|
|
1528
1789
|
}
|
|
1529
|
-
function
|
|
1530
|
-
const
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
existing
|
|
1534
|
-
|
|
1790
|
+
function mergeAdvertisements(current, candidates) {
|
|
1791
|
+
const advertisements = new Map(current.map((signed) => [advertisementKey(signed.advertisement), signed]));
|
|
1792
|
+
for (const candidate of candidates) {
|
|
1793
|
+
const key = advertisementKey(candidate.advertisement);
|
|
1794
|
+
const existing = advertisements.get(key);
|
|
1795
|
+
if (!existing || candidate.advertisement.revision > existing.advertisement.revision) {
|
|
1796
|
+
advertisements.set(key, candidate);
|
|
1797
|
+
continue;
|
|
1798
|
+
}
|
|
1799
|
+
if (candidate.advertisement.revision === existing.advertisement.revision &&
|
|
1800
|
+
advertisementFactDigest(candidate) !== advertisementFactDigest(existing)) {
|
|
1801
|
+
throw new Error('Peer Mesh advertisement revision identifies conflicting facts');
|
|
1802
|
+
}
|
|
1535
1803
|
}
|
|
1536
|
-
return
|
|
1804
|
+
return Object.freeze([...advertisements.values()].sort((left, right) => advertisementKey(left.advertisement).localeCompare(advertisementKey(right.advertisement))));
|
|
1537
1805
|
}
|
|
1538
|
-
function
|
|
1539
|
-
return Object.freeze(
|
|
1540
|
-
.filter((
|
|
1541
|
-
.
|
|
1806
|
+
function reachabilitySummaries(reachability, roster, now) {
|
|
1807
|
+
return Object.freeze(reachability
|
|
1808
|
+
.filter((signed) => usableHistoricalReachability(signed, now) &&
|
|
1809
|
+
roster.roster.members.includes(signed.lease.peerId))
|
|
1810
|
+
.map((signed) => Object.freeze({
|
|
1811
|
+
peerId: signed.lease.peerId,
|
|
1812
|
+
revision: signed.lease.revision,
|
|
1813
|
+
digest: reachabilityFactDigest(signed),
|
|
1814
|
+
}))
|
|
1542
1815
|
.sort((left, right) => left.peerId.localeCompare(right.peerId)));
|
|
1543
1816
|
}
|
|
1544
|
-
function
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1817
|
+
function advertisementSummaries(advertisements, roster) {
|
|
1818
|
+
return Object.freeze(advertisements
|
|
1819
|
+
.filter(({ advertisement }) => advertisement.meshId === roster.roster.meshId &&
|
|
1820
|
+
roster.roster.members.includes(advertisement.peerId))
|
|
1821
|
+
.map((signed) => Object.freeze({
|
|
1822
|
+
peerId: signed.advertisement.peerId,
|
|
1823
|
+
revision: signed.advertisement.revision,
|
|
1824
|
+
digest: advertisementFactDigest(signed),
|
|
1825
|
+
}))
|
|
1826
|
+
.sort((left, right) => left.peerId.localeCompare(right.peerId)));
|
|
1827
|
+
}
|
|
1828
|
+
function responseEvidence(state, reachability, advertisements, knownReachability, knownAdvertisements, now) {
|
|
1829
|
+
const knownLeases = new Map(knownReachability.map((summary) => [summary.peerId, summary]));
|
|
1830
|
+
const knownAds = new Map(knownAdvertisements.map((summary) => [summary.peerId, summary]));
|
|
1831
|
+
const missing = [
|
|
1832
|
+
...reachability
|
|
1833
|
+
.filter((signed) => usableHistoricalReachability(signed, now) &&
|
|
1834
|
+
state.roster.roster.members.includes(signed.lease.peerId) &&
|
|
1835
|
+
evidenceRequiresTransfer({
|
|
1836
|
+
peerId: signed.lease.peerId,
|
|
1837
|
+
revision: signed.lease.revision,
|
|
1838
|
+
digest: reachabilityFactDigest(signed),
|
|
1839
|
+
}, knownLeases.get(signed.lease.peerId), 'Peer reachability'))
|
|
1840
|
+
.map((value) => ({
|
|
1841
|
+
kind: 'reachability',
|
|
1842
|
+
peerId: value.lease.peerId,
|
|
1843
|
+
value,
|
|
1844
|
+
})),
|
|
1845
|
+
...advertisements
|
|
1846
|
+
.filter((signed) => signed.advertisement.meshId === state.roster.roster.meshId &&
|
|
1847
|
+
state.roster.roster.members.includes(signed.advertisement.peerId) &&
|
|
1848
|
+
evidenceRequiresTransfer({
|
|
1849
|
+
peerId: signed.advertisement.peerId,
|
|
1850
|
+
revision: signed.advertisement.revision,
|
|
1851
|
+
digest: advertisementFactDigest(signed),
|
|
1852
|
+
}, knownAds.get(signed.advertisement.peerId), 'Peer Mesh advertisement'))
|
|
1853
|
+
.map((value) => ({
|
|
1854
|
+
kind: 'advertisement',
|
|
1855
|
+
peerId: value.advertisement.peerId,
|
|
1856
|
+
value,
|
|
1857
|
+
})),
|
|
1858
|
+
].sort((left, right) => left.peerId === right.peerId
|
|
1859
|
+
? left.kind.localeCompare(right.kind)
|
|
1860
|
+
: left.peerId.localeCompare(right.peerId));
|
|
1861
|
+
const page = missing.slice(0, EVIDENCE_PAGE_SIZE);
|
|
1549
1862
|
return Object.freeze({
|
|
1550
|
-
|
|
1551
|
-
|
|
1863
|
+
reachability: Object.freeze(page.flatMap((entry) => (entry.kind === 'reachability' ? [entry.value] : []))),
|
|
1864
|
+
advertisements: Object.freeze(page.flatMap((entry) => (entry.kind === 'advertisement' ? [entry.value] : []))),
|
|
1865
|
+
more: missing.length > EVIDENCE_PAGE_SIZE,
|
|
1552
1866
|
});
|
|
1553
1867
|
}
|
|
1554
|
-
function
|
|
1555
|
-
|
|
1868
|
+
function evidenceRequiresTransfer(local, remote, label) {
|
|
1869
|
+
if (!remote || local.revision > remote.revision)
|
|
1870
|
+
return true;
|
|
1871
|
+
if (local.revision < remote.revision)
|
|
1872
|
+
return false;
|
|
1873
|
+
if (local.digest !== remote.digest) {
|
|
1874
|
+
throw new Error(`${label} revision identifies conflicting facts`);
|
|
1875
|
+
}
|
|
1876
|
+
return false;
|
|
1877
|
+
}
|
|
1878
|
+
function reachabilityFactDigest(signed) {
|
|
1879
|
+
return evidenceDigest(peerReachabilityLeaseSigningBytes(signed.lease));
|
|
1880
|
+
}
|
|
1881
|
+
function advertisementFactDigest(signed) {
|
|
1882
|
+
return evidenceDigest(peerMeshMemberAdvertisementSigningBytes(signed.advertisement));
|
|
1556
1883
|
}
|
|
1557
|
-
function
|
|
1884
|
+
function evidenceDigest(bytes) {
|
|
1885
|
+
return createHash('sha256').update(bytes).digest('hex');
|
|
1886
|
+
}
|
|
1887
|
+
function initialEvidence(state, reachability, advertisements, localPeerId, now) {
|
|
1888
|
+
const lease = latestReachability(reachability, localPeerId, now, true);
|
|
1889
|
+
const advertisement = findAdvertisement(advertisements, state.roster.roster.meshId, localPeerId);
|
|
1890
|
+
if (!lease || !advertisement)
|
|
1891
|
+
throw new Error('Peer Mesh authority evidence is unavailable');
|
|
1892
|
+
return Object.freeze({
|
|
1893
|
+
reachability: Object.freeze([lease]),
|
|
1894
|
+
advertisements: Object.freeze([advertisement]),
|
|
1895
|
+
});
|
|
1896
|
+
}
|
|
1897
|
+
function isCurrentLocalAdvertisement(existing, meshId, peerId, current, endpointKind) {
|
|
1558
1898
|
return Boolean(existing &&
|
|
1559
|
-
existing.
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
existing.
|
|
1563
|
-
existing.
|
|
1564
|
-
|
|
1899
|
+
existing.advertisement.meshId === meshId &&
|
|
1900
|
+
existing.advertisement.peerId === peerId &&
|
|
1901
|
+
existing.advertisement.endpointKind === endpointKind &&
|
|
1902
|
+
existing.advertisement.displayName === (current.displayName ?? undefined) &&
|
|
1903
|
+
existing.advertisement.offersTransit === (current.transitMeshId === meshId));
|
|
1904
|
+
}
|
|
1905
|
+
function latestReachability(reachability, peerId, now, includeHistorical) {
|
|
1906
|
+
const signed = reachability.find(({ lease }) => lease.peerId === peerId);
|
|
1907
|
+
if (!signed)
|
|
1908
|
+
return undefined;
|
|
1909
|
+
if (signed.lease.expiresAt > now)
|
|
1910
|
+
return signed;
|
|
1911
|
+
return includeHistorical && usableHistoricalReachability(signed, now) ? signed : undefined;
|
|
1912
|
+
}
|
|
1913
|
+
function emptyRouteResolution(state) {
|
|
1914
|
+
return Object.freeze({
|
|
1915
|
+
state,
|
|
1916
|
+
routeHints: Object.freeze([]),
|
|
1917
|
+
coordinationRelays: Object.freeze([]),
|
|
1918
|
+
transitRelayPeerIds: Object.freeze([]),
|
|
1919
|
+
});
|
|
1920
|
+
}
|
|
1921
|
+
function hasPeerRecoverySource(stored, sharedMeshIds, targetPeerId, localPeerId, now) {
|
|
1922
|
+
const shared = new Set(sharedMeshIds);
|
|
1923
|
+
const sourcePeerIds = new Set(stored.meshes
|
|
1924
|
+
.filter(({ roster }) => shared.has(roster.roster.meshId))
|
|
1925
|
+
.flatMap(({ roster }) => roster.roster.members)
|
|
1926
|
+
.filter((peerId) => peerId !== localPeerId && peerId !== targetPeerId));
|
|
1927
|
+
for (const sourcePeerId of sourcePeerIds) {
|
|
1928
|
+
const signed = latestReachability(stored.reachability, sourcePeerId, now, true);
|
|
1929
|
+
if (signed && hasReachabilityRoutes(signed))
|
|
1930
|
+
return true;
|
|
1931
|
+
}
|
|
1932
|
+
return false;
|
|
1933
|
+
}
|
|
1934
|
+
function hasReachabilityRoutes(signed) {
|
|
1935
|
+
return signed.lease.directRoutes.length + signed.lease.coordinationRoutes.length > 0;
|
|
1936
|
+
}
|
|
1937
|
+
function usableHistoricalReachability(signed, now) {
|
|
1938
|
+
return signed.lease.expiresAt > now - PEER_REACHABILITY_RECOVERY_HORIZON_MS;
|
|
1939
|
+
}
|
|
1940
|
+
function peerTarget(peerId, reachability, now) {
|
|
1941
|
+
return latestReachability(reachability, peerId, now, true);
|
|
1942
|
+
}
|
|
1943
|
+
function dialTarget(reachability) {
|
|
1944
|
+
return Object.freeze({
|
|
1945
|
+
peerId: reachability.lease.peerId,
|
|
1946
|
+
routeHints: reachability.lease.directRoutes,
|
|
1947
|
+
coordinationRelays: reachability.lease.coordinationRoutes,
|
|
1948
|
+
});
|
|
1949
|
+
}
|
|
1950
|
+
function findAdvertisement(advertisements, meshId, peerId) {
|
|
1951
|
+
return advertisements.find(({ advertisement }) => advertisement.meshId === meshId && advertisement.peerId === peerId);
|
|
1952
|
+
}
|
|
1953
|
+
function advertisementKey(advertisement) {
|
|
1954
|
+
return `${advertisement.meshId}\n${advertisement.peerId}`;
|
|
1565
1955
|
}
|
|
1566
1956
|
function mergeAddresses(primary, fallback) {
|
|
1567
1957
|
return Object.freeze([...new Set([...primary, ...fallback])].slice(0, 32));
|
|
@@ -1580,15 +1970,6 @@ function waitForTurn(previous, signal) {
|
|
|
1580
1970
|
});
|
|
1581
1971
|
});
|
|
1582
1972
|
}
|
|
1583
|
-
function mergeTargets(primary, fallback) {
|
|
1584
|
-
return Object.freeze({
|
|
1585
|
-
peerId: primary.peerId,
|
|
1586
|
-
routeHints: Object.freeze([...new Set([...primary.routeHints, ...fallback.routeHints])]),
|
|
1587
|
-
coordinationRelays: Object.freeze([
|
|
1588
|
-
...new Set([...primary.coordinationRelays, ...fallback.coordinationRelays]),
|
|
1589
|
-
]),
|
|
1590
|
-
});
|
|
1591
|
-
}
|
|
1592
1973
|
async function exchangeControl(stream, request, decode, signal) {
|
|
1593
1974
|
const timeout = AbortSignal.timeout(CONTROL_REQUEST_DEADLINE_MS);
|
|
1594
1975
|
const operationSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
@@ -1614,22 +1995,33 @@ async function exchangeControl(stream, request, decode, signal) {
|
|
|
1614
1995
|
function decodeControlRequest(value) {
|
|
1615
1996
|
const record = recordValue(value);
|
|
1616
1997
|
if (record.kind === 'redeem-invitation' &&
|
|
1617
|
-
hasExactKeys(record, ['kind', 'meshId', 'secret', '
|
|
1998
|
+
hasExactKeys(record, ['kind', 'meshId', 'secret', 'reachability', 'advertisement'])) {
|
|
1618
1999
|
return {
|
|
1619
2000
|
kind: 'redeem-invitation',
|
|
1620
2001
|
meshId: requiredString(record.meshId, 128),
|
|
1621
2002
|
secret: requiredString(record.secret, 64),
|
|
1622
|
-
|
|
2003
|
+
reachability: decodeSignedPeerReachabilityLease(record.reachability),
|
|
2004
|
+
advertisement: decodeSignedPeerMeshMemberAdvertisement(record.advertisement),
|
|
1623
2005
|
};
|
|
1624
2006
|
}
|
|
1625
2007
|
if (record.kind === 'sync' &&
|
|
1626
|
-
hasExactKeys(record, [
|
|
2008
|
+
hasExactKeys(record, [
|
|
2009
|
+
'kind',
|
|
2010
|
+
'meshId',
|
|
2011
|
+
'roster',
|
|
2012
|
+
'reachability',
|
|
2013
|
+
'advertisement',
|
|
2014
|
+
'knownReachability',
|
|
2015
|
+
'knownAdvertisements',
|
|
2016
|
+
])) {
|
|
1627
2017
|
return {
|
|
1628
2018
|
kind: 'sync',
|
|
1629
2019
|
meshId: requiredString(record.meshId, 128),
|
|
1630
2020
|
roster: decodeSignedPeerMeshRoster(record.roster),
|
|
1631
|
-
|
|
1632
|
-
|
|
2021
|
+
reachability: decodeSignedPeerReachabilityLease(record.reachability),
|
|
2022
|
+
advertisement: decodeSignedPeerMeshMemberAdvertisement(record.advertisement),
|
|
2023
|
+
knownReachability: decodeEvidenceSummaries(record.knownReachability),
|
|
2024
|
+
knownAdvertisements: decodeEvidenceSummaries(record.knownAdvertisements),
|
|
1633
2025
|
};
|
|
1634
2026
|
}
|
|
1635
2027
|
if (record.kind === 'leave' && hasExactKeys(record, ['kind', 'meshId', 'roster'])) {
|
|
@@ -1650,11 +2042,16 @@ function decodeControlRequest(value) {
|
|
|
1650
2042
|
}
|
|
1651
2043
|
function decodeRedeemResponse(value) {
|
|
1652
2044
|
const record = recordValue(value);
|
|
1653
|
-
if (record.kind === 'invitation-redeemed' &&
|
|
2045
|
+
if (record.kind === 'invitation-redeemed' &&
|
|
2046
|
+
hasExactKeys(record, ['kind', 'roster', 'reachability', 'advertisements'])) {
|
|
2047
|
+
const reachability = decodeReachabilityPage(record.reachability);
|
|
2048
|
+
const advertisements = decodeAdvertisementPage(record.advertisements);
|
|
2049
|
+
assertEvidencePageSize(reachability, advertisements);
|
|
1654
2050
|
return {
|
|
1655
2051
|
kind: 'invitation-redeemed',
|
|
1656
2052
|
roster: decodeSignedPeerMeshRoster(record.roster),
|
|
1657
|
-
|
|
2053
|
+
reachability,
|
|
2054
|
+
advertisements,
|
|
1658
2055
|
};
|
|
1659
2056
|
}
|
|
1660
2057
|
if (record.kind === 'invitation-rejected' &&
|
|
@@ -1670,12 +2067,16 @@ function decodeRedeemResponse(value) {
|
|
|
1670
2067
|
function decodeSyncResponse(value) {
|
|
1671
2068
|
const record = recordValue(value);
|
|
1672
2069
|
if (record.kind === 'sync-result' &&
|
|
1673
|
-
hasExactKeys(record, ['kind', 'roster', '
|
|
2070
|
+
hasExactKeys(record, ['kind', 'roster', 'reachability', 'advertisements', 'more']) &&
|
|
1674
2071
|
typeof record.more === 'boolean') {
|
|
2072
|
+
const reachability = decodeReachabilityPage(record.reachability);
|
|
2073
|
+
const advertisements = decodeAdvertisementPage(record.advertisements);
|
|
2074
|
+
assertEvidencePageSize(reachability, advertisements);
|
|
1675
2075
|
return {
|
|
1676
2076
|
kind: 'sync-result',
|
|
1677
2077
|
roster: decodeSignedPeerMeshRoster(record.roster),
|
|
1678
|
-
|
|
2078
|
+
reachability,
|
|
2079
|
+
advertisements,
|
|
1679
2080
|
more: record.more,
|
|
1680
2081
|
};
|
|
1681
2082
|
}
|
|
@@ -1710,34 +2111,49 @@ function decodeAnnounceRosterResponse(value) {
|
|
|
1710
2111
|
}
|
|
1711
2112
|
throw new Error('Invalid Peer Mesh roster announcement response');
|
|
1712
2113
|
}
|
|
1713
|
-
function
|
|
1714
|
-
if (!Array.isArray(value) || value.length >
|
|
1715
|
-
throw new Error('Invalid Peer Mesh
|
|
2114
|
+
function decodeReachabilityPage(value) {
|
|
2115
|
+
if (!Array.isArray(value) || value.length > EVIDENCE_PAGE_SIZE) {
|
|
2116
|
+
throw new Error('Invalid Peer Mesh reachability page');
|
|
2117
|
+
}
|
|
2118
|
+
return Object.freeze(value.map(decodeSignedPeerReachabilityLease));
|
|
2119
|
+
}
|
|
2120
|
+
function decodeAdvertisementPage(value) {
|
|
2121
|
+
if (!Array.isArray(value) || value.length > EVIDENCE_PAGE_SIZE) {
|
|
2122
|
+
throw new Error('Invalid Peer Mesh advertisement page');
|
|
1716
2123
|
}
|
|
1717
|
-
return Object.freeze(value.map(
|
|
2124
|
+
return Object.freeze(value.map(decodeSignedPeerMeshMemberAdvertisement));
|
|
1718
2125
|
}
|
|
1719
|
-
function
|
|
2126
|
+
function assertEvidencePageSize(reachability, advertisements) {
|
|
2127
|
+
if (reachability.length + advertisements.length > EVIDENCE_PAGE_SIZE) {
|
|
2128
|
+
throw new Error('Peer Mesh evidence page exceeds its bound');
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
function decodeEvidenceSummaries(value) {
|
|
1720
2132
|
if (!Array.isArray(value) || value.length > PEER_MESH_MAX_MEMBERS) {
|
|
1721
|
-
throw new Error('Invalid Peer Mesh
|
|
2133
|
+
throw new Error('Invalid Peer Mesh evidence revisions');
|
|
1722
2134
|
}
|
|
1723
|
-
const
|
|
2135
|
+
const revisions = value.map((entry) => {
|
|
1724
2136
|
const record = recordValue(entry);
|
|
1725
|
-
if (!hasExactKeys(record, ['peerId', '
|
|
1726
|
-
throw new Error('Invalid Peer Mesh
|
|
2137
|
+
if (!hasExactKeys(record, ['peerId', 'revision', 'digest'])) {
|
|
2138
|
+
throw new Error('Invalid Peer Mesh evidence revision');
|
|
2139
|
+
}
|
|
2140
|
+
const revision = record.revision;
|
|
2141
|
+
if (!Number.isSafeInteger(revision) || revision < 1) {
|
|
2142
|
+
throw new Error('Invalid Peer Mesh evidence revision');
|
|
1727
2143
|
}
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
throw new Error('Invalid Peer Mesh route sequence');
|
|
2144
|
+
if (typeof record.digest !== 'string' || !/^[0-9a-f]{64}$/u.test(record.digest)) {
|
|
2145
|
+
throw new Error('Invalid Peer Mesh evidence digest');
|
|
1731
2146
|
}
|
|
1732
2147
|
return Object.freeze({
|
|
1733
2148
|
peerId: requiredString(record.peerId, 256),
|
|
1734
|
-
|
|
2149
|
+
revision: revision,
|
|
2150
|
+
digest: record.digest,
|
|
1735
2151
|
});
|
|
1736
2152
|
});
|
|
1737
|
-
if (new Set(
|
|
1738
|
-
throw new Error('Duplicate Peer Mesh
|
|
2153
|
+
if (new Set(revisions.map(({ peerId }) => peerId)).size !== revisions.length) {
|
|
2154
|
+
throw new Error('Duplicate Peer Mesh evidence revision');
|
|
1739
2155
|
}
|
|
1740
|
-
return Object.freeze(
|
|
2156
|
+
return Object.freeze(revisions);
|
|
1741
2157
|
}
|
|
1742
2158
|
async function writeFrame(stream, value) {
|
|
1743
2159
|
const bytes = Buffer.from(`${JSON.stringify(value)}\n`);
|