@private.me/xbind 1.3.0 → 2.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSES.md +212 -0
- package/README.md +388 -6
- package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
- package/dist-standalone/_deps/shared/cjs/errors.js +1 -275
- package/dist-standalone/_deps/shared/cjs/index.js +1 -138
- package/dist-standalone/_deps/shared/cjs/types.js +1 -90
- package/dist-standalone/_deps/shared/errors.js +1 -262
- package/dist-standalone/_deps/shared/index.js +1 -77
- package/dist-standalone/_deps/shared/types.js +1 -91
- 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 +1 -642
- package/dist-standalone/agent-sdk.js +1 -328
- package/dist-standalone/agent.d.ts +95 -5
- package/dist-standalone/agent.js +1 -1545
- package/dist-standalone/approval.js +1 -193
- package/dist-standalone/async-iterators.d.ts +275 -0
- package/dist-standalone/async-iterators.js +1 -0
- package/dist-standalone/auth.js +1 -219
- package/dist-standalone/auto-accept.js +1 -229
- package/dist-standalone/backup-config.js +1 -201
- package/dist-standalone/backup.d.ts +114 -0
- package/dist-standalone/backup.js +1 -0
- package/dist-standalone/batch-operations.d.ts +297 -0
- package/dist-standalone/batch-operations.js +1 -0
- package/dist-standalone/cancellation.d.ts +301 -0
- package/dist-standalone/cancellation.js +1 -0
- package/dist-standalone/checkpoint.js +1 -186
- package/dist-standalone/circuit-breaker.d.ts +351 -0
- package/dist-standalone/circuit-breaker.js +1 -0
- package/dist-standalone/cjs/agent-call.js +1 -651
- package/dist-standalone/cjs/agent-sdk.js +1 -332
- package/dist-standalone/cjs/agent.js +1 -1582
- package/dist-standalone/cjs/approval.js +1 -199
- package/dist-standalone/cjs/async-iterators.js +1 -0
- package/dist-standalone/cjs/auth.js +1 -225
- package/dist-standalone/cjs/auto-accept.js +1 -233
- package/dist-standalone/cjs/backup-config.js +1 -207
- package/dist-standalone/cjs/backup.js +1 -0
- package/dist-standalone/cjs/batch-operations.js +1 -0
- package/dist-standalone/cjs/cancellation.js +1 -0
- package/dist-standalone/cjs/checkpoint.js +1 -193
- package/dist-standalone/cjs/circuit-breaker.js +1 -0
- package/dist-standalone/cjs/cli/init.js +1 -486
- package/dist-standalone/cjs/config-validation.js +1 -0
- package/dist-standalone/cjs/connect.js +1 -312
- package/dist-standalone/cjs/connection-pool.js +1 -0
- package/dist-standalone/cjs/correlation-id.js +1 -339
- package/dist-standalone/cjs/crypto-utils.js +1 -0
- package/dist-standalone/cjs/debug-mode.js +1 -0
- package/dist-standalone/cjs/did-document.js +1 -101
- package/dist-standalone/cjs/did-privateme.js +1 -130
- package/dist-standalone/cjs/did-web.js +1 -201
- package/dist-standalone/cjs/discovery.js +1 -462
- package/dist-standalone/cjs/dual-mode.js +1 -251
- package/dist-standalone/cjs/email-templates.js +1 -313
- package/dist-standalone/cjs/email-transport.js +1 -239
- package/dist-standalone/cjs/envelope.js +1 -510
- package/dist-standalone/cjs/errors.js +1 -826
- package/dist-standalone/cjs/event-emitter.js +1 -0
- package/dist-standalone/cjs/gateway-state.js +1 -55
- package/dist-standalone/cjs/gateway-transport.js +1 -120
- package/dist-standalone/cjs/graceful-degradation.js +1 -0
- package/dist-standalone/cjs/guardrails.js +1 -223
- package/dist-standalone/cjs/health-check.js +1 -0
- package/dist-standalone/cjs/http-compat.js +1 -272
- package/dist-standalone/cjs/http-status-map.js +1 -571
- package/dist-standalone/cjs/identity.js +1 -541
- package/dist-standalone/cjs/index.js +1 -237
- package/dist-standalone/cjs/invitation.js +1 -421
- package/dist-standalone/cjs/invite.js +1 -328
- package/dist-standalone/cjs/key-agreement.js +1 -246
- package/dist-standalone/cjs/lazy-init.js +1 -300
- package/dist-standalone/cjs/logger.js +1 -0
- package/dist-standalone/cjs/mdns-discovery.js +1 -202
- package/dist-standalone/cjs/nonce-store.js +1 -66
- package/dist-standalone/cjs/pairing-manager.js +1 -223
- package/dist-standalone/cjs/plugin-system.js +1 -0
- package/dist-standalone/cjs/plugins/logging.js +1 -0
- package/dist-standalone/cjs/plugins/metrics.js +1 -0
- package/dist-standalone/cjs/plugins/validation.js +1 -0
- package/dist-standalone/cjs/policy.js +1 -320
- package/dist-standalone/cjs/progress-callbacks.js +1 -0
- package/dist-standalone/cjs/redis-nonce-store.js +1 -76
- package/dist-standalone/cjs/registry-middleware.js +1 -50
- package/dist-standalone/cjs/retry-strategies.js +1 -0
- package/dist-standalone/cjs/retry-transport.js +1 -102
- package/dist-standalone/cjs/runtime/browser.js +1 -0
- package/dist-standalone/cjs/runtime/edge.js +1 -0
- package/dist-standalone/cjs/runtime/react-native.js +1 -0
- package/dist-standalone/cjs/security-policy.js +1 -245
- package/dist-standalone/cjs/serialization.js +1 -0
- package/dist-standalone/cjs/split-channel.js +1 -177
- package/dist-standalone/cjs/subscription-proof.js +1 -230
- package/dist-standalone/cjs/succession.js +1 -148
- package/dist-standalone/cjs/timeouts.js +1 -0
- package/dist-standalone/cjs/trace-context.js +1 -0
- package/dist-standalone/cjs/trace-spans.js +1 -0
- package/dist-standalone/cjs/transport.js +1 -63
- package/dist-standalone/cjs/trust-registry.js +1 -742
- package/dist-standalone/cjs/types/error-response.js +1 -56
- package/dist-standalone/cjs/vault-auth.js +1 -0
- package/dist-standalone/cjs/vault-store-loader.js +1 -0
- package/dist-standalone/cjs/verify.js +1 -25
- package/dist-standalone/cjs/version-info.js +1 -0
- package/dist-standalone/cjs/xfetch.js +1 -252
- package/dist-standalone/cli/init.js +1 -449
- package/dist-standalone/cli/setup.js +1 -514
- package/dist-standalone/cli/types.js +1 -27
- package/dist-standalone/cli/xbind.js +1 -148
- package/dist-standalone/config-validation.d.ts +185 -0
- package/dist-standalone/config-validation.js +1 -0
- package/dist-standalone/connect.js +1 -274
- package/dist-standalone/connection-pool.d.ts +251 -0
- package/dist-standalone/connection-pool.js +1 -0
- package/dist-standalone/correlation-id.js +1 -326
- package/dist-standalone/crypto-utils.d.ts +60 -0
- package/dist-standalone/crypto-utils.js +1 -0
- package/dist-standalone/debug-mode.d.ts +286 -0
- package/dist-standalone/debug-mode.js +1 -0
- package/dist-standalone/did-document.js +1 -96
- package/dist-standalone/did-privateme.js +1 -121
- package/dist-standalone/did-web.js +1 -196
- package/dist-standalone/discovery.js +1 -458
- package/dist-standalone/dual-mode.js +1 -247
- package/dist-standalone/email-templates.js +1 -309
- package/dist-standalone/email-transport.js +1 -232
- package/dist-standalone/envelope.d.ts +29 -1
- package/dist-standalone/envelope.js +1 -497
- package/dist-standalone/errors.d.ts +10 -0
- package/dist-standalone/errors.js +1 -811
- package/dist-standalone/event-emitter.d.ts +395 -0
- package/dist-standalone/event-emitter.js +1 -0
- package/dist-standalone/gateway-state.js +1 -51
- package/dist-standalone/gateway-transport.js +1 -116
- package/dist-standalone/graceful-degradation.d.ts +246 -0
- package/dist-standalone/graceful-degradation.js +1 -0
- package/dist-standalone/guardrails.js +1 -216
- package/dist-standalone/health-check.d.ts +150 -0
- package/dist-standalone/health-check.js +1 -0
- package/dist-standalone/http-compat.js +1 -267
- package/dist-standalone/http-status-map.js +1 -561
- package/dist-standalone/identity.d.ts +64 -1
- package/dist-standalone/identity.js +1 -516
- package/dist-standalone/index.d.ts +45 -3
- package/dist-standalone/index.js +1 -52
- package/dist-standalone/invitation.js +1 -415
- package/dist-standalone/invite.js +1 -324
- package/dist-standalone/key-agreement.d.ts +61 -13
- package/dist-standalone/key-agreement.js +1 -236
- package/dist-standalone/lazy-init.js +1 -295
- package/dist-standalone/logger.d.ts +77 -0
- package/dist-standalone/logger.js +1 -0
- package/dist-standalone/mdns-discovery.js +1 -195
- package/dist-standalone/nonce-store.d.ts +16 -3
- package/dist-standalone/nonce-store.js +1 -62
- package/dist-standalone/package.json +0 -1
- package/dist-standalone/pairing-manager.js +1 -219
- package/dist-standalone/plugin-system.d.ts +145 -0
- package/dist-standalone/plugin-system.js +1 -0
- package/dist-standalone/policy.js +1 -315
- package/dist-standalone/progress-callbacks.d.ts +394 -0
- package/dist-standalone/progress-callbacks.js +1 -0
- package/dist-standalone/redis-nonce-store.js +1 -72
- package/dist-standalone/registry-middleware.js +1 -47
- package/dist-standalone/retry-strategies.d.ts +382 -0
- package/dist-standalone/retry-strategies.js +1 -0
- package/dist-standalone/retry-transport.js +1 -98
- package/dist-standalone/security-policy.js +1 -239
- package/dist-standalone/serialization.d.ts +244 -0
- package/dist-standalone/serialization.js +1 -0
- package/dist-standalone/split-channel.d.ts +49 -1
- package/dist-standalone/split-channel.js +1 -171
- package/dist-standalone/subscription-proof.js +1 -224
- package/dist-standalone/succession.js +1 -142
- package/dist-standalone/timeouts.d.ts +275 -0
- package/dist-standalone/timeouts.js +1 -0
- package/dist-standalone/trace-context.d.ts +252 -0
- package/dist-standalone/trace-context.js +1 -0
- package/dist-standalone/trace-spans.d.ts +360 -0
- package/dist-standalone/trace-spans.js +1 -0
- package/dist-standalone/transport.js +1 -59
- package/dist-standalone/trust-registry.d.ts +106 -5
- package/dist-standalone/trust-registry.js +1 -702
- package/dist-standalone/vault-auth.d.ts +91 -0
- package/dist-standalone/vault-auth.js +1 -0
- package/dist-standalone/vault-store-loader.d.ts +110 -0
- package/dist-standalone/vault-store-loader.js +1 -0
- package/dist-standalone/verify.js +1 -16
- package/dist-standalone/version-info.d.ts +259 -0
- package/dist-standalone/version-info.js +1 -0
- package/dist-standalone/xfetch.js +1 -247
- package/llms.txt +1 -0
- package/package.json +66 -5
- package/share1.dat +0 -0
- package/dist-standalone/_deps/crypto/base64.d.ts +0 -29
- package/dist-standalone/_deps/crypto/base64.js +0 -209
- package/dist-standalone/_deps/crypto/cjs/base64.js +0 -103
- package/dist-standalone/_deps/crypto/cjs/errors.js +0 -119
- package/dist-standalone/_deps/crypto/cjs/hmac.js +0 -71
- package/dist-standalone/_deps/crypto/cjs/index.js +0 -86
- package/dist-standalone/_deps/crypto/cjs/padding.js +0 -57
- package/dist-standalone/_deps/crypto/cjs/share-header.js +0 -68
- package/dist-standalone/_deps/crypto/cjs/shares.js +0 -152
- package/dist-standalone/_deps/crypto/cjs/tlv.js +0 -199
- package/dist-standalone/_deps/crypto/cjs/uuid.js +0 -61
- package/dist-standalone/_deps/crypto/cjs/verify.js +0 -24
- package/dist-standalone/_deps/crypto/cjs/xorida.js +0 -221
- package/dist-standalone/_deps/crypto/errors.d.ts +0 -51
- package/dist-standalone/_deps/crypto/errors.js +0 -109
- package/dist-standalone/_deps/crypto/hmac.d.ts +0 -39
- package/dist-standalone/_deps/crypto/hmac.js +0 -66
- package/dist-standalone/_deps/crypto/index.d.ts +0 -20
- package/dist-standalone/_deps/crypto/index.js +0 -45
- package/dist-standalone/_deps/crypto/padding.d.ts +0 -19
- package/dist-standalone/_deps/crypto/padding.js +0 -53
- package/dist-standalone/_deps/crypto/share-header.d.ts +0 -44
- package/dist-standalone/_deps/crypto/share-header.js +0 -63
- package/dist-standalone/_deps/crypto/shares.d.ts +0 -27
- package/dist-standalone/_deps/crypto/shares.js +0 -148
- package/dist-standalone/_deps/crypto/tlv.d.ts +0 -26
- package/dist-standalone/_deps/crypto/tlv.js +0 -195
- package/dist-standalone/_deps/crypto/uuid.d.ts +0 -22
- package/dist-standalone/_deps/crypto/uuid.js +0 -56
- package/dist-standalone/_deps/crypto/verify.d.ts +0 -15
- package/dist-standalone/_deps/crypto/verify.js +0 -15
- package/dist-standalone/_deps/crypto/xorida.d.ts +0 -44
- package/dist-standalone/_deps/crypto/xorida.js +0 -215
- package/dist-standalone/_deps/shared/errors.d.ts.map +0 -1
- package/dist-standalone/_deps/shared/errors.js.map +0 -1
- package/dist-standalone/_deps/shared/index.d.ts.map +0 -1
- package/dist-standalone/_deps/shared/index.js.map +0 -1
- package/dist-standalone/_deps/shared/types.d.ts.map +0 -1
- package/dist-standalone/_deps/shared/types.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/errors.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/errors.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/index.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/index.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/pagination.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/pagination.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/progress.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/progress.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/search.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/search.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/types.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/types.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/errors.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/errors.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/index.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/index.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/pagination.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/pagination.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/progress.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/progress.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/search.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/search.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/types.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/types.js.map +0 -1
- package/dist-standalone/_deps/xregistry/discovery.d.ts.map +0 -1
- package/dist-standalone/_deps/xregistry/discovery.js.map +0 -1
- package/dist-standalone/_deps/xregistry/errors.d.ts.map +0 -1
- package/dist-standalone/_deps/xregistry/errors.js.map +0 -1
- package/dist-standalone/_deps/xregistry/index.d.ts.map +0 -1
- package/dist-standalone/_deps/xregistry/index.js.map +0 -1
- package/dist-standalone/_deps/xregistry/registry.d.ts.map +0 -1
- package/dist-standalone/_deps/xregistry/registry.js.map +0 -1
- package/dist-standalone/_deps/xregistry/schema.d.ts.map +0 -1
- package/dist-standalone/_deps/xregistry/schema.js.map +0 -1
- package/dist-standalone/_deps/xregistry/types.d.ts.map +0 -1
- package/dist-standalone/_deps/xregistry/types.js.map +0 -1
|
@@ -1,223 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* @module pairing-manager
|
|
4
|
-
* Security validation for peer-to-peer device pairing via mDNS.
|
|
5
|
-
*
|
|
6
|
-
* Security properties:
|
|
7
|
-
* - 16-byte cryptographically secure nonce (prevents replay attacks)
|
|
8
|
-
* - 60-second timeout (limits attack window)
|
|
9
|
-
* - User confirmation required on BOTH devices
|
|
10
|
-
* - Nonce echo in response (prevents MITM substitution)
|
|
11
|
-
* - Trust registry integration (stores paired DIDs with scopes)
|
|
12
|
-
* - Gold Standard compliant (GS-CONNECT requirement #26, GS-SEC-RNG compliant)
|
|
13
|
-
*/
|
|
14
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
-
exports.PairingManager = void 0;
|
|
16
|
-
const shared_1 = require("../_deps/shared/index.js");
|
|
17
|
-
/**
|
|
18
|
-
* Pairing manager for secure peer-to-peer device pairing.
|
|
19
|
-
*
|
|
20
|
-
* Implements challenge-response protocol with user confirmation.
|
|
21
|
-
* Integrates with trust registry for persistent pairing storage.
|
|
22
|
-
*/
|
|
23
|
-
class PairingManager {
|
|
24
|
-
pendingNonces = new Map(); // nonce → timestamp
|
|
25
|
-
registry;
|
|
26
|
-
deviceDid;
|
|
27
|
-
/**
|
|
28
|
-
* Create pairing manager.
|
|
29
|
-
*
|
|
30
|
-
* @param deviceDid - DID of this device
|
|
31
|
-
* @param registry - Trust registry instance
|
|
32
|
-
*/
|
|
33
|
-
constructor(deviceDid, registry) {
|
|
34
|
-
this.deviceDid = deviceDid;
|
|
35
|
-
this.registry = registry;
|
|
36
|
-
// Clean up expired nonces every 10 seconds
|
|
37
|
-
setInterval(() => {
|
|
38
|
-
const now = Date.now();
|
|
39
|
-
for (const [nonce, timestamp] of this.pendingNonces.entries()) {
|
|
40
|
-
if (now - timestamp > 60_000) {
|
|
41
|
-
this.pendingNonces.delete(nonce);
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
}, 10_000);
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Create pairing request.
|
|
48
|
-
*
|
|
49
|
-
* Generates cryptographically secure nonce and stores it for validation.
|
|
50
|
-
* Device A calls this before sending request to Device B.
|
|
51
|
-
*
|
|
52
|
-
* @returns Pairing request to send to remote device
|
|
53
|
-
*
|
|
54
|
-
* @example
|
|
55
|
-
* ```typescript
|
|
56
|
-
* const manager = new PairingManager('did:key:z6MkA...', registry);
|
|
57
|
-
* const request = manager.createRequest();
|
|
58
|
-
* // Send request to Device B via HTTP POST
|
|
59
|
-
* const response = await fetch(`${deviceB.endpoint}/pair`, {
|
|
60
|
-
* method: 'POST',
|
|
61
|
-
* body: JSON.stringify(request),
|
|
62
|
-
* });
|
|
63
|
-
* ```
|
|
64
|
-
*/
|
|
65
|
-
createRequest() {
|
|
66
|
-
// Generate cryptographically secure nonce (GS-SEC-RNG: NEVER use Math.random)
|
|
67
|
-
const nonceBytes = new Uint8Array(16);
|
|
68
|
-
if (typeof globalThis.crypto !== 'undefined' && globalThis.crypto.getRandomValues) {
|
|
69
|
-
globalThis.crypto.getRandomValues(nonceBytes);
|
|
70
|
-
}
|
|
71
|
-
else {
|
|
72
|
-
// Node.js environment
|
|
73
|
-
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
74
|
-
const crypto = require('node:crypto');
|
|
75
|
-
crypto.getRandomValues(nonceBytes);
|
|
76
|
-
}
|
|
77
|
-
const nonce = Array.from(nonceBytes)
|
|
78
|
-
.map((b) => b.toString(16).padStart(2, '0'))
|
|
79
|
-
.join('');
|
|
80
|
-
const timestamp = Date.now();
|
|
81
|
-
// Store nonce for validation (60-second TTL)
|
|
82
|
-
this.pendingNonces.set(nonce, timestamp);
|
|
83
|
-
return {
|
|
84
|
-
device_a_did: this.deviceDid,
|
|
85
|
-
nonce,
|
|
86
|
-
timestamp,
|
|
87
|
-
};
|
|
88
|
-
}
|
|
89
|
-
/**
|
|
90
|
-
* Validate pairing request.
|
|
91
|
-
*
|
|
92
|
-
* Checks timeout and nonce uniqueness.
|
|
93
|
-
* Device B calls this when receiving request from Device A.
|
|
94
|
-
*
|
|
95
|
-
* @param request - Pairing request from remote device
|
|
96
|
-
* @returns Ok if valid, Err with reason if invalid
|
|
97
|
-
*
|
|
98
|
-
* @example
|
|
99
|
-
* ```typescript
|
|
100
|
-
* // Device B receives request
|
|
101
|
-
* const validation = manager.validateRequest(request);
|
|
102
|
-
* if (!validation.ok) {
|
|
103
|
-
* return res.status(400).json({ error: validation.error });
|
|
104
|
-
* }
|
|
105
|
-
* ```
|
|
106
|
-
*/
|
|
107
|
-
validateRequest(request) {
|
|
108
|
-
// Check timeout (60-second window)
|
|
109
|
-
const age = Date.now() - request.timestamp;
|
|
110
|
-
if (age > 60_000) {
|
|
111
|
-
return (0, shared_1.err)(`Request expired (${Math.floor(age / 1000)}s old, max 60s)`);
|
|
112
|
-
}
|
|
113
|
-
if (age < 0) {
|
|
114
|
-
return (0, shared_1.err)('Request timestamp in the future (clock skew detected)');
|
|
115
|
-
}
|
|
116
|
-
// Check required fields
|
|
117
|
-
if (!request.device_a_did || !request.nonce || !request.timestamp) {
|
|
118
|
-
return (0, shared_1.err)('Missing required fields (device_a_did, nonce, timestamp)');
|
|
119
|
-
}
|
|
120
|
-
return (0, shared_1.ok)(undefined);
|
|
121
|
-
}
|
|
122
|
-
/**
|
|
123
|
-
* Accept pairing request.
|
|
124
|
-
*
|
|
125
|
-
* Shows UI prompt for user confirmation, then stores in trust registry.
|
|
126
|
-
* Device B calls this after validating request.
|
|
127
|
-
*
|
|
128
|
-
* @param request - Validated pairing request
|
|
129
|
-
* @param promptCallback - Async function to show UI prompt (returns true if accepted)
|
|
130
|
-
* @returns Pairing response to send back to Device A
|
|
131
|
-
*
|
|
132
|
-
* @example
|
|
133
|
-
* ```typescript
|
|
134
|
-
* const response = await manager.acceptPairing(request, async () => {
|
|
135
|
-
* // Show modal: "Device {name} wants to pair. Accept?"
|
|
136
|
-
* return await showConfirmationDialog({
|
|
137
|
-
* title: 'Pair with Device?',
|
|
138
|
-
* message: `DID: ${request.device_a_did.slice(0, 20)}...`,
|
|
139
|
-
* });
|
|
140
|
-
* });
|
|
141
|
-
*
|
|
142
|
-
* if (response.ok && response.value.accepted) {
|
|
143
|
-
* // Send response back to Device A
|
|
144
|
-
* }
|
|
145
|
-
* ```
|
|
146
|
-
*/
|
|
147
|
-
async acceptPairing(request, promptCallback) {
|
|
148
|
-
// Validate request first
|
|
149
|
-
const validation = this.validateRequest(request);
|
|
150
|
-
if (!validation.ok) {
|
|
151
|
-
return (0, shared_1.err)(validation.error);
|
|
152
|
-
}
|
|
153
|
-
// Prompt user for confirmation
|
|
154
|
-
const accepted = await promptCallback();
|
|
155
|
-
if (accepted) {
|
|
156
|
-
// Store in trust registry (Device A → Device B)
|
|
157
|
-
const registerResult = await this.registry.register(request.device_a_did, new Uint8Array(32), 'Paired Device', ['pairing']);
|
|
158
|
-
if (!registerResult.ok) {
|
|
159
|
-
const errorMsg = typeof registerResult.error === 'string'
|
|
160
|
-
? registerResult.error
|
|
161
|
-
: 'Unknown error';
|
|
162
|
-
return (0, shared_1.err)(`Failed to register pairing: ${errorMsg}`);
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
// Return response (echo nonce to prevent MITM)
|
|
166
|
-
return (0, shared_1.ok)({
|
|
167
|
-
device_b_did: this.deviceDid,
|
|
168
|
-
accepted,
|
|
169
|
-
nonce: request.nonce,
|
|
170
|
-
});
|
|
171
|
-
}
|
|
172
|
-
/**
|
|
173
|
-
* Finalize pairing.
|
|
174
|
-
*
|
|
175
|
-
* Verifies response nonce and stores remote DID in trust registry.
|
|
176
|
-
* Device A calls this after receiving response from Device B.
|
|
177
|
-
*
|
|
178
|
-
* @param response - Pairing response from Device B
|
|
179
|
-
* @param expectedNonce - Nonce from original request (for verification)
|
|
180
|
-
* @returns Ok if successful, Err if nonce mismatch or storage failed
|
|
181
|
-
*
|
|
182
|
-
* @example
|
|
183
|
-
* ```typescript
|
|
184
|
-
* const request = manager.createRequest();
|
|
185
|
-
* const response = await sendPairingRequest(deviceB.endpoint, request);
|
|
186
|
-
*
|
|
187
|
-
* const result = await manager.finalizePairing(response, request.nonce);
|
|
188
|
-
* if (result.ok) {
|
|
189
|
-
* console.log('Pairing successful!');
|
|
190
|
-
* } else {
|
|
191
|
-
* console.error('Pairing failed:', result.error);
|
|
192
|
-
* }
|
|
193
|
-
* ```
|
|
194
|
-
*/
|
|
195
|
-
async finalizePairing(response, expectedNonce) {
|
|
196
|
-
// Verify nonce echo (prevents MITM substitution)
|
|
197
|
-
if (response.nonce !== expectedNonce) {
|
|
198
|
-
return (0, shared_1.err)('Nonce mismatch (possible MITM attack)');
|
|
199
|
-
}
|
|
200
|
-
// Check if pairing was accepted
|
|
201
|
-
if (!response.accepted) {
|
|
202
|
-
return (0, shared_1.err)('Pairing rejected by remote device');
|
|
203
|
-
}
|
|
204
|
-
// Remove nonce from pending set
|
|
205
|
-
this.pendingNonces.delete(expectedNonce);
|
|
206
|
-
// Store in trust registry (Device B → Device A)
|
|
207
|
-
const registerResult = await this.registry.register(response.device_b_did, new Uint8Array(32), 'Paired Device', ['pairing']);
|
|
208
|
-
if (!registerResult.ok) {
|
|
209
|
-
const errorMsg = typeof registerResult.error === 'string'
|
|
210
|
-
? registerResult.error
|
|
211
|
-
: 'Unknown error';
|
|
212
|
-
return (0, shared_1.err)(`Failed to register pairing: ${errorMsg}`);
|
|
213
|
-
}
|
|
214
|
-
return (0, shared_1.ok)(undefined);
|
|
215
|
-
}
|
|
216
|
-
/**
|
|
217
|
-
* Get pending nonce count (for debugging/monitoring).
|
|
218
|
-
*/
|
|
219
|
-
getPendingNonceCount() {
|
|
220
|
-
return this.pendingNonces.size;
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
exports.PairingManager = PairingManager;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PairingManager=void 0;const shared_1=require("../_deps/shared/index.js");class PairingManager{pendingNonces=new Map;registry;deviceDid;constructor(e,r){this.deviceDid=e,this.registry=r,setInterval(()=>{const e=Date.now();for(const[r,i]of this.pendingNonces.entries())e-i>6e4&&this.pendingNonces.delete(r)},1e4)}createRequest(){const e=new Uint8Array(16);if(void 0!==globalThis.crypto&&globalThis.crypto.getRandomValues)globalThis.crypto.getRandomValues(e);else{require("node:crypto").getRandomValues(e)}const r=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""),i=Date.now();return this.pendingNonces.set(r,i),{device_a_did:this.deviceDid,nonce:r,timestamp:i}}validateRequest(e){const r=Date.now()-e.timestamp;return r>6e4?(0,shared_1.err)(`Request expired (${Math.floor(r/1e3)}s old, max 60s)`):r<0?(0,shared_1.err)("Request timestamp in the future (clock skew detected)"):e.device_a_did&&e.nonce&&e.timestamp?(0,shared_1.ok)(void 0):(0,shared_1.err)("Missing required fields (device_a_did, nonce, timestamp)")}async acceptPairing(e,r){const i=this.validateRequest(e);if(!i.ok)return(0,shared_1.err)(i.error);const t=await r();if(t){const r=await this.registry.register(e.device_a_did,new Uint8Array(32),"Paired Device",["pairing"]);if(!r.ok){const e="string"==typeof r.error?r.error:"Unknown error";return(0,shared_1.err)(`Failed to register pairing: ${e}`)}}return(0,shared_1.ok)({device_b_did:this.deviceDid,accepted:t,nonce:e.nonce})}async finalizePairing(e,r){if(e.nonce!==r)return(0,shared_1.err)("Nonce mismatch (possible MITM attack)");if(!e.accepted)return(0,shared_1.err)("Pairing rejected by remote device");this.pendingNonces.delete(r);const i=await this.registry.register(e.device_b_did,new Uint8Array(32),"Paired Device",["pairing"]);if(!i.ok){const e="string"==typeof i.error?i.error:"Unknown error";return(0,shared_1.err)(`Failed to register pairing: ${e}`)}return(0,shared_1.ok)(void 0)}getPendingNonceCount(){return this.pendingNonces.size}}exports.PairingManager=PairingManager;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PluginBuilder=exports.MiddlewareChain=void 0,exports.createPluginContext=createPluginContext,exports.createPlugin=createPlugin;const shared_1=require("../_deps/shared/index.js");class MiddlewareChain{plugins=[];initialized=!1;constructor(e=[]){this.plugins=[...e].sort((e,r)=>(e.priority??100)-(r.priority??100))}register(e){return this.plugins.some(r=>r.name===e.name)?(0,shared_1.err)(`PLUGIN_ALREADY_REGISTERED:${e.name}`):(this.plugins.push(e),this.plugins.sort((e,r)=>(e.priority??100)-(r.priority??100)),(0,shared_1.ok)(void 0))}unregister(e){const r=this.plugins.findIndex(r=>r.name===e);return-1===r?(0,shared_1.err)(`PLUGIN_NOT_FOUND:${e}`):(this.plugins.splice(r,1),(0,shared_1.ok)(void 0))}getPlugins(){return[...this.plugins]}async initialize(){if(this.initialized)return(0,shared_1.ok)(void 0);for(const e of this.plugins)if(e.onInit){const r=await e.onInit();if(!1===r.ok)return(0,shared_1.err)(`PLUGIN_INIT_FAILED:${e.name}:${r.error}`)}return this.initialized=!0,(0,shared_1.ok)(void 0)}async destroy(){const e=[];for(const r of this.plugins)if(r.onDestroy){const t=await r.onDestroy();!1===t.ok&&e.push(`${r.name}:${t.error}`)}return this.initialized=!1,e.length>0?(0,shared_1.err)(`PLUGIN_DESTROY_FAILED:${e.join(",")}`):(0,shared_1.ok)(void 0)}async executeSend(e,r){if(!this.initialized)return(0,shared_1.err)("MIDDLEWARE_NOT_INITIALIZED");let t=e;for(const e of this.plugins)if(e.onSend){const i=await e.onSend(t,r);if(!1===i.ok)return(0,shared_1.err)(`PLUGIN_HOOK_FAILED:${e.name}:${i.error}`);const n=i.value;if(n.abort)return(0,shared_1.err)(`PLUGIN_ABORTED:${e.name}:${n.reason??"no reason"}`);t=n.payload,n.metadata&&Object.assign(r.metadata,n.metadata)}return(0,shared_1.ok)(t)}async executeReceive(e,r){if(!this.initialized)return(0,shared_1.err)("MIDDLEWARE_NOT_INITIALIZED");let t=e;for(const e of this.plugins)if(e.onReceive){const i=await e.onReceive(t,r);if(!1===i.ok)return(0,shared_1.err)(`PLUGIN_HOOK_FAILED:${e.name}:${i.error}`);const n=i.value;if(n.abort)return(0,shared_1.err)(`PLUGIN_ABORTED:${e.name}:${n.reason??"no reason"}`);t=n.payload,n.metadata&&Object.assign(r.metadata,n.metadata)}return(0,shared_1.ok)(t)}async executeEncrypt(e,r){if(!this.initialized)return(0,shared_1.err)("MIDDLEWARE_NOT_INITIALIZED");let t=e;for(const e of this.plugins)if(e.onEncrypt){const i=await e.onEncrypt(t,r);if(!1===i.ok)return(0,shared_1.err)(`PLUGIN_HOOK_FAILED:${e.name}:${i.error}`);const n=i.value;if(n.abort)return(0,shared_1.err)(`PLUGIN_ABORTED:${e.name}:${n.reason??"no reason"}`);t=n.payload,n.metadata&&Object.assign(r.metadata,n.metadata)}return(0,shared_1.ok)(t)}async executeDecrypt(e,r){if(!this.initialized)return(0,shared_1.err)("MIDDLEWARE_NOT_INITIALIZED");let t=e;for(const e of this.plugins)if(e.onDecrypt){const i=await e.onDecrypt(t,r);if(!1===i.ok)return(0,shared_1.err)(`PLUGIN_HOOK_FAILED:${e.name}:${i.error}`);const n=i.value;if(n.abort)return(0,shared_1.err)(`PLUGIN_ABORTED:${e.name}:${n.reason??"no reason"}`);t=n.payload,n.metadata&&Object.assign(r.metadata,n.metadata)}return(0,shared_1.ok)(t)}}function createPluginContext(e,r={}){return{agent:e,recipient:r.recipient,scope:r.scope,timestamp:r.timestamp??Date.now(),state:r.state??new Map,metadata:r.metadata??{}}}exports.MiddlewareChain=MiddlewareChain;class PluginBuilder{plugin={};constructor(e,r){this.plugin.name=e,this.plugin.version=r}description(e){return this.plugin.description=e,this}priority(e){return this.plugin.priority=e,this}onSend(e){return this.plugin.onSend=e,this}onReceive(e){return this.plugin.onReceive=e,this}onEncrypt(e){return this.plugin.onEncrypt=e,this}onDecrypt(e){return this.plugin.onDecrypt=e,this}onInit(e){return this.plugin.onInit=e,this}onDestroy(e){return this.plugin.onDestroy=e,this}build(){if(!this.plugin.name||!this.plugin.version)throw new Error("Plugin name and version are required");return this.plugin}}function createPlugin(e,r){return new PluginBuilder(e,r)}exports.PluginBuilder=PluginBuilder;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.LoggingPlugin=exports.LogLevel=void 0,exports.createLoggingPlugin=createLoggingPlugin;const shared_1=require("../../_deps/shared/index.js");var LogLevel;!function(e){e.DEBUG="debug",e.INFO="info",e.WARN="warn",e.ERROR="error"}(LogLevel||(exports.LogLevel=LogLevel={}));class LoggingPlugin{name="logging";version="1.0.0";description="Captures message processing events for debugging and audit trails";priority=10;options;logs=[];constructor(e={}){this.options={level:e.level??LogLevel.INFO,includeSize:e.includeSize??!0,includeMetadata:e.includeMetadata??!1,logHandler:e.logHandler??(e=>console.log(JSON.stringify(e))),filter:e.filter??(()=>!0)}}onInit(){return this.log({timestamp:(new Date).toISOString(),level:LogLevel.INFO,event:"send",agent:"system",metadata:{message:"Logging plugin initialized"}}),(0,shared_1.ok)(void 0)}onDestroy(){return this.log({timestamp:(new Date).toISOString(),level:LogLevel.INFO,event:"send",agent:"system",metadata:{message:"Logging plugin destroyed",totalLogs:this.logs.length}}),this.logs=[],(0,shared_1.ok)(void 0)}onSend(e,t){const i=this.options.includeSize?this.estimateSize(e):void 0;return this.log({timestamp:(new Date).toISOString(),level:LogLevel.INFO,event:"send",agent:t.agent.did,recipient:t.recipient,scope:t.scope,payloadSize:i,metadata:this.options.includeMetadata?t.metadata:void 0}),(0,shared_1.ok)({payload:e})}onReceive(e,t){const i=this.options.includeSize?this.estimateSize(e):void 0;return this.log({timestamp:(new Date).toISOString(),level:LogLevel.INFO,event:"receive",agent:t.agent.did,recipient:e.sender,scope:t.scope,payloadSize:i,metadata:this.options.includeMetadata?t.metadata:void 0}),(0,shared_1.ok)({payload:e})}onEncrypt(e,t){return this.log({timestamp:(new Date).toISOString(),level:LogLevel.DEBUG,event:"encrypt",agent:t.agent.did,recipient:t.recipient,scope:t.scope,payloadSize:this.options.includeSize?e.length:void 0,metadata:this.options.includeMetadata?t.metadata:void 0}),(0,shared_1.ok)({payload:e})}onDecrypt(e,t){return this.log({timestamp:(new Date).toISOString(),level:LogLevel.DEBUG,event:"decrypt",agent:t.agent.did,scope:t.scope,payloadSize:this.options.includeSize?e.length:void 0,metadata:this.options.includeMetadata?t.metadata:void 0}),(0,shared_1.ok)({payload:e})}getLogs(){return[...this.logs]}clearLogs(){this.logs=[]}getFilteredLogs(e){return this.logs.filter(e)}log(e){this.shouldLog(e.level)&&this.options.filter(e)&&(this.logs.push(e),this.options.logHandler(e))}shouldLog(e){const t=[LogLevel.DEBUG,LogLevel.INFO,LogLevel.WARN,LogLevel.ERROR],i=t.indexOf(this.options.level);return t.indexOf(e)>=i}estimateSize(e){if(e instanceof Uint8Array)return e.length;try{return JSON.stringify(e).length}catch{return 0}}}function createLoggingPlugin(e){return new LoggingPlugin(e)}exports.LoggingPlugin=LoggingPlugin;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.MetricsPlugin=void 0,exports.createMetricsPlugin=createMetricsPlugin;const shared_1=require("../../_deps/shared/index.js");class MetricsPlugin{name="metrics";version="1.0.0";description="Tracks performance metrics, message counts, and error rates";priority=20;options;metrics=[];startTime=Date.now();exportTimer;constructor(t={}){this.options={highResolution:t.highResolution??!0,maxMetrics:t.maxMetrics??1e4,onExport:t.onExport??(()=>{}),exportInterval:t.exportInterval??6e4}}onInit(){return this.startTime=Date.now(),this.options.exportInterval>0&&(this.exportTimer=setInterval(()=>{this.export()},this.options.exportInterval)),(0,shared_1.ok)(void 0)}onDestroy(){return this.exportTimer&&(clearInterval(this.exportTimer),this.exportTimer=void 0),this.export(),this.metrics=[],(0,shared_1.ok)(void 0)}onSend(t,e){const r=this.now(),s=this.now();return this.record({timestamp:Date.now(),event:"send",duration:s-r,success:!0}),(0,shared_1.ok)({payload:t})}onReceive(t,e){const r=this.now(),s=this.now();return this.record({timestamp:Date.now(),event:"receive",duration:s-r,success:!0}),(0,shared_1.ok)({payload:t})}onEncrypt(t,e){const r=this.now(),s=this.now();return this.record({timestamp:Date.now(),event:"encrypt",duration:s-r,success:!0}),(0,shared_1.ok)({payload:t})}onDecrypt(t,e){const r=this.now(),s=this.now();return this.record({timestamp:Date.now(),event:"decrypt",duration:s-r,success:!0}),(0,shared_1.ok)({payload:t})}getMetrics(){return[...this.metrics]}getAggregatedMetrics(){const t=this.metrics.filter(t=>"send"===t.event),e=this.metrics.filter(t=>"receive"===t.event),r=this.metrics.filter(t=>"encrypt"===t.event),s=this.metrics.filter(t=>"decrypt"===t.event),i=this.metrics.filter(t=>!t.success),n=t=>0===t.length?0:t.reduce((t,e)=>t+e.duration,0)/t.length,o=this.metrics.length;return{totalSends:t.length,totalReceives:e.length,totalEncrypts:r.length,totalDecrypts:s.length,avgSendDuration:n(t),avgReceiveDuration:n(e),avgEncryptDuration:n(r),avgDecryptDuration:n(s),totalErrors:i.length,errorRate:o>0?i.length/o:0,uptime:Date.now()-this.startTime}}clearMetrics(){this.metrics=[],this.startTime=Date.now()}export(){this.metrics.length>0&&this.options.onExport([...this.metrics])}getMetricsInRange(t,e){return this.metrics.filter(r=>r.timestamp>=t&&r.timestamp<=e)}getMetricsByEvent(t){return this.metrics.filter(e=>e.event===t)}record(t){this.metrics.push(t),this.metrics.length>this.options.maxMetrics&&this.metrics.shift()}now(){return this.options.highResolution&&"undefined"!=typeof performance?performance.now():Date.now()}}function createMetricsPlugin(t){return new MetricsPlugin(t)}exports.MetricsPlugin=MetricsPlugin;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CommonRules=exports.ValidationPlugin=void 0,exports.createValidationPlugin=createValidationPlugin;const shared_1=require("../../_deps/shared/index.js");class ValidationPlugin{name="validation";version="1.0.0";description="Validates payloads and envelopes before processing";priority=5;options;validationErrors=[];constructor(e={}){this.options={maxPayloadSize:e.maxPayloadSize??10485760,maxEnvelopeSize:e.maxEnvelopeSize??15728640,allowedScopes:e.allowedScopes??[],customRules:e.customRules??[],strictMode:e.strictMode??!1,validateSchema:e.validateSchema??!1}}onInit(){return(0,shared_1.ok)(void 0)}onDestroy(){return this.validationErrors=[],(0,shared_1.ok)(void 0)}onSend(e,r){const t=this.validatePayloadSize(e);if(!1===t.ok)return this.recordError("payload_size",t.error),(0,shared_1.err)(t.error);if(r.scope){const e=this.validateScope(r.scope);if(!1===e.ok)return this.recordError("scope",e.error),(0,shared_1.err)(e.error)}const i=this.validatePayloadStructure(e);if(!1===i.ok)return this.recordError("payload_structure",i.error),(0,shared_1.err)(i.error);for(const t of this.options.customRules)if(!t.appliesTo||t.appliesTo.includes("send")){const i=t.validate(e,r);if(i)return this.recordError(t.name,i),(0,shared_1.err)(`VALIDATION_FAILED:${t.name}:${i}`)}return(0,shared_1.ok)({payload:e})}onReceive(e,r){const t=this.validateEnvelopeSize(e);if(!1===t.ok)return this.recordError("envelope_size",t.error),(0,shared_1.err)(t.error);const i=this.validateEnvelopeStructure(e);if(!1===i.ok)return this.recordError("envelope_structure",i.error),(0,shared_1.err)(i.error);for(const t of this.options.customRules)if(!t.appliesTo||t.appliesTo.includes("receive")){const i=t.validate(e,r);if(i)return this.recordError(t.name,i),(0,shared_1.err)(`VALIDATION_FAILED:${t.name}:${i}`)}return(0,shared_1.ok)({payload:e})}onEncrypt(e,r){if(0===e.length)return this.recordError("plaintext_empty","Plaintext cannot be empty"),(0,shared_1.err)("VALIDATION_FAILED:PLAINTEXT_EMPTY");if(e.length>this.options.maxPayloadSize)return this.recordError("plaintext_size",`Plaintext exceeds max size: ${e.length} bytes`),(0,shared_1.err)(`VALIDATION_FAILED:PLAINTEXT_TOO_LARGE:${e.length}`);for(const t of this.options.customRules)if(!t.appliesTo||t.appliesTo.includes("encrypt")){const i=t.validate(e,r);if(i)return this.recordError(t.name,i),(0,shared_1.err)(`VALIDATION_FAILED:${t.name}:${i}`)}return(0,shared_1.ok)({payload:e})}onDecrypt(e,r){if(0===e.length)return this.recordError("plaintext_empty","Decrypted plaintext is empty"),(0,shared_1.err)("VALIDATION_FAILED:DECRYPTED_EMPTY");for(const t of this.options.customRules)if(!t.appliesTo||t.appliesTo.includes("decrypt")){const i=t.validate(e,r);if(i)return this.recordError(t.name,i),(0,shared_1.err)(`VALIDATION_FAILED:${t.name}:${i}`)}return(0,shared_1.ok)({payload:e})}getValidationErrors(){return[...this.validationErrors]}clearErrors(){this.validationErrors=[]}addRule(e){this.options.customRules.push(e)}removeRule(e){const r=this.options.customRules.findIndex(r=>r.name===e);return-1!==r&&(this.options.customRules.splice(r,1),!0)}validatePayloadSize(e){const r=this.estimateSize(e);return r>this.options.maxPayloadSize?(0,shared_1.err)(`VALIDATION_FAILED:PAYLOAD_TOO_LARGE:${r}>${this.options.maxPayloadSize}`):(0,shared_1.ok)(void 0)}validateEnvelopeSize(e){const r=this.estimateSize(e);return r>this.options.maxEnvelopeSize?(0,shared_1.err)(`VALIDATION_FAILED:ENVELOPE_TOO_LARGE:${r}>${this.options.maxEnvelopeSize}`):(0,shared_1.ok)(void 0)}validateScope(e){return this.options.allowedScopes.length>0&&!this.options.allowedScopes.includes(e)?(0,shared_1.err)(`VALIDATION_FAILED:SCOPE_NOT_ALLOWED:${e}`):(0,shared_1.ok)(void 0)}validatePayloadStructure(e){if(null==e)return(0,shared_1.err)("VALIDATION_FAILED:PAYLOAD_NULL_OR_UNDEFINED");try{JSON.stringify(e)}catch(e){return(0,shared_1.err)(`VALIDATION_FAILED:PAYLOAD_NOT_SERIALIZABLE:${String(e)}`)}return(0,shared_1.ok)(void 0)}validateEnvelopeStructure(e){return"v"in e||"version"in e?e.sender?e.recipient?"payload"in e||"ciphertext"in e?(0,shared_1.ok)(void 0):(0,shared_1.err)("VALIDATION_FAILED:ENVELOPE_MISSING_CIPHERTEXT"):(0,shared_1.err)("VALIDATION_FAILED:ENVELOPE_MISSING_RECIPIENT"):(0,shared_1.err)("VALIDATION_FAILED:ENVELOPE_MISSING_SENDER"):(0,shared_1.err)("VALIDATION_FAILED:ENVELOPE_MISSING_VERSION")}estimateSize(e){if(e instanceof Uint8Array)return e.length;try{return JSON.stringify(e).length}catch{return 0}}recordError(e,r){this.validationErrors.push({timestamp:Date.now(),rule:e,error:r}),this.validationErrors.length>1e3&&this.validationErrors.shift()}}function createValidationPlugin(e){return new ValidationPlugin(e)}exports.ValidationPlugin=ValidationPlugin,exports.CommonRules={requireFields:e=>({name:"require_fields",appliesTo:["send"],validate:r=>{if("object"!=typeof r||null===r)return"Payload must be an object";const t=r,i=e.filter(e=>!(e in t));return i.length>0?`Missing required fields: ${i.join(", ")}`:null}}),validateDIDFormat:()=>({name:"did_format",appliesTo:["send","receive"],validate:(e,r)=>r.recipient&&!r.recipient.startsWith("did:")?`Invalid DID format: ${r.recipient}`:null}),validateTimestamp:(e=3e5)=>({name:"timestamp_freshness",appliesTo:["receive"],validate:(r,t)=>{const i=Date.now()-t.timestamp;return i>e?`Timestamp too old: ${i}ms > ${e}ms`:null}})};
|
|
@@ -1,320 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* @module policy
|
|
4
|
-
* PolicyEngine for agent.call() constraint enforcement
|
|
5
|
-
*
|
|
6
|
-
* Enforces spending limits, rate limits, scope restrictions, and data filters
|
|
7
|
-
* on agent tool calls. Separate from SecurityPolicy (risk classification).
|
|
8
|
-
*/
|
|
9
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
-
exports.PolicyEngine = void 0;
|
|
11
|
-
exports.getGlobalPolicyEngine = getGlobalPolicyEngine;
|
|
12
|
-
const shared_1 = require("../_deps/shared/index.js");
|
|
13
|
-
const agent_call_js_1 = require("./agent-call.js");
|
|
14
|
-
/**
|
|
15
|
-
* PolicyEngine - Enforces constraints on agent.call() requests
|
|
16
|
-
*
|
|
17
|
-
* Tracks:
|
|
18
|
-
* - Per-transaction spending limits
|
|
19
|
-
* - Daily spending limits
|
|
20
|
-
* - Rate limits (calls per minute)
|
|
21
|
-
* - Allowed tools/scopes
|
|
22
|
-
*
|
|
23
|
-
* Thread-safe for concurrent requests from the same agent.
|
|
24
|
-
*/
|
|
25
|
-
class PolicyEngine {
|
|
26
|
-
/** Rate limit tracker by agent DID */
|
|
27
|
-
rateLimits = new Map();
|
|
28
|
-
/** Daily spending tracker by agent DID */
|
|
29
|
-
dailySpending = new Map();
|
|
30
|
-
/** Monthly spending tracker by agent DID */
|
|
31
|
-
monthlySpending = new Map();
|
|
32
|
-
/**
|
|
33
|
-
* Evaluate a policy against a request
|
|
34
|
-
*
|
|
35
|
-
* @param agentDID - Agent DID making the request
|
|
36
|
-
* @param tool - Tool being called (e.g., "stripe:createCharge")
|
|
37
|
-
* @param params - Tool parameters
|
|
38
|
-
* @param constraints - Policy constraints to enforce
|
|
39
|
-
* @returns Policy evaluation result
|
|
40
|
-
*/
|
|
41
|
-
evaluate(agentDID, tool, params, constraints) {
|
|
42
|
-
// Check allowed tools
|
|
43
|
-
if (constraints.allowedTools && constraints.allowedTools.length > 0) {
|
|
44
|
-
const [service] = tool.split(':');
|
|
45
|
-
const isAllowed = constraints.allowedTools.some((allowed) => allowed === tool || allowed === `${service}:*` || allowed === '*');
|
|
46
|
-
if (!isAllowed) {
|
|
47
|
-
const details = {
|
|
48
|
-
requested: tool,
|
|
49
|
-
allowed: constraints.allowedTools,
|
|
50
|
-
constraint: 'tool',
|
|
51
|
-
fix: `Update policy.allowedTools to include "${tool}" or "${service}:*" or request approval`,
|
|
52
|
-
};
|
|
53
|
-
return (0, shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION, `Tool "${tool}" is not allowed by policy`, details));
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
// Check scopes
|
|
57
|
-
if (constraints.scopes && constraints.scopes.length > 0) {
|
|
58
|
-
// Extract scope from params if present
|
|
59
|
-
const scope = typeof params === 'object' && params !== null && 'scope' in params
|
|
60
|
-
? params.scope
|
|
61
|
-
: undefined;
|
|
62
|
-
if (scope && !constraints.scopes.includes(scope)) {
|
|
63
|
-
const details = {
|
|
64
|
-
requested: scope,
|
|
65
|
-
allowed: constraints.scopes,
|
|
66
|
-
constraint: 'scope',
|
|
67
|
-
fix: `Update policy.scopes to include "${scope}" or request additional permissions`,
|
|
68
|
-
};
|
|
69
|
-
return (0, shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION, `Scope "${scope}" is not allowed by policy`, details));
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
// Check rate limits
|
|
73
|
-
if (constraints.limits?.callsPerMinute) {
|
|
74
|
-
const rateCheck = this.checkRateLimit(agentDID, constraints.limits.callsPerMinute);
|
|
75
|
-
if (!rateCheck.ok) {
|
|
76
|
-
return rateCheck;
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
// Check spending limits (if amount is in params)
|
|
80
|
-
const amount = this.extractAmount(params);
|
|
81
|
-
if (amount !== null) {
|
|
82
|
-
// Check per-transaction limit
|
|
83
|
-
if (constraints.limits?.amountPerTxn && amount > constraints.limits.amountPerTxn) {
|
|
84
|
-
const details = {
|
|
85
|
-
requested: amount,
|
|
86
|
-
allowed: constraints.limits.amountPerTxn,
|
|
87
|
-
constraint: 'amountPerTxn',
|
|
88
|
-
fix: `Reduce amount to ${constraints.limits.amountPerTxn} or less, or update policy.limits.amountPerTxn`,
|
|
89
|
-
};
|
|
90
|
-
return (0, shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION, `Amount ${amount} exceeds per-transaction limit of ${constraints.limits.amountPerTxn}`, details));
|
|
91
|
-
}
|
|
92
|
-
// Check daily limit
|
|
93
|
-
if (constraints.limits?.dailyAmount) {
|
|
94
|
-
const dailyCheck = this.checkDailyLimit(agentDID, amount, constraints.limits.dailyAmount);
|
|
95
|
-
if (!dailyCheck.ok) {
|
|
96
|
-
return dailyCheck;
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
// Check monthly limit
|
|
100
|
-
if (constraints.limits?.monthlyAmount) {
|
|
101
|
-
const monthlyCheck = this.checkMonthlyLimit(agentDID, amount, constraints.limits.monthlyAmount);
|
|
102
|
-
if (!monthlyCheck.ok) {
|
|
103
|
-
return monthlyCheck;
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
// All checks passed
|
|
108
|
-
return (0, shared_1.ok)(undefined);
|
|
109
|
-
}
|
|
110
|
-
/**
|
|
111
|
-
* Record a successful call (for rate limiting)
|
|
112
|
-
*
|
|
113
|
-
* @param agentDID - Agent DID
|
|
114
|
-
*/
|
|
115
|
-
recordCall(agentDID) {
|
|
116
|
-
const now = Date.now();
|
|
117
|
-
const entry = this.rateLimits.get(agentDID) ?? {
|
|
118
|
-
calls: [],
|
|
119
|
-
windowStart: now,
|
|
120
|
-
};
|
|
121
|
-
entry.calls.push(now);
|
|
122
|
-
// Clean up old calls (older than 1 minute)
|
|
123
|
-
const oneMinuteAgo = now - 60000;
|
|
124
|
-
entry.calls = entry.calls.filter((timestamp) => timestamp > oneMinuteAgo);
|
|
125
|
-
this.rateLimits.set(agentDID, entry);
|
|
126
|
-
}
|
|
127
|
-
/**
|
|
128
|
-
* Record successful spending (for daily and monthly limits)
|
|
129
|
-
*
|
|
130
|
-
* @param agentDID - Agent DID
|
|
131
|
-
* @param amount - Amount spent
|
|
132
|
-
*/
|
|
133
|
-
recordSpending(agentDID, amount) {
|
|
134
|
-
const today = this.getCurrentDay();
|
|
135
|
-
const thisMonth = this.getCurrentMonth();
|
|
136
|
-
// Update daily spending
|
|
137
|
-
const dailyEntry = this.dailySpending.get(agentDID);
|
|
138
|
-
if (dailyEntry && dailyEntry.day === today) {
|
|
139
|
-
dailyEntry.amount += amount;
|
|
140
|
-
}
|
|
141
|
-
else {
|
|
142
|
-
this.dailySpending.set(agentDID, {
|
|
143
|
-
amount,
|
|
144
|
-
day: today,
|
|
145
|
-
});
|
|
146
|
-
}
|
|
147
|
-
// Update monthly spending
|
|
148
|
-
const monthlyEntry = this.monthlySpending.get(agentDID);
|
|
149
|
-
if (monthlyEntry && monthlyEntry.month === thisMonth) {
|
|
150
|
-
monthlyEntry.amount += amount;
|
|
151
|
-
}
|
|
152
|
-
else {
|
|
153
|
-
this.monthlySpending.set(agentDID, {
|
|
154
|
-
amount,
|
|
155
|
-
month: thisMonth,
|
|
156
|
-
});
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
/**
|
|
160
|
-
* Get current rate limit status for an agent
|
|
161
|
-
*
|
|
162
|
-
* @param agentDID - Agent DID
|
|
163
|
-
* @returns Calls in current minute
|
|
164
|
-
*/
|
|
165
|
-
getCurrentRateLimit(agentDID) {
|
|
166
|
-
const entry = this.rateLimits.get(agentDID);
|
|
167
|
-
if (!entry)
|
|
168
|
-
return 0;
|
|
169
|
-
const now = Date.now();
|
|
170
|
-
const oneMinuteAgo = now - 60000;
|
|
171
|
-
// Count calls in last minute
|
|
172
|
-
return entry.calls.filter((timestamp) => timestamp > oneMinuteAgo).length;
|
|
173
|
-
}
|
|
174
|
-
/**
|
|
175
|
-
* Get current daily spending for an agent
|
|
176
|
-
*
|
|
177
|
-
* @param agentDID - Agent DID
|
|
178
|
-
* @returns Amount spent today
|
|
179
|
-
*/
|
|
180
|
-
getDailySpending(agentDID) {
|
|
181
|
-
const today = this.getCurrentDay();
|
|
182
|
-
const entry = this.dailySpending.get(agentDID);
|
|
183
|
-
if (!entry || entry.day !== today)
|
|
184
|
-
return 0;
|
|
185
|
-
return entry.amount;
|
|
186
|
-
}
|
|
187
|
-
/**
|
|
188
|
-
* Get current monthly spending for an agent
|
|
189
|
-
*
|
|
190
|
-
* @param agentDID - Agent DID
|
|
191
|
-
* @returns Amount spent this month
|
|
192
|
-
*/
|
|
193
|
-
getMonthlySpending(agentDID) {
|
|
194
|
-
const thisMonth = this.getCurrentMonth();
|
|
195
|
-
const entry = this.monthlySpending.get(agentDID);
|
|
196
|
-
if (!entry || entry.month !== thisMonth)
|
|
197
|
-
return 0;
|
|
198
|
-
return entry.amount;
|
|
199
|
-
}
|
|
200
|
-
/**
|
|
201
|
-
* Reset all limits for an agent (for testing)
|
|
202
|
-
*
|
|
203
|
-
* @param agentDID - Agent DID
|
|
204
|
-
*/
|
|
205
|
-
reset(agentDID) {
|
|
206
|
-
this.rateLimits.delete(agentDID);
|
|
207
|
-
this.dailySpending.delete(agentDID);
|
|
208
|
-
this.monthlySpending.delete(agentDID);
|
|
209
|
-
}
|
|
210
|
-
/**
|
|
211
|
-
* Check rate limit
|
|
212
|
-
*/
|
|
213
|
-
checkRateLimit(agentDID, limit) {
|
|
214
|
-
const current = this.getCurrentRateLimit(agentDID);
|
|
215
|
-
if (current >= limit) {
|
|
216
|
-
const details = {
|
|
217
|
-
requested: current + 1,
|
|
218
|
-
allowed: limit,
|
|
219
|
-
constraint: 'callsPerMinute',
|
|
220
|
-
current,
|
|
221
|
-
fix: `Wait before making additional calls, or update policy.limits.callsPerMinute to a higher value`,
|
|
222
|
-
};
|
|
223
|
-
return (0, shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION, `Rate limit exceeded: ${current}/${limit} calls per minute`, details));
|
|
224
|
-
}
|
|
225
|
-
return (0, shared_1.ok)(undefined);
|
|
226
|
-
}
|
|
227
|
-
/**
|
|
228
|
-
* Check daily spending limit
|
|
229
|
-
*/
|
|
230
|
-
checkDailyLimit(agentDID, amount, limit) {
|
|
231
|
-
const current = this.getDailySpending(agentDID);
|
|
232
|
-
const newTotal = current + amount;
|
|
233
|
-
if (newTotal > limit) {
|
|
234
|
-
const remaining = limit - current;
|
|
235
|
-
const details = {
|
|
236
|
-
requested: amount,
|
|
237
|
-
allowed: limit,
|
|
238
|
-
constraint: 'dailyAmount',
|
|
239
|
-
current,
|
|
240
|
-
newTotal,
|
|
241
|
-
fix: remaining > 0
|
|
242
|
-
? `Reduce amount to ${remaining} or less (remaining today), or update policy.limits.dailyAmount`
|
|
243
|
-
: `Daily limit already reached. Wait until tomorrow or update policy.limits.dailyAmount`,
|
|
244
|
-
};
|
|
245
|
-
return (0, shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION, `Amount ${amount} would exceed daily limit: ${newTotal}/${limit} (current: ${current})`, details));
|
|
246
|
-
}
|
|
247
|
-
return (0, shared_1.ok)(undefined);
|
|
248
|
-
}
|
|
249
|
-
/**
|
|
250
|
-
* Extract amount from params
|
|
251
|
-
*/
|
|
252
|
-
extractAmount(params) {
|
|
253
|
-
if (typeof params !== 'object' || params === null)
|
|
254
|
-
return null;
|
|
255
|
-
const obj = params;
|
|
256
|
-
// Check common amount field names
|
|
257
|
-
if (typeof obj.amount === 'number')
|
|
258
|
-
return obj.amount;
|
|
259
|
-
if (typeof obj.value === 'number')
|
|
260
|
-
return obj.value;
|
|
261
|
-
if (typeof obj.price === 'number')
|
|
262
|
-
return obj.price;
|
|
263
|
-
if (typeof obj.total === 'number')
|
|
264
|
-
return obj.total;
|
|
265
|
-
return null;
|
|
266
|
-
}
|
|
267
|
-
/**
|
|
268
|
-
* Get current day identifier (YYYY-MM-DD in UTC)
|
|
269
|
-
*/
|
|
270
|
-
getCurrentDay() {
|
|
271
|
-
const now = new Date();
|
|
272
|
-
return now.toISOString().split('T')[0] ?? '';
|
|
273
|
-
}
|
|
274
|
-
/**
|
|
275
|
-
* Get current month identifier (YYYY-MM in UTC)
|
|
276
|
-
*/
|
|
277
|
-
getCurrentMonth() {
|
|
278
|
-
const now = new Date();
|
|
279
|
-
const iso = now.toISOString();
|
|
280
|
-
return iso.substring(0, 7); // YYYY-MM
|
|
281
|
-
}
|
|
282
|
-
/**
|
|
283
|
-
* Check monthly spending limit
|
|
284
|
-
*/
|
|
285
|
-
checkMonthlyLimit(agentDID, amount, limit) {
|
|
286
|
-
const current = this.getMonthlySpending(agentDID);
|
|
287
|
-
const newTotal = current + amount;
|
|
288
|
-
if (newTotal > limit) {
|
|
289
|
-
const remaining = limit - current;
|
|
290
|
-
const details = {
|
|
291
|
-
requested: amount,
|
|
292
|
-
allowed: limit,
|
|
293
|
-
constraint: 'dailyAmount', // Reuse constraint type (will add monthlyAmount later)
|
|
294
|
-
current,
|
|
295
|
-
newTotal,
|
|
296
|
-
fix: remaining > 0
|
|
297
|
-
? `Reduce amount to ${remaining} or less (remaining this month), or update policy.limits.monthlyAmount`
|
|
298
|
-
: `Monthly limit already reached. Wait until next month or update policy.limits.monthlyAmount`,
|
|
299
|
-
};
|
|
300
|
-
return (0, shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION, `Amount ${amount} would exceed monthly limit: ${newTotal}/${limit} (current: ${current})`, details));
|
|
301
|
-
}
|
|
302
|
-
return (0, shared_1.ok)(undefined);
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
exports.PolicyEngine = PolicyEngine;
|
|
306
|
-
/**
|
|
307
|
-
* Global policy engine instance (singleton)
|
|
308
|
-
*/
|
|
309
|
-
let globalPolicyEngine = null;
|
|
310
|
-
/**
|
|
311
|
-
* Get the global policy engine instance
|
|
312
|
-
*
|
|
313
|
-
* @returns PolicyEngine instance
|
|
314
|
-
*/
|
|
315
|
-
function getGlobalPolicyEngine() {
|
|
316
|
-
if (!globalPolicyEngine) {
|
|
317
|
-
globalPolicyEngine = new PolicyEngine();
|
|
318
|
-
}
|
|
319
|
-
return globalPolicyEngine;
|
|
320
|
-
}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PolicyEngine=void 0,exports.getGlobalPolicyEngine=getGlobalPolicyEngine;const shared_1=require("../_deps/shared/index.js"),agent_call_js_1=require("./agent-call.js");class PolicyEngine{rateLimits=new Map;dailySpending=new Map;monthlySpending=new Map;evaluate(t,e,n,o){if(o.allowedTools&&o.allowedTools.length>0){const[t]=e.split(":");if(!o.allowedTools.some(n=>n===e||n===`${t}:*`||"*"===n)){const n={requested:e,allowed:o.allowedTools,constraint:"tool",fix:`Update policy.allowedTools to include "${e}" or "${t}:*" or request approval`};return(0,shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION,`Tool "${e}" is not allowed by policy`,n))}}if(o.scopes&&o.scopes.length>0){const t="object"==typeof n&&null!==n&&"scope"in n?n.scope:void 0;if(t&&!o.scopes.includes(t)){const e={requested:t,allowed:o.scopes,constraint:"scope",fix:`Update policy.scopes to include "${t}" or request additional permissions`};return(0,shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION,`Scope "${t}" is not allowed by policy`,e))}}if(o.limits?.callsPerMinute){const e=this.checkRateLimit(t,o.limits.callsPerMinute);if(!e.ok)return e}const i=this.extractAmount(n);if(null!==i){if(o.limits?.amountPerTxn&&i>o.limits.amountPerTxn){const t={requested:i,allowed:o.limits.amountPerTxn,constraint:"amountPerTxn",fix:`Reduce amount to ${o.limits.amountPerTxn} or less, or update policy.limits.amountPerTxn`};return(0,shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION,`Amount ${i} exceeds per-transaction limit of ${o.limits.amountPerTxn}`,t))}if(o.limits?.dailyAmount){const e=this.checkDailyLimit(t,i,o.limits.dailyAmount);if(!e.ok)return e}if(o.limits?.monthlyAmount){const e=this.checkMonthlyLimit(t,i,o.limits.monthlyAmount);if(!e.ok)return e}}return(0,shared_1.ok)(void 0)}recordCall(t){const e=Date.now(),n=this.rateLimits.get(t)??{calls:[],windowStart:e};n.calls.push(e);const o=e-6e4;n.calls=n.calls.filter(t=>t>o),this.rateLimits.set(t,n)}recordSpending(t,e){const n=this.getCurrentDay(),o=this.getCurrentMonth(),i=this.dailySpending.get(t);i&&i.day===n?i.amount+=e:this.dailySpending.set(t,{amount:e,day:n});const l=this.monthlySpending.get(t);l&&l.month===o?l.amount+=e:this.monthlySpending.set(t,{amount:e,month:o})}getCurrentRateLimit(t){const e=this.rateLimits.get(t);if(!e)return 0;const n=Date.now()-6e4;return e.calls.filter(t=>t>n).length}getDailySpending(t){const e=this.getCurrentDay(),n=this.dailySpending.get(t);return n&&n.day===e?n.amount:0}getMonthlySpending(t){const e=this.getCurrentMonth(),n=this.monthlySpending.get(t);return n&&n.month===e?n.amount:0}reset(t){this.rateLimits.delete(t),this.dailySpending.delete(t),this.monthlySpending.delete(t)}checkRateLimit(t,e){const n=this.getCurrentRateLimit(t);if(n>=e){const t={requested:n+1,allowed:e,constraint:"callsPerMinute",current:n,fix:"Wait before making additional calls, or update policy.limits.callsPerMinute to a higher value"};return(0,shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION,`Rate limit exceeded: ${n}/${e} calls per minute`,t))}return(0,shared_1.ok)(void 0)}checkDailyLimit(t,e,n){const o=this.getDailySpending(t),i=o+e;if(i>n){const t=n-o,l={requested:e,allowed:n,constraint:"dailyAmount",current:o,newTotal:i,fix:t>0?`Reduce amount to ${t} or less (remaining today), or update policy.limits.dailyAmount`:"Daily limit already reached. Wait until tomorrow or update policy.limits.dailyAmount"};return(0,shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION,`Amount ${e} would exceed daily limit: ${i}/${n} (current: ${o})`,l))}return(0,shared_1.ok)(void 0)}extractAmount(t){if("object"!=typeof t||null===t)return null;const e=t;return"number"==typeof e.amount?e.amount:"number"==typeof e.value?e.value:"number"==typeof e.price?e.price:"number"==typeof e.total?e.total:null}getCurrentDay(){return(new Date).toISOString().split("T")[0]??""}getCurrentMonth(){return(new Date).toISOString().substring(0,7)}checkMonthlyLimit(t,e,n){const o=this.getMonthlySpending(t),i=o+e;if(i>n){const t=n-o,l={requested:e,allowed:n,constraint:"dailyAmount",current:o,newTotal:i,fix:t>0?`Reduce amount to ${t} or less (remaining this month), or update policy.limits.monthlyAmount`:"Monthly limit already reached. Wait until next month or update policy.limits.monthlyAmount"};return(0,shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION,`Amount ${e} would exceed monthly limit: ${i}/${n} (current: ${o})`,l))}return(0,shared_1.ok)(void 0)}}exports.PolicyEngine=PolicyEngine;let globalPolicyEngine=null;function getGlobalPolicyEngine(){return globalPolicyEngine||(globalPolicyEngine=new PolicyEngine),globalPolicyEngine}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.EncryptionProgressTracker=exports.ShareDistributionTracker=exports.TransferProgressTracker=exports.OperationProgressTracker=void 0;const ux_helpers_1=require("../_deps/ux-helpers/index.js");class OperationProgressTracker{callback;throttleMs;lastUpdateTime=0;currentStage="";currentStageWeight=0;currentStageProgress=0;completedWeight=0;metadata={};constructor(t,e){this.callback=t,this.throttleMs=e?.throttleMs??100}startStage(t,e,s){this.currentStage=t,this.currentStageWeight=Math.max(0,Math.min(100,e)),this.currentStageProgress=0,this.reportProgress(s??`Starting ${t}...`)}updateStageProgress(t,e,s){this.currentStageProgress=Math.max(0,Math.min(100,t)),s&&(this.metadata={...this.metadata,...s});const r=e??`${this.currentStage} (${Math.round(t)}%)`;this.reportProgress(r)}completeStage(){this.currentStageProgress=100,this.completedWeight+=this.currentStageWeight,this.reportProgress(`${this.currentStage} complete`),this.currentStage="",this.currentStageWeight=0,this.currentStageProgress=0}complete(){this.completedWeight=100,this.currentStageProgress=100,this.reportProgress("Complete")}getProgress(){const t=this.currentStageWeight*this.currentStageProgress/100;return Math.min(100,this.completedWeight+t)}updateMetadata(t){this.metadata={...this.metadata,...t}}reportProgress(t){if(!this.callback)return;const e=Date.now();if(e-this.lastUpdateTime<this.throttleMs){if(this.getProgress()<100)return}this.lastUpdateTime=e;const s=this.getProgress();if(this.isEnhancedCallback(this.callback)){const e={stage:this.currentStage,progress:s,stageProgress:this.currentStageProgress,status:t,metadata:Object.keys(this.metadata).length>0?this.metadata:void 0};this.callback(e)}else this.callback(t,s)}isEnhancedCallback(t){return 1===t.length}}exports.OperationProgressTracker=OperationProgressTracker;class TransferProgressTracker{totalBytes;callback;reporter;throttleMs;bytesTransferred=0;startTime=Date.now();lastUpdateTime=0;samples=[];maxSamples=10;constructor(t,e,s=100){this.totalBytes=t,this.callback=e,this.throttleMs=s,this.reporter=new ux_helpers_1.ProgressReporter("function"==typeof e&&2===e.length?e:void 0)}addTransferred(t){this.bytesTransferred+=t;const e=Date.now();this.samples.push({time:e,bytes:this.bytesTransferred}),this.samples.length>this.maxSamples&&this.samples.shift(),e-this.lastUpdateTime<this.throttleMs||(this.lastUpdateTime=e,this.reportProgress())}complete(){this.bytesTransferred=this.totalBytes,this.reportProgress()}getProgress(){return 0===this.totalBytes?100:Math.min(100,this.bytesTransferred/this.totalBytes*100)}calculateBytesPerSecond(){if(this.samples.length<2){const t=(Date.now()-this.startTime)/1e3;return t>0?this.bytesTransferred/t:0}const t=this.samples[0],e=this.samples[this.samples.length-1];if(!t||!e)return 0;const s=(e.time-t.time)/1e3,r=e.bytes-t.bytes;return s>0?r/s:0}estimateTimeRemaining(){const t=this.calculateBytesPerSecond();if(0===t)return 0;return(this.totalBytes-this.bytesTransferred)/t*1e3}reportProgress(){if(!this.callback)return;const t=this.getProgress(),e=this.calculateBytesPerSecond(),s=this.estimateTimeRemaining(),r=this.formatStatus(t,e,s);if(this.isEnhancedCallback(this.callback)){const a={stage:"transfer",progress:t,stageProgress:t,status:r,metadata:{bytesTransferred:this.bytesTransferred,totalBytes:this.totalBytes,bytesPerSecond:e,estimatedTimeRemaining:s}};this.callback(a)}else this.reporter.report(r,t)}formatStatus(t,e,s){const r=this.formatBytes(this.bytesTransferred),a=this.formatBytes(this.totalBytes),i=this.formatBytes(e),o=this.formatTime(s);return`Transferring ${r} / ${a} (${Math.round(t)}%) - ${i}/s - ${o} remaining`}formatBytes(t){const e=["B","KB","MB","GB","TB"];let s=t,r=0;for(;s>=1024&&r<e.length-1;)s/=1024,r++;return`${s.toFixed(1)} ${e[r]}`}formatTime(t){const e=Math.floor(t/1e3);if(e<60)return`${e}s`;const s=Math.floor(e/60);if(s<60)return`${s}m ${e%60}s`;return`${Math.floor(s/60)}h ${s%60}m`}isEnhancedCallback(t){return 1===t.length}}exports.TransferProgressTracker=TransferProgressTracker;class ShareDistributionTracker{totalShares;callback;reporter;distributedShares=new Set;constructor(t,e){this.totalShares=t,this.callback=e,this.reporter=new ux_helpers_1.ProgressReporter("function"==typeof e&&2===e.length?e:void 0)}markShareDistributed(t){this.distributedShares.add(t),this.reportProgress()}complete(){for(let t=0;t<this.totalShares;t++)this.distributedShares.add(t);this.reportProgress()}getProgress(){return 0===this.totalShares?100:this.distributedShares.size/this.totalShares*100}reportProgress(){if(!this.callback)return;const t=this.getProgress(),e=`Distributed ${this.distributedShares.size} / ${this.totalShares} shares`;if(this.isEnhancedCallback(this.callback)){const s={stage:"distribution",progress:t,stageProgress:t,status:e,metadata:{sharesDistributed:this.distributedShares.size,totalShares:this.totalShares}};this.callback(s)}else this.reporter.report(e,t)}isEnhancedCallback(t){return 1===t.length}}exports.ShareDistributionTracker=ShareDistributionTracker;class EncryptionProgressTracker{operation;totalItems;callback;reporter;itemsProcessed=0;constructor(t,e,s){this.operation=t,this.totalItems=e,this.callback=s,this.reporter=new ux_helpers_1.ProgressReporter("function"==typeof s&&2===s.length?s:void 0)}incrementProcessed(t=1){this.itemsProcessed+=t,this.reportProgress()}complete(){this.itemsProcessed=this.totalItems,this.reportProgress()}getProgress(){return 0===this.totalItems?100:Math.min(100,this.itemsProcessed/this.totalItems*100)}reportProgress(){if(!this.callback)return;const t=this.getProgress(),e=`${this.operation.charAt(0).toUpperCase()+this.operation.slice(1)}ing: ${this.itemsProcessed} / ${this.totalItems} items`;if(this.isEnhancedCallback(this.callback)){const s={stage:this.operation,progress:t,stageProgress:t,status:e,metadata:{cryptoOperation:this.operation,itemsProcessed:this.itemsProcessed,totalItems:this.totalItems}};this.callback(s)}else this.reporter.report(e,t)}isEnhancedCallback(t){return 1===t.length}}exports.EncryptionProgressTracker=EncryptionProgressTracker;
|