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