@dstorage-tech/dstorage-sdk 0.0.6 → 0.0.8

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 (33) hide show
  1. package/dist/KeypairEncryptionAdapter-EOBRCIGP-5PFPNLLA.mjs +8 -0
  2. package/dist/{KeypairEncryptionAdapter-XUKCLRFU-AYDAZ2TZ.mjs → KeypairEncryptionAdapter-EOBRCIGP-FLPJIL26.mjs} +3 -3
  3. package/dist/{MnemonicEncryptionAdapter-RCHUETBP-M7NHGSHO.mjs → MnemonicEncryptionAdapter-S56YG63Q-B3F3TO3T.mjs} +3 -3
  4. package/dist/MnemonicEncryptionAdapter-S56YG63Q-POTD74UN.mjs +8 -0
  5. package/dist/{PasswordEncryptionAdapter-ECHND672-MUTHAMZY.mjs → PasswordEncryptionAdapter-B2UG7MWB-M4C3KJ4S.mjs} +3 -3
  6. package/dist/{PasswordEncryptionAdapter-ECHND672-3DEFO6FP.mjs → PasswordEncryptionAdapter-B2UG7MWB-QCSOIQJA.mjs} +3 -3
  7. package/dist/browser.d.mts +91 -8
  8. package/dist/browser.mjs +171 -67
  9. package/dist/{chunk-HDD6SUU4.mjs → chunk-42O7KEL4.mjs} +30 -11
  10. package/dist/{chunk-X4LEBNK6.mjs → chunk-5F3HZ2RJ.mjs} +30 -11
  11. package/dist/{chunk-6IAQVMSM.mjs → chunk-E73HFT6J.mjs} +5 -5
  12. package/dist/{chunk-UDYXMII2.mjs → chunk-EOPUNIUH.mjs} +5 -5
  13. package/dist/{chunk-O37NHERH.mjs → chunk-L6WCT64V.mjs} +4 -2
  14. package/dist/{chunk-4X5K43JF.mjs → chunk-M3F2LR3B.mjs} +3 -1
  15. package/dist/{chunk-JMPRZK5D.mjs → chunk-O6COTUD4.mjs} +3 -1
  16. package/dist/{chunk-BWLEAAFW.mjs → chunk-PCXBQRCO.mjs} +55 -2056
  17. package/dist/{chunk-OLGVVM5Y.mjs → chunk-QFJ2Y4XE.mjs} +5 -5
  18. package/dist/{chunk-Z6DUAI5B.mjs → chunk-XW4RZG2X.mjs} +5 -5
  19. package/dist/{contract-api-TJ7JPHZA-6FUBJ6DS.mjs → contract-api-NUY4UEKE-ZANT3ICG.mjs} +3 -3
  20. package/dist/{contract-api-AO4RGPLT-ENC72WCG.mjs → contract-api-P6YEDYQ6-2X6BMD64.mjs} +3 -3
  21. package/dist/{dist-INTAFXQ7.mjs → dist-AGNOIJI4.mjs} +3 -1
  22. package/dist/{dist-MOLWJ4Y7.mjs → dist-J4JUJ2J5.mjs} +3 -1
  23. package/dist/errors.d.mts +2 -0
  24. package/dist/errors.d.ts +2 -0
  25. package/dist/errors.js +10 -2054
  26. package/dist/errors.mjs +10 -2054
  27. package/dist/index.d.mts +108 -8
  28. package/dist/index.d.ts +108 -8
  29. package/dist/index.js +306 -2187
  30. package/dist/index.mjs +174 -70
  31. package/package.json +3 -2
  32. package/dist/KeypairEncryptionAdapter-XUKCLRFU-ERPYK5S4.mjs +0 -8
  33. package/dist/MnemonicEncryptionAdapter-RCHUETBP-DZPBGQG6.mjs +0 -8
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { PaymentAdapter, PaymentNetworkName, TokenSymbol, NetworkType, PaymentAdapterLogger, PaymentQuote, PaymentInstruction, PaymentReceipt, MidnightWalletProvider, StorageAdapterLogger, StorageAdapter, StorageProviderName, StorageUploadResult, StorageQuote, ChainAdapter, ChainProviderName, ChainAdapterLogger, ChainReference, ChainWriteResult, ChainReferenceUpdate, DataReferenceSummary, ChainQuote, WalletBalances } from './types.js';
1
+ import { PaymentAdapter, PaymentNetworkName, TokenSymbol, NetworkType, PaymentAdapterLogger, PaymentQuote, PaymentInstruction, PaymentReceipt, MidnightWalletProvider, StorageAdapterLogger, StorageAdapter, StorageProviderName, StorageUploadResult, RetrieveOptions, StorageQuote, ChainAdapter, ChainProviderName, ChainAdapterLogger, ChainReference, ChainWriteResult, ChainReferenceUpdate, DataReferenceSummary, ChainQuote, WalletBalances } from './types.js';
2
2
  export { ChainAdapter, ChainAdapterLogger, ChainProviderName, ChainQuote, ChainReference, ChainReferenceUpdate, ChainWriteResult, DataReferenceSummary, MidnightWalletProvider, NetworkType, PaymentAdapter, PaymentAdapterLogger, PaymentNetworkName, PaymentQuote, PaymentReceipt, StorageAdapter, StorageAdapterLogger, StorageProviderName, StorageQuote, StorageUploadResult, TOKENS, Token, TokenSymbol, WalletBalances } from './types.js';
3
3
  import Arweave from 'arweave';
4
4
  import Transaction from 'arweave/node/lib/transaction';
@@ -346,6 +346,12 @@ declare class ManagedPaymentAdapter extends ArweavePaymentAdapter {
346
346
  *
347
347
  * • storageId (txId) is PUBLIC on Arweave. Data security relies entirely on
348
348
  * the XChaCha20-Poly1305 encryption applied by @dstorage/crypto before reaching here.
349
+ *
350
+ * • retrieve()'s content-hash check only defends against a malicious gateway when
351
+ * called with an `expectedContentHash` anchor sourced independently of this
352
+ * gateway (see skipIntegrityCheck below) — @dstorage/core supplies this
353
+ * automatically from the on-chain reference. Without an anchor, the check falls
354
+ * back to a gateway-supplied tag and only catches non-adversarial corruption.
349
355
  */
350
356
 
351
357
  interface ArweaveGatewayConfig {
@@ -413,9 +419,17 @@ interface ArweaveAdapterConfig {
413
419
  confirmationTimeoutMs?: number;
414
420
  /**
415
421
  * When true, skip the BLAKE3 content-hash check on retrieve.
416
- * By default (false) the adapter fetches the transaction metadata and verifies
417
- * that the `X-Content-Hash` tag recorded at upload time matches the retrieved
418
- * bytes. Set to true only if you trust the gateway entirely or are using an
422
+ * By default (false) the adapter verifies retrieved bytes against a content hash.
423
+ * The strength of that guarantee depends on the hash's source:
424
+ * - When retrieve() is called with `options.expectedContentHash` (as
425
+ * `@dstorage/core` does automatically, from the on-chain ChainReference),
426
+ * verification is anchored to that chain-committed value and holds even
427
+ * against a fully malicious/colluding gateway.
428
+ * - Without an anchor, the adapter falls back to the `X-Content-Hash` tag
429
+ * fetched from this same gateway — that only catches non-adversarial
430
+ * corruption in transit, since a malicious gateway controls both the tag
431
+ * and the bytes and can make them consistent with each other.
432
+ * Set to true only if you trust the gateway entirely or are using an
419
433
  * Arweave node that does not expose the transaction metadata endpoint.
420
434
  */
421
435
  skipIntegrityCheck?: boolean;
@@ -450,7 +464,7 @@ declare class ArweaveStorageAdapter implements StorageAdapter {
450
464
  constructor(config?: ArweaveAdapterConfig);
451
465
  private getClient;
452
466
  store(data: Uint8Array, metadata?: Record<string, string>): Promise<StorageUploadResult>;
453
- retrieve(id: string): Promise<{
467
+ retrieve(id: string, options?: RetrieveOptions): Promise<{
454
468
  bytes: Uint8Array;
455
469
  tags: Record<string, string>;
456
470
  }>;
@@ -489,6 +503,11 @@ declare class ArweaveStorageAdapter implements StorageAdapter {
489
503
  *
490
504
  * ── Retrieve flow ─────────────────────────────────────────────────────────────
491
505
  * Standard Arweave gateway fetch (identical to ArweaveStorageAdapter.retrieve).
506
+ * Its content-hash check only defends against a malicious gateway when called
507
+ * with an `expectedContentHash` anchor sourced independently of this gateway
508
+ * (see skipIntegrityCheck below) — @dstorage/core supplies this automatically
509
+ * from the on-chain reference. Without an anchor, the check falls back to a
510
+ * gateway-supplied tag and only catches non-adversarial corruption.
492
511
  *
493
512
  * ── Peer dependency ───────────────────────────────────────────────────────────
494
513
  * No extra install needed — @dha-team/arbundles ships as a dependency of @ardrive/turbo-sdk.
@@ -541,10 +560,32 @@ interface ArweaveBundlerAdapterConfig {
541
560
  maxRetrieveSizeBytes?: number;
542
561
  /**
543
562
  * Skip BLAKE3 content-hash verification on retrieve.
563
+ * By default (false) the adapter verifies retrieved bytes against a content hash.
564
+ * The strength of that guarantee depends on the hash's source:
565
+ * - When retrieve() is called with `options.expectedContentHash` (as
566
+ * `@dstorage/core` does automatically, from the on-chain ChainReference),
567
+ * verification is anchored to that chain-committed value and holds even
568
+ * against a fully malicious/colluding gateway.
569
+ * - Without an anchor, the adapter falls back to the `X-Content-Hash` tag
570
+ * fetched from this same gateway — that only catches non-adversarial
571
+ * corruption in transit, since a malicious gateway controls both the tag
572
+ * and the bytes and can make them consistent with each other.
544
573
  * Only set to true when connecting to a fully trusted gateway.
545
- * Defaults to false.
546
574
  */
547
575
  skipIntegrityCheck?: boolean;
576
+ /**
577
+ * Maximum time in milliseconds to wait for any single retrieve() request
578
+ * (metadata or data fetch) before aborting. Defaults to 30_000 ms (30 s).
579
+ * Pass `0` to disable the timeout entirely (not recommended for production).
580
+ */
581
+ requestTimeoutMs?: number;
582
+ /**
583
+ * Maximum number of bytes allowed in the transaction metadata/tags JSON
584
+ * response fetched during retrieve(). Guards against a hostile or
585
+ * misbehaving gateway returning an oversized body to exhaust memory.
586
+ * Defaults to 1_048_576 (1 MiB) — metadata/tags are always tiny in practice.
587
+ */
588
+ maxMetadataResponseBytes?: number;
548
589
  /**
549
590
  * Optional logger for SDK operational output.
550
591
  */
@@ -573,12 +614,16 @@ declare class ArweaveBundlerStorageAdapter implements StorageAdapter {
573
614
  private readonly gateway;
574
615
  private readonly maxRetrieveSizeBytes;
575
616
  private readonly skipIntegrityCheck;
617
+ private readonly requestTimeoutMs;
618
+ private readonly maxMetadataResponseBytes;
576
619
  protected readonly logger: StorageAdapterLogger | undefined;
577
620
  /** RSA-4096 public key modulus (512 bytes) parsed from the auth token at construction time. */
578
621
  private readonly ownerPublicKey;
579
622
  constructor(config?: ArweaveBundlerAdapterConfig);
580
623
  store(data: Uint8Array, metadata?: Record<string, string>): Promise<StorageUploadResult>;
581
- retrieve(id: string): Promise<{
624
+ /** Adds an AbortSignal.timeout() to a fetch init object (when requestTimeoutMs > 0). */
625
+ private _withTimeout;
626
+ retrieve(id: string, options?: RetrieveOptions): Promise<{
582
627
  bytes: Uint8Array;
583
628
  tags: Record<string, string>;
584
629
  }>;
@@ -1335,6 +1380,34 @@ declare function computeBlake3(bytes: Uint8Array): Promise<Uint8Array>;
1335
1380
  /** BLAKE3 hash of `bytes`, returned as a 64-character lowercase hex string. */
1336
1381
  declare function computeBlake3Hex(bytes: Uint8Array): Promise<string>;
1337
1382
 
1383
+ /**
1384
+ * @dstorage/crypto — boundedFetch.ts
1385
+ * Shared helper for reading a fetch Response body with a hard size cap —
1386
+ * used by chain/storage HTTP adapters to avoid a hostile or misbehaving
1387
+ * gateway exhausting memory with an oversized response.
1388
+ */
1389
+ interface BoundedTextReadOptions {
1390
+ /** Maximum number of bytes/characters allowed in the response body. */
1391
+ maxBytes: number;
1392
+ /** Error code to throw (caller-owned, package-specific) when the cap is exceeded. */
1393
+ code: number;
1394
+ /** Prefix identifying the caller/operation in the thrown error message. */
1395
+ component: string;
1396
+ }
1397
+ /**
1398
+ * Reads a fetch Response body as text, aborting once the accumulated size
1399
+ * exceeds `maxBytes`.
1400
+ *
1401
+ * Uses a streaming reader when the Response exposes `.body` (always true for
1402
+ * real `fetch()` responses), so a gateway that omits or lies about
1403
+ * `Content-Length` (e.g. chunked transfer encoding) can't force an unbounded
1404
+ * read — the read is aborted as soon as the limit is crossed, before the
1405
+ * full body is buffered. Falls back to a single `.text()` read + post-hoc
1406
+ * length check only when `.body` is unavailable (e.g. non-streaming
1407
+ * environments or simple test doubles).
1408
+ */
1409
+ declare function readResponseTextWithLimit(res: Response, opts: BoundedTextReadOptions): Promise<string>;
1410
+
1338
1411
  /**
1339
1412
  * @dstorage/chain — adapters/midnightSimulator.ts
1340
1413
  *
@@ -1418,6 +1491,19 @@ interface HttpGatewayChainAdapterConfig {
1418
1491
  */
1419
1492
  customFetch?: typeof fetch;
1420
1493
  logger?: ChainAdapterLogger;
1494
+ /**
1495
+ * Maximum time in milliseconds to wait for any single request before aborting.
1496
+ * Defaults to 30_000 ms (30 s). Pass `0` to disable the timeout entirely
1497
+ * (not recommended for production).
1498
+ */
1499
+ requestTimeoutMs?: number;
1500
+ /**
1501
+ * Maximum number of bytes allowed in a `readReference`/`listReferences`
1502
+ * JSON response body. Guards against a hostile or misbehaving gateway
1503
+ * returning an oversized body to exhaust memory. Defaults to 10_485_760
1504
+ * (10 MiB) — generous for reference/list JSON payloads.
1505
+ */
1506
+ maxResponseBytes?: number;
1421
1507
  }
1422
1508
  declare class HttpGatewayChainAdapter implements ChainAdapter {
1423
1509
  readonly name: ChainProviderName;
@@ -1429,7 +1515,11 @@ declare class HttpGatewayChainAdapter implements ChainAdapter {
1429
1515
  private readonly readUrl;
1430
1516
  private readonly listUrl;
1431
1517
  private readonly deleteUrl;
1518
+ private readonly requestTimeoutMs;
1519
+ private readonly maxResponseBytes;
1432
1520
  constructor(config: HttpGatewayChainAdapterConfig);
1521
+ /** Adds an AbortSignal.timeout() to a fetch init object (when requestTimeoutMs > 0). */
1522
+ private _withTimeout;
1433
1523
  writeReference(ref: ChainReference): Promise<ChainWriteResult>;
1434
1524
  updateReference(refId: string, update: ChainReferenceUpdate, _ownerSecret?: Uint8Array, _newOwnerSecret?: Uint8Array): Promise<void>;
1435
1525
  readReference(refId: string): Promise<ChainReference>;
@@ -1769,6 +1859,8 @@ declare const EncryptionErrorCode: {
1769
1859
  readonly PASSWORD_SEQUENTIAL_RUN: 13008;
1770
1860
  readonly PASSWORD_KEYBOARD_WALK: 13009;
1771
1861
  readonly PASSWORD_ENTROPY_TOO_LOW: 13010;
1862
+ readonly PASSWORD_SCRYPT_N_TOO_LOW: 13011;
1863
+ readonly PASSWORD_SCRYPT_N_NOT_POWER_OF_TWO: 13012;
1772
1864
  };
1773
1865
  type EncryptionErrorCode = (typeof EncryptionErrorCode)[keyof typeof EncryptionErrorCode];
1774
1866
 
@@ -1997,6 +2089,12 @@ interface PasswordEncryptionAdapterConfig {
1997
2089
  /**
1998
2090
  * Custom scrypt parameters. Only used when `preset` is not provided.
1999
2091
  * Prefer `preset` for well-known configurations.
2092
+ *
2093
+ * `N` is rejected if it is below 32768 (OWASP 2024 minimum, 32 MB
2094
+ * memory-hard) or is not a power of two — this floor also applies when
2095
+ * reconstructing via `fromKdfParams()`, since a downgraded or corrupted
2096
+ * stored value could otherwise collapse the KDF to something trivially
2097
+ * brute-forceable.
2000
2098
  */
2001
2099
  params?: {
2002
2100
  N?: number;
@@ -2628,6 +2726,7 @@ declare const CoreErrorCode: {
2628
2726
  readonly STORAGE_ADAPTER_MISMATCH: 10052;
2629
2727
  readonly RETRIEVE_BY_REF_ID_ENVELOPE_EMPTY: 10053;
2630
2728
  readonly CONTENT_HASH_MISMATCH: 10054;
2729
+ readonly METADATA_PARSE_FAILED: 10055;
2631
2730
  readonly LIST_REFS_REQUIRES_CHAIN: 10060;
2632
2731
  readonly LIST_REFS_NOT_SUPPORTED: 10061;
2633
2732
  readonly REMOVE_REF_REQUIRES_CHAIN: 10070;
@@ -2638,6 +2737,7 @@ declare const CoreErrorCode: {
2638
2737
  readonly DECRYPT_CHUNK_FAILED: 10093;
2639
2738
  readonly CHUNK_OVERFLOWS_TOTAL_SIZE: 10094;
2640
2739
  readonly REASSEMBLY_SIZE_MISMATCH: 10095;
2740
+ readonly MANIFEST_PARSE_FAILED: 10096;
2641
2741
  readonly NOT_INITIALIZED: 10100;
2642
2742
  readonly UNKNOWN_ERROR: 10999;
2643
2743
  };
@@ -2653,4 +2753,4 @@ declare class StorePartialError extends DStorageError {
2653
2753
  }
2654
2754
  declare function isStorePartialError(err: unknown): err is StorePartialError;
2655
2755
 
2656
- export { ARWEAVE_LOCAL, type AdapterWalletProvider, type ArweaveBundlerAdapterConfig, ArweaveBundlerStorageAdapter, type ArweaveLocalAdapterConfig, type ArweaveLocalBalance, ArweaveLocalError, ArweaveLocalHelper, type ArweaveLocalHelperConfig, type ArweaveLocalInfo, ArweaveLocalStorageAdapter, ArweavePaymentAdapter, ArweaveStorageAdapter, CHUNK_SIZE, type ChunkEntry, type ChunkManifest, CoreErrorCode, type CostEstimate, CryptoErrorCode, type CryptoScheme, DStorage, type DStorageConfig, DStorageError, type EncryptionAdapter, EncryptionErrorCode, type EncryptionScheme, type FromKdfParamsConfig, HttpGatewayChainAdapter, type HttpGatewayChainAdapterConfig, KDF_PRESETS, type KdfPreset, KeyDeriver, type KeyEnvelope, type KeyWrapper, KeypairEncryptionAdapter, type ListReferencesOptions, type Logger, MANIFEST_AAD, METADATA_AAD, METADATA_ONLY_OWNER_SECRET_SALT, type MLKemVariant, ManagedPaymentAdapter, MidnightChainAdapter, type MidnightChainAdapterConfig, MidnightSimulatorChainAdapter, MnemonicEncryptionAdapter, NETWORKS, PAYLOAD_AAD, PasswordEncryptionAdapter, type PasswordEncryptionAdapterConfig, type RegisterReferenceOptions, type RegisterReferenceResult, type RetrieveResult, type StoreOptions, StorePartialError, type StoreProgress, type StoreRecovery, type StoreResult, type StoredKdfParams, type UpdateResult, type WalletAddresses, type WalletInfo, type WrappedDekResult, type XChaChaPayload, XChaChaScheme, arlocalGateway, base64urlToBytes, buildKeyEnvelope, bytesToBase64url, chunkAad, computeBlake3, computeBlake3Hex, decryptStorageIdXChaCha, decryptXChaCha, deriveKek, deriveOwnerSecret, deriveSymmetricKeyFromSeed, deserializeXChaChaPayload, encryptStorageIdXChaCha, encryptXChaCha, findWrapper, generateDek, generatePqsPassword, hexToBytes, isDStorageError, isManifest, isStorePartialError, mlkemGenerateKeypair, mlkemGenerateKeypairFromSeed, mlkemUnwrapDek, mlkemWrapDek, parseKeyEnvelope, serializeKeyEnvelope, serializeXChaChaPayload, unwrapKey, waitForFacadeSync, wrapKey };
2756
+ export { ARWEAVE_LOCAL, type AdapterWalletProvider, type ArweaveBundlerAdapterConfig, ArweaveBundlerStorageAdapter, type ArweaveLocalAdapterConfig, type ArweaveLocalBalance, ArweaveLocalError, ArweaveLocalHelper, type ArweaveLocalHelperConfig, type ArweaveLocalInfo, ArweaveLocalStorageAdapter, ArweavePaymentAdapter, ArweaveStorageAdapter, type BoundedTextReadOptions, CHUNK_SIZE, type ChunkEntry, type ChunkManifest, CoreErrorCode, type CostEstimate, CryptoErrorCode, type CryptoScheme, DStorage, type DStorageConfig, DStorageError, type EncryptionAdapter, EncryptionErrorCode, type EncryptionScheme, type FromKdfParamsConfig, HttpGatewayChainAdapter, type HttpGatewayChainAdapterConfig, KDF_PRESETS, type KdfPreset, KeyDeriver, type KeyEnvelope, type KeyWrapper, KeypairEncryptionAdapter, type ListReferencesOptions, type Logger, MANIFEST_AAD, METADATA_AAD, METADATA_ONLY_OWNER_SECRET_SALT, type MLKemVariant, ManagedPaymentAdapter, MidnightChainAdapter, type MidnightChainAdapterConfig, MidnightSimulatorChainAdapter, MnemonicEncryptionAdapter, NETWORKS, PAYLOAD_AAD, PasswordEncryptionAdapter, type PasswordEncryptionAdapterConfig, type RegisterReferenceOptions, type RegisterReferenceResult, type RetrieveResult, type StoreOptions, StorePartialError, type StoreProgress, type StoreRecovery, type StoreResult, type StoredKdfParams, type UpdateResult, type WalletAddresses, type WalletInfo, type WrappedDekResult, type XChaChaPayload, XChaChaScheme, arlocalGateway, base64urlToBytes, buildKeyEnvelope, bytesToBase64url, chunkAad, computeBlake3, computeBlake3Hex, decryptStorageIdXChaCha, decryptXChaCha, deriveKek, deriveOwnerSecret, deriveSymmetricKeyFromSeed, deserializeXChaChaPayload, encryptStorageIdXChaCha, encryptXChaCha, findWrapper, generateDek, generatePqsPassword, hexToBytes, isDStorageError, isManifest, isStorePartialError, mlkemGenerateKeypair, mlkemGenerateKeypairFromSeed, mlkemUnwrapDek, mlkemWrapDek, parseKeyEnvelope, readResponseTextWithLimit, serializeKeyEnvelope, serializeXChaChaPayload, unwrapKey, waitForFacadeSync, wrapKey };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { PaymentAdapter, PaymentNetworkName, TokenSymbol, NetworkType, PaymentAdapterLogger, PaymentQuote, PaymentInstruction, PaymentReceipt, MidnightWalletProvider, StorageAdapterLogger, StorageAdapter, StorageProviderName, StorageUploadResult, StorageQuote, ChainAdapter, ChainProviderName, ChainAdapterLogger, ChainReference, ChainWriteResult, ChainReferenceUpdate, DataReferenceSummary, ChainQuote, WalletBalances } from './types.js';
1
+ import { PaymentAdapter, PaymentNetworkName, TokenSymbol, NetworkType, PaymentAdapterLogger, PaymentQuote, PaymentInstruction, PaymentReceipt, MidnightWalletProvider, StorageAdapterLogger, StorageAdapter, StorageProviderName, StorageUploadResult, RetrieveOptions, StorageQuote, ChainAdapter, ChainProviderName, ChainAdapterLogger, ChainReference, ChainWriteResult, ChainReferenceUpdate, DataReferenceSummary, ChainQuote, WalletBalances } from './types.js';
2
2
  export { ChainAdapter, ChainAdapterLogger, ChainProviderName, ChainQuote, ChainReference, ChainReferenceUpdate, ChainWriteResult, DataReferenceSummary, MidnightWalletProvider, NetworkType, PaymentAdapter, PaymentAdapterLogger, PaymentNetworkName, PaymentQuote, PaymentReceipt, StorageAdapter, StorageAdapterLogger, StorageProviderName, StorageQuote, StorageUploadResult, TOKENS, Token, TokenSymbol, WalletBalances } from './types.js';
3
3
  import Arweave from 'arweave';
4
4
  import Transaction from 'arweave/node/lib/transaction';
@@ -346,6 +346,12 @@ declare class ManagedPaymentAdapter extends ArweavePaymentAdapter {
346
346
  *
347
347
  * • storageId (txId) is PUBLIC on Arweave. Data security relies entirely on
348
348
  * the XChaCha20-Poly1305 encryption applied by @dstorage/crypto before reaching here.
349
+ *
350
+ * • retrieve()'s content-hash check only defends against a malicious gateway when
351
+ * called with an `expectedContentHash` anchor sourced independently of this
352
+ * gateway (see skipIntegrityCheck below) — @dstorage/core supplies this
353
+ * automatically from the on-chain reference. Without an anchor, the check falls
354
+ * back to a gateway-supplied tag and only catches non-adversarial corruption.
349
355
  */
350
356
 
351
357
  interface ArweaveGatewayConfig {
@@ -413,9 +419,17 @@ interface ArweaveAdapterConfig {
413
419
  confirmationTimeoutMs?: number;
414
420
  /**
415
421
  * When true, skip the BLAKE3 content-hash check on retrieve.
416
- * By default (false) the adapter fetches the transaction metadata and verifies
417
- * that the `X-Content-Hash` tag recorded at upload time matches the retrieved
418
- * bytes. Set to true only if you trust the gateway entirely or are using an
422
+ * By default (false) the adapter verifies retrieved bytes against a content hash.
423
+ * The strength of that guarantee depends on the hash's source:
424
+ * - When retrieve() is called with `options.expectedContentHash` (as
425
+ * `@dstorage/core` does automatically, from the on-chain ChainReference),
426
+ * verification is anchored to that chain-committed value and holds even
427
+ * against a fully malicious/colluding gateway.
428
+ * - Without an anchor, the adapter falls back to the `X-Content-Hash` tag
429
+ * fetched from this same gateway — that only catches non-adversarial
430
+ * corruption in transit, since a malicious gateway controls both the tag
431
+ * and the bytes and can make them consistent with each other.
432
+ * Set to true only if you trust the gateway entirely or are using an
419
433
  * Arweave node that does not expose the transaction metadata endpoint.
420
434
  */
421
435
  skipIntegrityCheck?: boolean;
@@ -450,7 +464,7 @@ declare class ArweaveStorageAdapter implements StorageAdapter {
450
464
  constructor(config?: ArweaveAdapterConfig);
451
465
  private getClient;
452
466
  store(data: Uint8Array, metadata?: Record<string, string>): Promise<StorageUploadResult>;
453
- retrieve(id: string): Promise<{
467
+ retrieve(id: string, options?: RetrieveOptions): Promise<{
454
468
  bytes: Uint8Array;
455
469
  tags: Record<string, string>;
456
470
  }>;
@@ -489,6 +503,11 @@ declare class ArweaveStorageAdapter implements StorageAdapter {
489
503
  *
490
504
  * ── Retrieve flow ─────────────────────────────────────────────────────────────
491
505
  * Standard Arweave gateway fetch (identical to ArweaveStorageAdapter.retrieve).
506
+ * Its content-hash check only defends against a malicious gateway when called
507
+ * with an `expectedContentHash` anchor sourced independently of this gateway
508
+ * (see skipIntegrityCheck below) — @dstorage/core supplies this automatically
509
+ * from the on-chain reference. Without an anchor, the check falls back to a
510
+ * gateway-supplied tag and only catches non-adversarial corruption.
492
511
  *
493
512
  * ── Peer dependency ───────────────────────────────────────────────────────────
494
513
  * No extra install needed — @dha-team/arbundles ships as a dependency of @ardrive/turbo-sdk.
@@ -541,10 +560,32 @@ interface ArweaveBundlerAdapterConfig {
541
560
  maxRetrieveSizeBytes?: number;
542
561
  /**
543
562
  * Skip BLAKE3 content-hash verification on retrieve.
563
+ * By default (false) the adapter verifies retrieved bytes against a content hash.
564
+ * The strength of that guarantee depends on the hash's source:
565
+ * - When retrieve() is called with `options.expectedContentHash` (as
566
+ * `@dstorage/core` does automatically, from the on-chain ChainReference),
567
+ * verification is anchored to that chain-committed value and holds even
568
+ * against a fully malicious/colluding gateway.
569
+ * - Without an anchor, the adapter falls back to the `X-Content-Hash` tag
570
+ * fetched from this same gateway — that only catches non-adversarial
571
+ * corruption in transit, since a malicious gateway controls both the tag
572
+ * and the bytes and can make them consistent with each other.
544
573
  * Only set to true when connecting to a fully trusted gateway.
545
- * Defaults to false.
546
574
  */
547
575
  skipIntegrityCheck?: boolean;
576
+ /**
577
+ * Maximum time in milliseconds to wait for any single retrieve() request
578
+ * (metadata or data fetch) before aborting. Defaults to 30_000 ms (30 s).
579
+ * Pass `0` to disable the timeout entirely (not recommended for production).
580
+ */
581
+ requestTimeoutMs?: number;
582
+ /**
583
+ * Maximum number of bytes allowed in the transaction metadata/tags JSON
584
+ * response fetched during retrieve(). Guards against a hostile or
585
+ * misbehaving gateway returning an oversized body to exhaust memory.
586
+ * Defaults to 1_048_576 (1 MiB) — metadata/tags are always tiny in practice.
587
+ */
588
+ maxMetadataResponseBytes?: number;
548
589
  /**
549
590
  * Optional logger for SDK operational output.
550
591
  */
@@ -573,12 +614,16 @@ declare class ArweaveBundlerStorageAdapter implements StorageAdapter {
573
614
  private readonly gateway;
574
615
  private readonly maxRetrieveSizeBytes;
575
616
  private readonly skipIntegrityCheck;
617
+ private readonly requestTimeoutMs;
618
+ private readonly maxMetadataResponseBytes;
576
619
  protected readonly logger: StorageAdapterLogger | undefined;
577
620
  /** RSA-4096 public key modulus (512 bytes) parsed from the auth token at construction time. */
578
621
  private readonly ownerPublicKey;
579
622
  constructor(config?: ArweaveBundlerAdapterConfig);
580
623
  store(data: Uint8Array, metadata?: Record<string, string>): Promise<StorageUploadResult>;
581
- retrieve(id: string): Promise<{
624
+ /** Adds an AbortSignal.timeout() to a fetch init object (when requestTimeoutMs > 0). */
625
+ private _withTimeout;
626
+ retrieve(id: string, options?: RetrieveOptions): Promise<{
582
627
  bytes: Uint8Array;
583
628
  tags: Record<string, string>;
584
629
  }>;
@@ -1335,6 +1380,34 @@ declare function computeBlake3(bytes: Uint8Array): Promise<Uint8Array>;
1335
1380
  /** BLAKE3 hash of `bytes`, returned as a 64-character lowercase hex string. */
1336
1381
  declare function computeBlake3Hex(bytes: Uint8Array): Promise<string>;
1337
1382
 
1383
+ /**
1384
+ * @dstorage/crypto — boundedFetch.ts
1385
+ * Shared helper for reading a fetch Response body with a hard size cap —
1386
+ * used by chain/storage HTTP adapters to avoid a hostile or misbehaving
1387
+ * gateway exhausting memory with an oversized response.
1388
+ */
1389
+ interface BoundedTextReadOptions {
1390
+ /** Maximum number of bytes/characters allowed in the response body. */
1391
+ maxBytes: number;
1392
+ /** Error code to throw (caller-owned, package-specific) when the cap is exceeded. */
1393
+ code: number;
1394
+ /** Prefix identifying the caller/operation in the thrown error message. */
1395
+ component: string;
1396
+ }
1397
+ /**
1398
+ * Reads a fetch Response body as text, aborting once the accumulated size
1399
+ * exceeds `maxBytes`.
1400
+ *
1401
+ * Uses a streaming reader when the Response exposes `.body` (always true for
1402
+ * real `fetch()` responses), so a gateway that omits or lies about
1403
+ * `Content-Length` (e.g. chunked transfer encoding) can't force an unbounded
1404
+ * read — the read is aborted as soon as the limit is crossed, before the
1405
+ * full body is buffered. Falls back to a single `.text()` read + post-hoc
1406
+ * length check only when `.body` is unavailable (e.g. non-streaming
1407
+ * environments or simple test doubles).
1408
+ */
1409
+ declare function readResponseTextWithLimit(res: Response, opts: BoundedTextReadOptions): Promise<string>;
1410
+
1338
1411
  /**
1339
1412
  * @dstorage/chain — adapters/midnightSimulator.ts
1340
1413
  *
@@ -1418,6 +1491,19 @@ interface HttpGatewayChainAdapterConfig {
1418
1491
  */
1419
1492
  customFetch?: typeof fetch;
1420
1493
  logger?: ChainAdapterLogger;
1494
+ /**
1495
+ * Maximum time in milliseconds to wait for any single request before aborting.
1496
+ * Defaults to 30_000 ms (30 s). Pass `0` to disable the timeout entirely
1497
+ * (not recommended for production).
1498
+ */
1499
+ requestTimeoutMs?: number;
1500
+ /**
1501
+ * Maximum number of bytes allowed in a `readReference`/`listReferences`
1502
+ * JSON response body. Guards against a hostile or misbehaving gateway
1503
+ * returning an oversized body to exhaust memory. Defaults to 10_485_760
1504
+ * (10 MiB) — generous for reference/list JSON payloads.
1505
+ */
1506
+ maxResponseBytes?: number;
1421
1507
  }
1422
1508
  declare class HttpGatewayChainAdapter implements ChainAdapter {
1423
1509
  readonly name: ChainProviderName;
@@ -1429,7 +1515,11 @@ declare class HttpGatewayChainAdapter implements ChainAdapter {
1429
1515
  private readonly readUrl;
1430
1516
  private readonly listUrl;
1431
1517
  private readonly deleteUrl;
1518
+ private readonly requestTimeoutMs;
1519
+ private readonly maxResponseBytes;
1432
1520
  constructor(config: HttpGatewayChainAdapterConfig);
1521
+ /** Adds an AbortSignal.timeout() to a fetch init object (when requestTimeoutMs > 0). */
1522
+ private _withTimeout;
1433
1523
  writeReference(ref: ChainReference): Promise<ChainWriteResult>;
1434
1524
  updateReference(refId: string, update: ChainReferenceUpdate, _ownerSecret?: Uint8Array, _newOwnerSecret?: Uint8Array): Promise<void>;
1435
1525
  readReference(refId: string): Promise<ChainReference>;
@@ -1769,6 +1859,8 @@ declare const EncryptionErrorCode: {
1769
1859
  readonly PASSWORD_SEQUENTIAL_RUN: 13008;
1770
1860
  readonly PASSWORD_KEYBOARD_WALK: 13009;
1771
1861
  readonly PASSWORD_ENTROPY_TOO_LOW: 13010;
1862
+ readonly PASSWORD_SCRYPT_N_TOO_LOW: 13011;
1863
+ readonly PASSWORD_SCRYPT_N_NOT_POWER_OF_TWO: 13012;
1772
1864
  };
1773
1865
  type EncryptionErrorCode = (typeof EncryptionErrorCode)[keyof typeof EncryptionErrorCode];
1774
1866
 
@@ -1997,6 +2089,12 @@ interface PasswordEncryptionAdapterConfig {
1997
2089
  /**
1998
2090
  * Custom scrypt parameters. Only used when `preset` is not provided.
1999
2091
  * Prefer `preset` for well-known configurations.
2092
+ *
2093
+ * `N` is rejected if it is below 32768 (OWASP 2024 minimum, 32 MB
2094
+ * memory-hard) or is not a power of two — this floor also applies when
2095
+ * reconstructing via `fromKdfParams()`, since a downgraded or corrupted
2096
+ * stored value could otherwise collapse the KDF to something trivially
2097
+ * brute-forceable.
2000
2098
  */
2001
2099
  params?: {
2002
2100
  N?: number;
@@ -2628,6 +2726,7 @@ declare const CoreErrorCode: {
2628
2726
  readonly STORAGE_ADAPTER_MISMATCH: 10052;
2629
2727
  readonly RETRIEVE_BY_REF_ID_ENVELOPE_EMPTY: 10053;
2630
2728
  readonly CONTENT_HASH_MISMATCH: 10054;
2729
+ readonly METADATA_PARSE_FAILED: 10055;
2631
2730
  readonly LIST_REFS_REQUIRES_CHAIN: 10060;
2632
2731
  readonly LIST_REFS_NOT_SUPPORTED: 10061;
2633
2732
  readonly REMOVE_REF_REQUIRES_CHAIN: 10070;
@@ -2638,6 +2737,7 @@ declare const CoreErrorCode: {
2638
2737
  readonly DECRYPT_CHUNK_FAILED: 10093;
2639
2738
  readonly CHUNK_OVERFLOWS_TOTAL_SIZE: 10094;
2640
2739
  readonly REASSEMBLY_SIZE_MISMATCH: 10095;
2740
+ readonly MANIFEST_PARSE_FAILED: 10096;
2641
2741
  readonly NOT_INITIALIZED: 10100;
2642
2742
  readonly UNKNOWN_ERROR: 10999;
2643
2743
  };
@@ -2653,4 +2753,4 @@ declare class StorePartialError extends DStorageError {
2653
2753
  }
2654
2754
  declare function isStorePartialError(err: unknown): err is StorePartialError;
2655
2755
 
2656
- export { ARWEAVE_LOCAL, type AdapterWalletProvider, type ArweaveBundlerAdapterConfig, ArweaveBundlerStorageAdapter, type ArweaveLocalAdapterConfig, type ArweaveLocalBalance, ArweaveLocalError, ArweaveLocalHelper, type ArweaveLocalHelperConfig, type ArweaveLocalInfo, ArweaveLocalStorageAdapter, ArweavePaymentAdapter, ArweaveStorageAdapter, CHUNK_SIZE, type ChunkEntry, type ChunkManifest, CoreErrorCode, type CostEstimate, CryptoErrorCode, type CryptoScheme, DStorage, type DStorageConfig, DStorageError, type EncryptionAdapter, EncryptionErrorCode, type EncryptionScheme, type FromKdfParamsConfig, HttpGatewayChainAdapter, type HttpGatewayChainAdapterConfig, KDF_PRESETS, type KdfPreset, KeyDeriver, type KeyEnvelope, type KeyWrapper, KeypairEncryptionAdapter, type ListReferencesOptions, type Logger, MANIFEST_AAD, METADATA_AAD, METADATA_ONLY_OWNER_SECRET_SALT, type MLKemVariant, ManagedPaymentAdapter, MidnightChainAdapter, type MidnightChainAdapterConfig, MidnightSimulatorChainAdapter, MnemonicEncryptionAdapter, NETWORKS, PAYLOAD_AAD, PasswordEncryptionAdapter, type PasswordEncryptionAdapterConfig, type RegisterReferenceOptions, type RegisterReferenceResult, type RetrieveResult, type StoreOptions, StorePartialError, type StoreProgress, type StoreRecovery, type StoreResult, type StoredKdfParams, type UpdateResult, type WalletAddresses, type WalletInfo, type WrappedDekResult, type XChaChaPayload, XChaChaScheme, arlocalGateway, base64urlToBytes, buildKeyEnvelope, bytesToBase64url, chunkAad, computeBlake3, computeBlake3Hex, decryptStorageIdXChaCha, decryptXChaCha, deriveKek, deriveOwnerSecret, deriveSymmetricKeyFromSeed, deserializeXChaChaPayload, encryptStorageIdXChaCha, encryptXChaCha, findWrapper, generateDek, generatePqsPassword, hexToBytes, isDStorageError, isManifest, isStorePartialError, mlkemGenerateKeypair, mlkemGenerateKeypairFromSeed, mlkemUnwrapDek, mlkemWrapDek, parseKeyEnvelope, serializeKeyEnvelope, serializeXChaChaPayload, unwrapKey, waitForFacadeSync, wrapKey };
2756
+ export { ARWEAVE_LOCAL, type AdapterWalletProvider, type ArweaveBundlerAdapterConfig, ArweaveBundlerStorageAdapter, type ArweaveLocalAdapterConfig, type ArweaveLocalBalance, ArweaveLocalError, ArweaveLocalHelper, type ArweaveLocalHelperConfig, type ArweaveLocalInfo, ArweaveLocalStorageAdapter, ArweavePaymentAdapter, ArweaveStorageAdapter, type BoundedTextReadOptions, CHUNK_SIZE, type ChunkEntry, type ChunkManifest, CoreErrorCode, type CostEstimate, CryptoErrorCode, type CryptoScheme, DStorage, type DStorageConfig, DStorageError, type EncryptionAdapter, EncryptionErrorCode, type EncryptionScheme, type FromKdfParamsConfig, HttpGatewayChainAdapter, type HttpGatewayChainAdapterConfig, KDF_PRESETS, type KdfPreset, KeyDeriver, type KeyEnvelope, type KeyWrapper, KeypairEncryptionAdapter, type ListReferencesOptions, type Logger, MANIFEST_AAD, METADATA_AAD, METADATA_ONLY_OWNER_SECRET_SALT, type MLKemVariant, ManagedPaymentAdapter, MidnightChainAdapter, type MidnightChainAdapterConfig, MidnightSimulatorChainAdapter, MnemonicEncryptionAdapter, NETWORKS, PAYLOAD_AAD, PasswordEncryptionAdapter, type PasswordEncryptionAdapterConfig, type RegisterReferenceOptions, type RegisterReferenceResult, type RetrieveResult, type StoreOptions, StorePartialError, type StoreProgress, type StoreRecovery, type StoreResult, type StoredKdfParams, type UpdateResult, type WalletAddresses, type WalletInfo, type WrappedDekResult, type XChaChaPayload, XChaChaScheme, arlocalGateway, base64urlToBytes, buildKeyEnvelope, bytesToBase64url, chunkAad, computeBlake3, computeBlake3Hex, decryptStorageIdXChaCha, decryptXChaCha, deriveKek, deriveOwnerSecret, deriveSymmetricKeyFromSeed, deserializeXChaChaPayload, encryptStorageIdXChaCha, encryptXChaCha, findWrapper, generateDek, generatePqsPassword, hexToBytes, isDStorageError, isManifest, isStorePartialError, mlkemGenerateKeypair, mlkemGenerateKeypairFromSeed, mlkemUnwrapDek, mlkemWrapDek, parseKeyEnvelope, readResponseTextWithLimit, serializeKeyEnvelope, serializeXChaChaPayload, unwrapKey, waitForFacadeSync, wrapKey };