@agirails/sdk 2.0.3 → 2.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.
Files changed (151) hide show
  1. package/README.md +536 -87
  2. package/dist/adapters/BaseAdapter.js +2 -2
  3. package/dist/adapters/BaseAdapter.js.map +1 -1
  4. package/dist/adapters/BasicAdapter.d.ts.map +1 -1
  5. package/dist/adapters/BasicAdapter.js +8 -0
  6. package/dist/adapters/BasicAdapter.js.map +1 -1
  7. package/dist/adapters/StandardAdapter.d.ts +10 -5
  8. package/dist/adapters/StandardAdapter.d.ts.map +1 -1
  9. package/dist/adapters/StandardAdapter.js +19 -6
  10. package/dist/adapters/StandardAdapter.js.map +1 -1
  11. package/dist/builders/QuoteBuilder.js +1 -1
  12. package/dist/builders/QuoteBuilder.js.map +1 -1
  13. package/dist/cli/commands/config.js +1 -1
  14. package/dist/cli/commands/config.js.map +1 -1
  15. package/dist/cli/commands/simulate.js.map +1 -1
  16. package/dist/cli/commands/time.d.ts.map +1 -1
  17. package/dist/cli/commands/time.js.map +1 -1
  18. package/dist/config/networks.d.ts +9 -0
  19. package/dist/config/networks.d.ts.map +1 -1
  20. package/dist/config/networks.js +25 -10
  21. package/dist/config/networks.js.map +1 -1
  22. package/dist/index.d.ts +6 -1
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +31 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/level0/provide.d.ts.map +1 -1
  27. package/dist/level0/provide.js +2 -1
  28. package/dist/level0/provide.js.map +1 -1
  29. package/dist/level0/request.d.ts.map +1 -1
  30. package/dist/level0/request.js +1 -2
  31. package/dist/level0/request.js.map +1 -1
  32. package/dist/level1/Agent.d.ts.map +1 -1
  33. package/dist/level1/Agent.js +11 -3
  34. package/dist/level1/Agent.js.map +1 -1
  35. package/dist/level1/pricing/PriceCalculator.js +1 -1
  36. package/dist/level1/pricing/PriceCalculator.js.map +1 -1
  37. package/dist/level1/types/Options.d.ts.map +1 -1
  38. package/dist/protocol/ACTPKernel.d.ts.map +1 -1
  39. package/dist/protocol/ACTPKernel.js +7 -5
  40. package/dist/protocol/ACTPKernel.js.map +1 -1
  41. package/dist/protocol/DIDResolver.js +1 -1
  42. package/dist/protocol/DIDResolver.js.map +1 -1
  43. package/dist/protocol/EASHelper.d.ts.map +1 -1
  44. package/dist/protocol/EASHelper.js +2 -3
  45. package/dist/protocol/EASHelper.js.map +1 -1
  46. package/dist/protocol/MessageSigner.d.ts.map +1 -1
  47. package/dist/protocol/MessageSigner.js +9 -9
  48. package/dist/protocol/MessageSigner.js.map +1 -1
  49. package/dist/protocol/ProofGenerator.d.ts.map +1 -1
  50. package/dist/protocol/ProofGenerator.js +1 -0
  51. package/dist/protocol/ProofGenerator.js.map +1 -1
  52. package/dist/runtime/BlockchainRuntime.d.ts +10 -3
  53. package/dist/runtime/BlockchainRuntime.d.ts.map +1 -1
  54. package/dist/runtime/BlockchainRuntime.js +41 -25
  55. package/dist/runtime/BlockchainRuntime.js.map +1 -1
  56. package/dist/runtime/IACTPRuntime.d.ts +15 -0
  57. package/dist/runtime/IACTPRuntime.d.ts.map +1 -1
  58. package/dist/runtime/MockRuntime.d.ts +7 -0
  59. package/dist/runtime/MockRuntime.d.ts.map +1 -1
  60. package/dist/runtime/MockRuntime.js +15 -4
  61. package/dist/runtime/MockRuntime.js.map +1 -1
  62. package/dist/runtime/types/MockState.d.ts +5 -2
  63. package/dist/runtime/types/MockState.d.ts.map +1 -1
  64. package/dist/runtime/types/MockState.js.map +1 -1
  65. package/dist/storage/ArchiveBundleBuilder.d.ts +150 -0
  66. package/dist/storage/ArchiveBundleBuilder.d.ts.map +1 -0
  67. package/dist/storage/ArchiveBundleBuilder.js +468 -0
  68. package/dist/storage/ArchiveBundleBuilder.js.map +1 -0
  69. package/dist/storage/ArweaveClient.d.ts +271 -0
  70. package/dist/storage/ArweaveClient.d.ts.map +1 -0
  71. package/dist/storage/ArweaveClient.js +761 -0
  72. package/dist/storage/ArweaveClient.js.map +1 -0
  73. package/dist/storage/FilebaseClient.d.ts +193 -0
  74. package/dist/storage/FilebaseClient.d.ts.map +1 -0
  75. package/dist/storage/FilebaseClient.js +643 -0
  76. package/dist/storage/FilebaseClient.js.map +1 -0
  77. package/dist/storage/index.d.ts +47 -0
  78. package/dist/storage/index.d.ts.map +1 -0
  79. package/dist/storage/index.js +64 -0
  80. package/dist/storage/index.js.map +1 -0
  81. package/dist/storage/types.d.ts +291 -0
  82. package/dist/storage/types.d.ts.map +1 -0
  83. package/dist/storage/types.js +18 -0
  84. package/dist/storage/types.js.map +1 -0
  85. package/dist/types/state.d.ts +5 -4
  86. package/dist/types/state.d.ts.map +1 -1
  87. package/dist/types/state.js +10 -9
  88. package/dist/types/state.js.map +1 -1
  89. package/dist/utils/ErrorRecoveryGuide.d.ts.map +1 -1
  90. package/dist/utils/ErrorRecoveryGuide.js +1 -2
  91. package/dist/utils/ErrorRecoveryGuide.js.map +1 -1
  92. package/dist/utils/IPFSClient.d.ts.map +1 -1
  93. package/dist/utils/IPFSClient.js +5 -2
  94. package/dist/utils/IPFSClient.js.map +1 -1
  95. package/dist/utils/NonceManager.d.ts.map +1 -1
  96. package/dist/utils/NonceManager.js +3 -2
  97. package/dist/utils/NonceManager.js.map +1 -1
  98. package/dist/utils/UsedAttestationTracker.d.ts +1 -1
  99. package/dist/utils/UsedAttestationTracker.d.ts.map +1 -1
  100. package/dist/utils/UsedAttestationTracker.js +4 -4
  101. package/dist/utils/UsedAttestationTracker.js.map +1 -1
  102. package/dist/utils/circuitBreaker.d.ts +136 -0
  103. package/dist/utils/circuitBreaker.d.ts.map +1 -0
  104. package/dist/utils/circuitBreaker.js +253 -0
  105. package/dist/utils/circuitBreaker.js.map +1 -0
  106. package/dist/utils/retry.d.ts +120 -0
  107. package/dist/utils/retry.d.ts.map +1 -0
  108. package/dist/utils/retry.js +260 -0
  109. package/dist/utils/retry.js.map +1 -0
  110. package/dist/utils/validation.d.ts +100 -0
  111. package/dist/utils/validation.d.ts.map +1 -1
  112. package/dist/utils/validation.js +248 -1
  113. package/dist/utils/validation.js.map +1 -1
  114. package/package.json +14 -2
  115. package/src/adapters/BaseAdapter.ts +2 -2
  116. package/src/adapters/BasicAdapter.ts +12 -2
  117. package/src/adapters/StandardAdapter.ts +27 -7
  118. package/src/builders/QuoteBuilder.ts +1 -1
  119. package/src/cli/commands/config.ts +1 -1
  120. package/src/cli/commands/simulate.ts +1 -1
  121. package/src/cli/commands/time.ts +1 -2
  122. package/src/config/networks.ts +34 -10
  123. package/src/index.ts +54 -0
  124. package/src/level0/provide.ts +2 -1
  125. package/src/level0/request.ts +1 -2
  126. package/src/level1/Agent.ts +15 -5
  127. package/src/level1/pricing/PriceCalculator.ts +1 -1
  128. package/src/level1/types/Options.ts +1 -1
  129. package/src/protocol/ACTPKernel.ts +7 -5
  130. package/src/protocol/DIDResolver.ts +1 -1
  131. package/src/protocol/EASHelper.ts +2 -5
  132. package/src/protocol/MessageSigner.ts +9 -15
  133. package/src/protocol/ProofGenerator.ts +1 -0
  134. package/src/runtime/BlockchainRuntime.ts +42 -48
  135. package/src/runtime/IACTPRuntime.ts +16 -0
  136. package/src/runtime/MockRuntime.ts +16 -6
  137. package/src/runtime/types/MockState.ts +5 -2
  138. package/src/storage/ArchiveBundleBuilder.ts +563 -0
  139. package/src/storage/ArweaveClient.ts +945 -0
  140. package/src/storage/FilebaseClient.ts +790 -0
  141. package/src/storage/index.ts +96 -0
  142. package/src/storage/types.ts +348 -0
  143. package/src/types/state.ts +10 -9
  144. package/src/utils/ErrorRecoveryGuide.ts +1 -2
  145. package/src/utils/IPFSClient.ts +5 -4
  146. package/src/utils/NonceManager.ts +3 -2
  147. package/src/utils/UsedAttestationTracker.ts +4 -6
  148. package/src/utils/circuitBreaker.ts +324 -0
  149. package/src/utils/fsSafe.ts +5 -0
  150. package/src/utils/retry.ts +365 -0
  151. package/src/utils/validation.ts +295 -1
@@ -2,13 +2,72 @@ import { isAddress, getAddress } from 'ethers';
2
2
  import {
3
3
  InvalidAddressError,
4
4
  InvalidAmountError,
5
- ValidationError
5
+ ValidationError,
6
+ InvalidCIDError,
7
+ InvalidArweaveTxIdError
6
8
  } from '../errors';
7
9
 
8
10
  /**
9
11
  * Input validation utilities
10
12
  */
11
13
 
14
+ // ============================================================================
15
+ // Shared Validation Patterns (AIP-7 Storage)
16
+ // ============================================================================
17
+
18
+ /** Ethereum address validation pattern */
19
+ export const ADDRESS_PATTERN = /^0x[a-fA-F0-9]{40}$/;
20
+
21
+ /** Transaction ID (bytes32) validation pattern */
22
+ export const TX_ID_PATTERN = /^0x[a-fA-F0-9]{64}$/;
23
+
24
+ /** Hash (bytes32) validation pattern */
25
+ export const HASH_PATTERN = /^0x[a-fA-F0-9]{64}$/;
26
+
27
+ /** Signature (65 bytes = 130 hex chars) validation pattern */
28
+ export const SIGNATURE_PATTERN = /^0x[a-fA-F0-9]{130}$/;
29
+
30
+ /** CID validation pattern (CIDv0 or CIDv1) */
31
+ export const CID_PATTERN = /^(Qm[1-9A-HJ-NP-Za-km-z]{44}|b[a-z2-7]{58,})$/;
32
+
33
+ /** Arweave TX ID pattern (43 characters, base64url) */
34
+ export const ARWEAVE_TX_ID_PATTERN = /^[a-zA-Z0-9_-]{43}$/;
35
+
36
+ /** Semver pattern for version validation */
37
+ export const SEMVER_PATTERN = /^\d+\.\d+\.\d+$/;
38
+
39
+ // ============================================================================
40
+ // Gateway URL Whitelist (SSRF Protection - P0-1)
41
+ // ============================================================================
42
+
43
+ /**
44
+ * Allowed IPFS gateway domains
45
+ * Only whitelisted gateways are allowed for downloads
46
+ */
47
+ export const ALLOWED_IPFS_GATEWAYS = [
48
+ 'ipfs.filebase.io',
49
+ 'gateway.pinata.cloud',
50
+ 'cloudflare-ipfs.com',
51
+ 'ipfs.io',
52
+ 'dweb.link',
53
+ 'w3s.link',
54
+ 'nftstorage.link'
55
+ ] as const;
56
+
57
+ /**
58
+ * Allowed Arweave gateway domains
59
+ * Only whitelisted gateways are allowed for downloads
60
+ */
61
+ export const ALLOWED_ARWEAVE_GATEWAYS = [
62
+ 'arweave.net',
63
+ 'gateway.irys.xyz',
64
+ 'arweave.dev'
65
+ ] as const;
66
+
67
+ // ============================================================================
68
+ // Validation Functions
69
+ // ============================================================================
70
+
12
71
  /**
13
72
  * Validate Ethereum address
14
73
  */
@@ -113,13 +172,19 @@ function isPrivateIP(ip: string): boolean {
113
172
  }
114
173
 
115
174
  // IPv6 patterns (without brackets)
175
+ // Includes both standard ::ffff: and alternative ::ffff:0: notation (NEW-2 fix)
116
176
  const ipv6PrivatePatterns = [
117
177
  /^::1$/, // IPv6 loopback
118
178
  /^::ffff:127\./, // IPv4-mapped localhost
179
+ /^::ffff:0:127\./, // Alternative IPv4-mapped localhost
119
180
  /^::ffff:10\./, // IPv4-mapped private 10.x
181
+ /^::ffff:0:10\./, // Alternative IPv4-mapped private 10.x
120
182
  /^::ffff:192\.168\./, // IPv4-mapped private 192.168.x
183
+ /^::ffff:0:192\.168\./, // Alternative IPv4-mapped private 192.168.x
121
184
  /^::ffff:172\.(1[6-9]|2\d|3[01])\./, // IPv4-mapped private 172.16-31.x
185
+ /^::ffff:0:172\.(1[6-9]|2\d|3[01])\./,// Alternative IPv4-mapped private 172.16-31.x
122
186
  /^::ffff:169\.254\./, // IPv4-mapped link-local (CRITICAL: AWS metadata)
187
+ /^::ffff:0:169\.254\./, // Alternative IPv4-mapped link-local
123
188
  /^fc00:/i, // IPv6 ULA fc00::/7
124
189
  /^fd/i, // IPv6 ULA fd00::/8
125
190
  /^fe80:/i // IPv6 link-local fe80::/10
@@ -244,3 +309,232 @@ export async function validateEndpointURL(endpoint: string, fieldName: string =
244
309
  // IPFS endpoints skip DNS check (no DNS resolution for IPFS CIDs)
245
310
  }
246
311
 
312
+ // ============================================================================
313
+ // Storage Validation Functions (AIP-7)
314
+ // ============================================================================
315
+
316
+ /**
317
+ * Validate IPFS CID format
318
+ *
319
+ * @param cid - IPFS CID to validate
320
+ * @param fieldName - Field name for error messages
321
+ * @throws {InvalidCIDError} If CID is invalid
322
+ */
323
+ export function validateCID(cid: string, fieldName: string = 'cid'): void {
324
+ if (!cid || typeof cid !== 'string') {
325
+ throw new InvalidCIDError(String(cid), 'CID is required');
326
+ }
327
+
328
+ if (!CID_PATTERN.test(cid)) {
329
+ throw new InvalidCIDError(cid, 'Invalid CID format (expected CIDv0 Qm... or CIDv1 bafy...)');
330
+ }
331
+ }
332
+
333
+ /**
334
+ * Validate Arweave transaction ID format
335
+ *
336
+ * @param txId - Arweave TX ID to validate
337
+ * @param fieldName - Field name for error messages
338
+ * @throws {InvalidArweaveTxIdError} If TX ID is invalid
339
+ */
340
+ export function validateArweaveTxId(txId: string, fieldName: string = 'txId'): void {
341
+ if (!txId || typeof txId !== 'string') {
342
+ throw new InvalidArweaveTxIdError(String(txId), 'TX ID is required');
343
+ }
344
+
345
+ if (!ARWEAVE_TX_ID_PATTERN.test(txId)) {
346
+ throw new InvalidArweaveTxIdError(
347
+ txId,
348
+ 'Invalid format (expected 43 character base64url string)'
349
+ );
350
+ }
351
+ }
352
+
353
+ /**
354
+ * Validate gateway URL against whitelist (SSRF Protection - P0-1)
355
+ *
356
+ * SECURITY FIX: Only allow downloads from whitelisted gateway domains.
357
+ * This prevents SSRF attacks where attacker controls the gateway URL.
358
+ *
359
+ * @param url - Full gateway URL to validate
360
+ * @param allowedGateways - List of allowed gateway domains
361
+ * @param fieldName - Field name for error messages
362
+ * @throws {ValidationError} If gateway is not whitelisted
363
+ */
364
+ export function validateGatewayURL(
365
+ url: string,
366
+ allowedGateways: readonly string[],
367
+ fieldName: string = 'gatewayUrl'
368
+ ): void {
369
+ if (!url || typeof url !== 'string') {
370
+ throw new ValidationError(fieldName, 'Gateway URL is required');
371
+ }
372
+
373
+ let parsedUrl: URL;
374
+ try {
375
+ parsedUrl = new URL(url);
376
+ } catch {
377
+ throw new ValidationError(fieldName, 'Invalid URL format');
378
+ }
379
+
380
+ // Must be HTTPS
381
+ if (parsedUrl.protocol !== 'https:') {
382
+ throw new ValidationError(fieldName, 'Gateway URL must use HTTPS');
383
+ }
384
+
385
+ // NEW-3: Validate port (must be 443 or default, prevents port bypass attacks)
386
+ const port = parsedUrl.port;
387
+ if (port && !['443', ''].includes(port)) {
388
+ throw new ValidationError(
389
+ fieldName,
390
+ `Gateway URL must use standard HTTPS port (443). Found port: ${port}. ` +
391
+ `Non-standard ports may bypass whitelist intent.`
392
+ );
393
+ }
394
+
395
+ // Check hostname against whitelist
396
+ const hostname = parsedUrl.hostname.toLowerCase();
397
+ const isAllowed = allowedGateways.some(gateway =>
398
+ hostname === gateway.toLowerCase() ||
399
+ hostname.endsWith('.' + gateway.toLowerCase())
400
+ );
401
+
402
+ if (!isAllowed) {
403
+ throw new ValidationError(
404
+ fieldName,
405
+ `Gateway "${hostname}" is not in the allowed list. ` +
406
+ `Allowed gateways: ${allowedGateways.join(', ')}. ` +
407
+ `This restriction prevents SSRF attacks.`
408
+ );
409
+ }
410
+ }
411
+
412
+ /**
413
+ * Validate semver version string
414
+ *
415
+ * @param version - Version string to validate
416
+ * @param fieldName - Field name for error messages
417
+ * @throws {ValidationError} If version is invalid
418
+ */
419
+ export function validateSemver(version: string, fieldName: string = 'version'): void {
420
+ if (!version || typeof version !== 'string') {
421
+ throw new ValidationError(fieldName, 'Version is required');
422
+ }
423
+
424
+ if (!SEMVER_PATTERN.test(version)) {
425
+ throw new ValidationError(fieldName, 'Must be semver format (e.g., 1.0.0)');
426
+ }
427
+ }
428
+
429
+ /**
430
+ * Validate hash (bytes32) format
431
+ *
432
+ * @param hash - Hash to validate
433
+ * @param fieldName - Field name for error messages
434
+ * @throws {ValidationError} If hash is invalid
435
+ */
436
+ export function validateHash(hash: string, fieldName: string = 'hash'): void {
437
+ if (!hash || typeof hash !== 'string') {
438
+ throw new ValidationError(fieldName, 'Hash is required');
439
+ }
440
+
441
+ if (!HASH_PATTERN.test(hash)) {
442
+ throw new ValidationError(fieldName, 'Invalid hash format (expected bytes32 hex string)');
443
+ }
444
+ }
445
+
446
+ /**
447
+ * Validate signature format (65 bytes)
448
+ *
449
+ * @param signature - Signature to validate
450
+ * @param fieldName - Field name for error messages
451
+ * @throws {ValidationError} If signature is invalid
452
+ */
453
+ export function validateSignature(signature: string, fieldName: string = 'signature'): void {
454
+ if (!signature || typeof signature !== 'string') {
455
+ throw new ValidationError(fieldName, 'Signature is required');
456
+ }
457
+
458
+ if (!SIGNATURE_PATTERN.test(signature)) {
459
+ throw new ValidationError(
460
+ fieldName,
461
+ 'Invalid signature format (expected 65 bytes = 0x + 130 hex chars)'
462
+ );
463
+ }
464
+ }
465
+
466
+ // ============================================================================
467
+ // Error Sanitization (P0-2)
468
+ // ============================================================================
469
+
470
+ /**
471
+ * Sanitize error messages to remove sensitive data
472
+ *
473
+ * SECURITY FIX (P0-2): Removes credentials, private keys, and other
474
+ * sensitive data from error messages before logging/returning.
475
+ *
476
+ * @param error - Error to sanitize
477
+ * @returns Sanitized error message
478
+ */
479
+ export function sanitizeErrorMessage(error: unknown): string {
480
+ if (!error) return 'Unknown error';
481
+
482
+ let message = '';
483
+ if (error instanceof Error) {
484
+ message = error.message;
485
+ } else if (typeof error === 'string') {
486
+ message = error;
487
+ } else {
488
+ message = String(error);
489
+ }
490
+
491
+ // Patterns to redact
492
+ const sensitivePatterns = [
493
+ // Private keys (hex)
494
+ /0x[a-fA-F0-9]{64}/g,
495
+ // AWS access key IDs
496
+ /AKIA[0-9A-Z]{16}/g,
497
+ // AWS secret keys (40 chars)
498
+ /[a-zA-Z0-9/+=]{40}/g,
499
+ // Bearer tokens
500
+ /Bearer\s+[a-zA-Z0-9._-]+/gi,
501
+ // API keys (generic pattern)
502
+ /api[_-]?key[=:]\s*["']?[a-zA-Z0-9_-]+["']?/gi,
503
+ // Secret in URL query params
504
+ /secret[=][^&\s]+/gi,
505
+ // Password in URL
506
+ /password[=][^&\s]+/gi,
507
+ // Authorization headers
508
+ /authorization[=:]\s*["']?[^"'\s]+["']?/gi
509
+ ];
510
+
511
+ let sanitized = message;
512
+ for (const pattern of sensitivePatterns) {
513
+ sanitized = sanitized.replace(pattern, '[REDACTED]');
514
+ }
515
+
516
+ return sanitized;
517
+ }
518
+
519
+ /**
520
+ * Create a safe error object for external consumption
521
+ *
522
+ * SECURITY FIX (P0-2): Returns error without stack trace or sensitive details
523
+ *
524
+ * @param error - Original error
525
+ * @param operation - What operation failed
526
+ * @returns Safe error object
527
+ */
528
+ export function createSafeError(
529
+ error: unknown,
530
+ operation: string
531
+ ): { message: string; code: string; operation: string } {
532
+ const sanitizedMessage = sanitizeErrorMessage(error);
533
+
534
+ // Don't expose internal details - generic message with operation context
535
+ return {
536
+ message: `Operation failed: ${operation}. ${sanitizedMessage}`,
537
+ code: (error as any)?.code || 'UNKNOWN_ERROR',
538
+ operation
539
+ };
540
+ }