@private.me/xbind 1.3.5 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (306) hide show
  1. package/LICENSES.md +212 -0
  2. package/README.md +388 -6
  3. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
  4. package/dist-standalone/_deps/shared/cjs/errors.js +1 -639
  5. package/dist-standalone/_deps/shared/cjs/index.js +1 -496
  6. package/dist-standalone/_deps/shared/cjs/types.js +1 -317
  7. package/dist-standalone/_deps/shared/errors.js +1 -255
  8. package/dist-standalone/_deps/shared/index.js +1 -74
  9. package/dist-standalone/_deps/shared/types.js +1 -90
  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.js +1 -642
  48. package/dist-standalone/agent-sdk.js +1 -328
  49. package/dist-standalone/agent.d.ts +95 -5
  50. package/dist-standalone/agent.js +1 -1545
  51. package/dist-standalone/approval.js +1 -193
  52. package/dist-standalone/async-iterators.d.ts +275 -0
  53. package/dist-standalone/async-iterators.js +1 -0
  54. package/dist-standalone/auth.js +1 -219
  55. package/dist-standalone/auto-accept.js +1 -229
  56. package/dist-standalone/backup-config.js +1 -201
  57. package/dist-standalone/backup.d.ts +114 -0
  58. package/dist-standalone/backup.js +1 -0
  59. package/dist-standalone/batch-operations.d.ts +297 -0
  60. package/dist-standalone/batch-operations.js +1 -0
  61. package/dist-standalone/cancellation.d.ts +301 -0
  62. package/dist-standalone/cancellation.js +1 -0
  63. package/dist-standalone/checkpoint.js +1 -186
  64. package/dist-standalone/circuit-breaker.d.ts +351 -0
  65. package/dist-standalone/circuit-breaker.js +1 -0
  66. package/dist-standalone/cjs/agent-call.js +1 -651
  67. package/dist-standalone/cjs/agent-sdk.js +1 -332
  68. package/dist-standalone/cjs/agent.js +1 -1582
  69. package/dist-standalone/cjs/approval.js +1 -199
  70. package/dist-standalone/cjs/async-iterators.js +1 -0
  71. package/dist-standalone/cjs/auth.js +1 -225
  72. package/dist-standalone/cjs/auto-accept.js +1 -233
  73. package/dist-standalone/cjs/backup-config.js +1 -207
  74. package/dist-standalone/cjs/backup.js +1 -0
  75. package/dist-standalone/cjs/batch-operations.js +1 -0
  76. package/dist-standalone/cjs/cancellation.js +1 -0
  77. package/dist-standalone/cjs/checkpoint.js +1 -193
  78. package/dist-standalone/cjs/circuit-breaker.js +1 -0
  79. package/dist-standalone/cjs/cli/init.js +1 -486
  80. package/dist-standalone/cjs/config-validation.js +1 -0
  81. package/dist-standalone/cjs/connect.js +1 -312
  82. package/dist-standalone/cjs/connection-pool.js +1 -0
  83. package/dist-standalone/cjs/correlation-id.js +1 -339
  84. package/dist-standalone/cjs/crypto-utils.js +1 -0
  85. package/dist-standalone/cjs/debug-mode.js +1 -0
  86. package/dist-standalone/cjs/did-document.js +1 -101
  87. package/dist-standalone/cjs/did-privateme.js +1 -130
  88. package/dist-standalone/cjs/did-web.js +1 -201
  89. package/dist-standalone/cjs/discovery.js +1 -462
  90. package/dist-standalone/cjs/dual-mode.js +1 -251
  91. package/dist-standalone/cjs/email-templates.js +1 -313
  92. package/dist-standalone/cjs/email-transport.js +1 -239
  93. package/dist-standalone/cjs/envelope.js +1 -510
  94. package/dist-standalone/cjs/errors.js +1 -826
  95. package/dist-standalone/cjs/event-emitter.js +1 -0
  96. package/dist-standalone/cjs/gateway-state.js +1 -55
  97. package/dist-standalone/cjs/gateway-transport.js +1 -120
  98. package/dist-standalone/cjs/graceful-degradation.js +1 -0
  99. package/dist-standalone/cjs/guardrails.js +1 -223
  100. package/dist-standalone/cjs/health-check.js +1 -0
  101. package/dist-standalone/cjs/http-compat.js +1 -272
  102. package/dist-standalone/cjs/http-status-map.js +1 -571
  103. package/dist-standalone/cjs/identity.js +1 -540
  104. package/dist-standalone/cjs/index.js +1 -237
  105. package/dist-standalone/cjs/invitation.js +1 -421
  106. package/dist-standalone/cjs/invite.js +1 -328
  107. package/dist-standalone/cjs/key-agreement.js +1 -246
  108. package/dist-standalone/cjs/lazy-init.js +1 -300
  109. package/dist-standalone/cjs/logger.js +1 -0
  110. package/dist-standalone/cjs/mdns-discovery.js +1 -202
  111. package/dist-standalone/cjs/nonce-store.js +1 -66
  112. package/dist-standalone/cjs/pairing-manager.js +1 -223
  113. package/dist-standalone/cjs/plugin-system.js +1 -0
  114. package/dist-standalone/cjs/plugins/logging.js +1 -0
  115. package/dist-standalone/cjs/plugins/metrics.js +1 -0
  116. package/dist-standalone/cjs/plugins/validation.js +1 -0
  117. package/dist-standalone/cjs/policy.js +1 -320
  118. package/dist-standalone/cjs/progress-callbacks.js +1 -0
  119. package/dist-standalone/cjs/redis-nonce-store.js +1 -76
  120. package/dist-standalone/cjs/registry-middleware.js +1 -50
  121. package/dist-standalone/cjs/retry-strategies.js +1 -0
  122. package/dist-standalone/cjs/retry-transport.js +1 -102
  123. package/dist-standalone/cjs/runtime/browser.js +1 -0
  124. package/dist-standalone/cjs/runtime/edge.js +1 -0
  125. package/dist-standalone/cjs/runtime/react-native.js +1 -0
  126. package/dist-standalone/cjs/security-policy.js +1 -245
  127. package/dist-standalone/cjs/serialization.js +1 -0
  128. package/dist-standalone/cjs/split-channel.js +1 -177
  129. package/dist-standalone/cjs/subscription-proof.js +1 -230
  130. package/dist-standalone/cjs/succession.js +1 -148
  131. package/dist-standalone/cjs/timeouts.js +1 -0
  132. package/dist-standalone/cjs/trace-context.js +1 -0
  133. package/dist-standalone/cjs/trace-spans.js +1 -0
  134. package/dist-standalone/cjs/transport.js +1 -63
  135. package/dist-standalone/cjs/trust-registry.js +1 -742
  136. package/dist-standalone/cjs/types/error-response.js +1 -56
  137. package/dist-standalone/cjs/vault-auth.js +1 -0
  138. package/dist-standalone/cjs/vault-store-loader.js +1 -0
  139. package/dist-standalone/cjs/verify.js +1 -25
  140. package/dist-standalone/cjs/version-info.js +1 -0
  141. package/dist-standalone/cjs/xfetch.js +1 -252
  142. package/dist-standalone/cli/init.js +1 -449
  143. package/dist-standalone/cli/setup.js +1 -514
  144. package/dist-standalone/cli/types.js +1 -27
  145. package/dist-standalone/cli/xbind.js +1 -148
  146. package/dist-standalone/config-validation.d.ts +185 -0
  147. package/dist-standalone/config-validation.js +1 -0
  148. package/dist-standalone/connect.js +1 -274
  149. package/dist-standalone/connection-pool.d.ts +251 -0
  150. package/dist-standalone/connection-pool.js +1 -0
  151. package/dist-standalone/correlation-id.js +1 -326
  152. package/dist-standalone/crypto-utils.d.ts +60 -0
  153. package/dist-standalone/crypto-utils.js +1 -0
  154. package/dist-standalone/debug-mode.d.ts +286 -0
  155. package/dist-standalone/debug-mode.js +1 -0
  156. package/dist-standalone/did-document.js +1 -96
  157. package/dist-standalone/did-privateme.js +1 -121
  158. package/dist-standalone/did-web.js +1 -196
  159. package/dist-standalone/discovery.js +1 -458
  160. package/dist-standalone/dual-mode.js +1 -247
  161. package/dist-standalone/email-templates.js +1 -309
  162. package/dist-standalone/email-transport.js +1 -232
  163. package/dist-standalone/envelope.d.ts +29 -1
  164. package/dist-standalone/envelope.js +1 -497
  165. package/dist-standalone/errors.d.ts +10 -0
  166. package/dist-standalone/errors.js +1 -811
  167. package/dist-standalone/event-emitter.d.ts +395 -0
  168. package/dist-standalone/event-emitter.js +1 -0
  169. package/dist-standalone/gateway-state.js +1 -51
  170. package/dist-standalone/gateway-transport.js +1 -116
  171. package/dist-standalone/graceful-degradation.d.ts +246 -0
  172. package/dist-standalone/graceful-degradation.js +1 -0
  173. package/dist-standalone/guardrails.js +1 -216
  174. package/dist-standalone/health-check.d.ts +150 -0
  175. package/dist-standalone/health-check.js +1 -0
  176. package/dist-standalone/http-compat.js +1 -267
  177. package/dist-standalone/http-status-map.js +1 -561
  178. package/dist-standalone/identity.d.ts +64 -1
  179. package/dist-standalone/identity.js +1 -515
  180. package/dist-standalone/index.d.ts +45 -3
  181. package/dist-standalone/index.js +1 -52
  182. package/dist-standalone/invitation.js +1 -415
  183. package/dist-standalone/invite.js +1 -324
  184. package/dist-standalone/key-agreement.d.ts +61 -13
  185. package/dist-standalone/key-agreement.js +1 -236
  186. package/dist-standalone/lazy-init.js +1 -295
  187. package/dist-standalone/logger.d.ts +77 -0
  188. package/dist-standalone/logger.js +1 -0
  189. package/dist-standalone/mdns-discovery.js +1 -195
  190. package/dist-standalone/nonce-store.d.ts +16 -3
  191. package/dist-standalone/nonce-store.js +1 -62
  192. package/dist-standalone/package.json +0 -1
  193. package/dist-standalone/pairing-manager.js +1 -219
  194. package/dist-standalone/plugin-system.d.ts +145 -0
  195. package/dist-standalone/plugin-system.js +1 -0
  196. package/dist-standalone/policy.js +1 -315
  197. package/dist-standalone/progress-callbacks.d.ts +394 -0
  198. package/dist-standalone/progress-callbacks.js +1 -0
  199. package/dist-standalone/redis-nonce-store.js +1 -72
  200. package/dist-standalone/registry-middleware.js +1 -47
  201. package/dist-standalone/retry-strategies.d.ts +382 -0
  202. package/dist-standalone/retry-strategies.js +1 -0
  203. package/dist-standalone/retry-transport.js +1 -98
  204. package/dist-standalone/security-policy.js +1 -239
  205. package/dist-standalone/serialization.d.ts +244 -0
  206. package/dist-standalone/serialization.js +1 -0
  207. package/dist-standalone/split-channel.d.ts +49 -1
  208. package/dist-standalone/split-channel.js +1 -171
  209. package/dist-standalone/subscription-proof.js +1 -224
  210. package/dist-standalone/succession.js +1 -142
  211. package/dist-standalone/timeouts.d.ts +275 -0
  212. package/dist-standalone/timeouts.js +1 -0
  213. package/dist-standalone/trace-context.d.ts +252 -0
  214. package/dist-standalone/trace-context.js +1 -0
  215. package/dist-standalone/trace-spans.d.ts +360 -0
  216. package/dist-standalone/trace-spans.js +1 -0
  217. package/dist-standalone/transport.js +1 -59
  218. package/dist-standalone/trust-registry.d.ts +106 -5
  219. package/dist-standalone/trust-registry.js +1 -702
  220. package/dist-standalone/vault-auth.d.ts +91 -0
  221. package/dist-standalone/vault-auth.js +1 -0
  222. package/dist-standalone/vault-store-loader.d.ts +110 -0
  223. package/dist-standalone/vault-store-loader.js +1 -0
  224. package/dist-standalone/verify.js +1 -16
  225. package/dist-standalone/version-info.d.ts +259 -0
  226. package/dist-standalone/version-info.js +1 -0
  227. package/dist-standalone/xfetch.js +1 -247
  228. package/llms.txt +1 -0
  229. package/package.json +65 -5
  230. package/share1.dat +0 -0
  231. package/dist-standalone/_deps/crypto/base64.d.ts +0 -29
  232. package/dist-standalone/_deps/crypto/base64.js +0 -222
  233. package/dist-standalone/_deps/crypto/cjs/base64.js +0 -665
  234. package/dist-standalone/_deps/crypto/cjs/errors.js +0 -675
  235. package/dist-standalone/_deps/crypto/cjs/hmac.js +0 -473
  236. package/dist-standalone/_deps/crypto/cjs/index.js +0 -852
  237. package/dist-standalone/_deps/crypto/cjs/package.json +0 -1
  238. package/dist-standalone/_deps/crypto/cjs/padding.js +0 -511
  239. package/dist-standalone/_deps/crypto/cjs/share-header.js +0 -372
  240. package/dist-standalone/_deps/crypto/cjs/shares.js +0 -874
  241. package/dist-standalone/_deps/crypto/cjs/tlv.js +0 -1021
  242. package/dist-standalone/_deps/crypto/cjs/uuid.js +0 -443
  243. package/dist-standalone/_deps/crypto/cjs/verify.js +0 -414
  244. package/dist-standalone/_deps/crypto/cjs/xorida.js +0 -923
  245. package/dist-standalone/_deps/crypto/errors.d.ts +0 -51
  246. package/dist-standalone/_deps/crypto/errors.js +0 -199
  247. package/dist-standalone/_deps/crypto/hmac.d.ts +0 -39
  248. package/dist-standalone/_deps/crypto/hmac.js +0 -134
  249. package/dist-standalone/_deps/crypto/index.d.ts +0 -20
  250. package/dist-standalone/_deps/crypto/index.js +0 -145
  251. package/dist-standalone/_deps/crypto/padding.d.ts +0 -19
  252. package/dist-standalone/_deps/crypto/padding.js +0 -159
  253. package/dist-standalone/_deps/crypto/share-header.d.ts +0 -44
  254. package/dist-standalone/_deps/crypto/share-header.js +0 -92
  255. package/dist-standalone/_deps/crypto/shares.d.ts +0 -27
  256. package/dist-standalone/_deps/crypto/shares.js +0 -295
  257. package/dist-standalone/_deps/crypto/tlv.d.ts +0 -26
  258. package/dist-standalone/_deps/crypto/tlv.js +0 -364
  259. package/dist-standalone/_deps/crypto/uuid.d.ts +0 -22
  260. package/dist-standalone/_deps/crypto/uuid.js +0 -136
  261. package/dist-standalone/_deps/crypto/verify.d.ts +0 -15
  262. package/dist-standalone/_deps/crypto/verify.js +0 -71
  263. package/dist-standalone/_deps/crypto/xorida.d.ts +0 -44
  264. package/dist-standalone/_deps/crypto/xorida.js +0 -366
  265. package/dist-standalone/_deps/shared/errors.d.ts.map +0 -1
  266. package/dist-standalone/_deps/shared/errors.js.map +0 -1
  267. package/dist-standalone/_deps/shared/index.d.ts.map +0 -1
  268. package/dist-standalone/_deps/shared/index.js.map +0 -1
  269. package/dist-standalone/_deps/shared/types.d.ts.map +0 -1
  270. package/dist-standalone/_deps/shared/types.js.map +0 -1
  271. package/dist-standalone/_deps/ux-helpers/cjs/errors.d.ts.map +0 -1
  272. package/dist-standalone/_deps/ux-helpers/cjs/errors.js.map +0 -1
  273. package/dist-standalone/_deps/ux-helpers/cjs/index.d.ts.map +0 -1
  274. package/dist-standalone/_deps/ux-helpers/cjs/index.js.map +0 -1
  275. package/dist-standalone/_deps/ux-helpers/cjs/pagination.d.ts.map +0 -1
  276. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js.map +0 -1
  277. package/dist-standalone/_deps/ux-helpers/cjs/progress.d.ts.map +0 -1
  278. package/dist-standalone/_deps/ux-helpers/cjs/progress.js.map +0 -1
  279. package/dist-standalone/_deps/ux-helpers/cjs/search.d.ts.map +0 -1
  280. package/dist-standalone/_deps/ux-helpers/cjs/search.js.map +0 -1
  281. package/dist-standalone/_deps/ux-helpers/cjs/types.d.ts.map +0 -1
  282. package/dist-standalone/_deps/ux-helpers/cjs/types.js.map +0 -1
  283. package/dist-standalone/_deps/ux-helpers/errors.d.ts.map +0 -1
  284. package/dist-standalone/_deps/ux-helpers/errors.js.map +0 -1
  285. package/dist-standalone/_deps/ux-helpers/index.d.ts.map +0 -1
  286. package/dist-standalone/_deps/ux-helpers/index.js.map +0 -1
  287. package/dist-standalone/_deps/ux-helpers/pagination.d.ts.map +0 -1
  288. package/dist-standalone/_deps/ux-helpers/pagination.js.map +0 -1
  289. package/dist-standalone/_deps/ux-helpers/progress.d.ts.map +0 -1
  290. package/dist-standalone/_deps/ux-helpers/progress.js.map +0 -1
  291. package/dist-standalone/_deps/ux-helpers/search.d.ts.map +0 -1
  292. package/dist-standalone/_deps/ux-helpers/search.js.map +0 -1
  293. package/dist-standalone/_deps/ux-helpers/types.d.ts.map +0 -1
  294. package/dist-standalone/_deps/ux-helpers/types.js.map +0 -1
  295. package/dist-standalone/_deps/xregistry/discovery.d.ts.map +0 -1
  296. package/dist-standalone/_deps/xregistry/discovery.js.map +0 -1
  297. package/dist-standalone/_deps/xregistry/errors.d.ts.map +0 -1
  298. package/dist-standalone/_deps/xregistry/errors.js.map +0 -1
  299. package/dist-standalone/_deps/xregistry/index.d.ts.map +0 -1
  300. package/dist-standalone/_deps/xregistry/index.js.map +0 -1
  301. package/dist-standalone/_deps/xregistry/registry.d.ts.map +0 -1
  302. package/dist-standalone/_deps/xregistry/registry.js.map +0 -1
  303. package/dist-standalone/_deps/xregistry/schema.d.ts.map +0 -1
  304. package/dist-standalone/_deps/xregistry/schema.js.map +0 -1
  305. package/dist-standalone/_deps/xregistry/types.d.ts.map +0 -1
  306. package/dist-standalone/_deps/xregistry/types.js.map +0 -1
@@ -1,295 +1 @@
1
- /**
2
- * @module lazy-init
3
- * Lazy agent initialization for zero-click onboarding.
4
- *
5
- * Defers invite acceptance and identity generation until first
6
- * send/receive call. Enables: `Agent.lazy({ name: 'my-service' })`
7
- * with no async/await at construction time.
8
- *
9
- * @example
10
- * ```ts
11
- * // Environment: XBIND_INVITE_CODE=XBD-abc123
12
- *
13
- * // Old way (explicit):
14
- * const agent = await Agent.create({ name: 'my-service', registry, transport });
15
- *
16
- * // New way (lazy):
17
- * const agent = Agent.lazy({ name: 'my-service' });
18
- * // No await, no async — agent is constructed synchronously.
19
- * // Invite auto-accepts on first send/receive:
20
- * await agent.send({ to: partnerDid, payload: data, scope: 'test' });
21
- * ```
22
- */
23
- import { ok, err } from"./_deps/shared/index.js";
24
- import { Agent } from './agent.js';
25
- import { autoAcceptInvite } from './auto-accept.js';
26
- import { MemoryTrustRegistry } from './trust-registry.js';
27
- import { HttpsTransportAdapter } from './transport.js';
28
- import { toBase64 } from"./_deps/crypto/index.js";
29
- /**
30
- * Lazy agent error codes.
31
- */
32
- export var LazyAgentErrorCode;
33
- (function (LazyAgentErrorCode) {
34
- LazyAgentErrorCode["INIT_FAILED"] = "LAZY_AGENT_INIT_FAILED";
35
- LazyAgentErrorCode["AUTO_ACCEPT_FAILED"] = "LAZY_AGENT_AUTO_ACCEPT_FAILED";
36
- LazyAgentErrorCode["AGENT_CREATION_FAILED"] = "LAZY_AGENT_AGENT_CREATION_FAILED";
37
- })(LazyAgentErrorCode || (LazyAgentErrorCode = {}));
38
- /**
39
- * Lazy agent wrapper.
40
- *
41
- * Proxies all Agent methods and initializes on first call.
42
- * Caches the initialized agent for subsequent calls.
43
- */
44
- export class LazyAgent {
45
- config;
46
- agent = null;
47
- initPromise = null;
48
- lastError = null;
49
- constructor(config) {
50
- this.config = config;
51
- }
52
- /**
53
- * Get the agent's DID.
54
- *
55
- * Triggers initialization if not already initialized.
56
- * Throws if initialization fails.
57
- */
58
- get did() {
59
- if (!this.agent) {
60
- throw new Error('Agent not initialized. Call send/receive first or await ensureInitialized().');
61
- }
62
- return this.agent.did;
63
- }
64
- /**
65
- * Check if agent is ready (initialized).
66
- */
67
- isReady() {
68
- return this.agent !== null;
69
- }
70
- /**
71
- * Get last initialization error (if any).
72
- */
73
- getLastError() {
74
- return this.lastError;
75
- }
76
- /**
77
- * Ensure agent is initialized.
78
- *
79
- * Can be called explicitly to trigger init before first send/receive.
80
- * Safe to call multiple times — subsequent calls return cached agent.
81
- *
82
- * @returns Agent instance or error
83
- */
84
- async ensureInitialized() {
85
- // If already initialized, return cached agent
86
- if (this.agent) {
87
- return ok(this.agent);
88
- }
89
- // If initialization is in progress, wait for it
90
- if (this.initPromise) {
91
- return this.initPromise;
92
- }
93
- // Start initialization
94
- this.initPromise = this.initialize();
95
- const result = await this.initPromise;
96
- // Clear promise after completion (success or failure)
97
- this.initPromise = null;
98
- if (result.ok) {
99
- this.agent = result.value;
100
- this.lastError = null;
101
- }
102
- else {
103
- this.lastError = {
104
- code: LazyAgentErrorCode.INIT_FAILED,
105
- message: `Agent initialization failed: ${result.error}`,
106
- cause: result.error,
107
- };
108
- }
109
- return result;
110
- }
111
- /**
112
- * Internal initialization logic.
113
- *
114
- * 1. Auto-accept invite (if XBIND_INVITE_CODE set)
115
- * 2. Create agent identity
116
- * 3. Configure registry and transport
117
- * 4. Return initialized agent
118
- */
119
- async initialize() {
120
- // Step 1: Attempt auto-accept if invite code is available
121
- const inviteCode = this.config.inviteCode ?? this.getEnv('XBIND_INVITE_CODE');
122
- let registry = this.config.registry;
123
- let transport = this.config.transport;
124
- const endpoint = this.config.endpoint ?? this.getEnv('XBIND_ENDPOINT') ?? '';
125
- if (inviteCode) {
126
- // Create temporary agent to get DID and public key for invite acceptance
127
- const tempAgentResult = await Agent.create({
128
- name: this.config.name,
129
- registry: new MemoryTrustRegistry(),
130
- transport: new HttpsTransportAdapter({ baseUrl: 'http://localhost' }), // Placeholder
131
- postQuantumSig: this.config.postQuantumSig,
132
- xchange: this.config.xchange,
133
- });
134
- if (!tempAgentResult.ok) {
135
- return err(tempAgentResult.error);
136
- }
137
- const tempAgent = tempAgentResult.value;
138
- // Export public key for invite acceptance
139
- const seedsResult = await tempAgent.exportSeeds();
140
- if (!seedsResult.ok) {
141
- return err('IDENTITY_FAILED');
142
- }
143
- const publicKey = toBase64(tempAgent.identity.rawPublicKey);
144
- const x25519PublicKey = tempAgent.identity.rawX25519PublicKey
145
- ? toBase64(tempAgent.identity.rawX25519PublicKey)
146
- : undefined;
147
- // Auto-accept invite
148
- const acceptResult = await autoAcceptInvite({
149
- inviteCode,
150
- enabled: true,
151
- registry: this.config.autoAccept?.registry,
152
- inviteApiUrl: this.config.autoAccept?.inviteApiUrl,
153
- }, {
154
- name: this.config.name,
155
- did: tempAgent.did,
156
- endpoint,
157
- publicKey,
158
- x25519PublicKey,
159
- });
160
- if (!acceptResult.ok) {
161
- this.lastError = {
162
- code: LazyAgentErrorCode.AUTO_ACCEPT_FAILED,
163
- message: acceptResult.error.message,
164
- hint: acceptResult.error.hint,
165
- cause: acceptResult.error,
166
- };
167
- // Non-fatal: continue with temp agent even if auto-accept fails
168
- // (registry may already be configured)
169
- }
170
- else {
171
- // Use auto-configured registry if not provided
172
- if (!registry && acceptResult.value.registryAutoconfigured) {
173
- // Registry was already configured by autoAcceptInvite
174
- registry = this.config.autoAccept?.registry ?? new MemoryTrustRegistry();
175
- }
176
- // Use inviter's endpoint as default transport if not provided
177
- if (!transport) {
178
- transport = new HttpsTransportAdapter({
179
- baseUrl: acceptResult.value.from.endpoint,
180
- });
181
- }
182
- }
183
- // Return temp agent as initialized agent
184
- this.agent = tempAgent;
185
- return ok(tempAgent);
186
- }
187
- // Step 2: No invite code — create agent normally
188
- const defaultRegistry = registry ?? new MemoryTrustRegistry();
189
- const defaultTransport = transport ?? new HttpsTransportAdapter({
190
- baseUrl: endpoint || 'http://localhost',
191
- });
192
- const agentResult = await Agent.create({
193
- name: this.config.name,
194
- registry: defaultRegistry,
195
- transport: defaultTransport,
196
- postQuantumSig: this.config.postQuantumSig,
197
- xchange: this.config.xchange,
198
- });
199
- if (!agentResult.ok) {
200
- this.lastError = {
201
- code: LazyAgentErrorCode.AGENT_CREATION_FAILED,
202
- message: `Agent creation failed: ${agentResult.error}`,
203
- cause: agentResult.error,
204
- };
205
- return agentResult;
206
- }
207
- this.agent = agentResult.value;
208
- return ok(this.agent);
209
- }
210
- /**
211
- * Send a message (proxied to underlying agent).
212
- *
213
- * Automatically initializes agent on first call.
214
- */
215
- async send(opts) {
216
- const agentResult = await this.ensureInitialized();
217
- if (!agentResult.ok) {
218
- return agentResult;
219
- }
220
- return agentResult.value.send(opts);
221
- }
222
- /**
223
- * Receive a message (proxied to underlying agent).
224
- *
225
- * Automatically initializes agent on first call.
226
- */
227
- async receive(envelope, opts) {
228
- const agentResult = await this.ensureInitialized();
229
- if (!agentResult.ok) {
230
- return err(agentResult.error);
231
- }
232
- return agentResult.value.receive(envelope, opts);
233
- }
234
- /**
235
- * Receive a split-channel share (proxied to underlying agent).
236
- *
237
- * Automatically initializes agent on first call.
238
- */
239
- async receiveSplitShare(envelope) {
240
- const agentResult = await this.ensureInitialized();
241
- if (!agentResult.ok) {
242
- return err(agentResult.error);
243
- }
244
- return agentResult.value.receiveSplitShare(envelope);
245
- }
246
- /**
247
- * Get environment variable value.
248
- *
249
- * @param key - Environment variable name
250
- * @returns Environment variable value or empty string
251
- */
252
- getEnv(key) {
253
- // SAFETY: Check for Node.js environment before accessing process
254
- if (typeof process !== 'undefined' && typeof process.env !== 'undefined') {
255
- return process.env[key] ?? '';
256
- }
257
- return '';
258
- }
259
- /**
260
- * Export the underlying agent (for advanced use cases).
261
- *
262
- * Throws if agent is not initialized.
263
- */
264
- getAgent() {
265
- if (!this.agent) {
266
- throw new Error('Agent not initialized. Call send/receive first or await ensureInitialized().');
267
- }
268
- return this.agent;
269
- }
270
- }
271
- /**
272
- * Create a lazy agent that initializes on first use.
273
- *
274
- * Extension method for Agent class. Adds `Agent.lazy()` factory.
275
- *
276
- * @param config - Lazy agent configuration
277
- * @returns Lazy agent wrapper
278
- *
279
- * @example
280
- * ```ts
281
- * // Environment: XBIND_INVITE_CODE=XBD-abc123
282
- *
283
- * const agent = createLazyAgent({ name: 'my-service' });
284
- *
285
- * // No initialization yet — happens on first send:
286
- * await agent.send({
287
- * to: 'did:key:z6Mk...',
288
- * payload: { action: 'test' },
289
- * scope: 'test',
290
- * });
291
- * ```
292
- */
293
- export function createLazyAgent(config) {
294
- return new LazyAgent(config);
295
- }
1
+ import{ok,err}from"./_deps/shared/index.js";import{Agent}from"./agent.js";import{autoAcceptInvite}from"./auto-accept.js";import{MemoryTrustRegistry}from"./trust-registry.js";import{HttpsTransportAdapter}from"./transport.js";import{toBase64}from"./crypto-utils.js";export var LazyAgentErrorCode;!function(t){t.INIT_FAILED="LAZY_AGENT_INIT_FAILED",t.AUTO_ACCEPT_FAILED="LAZY_AGENT_AUTO_ACCEPT_FAILED",t.AGENT_CREATION_FAILED="LAZY_AGENT_AGENT_CREATION_FAILED"}(LazyAgentErrorCode||(LazyAgentErrorCode={}));export class LazyAgent{config;agent=null;initPromise=null;lastError=null;constructor(t){this.config=t}get did(){if(!this.agent)throw new Error("Agent not initialized. Call send/receive first or await ensureInitialized().");return this.agent.did}isReady(){return null!==this.agent}getLastError(){return this.lastError}async ensureInitialized(){if(this.agent)return ok(this.agent);if(this.initPromise)return this.initPromise;this.initPromise=this.initialize();const t=await this.initPromise;return this.initPromise=null,t.ok?(this.agent=t.value,this.lastError=null):this.lastError={code:LazyAgentErrorCode.INIT_FAILED,message:`Agent initialization failed: ${t.error}`,cause:t.error},t}async initialize(){const t=this.config.inviteCode??this.getEnv("XBIND_INVITE_CODE");let e=this.config.registry,r=this.config.transport;const i=this.config.endpoint??this.getEnv("XBIND_ENDPOINT")??"";if(t){const n=await Agent.create({name:this.config.name,registry:new MemoryTrustRegistry,transport:new HttpsTransportAdapter({baseUrl:"http://localhost"}),postQuantumSig:this.config.postQuantumSig,xchange:this.config.xchange});if(!n.ok)return err(n.error);const s=n.value;if(!(await s.exportSeeds()).ok)return err("IDENTITY_FAILED");const o=toBase64(s.identity.rawPublicKey),a=s.identity.rawX25519PublicKey?toBase64(s.identity.rawX25519PublicKey):void 0,c=await autoAcceptInvite({inviteCode:t,enabled:!0,registry:this.config.autoAccept?.registry,inviteApiUrl:this.config.autoAccept?.inviteApiUrl},{name:this.config.name,did:s.did,endpoint:i,publicKey:o,x25519PublicKey:a});return c.ok?(!e&&c.value.registryAutoconfigured&&(e=this.config.autoAccept?.registry??new MemoryTrustRegistry),r||(r=new HttpsTransportAdapter({baseUrl:c.value.from.endpoint}))):this.lastError={code:LazyAgentErrorCode.AUTO_ACCEPT_FAILED,message:c.error.message,hint:c.error.hint,cause:c.error},this.agent=s,ok(s)}const n=e??new MemoryTrustRegistry,s=r??new HttpsTransportAdapter({baseUrl:i||"http://localhost"}),o=await Agent.create({name:this.config.name,registry:n,transport:s,postQuantumSig:this.config.postQuantumSig,xchange:this.config.xchange});return o.ok?(this.agent=o.value,ok(this.agent)):(this.lastError={code:LazyAgentErrorCode.AGENT_CREATION_FAILED,message:`Agent creation failed: ${o.error}`,cause:o.error},o)}async send(t){const e=await this.ensureInitialized();return e.ok?e.value.send(t):e}async receive(t,e){const r=await this.ensureInitialized();return r.ok?r.value.receive(t,e):err(r.error)}async receiveSplitShare(t){const e=await this.ensureInitialized();return e.ok?e.value.receiveSplitShare(t):err(e.error)}getEnv(t){return"undefined"!=typeof process&&void 0!==process.env?process.env[t]??"":""}getAgent(){if(!this.agent)throw new Error("Agent not initialized. Call send/receive first or await ensureInitialized().");return this.agent}}export function createLazyAgent(t){return new LazyAgent(t)}
@@ -0,0 +1,77 @@
1
+ /**
2
+ * @module logger
3
+ * Structured logging for debugging with context fields and sensitive data redaction
4
+ *
5
+ * Provides structured logging with multiple log levels, context tracking,
6
+ * and automatic redaction of sensitive information like DIDs, keys, and tokens.
7
+ *
8
+ * Usage:
9
+ * ```typescript
10
+ * import { createLogger } from '@private.me/xbind';
11
+ *
12
+ * const logger = createLogger('agent-gateway');
13
+ *
14
+ * // Basic logging
15
+ * logger.info('Agent initialized', { did: 'did:key:z6Mk...' });
16
+ *
17
+ * // With context
18
+ * logger.debug('Processing message', {
19
+ * nonce: '12345',
20
+ * scope: 'billing',
21
+ * encrypted: true
22
+ * });
23
+ *
24
+ * // Errors
25
+ * logger.error('Authentication failed', { code: 'AUTH_FAILED' }, error);
26
+ * ```
27
+ */
28
+ /**
29
+ * Log level enumeration
30
+ */
31
+ export declare enum LogLevel {
32
+ DEBUG = 0,
33
+ INFO = 1,
34
+ WARN = 2,
35
+ ERROR = 3,
36
+ SILENT = 4
37
+ }
38
+ /**
39
+ * Context fields for structured logging
40
+ */
41
+ export interface LogContext {
42
+ [key: string]: unknown;
43
+ /** Optional trace ID for correlation */
44
+ traceId?: string;
45
+ /** Optional span ID for correlation */
46
+ spanId?: string;
47
+ /** Optional parent span ID for correlation */
48
+ parentSpanId?: string;
49
+ }
50
+ /**
51
+ * Logger interface for structured logging
52
+ */
53
+ export interface Logger {
54
+ debug(message: string, context?: LogContext): void;
55
+ info(message: string, context?: LogContext): void;
56
+ warn(message: string, context?: LogContext): void;
57
+ error(message: string, context?: LogContext, error?: Error | unknown): void;
58
+ setLevel(level: LogLevel): void;
59
+ getLevel(): LogLevel;
60
+ isEnabled(level: LogLevel): boolean;
61
+ }
62
+ /**
63
+ * Create a logger instance with optional name
64
+ */
65
+ export declare function createLogger(name?: string): Logger;
66
+ /**
67
+ * Get or create global logger
68
+ */
69
+ export declare function getGlobalLogger(): Logger;
70
+ /**
71
+ * Set global logger instance
72
+ */
73
+ export declare function setGlobalLogger(logger: Logger): void;
74
+ /**
75
+ * Default export for convenience
76
+ */
77
+ export declare const logger: Logger;
@@ -0,0 +1 @@
1
+ export var LogLevel;!function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.SILENT=4]="SILENT"}(LogLevel||(LogLevel={}));const SENSITIVE_PATTERNS={did:/^did:[a-zA-Z0-9]+:/,nonce:/^[a-f0-9]{32,}$|^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,key:/^[a-zA-Z0-9+/]{40,}={0,2}$|^[a-f0-9]{64,}$/,token:/^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/,email:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,phone:/^\+?[1-9]\d{9,14}$/,apiKey:/^(sk_|pk_|ak_)[a-zA-Z0-9_-]{20,}$/},SENSITIVE_FIELD_NAMES=new Set(["password","secret","apiKey","api_key","privateKey","private_key","accessToken","access_token","refreshToken","refresh_token","masterKey","master_key","encryptionKey","encryption_key","authToken","auth_token","sessionToken","session_token","jwtToken","jwt_token","did","nonce","key","token","seed","entropy"]);function isSensitive(e,t){if("string"!=typeof t)return!1;const o=e.toLowerCase();if(SENSITIVE_FIELD_NAMES.has(o))return!0;for(const[e,n]of Object.entries(SENSITIVE_PATTERNS))if(o.includes(e)&&n.test(t))return!0;return!1}function redactValue(e){if(e.length<=4)return"*".repeat(Math.max(1,e.length));const t=Math.min(4,Math.ceil(e.length/4));return e.substring(0,t)+"*".repeat(Math.max(3,e.length-t-2))+e.substring(e.length-2)}function parseContextForLogging(e){const t=[],o={};for(const[n,r]of Object.entries(e))if(null!=r)if("object"==typeof r)if(r instanceof Error)o[n]={name:r.name,message:r.message};else if(r instanceof Map||r instanceof Set)o[n]=`[${r.constructor.name}]`;else if(Array.isArray(r))o[n]=r.map(e=>"string"==typeof e&&isSensitive(n,e)?(t.push(n),redactValue(e)):e);else{const e=parseContextForLogging(r);o[n]=e.context,e.redacted.length>0&&t.push(...e.redacted.map(e=>`${n}.${e}`))}else"string"==typeof r?isSensitive(n,r)?(t.push(n),o[n]=redactValue(r)):o[n]=r:o[n]="boolean"==typeof r||"number"==typeof r?r:`[${typeof r}]`;else o[n]=r;return{redacted:t,context:o}}function formatLogEntry(e,t,o,n,r){const a={timestamp:n,level:e,message:t};return o&&Object.keys(o).length>0&&(a.context=o),r.length>0&&(a.redacted=r),JSON.stringify(a)}export function createLogger(e="default"){let t=LogLevel.INFO;const o=process.env.XAIL_LOG_LEVEL?.toUpperCase();o&&o in LogLevel&&(t=LogLevel[o]);return{debug(t,o){if(!this.isEnabled(LogLevel.DEBUG))return;const n=(new Date).toISOString(),r=o?parseContextForLogging(o):{redacted:[],context:{}},a=formatLogEntry("DEBUG",t,r.context,n,r.redacted);console.debug(`[${e}] ${a}`)},info(t,o){if(!this.isEnabled(LogLevel.INFO))return;const n=(new Date).toISOString(),r=o?parseContextForLogging(o):{redacted:[],context:{}},a=formatLogEntry("INFO",t,r.context,n,r.redacted);console.log(`[${e}] ${a}`)},warn(t,o){if(!this.isEnabled(LogLevel.WARN))return;const n=(new Date).toISOString(),r=o?parseContextForLogging(o):{redacted:[],context:{}},a=formatLogEntry("WARN",t,r.context,n,r.redacted);console.warn(`[${e}] ${a}`)},error(t,o,n){if(!this.isEnabled(LogLevel.ERROR))return;const r=(new Date).toISOString(),a=o?{...o}:{};n instanceof Error?a.error={name:n.name,message:n.message,stack:n.stack}:void 0!==n&&(a.error=n);const s=Object.keys(a).length>0?parseContextForLogging(a):{redacted:[],context:{}},g=formatLogEntry("ERROR",t,s.context,r,s.redacted);console.error(`[${e}] ${g}`)},setLevel(e){t=e},getLevel:()=>t,isEnabled:e=>e>=t}}let globalLogger=null;export function getGlobalLogger(){return globalLogger||(globalLogger=createLogger("xbind")),globalLogger}export function setGlobalLogger(e){globalLogger=e}export const logger=getGlobalLogger();
@@ -1,195 +1 @@
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
+ 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,10 +1,19 @@
1
+ /** Optional context for share-aware deduplication. */
2
+ export interface ShareContext {
3
+ /** Share group identifier (e.g., for XorIDA splitting). */
4
+ readonly shareGroupId?: string;
5
+ /** Share index within the group (0-based). */
6
+ readonly shareIndex?: number;
7
+ }
1
8
  /** Interface for nonce stores that prevent replay attacks. */
2
9
  export interface NonceStore {
3
10
  /**
4
11
  * Check if a nonce is fresh and record it atomically.
12
+ * With shareContext: allows same nonce with different shares (idempotent retries).
13
+ * Without shareContext: blocks any nonce reuse (pure replay protection).
5
14
  * @returns true if nonce is new (accepted), false if duplicate (rejected).
6
15
  */
7
- check(nonce: string, senderDid: string): Promise<boolean>;
16
+ check(nonce: string, senderDid: string, shareContext?: ShareContext): Promise<boolean>;
8
17
  /** Remove expired entries. Called automatically on interval. */
9
18
  cleanup(): void;
10
19
  /** Shut down the store and clear any timers. */
@@ -20,7 +29,9 @@ export interface MemoryNonceStoreOptions {
20
29
  /**
21
30
  * In-memory nonce store for development and single-process deployments.
22
31
  *
23
- * Stores nonces in a Map keyed by "senderDid:nonce" with expiry timestamps.
32
+ * Stores nonces in a Map keyed by "senderDid:nonce:shareContext" with expiry timestamps.
33
+ * Supports share-aware deduplication: same nonce + different shares = allowed (idempotent retry),
34
+ * same nonce + same share = blocked (true replay).
24
35
  * Periodic cleanup removes expired entries to prevent unbounded growth.
25
36
  */
26
37
  export declare class MemoryNonceStore implements NonceStore {
@@ -31,7 +42,9 @@ export declare class MemoryNonceStore implements NonceStore {
31
42
  constructor(opts?: MemoryNonceStoreOptions);
32
43
  /** Start cleanup timer on first use. */
33
44
  private ensureTimer;
34
- check(nonce: string, senderDid: string): Promise<boolean>;
45
+ /** Build composite key: senderDid:nonce:shareGroupId:shareIndex */
46
+ private buildKey;
47
+ check(nonce: string, senderDid: string, shareContext?: ShareContext): Promise<boolean>;
35
48
  cleanup(): void;
36
49
  dispose(): void;
37
50
  /** Number of active (non-expired) entries. Useful for testing. */