@private.me/xbind 1.2.0
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/AGENTS.md +778 -0
- package/LICENSE.md +27 -0
- package/README.md +400 -0
- package/dist-standalone/_deps/crypto/base64.d.ts +29 -0
- package/dist-standalone/_deps/crypto/base64.js +97 -0
- package/dist-standalone/_deps/crypto/cjs/base64.js +103 -0
- package/dist-standalone/_deps/crypto/cjs/errors.js +119 -0
- package/dist-standalone/_deps/crypto/cjs/hmac.js +71 -0
- package/dist-standalone/_deps/crypto/cjs/index.js +86 -0
- package/dist-standalone/_deps/crypto/cjs/padding.js +57 -0
- package/dist-standalone/_deps/crypto/cjs/share-header.js +68 -0
- package/dist-standalone/_deps/crypto/cjs/shares.js +152 -0
- package/dist-standalone/_deps/crypto/cjs/tlv.js +199 -0
- package/dist-standalone/_deps/crypto/cjs/uuid.js +61 -0
- package/dist-standalone/_deps/crypto/cjs/verify.js +24 -0
- package/dist-standalone/_deps/crypto/cjs/xorida.js +221 -0
- package/dist-standalone/_deps/crypto/errors.d.ts +51 -0
- package/dist-standalone/_deps/crypto/errors.js +109 -0
- package/dist-standalone/_deps/crypto/hmac.d.ts +39 -0
- package/dist-standalone/_deps/crypto/hmac.js +66 -0
- package/dist-standalone/_deps/crypto/index.d.ts +20 -0
- package/dist-standalone/_deps/crypto/index.js +45 -0
- package/dist-standalone/_deps/crypto/padding.d.ts +19 -0
- package/dist-standalone/_deps/crypto/padding.js +53 -0
- package/dist-standalone/_deps/crypto/share-header.d.ts +44 -0
- package/dist-standalone/_deps/crypto/share-header.js +63 -0
- package/dist-standalone/_deps/crypto/shares.d.ts +27 -0
- package/dist-standalone/_deps/crypto/shares.js +148 -0
- package/dist-standalone/_deps/crypto/tlv.d.ts +26 -0
- package/dist-standalone/_deps/crypto/tlv.js +195 -0
- package/dist-standalone/_deps/crypto/uuid.d.ts +22 -0
- package/dist-standalone/_deps/crypto/uuid.js +56 -0
- package/dist-standalone/_deps/crypto/verify.d.ts +15 -0
- package/dist-standalone/_deps/crypto/verify.js +15 -0
- package/dist-standalone/_deps/crypto/xorida.d.ts +44 -0
- package/dist-standalone/_deps/crypto/xorida.js +215 -0
- package/dist-standalone/_deps/mldsa-wasm/LICENSE +24 -0
- package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1920 -0
- package/dist-standalone/_deps/mldsa-wasm/package.json +46 -0
- package/dist-standalone/_deps/mldsa-wasm/types/mldsa.d.ts +30 -0
- package/dist-standalone/_deps/shared/cjs/errors.js +582 -0
- package/dist-standalone/_deps/shared/cjs/index.js +492 -0
- package/dist-standalone/_deps/shared/cjs/package.json +1 -0
- package/dist-standalone/_deps/shared/cjs/types.js +403 -0
- package/dist-standalone/_deps/shared/errors.d.ts +48 -0
- package/dist-standalone/_deps/shared/errors.d.ts.map +1 -0
- package/dist-standalone/_deps/shared/errors.js +192 -0
- package/dist-standalone/_deps/shared/errors.js.map +1 -0
- package/dist-standalone/_deps/shared/index.d.ts +4 -0
- package/dist-standalone/_deps/shared/index.d.ts.map +1 -0
- package/dist-standalone/_deps/shared/index.js +78 -0
- package/dist-standalone/_deps/shared/index.js.map +1 -0
- package/dist-standalone/_deps/shared/types.d.ts +1097 -0
- package/dist-standalone/_deps/shared/types.d.ts.map +1 -0
- package/dist-standalone/_deps/shared/types.js +89 -0
- package/dist-standalone/_deps/shared/types.js.map +1 -0
- package/dist-standalone/_deps/ux-helpers/cjs/errors.d.ts +115 -0
- package/dist-standalone/_deps/ux-helpers/cjs/errors.d.ts.map +1 -0
- package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -0
- package/dist-standalone/_deps/ux-helpers/cjs/errors.js.map +1 -0
- package/dist-standalone/_deps/ux-helpers/cjs/index.d.ts +13 -0
- package/dist-standalone/_deps/ux-helpers/cjs/index.d.ts.map +1 -0
- package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -0
- package/dist-standalone/_deps/ux-helpers/cjs/index.js.map +1 -0
- package/dist-standalone/_deps/ux-helpers/cjs/package.json +1 -0
- package/dist-standalone/_deps/ux-helpers/cjs/pagination.d.ts +39 -0
- package/dist-standalone/_deps/ux-helpers/cjs/pagination.d.ts.map +1 -0
- package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +83 -0
- package/dist-standalone/_deps/ux-helpers/cjs/pagination.js.map +1 -0
- package/dist-standalone/_deps/ux-helpers/cjs/progress.d.ts +99 -0
- package/dist-standalone/_deps/ux-helpers/cjs/progress.d.ts.map +1 -0
- package/dist-standalone/_deps/ux-helpers/cjs/progress.js +143 -0
- package/dist-standalone/_deps/ux-helpers/cjs/progress.js.map +1 -0
- package/dist-standalone/_deps/ux-helpers/cjs/search.d.ts +32 -0
- package/dist-standalone/_deps/ux-helpers/cjs/search.d.ts.map +1 -0
- package/dist-standalone/_deps/ux-helpers/cjs/search.js +119 -0
- package/dist-standalone/_deps/ux-helpers/cjs/search.js.map +1 -0
- package/dist-standalone/_deps/ux-helpers/cjs/types.d.ts +109 -0
- package/dist-standalone/_deps/ux-helpers/cjs/types.d.ts.map +1 -0
- package/dist-standalone/_deps/ux-helpers/cjs/types.js +8 -0
- package/dist-standalone/_deps/ux-helpers/cjs/types.js.map +1 -0
- package/dist-standalone/_deps/ux-helpers/errors.d.ts +115 -0
- package/dist-standalone/_deps/ux-helpers/errors.d.ts.map +1 -0
- package/dist-standalone/_deps/ux-helpers/errors.js +253 -0
- package/dist-standalone/_deps/ux-helpers/errors.js.map +1 -0
- package/dist-standalone/_deps/ux-helpers/index.d.ts +13 -0
- package/dist-standalone/_deps/ux-helpers/index.d.ts.map +1 -0
- package/dist-standalone/_deps/ux-helpers/index.js +16 -0
- package/dist-standalone/_deps/ux-helpers/index.js.map +1 -0
- package/dist-standalone/_deps/ux-helpers/pagination.d.ts +39 -0
- package/dist-standalone/_deps/ux-helpers/pagination.d.ts.map +1 -0
- package/dist-standalone/_deps/ux-helpers/pagination.js +79 -0
- package/dist-standalone/_deps/ux-helpers/pagination.js.map +1 -0
- package/dist-standalone/_deps/ux-helpers/progress.d.ts +99 -0
- package/dist-standalone/_deps/ux-helpers/progress.d.ts.map +1 -0
- package/dist-standalone/_deps/ux-helpers/progress.js +138 -0
- package/dist-standalone/_deps/ux-helpers/progress.js.map +1 -0
- package/dist-standalone/_deps/ux-helpers/search.d.ts +32 -0
- package/dist-standalone/_deps/ux-helpers/search.d.ts.map +1 -0
- package/dist-standalone/_deps/ux-helpers/search.js +116 -0
- package/dist-standalone/_deps/ux-helpers/search.js.map +1 -0
- package/dist-standalone/_deps/ux-helpers/types.d.ts +109 -0
- package/dist-standalone/_deps/ux-helpers/types.d.ts.map +1 -0
- package/dist-standalone/_deps/ux-helpers/types.js +7 -0
- package/dist-standalone/_deps/ux-helpers/types.js.map +1 -0
- package/dist-standalone/_deps/xchange/auto-accept.d.ts +127 -0
- package/dist-standalone/_deps/xchange/auto-accept.js +1 -0
- package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -0
- package/dist-standalone/_deps/xchange/cjs/errors.js +1 -0
- package/dist-standalone/_deps/xchange/cjs/index.js +1 -0
- package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -0
- package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -0
- package/dist-standalone/_deps/xchange/cjs/package.json +1 -0
- package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -0
- package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -0
- package/dist-standalone/_deps/xchange/errors.d.ts +69 -0
- package/dist-standalone/_deps/xchange/errors.js +1 -0
- package/dist-standalone/_deps/xchange/index.d.ts +15 -0
- package/dist-standalone/_deps/xchange/index.js +1 -0
- package/dist-standalone/_deps/xchange/invite-client.d.ts +178 -0
- package/dist-standalone/_deps/xchange/invite-client.js +1 -0
- package/dist-standalone/_deps/xchange/lazy-init.d.ts +176 -0
- package/dist-standalone/_deps/xchange/lazy-init.js +1 -0
- package/dist-standalone/_deps/xchange/trust-integration.d.ts +102 -0
- package/dist-standalone/_deps/xchange/trust-integration.js +1 -0
- package/dist-standalone/_deps/xchange/xchange.d.ts +60 -0
- package/dist-standalone/_deps/xchange/xchange.js +1 -0
- package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -0
- package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -0
- package/dist-standalone/_deps/xregistry/cjs/index.js +1 -0
- package/dist-standalone/_deps/xregistry/cjs/package.json +1 -0
- package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -0
- package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -0
- package/dist-standalone/_deps/xregistry/cjs/types.js +1 -0
- package/dist-standalone/_deps/xregistry/discovery.d.ts +126 -0
- package/dist-standalone/_deps/xregistry/discovery.d.ts.map +1 -0
- package/dist-standalone/_deps/xregistry/discovery.js +1 -0
- package/dist-standalone/_deps/xregistry/discovery.js.map +1 -0
- package/dist-standalone/_deps/xregistry/errors.d.ts +41 -0
- package/dist-standalone/_deps/xregistry/errors.d.ts.map +1 -0
- package/dist-standalone/_deps/xregistry/errors.js +1 -0
- package/dist-standalone/_deps/xregistry/errors.js.map +1 -0
- package/dist-standalone/_deps/xregistry/index.d.ts +8 -0
- package/dist-standalone/_deps/xregistry/index.d.ts.map +1 -0
- package/dist-standalone/_deps/xregistry/index.js +1 -0
- package/dist-standalone/_deps/xregistry/index.js.map +1 -0
- package/dist-standalone/_deps/xregistry/registry.d.ts +85 -0
- package/dist-standalone/_deps/xregistry/registry.d.ts.map +1 -0
- package/dist-standalone/_deps/xregistry/registry.js +1 -0
- package/dist-standalone/_deps/xregistry/registry.js.map +1 -0
- package/dist-standalone/_deps/xregistry/schema.d.ts +81 -0
- package/dist-standalone/_deps/xregistry/schema.d.ts.map +1 -0
- package/dist-standalone/_deps/xregistry/schema.js +1 -0
- package/dist-standalone/_deps/xregistry/schema.js.map +1 -0
- package/dist-standalone/_deps/xregistry/types.d.ts +95 -0
- package/dist-standalone/_deps/xregistry/types.d.ts.map +1 -0
- package/dist-standalone/_deps/xregistry/types.js +1 -0
- package/dist-standalone/_deps/xregistry/types.js.map +1 -0
- package/dist-standalone/agent-call.d.ts +286 -0
- package/dist-standalone/agent-call.js +642 -0
- package/dist-standalone/agent-sdk.d.ts +207 -0
- package/dist-standalone/agent-sdk.js +328 -0
- package/dist-standalone/agent.d.ts +670 -0
- package/dist-standalone/agent.js +1529 -0
- package/dist-standalone/approval.d.ts +145 -0
- package/dist-standalone/approval.js +193 -0
- package/dist-standalone/auth.d.ts +75 -0
- package/dist-standalone/auth.js +219 -0
- package/dist-standalone/auto-accept.d.ts +102 -0
- package/dist-standalone/auto-accept.js +229 -0
- package/dist-standalone/backup-config.d.ts +150 -0
- package/dist-standalone/backup-config.js +201 -0
- package/dist-standalone/checkpoint.d.ts +125 -0
- package/dist-standalone/checkpoint.js +186 -0
- package/dist-standalone/cjs/agent-call.js +651 -0
- package/dist-standalone/cjs/agent-sdk.js +332 -0
- package/dist-standalone/cjs/agent.js +1566 -0
- package/dist-standalone/cjs/approval.js +199 -0
- package/dist-standalone/cjs/auth.js +225 -0
- package/dist-standalone/cjs/auto-accept.js +233 -0
- package/dist-standalone/cjs/backup-config.js +207 -0
- package/dist-standalone/cjs/checkpoint.js +193 -0
- package/dist-standalone/cjs/cli/init.js +487 -0
- package/dist-standalone/cjs/connect.js +312 -0
- package/dist-standalone/cjs/did-document.js +101 -0
- package/dist-standalone/cjs/did-privateme.js +130 -0
- package/dist-standalone/cjs/did-web.js +201 -0
- package/dist-standalone/cjs/discovery.js +462 -0
- package/dist-standalone/cjs/dual-mode.js +251 -0
- package/dist-standalone/cjs/email-templates.js +313 -0
- package/dist-standalone/cjs/email-transport.js +239 -0
- package/dist-standalone/cjs/envelope.js +510 -0
- package/dist-standalone/cjs/errors.js +562 -0
- package/dist-standalone/cjs/gateway-state.js +55 -0
- package/dist-standalone/cjs/gateway-transport.js +120 -0
- package/dist-standalone/cjs/guardrails.js +223 -0
- package/dist-standalone/cjs/http-compat.js +272 -0
- package/dist-standalone/cjs/identity.js +541 -0
- package/dist-standalone/cjs/index.js +224 -0
- package/dist-standalone/cjs/invitation.js +421 -0
- package/dist-standalone/cjs/invite.js +328 -0
- package/dist-standalone/cjs/key-agreement.js +246 -0
- package/dist-standalone/cjs/lazy-init.js +300 -0
- package/dist-standalone/cjs/mdns-discovery.js +202 -0
- package/dist-standalone/cjs/nonce-store.js +66 -0
- package/dist-standalone/cjs/package.json +3 -0
- package/dist-standalone/cjs/pairing-manager.js +223 -0
- package/dist-standalone/cjs/policy.js +320 -0
- package/dist-standalone/cjs/redis-nonce-store.js +76 -0
- package/dist-standalone/cjs/registry-middleware.js +50 -0
- package/dist-standalone/cjs/retry-transport.js +102 -0
- package/dist-standalone/cjs/security-policy.js +204 -0
- package/dist-standalone/cjs/split-channel.js +177 -0
- package/dist-standalone/cjs/subscription-proof.js +230 -0
- package/dist-standalone/cjs/succession.js +148 -0
- package/dist-standalone/cjs/transport.js +63 -0
- package/dist-standalone/cjs/trust-registry.js +742 -0
- package/dist-standalone/cjs/verify.js +25 -0
- package/dist-standalone/cjs/xfetch.js +252 -0
- package/dist-standalone/cli/init.d.ts +63 -0
- package/dist-standalone/cli/init.js +450 -0
- package/dist-standalone/connect.d.ts +143 -0
- package/dist-standalone/connect.js +274 -0
- package/dist-standalone/did-document.d.ts +65 -0
- package/dist-standalone/did-document.js +96 -0
- package/dist-standalone/did-privateme.d.ts +70 -0
- package/dist-standalone/did-privateme.js +121 -0
- package/dist-standalone/did-web.d.ts +73 -0
- package/dist-standalone/did-web.js +196 -0
- package/dist-standalone/discovery.d.ts +176 -0
- package/dist-standalone/discovery.js +458 -0
- package/dist-standalone/dual-mode.d.ts +145 -0
- package/dist-standalone/dual-mode.js +247 -0
- package/dist-standalone/email-templates.d.ts +41 -0
- package/dist-standalone/email-templates.js +309 -0
- package/dist-standalone/email-transport.d.ts +139 -0
- package/dist-standalone/email-transport.js +232 -0
- package/dist-standalone/envelope.d.ts +288 -0
- package/dist-standalone/envelope.js +497 -0
- package/dist-standalone/errors.d.ts +74 -0
- package/dist-standalone/errors.js +548 -0
- package/dist-standalone/gateway-state.d.ts +32 -0
- package/dist-standalone/gateway-state.js +51 -0
- package/dist-standalone/gateway-transport.d.ts +59 -0
- package/dist-standalone/gateway-transport.js +116 -0
- package/dist-standalone/guardrails.d.ts +136 -0
- package/dist-standalone/guardrails.js +216 -0
- package/dist-standalone/http-compat.d.ts +150 -0
- package/dist-standalone/http-compat.js +267 -0
- package/dist-standalone/identity.d.ts +176 -0
- package/dist-standalone/identity.js +516 -0
- package/dist-standalone/index.d.ts +83 -0
- package/dist-standalone/index.js +51 -0
- package/dist-standalone/invitation.d.ts +211 -0
- package/dist-standalone/invitation.js +415 -0
- package/dist-standalone/invite.d.ts +192 -0
- package/dist-standalone/invite.js +324 -0
- package/dist-standalone/key-agreement.d.ts +122 -0
- package/dist-standalone/key-agreement.js +236 -0
- package/dist-standalone/lazy-init.d.ts +167 -0
- package/dist-standalone/lazy-init.js +295 -0
- package/dist-standalone/mdns-discovery.d.ts +117 -0
- package/dist-standalone/mdns-discovery.js +195 -0
- package/dist-standalone/nonce-store.d.ts +39 -0
- package/dist-standalone/nonce-store.js +62 -0
- package/dist-standalone/package.json +11 -0
- package/dist-standalone/pairing-manager.d.ts +147 -0
- package/dist-standalone/pairing-manager.js +219 -0
- package/dist-standalone/policy.d.ts +150 -0
- package/dist-standalone/policy.js +315 -0
- package/dist-standalone/redis-nonce-store.d.ts +93 -0
- package/dist-standalone/redis-nonce-store.js +72 -0
- package/dist-standalone/registry-middleware.d.ts +38 -0
- package/dist-standalone/registry-middleware.js +47 -0
- package/dist-standalone/retry-transport.d.ts +76 -0
- package/dist-standalone/retry-transport.js +98 -0
- package/dist-standalone/security-policy.d.ts +146 -0
- package/dist-standalone/security-policy.js +198 -0
- package/dist-standalone/split-channel.d.ts +69 -0
- package/dist-standalone/split-channel.js +171 -0
- package/dist-standalone/subscription-proof.d.ts +103 -0
- package/dist-standalone/subscription-proof.js +224 -0
- package/dist-standalone/succession.d.ts +57 -0
- package/dist-standalone/succession.js +142 -0
- package/dist-standalone/transport.d.ts +50 -0
- package/dist-standalone/transport.js +59 -0
- package/dist-standalone/trust-registry.d.ts +286 -0
- package/dist-standalone/trust-registry.js +702 -0
- package/dist-standalone/verify.d.ts +16 -0
- package/dist-standalone/verify.js +16 -0
- package/dist-standalone/xfetch.d.ts +129 -0
- package/dist-standalone/xfetch.js +247 -0
- package/llms.txt +800 -0
- package/package.json +79 -0
- package/share1.dat +0 -0
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module pairing-manager
|
|
3
|
+
* Security validation for peer-to-peer device pairing via mDNS.
|
|
4
|
+
*
|
|
5
|
+
* Security properties:
|
|
6
|
+
* - 16-byte cryptographically secure nonce (prevents replay attacks)
|
|
7
|
+
* - 60-second timeout (limits attack window)
|
|
8
|
+
* - User confirmation required on BOTH devices
|
|
9
|
+
* - Nonce echo in response (prevents MITM substitution)
|
|
10
|
+
* - Trust registry integration (stores paired DIDs with scopes)
|
|
11
|
+
* - Gold Standard compliant (GS-CONNECT requirement #26, GS-SEC-RNG compliant)
|
|
12
|
+
*/
|
|
13
|
+
import { ok, err } from"./_deps/shared/index.js";
|
|
14
|
+
/**
|
|
15
|
+
* Pairing manager for secure peer-to-peer device pairing.
|
|
16
|
+
*
|
|
17
|
+
* Implements challenge-response protocol with user confirmation.
|
|
18
|
+
* Integrates with trust registry for persistent pairing storage.
|
|
19
|
+
*/
|
|
20
|
+
export class PairingManager {
|
|
21
|
+
pendingNonces = new Map(); // nonce → timestamp
|
|
22
|
+
registry;
|
|
23
|
+
deviceDid;
|
|
24
|
+
/**
|
|
25
|
+
* Create pairing manager.
|
|
26
|
+
*
|
|
27
|
+
* @param deviceDid - DID of this device
|
|
28
|
+
* @param registry - Trust registry instance
|
|
29
|
+
*/
|
|
30
|
+
constructor(deviceDid, registry) {
|
|
31
|
+
this.deviceDid = deviceDid;
|
|
32
|
+
this.registry = registry;
|
|
33
|
+
// Clean up expired nonces every 10 seconds
|
|
34
|
+
setInterval(() => {
|
|
35
|
+
const now = Date.now();
|
|
36
|
+
for (const [nonce, timestamp] of this.pendingNonces.entries()) {
|
|
37
|
+
if (now - timestamp > 60_000) {
|
|
38
|
+
this.pendingNonces.delete(nonce);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}, 10_000);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Create pairing request.
|
|
45
|
+
*
|
|
46
|
+
* Generates cryptographically secure nonce and stores it for validation.
|
|
47
|
+
* Device A calls this before sending request to Device B.
|
|
48
|
+
*
|
|
49
|
+
* @returns Pairing request to send to remote device
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```typescript
|
|
53
|
+
* const manager = new PairingManager('did:key:z6MkA...', registry);
|
|
54
|
+
* const request = manager.createRequest();
|
|
55
|
+
* // Send request to Device B via HTTP POST
|
|
56
|
+
* const response = await fetch(`${deviceB.endpoint}/pair`, {
|
|
57
|
+
* method: 'POST',
|
|
58
|
+
* body: JSON.stringify(request),
|
|
59
|
+
* });
|
|
60
|
+
* ```
|
|
61
|
+
*/
|
|
62
|
+
createRequest() {
|
|
63
|
+
// Generate cryptographically secure nonce (GS-SEC-RNG: NEVER use Math.random)
|
|
64
|
+
const nonceBytes = new Uint8Array(16);
|
|
65
|
+
if (typeof globalThis.crypto !== 'undefined' && globalThis.crypto.getRandomValues) {
|
|
66
|
+
globalThis.crypto.getRandomValues(nonceBytes);
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
// Node.js environment
|
|
70
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
71
|
+
const crypto = require('node:crypto');
|
|
72
|
+
crypto.getRandomValues(nonceBytes);
|
|
73
|
+
}
|
|
74
|
+
const nonce = Array.from(nonceBytes)
|
|
75
|
+
.map((b) => b.toString(16).padStart(2, '0'))
|
|
76
|
+
.join('');
|
|
77
|
+
const timestamp = Date.now();
|
|
78
|
+
// Store nonce for validation (60-second TTL)
|
|
79
|
+
this.pendingNonces.set(nonce, timestamp);
|
|
80
|
+
return {
|
|
81
|
+
device_a_did: this.deviceDid,
|
|
82
|
+
nonce,
|
|
83
|
+
timestamp,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Validate pairing request.
|
|
88
|
+
*
|
|
89
|
+
* Checks timeout and nonce uniqueness.
|
|
90
|
+
* Device B calls this when receiving request from Device A.
|
|
91
|
+
*
|
|
92
|
+
* @param request - Pairing request from remote device
|
|
93
|
+
* @returns Ok if valid, Err with reason if invalid
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* ```typescript
|
|
97
|
+
* // Device B receives request
|
|
98
|
+
* const validation = manager.validateRequest(request);
|
|
99
|
+
* if (!validation.ok) {
|
|
100
|
+
* return res.status(400).json({ error: validation.error });
|
|
101
|
+
* }
|
|
102
|
+
* ```
|
|
103
|
+
*/
|
|
104
|
+
validateRequest(request) {
|
|
105
|
+
// Check timeout (60-second window)
|
|
106
|
+
const age = Date.now() - request.timestamp;
|
|
107
|
+
if (age > 60_000) {
|
|
108
|
+
return err(`Request expired (${Math.floor(age / 1000)}s old, max 60s)`);
|
|
109
|
+
}
|
|
110
|
+
if (age < 0) {
|
|
111
|
+
return err('Request timestamp in the future (clock skew detected)');
|
|
112
|
+
}
|
|
113
|
+
// Check required fields
|
|
114
|
+
if (!request.device_a_did || !request.nonce || !request.timestamp) {
|
|
115
|
+
return err('Missing required fields (device_a_did, nonce, timestamp)');
|
|
116
|
+
}
|
|
117
|
+
return ok(undefined);
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Accept pairing request.
|
|
121
|
+
*
|
|
122
|
+
* Shows UI prompt for user confirmation, then stores in trust registry.
|
|
123
|
+
* Device B calls this after validating request.
|
|
124
|
+
*
|
|
125
|
+
* @param request - Validated pairing request
|
|
126
|
+
* @param promptCallback - Async function to show UI prompt (returns true if accepted)
|
|
127
|
+
* @returns Pairing response to send back to Device A
|
|
128
|
+
*
|
|
129
|
+
* @example
|
|
130
|
+
* ```typescript
|
|
131
|
+
* const response = await manager.acceptPairing(request, async () => {
|
|
132
|
+
* // Show modal: "Device {name} wants to pair. Accept?"
|
|
133
|
+
* return await showConfirmationDialog({
|
|
134
|
+
* title: 'Pair with Device?',
|
|
135
|
+
* message: `DID: ${request.device_a_did.slice(0, 20)}...`,
|
|
136
|
+
* });
|
|
137
|
+
* });
|
|
138
|
+
*
|
|
139
|
+
* if (response.ok && response.value.accepted) {
|
|
140
|
+
* // Send response back to Device A
|
|
141
|
+
* }
|
|
142
|
+
* ```
|
|
143
|
+
*/
|
|
144
|
+
async acceptPairing(request, promptCallback) {
|
|
145
|
+
// Validate request first
|
|
146
|
+
const validation = this.validateRequest(request);
|
|
147
|
+
if (!validation.ok) {
|
|
148
|
+
return err(validation.error);
|
|
149
|
+
}
|
|
150
|
+
// Prompt user for confirmation
|
|
151
|
+
const accepted = await promptCallback();
|
|
152
|
+
if (accepted) {
|
|
153
|
+
// Store in trust registry (Device A → Device B)
|
|
154
|
+
const registerResult = await this.registry.register(request.device_a_did, new Uint8Array(32), 'Paired Device', ['pairing']);
|
|
155
|
+
if (!registerResult.ok) {
|
|
156
|
+
const errorMsg = typeof registerResult.error === 'string'
|
|
157
|
+
? registerResult.error
|
|
158
|
+
: 'Unknown error';
|
|
159
|
+
return err(`Failed to register pairing: ${errorMsg}`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// Return response (echo nonce to prevent MITM)
|
|
163
|
+
return ok({
|
|
164
|
+
device_b_did: this.deviceDid,
|
|
165
|
+
accepted,
|
|
166
|
+
nonce: request.nonce,
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Finalize pairing.
|
|
171
|
+
*
|
|
172
|
+
* Verifies response nonce and stores remote DID in trust registry.
|
|
173
|
+
* Device A calls this after receiving response from Device B.
|
|
174
|
+
*
|
|
175
|
+
* @param response - Pairing response from Device B
|
|
176
|
+
* @param expectedNonce - Nonce from original request (for verification)
|
|
177
|
+
* @returns Ok if successful, Err if nonce mismatch or storage failed
|
|
178
|
+
*
|
|
179
|
+
* @example
|
|
180
|
+
* ```typescript
|
|
181
|
+
* const request = manager.createRequest();
|
|
182
|
+
* const response = await sendPairingRequest(deviceB.endpoint, request);
|
|
183
|
+
*
|
|
184
|
+
* const result = await manager.finalizePairing(response, request.nonce);
|
|
185
|
+
* if (result.ok) {
|
|
186
|
+
* console.log('Pairing successful!');
|
|
187
|
+
* } else {
|
|
188
|
+
* console.error('Pairing failed:', result.error);
|
|
189
|
+
* }
|
|
190
|
+
* ```
|
|
191
|
+
*/
|
|
192
|
+
async finalizePairing(response, expectedNonce) {
|
|
193
|
+
// Verify nonce echo (prevents MITM substitution)
|
|
194
|
+
if (response.nonce !== expectedNonce) {
|
|
195
|
+
return err('Nonce mismatch (possible MITM attack)');
|
|
196
|
+
}
|
|
197
|
+
// Check if pairing was accepted
|
|
198
|
+
if (!response.accepted) {
|
|
199
|
+
return err('Pairing rejected by remote device');
|
|
200
|
+
}
|
|
201
|
+
// Remove nonce from pending set
|
|
202
|
+
this.pendingNonces.delete(expectedNonce);
|
|
203
|
+
// Store in trust registry (Device B → Device A)
|
|
204
|
+
const registerResult = await this.registry.register(response.device_b_did, new Uint8Array(32), 'Paired Device', ['pairing']);
|
|
205
|
+
if (!registerResult.ok) {
|
|
206
|
+
const errorMsg = typeof registerResult.error === 'string'
|
|
207
|
+
? registerResult.error
|
|
208
|
+
: 'Unknown error';
|
|
209
|
+
return err(`Failed to register pairing: ${errorMsg}`);
|
|
210
|
+
}
|
|
211
|
+
return ok(undefined);
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Get pending nonce count (for debugging/monitoring).
|
|
215
|
+
*/
|
|
216
|
+
getPendingNonceCount() {
|
|
217
|
+
return this.pendingNonces.size;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module policy
|
|
3
|
+
* PolicyEngine for agent.call() constraint enforcement
|
|
4
|
+
*
|
|
5
|
+
* Enforces spending limits, rate limits, scope restrictions, and data filters
|
|
6
|
+
* on agent tool calls. Separate from SecurityPolicy (risk classification).
|
|
7
|
+
*/
|
|
8
|
+
import type { Result } from '@private.me/shared';
|
|
9
|
+
import { AgentError } from './agent-call.js';
|
|
10
|
+
import type { PolicyConstraints } from './agent-call.js';
|
|
11
|
+
/**
|
|
12
|
+
* Policy evaluation result
|
|
13
|
+
*/
|
|
14
|
+
export interface PolicyResult {
|
|
15
|
+
/** Whether the request is allowed */
|
|
16
|
+
allowed: boolean;
|
|
17
|
+
/** Reason for denial (if not allowed) */
|
|
18
|
+
reason?: string;
|
|
19
|
+
/** Which constraint was violated (if not allowed) */
|
|
20
|
+
violatedConstraint?: 'amount' | 'daily' | 'rate' | 'scope' | 'tool';
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Detailed policy violation information for AI agents
|
|
24
|
+
*/
|
|
25
|
+
export interface PolicyViolationDetails extends Record<string, unknown> {
|
|
26
|
+
/** What was requested/denied */
|
|
27
|
+
requested: string | number;
|
|
28
|
+
/** What the limit/constraint is */
|
|
29
|
+
allowed: string | number | string[];
|
|
30
|
+
/** Which constraint type was violated */
|
|
31
|
+
constraint: 'amountPerTxn' | 'dailyAmount' | 'callsPerMinute' | 'scope' | 'tool';
|
|
32
|
+
/** How to fix the issue */
|
|
33
|
+
fix: string;
|
|
34
|
+
/** Additional context (optional) */
|
|
35
|
+
current?: number;
|
|
36
|
+
/** New total after this request (optional, for daily limits) */
|
|
37
|
+
newTotal?: number;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Policy limits with time-window tracking
|
|
41
|
+
*/
|
|
42
|
+
export interface PolicyLimits {
|
|
43
|
+
/** Maximum amount per transaction */
|
|
44
|
+
amountPerTxn?: number;
|
|
45
|
+
/** Maximum amount per day (24-hour window) */
|
|
46
|
+
dailyAmount?: number;
|
|
47
|
+
/** Maximum amount per month (30-day window) */
|
|
48
|
+
monthlyAmount?: number;
|
|
49
|
+
/** Maximum calls per minute */
|
|
50
|
+
callsPerMinute?: number;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* PolicyEngine - Enforces constraints on agent.call() requests
|
|
54
|
+
*
|
|
55
|
+
* Tracks:
|
|
56
|
+
* - Per-transaction spending limits
|
|
57
|
+
* - Daily spending limits
|
|
58
|
+
* - Rate limits (calls per minute)
|
|
59
|
+
* - Allowed tools/scopes
|
|
60
|
+
*
|
|
61
|
+
* Thread-safe for concurrent requests from the same agent.
|
|
62
|
+
*/
|
|
63
|
+
export declare class PolicyEngine {
|
|
64
|
+
/** Rate limit tracker by agent DID */
|
|
65
|
+
private readonly rateLimits;
|
|
66
|
+
/** Daily spending tracker by agent DID */
|
|
67
|
+
private readonly dailySpending;
|
|
68
|
+
/** Monthly spending tracker by agent DID */
|
|
69
|
+
private readonly monthlySpending;
|
|
70
|
+
/**
|
|
71
|
+
* Evaluate a policy against a request
|
|
72
|
+
*
|
|
73
|
+
* @param agentDID - Agent DID making the request
|
|
74
|
+
* @param tool - Tool being called (e.g., "stripe:createCharge")
|
|
75
|
+
* @param params - Tool parameters
|
|
76
|
+
* @param constraints - Policy constraints to enforce
|
|
77
|
+
* @returns Policy evaluation result
|
|
78
|
+
*/
|
|
79
|
+
evaluate(agentDID: string, tool: string, params: unknown, constraints: PolicyConstraints): Result<void, AgentError>;
|
|
80
|
+
/**
|
|
81
|
+
* Record a successful call (for rate limiting)
|
|
82
|
+
*
|
|
83
|
+
* @param agentDID - Agent DID
|
|
84
|
+
*/
|
|
85
|
+
recordCall(agentDID: string): void;
|
|
86
|
+
/**
|
|
87
|
+
* Record successful spending (for daily and monthly limits)
|
|
88
|
+
*
|
|
89
|
+
* @param agentDID - Agent DID
|
|
90
|
+
* @param amount - Amount spent
|
|
91
|
+
*/
|
|
92
|
+
recordSpending(agentDID: string, amount: number): void;
|
|
93
|
+
/**
|
|
94
|
+
* Get current rate limit status for an agent
|
|
95
|
+
*
|
|
96
|
+
* @param agentDID - Agent DID
|
|
97
|
+
* @returns Calls in current minute
|
|
98
|
+
*/
|
|
99
|
+
getCurrentRateLimit(agentDID: string): number;
|
|
100
|
+
/**
|
|
101
|
+
* Get current daily spending for an agent
|
|
102
|
+
*
|
|
103
|
+
* @param agentDID - Agent DID
|
|
104
|
+
* @returns Amount spent today
|
|
105
|
+
*/
|
|
106
|
+
getDailySpending(agentDID: string): number;
|
|
107
|
+
/**
|
|
108
|
+
* Get current monthly spending for an agent
|
|
109
|
+
*
|
|
110
|
+
* @param agentDID - Agent DID
|
|
111
|
+
* @returns Amount spent this month
|
|
112
|
+
*/
|
|
113
|
+
getMonthlySpending(agentDID: string): number;
|
|
114
|
+
/**
|
|
115
|
+
* Reset all limits for an agent (for testing)
|
|
116
|
+
*
|
|
117
|
+
* @param agentDID - Agent DID
|
|
118
|
+
*/
|
|
119
|
+
reset(agentDID: string): void;
|
|
120
|
+
/**
|
|
121
|
+
* Check rate limit
|
|
122
|
+
*/
|
|
123
|
+
private checkRateLimit;
|
|
124
|
+
/**
|
|
125
|
+
* Check daily spending limit
|
|
126
|
+
*/
|
|
127
|
+
private checkDailyLimit;
|
|
128
|
+
/**
|
|
129
|
+
* Extract amount from params
|
|
130
|
+
*/
|
|
131
|
+
private extractAmount;
|
|
132
|
+
/**
|
|
133
|
+
* Get current day identifier (YYYY-MM-DD in UTC)
|
|
134
|
+
*/
|
|
135
|
+
private getCurrentDay;
|
|
136
|
+
/**
|
|
137
|
+
* Get current month identifier (YYYY-MM in UTC)
|
|
138
|
+
*/
|
|
139
|
+
private getCurrentMonth;
|
|
140
|
+
/**
|
|
141
|
+
* Check monthly spending limit
|
|
142
|
+
*/
|
|
143
|
+
private checkMonthlyLimit;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Get the global policy engine instance
|
|
147
|
+
*
|
|
148
|
+
* @returns PolicyEngine instance
|
|
149
|
+
*/
|
|
150
|
+
export declare function getGlobalPolicyEngine(): PolicyEngine;
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module policy
|
|
3
|
+
* PolicyEngine for agent.call() constraint enforcement
|
|
4
|
+
*
|
|
5
|
+
* Enforces spending limits, rate limits, scope restrictions, and data filters
|
|
6
|
+
* on agent tool calls. Separate from SecurityPolicy (risk classification).
|
|
7
|
+
*/
|
|
8
|
+
import { ok, err } from"./_deps/shared/index.js";
|
|
9
|
+
import { AgentError, AgentErrorCode } from './agent-call.js';
|
|
10
|
+
/**
|
|
11
|
+
* PolicyEngine - Enforces constraints on agent.call() requests
|
|
12
|
+
*
|
|
13
|
+
* Tracks:
|
|
14
|
+
* - Per-transaction spending limits
|
|
15
|
+
* - Daily spending limits
|
|
16
|
+
* - Rate limits (calls per minute)
|
|
17
|
+
* - Allowed tools/scopes
|
|
18
|
+
*
|
|
19
|
+
* Thread-safe for concurrent requests from the same agent.
|
|
20
|
+
*/
|
|
21
|
+
export class PolicyEngine {
|
|
22
|
+
/** Rate limit tracker by agent DID */
|
|
23
|
+
rateLimits = new Map();
|
|
24
|
+
/** Daily spending tracker by agent DID */
|
|
25
|
+
dailySpending = new Map();
|
|
26
|
+
/** Monthly spending tracker by agent DID */
|
|
27
|
+
monthlySpending = new Map();
|
|
28
|
+
/**
|
|
29
|
+
* Evaluate a policy against a request
|
|
30
|
+
*
|
|
31
|
+
* @param agentDID - Agent DID making the request
|
|
32
|
+
* @param tool - Tool being called (e.g., "stripe:createCharge")
|
|
33
|
+
* @param params - Tool parameters
|
|
34
|
+
* @param constraints - Policy constraints to enforce
|
|
35
|
+
* @returns Policy evaluation result
|
|
36
|
+
*/
|
|
37
|
+
evaluate(agentDID, tool, params, constraints) {
|
|
38
|
+
// Check allowed tools
|
|
39
|
+
if (constraints.allowedTools && constraints.allowedTools.length > 0) {
|
|
40
|
+
const [service] = tool.split(':');
|
|
41
|
+
const isAllowed = constraints.allowedTools.some((allowed) => allowed === tool || allowed === `${service}:*` || allowed === '*');
|
|
42
|
+
if (!isAllowed) {
|
|
43
|
+
const details = {
|
|
44
|
+
requested: tool,
|
|
45
|
+
allowed: constraints.allowedTools,
|
|
46
|
+
constraint: 'tool',
|
|
47
|
+
fix: `Update policy.allowedTools to include "${tool}" or "${service}:*" or request approval`,
|
|
48
|
+
};
|
|
49
|
+
return err(new AgentError(AgentErrorCode.POLICY_VIOLATION, `Tool "${tool}" is not allowed by policy`, details));
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
// Check scopes
|
|
53
|
+
if (constraints.scopes && constraints.scopes.length > 0) {
|
|
54
|
+
// Extract scope from params if present
|
|
55
|
+
const scope = typeof params === 'object' && params !== null && 'scope' in params
|
|
56
|
+
? params.scope
|
|
57
|
+
: undefined;
|
|
58
|
+
if (scope && !constraints.scopes.includes(scope)) {
|
|
59
|
+
const details = {
|
|
60
|
+
requested: scope,
|
|
61
|
+
allowed: constraints.scopes,
|
|
62
|
+
constraint: 'scope',
|
|
63
|
+
fix: `Update policy.scopes to include "${scope}" or request additional permissions`,
|
|
64
|
+
};
|
|
65
|
+
return err(new AgentError(AgentErrorCode.POLICY_VIOLATION, `Scope "${scope}" is not allowed by policy`, details));
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
// Check rate limits
|
|
69
|
+
if (constraints.limits?.callsPerMinute) {
|
|
70
|
+
const rateCheck = this.checkRateLimit(agentDID, constraints.limits.callsPerMinute);
|
|
71
|
+
if (!rateCheck.ok) {
|
|
72
|
+
return rateCheck;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
// Check spending limits (if amount is in params)
|
|
76
|
+
const amount = this.extractAmount(params);
|
|
77
|
+
if (amount !== null) {
|
|
78
|
+
// Check per-transaction limit
|
|
79
|
+
if (constraints.limits?.amountPerTxn && amount > constraints.limits.amountPerTxn) {
|
|
80
|
+
const details = {
|
|
81
|
+
requested: amount,
|
|
82
|
+
allowed: constraints.limits.amountPerTxn,
|
|
83
|
+
constraint: 'amountPerTxn',
|
|
84
|
+
fix: `Reduce amount to ${constraints.limits.amountPerTxn} or less, or update policy.limits.amountPerTxn`,
|
|
85
|
+
};
|
|
86
|
+
return err(new AgentError(AgentErrorCode.POLICY_VIOLATION, `Amount ${amount} exceeds per-transaction limit of ${constraints.limits.amountPerTxn}`, details));
|
|
87
|
+
}
|
|
88
|
+
// Check daily limit
|
|
89
|
+
if (constraints.limits?.dailyAmount) {
|
|
90
|
+
const dailyCheck = this.checkDailyLimit(agentDID, amount, constraints.limits.dailyAmount);
|
|
91
|
+
if (!dailyCheck.ok) {
|
|
92
|
+
return dailyCheck;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
// Check monthly limit
|
|
96
|
+
if (constraints.limits?.monthlyAmount) {
|
|
97
|
+
const monthlyCheck = this.checkMonthlyLimit(agentDID, amount, constraints.limits.monthlyAmount);
|
|
98
|
+
if (!monthlyCheck.ok) {
|
|
99
|
+
return monthlyCheck;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
// All checks passed
|
|
104
|
+
return ok(undefined);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Record a successful call (for rate limiting)
|
|
108
|
+
*
|
|
109
|
+
* @param agentDID - Agent DID
|
|
110
|
+
*/
|
|
111
|
+
recordCall(agentDID) {
|
|
112
|
+
const now = Date.now();
|
|
113
|
+
const entry = this.rateLimits.get(agentDID) ?? {
|
|
114
|
+
calls: [],
|
|
115
|
+
windowStart: now,
|
|
116
|
+
};
|
|
117
|
+
entry.calls.push(now);
|
|
118
|
+
// Clean up old calls (older than 1 minute)
|
|
119
|
+
const oneMinuteAgo = now - 60000;
|
|
120
|
+
entry.calls = entry.calls.filter((timestamp) => timestamp > oneMinuteAgo);
|
|
121
|
+
this.rateLimits.set(agentDID, entry);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Record successful spending (for daily and monthly limits)
|
|
125
|
+
*
|
|
126
|
+
* @param agentDID - Agent DID
|
|
127
|
+
* @param amount - Amount spent
|
|
128
|
+
*/
|
|
129
|
+
recordSpending(agentDID, amount) {
|
|
130
|
+
const today = this.getCurrentDay();
|
|
131
|
+
const thisMonth = this.getCurrentMonth();
|
|
132
|
+
// Update daily spending
|
|
133
|
+
const dailyEntry = this.dailySpending.get(agentDID);
|
|
134
|
+
if (dailyEntry && dailyEntry.day === today) {
|
|
135
|
+
dailyEntry.amount += amount;
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
this.dailySpending.set(agentDID, {
|
|
139
|
+
amount,
|
|
140
|
+
day: today,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
// Update monthly spending
|
|
144
|
+
const monthlyEntry = this.monthlySpending.get(agentDID);
|
|
145
|
+
if (monthlyEntry && monthlyEntry.month === thisMonth) {
|
|
146
|
+
monthlyEntry.amount += amount;
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
this.monthlySpending.set(agentDID, {
|
|
150
|
+
amount,
|
|
151
|
+
month: thisMonth,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Get current rate limit status for an agent
|
|
157
|
+
*
|
|
158
|
+
* @param agentDID - Agent DID
|
|
159
|
+
* @returns Calls in current minute
|
|
160
|
+
*/
|
|
161
|
+
getCurrentRateLimit(agentDID) {
|
|
162
|
+
const entry = this.rateLimits.get(agentDID);
|
|
163
|
+
if (!entry)
|
|
164
|
+
return 0;
|
|
165
|
+
const now = Date.now();
|
|
166
|
+
const oneMinuteAgo = now - 60000;
|
|
167
|
+
// Count calls in last minute
|
|
168
|
+
return entry.calls.filter((timestamp) => timestamp > oneMinuteAgo).length;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Get current daily spending for an agent
|
|
172
|
+
*
|
|
173
|
+
* @param agentDID - Agent DID
|
|
174
|
+
* @returns Amount spent today
|
|
175
|
+
*/
|
|
176
|
+
getDailySpending(agentDID) {
|
|
177
|
+
const today = this.getCurrentDay();
|
|
178
|
+
const entry = this.dailySpending.get(agentDID);
|
|
179
|
+
if (!entry || entry.day !== today)
|
|
180
|
+
return 0;
|
|
181
|
+
return entry.amount;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Get current monthly spending for an agent
|
|
185
|
+
*
|
|
186
|
+
* @param agentDID - Agent DID
|
|
187
|
+
* @returns Amount spent this month
|
|
188
|
+
*/
|
|
189
|
+
getMonthlySpending(agentDID) {
|
|
190
|
+
const thisMonth = this.getCurrentMonth();
|
|
191
|
+
const entry = this.monthlySpending.get(agentDID);
|
|
192
|
+
if (!entry || entry.month !== thisMonth)
|
|
193
|
+
return 0;
|
|
194
|
+
return entry.amount;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Reset all limits for an agent (for testing)
|
|
198
|
+
*
|
|
199
|
+
* @param agentDID - Agent DID
|
|
200
|
+
*/
|
|
201
|
+
reset(agentDID) {
|
|
202
|
+
this.rateLimits.delete(agentDID);
|
|
203
|
+
this.dailySpending.delete(agentDID);
|
|
204
|
+
this.monthlySpending.delete(agentDID);
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Check rate limit
|
|
208
|
+
*/
|
|
209
|
+
checkRateLimit(agentDID, limit) {
|
|
210
|
+
const current = this.getCurrentRateLimit(agentDID);
|
|
211
|
+
if (current >= limit) {
|
|
212
|
+
const details = {
|
|
213
|
+
requested: current + 1,
|
|
214
|
+
allowed: limit,
|
|
215
|
+
constraint: 'callsPerMinute',
|
|
216
|
+
current,
|
|
217
|
+
fix: `Wait before making additional calls, or update policy.limits.callsPerMinute to a higher value`,
|
|
218
|
+
};
|
|
219
|
+
return err(new AgentError(AgentErrorCode.POLICY_VIOLATION, `Rate limit exceeded: ${current}/${limit} calls per minute`, details));
|
|
220
|
+
}
|
|
221
|
+
return ok(undefined);
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Check daily spending limit
|
|
225
|
+
*/
|
|
226
|
+
checkDailyLimit(agentDID, amount, limit) {
|
|
227
|
+
const current = this.getDailySpending(agentDID);
|
|
228
|
+
const newTotal = current + amount;
|
|
229
|
+
if (newTotal > limit) {
|
|
230
|
+
const remaining = limit - current;
|
|
231
|
+
const details = {
|
|
232
|
+
requested: amount,
|
|
233
|
+
allowed: limit,
|
|
234
|
+
constraint: 'dailyAmount',
|
|
235
|
+
current,
|
|
236
|
+
newTotal,
|
|
237
|
+
fix: remaining > 0
|
|
238
|
+
? `Reduce amount to ${remaining} or less (remaining today), or update policy.limits.dailyAmount`
|
|
239
|
+
: `Daily limit already reached. Wait until tomorrow or update policy.limits.dailyAmount`,
|
|
240
|
+
};
|
|
241
|
+
return err(new AgentError(AgentErrorCode.POLICY_VIOLATION, `Amount ${amount} would exceed daily limit: ${newTotal}/${limit} (current: ${current})`, details));
|
|
242
|
+
}
|
|
243
|
+
return ok(undefined);
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Extract amount from params
|
|
247
|
+
*/
|
|
248
|
+
extractAmount(params) {
|
|
249
|
+
if (typeof params !== 'object' || params === null)
|
|
250
|
+
return null;
|
|
251
|
+
const obj = params;
|
|
252
|
+
// Check common amount field names
|
|
253
|
+
if (typeof obj.amount === 'number')
|
|
254
|
+
return obj.amount;
|
|
255
|
+
if (typeof obj.value === 'number')
|
|
256
|
+
return obj.value;
|
|
257
|
+
if (typeof obj.price === 'number')
|
|
258
|
+
return obj.price;
|
|
259
|
+
if (typeof obj.total === 'number')
|
|
260
|
+
return obj.total;
|
|
261
|
+
return null;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Get current day identifier (YYYY-MM-DD in UTC)
|
|
265
|
+
*/
|
|
266
|
+
getCurrentDay() {
|
|
267
|
+
const now = new Date();
|
|
268
|
+
return now.toISOString().split('T')[0] ?? '';
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Get current month identifier (YYYY-MM in UTC)
|
|
272
|
+
*/
|
|
273
|
+
getCurrentMonth() {
|
|
274
|
+
const now = new Date();
|
|
275
|
+
const iso = now.toISOString();
|
|
276
|
+
return iso.substring(0, 7); // YYYY-MM
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Check monthly spending limit
|
|
280
|
+
*/
|
|
281
|
+
checkMonthlyLimit(agentDID, amount, limit) {
|
|
282
|
+
const current = this.getMonthlySpending(agentDID);
|
|
283
|
+
const newTotal = current + amount;
|
|
284
|
+
if (newTotal > limit) {
|
|
285
|
+
const remaining = limit - current;
|
|
286
|
+
const details = {
|
|
287
|
+
requested: amount,
|
|
288
|
+
allowed: limit,
|
|
289
|
+
constraint: 'dailyAmount', // Reuse constraint type (will add monthlyAmount later)
|
|
290
|
+
current,
|
|
291
|
+
newTotal,
|
|
292
|
+
fix: remaining > 0
|
|
293
|
+
? `Reduce amount to ${remaining} or less (remaining this month), or update policy.limits.monthlyAmount`
|
|
294
|
+
: `Monthly limit already reached. Wait until next month or update policy.limits.monthlyAmount`,
|
|
295
|
+
};
|
|
296
|
+
return err(new AgentError(AgentErrorCode.POLICY_VIOLATION, `Amount ${amount} would exceed monthly limit: ${newTotal}/${limit} (current: ${current})`, details));
|
|
297
|
+
}
|
|
298
|
+
return ok(undefined);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Global policy engine instance (singleton)
|
|
303
|
+
*/
|
|
304
|
+
let globalPolicyEngine = null;
|
|
305
|
+
/**
|
|
306
|
+
* Get the global policy engine instance
|
|
307
|
+
*
|
|
308
|
+
* @returns PolicyEngine instance
|
|
309
|
+
*/
|
|
310
|
+
export function getGlobalPolicyEngine() {
|
|
311
|
+
if (!globalPolicyEngine) {
|
|
312
|
+
globalPolicyEngine = new PolicyEngine();
|
|
313
|
+
}
|
|
314
|
+
return globalPolicyEngine;
|
|
315
|
+
}
|