@private.me/xbind 3.0.1 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/README.md +55 -14
  2. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1920 -1
  3. package/dist-standalone/_deps/shared/cjs/errors.js +729 -1
  4. package/dist-standalone/_deps/shared/cjs/index.js +463 -1
  5. package/dist-standalone/_deps/shared/cjs/types.js +315 -1
  6. package/dist-standalone/_deps/shared/errors.js +244 -1
  7. package/dist-standalone/_deps/shared/index.js +72 -1
  8. package/dist-standalone/_deps/shared/types.js +86 -1
  9. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  10. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  20. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  21. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  28. package/dist-standalone/_deps/xchange/errors.js +1 -1
  29. package/dist-standalone/_deps/xchange/index.js +1 -1
  30. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  31. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  32. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  33. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  34. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  40. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  41. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  42. package/dist-standalone/_deps/xregistry/index.js +1 -1
  43. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  44. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  45. package/dist-standalone/_deps/xregistry/types.js +1 -1
  46. package/dist-standalone/agent-call.js +659 -1
  47. package/dist-standalone/agent-sdk.js +328 -1
  48. package/dist-standalone/agent.js +1800 -1
  49. package/dist-standalone/approval.js +193 -1
  50. package/dist-standalone/async-iterators.js +382 -1
  51. package/dist-standalone/auth.js +219 -1
  52. package/dist-standalone/auto-accept.js +229 -1
  53. package/dist-standalone/backup-config.js +201 -1
  54. package/dist-standalone/backup.js +326 -1
  55. package/dist-standalone/batch-operations.js +388 -1
  56. package/dist-standalone/cancellation.js +477 -1
  57. package/dist-standalone/checkpoint.js +186 -1
  58. package/dist-standalone/circuit-breaker.js +468 -1
  59. package/dist-standalone/cjs/agent-call.js +701 -1
  60. package/dist-standalone/cjs/agent-sdk.js +332 -1
  61. package/dist-standalone/cjs/agent.js +1837 -1
  62. package/dist-standalone/cjs/approval.js +199 -1
  63. package/dist-standalone/cjs/async-iterators.js +392 -1
  64. package/dist-standalone/cjs/auth.js +225 -1
  65. package/dist-standalone/cjs/auto-accept.js +233 -1
  66. package/dist-standalone/cjs/backup-config.js +207 -1
  67. package/dist-standalone/cjs/backup.js +330 -1
  68. package/dist-standalone/cjs/batch-operations.js +397 -1
  69. package/dist-standalone/cjs/cancellation.js +490 -1
  70. package/dist-standalone/cjs/checkpoint.js +193 -1
  71. package/dist-standalone/cjs/circuit-breaker.js +476 -1
  72. package/dist-standalone/cjs/cli/init.js +492 -1
  73. package/dist-standalone/cjs/config-validation.js +522 -1
  74. package/dist-standalone/cjs/connect.js +312 -1
  75. package/dist-standalone/cjs/connection-pool.js +506 -1
  76. package/dist-standalone/cjs/correlation-id.js +339 -1
  77. package/dist-standalone/cjs/crypto-utils.js +176 -1
  78. package/dist-standalone/cjs/debug-mode.js +534 -1
  79. package/dist-standalone/cjs/did-document.js +101 -1
  80. package/dist-standalone/cjs/did-privateme.js +130 -1
  81. package/dist-standalone/cjs/did-web.js +201 -1
  82. package/dist-standalone/cjs/discovery.js +462 -1
  83. package/dist-standalone/cjs/dual-mode.js +251 -1
  84. package/dist-standalone/cjs/email-templates.js +313 -1
  85. package/dist-standalone/cjs/email-transport.js +239 -1
  86. package/dist-standalone/cjs/envelope.js +538 -1
  87. package/dist-standalone/cjs/errors.js +913 -1
  88. package/dist-standalone/cjs/event-emitter.js +461 -1
  89. package/dist-standalone/cjs/gateway-state.js +55 -1
  90. package/dist-standalone/cjs/gateway-transport.js +120 -1
  91. package/dist-standalone/cjs/graceful-degradation.js +403 -1
  92. package/dist-standalone/cjs/guardrails.js +223 -1
  93. package/dist-standalone/cjs/health-check.js +336 -1
  94. package/dist-standalone/cjs/http-compat.js +272 -1
  95. package/dist-standalone/cjs/http-status-map.js +571 -1
  96. package/dist-standalone/cjs/identity.js +645 -1
  97. package/dist-standalone/cjs/index.js +406 -1
  98. package/dist-standalone/cjs/invitation.js +421 -1
  99. package/dist-standalone/cjs/invite.js +328 -1
  100. package/dist-standalone/cjs/key-agreement.js +335 -1
  101. package/dist-standalone/cjs/lazy-init.js +300 -1
  102. package/dist-standalone/cjs/logger.js +291 -1
  103. package/dist-standalone/cjs/mdns-discovery.js +202 -1
  104. package/dist-standalone/cjs/nonce-store.js +80 -1
  105. package/dist-standalone/cjs/pairing-manager.js +223 -1
  106. package/dist-standalone/cjs/plugin-system.js +264 -1
  107. package/dist-standalone/cjs/plugins/logging.js +168 -1
  108. package/dist-standalone/cjs/plugins/metrics.js +181 -1
  109. package/dist-standalone/cjs/plugins/validation.js +302 -1
  110. package/dist-standalone/cjs/policy.js +320 -1
  111. package/dist-standalone/cjs/progress-callbacks.js +583 -1
  112. package/dist-standalone/cjs/redis-nonce-store.js +76 -1
  113. package/dist-standalone/cjs/registry-middleware.js +50 -1
  114. package/dist-standalone/cjs/retry-strategies.js +544 -1
  115. package/dist-standalone/cjs/retry-transport.js +102 -1
  116. package/dist-standalone/cjs/runtime/browser.js +533 -1
  117. package/dist-standalone/cjs/runtime/edge.js +526 -1
  118. package/dist-standalone/cjs/runtime/react-native.js +394 -1
  119. package/dist-standalone/cjs/security-policy.js +245 -1
  120. package/dist-standalone/cjs/serialization.js +1040 -1
  121. package/dist-standalone/cjs/split-channel.js +225 -1
  122. package/dist-standalone/cjs/subscription-proof.js +230 -1
  123. package/dist-standalone/cjs/succession.js +148 -1
  124. package/dist-standalone/cjs/timeouts.js +412 -1
  125. package/dist-standalone/cjs/trace-context.js +424 -1
  126. package/dist-standalone/cjs/trace-spans.js +495 -1
  127. package/dist-standalone/cjs/transport.js +63 -1
  128. package/dist-standalone/cjs/trust-registry.js +991 -1
  129. package/dist-standalone/cjs/types/error-response.js +56 -1
  130. package/dist-standalone/cjs/vault-auth.js +178 -1
  131. package/dist-standalone/cjs/vault-store-loader.js +194 -1
  132. package/dist-standalone/cjs/verify.js +25 -1
  133. package/dist-standalone/cjs/version-info.js +543 -1
  134. package/dist-standalone/cjs/xfetch.js +340 -1
  135. package/dist-standalone/cli/init.js +455 -1
  136. package/dist-standalone/cli/setup.js +514 -1
  137. package/dist-standalone/cli/types.js +27 -1
  138. package/dist-standalone/cli/xbind.js +148 -1
  139. package/dist-standalone/config-validation.js +513 -1
  140. package/dist-standalone/connect.js +274 -1
  141. package/dist-standalone/connection-pool.js +500 -1
  142. package/dist-standalone/correlation-id.js +326 -1
  143. package/dist-standalone/crypto-utils.js +157 -1
  144. package/dist-standalone/debug-mode.js +510 -1
  145. package/dist-standalone/did-document.js +96 -1
  146. package/dist-standalone/did-privateme.js +121 -1
  147. package/dist-standalone/did-web.js +196 -1
  148. package/dist-standalone/discovery.js +458 -1
  149. package/dist-standalone/dual-mode.js +247 -1
  150. package/dist-standalone/email-templates.js +309 -1
  151. package/dist-standalone/email-transport.js +232 -1
  152. package/dist-standalone/envelope.js +525 -1
  153. package/dist-standalone/errors.js +896 -1
  154. package/dist-standalone/event-emitter.js +456 -1
  155. package/dist-standalone/gateway-state.js +51 -1
  156. package/dist-standalone/gateway-transport.js +116 -1
  157. package/dist-standalone/graceful-degradation.js +396 -1
  158. package/dist-standalone/guardrails.js +216 -1
  159. package/dist-standalone/health-check.js +332 -1
  160. package/dist-standalone/http-compat.js +267 -1
  161. package/dist-standalone/http-status-map.js +561 -1
  162. package/dist-standalone/identity.js +619 -1
  163. package/dist-standalone/index.js +78 -1
  164. package/dist-standalone/invitation.js +415 -1
  165. package/dist-standalone/invite.js +324 -1
  166. package/dist-standalone/key-agreement.js +325 -1
  167. package/dist-standalone/lazy-init.js +295 -1
  168. package/dist-standalone/logger.js +285 -1
  169. package/dist-standalone/mdns-discovery.js +195 -1
  170. package/dist-standalone/nonce-store.js +76 -1
  171. package/dist-standalone/pairing-manager.js +219 -1
  172. package/dist-standalone/plugin-system.js +257 -1
  173. package/dist-standalone/plugins/logging.js +163 -1
  174. package/dist-standalone/plugins/metrics.js +176 -1
  175. package/dist-standalone/plugins/validation.js +297 -1
  176. package/dist-standalone/policy.js +315 -1
  177. package/dist-standalone/progress-callbacks.js +576 -1
  178. package/dist-standalone/redis-nonce-store.js +72 -1
  179. package/dist-standalone/registry-middleware.js +47 -1
  180. package/dist-standalone/retry-strategies.js +534 -1
  181. package/dist-standalone/retry-transport.js +98 -1
  182. package/dist-standalone/runtime/browser.js +516 -1
  183. package/dist-standalone/runtime/edge.js +511 -1
  184. package/dist-standalone/runtime/react-native.js +383 -1
  185. package/dist-standalone/security-policy.js +239 -1
  186. package/dist-standalone/serialization.js +1031 -1
  187. package/dist-standalone/split-channel.js +219 -1
  188. package/dist-standalone/subscription-proof.js +224 -1
  189. package/dist-standalone/succession.js +142 -1
  190. package/dist-standalone/timeouts.js +398 -1
  191. package/dist-standalone/trace-context.js +414 -1
  192. package/dist-standalone/trace-spans.js +488 -1
  193. package/dist-standalone/transport.js +59 -1
  194. package/dist-standalone/trust-registry.js +950 -1
  195. package/dist-standalone/types/error-response.js +52 -1
  196. package/dist-standalone/vault-auth.js +174 -1
  197. package/dist-standalone/vault-store-loader.js +187 -1
  198. package/dist-standalone/verify.js +16 -1
  199. package/dist-standalone/version-info.js +530 -1
  200. package/dist-standalone/xfetch.js +335 -1
  201. package/package.json +4 -13
  202. package/share1.dat +0 -0
  203. package/dist-standalone/_deps/mldsa-wasm/LICENSE +0 -24
  204. package/dist-standalone/_deps/mldsa-wasm/package.json +0 -46
  205. package/dist-standalone/_deps/shared/cjs/package.json +0 -1
  206. package/dist-standalone/_deps/ux-helpers/cjs/package.json +0 -1
  207. package/dist-standalone/_deps/xchange/cjs/package.json +0 -1
  208. package/dist-standalone/_deps/xregistry/cjs/package.json +0 -1
  209. package/dist-standalone/cjs/package.json +0 -3
  210. package/dist-standalone/package.json +0 -10
@@ -1 +1,195 @@
1
- import Bonjour from"bonjour-service";import{ok,err}from"./_deps/shared/index.js";export var DiscoveryErrorCode;!function(e){e.NETWORK_ERROR="NETWORK_ERROR",e.TIMEOUT="TIMEOUT",e.NO_SERVICES="NO_SERVICES",e.INVALID_SERVICE="INVALID_SERVICE"}(DiscoveryErrorCode||(DiscoveryErrorCode={}));export class MdnsDiscoveryManager{bonjour;service=null;serviceType="privateme";protocol="tcp";port=58472;constructor(){this.bonjour=new Bonjour}advertise(e,o,r=this.port){this.service&&this.service.stop?.(),this.service=this.bonjour.publish({name:e,type:this.serviceType,protocol:this.protocol,port:r,txt:{did:o,endpoint:`http://localhost:${r}`,name:e}})}async scan(e,o=5e3){return new Promise(r=>{const t=new Map;let s=!1;const i=this.bonjour.find({type:this.serviceType,protocol:this.protocol});i.on("up",o=>{try{const r=o.txt;if(!r||!r.did||!r.name)return;if(r.did===e)return;const s=r.endpoint||`http://${o.host||"localhost"}:${o.port}`,i=(o.addresses||[]).filter(e=>e.includes(".")&&!e.includes(":")),n={name:r.name,did:r.did,endpoint:s,addresses:i,port:o.port||this.port};t.set(r.did,n)}catch(e){}});const n=setTimeout(()=>{s||(s=!0,i.stop(),0===t.size?r(err({code:DiscoveryErrorCode.NO_SERVICES,message:"No devices found on local network",hint:"Ensure both devices are on the same Wi-Fi network"})):r(ok(Array.from(t.values()))))},o);i.on("error",e=>{s||(s=!0,clearTimeout(n),i.stop(),r(err({code:DiscoveryErrorCode.NETWORK_ERROR,message:e.message,hint:"Check firewall settings and network connectivity"})))})})}stopAdvertising(){this.service&&(this.service.stop?.(),this.service=null)}destroy(){this.stopAdvertising(),this.bonjour.destroy()}}
1
+ /**
2
+ * @module mdns-discovery
3
+ * mDNS service discovery for local network device pairing.
4
+ *
5
+ * Service Type: _privateme._tcp.local (RFC 6763 compliant)
6
+ * Port: 58472 (dynamic range 58000-58999)
7
+ * TXT Record: did=z6Mk..., endpoint=http://192.168.1.5:58472, name=Desktop
8
+ *
9
+ * Security properties:
10
+ * - Physical proximity required (same LAN)
11
+ * - User confirmation on both devices
12
+ * - Nonce-based challenge-response
13
+ * - 60-second timeout
14
+ * - Gold Standard compliant (GS-CONNECT requirement #26)
15
+ */
16
+ import Bonjour from 'bonjour-service';
17
+ import { ok, err } from"./_deps/shared/index.js";
18
+ /**
19
+ * Discovery error types.
20
+ */
21
+ export var DiscoveryErrorCode;
22
+ (function (DiscoveryErrorCode) {
23
+ DiscoveryErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR";
24
+ DiscoveryErrorCode["TIMEOUT"] = "TIMEOUT";
25
+ DiscoveryErrorCode["NO_SERVICES"] = "NO_SERVICES";
26
+ DiscoveryErrorCode["INVALID_SERVICE"] = "INVALID_SERVICE";
27
+ })(DiscoveryErrorCode || (DiscoveryErrorCode = {}));
28
+ /**
29
+ * mDNS discovery manager.
30
+ *
31
+ * Advertises service on local network and scans for other devices.
32
+ * Uses bonjour-service library (RFC 6763/6762 compliant).
33
+ */
34
+ export class MdnsDiscoveryManager {
35
+ bonjour;
36
+ service = null;
37
+ serviceType = 'privateme';
38
+ protocol = 'tcp';
39
+ port = 58472;
40
+ constructor() {
41
+ this.bonjour = new Bonjour();
42
+ }
43
+ /**
44
+ * Advertise service on local network.
45
+ *
46
+ * Broadcasts mDNS announcement with device DID and HTTP endpoint.
47
+ * Other devices on the same LAN can discover this service via scan().
48
+ *
49
+ * @param name - Device name (e.g., "Desktop", "MacBook Pro")
50
+ * @param did - Device DID
51
+ * @param port - Local HTTP server port (default: 58472)
52
+ *
53
+ * @example
54
+ * ```typescript
55
+ * const manager = new MdnsDiscoveryManager();
56
+ * manager.advertise('Desktop', 'did:key:z6Mk...', 58472);
57
+ * // Service now visible to other devices on LAN
58
+ * ```
59
+ */
60
+ advertise(name, did, port = this.port) {
61
+ // Stop existing advertisement
62
+ if (this.service) {
63
+ this.service.stop?.();
64
+ }
65
+ // Publish service
66
+ this.service = this.bonjour.publish({
67
+ name,
68
+ type: this.serviceType,
69
+ protocol: this.protocol,
70
+ port,
71
+ txt: {
72
+ did,
73
+ endpoint: `http://localhost:${port}`, // Will be replaced with actual IP by Bonjour
74
+ name,
75
+ },
76
+ });
77
+ }
78
+ /**
79
+ * Scan local network for services.
80
+ *
81
+ * Discovers all Private.Me devices on the same LAN.
82
+ * Filters out own DID from results (can't pair with self).
83
+ *
84
+ * @param ownDid - Own device DID (to filter out)
85
+ * @param timeoutMs - Scan timeout in milliseconds (default: 5000ms)
86
+ * @returns Array of discovered services
87
+ *
88
+ * @example
89
+ * ```typescript
90
+ * const manager = new MdnsDiscoveryManager();
91
+ * const result = await manager.scan('did:key:z6Mk...myDid', 5000);
92
+ * if (result.ok) {
93
+ * console.log(`Found ${result.value.length} devices`);
94
+ * for (const service of result.value) {
95
+ * console.log(`${service.name} - ${service.did}`);
96
+ * }
97
+ * }
98
+ * ```
99
+ */
100
+ async scan(ownDid, timeoutMs = 5000) {
101
+ return new Promise((resolve) => {
102
+ const discovered = new Map();
103
+ let resolved = false;
104
+ // Browse for services
105
+ const browser = this.bonjour.find({
106
+ type: this.serviceType,
107
+ protocol: this.protocol,
108
+ });
109
+ // Handle service discovery
110
+ browser.on('up', (service) => {
111
+ try {
112
+ // Parse TXT record
113
+ const txt = service.txt;
114
+ if (!txt || !txt.did || !txt.name) {
115
+ return; // Invalid service - missing required fields
116
+ }
117
+ // Filter out own DID
118
+ if (txt.did === ownDid) {
119
+ return;
120
+ }
121
+ // Extract endpoint
122
+ const endpoint = txt.endpoint || `http://${service.host || 'localhost'}:${service.port}`;
123
+ // Extract addresses (filter IPv4 only)
124
+ const addresses = (service.addresses || []).filter((addr) => {
125
+ // Simple IPv4 check (contains dots, not colons)
126
+ return addr.includes('.') && !addr.includes(':');
127
+ });
128
+ const info = {
129
+ name: txt.name,
130
+ did: txt.did,
131
+ endpoint,
132
+ addresses,
133
+ port: service.port || this.port,
134
+ };
135
+ discovered.set(txt.did, info);
136
+ }
137
+ catch (error) {
138
+ // Ignore invalid service
139
+ }
140
+ });
141
+ // Timeout after specified duration
142
+ const timeoutId = setTimeout(() => {
143
+ if (resolved)
144
+ return;
145
+ resolved = true;
146
+ browser.stop();
147
+ if (discovered.size === 0) {
148
+ resolve(err({
149
+ code: DiscoveryErrorCode.NO_SERVICES,
150
+ message: 'No devices found on local network',
151
+ hint: 'Ensure both devices are on the same Wi-Fi network',
152
+ }));
153
+ }
154
+ else {
155
+ resolve(ok(Array.from(discovered.values())));
156
+ }
157
+ }, timeoutMs);
158
+ // Allow cleanup if promise resolves early
159
+ browser.on('error', (error) => {
160
+ if (resolved)
161
+ return;
162
+ resolved = true;
163
+ clearTimeout(timeoutId);
164
+ browser.stop();
165
+ resolve(err({
166
+ code: DiscoveryErrorCode.NETWORK_ERROR,
167
+ message: error.message,
168
+ hint: 'Check firewall settings and network connectivity',
169
+ }));
170
+ });
171
+ });
172
+ }
173
+ /**
174
+ * Stop advertising service.
175
+ *
176
+ * Removes mDNS announcement from local network.
177
+ * Other devices will no longer see this service.
178
+ */
179
+ stopAdvertising() {
180
+ if (this.service) {
181
+ this.service.stop?.();
182
+ this.service = null;
183
+ }
184
+ }
185
+ /**
186
+ * Release resources.
187
+ *
188
+ * Stops advertising and cleans up Bonjour instance.
189
+ * Call this when shutting down the application.
190
+ */
191
+ destroy() {
192
+ this.stopAdvertising();
193
+ this.bonjour.destroy();
194
+ }
195
+ }
@@ -1 +1,76 @@
1
- const DEFAULT_TTL_MS=6e5,DEFAULT_CLEANUP_INTERVAL_MS=6e4;export class MemoryNonceStore{seen=new Map;ttlMs;cleanupIntervalMs;timer=null;constructor(e){this.ttlMs=e?.ttlMs??6e5,this.cleanupIntervalMs=e?.cleanupIntervalMs??6e4}ensureTimer(){if(null!==this.timer)return;const e=setInterval(()=>this.cleanup(),this.cleanupIntervalMs);"object"==typeof e&&"unref"in e&&e.unref(),this.timer=e}buildKey(e,t,s){if(null==s)return`${t}:${e}`;return`${t}:${e}:${"string"==typeof s.shareGroupId?s.shareGroupId:""}:${"number"==typeof s.shareIndex?String(s.shareIndex):""}`}async check(e,t,s){this.ensureTimer();const n=this.buildKey(e,t,s),r=this.seen.get(n),i=Date.now();return!(void 0!==r&&r>i)&&(this.seen.set(n,i+this.ttlMs),!0)}cleanup(){const e=Date.now(),t=Array.from(this.seen.keys());for(const s of t){const t=this.seen.get(s);void 0!==t&&t<=e&&this.seen.delete(s)}}dispose(){null!==this.timer&&(clearInterval(this.timer),this.timer=null),this.seen.clear()}get size(){return this.seen.size}}
1
+ /* ── NonceStore Replay Prevention ── */
2
+ /** Default TTL for nonce entries: 10 minutes. */
3
+ const DEFAULT_TTL_MS = 10 * 60 * 1000;
4
+ /** Default cleanup interval: 60 seconds. */
5
+ const DEFAULT_CLEANUP_INTERVAL_MS = 60 * 1000;
6
+ /**
7
+ * In-memory nonce store for development and single-process deployments.
8
+ *
9
+ * Stores nonces in a Map keyed by "senderDid:nonce:shareContext" with expiry timestamps.
10
+ * Supports share-aware deduplication: same nonce + different shares = allowed (idempotent retry),
11
+ * same nonce + same share = blocked (true replay).
12
+ * Periodic cleanup removes expired entries to prevent unbounded growth.
13
+ */
14
+ export class MemoryNonceStore {
15
+ seen = new Map();
16
+ ttlMs;
17
+ cleanupIntervalMs;
18
+ timer = null;
19
+ constructor(opts) {
20
+ this.ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;
21
+ this.cleanupIntervalMs = opts?.cleanupIntervalMs ?? DEFAULT_CLEANUP_INTERVAL_MS;
22
+ // Timer starts lazily on first check() to avoid blocking process exit in tests
23
+ }
24
+ /** Start cleanup timer on first use. */
25
+ ensureTimer() {
26
+ if (this.timer !== null)
27
+ return;
28
+ const t = setInterval(() => this.cleanup(), this.cleanupIntervalMs);
29
+ // Unref so the timer doesn't block Node.js process exit
30
+ if (typeof t === 'object' && 'unref' in t) {
31
+ t.unref(); // SAFETY: runtime check guards access
32
+ }
33
+ this.timer = t;
34
+ }
35
+ /** Build composite key: senderDid:nonce:shareGroupId:shareIndex */
36
+ buildKey(nonce, senderDid, shareContext) {
37
+ if (shareContext === undefined || shareContext === null) {
38
+ return `${senderDid}:${nonce}`;
39
+ }
40
+ const groupId = typeof shareContext.shareGroupId === 'string' ? shareContext.shareGroupId : '';
41
+ const index = typeof shareContext.shareIndex === 'number' ? String(shareContext.shareIndex) : '';
42
+ return `${senderDid}:${nonce}:${groupId}:${index}`;
43
+ }
44
+ async check(nonce, senderDid, shareContext) {
45
+ this.ensureTimer();
46
+ const key = this.buildKey(nonce, senderDid, shareContext);
47
+ const existing = this.seen.get(key);
48
+ const now = Date.now();
49
+ if (existing !== undefined && existing > now) {
50
+ return false;
51
+ }
52
+ this.seen.set(key, now + this.ttlMs);
53
+ return true;
54
+ }
55
+ cleanup() {
56
+ const now = Date.now();
57
+ const keys = Array.from(this.seen.keys());
58
+ for (const key of keys) {
59
+ const expiry = this.seen.get(key);
60
+ if (expiry !== undefined && expiry <= now) {
61
+ this.seen.delete(key);
62
+ }
63
+ }
64
+ }
65
+ dispose() {
66
+ if (this.timer !== null) {
67
+ clearInterval(this.timer);
68
+ this.timer = null;
69
+ }
70
+ this.seen.clear();
71
+ }
72
+ /** Number of active (non-expired) entries. Useful for testing. */
73
+ get size() {
74
+ return this.seen.size;
75
+ }
76
+ }
@@ -1 +1,219 @@
1
- import{ok,err}from"./_deps/shared/index.js";export class PairingManager{pendingNonces=new Map;registry;deviceDid;constructor(e,r){this.deviceDid=e,this.registry=r,setInterval(()=>{const e=Date.now();for(const[r,i]of this.pendingNonces.entries())e-i>6e4&&this.pendingNonces.delete(r)},1e4)}createRequest(){const e=new Uint8Array(16);if(void 0!==globalThis.crypto&&globalThis.crypto.getRandomValues)globalThis.crypto.getRandomValues(e);else{require("node:crypto").getRandomValues(e)}const r=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""),i=Date.now();return this.pendingNonces.set(r,i),{device_a_did:this.deviceDid,nonce:r,timestamp:i}}validateRequest(e){const r=Date.now()-e.timestamp;return r>6e4?err(`Request expired (${Math.floor(r/1e3)}s old, max 60s)`):r<0?err("Request timestamp in the future (clock skew detected)"):e.device_a_did&&e.nonce&&e.timestamp?ok(void 0):err("Missing required fields (device_a_did, nonce, timestamp)")}async acceptPairing(e,r){const i=this.validateRequest(e);if(!i.ok)return err(i.error);const t=await r();if(t){const r=await this.registry.register(e.device_a_did,new Uint8Array(32),"Paired Device",["pairing"]);if(!r.ok){const e="string"==typeof r.error?r.error:"Unknown error";return err(`Failed to register pairing: ${e}`)}}return ok({device_b_did:this.deviceDid,accepted:t,nonce:e.nonce})}async finalizePairing(e,r){if(e.nonce!==r)return err("Nonce mismatch (possible MITM attack)");if(!e.accepted)return err("Pairing rejected by remote device");this.pendingNonces.delete(r);const i=await this.registry.register(e.device_b_did,new Uint8Array(32),"Paired Device",["pairing"]);if(!i.ok){const e="string"==typeof i.error?i.error:"Unknown error";return err(`Failed to register pairing: ${e}`)}return ok(void 0)}getPendingNonceCount(){return this.pendingNonces.size}}
1
+ /**
2
+ * @module pairing-manager
3
+ * Security validation for peer-to-peer device pairing via mDNS.
4
+ *
5
+ * Security properties:
6
+ * - 16-byte cryptographically secure nonce (prevents replay attacks)
7
+ * - 60-second timeout (limits attack window)
8
+ * - User confirmation required on BOTH devices
9
+ * - Nonce echo in response (prevents MITM substitution)
10
+ * - Trust registry integration (stores paired DIDs with scopes)
11
+ * - Gold Standard compliant (GS-CONNECT requirement #26, GS-SEC-RNG compliant)
12
+ */
13
+ import { ok, err } from"./_deps/shared/index.js";
14
+ /**
15
+ * Pairing manager for secure peer-to-peer device pairing.
16
+ *
17
+ * Implements challenge-response protocol with user confirmation.
18
+ * Integrates with trust registry for persistent pairing storage.
19
+ */
20
+ export class PairingManager {
21
+ pendingNonces = new Map(); // nonce → timestamp
22
+ registry;
23
+ deviceDid;
24
+ /**
25
+ * Create pairing manager.
26
+ *
27
+ * @param deviceDid - DID of this device
28
+ * @param registry - Trust registry instance
29
+ */
30
+ constructor(deviceDid, registry) {
31
+ this.deviceDid = deviceDid;
32
+ this.registry = registry;
33
+ // Clean up expired nonces every 10 seconds
34
+ setInterval(() => {
35
+ const now = Date.now();
36
+ for (const [nonce, timestamp] of this.pendingNonces.entries()) {
37
+ if (now - timestamp > 60_000) {
38
+ this.pendingNonces.delete(nonce);
39
+ }
40
+ }
41
+ }, 10_000);
42
+ }
43
+ /**
44
+ * Create pairing request.
45
+ *
46
+ * Generates cryptographically secure nonce and stores it for validation.
47
+ * Device A calls this before sending request to Device B.
48
+ *
49
+ * @returns Pairing request to send to remote device
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * const manager = new PairingManager('did:key:z6MkA...', registry);
54
+ * const request = manager.createRequest();
55
+ * // Send request to Device B via HTTP POST
56
+ * const response = await fetch(`${deviceB.endpoint}/pair`, {
57
+ * method: 'POST',
58
+ * body: JSON.stringify(request),
59
+ * });
60
+ * ```
61
+ */
62
+ createRequest() {
63
+ // Generate cryptographically secure nonce (GS-SEC-RNG: NEVER use Math.random)
64
+ const nonceBytes = new Uint8Array(16);
65
+ if (typeof globalThis.crypto !== 'undefined' && globalThis.crypto.getRandomValues) {
66
+ globalThis.crypto.getRandomValues(nonceBytes);
67
+ }
68
+ else {
69
+ // Node.js environment
70
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
71
+ const crypto = require('node:crypto');
72
+ crypto.getRandomValues(nonceBytes);
73
+ }
74
+ const nonce = Array.from(nonceBytes)
75
+ .map((b) => b.toString(16).padStart(2, '0'))
76
+ .join('');
77
+ const timestamp = Date.now();
78
+ // Store nonce for validation (60-second TTL)
79
+ this.pendingNonces.set(nonce, timestamp);
80
+ return {
81
+ device_a_did: this.deviceDid,
82
+ nonce,
83
+ timestamp,
84
+ };
85
+ }
86
+ /**
87
+ * Validate pairing request.
88
+ *
89
+ * Checks timeout and nonce uniqueness.
90
+ * Device B calls this when receiving request from Device A.
91
+ *
92
+ * @param request - Pairing request from remote device
93
+ * @returns Ok if valid, Err with reason if invalid
94
+ *
95
+ * @example
96
+ * ```typescript
97
+ * // Device B receives request
98
+ * const validation = manager.validateRequest(request);
99
+ * if (!validation.ok) {
100
+ * return res.status(400).json({ error: validation.error });
101
+ * }
102
+ * ```
103
+ */
104
+ validateRequest(request) {
105
+ // Check timeout (60-second window)
106
+ const age = Date.now() - request.timestamp;
107
+ if (age > 60_000) {
108
+ return err(`Request expired (${Math.floor(age / 1000)}s old, max 60s)`);
109
+ }
110
+ if (age < 0) {
111
+ return err('Request timestamp in the future (clock skew detected)');
112
+ }
113
+ // Check required fields
114
+ if (!request.device_a_did || !request.nonce || !request.timestamp) {
115
+ return err('Missing required fields (device_a_did, nonce, timestamp)');
116
+ }
117
+ return ok(undefined);
118
+ }
119
+ /**
120
+ * Accept pairing request.
121
+ *
122
+ * Shows UI prompt for user confirmation, then stores in trust registry.
123
+ * Device B calls this after validating request.
124
+ *
125
+ * @param request - Validated pairing request
126
+ * @param promptCallback - Async function to show UI prompt (returns true if accepted)
127
+ * @returns Pairing response to send back to Device A
128
+ *
129
+ * @example
130
+ * ```typescript
131
+ * const response = await manager.acceptPairing(request, async () => {
132
+ * // Show modal: "Device {name} wants to pair. Accept?"
133
+ * return await showConfirmationDialog({
134
+ * title: 'Pair with Device?',
135
+ * message: `DID: ${request.device_a_did.slice(0, 20)}...`,
136
+ * });
137
+ * });
138
+ *
139
+ * if (response.ok && response.value.accepted) {
140
+ * // Send response back to Device A
141
+ * }
142
+ * ```
143
+ */
144
+ async acceptPairing(request, promptCallback) {
145
+ // Validate request first
146
+ const validation = this.validateRequest(request);
147
+ if (!validation.ok) {
148
+ return err(validation.error);
149
+ }
150
+ // Prompt user for confirmation
151
+ const accepted = await promptCallback();
152
+ if (accepted) {
153
+ // Store in trust registry (Device A → Device B)
154
+ const registerResult = await this.registry.register(request.device_a_did, new Uint8Array(32), 'Paired Device', ['pairing']);
155
+ if (!registerResult.ok) {
156
+ const errorMsg = typeof registerResult.error === 'string'
157
+ ? registerResult.error
158
+ : 'Unknown error';
159
+ return err(`Failed to register pairing: ${errorMsg}`);
160
+ }
161
+ }
162
+ // Return response (echo nonce to prevent MITM)
163
+ return ok({
164
+ device_b_did: this.deviceDid,
165
+ accepted,
166
+ nonce: request.nonce,
167
+ });
168
+ }
169
+ /**
170
+ * Finalize pairing.
171
+ *
172
+ * Verifies response nonce and stores remote DID in trust registry.
173
+ * Device A calls this after receiving response from Device B.
174
+ *
175
+ * @param response - Pairing response from Device B
176
+ * @param expectedNonce - Nonce from original request (for verification)
177
+ * @returns Ok if successful, Err if nonce mismatch or storage failed
178
+ *
179
+ * @example
180
+ * ```typescript
181
+ * const request = manager.createRequest();
182
+ * const response = await sendPairingRequest(deviceB.endpoint, request);
183
+ *
184
+ * const result = await manager.finalizePairing(response, request.nonce);
185
+ * if (result.ok) {
186
+ * console.log('Pairing successful!');
187
+ * } else {
188
+ * console.error('Pairing failed:', result.error);
189
+ * }
190
+ * ```
191
+ */
192
+ async finalizePairing(response, expectedNonce) {
193
+ // Verify nonce echo (prevents MITM substitution)
194
+ if (response.nonce !== expectedNonce) {
195
+ return err('Nonce mismatch (possible MITM attack)');
196
+ }
197
+ // Check if pairing was accepted
198
+ if (!response.accepted) {
199
+ return err('Pairing rejected by remote device');
200
+ }
201
+ // Remove nonce from pending set
202
+ this.pendingNonces.delete(expectedNonce);
203
+ // Store in trust registry (Device B → Device A)
204
+ const registerResult = await this.registry.register(response.device_b_did, new Uint8Array(32), 'Paired Device', ['pairing']);
205
+ if (!registerResult.ok) {
206
+ const errorMsg = typeof registerResult.error === 'string'
207
+ ? registerResult.error
208
+ : 'Unknown error';
209
+ return err(`Failed to register pairing: ${errorMsg}`);
210
+ }
211
+ return ok(undefined);
212
+ }
213
+ /**
214
+ * Get pending nonce count (for debugging/monitoring).
215
+ */
216
+ getPendingNonceCount() {
217
+ return this.pendingNonces.size;
218
+ }
219
+ }