@private.me/xbind 3.0.2 → 3.0.4

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 (222) hide show
  1. package/README.md +2366 -204
  2. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
  3. package/dist-standalone/_deps/shared/cjs/errors.js +1 -729
  4. package/dist-standalone/_deps/shared/cjs/index.js +1 -463
  5. package/dist-standalone/_deps/shared/cjs/types.js +1 -315
  6. package/dist-standalone/_deps/shared/errors.js +1 -244
  7. package/dist-standalone/_deps/shared/index.js +1 -72
  8. package/dist-standalone/_deps/shared/types.js +1 -86
  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.d.ts +2 -2
  47. package/dist-standalone/agent-call.js +1 -659
  48. package/dist-standalone/agent-sdk.js +1 -328
  49. package/dist-standalone/agent.d.ts +2 -0
  50. package/dist-standalone/agent.js +1 -1800
  51. package/dist-standalone/approval.js +1 -193
  52. package/dist-standalone/async-iterators.d.ts +3 -3
  53. package/dist-standalone/async-iterators.js +1 -382
  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.js +1 -326
  58. package/dist-standalone/batch-operations.js +1 -388
  59. package/dist-standalone/cancellation.js +1 -477
  60. package/dist-standalone/checkpoint.js +1 -186
  61. package/dist-standalone/circuit-breaker.js +1 -468
  62. package/dist-standalone/cjs/agent-call.js +1 -701
  63. package/dist-standalone/cjs/agent-sdk.js +1 -332
  64. package/dist-standalone/cjs/agent.js +1 -1837
  65. package/dist-standalone/cjs/approval.js +1 -199
  66. package/dist-standalone/cjs/async-iterators.js +1 -392
  67. package/dist-standalone/cjs/auth.js +1 -225
  68. package/dist-standalone/cjs/auto-accept.js +1 -233
  69. package/dist-standalone/cjs/backup-config.js +1 -207
  70. package/dist-standalone/cjs/backup.js +1 -330
  71. package/dist-standalone/cjs/batch-operations.js +1 -397
  72. package/dist-standalone/cjs/cancellation.js +1 -490
  73. package/dist-standalone/cjs/checkpoint.js +1 -193
  74. package/dist-standalone/cjs/circuit-breaker.js +1 -476
  75. package/dist-standalone/cjs/cli/init.js +1 -492
  76. package/dist-standalone/cjs/config-validation.js +1 -522
  77. package/dist-standalone/cjs/connect.js +1 -312
  78. package/dist-standalone/cjs/connection-pool.js +1 -506
  79. package/dist-standalone/cjs/correlation-id.js +1 -339
  80. package/dist-standalone/cjs/crypto-utils.js +1 -176
  81. package/dist-standalone/cjs/debug-mode.js +1 -534
  82. package/dist-standalone/cjs/did-document.js +1 -101
  83. package/dist-standalone/cjs/did-privateme.js +1 -130
  84. package/dist-standalone/cjs/did-web.js +1 -201
  85. package/dist-standalone/cjs/discovery.js +1 -462
  86. package/dist-standalone/cjs/dual-mode.js +1 -251
  87. package/dist-standalone/cjs/email-templates.js +1 -313
  88. package/dist-standalone/cjs/email-transport.js +1 -239
  89. package/dist-standalone/cjs/envelope.js +1 -538
  90. package/dist-standalone/cjs/errors.js +1 -913
  91. package/dist-standalone/cjs/event-emitter.js +1 -461
  92. package/dist-standalone/cjs/gateway-state.js +1 -55
  93. package/dist-standalone/cjs/gateway-transport.js +1 -120
  94. package/dist-standalone/cjs/graceful-degradation.js +1 -403
  95. package/dist-standalone/cjs/guardrails.js +1 -223
  96. package/dist-standalone/cjs/health-check.js +1 -336
  97. package/dist-standalone/cjs/http-compat.js +1 -272
  98. package/dist-standalone/cjs/http-status-map.js +1 -571
  99. package/dist-standalone/cjs/identity.js +1 -645
  100. package/dist-standalone/cjs/index.js +1 -406
  101. package/dist-standalone/cjs/invitation.js +1 -421
  102. package/dist-standalone/cjs/invite.js +1 -328
  103. package/dist-standalone/cjs/key-agreement.js +1 -335
  104. package/dist-standalone/cjs/lazy-init.js +1 -300
  105. package/dist-standalone/cjs/logger.js +1 -291
  106. package/dist-standalone/cjs/loopback-transport.js +1 -0
  107. package/dist-standalone/cjs/mdns-discovery.js +1 -202
  108. package/dist-standalone/cjs/nonce-store.js +1 -80
  109. package/dist-standalone/cjs/pairing-manager.js +1 -223
  110. package/dist-standalone/cjs/plugin-system.js +1 -264
  111. package/dist-standalone/cjs/plugins/logging.js +1 -168
  112. package/dist-standalone/cjs/plugins/metrics.js +1 -181
  113. package/dist-standalone/cjs/plugins/validation.js +1 -302
  114. package/dist-standalone/cjs/policy.js +1 -320
  115. package/dist-standalone/cjs/progress-callbacks.js +1 -583
  116. package/dist-standalone/cjs/redis-nonce-store.js +1 -76
  117. package/dist-standalone/cjs/registry-middleware.js +1 -50
  118. package/dist-standalone/cjs/retry-strategies.js +1 -544
  119. package/dist-standalone/cjs/retry-transport.js +1 -102
  120. package/dist-standalone/cjs/runtime/browser.js +1 -533
  121. package/dist-standalone/cjs/runtime/edge.js +1 -526
  122. package/dist-standalone/cjs/runtime/react-native.js +1 -394
  123. package/dist-standalone/cjs/security-policy.js +1 -245
  124. package/dist-standalone/cjs/serialization.js +1 -1040
  125. package/dist-standalone/cjs/split-channel.js +1 -225
  126. package/dist-standalone/cjs/subscription-proof.js +1 -230
  127. package/dist-standalone/cjs/succession.js +1 -148
  128. package/dist-standalone/cjs/timeouts.js +1 -412
  129. package/dist-standalone/cjs/trace-context.js +1 -424
  130. package/dist-standalone/cjs/trace-spans.js +1 -495
  131. package/dist-standalone/cjs/transport.js +1 -63
  132. package/dist-standalone/cjs/trust-registry.js +1 -991
  133. package/dist-standalone/cjs/types/error-response.js +1 -56
  134. package/dist-standalone/cjs/vault-auth.js +1 -178
  135. package/dist-standalone/cjs/vault-store-loader.js +1 -194
  136. package/dist-standalone/cjs/verify.js +1 -25
  137. package/dist-standalone/cjs/version-info.js +1 -543
  138. package/dist-standalone/cjs/xfetch.js +1 -340
  139. package/dist-standalone/cli/init.js +1 -455
  140. package/dist-standalone/cli/setup.js +1 -514
  141. package/dist-standalone/cli/types.js +1 -27
  142. package/dist-standalone/cli/xbind.js +1 -148
  143. package/dist-standalone/config-validation.js +1 -513
  144. package/dist-standalone/connect.js +1 -274
  145. package/dist-standalone/connection-pool.js +1 -500
  146. package/dist-standalone/correlation-id.js +1 -326
  147. package/dist-standalone/crypto-utils.d.ts +2 -7
  148. package/dist-standalone/crypto-utils.js +1 -157
  149. package/dist-standalone/debug-mode.js +1 -510
  150. package/dist-standalone/did-document.js +1 -96
  151. package/dist-standalone/did-privateme.js +1 -121
  152. package/dist-standalone/did-web.js +1 -196
  153. package/dist-standalone/discovery.js +1 -458
  154. package/dist-standalone/dual-mode.js +1 -247
  155. package/dist-standalone/email-templates.js +1 -309
  156. package/dist-standalone/email-transport.d.ts +2 -2
  157. package/dist-standalone/email-transport.js +1 -232
  158. package/dist-standalone/envelope.js +1 -525
  159. package/dist-standalone/errors.d.ts +13 -3
  160. package/dist-standalone/errors.js +1 -896
  161. package/dist-standalone/event-emitter.js +1 -456
  162. package/dist-standalone/gateway-state.d.ts +1 -1
  163. package/dist-standalone/gateway-state.js +1 -51
  164. package/dist-standalone/gateway-transport.js +1 -116
  165. package/dist-standalone/graceful-degradation.js +1 -396
  166. package/dist-standalone/guardrails.js +1 -216
  167. package/dist-standalone/health-check.d.ts +5 -1
  168. package/dist-standalone/health-check.js +1 -332
  169. package/dist-standalone/http-compat.d.ts +1 -1
  170. package/dist-standalone/http-compat.js +1 -267
  171. package/dist-standalone/http-status-map.js +1 -561
  172. package/dist-standalone/identity.js +1 -619
  173. package/dist-standalone/index.d.ts +15 -4
  174. package/dist-standalone/index.js +1 -78
  175. package/dist-standalone/invitation.js +1 -415
  176. package/dist-standalone/invite.js +1 -324
  177. package/dist-standalone/key-agreement.js +1 -325
  178. package/dist-standalone/lazy-init.d.ts +11 -6
  179. package/dist-standalone/lazy-init.js +1 -295
  180. package/dist-standalone/logger.js +1 -285
  181. package/dist-standalone/loopback-transport.d.ts +87 -0
  182. package/dist-standalone/loopback-transport.js +1 -0
  183. package/dist-standalone/mdns-discovery.js +1 -195
  184. package/dist-standalone/nonce-store.js +1 -76
  185. package/dist-standalone/pairing-manager.js +1 -219
  186. package/dist-standalone/plugin-system.js +1 -257
  187. package/dist-standalone/plugins/logging.js +1 -163
  188. package/dist-standalone/plugins/metrics.d.ts +4 -4
  189. package/dist-standalone/plugins/metrics.js +1 -176
  190. package/dist-standalone/plugins/validation.js +1 -297
  191. package/dist-standalone/policy.js +1 -315
  192. package/dist-standalone/progress-callbacks.js +1 -576
  193. package/dist-standalone/redis-nonce-store.js +1 -72
  194. package/dist-standalone/registry-middleware.js +1 -47
  195. package/dist-standalone/retry-strategies.js +1 -534
  196. package/dist-standalone/retry-transport.js +1 -98
  197. package/dist-standalone/runtime/browser.js +1 -516
  198. package/dist-standalone/runtime/edge.js +1 -511
  199. package/dist-standalone/runtime/react-native.d.ts +1 -1
  200. package/dist-standalone/runtime/react-native.js +1 -383
  201. package/dist-standalone/security-policy.js +1 -239
  202. package/dist-standalone/serialization.js +1 -1031
  203. package/dist-standalone/split-channel.d.ts +1 -1
  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.d.ts +1 -1
  211. package/dist-standalone/transport.js +1 -59
  212. package/dist-standalone/trust-registry.d.ts +3 -3
  213. package/dist-standalone/trust-registry.js +1 -950
  214. package/dist-standalone/types/error-response.js +1 -52
  215. package/dist-standalone/vault-auth.js +1 -174
  216. package/dist-standalone/vault-store-loader.d.ts +9 -0
  217. package/dist-standalone/vault-store-loader.js +1 -187
  218. package/dist-standalone/verify.js +1 -16
  219. package/dist-standalone/version-info.js +1 -530
  220. package/dist-standalone/xfetch.js +1 -335
  221. package/package.json +1 -1
  222. package/share1.dat +0 -0
@@ -1,300 +1 @@
1
- "use strict";
2
- /**
3
- * @module lazy-init
4
- * Lazy agent initialization for zero-click onboarding.
5
- *
6
- * Defers invite acceptance and identity generation until first
7
- * send/receive call. Enables: `Agent.lazy({ name: 'my-service' })`
8
- * with no async/await at construction time.
9
- *
10
- * @example
11
- * ```ts
12
- * // Environment: XBIND_INVITE_CODE=XBD-abc123
13
- *
14
- * // Old way (explicit):
15
- * const agent = await Agent.create({ name: 'my-service', registry, transport });
16
- *
17
- * // New way (lazy):
18
- * const agent = Agent.lazy({ name: 'my-service' });
19
- * // No await, no async — agent is constructed synchronously.
20
- * // Invite auto-accepts on first send/receive:
21
- * await agent.send({ to: partnerDid, payload: data, scope: 'test' });
22
- * ```
23
- */
24
- Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.LazyAgent = exports.LazyAgentErrorCode = void 0;
26
- exports.createLazyAgent = createLazyAgent;
27
- const shared_1 = require("../_deps/shared/index.js");
28
- const agent_js_1 = require("./agent.js");
29
- const auto_accept_js_1 = require("./auto-accept.js");
30
- const trust_registry_js_1 = require("./trust-registry.js");
31
- const transport_js_1 = require("./transport.js");
32
- const crypto_utils_js_1 = require("./crypto-utils.js");
33
- /**
34
- * Lazy agent error codes.
35
- */
36
- var LazyAgentErrorCode;
37
- (function (LazyAgentErrorCode) {
38
- LazyAgentErrorCode["INIT_FAILED"] = "LAZY_AGENT_INIT_FAILED";
39
- LazyAgentErrorCode["AUTO_ACCEPT_FAILED"] = "LAZY_AGENT_AUTO_ACCEPT_FAILED";
40
- LazyAgentErrorCode["AGENT_CREATION_FAILED"] = "LAZY_AGENT_AGENT_CREATION_FAILED";
41
- })(LazyAgentErrorCode || (exports.LazyAgentErrorCode = LazyAgentErrorCode = {}));
42
- /**
43
- * Lazy agent wrapper.
44
- *
45
- * Proxies all Agent methods and initializes on first call.
46
- * Caches the initialized agent for subsequent calls.
47
- */
48
- class LazyAgent {
49
- config;
50
- agent = null;
51
- initPromise = null;
52
- lastError = null;
53
- constructor(config) {
54
- this.config = config;
55
- }
56
- /**
57
- * Get the agent's DID.
58
- *
59
- * Triggers initialization if not already initialized.
60
- * Throws if initialization fails.
61
- */
62
- get did() {
63
- if (!this.agent) {
64
- throw new Error('Agent not initialized. Call send/receive first or await ensureInitialized().');
65
- }
66
- return this.agent.did;
67
- }
68
- /**
69
- * Check if agent is ready (initialized).
70
- */
71
- isReady() {
72
- return this.agent !== null;
73
- }
74
- /**
75
- * Get last initialization error (if any).
76
- */
77
- getLastError() {
78
- return this.lastError;
79
- }
80
- /**
81
- * Ensure agent is initialized.
82
- *
83
- * Can be called explicitly to trigger init before first send/receive.
84
- * Safe to call multiple times — subsequent calls return cached agent.
85
- *
86
- * @returns Agent instance or error
87
- */
88
- async ensureInitialized() {
89
- // If already initialized, return cached agent
90
- if (this.agent) {
91
- return (0, shared_1.ok)(this.agent);
92
- }
93
- // If initialization is in progress, wait for it
94
- if (this.initPromise) {
95
- return this.initPromise;
96
- }
97
- // Start initialization
98
- this.initPromise = this.initialize();
99
- const result = await this.initPromise;
100
- // Clear promise after completion (success or failure)
101
- this.initPromise = null;
102
- if (result.ok) {
103
- this.agent = result.value;
104
- this.lastError = null;
105
- }
106
- else {
107
- this.lastError = {
108
- code: LazyAgentErrorCode.INIT_FAILED,
109
- message: `Agent initialization failed: ${result.error}`,
110
- cause: result.error,
111
- };
112
- }
113
- return result;
114
- }
115
- /**
116
- * Internal initialization logic.
117
- *
118
- * 1. Auto-accept invite (if XBIND_INVITE_CODE set)
119
- * 2. Create agent identity
120
- * 3. Configure registry and transport
121
- * 4. Return initialized agent
122
- */
123
- async initialize() {
124
- // Step 1: Attempt auto-accept if invite code is available
125
- const inviteCode = this.config.inviteCode ?? this.getEnv('XBIND_INVITE_CODE');
126
- let registry = this.config.registry;
127
- let transport = this.config.transport;
128
- const endpoint = this.config.endpoint ?? this.getEnv('XBIND_ENDPOINT') ?? '';
129
- if (inviteCode) {
130
- // Create temporary agent to get DID and public key for invite acceptance
131
- const tempAgentResult = await agent_js_1.Agent.create({
132
- name: this.config.name,
133
- registry: new trust_registry_js_1.MemoryTrustRegistry(),
134
- transport: new transport_js_1.HttpsTransportAdapter({ baseUrl: 'http://localhost' }), // Placeholder
135
- postQuantumSig: this.config.postQuantumSig,
136
- xchange: this.config.xchange,
137
- });
138
- if (!tempAgentResult.ok) {
139
- return (0, shared_1.err)(tempAgentResult.error);
140
- }
141
- const tempAgent = tempAgentResult.value;
142
- // Export public key for invite acceptance
143
- const seedsResult = await tempAgent.exportSeeds();
144
- if (!seedsResult.ok) {
145
- return (0, shared_1.err)('IDENTITY_FAILED');
146
- }
147
- const publicKey = (0, crypto_utils_js_1.toBase64)(tempAgent.identity.rawPublicKey);
148
- const x25519PublicKey = tempAgent.identity.rawX25519PublicKey
149
- ? (0, crypto_utils_js_1.toBase64)(tempAgent.identity.rawX25519PublicKey)
150
- : undefined;
151
- // Auto-accept invite
152
- const acceptResult = await (0, auto_accept_js_1.autoAcceptInvite)({
153
- inviteCode,
154
- enabled: true,
155
- registry: this.config.autoAccept?.registry,
156
- inviteApiUrl: this.config.autoAccept?.inviteApiUrl,
157
- }, {
158
- name: this.config.name,
159
- did: tempAgent.did,
160
- endpoint,
161
- publicKey,
162
- x25519PublicKey,
163
- });
164
- if (!acceptResult.ok) {
165
- this.lastError = {
166
- code: LazyAgentErrorCode.AUTO_ACCEPT_FAILED,
167
- message: acceptResult.error.message,
168
- hint: acceptResult.error.hint,
169
- cause: acceptResult.error,
170
- };
171
- // Non-fatal: continue with temp agent even if auto-accept fails
172
- // (registry may already be configured)
173
- }
174
- else {
175
- // Use auto-configured registry if not provided
176
- if (!registry && acceptResult.value.registryAutoconfigured) {
177
- // Registry was already configured by autoAcceptInvite
178
- registry = this.config.autoAccept?.registry ?? new trust_registry_js_1.MemoryTrustRegistry();
179
- }
180
- // Use inviter's endpoint as default transport if not provided
181
- if (!transport) {
182
- transport = new transport_js_1.HttpsTransportAdapter({
183
- baseUrl: acceptResult.value.from.endpoint,
184
- });
185
- }
186
- }
187
- // Return temp agent as initialized agent
188
- this.agent = tempAgent;
189
- return (0, shared_1.ok)(tempAgent);
190
- }
191
- // Step 2: No invite code — create agent normally
192
- const defaultRegistry = registry ?? new trust_registry_js_1.MemoryTrustRegistry();
193
- const defaultTransport = transport ?? new transport_js_1.HttpsTransportAdapter({
194
- baseUrl: endpoint || 'http://localhost',
195
- });
196
- const agentResult = await agent_js_1.Agent.create({
197
- name: this.config.name,
198
- registry: defaultRegistry,
199
- transport: defaultTransport,
200
- postQuantumSig: this.config.postQuantumSig,
201
- xchange: this.config.xchange,
202
- });
203
- if (!agentResult.ok) {
204
- this.lastError = {
205
- code: LazyAgentErrorCode.AGENT_CREATION_FAILED,
206
- message: `Agent creation failed: ${agentResult.error}`,
207
- cause: agentResult.error,
208
- };
209
- return agentResult;
210
- }
211
- this.agent = agentResult.value;
212
- return (0, shared_1.ok)(this.agent);
213
- }
214
- /**
215
- * Send a message (proxied to underlying agent).
216
- *
217
- * Automatically initializes agent on first call.
218
- */
219
- async send(opts) {
220
- const agentResult = await this.ensureInitialized();
221
- if (!agentResult.ok) {
222
- return agentResult;
223
- }
224
- return agentResult.value.send(opts);
225
- }
226
- /**
227
- * Receive a message (proxied to underlying agent).
228
- *
229
- * Automatically initializes agent on first call.
230
- */
231
- async receive(envelope, opts) {
232
- const agentResult = await this.ensureInitialized();
233
- if (!agentResult.ok) {
234
- return (0, shared_1.err)(agentResult.error);
235
- }
236
- return agentResult.value.receive(envelope, opts);
237
- }
238
- /**
239
- * Receive a split-channel share (proxied to underlying agent).
240
- *
241
- * Automatically initializes agent on first call.
242
- */
243
- async receiveSplitShare(envelope) {
244
- const agentResult = await this.ensureInitialized();
245
- if (!agentResult.ok) {
246
- return (0, shared_1.err)(agentResult.error);
247
- }
248
- return agentResult.value.receiveSplitShare(envelope);
249
- }
250
- /**
251
- * Get environment variable value.
252
- *
253
- * @param key - Environment variable name
254
- * @returns Environment variable value or empty string
255
- */
256
- getEnv(key) {
257
- // SAFETY: Check for Node.js environment before accessing process
258
- if (typeof process !== 'undefined' && typeof process.env !== 'undefined') {
259
- return process.env[key] ?? '';
260
- }
261
- return '';
262
- }
263
- /**
264
- * Export the underlying agent (for advanced use cases).
265
- *
266
- * Throws if agent is not initialized.
267
- */
268
- getAgent() {
269
- if (!this.agent) {
270
- throw new Error('Agent not initialized. Call send/receive first or await ensureInitialized().');
271
- }
272
- return this.agent;
273
- }
274
- }
275
- exports.LazyAgent = LazyAgent;
276
- /**
277
- * Create a lazy agent that initializes on first use.
278
- *
279
- * Extension method for Agent class. Adds `Agent.lazy()` factory.
280
- *
281
- * @param config - Lazy agent configuration
282
- * @returns Lazy agent wrapper
283
- *
284
- * @example
285
- * ```ts
286
- * // Environment: XBIND_INVITE_CODE=XBD-abc123
287
- *
288
- * const agent = createLazyAgent({ name: 'my-service' });
289
- *
290
- * // No initialization yet — happens on first send:
291
- * await agent.send({
292
- * to: 'did:key:z6Mk...',
293
- * payload: { action: 'test' },
294
- * scope: 'test',
295
- * });
296
- * ```
297
- */
298
- function createLazyAgent(config) {
299
- return new LazyAgent(config);
300
- }
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){void 0===i&&(i=r),e[i]=t[r]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(null!=t)for(var i=e(t),n=0;n<i.length;n++)"default"!==i[n]&&__createBinding(r,t,i[n]);return __setModuleDefault(r,t),r}}();Object.defineProperty(exports,"__esModule",{value:!0}),exports.LazyAgent=exports.LazyAgentErrorCode=void 0,exports.createLazyAgent=createLazyAgent;const shared_1=require("../_deps/shared/index.js"),auto_accept_js_1=require("./auto-accept.js"),trust_registry_js_1=require("./trust-registry.js"),transport_js_1=require("./transport.js"),crypto_utils_js_1=require("./crypto-utils.js");var LazyAgentErrorCode;!function(e){e.INIT_FAILED="LAZY_AGENT_INIT_FAILED",e.AUTO_ACCEPT_FAILED="LAZY_AGENT_AUTO_ACCEPT_FAILED",e.AGENT_CREATION_FAILED="LAZY_AGENT_AGENT_CREATION_FAILED"}(LazyAgentErrorCode||(exports.LazyAgentErrorCode=LazyAgentErrorCode={}));class LazyAgent{config;agent=null;initPromise=null;lastError=null;_did;_identity;constructor(e,t){this.config=e,this._identity=t,this._did=t.did}get did(){return this._did}isReady(){return null!==this.agent}getLastError(){return this.lastError}async ensureInitialized(){if(this.agent)return(0,shared_1.ok)(this.agent);if(this.initPromise)return this.initPromise;this.initPromise=this.initialize();const e=await this.initPromise;return this.initPromise=null,e.ok?(this.agent=e.value,this.lastError=null):this.lastError={code:LazyAgentErrorCode.INIT_FAILED,message:`Agent initialization failed: ${e.error}`,cause:e.error},e}async initialize(){const e=this.config.inviteCode??this.getEnv("XBIND_INVITE_CODE");let t=this.config.registry,r=this.config.transport;const i=this.config.endpoint??this.getEnv("XBIND_ENDPOINT")??"";if(e){const n=(0,crypto_utils_js_1.toBase64)(this._identity.rawPublicKey),s=this._identity.rawX25519PublicKey?(0,crypto_utils_js_1.toBase64)(this._identity.rawX25519PublicKey):void 0,o=await(0,auto_accept_js_1.autoAcceptInvite)({inviteCode:e,enabled:!0,registry:this.config.autoAccept?.registry,inviteApiUrl:this.config.autoAccept?.inviteApiUrl},{name:this.config.name,did:this._identity.did,endpoint:i,publicKey:n,x25519PublicKey:s});o.ok?(!t&&o.value.registryAutoconfigured&&(t=this.config.autoAccept?.registry??new trust_registry_js_1.MemoryTrustRegistry),r||(r=new transport_js_1.HttpsTransportAdapter({baseUrl:o.value.from.endpoint}))):this.lastError={code:LazyAgentErrorCode.AUTO_ACCEPT_FAILED,message:o.error.message,hint:o.error.hint,cause:o.error}}const n=t??new trust_registry_js_1.MemoryTrustRegistry,s=r??new transport_js_1.HttpsTransportAdapter({baseUrl:i||"http://localhost"}),o=await n.register(this._identity.did,this._identity.rawPublicKey,this.config.name,void 0,this._identity.rawX25519PublicKey,this._identity.mlKemPublicKey,this._identity.mlDsaPublicKey,this.config.xchange??!1);if(!o.ok){this.lastError={code:LazyAgentErrorCode.AGENT_CREATION_FAILED,message:`Agent registration failed: ${o.error}`,cause:o.error};const e="ALREADY_REGISTERED"===o.error?"REGISTRATION_FAILED:ALREADY_REGISTERED":"NETWORK_ERROR"===o.error?"REGISTRATION_FAILED:NETWORK_ERROR":"REGISTRATION_FAILED";return(0,shared_1.err)(e)}const{MemoryNonceStore:a}=await Promise.resolve().then(()=>__importStar(require("./nonce-store.js"))),{DefaultSecurityPolicy:u}=await Promise.resolve().then(()=>__importStar(require("./security-policy.js"))),c=new a,_=Array.isArray(s)?s:[s],d=new(0,(await Promise.resolve().then(()=>__importStar(require("./agent.js")))).Agent)(this._identity,this.config.name,n,_,c,3e4,new u,void 0);return this.agent=d,(0,shared_1.ok)(d)}async send(e){const t=await this.ensureInitialized();return t.ok?t.value.send(e):t}async receive(e,t){const r=await this.ensureInitialized();return r.ok?r.value.receive(e,t):(0,shared_1.err)(r.error)}async receiveSplitShare(e){const t=await this.ensureInitialized();return t.ok?t.value.receiveSplitShare(e):(0,shared_1.err)(t.error)}getEnv(e){return"undefined"!=typeof process&&void 0!==process.env?process.env[e]??"":""}getAgent(){if(!this.agent)throw new Error("Agent not initialized. Call send/receive first or await ensureInitialized().");return this.agent}}async function createLazyAgent(e){const{generateIdentity:t}=await Promise.resolve().then(()=>__importStar(require("./identity.js"))),r=await t({postQuantumSig:e.postQuantumSig});if(!r.ok)throw new Error(`Failed to generate identity: ${r.error}`);return new LazyAgent(e,r.value)}exports.LazyAgent=LazyAgent;
@@ -1,291 +1 @@
1
- "use strict";
2
- /**
3
- * @module logger
4
- * Structured logging for debugging with context fields and sensitive data redaction
5
- *
6
- * Provides structured logging with multiple log levels, context tracking,
7
- * and automatic redaction of sensitive information like DIDs, keys, and tokens.
8
- *
9
- * Usage:
10
- * ```typescript
11
- * import { createLogger } from '@private.me/xbind';
12
- *
13
- * const logger = createLogger('agent-gateway');
14
- *
15
- * // Basic logging
16
- * logger.info('Agent initialized', { did: 'did:key:z6Mk...' });
17
- *
18
- * // With context
19
- * logger.debug('Processing message', {
20
- * nonce: '12345',
21
- * scope: 'billing',
22
- * encrypted: true
23
- * });
24
- *
25
- * // Errors
26
- * logger.error('Authentication failed', { code: 'AUTH_FAILED' }, error);
27
- * ```
28
- */
29
- Object.defineProperty(exports, "__esModule", { value: true });
30
- exports.logger = exports.LogLevel = void 0;
31
- exports.createLogger = createLogger;
32
- exports.getGlobalLogger = getGlobalLogger;
33
- exports.setGlobalLogger = setGlobalLogger;
34
- /**
35
- * Log level enumeration
36
- */
37
- var LogLevel;
38
- (function (LogLevel) {
39
- LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
40
- LogLevel[LogLevel["INFO"] = 1] = "INFO";
41
- LogLevel[LogLevel["WARN"] = 2] = "WARN";
42
- LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
43
- LogLevel[LogLevel["SILENT"] = 4] = "SILENT";
44
- })(LogLevel || (exports.LogLevel = LogLevel = {}));
45
- /**
46
- * Patterns for detecting sensitive data
47
- */
48
- const SENSITIVE_PATTERNS = {
49
- // DIDs: did:key:*, did:web:*, etc.
50
- did: /^did:[a-zA-Z0-9]+:/,
51
- // Nonces: typically hex strings or UUIDs (32+ hex chars or UUID format)
52
- 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}$/,
53
- // Keys: base64 or hex strings that look like cryptographic keys (40+ chars)
54
- key: /^[a-zA-Z0-9+/]{40,}={0,2}$|^[a-f0-9]{64,}$/,
55
- // Tokens: JWT-like or similar
56
- token: /^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/,
57
- // Email addresses
58
- email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
59
- // Phone numbers (at least 10 digits with optional country code)
60
- phone: /^\+?[1-9]\d{9,14}$/,
61
- // API keys (common prefixes like sk_, pk_, ak_)
62
- apiKey: /^(sk_|pk_|ak_)[a-zA-Z0-9_-]{20,}$/,
63
- };
64
- /**
65
- * Sensitive field names that should always be redacted
66
- */
67
- const SENSITIVE_FIELD_NAMES = new Set([
68
- 'password',
69
- 'secret',
70
- 'apiKey',
71
- 'api_key',
72
- 'privateKey',
73
- 'private_key',
74
- 'accessToken',
75
- 'access_token',
76
- 'refreshToken',
77
- 'refresh_token',
78
- 'masterKey',
79
- 'master_key',
80
- 'encryptionKey',
81
- 'encryption_key',
82
- 'authToken',
83
- 'auth_token',
84
- 'sessionToken',
85
- 'session_token',
86
- 'jwtToken',
87
- 'jwt_token',
88
- 'did',
89
- 'nonce',
90
- 'key',
91
- 'token',
92
- 'seed',
93
- 'entropy',
94
- ]);
95
- /**
96
- * Detect if a value is sensitive based on field name or content
97
- */
98
- function isSensitive(fieldName, value) {
99
- if (typeof value !== 'string')
100
- return false;
101
- // Check field name
102
- const normalizedName = fieldName.toLowerCase();
103
- if (SENSITIVE_FIELD_NAMES.has(normalizedName)) {
104
- return true;
105
- }
106
- // Check content patterns
107
- for (const [patternName, pattern] of Object.entries(SENSITIVE_PATTERNS)) {
108
- if (normalizedName.includes(patternName) && pattern.test(value)) {
109
- return true;
110
- }
111
- }
112
- return false;
113
- }
114
- /**
115
- * Redact sensitive data from a value
116
- */
117
- function redactValue(value) {
118
- if (value.length <= 4) {
119
- return '*'.repeat(Math.max(1, value.length));
120
- }
121
- // Show first 4 chars + last 2 chars with redaction in between
122
- const shown = Math.min(4, Math.ceil(value.length / 4));
123
- return value.substring(0, shown) + '*'.repeat(Math.max(3, value.length - shown - 2)) + value.substring(value.length - 2);
124
- }
125
- /**
126
- * Recursively redact sensitive data from context
127
- */
128
- function parseContextForLogging(context) {
129
- const redacted = [];
130
- const processed = {};
131
- for (const [key, value] of Object.entries(context)) {
132
- if (value === null || value === undefined) {
133
- processed[key] = value;
134
- continue;
135
- }
136
- if (typeof value === 'object') {
137
- if (value instanceof Error) {
138
- // Don't redact error fields - they're diagnostic
139
- processed[key] = {
140
- name: value.name,
141
- message: value.message,
142
- };
143
- }
144
- else if (value instanceof Map || value instanceof Set) {
145
- processed[key] = `[${value.constructor.name}]`;
146
- }
147
- else if (Array.isArray(value)) {
148
- processed[key] = value.map(v => {
149
- if (typeof v === 'string' && isSensitive(key, v)) {
150
- redacted.push(key);
151
- return redactValue(v);
152
- }
153
- return v;
154
- });
155
- }
156
- else {
157
- // Recursively process objects
158
- const nested = parseContextForLogging(value);
159
- processed[key] = nested.context;
160
- if (nested.redacted.length > 0) {
161
- redacted.push(...nested.redacted.map(r => `${key}.${r}`));
162
- }
163
- }
164
- }
165
- else if (typeof value === 'string') {
166
- if (isSensitive(key, value)) {
167
- redacted.push(key);
168
- processed[key] = redactValue(value);
169
- }
170
- else {
171
- processed[key] = value;
172
- }
173
- }
174
- else if (typeof value === 'boolean' || typeof value === 'number') {
175
- processed[key] = value;
176
- }
177
- else {
178
- // Other types (functions, symbols, etc.)
179
- processed[key] = `[${typeof value}]`;
180
- }
181
- }
182
- return { redacted, context: processed };
183
- }
184
- /**
185
- * Format log entry as JSON string
186
- */
187
- function formatLogEntry(level, message, context, timestamp, redactedFields) {
188
- const entry = {
189
- timestamp,
190
- level,
191
- message,
192
- };
193
- if (context && Object.keys(context).length > 0) {
194
- entry.context = context;
195
- }
196
- if (redactedFields.length > 0) {
197
- entry.redacted = redactedFields;
198
- }
199
- return JSON.stringify(entry);
200
- }
201
- /**
202
- * Create a logger instance with optional name
203
- */
204
- function createLogger(name = 'default') {
205
- let currentLevel = LogLevel.INFO;
206
- // Support XAIL_LOG_LEVEL environment variable
207
- const envLevel = process.env['XAIL_LOG_LEVEL']?.toUpperCase();
208
- if (envLevel && envLevel in LogLevel) {
209
- currentLevel = LogLevel[envLevel];
210
- }
211
- const logger = {
212
- debug(message, context) {
213
- if (!this.isEnabled(LogLevel.DEBUG))
214
- return;
215
- const timestamp = new Date().toISOString();
216
- const parsed = context ? parseContextForLogging(context) : { redacted: [], context: {} };
217
- const entry = formatLogEntry('DEBUG', message, parsed.context, timestamp, parsed.redacted);
218
- console.debug(`[${name}] ${entry}`);
219
- },
220
- info(message, context) {
221
- if (!this.isEnabled(LogLevel.INFO))
222
- return;
223
- const timestamp = new Date().toISOString();
224
- const parsed = context ? parseContextForLogging(context) : { redacted: [], context: {} };
225
- const entry = formatLogEntry('INFO', message, parsed.context, timestamp, parsed.redacted);
226
- console.log(`[${name}] ${entry}`);
227
- },
228
- warn(message, context) {
229
- if (!this.isEnabled(LogLevel.WARN))
230
- return;
231
- const timestamp = new Date().toISOString();
232
- const parsed = context ? parseContextForLogging(context) : { redacted: [], context: {} };
233
- const entry = formatLogEntry('WARN', message, parsed.context, timestamp, parsed.redacted);
234
- console.warn(`[${name}] ${entry}`);
235
- },
236
- error(message, context, error) {
237
- if (!this.isEnabled(LogLevel.ERROR))
238
- return;
239
- const timestamp = new Date().toISOString();
240
- const contextWithError = context ? { ...context } : {};
241
- if (error instanceof Error) {
242
- contextWithError.error = {
243
- name: error.name,
244
- message: error.message,
245
- stack: error.stack,
246
- };
247
- }
248
- else if (error !== undefined) {
249
- contextWithError.error = error;
250
- }
251
- const parsed = Object.keys(contextWithError).length > 0
252
- ? parseContextForLogging(contextWithError)
253
- : { redacted: [], context: {} };
254
- const entry = formatLogEntry('ERROR', message, parsed.context, timestamp, parsed.redacted);
255
- console.error(`[${name}] ${entry}`);
256
- },
257
- setLevel(level) {
258
- currentLevel = level;
259
- },
260
- getLevel() {
261
- return currentLevel;
262
- },
263
- isEnabled(level) {
264
- return level >= currentLevel;
265
- },
266
- };
267
- return logger;
268
- }
269
- /**
270
- * Global logger instance (shared across application)
271
- */
272
- let globalLogger = null;
273
- /**
274
- * Get or create global logger
275
- */
276
- function getGlobalLogger() {
277
- if (!globalLogger) {
278
- globalLogger = createLogger('xbind');
279
- }
280
- return globalLogger;
281
- }
282
- /**
283
- * Set global logger instance
284
- */
285
- function setGlobalLogger(logger) {
286
- globalLogger = logger;
287
- }
288
- /**
289
- * Default export for convenience
290
- */
291
- exports.logger = getGlobalLogger();
1
+ "use strict";var LogLevel;Object.defineProperty(exports,"__esModule",{value:!0}),exports.logger=exports.LogLevel=void 0,exports.createLogger=createLogger,exports.getGlobalLogger=getGlobalLogger,exports.setGlobalLogger=setGlobalLogger,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||(exports.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 s={timestamp:n,level:e,message:t};return o&&Object.keys(o).length>0&&(s.context=o),r.length>0&&(s.redacted=r),JSON.stringify(s)}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:{}},s=formatLogEntry("DEBUG",t,r.context,n,r.redacted);console.debug(`[${e}] ${s}`)},info(t,o){if(!this.isEnabled(LogLevel.INFO))return;const n=(new Date).toISOString(),r=o?parseContextForLogging(o):{redacted:[],context:{}},s=formatLogEntry("INFO",t,r.context,n,r.redacted);console.log(`[${e}] ${s}`)},warn(t,o){if(!this.isEnabled(LogLevel.WARN))return;const n=(new Date).toISOString(),r=o?parseContextForLogging(o):{redacted:[],context:{}},s=formatLogEntry("WARN",t,r.context,n,r.redacted);console.warn(`[${e}] ${s}`)},error(t,o,n){if(!this.isEnabled(LogLevel.ERROR))return;const r=(new Date).toISOString(),s=o?{...o}:{};n instanceof Error?s.error={name:n.name,message:n.message,stack:n.stack}:void 0!==n&&(s.error=n);const a=Object.keys(s).length>0?parseContextForLogging(s):{redacted:[],context:{}},g=formatLogEntry("ERROR",t,a.context,r,a.redacted);console.error(`[${e}] ${g}`)},setLevel(e){t=e},getLevel:()=>t,isEnabled:e=>e>=t}}let globalLogger=null;function getGlobalLogger(){return globalLogger||(globalLogger=createLogger("xbind")),globalLogger}function setGlobalLogger(e){globalLogger=e}exports.logger=getGlobalLogger();
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.LoopbackTransport=void 0;const shared_1=require("../_deps/shared/index.js");class LoopbackTransport{sent=[];handlers=[];async send(s,e){this.sent.push({envelope:s,to:e});for(const e of this.handlers)e(s);return(0,shared_1.ok)(void 0)}onReceive(s){this.handlers.push(s)}dispose(){this.handlers=[]}}exports.LoopbackTransport=LoopbackTransport;