@private.me/xbind 3.0.0 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/README.md +55 -7
  2. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1920 -1
  3. package/dist-standalone/_deps/shared/cjs/errors.js +729 -1
  4. package/dist-standalone/_deps/shared/cjs/index.js +463 -1
  5. package/dist-standalone/_deps/shared/cjs/types.js +315 -1
  6. package/dist-standalone/_deps/shared/errors.js +244 -1
  7. package/dist-standalone/_deps/shared/index.js +72 -1
  8. package/dist-standalone/_deps/shared/types.js +86 -1
  9. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  10. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  20. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  21. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  28. package/dist-standalone/_deps/xchange/errors.js +1 -1
  29. package/dist-standalone/_deps/xchange/index.js +1 -1
  30. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  31. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  32. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  33. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  34. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  40. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  41. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  42. package/dist-standalone/_deps/xregistry/index.js +1 -1
  43. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  44. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  45. package/dist-standalone/_deps/xregistry/types.js +1 -1
  46. package/dist-standalone/agent-call.js +659 -1
  47. package/dist-standalone/agent-sdk.js +328 -1
  48. package/dist-standalone/agent.js +1800 -1
  49. package/dist-standalone/approval.js +193 -1
  50. package/dist-standalone/async-iterators.js +382 -1
  51. package/dist-standalone/auth.js +219 -1
  52. package/dist-standalone/auto-accept.js +229 -1
  53. package/dist-standalone/backup-config.js +201 -1
  54. package/dist-standalone/backup.js +326 -1
  55. package/dist-standalone/batch-operations.js +388 -1
  56. package/dist-standalone/cancellation.js +477 -1
  57. package/dist-standalone/checkpoint.js +186 -1
  58. package/dist-standalone/circuit-breaker.js +468 -1
  59. package/dist-standalone/cjs/agent-call.js +701 -1
  60. package/dist-standalone/cjs/agent-sdk.js +332 -1
  61. package/dist-standalone/cjs/agent.js +1837 -1
  62. package/dist-standalone/cjs/approval.js +199 -1
  63. package/dist-standalone/cjs/async-iterators.js +392 -1
  64. package/dist-standalone/cjs/auth.js +225 -1
  65. package/dist-standalone/cjs/auto-accept.js +233 -1
  66. package/dist-standalone/cjs/backup-config.js +207 -1
  67. package/dist-standalone/cjs/backup.js +330 -1
  68. package/dist-standalone/cjs/batch-operations.js +397 -1
  69. package/dist-standalone/cjs/cancellation.js +490 -1
  70. package/dist-standalone/cjs/checkpoint.js +193 -1
  71. package/dist-standalone/cjs/circuit-breaker.js +476 -1
  72. package/dist-standalone/cjs/cli/init.js +492 -1
  73. package/dist-standalone/cjs/config-validation.js +522 -1
  74. package/dist-standalone/cjs/connect.js +312 -1
  75. package/dist-standalone/cjs/connection-pool.js +506 -1
  76. package/dist-standalone/cjs/correlation-id.js +339 -1
  77. package/dist-standalone/cjs/crypto-utils.js +176 -1
  78. package/dist-standalone/cjs/debug-mode.js +534 -1
  79. package/dist-standalone/cjs/did-document.js +101 -1
  80. package/dist-standalone/cjs/did-privateme.js +130 -1
  81. package/dist-standalone/cjs/did-web.js +201 -1
  82. package/dist-standalone/cjs/discovery.js +462 -1
  83. package/dist-standalone/cjs/dual-mode.js +251 -1
  84. package/dist-standalone/cjs/email-templates.js +313 -1
  85. package/dist-standalone/cjs/email-transport.js +239 -1
  86. package/dist-standalone/cjs/envelope.js +538 -1
  87. package/dist-standalone/cjs/errors.js +913 -1
  88. package/dist-standalone/cjs/event-emitter.js +461 -1
  89. package/dist-standalone/cjs/gateway-state.js +55 -1
  90. package/dist-standalone/cjs/gateway-transport.js +120 -1
  91. package/dist-standalone/cjs/graceful-degradation.js +403 -1
  92. package/dist-standalone/cjs/guardrails.js +223 -1
  93. package/dist-standalone/cjs/health-check.js +336 -1
  94. package/dist-standalone/cjs/http-compat.js +272 -1
  95. package/dist-standalone/cjs/http-status-map.js +571 -1
  96. package/dist-standalone/cjs/identity.js +645 -1
  97. package/dist-standalone/cjs/index.js +406 -1
  98. package/dist-standalone/cjs/invitation.js +421 -1
  99. package/dist-standalone/cjs/invite.js +328 -1
  100. package/dist-standalone/cjs/key-agreement.js +335 -1
  101. package/dist-standalone/cjs/lazy-init.js +300 -1
  102. package/dist-standalone/cjs/logger.js +291 -1
  103. package/dist-standalone/cjs/mdns-discovery.js +202 -1
  104. package/dist-standalone/cjs/nonce-store.js +80 -1
  105. package/dist-standalone/cjs/pairing-manager.js +223 -1
  106. package/dist-standalone/cjs/plugin-system.js +264 -1
  107. package/dist-standalone/cjs/plugins/logging.js +168 -1
  108. package/dist-standalone/cjs/plugins/metrics.js +181 -1
  109. package/dist-standalone/cjs/plugins/validation.js +302 -1
  110. package/dist-standalone/cjs/policy.js +320 -1
  111. package/dist-standalone/cjs/progress-callbacks.js +583 -1
  112. package/dist-standalone/cjs/redis-nonce-store.js +76 -1
  113. package/dist-standalone/cjs/registry-middleware.js +50 -1
  114. package/dist-standalone/cjs/retry-strategies.js +544 -1
  115. package/dist-standalone/cjs/retry-transport.js +102 -1
  116. package/dist-standalone/cjs/runtime/browser.js +533 -1
  117. package/dist-standalone/cjs/runtime/edge.js +526 -1
  118. package/dist-standalone/cjs/runtime/react-native.js +394 -1
  119. package/dist-standalone/cjs/security-policy.js +245 -1
  120. package/dist-standalone/cjs/serialization.js +1040 -1
  121. package/dist-standalone/cjs/split-channel.js +225 -1
  122. package/dist-standalone/cjs/subscription-proof.js +230 -1
  123. package/dist-standalone/cjs/succession.js +148 -1
  124. package/dist-standalone/cjs/timeouts.js +412 -1
  125. package/dist-standalone/cjs/trace-context.js +424 -1
  126. package/dist-standalone/cjs/trace-spans.js +495 -1
  127. package/dist-standalone/cjs/transport.js +63 -1
  128. package/dist-standalone/cjs/trust-registry.js +991 -1
  129. package/dist-standalone/cjs/types/error-response.js +56 -1
  130. package/dist-standalone/cjs/vault-auth.js +178 -1
  131. package/dist-standalone/cjs/vault-store-loader.js +194 -1
  132. package/dist-standalone/cjs/verify.js +25 -1
  133. package/dist-standalone/cjs/version-info.js +543 -1
  134. package/dist-standalone/cjs/xfetch.js +340 -1
  135. package/dist-standalone/cli/init.js +455 -1
  136. package/dist-standalone/cli/setup.js +514 -1
  137. package/dist-standalone/cli/types.js +27 -1
  138. package/dist-standalone/cli/xbind.js +148 -1
  139. package/dist-standalone/config-validation.js +513 -1
  140. package/dist-standalone/connect.js +274 -1
  141. package/dist-standalone/connection-pool.js +500 -1
  142. package/dist-standalone/correlation-id.js +326 -1
  143. package/dist-standalone/crypto-utils.js +157 -1
  144. package/dist-standalone/debug-mode.js +510 -1
  145. package/dist-standalone/did-document.js +96 -1
  146. package/dist-standalone/did-privateme.js +121 -1
  147. package/dist-standalone/did-web.js +196 -1
  148. package/dist-standalone/discovery.js +458 -1
  149. package/dist-standalone/dual-mode.js +247 -1
  150. package/dist-standalone/email-templates.js +309 -1
  151. package/dist-standalone/email-transport.js +232 -1
  152. package/dist-standalone/envelope.js +525 -1
  153. package/dist-standalone/errors.js +896 -1
  154. package/dist-standalone/event-emitter.js +456 -1
  155. package/dist-standalone/gateway-state.js +51 -1
  156. package/dist-standalone/gateway-transport.js +116 -1
  157. package/dist-standalone/graceful-degradation.js +396 -1
  158. package/dist-standalone/guardrails.js +216 -1
  159. package/dist-standalone/health-check.js +332 -1
  160. package/dist-standalone/http-compat.js +267 -1
  161. package/dist-standalone/http-status-map.js +561 -1
  162. package/dist-standalone/identity.js +619 -1
  163. package/dist-standalone/index.js +78 -1
  164. package/dist-standalone/invitation.js +415 -1
  165. package/dist-standalone/invite.js +324 -1
  166. package/dist-standalone/key-agreement.js +325 -1
  167. package/dist-standalone/lazy-init.js +295 -1
  168. package/dist-standalone/logger.js +285 -1
  169. package/dist-standalone/mdns-discovery.js +195 -1
  170. package/dist-standalone/nonce-store.js +76 -1
  171. package/dist-standalone/pairing-manager.js +219 -1
  172. package/dist-standalone/plugin-system.js +257 -1
  173. package/dist-standalone/plugins/logging.d.ts +84 -0
  174. package/dist-standalone/plugins/logging.js +163 -0
  175. package/dist-standalone/plugins/metrics.d.ts +111 -0
  176. package/dist-standalone/plugins/metrics.js +176 -0
  177. package/dist-standalone/plugins/validation.d.ts +104 -0
  178. package/dist-standalone/plugins/validation.js +297 -0
  179. package/dist-standalone/policy.js +315 -1
  180. package/dist-standalone/progress-callbacks.js +576 -1
  181. package/dist-standalone/redis-nonce-store.js +72 -1
  182. package/dist-standalone/registry-middleware.js +47 -1
  183. package/dist-standalone/retry-strategies.js +534 -1
  184. package/dist-standalone/retry-transport.js +98 -1
  185. package/dist-standalone/runtime/browser.d.ts +311 -0
  186. package/dist-standalone/runtime/browser.js +516 -0
  187. package/dist-standalone/runtime/edge.d.ts +282 -0
  188. package/dist-standalone/runtime/edge.js +511 -0
  189. package/dist-standalone/runtime/react-native.d.ts +157 -0
  190. package/dist-standalone/runtime/react-native.js +383 -0
  191. package/dist-standalone/security-policy.js +239 -1
  192. package/dist-standalone/serialization.js +1031 -1
  193. package/dist-standalone/split-channel.js +219 -1
  194. package/dist-standalone/subscription-proof.js +224 -1
  195. package/dist-standalone/succession.js +142 -1
  196. package/dist-standalone/timeouts.js +398 -1
  197. package/dist-standalone/trace-context.js +414 -1
  198. package/dist-standalone/trace-spans.js +488 -1
  199. package/dist-standalone/transport.js +59 -1
  200. package/dist-standalone/trust-registry.js +950 -1
  201. package/dist-standalone/types/error-response.d.ts +209 -0
  202. package/dist-standalone/types/error-response.js +52 -0
  203. package/dist-standalone/vault-auth.js +174 -1
  204. package/dist-standalone/vault-store-loader.js +187 -1
  205. package/dist-standalone/verify.js +16 -1
  206. package/dist-standalone/version-info.js +530 -1
  207. package/dist-standalone/xfetch.js +335 -1
  208. package/package.json +4 -10
  209. package/share1.dat +0 -0
  210. package/dist-standalone/_deps/mldsa-wasm/LICENSE +0 -24
  211. package/dist-standalone/_deps/mldsa-wasm/package.json +0 -46
  212. package/dist-standalone/_deps/shared/cjs/package.json +0 -1
  213. package/dist-standalone/_deps/ux-helpers/cjs/package.json +0 -1
  214. package/dist-standalone/_deps/xchange/cjs/package.json +0 -1
  215. package/dist-standalone/_deps/xregistry/cjs/package.json +0 -1
  216. package/dist-standalone/cjs/package.json +0 -3
  217. package/dist-standalone/package.json +0 -10
@@ -1 +1,302 @@
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
+ "use strict";
2
+ /**
3
+ * @module plugins/validation
4
+ * Validation plugin for xBind plugin system
5
+ *
6
+ * Validates payloads, envelopes, and ensures data integrity before processing.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.CommonRules = exports.ValidationPlugin = void 0;
10
+ exports.createValidationPlugin = createValidationPlugin;
11
+ const shared_1 = require("../../_deps/shared/index.js");
12
+ /**
13
+ * Validation plugin implementation.
14
+ * Validates all data before processing to ensure integrity and compliance.
15
+ */
16
+ class ValidationPlugin {
17
+ name = 'validation';
18
+ version = '1.0.0';
19
+ description = 'Validates payloads and envelopes before processing';
20
+ priority = 5; // Execute very early
21
+ options;
22
+ validationErrors = [];
23
+ constructor(options = {}) {
24
+ this.options = {
25
+ maxPayloadSize: options.maxPayloadSize ?? 10 * 1024 * 1024, // 10MB
26
+ maxEnvelopeSize: options.maxEnvelopeSize ?? 15 * 1024 * 1024, // 15MB
27
+ allowedScopes: options.allowedScopes ?? [],
28
+ customRules: options.customRules ?? [],
29
+ strictMode: options.strictMode ?? false,
30
+ validateSchema: options.validateSchema ?? false,
31
+ };
32
+ }
33
+ onInit() {
34
+ return (0, shared_1.ok)(undefined);
35
+ }
36
+ onDestroy() {
37
+ this.validationErrors = [];
38
+ return (0, shared_1.ok)(undefined);
39
+ }
40
+ onSend(payload, context) {
41
+ // Validate payload size
42
+ const sizeResult = this.validatePayloadSize(payload);
43
+ if (sizeResult.ok === false) {
44
+ this.recordError('payload_size', sizeResult.error);
45
+ return (0, shared_1.err)(sizeResult.error);
46
+ }
47
+ // Validate scope
48
+ if (context.scope) {
49
+ const scopeResult = this.validateScope(context.scope);
50
+ if (scopeResult.ok === false) {
51
+ this.recordError('scope', scopeResult.error);
52
+ return (0, shared_1.err)(scopeResult.error);
53
+ }
54
+ }
55
+ // Validate payload structure
56
+ const structureResult = this.validatePayloadStructure(payload);
57
+ if (structureResult.ok === false) {
58
+ this.recordError('payload_structure', structureResult.error);
59
+ return (0, shared_1.err)(structureResult.error);
60
+ }
61
+ // Apply custom rules
62
+ for (const rule of this.options.customRules) {
63
+ if (!rule.appliesTo || rule.appliesTo.includes('send')) {
64
+ const error = rule.validate(payload, context);
65
+ if (error) {
66
+ this.recordError(rule.name, error);
67
+ return (0, shared_1.err)(`VALIDATION_FAILED:${rule.name}:${error}`);
68
+ }
69
+ }
70
+ }
71
+ return (0, shared_1.ok)({ payload });
72
+ }
73
+ onReceive(envelope, context) {
74
+ // Validate envelope size
75
+ const sizeResult = this.validateEnvelopeSize(envelope);
76
+ if (sizeResult.ok === false) {
77
+ this.recordError('envelope_size', sizeResult.error);
78
+ return (0, shared_1.err)(sizeResult.error);
79
+ }
80
+ // Validate envelope structure
81
+ const structureResult = this.validateEnvelopeStructure(envelope);
82
+ if (structureResult.ok === false) {
83
+ this.recordError('envelope_structure', structureResult.error);
84
+ return (0, shared_1.err)(structureResult.error);
85
+ }
86
+ // Apply custom rules
87
+ for (const rule of this.options.customRules) {
88
+ if (!rule.appliesTo || rule.appliesTo.includes('receive')) {
89
+ const error = rule.validate(envelope, context);
90
+ if (error) {
91
+ this.recordError(rule.name, error);
92
+ return (0, shared_1.err)(`VALIDATION_FAILED:${rule.name}:${error}`);
93
+ }
94
+ }
95
+ }
96
+ return (0, shared_1.ok)({ payload: envelope });
97
+ }
98
+ onEncrypt(plaintext, context) {
99
+ // Validate plaintext is not empty
100
+ if (plaintext.length === 0) {
101
+ this.recordError('plaintext_empty', 'Plaintext cannot be empty');
102
+ return (0, shared_1.err)('VALIDATION_FAILED:PLAINTEXT_EMPTY');
103
+ }
104
+ // Validate plaintext size
105
+ if (plaintext.length > this.options.maxPayloadSize) {
106
+ this.recordError('plaintext_size', `Plaintext exceeds max size: ${plaintext.length} bytes`);
107
+ return (0, shared_1.err)(`VALIDATION_FAILED:PLAINTEXT_TOO_LARGE:${plaintext.length}`);
108
+ }
109
+ // Apply custom rules
110
+ for (const rule of this.options.customRules) {
111
+ if (!rule.appliesTo || rule.appliesTo.includes('encrypt')) {
112
+ const error = rule.validate(plaintext, context);
113
+ if (error) {
114
+ this.recordError(rule.name, error);
115
+ return (0, shared_1.err)(`VALIDATION_FAILED:${rule.name}:${error}`);
116
+ }
117
+ }
118
+ }
119
+ return (0, shared_1.ok)({ payload: plaintext });
120
+ }
121
+ onDecrypt(plaintext, context) {
122
+ // Validate plaintext is not empty
123
+ if (plaintext.length === 0) {
124
+ this.recordError('plaintext_empty', 'Decrypted plaintext is empty');
125
+ return (0, shared_1.err)('VALIDATION_FAILED:DECRYPTED_EMPTY');
126
+ }
127
+ // Apply custom rules
128
+ for (const rule of this.options.customRules) {
129
+ if (!rule.appliesTo || rule.appliesTo.includes('decrypt')) {
130
+ const error = rule.validate(plaintext, context);
131
+ if (error) {
132
+ this.recordError(rule.name, error);
133
+ return (0, shared_1.err)(`VALIDATION_FAILED:${rule.name}:${error}`);
134
+ }
135
+ }
136
+ }
137
+ return (0, shared_1.ok)({ payload: plaintext });
138
+ }
139
+ /**
140
+ * Get all validation errors.
141
+ */
142
+ getValidationErrors() {
143
+ return [...this.validationErrors];
144
+ }
145
+ /**
146
+ * Clear validation errors.
147
+ */
148
+ clearErrors() {
149
+ this.validationErrors = [];
150
+ }
151
+ /**
152
+ * Add a custom validation rule.
153
+ */
154
+ addRule(rule) {
155
+ this.options.customRules.push(rule);
156
+ }
157
+ /**
158
+ * Remove a custom validation rule by name.
159
+ */
160
+ removeRule(name) {
161
+ const index = this.options.customRules.findIndex((r) => r.name === name);
162
+ if (index === -1) {
163
+ return false;
164
+ }
165
+ this.options.customRules.splice(index, 1);
166
+ return true;
167
+ }
168
+ validatePayloadSize(payload) {
169
+ const size = this.estimateSize(payload);
170
+ if (size > this.options.maxPayloadSize) {
171
+ return (0, shared_1.err)(`VALIDATION_FAILED:PAYLOAD_TOO_LARGE:${size}>${this.options.maxPayloadSize}`);
172
+ }
173
+ return (0, shared_1.ok)(undefined);
174
+ }
175
+ validateEnvelopeSize(envelope) {
176
+ const size = this.estimateSize(envelope);
177
+ if (size > this.options.maxEnvelopeSize) {
178
+ return (0, shared_1.err)(`VALIDATION_FAILED:ENVELOPE_TOO_LARGE:${size}>${this.options.maxEnvelopeSize}`);
179
+ }
180
+ return (0, shared_1.ok)(undefined);
181
+ }
182
+ validateScope(scope) {
183
+ if (this.options.allowedScopes.length > 0 && !this.options.allowedScopes.includes(scope)) {
184
+ return (0, shared_1.err)(`VALIDATION_FAILED:SCOPE_NOT_ALLOWED:${scope}`);
185
+ }
186
+ return (0, shared_1.ok)(undefined);
187
+ }
188
+ validatePayloadStructure(payload) {
189
+ if (payload === null || payload === undefined) {
190
+ return (0, shared_1.err)('VALIDATION_FAILED:PAYLOAD_NULL_OR_UNDEFINED');
191
+ }
192
+ // Validate can be serialized to JSON
193
+ try {
194
+ JSON.stringify(payload);
195
+ }
196
+ catch (error) {
197
+ return (0, shared_1.err)(`VALIDATION_FAILED:PAYLOAD_NOT_SERIALIZABLE:${String(error)}`);
198
+ }
199
+ return (0, shared_1.ok)(undefined);
200
+ }
201
+ validateEnvelopeStructure(envelope) {
202
+ // Validate required fields
203
+ if (!('v' in envelope) && !('version' in envelope)) {
204
+ return (0, shared_1.err)('VALIDATION_FAILED:ENVELOPE_MISSING_VERSION');
205
+ }
206
+ if (!envelope.sender) {
207
+ return (0, shared_1.err)('VALIDATION_FAILED:ENVELOPE_MISSING_SENDER');
208
+ }
209
+ if (!envelope.recipient) {
210
+ return (0, shared_1.err)('VALIDATION_FAILED:ENVELOPE_MISSING_RECIPIENT');
211
+ }
212
+ if (!('payload' in envelope) && !('ciphertext' in envelope)) {
213
+ return (0, shared_1.err)('VALIDATION_FAILED:ENVELOPE_MISSING_CIPHERTEXT');
214
+ }
215
+ return (0, shared_1.ok)(undefined);
216
+ }
217
+ estimateSize(value) {
218
+ if (value instanceof Uint8Array) {
219
+ return value.length;
220
+ }
221
+ try {
222
+ return JSON.stringify(value).length;
223
+ }
224
+ catch {
225
+ return 0;
226
+ }
227
+ }
228
+ recordError(rule, error) {
229
+ this.validationErrors.push({
230
+ timestamp: Date.now(),
231
+ rule,
232
+ error,
233
+ });
234
+ // Keep only last 1000 errors
235
+ if (this.validationErrors.length > 1000) {
236
+ this.validationErrors.shift();
237
+ }
238
+ }
239
+ }
240
+ exports.ValidationPlugin = ValidationPlugin;
241
+ /**
242
+ * Create a validation plugin with options.
243
+ */
244
+ function createValidationPlugin(options) {
245
+ return new ValidationPlugin(options);
246
+ }
247
+ /**
248
+ * Common validation rules.
249
+ */
250
+ exports.CommonRules = {
251
+ /**
252
+ * Validate payload contains required fields.
253
+ */
254
+ requireFields(fields) {
255
+ return {
256
+ name: 'require_fields',
257
+ appliesTo: ['send'],
258
+ validate: (value) => {
259
+ if (typeof value !== 'object' || value === null) {
260
+ return 'Payload must be an object';
261
+ }
262
+ const obj = value;
263
+ const missing = fields.filter((field) => !(field in obj));
264
+ if (missing.length > 0) {
265
+ return `Missing required fields: ${missing.join(', ')}`;
266
+ }
267
+ return null;
268
+ },
269
+ };
270
+ },
271
+ /**
272
+ * Validate DID format.
273
+ */
274
+ validateDIDFormat() {
275
+ return {
276
+ name: 'did_format',
277
+ appliesTo: ['send', 'receive'],
278
+ validate: (value, context) => {
279
+ if (context.recipient && !context.recipient.startsWith('did:')) {
280
+ return `Invalid DID format: ${context.recipient}`;
281
+ }
282
+ return null;
283
+ },
284
+ };
285
+ },
286
+ /**
287
+ * Validate timestamp is recent.
288
+ */
289
+ validateTimestamp(maxAgeMs = 300000) {
290
+ return {
291
+ name: 'timestamp_freshness',
292
+ appliesTo: ['receive'],
293
+ validate: (value, context) => {
294
+ const age = Date.now() - context.timestamp;
295
+ if (age > maxAgeMs) {
296
+ return `Timestamp too old: ${age}ms > ${maxAgeMs}ms`;
297
+ }
298
+ return null;
299
+ },
300
+ };
301
+ },
302
+ };
@@ -1 +1,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}
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
+ }