@serfab/cadre-core 0.6.0 → 0.8.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.
Files changed (166) hide show
  1. package/README.md +9 -8
  2. package/dist/authority-key.d.ts +41 -0
  3. package/dist/authority-key.js +52 -0
  4. package/dist/authority-key.js.map +1 -0
  5. package/dist/cadre-node.d.ts +777 -11
  6. package/dist/cadre-node.js +1912 -82
  7. package/dist/cadre-node.js.map +1 -1
  8. package/dist/canonical-datetime.d.ts +33 -0
  9. package/dist/canonical-datetime.js +38 -0
  10. package/dist/canonical-datetime.js.map +1 -0
  11. package/dist/canonical-json.d.ts +12 -0
  12. package/dist/canonical-json.js +33 -0
  13. package/dist/canonical-json.js.map +1 -0
  14. package/dist/control-cohort.d.ts +63 -0
  15. package/dist/control-cohort.js +80 -0
  16. package/dist/control-cohort.js.map +1 -0
  17. package/dist/control-database.d.ts +259 -5
  18. package/dist/control-database.js +541 -128
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +89 -0
  21. package/dist/control-formation-recorder.js +139 -0
  22. package/dist/control-formation-recorder.js.map +1 -0
  23. package/dist/control-schema.d.ts +12 -0
  24. package/dist/control-schema.js +199 -0
  25. package/dist/control-schema.js.map +1 -0
  26. package/dist/control-stream.d.ts +54 -0
  27. package/dist/control-stream.js +104 -0
  28. package/dist/control-stream.js.map +1 -0
  29. package/dist/device-token.d.ts +50 -0
  30. package/dist/device-token.js +66 -0
  31. package/dist/device-token.js.map +1 -0
  32. package/dist/diagnostics/connection-path.d.ts +118 -0
  33. package/dist/diagnostics/connection-path.js +204 -0
  34. package/dist/diagnostics/connection-path.js.map +1 -0
  35. package/dist/diagnostics/webrtc-turn-tracker.d.ts +50 -0
  36. package/dist/diagnostics/webrtc-turn-tracker.js +196 -0
  37. package/dist/diagnostics/webrtc-turn-tracker.js.map +1 -0
  38. package/dist/hibernation-manager.d.ts +79 -0
  39. package/dist/hibernation-manager.js +173 -23
  40. package/dist/hibernation-manager.js.map +1 -1
  41. package/dist/index.d.ts +25 -4
  42. package/dist/index.js +59 -4
  43. package/dist/index.js.map +1 -1
  44. package/dist/key-store-file.d.ts +52 -0
  45. package/dist/key-store-file.js +194 -0
  46. package/dist/key-store-file.js.map +1 -0
  47. package/dist/key-store.d.ts +75 -0
  48. package/dist/key-store.js +66 -0
  49. package/dist/key-store.js.map +1 -0
  50. package/dist/peer-authorization.d.ts +26 -0
  51. package/dist/peer-authorization.js +40 -0
  52. package/dist/peer-authorization.js.map +1 -0
  53. package/dist/peer-record.d.ts +89 -0
  54. package/dist/peer-record.js +117 -0
  55. package/dist/peer-record.js.map +1 -0
  56. package/dist/push-credentials.d.ts +34 -0
  57. package/dist/push-credentials.js +81 -0
  58. package/dist/push-credentials.js.map +1 -0
  59. package/dist/push-fanout.d.ts +137 -0
  60. package/dist/push-fanout.js +197 -0
  61. package/dist/push-fanout.js.map +1 -0
  62. package/dist/push-notifier-apns.d.ts +53 -0
  63. package/dist/push-notifier-apns.js +195 -0
  64. package/dist/push-notifier-apns.js.map +1 -0
  65. package/dist/push-notifier-fcm.d.ts +38 -0
  66. package/dist/push-notifier-fcm.js +183 -0
  67. package/dist/push-notifier-fcm.js.map +1 -0
  68. package/dist/push-notifier-shared.d.ts +18 -0
  69. package/dist/push-notifier-shared.js +25 -0
  70. package/dist/push-notifier-shared.js.map +1 -0
  71. package/dist/push-notifier.d.ts +71 -0
  72. package/dist/push-notifier.js +50 -0
  73. package/dist/push-notifier.js.map +1 -0
  74. package/dist/schema-verification.d.ts +11 -2
  75. package/dist/schema-verification.js +15 -4
  76. package/dist/schema-verification.js.map +1 -1
  77. package/dist/seed-bootstrap.d.ts +210 -7
  78. package/dist/seed-bootstrap.js +429 -131
  79. package/dist/seed-bootstrap.js.map +1 -1
  80. package/dist/seed-trust-policy.d.ts +63 -0
  81. package/dist/seed-trust-policy.js +56 -0
  82. package/dist/seed-trust-policy.js.map +1 -0
  83. package/dist/strand-addr-protocol.d.ts +132 -0
  84. package/dist/strand-addr-protocol.js +313 -0
  85. package/dist/strand-addr-protocol.js.map +1 -0
  86. package/dist/strand-cohort.d.ts +54 -0
  87. package/dist/strand-cohort.js +38 -0
  88. package/dist/strand-cohort.js.map +1 -0
  89. package/dist/strand-database.d.ts +54 -6
  90. package/dist/strand-database.js +88 -89
  91. package/dist/strand-database.js.map +1 -1
  92. package/dist/strand-formation-manager.d.ts +79 -19
  93. package/dist/strand-formation-manager.js +196 -104
  94. package/dist/strand-formation-manager.js.map +1 -1
  95. package/dist/strand-formation-protocol.d.ts +162 -0
  96. package/dist/strand-formation-protocol.js +279 -0
  97. package/dist/strand-formation-protocol.js.map +1 -0
  98. package/dist/strand-instance-manager.d.ts +73 -4
  99. package/dist/strand-instance-manager.js +167 -41
  100. package/dist/strand-instance-manager.js.map +1 -1
  101. package/dist/strand-member-key.d.ts +29 -0
  102. package/dist/strand-member-key.js +38 -0
  103. package/dist/strand-member-key.js.map +1 -0
  104. package/dist/strand-member-registry.d.ts +98 -0
  105. package/dist/strand-member-registry.js +129 -0
  106. package/dist/strand-member-registry.js.map +1 -0
  107. package/dist/strand-membership-writer.d.ts +361 -0
  108. package/dist/strand-membership-writer.js +449 -0
  109. package/dist/strand-membership-writer.js.map +1 -0
  110. package/dist/strand-solicitation.d.ts +77 -2
  111. package/dist/strand-solicitation.js +25 -4
  112. package/dist/strand-solicitation.js.map +1 -1
  113. package/dist/strand-wake-payload.d.ts +30 -0
  114. package/dist/strand-wake-payload.js +20 -0
  115. package/dist/strand-wake-payload.js.map +1 -0
  116. package/dist/strand-wake-protocol.d.ts +114 -0
  117. package/dist/strand-wake-protocol.js +257 -0
  118. package/dist/strand-wake-protocol.js.map +1 -0
  119. package/dist/strand-watcher.d.ts +6 -2
  120. package/dist/strand-watcher.js +57 -17
  121. package/dist/strand-watcher.js.map +1 -1
  122. package/dist/types.d.ts +413 -23
  123. package/dist/types.js +22 -5
  124. package/dist/types.js.map +1 -1
  125. package/package.json +14 -8
  126. package/src/authority-key.ts +68 -0
  127. package/src/cadre-node.ts +2937 -929
  128. package/src/canonical-datetime.ts +39 -0
  129. package/src/canonical-json.ts +30 -0
  130. package/src/control-cohort.ts +103 -0
  131. package/src/control-database.ts +931 -383
  132. package/src/control-formation-recorder.ts +151 -0
  133. package/src/control-schema.ts +198 -0
  134. package/src/control-stream.ts +128 -0
  135. package/src/device-token.ts +89 -0
  136. package/src/diagnostics/connection-path.ts +277 -0
  137. package/src/diagnostics/webrtc-turn-tracker.ts +222 -0
  138. package/src/hibernation-manager.ts +197 -28
  139. package/src/index.ts +273 -79
  140. package/src/key-store-file.ts +203 -0
  141. package/src/key-store.ts +99 -0
  142. package/src/peer-authorization.ts +53 -0
  143. package/src/peer-record.ts +146 -0
  144. package/src/push-credentials.ts +84 -0
  145. package/src/push-fanout.ts +272 -0
  146. package/src/push-notifier-apns.ts +243 -0
  147. package/src/push-notifier-fcm.ts +221 -0
  148. package/src/push-notifier-shared.ts +28 -0
  149. package/src/push-notifier.ts +93 -0
  150. package/src/schema-verification.ts +18 -4
  151. package/src/seed-bootstrap.ts +504 -171
  152. package/src/seed-trust-policy.ts +107 -0
  153. package/src/strand-addr-protocol.ts +410 -0
  154. package/src/strand-cohort.ts +77 -0
  155. package/src/strand-database.ts +113 -126
  156. package/src/strand-formation-manager.ts +233 -142
  157. package/src/strand-formation-protocol.ts +391 -0
  158. package/src/strand-instance-manager.ts +207 -56
  159. package/src/strand-member-key.ts +39 -0
  160. package/src/strand-member-registry.ts +177 -0
  161. package/src/strand-membership-writer.ts +640 -0
  162. package/src/strand-solicitation.ts +93 -4
  163. package/src/strand-wake-payload.ts +32 -0
  164. package/src/strand-wake-protocol.ts +331 -0
  165. package/src/strand-watcher.ts +61 -17
  166. package/src/types.ts +1012 -575
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Shared control-network stream primitives.
3
+ *
4
+ * The cadre control protocols — seed delivery (`seed-bootstrap.ts`), push-wake
5
+ * (`strand-wake-protocol.ts`), and strand formation (`strand-formation-protocol.ts`)
6
+ * — all speak 4-byte big-endian length-prefixed JSON frames over a libp2p 3.x
7
+ * stream. This module lifts the previously-triplicated stream shape, frame
8
+ * writer, and `withTimeout` wrapper into one place, and adds a timeout-bounded,
9
+ * abort-on-timeout read-to-EOF helper so a misbehaving peer that opens a stream
10
+ * and never half-closes its write end cannot pin a receiver forever.
11
+ *
12
+ * Dependency-free by design: it imports nothing from the protocol modules, so
13
+ * the import graph stays acyclic (`control-stream` ← `seed-bootstrap` ←
14
+ * `strand-wake-protocol`). In particular it returns RAW bytes from
15
+ * {@link readStreamToEnd} rather than decoding a frame — callers own the
16
+ * `decodeLengthPrefixedFrame` guard.
17
+ */
18
+ /** Write a JSON object as a single 4-byte big-endian length-prefixed frame. */
19
+ export function writeFrame(stream, obj) {
20
+ const body = new TextEncoder().encode(JSON.stringify(obj));
21
+ const prefix = new Uint8Array(4);
22
+ new DataView(prefix.buffer).setUint32(0, body.length, false);
23
+ stream.send(prefix);
24
+ stream.send(body);
25
+ }
26
+ /**
27
+ * Reject if `op` does not settle within `ms`. On timeout, invoke `onTimeout`
28
+ * (used by the sender to abort the in-flight dial/stream so it does not leak)
29
+ * before rejecting. A throwing `onTimeout` is swallowed so it cannot mask the
30
+ * timeout rejection. The rejection message is exactly `<label> timed out after
31
+ * <ms>ms`, so callers fold any domain prefix into `label`.
32
+ */
33
+ export function withTimeout(ms, label, op, onTimeout) {
34
+ return new Promise((resolve, reject) => {
35
+ const timer = setTimeout(() => {
36
+ try {
37
+ onTimeout?.();
38
+ }
39
+ catch {
40
+ // Best-effort: a throwing onTimeout must not replace the timeout error.
41
+ }
42
+ reject(new Error(`${label} timed out after ${ms}ms`));
43
+ }, ms);
44
+ op().then(resolve, reject).finally(() => clearTimeout(timer));
45
+ });
46
+ }
47
+ /** Normalize a libp2p chunk (Uint8Array or Uint8ArrayList) to a flat Uint8Array. */
48
+ function toBytes(chunk) {
49
+ return chunk instanceof Uint8Array ? chunk : chunk.subarray();
50
+ }
51
+ /**
52
+ * Read a stream to EOF, capped at `maxBytes`, bounded by `timeoutMs`, returning
53
+ * the assembled bytes (the caller decodes via `decodeLengthPrefixedFrame`).
54
+ *
55
+ * Implemented as `Promise.race([readLoop, timeout])`:
56
+ * - The size cap throws synchronously inside `readLoop` (a well-behaved peer may
57
+ * have sent a real-but-too-large frame and could still be reading for the ack,
58
+ * so this path does NOT abort the stream — it just rejects).
59
+ * - The timeout path is the true hang: it ALSO calls `stream.abort(err)` to
60
+ * release the stuck read. The race guarantees the helper settles at the
61
+ * deadline even if `abort()` does not immediately unblock the iterator (e.g. a
62
+ * test double whose `abort()` is a no-op).
63
+ */
64
+ export function readStreamToEnd(stream, opts) {
65
+ const { maxBytes, timeoutMs, label } = opts;
66
+ let timer;
67
+ const timeout = new Promise((_resolve, reject) => {
68
+ timer = setTimeout(() => {
69
+ const err = new Error(`${label} read timed out after ${timeoutMs}ms`);
70
+ // Release the hung read; the race below settles on `err` regardless of
71
+ // whether abort() promptly unblocks the iterator.
72
+ try {
73
+ stream.abort(err);
74
+ }
75
+ catch {
76
+ // Best-effort: a broken/closed stream may reject abort.
77
+ }
78
+ reject(err);
79
+ }, timeoutMs);
80
+ });
81
+ const readLoop = collect(stream, maxBytes, label);
82
+ return Promise.race([readLoop, timeout]).finally(() => clearTimeout(timer));
83
+ }
84
+ /** Accumulate every chunk to EOF, rejecting once the running total exceeds `maxBytes`. */
85
+ async function collect(stream, maxBytes, label) {
86
+ const chunks = [];
87
+ let total = 0;
88
+ for await (const chunk of stream) {
89
+ const bytes = toBytes(chunk);
90
+ chunks.push(bytes);
91
+ total += bytes.length;
92
+ if (total > maxBytes) {
93
+ throw new Error(`${label} message too large: ${total} bytes exceeds max ${maxBytes}`);
94
+ }
95
+ }
96
+ const data = new Uint8Array(total);
97
+ let offset = 0;
98
+ for (const chunk of chunks) {
99
+ data.set(chunk, offset);
100
+ offset += chunk.length;
101
+ }
102
+ return data;
103
+ }
104
+ //# sourceMapp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OAAO,CAAC,KAAK,CAAC,CAAC;QAC7B,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACnB,KAAK,IAAI,KAAK,CAAC,MAAM,CAAC;QACtB,IAAI,KAAK,GAAG,QAAQ,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,uBAAuB,KAAK,sBAAsB,QAAQ,EAAE,CAAC,CAAC;QACxF,CAAC;IACH,CAAC;IAED,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;IACnC,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC;IACzB,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Device-token record helpers: the single source of truth for the bytes a node
3
+ * signs when publishing its own `DeviceToken` row and re-verifies when resolving
4
+ * another peer's row.
5
+ *
6
+ * Modeled directly on {@link peerRecordSignedPayload} (peer-record.ts): the signed
7
+ * payload is a single SHA-256 digest of a delimited string of the authenticated
8
+ * fields. It is intentionally NOT JSON-canonicalized — a delimited digest is
9
+ * trivially deterministic across node/browser/RN (plain string concat + sha256, no
10
+ * key ordering) and is reconstructable inside the `DeviceToken.AuthorizedUpdate` SQL
11
+ * constraint from the row's own columns:
12
+ *
13
+ * digest(new.PeerId || '|' || new.Platform || '|' || new.Token || '|'
14
+ * || cast(new.UpdatedAt as text))
15
+ *
16
+ * Keep {@link deviceTokenSignedPayload} and that constraint byte-for-byte in sync.
17
+ * The `'|'` delimiter is safe: a base58btc PeerId, a fixed `'fcm'`/`'apns'` platform
18
+ * string, and a base-10 integer never contain it. The opaque platform token is the
19
+ * last variable-length field before the integer stamp, so even a token containing a
20
+ * `'|'` cannot create a collision with a different field split.
21
+ *
22
+ * Unlike a peer-address record, a device-token record carries NO public key: the
23
+ * signature is verified against the `CadrePeer.PublicKey` bound to the same PeerId
24
+ * (the resolver supplies it), so the key binding is checked exactly once, where the
25
+ * membership row already lives.
26
+ */
27
+ import type { DeviceTokenRecord, PushPlatform } from './types.js';
28
+ /**
29
+ * Build the base64url SHA-256 digest that the self-signature covers. Mirrors the
30
+ * `DeviceToken.AuthorizedUpdate` constraint exactly; both sides take the default
31
+ * base64url output of a single `digest(...)`, which round-trips cleanly.
32
+ */
33
+ export declare function deviceTokenSignedPayload(record: Omit<DeviceTokenRecord, 'sig'>): string;
34
+ /**
35
+ * Sign a device-token record with the ed25519 private key behind its `peerId`.
36
+ * Returns a fully-populated {@link DeviceTokenRecord}.
37
+ *
38
+ * @param fields - the record fields to sign
39
+ * @param privateKeyB64 - base64url ed25519 seed (see `authorityKeyFromLibp2p`)
40
+ */
41
+ export declare function signDeviceTokenRecord(fields: Omit<DeviceTokenRecord, 'sig'>, privateKeyB64: string): DeviceTokenRecord;
42
+ /**
43
+ * Verify a record's self-signature against the `CadrePeer.PublicKey` (base64url)
44
+ * bound to its `peerId`. Reconstructs the signed bytes from the record exactly as
45
+ * {@link signDeviceTokenRecord} produced them. Returns false on a missing key/sig or
46
+ * any verification failure.
47
+ */
48
+ export declare function verifyDeviceTokenSignature(record: DeviceTokenRecord, publicKeyB64: string): boolean;
49
+ /** Narrow an arbitrary stored string to a known {@link PushPlatform}. */
50
+ export declare function isPushPlatform(value: string): value is PushPlatform;
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Device-token record helpers: the single source of truth for the bytes a node
3
+ * signs when publishing its own `DeviceToken` row and re-verifies when resolving
4
+ * another peer's row.
5
+ *
6
+ * Modeled directly on {@link peerRecordSignedPayload} (peer-record.ts): the signed
7
+ * payload is a single SHA-256 digest of a delimited string of the authenticated
8
+ * fields. It is intentionally NOT JSON-canonicalized — a delimited digest is
9
+ * trivially deterministic across node/browser/RN (plain string concat + sha256, no
10
+ * key ordering) and is reconstructable inside the `DeviceToken.AuthorizedUpdate` SQL
11
+ * constraint from the row's own columns:
12
+ *
13
+ * digest(new.PeerId || '|' || new.Platform || '|' || new.Token || '|'
14
+ * || cast(new.UpdatedAt as text))
15
+ *
16
+ * Keep {@link deviceTokenSignedPayload} and that constraint byte-for-byte in sync.
17
+ * The `'|'` delimiter is safe: a base58btc PeerId, a fixed `'fcm'`/`'apns'` platform
18
+ * string, and a base-10 integer never contain it. The opaque platform token is the
19
+ * last variable-length field before the integer stamp, so even a token containing a
20
+ * `'|'` cannot create a collision with a different field split.
21
+ *
22
+ * Unlike a peer-address record, a device-token record carries NO public key: the
23
+ * signature is verified against the `CadrePeer.PublicKey` bound to the same PeerId
24
+ * (the resolver supplies it), so the key binding is checked exactly once, where the
25
+ * membership row already lives.
26
+ */
27
+ import { digest, sign, verify } from '@optimystic/quereus-plugin-crypto';
28
+ /**
29
+ * Build the base64url SHA-256 digest that the self-signature covers. Mirrors the
30
+ * `DeviceToken.AuthorizedUpdate` constraint exactly; both sides take the default
31
+ * base64url output of a single `digest(...)`, which round-trips cleanly.
32
+ */
33
+ export function deviceTokenSignedPayload(record) {
34
+ const joined = `${record.peerId}|${record.platform}|${record.token}|${record.updatedAt}`;
35
+ return digest([joined], 'sha256', 'base64url');
36
+ }
37
+ /**
38
+ * Sign a device-token record with the ed25519 private key behind its `peerId`.
39
+ * Returns a fully-populated {@link DeviceTokenRecord}.
40
+ *
41
+ * @param fields - the record fields to sign
42
+ * @param privateKeyB64 - base64url ed25519 seed (see `authorityKeyFromLibp2p`)
43
+ */
44
+ export function signDeviceTokenRecord(fields, privateKeyB64) {
45
+ const payloadDigest = deviceTokenSignedPayload(fields);
46
+ const sig = sign(payloadDigest, privateKeyB64, 'ed25519', 'base64url', 'base64url', 'base64url');
47
+ return { peerId: fields.peerId, platform: fields.platform, token: fields.token, updatedAt: fields.updatedAt, sig };
48
+ }
49
+ /**
50
+ * Verify a record's self-signature against the `CadrePeer.PublicKey` (base64url)
51
+ * bound to its `peerId`. Reconstructs the signed bytes from the record exactly as
52
+ * {@link signDeviceTokenRecord} produced them. Returns false on a missing key/sig or
53
+ * any verification failure.
54
+ */
55
+ export function verifyDeviceTokenSignature(record, publicKeyB64) {
56
+ if (!publicKeyB64 || !record.sig) {
57
+ return false;
58
+ }
59
+ const payloadDigest = deviceTokenSignedPayload(record);
60
+ return verify(payloadDigest, record.sig, publicKeyB64, 'ed25519', 'base64url', 'base64url', 'base64url');
61
+ }
62
+ /** Narrow an arbitrary stored string to a known {@link PushPlatform}. */
63
+ export function isPushPlatform(value) {
64
+ return value === 'fcm' || value === 'apns';
65
+ }
66
+ //# sourceMappingURL=device-token.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"device-token.js","sourceRoot":"","sources":["../src/device-token.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,mCAAmC,CAAC;AAGzE;;;;GAIG;AACH,MAAM,UAAU,wBAAwB,CAAC,MAAsC;IAC7E,MAAM,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,QAAQ,IAAI,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,SAAS,EAAE,CAAC;IACzF,OAAO,MAAM,CAAC,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,WAAW,CAAW,CAAC;AAC3D,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,qBAAqB,CACnC,MAAsC,EACtC,aAAqB;IAErB,MAAM,aAAa,GAAG,wBAAwB,CAAC,MAAM,CAAC,CAAC;IACvD,MAAM,GAAG,GAAG,IAAI,CACd,aAAa,EACb,aAAa,EACb,SAAS,EACT,WAAW,EACX,WAAW,EACX,WAAW,CACF,CAAC;IACZ,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,SAAS,EAAE,MAAM,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC;AACrH,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CAAC,MAAyB,EAAE,YAAoB;IACxF,IAAI,CAAC,YAAY,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;QACjC,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,aAAa,GAAG,wBAAwB,CAAC,MAAM,CAAC,CAAC;IACvD,OAAO,MAAM,CACX,aAAa,EACb,MAAM,CAAC,GAAG,EACV,YAAY,EACZ,SAAS,EACT,WAAW,EACX,WAAW,EACX,WAAW,CACZ,CAAC;AACJ,CAAC;AAED,yEAAyE;AACzE,MAAM,UAAU,cAAc,CAAC,KAAa;IAC1C,OAAO,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,MAAM,CAAC;AAC7C,CAAC"}
@@ -0,0 +1,118 @@
1
+ /**
2
+ * connection-path.ts — classify each open libp2p connection as relayed
3
+ * (`/p2p-circuit`) vs direct, tag its transport, and summarise counts plus a
4
+ * "stuck on relay" condition.
5
+ *
6
+ * This is the **canonical** implementation. The web reference app keeps a
7
+ * deliberate, documented duplicate at
8
+ * `packages/reference-app-web/src/lib/connection-path.ts` (it does not depend on
9
+ * `@serfab/cadre-core`). Keep the function signatures and classification table
10
+ * identical across both copies so a future shared micro-package would be a
11
+ * drop-in.
12
+ *
13
+ * The whole signal is a pure function over `node.getConnections()` + a settle
14
+ * window + `Date.now()`. A connection's path is derivable from its `remoteAddr`
15
+ * multiaddr string alone — no I/O, no events, no stateful observer.
16
+ */
17
+ export type ConnectionPathKind = 'relayed' | 'direct';
18
+ export type ConnectionTransport = 'circuit-relay' | 'webrtc' | 'webrtc-turn' | 'webrtc-direct' | 'websocket' | 'tcp' | 'unknown';
19
+ export interface ConnectionPath {
20
+ /** remotePeer.toString() */
21
+ peerId: string;
22
+ remoteAddr: string;
23
+ kind: ConnectionPathKind;
24
+ transport: ConnectionTransport;
25
+ direction: 'inbound' | 'outbound';
26
+ /** connection.timeline.open ?? null */
27
+ openedAtMs: number | null;
28
+ /** now - openedAtMs */
29
+ ageMs: number | null;
30
+ /** relayed && age > settleWindow && no direct conn to same peer */
31
+ stuckOnRelay: boolean;
32
+ }
33
+ export interface ConnectionPathSummary {
34
+ total: number;
35
+ relayed: number;
36
+ direct: number;
37
+ stuckOnRelay: number;
38
+ byTransport: Record<ConnectionTransport, number>;
39
+ /** best-effort; null when libp2p exposes no byte counter (see classifier docs) */
40
+ bytesOverRelay: number | null;
41
+ paths: ConnectionPath[];
42
+ settleWindowMs: number;
43
+ }
44
+ /**
45
+ * The minimal connection shape the classifier needs. The stock libp2p
46
+ * `Connection` (from `@libp2p/interface`) satisfies this structurally, and
47
+ * tests can build small synthetic objects against it.
48
+ */
49
+ export interface ConnectionLike {
50
+ remotePeer?: {
51
+ toString(): string;
52
+ };
53
+ remoteAddr?: {
54
+ toString(): string;
55
+ };
56
+ direction?: 'inbound' | 'outbound';
57
+ timeline?: {
58
+ open?: number;
59
+ };
60
+ /**
61
+ * Set externally (by {@link CadreNode}, from a {@link TurnRelayTracker}
62
+ * observation) when ICE selected a TURN relay candidate for this `/webrtc`
63
+ * session. `undefined` = unknown (the multiaddr alone cannot reveal it). Only
64
+ * honoured for the `webrtc` transport — see {@link classifyConnectionPath}.
65
+ */
66
+ turnRelayed?: boolean;
67
+ }
68
+ export declare const DEFAULT_SETTLE_WINDOW_MS = 10000;
69
+ interface TransportClass {
70
+ kind: ConnectionPathKind;
71
+ transport: ConnectionTransport;
72
+ }
73
+ /**
74
+ * Classify a remote multiaddr string into a (kind, transport) pair. Order
75
+ * matters — first match wins:
76
+ *
77
+ * | multiaddr contains | kind | transport |
78
+ * |-------------------------------|---------|----------------|
79
+ * | `/webrtc-direct` | direct | webrtc-direct |
80
+ * | `/webrtc` | direct | webrtc |
81
+ * | `/p2p-circuit` (no webrtc) | relayed | circuit-relay |
82
+ * | `/ws` (or `/wss`) | direct | websocket |
83
+ * | `/tcp` (and none of the above)| direct | tcp |
84
+ * | _none_ | direct | unknown |
85
+ *
86
+ * Note the ordering: a browser-to-browser WebRTC connection is dialed *over* a
87
+ * relay for SDP signalling and js-libp2p keeps the circuit prefix in the
88
+ * connection's remoteAddr — a successful hole-punch reads as
89
+ * `…/p2p-circuit/webrtc/p2p/…`, i.e. it contains BOTH `/p2p-circuit` and
90
+ * `/webrtc`. Its data path is nevertheless **direct**, so the WebRTC checks
91
+ * must come *before* `/p2p-circuit`. Only a connection with no transport after
92
+ * `/p2p-circuit` (`…/p2p-circuit/p2p/…`) is genuinely relay-carried.
93
+ */
94
+ export declare function classifyTransport(remoteAddr: string): TransportClass;
95
+ /**
96
+ * Per-connection classifier. Starts from the pure multiaddr classification, then
97
+ * applies the TURN override: a `/webrtc` session whose ICE selected a TURN relay
98
+ * candidate (`conn.turnRelayed === true`, set externally — the multiaddr alone
99
+ * cannot reveal it) is reclassified `relayed`/`webrtc-turn`. The
100
+ * `transport === 'webrtc'` guard means a `webrtc-direct` connection is never
101
+ * promoted (it uses no ICE and so can never be TURN-relayed), and `undefined`
102
+ * (unknown) degrades safely to the multiaddr result — not relayed.
103
+ */
104
+ export declare function classifyConnectionPath(conn: ConnectionLike): TransportClass;
105
+ /** An all-zero summary, used when no node/connections are available. */
106
+ export declare function emptyConnectionPathSummary(settleWindowMs?: number): ConnectionPathSummary;
107
+ /**
108
+ * Build a {@link ConnectionPathSummary} from the node's current connections.
109
+ *
110
+ * `stuckOnRelay` per connection is `relayed && ageMs != null && ageMs >
111
+ * settleWindowMs && no direct connection to the same peer` — the relay-only
112
+ * silent-failure condition (WebRTC negotiation failed, the connection quietly
113
+ * stays on the relay). The direct-peer set is the set of `peerId`s that have at
114
+ * least one `direct` connection, so a peer mid-upgrade (a relayed circuit conn
115
+ * *and* a direct webrtc conn at once) is correctly not flagged.
116
+ */
117
+ export declare function summarizeConnectionPaths(conns: Iterable<ConnectionLike> | null | undefined, settleWindowMs?: number): ConnectionPathSummary;
118
+ export {};
@@ -0,0 +1,204 @@
1
+ /**
2
+ * connection-path.ts — classify each open libp2p connection as relayed
3
+ * (`/p2p-circuit`) vs direct, tag its transport, and summarise counts plus a
4
+ * "stuck on relay" condition.
5
+ *
6
+ * This is the **canonical** implementation. The web reference app keeps a
7
+ * deliberate, documented duplicate at
8
+ * `packages/reference-app-web/src/lib/connection-path.ts` (it does not depend on
9
+ * `@serfab/cadre-core`). Keep the function signatures and classification table
10
+ * identical across both copies so a future shared micro-package would be a
11
+ * drop-in.
12
+ *
13
+ * The whole signal is a pure function over `node.getConnections()` + a settle
14
+ * window + `Date.now()`. A connection's path is derivable from its `remoteAddr`
15
+ * multiaddr string alone — no I/O, no events, no stateful observer.
16
+ */
17
+ export const DEFAULT_SETTLE_WINDOW_MS = 10000;
18
+ const ALL_TRANSPORTS = [
19
+ 'circuit-relay',
20
+ 'webrtc',
21
+ 'webrtc-turn',
22
+ 'webrtc-direct',
23
+ 'websocket',
24
+ 'tcp',
25
+ 'unknown',
26
+ ];
27
+ /**
28
+ * Classify a remote multiaddr string into a (kind, transport) pair. Order
29
+ * matters — first match wins:
30
+ *
31
+ * | multiaddr contains | kind | transport |
32
+ * |-------------------------------|---------|----------------|
33
+ * | `/webrtc-direct` | direct | webrtc-direct |
34
+ * | `/webrtc` | direct | webrtc |
35
+ * | `/p2p-circuit` (no webrtc) | relayed | circuit-relay |
36
+ * | `/ws` (or `/wss`) | direct | websocket |
37
+ * | `/tcp` (and none of the above)| direct | tcp |
38
+ * | _none_ | direct | unknown |
39
+ *
40
+ * Note the ordering: a browser-to-browser WebRTC connection is dialed *over* a
41
+ * relay for SDP signalling and js-libp2p keeps the circuit prefix in the
42
+ * connection's remoteAddr — a successful hole-punch reads as
43
+ * `…/p2p-circuit/webrtc/p2p/…`, i.e. it contains BOTH `/p2p-circuit` and
44
+ * `/webrtc`. Its data path is nevertheless **direct**, so the WebRTC checks
45
+ * must come *before* `/p2p-circuit`. Only a connection with no transport after
46
+ * `/p2p-circuit` (`…/p2p-circuit/p2p/…`) is genuinely relay-carried.
47
+ */
48
+ export function classifyTransport(remoteAddr) {
49
+ const addr = remoteAddr ?? '';
50
+ if (addr.includes('/webrtc-direct'))
51
+ return { kind: 'direct', transport: 'webrtc-direct' };
52
+ if (addr.includes('/webrtc'))
53
+ return { kind: 'direct', transport: 'webrtc' };
54
+ if (addr.includes('/p2p-circuit'))
55
+ return { kind: 'relayed', transport: 'circuit-relay' };
56
+ if (addr.includes('/ws'))
57
+ return { kind: 'direct', transport: 'websocket' };
58
+ if (addr.includes('/tcp'))
59
+ return { kind: 'direct', transport: 'tcp' };
60
+ return { kind: 'direct', transport: 'unknown' };
61
+ }
62
+ /** Read a connection's remote address as a string, never throwing. */
63
+ function addrString(conn) {
64
+ try {
65
+ return conn.remoteAddr?.toString?.() ?? '';
66
+ }
67
+ catch {
68
+ return '';
69
+ }
70
+ }
71
+ /**
72
+ * Per-connection classifier. Starts from the pure multiaddr classification, then
73
+ * applies the TURN override: a `/webrtc` session whose ICE selected a TURN relay
74
+ * candidate (`conn.turnRelayed === true`, set externally — the multiaddr alone
75
+ * cannot reveal it) is reclassified `relayed`/`webrtc-turn`. The
76
+ * `transport === 'webrtc'` guard means a `webrtc-direct` connection is never
77
+ * promoted (it uses no ICE and so can never be TURN-relayed), and `undefined`
78
+ * (unknown) degrades safely to the multiaddr result — not relayed.
79
+ */
80
+ export function classifyConnectionPath(conn) {
81
+ const { kind, transport } = classifyTransport(addrString(conn));
82
+ if (transport === 'webrtc' && conn.turnRelayed === true) {
83
+ return { kind: 'relayed', transport: 'webrtc-turn' };
84
+ }
85
+ return { kind, transport };
86
+ }
87
+ /**
88
+ * Best-effort per-connection byte counter. The stock libp2p `Connection`
89
+ * interface carries no byte counter, so unless a metrics implementation is
90
+ * wired into the node this returns `null`. Never throws.
91
+ */
92
+ function readConnectionBytes(conn) {
93
+ try {
94
+ const metrics = conn.metrics;
95
+ if (!metrics)
96
+ return null;
97
+ const received = typeof metrics.bytesReceived === 'number' ? metrics.bytesReceived : 0;
98
+ const sent = typeof metrics.bytesSent === 'number' ? metrics.bytesSent : 0;
99
+ const total = received + sent;
100
+ return Number.isFinite(total) ? total : null;
101
+ }
102
+ catch {
103
+ return null;
104
+ }
105
+ }
106
+ function zeroByTransport() {
107
+ const out = {};
108
+ for (const t of ALL_TRANSPORTS)
109
+ out[t] = 0;
110
+ return out;
111
+ }
112
+ /** An all-zero summary, used when no node/connections are available. */
113
+ export function emptyConnectionPathSummary(settleWindowMs = DEFAULT_SETTLE_WINDOW_MS) {
114
+ return {
115
+ total: 0,
116
+ relayed: 0,
117
+ direct: 0,
118
+ stuckOnRelay: 0,
119
+ byTransport: zeroByTransport(),
120
+ bytesOverRelay: null,
121
+ paths: [],
122
+ settleWindowMs,
123
+ };
124
+ }
125
+ /**
126
+ * Build a {@link ConnectionPathSummary} from the node's current connections.
127
+ *
128
+ * `stuckOnRelay` per connection is `relayed && ageMs != null && ageMs >
129
+ * settleWindowMs && no direct connection to the same peer` — the relay-only
130
+ * silent-failure condition (WebRTC negotiation failed, the connection quietly
131
+ * stays on the relay). The direct-peer set is the set of `peerId`s that have at
132
+ * least one `direct` connection, so a peer mid-upgrade (a relayed circuit conn
133
+ * *and* a direct webrtc conn at once) is correctly not flagged.
134
+ */
135
+ export function summarizeConnectionPaths(conns, settleWindowMs = DEFAULT_SETTLE_WINDOW_MS) {
136
+ const now = Date.now();
137
+ const list = conns ? Array.from(conns) : [];
138
+ // First pass: classify each connection and find the set of peers that have at
139
+ // least one direct connection.
140
+ const classified = list.map((conn) => {
141
+ const remoteAddr = addrString(conn);
142
+ // classifyConnectionPath (not classifyTransport) so the externally-set
143
+ // turnRelayed hint promotes webrtc → webrtc-turn (relayed).
144
+ const { kind, transport } = classifyConnectionPath(conn);
145
+ const openedAtMs = typeof conn.timeline?.open === 'number' ? conn.timeline.open : null;
146
+ const ageMs = openedAtMs != null ? Math.max(0, now - openedAtMs) : null;
147
+ const peerId = safePeerId(conn);
148
+ const direction = conn.direction === 'inbound' ? 'inbound' : 'outbound';
149
+ return { conn, peerId, remoteAddr, kind, transport, openedAtMs, ageMs, direction };
150
+ });
151
+ const directPeerSet = new Set(classified.filter((c) => c.kind === 'direct').map((c) => c.peerId));
152
+ const byTransport = zeroByTransport();
153
+ let relayed = 0;
154
+ let direct = 0;
155
+ let stuckCount = 0;
156
+ let bytesOverRelay = null;
157
+ const paths = classified.map((c) => {
158
+ byTransport[c.transport] += 1;
159
+ if (c.kind === 'relayed') {
160
+ relayed += 1;
161
+ const bytes = readConnectionBytes(c.conn);
162
+ if (bytes != null)
163
+ bytesOverRelay = (bytesOverRelay ?? 0) + bytes;
164
+ }
165
+ else {
166
+ direct += 1;
167
+ }
168
+ const stuckOnRelay = c.kind === 'relayed' &&
169
+ c.ageMs != null &&
170
+ c.ageMs > settleWindowMs &&
171
+ !directPeerSet.has(c.peerId);
172
+ if (stuckOnRelay)
173
+ stuckCount += 1;
174
+ return {
175
+ peerId: c.peerId,
176
+ remoteAddr: c.remoteAddr,
177
+ kind: c.kind,
178
+ transport: c.transport,
179
+ direction: c.direction,
180
+ openedAtMs: c.openedAtMs,
181
+ ageMs: c.ageMs,
182
+ stuckOnRelay,
183
+ };
184
+ });
185
+ return {
186
+ total: list.length,
187
+ relayed,
188
+ direct,
189
+ stuckOnRelay: stuckCount,
190
+ byTransport,
191
+ bytesOverRelay,
192
+ paths,
193
+ settleWindowMs,
194
+ };
195
+ }
196
+ function safePeerId(conn) {
197
+ try {
198
+ return conn.remotePeer?.toString?.() ?? '';
199
+ }
200
+ catch {
201
+ return '';
202
+ }
203
+ }
204
+ //# sourceMappingURL=connection-path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection-path.js","sourceRoot":"","sources":["../../src/diagnostics/connection-path.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AA2DH,MAAM,CAAC,MAAM,wBAAwB,GAAG,KAAM,CAA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AU,EAAE,CAAC,CAAC,UAAU;YACxB,IAAI,EAAE,CAAC,CAAC,IAAI;YACZ,SAAS,EAAE,CAAC,CAAC,SAAS;YACtB,SAAS,EAAE,CAAC,CAAC,SAAS;YACtB,UAAU,EAAE,CAAC,CAAC,UAAU;YACxB,KAAK,EAAE,CAAC,CAAC,KAAK;YACd,YAAY;SACb,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO;QACL,KAAK,EAAE,IAAI,CAAC,MAAM;QAClB,OAAO;QACP,MAAM;QACN,YAAY,EAAE,UAAU;QACxB,WAAW;QACX,cAAc;QACd,KAAK;QACL,cAAc;KACf,CAAC;AACJ,CAAC;AAED,SAAS,UAAU,CAAC,IAAoB;IACtC,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,UAAU,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,CAAC;IAC7C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC"}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * webrtc-turn-tracker.ts — observe whether ICE selected a TURN relay candidate
3
+ * for each WebRTC session, so a TURN-relayed `/webrtc` connection can be
4
+ * reclassified `relayed`/`webrtc-turn` instead of silently counted `direct`.
5
+ *
6
+ * `@libp2p/webrtc` keeps the underlying `RTCPeerConnection` private and never
7
+ * surfaces it on the libp2p `Connection`, so the multiaddr classifier
8
+ * (`connection-path.ts`) cannot see the ICE candidate types. This tracker hooks
9
+ * `globalThis.RTCPeerConnection` at install time: every connection that reaches
10
+ * `connectionState === 'connected'` is inspected via `getStats()`, and the
11
+ * relay/not-relay verdict for the selected candidate pair is pushed onto a FIFO
12
+ * queue. {@link CadreNode} drains that queue on each `connection:open` to tag the
13
+ * matching peer (see {@link consume}).
14
+ *
15
+ * The correlation between a queued settlement and a `connection:open` is
16
+ * timing-based and best-effort — it degrades gracefully (unknown → treated as not
17
+ * relayed, a safe default that never produces a false `relayed`). It is inert on
18
+ * Node.js / any runtime with no `RTCPeerConnection`.
19
+ */
20
+ export declare class TurnRelayTracker {
21
+ private readonly queue;
22
+ private OriginalRTCPeerConnection;
23
+ /** One settlement record per connection; guards against repeated `connected` events. */
24
+ private readonly observed;
25
+ /**
26
+ * Wrap `globalThis.RTCPeerConnection` with a subclass that records each
27
+ * connection's TURN-relay verdict when it settles. Idempotent. A NOP when no
28
+ * `RTCPeerConnection` exists (Node.js / no WebRTC polyfill) — the tracker stays
29
+ * inert and {@link consume} always returns `null`.
30
+ */
31
+ install(): void;
32
+ /**
33
+ * Pop the most recent settled entry within `windowMs` ms of now, returning its
34
+ * relay verdict (`true`/`false`); `null` when the queue has no matching entry.
35
+ * Also prunes entries older than the window (they can never match a later
36
+ * consume). Synchronous and safe to call from a `connection:open` handler.
37
+ */
38
+ consume(windowMs: number): boolean | null;
39
+ /** Restore the original `RTCPeerConnection` and clear the queue. Idempotent. */
40
+ dispose(): void;
41
+ /**
42
+ * Inspect a settled connection's stats and queue its TURN-relay verdict. Any
43
+ * failure (stats API absent, rejected promise, malformed report) is caught and
44
+ * recorded as `isRelay: false` — the safe default (unknown → not relayed) keeps
45
+ * the connection counted rather than dropping it.
46
+ */
47
+ private recordSettlement;
48
+ /** Drop queued entries settled before `cutoffMs` (the queue is in push order). */
49
+ private pruneOlderThan;
50
+ }