@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.
- package/README.md +55 -7
- package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1920 -1
- package/dist-standalone/_deps/shared/cjs/errors.js +729 -1
- package/dist-standalone/_deps/shared/cjs/index.js +463 -1
- package/dist-standalone/_deps/shared/cjs/types.js +315 -1
- package/dist-standalone/_deps/shared/errors.js +244 -1
- package/dist-standalone/_deps/shared/index.js +72 -1
- package/dist-standalone/_deps/shared/types.js +86 -1
- package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
- package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
- package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
- package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
- package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
- package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
- package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
- package/dist-standalone/_deps/ux-helpers/index.js +1 -1
- package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
- package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
- package/dist-standalone/_deps/ux-helpers/search.js +1 -1
- package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
- package/dist-standalone/_deps/xchange/errors.js +1 -1
- package/dist-standalone/_deps/xchange/index.js +1 -1
- package/dist-standalone/_deps/xchange/invite-client.js +1 -1
- package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
- package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
- package/dist-standalone/_deps/xchange/xchange.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
- package/dist-standalone/_deps/xregistry/discovery.js +1 -1
- package/dist-standalone/_deps/xregistry/errors.js +1 -1
- package/dist-standalone/_deps/xregistry/index.js +1 -1
- package/dist-standalone/_deps/xregistry/registry.js +1 -1
- package/dist-standalone/_deps/xregistry/schema.js +1 -1
- package/dist-standalone/_deps/xregistry/types.js +1 -1
- package/dist-standalone/agent-call.js +659 -1
- package/dist-standalone/agent-sdk.js +328 -1
- package/dist-standalone/agent.js +1800 -1
- package/dist-standalone/approval.js +193 -1
- package/dist-standalone/async-iterators.js +382 -1
- package/dist-standalone/auth.js +219 -1
- package/dist-standalone/auto-accept.js +229 -1
- package/dist-standalone/backup-config.js +201 -1
- package/dist-standalone/backup.js +326 -1
- package/dist-standalone/batch-operations.js +388 -1
- package/dist-standalone/cancellation.js +477 -1
- package/dist-standalone/checkpoint.js +186 -1
- package/dist-standalone/circuit-breaker.js +468 -1
- package/dist-standalone/cjs/agent-call.js +701 -1
- package/dist-standalone/cjs/agent-sdk.js +332 -1
- package/dist-standalone/cjs/agent.js +1837 -1
- package/dist-standalone/cjs/approval.js +199 -1
- package/dist-standalone/cjs/async-iterators.js +392 -1
- package/dist-standalone/cjs/auth.js +225 -1
- package/dist-standalone/cjs/auto-accept.js +233 -1
- package/dist-standalone/cjs/backup-config.js +207 -1
- package/dist-standalone/cjs/backup.js +330 -1
- package/dist-standalone/cjs/batch-operations.js +397 -1
- package/dist-standalone/cjs/cancellation.js +490 -1
- package/dist-standalone/cjs/checkpoint.js +193 -1
- package/dist-standalone/cjs/circuit-breaker.js +476 -1
- package/dist-standalone/cjs/cli/init.js +492 -1
- package/dist-standalone/cjs/config-validation.js +522 -1
- package/dist-standalone/cjs/connect.js +312 -1
- package/dist-standalone/cjs/connection-pool.js +506 -1
- package/dist-standalone/cjs/correlation-id.js +339 -1
- package/dist-standalone/cjs/crypto-utils.js +176 -1
- package/dist-standalone/cjs/debug-mode.js +534 -1
- package/dist-standalone/cjs/did-document.js +101 -1
- package/dist-standalone/cjs/did-privateme.js +130 -1
- package/dist-standalone/cjs/did-web.js +201 -1
- package/dist-standalone/cjs/discovery.js +462 -1
- package/dist-standalone/cjs/dual-mode.js +251 -1
- package/dist-standalone/cjs/email-templates.js +313 -1
- package/dist-standalone/cjs/email-transport.js +239 -1
- package/dist-standalone/cjs/envelope.js +538 -1
- package/dist-standalone/cjs/errors.js +913 -1
- package/dist-standalone/cjs/event-emitter.js +461 -1
- package/dist-standalone/cjs/gateway-state.js +55 -1
- package/dist-standalone/cjs/gateway-transport.js +120 -1
- package/dist-standalone/cjs/graceful-degradation.js +403 -1
- package/dist-standalone/cjs/guardrails.js +223 -1
- package/dist-standalone/cjs/health-check.js +336 -1
- package/dist-standalone/cjs/http-compat.js +272 -1
- package/dist-standalone/cjs/http-status-map.js +571 -1
- package/dist-standalone/cjs/identity.js +645 -1
- package/dist-standalone/cjs/index.js +406 -1
- package/dist-standalone/cjs/invitation.js +421 -1
- package/dist-standalone/cjs/invite.js +328 -1
- package/dist-standalone/cjs/key-agreement.js +335 -1
- package/dist-standalone/cjs/lazy-init.js +300 -1
- package/dist-standalone/cjs/logger.js +291 -1
- package/dist-standalone/cjs/mdns-discovery.js +202 -1
- package/dist-standalone/cjs/nonce-store.js +80 -1
- package/dist-standalone/cjs/pairing-manager.js +223 -1
- package/dist-standalone/cjs/plugin-system.js +264 -1
- package/dist-standalone/cjs/plugins/logging.js +168 -1
- package/dist-standalone/cjs/plugins/metrics.js +181 -1
- package/dist-standalone/cjs/plugins/validation.js +302 -1
- package/dist-standalone/cjs/policy.js +320 -1
- package/dist-standalone/cjs/progress-callbacks.js +583 -1
- package/dist-standalone/cjs/redis-nonce-store.js +76 -1
- package/dist-standalone/cjs/registry-middleware.js +50 -1
- package/dist-standalone/cjs/retry-strategies.js +544 -1
- package/dist-standalone/cjs/retry-transport.js +102 -1
- package/dist-standalone/cjs/runtime/browser.js +533 -1
- package/dist-standalone/cjs/runtime/edge.js +526 -1
- package/dist-standalone/cjs/runtime/react-native.js +394 -1
- package/dist-standalone/cjs/security-policy.js +245 -1
- package/dist-standalone/cjs/serialization.js +1040 -1
- package/dist-standalone/cjs/split-channel.js +225 -1
- package/dist-standalone/cjs/subscription-proof.js +230 -1
- package/dist-standalone/cjs/succession.js +148 -1
- package/dist-standalone/cjs/timeouts.js +412 -1
- package/dist-standalone/cjs/trace-context.js +424 -1
- package/dist-standalone/cjs/trace-spans.js +495 -1
- package/dist-standalone/cjs/transport.js +63 -1
- package/dist-standalone/cjs/trust-registry.js +991 -1
- package/dist-standalone/cjs/types/error-response.js +56 -1
- package/dist-standalone/cjs/vault-auth.js +178 -1
- package/dist-standalone/cjs/vault-store-loader.js +194 -1
- package/dist-standalone/cjs/verify.js +25 -1
- package/dist-standalone/cjs/version-info.js +543 -1
- package/dist-standalone/cjs/xfetch.js +340 -1
- package/dist-standalone/cli/init.js +455 -1
- package/dist-standalone/cli/setup.js +514 -1
- package/dist-standalone/cli/types.js +27 -1
- package/dist-standalone/cli/xbind.js +148 -1
- package/dist-standalone/config-validation.js +513 -1
- package/dist-standalone/connect.js +274 -1
- package/dist-standalone/connection-pool.js +500 -1
- package/dist-standalone/correlation-id.js +326 -1
- package/dist-standalone/crypto-utils.js +157 -1
- package/dist-standalone/debug-mode.js +510 -1
- package/dist-standalone/did-document.js +96 -1
- package/dist-standalone/did-privateme.js +121 -1
- package/dist-standalone/did-web.js +196 -1
- package/dist-standalone/discovery.js +458 -1
- package/dist-standalone/dual-mode.js +247 -1
- package/dist-standalone/email-templates.js +309 -1
- package/dist-standalone/email-transport.js +232 -1
- package/dist-standalone/envelope.js +525 -1
- package/dist-standalone/errors.js +896 -1
- package/dist-standalone/event-emitter.js +456 -1
- package/dist-standalone/gateway-state.js +51 -1
- package/dist-standalone/gateway-transport.js +116 -1
- package/dist-standalone/graceful-degradation.js +396 -1
- package/dist-standalone/guardrails.js +216 -1
- package/dist-standalone/health-check.js +332 -1
- package/dist-standalone/http-compat.js +267 -1
- package/dist-standalone/http-status-map.js +561 -1
- package/dist-standalone/identity.js +619 -1
- package/dist-standalone/index.js +78 -1
- package/dist-standalone/invitation.js +415 -1
- package/dist-standalone/invite.js +324 -1
- package/dist-standalone/key-agreement.js +325 -1
- package/dist-standalone/lazy-init.js +295 -1
- package/dist-standalone/logger.js +285 -1
- package/dist-standalone/mdns-discovery.js +195 -1
- package/dist-standalone/nonce-store.js +76 -1
- package/dist-standalone/pairing-manager.js +219 -1
- package/dist-standalone/plugin-system.js +257 -1
- package/dist-standalone/plugins/logging.d.ts +84 -0
- package/dist-standalone/plugins/logging.js +163 -0
- package/dist-standalone/plugins/metrics.d.ts +111 -0
- package/dist-standalone/plugins/metrics.js +176 -0
- package/dist-standalone/plugins/validation.d.ts +104 -0
- package/dist-standalone/plugins/validation.js +297 -0
- package/dist-standalone/policy.js +315 -1
- package/dist-standalone/progress-callbacks.js +576 -1
- package/dist-standalone/redis-nonce-store.js +72 -1
- package/dist-standalone/registry-middleware.js +47 -1
- package/dist-standalone/retry-strategies.js +534 -1
- package/dist-standalone/retry-transport.js +98 -1
- package/dist-standalone/runtime/browser.d.ts +311 -0
- package/dist-standalone/runtime/browser.js +516 -0
- package/dist-standalone/runtime/edge.d.ts +282 -0
- package/dist-standalone/runtime/edge.js +511 -0
- package/dist-standalone/runtime/react-native.d.ts +157 -0
- package/dist-standalone/runtime/react-native.js +383 -0
- package/dist-standalone/security-policy.js +239 -1
- package/dist-standalone/serialization.js +1031 -1
- package/dist-standalone/split-channel.js +219 -1
- package/dist-standalone/subscription-proof.js +224 -1
- package/dist-standalone/succession.js +142 -1
- package/dist-standalone/timeouts.js +398 -1
- package/dist-standalone/trace-context.js +414 -1
- package/dist-standalone/trace-spans.js +488 -1
- package/dist-standalone/transport.js +59 -1
- package/dist-standalone/trust-registry.js +950 -1
- package/dist-standalone/types/error-response.d.ts +209 -0
- package/dist-standalone/types/error-response.js +52 -0
- package/dist-standalone/vault-auth.js +174 -1
- package/dist-standalone/vault-store-loader.js +187 -1
- package/dist-standalone/verify.js +16 -1
- package/dist-standalone/version-info.js +530 -1
- package/dist-standalone/xfetch.js +335 -1
- package/package.json +4 -10
- package/share1.dat +0 -0
- package/dist-standalone/_deps/mldsa-wasm/LICENSE +0 -24
- package/dist-standalone/_deps/mldsa-wasm/package.json +0 -46
- package/dist-standalone/_deps/shared/cjs/package.json +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/package.json +0 -1
- package/dist-standalone/_deps/xchange/cjs/package.json +0 -1
- package/dist-standalone/_deps/xregistry/cjs/package.json +0 -1
- package/dist-standalone/cjs/package.json +0 -3
- package/dist-standalone/package.json +0 -10
|
@@ -1 +1,295 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* @module lazy-init
|
|
3
|
+
* Lazy agent initialization for zero-click onboarding.
|
|
4
|
+
*
|
|
5
|
+
* Defers invite acceptance and identity generation until first
|
|
6
|
+
* send/receive call. Enables: `Agent.lazy({ name: 'my-service' })`
|
|
7
|
+
* with no async/await at construction time.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* // Environment: XBIND_INVITE_CODE=XBD-abc123
|
|
12
|
+
*
|
|
13
|
+
* // Old way (explicit):
|
|
14
|
+
* const agent = await Agent.create({ name: 'my-service', registry, transport });
|
|
15
|
+
*
|
|
16
|
+
* // New way (lazy):
|
|
17
|
+
* const agent = Agent.lazy({ name: 'my-service' });
|
|
18
|
+
* // No await, no async — agent is constructed synchronously.
|
|
19
|
+
* // Invite auto-accepts on first send/receive:
|
|
20
|
+
* await agent.send({ to: partnerDid, payload: data, scope: 'test' });
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
import { ok, err } from"./_deps/shared/index.js";
|
|
24
|
+
import { Agent } from './agent.js';
|
|
25
|
+
import { autoAcceptInvite } from './auto-accept.js';
|
|
26
|
+
import { MemoryTrustRegistry } from './trust-registry.js';
|
|
27
|
+
import { HttpsTransportAdapter } from './transport.js';
|
|
28
|
+
import { toBase64 } from './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
|
-
|
|
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();
|