@private.me/xbind 3.0.0 → 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 (217) hide show
  1. package/README.md +55 -7
  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.d.ts +84 -0
  174. package/dist-standalone/plugins/logging.js +163 -0
  175. package/dist-standalone/plugins/metrics.d.ts +111 -0
  176. package/dist-standalone/plugins/metrics.js +176 -0
  177. package/dist-standalone/plugins/validation.d.ts +104 -0
  178. package/dist-standalone/plugins/validation.js +297 -0
  179. package/dist-standalone/policy.js +315 -1
  180. package/dist-standalone/progress-callbacks.js +576 -1
  181. package/dist-standalone/redis-nonce-store.js +72 -1
  182. package/dist-standalone/registry-middleware.js +47 -1
  183. package/dist-standalone/retry-strategies.js +534 -1
  184. package/dist-standalone/retry-transport.js +98 -1
  185. package/dist-standalone/runtime/browser.d.ts +311 -0
  186. package/dist-standalone/runtime/browser.js +516 -0
  187. package/dist-standalone/runtime/edge.d.ts +282 -0
  188. package/dist-standalone/runtime/edge.js +511 -0
  189. package/dist-standalone/runtime/react-native.d.ts +157 -0
  190. package/dist-standalone/runtime/react-native.js +383 -0
  191. package/dist-standalone/security-policy.js +239 -1
  192. package/dist-standalone/serialization.js +1031 -1
  193. package/dist-standalone/split-channel.js +219 -1
  194. package/dist-standalone/subscription-proof.js +224 -1
  195. package/dist-standalone/succession.js +142 -1
  196. package/dist-standalone/timeouts.js +398 -1
  197. package/dist-standalone/trace-context.js +414 -1
  198. package/dist-standalone/trace-spans.js +488 -1
  199. package/dist-standalone/transport.js +59 -1
  200. package/dist-standalone/trust-registry.js +950 -1
  201. package/dist-standalone/types/error-response.d.ts +209 -0
  202. package/dist-standalone/types/error-response.js +52 -0
  203. package/dist-standalone/vault-auth.js +174 -1
  204. package/dist-standalone/vault-store-loader.js +187 -1
  205. package/dist-standalone/verify.js +16 -1
  206. package/dist-standalone/version-info.js +530 -1
  207. package/dist-standalone/xfetch.js +335 -1
  208. package/package.json +4 -10
  209. package/share1.dat +0 -0
  210. package/dist-standalone/_deps/mldsa-wasm/LICENSE +0 -24
  211. package/dist-standalone/_deps/mldsa-wasm/package.json +0 -46
  212. package/dist-standalone/_deps/shared/cjs/package.json +0 -1
  213. package/dist-standalone/_deps/ux-helpers/cjs/package.json +0 -1
  214. package/dist-standalone/_deps/xchange/cjs/package.json +0 -1
  215. package/dist-standalone/_deps/xregistry/cjs/package.json +0 -1
  216. package/dist-standalone/cjs/package.json +0 -3
  217. package/dist-standalone/package.json +0 -10
@@ -1 +1,300 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.LazyAgent=exports.LazyAgentErrorCode=void 0,exports.createLazyAgent=createLazyAgent;const shared_1=require("../_deps/shared/index.js"),agent_js_1=require("./agent.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;constructor(e){this.config=e}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(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 s=await agent_js_1.Agent.create({name:this.config.name,registry:new trust_registry_js_1.MemoryTrustRegistry,transport:new transport_js_1.HttpsTransportAdapter({baseUrl:"http://localhost"}),postQuantumSig:this.config.postQuantumSig,xchange:this.config.xchange});if(!s.ok)return(0,shared_1.err)(s.error);const n=s.value;if(!(await n.exportSeeds()).ok)return(0,shared_1.err)("IDENTITY_FAILED");const a=(0,crypto_utils_js_1.toBase64)(n.identity.rawPublicKey),o=n.identity.rawX25519PublicKey?(0,crypto_utils_js_1.toBase64)(n.identity.rawX25519PublicKey):void 0,c=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:n.did,endpoint:i,publicKey:a,x25519PublicKey:o});return c.ok?(!t&&c.value.registryAutoconfigured&&(t=this.config.autoAccept?.registry??new trust_registry_js_1.MemoryTrustRegistry),r||(r=new transport_js_1.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=n,(0,shared_1.ok)(n)}const s=t??new trust_registry_js_1.MemoryTrustRegistry,n=r??new transport_js_1.HttpsTransportAdapter({baseUrl:i||"http://localhost"}),a=await agent_js_1.Agent.create({name:this.config.name,registry:s,transport:n,postQuantumSig:this.config.postQuantumSig,xchange:this.config.xchange});return a.ok?(this.agent=a.value,(0,shared_1.ok)(this.agent)):(this.lastError={code:LazyAgentErrorCode.AGENT_CREATION_FAILED,message:`Agent creation failed: ${a.error}`,cause:a.error},a)}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}}function createLazyAgent(e){return new LazyAgent(e)}exports.LazyAgent=LazyAgent;
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 +1,291 @@
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();
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();