@private.me/xbind 3.0.2 → 3.0.3

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 (221) hide show
  1. package/README.md +2366 -204
  2. package/README.md.backup +2121 -0
  3. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
  4. package/dist-standalone/_deps/shared/cjs/errors.js +1 -729
  5. package/dist-standalone/_deps/shared/cjs/index.js +1 -463
  6. package/dist-standalone/_deps/shared/cjs/types.js +1 -315
  7. package/dist-standalone/_deps/shared/errors.js +1 -244
  8. package/dist-standalone/_deps/shared/index.js +1 -72
  9. package/dist-standalone/_deps/shared/types.js +1 -86
  10. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  20. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  21. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  28. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  29. package/dist-standalone/_deps/xchange/errors.js +1 -1
  30. package/dist-standalone/_deps/xchange/index.js +1 -1
  31. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  32. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  33. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  34. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  40. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  41. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  42. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  43. package/dist-standalone/_deps/xregistry/index.js +1 -1
  44. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  45. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  46. package/dist-standalone/_deps/xregistry/types.js +1 -1
  47. package/dist-standalone/agent-call.d.ts +2 -2
  48. package/dist-standalone/agent-call.js +1 -659
  49. package/dist-standalone/agent-sdk.js +1 -328
  50. package/dist-standalone/agent.d.ts +2 -0
  51. package/dist-standalone/agent.js +1 -1800
  52. package/dist-standalone/approval.js +1 -193
  53. package/dist-standalone/async-iterators.d.ts +3 -3
  54. package/dist-standalone/async-iterators.js +1 -382
  55. package/dist-standalone/auth.js +1 -219
  56. package/dist-standalone/auto-accept.js +1 -229
  57. package/dist-standalone/backup-config.js +1 -201
  58. package/dist-standalone/backup.js +1 -326
  59. package/dist-standalone/batch-operations.js +1 -388
  60. package/dist-standalone/cancellation.js +1 -477
  61. package/dist-standalone/checkpoint.js +1 -186
  62. package/dist-standalone/circuit-breaker.js +1 -468
  63. package/dist-standalone/cjs/agent-call.js +1 -701
  64. package/dist-standalone/cjs/agent-sdk.js +1 -332
  65. package/dist-standalone/cjs/agent.js +1 -1837
  66. package/dist-standalone/cjs/approval.js +1 -199
  67. package/dist-standalone/cjs/async-iterators.js +1 -392
  68. package/dist-standalone/cjs/auth.js +1 -225
  69. package/dist-standalone/cjs/auto-accept.js +1 -233
  70. package/dist-standalone/cjs/backup-config.js +1 -207
  71. package/dist-standalone/cjs/backup.js +1 -330
  72. package/dist-standalone/cjs/batch-operations.js +1 -397
  73. package/dist-standalone/cjs/cancellation.js +1 -490
  74. package/dist-standalone/cjs/checkpoint.js +1 -193
  75. package/dist-standalone/cjs/circuit-breaker.js +1 -476
  76. package/dist-standalone/cjs/cli/init.js +1 -492
  77. package/dist-standalone/cjs/config-validation.js +1 -522
  78. package/dist-standalone/cjs/connect.js +1 -312
  79. package/dist-standalone/cjs/connection-pool.js +1 -506
  80. package/dist-standalone/cjs/correlation-id.js +1 -339
  81. package/dist-standalone/cjs/crypto-utils.js +1 -176
  82. package/dist-standalone/cjs/debug-mode.js +1 -534
  83. package/dist-standalone/cjs/did-document.js +1 -101
  84. package/dist-standalone/cjs/did-privateme.js +1 -130
  85. package/dist-standalone/cjs/did-web.js +1 -201
  86. package/dist-standalone/cjs/discovery.js +1 -462
  87. package/dist-standalone/cjs/dual-mode.js +1 -251
  88. package/dist-standalone/cjs/email-templates.js +1 -313
  89. package/dist-standalone/cjs/email-transport.js +1 -239
  90. package/dist-standalone/cjs/envelope.js +1 -538
  91. package/dist-standalone/cjs/errors.js +1 -913
  92. package/dist-standalone/cjs/event-emitter.js +1 -461
  93. package/dist-standalone/cjs/gateway-state.js +1 -55
  94. package/dist-standalone/cjs/gateway-transport.js +1 -120
  95. package/dist-standalone/cjs/graceful-degradation.js +1 -403
  96. package/dist-standalone/cjs/guardrails.js +1 -223
  97. package/dist-standalone/cjs/health-check.js +1 -336
  98. package/dist-standalone/cjs/http-compat.js +1 -272
  99. package/dist-standalone/cjs/http-status-map.js +1 -571
  100. package/dist-standalone/cjs/identity.js +1 -645
  101. package/dist-standalone/cjs/index.js +1 -406
  102. package/dist-standalone/cjs/invitation.js +1 -421
  103. package/dist-standalone/cjs/invite.js +1 -328
  104. package/dist-standalone/cjs/key-agreement.js +1 -335
  105. package/dist-standalone/cjs/lazy-init.js +1 -300
  106. package/dist-standalone/cjs/logger.js +1 -291
  107. package/dist-standalone/cjs/loopback-transport.js +1 -0
  108. package/dist-standalone/cjs/mdns-discovery.js +1 -202
  109. package/dist-standalone/cjs/nonce-store.js +1 -80
  110. package/dist-standalone/cjs/pairing-manager.js +1 -223
  111. package/dist-standalone/cjs/plugin-system.js +1 -264
  112. package/dist-standalone/cjs/plugins/logging.js +1 -168
  113. package/dist-standalone/cjs/plugins/metrics.js +1 -181
  114. package/dist-standalone/cjs/plugins/validation.js +1 -302
  115. package/dist-standalone/cjs/policy.js +1 -320
  116. package/dist-standalone/cjs/progress-callbacks.js +1 -583
  117. package/dist-standalone/cjs/redis-nonce-store.js +1 -76
  118. package/dist-standalone/cjs/registry-middleware.js +1 -50
  119. package/dist-standalone/cjs/retry-strategies.js +1 -544
  120. package/dist-standalone/cjs/retry-transport.js +1 -102
  121. package/dist-standalone/cjs/runtime/browser.js +1 -533
  122. package/dist-standalone/cjs/runtime/edge.js +1 -526
  123. package/dist-standalone/cjs/runtime/react-native.js +1 -394
  124. package/dist-standalone/cjs/security-policy.js +1 -245
  125. package/dist-standalone/cjs/serialization.js +1 -1040
  126. package/dist-standalone/cjs/split-channel.js +1 -225
  127. package/dist-standalone/cjs/subscription-proof.js +1 -230
  128. package/dist-standalone/cjs/succession.js +1 -148
  129. package/dist-standalone/cjs/timeouts.js +1 -412
  130. package/dist-standalone/cjs/trace-context.js +1 -424
  131. package/dist-standalone/cjs/trace-spans.js +1 -495
  132. package/dist-standalone/cjs/transport.js +1 -63
  133. package/dist-standalone/cjs/trust-registry.js +1 -991
  134. package/dist-standalone/cjs/types/error-response.js +1 -56
  135. package/dist-standalone/cjs/vault-auth.js +1 -178
  136. package/dist-standalone/cjs/vault-store-loader.js +1 -194
  137. package/dist-standalone/cjs/verify.js +1 -25
  138. package/dist-standalone/cjs/version-info.js +1 -543
  139. package/dist-standalone/cjs/xfetch.js +1 -340
  140. package/dist-standalone/cli/init.js +1 -455
  141. package/dist-standalone/cli/setup.js +1 -514
  142. package/dist-standalone/cli/types.js +1 -27
  143. package/dist-standalone/cli/xbind.js +1 -148
  144. package/dist-standalone/config-validation.js +1 -513
  145. package/dist-standalone/connect.js +1 -274
  146. package/dist-standalone/connection-pool.js +1 -500
  147. package/dist-standalone/correlation-id.js +1 -326
  148. package/dist-standalone/crypto-utils.d.ts +2 -7
  149. package/dist-standalone/crypto-utils.js +1 -157
  150. package/dist-standalone/debug-mode.js +1 -510
  151. package/dist-standalone/did-document.js +1 -96
  152. package/dist-standalone/did-privateme.js +1 -121
  153. package/dist-standalone/did-web.js +1 -196
  154. package/dist-standalone/discovery.js +1 -458
  155. package/dist-standalone/dual-mode.js +1 -247
  156. package/dist-standalone/email-templates.js +1 -309
  157. package/dist-standalone/email-transport.d.ts +2 -2
  158. package/dist-standalone/email-transport.js +1 -232
  159. package/dist-standalone/envelope.js +1 -525
  160. package/dist-standalone/errors.d.ts +13 -3
  161. package/dist-standalone/errors.js +1 -896
  162. package/dist-standalone/event-emitter.js +1 -456
  163. package/dist-standalone/gateway-state.d.ts +1 -1
  164. package/dist-standalone/gateway-state.js +1 -51
  165. package/dist-standalone/gateway-transport.js +1 -116
  166. package/dist-standalone/graceful-degradation.js +1 -396
  167. package/dist-standalone/guardrails.js +1 -216
  168. package/dist-standalone/health-check.d.ts +5 -1
  169. package/dist-standalone/health-check.js +1 -332
  170. package/dist-standalone/http-compat.d.ts +1 -1
  171. package/dist-standalone/http-compat.js +1 -267
  172. package/dist-standalone/http-status-map.js +1 -561
  173. package/dist-standalone/identity.js +1 -619
  174. package/dist-standalone/index.d.ts +15 -4
  175. package/dist-standalone/index.js +1 -78
  176. package/dist-standalone/invitation.js +1 -415
  177. package/dist-standalone/invite.js +1 -324
  178. package/dist-standalone/key-agreement.js +1 -325
  179. package/dist-standalone/lazy-init.d.ts +11 -6
  180. package/dist-standalone/lazy-init.js +1 -295
  181. package/dist-standalone/logger.js +1 -285
  182. package/dist-standalone/loopback-transport.d.ts +87 -0
  183. package/dist-standalone/loopback-transport.js +1 -0
  184. package/dist-standalone/mdns-discovery.js +1 -195
  185. package/dist-standalone/nonce-store.js +1 -76
  186. package/dist-standalone/pairing-manager.js +1 -219
  187. package/dist-standalone/plugin-system.js +1 -257
  188. package/dist-standalone/plugins/logging.js +1 -163
  189. package/dist-standalone/plugins/metrics.d.ts +4 -4
  190. package/dist-standalone/plugins/metrics.js +1 -176
  191. package/dist-standalone/plugins/validation.js +1 -297
  192. package/dist-standalone/policy.js +1 -315
  193. package/dist-standalone/progress-callbacks.js +1 -576
  194. package/dist-standalone/redis-nonce-store.js +1 -72
  195. package/dist-standalone/registry-middleware.js +1 -47
  196. package/dist-standalone/retry-strategies.js +1 -534
  197. package/dist-standalone/retry-transport.js +1 -98
  198. package/dist-standalone/runtime/browser.js +1 -516
  199. package/dist-standalone/runtime/edge.js +1 -511
  200. package/dist-standalone/runtime/react-native.d.ts +1 -1
  201. package/dist-standalone/runtime/react-native.js +1 -383
  202. package/dist-standalone/security-policy.js +1 -239
  203. package/dist-standalone/serialization.js +1 -1031
  204. package/dist-standalone/split-channel.js +1 -219
  205. package/dist-standalone/subscription-proof.js +1 -224
  206. package/dist-standalone/succession.js +1 -142
  207. package/dist-standalone/timeouts.js +1 -398
  208. package/dist-standalone/trace-context.js +1 -414
  209. package/dist-standalone/trace-spans.js +1 -488
  210. package/dist-standalone/transport.js +1 -59
  211. package/dist-standalone/trust-registry.d.ts +3 -3
  212. package/dist-standalone/trust-registry.js +1 -950
  213. package/dist-standalone/types/error-response.js +1 -52
  214. package/dist-standalone/vault-auth.js +1 -174
  215. package/dist-standalone/vault-store-loader.d.ts +9 -0
  216. package/dist-standalone/vault-store-loader.js +1 -187
  217. package/dist-standalone/verify.js +1 -16
  218. package/dist-standalone/version-info.js +1 -530
  219. package/dist-standalone/xfetch.js +1 -335
  220. package/package.json +1 -1
  221. package/share1.dat +0 -0
@@ -1,202 +1 @@
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
+ "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{}});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,80 +1 @@
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
+ "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,223 +1 @@
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;
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;