@serfab/cadre-core 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/README.md +255 -253
  2. package/dist/bootstrap-peer-store-file.d.ts +13 -0
  3. package/dist/bootstrap-peer-store-file.js +42 -0
  4. package/dist/bootstrap-peer-store-file.js.map +1 -0
  5. package/dist/bootstrap-peer-store.d.ts +73 -0
  6. package/dist/bootstrap-peer-store.js +128 -0
  7. package/dist/bootstrap-peer-store.js.map +1 -0
  8. package/dist/cadre-node.d.ts +1121 -81
  9. package/dist/cadre-node.js +2276 -262
  10. package/dist/cadre-node.js.map +1 -1
  11. package/dist/control-authorization.d.ts +93 -0
  12. package/dist/control-authorization.js +57 -0
  13. package/dist/control-authorization.js.map +1 -0
  14. package/dist/control-cohort.d.ts +26 -0
  15. package/dist/control-cohort.js +26 -0
  16. package/dist/control-cohort.js.map +1 -1
  17. package/dist/control-database.d.ts +959 -54
  18. package/dist/control-database.js +1421 -148
  19. package/dist/control-database.js.map +1 -1
  20. package/dist/control-formation-recorder.d.ts +90 -10
  21. package/dist/control-formation-recorder.js +130 -14
  22. package/dist/control-formation-recorder.js.map +1 -1
  23. package/dist/control-schema.d.ts +1 -1
  24. package/dist/control-schema.js +651 -72
  25. package/dist/control-schema.js.map +1 -1
  26. package/dist/control-stream.d.ts +38 -4
  27. package/dist/control-stream.js +70 -4
  28. package/dist/control-stream.js.map +1 -1
  29. package/dist/control-write-retry.d.ts +161 -0
  30. package/dist/control-write-retry.js +412 -0
  31. package/dist/control-write-retry.js.map +1 -0
  32. package/dist/delegate-admission.d.ts +134 -0
  33. package/dist/delegate-admission.js +244 -0
  34. package/dist/delegate-admission.js.map +1 -0
  35. package/dist/device-token.d.ts +11 -11
  36. package/dist/device-token.js +14 -13
  37. package/dist/device-token.js.map +1 -1
  38. package/dist/ed25519-key.d.ts +26 -0
  39. package/dist/ed25519-key.js +56 -1
  40. package/dist/ed25519-key.js.map +1 -1
  41. package/dist/file-durable-slot.d.ts +20 -0
  42. package/dist/file-durable-slot.js +53 -0
  43. package/dist/file-durable-slot.js.map +1 -0
  44. package/dist/formation-approval.d.ts +157 -0
  45. package/dist/formation-approval.js +375 -0
  46. package/dist/formation-approval.js.map +1 -0
  47. package/dist/fs-atomic.d.ts +38 -0
  48. package/dist/fs-atomic.js +97 -0
  49. package/dist/fs-atomic.js.map +1 -0
  50. package/dist/identity-key.d.ts +49 -0
  51. package/dist/identity-key.js +81 -0
  52. package/dist/identity-key.js.map +1 -0
  53. package/dist/index.d.ts +17 -7
  54. package/dist/index.js +40 -6
  55. package/dist/index.js.map +1 -1
  56. package/dist/key-store-file.d.ts +2 -24
  57. package/dist/key-store-file.js +10 -77
  58. package/dist/key-store-file.js.map +1 -1
  59. package/dist/membership-connection-gater.d.ts +146 -0
  60. package/dist/membership-connection-gater.js +180 -0
  61. package/dist/membership-connection-gater.js.map +1 -0
  62. package/dist/node-local-snapshot.d.ts +109 -0
  63. package/dist/node-local-snapshot.js +182 -0
  64. package/dist/node-local-snapshot.js.map +1 -0
  65. package/dist/peer-addr-book.d.ts +92 -0
  66. package/dist/peer-addr-book.js +220 -0
  67. package/dist/peer-addr-book.js.map +1 -0
  68. package/dist/peer-authorization.d.ts +135 -18
  69. package/dist/peer-authorization.js +152 -21
  70. package/dist/peer-authorization.js.map +1 -1
  71. package/dist/peer-record.d.ts +21 -8
  72. package/dist/peer-record.js +26 -10
  73. package/dist/peer-record.js.map +1 -1
  74. package/dist/relay-addrs.d.ts +45 -0
  75. package/dist/relay-addrs.js +103 -0
  76. package/dist/relay-addrs.js.map +1 -0
  77. package/dist/relay-reservation.d.ts +266 -0
  78. package/dist/relay-reservation.js +613 -0
  79. package/dist/relay-reservation.js.map +1 -0
  80. package/dist/seed-bootstrap.d.ts +228 -56
  81. package/dist/seed-bootstrap.js +340 -198
  82. package/dist/seed-bootstrap.js.map +1 -1
  83. package/dist/seed-trust-policy.d.ts +47 -21
  84. package/dist/seed-trust-policy.js +24 -15
  85. package/dist/seed-trust-policy.js.map +1 -1
  86. package/dist/strand-addr-protocol.d.ts +42 -13
  87. package/dist/strand-addr-protocol.js +58 -52
  88. package/dist/strand-addr-protocol.js.map +1 -1
  89. package/dist/strand-backfill.d.ts +109 -0
  90. package/dist/strand-backfill.js +279 -0
  91. package/dist/strand-backfill.js.map +1 -0
  92. package/dist/strand-cohort.d.ts +4 -37
  93. package/dist/strand-cohort.js +4 -15
  94. package/dist/strand-cohort.js.map +1 -1
  95. package/dist/strand-database.d.ts +11 -16
  96. package/dist/strand-database.js +19 -7
  97. package/dist/strand-database.js.map +1 -1
  98. package/dist/strand-formation-manager.d.ts +36 -7
  99. package/dist/strand-formation-manager.js +115 -15
  100. package/dist/strand-formation-manager.js.map +1 -1
  101. package/dist/strand-formation-protocol.d.ts +103 -4
  102. package/dist/strand-formation-protocol.js +232 -4
  103. package/dist/strand-formation-protocol.js.map +1 -1
  104. package/dist/strand-instance-manager.d.ts +88 -19
  105. package/dist/strand-instance-manager.js +178 -34
  106. package/dist/strand-instance-manager.js.map +1 -1
  107. package/dist/strand-member-registry.d.ts +5 -5
  108. package/dist/strand-member-registry.js +18 -10
  109. package/dist/strand-member-registry.js.map +1 -1
  110. package/dist/strand-membership-writer.d.ts +484 -88
  111. package/dist/strand-membership-writer.js +751 -128
  112. package/dist/strand-membership-writer.js.map +1 -1
  113. package/dist/strand-solicitation.d.ts +99 -33
  114. package/dist/strand-solicitation.js +100 -52
  115. package/dist/strand-solicitation.js.map +1 -1
  116. package/dist/strand-transport-key.d.ts +40 -0
  117. package/dist/strand-transport-key.js +56 -0
  118. package/dist/strand-transport-key.js.map +1 -0
  119. package/dist/strand-wake-protocol.d.ts +9 -7
  120. package/dist/strand-wake-protocol.js +22 -46
  121. package/dist/strand-wake-protocol.js.map +1 -1
  122. package/dist/strand-watcher.d.ts +17 -2
  123. package/dist/strand-watcher.js +47 -3
  124. package/dist/strand-watcher.js.map +1 -1
  125. package/dist/trusted-owner-store-file.d.ts +12 -0
  126. package/dist/trusted-owner-store-file.js +39 -0
  127. package/dist/trusted-owner-store-file.js.map +1 -0
  128. package/dist/trusted-owner-store.d.ts +64 -0
  129. package/dist/trusted-owner-store.js +126 -0
  130. package/dist/trusted-owner-store.js.map +1 -0
  131. package/dist/types.d.ts +307 -44
  132. package/dist/types.js +13 -0
  133. package/dist/types.js.map +1 -1
  134. package/package.json +20 -8
  135. package/src/arachnode-stub.ts +159 -159
  136. package/src/bootstrap-peer-store-file.ts +44 -0
  137. package/src/bootstrap-peer-store.ts +172 -0
  138. package/src/cadre-node.ts +5158 -2981
  139. package/src/canonical-json.ts +30 -30
  140. package/src/control-authorization.ts +114 -0
  141. package/src/control-cohort.ts +130 -103
  142. package/src/control-database.ts +2406 -948
  143. package/src/control-formation-recorder.ts +305 -151
  144. package/src/control-schema.ts +651 -72
  145. package/src/control-stream.ts +205 -128
  146. package/src/control-write-retry.ts +483 -0
  147. package/src/delegate-admission.ts +302 -0
  148. package/src/device-token.ts +94 -89
  149. package/src/diagnostics/connection-path.ts +277 -277
  150. package/src/diagnostics/webrtc-turn-tracker.ts +222 -222
  151. package/src/ed25519-key.ts +66 -1
  152. package/src/enrollment.ts +199 -199
  153. package/src/file-durable-slot.ts +61 -0
  154. package/src/formation-approval.ts +604 -0
  155. package/src/fs-atomic.ts +107 -0
  156. package/src/hibernation-manager.ts +437 -437
  157. package/src/identity-key.ts +109 -0
  158. package/src/index.ts +137 -5
  159. package/src/key-store-file.ts +132 -203
  160. package/src/key-store.ts +99 -99
  161. package/src/membership-connection-gater.ts +204 -0
  162. package/src/node-local-snapshot.ts +260 -0
  163. package/src/peer-addr-book.ts +250 -0
  164. package/src/peer-authorization.ts +259 -81
  165. package/src/peer-record.ts +164 -146
  166. package/src/push-credentials.ts +84 -84
  167. package/src/push-node.ts +64 -64
  168. package/src/push-notifier-apns.ts +247 -247
  169. package/src/push-notifier-fcm.ts +220 -220
  170. package/src/push-notifier-shared.ts +28 -28
  171. package/src/push-notifier.ts +52 -52
  172. package/src/relay-addrs.ts +111 -0
  173. package/src/relay-reservation.ts +823 -0
  174. package/src/seed-bootstrap.ts +409 -209
  175. package/src/seed-trust-policy.ts +140 -107
  176. package/src/strand-addr-protocol.ts +441 -410
  177. package/src/strand-backfill.ts +366 -0
  178. package/src/strand-cohort.ts +38 -77
  179. package/src/strand-database.ts +202 -204
  180. package/src/strand-formation-manager.ts +491 -368
  181. package/src/strand-formation-protocol.ts +692 -391
  182. package/src/strand-instance-manager.ts +201 -46
  183. package/src/strand-member-key.ts +39 -39
  184. package/src/strand-member-registry.ts +182 -177
  185. package/src/strand-membership-writer.ts +938 -146
  186. package/src/strand-solicitation.ts +472 -407
  187. package/src/strand-transport-key.ts +58 -0
  188. package/src/strand-wake-payload.ts +32 -32
  189. package/src/strand-wake-protocol.ts +314 -331
  190. package/src/strand-watcher.ts +314 -251
  191. package/src/trusted-owner-store-file.ts +41 -0
  192. package/src/trusted-owner-store.ts +171 -0
  193. package/src/types.ts +1309 -1032
@@ -1,44 +1,120 @@
1
1
  import debug from 'debug';
2
2
  import { digest, verify } from '@optimystic/quereus-plugin-crypto';
3
+ import { controlAuthorizationFields } from './control-authorization.js';
3
4
  const log = debug('sereus:cadre:peer-authorization');
4
5
  /**
5
- * Canonical digest an owner signs to authorize a peer.
6
+ * base64url SHA-256 digest over the shared domain-tagged field vector (see
7
+ * control-authorization.ts). The base64url twin of
8
+ * control-database.ts:buildAuthorizationMessage (which returns the same digest as raw
9
+ * bytes): sign either encoding with input encoding to match and the signed bytes agree.
10
+ */
11
+ function taggedDigest(domain, action, rowFields) {
12
+ return digest(controlAuthorizationFields(domain, action, rowFields), 'sha256', 'base64url');
13
+ }
14
+ /**
15
+ * Canonical digest an owner signs to vouch a peer's ENROLLMENT — the offline
16
+ * credential `cadre enroll register` verifies. No table checks this digest, so it
17
+ * carries its own `'Cadre.Enrollment'` domain tag to stay disjoint from every
18
+ * CadreControl table rule (pre-tag it collided with the `DeviceToken` owner digests,
19
+ * so an enrollment vouch doubled as a push-token delete approval).
6
20
  *
7
- * This is the exact byte construction {@link SeedBootstrapService.authorizePeer}
8
- * signs over when it inserts an authorized `CadrePeer` row:
9
- * `digest([peerId], 'sha256', 'base64url')`. Factored into one place so the
10
- * producer (owner signing) and the verifier (the offline `cadre enroll
11
- * register` check) can never drift apart — change the digest here and both move
12
- * together. The SQL mirror is the bare single-field `digest(coalesce(new.PeerId, old.PeerId))`.
21
+ * Factored into one place so the producer (owner signing) and the verifier (the
22
+ * offline `cadre enroll register` check) can never drift apart — change the digest
23
+ * here and both move together.
13
24
  */
14
25
  export function peerAuthorizationDigest(peerId) {
15
- return digest([peerId], 'sha256', 'base64url');
26
+ return taggedDigest('Cadre.Enrollment', 'vouch', [peerId]);
27
+ }
28
+ /**
29
+ * Canonical digest an owner signs to authorize a `DeviceToken` INSERT — the WHOLE row,
30
+ * ending in its single-use `StampId` nonce. SQL mirror:
31
+ * `digest('CadreControl.DeviceToken', 'add', new.PeerId, new.Platform, new.Token,
32
+ * coalesce(cast(new.UpdatedAt as text), ''), coalesce(new.Sig, ''), new.StampId)` in
33
+ * `DeviceToken.AuthorizedInsert`.
34
+ *
35
+ * Binding every column means a captured approval can only ever reproduce the exact row
36
+ * it approved — never one carrying attacker-chosen `Platform`/`Token`/`UpdatedAt` — and
37
+ * binding the stamp makes it single-use: while the row lives the `unique` column blocks
38
+ * a replay, and after a clear the stamp is retired permanently into
39
+ * `CadreControl.Revocation` (`DeviceToken.NotRevoked`). This matters more here than for
40
+ * `CadrePeer`: a resurrected push token has NO freshness ceiling to retire it
41
+ * (`CadreNode.resolveDeviceToken` defaults `maxAgeMs` to infinity by design), so stamp
42
+ * retirement is the only thing that sticks.
43
+ *
44
+ * Distinct from {@link deviceTokenRemoveDigest} so a captured insert approval can never
45
+ * be replayed to delete the token, and vice versa.
46
+ */
47
+ export function deviceTokenAddDigest(row) {
48
+ return taggedDigest('CadreControl.DeviceToken', 'add', [
49
+ row.peerId,
50
+ row.platform,
51
+ row.token,
52
+ row.updatedAt === null ? '' : String(row.updatedAt),
53
+ row.sig ?? '',
54
+ row.stampId,
55
+ ]);
56
+ }
57
+ /**
58
+ * Canonical digest an owner signs to authorize a `DeviceToken` DELETE, bound to the
59
+ * STORED row's (PeerId, StampId). SQL mirror:
60
+ * `digest('CadreControl.DeviceToken', 'remove', old.PeerId, old.StampId)` in
61
+ * `DeviceToken.AuthorizedDelete`.
62
+ *
63
+ * A narrower vector than {@link deviceTokenAddDigest} on purpose (the same split
64
+ * `CadrePeer` makes): the clear approval names only which row is being retired, so it
65
+ * cannot be re-cut into an insert approval, and it is dead the moment the stamp it
66
+ * names is tombstoned.
67
+ */
68
+ export function deviceTokenRemoveDigest(peerId, stampId) {
69
+ return taggedDigest('CadreControl.DeviceToken', 'remove', [peerId, stampId]);
16
70
  }
17
71
  /**
18
72
  * Canonical digest an owner signs to VOUCH a `CadrePeer` membership row (insert
19
- * and the owner re-touch update). Binds the peer id to the row's single-use
20
- * `StampId` nonce, so a captured signed insert cannot be replayed (the `StampId` is
21
- * unique) and — because {@link cadrePeerRemoveDigest} scopes a DIFFERENT payload — the
22
- * stored voucher (`VouchSig`) cannot be replayed to authorize a delete.
73
+ * and the owner re-touch update — same semantics, deliberately the same digest).
74
+ * Binds the peer id to the row's single-use `StampId` nonce, so a captured signed
75
+ * insert cannot be replayed — while the row lives the `unique` column blocks it, and
76
+ * after a removal the stamp is retired permanently into `CadreControl.Revocation`
77
+ * (`CadrePeer.NotRevoked`) — and, because {@link cadrePeerRemoveDigest} scopes a
78
+ * DIFFERENT payload, the stored voucher (`VouchSig`) cannot be replayed to authorize
79
+ * a delete. The domain tag keeps the stored, replicated `VouchSig` useless against
80
+ * every OTHER table's rules.
23
81
  *
24
- * The SQL mirror is `digest(new.PeerId, new.StampId)` (two TEXT fields), matching the
25
- * canonical multi-field framing in control-database.ts:buildAuthorizationMessage.
82
+ * SQL mirror: `digest('CadreControl.CadrePeer', 'vouch', new.PeerId, new.StampId)`.
26
83
  */
27
84
  export function cadrePeerVoucherDigest(peerId, stampId) {
28
- return digest([peerId, stampId], 'sha256', 'base64url');
85
+ return taggedDigest('CadreControl.CadrePeer', 'vouch', [peerId, stampId]);
29
86
  }
30
87
  /**
31
88
  * Canonical digest an owner signs to REMOVE a `CadrePeer` row. Deliberately a
32
- * distinct payload from {@link cadrePeerVoucherDigest} (adds the `'remove'` action
33
- * tag) so the row's stored voucher — a signature over the voucher digest — can never
89
+ * distinct payload from {@link cadrePeerVoucherDigest} (the `'remove'` action tag)
90
+ * so the row's stored voucher — a signature over the voucher digest — can never
34
91
  * satisfy this delete check. The signature is supplied in write context and never
35
- * stored, so no reader can replay it; binding the live row's `StampId` also invalidates
36
- * any captured remove after a delete+reinsert (the nonce rotates).
92
+ * stored, so no reader can replay it; a captured remove is also dead after the
93
+ * delete lands, because a re-added row carries a FRESH `StampId` (the removed row's
94
+ * stamp is retired into `CadreControl.Revocation` and never reused).
37
95
  *
38
- * SQL mirror: `digest(old.PeerId, old.StampId, 'remove')`.
96
+ * SQL mirror: `digest('CadreControl.CadrePeer', 'remove', old.PeerId, old.StampId)`.
39
97
  */
40
98
  export function cadrePeerRemoveDigest(peerId, stampId) {
41
- return digest([peerId, stampId, 'remove'], 'sha256', 'base64url');
99
+ return taggedDigest('CadreControl.CadrePeer', 'remove', [peerId, stampId]);
100
+ }
101
+ /**
102
+ * Canonical digest an owner signs to APPEND a `CadreControl.Revocation` tombstone —
103
+ * the row retiring `stampId` for the named guarded table, and recording `rowKey`
104
+ * (the removed row's primary key: OwnerKey.Key / ValidationKey.Key /
105
+ * CadrePeer.PeerId / DeviceToken.PeerId / Strand.Id) as which row was retired.
106
+ * SQL mirror:
107
+ * `digest('CadreControl.Revocation', 'remove', new.TableName, new.RowKey, new.StampId)`
108
+ * in `Revocation.Authorized`.
109
+ *
110
+ * Its own `'CadreControl.Revocation'` domain tag makes it disjoint from the
111
+ * `'CadreControl.CadrePeer'` (or `OwnerKey` / `ValidationKey` / `Strand`)
112
+ * `'remove'` digest the same owner signs in the SAME transaction for the delete
113
+ * this tombstone accompanies — a removal signature is not a retirement
114
+ * signature and cannot be replayed as one.
115
+ */
116
+ export function revocationDigest(tableName, rowKey, stampId) {
117
+ return taggedDigest('CadreControl.Revocation', 'remove', [tableName, rowKey, stampId]);
42
118
  }
43
119
  /**
44
120
  * Verify that `signature` is a valid owner ed25519 signature over `peerId`'s
@@ -63,4 +139,59 @@ export function verifyPeerAuthorization(peerId, ownerPublicKey, signature) {
63
139
  return false;
64
140
  }
65
141
  }
142
+ /**
143
+ * Verify that `signature` is a valid owner ed25519 signature over the
144
+ * `CadrePeer` voucher digest for (`peerId`, `stampId`) — the read-side mirror
145
+ * of the voucher {@link ControlDatabase.insertCadrePeer} signs and persists into
146
+ * `VouchOwner`/`VouchSig` (see {@link cadrePeerVoucherDigest}).
147
+ *
148
+ * A `true` result means the holder of `ownerPublicKey` vouched THIS membership
149
+ * row (the peer id bound to the row's single-use `StampId` nonce). It says
150
+ * nothing about whether that owner key is itself trustworthy — the caller must
151
+ * separately check the key against the node-local trusted-owner anchor
152
+ * (`TrustedOwnerStore`), never the replicated `OwnerKey` table.
153
+ *
154
+ * Returns a boolean and never throws (same contract as
155
+ * {@link verifyPeerAuthorization}): malformed input or any crypto failure
156
+ * resolves to `false`, logged at debug.
157
+ */
158
+ export function verifyCadrePeerVoucher(peerId, stampId, ownerPublicKey, signature) {
159
+ try {
160
+ return verify(cadrePeerVoucherDigest(peerId, stampId), signature, ownerPublicKey, 'ed25519', 'base64url', 'base64url', 'base64url');
161
+ }
162
+ catch (error) {
163
+ log('verifyCadrePeerVoucher failed: %o', error);
164
+ return false;
165
+ }
166
+ }
167
+ /**
168
+ * Canonical digest a JOINING peer signs to consent to ONE `FormationUsage`
169
+ * redemption — the read-side mirror of `formationConsentMessage` in
170
+ * control-database.ts, base64url-encoded instead of raw bytes (see
171
+ * {@link taggedDigest}). That doc comment carries the field-vector rationale
172
+ * (notably why `strandId` is not signed); the two vectors must not drift, which
173
+ * peer-authorization.spec.ts pins by signing one form and verifying the other.
174
+ */
175
+ export function formationConsentDigest(token, usageStampId, peerKey, disclosure) {
176
+ return taggedDigest('CadreControl.FormationUsage', 'consent', [token, usageStampId, peerKey, disclosure]);
177
+ }
178
+ /**
179
+ * Verify that `row.peerSig` is a valid ed25519 signature over the joining peer's
180
+ * consent digest (see {@link formationConsentDigest}) — the row's OWN `peerKey`.
181
+ *
182
+ * Unlike {@link verifyCadrePeerVoucher} there is no separate enrolled/owner row to
183
+ * look up: the identity IS the key carried on the row, so a forged consent would
184
+ * need that joiner's own private key. Returns a boolean and never throws (same
185
+ * contract as the siblings above): malformed input or any crypto failure resolves
186
+ * to `false`, logged at debug.
187
+ */
188
+ export function verifyFormationConsent(row) {
189
+ try {
190
+ return verify(formationConsentDigest(row.token, row.usageStampId, row.peerKey, row.disclosure), row.peerSig, row.peerKey, 'ed25519', 'base64url', 'base64url', 'base64url');
191
+ }
192
+ catch (error) {
193
+ log('verifyFormationConsent failed: %o', error);
194
+ return false;
195
+ }
196
+ }
66
197
  //# sourceMappingURL=peer-authorization.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"peer-authorization.js","sourceRoot":"","sources":["../src/peer-authorization.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,mCAAmC,CAAC;AAEnE,MAAM,GAAG,GAAG,KAAK,CAAC,iCAAiC,CAAC,CAAC;AAErD;;;;;;;;;GASG;AACH,MAAM,UAAU,uBAAuB,CAAC,MAAc;IACpD,OAAO,MAAM,CAAC,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,WAAW,CAAW,CAAC;AAC3D,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,sBAAsB,CAAC,MAAc,EAAE,OAAe;IACpE,OAAO,MAAM,CAAC,CAAC,MAAM,EAAE,OAAO,CA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ACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,GAAG,CAAC,mCAAmC,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC"}
@@ -3,22 +3,26 @@
3
3
  * signs when publishing its own `CadrePeer` row and re-verifies when resolving
4
4
  * another peer's row.
5
5
  *
6
- * The signed payload is a single SHA-256 digest of a delimited string of the
7
- * authenticated fields. It is intentionally NOT JSON-canonicalized: a delimited
8
- * digest is trivially deterministic across node/browser/RN (plain string concat
9
- * + sha256, no key ordering) and — crucially — is reconstructable inside the
10
- * `CadrePeer.AuthorizedUpdate` SQL constraint from the row's own columns:
6
+ * The signed payload is a single SHA-256 digest over the shared domain-tagged
7
+ * field vector (see control-authorization.ts) — the crypto plugin's injective
8
+ * multi-field encoding, so no field split is ambiguous. It is intentionally NOT
9
+ * JSON-canonicalized (deterministic across node/browser/RN, no key ordering)
10
+ * and — crucially — is reconstructable inside the `CadrePeer.AuthorizedUpdate`
11
+ * SQL constraint from the row's own columns:
11
12
  *
12
- * digest(new.PeerId || '|' || new.Multiaddr || '|' || cast(new.UpdatedAt as text))
13
+ * digest('CadreControl.CadrePeer', 'publish',
14
+ * new.PeerId, new.Multiaddr, cast(new.UpdatedAt as text))
13
15
  *
14
16
  * Keep {@link peerRecordSignedPayload} and that constraint byte-for-byte in
15
- * sync. The `'|'` delimiter is safe: a base58btc PeerId, a multiaddr (which uses
16
- * `/`), and a base-10 integer never contain it.
17
+ * sync. The `'publish'` action tag marks this as a peer's SELF-signed record
18
+ * (signed with the peer's own key, not an owner key) and keeps it disjoint from
19
+ * every owner-signed digest.
17
20
  *
18
21
  * `publicKey` is deliberately excluded from the payload — it is the key the
19
22
  * signature is verified *with* (so a signature already commits to exactly one
20
23
  * key), and its binding to `peerId` is checked separately at resolve time.
21
24
  */
25
+ import type { Multiaddr } from '@multiformats/multiaddr';
22
26
  import type { PeerAddressRecord, PeerResolveTrustPolicy } from './types.js';
23
27
  /**
24
28
  * Default freshness ceiling for resolved peer-address records (15 minutes).
@@ -71,6 +75,15 @@ export declare function verifyPeerRecordSignature(record: PeerAddressRecord): bo
71
75
  export declare function isPeerRecordFresh(updatedAt: number, maxAgeMs: number, now: number): boolean;
72
76
  /** True if `addr` is a `/p2p-circuit` signaling/relay multiaddr. */
73
77
  export declare function isSignalingAddr(addr: string): boolean;
78
+ /**
79
+ * The peer id a multiaddr terminates in, or `null` when it names none.
80
+ *
81
+ * The LAST `/p2p/` component is the dial target: a circuit address
82
+ * (`…/p2p/<relay>/p2p-circuit/p2p/<target>`) names the relay first and the peer
83
+ * being reached last. Replaces the deprecated `Multiaddr.getPeerId()`, which
84
+ * cannot express that distinction.
85
+ */
86
+ export declare function trailingPeerId(addr: Multiaddr): string | null;
74
87
  /**
75
88
  * Return `addrs` with signaling (`/p2p-circuit`) addrs first, otherwise stable.
76
89
  * Used to present the WebRTC dial input ahead of direct addrs. Does NOT mutate
@@ -3,23 +3,27 @@
3
3
  * signs when publishing its own `CadrePeer` row and re-verifies when resolving
4
4
  * another peer's row.
5
5
  *
6
- * The signed payload is a single SHA-256 digest of a delimited string of the
7
- * authenticated fields. It is intentionally NOT JSON-canonicalized: a delimited
8
- * digest is trivially deterministic across node/browser/RN (plain string concat
9
- * + sha256, no key ordering) and — crucially — is reconstructable inside the
10
- * `CadrePeer.AuthorizedUpdate` SQL constraint from the row's own columns:
6
+ * The signed payload is a single SHA-256 digest over the shared domain-tagged
7
+ * field vector (see control-authorization.ts) — the crypto plugin's injective
8
+ * multi-field encoding, so no field split is ambiguous. It is intentionally NOT
9
+ * JSON-canonicalized (deterministic across node/browser/RN, no key ordering)
10
+ * and — crucially — is reconstructable inside the `CadrePeer.AuthorizedUpdate`
11
+ * SQL constraint from the row's own columns:
11
12
  *
12
- * digest(new.PeerId || '|' || new.Multiaddr || '|' || cast(new.UpdatedAt as text))
13
+ * digest('CadreControl.CadrePeer', 'publish',
14
+ * new.PeerId, new.Multiaddr, cast(new.UpdatedAt as text))
13
15
  *
14
16
  * Keep {@link peerRecordSignedPayload} and that constraint byte-for-byte in
15
- * sync. The `'|'` delimiter is safe: a base58btc PeerId, a multiaddr (which uses
16
- * `/`), and a base-10 integer never contain it.
17
+ * sync. The `'publish'` action tag marks this as a peer's SELF-signed record
18
+ * (signed with the peer's own key, not an owner key) and keeps it disjoint from
19
+ * every owner-signed digest.
17
20
  *
18
21
  * `publicKey` is deliberately excluded from the payload — it is the key the
19
22
  * signature is verified *with* (so a signature already commits to exactly one
20
23
  * key), and its binding to `peerId` is checked separately at resolve time.
21
24
  */
22
25
  import { digest, sign, verify } from '@optimystic/quereus-plugin-crypto';
26
+ import { controlAuthorizationFields } from './control-authorization.js';
23
27
  /**
24
28
  * Default freshness ceiling for resolved peer-address records (15 minutes).
25
29
  * A record older than this is treated as stale and filtered out, so a resolver
@@ -45,8 +49,8 @@ const SIGNALING_PREFIX = '/p2p-circuit';
45
49
  * @param updatedAt - epoch-ms freshness stamp
46
50
  */
47
51
  export function peerRecordSignedPayload(peerId, multiaddr, updatedAt) {
48
- const joined = `${peerId}|${multiaddr}|${updatedAt}`;
49
- return digest([joined], 'sha256', 'base64url');
52
+ const fields = controlAuthorizationFields('CadreControl.CadrePeer', 'publish', [peerId, multiaddr, String(updatedAt)]);
53
+ return digest(fields, 'sha256', 'base64url');
50
54
  }
51
55
  /**
52
56
  * Sign a peer-address record with the ed25519 private key behind its `peerId`.
@@ -88,6 +92,18 @@ export function isPeerRecordFresh(updatedAt, maxAgeMs, now) {
88
92
  export function isSignalingAddr(addr) {
89
93
  return addr.includes(SIGNALING_PREFIX);
90
94
  }
95
+ /**
96
+ * The peer id a multiaddr terminates in, or `null` when it names none.
97
+ *
98
+ * The LAST `/p2p/` component is the dial target: a circuit address
99
+ * (`…/p2p/<relay>/p2p-circuit/p2p/<target>`) names the relay first and the peer
100
+ * being reached last. Replaces the deprecated `Multiaddr.getPeerId()`, which
101
+ * cannot express that distinction.
102
+ */
103
+ export function trailingPeerId(addr) {
104
+ const p2p = addr.getComponents().filter((c) => c.name === 'p2p');
105
+ return p2p.length > 0 ? (p2p[p2p.length - 1].value ?? null) : null;
106
+ }
91
107
  /**
92
108
  * Return `addrs` with signaling (`/p2p-circuit`) addrs first, otherwise stable.
93
109
  * Used to present the WebRTC dial input ahead of direct addrs. Does NOT mutate
@@ -1 +1 @@
1
- {"version":3,"file":"peer-record.js","sourceRoot":"","sources":["../src/peer-record.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,mCAAmC,CAAC;AAGzE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7D;;;GAGG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,8BAA8B,GAAG,CAAC,CAAC;AAEnF,+EAA+E;AAC/E,MAAM,gBAAgB,GAAG,cAAc,CAAC;AAExC;;;;;;;;;GASG;AACH,MAAM,UAAU,uBAAuB,CAAC,MAAc,EAAE,SAAiB,EAAE,SAAiB;IAC1F,MAAM,MAAM,GAAG,GAAG,MAAM,IAAI,SAAS,IAAI,SAAS,EAAE,CAAC;IACrD,OAAO,MAAM,CAAC,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,WAAW,CAAW,CAAC;AAC3D,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,cAAc,CAC5B,MAAiF,EACjF,aAAqB;IAErB,MAAM,aAAa,GAAG,uBAAuB,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC;IACvG,MAAM,GAAG,GAAG,IAAI,CACd,aAAa,EACb,aAAa,EACb,SAAS,EACT,WAAW,EACX,WAAW,EACX,WAAW,CACF,CAAC;IACZ,OAAO,EAAE,MAAM,EAAE,M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AAK,KAAK,CAAC,CAAC;IACjE,OAAO,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACrE,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAe;IACjD,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC;IAChD,MAAM,IAAI,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC;IACpD,OAAO,CAAC,GAAG,SAAS,EAAE,GAAG,IAAI,CAAC,CAAC;AACjC,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,wBAAwB;IACtC,OAAO;QACL,QAAQ;YACN,OAAO,IAAI,CAAC;QACd,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Translate `network.relayAddrs` — the operator-facing "use these relay servers"
3
+ * setting — into the mechanism this repo already has for reserving a circuit-relay
4
+ * slot: a `…/p2p/<relayPeerId>/p2p-circuit` entry in the node's listen addrs.
5
+ *
6
+ * `@libp2p/circuit-relay-v2`'s transport is always present on the Node path
7
+ * (`../optimystic/packages/db-p2p/src/libp2p-node.ts` pushes `circuitRelayTransport()`
8
+ * unconditionally), and listening on a relay's circuit addr is what makes libp2p dial
9
+ * that relay and hold a reservation. Everything downstream of the listen list —
10
+ * the reservation itself, `CadreNode.circuitRelayTargets()` picking delegate-announce
11
+ * targets, strand nodes inheriting the listen addrs, the `/p2p-circuit`-first address
12
+ * publishing in `registerSelf` — then works unchanged.
13
+ *
14
+ * So `relayAddrs` is a second, friendlier door onto an existing mechanism:
15
+ *
16
+ * effective listen addrs = listenAddrs ++ relayAddrs.map(a => a + '/p2p-circuit')
17
+ *
18
+ * NOTE: this is the FAIL-FAST route to a reservation — libp2p's transport manager
19
+ * throws when a configured circuit listener cannot listen, so naming a relay that
20
+ * is down means the node does not start. The fail-soft route is the bare
21
+ * `/p2p-circuit` search listener driven by `relay-reservation.ts`. The two are
22
+ * ALTERNATIVES, not layers: configuring `relayAddrs` on a node that already
23
+ * reserves via the search listener adds the fatal listener back and the node
24
+ * stops booting when its relay is down.
25
+ */
26
+ import type { NetworkConfig } from './types.js';
27
+ /**
28
+ * The circuit-listen multiaddr for each configured relay: `<relayAddr>/p2p-circuit`.
29
+ * An entry that already carries `/p2p-circuit` is passed through unchanged.
30
+ * Throws on an entry that is unparsable or names no relay peerId — this is
31
+ * operator configuration, so a typo must fail loudly at start rather than
32
+ * silently costing the node its reachability.
33
+ *
34
+ * Deliberately unlike `extractCircuitRelayTargets` (`delegate-admission.ts`), which
35
+ * SKIPS a bad entry: that one reads addresses discovered at runtime from peers, where
36
+ * one bad entry must not be fatal.
37
+ */
38
+ export declare function relayCircuitAddrs(relayAddrs: readonly string[]): string[];
39
+ /**
40
+ * The listen multiaddrs a node actually binds: configured `listenAddrs` plus the
41
+ * circuit-listen addr of every configured relay, deduplicated, order-stable
42
+ * (configured entries first). Returns `undefined` when neither field is set, so
43
+ * callers keep omitting `listenAddrs` and inherit db-p2p's default.
44
+ */
45
+ export declare function resolveListenAddrs(network: NetworkConfig | undefined): string[] | undefined;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Translate `network.relayAddrs` — the operator-facing "use these relay servers"
3
+ * setting — into the mechanism this repo already has for reserving a circuit-relay
4
+ * slot: a `…/p2p/<relayPeerId>/p2p-circuit` entry in the node's listen addrs.
5
+ *
6
+ * `@libp2p/circuit-relay-v2`'s transport is always present on the Node path
7
+ * (`../optimystic/packages/db-p2p/src/libp2p-node.ts` pushes `circuitRelayTransport()`
8
+ * unconditionally), and listening on a relay's circuit addr is what makes libp2p dial
9
+ * that relay and hold a reservation. Everything downstream of the listen list —
10
+ * the reservation itself, `CadreNode.circuitRelayTargets()` picking delegate-announce
11
+ * targets, strand nodes inheriting the listen addrs, the `/p2p-circuit`-first address
12
+ * publishing in `registerSelf` — then works unchanged.
13
+ *
14
+ * So `relayAddrs` is a second, friendlier door onto an existing mechanism:
15
+ *
16
+ * effective listen addrs = listenAddrs ++ relayAddrs.map(a => a + '/p2p-circuit')
17
+ *
18
+ * NOTE: this is the FAIL-FAST route to a reservation — libp2p's transport manager
19
+ * throws when a configured circuit listener cannot listen, so naming a relay that
20
+ * is down means the node does not start. The fail-soft route is the bare
21
+ * `/p2p-circuit` search listener driven by `relay-reservation.ts`. The two are
22
+ * ALTERNATIVES, not layers: configuring `relayAddrs` on a node that already
23
+ * reserves via the search listener adds the fatal listener back and the node
24
+ * stops booting when its relay is down.
25
+ */
26
+ import { multiaddr } from '@multiformats/multiaddr';
27
+ import { circuitRelayTargetOrThrow } from './delegate-admission.js';
28
+ /**
29
+ * The direct listener a node keeps when it configures `relayAddrs` but no
30
+ * `listenAddrs`. Without this, naming a relay would silently REPLACE the node's
31
+ * direct TCP listener with a circuit-only one.
32
+ *
33
+ * NOTE: mirrors `createLibp2pNode`'s own default listen addr in
34
+ * `../optimystic/packages/db-p2p/src/libp2p-node.ts` (`/ip4/0.0.0.0/tcp/<port>`,
35
+ * and `CadreNode` passes `port: 0`) — that file is the source of truth. If it
36
+ * ever changes its default, this constant has to follow.
37
+ */
38
+ const DEFAULT_DIRECT_LISTEN_ADDR = '/ip4/0.0.0.0/tcp/0';
39
+ /**
40
+ * The circuit-listen multiaddr for each configured relay: `<relayAddr>/p2p-circuit`.
41
+ * An entry that already carries `/p2p-circuit` is passed through unchanged.
42
+ * Throws on an entry that is unparsable or names no relay peerId — this is
43
+ * operator configuration, so a typo must fail loudly at start rather than
44
+ * silently costing the node its reachability.
45
+ *
46
+ * Deliberately unlike `extractCircuitRelayTargets` (`delegate-admission.ts`), which
47
+ * SKIPS a bad entry: that one reads addresses discovered at runtime from peers, where
48
+ * one bad entry must not be fatal.
49
+ */
50
+ export function relayCircuitAddrs(relayAddrs) {
51
+ return dedupe(relayAddrs.map(circuitListenAddr));
52
+ }
53
+ /**
54
+ * The listen multiaddrs a node actually binds: configured `listenAddrs` plus the
55
+ * circuit-listen addr of every configured relay, deduplicated, order-stable
56
+ * (configured entries first). Returns `undefined` when neither field is set, so
57
+ * callers keep omitting `listenAddrs` and inherit db-p2p's default.
58
+ */
59
+ export function resolveListenAddrs(network) {
60
+ const circuits = relayCircuitAddrs(network?.relayAddrs ?? []);
61
+ const listenAddrs = network?.listenAddrs;
62
+ if (!listenAddrs && circuits.length === 0) {
63
+ return undefined;
64
+ }
65
+ // An explicitly empty `listenAddrs` (the React Native "cannot listen" case) stays
66
+ // empty — but a relay named alongside it still gets its circuit listener, since
67
+ // acquiring one is the whole point of configuring a relay.
68
+ return dedupe([...(listenAddrs ?? [DEFAULT_DIRECT_LISTEN_ADDR]), ...circuits]);
69
+ }
70
+ /**
71
+ * One entry of {@link relayCircuitAddrs}: the addr the node listens on for this relay.
72
+ *
73
+ * NOTE: an entry carrying components AFTER `/p2p-circuit` — a full relayed DIAL addr,
74
+ * `…/p2p/<relay>/p2p-circuit/p2p/<someone else>` — is passed through as written and
75
+ * would be listened on verbatim. It validates (the relay it names is real), so only an
76
+ * operator who pastes a peer's relayed address into `relayAddrs` hits it; if that turns
77
+ * out to be a common paste, truncate at the `/p2p-circuit` component here.
78
+ */
79
+ function circuitListenAddr(relayAddr) {
80
+ const alreadyCircuit = parseComponents(relayAddr).some((c) => c.name === 'p2p-circuit');
81
+ const listenAddr = alreadyCircuit ? relayAddr : `${relayAddr}/p2p-circuit`;
82
+ try {
83
+ circuitRelayTargetOrThrow(listenAddr); // validates the relay peerId
84
+ }
85
+ catch (err) {
86
+ throw new Error(`network.relayAddrs entry names no relay peerId (expected <dial addr>/p2p/<relayPeerId>): ${relayAddr}`, { cause: err });
87
+ }
88
+ return listenAddr;
89
+ }
90
+ /** Multiaddr components of `relayAddr`, with the config field named on a parse failure. */
91
+ function parseComponents(relayAddr) {
92
+ try {
93
+ return multiaddr(relayAddr).getComponents();
94
+ }
95
+ catch (err) {
96
+ throw new Error(`network.relayAddrs entry is not a valid multiaddr: ${relayAddr}`, { cause: err });
97
+ }
98
+ }
99
+ /** Exact-string dedupe, first occurrence wins, so the list is stable across restarts. */
100
+ function dedupe(addrs) {
101
+ return [...new Set(addrs)];
102
+ }
103
+ //# sourceMappingURL=relay-addrs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relay-addrs.js","sourceRoot":"","sources":["../src/relay-addrs.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,EAAE,SAAS,EAAkB,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AAGpE;;;;;;;;;GASG;AACH,MAAM,0BAA0B,GAAG,oBAAoB,CAAC;AAExD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,iBAAiB,CAAC,UAA6B;IAC7D,OAAO,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAC;AACnD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAAkC;IACnE,MAAM,QAAQ,GAAG,iBAAiB,CAAC,OAAO,EAAE,UAAU,IAAI,EAAE,CAAC,CAAC;IAC9D,MAAM,WAAW,GAAG,OAAO,EAAE,WAAW,CAAC;IACzC,IAAI,CAAC,WAAW,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1C,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,kFAAkF;IAClF,gFAAgF;IAChF,2DAA2D;IAC3D,OAAO,MAAM,CAAC,CAAC,GAAG,CAAC,WAAW,IAAI,CAAC,0BAA0B,CAAC,CAAC,EAAE,GAAG,QAAQ,CAAC,CAAC,CAAC;AACjF,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,iBAAiB,C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