@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
@@ -76,12 +76,14 @@ export declare class LazyAgent {
76
76
  private agent;
77
77
  private initPromise;
78
78
  private lastError;
79
- constructor(config: LazyAgentConfig);
79
+ private _did;
80
+ private _identity;
81
+ constructor(config: LazyAgentConfig, identity: import('./identity.js').AgentIdentity);
80
82
  /**
81
83
  * Get the agent's DID.
82
84
  *
83
- * Triggers initialization if not already initialized.
84
- * Throws if initialization fails.
85
+ * Returns the pre-generated DID immediately (no initialization required).
86
+ * This allows accessing `agent.did` right after `Agent.lazy()` returns.
85
87
  */
86
88
  get did(): string;
87
89
  /**
@@ -154,9 +156,12 @@ export declare class LazyAgent {
154
156
  * ```ts
155
157
  * // Environment: XBIND_INVITE_CODE=XBD-abc123
156
158
  *
157
- * const agent = createLazyAgent({ name: 'my-service' });
159
+ * const agent = await Agent.lazy({ name: 'my-service' });
158
160
  *
159
- * // No initialization yet — happens on first send:
161
+ * // DID is available immediately:
162
+ * console.log(agent.did); // did:key:z6Mk...
163
+ *
164
+ * // Full initialization happens on first send:
160
165
  * await agent.send({
161
166
  * to: 'did:key:z6Mk...',
162
167
  * payload: { action: 'test' },
@@ -164,4 +169,4 @@ export declare class LazyAgent {
164
169
  * });
165
170
  * ```
166
171
  */
167
- export declare function createLazyAgent(config: LazyAgentConfig): LazyAgent;
172
+ export declare function createLazyAgent(config: LazyAgentConfig): Promise<LazyAgent>;
@@ -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 './crypto-utils.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{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;_did;_identity;constructor(t,e){this.config=t,this._identity=e,this._did=e.did}get did(){return this._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,i=this.config.transport;const r=this.config.endpoint??this.getEnv("XBIND_ENDPOINT")??"";if(t){const n=toBase64(this._identity.rawPublicKey),s=this._identity.rawX25519PublicKey?toBase64(this._identity.rawX25519PublicKey):void 0,o=await autoAcceptInvite({inviteCode:t,enabled:!0,registry:this.config.autoAccept?.registry,inviteApiUrl:this.config.autoAccept?.inviteApiUrl},{name:this.config.name,did:this._identity.did,endpoint:r,publicKey:n,x25519PublicKey:s});o.ok?(!e&&o.value.registryAutoconfigured&&(e=this.config.autoAccept?.registry??new MemoryTrustRegistry),i||(i=new 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=e??new MemoryTrustRegistry,s=i??new HttpsTransportAdapter({baseUrl:r||"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 t="ALREADY_REGISTERED"===o.error?"REGISTRATION_FAILED:ALREADY_REGISTERED":"NETWORK_ERROR"===o.error?"REGISTRATION_FAILED:NETWORK_ERROR":"REGISTRATION_FAILED";return err(t)}const{MemoryNonceStore:a}=await import("./nonce-store.js"),{DefaultSecurityPolicy:c}=await import("./security-policy.js"),d=new a,u=Array.isArray(s)?s:[s],l=new(0,(await import("./agent.js")).Agent)(this._identity,this.config.name,n,u,d,3e4,new c,void 0);return this.agent=l,ok(l)}async send(t){const e=await this.ensureInitialized();return e.ok?e.value.send(t):e}async receive(t,e){const i=await this.ensureInitialized();return i.ok?i.value.receive(t,e):err(i.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 async function createLazyAgent(t){const{generateIdentity:e}=await import("./identity.js"),i=await e({postQuantumSig:t.postQuantumSig});if(!i.ok)throw new Error(`Failed to generate identity: ${i.error}`);return new LazyAgent(t,i.value)}
@@ -1,285 +1 @@
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 var LogLevel;
32
- (function (LogLevel) {
33
- LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
34
- LogLevel[LogLevel["INFO"] = 1] = "INFO";
35
- LogLevel[LogLevel["WARN"] = 2] = "WARN";
36
- LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
37
- LogLevel[LogLevel["SILENT"] = 4] = "SILENT";
38
- })(LogLevel || (LogLevel = {}));
39
- /**
40
- * Patterns for detecting sensitive data
41
- */
42
- const SENSITIVE_PATTERNS = {
43
- // DIDs: did:key:*, did:web:*, etc.
44
- did: /^did:[a-zA-Z0-9]+:/,
45
- // Nonces: typically hex strings or UUIDs (32+ hex chars or UUID format)
46
- 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}$/,
47
- // Keys: base64 or hex strings that look like cryptographic keys (40+ chars)
48
- key: /^[a-zA-Z0-9+/]{40,}={0,2}$|^[a-f0-9]{64,}$/,
49
- // Tokens: JWT-like or similar
50
- token: /^eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/,
51
- // Email addresses
52
- email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
53
- // Phone numbers (at least 10 digits with optional country code)
54
- phone: /^\+?[1-9]\d{9,14}$/,
55
- // API keys (common prefixes like sk_, pk_, ak_)
56
- apiKey: /^(sk_|pk_|ak_)[a-zA-Z0-9_-]{20,}$/,
57
- };
58
- /**
59
- * Sensitive field names that should always be redacted
60
- */
61
- const SENSITIVE_FIELD_NAMES = new Set([
62
- 'password',
63
- 'secret',
64
- 'apiKey',
65
- 'api_key',
66
- 'privateKey',
67
- 'private_key',
68
- 'accessToken',
69
- 'access_token',
70
- 'refreshToken',
71
- 'refresh_token',
72
- 'masterKey',
73
- 'master_key',
74
- 'encryptionKey',
75
- 'encryption_key',
76
- 'authToken',
77
- 'auth_token',
78
- 'sessionToken',
79
- 'session_token',
80
- 'jwtToken',
81
- 'jwt_token',
82
- 'did',
83
- 'nonce',
84
- 'key',
85
- 'token',
86
- 'seed',
87
- 'entropy',
88
- ]);
89
- /**
90
- * Detect if a value is sensitive based on field name or content
91
- */
92
- function isSensitive(fieldName, value) {
93
- if (typeof value !== 'string')
94
- return false;
95
- // Check field name
96
- const normalizedName = fieldName.toLowerCase();
97
- if (SENSITIVE_FIELD_NAMES.has(normalizedName)) {
98
- return true;
99
- }
100
- // Check content patterns
101
- for (const [patternName, pattern] of Object.entries(SENSITIVE_PATTERNS)) {
102
- if (normalizedName.includes(patternName) && pattern.test(value)) {
103
- return true;
104
- }
105
- }
106
- return false;
107
- }
108
- /**
109
- * Redact sensitive data from a value
110
- */
111
- function redactValue(value) {
112
- if (value.length <= 4) {
113
- return '*'.repeat(Math.max(1, value.length));
114
- }
115
- // Show first 4 chars + last 2 chars with redaction in between
116
- const shown = Math.min(4, Math.ceil(value.length / 4));
117
- return value.substring(0, shown) + '*'.repeat(Math.max(3, value.length - shown - 2)) + value.substring(value.length - 2);
118
- }
119
- /**
120
- * Recursively redact sensitive data from context
121
- */
122
- function parseContextForLogging(context) {
123
- const redacted = [];
124
- const processed = {};
125
- for (const [key, value] of Object.entries(context)) {
126
- if (value === null || value === undefined) {
127
- processed[key] = value;
128
- continue;
129
- }
130
- if (typeof value === 'object') {
131
- if (value instanceof Error) {
132
- // Don't redact error fields - they're diagnostic
133
- processed[key] = {
134
- name: value.name,
135
- message: value.message,
136
- };
137
- }
138
- else if (value instanceof Map || value instanceof Set) {
139
- processed[key] = `[${value.constructor.name}]`;
140
- }
141
- else if (Array.isArray(value)) {
142
- processed[key] = value.map(v => {
143
- if (typeof v === 'string' && isSensitive(key, v)) {
144
- redacted.push(key);
145
- return redactValue(v);
146
- }
147
- return v;
148
- });
149
- }
150
- else {
151
- // Recursively process objects
152
- const nested = parseContextForLogging(value);
153
- processed[key] = nested.context;
154
- if (nested.redacted.length > 0) {
155
- redacted.push(...nested.redacted.map(r => `${key}.${r}`));
156
- }
157
- }
158
- }
159
- else if (typeof value === 'string') {
160
- if (isSensitive(key, value)) {
161
- redacted.push(key);
162
- processed[key] = redactValue(value);
163
- }
164
- else {
165
- processed[key] = value;
166
- }
167
- }
168
- else if (typeof value === 'boolean' || typeof value === 'number') {
169
- processed[key] = value;
170
- }
171
- else {
172
- // Other types (functions, symbols, etc.)
173
- processed[key] = `[${typeof value}]`;
174
- }
175
- }
176
- return { redacted, context: processed };
177
- }
178
- /**
179
- * Format log entry as JSON string
180
- */
181
- function formatLogEntry(level, message, context, timestamp, redactedFields) {
182
- const entry = {
183
- timestamp,
184
- level,
185
- message,
186
- };
187
- if (context && Object.keys(context).length > 0) {
188
- entry.context = context;
189
- }
190
- if (redactedFields.length > 0) {
191
- entry.redacted = redactedFields;
192
- }
193
- return JSON.stringify(entry);
194
- }
195
- /**
196
- * Create a logger instance with optional name
197
- */
198
- export function createLogger(name = 'default') {
199
- let currentLevel = LogLevel.INFO;
200
- // Support XAIL_LOG_LEVEL environment variable
201
- const envLevel = process.env['XAIL_LOG_LEVEL']?.toUpperCase();
202
- if (envLevel && envLevel in LogLevel) {
203
- currentLevel = LogLevel[envLevel];
204
- }
205
- const logger = {
206
- debug(message, context) {
207
- if (!this.isEnabled(LogLevel.DEBUG))
208
- return;
209
- const timestamp = new Date().toISOString();
210
- const parsed = context ? parseContextForLogging(context) : { redacted: [], context: {} };
211
- const entry = formatLogEntry('DEBUG', message, parsed.context, timestamp, parsed.redacted);
212
- console.debug(`[${name}] ${entry}`);
213
- },
214
- info(message, context) {
215
- if (!this.isEnabled(LogLevel.INFO))
216
- return;
217
- const timestamp = new Date().toISOString();
218
- const parsed = context ? parseContextForLogging(context) : { redacted: [], context: {} };
219
- const entry = formatLogEntry('INFO', message, parsed.context, timestamp, parsed.redacted);
220
- console.log(`[${name}] ${entry}`);
221
- },
222
- warn(message, context) {
223
- if (!this.isEnabled(LogLevel.WARN))
224
- return;
225
- const timestamp = new Date().toISOString();
226
- const parsed = context ? parseContextForLogging(context) : { redacted: [], context: {} };
227
- const entry = formatLogEntry('WARN', message, parsed.context, timestamp, parsed.redacted);
228
- console.warn(`[${name}] ${entry}`);
229
- },
230
- error(message, context, error) {
231
- if (!this.isEnabled(LogLevel.ERROR))
232
- return;
233
- const timestamp = new Date().toISOString();
234
- const contextWithError = context ? { ...context } : {};
235
- if (error instanceof Error) {
236
- contextWithError.error = {
237
- name: error.name,
238
- message: error.message,
239
- stack: error.stack,
240
- };
241
- }
242
- else if (error !== undefined) {
243
- contextWithError.error = error;
244
- }
245
- const parsed = Object.keys(contextWithError).length > 0
246
- ? parseContextForLogging(contextWithError)
247
- : { redacted: [], context: {} };
248
- const entry = formatLogEntry('ERROR', message, parsed.context, timestamp, parsed.redacted);
249
- console.error(`[${name}] ${entry}`);
250
- },
251
- setLevel(level) {
252
- currentLevel = level;
253
- },
254
- getLevel() {
255
- return currentLevel;
256
- },
257
- isEnabled(level) {
258
- return level >= currentLevel;
259
- },
260
- };
261
- return logger;
262
- }
263
- /**
264
- * Global logger instance (shared across application)
265
- */
266
- let globalLogger = null;
267
- /**
268
- * Get or create global logger
269
- */
270
- export function getGlobalLogger() {
271
- if (!globalLogger) {
272
- globalLogger = createLogger('xbind');
273
- }
274
- return globalLogger;
275
- }
276
- /**
277
- * Set global logger instance
278
- */
279
- export function setGlobalLogger(logger) {
280
- globalLogger = logger;
281
- }
282
- /**
283
- * Default export for convenience
284
- */
285
- export const logger = getGlobalLogger();
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();