@private.me/xbind 3.0.1 → 3.0.2

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