@provablehq/sdk 0.11.7 → 0.11.9

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.
@@ -58,6 +58,7 @@ import { BaseFunctionKeyLocator, InvalidLocatorError, InvalidLocatorReason, KeyL
58
58
  import { OfflineKeyProvider, OfflineSearchParams } from "./keys/provider/offline.js";
59
59
  import { BlockHeightSearch, NetworkRecordProvider, RecordProvider } from "./record-provider.js";
60
60
  import { RecordScanner, RecordScannerJWTData, RecordScannerOptions } from "./record-scanner.js";
61
+ import { ApiAuth, ApiAuthConfig, DEFAULT_API_KEY_HEADER, normalizeAuthConfig } from "./api-auth.js";
61
62
  import { SealanceMerkleTree } from "./integrations/sealance/merkle-tree.js";
62
63
  import { generateHookData } from "./integrations/circle/hook-data.js";
63
64
  declare function initializeWasm(): Promise<void>;
@@ -68,7 +69,7 @@ export type { LogLevel } from "./utils/logger.js";
68
69
  export { Address, Authorization, Boolean, BHP256, BHP512, BHP768, BHP1024, Ciphertext, ComputeKey, DynamicRecord, Execution as FunctionExecution, ExecutionRequest, ExecutionResponse, EncryptionToolkit, Field, GraphKey, Group, I8, I16, I32, I64, I128, OfflineQuery, QueryOption, Pedersen64, Pedersen128, Plaintext, Poseidon2, Poseidon4, Poseidon8, PrivateKey, PrivateKeyCiphertext, Program, ProgramImportsBuilder, ProgramManager as ProgramManagerBase, Proof, ProvingKey, ProvingRequest, RecordCiphertext, RecordPlaintext, Signature, Scalar, stringToField, Transaction, Transition, U8, U16, U32, U64, U128, Value, VerifyingKey, ViewKey, getMaxProgramImports, initThreadPool, getOrInitConsensusVersionTestHeights, setWasmLogLevel, snarkVerify, snarkVerifyBatch, verifyFunctionExecution, } from "./wasm.js";
69
70
  export { initializeWasm };
70
71
  export { Key, CREDITS_PROGRAM_KEYS, KEY_STORE, PRIVATE_TRANSFER, PRIVATE_TO_PUBLIC_TRANSFER, PRIVATE_TRANSFER_TYPES, PUBLIC_TRANSFER, PUBLIC_TRANSFER_AS_SIGNER, PUBLIC_TO_PRIVATE_TRANSFER, RECORD_DOMAIN, VALID_TRANSFER_TYPES, } from "./constants.js";
71
- export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoKeyProviderInitParams, AleoNetworkClient, BlockJSON, BlockHeightSearch, BroadcastResponse, BroadcastResult, CachedKeyPair, ConfirmedTransactionJSON, CryptoBoxPubKey, DecryptionNotEnabledError, DeploymentJSON, DeploymentObject, EncryptedProvingRequest, EncryptedRecord, EncryptedRegistrationRequest, EncryptedRecordsResult, EncryptedRecordsSuccess, ExecutionJSON, ExecutionObject, FeeExecutionJSON, FeeExecutionObject, FinalizeJSON, FunctionInput, FunctionObject, FunctionKeyPair, FunctionKeyProvider, generateHookData, Header, isProvingResponse, isProveApiErrorBody, ImportedPrograms, ImportedVerifyingKeys, IndexedDBKeyStore, InputJSON, InputObject, InvalidLocatorError, InvalidLocatorReason, BaseFunctionKeyLocator, KeyFingerprint, KeyLocator, KeyMetadata, KeySearchParams, KeyStore, KeyType, KeyVerificationError, ProvingKeyLocator, provingKeyLocator, TranslationKeyLocator, translationKeyLocator, VerifyingKeyLocator, verifyingKeyLocator, KeyVerifier, MemKeyVerifier, Metadata, NetworkRecordProvider, OfflineKeyProvider, OfflineSearchParams, OutputJSON, OutputObject, OwnedFilter, OwnedRecord, OwnedRecordsResult, OwnedRecordsResponseFilter, OwnedRecordsSuccess, OwnerJSON, PartialSolutionJSON, PlaintextArray, PlaintextLiteral, PlaintextObject, PlaintextStruct, ProgramImports, ProveApiErrorBody, ProvingFailure, ProvingRequestError, ProvingRequestJSON, ProvingResult, ProvingSuccess, ProvingResponse, RatificationJSON, RecordsFilter, RecordsResponseFilter, RecordProvider, RecordScanner, RecordScannerErrorBody, RecordScannerFailure, RecordScannerJWTData, RecordScannerOptions, RecordNotFoundError, RecordScannerRequestError, ViewKeyNotStoredError, RecordSearchParams, RegisterResult, RegisterSuccess, RegistrationResponse, RevokeResult, RevokeSuccess, RevokeResponse, SealanceMerkleTree, SerialNumbersResult, SerialNumbersSuccess, sha256Hex, SolutionJSON, SolutionsJSON, StatusResponse, StatusResult, StatusSuccess, TagsResult, TagsSuccess, TransactionJSON, TransactionObject, TransitionJSON, TransitionObject, UUIDError, VerifyingKeys, };
72
+ export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoKeyProviderInitParams, AleoNetworkClient, BlockJSON, BlockHeightSearch, BroadcastResponse, BroadcastResult, CachedKeyPair, ConfirmedTransactionJSON, CryptoBoxPubKey, DecryptionNotEnabledError, DeploymentJSON, DeploymentObject, EncryptedProvingRequest, EncryptedRecord, EncryptedRegistrationRequest, EncryptedRecordsResult, EncryptedRecordsSuccess, ExecutionJSON, ExecutionObject, FeeExecutionJSON, FeeExecutionObject, FinalizeJSON, FunctionInput, FunctionObject, FunctionKeyPair, FunctionKeyProvider, generateHookData, Header, isProvingResponse, isProveApiErrorBody, ImportedPrograms, ImportedVerifyingKeys, IndexedDBKeyStore, InputJSON, InputObject, InvalidLocatorError, InvalidLocatorReason, BaseFunctionKeyLocator, KeyFingerprint, KeyLocator, KeyMetadata, KeySearchParams, KeyStore, KeyType, KeyVerificationError, ProvingKeyLocator, provingKeyLocator, TranslationKeyLocator, translationKeyLocator, VerifyingKeyLocator, verifyingKeyLocator, KeyVerifier, MemKeyVerifier, Metadata, NetworkRecordProvider, OfflineKeyProvider, OfflineSearchParams, OutputJSON, OutputObject, OwnedFilter, OwnedRecord, OwnedRecordsResult, OwnedRecordsResponseFilter, OwnedRecordsSuccess, OwnerJSON, PartialSolutionJSON, PlaintextArray, PlaintextLiteral, PlaintextObject, PlaintextStruct, ProgramImports, ProveApiErrorBody, ProvingFailure, ProvingRequestError, ProvingRequestJSON, ProvingResult, ProvingSuccess, ProvingResponse, ApiAuth, ApiAuthConfig, DEFAULT_API_KEY_HEADER, normalizeAuthConfig, RatificationJSON, RecordsFilter, RecordsResponseFilter, RecordProvider, RecordScanner, RecordScannerErrorBody, RecordScannerFailure, RecordScannerJWTData, RecordScannerOptions, RecordNotFoundError, RecordScannerRequestError, ViewKeyNotStoredError, RecordSearchParams, RegisterResult, RegisterSuccess, RegistrationResponse, RevokeResult, RevokeSuccess, RevokeResponse, SealanceMerkleTree, SerialNumbersResult, SerialNumbersSuccess, sha256Hex, SolutionJSON, SolutionsJSON, StatusResponse, StatusResult, StatusSuccess, TagsResult, TagsSuccess, TransactionJSON, TransactionObject, TransitionJSON, TransitionObject, UUIDError, VerifyingKeys, };
72
73
  export { KeyVerificationError as ChecksumMismatchError, KeyVerifier as FunctionKeyVerifier, } from "./keys/verifier/interface.js";
73
74
  export { encryptAuthorization, encryptProvingRequest, encryptSerializedProvingRequest, encryptViewKey, encryptRegistrationRequest, serializeProvingRequest, zeroizeBytes, } from "./security.js";
74
75
  export { toField, toGroup, toViewKey, toSignature, toAddress, isViewKeyStrategy, isInputIdStrategy, isRecordViewKeyStrategy, buildExecutionRequestFromExternallySignedData, computeExternalSigningInputs, } from "./external-signing.js";
@@ -58,6 +58,7 @@ import { BaseFunctionKeyLocator, InvalidLocatorError, InvalidLocatorReason, KeyL
58
58
  import { OfflineKeyProvider, OfflineSearchParams } from "./keys/provider/offline.js";
59
59
  import { BlockHeightSearch, NetworkRecordProvider, RecordProvider } from "./record-provider.js";
60
60
  import { RecordScanner, RecordScannerJWTData, RecordScannerOptions } from "./record-scanner.js";
61
+ import { ApiAuth, ApiAuthConfig, DEFAULT_API_KEY_HEADER, normalizeAuthConfig } from "./api-auth.js";
61
62
  import { SealanceMerkleTree } from "./integrations/sealance/merkle-tree.js";
62
63
  import { generateHookData } from "./integrations/circle/hook-data.js";
63
64
  declare function initializeWasm(): Promise<void>;
@@ -68,7 +69,7 @@ export type { LogLevel } from "./utils/logger.js";
68
69
  export { Address, Authorization, Boolean, BHP256, BHP512, BHP768, BHP1024, Ciphertext, ComputeKey, DynamicRecord, Execution as FunctionExecution, ExecutionRequest, ExecutionResponse, EncryptionToolkit, Field, GraphKey, Group, I8, I16, I32, I64, I128, OfflineQuery, QueryOption, Pedersen64, Pedersen128, Plaintext, Poseidon2, Poseidon4, Poseidon8, PrivateKey, PrivateKeyCiphertext, Program, ProgramImportsBuilder, ProgramManager as ProgramManagerBase, Proof, ProvingKey, ProvingRequest, RecordCiphertext, RecordPlaintext, Signature, Scalar, stringToField, Transaction, Transition, U8, U16, U32, U64, U128, Value, VerifyingKey, ViewKey, getMaxProgramImports, initThreadPool, getOrInitConsensusVersionTestHeights, setWasmLogLevel, snarkVerify, snarkVerifyBatch, verifyFunctionExecution, } from "./wasm.js";
69
70
  export { initializeWasm };
70
71
  export { Key, CREDITS_PROGRAM_KEYS, KEY_STORE, PRIVATE_TRANSFER, PRIVATE_TO_PUBLIC_TRANSFER, PRIVATE_TRANSFER_TYPES, PUBLIC_TRANSFER, PUBLIC_TRANSFER_AS_SIGNER, PUBLIC_TO_PRIVATE_TRANSFER, RECORD_DOMAIN, VALID_TRANSFER_TYPES, } from "./constants.js";
71
- export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoKeyProviderInitParams, AleoNetworkClient, BlockJSON, BlockHeightSearch, BroadcastResponse, BroadcastResult, CachedKeyPair, ConfirmedTransactionJSON, CryptoBoxPubKey, DecryptionNotEnabledError, DeploymentJSON, DeploymentObject, EncryptedProvingRequest, EncryptedRecord, EncryptedRegistrationRequest, EncryptedRecordsResult, EncryptedRecordsSuccess, ExecutionJSON, ExecutionObject, FeeExecutionJSON, FeeExecutionObject, FinalizeJSON, FunctionInput, FunctionObject, FunctionKeyPair, FunctionKeyProvider, generateHookData, Header, isProvingResponse, isProveApiErrorBody, ImportedPrograms, ImportedVerifyingKeys, IndexedDBKeyStore, InputJSON, InputObject, InvalidLocatorError, InvalidLocatorReason, BaseFunctionKeyLocator, KeyFingerprint, KeyLocator, KeyMetadata, KeySearchParams, KeyStore, KeyType, KeyVerificationError, ProvingKeyLocator, provingKeyLocator, TranslationKeyLocator, translationKeyLocator, VerifyingKeyLocator, verifyingKeyLocator, KeyVerifier, MemKeyVerifier, Metadata, NetworkRecordProvider, OfflineKeyProvider, OfflineSearchParams, OutputJSON, OutputObject, OwnedFilter, OwnedRecord, OwnedRecordsResult, OwnedRecordsResponseFilter, OwnedRecordsSuccess, OwnerJSON, PartialSolutionJSON, PlaintextArray, PlaintextLiteral, PlaintextObject, PlaintextStruct, ProgramImports, ProveApiErrorBody, ProvingFailure, ProvingRequestError, ProvingRequestJSON, ProvingResult, ProvingSuccess, ProvingResponse, RatificationJSON, RecordsFilter, RecordsResponseFilter, RecordProvider, RecordScanner, RecordScannerErrorBody, RecordScannerFailure, RecordScannerJWTData, RecordScannerOptions, RecordNotFoundError, RecordScannerRequestError, ViewKeyNotStoredError, RecordSearchParams, RegisterResult, RegisterSuccess, RegistrationResponse, RevokeResult, RevokeSuccess, RevokeResponse, SealanceMerkleTree, SerialNumbersResult, SerialNumbersSuccess, sha256Hex, SolutionJSON, SolutionsJSON, StatusResponse, StatusResult, StatusSuccess, TagsResult, TagsSuccess, TransactionJSON, TransactionObject, TransitionJSON, TransitionObject, UUIDError, VerifyingKeys, };
72
+ export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoKeyProviderInitParams, AleoNetworkClient, BlockJSON, BlockHeightSearch, BroadcastResponse, BroadcastResult, CachedKeyPair, ConfirmedTransactionJSON, CryptoBoxPubKey, DecryptionNotEnabledError, DeploymentJSON, DeploymentObject, EncryptedProvingRequest, EncryptedRecord, EncryptedRegistrationRequest, EncryptedRecordsResult, EncryptedRecordsSuccess, ExecutionJSON, ExecutionObject, FeeExecutionJSON, FeeExecutionObject, FinalizeJSON, FunctionInput, FunctionObject, FunctionKeyPair, FunctionKeyProvider, generateHookData, Header, isProvingResponse, isProveApiErrorBody, ImportedPrograms, ImportedVerifyingKeys, IndexedDBKeyStore, InputJSON, InputObject, InvalidLocatorError, InvalidLocatorReason, BaseFunctionKeyLocator, KeyFingerprint, KeyLocator, KeyMetadata, KeySearchParams, KeyStore, KeyType, KeyVerificationError, ProvingKeyLocator, provingKeyLocator, TranslationKeyLocator, translationKeyLocator, VerifyingKeyLocator, verifyingKeyLocator, KeyVerifier, MemKeyVerifier, Metadata, NetworkRecordProvider, OfflineKeyProvider, OfflineSearchParams, OutputJSON, OutputObject, OwnedFilter, OwnedRecord, OwnedRecordsResult, OwnedRecordsResponseFilter, OwnedRecordsSuccess, OwnerJSON, PartialSolutionJSON, PlaintextArray, PlaintextLiteral, PlaintextObject, PlaintextStruct, ProgramImports, ProveApiErrorBody, ProvingFailure, ProvingRequestError, ProvingRequestJSON, ProvingResult, ProvingSuccess, ProvingResponse, ApiAuth, ApiAuthConfig, DEFAULT_API_KEY_HEADER, normalizeAuthConfig, RatificationJSON, RecordsFilter, RecordsResponseFilter, RecordProvider, RecordScanner, RecordScannerErrorBody, RecordScannerFailure, RecordScannerJWTData, RecordScannerOptions, RecordNotFoundError, RecordScannerRequestError, ViewKeyNotStoredError, RecordSearchParams, RegisterResult, RegisterSuccess, RegistrationResponse, RevokeResult, RevokeSuccess, RevokeResponse, SealanceMerkleTree, SerialNumbersResult, SerialNumbersSuccess, sha256Hex, SolutionJSON, SolutionsJSON, StatusResponse, StatusResult, StatusSuccess, TagsResult, TagsSuccess, TransactionJSON, TransactionObject, TransitionJSON, TransitionObject, UUIDError, VerifyingKeys, };
72
73
  export { KeyVerificationError as ChecksumMismatchError, KeyVerifier as FunctionKeyVerifier, } from "./keys/verifier/interface.js";
73
74
  export { encryptAuthorization, encryptProvingRequest, encryptSerializedProvingRequest, encryptViewKey, encryptRegistrationRequest, serializeProvingRequest, zeroizeBytes, } from "./security.js";
74
75
  export { toField, toGroup, toViewKey, toSignature, toAddress, isViewKeyStrategy, isInputIdStrategy, isRecordViewKeyStrategy, buildExecutionRequestFromExternallySignedData, computeExternalSigningInputs, } from "./external-signing.js";
@@ -1435,21 +1435,6 @@ async function retryWithBackoff(fn, { maxAttempts = 5, baseDelay = 100, jitter,
1435
1435
  throw new Error("retryWithBackoff: unreachable");
1436
1436
  }
1437
1437
 
1438
- /** Type guard: value is a ProvingResponse. */
1439
- function isProvingResponse(value) {
1440
- return (typeof value === "object" &&
1441
- value !== null &&
1442
- "transaction" in value &&
1443
- "broadcast_result" in value &&
1444
- typeof value.broadcast_result === "object");
1445
- }
1446
- /** Type guard: value is a ProveApiErrorBody. */
1447
- function isProveApiErrorBody(value) {
1448
- return (typeof value === "object" &&
1449
- value !== null &&
1450
- "message" in value);
1451
- }
1452
-
1453
1438
  const KEY_STORE = Metadata.baseUrl();
1454
1439
  function convert(metadata) {
1455
1440
  // This looks up the method name in VerifyingKey
@@ -1550,6 +1535,168 @@ const RECORD_DOMAIN = "RecordScannerV0";
1550
1535
  const ZERO_ADDRESS = "aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc";
1551
1536
  const FIVE_MINUTES = 5 * 60 * 1000; // 5 minutes in milliseconds
1552
1537
 
1538
+ /** Default header carrying a provisioned API key (e.g. edge.provable.com). */
1539
+ const DEFAULT_API_KEY_HEADER = "X-API-Key";
1540
+ /**
1541
+ * Normalize legacy auth options into an explicit {@link ApiAuthConfig}.
1542
+ *
1543
+ * Rules, preserving the pre-mode behavior of both clients:
1544
+ * - An explicit `auth` wins. Combining it with legacy fields throws — the caller's intent
1545
+ * is ambiguous and guessing hides misconfiguration.
1546
+ * - A string `apiKey` (with or without `consumerId`) or a bare `jwtData` selects `jwt` mode.
1547
+ * - An `{ header, value }` apiKey selects `api-key` mode with that header. Combining it with
1548
+ * a `consumerId` throws: keyed auth has no consumer and the pair would silently pick one.
1549
+ * - Nothing configured selects `none`.
1550
+ */
1551
+ function normalizeAuthConfig(options) {
1552
+ if (options.auth) {
1553
+ if (options.apiKey !== undefined || options.consumerId !== undefined || options.jwtData !== undefined) {
1554
+ throw new Error("Pass either `auth` or the legacy apiKey/consumerId/jwtData options, not both");
1555
+ }
1556
+ validateKeyed(options.auth);
1557
+ return options.auth;
1558
+ }
1559
+ if (typeof options.apiKey === "object" && options.apiKey !== null) {
1560
+ if (options.consumerId !== undefined) {
1561
+ throw new Error("A custom-header apiKey cannot be combined with consumerId — keyed auth has no consumer. Use a string apiKey for JWT auth.");
1562
+ }
1563
+ const config = { mode: "api-key", value: options.apiKey.value, header: options.apiKey.header };
1564
+ validateKeyed(config);
1565
+ return config;
1566
+ }
1567
+ if (options.apiKey !== undefined || options.consumerId !== undefined || options.jwtData !== undefined) {
1568
+ return { mode: "jwt", apiKey: options.apiKey, consumerId: options.consumerId, jwtData: options.jwtData };
1569
+ }
1570
+ return { mode: "none" };
1571
+ }
1572
+ /**
1573
+ * Rejects api-key configurations that would emit an empty or nameless header.
1574
+ *
1575
+ * @param config Any auth configuration; only the api-key mode has anything to check.
1576
+ * @throws When the key value is empty, or a custom header name is given but empty.
1577
+ */
1578
+ function validateKeyed(config) {
1579
+ if (config.mode !== "api-key")
1580
+ return;
1581
+ if (!config.value) {
1582
+ throw new Error("api-key auth mode requires a key value. Keys are provisioned, not registered — supply one.");
1583
+ }
1584
+ if (config.header !== undefined && !config.header) {
1585
+ throw new Error("api-key auth header must be a non-empty header name when given.");
1586
+ }
1587
+ }
1588
+ /**
1589
+ * ApiAuth resolves the auth headers each request must carry, owning the JWT mint/refresh
1590
+ * lifecycle in `jwt` mode. Share one instance across clients that use the same credentials so
1591
+ * only one minter exists and concurrent refreshes are deduplicated.
1592
+ */
1593
+ class ApiAuth {
1594
+ config;
1595
+ baseUrl;
1596
+ transport;
1597
+ jwtData;
1598
+ inFlight;
1599
+ warned = false;
1600
+ mintHeaders;
1601
+ /**
1602
+ * @param {ApiAuthConfig} config The auth mode and its material.
1603
+ * @param {string} baseUrl API root origin; `/jwts/{consumerId}` lives here in `jwt` mode.
1604
+ * @param {TransportFunction} transport Transport used for the JWT mint request.
1605
+ * @param {Record<string, string>} [mintHeaders] Extra headers on the mint request (e.g. SDK telemetry).
1606
+ */
1607
+ constructor(config, baseUrl, transport = defaultTransport, mintHeaders = {}) {
1608
+ this.config = config;
1609
+ this.baseUrl = baseUrl;
1610
+ this.transport = transport;
1611
+ this.mintHeaders = mintHeaders;
1612
+ if (config.mode === "jwt")
1613
+ this.jwtData = config.jwtData;
1614
+ }
1615
+ /** The mode this instance authenticates with. */
1616
+ get mode() {
1617
+ return this.config.mode;
1618
+ }
1619
+ /** Replace the stored JWT, e.g. one minted elsewhere. Only meaningful in `jwt` mode. */
1620
+ setJwtData(jwtData) {
1621
+ this.jwtData = jwtData;
1622
+ }
1623
+ /** The stored JWT, when one exists. */
1624
+ getJwtData() {
1625
+ return this.jwtData;
1626
+ }
1627
+ /**
1628
+ * The auth headers a request must carry, refreshing the JWT first when it is stale and a
1629
+ * refresh is possible. Returns an empty object in `none` mode or when `jwt` mode lacks
1630
+ * both a usable token and the material to mint one.
1631
+ */
1632
+ async headers() {
1633
+ if (this.config.mode === "api-key") {
1634
+ return { [this.config.header ?? DEFAULT_API_KEY_HEADER]: this.config.value };
1635
+ }
1636
+ if (this.config.mode === "none") {
1637
+ // A token injected via setJwtData authenticates even without mint
1638
+ // material: an external session owns minting and hands tokens in.
1639
+ return this.jwtData?.jwt ? { Authorization: this.jwtData.jwt } : {};
1640
+ }
1641
+ const stale = !this.jwtData || Date.now() >= this.jwtData.expiration - FIVE_MINUTES;
1642
+ if (stale) {
1643
+ const { apiKey, consumerId } = this.config;
1644
+ if (apiKey && consumerId) {
1645
+ this.inFlight ??= this.refreshJwt(apiKey, consumerId).finally(() => {
1646
+ this.inFlight = undefined;
1647
+ });
1648
+ this.jwtData = await this.inFlight;
1649
+ }
1650
+ else if (!this.jwtData && !this.warned) {
1651
+ this.warned = true;
1652
+ logger.warn("JWT or both apiKey and consumerId are required when using the Provable API");
1653
+ }
1654
+ // A stale JWT that cannot be refreshed is still sent: the server is the
1655
+ // authority on expiry and rejecting locally would break long-lived callers.
1656
+ }
1657
+ return this.jwtData?.jwt ? { Authorization: this.jwtData.jwt } : {};
1658
+ }
1659
+ /**
1660
+ * Refreshes the JWT by making a POST request to /jwts/{consumer_id}.
1661
+ *
1662
+ * @param {string} apiKey The API key to use for the refresh request.
1663
+ * @param {string} consumerId The consumer ID for the JWT endpoint.
1664
+ * @returns {Promise<JWTData>} The new JWT data.
1665
+ */
1666
+ async refreshJwt(apiKey, consumerId) {
1667
+ const response = await post(`${this.baseUrl}/jwts/${consumerId}`, {
1668
+ headers: {
1669
+ ...this.mintHeaders,
1670
+ "X-Provable-API-Key": apiKey,
1671
+ },
1672
+ }, this.transport);
1673
+ const authHeader = response.headers.get("authorization");
1674
+ if (!authHeader) {
1675
+ throw new Error("No authorization header in JWT refresh response");
1676
+ }
1677
+ const body = await response.json();
1678
+ return {
1679
+ jwt: authHeader,
1680
+ expiration: body.exp * 1000, // Convert to milliseconds
1681
+ };
1682
+ }
1683
+ }
1684
+
1685
+ /** Type guard: value is a ProvingResponse. */
1686
+ function isProvingResponse(value) {
1687
+ return (typeof value === "object" &&
1688
+ value !== null &&
1689
+ "transaction" in value &&
1690
+ "broadcast_result" in value &&
1691
+ typeof value.broadcast_result === "object");
1692
+ }
1693
+ /** Type guard: value is a ProveApiErrorBody. */
1694
+ function isProveApiErrorBody(value) {
1695
+ return (typeof value === "object" &&
1696
+ value !== null &&
1697
+ "message" in value);
1698
+ }
1699
+
1553
1700
  const HEADERS = new Set([
1554
1701
  "x-aleo-sdk-version",
1555
1702
  "x-aleo-environment",
@@ -1580,9 +1727,13 @@ class AleoNetworkClient {
1580
1727
  network;
1581
1728
  transport;
1582
1729
  hasCustomTransport;
1730
+ auth;
1583
1731
  apiKey;
1584
1732
  consumerId;
1585
1733
  jwtData;
1734
+ // The consumer the cached jwtData was minted for, so the cache is never
1735
+ // reused for a different identity on a shared client.
1736
+ jwtConsumerId;
1586
1737
  proverUri;
1587
1738
  recordScannerUri;
1588
1739
  constructor(host, options) {
@@ -1602,7 +1753,7 @@ class AleoNetworkClient {
1602
1753
  else {
1603
1754
  this.headers = {
1604
1755
  // This is replaced by the actual version by a Rollup plugin
1605
- "X-Aleo-SDK-Version": "0.11.7",
1756
+ "X-Aleo-SDK-Version": "0.11.9",
1606
1757
  "X-Aleo-environment": environment(),
1607
1758
  };
1608
1759
  }
@@ -1614,11 +1765,17 @@ class AleoNetworkClient {
1614
1765
  if (options.recordScannerUri) {
1615
1766
  this.recordScannerUri = options.recordScannerUri + "/mainnet";
1616
1767
  }
1768
+ // If an explicit auth mode was specified, validate and set it, so a
1769
+ // bad key fails here rather than on the first proving request.
1770
+ if (options.auth) {
1771
+ normalizeAuthConfig({ auth: options.auth });
1772
+ this.auth = options.auth;
1773
+ }
1617
1774
  }
1618
1775
  else {
1619
1776
  this.headers = {
1620
1777
  // This is replaced by the actual version by a Rollup plugin
1621
- "X-Aleo-SDK-Version": "0.11.7",
1778
+ "X-Aleo-SDK-Version": "0.11.9",
1622
1779
  "X-Aleo-environment": environment(),
1623
1780
  };
1624
1781
  }
@@ -3052,33 +3209,6 @@ class AleoNetworkClient {
3052
3209
  throw new Error(`Error posting solution: No response received: ${error.message}`);
3053
3210
  }
3054
3211
  }
3055
- /**
3056
- * Refreshes the JWT by making a POST request to /jwts/{consumer_id}
3057
- *
3058
- * @param {string} apiKey - The API key for authentication.
3059
- * @param {string} consumerId - The consumer ID associated with the API key.
3060
- * @returns {Promise<JwtData>} The JWT token and expiration time
3061
- */
3062
- async refreshJwt(apiKey, consumerId) {
3063
- if (!apiKey || !consumerId) {
3064
- throw new Error('API key and consumer ID are required to refresh JWT');
3065
- }
3066
- const response = await post(`${this.baseUrl}/jwts/${consumerId}`, {
3067
- headers: {
3068
- ...this.method("refreshJwt"),
3069
- 'X-Provable-API-Key': apiKey,
3070
- }
3071
- }, this.transport);
3072
- const authHeader = response.headers.get('authorization');
3073
- if (!authHeader) {
3074
- throw new Error('No authorization header in JWT refresh response');
3075
- }
3076
- const body = await response.json();
3077
- return {
3078
- jwt: authHeader,
3079
- expiration: body.exp * 1000 // Convert to milliseconds
3080
- };
3081
- }
3082
3212
  /**
3083
3213
  * Parses a /prove/authorization or /prove/request response. Returns a result object (never throws for 200/400/500/503).
3084
3214
  */
@@ -3141,31 +3271,40 @@ class AleoNetworkClient {
3141
3271
  async submitProvingRequestSafe(options) {
3142
3272
  // Attempt to get the Prover URI first from the options, then from any configured globally, or third try the main configured host.
3143
3273
  const proverUri = (options.url ?? this.proverUri) ?? this.host;
3144
- // Try to get JWT data to access the Provable API.
3145
- const apiKey = options.apiKey ?? this.apiKey;
3146
- const consumerId = options.consumerId ?? this.consumerId;
3147
- let jwtData = options.jwtData ?? this.jwtData;
3148
- // Check to see if the JWT needs refreshing. Runs before parsing the
3149
- // proving request so JWT refresh errors propagate as they always have.
3150
- const isExpired = jwtData && Date.now() >= jwtData.expiration - FIVE_MINUTES;
3151
- if (!jwtData || isExpired) {
3152
- if (apiKey && consumerId) {
3153
- jwtData = await this.refreshJwt(apiKey, consumerId);
3154
- this.jwtData = jwtData;
3155
- options.jwtData = jwtData;
3156
- }
3157
- else {
3158
- logger.warn('JWT or both apiKey and consumerId are required when using the Provable API');
3159
- }
3274
+ // Resolve the auth mode: per-request, then client-wide, then the legacy fields.
3275
+ // Mixing an explicit per-request auth with per-request legacy fields is
3276
+ // ambiguous, so it throws — matching normalizeAuthConfig and RecordScanner.
3277
+ if (options.auth && (options.apiKey !== undefined || options.consumerId !== undefined || options.jwtData !== undefined)) {
3278
+ throw new Error("Pass either `auth` or the legacy apiKey/consumerId/jwtData options, not both");
3279
+ }
3280
+ const config = options.auth ?? this.auth ?? normalizeAuthConfig({
3281
+ apiKey: options.apiKey ?? this.apiKey,
3282
+ consumerId: options.consumerId ?? this.consumerId,
3283
+ jwtData: options.jwtData ?? this.jwtData,
3284
+ });
3285
+ const auth = new ApiAuth(config, this.baseUrl, this.transport, this.method("refreshJwt"));
3286
+ // Seed the cached token so an explicit jwt config reuses it until the
3287
+ // refresh window instead of minting on every request — but only for the
3288
+ // consumer that minted it, so per-request credentials on a shared
3289
+ // client never ride another identity's token.
3290
+ if (config.mode === "jwt" && !config.jwtData && this.jwtData && config.consumerId === this.jwtConsumerId) {
3291
+ auth.setJwtData(this.jwtData);
3292
+ }
3293
+ // Resolves the auth headers, which refreshes the JWT when it is stale. Runs before
3294
+ // parsing the proving request so JWT refresh errors propagate as they always have.
3295
+ const authHeaders = await auth.headers();
3296
+ const jwtData = auth.getJwtData();
3297
+ if (config.mode === "jwt" && jwtData) {
3298
+ this.jwtData = jwtData;
3299
+ this.jwtConsumerId = config.consumerId;
3300
+ options.jwtData = jwtData;
3160
3301
  }
3161
3302
  // Create the necessary headers to hit the provable api.
3162
3303
  const headers = {
3163
3304
  ...this.method("submitProvingRequest"),
3164
3305
  "Content-Type": "application/json",
3306
+ ...authHeaders,
3165
3307
  };
3166
- if (jwtData?.jwt) {
3167
- headers["Authorization"] = jwtData.jwt;
3168
- }
3169
3308
  // Send the proving request encrypted (libsodium-compatible sealed box).
3170
3309
  // Used by both `/prove/authorization` (Authorization variant) and
3171
3310
  // `/prove/request` (Request variant). The legacy plaintext `/prove`
@@ -4718,9 +4857,10 @@ class RecordScanner {
4718
4857
  cacheViewKeysOnRegister;
4719
4858
  url;
4720
4859
  baseUrl;
4721
- apiKey;
4860
+ auth;
4861
+ explicitAuth;
4862
+ legacyApiKey;
4722
4863
  consumerId;
4723
- jwtData;
4724
4864
  uuid;
4725
4865
  viewKeys;
4726
4866
  autoReRegister;
@@ -4757,23 +4897,71 @@ class RecordScanner {
4757
4897
  // Add the view key to the scanner's view keys.
4758
4898
  this.addViewKey(this.account.viewKey());
4759
4899
  }
4760
- // Configure authentication options.
4761
- this.apiKey = typeof options.apiKey === "string" ? {
4762
- header: "X-Provable-API-Key",
4763
- value: options.apiKey
4764
- } : options.apiKey;
4900
+ // Configure authentication options. Validated up front so an explicit
4901
+ // auth combined with the legacy fields throws instead of the legacy key
4902
+ // leaking onto requests the explicit mode should own.
4903
+ normalizeAuthConfig(options);
4904
+ this.explicitAuth = options.auth;
4905
+ this.legacyApiKey = options.apiKey;
4765
4906
  this.consumerId = options.consumerId;
4766
- this.jwtData = options.jwtData;
4907
+ this.auth = this.buildAuth(options.jwtData);
4767
4908
  this.autoReRegister = options.autoReRegister;
4768
4909
  this.decryptEnabled = options.decryptEnabled;
4769
4910
  }
4911
+ /**
4912
+ * Builds the ApiAuth for the current auth configuration. An explicit `auth` option wins;
4913
+ * the legacy apiKey/consumerId fields normalize onto a mode otherwise.
4914
+ *
4915
+ * @param {RecordScannerJWTData} [jwtData] JWT to carry into the rebuilt auth.
4916
+ * @returns {ApiAuth} The auth for the current configuration.
4917
+ */
4918
+ buildAuth(jwtData) {
4919
+ const config = this.explicitAuth ?? normalizeAuthConfig({
4920
+ apiKey: this.legacyApiKey,
4921
+ consumerId: this.consumerId,
4922
+ jwtData,
4923
+ });
4924
+ const auth = new ApiAuth(config, this.baseUrl, this.transport);
4925
+ if (jwtData)
4926
+ auth.setJwtData(jwtData);
4927
+ return auth;
4928
+ }
4929
+ /**
4930
+ * Legacy raw-key header echoed on every request alongside the mode's own headers, matching
4931
+ * the pre-mode wire behavior when the legacy apiKey option is used.
4932
+ *
4933
+ * @returns {{ header: string, value: string } | undefined} The raw key header, when a legacy apiKey is set.
4934
+ */
4935
+ rawKeyHeader() {
4936
+ if (this.legacyApiKey === undefined)
4937
+ return undefined;
4938
+ return typeof this.legacyApiKey === "string"
4939
+ ? { header: "X-Provable-API-Key", value: this.legacyApiKey }
4940
+ : this.legacyApiKey;
4941
+ }
4770
4942
  /**
4771
4943
  * Set the API key to use for the record scanner.
4772
4944
  *
4773
4945
  * @param {string | { header: string, value: string }} apiKey The API key to use for the record scanner.
4774
4946
  */
4775
4947
  setApiKey(apiKey) {
4776
- this.apiKey = typeof apiKey === "string" ? { header: "X-Provable-API-Key", value: apiKey } : apiKey;
4948
+ if (this.explicitAuth) {
4949
+ throw new Error("This scanner uses an explicit auth mode — replace it with setAuth instead of the legacy setApiKey");
4950
+ }
4951
+ this.legacyApiKey = apiKey;
4952
+ this.auth = this.buildAuth(this.auth.getJwtData());
4953
+ }
4954
+ /**
4955
+ * Set the explicit auth mode, replacing any legacy apiKey/consumerId configuration.
4956
+ *
4957
+ * @param {ApiAuthConfig} auth The auth mode and its material.
4958
+ */
4959
+ setAuth(auth) {
4960
+ normalizeAuthConfig({ auth });
4961
+ this.explicitAuth = auth;
4962
+ this.legacyApiKey = undefined;
4963
+ this.consumerId = undefined;
4964
+ this.auth = this.buildAuth();
4777
4965
  }
4778
4966
  /**
4779
4967
  * Set the consumer ID used for JWT refresh when using authenticated record scanner (e.g. Provable API).
@@ -4781,7 +4969,11 @@ class RecordScanner {
4781
4969
  * @param {string} consumerId The consumer ID to use for JWT refresh.
4782
4970
  */
4783
4971
  setConsumerId(consumerId) {
4972
+ if (this.explicitAuth) {
4973
+ throw new Error("This scanner uses an explicit auth mode — replace it with setAuth instead of the legacy setConsumerId");
4974
+ }
4784
4975
  this.consumerId = consumerId;
4976
+ this.auth = this.buildAuth(this.auth.getJwtData());
4785
4977
  }
4786
4978
  /**
4787
4979
  * Set JWT data for authentication. Optional; when not set, JWT can be refreshed from apiKey + consumerId if provided.
@@ -4789,7 +4981,7 @@ class RecordScanner {
4789
4981
  * @param {RecordScannerJWTData | undefined} jwtData The JWT data to use, or undefined to clear.
4790
4982
  */
4791
4983
  setJwtData(jwtData) {
4792
- this.jwtData = jwtData;
4984
+ this.auth.setJwtData(jwtData);
4793
4985
  }
4794
4986
  /**
4795
4987
  * Set whether /owned should automatically re-register on 422 (when a view key for the UUID is in viewKeys or account) and retry once.
@@ -4862,54 +5054,6 @@ class RecordScanner {
4862
5054
  this.removeViewKey(this.computeUUID(existingVk).toString());
4863
5055
  }
4864
5056
  }
4865
- /**
4866
- * Refreshes the JWT by making a POST request to /jwts/{consumer_id}. Used when authentication is required.
4867
- *
4868
- * @param {string} apiKey The API key to use for the refresh request.
4869
- * @param {string} consumerId The consumer ID for the JWT endpoint.
4870
- * @returns {Promise<RecordScannerJWTData>} The new JWT data.
4871
- */
4872
- async refreshJwt(apiKey, consumerId) {
4873
- const response = await post(`${this.baseUrl}/jwts/${consumerId}`, {
4874
- headers: {
4875
- "X-Provable-API-Key": apiKey,
4876
- },
4877
- }, this.transport);
4878
- const authHeader = response.headers.get("authorization");
4879
- if (!authHeader) {
4880
- throw new Error("No authorization header in JWT refresh response");
4881
- }
4882
- const body = await response.json();
4883
- return {
4884
- jwt: authHeader,
4885
- expiration: body.exp * 1000, // Convert to milliseconds
4886
- };
4887
- }
4888
- /**
4889
- * Returns auth headers (e.g. Authorization with JWT). Refreshes JWT if expired and apiKey + consumerId are set. Empty when auth is not configured.
4890
- *
4891
- * @returns {Promise<Record<string, string>>} Auth headers to add to requests, or empty object when not configured.
4892
- */
4893
- async getAuthHeaders() {
4894
- let jwtData = this.jwtData;
4895
- // Consider JWT expired a few minutes early to avoid race at boundary.
4896
- const isExpired = jwtData && Date.now() >= jwtData.expiration - FIVE_MINUTES;
4897
- if (!jwtData || isExpired) {
4898
- const apiKey = this.apiKey?.value;
4899
- if (apiKey && this.consumerId) {
4900
- jwtData = await this.refreshJwt(apiKey, this.consumerId);
4901
- this.jwtData = jwtData;
4902
- }
4903
- else if (jwtData?.jwt) {
4904
- // Use existing JWT even if expired when refresh is not possible.
4905
- return { Authorization: jwtData.jwt };
4906
- }
4907
- else {
4908
- return {};
4909
- }
4910
- }
4911
- return jwtData?.jwt ? { Authorization: jwtData.jwt } : {};
4912
- }
4913
5057
  /**
4914
5058
  * Set the UUID for the record scanner.
4915
5059
  *
@@ -5414,13 +5558,15 @@ class RecordScanner {
5414
5558
  */
5415
5559
  async request(req) {
5416
5560
  try {
5417
- // Attach JWT (if configured) and API key before sending.
5418
- const authHeaders = await this.getAuthHeaders();
5561
+ // Attach the mode's auth headers before sending.
5562
+ const authHeaders = await this.auth.headers();
5419
5563
  for (const [key, value] of Object.entries(authHeaders)) {
5420
5564
  req.headers.set(key, value);
5421
5565
  }
5422
- if (this.apiKey) {
5423
- req.headers.set(this.apiKey.header, this.apiKey.value);
5566
+ // Legacy apiKey callers also got their raw key echoed on every request.
5567
+ const rawKey = this.rawKeyHeader();
5568
+ if (rawKey) {
5569
+ req.headers.set(rawKey.header, rawKey.value);
5424
5570
  }
5425
5571
  const body = req.body ? await req.text() : undefined;
5426
5572
  const plainHeaders = {};
@@ -9373,5 +9519,5 @@ async function initializeWasm() {
9373
9519
  logger.warn("initializeWasm is deprecated, you no longer need to use it");
9374
9520
  }
9375
9521
 
9376
- export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoNetworkClient, BlockHeightSearch, CREDITS_PROGRAM_KEYS, KeyVerificationError as ChecksumMismatchError, DecryptionNotEnabledError, IndexedDBKeyStore, InvalidLocatorError, KEY_STORE, KeyVerificationError, MemKeyVerifier, NetworkRecordProvider, OfflineKeyProvider, OfflineSearchParams, PRIVATE_TO_PUBLIC_TRANSFER, PRIVATE_TRANSFER, PRIVATE_TRANSFER_TYPES, PUBLIC_TO_PRIVATE_TRANSFER, PUBLIC_TRANSFER, PUBLIC_TRANSFER_AS_SIGNER, PreparedProgram, ProgramManager, RECORD_DOMAIN, RecordNotFoundError, RecordScanner, RecordScannerRequestError, SealanceMerkleTree, UUIDError, VALID_TRANSFER_TYPES, ViewKeyNotStoredError, buildExecutionRequestFromExternallySignedData, computeExternalSigningInputs, cookieAffinityTransport, defaultTransport, encryptAuthorization, encryptProvingRequest, encryptRegistrationRequest, encryptSerializedProvingRequest, encryptViewKey, generateHookData, getLogLevel, initializeWasm, inputsToFields, isInputIdStrategy, isProveApiErrorBody, isProvingResponse, isRecordViewKeyStrategy, isViewKeyStrategy, logAndThrow, programChecksum, provingKeyLocator, serializeProvingRequest, setLogLevel, sha256Hex, toAddress, toField, toGroup, toSignature, toViewKey, translationKeyLocator, verifyBatchProof, verifyProof, verifyingKeyLocator, zeroizeBytes };
9522
+ export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoNetworkClient, ApiAuth, BlockHeightSearch, CREDITS_PROGRAM_KEYS, KeyVerificationError as ChecksumMismatchError, DEFAULT_API_KEY_HEADER, DecryptionNotEnabledError, IndexedDBKeyStore, InvalidLocatorError, KEY_STORE, KeyVerificationError, MemKeyVerifier, NetworkRecordProvider, OfflineKeyProvider, OfflineSearchParams, PRIVATE_TO_PUBLIC_TRANSFER, PRIVATE_TRANSFER, PRIVATE_TRANSFER_TYPES, PUBLIC_TO_PRIVATE_TRANSFER, PUBLIC_TRANSFER, PUBLIC_TRANSFER_AS_SIGNER, PreparedProgram, ProgramManager, RECORD_DOMAIN, RecordNotFoundError, RecordScanner, RecordScannerRequestError, SealanceMerkleTree, UUIDError, VALID_TRANSFER_TYPES, ViewKeyNotStoredError, buildExecutionRequestFromExternallySignedData, computeExternalSigningInputs, cookieAffinityTransport, defaultTransport, encryptAuthorization, encryptProvingRequest, encryptRegistrationRequest, encryptSerializedProvingRequest, encryptViewKey, generateHookData, getLogLevel, initializeWasm, inputsToFields, isInputIdStrategy, isProveApiErrorBody, isProvingResponse, isRecordViewKeyStrategy, isViewKeyStrategy, logAndThrow, normalizeAuthConfig, programChecksum, provingKeyLocator, serializeProvingRequest, setLogLevel, sha256Hex, toAddress, toField, toGroup, toSignature, toViewKey, translationKeyLocator, verifyBatchProof, verifyProof, verifyingKeyLocator, zeroizeBytes };
9377
9523
  //# sourceMappingURL=browser.js.map