@bowl42/keywire 0.0.0-stage → 0.3.1
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/LICENSE +21 -0
- package/README.md +118 -2
- package/dist/app.d.ts +2 -0
- package/dist/app.js +13 -0
- package/dist/app.js.map +1 -0
- package/dist/bytes.d.ts +1 -0
- package/dist/bytes.js +7 -0
- package/dist/bytes.js.map +1 -0
- package/dist/client.d.ts +66 -0
- package/dist/client.js +846 -0
- package/dist/client.js.map +1 -0
- package/dist/compress/block.d.ts +51 -0
- package/dist/compress/block.js +667 -0
- package/dist/compress/block.js.map +1 -0
- package/dist/compress/deflate.d.ts +7 -0
- package/dist/compress/deflate.js +603 -0
- package/dist/compress/deflate.js.map +1 -0
- package/dist/compress/index.d.ts +6 -0
- package/dist/compress/index.js +13 -0
- package/dist/compress/index.js.map +1 -0
- package/dist/compress/inflate.d.ts +21 -0
- package/dist/compress/inflate.js +380 -0
- package/dist/compress/inflate.js.map +1 -0
- package/dist/compress/wasm.d.ts +50 -0
- package/dist/compress/wasm.js +192 -0
- package/dist/compress/wasm.js.map +1 -0
- package/dist/compress/zlib-wasm.d.ts +15 -0
- package/dist/compress/zlib-wasm.js +18 -0
- package/dist/compress/zlib-wasm.js.map +1 -0
- package/dist/conn.d.ts +126 -0
- package/dist/conn.js +685 -0
- package/dist/conn.js.map +1 -0
- package/dist/dial/index.d.ts +3 -0
- package/dist/dial/index.js +10 -0
- package/dist/dial/index.js.map +1 -0
- package/dist/discovery/index.d.ts +16 -0
- package/dist/discovery/index.js +173 -0
- package/dist/discovery/index.js.map +1 -0
- package/dist/discovery/reach.d.ts +4 -0
- package/dist/discovery/reach.js +36 -0
- package/dist/discovery/reach.js.map +1 -0
- package/dist/domain.d.ts +3 -0
- package/dist/domain.js +12 -0
- package/dist/domain.js.map +1 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +49 -0
- package/dist/errors.js.map +1 -0
- package/dist/extension.d.ts +53 -0
- package/dist/extension.js +158 -0
- package/dist/extension.js.map +1 -0
- package/dist/forward.d.ts +11 -0
- package/dist/forward.js +125 -0
- package/dist/forward.js.map +1 -0
- package/dist/framed-stream.d.ts +14 -0
- package/dist/framed-stream.js +113 -0
- package/dist/framed-stream.js.map +1 -0
- package/dist/gen/keywire/discovery/v1/discovery_pb.d.ts +105 -0
- package/dist/gen/keywire/discovery/v1/discovery_pb.js +57 -0
- package/dist/gen/keywire/discovery/v1/discovery_pb.js.map +1 -0
- package/dist/gen/keywire/state/v1/state_pb.d.ts +988 -0
- package/dist/gen/keywire/state/v1/state_pb.js +184 -0
- package/dist/gen/keywire/state/v1/state_pb.js.map +1 -0
- package/dist/gen/keywire/v1/forward_pb.d.ts +53 -0
- package/dist/gen/keywire/v1/forward_pb.js +58 -0
- package/dist/gen/keywire/v1/forward_pb.js.map +1 -0
- package/dist/gen/keywire/v1/guest_pb.d.ts +322 -0
- package/dist/gen/keywire/v1/guest_pb.js +100 -0
- package/dist/gen/keywire/v1/guest_pb.js.map +1 -0
- package/dist/gen/keywire/v1/pair_pb.d.ts +106 -0
- package/dist/gen/keywire/v1/pair_pb.js +45 -0
- package/dist/gen/keywire/v1/pair_pb.js.map +1 -0
- package/dist/gen/keywire/v1/relay_pb.d.ts +116 -0
- package/dist/gen/keywire/v1/relay_pb.js +20 -0
- package/dist/gen/keywire/v1/relay_pb.js.map +1 -0
- package/dist/gen/keywire/v1/roster_pb.d.ts +213 -0
- package/dist/gen/keywire/v1/roster_pb.js +77 -0
- package/dist/gen/keywire/v1/roster_pb.js.map +1 -0
- package/dist/gen/keywire/v1/sync_pb.d.ts +68 -0
- package/dist/gen/keywire/v1/sync_pb.js +24 -0
- package/dist/gen/keywire/v1/sync_pb.js.map +1 -0
- package/dist/guest/equal-bytes.d.ts +1 -0
- package/dist/guest/equal-bytes.js +10 -0
- package/dist/guest/equal-bytes.js.map +1 -0
- package/dist/guest/hello.d.ts +4 -0
- package/dist/guest/hello.js +42 -0
- package/dist/guest/hello.js.map +1 -0
- package/dist/guest/invite-frame.d.ts +8 -0
- package/dist/guest/invite-frame.js +44 -0
- package/dist/guest/invite-frame.js.map +1 -0
- package/dist/guest/invite.d.ts +17 -0
- package/dist/guest/invite.js +86 -0
- package/dist/guest/invite.js.map +1 -0
- package/dist/guest/relay-hello.d.ts +2 -0
- package/dist/guest/relay-hello.js +38 -0
- package/dist/guest/relay-hello.js.map +1 -0
- package/dist/guest/revocations.d.ts +12 -0
- package/dist/guest/revocations.js +134 -0
- package/dist/guest/revocations.js.map +1 -0
- package/dist/guest/roster.d.ts +2 -0
- package/dist/guest/roster.js +14 -0
- package/dist/guest/roster.js.map +1 -0
- package/dist/guest/token-payload.d.ts +2 -0
- package/dist/guest/token-payload.js +71 -0
- package/dist/guest/token-payload.js.map +1 -0
- package/dist/guest-conn.d.ts +20 -0
- package/dist/guest-conn.js +99 -0
- package/dist/guest-conn.js.map +1 -0
- package/dist/guest-relay.d.ts +7 -0
- package/dist/guest-relay.js +45 -0
- package/dist/guest-relay.js.map +1 -0
- package/dist/guest.d.ts +20 -0
- package/dist/guest.js +99 -0
- package/dist/guest.js.map +1 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +28 -0
- package/dist/index.js.map +1 -0
- package/dist/msg-path.d.ts +9 -0
- package/dist/msg-path.js +2 -0
- package/dist/msg-path.js.map +1 -0
- package/dist/mux/byte-queue.d.ts +9 -0
- package/dist/mux/byte-queue.js +62 -0
- package/dist/mux/byte-queue.js.map +1 -0
- package/dist/mux/codec.d.ts +30 -0
- package/dist/mux/codec.js +23 -0
- package/dist/mux/codec.js.map +1 -0
- package/dist/mux/errors.d.ts +23 -0
- package/dist/mux/errors.js +47 -0
- package/dist/mux/errors.js.map +1 -0
- package/dist/mux/frame.d.ts +44 -0
- package/dist/mux/frame.js +161 -0
- package/dist/mux/frame.js.map +1 -0
- package/dist/mux/nexttask.d.ts +1 -0
- package/dist/mux/nexttask.js +19 -0
- package/dist/mux/nexttask.js.map +1 -0
- package/dist/mux/session.d.ts +69 -0
- package/dist/mux/session.js +586 -0
- package/dist/mux/session.js.map +1 -0
- package/dist/mux/signal.d.ts +5 -0
- package/dist/mux/signal.js +14 -0
- package/dist/mux/signal.js.map +1 -0
- package/dist/mux/stream.d.ts +34 -0
- package/dist/mux/stream.js +620 -0
- package/dist/mux/stream.js.map +1 -0
- package/dist/nodekit/device.d.ts +40 -0
- package/dist/nodekit/device.js +188 -0
- package/dist/nodekit/device.js.map +1 -0
- package/dist/nodekit/index.d.ts +5 -0
- package/dist/nodekit/index.js +8 -0
- package/dist/nodekit/index.js.map +1 -0
- package/dist/nodekit/indexeddb.d.ts +2 -0
- package/dist/nodekit/indexeddb.js +114 -0
- package/dist/nodekit/indexeddb.js.map +1 -0
- package/dist/nodekit/pair-device.d.ts +27 -0
- package/dist/nodekit/pair-device.js +44 -0
- package/dist/nodekit/pair-device.js.map +1 -0
- package/dist/nodekit/sealed-signer.d.ts +22 -0
- package/dist/nodekit/sealed-signer.js +74 -0
- package/dist/nodekit/sealed-signer.js.map +1 -0
- package/dist/nodekit/store.d.ts +22 -0
- package/dist/nodekit/store.js +21 -0
- package/dist/nodekit/store.js.map +1 -0
- package/dist/noise/backend.d.ts +25 -0
- package/dist/noise/backend.js +2 -0
- package/dist/noise/backend.js.map +1 -0
- package/dist/noise/backends.d.ts +4 -0
- package/dist/noise/backends.js +19 -0
- package/dist/noise/backends.js.map +1 -0
- package/dist/noise/cipher.d.ts +18 -0
- package/dist/noise/cipher.js +69 -0
- package/dist/noise/cipher.js.map +1 -0
- package/dist/noise/crypto.d.ts +11 -0
- package/dist/noise/crypto.js +47 -0
- package/dist/noise/crypto.js.map +1 -0
- package/dist/noise/handshake.d.ts +28 -0
- package/dist/noise/handshake.js +183 -0
- package/dist/noise/handshake.js.map +1 -0
- package/dist/noise/import.d.ts +2 -0
- package/dist/noise/import.js +16 -0
- package/dist/noise/import.js.map +1 -0
- package/dist/noise/noble.d.ts +2 -0
- package/dist/noise/noble.js +51 -0
- package/dist/noise/noble.js.map +1 -0
- package/dist/noise/pair-code.d.ts +2 -0
- package/dist/noise/pair-code.js +11 -0
- package/dist/noise/pair-code.js.map +1 -0
- package/dist/noise/pkcs8.d.ts +3 -0
- package/dist/noise/pkcs8.js +18 -0
- package/dist/noise/pkcs8.js.map +1 -0
- package/dist/noise/sealed.d.ts +21 -0
- package/dist/noise/sealed.js +40 -0
- package/dist/noise/sealed.js.map +1 -0
- package/dist/noise/symmetric.d.ts +17 -0
- package/dist/noise/symmetric.js +56 -0
- package/dist/noise/symmetric.js.map +1 -0
- package/dist/noise/webcrypto.d.ts +3 -0
- package/dist/noise/webcrypto.js +98 -0
- package/dist/noise/webcrypto.js.map +1 -0
- package/dist/pair-relay.d.ts +4 -0
- package/dist/pair-relay.js +46 -0
- package/dist/pair-relay.js.map +1 -0
- package/dist/pair.d.ts +7 -0
- package/dist/pair.js +50 -0
- package/dist/pair.js.map +1 -0
- package/dist/paths/link.d.ts +33 -0
- package/dist/paths/link.js +132 -0
- package/dist/paths/link.js.map +1 -0
- package/dist/paths/node-paths.d.ts +10 -0
- package/dist/paths/node-paths.js +41 -0
- package/dist/paths/node-paths.js.map +1 -0
- package/dist/paths/path.d.ts +11 -0
- package/dist/paths/path.js +25 -0
- package/dist/paths/path.js.map +1 -0
- package/dist/paths/race.d.ts +18 -0
- package/dist/paths/race.js +157 -0
- package/dist/paths/race.js.map +1 -0
- package/dist/paths/relay-sessions.d.ts +11 -0
- package/dist/paths/relay-sessions.js +93 -0
- package/dist/paths/relay-sessions.js.map +1 -0
- package/dist/paths/upgrades.d.ts +12 -0
- package/dist/paths/upgrades.js +58 -0
- package/dist/paths/upgrades.js.map +1 -0
- package/dist/relay-server/admission.d.ts +24 -0
- package/dist/relay-server/admission.js +140 -0
- package/dist/relay-server/admission.js.map +1 -0
- package/dist/relay-server/config.d.ts +28 -0
- package/dist/relay-server/config.js +47 -0
- package/dist/relay-server/config.js.map +1 -0
- package/dist/relay-server/discovery/addr.d.ts +18 -0
- package/dist/relay-server/discovery/addr.js +211 -0
- package/dist/relay-server/discovery/addr.js.map +1 -0
- package/dist/relay-server/discovery/directory.d.ts +42 -0
- package/dist/relay-server/discovery/directory.js +101 -0
- package/dist/relay-server/discovery/directory.js.map +1 -0
- package/dist/relay-server/discovery/http.d.ts +10 -0
- package/dist/relay-server/discovery/http.js +172 -0
- package/dist/relay-server/discovery/http.js.map +1 -0
- package/dist/relay-server/discovery/index.d.ts +6 -0
- package/dist/relay-server/discovery/index.js +15 -0
- package/dist/relay-server/discovery/index.js.map +1 -0
- package/dist/relay-server/discovery/listing.d.ts +24 -0
- package/dist/relay-server/discovery/listing.js +115 -0
- package/dist/relay-server/discovery/listing.js.map +1 -0
- package/dist/relay-server/discovery/options.d.ts +39 -0
- package/dist/relay-server/discovery/options.js +97 -0
- package/dist/relay-server/discovery/options.js.map +1 -0
- package/dist/relay-server/discovery/service.d.ts +21 -0
- package/dist/relay-server/discovery/service.js +409 -0
- package/dist/relay-server/discovery/service.js.map +1 -0
- package/dist/relay-server/forward.d.ts +3 -0
- package/dist/relay-server/forward.js +97 -0
- package/dist/relay-server/forward.js.map +1 -0
- package/dist/relay-server/handshake.d.ts +10 -0
- package/dist/relay-server/handshake.js +36 -0
- package/dist/relay-server/handshake.js.map +1 -0
- package/dist/relay-server/index.d.ts +6 -0
- package/dist/relay-server/index.js +10 -0
- package/dist/relay-server/index.js.map +1 -0
- package/dist/relay-server/relay.d.ts +25 -0
- package/dist/relay-server/relay.js +392 -0
- package/dist/relay-server/relay.js.map +1 -0
- package/dist/relay-server/service-read.d.ts +4 -0
- package/dist/relay-server/service-read.js +16 -0
- package/dist/relay-server/service-read.js.map +1 -0
- package/dist/relay-server/service.d.ts +25 -0
- package/dist/relay-server/service.js +8 -0
- package/dist/relay-server/service.js.map +1 -0
- package/dist/relay-server/session.d.ts +60 -0
- package/dist/relay-server/session.js +35 -0
- package/dist/relay-server/session.js.map +1 -0
- package/dist/relay-server/url.d.ts +1 -0
- package/dist/relay-server/url.js +8 -0
- package/dist/relay-server/url.js.map +1 -0
- package/dist/relay-url.d.ts +2 -0
- package/dist/relay-url.js +11 -0
- package/dist/relay-url.js.map +1 -0
- package/dist/relay.d.ts +5 -0
- package/dist/relay.js +60 -0
- package/dist/relay.js.map +1 -0
- package/dist/roster/admission.d.ts +17 -0
- package/dist/roster/admission.js +85 -0
- package/dist/roster/admission.js.map +1 -0
- package/dist/roster/credentials.d.ts +5 -0
- package/dist/roster/credentials.js +72 -0
- package/dist/roster/credentials.js.map +1 -0
- package/dist/roster/digest.d.ts +3 -0
- package/dist/roster/digest.js +23 -0
- package/dist/roster/digest.js.map +1 -0
- package/dist/roster/envelope.d.ts +11 -0
- package/dist/roster/envelope.js +35 -0
- package/dist/roster/envelope.js.map +1 -0
- package/dist/roster/errors.d.ts +6 -0
- package/dist/roster/errors.js +11 -0
- package/dist/roster/errors.js.map +1 -0
- package/dist/roster/limits.d.ts +25 -0
- package/dist/roster/limits.js +26 -0
- package/dist/roster/limits.js.map +1 -0
- package/dist/roster/merge.d.ts +10 -0
- package/dist/roster/merge.js +101 -0
- package/dist/roster/merge.js.map +1 -0
- package/dist/roster/name.d.ts +1 -0
- package/dist/roster/name.js +7 -0
- package/dist/roster/name.js.map +1 -0
- package/dist/roster/order.d.ts +5 -0
- package/dist/roster/order.js +22 -0
- package/dist/roster/order.js.map +1 -0
- package/dist/roster/ownership.d.ts +9 -0
- package/dist/roster/ownership.js +42 -0
- package/dist/roster/ownership.js.map +1 -0
- package/dist/roster/retain.d.ts +2 -0
- package/dist/roster/retain.js +55 -0
- package/dist/roster/retain.js.map +1 -0
- package/dist/roster/revocations.d.ts +5 -0
- package/dist/roster/revocations.js +37 -0
- package/dist/roster/revocations.js.map +1 -0
- package/dist/roster/scan.d.ts +16 -0
- package/dist/roster/scan.js +194 -0
- package/dist/roster/scan.js.map +1 -0
- package/dist/roster/state.d.ts +34 -0
- package/dist/roster/state.js +204 -0
- package/dist/roster/state.js.map +1 -0
- package/dist/roster/statement.d.ts +38 -0
- package/dist/roster/statement.js +176 -0
- package/dist/roster/statement.js.map +1 -0
- package/dist/roster/types.d.ts +35 -0
- package/dist/roster/types.js +2 -0
- package/dist/roster/types.js.map +1 -0
- package/dist/roster/verify.d.ts +3 -0
- package/dist/roster/verify.js +63 -0
- package/dist/roster/verify.js.map +1 -0
- package/dist/roster-sync/apply.d.ts +2 -0
- package/dist/roster-sync/apply.js +23 -0
- package/dist/roster-sync/apply.js.map +1 -0
- package/dist/roster-sync/exchange.d.ts +3 -0
- package/dist/roster-sync/exchange.js +25 -0
- package/dist/roster-sync/exchange.js.map +1 -0
- package/dist/roster-sync/frame.d.ts +17 -0
- package/dist/roster-sync/frame.js +66 -0
- package/dist/roster-sync/frame.js.map +1 -0
- package/dist/roster-sync/records.d.ts +8 -0
- package/dist/roster-sync/records.js +78 -0
- package/dist/roster-sync/records.js.map +1 -0
- package/dist/roster-sync/sync.d.ts +12 -0
- package/dist/roster-sync/sync.js +69 -0
- package/dist/roster-sync/sync.js.map +1 -0
- package/dist/rtc.d.ts +15 -0
- package/dist/rtc.js +275 -0
- package/dist/rtc.js.map +1 -0
- package/dist/state/errors.d.ts +30 -0
- package/dist/state/errors.js +72 -0
- package/dist/state/errors.js.map +1 -0
- package/dist/state/index.d.ts +6 -0
- package/dist/state/index.js +11 -0
- package/dist/state/index.js.map +1 -0
- package/dist/state/limits.d.ts +34 -0
- package/dist/state/limits.js +115 -0
- package/dist/state/limits.js.map +1 -0
- package/dist/state/remote.d.ts +217 -0
- package/dist/state/remote.js +1934 -0
- package/dist/state/remote.js.map +1 -0
- package/dist/state/shared.d.ts +56 -0
- package/dist/state/shared.js +300 -0
- package/dist/state/shared.js.map +1 -0
- package/dist/state/state.d.ts +118 -0
- package/dist/state/state.js +1048 -0
- package/dist/state/state.js.map +1 -0
- package/dist/state/store.d.ts +31 -0
- package/dist/state/store.js +375 -0
- package/dist/state/store.js.map +1 -0
- package/dist/state/wire.d.ts +43 -0
- package/dist/state/wire.js +179 -0
- package/dist/state/wire.js.map +1 -0
- package/dist/strict-proto.d.ts +10 -0
- package/dist/strict-proto.js +167 -0
- package/dist/strict-proto.js.map +1 -0
- package/dist/token.d.ts +18 -0
- package/dist/token.js +60 -0
- package/dist/token.js.map +1 -0
- package/dist/urls.d.ts +7 -0
- package/dist/urls.js +117 -0
- package/dist/urls.js.map +1 -0
- package/dist/ws.d.ts +19 -0
- package/dist/ws.js +143 -0
- package/dist/ws.js.map +1 -0
- package/package.json +72 -3
package/dist/client.js
ADDED
|
@@ -0,0 +1,846 @@
|
|
|
1
|
+
import { bytesToHex } from "@noble/hashes/utils.js";
|
|
2
|
+
import { acceptPath, compressionModeOf, dial, openExtensionStream, registerService, serveExtension, } from "./conn.js";
|
|
3
|
+
import { resolveDomain } from "./domain.js";
|
|
4
|
+
import { KeywireError } from "./errors.js";
|
|
5
|
+
import { attachExtensions, checkExtensions, extensionLink, RoleFeeds, } from "./extension.js";
|
|
6
|
+
import { FramedStream } from "./framed-stream.js";
|
|
7
|
+
import { GoingAway, SessionClosed } from "./mux/errors.js";
|
|
8
|
+
import { CODE_CANCEL, CODE_REFUSED } from "./mux/frame.js";
|
|
9
|
+
import { NodePaths } from "./paths/node-paths.js";
|
|
10
|
+
import { improvesPath } from "./paths/path.js";
|
|
11
|
+
import { watchNetwork } from "./paths/upgrades.js";
|
|
12
|
+
import { maxOwners } from "./roster/limits.js";
|
|
13
|
+
import { syncRoster } from "./roster-sync/sync.js";
|
|
14
|
+
import { serveRtc } from "./rtc.js";
|
|
15
|
+
// MAX_DRAINING bounds the connections to one device going away while they
|
|
16
|
+
// still carry streams: past it a better path waits, closed, rather than
|
|
17
|
+
// cut what they carry.
|
|
18
|
+
const MAX_DRAINING = 2;
|
|
19
|
+
// ROSTER_DEBOUNCE_MS is how long after a change to the roster the Client
|
|
20
|
+
// syncs it with every device it is connected to.
|
|
21
|
+
// ADMISSION_CHECK_MS is how often the feeds take this device's role anew,
|
|
22
|
+
// as Go's admission check.
|
|
23
|
+
const ADMISSION_CHECK_MS = 60_000;
|
|
24
|
+
const ROSTER_DEBOUNCE_MS = 500;
|
|
25
|
+
// FORWARDED_PER_CONN bounds the connections a Node forwards to this device
|
|
26
|
+
// over one connection at once, handshakes included.
|
|
27
|
+
const FORWARDED_PER_CONN = 32;
|
|
28
|
+
const hex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
29
|
+
const equal = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
|
|
30
|
+
function positive(value, fallback, name) {
|
|
31
|
+
const v = value ?? fallback;
|
|
32
|
+
if (!Number.isSafeInteger(v) || v < 1)
|
|
33
|
+
throw new RangeError(`keywire: ${name} must be a positive integer`);
|
|
34
|
+
return v;
|
|
35
|
+
}
|
|
36
|
+
class Peer {
|
|
37
|
+
key;
|
|
38
|
+
link;
|
|
39
|
+
current;
|
|
40
|
+
since = 0;
|
|
41
|
+
dialing;
|
|
42
|
+
kept = false;
|
|
43
|
+
// conns are every connection to the device until it closes, made by
|
|
44
|
+
// either side, and how each reaches it.
|
|
45
|
+
conns = new Map();
|
|
46
|
+
retryMs = 0;
|
|
47
|
+
retry;
|
|
48
|
+
retryAt = 0;
|
|
49
|
+
failures = 0;
|
|
50
|
+
constructor(key, link) {
|
|
51
|
+
this.key = key;
|
|
52
|
+
this.link = link;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
// Client keeps this device's connections to the devices of its Network:
|
|
56
|
+
// Nodes, at their endpoints, through other Nodes and through relays, and
|
|
57
|
+
// members, through the Nodes it is connected to, which also bring it the
|
|
58
|
+
// connections other devices make to it. An application opens streams to a
|
|
59
|
+
// device by its key and accepts those devices open; which connection
|
|
60
|
+
// carries them, and when a better one replaces it, is the Client's to
|
|
61
|
+
// decide. It syncs the roster with every device it is connected to, and
|
|
62
|
+
// runs the application's extensions on those connections: it is the
|
|
63
|
+
// TypeScript counterpart of Go's Network, for devices that sign nothing.
|
|
64
|
+
export class Client {
|
|
65
|
+
#opts;
|
|
66
|
+
#paths;
|
|
67
|
+
#peers = new Map();
|
|
68
|
+
#queues = new Map();
|
|
69
|
+
#turns = [];
|
|
70
|
+
#takers = [];
|
|
71
|
+
#watchers = new Set();
|
|
72
|
+
#unwatch;
|
|
73
|
+
#retryMin;
|
|
74
|
+
#retryMax;
|
|
75
|
+
#acceptQueue;
|
|
76
|
+
#acceptPerPeer;
|
|
77
|
+
// pending counts the forwarded handshakes in progress, at most
|
|
78
|
+
// #pendingHandshakes.
|
|
79
|
+
#pending = { active: 0 };
|
|
80
|
+
#pendingHandshakes;
|
|
81
|
+
// dialed are the connections this device made, the only ones it has go
|
|
82
|
+
// away.
|
|
83
|
+
#dialed = new WeakSet();
|
|
84
|
+
#rtcSetups = { active: 0 };
|
|
85
|
+
#extensions;
|
|
86
|
+
// syncs are the roster syncs of the connections the Client keeps.
|
|
87
|
+
#syncs = new Map();
|
|
88
|
+
// feeds are the extensions' RoleFeeds; standing checks them every
|
|
89
|
+
// ADMISSION_CHECK_MS, as a member's standing lapses with no roster
|
|
90
|
+
// change.
|
|
91
|
+
#feeds;
|
|
92
|
+
#standing;
|
|
93
|
+
#saving = Promise.resolve();
|
|
94
|
+
#push;
|
|
95
|
+
#queued = 0;
|
|
96
|
+
#moved = false;
|
|
97
|
+
#closed = false;
|
|
98
|
+
constructor(opts) {
|
|
99
|
+
if (resolveDomain(opts.domain) !== opts.roster.domain)
|
|
100
|
+
throw new Error("keywire: roster domain mismatch");
|
|
101
|
+
compressionModeOf(opts);
|
|
102
|
+
this.#opts = opts;
|
|
103
|
+
this.#extensions = [...(opts.extensions ?? [])];
|
|
104
|
+
checkExtensions(this.#extensions);
|
|
105
|
+
this.#retryMin = positive(opts.retryMinMs, 1000, "retryMinMs");
|
|
106
|
+
this.#retryMax = positive(opts.retryMaxMs, 30_000, "retryMaxMs");
|
|
107
|
+
if (this.#retryMax < this.#retryMin)
|
|
108
|
+
throw new RangeError("keywire: retryMaxMs must not be below retryMinMs");
|
|
109
|
+
this.#acceptQueue = positive(opts.acceptQueue, 256, "acceptQueue");
|
|
110
|
+
this.#acceptPerPeer = positive(opts.acceptPerPeer, 32, "acceptPerPeer");
|
|
111
|
+
this.#pendingHandshakes = positive(opts.pendingHandshakes, 64, "pendingHandshakes");
|
|
112
|
+
this.#paths = new NodePaths(opts.dialers, opts.stun);
|
|
113
|
+
this.#unwatch =
|
|
114
|
+
opts.events === null ? () => { } : watchNetwork(() => this.#networkChanged(), opts.events);
|
|
115
|
+
// Attaching is last, before any connection: an attach that throws
|
|
116
|
+
// leaves nothing behind.
|
|
117
|
+
this.#feeds = new RoleFeeds((e) => this.#opts.onError?.(e));
|
|
118
|
+
try {
|
|
119
|
+
attachExtensions(this.#extensions, opts.keypair.publicKey, this.#feeds, this.#selfRole(), this.#extensions.some((e) => e.attach) ? this.#admissions() : "");
|
|
120
|
+
}
|
|
121
|
+
catch (e) {
|
|
122
|
+
this.#unwatch();
|
|
123
|
+
this.#paths.close();
|
|
124
|
+
throw e;
|
|
125
|
+
}
|
|
126
|
+
if (this.#feeds.size)
|
|
127
|
+
this.#standing = setInterval(() => this.#updateFeeds(), ADMISSION_CHECK_MS);
|
|
128
|
+
this.#keepNodes();
|
|
129
|
+
}
|
|
130
|
+
// #selfRole is the role the roster admits this device with now.
|
|
131
|
+
#selfRole() {
|
|
132
|
+
return this.#opts.roster.admitted(this.#opts.keypair.publicKey, Date.now())?.role;
|
|
133
|
+
}
|
|
134
|
+
// #admissions is a digest of whom the roster admits now, and in what role
|
|
135
|
+
// and standing: owners by key and conflict, members by key and expiry.
|
|
136
|
+
#admissions() {
|
|
137
|
+
const r = this.#opts.roster;
|
|
138
|
+
let d = "";
|
|
139
|
+
for (const o of r.owners())
|
|
140
|
+
d += `o${bytesToHex(o.noiseKey)}${o.conflict ? 1 : 0}`;
|
|
141
|
+
for (const m of r.members(Date.now()))
|
|
142
|
+
d += `m${bytesToHex(m.noiseKey)}.${m.expiresMs}`;
|
|
143
|
+
return d;
|
|
144
|
+
}
|
|
145
|
+
// #updateFeeds has the feeds take this device's role and whom the roster
|
|
146
|
+
// admits now.
|
|
147
|
+
#updateFeeds() {
|
|
148
|
+
if (this.#feeds.size)
|
|
149
|
+
this.#feeds.set(this.#selfRole(), this.#admissions());
|
|
150
|
+
}
|
|
151
|
+
// connect connects to the device with key at a WebSocket URL learned
|
|
152
|
+
// outside the roster, such as where it paired, for openStream to use, as
|
|
153
|
+
// Go's Network.Connect. The connection stays only if it is the first to
|
|
154
|
+
// the device or a better path than the one in use.
|
|
155
|
+
async connect(url, key, signal) {
|
|
156
|
+
const peer = this.#peer(key);
|
|
157
|
+
const conn = await (this.#opts.dialers?.direct ?? dial)(url, {
|
|
158
|
+
...this.#dialOptions(peer.key),
|
|
159
|
+
...(signal && { signal }),
|
|
160
|
+
});
|
|
161
|
+
const result = { conn, path: "direct" };
|
|
162
|
+
if (this.#closed || (peer.current && !improvesPath(peer.current, result))) {
|
|
163
|
+
conn.close();
|
|
164
|
+
if (this.#closed)
|
|
165
|
+
throw new KeywireError("closed", "client");
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
peer.link.accepted(result);
|
|
169
|
+
this.#adopt(peer, result);
|
|
170
|
+
}
|
|
171
|
+
// syncRoster waits for a complete roster exchange with the device with
|
|
172
|
+
// key, over the best connection to it, connecting first as openStream
|
|
173
|
+
// does. The Client syncs the roster on its own as it changes; this is
|
|
174
|
+
// for a caller that needs the device's records now.
|
|
175
|
+
async syncRoster(key, signal) {
|
|
176
|
+
const conn = await this.#connect(this.#peer(key), signal);
|
|
177
|
+
const sync = this.#syncs.get(conn);
|
|
178
|
+
if (!sync)
|
|
179
|
+
throw new KeywireError("closed", "connection");
|
|
180
|
+
await sync.sync();
|
|
181
|
+
}
|
|
182
|
+
// ready resolves once the device with key is connected, connecting if
|
|
183
|
+
// need be; signal ends the wait, not the attempt, which others may share.
|
|
184
|
+
async ready(key, signal) {
|
|
185
|
+
await this.#connect(this.#peer(key), signal);
|
|
186
|
+
}
|
|
187
|
+
// openStream opens a stream to the device with key over the best
|
|
188
|
+
// connection to it, connecting first if there is none: a Node at its
|
|
189
|
+
// endpoints, through other Nodes and through its relays; a member through
|
|
190
|
+
// the Nodes this device is connected to, the first that holds it.
|
|
191
|
+
// options.compress asks for the stream to be compressed (StreamOptions).
|
|
192
|
+
async openStream(key, signal, options) {
|
|
193
|
+
const peer = this.#peer(key);
|
|
194
|
+
for (let attempt = 0;; attempt++) {
|
|
195
|
+
const conn = await this.#connect(peer, signal);
|
|
196
|
+
try {
|
|
197
|
+
return conn.openStream(options);
|
|
198
|
+
}
|
|
199
|
+
catch (e) {
|
|
200
|
+
// It went away, or ended, between choosing it and opening on it.
|
|
201
|
+
if (attempt >= 2 || !(e instanceof GoingAway || e instanceof SessionClosed))
|
|
202
|
+
throw e;
|
|
203
|
+
if (peer.current?.conn === conn)
|
|
204
|
+
this.#lost(peer, conn);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
// openExtensionStream opens a stream of an extension service to the
|
|
209
|
+
// device with key, over the best connection to it, connecting first if
|
|
210
|
+
// there is none, as openStream does. This Client must run an extension
|
|
211
|
+
// of service, and both devices must be admitted. Each call chooses
|
|
212
|
+
// again, so a caller opening a stream per request follows the device
|
|
213
|
+
// across path changes.
|
|
214
|
+
async openExtensionStream(key, service, signal, options) {
|
|
215
|
+
if (!this.#extensions.some((e) => e.service === service))
|
|
216
|
+
throw new KeywireError("not-extension", `service ${service}`);
|
|
217
|
+
const peer = this.#peer(key);
|
|
218
|
+
for (let attempt = 0;; attempt++) {
|
|
219
|
+
const conn = await this.#connect(peer, signal);
|
|
220
|
+
if (!this.#roles(peer.key))
|
|
221
|
+
throw new KeywireError("not-extension", "the peer is not admitted");
|
|
222
|
+
try {
|
|
223
|
+
const st = openExtensionStream(conn, service, options);
|
|
224
|
+
st.peer = conn.peer.slice();
|
|
225
|
+
return st;
|
|
226
|
+
}
|
|
227
|
+
catch (e) {
|
|
228
|
+
if (attempt >= 2 || !(e instanceof GoingAway || e instanceof SessionClosed))
|
|
229
|
+
throw e;
|
|
230
|
+
if (peer.current?.conn === conn)
|
|
231
|
+
this.#lost(peer, conn);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
// acceptStream resolves with the next stream a device opened, taking
|
|
236
|
+
// each device's in turn. At most acceptQueue calls wait at once.
|
|
237
|
+
acceptStream(signal) {
|
|
238
|
+
if (this.#closed)
|
|
239
|
+
return Promise.reject(new KeywireError("closed", "client"));
|
|
240
|
+
signal?.throwIfAborted();
|
|
241
|
+
const next = this.#take();
|
|
242
|
+
if (next)
|
|
243
|
+
return Promise.resolve(next);
|
|
244
|
+
if (this.#takers.length >= this.#acceptQueue)
|
|
245
|
+
return Promise.reject(new RangeError("keywire: too many acceptStream calls waiting"));
|
|
246
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
247
|
+
const taker = { resolve, reject };
|
|
248
|
+
this.#takers.push(taker);
|
|
249
|
+
const abort = () => {
|
|
250
|
+
const i = this.#takers.indexOf(taker);
|
|
251
|
+
if (i >= 0)
|
|
252
|
+
this.#takers.splice(i, 1);
|
|
253
|
+
reject(signal.reason);
|
|
254
|
+
};
|
|
255
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
256
|
+
return promise.finally(() => signal?.removeEventListener("abort", abort));
|
|
257
|
+
}
|
|
258
|
+
// peers are the devices connected now.
|
|
259
|
+
peers() {
|
|
260
|
+
const out = [];
|
|
261
|
+
for (const peer of this.#peers.values()) {
|
|
262
|
+
const c = peer.current;
|
|
263
|
+
if (!c)
|
|
264
|
+
continue;
|
|
265
|
+
const state = {
|
|
266
|
+
key: peer.key.slice(),
|
|
267
|
+
path: c.path,
|
|
268
|
+
since: peer.since,
|
|
269
|
+
rtt: c.conn.rtt(),
|
|
270
|
+
};
|
|
271
|
+
if (c.path === "relayed" && c.relay !== undefined)
|
|
272
|
+
state.via = { relay: c.relay };
|
|
273
|
+
else if (c.path === "forwarded" && c.carrier)
|
|
274
|
+
state.via = { carrier: c.carrier.peer.slice() };
|
|
275
|
+
out.push(state);
|
|
276
|
+
}
|
|
277
|
+
return out;
|
|
278
|
+
}
|
|
279
|
+
// reaching are the devices not connected that the Client is trying to
|
|
280
|
+
// reach now.
|
|
281
|
+
reaching() {
|
|
282
|
+
const out = [];
|
|
283
|
+
for (const peer of this.#peers.values()) {
|
|
284
|
+
if (peer.current)
|
|
285
|
+
continue;
|
|
286
|
+
if (peer.dialing)
|
|
287
|
+
out.push({ key: peer.key.slice(), dialing: true, failures: peer.failures });
|
|
288
|
+
else if (peer.retry)
|
|
289
|
+
out.push({
|
|
290
|
+
key: peer.key.slice(),
|
|
291
|
+
dialing: false,
|
|
292
|
+
retryAtMs: peer.retryAt,
|
|
293
|
+
failures: peer.failures,
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
return out;
|
|
297
|
+
}
|
|
298
|
+
// watch calls f with peers and reaching now and after each change,
|
|
299
|
+
// several changes in one task at once, until the returned function is
|
|
300
|
+
// called.
|
|
301
|
+
watch(f) {
|
|
302
|
+
this.#watchers.add(f);
|
|
303
|
+
f(this.peers(), this.reaching());
|
|
304
|
+
return () => this.#watchers.delete(f);
|
|
305
|
+
}
|
|
306
|
+
close() {
|
|
307
|
+
if (this.#closed)
|
|
308
|
+
return;
|
|
309
|
+
this.#closed = true;
|
|
310
|
+
this.#unwatch();
|
|
311
|
+
clearInterval(this.#standing);
|
|
312
|
+
this.#feeds.end();
|
|
313
|
+
this.#watchers.clear();
|
|
314
|
+
for (const peer of this.#peers.values()) {
|
|
315
|
+
clearTimeout(peer.retry);
|
|
316
|
+
peer.link.close();
|
|
317
|
+
for (const conn of peer.conns.keys())
|
|
318
|
+
conn.close();
|
|
319
|
+
}
|
|
320
|
+
this.#paths.close();
|
|
321
|
+
clearTimeout(this.#push);
|
|
322
|
+
for (const queue of this.#queues.values())
|
|
323
|
+
for (const i of queue)
|
|
324
|
+
i.stream.reset(CODE_REFUSED);
|
|
325
|
+
this.#queues.clear();
|
|
326
|
+
for (const taker of this.#takers.splice(0))
|
|
327
|
+
taker.reject(new KeywireError("closed", "client"));
|
|
328
|
+
}
|
|
329
|
+
// #keepNodes keeps connected to the owner Nodes of the roster, at most
|
|
330
|
+
// maxOwners, unless the Client is passive, and stops keeping those the
|
|
331
|
+
// roster no longer has.
|
|
332
|
+
#keepNodes() {
|
|
333
|
+
if (this.#opts.passive || this.#closed)
|
|
334
|
+
return;
|
|
335
|
+
const self = this.#opts.keypair.publicKey;
|
|
336
|
+
const nodes = new Map();
|
|
337
|
+
for (const o of this.#opts.roster.owners()) {
|
|
338
|
+
if (nodes.size >= maxOwners)
|
|
339
|
+
break;
|
|
340
|
+
const key = new Uint8Array(o.noiseKey);
|
|
341
|
+
if (!o.conflict && !equal(key, self))
|
|
342
|
+
nodes.set(hex(key), key);
|
|
343
|
+
}
|
|
344
|
+
for (const [id, peer] of this.#peers) {
|
|
345
|
+
if (!peer.kept || nodes.has(id))
|
|
346
|
+
continue;
|
|
347
|
+
peer.kept = false;
|
|
348
|
+
clearTimeout(peer.retry);
|
|
349
|
+
peer.retry = undefined;
|
|
350
|
+
if (peer.current)
|
|
351
|
+
this.#retire(peer, peer.current.conn);
|
|
352
|
+
else
|
|
353
|
+
this.#changed();
|
|
354
|
+
}
|
|
355
|
+
for (const key of nodes.values()) {
|
|
356
|
+
const peer = this.#peer(key);
|
|
357
|
+
if (peer.kept)
|
|
358
|
+
continue;
|
|
359
|
+
peer.kept = true;
|
|
360
|
+
if (!peer.current)
|
|
361
|
+
this.#reconnect(peer);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
#peer(key) {
|
|
365
|
+
if (this.#closed)
|
|
366
|
+
throw new KeywireError("closed", "client");
|
|
367
|
+
if (equal(key, this.#opts.keypair.publicKey))
|
|
368
|
+
throw new KeywireError("self");
|
|
369
|
+
const id = hex(key);
|
|
370
|
+
let peer = this.#peers.get(id);
|
|
371
|
+
if (!peer) {
|
|
372
|
+
const remote = key.slice();
|
|
373
|
+
const link = this.#paths.link({
|
|
374
|
+
target: () => this.#target(remote),
|
|
375
|
+
dialOptions: () => this.#dialOptions(remote),
|
|
376
|
+
via: () => this.#carriers(id),
|
|
377
|
+
live: () => this.#peers.get(id)?.current?.conn,
|
|
378
|
+
better: () => void this.#upgrade(this.#peers.get(id)),
|
|
379
|
+
});
|
|
380
|
+
peer = new Peer(remote, link);
|
|
381
|
+
this.#peers.set(id, peer);
|
|
382
|
+
}
|
|
383
|
+
return peer;
|
|
384
|
+
}
|
|
385
|
+
#target(key) {
|
|
386
|
+
const { roster } = this.#opts;
|
|
387
|
+
const owner = roster.owners().find((o) => equal(o.noiseKey, key));
|
|
388
|
+
if (owner?.conflict)
|
|
389
|
+
throw new KeywireError("conflicted-node", hex(key));
|
|
390
|
+
if (owner)
|
|
391
|
+
return {
|
|
392
|
+
endpoints: owner.endpoints,
|
|
393
|
+
relays: owner.relays,
|
|
394
|
+
node: new Uint8Array(owner.nodeId),
|
|
395
|
+
offer: this.#offers(key, true),
|
|
396
|
+
};
|
|
397
|
+
// As Go, which may hold a guest by a key its roster lacks: a device
|
|
398
|
+
// not connected that the roster does not admit is unreachable for now.
|
|
399
|
+
if (roster.admitted(key, Date.now())?.role !== "member")
|
|
400
|
+
throw new KeywireError("unreachable", `${hex(key)} is not connected, and no device the roster admits`);
|
|
401
|
+
return {
|
|
402
|
+
endpoints: [],
|
|
403
|
+
relays: [],
|
|
404
|
+
offer: this.#offers(key, false),
|
|
405
|
+
stunRelays: this.#relayUrls(),
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
// #isNode says the roster has key as an owner Node, not in conflict.
|
|
409
|
+
#isNode(key) {
|
|
410
|
+
return this.#opts.roster.owners().some((o) => !o.conflict && equal(o.noiseKey, key));
|
|
411
|
+
}
|
|
412
|
+
// #offers says this device offers the peer-to-peer path to remote, rather
|
|
413
|
+
// than answering its offer: a device that is no Node offers to a Node,
|
|
414
|
+
// and of two Nodes or two other devices the one with the lower key.
|
|
415
|
+
#offers(remote, remoteNode) {
|
|
416
|
+
const self = this.#opts.keypair.publicKey;
|
|
417
|
+
const selfNode = this.#isNode(self);
|
|
418
|
+
if (selfNode !== remoteNode)
|
|
419
|
+
return !selfNode;
|
|
420
|
+
for (let i = 0; i < self.length; i++) {
|
|
421
|
+
if (self[i] !== remote[i])
|
|
422
|
+
return self[i] < remote[i];
|
|
423
|
+
}
|
|
424
|
+
return false;
|
|
425
|
+
}
|
|
426
|
+
#acceptOptions() {
|
|
427
|
+
const { app, domain, network, keypair, roster, limits, compression, compressionMode } = this.#opts;
|
|
428
|
+
return {
|
|
429
|
+
...(compression && { compression }),
|
|
430
|
+
...(compressionMode && { compressionMode }),
|
|
431
|
+
app,
|
|
432
|
+
...(domain !== undefined && { domain }),
|
|
433
|
+
network,
|
|
434
|
+
keypair,
|
|
435
|
+
roster,
|
|
436
|
+
...(limits && { limits }),
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
#dialOptions(remote) {
|
|
440
|
+
const { app, domain, network, keypair, limits, roster, compression, compressionMode } = this.#opts;
|
|
441
|
+
return {
|
|
442
|
+
...(compression && { compression }),
|
|
443
|
+
...(compressionMode && { compressionMode }),
|
|
444
|
+
app,
|
|
445
|
+
...(domain !== undefined && { domain }),
|
|
446
|
+
network,
|
|
447
|
+
keypair,
|
|
448
|
+
remote,
|
|
449
|
+
...(limits && { limits }),
|
|
450
|
+
credentials: roster.credentials(keypair.publicKey, Date.now()),
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
// #roles are the roles this device and the device with key hold now, or
|
|
454
|
+
// undefined unless both are admitted.
|
|
455
|
+
#roles(key) {
|
|
456
|
+
const now = Date.now();
|
|
457
|
+
const local = this.#opts.roster.admitted(this.#opts.keypair.publicKey, now)?.role;
|
|
458
|
+
const remote = this.#opts.roster.admitted(key, now)?.role;
|
|
459
|
+
return local && remote ? { local, remote } : undefined;
|
|
460
|
+
}
|
|
461
|
+
// #rosterChanged keeps the roster roster sync changed, keeps connected
|
|
462
|
+
// to the Nodes it now has, and syncs it with every device a debounce
|
|
463
|
+
// after the last change.
|
|
464
|
+
#rosterChanged(records) {
|
|
465
|
+
const save = this.#opts.saveRoster;
|
|
466
|
+
if (save)
|
|
467
|
+
this.#saving = this.#saving
|
|
468
|
+
.then(() => save(records))
|
|
469
|
+
.catch((e) => this.#opts.onError?.(e));
|
|
470
|
+
this.#updateFeeds();
|
|
471
|
+
this.#keepNodes();
|
|
472
|
+
clearTimeout(this.#push);
|
|
473
|
+
this.#push = setTimeout(() => {
|
|
474
|
+
for (const sync of this.#syncs.values())
|
|
475
|
+
void sync.sync().catch(() => { });
|
|
476
|
+
}, ROSTER_DEBOUNCE_MS);
|
|
477
|
+
}
|
|
478
|
+
// #serveNetwork runs roster sync and the extensions on conn, a
|
|
479
|
+
// connection to peer, until it ends; dialer says this device made it.
|
|
480
|
+
#serveNetwork(peer, conn, dialer) {
|
|
481
|
+
const sync = syncRoster(conn, this.#opts.roster, (records) => this.#rosterChanged(records), {
|
|
482
|
+
initiate: dialer,
|
|
483
|
+
});
|
|
484
|
+
this.#syncs.set(conn, sync);
|
|
485
|
+
const links = this.#extensions.map((e) => [
|
|
486
|
+
e,
|
|
487
|
+
extensionLink(conn, e, dialer, () => this.#roles(peer.key)),
|
|
488
|
+
]);
|
|
489
|
+
// The extensions are told of the connection once both devices are
|
|
490
|
+
// admitted, as it starts or at its first stream, and of its end if
|
|
491
|
+
// they were told of it.
|
|
492
|
+
// What an extension throws goes to onError: it fails neither the
|
|
493
|
+
// connection nor the others.
|
|
494
|
+
let told = false;
|
|
495
|
+
const tell = () => {
|
|
496
|
+
if (told || !this.#roles(peer.key))
|
|
497
|
+
return;
|
|
498
|
+
told = true;
|
|
499
|
+
for (const [e, link] of links)
|
|
500
|
+
this.#guard(() => e.connected?.(link));
|
|
501
|
+
};
|
|
502
|
+
for (const [e, link] of links) {
|
|
503
|
+
serveExtension(conn, e.service, (stream) => {
|
|
504
|
+
if (this.#closed || !link.roles()) {
|
|
505
|
+
stream.reset(CODE_REFUSED);
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
tell();
|
|
509
|
+
if (!this.#guard(() => e.serve(link, stream)))
|
|
510
|
+
stream.reset(CODE_CANCEL);
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
tell();
|
|
514
|
+
void conn.closed.then(() => {
|
|
515
|
+
this.#syncs.delete(conn);
|
|
516
|
+
if (told)
|
|
517
|
+
for (const [e, link] of links)
|
|
518
|
+
this.#guard(() => e.ended?.(link));
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
// #guard runs f, an application's, and reports whether it returned: what
|
|
522
|
+
// it throws goes to onError.
|
|
523
|
+
#guard(f) {
|
|
524
|
+
try {
|
|
525
|
+
f();
|
|
526
|
+
return true;
|
|
527
|
+
}
|
|
528
|
+
catch (e) {
|
|
529
|
+
this.#opts.onError?.(e);
|
|
530
|
+
return false;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
// #carriers are the connections to other Nodes a connection to the
|
|
534
|
+
// device id may be forwarded through: none a Node forwarded, which no
|
|
535
|
+
// Node forwards again. A relayed one serves, as the target may be
|
|
536
|
+
// registered at no relay this client reaches.
|
|
537
|
+
#carriers(id) {
|
|
538
|
+
const out = [];
|
|
539
|
+
for (const [other, peer] of this.#peers) {
|
|
540
|
+
const path = peer.current?.path;
|
|
541
|
+
if (other === id || !path || path === "forwarded")
|
|
542
|
+
continue;
|
|
543
|
+
if (this.#isNode(peer.key))
|
|
544
|
+
out.push(peer.current.conn);
|
|
545
|
+
}
|
|
546
|
+
return out;
|
|
547
|
+
}
|
|
548
|
+
// #connect returns the connection new streams to peer take, making one
|
|
549
|
+
// if there is none; callers share an attempt in progress. demand is
|
|
550
|
+
// whether the caller will use the connection, as reconnecting to a kept
|
|
551
|
+
// Node does not: a connection made after the Node stopped being kept
|
|
552
|
+
// that no caller asked for goes away.
|
|
553
|
+
async #connect(peer, signal, demand = true) {
|
|
554
|
+
signal?.throwIfAborted();
|
|
555
|
+
if (peer.current)
|
|
556
|
+
return peer.current.conn;
|
|
557
|
+
let attempt = peer.dialing;
|
|
558
|
+
if (!attempt) {
|
|
559
|
+
const made = { promise: Promise.resolve(), demand: 0 };
|
|
560
|
+
made.promise = (async () => {
|
|
561
|
+
this.#target(peer.key);
|
|
562
|
+
let result;
|
|
563
|
+
try {
|
|
564
|
+
// A Node no path reaches, or a member no Node holds, is
|
|
565
|
+
// "unreachable", wrapping why the last path failed.
|
|
566
|
+
result = await peer.link.connect();
|
|
567
|
+
}
|
|
568
|
+
catch (e) {
|
|
569
|
+
if (this.#closed)
|
|
570
|
+
throw new KeywireError("closed", "client");
|
|
571
|
+
peer.failures++;
|
|
572
|
+
throw e;
|
|
573
|
+
}
|
|
574
|
+
peer.failures = 0;
|
|
575
|
+
if (this.#closed) {
|
|
576
|
+
result.conn.close();
|
|
577
|
+
throw new KeywireError("closed", "client");
|
|
578
|
+
}
|
|
579
|
+
this.#adopt(peer, result);
|
|
580
|
+
if (!peer.kept && made.demand === 0)
|
|
581
|
+
this.#retire(peer, result.conn);
|
|
582
|
+
return result.conn;
|
|
583
|
+
})();
|
|
584
|
+
// Cleared once settled, whatever the attempt threw and when.
|
|
585
|
+
const clear = () => {
|
|
586
|
+
if (peer.dialing === made)
|
|
587
|
+
peer.dialing = undefined;
|
|
588
|
+
this.#changed();
|
|
589
|
+
};
|
|
590
|
+
made.promise.then(clear, clear);
|
|
591
|
+
peer.dialing = attempt = made;
|
|
592
|
+
this.#changed();
|
|
593
|
+
}
|
|
594
|
+
if (demand)
|
|
595
|
+
attempt.demand++;
|
|
596
|
+
if (!signal)
|
|
597
|
+
return attempt.promise;
|
|
598
|
+
const { promise, reject } = Promise.withResolvers();
|
|
599
|
+
const abort = () => reject(signal.reason);
|
|
600
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
601
|
+
return Promise.race([attempt.promise, promise]).finally(() => signal.removeEventListener("abort", abort));
|
|
602
|
+
}
|
|
603
|
+
// #upgrade takes the better path the link found, unless the connection
|
|
604
|
+
// it would replace is gone meanwhile or too much is going away already.
|
|
605
|
+
async #upgrade(peer) {
|
|
606
|
+
let result;
|
|
607
|
+
try {
|
|
608
|
+
result = await peer.link.connect();
|
|
609
|
+
}
|
|
610
|
+
catch {
|
|
611
|
+
return; // The connection in use stays.
|
|
612
|
+
}
|
|
613
|
+
const old = peer.current;
|
|
614
|
+
const busy = [...peer.conns.keys()].filter((c) => c.goingAway && c.streams() > 0 && c !== old?.conn).length;
|
|
615
|
+
if (this.#closed || !old || busy + (old.conn.streams() > 0 ? 1 : 0) > MAX_DRAINING) {
|
|
616
|
+
result.conn.close();
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
this.#adopt(peer, result);
|
|
620
|
+
}
|
|
621
|
+
// #adopt makes result the connection new streams to peer take, and has
|
|
622
|
+
// the one before go away if this device made it. accepted says the peer
|
|
623
|
+
// made result.
|
|
624
|
+
#adopt(peer, result, accepted = false) {
|
|
625
|
+
const old = peer.current;
|
|
626
|
+
peer.current = result;
|
|
627
|
+
peer.since = Date.now();
|
|
628
|
+
peer.failures = 0;
|
|
629
|
+
if (!accepted)
|
|
630
|
+
this.#dialed.add(result.conn);
|
|
631
|
+
this.#track(peer, result);
|
|
632
|
+
if (accepted)
|
|
633
|
+
peer.link.accepted(result);
|
|
634
|
+
peer.link.connected();
|
|
635
|
+
if (old)
|
|
636
|
+
this.#retire(peer, old.conn);
|
|
637
|
+
this.#changed();
|
|
638
|
+
}
|
|
639
|
+
// #track serves the streams and services of a connection to peer until
|
|
640
|
+
// it closes.
|
|
641
|
+
#track(peer, result) {
|
|
642
|
+
const { conn } = result;
|
|
643
|
+
if (peer.conns.has(conn))
|
|
644
|
+
return;
|
|
645
|
+
peer.conns.set(conn, result);
|
|
646
|
+
void this.#serve(peer, conn);
|
|
647
|
+
this.#serveNetwork(peer, conn, this.#dialed.has(conn));
|
|
648
|
+
// As Go, on every connection: whether the peer is an owner, and so may
|
|
649
|
+
// forward, is asked of each stream.
|
|
650
|
+
this.#serveForwarded(result);
|
|
651
|
+
if (!this.#isNode(peer.key)) {
|
|
652
|
+
serveRtc(conn, () => ({
|
|
653
|
+
...this.#acceptOptions(),
|
|
654
|
+
relays: this.#relayUrls(),
|
|
655
|
+
...(this.#opts.stun && { stun: this.#opts.stun }),
|
|
656
|
+
setups: this.#rtcSetups,
|
|
657
|
+
}), (accepted) => this.#accepted(accepted, { conn: accepted, path: "peer-to-peer" }));
|
|
658
|
+
}
|
|
659
|
+
void conn.wentAway.then(() => {
|
|
660
|
+
if (peer.current?.conn === conn)
|
|
661
|
+
this.#lost(peer, conn);
|
|
662
|
+
});
|
|
663
|
+
void conn.closed.then(() => {
|
|
664
|
+
peer.conns.delete(conn);
|
|
665
|
+
if (peer.current?.conn === conn)
|
|
666
|
+
this.#lost(peer, conn);
|
|
667
|
+
});
|
|
668
|
+
}
|
|
669
|
+
// #relayUrls are the relays of the Network's Nodes, whose STUN servers
|
|
670
|
+
// an answer asks.
|
|
671
|
+
#relayUrls() {
|
|
672
|
+
return [...new Set(this.#opts.roster.owners().flatMap((o) => o.relays))];
|
|
673
|
+
}
|
|
674
|
+
// #serveForwarded takes the connections the device at the other end of
|
|
675
|
+
// carrier forwards to this device while it is an owner, unless a Node
|
|
676
|
+
// forwarded carrier itself: at most FORWARDED_PER_CONN at once over
|
|
677
|
+
// carrier, each until it or carrier ends, and at most pendingHandshakes
|
|
678
|
+
// handshakes at once over all carriers.
|
|
679
|
+
#serveForwarded({ conn: carrier, path }) {
|
|
680
|
+
let active = 0;
|
|
681
|
+
registerService(carrier, 3, (stream) => {
|
|
682
|
+
const role = this.#opts.roster.admitted(carrier.peer, Date.now())?.role;
|
|
683
|
+
if (this.#closed ||
|
|
684
|
+
role !== "owner" ||
|
|
685
|
+
path === "forwarded" ||
|
|
686
|
+
active >= FORWARDED_PER_CONN ||
|
|
687
|
+
this.#pending.active >= this.#pendingHandshakes) {
|
|
688
|
+
stream.reset(CODE_CANCEL);
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
active++;
|
|
692
|
+
this.#pending.active++;
|
|
693
|
+
acceptPath(new FramedStream(stream), this.#acceptOptions()).then((conn) => {
|
|
694
|
+
this.#pending.active--;
|
|
695
|
+
void conn.closed.then(() => active--);
|
|
696
|
+
void carrier.closed.then(() => conn.close());
|
|
697
|
+
this.#accepted(conn, { conn, path: "forwarded", carrier });
|
|
698
|
+
}, () => {
|
|
699
|
+
this.#pending.active--;
|
|
700
|
+
active--;
|
|
701
|
+
});
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
// #accepted keeps a connection another device made to this one: it
|
|
705
|
+
// carries new streams if none does, or if it is a better path.
|
|
706
|
+
#accepted(conn, result) {
|
|
707
|
+
if (this.#closed || equal(conn.peer, this.#opts.keypair.publicKey)) {
|
|
708
|
+
conn.close();
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
const peer = this.#peer(conn.peer);
|
|
712
|
+
if (!peer.current || improvesPath(peer.current, result))
|
|
713
|
+
this.#adopt(peer, result, true);
|
|
714
|
+
else
|
|
715
|
+
this.#track(peer, result);
|
|
716
|
+
}
|
|
717
|
+
// #retire stops new streams taking conn, and has it go away if this
|
|
718
|
+
// device made it: it ends once its streams do. One the peer made is the
|
|
719
|
+
// peer's to retire.
|
|
720
|
+
#retire(peer, conn) {
|
|
721
|
+
if (peer.current?.conn === conn) {
|
|
722
|
+
peer.current = undefined;
|
|
723
|
+
peer.link.disconnected();
|
|
724
|
+
this.#changed();
|
|
725
|
+
}
|
|
726
|
+
if (this.#dialed.has(conn))
|
|
727
|
+
conn.goAway();
|
|
728
|
+
}
|
|
729
|
+
// #lost forgets a connection that new streams can no longer take; another
|
|
730
|
+
// that the peer made and that is still up takes them instead.
|
|
731
|
+
#lost(peer, conn) {
|
|
732
|
+
if (peer.current?.conn !== conn)
|
|
733
|
+
return;
|
|
734
|
+
// A connection that lasted starts the waits over; one that keeps
|
|
735
|
+
// failing soon after it is made does not.
|
|
736
|
+
if (Date.now() - peer.since >= this.#retryMax)
|
|
737
|
+
peer.retryMs = 0;
|
|
738
|
+
peer.current = undefined;
|
|
739
|
+
peer.link.disconnected();
|
|
740
|
+
this.#changed();
|
|
741
|
+
let next;
|
|
742
|
+
for (const [other, result] of peer.conns) {
|
|
743
|
+
if (other === conn || other.goingAway || this.#dialed.has(other))
|
|
744
|
+
continue;
|
|
745
|
+
if (!next || improvesPath(next, result))
|
|
746
|
+
next = result;
|
|
747
|
+
}
|
|
748
|
+
if (next)
|
|
749
|
+
this.#adopt(peer, next, true);
|
|
750
|
+
else if (peer.kept)
|
|
751
|
+
this.#reconnect(peer);
|
|
752
|
+
}
|
|
753
|
+
// #reconnect connects a kept Node after the retry wait, doubling it after
|
|
754
|
+
// each failure.
|
|
755
|
+
#reconnect(peer) {
|
|
756
|
+
if (this.#closed || !peer.kept || peer.retry || peer.current)
|
|
757
|
+
return;
|
|
758
|
+
const wait = peer.retryMs * (0.8 + Math.random() * 0.4);
|
|
759
|
+
peer.retryMs = Math.min(Math.max(peer.retryMs * 2, this.#retryMin), this.#retryMax);
|
|
760
|
+
peer.retryAt = Date.now() + Math.round(wait);
|
|
761
|
+
peer.retry = setTimeout(() => {
|
|
762
|
+
peer.retry = undefined;
|
|
763
|
+
this.#connect(peer, undefined, false).catch(() => this.#reconnect(peer));
|
|
764
|
+
}, wait);
|
|
765
|
+
this.#changed();
|
|
766
|
+
}
|
|
767
|
+
#networkChanged() {
|
|
768
|
+
void this.#paths.probeRelays(3000).catch(() => { });
|
|
769
|
+
for (const peer of this.#peers.values()) {
|
|
770
|
+
peer.link.networkChanged();
|
|
771
|
+
if (peer.current) {
|
|
772
|
+
// A path that died with the network fails its probe, and closes.
|
|
773
|
+
void peer.current.conn.probe(3000).catch(() => { });
|
|
774
|
+
peer.link.upgrade();
|
|
775
|
+
}
|
|
776
|
+
else if (peer.kept) {
|
|
777
|
+
clearTimeout(peer.retry);
|
|
778
|
+
peer.retry = undefined;
|
|
779
|
+
peer.retryMs = 0;
|
|
780
|
+
this.#reconnect(peer);
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
// #serve passes the streams the device opens on conn to acceptStream.
|
|
785
|
+
async #serve(peer, conn) {
|
|
786
|
+
const id = hex(peer.key);
|
|
787
|
+
for (;;) {
|
|
788
|
+
let stream;
|
|
789
|
+
try {
|
|
790
|
+
stream = await conn.acceptStream();
|
|
791
|
+
}
|
|
792
|
+
catch {
|
|
793
|
+
return;
|
|
794
|
+
}
|
|
795
|
+
const incoming = { peer: peer.key.slice(), stream };
|
|
796
|
+
const taker = this.#takers.shift();
|
|
797
|
+
if (taker) {
|
|
798
|
+
taker.resolve(incoming);
|
|
799
|
+
continue;
|
|
800
|
+
}
|
|
801
|
+
let queue = this.#queues.get(id);
|
|
802
|
+
if (this.#closed ||
|
|
803
|
+
this.#queued >= this.#acceptQueue ||
|
|
804
|
+
(queue?.length ?? 0) >= this.#acceptPerPeer) {
|
|
805
|
+
stream.reset(CODE_REFUSED);
|
|
806
|
+
continue;
|
|
807
|
+
}
|
|
808
|
+
if (!queue) {
|
|
809
|
+
queue = [];
|
|
810
|
+
this.#queues.set(id, queue);
|
|
811
|
+
this.#turns.push(id);
|
|
812
|
+
}
|
|
813
|
+
queue.push(incoming);
|
|
814
|
+
this.#queued++;
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
// #take is the next device's oldest queued stream, if any.
|
|
818
|
+
#take() {
|
|
819
|
+
const id = this.#turns.shift();
|
|
820
|
+
if (id === undefined)
|
|
821
|
+
return undefined;
|
|
822
|
+
const queue = this.#queues.get(id);
|
|
823
|
+
const next = queue.shift();
|
|
824
|
+
this.#queued--;
|
|
825
|
+
if (queue.length)
|
|
826
|
+
this.#turns.push(id);
|
|
827
|
+
else
|
|
828
|
+
this.#queues.delete(id);
|
|
829
|
+
return next;
|
|
830
|
+
}
|
|
831
|
+
#changed() {
|
|
832
|
+
if (this.#moved)
|
|
833
|
+
return;
|
|
834
|
+
this.#moved = true;
|
|
835
|
+
queueMicrotask(() => {
|
|
836
|
+
this.#moved = false;
|
|
837
|
+
if (this.#closed)
|
|
838
|
+
return;
|
|
839
|
+
const peers = this.peers();
|
|
840
|
+
const reaching = this.reaching();
|
|
841
|
+
for (const f of this.#watchers)
|
|
842
|
+
f(peers, reaching);
|
|
843
|
+
});
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
//# sourceMappingURL=client.js.map
|