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