@stellar/stellar-sdk 16.0.1 → 16.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.
- package/README.md +41 -2
- package/dist/stellar-sdk-axios.js +5401 -3690
- package/dist/stellar-sdk-axios.js.map +1 -1
- package/dist/stellar-sdk-axios.min.js +12 -11
- package/dist/stellar-sdk-axios.min.js.map +1 -1
- package/dist/stellar-sdk.js +4850 -3681
- package/dist/stellar-sdk.js.map +1 -1
- package/dist/stellar-sdk.min.js +17 -17
- package/dist/stellar-sdk.min.js.map +1 -1
- package/lib/axios/cjs/base/auth.js +147 -30
- package/lib/axios/cjs/base/auth.js.map +1 -1
- package/lib/axios/cjs/base/index.js +113 -0
- package/lib/axios/cjs/base/index.js.map +1 -0
- package/lib/axios/cjs/base/keypair.js +39 -0
- package/lib/axios/cjs/base/keypair.js.map +1 -1
- package/lib/axios/cjs/base/scval.js +34 -0
- package/lib/axios/cjs/base/scval.js.map +1 -1
- package/lib/axios/cjs/bindings/client.js +170 -0
- package/lib/axios/cjs/bindings/client.js.map +1 -1
- package/lib/axios/cjs/bindings/config.js +1 -1
- package/lib/axios/cjs/bindings/generator.js +45 -16
- package/lib/axios/cjs/bindings/generator.js.map +1 -1
- package/lib/axios/cjs/bindings/types.js +151 -1
- package/lib/axios/cjs/bindings/types.js.map +1 -1
- package/lib/axios/cjs/bindings/utils.js +10 -0
- package/lib/axios/cjs/bindings/utils.js.map +1 -1
- package/lib/axios/cjs/cli/index.js +19 -22
- package/lib/axios/cjs/cli/index.js.map +1 -1
- package/lib/axios/cjs/cli/util.js +1 -20
- package/lib/axios/cjs/cli/util.js.map +1 -1
- package/lib/axios/cjs/contract/assembled_transaction.js +39 -17
- package/lib/axios/cjs/contract/assembled_transaction.js.map +1 -1
- package/lib/axios/cjs/contract/basic_node_signer.js +8 -42
- package/lib/axios/cjs/contract/basic_node_signer.js.map +1 -1
- package/lib/axios/cjs/contract/client.js +56 -3
- package/lib/axios/cjs/contract/client.js.map +1 -1
- package/lib/axios/cjs/contract/event_spec.js +164 -0
- package/lib/axios/cjs/contract/event_spec.js.map +1 -0
- package/lib/axios/cjs/contract/index.js +2 -0
- package/lib/axios/cjs/contract/index.js.map +1 -1
- package/lib/axios/cjs/contract/sent_transaction.js +0 -20
- package/lib/axios/cjs/contract/sent_transaction.js.map +1 -1
- package/lib/axios/cjs/contract/signer.js +96 -0
- package/lib/axios/cjs/contract/signer.js.map +1 -0
- package/lib/axios/cjs/contract/spec.js +107 -3
- package/lib/axios/cjs/contract/spec.js.map +1 -1
- package/lib/axios/cjs/contract/types.js.map +1 -1
- package/lib/axios/cjs/errors/transaction_failed.js +62 -0
- package/lib/axios/cjs/errors/transaction_failed.js.map +1 -0
- package/lib/axios/cjs/errors/wrap_http_error.js +20 -0
- package/lib/axios/cjs/errors/wrap_http_error.js.map +1 -0
- package/lib/axios/cjs/federation/server.js +15 -35
- package/lib/axios/cjs/federation/server.js.map +1 -1
- package/lib/axios/cjs/horizon/account_response.js +0 -20
- package/lib/axios/cjs/horizon/account_response.js.map +1 -1
- package/lib/axios/cjs/horizon/horizon_api.js +5 -0
- package/lib/axios/cjs/horizon/horizon_api.js.map +1 -1
- package/lib/axios/cjs/horizon/horizon_axios_client.js +1 -1
- package/lib/axios/cjs/horizon/server.js +20 -26
- package/lib/axios/cjs/horizon/server.js.map +1 -1
- package/lib/axios/cjs/index.js +66 -65
- package/lib/axios/cjs/index.js.map +1 -1
- package/lib/axios/cjs/rpc/api.js.map +1 -1
- package/lib/axios/cjs/rpc/axios.js +1 -1
- package/lib/axios/cjs/rpc/server.js +181 -13
- package/lib/axios/cjs/rpc/server.js.map +1 -1
- package/lib/axios/cjs/rpc/transaction.js +2 -20
- package/lib/axios/cjs/rpc/transaction.js.map +1 -1
- package/lib/axios/cjs/webauth/challenge_transaction.js +7 -22
- package/lib/axios/cjs/webauth/challenge_transaction.js.map +1 -1
- package/lib/axios/cjs/webauth/utils.js +1 -20
- package/lib/axios/cjs/webauth/utils.js.map +1 -1
- package/lib/axios/esm/base/auth.d.ts +181 -13
- package/lib/axios/esm/base/auth.js +146 -31
- package/lib/axios/esm/base/auth.js.map +1 -1
- package/lib/axios/esm/base/index.d.ts +2 -2
- package/lib/axios/esm/base/index.js +44 -0
- package/lib/axios/esm/base/index.js.map +1 -0
- package/lib/axios/esm/base/keypair.d.ts +27 -0
- package/lib/axios/esm/base/keypair.js +39 -0
- package/lib/axios/esm/base/keypair.js.map +1 -1
- package/lib/axios/esm/base/scval.d.ts +4 -0
- package/lib/axios/esm/base/scval.js +34 -0
- package/lib/axios/esm/base/scval.js.map +1 -1
- package/lib/axios/esm/bindings/client.d.ts +39 -0
- package/lib/axios/esm/bindings/client.js +171 -1
- package/lib/axios/esm/bindings/client.js.map +1 -1
- package/lib/axios/esm/bindings/config.js +1 -1
- package/lib/axios/esm/bindings/generator.d.ts +34 -0
- package/lib/axios/esm/bindings/generator.js +45 -16
- package/lib/axios/esm/bindings/generator.js.map +1 -1
- package/lib/axios/esm/bindings/types.d.ts +42 -0
- package/lib/axios/esm/bindings/types.js +153 -3
- package/lib/axios/esm/bindings/types.js.map +1 -1
- package/lib/axios/esm/bindings/utils.d.ts +10 -0
- package/lib/axios/esm/bindings/utils.js +9 -1
- package/lib/axios/esm/bindings/utils.js.map +1 -1
- package/lib/axios/esm/cli/index.js +19 -22
- package/lib/axios/esm/cli/index.js.map +1 -1
- package/lib/axios/esm/cli/util.d.ts +1 -1
- package/lib/axios/esm/cli/util.js +1 -20
- package/lib/axios/esm/cli/util.js.map +1 -1
- package/lib/axios/esm/contract/assembled_transaction.d.ts +7 -5
- package/lib/axios/esm/contract/assembled_transaction.js +39 -17
- package/lib/axios/esm/contract/assembled_transaction.js.map +1 -1
- package/lib/axios/esm/contract/basic_node_signer.d.ts +3 -0
- package/lib/axios/esm/contract/basic_node_signer.js +8 -42
- package/lib/axios/esm/contract/basic_node_signer.js.map +1 -1
- package/lib/axios/esm/contract/client.d.ts +49 -3
- package/lib/axios/esm/contract/client.js +56 -3
- package/lib/axios/esm/contract/client.js.map +1 -1
- package/lib/axios/esm/contract/event_spec.d.ts +78 -0
- package/lib/axios/esm/contract/event_spec.js +159 -0
- package/lib/axios/esm/contract/event_spec.js.map +1 -0
- package/lib/axios/esm/contract/index.d.ts +3 -0
- package/lib/axios/esm/contract/index.js +1 -0
- package/lib/axios/esm/contract/index.js.map +1 -1
- package/lib/axios/esm/contract/sent_transaction.js +0 -20
- package/lib/axios/esm/contract/sent_transaction.js.map +1 -1
- package/lib/axios/esm/contract/signer.d.ts +104 -0
- package/lib/axios/esm/contract/signer.js +91 -0
- package/lib/axios/esm/contract/signer.js.map +1 -0
- package/lib/axios/esm/contract/spec.d.ts +84 -0
- package/lib/axios/esm/contract/spec.js +107 -3
- package/lib/axios/esm/contract/spec.js.map +1 -1
- package/lib/axios/esm/contract/types.d.ts +25 -8
- package/lib/axios/esm/contract/types.js.map +1 -1
- package/lib/axios/esm/errors/index.d.ts +1 -0
- package/lib/axios/esm/errors/transaction_failed.d.ts +55 -0
- package/lib/axios/esm/errors/transaction_failed.js +60 -0
- package/lib/axios/esm/errors/transaction_failed.js.map +1 -0
- package/lib/axios/esm/errors/wrap_http_error.d.ts +20 -0
- package/lib/axios/esm/errors/wrap_http_error.js +18 -0
- package/lib/axios/esm/errors/wrap_http_error.js.map +1 -0
- package/lib/axios/esm/federation/server.js +15 -35
- package/lib/axios/esm/federation/server.js.map +1 -1
- package/lib/axios/esm/horizon/account_response.js +0 -20
- package/lib/axios/esm/horizon/account_response.js.map +1 -1
- package/lib/axios/esm/horizon/horizon_api.d.ts +12 -1
- package/lib/axios/esm/horizon/horizon_api.js +5 -0
- package/lib/axios/esm/horizon/horizon_api.js.map +1 -1
- package/lib/axios/esm/horizon/horizon_axios_client.js +1 -1
- package/lib/axios/esm/horizon/server.d.ts +10 -4
- package/lib/axios/esm/horizon/server.js +20 -26
- package/lib/axios/esm/horizon/server.js.map +1 -1
- package/lib/axios/esm/index.js +27 -29
- package/lib/axios/esm/index.js.map +1 -1
- package/lib/axios/esm/rpc/api.d.ts +21 -0
- package/lib/axios/esm/rpc/api.js.map +1 -1
- package/lib/axios/esm/rpc/axios.js +1 -1
- package/lib/axios/esm/rpc/server.d.ts +115 -3
- package/lib/axios/esm/rpc/server.js +181 -13
- package/lib/axios/esm/rpc/server.js.map +1 -1
- package/lib/axios/esm/rpc/transaction.js +2 -20
- package/lib/axios/esm/rpc/transaction.js.map +1 -1
- package/lib/axios/esm/webauth/challenge_transaction.js +7 -22
- package/lib/axios/esm/webauth/challenge_transaction.js.map +1 -1
- package/lib/axios/esm/webauth/utils.js +1 -20
- package/lib/axios/esm/webauth/utils.js.map +1 -1
- package/lib/cjs/base/auth.js +147 -30
- package/lib/cjs/base/auth.js.map +1 -1
- package/lib/cjs/base/index.js +113 -0
- package/lib/cjs/base/index.js.map +1 -0
- package/lib/cjs/base/keypair.js +39 -0
- package/lib/cjs/base/keypair.js.map +1 -1
- package/lib/cjs/base/scval.js +34 -0
- package/lib/cjs/base/scval.js.map +1 -1
- package/lib/cjs/bindings/client.js +170 -0
- package/lib/cjs/bindings/client.js.map +1 -1
- package/lib/cjs/bindings/config.js +1 -1
- package/lib/cjs/bindings/generator.js +45 -16
- package/lib/cjs/bindings/generator.js.map +1 -1
- package/lib/cjs/bindings/types.js +151 -1
- package/lib/cjs/bindings/types.js.map +1 -1
- package/lib/cjs/bindings/utils.js +10 -0
- package/lib/cjs/bindings/utils.js.map +1 -1
- package/lib/cjs/cli/index.js +19 -22
- package/lib/cjs/cli/index.js.map +1 -1
- package/lib/cjs/cli/util.js +1 -20
- package/lib/cjs/cli/util.js.map +1 -1
- package/lib/cjs/contract/assembled_transaction.js +39 -17
- package/lib/cjs/contract/assembled_transaction.js.map +1 -1
- package/lib/cjs/contract/basic_node_signer.js +8 -42
- package/lib/cjs/contract/basic_node_signer.js.map +1 -1
- package/lib/cjs/contract/client.js +56 -3
- package/lib/cjs/contract/client.js.map +1 -1
- package/lib/cjs/contract/event_spec.js +164 -0
- package/lib/cjs/contract/event_spec.js.map +1 -0
- package/lib/cjs/contract/index.js +2 -0
- package/lib/cjs/contract/index.js.map +1 -1
- package/lib/cjs/contract/sent_transaction.js +0 -20
- package/lib/cjs/contract/sent_transaction.js.map +1 -1
- package/lib/cjs/contract/signer.js +96 -0
- package/lib/cjs/contract/signer.js.map +1 -0
- package/lib/cjs/contract/spec.js +107 -3
- package/lib/cjs/contract/spec.js.map +1 -1
- package/lib/cjs/contract/types.js.map +1 -1
- package/lib/cjs/errors/transaction_failed.js +62 -0
- package/lib/cjs/errors/transaction_failed.js.map +1 -0
- package/lib/cjs/errors/wrap_http_error.js +20 -0
- package/lib/cjs/errors/wrap_http_error.js.map +1 -0
- package/lib/cjs/federation/server.js +15 -35
- package/lib/cjs/federation/server.js.map +1 -1
- package/lib/cjs/horizon/account_response.js +0 -20
- package/lib/cjs/horizon/account_response.js.map +1 -1
- package/lib/cjs/horizon/horizon_api.js +5 -0
- package/lib/cjs/horizon/horizon_api.js.map +1 -1
- package/lib/cjs/horizon/horizon_axios_client.js +1 -1
- package/lib/cjs/horizon/server.js +20 -26
- package/lib/cjs/horizon/server.js.map +1 -1
- package/lib/cjs/index.js +66 -65
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/rpc/api.js.map +1 -1
- package/lib/cjs/rpc/axios.js +1 -1
- package/lib/cjs/rpc/server.js +181 -13
- package/lib/cjs/rpc/server.js.map +1 -1
- package/lib/cjs/rpc/transaction.js +2 -20
- package/lib/cjs/rpc/transaction.js.map +1 -1
- package/lib/cjs/webauth/challenge_transaction.js +7 -22
- package/lib/cjs/webauth/challenge_transaction.js.map +1 -1
- package/lib/cjs/webauth/utils.js +1 -20
- package/lib/cjs/webauth/utils.js.map +1 -1
- package/lib/esm/base/auth.d.ts +181 -13
- package/lib/esm/base/auth.js +146 -31
- package/lib/esm/base/auth.js.map +1 -1
- package/lib/esm/base/index.d.ts +2 -2
- package/lib/esm/base/index.js +44 -0
- package/lib/esm/base/index.js.map +1 -0
- package/lib/esm/base/keypair.d.ts +27 -0
- package/lib/esm/base/keypair.js +39 -0
- package/lib/esm/base/keypair.js.map +1 -1
- package/lib/esm/base/scval.d.ts +4 -0
- package/lib/esm/base/scval.js +34 -0
- package/lib/esm/base/scval.js.map +1 -1
- package/lib/esm/bindings/client.d.ts +39 -0
- package/lib/esm/bindings/client.js +171 -1
- package/lib/esm/bindings/client.js.map +1 -1
- package/lib/esm/bindings/config.js +1 -1
- package/lib/esm/bindings/generator.d.ts +34 -0
- package/lib/esm/bindings/generator.js +45 -16
- package/lib/esm/bindings/generator.js.map +1 -1
- package/lib/esm/bindings/types.d.ts +42 -0
- package/lib/esm/bindings/types.js +153 -3
- package/lib/esm/bindings/types.js.map +1 -1
- package/lib/esm/bindings/utils.d.ts +10 -0
- package/lib/esm/bindings/utils.js +9 -1
- package/lib/esm/bindings/utils.js.map +1 -1
- package/lib/esm/cli/index.js +19 -22
- package/lib/esm/cli/index.js.map +1 -1
- package/lib/esm/cli/util.d.ts +1 -1
- package/lib/esm/cli/util.js +1 -20
- package/lib/esm/cli/util.js.map +1 -1
- package/lib/esm/contract/assembled_transaction.d.ts +7 -5
- package/lib/esm/contract/assembled_transaction.js +39 -17
- package/lib/esm/contract/assembled_transaction.js.map +1 -1
- package/lib/esm/contract/basic_node_signer.d.ts +3 -0
- package/lib/esm/contract/basic_node_signer.js +8 -42
- package/lib/esm/contract/basic_node_signer.js.map +1 -1
- package/lib/esm/contract/client.d.ts +49 -3
- package/lib/esm/contract/client.js +56 -3
- package/lib/esm/contract/client.js.map +1 -1
- package/lib/esm/contract/event_spec.d.ts +78 -0
- package/lib/esm/contract/event_spec.js +159 -0
- package/lib/esm/contract/event_spec.js.map +1 -0
- package/lib/esm/contract/index.d.ts +3 -0
- package/lib/esm/contract/index.js +1 -0
- package/lib/esm/contract/index.js.map +1 -1
- package/lib/esm/contract/sent_transaction.js +0 -20
- package/lib/esm/contract/sent_transaction.js.map +1 -1
- package/lib/esm/contract/signer.d.ts +104 -0
- package/lib/esm/contract/signer.js +91 -0
- package/lib/esm/contract/signer.js.map +1 -0
- package/lib/esm/contract/spec.d.ts +84 -0
- package/lib/esm/contract/spec.js +107 -3
- package/lib/esm/contract/spec.js.map +1 -1
- package/lib/esm/contract/types.d.ts +25 -8
- package/lib/esm/contract/types.js.map +1 -1
- package/lib/esm/errors/index.d.ts +1 -0
- package/lib/esm/errors/transaction_failed.d.ts +55 -0
- package/lib/esm/errors/transaction_failed.js +60 -0
- package/lib/esm/errors/transaction_failed.js.map +1 -0
- package/lib/esm/errors/wrap_http_error.d.ts +20 -0
- package/lib/esm/errors/wrap_http_error.js +18 -0
- package/lib/esm/errors/wrap_http_error.js.map +1 -0
- package/lib/esm/federation/server.js +15 -35
- package/lib/esm/federation/server.js.map +1 -1
- package/lib/esm/horizon/account_response.js +0 -20
- package/lib/esm/horizon/account_response.js.map +1 -1
- package/lib/esm/horizon/horizon_api.d.ts +12 -1
- package/lib/esm/horizon/horizon_api.js +5 -0
- package/lib/esm/horizon/horizon_api.js.map +1 -1
- package/lib/esm/horizon/horizon_axios_client.js +1 -1
- package/lib/esm/horizon/server.d.ts +10 -4
- package/lib/esm/horizon/server.js +20 -26
- package/lib/esm/horizon/server.js.map +1 -1
- package/lib/esm/index.js +27 -29
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/rpc/api.d.ts +21 -0
- package/lib/esm/rpc/api.js.map +1 -1
- package/lib/esm/rpc/axios.js +1 -1
- package/lib/esm/rpc/server.d.ts +115 -3
- package/lib/esm/rpc/server.js +181 -13
- package/lib/esm/rpc/server.js.map +1 -1
- package/lib/esm/rpc/transaction.js +2 -20
- package/lib/esm/rpc/transaction.js.map +1 -1
- package/lib/esm/webauth/challenge_transaction.js +7 -22
- package/lib/esm/webauth/challenge_transaction.js.map +1 -1
- package/lib/esm/webauth/utils.js +1 -20
- package/lib/esm/webauth/utils.js.map +1 -1
- package/package.json +35 -30
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"challenge_transaction.js","sources":["../../../../src/webauth/challenge_transaction.ts"],"sourcesContent":["import {\n Keypair,\n Account,\n TransactionBuilder,\n BASE_FEE,\n Operation,\n Memo,\n MemoNone,\n MemoID,\n FeeBumpTransaction,\n TimeoutInfinite,\n Transaction,\n Networks,\n} from \"../base/index.js\";\nimport { InvalidChallengeError } from \"./errors.js\";\nimport { gatherTxSigners, verifyTxSignedBy } from \"./utils.js\";\nimport { Utils } from \"../utils.js\";\nimport { ServerApi } from \"../horizon/server_api.js\";\nimport { uint8ArrayToBase64 } from \"uint8array-extras\";\n\n/**\n * Returns a valid {@link https://stellar.org/protocol/sep-10 | SEP-10}\n * challenge transaction which you can use for Stellar Web Authentication.\n * @param serverKeypair - Keypair for server's signing account.\n * @param clientAccountID - The stellar account (G...) or muxed account\n * (M...) that the wallet wishes to authenticate with the server.\n * @param homeDomain - The fully qualified domain name of the service\n * requiring authentication\n * @param timeout - Challenge duration (default to 5 minutes).\n * @param networkPassphrase - The network passphrase. If you pass this\n * argument then timeout is required.\n * @param webAuthDomain - The fully qualified domain name of the service\n * issuing the challenge.\n * @param memo - The memo to attach to the challenge transaction. The\n * memo must be of type `id`. If the `clientaccountID` is a muxed account,\n * memos cannot be used.\n * @param clientDomain - The fully qualified domain of the client\n * requesting the challenge. Only necessary when the 'client_domain'\n * parameter is passed.\n * @param clientSigningKey - The public key assigned to the SIGNING_KEY\n * attribute specified on the stellar.toml hosted on the client domain. Only\n * necessary when the 'client_domain' parameter is passed.\n * @returns A base64 encoded string of the raw TransactionEnvelope xdr\n * struct for the transaction.\n * @throws Will throw if `clientAccountID` is a muxed account, and `memo`\n * is present.\n * @throws Will throw if `clientDomain` is provided, but\n * `clientSigningKey` is missing\n * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth}\n * @example\n * ```ts\n * import { Keypair, Networks, WebAuth } from 'stellar-sdk'\n *\n * let serverKeyPair = Keypair.fromSecret(\"server-secret\")\n * let challenge = WebAuth.buildChallengeTx(\n * serverKeyPair,\n * \"client-stellar-account-id\",\n * \"stellar.org\",\n * 300,\n * Networks.TESTNET);\n * ```\n */\nexport function buildChallengeTx(\n serverKeypair: Keypair,\n clientAccountID: string,\n homeDomain: string,\n\n timeout: number = 300,\n networkPassphrase: string,\n webAuthDomain: string,\n memo: string | null = null,\n clientDomain: string | null = null,\n clientSigningKey: string | null = null,\n): string {\n if (clientAccountID.startsWith(\"M\") && memo) {\n throw Error(\"memo cannot be used if clientAccountID is a muxed account\");\n }\n\n const account = new Account(serverKeypair.publicKey(), \"-1\");\n const now = Math.floor(Date.now() / 1000);\n\n // A Base64 digit represents 6 bits, to generate a random 64 bytes\n // base64 string, we need 48 random bytes = (64 * 6)/8\n //\n // Each Base64 digit is in ASCII and each ASCII characters when\n // turned into binary represents 8 bits = 1 bytes.\n const value = uint8ArrayToBase64(crypto.getRandomValues(new Uint8Array(48)));\n\n const builder = new TransactionBuilder(account, {\n fee: BASE_FEE,\n networkPassphrase,\n timebounds: {\n minTime: now,\n maxTime: now + timeout,\n },\n })\n .addOperation(\n Operation.manageData({\n name: `${homeDomain} auth`,\n value,\n source: clientAccountID,\n }),\n )\n .addOperation(\n Operation.manageData({\n name: \"web_auth_domain\",\n value: webAuthDomain,\n source: account.accountId(),\n }),\n );\n\n if (clientDomain) {\n if (!clientSigningKey) {\n throw Error(\"clientSigningKey is required if clientDomain is provided\");\n }\n builder.addOperation(\n Operation.manageData({\n name: `client_domain`,\n value: clientDomain,\n source: clientSigningKey,\n }),\n );\n }\n\n if (memo) {\n builder.addMemo(Memo.id(memo));\n }\n\n const transaction = builder.build();\n transaction.sign(serverKeypair);\n\n return transaction.toEnvelope().toXDR(\"base64\").toString();\n}\n\n/**\n * Reads a SEP-10 challenge transaction and returns the decoded transaction and\n * client account ID contained within.\n *\n * It also verifies that the transaction has been signed by the server.\n *\n * It does not verify that the transaction has been signed by the client or that\n * any signatures other than the server's on the transaction are valid. Use one\n * of the following functions to completely verify the transaction:\n *\n * - {@link WebAuth.verifyChallengeTxThreshold}\n * - {@link WebAuth.verifyChallengeTxSigners}\n * @param challengeTx - SEP0010 challenge transaction in base64.\n * @param serverAccountID - The server's stellar account (public key).\n * @param networkPassphrase - The network passphrase, e.g.: 'Test SDF\n * Network ; September 2015' (see {@link Networks})\n * @param homeDomains - The home domain that is expected\n * to be included in the first Manage Data operation's string key. If an\n * array is provided, one of the domain names in the array must match.\n * @param webAuthDomain - The home domain that is expected to be included\n * as the value of the Manage Data operation with the 'web_auth_domain' key.\n * If no such operation is included, this parameter is not used.\n * @returns The actual transaction and the\n * Stellar public key (master key) used to sign the Manage Data operation,\n * the matched home domain, and the memo attached to the transaction, which\n * will be null if not present.\n * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth}\n */\nexport function readChallengeTx(\n challengeTx: string,\n serverAccountID: string,\n networkPassphrase: string,\n homeDomains: string | string[],\n webAuthDomain: string,\n): {\n tx: Transaction;\n clientAccountID: string;\n matchedHomeDomain: string;\n memo: string | null;\n} {\n if (serverAccountID.startsWith(\"M\")) {\n throw Error(\n \"Invalid serverAccountID: multiplexed accounts are not supported.\",\n );\n }\n\n let transaction;\n try {\n transaction = new Transaction(challengeTx, networkPassphrase);\n } catch {\n try {\n transaction = new FeeBumpTransaction(challengeTx, networkPassphrase);\n } catch {\n throw new InvalidChallengeError(\n \"Invalid challenge: unable to deserialize challengeTx transaction string\",\n );\n }\n throw new InvalidChallengeError(\n \"Invalid challenge: expected a Transaction but received a FeeBumpTransaction\",\n );\n }\n\n // verify sequence number\n const sequence = Number.parseInt(transaction.sequence, 10);\n\n if (sequence !== 0) {\n throw new InvalidChallengeError(\n \"The transaction sequence number should be zero\",\n );\n }\n\n // verify transaction source\n if (transaction.source !== serverAccountID) {\n throw new InvalidChallengeError(\n \"The transaction source account is not equal to the server's account\",\n );\n }\n\n // verify operation\n if (transaction.operations.length < 1) {\n throw new InvalidChallengeError(\n \"The transaction should contain at least one operation\",\n );\n }\n\n const [operation, ...subsequentOperations] = transaction.operations;\n\n if (!operation.source) {\n throw new InvalidChallengeError(\n \"The transaction's operation should contain a source account\",\n );\n }\n const clientAccountID: string = operation.source!;\n\n let memo: string | null = null;\n if (transaction.memo.type !== MemoNone) {\n if (clientAccountID.startsWith(\"M\")) {\n throw new InvalidChallengeError(\n \"The transaction has a memo but the client account ID is a muxed account\",\n );\n }\n if (transaction.memo.type !== MemoID) {\n throw new InvalidChallengeError(\n \"The transaction's memo must be of type `id`\",\n );\n }\n memo = transaction.memo.value as string;\n }\n\n if (operation.type !== \"manageData\") {\n throw new InvalidChallengeError(\n \"The transaction's operation type should be 'manageData'\",\n );\n }\n\n // verify timebounds\n if (\n transaction.timeBounds &&\n Number.parseInt(transaction.timeBounds?.maxTime, 10) === TimeoutInfinite\n ) {\n throw new InvalidChallengeError(\n \"The transaction requires non-infinite timebounds\",\n );\n }\n\n // give a small grace period for the transaction time to account for clock drift\n if (!Utils.validateTimebounds(transaction, 60 * 5)) {\n throw new InvalidChallengeError(\"The transaction has expired\");\n }\n\n if (operation.value === undefined) {\n throw new InvalidChallengeError(\n \"The transaction's operation values should not be null\",\n );\n }\n\n // verify base64\n if (!operation.value) {\n throw new InvalidChallengeError(\n \"The transaction's operation value should not be null\",\n );\n }\n\n if (Buffer.from(operation.value.toString(), \"base64\").length !== 48) {\n throw new InvalidChallengeError(\n \"The transaction's operation value should be a 64 bytes base64 random string\",\n );\n }\n\n // verify homeDomains\n if (!homeDomains) {\n throw new InvalidChallengeError(\n \"Invalid homeDomains: a home domain must be provided for verification\",\n );\n }\n\n let matchedHomeDomain;\n\n if (typeof homeDomains === \"string\") {\n if (`${homeDomains} auth` === operation.name) {\n matchedHomeDomain = homeDomains;\n }\n } else if (Array.isArray(homeDomains)) {\n matchedHomeDomain = homeDomains.find(\n (domain) => `${domain} auth` === operation.name,\n );\n } else {\n throw new InvalidChallengeError(\n `Invalid homeDomains: homeDomains type is ${typeof homeDomains} but should be a string or an array`,\n );\n }\n\n if (!matchedHomeDomain) {\n throw new InvalidChallengeError(\n \"Invalid homeDomains: the transaction's operation key name does not match the expected home domain\",\n );\n }\n\n // verify any subsequent operations are manage data ops and source account is the server\n for (const op of subsequentOperations) {\n if (op.type !== \"manageData\") {\n throw new InvalidChallengeError(\n \"The transaction has operations that are not of type 'manageData'\",\n );\n }\n if (op.source !== serverAccountID && op.name !== \"client_domain\") {\n throw new InvalidChallengeError(\n \"The transaction has operations that are unrecognized\",\n );\n }\n if (op.name === \"web_auth_domain\") {\n if (op.value === undefined) {\n throw new InvalidChallengeError(\n \"'web_auth_domain' operation value should not be null\",\n );\n }\n if (op.value.compare(Buffer.from(webAuthDomain))) {\n throw new InvalidChallengeError(\n `'web_auth_domain' operation value does not match ${webAuthDomain}`,\n );\n }\n }\n }\n\n if (!verifyTxSignedBy(transaction, serverAccountID)) {\n throw new InvalidChallengeError(\n `Transaction not signed by server: '${serverAccountID}'`,\n );\n }\n\n return { tx: transaction, clientAccountID, matchedHomeDomain, memo };\n}\n\n/**\n * Verifies that for a SEP 10 challenge transaction all signatures on the\n * transaction are accounted for. A transaction is verified if it is signed by\n * the server account, and all other signatures match a signer that has been\n * provided as an argument (as the accountIDs list). Additional signers can be\n * provided that do not have a signature, but all signatures must be matched to\n * a signer (accountIDs) for verification to succeed. If verification succeeds,\n * a list of signers that were found is returned, not including the server\n * account ID.\n *\n * Signers that are not prefixed as an address/account ID strkey (G...) will be\n * ignored.\n *\n * Errors will be raised if:\n * - The transaction is invalid according to\n * {@link WebAuth.readChallengeTx}.\n * - No client signatures are found on the transaction.\n * - One or more signatures in the transaction are not identifiable as the\n * server account or one of the signers provided in the arguments.\n * @param challengeTx - SEP0010 challenge transaction in base64.\n * @param serverAccountID - The server's stellar account (public key).\n * @param networkPassphrase - The network passphrase, e.g.: 'Test SDF\n * Network ; September 2015' (see {@link Networks}).\n * @param signers - The signers public keys. This list should\n * contain the public keys for all signers that have signed the transaction.\n * @param homeDomains - The home domain(s) that should\n * be included in the first Manage Data operation's string key. Required in\n * readChallengeTx().\n * @param webAuthDomain - The home domain that is expected to be included\n * as the value of the Manage Data operation with the 'web_auth_domain' key,\n * if present. Used in readChallengeTx().\n * @returns The list of signers public keys that have signed\n * the transaction, excluding the server account ID.\n * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth}\n * @example\n * ```ts\n * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk';\n *\n * const serverKP = Keypair.random();\n * const clientKP1 = Keypair.random();\n * const clientKP2 = Keypair.random();\n *\n * // Challenge, possibly built in the server side\n * const challenge = WebAuth.buildChallengeTx(\n * serverKP,\n * clientKP1.publicKey(),\n * \"SDF\",\n * 300,\n * Networks.TESTNET\n * );\n *\n * // clock.tick(200); // Simulates a 200 ms delay when communicating from server to client\n *\n * // Transaction gathered from a challenge, possibly from the client side\n * const transaction = TransactionBuilder.fromXDR(challenge, Networks.TESTNET);\n * transaction.sign(clientKP1, clientKP2);\n * const signedChallenge = transaction\n * .toEnvelope()\n * .toXDR(\"base64\")\n * .toString();\n *\n * // The result below should be equal to [clientKP1.publicKey(), clientKP2.publicKey()]\n * WebAuth.verifyChallengeTxSigners(\n * signedChallenge,\n * serverKP.publicKey(),\n * Networks.TESTNET,\n * threshold,\n * [clientKP1.publicKey(), clientKP2.publicKey()]\n * );\n * ```\n */\nexport function verifyChallengeTxSigners(\n challengeTx: string,\n serverAccountID: string,\n networkPassphrase: string,\n signers: string[],\n homeDomains: string | string[],\n webAuthDomain: string,\n): string[] {\n // Read the transaction which validates its structure.\n const { tx } = readChallengeTx(\n challengeTx,\n serverAccountID,\n networkPassphrase,\n homeDomains,\n webAuthDomain,\n );\n\n // Ensure the server account ID is an address and not a seed.\n let serverKP: Keypair;\n try {\n serverKP = Keypair.fromPublicKey(serverAccountID); // can throw 'Invalid Stellar public key'\n } catch (err: any) {\n throw new Error(\n `Couldn't infer keypair from the provided 'serverAccountID': ${\n err.message\n }`,\n );\n }\n\n // Deduplicate the client signers and ensure the server is not included\n // anywhere we check or output the list of signers.\n const clientSigners = new Set<string>();\n for (const signer of signers) {\n // Ignore the server signer if it is in the signers list. It's\n // important when verifying signers of a challenge transaction that we\n // only verify and return client signers. If an account has the server\n // as a signer the server should not play a part in the authentication\n // of the client.\n if (signer === serverKP.publicKey()) {\n continue;\n }\n\n // Ignore non-G... account/address signers.\n if (signer.charAt(0) !== \"G\") {\n continue;\n }\n\n clientSigners.add(signer);\n }\n\n // Don't continue if none of the signers provided are in the final list.\n if (clientSigners.size === 0) {\n throw new InvalidChallengeError(\n \"No verifiable client signers provided, at least one G... address must be provided\",\n );\n }\n\n let clientSigningKey;\n for (const op of tx.operations) {\n if (op.type === \"manageData\" && op.name === \"client_domain\") {\n if (clientSigningKey) {\n throw new InvalidChallengeError(\n \"Found more than one client_domain operation\",\n );\n }\n clientSigningKey = op.source;\n }\n }\n\n // Verify all the transaction's signers (server and client) in one\n // hit. We do this in one hit here even though the server signature was\n // checked in the ReadChallengeTx to ensure that every signature and signer\n // are consumed only once on the transaction.\n const allSigners: string[] = [\n serverKP.publicKey(),\n ...Array.from(clientSigners),\n ];\n if (clientSigningKey) {\n allSigners.push(clientSigningKey);\n }\n\n const signersFound: string[] = gatherTxSigners(tx, allSigners);\n\n let serverSignatureFound = false;\n let clientSigningKeySignatureFound = false;\n for (const signer of signersFound) {\n if (signer === serverKP.publicKey()) {\n serverSignatureFound = true;\n }\n if (signer === clientSigningKey) {\n clientSigningKeySignatureFound = true;\n }\n }\n\n // Confirm we matched a signature to the server signer.\n if (!serverSignatureFound) {\n throw new InvalidChallengeError(\n `Transaction not signed by server: '${serverKP.publicKey()}'`,\n );\n }\n\n // Confirm we matched a signature to the client domain's signer\n if (clientSigningKey && !clientSigningKeySignatureFound) {\n throw new InvalidChallengeError(\n \"Transaction not signed by the source account of the 'client_domain' \" +\n \"ManageData operation\",\n );\n }\n\n // Confirm we matched at least one given signer with the transaction signatures\n if (signersFound.length === 1) {\n throw new InvalidChallengeError(\n \"None of the given signers match the transaction signatures\",\n );\n }\n\n // Confirm all signatures, including the server signature, were consumed by a signer:\n if (signersFound.length !== tx.signatures.length) {\n throw new InvalidChallengeError(\"Transaction has unrecognized signatures\");\n }\n\n // Remove the server public key before returning\n signersFound.splice(signersFound.indexOf(serverKP.publicKey()), 1);\n if (clientSigningKey) {\n // Remove the client domain public key public key before returning\n signersFound.splice(signersFound.indexOf(clientSigningKey), 1);\n }\n\n if (signersFound.length === 0) {\n throw new InvalidChallengeError(\n \"None of the given signers match the transaction signatures\",\n );\n }\n\n return signersFound;\n}\n\n/**\n * Verifies that for a SEP-10 challenge transaction all signatures on the\n * transaction are accounted for and that the signatures meet a threshold on an\n * account. A transaction is verified if it is signed by the server account, and\n * all other signatures match a signer that has been provided as an argument,\n * and those signatures meet a threshold on the account.\n *\n * Signers that are not prefixed as an address/account ID strkey (G...) will be\n * ignored.\n *\n * Errors will be raised if:\n * - The transaction is invalid according to\n * {@link WebAuth.readChallengeTx}.\n * - No client signatures are found on the transaction.\n * - One or more signatures in the transaction are not identifiable as the\n * server account or one of the signers provided in the arguments.\n * - The signatures are all valid but do not meet the threshold.\n * @param challengeTx - SEP0010 challenge transaction in base64.\n * @param serverAccountID - The server's stellar account (public key).\n * @param networkPassphrase - The network passphrase, e.g.: 'Test SDF\n * Network ; September 2015' (see {@link Networks}).\n * @param threshold - The required signatures threshold for verifying\n * this transaction.\n * @param signerSummary - a map of all\n * authorized signers to their weights. It's used to validate if the\n * transaction signatures have met the given threshold.\n * @param homeDomains - The home domain(s) that should\n * be included in the first Manage Data operation's string key. Required in\n * `verifyChallengeTxSigners() => readChallengeTx()`.\n * @param webAuthDomain - The home domain that is expected to be included\n * as the value of the Manage Data operation with the 'web_auth_domain' key,\n * if present. Used in `verifyChallengeTxSigners() => readChallengeTx()`.\n * @returns The list of signers public keys that have signed\n * the transaction, excluding the server account ID, given that the threshold\n * was met.\n * @throws Will throw if the collective\n * weight of the transaction's signers does not meet the necessary threshold\n * to verify this transaction.\n * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth}\n * @example\n * ```ts\n * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk';\n *\n * const serverKP = Keypair.random();\n * const clientKP1 = Keypair.random();\n * const clientKP2 = Keypair.random();\n *\n * // Challenge, possibly built in the server side\n * const challenge = WebAuth.buildChallengeTx(\n * serverKP,\n * clientKP1.publicKey(),\n * \"SDF\",\n * 300,\n * Networks.TESTNET\n * );\n *\n * // clock.tick(200); // Simulates a 200 ms delay when communicating from server to client\n *\n * // Transaction gathered from a challenge, possibly from the client side\n * const transaction = TransactionBuilder.fromXDR(challenge, Networks.TESTNET);\n * transaction.sign(clientKP1, clientKP2);\n * const signedChallenge = transaction\n * .toEnvelope()\n * .toXDR(\"base64\")\n * .toString();\n *\n * // Defining the threshold and signerSummary\n * const threshold = 3;\n * const signerSummary = [\n * {\n * key: this.clientKP1.publicKey(),\n * weight: 1,\n * },\n * {\n * key: this.clientKP2.publicKey(),\n * weight: 2,\n * },\n * ];\n *\n * // The result below should be equal to [clientKP1.publicKey(), clientKP2.publicKey()]\n * WebAuth.verifyChallengeTxThreshold(\n * signedChallenge,\n * serverKP.publicKey(),\n * Networks.TESTNET,\n * threshold,\n * signerSummary\n * );\n * ```\n */\nexport function verifyChallengeTxThreshold(\n challengeTx: string,\n serverAccountID: string,\n networkPassphrase: string,\n threshold: number,\n signerSummary: ServerApi.AccountRecordSigners[],\n homeDomains: string | string[],\n webAuthDomain: string,\n): string[] {\n const signers = signerSummary.map((signer) => signer.key);\n\n const signersFound = verifyChallengeTxSigners(\n challengeTx,\n serverAccountID,\n networkPassphrase,\n signers,\n homeDomains,\n webAuthDomain,\n );\n\n let weight = 0;\n for (const signer of signersFound) {\n const sigWeight = signerSummary.find((s) => s.key === signer)?.weight || 0;\n weight += sigWeight;\n }\n\n if (weight < threshold) {\n throw new InvalidChallengeError(\n `signers with weight ${weight} do not meet threshold ${threshold}\"`,\n );\n }\n\n return sign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ACT;AA2FO,SAAS,2BACd,WAAA,EACA,eAAA,EACA,mBACA,SAAA,EACA,aAAA,EACA,aACA,aAAA,EACU;AACV,EAAA,MAAM,UAAU,aAAA,CAAc,GAAA,CAAI,CAAC,MAAA,KAAW,OAAO,GAAG,CAAA;AAExD,EAAA,MAAM,YAAA,GAAe,wBAAA;AAAA,IACnB,WAAA;AAAA,IACA,eAAA;AAAA,IACA,iBAAA;AAAA,IACA,OAAA;AAAA,IACA,WAAA;AAAA,IACA;AAAA,GACF;AAEA,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,KAAA,MAAW,UAAU,YAAA,EAAc;AACjC,IAAA,MAAM,SAAA,GAAY,cAAc,IAAA,CAAK,CAAC,MAAM,CAAA,CAAE,GAAA,KAAQ,MAAM,CAAA,EAAG,MAAA,IAAU,CAAA;AACzE,IAAA,MAAA,IAAU,SAAA;AAAA,EACZ;AAEA,EAAA,IAAI,SAAS,SAAA,EAAW;AACtB,IAAA,MAAM,IAAI,qBAAA;AAAA,MACR,CAAA,oBAAA,EAAuB,MAAM,CAAA,uBAAA,EAA0B,SAAS,CAAA,CAAA;AAAA,KAClE;AAAA,EACF;AAEA,EAAA,OAAO,YAAA;AACT;;;;"}
|
|
1
|
+
{"version":3,"file":"challenge_transaction.js","sources":["../../../../src/webauth/challenge_transaction.ts"],"sourcesContent":["import {\n Keypair,\n Account,\n TransactionBuilder,\n BASE_FEE,\n Operation,\n Memo,\n MemoNone,\n MemoID,\n FeeBumpTransaction,\n TimeoutInfinite,\n Transaction,\n Networks,\n} from \"../base/index.js\";\nimport { InvalidChallengeError } from \"./errors.js\";\nimport { gatherTxSigners, verifyTxSignedBy } from \"./utils.js\";\nimport { Utils } from \"../utils.js\";\nimport { ServerApi } from \"../horizon/server_api.js\";\nimport { uint8ArrayToBase64 } from \"uint8array-extras\";\n\n/**\n * Returns a valid {@link https://stellar.org/protocol/sep-10 | SEP-10}\n * challenge transaction which you can use for Stellar Web Authentication.\n * @param serverKeypair - Keypair for server's signing account.\n * @param clientAccountID - The stellar account (G...) or muxed account\n * (M...) that the wallet wishes to authenticate with the server.\n * @param homeDomain - The fully qualified domain name of the service\n * requiring authentication\n * @param timeout - Challenge duration (default to 5 minutes).\n * @param networkPassphrase - The network passphrase. If you pass this\n * argument then timeout is required.\n * @param webAuthDomain - The fully qualified domain name of the service\n * issuing the challenge.\n * @param memo - The memo to attach to the challenge transaction. The\n * memo must be of type `id`. If the `clientaccountID` is a muxed account,\n * memos cannot be used.\n * @param clientDomain - The fully qualified domain of the client\n * requesting the challenge. Only necessary when the 'client_domain'\n * parameter is passed.\n * @param clientSigningKey - The public key assigned to the SIGNING_KEY\n * attribute specified on the stellar.toml hosted on the client domain. Only\n * necessary when the 'client_domain' parameter is passed.\n * @returns A base64 encoded string of the raw TransactionEnvelope xdr\n * struct for the transaction.\n * @throws Will throw if `clientAccountID` is a muxed account, and `memo`\n * is present.\n * @throws Will throw if `clientDomain` is provided, but\n * `clientSigningKey` is missing\n * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth}\n * @example\n * ```ts\n * import { Keypair, Networks, WebAuth } from 'stellar-sdk'\n *\n * let serverKeyPair = Keypair.fromSecret(\"server-secret\")\n * let challenge = WebAuth.buildChallengeTx(\n * serverKeyPair,\n * \"client-stellar-account-id\",\n * \"stellar.org\",\n * 300,\n * Networks.TESTNET);\n * ```\n */\nexport function buildChallengeTx(\n serverKeypair: Keypair,\n clientAccountID: string,\n homeDomain: string,\n\n timeout: number = 300,\n networkPassphrase: string,\n webAuthDomain: string,\n memo: string | null = null,\n clientDomain: string | null = null,\n clientSigningKey: string | null = null,\n): string {\n if (clientAccountID.startsWith(\"M\") && memo) {\n throw Error(\"memo cannot be used if clientAccountID is a muxed account\");\n }\n\n const account = new Account(serverKeypair.publicKey(), \"-1\");\n const now = Math.floor(Date.now() / 1000);\n\n // A Base64 digit represents 6 bits, to generate a random 64 bytes\n // base64 string, we need 48 random bytes = (64 * 6)/8\n //\n // Each Base64 digit is in ASCII and each ASCII characters when\n // turned into binary represents 8 bits = 1 bytes.\n const value = uint8ArrayToBase64(crypto.getRandomValues(new Uint8Array(48)));\n\n const builder = new TransactionBuilder(account, {\n fee: BASE_FEE,\n networkPassphrase,\n timebounds: {\n minTime: now,\n maxTime: now + timeout,\n },\n })\n .addOperation(\n Operation.manageData({\n name: `${homeDomain} auth`,\n value,\n source: clientAccountID,\n }),\n )\n .addOperation(\n Operation.manageData({\n name: \"web_auth_domain\",\n value: webAuthDomain,\n source: account.accountId(),\n }),\n );\n\n if (clientDomain) {\n if (!clientSigningKey) {\n throw Error(\"clientSigningKey is required if clientDomain is provided\");\n }\n builder.addOperation(\n Operation.manageData({\n name: `client_domain`,\n value: clientDomain,\n source: clientSigningKey,\n }),\n );\n }\n\n if (memo) {\n builder.addMemo(Memo.id(memo));\n }\n\n const transaction = builder.build();\n transaction.sign(serverKeypair);\n\n return transaction.toEnvelope().toXDR(\"base64\").toString();\n}\n\n/**\n * Reads a SEP-10 challenge transaction and returns the decoded transaction and\n * client account ID contained within.\n *\n * It also verifies that the transaction has been signed by the server.\n *\n * It does not verify that the transaction has been signed by the client or that\n * any signatures other than the server's on the transaction are valid. Use one\n * of the following functions to completely verify the transaction:\n *\n * - {@link WebAuth.verifyChallengeTxThreshold}\n * - {@link WebAuth.verifyChallengeTxSigners}\n * @param challengeTx - SEP0010 challenge transaction in base64.\n * @param serverAccountID - The server's stellar account (public key).\n * @param networkPassphrase - The network passphrase, e.g.: 'Test SDF\n * Network ; September 2015' (see {@link Networks})\n * @param homeDomains - The home domain that is expected\n * to be included in the first Manage Data operation's string key. If an\n * array is provided, one of the domain names in the array must match.\n * @param webAuthDomain - The home domain that is expected to be included\n * as the value of the Manage Data operation with the 'web_auth_domain' key.\n * If no such operation is included, this parameter is not used.\n * @returns The actual transaction and the\n * Stellar public key (master key) used to sign the Manage Data operation,\n * the matched home domain, and the memo attached to the transaction, which\n * will be null if not present.\n * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth}\n */\nexport function readChallengeTx(\n challengeTx: string,\n serverAccountID: string,\n networkPassphrase: string,\n homeDomains: string | string[],\n webAuthDomain: string,\n): {\n tx: Transaction;\n clientAccountID: string;\n matchedHomeDomain: string;\n memo: string | null;\n} {\n if (serverAccountID.startsWith(\"M\")) {\n throw Error(\n \"Invalid serverAccountID: multiplexed accounts are not supported.\",\n );\n }\n\n let transaction;\n try {\n transaction = new Transaction(challengeTx, networkPassphrase);\n } catch {\n try {\n transaction = new FeeBumpTransaction(challengeTx, networkPassphrase);\n } catch {\n throw new InvalidChallengeError(\n \"Invalid challenge: unable to deserialize challengeTx transaction string\",\n );\n }\n throw new InvalidChallengeError(\n \"Invalid challenge: expected a Transaction but received a FeeBumpTransaction\",\n );\n }\n\n // verify sequence number\n const sequence = Number.parseInt(transaction.sequence, 10);\n\n if (sequence !== 0) {\n throw new InvalidChallengeError(\n \"The transaction sequence number should be zero\",\n );\n }\n\n // verify transaction source\n if (transaction.source !== serverAccountID) {\n throw new InvalidChallengeError(\n \"The transaction source account is not equal to the server's account\",\n );\n }\n\n // verify operation\n if (transaction.operations.length < 1) {\n throw new InvalidChallengeError(\n \"The transaction should contain at least one operation\",\n );\n }\n\n const [operation, ...subsequentOperations] = transaction.operations;\n\n if (!operation.source) {\n throw new InvalidChallengeError(\n \"The transaction's operation should contain a source account\",\n );\n }\n const clientAccountID: string = operation.source!;\n\n let memo: string | null = null;\n if (transaction.memo.type !== MemoNone) {\n if (clientAccountID.startsWith(\"M\")) {\n throw new InvalidChallengeError(\n \"The transaction has a memo but the client account ID is a muxed account\",\n );\n }\n if (transaction.memo.type !== MemoID) {\n throw new InvalidChallengeError(\n \"The transaction's memo must be of type `id`\",\n );\n }\n memo = transaction.memo.value as string;\n }\n\n if (operation.type !== \"manageData\") {\n throw new InvalidChallengeError(\n \"The transaction's operation type should be 'manageData'\",\n );\n }\n\n // verify timebounds\n if (\n transaction.timeBounds &&\n Number.parseInt(transaction.timeBounds?.maxTime, 10) === TimeoutInfinite\n ) {\n throw new InvalidChallengeError(\n \"The transaction requires non-infinite timebounds\",\n );\n }\n\n // give a small grace period for the transaction time to account for clock drift\n if (!Utils.validateTimebounds(transaction, 60 * 5)) {\n throw new InvalidChallengeError(\"The transaction has expired\");\n }\n\n if (operation.value === undefined) {\n throw new InvalidChallengeError(\n \"The transaction's operation values should not be null\",\n );\n }\n\n // verify base64\n if (!operation.value) {\n throw new InvalidChallengeError(\n \"The transaction's operation value should not be null\",\n );\n }\n\n if (Buffer.from(operation.value.toString(), \"base64\").length !== 48) {\n throw new InvalidChallengeError(\n \"The transaction's operation value should be a 64 bytes base64 random string\",\n );\n }\n\n // verify homeDomains\n if (!homeDomains) {\n throw new InvalidChallengeError(\n \"Invalid homeDomains: a home domain must be provided for verification\",\n );\n }\n\n let matchedHomeDomain;\n\n if (typeof homeDomains === \"string\") {\n if (`${homeDomains} auth` === operation.name) {\n matchedHomeDomain = homeDomains;\n }\n } else if (Array.isArray(homeDomains)) {\n matchedHomeDomain = homeDomains.find(\n (domain) => `${domain} auth` === operation.name,\n );\n } else {\n throw new InvalidChallengeError(\n `Invalid homeDomains: homeDomains type is ${typeof homeDomains} but should be a string or an array`,\n );\n }\n\n if (!matchedHomeDomain) {\n throw new InvalidChallengeError(\n \"Invalid homeDomains: the transaction's operation key name does not match the expected home domain\",\n );\n }\n\n // verify any subsequent operations are manage data ops and source account is the server\n for (const op of subsequentOperations) {\n if (op.type !== \"manageData\") {\n throw new InvalidChallengeError(\n \"The transaction has operations that are not of type 'manageData'\",\n );\n }\n if (op.source !== serverAccountID && op.name !== \"client_domain\") {\n throw new InvalidChallengeError(\n \"The transaction has operations that are unrecognized\",\n );\n }\n if (op.name === \"web_auth_domain\") {\n if (op.value === undefined) {\n throw new InvalidChallengeError(\n \"'web_auth_domain' operation value should not be null\",\n );\n }\n if (op.value.compare(Buffer.from(webAuthDomain))) {\n throw new InvalidChallengeError(\n `'web_auth_domain' operation value does not match ${webAuthDomain}`,\n );\n }\n }\n }\n\n if (!verifyTxSignedBy(transaction, serverAccountID)) {\n throw new InvalidChallengeError(\n `Transaction not signed by server: '${serverAccountID}'`,\n );\n }\n\n return { tx: transaction, clientAccountID, matchedHomeDomain, memo };\n}\n\n/**\n * Verifies that for a SEP 10 challenge transaction all signatures on the\n * transaction are accounted for. A transaction is verified if it is signed by\n * the server account, and all other signatures match a signer that has been\n * provided as an argument (as the accountIDs list). Additional signers can be\n * provided that do not have a signature, but all signatures must be matched to\n * a signer (accountIDs) for verification to succeed. If verification succeeds,\n * a list of signers that were found is returned, not including the server\n * account ID.\n *\n * Signers that are not prefixed as an address/account ID strkey (G...) will be\n * ignored.\n *\n * Errors will be raised if:\n * - The transaction is invalid according to\n * {@link WebAuth.readChallengeTx}.\n * - No client signatures are found on the transaction.\n * - One or more signatures in the transaction are not identifiable as the\n * server account or one of the signers provided in the arguments.\n * @param challengeTx - SEP0010 challenge transaction in base64.\n * @param serverAccountID - The server's stellar account (public key).\n * @param networkPassphrase - The network passphrase, e.g.: 'Test SDF\n * Network ; September 2015' (see {@link Networks}).\n * @param signers - The signers public keys. This list should\n * contain the public keys for all signers that have signed the transaction.\n * @param homeDomains - The home domain(s) that should\n * be included in the first Manage Data operation's string key. Required in\n * readChallengeTx().\n * @param webAuthDomain - The home domain that is expected to be included\n * as the value of the Manage Data operation with the 'web_auth_domain' key,\n * if present. Used in readChallengeTx().\n * @returns The list of signers public keys that have signed\n * the transaction, excluding the server account ID.\n * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth}\n * @example\n * ```ts\n * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk';\n *\n * const serverKP = Keypair.random();\n * const clientKP1 = Keypair.random();\n * const clientKP2 = Keypair.random();\n *\n * // Challenge, possibly built in the server side\n * const challenge = WebAuth.buildChallengeTx(\n * serverKP,\n * clientKP1.publicKey(),\n * \"SDF\",\n * 300,\n * Networks.TESTNET\n * );\n *\n * // clock.tick(200); // Simulates a 200 ms delay when communicating from server to client\n *\n * // Transaction gathered from a challenge, possibly from the client side\n * const transaction = TransactionBuilder.fromXDR(challenge, Networks.TESTNET);\n * transaction.sign(clientKP1, clientKP2);\n * const signedChallenge = transaction\n * .toEnvelope()\n * .toXDR(\"base64\")\n * .toString();\n *\n * // The result below should be equal to [clientKP1.publicKey(), clientKP2.publicKey()]\n * WebAuth.verifyChallengeTxSigners(\n * signedChallenge,\n * serverKP.publicKey(),\n * Networks.TESTNET,\n * threshold,\n * [clientKP1.publicKey(), clientKP2.publicKey()]\n * );\n * ```\n */\nexport function verifyChallengeTxSigners(\n challengeTx: string,\n serverAccountID: string,\n networkPassphrase: string,\n signers: string[],\n homeDomains: string | string[],\n webAuthDomain: string,\n): string[] {\n // Read the transaction which validates its structure.\n const { tx } = readChallengeTx(\n challengeTx,\n serverAccountID,\n networkPassphrase,\n homeDomains,\n webAuthDomain,\n );\n\n // Ensure the server account ID is an address and not a seed.\n let serverKP: Keypair;\n try {\n serverKP = Keypair.fromPublicKey(serverAccountID); // can throw 'Invalid Stellar public key'\n } catch (err: any) {\n throw new Error(\n `Couldn't infer keypair from the provided 'serverAccountID': ${\n err.message\n }`,\n );\n }\n\n // Deduplicate the client signers and ensure the server is not included\n // anywhere we check or output the list of signers.\n const clientSigners = new Set<string>();\n for (const signer of signers) {\n // Ignore the server signer if it is in the signers list. It's\n // important when verifying signers of a challenge transaction that we\n // only verify and return client signers. If an account has the server\n // as a signer the server should not play a part in the authentication\n // of the client.\n if (signer === serverKP.publicKey()) {\n continue;\n }\n\n // Ignore non-G... account/address signers.\n if (signer.charAt(0) !== \"G\") {\n continue;\n }\n\n clientSigners.add(signer);\n }\n\n // Don't continue if none of the signers provided are in the final list.\n if (clientSigners.size === 0) {\n throw new InvalidChallengeError(\n \"No verifiable client signers provided, at least one G... address must be provided\",\n );\n }\n\n let clientSigningKey;\n for (const op of tx.operations) {\n if (op.type === \"manageData\" && op.name === \"client_domain\") {\n if (clientSigningKey) {\n throw new InvalidChallengeError(\n \"Found more than one client_domain operation\",\n );\n }\n clientSigningKey = op.source;\n }\n }\n\n // Verify all the transaction's signers (server and client) in one\n // hit. We do this in one hit here even though the server signature was\n // checked in the ReadChallengeTx to ensure that every signature and signer\n // are consumed only once on the transaction.\n const allSigners: string[] = [\n serverKP.publicKey(),\n ...Array.from(clientSigners),\n ];\n if (clientSigningKey) {\n allSigners.push(clientSigningKey);\n }\n\n const signersFound: string[] = gatherTxSigners(tx, allSigners);\n\n let serverSignatureFound = false;\n let clientSigningKeySignatureFound = false;\n for (const signer of signersFound) {\n if (signer === serverKP.publicKey()) {\n serverSignatureFound = true;\n }\n if (signer === clientSigningKey) {\n clientSigningKeySignatureFound = true;\n }\n }\n\n // Confirm we matched a signature to the server signer.\n if (!serverSignatureFound) {\n throw new InvalidChallengeError(\n `Transaction not signed by server: '${serverKP.publicKey()}'`,\n );\n }\n\n // Confirm we matched a signature to the client domain's signer\n if (clientSigningKey && !clientSigningKeySignatureFound) {\n throw new InvalidChallengeError(\n \"Transaction not signed by the source account of the 'client_domain' \" +\n \"ManageData operation\",\n );\n }\n\n // Confirm we matched at least one given signer with the transaction signatures\n if (signersFound.length === 1) {\n throw new InvalidChallengeError(\n \"None of the given signers match the transaction signatures\",\n );\n }\n\n // Confirm all signatures, including the server signature, were consumed by a signer:\n if (signersFound.length !== tx.signatures.length) {\n throw new InvalidChallengeError(\"Transaction has unrecognized signatures\");\n }\n\n // Remove the server public key before returning\n signersFound.splice(signersFound.indexOf(serverKP.publicKey()), 1);\n if (clientSigningKey) {\n // Remove the client domain public key public key before returning\n signersFound.splice(signersFound.indexOf(clientSigningKey), 1);\n }\n\n if (signersFound.length === 0) {\n throw new InvalidChallengeError(\n \"None of the given signers match the transaction signatures\",\n );\n }\n\n return signersFound;\n}\n\n/**\n * Verifies that for a SEP-10 challenge transaction all signatures on the\n * transaction are accounted for and that the signatures meet a threshold on an\n * account. A transaction is verified if it is signed by the server account, and\n * all other signatures match a signer that has been provided as an argument,\n * and those signatures meet a threshold on the account.\n *\n * Signers that are not prefixed as an address/account ID strkey (G...) will be\n * ignored.\n *\n * Errors will be raised if:\n * - The transaction is invalid according to\n * {@link WebAuth.readChallengeTx}.\n * - No client signatures are found on the transaction.\n * - One or more signatures in the transaction are not identifiable as the\n * server account or one of the signers provided in the arguments.\n * - The signatures are all valid but do not meet the threshold.\n * @param challengeTx - SEP0010 challenge transaction in base64.\n * @param serverAccountID - The server's stellar account (public key).\n * @param networkPassphrase - The network passphrase, e.g.: 'Test SDF\n * Network ; September 2015' (see {@link Networks}).\n * @param threshold - The required signatures threshold for verifying\n * this transaction.\n * @param signerSummary - a map of all\n * authorized signers to their weights. It's used to validate if the\n * transaction signatures have met the given threshold.\n * @param homeDomains - The home domain(s) that should\n * be included in the first Manage Data operation's string key. Required in\n * `verifyChallengeTxSigners() => readChallengeTx()`.\n * @param webAuthDomain - The home domain that is expected to be included\n * as the value of the Manage Data operation with the 'web_auth_domain' key,\n * if present. Used in `verifyChallengeTxSigners() => readChallengeTx()`.\n * @returns The list of signers public keys that have signed\n * the transaction, excluding the server account ID, given that the threshold\n * was met.\n * @throws Will throw if the collective\n * weight of the transaction's signers does not meet the necessary threshold\n * to verify this transaction.\n * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth}\n * @example\n * ```ts\n * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk';\n *\n * const serverKP = Keypair.random();\n * const clientKP1 = Keypair.random();\n * const clientKP2 = Keypair.random();\n *\n * // Challenge, possibly built in the server side\n * const challenge = WebAuth.buildChallengeTx(\n * serverKP,\n * clientKP1.publicKey(),\n * \"SDF\",\n * 300,\n * Networks.TESTNET\n * );\n *\n * // clock.tick(200); // Simulates a 200 ms delay when communicating from server to client\n *\n * // Transaction gathered from a challenge, possibly from the client side\n * const transaction = TransactionBuilder.fromXDR(challenge, Networks.TESTNET);\n * transaction.sign(clientKP1, clientKP2);\n * const signedChallenge = transaction\n * .toEnvelope()\n * .toXDR(\"base64\")\n * .toString();\n *\n * // Defining the threshold and signerSummary\n * const threshold = 3;\n * const signerSummary = [\n * {\n * key: this.clientKP1.publicKey(),\n * weight: 1,\n * },\n * {\n * key: this.clientKP2.publicKey(),\n * weight: 2,\n * },\n * ];\n *\n * // The result below should be equal to [clientKP1.publicKey(), clientKP2.publicKey()]\n * WebAuth.verifyChallengeTxThreshold(\n * signedChallenge,\n * serverKP.publicKey(),\n * Networks.TESTNET,\n * threshold,\n * signerSummary\n * );\n * ```\n */\nexport function verifyChallengeTxThreshold(\n challengeTx: string,\n serverAccountID: string,\n networkPassphrase: string,\n threshold: number,\n signerSummary: ServerApi.AccountRecordSigners[],\n homeDomains: string | string[],\n webAuthDomain: string,\n): string[] {\n const signers = signerSummary.map((signer) => signer.key);\n\n const signersFound = verifyChallengeTxSigners(\n challengeTx,\n serverAccountID,\n networkPassphrase,\n signers,\n homeDomains,\n webAuthDomain,\n );\n\n let weight = 0;\n for (const signer of signersFound) {\n const sigWeight = signerSummary.find((s) => s.key === signer)?.weight || 0;\n weight += sigWeight;\n }\n\n if (weight < threshold) {\n throw new InvalidChallengeError(\n `signers with weight ${weight} do not meet threshold ${threshold}\"`,\n );\n }\n\n return signersFound;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;AA8DO,SAAS,gBAAA,CACd,aAAA,EACA,eAAA,EACA,UAAA,EAEA,OAAA,GAAkB,GAAA,EAClB,iBAAA,EACA,aAAA,EACA,IAAA,GAAsB,IAAA,EACtB,YAAA,GAA8B,IAAA,EAC9B,mBAAkC,IAAA,EAC1B;AACR,EAAA,IAAI,eAAA,CAAgB,UAAA,CAAW,GAAG,CAAA,IAAK,IAAA,EAAM;AAC3C,IAAA,MAAM,MAAM,2DAA2D,CAAA;AAAA,EACzE;AAEA,EAAA,MAAM,UAAU,IAAI,OAAA,CAAQ,aAAA,CAAc,SAAA,IAAa,IAAI,CAAA;AAC3D,EAAA,MAAM,MAAM,IAAA,CAAK,KAAA,CAAM,IAAA,CA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A,IAAU,CAAA;AACzE,IAAA,MAAA,IAAU,SAAA;AAAA,EACZ;AAEA,EAAA,IAAI,SAAS,SAAA,EAAW;AACtB,IAAA,MAAM,IAAI,qBAAA;AAAA,MACR,CAAA,oBAAA,EAAuB,MAAM,CAAA,uBAAA,EAA0B,SAAS,CAAA,CAAA;AAAA,KAClE;AAAA,EACF;AAEA,EAAA,OAAO,YAAA;AACT;;;;"}
|
|
@@ -1,24 +1,5 @@
|
|
|
1
|
-
import '../node_modules/.pnpm/@stellar_js-xdr@4.0.0/node_modules/@stellar/js-xdr/src/int.js';
|
|
2
|
-
import '../node_modules/.pnpm/@stellar_js-xdr@4.0.0/node_modules/@stellar/js-xdr/src/hyper.js';
|
|
3
|
-
import '../node_modules/.pnpm/@stellar_js-xdr@4.0.0/node_modules/@stellar/js-xdr/src/unsigned-int.js';
|
|
4
|
-
import '../node_modules/.pnpm/@stellar_js-xdr@4.0.0/node_modules/@stellar/js-xdr/src/unsigned-hyper.js';
|
|
5
|
-
import '../node_modules/.pnpm/@stellar_js-xdr@4.0.0/node_modules/@stellar/js-xdr/src/xdr-type.js';
|
|
6
|
-
import 'buffer';
|
|
7
|
-
import '../base/generated/curr_generated.js';
|
|
8
|
-
import '@noble/hashes/sha2.js';
|
|
9
|
-
import '../base/signing.js';
|
|
10
|
-
import { Keypair } from '../base/keypair.js';
|
|
11
|
-
import 'base32.js';
|
|
12
|
-
import '../base/util/continued_fraction.js';
|
|
13
|
-
import '../base/util/bignumber.js';
|
|
14
|
-
import '../base/transaction_builder.js';
|
|
15
|
-
import '../base/muxed_account.js';
|
|
16
|
-
import '../base/scval.js';
|
|
17
|
-
import '../base/numbers/uint128.js';
|
|
18
|
-
import '../base/numbers/uint256.js';
|
|
19
|
-
import '../base/numbers/int128.js';
|
|
20
|
-
import '../base/numbers/int256.js';
|
|
21
1
|
import { InvalidChallengeError } from './errors.js';
|
|
2
|
+
import { Keypair } from '../base/keypair.js';
|
|
22
3
|
|
|
23
4
|
function gatherTxSigners(transaction, signers) {
|
|
24
5
|
const hashedSignatureBase = transaction.hash();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sources":["../../../../src/webauth/utils.ts"],"sourcesContent":["/**\n * Stellar Web Authentication\n * @see {@link https://stellar.org/protocol-10 | SEP-10 Specification}\n */\n\nimport { FeeBumpTransaction, Keypair, Transaction } from \"../base/index.js\";\nimport { InvalidChallengeError } from \"./errors.js\";\n/**\n * Checks if a transaction has been signed by one or more of the given signers,\n * returning a list of non-repeated signers that were found to have signed the\n * given transaction.\n *\n * @param transaction - The signed transaction.\n * @param signers - The signer's public keys.\n * @returns A list of signers that were found to have signed\n * the transaction.\n *\n * @example\n * ```ts\n * let keypair1 = Keypair.random();\n * let keypair2 = Keypair.random();\n * const account = new StellarSdk.Account(keypair1.publicKey(), \"-1\");\n *\n * const transaction = new TransactionBuilder(account, { fee: 100 })\n * .setTimeout(30)\n * .build();\n *\n * transaction.sign(keypair1, keypair2)\n * WebAuth.gatherTxSigners(transaction, [keypair1.publicKey(), keypair2.publicKey()])\n * ```\n */\nexport function gatherTxSigners(\n transaction: FeeBumpTransaction | Transaction,\n signers: string[],\n): string[] {\n const hashedSignatureBase = transaction.hash();\n\n const txSignatures = [...transaction.signatures]; // shallow copy for safe splicing\n const signersFound = new Set<string>();\n\n for (const signer of signers) {\n if (txSignatures.length === 0) {\n break;\n }\n\n let keypair: Keypair;\n try {\n keypair = Keypair.fromPublicKey(signer); // This can throw a few different errors\n } catch (err: any) {\n throw new InvalidChallengeError(\n `Signer is not a valid address: ${err.message}`,\n );\n }\n\n for (let i = 0; i < txSignatures.length; i++) {\n const decSig = txSignatures[i];\n\n if (!decSig.hint().equals(keypair.signatureHint())) {\n continue;\n }\n\n if (keypair.verify(hashedSignatureBase, decSig.signature())) {\n signersFound.add(signer);\n txSignatures.splice(i, 1);\n break;\n }\n }\n }\n\n return Array.from(signersFound);\n}\n\n/**\n * Verifies if a transaction was signed by the given account id.\n *\n * @param transaction - The signed transaction.\n * @param accountID - The signer's public key.\n * @returns Whether or not `accountID` was found to have signed the\n * transaction.\n *\n * @example\n * ```ts\n * let keypair = Keypair.random();\n * const account = new StellarSdk.Account(keypair.publicKey(), \"-1\");\n *\n * const transaction = new TransactionBuilder(account, { fee: 100 })\n * .setTimeout(30)\n * .build();\n *\n * transaction.sign(keypair)\n * WebAuth.verifyTxSignedBy(transaction, keypair.publicKey())\n * ```\n */\nexport function verifyTxSignedBy(\n transaction: FeeBumpTransaction | Transaction,\n accountID: string,\n): boolean {\n return gatherTxSigners(transaction, [accountID]).length !== 0;\n}\n\n/**\n * A parsed and validated challenge transaction, and some of its constituent details.\n */\nexport type ChallengeTxDetails = {\n /** The challenge transaction. */\n tx: Transaction;\n /** The Stellar public key (master key) used to sign the Manage Data operation. */\n clientAccountId: string;\n /** The matched home domain. */\n matchedHomeDomain: string;\n /** The memo attached to the transaction, which will be null if not present */\n memo?: string;\n};\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../../../src/webauth/utils.ts"],"sourcesContent":["/**\n * Stellar Web Authentication\n * @see {@link https://stellar.org/protocol-10 | SEP-10 Specification}\n */\n\nimport { FeeBumpTransaction, Keypair, Transaction } from \"../base/index.js\";\nimport { InvalidChallengeError } from \"./errors.js\";\n/**\n * Checks if a transaction has been signed by one or more of the given signers,\n * returning a list of non-repeated signers that were found to have signed the\n * given transaction.\n *\n * @param transaction - The signed transaction.\n * @param signers - The signer's public keys.\n * @returns A list of signers that were found to have signed\n * the transaction.\n *\n * @example\n * ```ts\n * let keypair1 = Keypair.random();\n * let keypair2 = Keypair.random();\n * const account = new StellarSdk.Account(keypair1.publicKey(), \"-1\");\n *\n * const transaction = new TransactionBuilder(account, { fee: 100 })\n * .setTimeout(30)\n * .build();\n *\n * transaction.sign(keypair1, keypair2)\n * WebAuth.gatherTxSigners(transaction, [keypair1.publicKey(), keypair2.publicKey()])\n * ```\n */\nexport function gatherTxSigners(\n transaction: FeeBumpTransaction | Transaction,\n signers: string[],\n): string[] {\n const hashedSignatureBase = transaction.hash();\n\n const txSignatures = [...transaction.signatures]; // shallow copy for safe splicing\n const signersFound = new Set<string>();\n\n for (const signer of signers) {\n if (txSignatures.length === 0) {\n break;\n }\n\n let keypair: Keypair;\n try {\n keypair = Keypair.fromPublicKey(signer); // This can throw a few different errors\n } catch (err: any) {\n throw new InvalidChallengeError(\n `Signer is not a valid address: ${err.message}`,\n );\n }\n\n for (let i = 0; i < txSignatures.length; i++) {\n const decSig = txSignatures[i];\n\n if (!decSig.hint().equals(keypair.signatureHint())) {\n continue;\n }\n\n if (keypair.verify(hashedSignatureBase, decSig.signature())) {\n signersFound.add(signer);\n txSignatures.splice(i, 1);\n break;\n }\n }\n }\n\n return Array.from(signersFound);\n}\n\n/**\n * Verifies if a transaction was signed by the given account id.\n *\n * @param transaction - The signed transaction.\n * @param accountID - The signer's public key.\n * @returns Whether or not `accountID` was found to have signed the\n * transaction.\n *\n * @example\n * ```ts\n * let keypair = Keypair.random();\n * const account = new StellarSdk.Account(keypair.publicKey(), \"-1\");\n *\n * const transaction = new TransactionBuilder(account, { fee: 100 })\n * .setTimeout(30)\n * .build();\n *\n * transaction.sign(keypair)\n * WebAuth.verifyTxSignedBy(transaction, keypair.publicKey())\n * ```\n */\nexport function verifyTxSignedBy(\n transaction: FeeBumpTransaction | Transaction,\n accountID: string,\n): boolean {\n return gatherTxSigners(transaction, [accountID]).length !== 0;\n}\n\n/**\n * A parsed and validated challenge transaction, and some of its constituent details.\n */\nexport type ChallengeTxDetails = {\n /** The challenge transaction. */\n tx: Transaction;\n /** The Stellar public key (master key) used to sign the Manage Data operation. */\n clientAccountId: string;\n /** The matched home domain. */\n matchedHomeDomain: string;\n /** The memo attached to the transaction, which will be null if not present */\n memo?: string;\n};\n"],"names":[],"mappings":";;;AA+BO,SAAS,eAAA,CACd,aACA,OAAA,EACU;AACV,EAAA,MAAM,mBAAA,GAAsB,YAAY,IAAA,EAAK;AAE7C,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
31
31
|
networkPassphrase
|
|
32
32
|
);
|
|
33
33
|
const payload = hashing.hash(preimage.toXDR());
|
|
34
|
-
let
|
|
35
|
-
let
|
|
34
|
+
let signatureScVal;
|
|
35
|
+
let targetAddress = forAddress;
|
|
36
|
+
let sigResult = null;
|
|
36
37
|
if (typeof signer === "function") {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
signature = toBuffer(sigResult);
|
|
43
|
-
publicKey = address.Address.fromScAddress(addrAuth.address()).toString();
|
|
44
|
-
}
|
|
38
|
+
sigResult = await signer(preimage, buffer.Buffer.from(payload));
|
|
39
|
+
}
|
|
40
|
+
if (sigResult !== null && typeof sigResult === "object" && "signatureScVal" in sigResult) {
|
|
41
|
+
signatureScVal = sigResult.signatureScVal;
|
|
42
|
+
targetAddress ??= sigResult.address;
|
|
45
43
|
} else {
|
|
46
|
-
signature
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
signature
|
|
56
|
-
},
|
|
57
|
-
{
|
|
58
|
-
type: {
|
|
59
|
-
public_key: ["symbol", null],
|
|
60
|
-
signature: ["symbol", null]
|
|
44
|
+
let signature;
|
|
45
|
+
let publicKey;
|
|
46
|
+
if (typeof signer === "function") {
|
|
47
|
+
if (sigResult !== null && typeof sigResult === "object" && "signature" in sigResult) {
|
|
48
|
+
signature = toBuffer(sigResult.signature);
|
|
49
|
+
publicKey = sigResult.publicKey;
|
|
50
|
+
} else {
|
|
51
|
+
signature = toBuffer(sigResult);
|
|
52
|
+
publicKey = address.Address.fromScAddress(addrAuth.address()).toString();
|
|
61
53
|
}
|
|
54
|
+
} else {
|
|
55
|
+
signature = toBuffer(signer.sign(payload));
|
|
56
|
+
publicKey = signer.publicKey();
|
|
62
57
|
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
58
|
+
if (!keypair.Keypair.fromPublicKey(publicKey).verify(payload, signature)) {
|
|
59
|
+
throw new Error(`signature doesn't match payload`);
|
|
60
|
+
}
|
|
61
|
+
const sigScVal = scval.nativeToScVal(
|
|
62
|
+
{
|
|
63
|
+
public_key: strkey.StrKey.decodeEd25519PublicKey(publicKey),
|
|
64
|
+
signature
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
type: {
|
|
68
|
+
public_key: ["symbol", null],
|
|
69
|
+
signature: ["symbol", null]
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
);
|
|
73
|
+
signatureScVal = curr_generated.default.ScVal.scvVec([sigScVal]);
|
|
74
|
+
}
|
|
75
|
+
const targets = targetAddress === void 0 ? [addrAuth] : collectSignatureNodes(credentials).filter(
|
|
76
|
+
(node) => address.Address.fromScAddress(node.address()).toString() === targetAddress
|
|
67
77
|
);
|
|
68
78
|
if (targets.length === 0) {
|
|
69
79
|
throw new Error(
|
|
70
|
-
`the authorization entry has no credential node for address ${
|
|
80
|
+
`the authorization entry has no credential node for address ${targetAddress}`
|
|
71
81
|
);
|
|
72
82
|
}
|
|
73
83
|
targets.forEach((node) => node.signature(signatureScVal));
|
|
@@ -224,6 +234,111 @@ function collectSignatureNodes(credentials) {
|
|
|
224
234
|
return [];
|
|
225
235
|
}
|
|
226
236
|
}
|
|
237
|
+
function inspectAuthEntry(entry) {
|
|
238
|
+
const credentials = entry.credentials();
|
|
239
|
+
const addrAuth = getAddressCredentials(credentials);
|
|
240
|
+
let credentialType;
|
|
241
|
+
switch (credentials.switch().value) {
|
|
242
|
+
case curr_generated.default.SorobanCredentialsType.sorobanCredentialsSourceAccount().value:
|
|
243
|
+
credentialType = "sourceAccount";
|
|
244
|
+
break;
|
|
245
|
+
case curr_generated.default.SorobanCredentialsType.sorobanCredentialsAddress().value:
|
|
246
|
+
credentialType = "address";
|
|
247
|
+
break;
|
|
248
|
+
case curr_generated.default.SorobanCredentialsType.sorobanCredentialsAddressV2().value:
|
|
249
|
+
credentialType = "addressV2";
|
|
250
|
+
break;
|
|
251
|
+
case curr_generated.default.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value:
|
|
252
|
+
credentialType = "addressWithDelegates";
|
|
253
|
+
break;
|
|
254
|
+
default:
|
|
255
|
+
throw new Error(
|
|
256
|
+
`unsupported credential type ${credentials.switch().name}`
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
const signers = collectSignatureNodes(credentials).map(
|
|
260
|
+
(node) => {
|
|
261
|
+
const rawSignature = node.signature();
|
|
262
|
+
return {
|
|
263
|
+
address: address.Address.fromScAddress(node.address()).toString(),
|
|
264
|
+
signed: signaturePresent(rawSignature),
|
|
265
|
+
signatures: parseEd25519Signatures(rawSignature),
|
|
266
|
+
rawSignature
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
);
|
|
270
|
+
return {
|
|
271
|
+
credentialType,
|
|
272
|
+
address: addrAuth === null ? null : address.Address.fromScAddress(addrAuth.address()).toString(),
|
|
273
|
+
nonce: addrAuth === null ? null : addrAuth.nonce().toBigInt(),
|
|
274
|
+
signatureExpirationLedger: addrAuth === null ? null : addrAuth.signatureExpirationLedger(),
|
|
275
|
+
signers,
|
|
276
|
+
signed: signers.length > 0 && signers.every((signer) => signer.signed),
|
|
277
|
+
invocation: entry.rootInvocation()
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
function checkAuthEntryReadiness(entry, currentLedgerSeq) {
|
|
281
|
+
if (!Number.isInteger(currentLedgerSeq) || currentLedgerSeq < 0 || currentLedgerSeq > 4294967295) {
|
|
282
|
+
throw new Error(
|
|
283
|
+
`currentLedgerSeq must be a uint32 ledger sequence, got ${currentLedgerSeq}`
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
const info = inspectAuthEntry(entry);
|
|
287
|
+
if (info.credentialType === "sourceAccount") {
|
|
288
|
+
return { ready: true, expired: false, unsignedBy: [] };
|
|
289
|
+
}
|
|
290
|
+
const expired = currentLedgerSeq >= (info.signatureExpirationLedger ?? 0);
|
|
291
|
+
const unsignedBy = info.signers.filter((signer) => !signer.signed).map((signer) => signer.address);
|
|
292
|
+
return { ready: !expired && unsignedBy.length === 0, expired, unsignedBy };
|
|
293
|
+
}
|
|
294
|
+
function signaturePresent(signature) {
|
|
295
|
+
switch (signature.switch().value) {
|
|
296
|
+
case curr_generated.default.ScValType.scvVoid().value:
|
|
297
|
+
return false;
|
|
298
|
+
case curr_generated.default.ScValType.scvVec().value:
|
|
299
|
+
return (signature.vec() ?? []).length > 0;
|
|
300
|
+
default:
|
|
301
|
+
return true;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
function parseEd25519Signatures(signature) {
|
|
305
|
+
if (signature.switch().value !== curr_generated.default.ScValType.scvVec().value) {
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
const parsed = [];
|
|
309
|
+
for (const element of signature.vec() ?? []) {
|
|
310
|
+
if (element.switch().value !== curr_generated.default.ScValType.scvMap().value) {
|
|
311
|
+
return null;
|
|
312
|
+
}
|
|
313
|
+
let publicKey = null;
|
|
314
|
+
let sig = null;
|
|
315
|
+
for (const mapEntry of element.map() ?? []) {
|
|
316
|
+
const key = mapEntry.key();
|
|
317
|
+
const val = mapEntry.val();
|
|
318
|
+
if (key.switch().value !== curr_generated.default.ScValType.scvSymbol().value || val.switch().value !== curr_generated.default.ScValType.scvBytes().value) {
|
|
319
|
+
return null;
|
|
320
|
+
}
|
|
321
|
+
switch (key.sym().toString()) {
|
|
322
|
+
case "public_key":
|
|
323
|
+
publicKey = val.bytes();
|
|
324
|
+
break;
|
|
325
|
+
case "signature":
|
|
326
|
+
sig = val.bytes();
|
|
327
|
+
break;
|
|
328
|
+
default:
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
if (publicKey === null || sig === null || publicKey.length !== 32 || sig.length !== 64) {
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
parsed.push({
|
|
336
|
+
publicKey: strkey.StrKey.encodeEd25519PublicKey(publicKey),
|
|
337
|
+
signature: sig
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
return parsed;
|
|
341
|
+
}
|
|
227
342
|
function bytesToInt64(bytes) {
|
|
228
343
|
const buf = bytes.subarray(0, 8);
|
|
229
344
|
if (buf.length < 8) {
|
|
@@ -240,5 +355,7 @@ exports.authorizeEntry = authorizeEntry;
|
|
|
240
355
|
exports.authorizeInvocation = authorizeInvocation;
|
|
241
356
|
exports.buildAuthorizationEntryPreimage = buildAuthorizationEntryPreimage;
|
|
242
357
|
exports.buildWithDelegatesEntry = buildWithDelegatesEntry;
|
|
358
|
+
exports.checkAuthEntryReadiness = checkAuthEntryReadiness;
|
|
243
359
|
exports.getAddressCredentials = getAddressCredentials;
|
|
360
|
+
exports.inspectAuthEntry = inspectAuthEntry;
|
|
244
361
|
//# sourceMappingURL=auth.js.map
|
package/lib/cjs/base/auth.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.js","sources":["../../../src/base/auth.ts"],"sourcesContent":["import xdr from \"./xdr.js\";\n\nimport { Keypair } from \"./keypair.js\";\nimport { StrKey } from \"./strkey.js\";\n\nimport type { Networks } from \"./network.js\";\nimport { hash } from \"./hashing.js\";\n\nimport { Address } from \"./address.js\";\nimport { nativeToScVal } from \"./scval.js\";\n\ntype BufferLike = ArrayBuffer | Buffer | Uint8Array;\n\nfunction toBuffer(value: BufferLike): Buffer {\n if (value instanceof ArrayBuffer) {\n return Buffer.from(new Uint8Array(value));\n }\n return Buffer.from(value);\n}\n\n/**\n * A callback for signing an XDR structure representing all of the details\n * necessary to authorize an invocation tree.\n *\n * @param preimage - the entire authorization envelope whose hash you should\n * sign, so that you can inspect the entire structure if necessary (rather\n * than blindly signing a hash)\n *\n * @returns the signature of the raw payload (which is the sha256 hash of the\n * preimage bytes, so `hash(preimage.toXDR())`) either naked, implying it is\n * signed by the key corresponding to the public key in the entry you pass to\n * {@link authorizeEntry} (decipherable from its\n * `credentials().address().address()`), or alongside an explicit `publicKey`.\n */\nexport type SigningCallback = (\n preimage: xdr.HashIdPreimage,\n) => Promise<BufferLike | { signature: BufferLike; publicKey: string }>;\n\n/**\n * Actually authorizes an existing authorization entry using the given\n * credentials and expiration details, returning a signed copy.\n *\n * This \"fills out\" the authorization entry with a signature, indicating to the\n * {@link Operation.invokeHostFunction} its attached to that:\n * - a particular identity (i.e. signing {@link Keypair} or other signer)\n * - approving the execution of an invocation tree (i.e. a simulation-acquired\n * {@link xdr.SorobanAuthorizedInvocation} or otherwise built)\n * - on a particular network (uniquely identified by its passphrase, see\n * {@link Networks})\n * - until a particular ledger sequence is reached.\n *\n * This one lets you pass either a {@link Keypair} (or, more accurately,\n * anything with a `sign(Buffer): Buffer` method) or a callback function (see\n * {@link SigningCallback}) to handle signing the envelope hash.\n *\n * @param entry - an unsigned authorization entry\n * @param signer - either a {@link Keypair} instance or a function which takes a\n * {@link xdr.HashIdPreimageSorobanAuthorization} input payload and returns\n * EITHER\n *\n * (a) an object containing a `signature` of the hash of the raw payload\n * bytes as a Buffer-like and a `publicKey` string representing who just\n * created this signature, or\n * (b) just the naked signature of the hash of the raw payload bytes (where\n * the signing key is implied to be the address in the `entry`).\n *\n * The latter option (b) is JUST for backwards compatibility and will be\n * removed in the future.\n * @param validUntilLedgerSeq - the (exclusive) future ledger sequence number\n * until which this authorization entry should be valid (if\n * `currentLedgerSeq==validUntil`, this is expired)\n * @param networkPassphrase - the network passphrase is incorporated into the\n * signature (see {@link Networks} for options)\n *\n * If using the `SigningCallback` variation, the signer is assumed to be\n * the entry's credential address unless you use the variant that returns\n * the object.\n *\n * @param forAddress - which credential node the signature should be written\n * to. Only relevant for `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES`, where\n * a single entry can be signed by the top-level account and/or any of its\n * (possibly nested) delegates. Per CAP-71-01 every one of these signers\n * signs the *same* payload (bound to the top-level address), so the\n * signature produced here is written to whichever node(s) carry\n * `forAddress`. When omitted, the signature is written to the top-level\n * credentials, which preserves the behavior for `SOROBAN_CREDENTIALS_ADDRESS`\n * / `SOROBAN_CREDENTIALS_ADDRESS_V2` and for accounts whose signing key\n * differs from the credential address (e.g. multisig).\n *\n * @see authorizeInvocation\n * @example\n * ```ts\n * import {\n * SorobanRpc,\n * Transaction,\n * Networks,\n * authorizeEntry\n * } from '@stellar/stellar-sdk';\n *\n * // Assume signPayloadCallback is a well-formed signing callback.\n * //\n * // It might, for example, pop up a modal from a browser extension, send the\n * // transaction to a third-party service for signing, or just do simple\n * // signing via Keypair like it does here:\n * function signPayloadCallback(payload) {\n * return signer.sign(hash(payload.toXDR()));\n * }\n *\n * function multiPartyAuth(\n * server: SorobanRpc.Server,\n * // assume this involves multi-party auth\n * tx: Transaction,\n * ) {\n * return server\n * .simulateTransaction(tx)\n * .then((simResult) => {\n * tx.operations[0].auth.map(entry =>\n * authorizeEntry(\n * entry,\n * signPayloadCallback,\n * currentLedger + 1000,\n * Networks.TESTNET)\n * );\n *\n * return server.prepareTransaction(tx, simResult);\n * })\n * .then((preppedTx) => {\n * preppedTx.sign(source);\n * return server.sendTransaction(preppedTx);\n * });\n * }\n * ```\n */\nexport async function authorizeEntry(\n entry: xdr.SorobanAuthorizationEntry,\n signer: Keypair | SigningCallback,\n validUntilLedgerSeq: number,\n networkPassphrase: string,\n forAddress?: string,\n): Promise<xdr.SorobanAuthorizationEntry> {\n // no-op if it's source account auth\n if (\n entry.credentials().switch().value ===\n xdr.SorobanCredentialsType.sorobanCredentialsSourceAccount().value\n ) {\n return entry;\n }\n\n const clone = xdr.SorobanAuthorizationEntry.fromXDR(entry.toXDR());\n const credentials = clone.credentials();\n const addrAuth = getAddressCredentials(credentials);\n if (addrAuth === null) {\n // We should have already returned if the credentials were source account credentials,\n // so if we can't get address credentials out of this, it's an unsupported credential type.\n throw new Error(`unsupported credential type ${credentials.switch().name}`);\n }\n\n // Set the expiration before building the preimage, so the hash that gets\n // signed commits to the same expiration ledger stored in the credentials.\n // Otherwise the network reconstructs the preimage from the (updated)\n // credentials and the signature no longer matches.\n addrAuth.signatureExpirationLedger(validUntilLedgerSeq);\n\n const preimage = buildAuthorizationEntryPreimage(\n clone,\n validUntilLedgerSeq,\n networkPassphrase,\n );\n\n const payload = hash(preimage.toXDR());\n\n let signature: Buffer;\n let publicKey: string;\n if (typeof signer === \"function\") {\n const sigResult = await signer(preimage);\n if (\n sigResult !== null &&\n typeof sigResult === \"object\" &&\n \"signature\" in sigResult\n ) {\n signature = toBuffer(sigResult.signature);\n publicKey = sigResult.publicKey;\n } else {\n // if using the deprecated form, assume it's for the entry\n signature = toBuffer(sigResult);\n publicKey = Address.fromScAddress(addrAuth.address()).toString();\n }\n } else {\n signature = toBuffer(signer.sign(payload));\n publicKey = signer.publicKey();\n }\n\n if (!Keypair.fromPublicKey(publicKey).verify(payload, signature)) {\n throw new Error(`signature doesn't match payload`);\n }\n\n // This structure is defined here:\n // https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#stellar-account-signatures\n //\n // Encoding a contract structure as an ScVal means the map keys are supposed\n // to be symbols, hence the forced typing here.\n const sigScVal = nativeToScVal(\n {\n public_key: StrKey.decodeEd25519PublicKey(publicKey),\n signature,\n },\n {\n type: {\n public_key: [\"symbol\", null],\n signature: [\"symbol\", null],\n },\n },\n );\n\n const signatureScVal = xdr.ScVal.scvVec([sigScVal]);\n\n // CAP-71-01: the signature payload is shared across the top-level address\n // and every (possibly nested) delegate, so this signer's signature is\n // written to whichever credential node(s) carry `forAddress`. When no\n // `forAddress` is given we fall back to the top-level credentials, which\n // preserves the behavior for ADDRESS / ADDRESS_V2 and for accounts whose\n // signing key differs from the credential address (e.g. multisig).\n const targets: SignableCredential[] =\n forAddress === undefined\n ? [addrAuth]\n : collectSignatureNodes(credentials).filter(\n (node) =>\n Address.fromScAddress(node.address()).toString() === forAddress,\n );\n\n if (targets.length === 0) {\n throw new Error(\n `the authorization entry has no credential node for address ${forAddress}`,\n );\n }\n\n targets.forEach((node) => node.signature(signatureScVal));\n return clone;\n}\n\nexport interface AuthorizeInvocationParams {\n signer: Keypair | SigningCallback;\n validUntilLedgerSeq: number;\n invocation: xdr.SorobanAuthorizedInvocation;\n networkPassphrase: string;\n publicKey?: string;\n /**\n * Build `SOROBAN_CREDENTIALS_ADDRESS_V2` (CAP-71) credentials instead of the\n * legacy `SOROBAN_CREDENTIALS_ADDRESS`. V2 credentials bind the address into\n * the signed payload but are only valid on networks that have activated\n * CAP-71, so leave this off until the activation vote passes for your target\n * network. The default flips to `true` once V2 becomes mandatory.\n * @defaultValue false\n */\n authV2?: boolean;\n}\n/**\n * This builds an entry from scratch, allowing you to express authorization as a\n * function of:\n * - a particular identity (i.e. signing {@link Keypair} or other signer)\n * - approving the execution of an invocation tree (i.e. a simulation-acquired\n * {@link xdr.SorobanAuthorizedInvocation} or otherwise built)\n * - on a particular network (uniquely identified by its passphrase, see\n * {@link Networks})\n * - until a particular ledger sequence is reached.\n *\n * This is in contrast to {@link authorizeEntry}, which signs an existing entry.\n *\n * @param params - the parameters for building and signing the authorization\n * - `signer`: either a {@link Keypair} instance (or anything with a\n * `.sign(buf): Buffer-like` method) or a function which takes a payload (a\n * {@link xdr.HashIdPreimageSorobanAuthorization} instance) input and returns\n * the signature of the hash of the raw payload bytes (where the signing key\n * should correspond to the address in the `entry`)\n * - `validUntilLedgerSeq`: the (exclusive) future ledger sequence\n * number until which this authorization entry should be valid (if\n * `currentLedgerSeq==validUntilLedgerSeq`, this is expired)\n * - `invocation`: the invocation tree that we're authorizing\n * (likely, this comes from transaction simulation)\n * - `networkPassphrase`: the network passphrase is incorporated into\n * the signature (see {@link Networks} for options)\n * - `publicKey`: the public identity of the signer (when providing a\n * {@link Keypair} to `signer`, this can be omitted, as it just uses\n * {@link Keypair.publicKey})\n * - `authV2`: build `SOROBAN_CREDENTIALS_ADDRESS_V2` (CAP-71) credentials\n * rather than the legacy `SOROBAN_CREDENTIALS_ADDRESS`. Defaults to `false`;\n * only enable it for networks that have activated CAP-71.\n *\n * @see authorizeEntry\n */\nexport function authorizeInvocation(\n params: AuthorizeInvocationParams,\n): Promise<xdr.SorobanAuthorizationEntry> {\n const {\n signer,\n validUntilLedgerSeq,\n invocation,\n networkPassphrase,\n publicKey = \"\",\n authV2 = false,\n } = params;\n // We use keypairs as a source of randomness for the nonce to avoid mucking\n // with any crypto dependencies. Note that this just has to be random and\n // unique, not cryptographically secure, so it's fine.\n const kp = Keypair.random().rawPublicKey();\n const nonce = new xdr.Int64(bytesToInt64(kp));\n\n const pk =\n publicKey || (signer instanceof Keypair ? signer.publicKey() : null);\n if (!pk) {\n throw new Error(`authorizeInvocation requires publicKey parameter`);\n }\n\n // V1 and V2 carry the identical SorobanAddressCredentials payload; only the\n // credential union arm differs. authorizeEntry picks the matching signature\n // preimage (legacy vs. address-bound) off whichever arm we build here.\n const addressCredentials = new xdr.SorobanAddressCredentials({\n address: new Address(pk).toScAddress(),\n nonce,\n signatureExpirationLedger: 0, // replaced\n signature: xdr.ScVal.scvVec([]), // replaced\n });\n\n const entry = new xdr.SorobanAuthorizationEntry({\n rootInvocation: invocation,\n credentials: authV2\n ? xdr.SorobanCredentials.sorobanCredentialsAddressV2(addressCredentials)\n : xdr.SorobanCredentials.sorobanCredentialsAddress(addressCredentials),\n });\n\n return authorizeEntry(entry, signer, validUntilLedgerSeq, networkPassphrase);\n}\n\n/**\n * Builds the {@link xdr.HashIdPreimage} whose hash a signer must sign to\n * authorize `entry`. This is the low-level signature payload used by\n * {@link authorizeEntry}, exposed for callers that drive signing themselves —\n * most notably for `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES`, where the\n * client (not simulation) decides which delegates sign and how.\n *\n * For `SOROBAN_CREDENTIALS_ADDRESS` this is the legacy, non-address-bound\n * `ENVELOPE_TYPE_SOROBAN_AUTHORIZATION` preimage. For `SOROBAN_CREDENTIALS_ADDRESS_V2`\n * and `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES` it is the address-bound\n * `ENVELOPE_TYPE_SOROBAN_AUTHORIZATION_WITH_ADDRESS` preimage (CAP-71). For the\n * delegates variant this single payload — bound to the *top-level* address — is\n * what the top-level account and every (nested) delegate each sign.\n *\n * To get the raw bytes to sign, hash the XDR: `hash(preimage.toXDR())`.\n *\n * @param entry - the authorization entry to build the payload for\n * @param validUntilLedgerSeq - the expiration ledger committed into the payload\n * (must match the `signatureExpirationLedger` on the credentials you submit)\n * @param networkPassphrase - the network passphrase mixed into the payload\n * @throws `Error` if `entry` carries source-account or otherwise non-address\n * credentials\n */\nexport function buildAuthorizationEntryPreimage(\n entry: xdr.SorobanAuthorizationEntry,\n validUntilLedgerSeq: number,\n networkPassphrase: string,\n): xdr.HashIdPreimage {\n const credentials = entry.credentials();\n const addrAuth = getAddressCredentials(credentials);\n if (addrAuth === null) {\n throw new Error(\n `cannot build a signature payload for credential type ${credentials.switch().name}`,\n );\n }\n\n const networkId = hash(Buffer.from(networkPassphrase));\n\n switch (credentials.switch().value) {\n // legacy address credentials are not address-bound\n case xdr.SorobanCredentialsType.sorobanCredentialsAddress().value:\n return xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(\n new xdr.HashIdPreimageSorobanAuthorization({\n networkId,\n nonce: addrAuth.nonce(),\n invocation: entry.rootInvocation(),\n signatureExpirationLedger: validUntilLedgerSeq,\n }),\n );\n\n // ADDRESS_V2 and ADDRESS_WITH_DELEGATES bind the address into the signed\n // payload via the WithAddress preimage (CAP-71)\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressV2().value:\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates()\n .value:\n return xdr.HashIdPreimage.envelopeTypeSorobanAuthorizationWithAddress(\n new xdr.HashIdPreimageSorobanAuthorizationWithAddress({\n networkId,\n nonce: addrAuth.nonce(),\n invocation: entry.rootInvocation(),\n address: addrAuth.address(),\n signatureExpirationLedger: validUntilLedgerSeq,\n }),\n );\n\n default:\n throw new Error(\n `unsupported credential type ${credentials.switch().name}`,\n );\n }\n}\n\n/**\n * A delegate signer to attach to a\n * `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES` entry via\n * {@link buildWithDelegatesEntry}.\n */\nexport interface DelegateSignature {\n /** the delegate's address (`G…` account or `C…` contract). */\n address: string;\n /**\n * the delegate's signature value. Defaults to a `scvVoid` placeholder, which\n * you can fill afterwards with {@link authorizeEntry} (passing this address\n * as `forAddress`) or by editing the entry directly.\n */\n signature?: xdr.ScVal;\n /** signers this delegate in turn delegates to (recursive). */\n nestedDelegates?: DelegateSignature[];\n}\n\n/** Parameters for {@link buildWithDelegatesEntry}. */\nexport interface BuildWithDelegatesParams {\n /**\n * an existing `SOROBAN_CREDENTIALS_ADDRESS` or\n * `SOROBAN_CREDENTIALS_ADDRESS_V2` entry — typically one returned by\n * simulation — whose address credentials should be wrapped.\n */\n entry: xdr.SorobanAuthorizationEntry;\n /** the expiration ledger sequence stored on the top-level credentials. */\n validUntilLedgerSeq: number;\n /** the delegate signers to attach. */\n delegates: DelegateSignature[];\n /**\n * the top-level account's signature. Defaults to `scvVoid`, which is valid\n * for accounts that authorize purely via delegated signers (CAP-71-01).\n */\n signature?: xdr.ScVal;\n}\n\n/**\n * Builds a `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES` authorization entry by\n * wrapping the address credentials of an existing `ADDRESS`/`ADDRESS_V2` entry\n * (e.g. one returned by simulation) together with a caller-provided set of\n * delegate signers.\n *\n * Simulation never emits the delegates variant on its own — which accounts use\n * delegated authentication is account-specific policy known only to the client\n * (much like a multisig policy). This helper just assembles the wrapper XDR;\n * you supply the delegate tree (addresses and, optionally, signatures). To\n * produce the signatures, build the shared payload with\n * {@link buildAuthorizationEntryPreimage} on the returned entry and sign it,\n * or fill each node afterwards with {@link authorizeEntry} (passing the\n * signer's address as `forAddress`).\n *\n * Each delegates array (the top-level set and every `nestedDelegates`) is\n * sorted by address in ascending order, and duplicate addresses within an array\n * are rejected, as the protocol requires (CAP-71-01) — otherwise the host\n * rejects the entry.\n *\n * @param params - see {@link BuildWithDelegatesParams}\n * @throws `Error` if `entry` is not an `ADDRESS`/`ADDRESS_V2` entry, or if any\n * delegates array contains a duplicate address.\n */\nexport function buildWithDelegatesEntry(\n params: BuildWithDelegatesParams,\n): xdr.SorobanAuthorizationEntry {\n const { entry, validUntilLedgerSeq, delegates, signature } = params;\n const credentials = entry.credentials();\n const addrAuth = getAddressCredentials(credentials);\n if (\n addrAuth === null ||\n credentials.switch().value ===\n xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value\n ) {\n throw new Error(\n `buildWithDelegatesEntry expects ADDRESS or ADDRESS_V2 credentials, got ${\n credentials.switch().name\n }`,\n );\n }\n\n return new xdr.SorobanAuthorizationEntry({\n rootInvocation: entry.rootInvocation(),\n credentials: xdr.SorobanCredentials.sorobanCredentialsAddressWithDelegates(\n new xdr.SorobanAddressCredentialsWithDelegates({\n addressCredentials: new xdr.SorobanAddressCredentials({\n address: addrAuth.address(),\n nonce: addrAuth.nonce(),\n signatureExpirationLedger: validUntilLedgerSeq,\n signature: signature ?? xdr.ScVal.scvVoid(),\n }),\n delegates: buildDelegateNodes(delegates),\n }),\n ),\n });\n}\n\n/**\n * Recursively converts {@link DelegateSignature} descriptors into\n * {@link xdr.SorobanDelegateSignature} nodes, sorting each level by address and\n * rejecting duplicates (CAP-71-01).\n */\nfunction buildDelegateNodes(\n delegates: DelegateSignature[],\n): xdr.SorobanDelegateSignature[] {\n const nodes = delegates.map(\n (delegate) =>\n new xdr.SorobanDelegateSignature({\n address: new Address(delegate.address).toScAddress(),\n signature: delegate.signature ?? xdr.ScVal.scvVoid(),\n nestedDelegates: buildDelegateNodes(delegate.nestedDelegates ?? []),\n }),\n );\n\n nodes.sort((a, b) =>\n Buffer.compare(a.address().toXDR(), b.address().toXDR()),\n );\n\n for (let i = 1; i < nodes.length; i++) {\n if (\n Buffer.compare(\n nodes[i - 1].address().toXDR(),\n nodes[i].address().toXDR(),\n ) === 0\n ) {\n throw new Error(\n `duplicate delegate address ${Address.fromScAddress(\n nodes[i].address(),\n ).toString()}`,\n );\n }\n }\n\n return nodes;\n}\n\n/**\n * Internal helper — intentionally NOT re-exported from `base/index.js`, so it\n * is not part of the public SDK API. Shared with the contract package, which\n * imports it directly from this module. If a public need arises, add it to the\n * explicit auth re-exports in `base/index.ts`.\n *\n * Extracts the {@link xdr.SorobanAddressCredentials} from any address-based\n * Soroban credential, regardless of which credential type variant is used.\n *\n * This unifies access across `SOROBAN_CREDENTIALS_ADDRESS`,\n * `SOROBAN_CREDENTIALS_ADDRESS_V2` (which carries identical fields but binds\n * the address into the signature payload), and\n * `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES` (which wraps the same address\n * credentials alongside a set of delegate signatures).\n *\n * @param credentials - the credentials to inspect\n * @returns the inner address credentials, or `null` for source-account\n * credentials (which carry no address payload)\n */\nexport function getAddressCredentials(\n credentials: xdr.SorobanCredentials,\n): xdr.SorobanAddressCredentials | null {\n switch (credentials.switch().value) {\n case xdr.SorobanCredentialsType.sorobanCredentialsAddress().value:\n return credentials.address();\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressV2().value:\n return credentials.addressV2();\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates()\n .value:\n return credentials.addressWithDelegates().addressCredentials();\n default:\n return null;\n }\n}\n\n/**\n * The common shape of every node in an authorization entry that can carry a\n * signature: the top-level {@link xdr.SorobanAddressCredentials} and, for the\n * delegates variant, each {@link xdr.SorobanDelegateSignature}. Both expose an\n * `address()` and a `signature()` accessor.\n */\ninterface SignableCredential {\n address(value?: xdr.ScAddress): xdr.ScAddress;\n signature(value?: xdr.ScVal): xdr.ScVal;\n}\n\n/**\n * Internal helper. Returns every node in an address-based credential that can\n * carry a signature, in a stable order: the top-level address credentials\n * first, then (only for `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES`) the\n * delegates and their nested delegates, depth-first. Returns an empty array\n * for source-account credentials, which carry no signature.\n *\n * Per CAP-71-01 all of these nodes commit to the same payload (the one bound to\n * the top-level address), so the caller can fill any of them with a signature\n * produced from that shared payload.\n */\nfunction collectSignatureNodes(\n credentials: xdr.SorobanCredentials,\n): SignableCredential[] {\n switch (credentials.switch().value) {\n case xdr.SorobanCredentialsType.sorobanCredentialsAddress().value:\n return [credentials.address()];\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressV2().value:\n return [credentials.addressV2()];\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates()\n .value: {\n const withDelegates = credentials.addressWithDelegates();\n const nodes: SignableCredential[] = [withDelegates.addressCredentials()];\n const walk = (delegates: xdr.SorobanDelegateSignature[]) => {\n delegates.forEach((delegate) => {\n nodes.push(delegate);\n walk(delegate.nestedDelegates());\n });\n };\n walk(withDelegates.delegates());\n return nodes;\n }\n default:\n return [];\n }\n}\n\nfunction bytesToInt64(bytes: Uint8Array): bigint {\n const buf = bytes.subarray(0, 8);\n if (buf.length < 8) {\n throw new Error(\n `need at least 8 bytes to convert to Int64, got ${bytes.length}`,\n );\n }\n const view = new DataView(buf.buffer, buf.byteOffset, 8);\n const value = view.getBigInt64(0, false);\n\n return value;\n}\n"],"names":["Buffer","xdr","hash","Address","Keypair","nativeToScVal","StrKey"],"mappings":";;;;;;;;;;AAaA,SAAS,SAAS,KAAA,EAA2B;AAC3C,EAAA,IAAI,iBAAiB,WAAA,EAAa;AAChC,IAAA,OAAOA,aAAA,CAAO,IAAA,CAAK,IAAI,UAAA,CAAW,KAAK,CAAC,CAAA;AAAA,EAC1C;AACA,EAAA,OAAOA,aAAA,CAAO,KAAK,KAAK,CAAA;AAC1B;AAmHA,eAAsB,cAAA,CACpB,KAAA,EACA,MAAA,EACA,mBAAA,EACA,mBACA,UAAA,EACwC;AAExC,EAAA,IACE,KAAA,CAAM,WAAA,EAAY,CAAE,MAAA,EAAO,CAAE,UAC7BC,sBAAA,CAAI,sBAAA,CAAuB,+BAAA,EAAgC,CAAE,KAAA,EAC7D;AACA,I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A,CAAS,IAAI,MAAA,EAAQ,GAAA,CAAI,YAAY,CAAC,CAAA;AACvD,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,WAAA,CAAY,CAAA,EAAG,KAAK,CAAA;AAEvC,EAAA,OAAO,KAAA;AACT;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"auth.js","sources":["../../../src/base/auth.ts"],"sourcesContent":["import xdr from \"./xdr.js\";\n\nimport { Keypair } from \"./keypair.js\";\nimport { StrKey } from \"./strkey.js\";\n\nimport type { Networks } from \"./network.js\";\nimport { hash } from \"./hashing.js\";\n\nimport { Address } from \"./address.js\";\nimport { nativeToScVal } from \"./scval.js\";\n\ntype BufferLike = ArrayBuffer | Buffer | Uint8Array;\n\nfunction toBuffer(value: BufferLike): Buffer {\n if (value instanceof ArrayBuffer) {\n return Buffer.from(new Uint8Array(value));\n }\n return Buffer.from(value);\n}\n\n/**\n * A callback for signing an XDR structure representing all of the details\n * necessary to authorize an invocation tree.\n *\n * @param preimage - the entire authorization envelope whose hash you should\n * sign, so that you can inspect the entire structure if necessary (rather\n * than blindly signing a hash)\n * @param payload - the 32-byte signing payload, i.e. the sha256 hash of the\n * preimage bytes (`hash(preimage.toXDR())`), provided as a convenience so\n * you never have to re-derive it (e.g. for HSMs or remote signers that only\n * accept a digest)\n *\n * @returns one of the following:\n *\n * - the signature of the payload as a naked buffer, implying it is signed by\n * the key corresponding to the public key in the entry you pass to\n * {@link authorizeEntry} (decipherable from its\n * `credentials().address().address()`),\n * - an object with the `signature` alongside an explicit `publicKey` string\n * identifying the Ed25519 signer, or\n * - an object with a `signatureScVal`: an arbitrary, caller-built\n * {@link xdr.ScVal} that is placed verbatim into the credentials'\n * `signature` field. Use this for custom account contracts (smart wallets,\n * passkey/WebAuthn signers, etc.) whose `__check_auth` expects a signature\n * structure other than the built-in Stellar account\n * `{public_key, signature}` vector. No Ed25519 verification is performed on\n * this variant, and no `scvVec` wrapping is applied — you own the exact\n * shape. The optional `address` selects which credential node receives the\n * signature (like `forAddress` on {@link authorizeEntry}, which takes\n * precedence if both are given).\n */\nexport type SigningCallback = (\n preimage: xdr.HashIdPreimage,\n payload: Buffer,\n) => Promise<\n | BufferLike\n | { signature: BufferLike; publicKey: string }\n | { signatureScVal: xdr.ScVal; address?: string }\n>;\n\n/**\n * Actually authorizes an existing authorization entry using the given\n * credentials and expiration details, returning a signed copy.\n *\n * This \"fills out\" the authorization entry with a signature, indicating to the\n * {@link Operation.invokeHostFunction} its attached to that:\n * - a particular identity (i.e. signing {@link Keypair} or other signer)\n * - approving the execution of an invocation tree (i.e. a simulation-acquired\n * {@link xdr.SorobanAuthorizedInvocation} or otherwise built)\n * - on a particular network (uniquely identified by its passphrase, see\n * {@link Networks})\n * - until a particular ledger sequence is reached.\n *\n * This one lets you pass either a {@link Keypair} (or, more accurately,\n * anything with a `sign(Buffer): Buffer` method) or a callback function (see\n * {@link SigningCallback}) to handle signing the envelope hash.\n *\n * @param entry - an unsigned authorization entry\n * @param signer - either a {@link Keypair} instance or a function (see\n * {@link SigningCallback}) which receives the\n * {@link xdr.HashIdPreimage} input payload plus its 32-byte signing hash\n * and returns EITHER\n *\n * (a) an object containing a `signature` of the hash of the raw payload\n * bytes as a Buffer-like and a `publicKey` string representing who just\n * created this signature,\n * (b) just the naked signature of the hash of the raw payload bytes (where\n * the signing key is implied to be the address in the `entry`), or\n * (c) an object containing a `signatureScVal` — an arbitrary, caller-built\n * {@link xdr.ScVal} written verbatim as the credentials' signature,\n * for custom account contracts (smart wallets, passkey/WebAuthn\n * signers) whose `__check_auth` expects a non-Ed25519 signature shape.\n *\n * Option (b) is JUST for backwards compatibility and will be\n * removed in the future.\n * @param validUntilLedgerSeq - the (exclusive) future ledger sequence number\n * until which this authorization entry should be valid (if\n * `currentLedgerSeq==validUntil`, this is expired)\n * @param networkPassphrase - the network passphrase is incorporated into the\n * signature (see {@link Networks} for options)\n *\n * If using the `SigningCallback` variation, the signer is assumed to be\n * the entry's credential address unless you use the variant that returns\n * the object.\n *\n * @param forAddress - which credential node the signature should be written\n * to. Only relevant for `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES`, where\n * a single entry can be signed by the top-level account and/or any of its\n * (possibly nested) delegates. Per CAP-71-01 every one of these signers\n * signs the *same* payload (bound to the top-level address), so the\n * signature produced here is written to whichever node(s) carry\n * `forAddress`. When omitted, the signature is written to the top-level\n * credentials, which preserves the behavior for `SOROBAN_CREDENTIALS_ADDRESS`\n * / `SOROBAN_CREDENTIALS_ADDRESS_V2` and for accounts whose signing key\n * differs from the credential address (e.g. multisig).\n *\n * @see authorizeInvocation\n * @example\n * ```ts\n * import {\n * SorobanRpc,\n * Transaction,\n * Networks,\n * authorizeEntry\n * } from '@stellar/stellar-sdk';\n *\n * // Assume signPayloadCallback is a well-formed signing callback.\n * //\n * // It might, for example, pop up a modal from a browser extension, send the\n * // transaction to a third-party service for signing, or just do simple\n * // signing via Keypair like it does here:\n * function signPayloadCallback(preimage, payload) {\n * // `payload` is hash(preimage.toXDR()) — inspect `preimage` if you want\n * // to display/verify what is being authorized before signing.\n * return signer.sign(payload);\n * }\n *\n * function multiPartyAuth(\n * server: SorobanRpc.Server,\n * // assume this involves multi-party auth\n * tx: Transaction,\n * ) {\n * return server\n * .simulateTransaction(tx)\n * .then((simResult) => {\n * tx.operations[0].auth.map(entry =>\n * authorizeEntry(\n * entry,\n * signPayloadCallback,\n * currentLedger + 1000,\n * Networks.TESTNET)\n * );\n *\n * return server.prepareTransaction(tx, simResult);\n * })\n * .then((preppedTx) => {\n * preppedTx.sign(source);\n * return server.sendTransaction(preppedTx);\n * });\n * }\n * ```\n */\nexport async function authorizeEntry(\n entry: xdr.SorobanAuthorizationEntry,\n signer: Keypair | SigningCallback,\n validUntilLedgerSeq: number,\n networkPassphrase: string,\n forAddress?: string,\n): Promise<xdr.SorobanAuthorizationEntry> {\n // no-op if it's source account auth\n if (\n entry.credentials().switch().value ===\n xdr.SorobanCredentialsType.sorobanCredentialsSourceAccount().value\n ) {\n return entry;\n }\n\n const clone = xdr.SorobanAuthorizationEntry.fromXDR(entry.toXDR());\n const credentials = clone.credentials();\n const addrAuth = getAddressCredentials(credentials);\n if (addrAuth === null) {\n // We should have already returned if the credentials were source account credentials,\n // so if we can't get address credentials out of this, it's an unsupported credential type.\n throw new Error(`unsupported credential type ${credentials.switch().name}`);\n }\n\n // Set the expiration before building the preimage, so the hash that gets\n // signed commits to the same expiration ledger stored in the credentials.\n // Otherwise the network reconstructs the preimage from the (updated)\n // credentials and the signature no longer matches.\n addrAuth.signatureExpirationLedger(validUntilLedgerSeq);\n\n const preimage = buildAuthorizationEntryPreimage(\n clone,\n validUntilLedgerSeq,\n networkPassphrase,\n );\n\n const payload = hash(preimage.toXDR());\n\n let signatureScVal: xdr.ScVal;\n let targetAddress = forAddress;\n let sigResult: Awaited<ReturnType<SigningCallback>> | null = null;\n if (typeof signer === \"function\") {\n // Hand the callback its own copy of the payload: `payload` is what the\n // Ed25519 signature is verified against below, so a callback mutating the\n // buffer it received must not be able to shift what \"valid\" means.\n sigResult = await signer(preimage, Buffer.from(payload));\n }\n\n if (\n sigResult !== null &&\n typeof sigResult === \"object\" &&\n \"signatureScVal\" in sigResult\n ) {\n // Custom-credential path (smart wallets, passkeys/WebAuthn, etc.): the\n // caller owns the exact ScVal their account contract's `__check_auth`\n // expects, so it is written verbatim — no Ed25519 verification and no\n // scvVec wrapping.\n signatureScVal = sigResult.signatureScVal;\n targetAddress ??= sigResult.address;\n } else {\n let signature: Buffer;\n let publicKey: string;\n if (typeof signer === \"function\") {\n if (\n sigResult !== null &&\n typeof sigResult === \"object\" &&\n \"signature\" in sigResult\n ) {\n signature = toBuffer(sigResult.signature);\n publicKey = sigResult.publicKey;\n } else {\n // if using the deprecated form, assume it's for the entry\n signature = toBuffer(sigResult as BufferLike);\n publicKey = Address.fromScAddress(addrAuth.address()).toString();\n }\n } else {\n signature = toBuffer(signer.sign(payload));\n publicKey = signer.publicKey();\n }\n\n if (!Keypair.fromPublicKey(publicKey).verify(payload, signature)) {\n throw new Error(`signature doesn't match payload`);\n }\n\n // This structure is defined here:\n // https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#stellar-account-signatures\n //\n // Encoding a contract structure as an ScVal means the map keys are supposed\n // to be symbols, hence the forced typing here.\n const sigScVal = nativeToScVal(\n {\n public_key: StrKey.decodeEd25519PublicKey(publicKey),\n signature,\n },\n {\n type: {\n public_key: [\"symbol\", null],\n signature: [\"symbol\", null],\n },\n },\n );\n\n signatureScVal = xdr.ScVal.scvVec([sigScVal]);\n }\n\n // CAP-71-01: the signature payload is shared across the top-level address\n // and every (possibly nested) delegate, so this signer's signature is\n // written to whichever credential node(s) carry `forAddress`. When no\n // `forAddress` is given we fall back to the top-level credentials, which\n // preserves the behavior for ADDRESS / ADDRESS_V2 and for accounts whose\n // signing key differs from the credential address (e.g. multisig).\n const targets: SignableCredential[] =\n targetAddress === undefined\n ? [addrAuth]\n : collectSignatureNodes(credentials).filter(\n (node) =>\n Address.fromScAddress(node.address()).toString() === targetAddress,\n );\n\n if (targets.length === 0) {\n throw new Error(\n `the authorization entry has no credential node for address ${targetAddress}`,\n );\n }\n\n targets.forEach((node) => node.signature(signatureScVal));\n return clone;\n}\n\nexport interface AuthorizeInvocationParams {\n signer: Keypair | SigningCallback;\n validUntilLedgerSeq: number;\n invocation: xdr.SorobanAuthorizedInvocation;\n networkPassphrase: string;\n publicKey?: string;\n /**\n * Build `SOROBAN_CREDENTIALS_ADDRESS_V2` (CAP-71) credentials instead of the\n * legacy `SOROBAN_CREDENTIALS_ADDRESS`. V2 credentials bind the address into\n * the signed payload but are only valid on networks that have activated\n * CAP-71, so leave this off until the activation vote passes for your target\n * network. The default flips to `true` once V2 becomes mandatory.\n * @defaultValue false\n */\n authV2?: boolean;\n}\n/**\n * This builds an entry from scratch, allowing you to express authorization as a\n * function of:\n * - a particular identity (i.e. signing {@link Keypair} or other signer)\n * - approving the execution of an invocation tree (i.e. a simulation-acquired\n * {@link xdr.SorobanAuthorizedInvocation} or otherwise built)\n * - on a particular network (uniquely identified by its passphrase, see\n * {@link Networks})\n * - until a particular ledger sequence is reached.\n *\n * This is in contrast to {@link authorizeEntry}, which signs an existing entry.\n *\n * @param params - the parameters for building and signing the authorization\n * - `signer`: either a {@link Keypair} instance (or anything with a\n * `.sign(buf): Buffer-like` method) or a function which takes a payload (a\n * {@link xdr.HashIdPreimageSorobanAuthorization} instance) input and returns\n * the signature of the hash of the raw payload bytes (where the signing key\n * should correspond to the address in the `entry`)\n * - `validUntilLedgerSeq`: the (exclusive) future ledger sequence\n * number until which this authorization entry should be valid (if\n * `currentLedgerSeq==validUntilLedgerSeq`, this is expired)\n * - `invocation`: the invocation tree that we're authorizing\n * (likely, this comes from transaction simulation)\n * - `networkPassphrase`: the network passphrase is incorporated into\n * the signature (see {@link Networks} for options)\n * - `publicKey`: the public identity of the signer (when providing a\n * {@link Keypair} to `signer`, this can be omitted, as it just uses\n * {@link Keypair.publicKey})\n * - `authV2`: build `SOROBAN_CREDENTIALS_ADDRESS_V2` (CAP-71) credentials\n * rather than the legacy `SOROBAN_CREDENTIALS_ADDRESS`. Defaults to `false`;\n * only enable it for networks that have activated CAP-71.\n *\n * @see authorizeEntry\n */\nexport function authorizeInvocation(\n params: AuthorizeInvocationParams,\n): Promise<xdr.SorobanAuthorizationEntry> {\n const {\n signer,\n validUntilLedgerSeq,\n invocation,\n networkPassphrase,\n publicKey = \"\",\n authV2 = false,\n } = params;\n // We use keypairs as a source of randomness for the nonce to avoid mucking\n // with any crypto dependencies. Note that this just has to be random and\n // unique, not cryptographically secure, so it's fine.\n const kp = Keypair.random().rawPublicKey();\n const nonce = new xdr.Int64(bytesToInt64(kp));\n\n const pk =\n publicKey || (signer instanceof Keypair ? signer.publicKey() : null);\n if (!pk) {\n throw new Error(`authorizeInvocation requires publicKey parameter`);\n }\n\n // V1 and V2 carry the identical SorobanAddressCredentials payload; only the\n // credential union arm differs. authorizeEntry picks the matching signature\n // preimage (legacy vs. address-bound) off whichever arm we build here.\n const addressCredentials = new xdr.SorobanAddressCredentials({\n address: new Address(pk).toScAddress(),\n nonce,\n signatureExpirationLedger: 0, // replaced\n signature: xdr.ScVal.scvVec([]), // replaced\n });\n\n const entry = new xdr.SorobanAuthorizationEntry({\n rootInvocation: invocation,\n credentials: authV2\n ? xdr.SorobanCredentials.sorobanCredentialsAddressV2(addressCredentials)\n : xdr.SorobanCredentials.sorobanCredentialsAddress(addressCredentials),\n });\n\n return authorizeEntry(entry, signer, validUntilLedgerSeq, networkPassphrase);\n}\n\n/**\n * Builds the {@link xdr.HashIdPreimage} whose hash a signer must sign to\n * authorize `entry`. This is the low-level signature payload used by\n * {@link authorizeEntry}, exposed for callers that drive signing themselves —\n * most notably for `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES`, where the\n * client (not simulation) decides which delegates sign and how.\n *\n * For `SOROBAN_CREDENTIALS_ADDRESS` this is the legacy, non-address-bound\n * `ENVELOPE_TYPE_SOROBAN_AUTHORIZATION` preimage. For `SOROBAN_CREDENTIALS_ADDRESS_V2`\n * and `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES` it is the address-bound\n * `ENVELOPE_TYPE_SOROBAN_AUTHORIZATION_WITH_ADDRESS` preimage (CAP-71). For the\n * delegates variant this single payload — bound to the *top-level* address — is\n * what the top-level account and every (nested) delegate each sign.\n *\n * To get the raw bytes to sign, hash the XDR: `hash(preimage.toXDR())`.\n *\n * @param entry - the authorization entry to build the payload for\n * @param validUntilLedgerSeq - the expiration ledger committed into the payload\n * (must match the `signatureExpirationLedger` on the credentials you submit)\n * @param networkPassphrase - the network passphrase mixed into the payload\n * @throws `Error` if `entry` carries source-account or otherwise non-address\n * credentials\n */\nexport function buildAuthorizationEntryPreimage(\n entry: xdr.SorobanAuthorizationEntry,\n validUntilLedgerSeq: number,\n networkPassphrase: string,\n): xdr.HashIdPreimage {\n const credentials = entry.credentials();\n const addrAuth = getAddressCredentials(credentials);\n if (addrAuth === null) {\n throw new Error(\n `cannot build a signature payload for credential type ${credentials.switch().name}`,\n );\n }\n\n const networkId = hash(Buffer.from(networkPassphrase));\n\n switch (credentials.switch().value) {\n // legacy address credentials are not address-bound\n case xdr.SorobanCredentialsType.sorobanCredentialsAddress().value:\n return xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(\n new xdr.HashIdPreimageSorobanAuthorization({\n networkId,\n nonce: addrAuth.nonce(),\n invocation: entry.rootInvocation(),\n signatureExpirationLedger: validUntilLedgerSeq,\n }),\n );\n\n // ADDRESS_V2 and ADDRESS_WITH_DELEGATES bind the address into the signed\n // payload via the WithAddress preimage (CAP-71)\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressV2().value:\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates()\n .value:\n return xdr.HashIdPreimage.envelopeTypeSorobanAuthorizationWithAddress(\n new xdr.HashIdPreimageSorobanAuthorizationWithAddress({\n networkId,\n nonce: addrAuth.nonce(),\n invocation: entry.rootInvocation(),\n address: addrAuth.address(),\n signatureExpirationLedger: validUntilLedgerSeq,\n }),\n );\n\n default:\n throw new Error(\n `unsupported credential type ${credentials.switch().name}`,\n );\n }\n}\n\n/**\n * A delegate signer to attach to a\n * `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES` entry via\n * {@link buildWithDelegatesEntry}.\n */\nexport interface DelegateSignature {\n /** the delegate's address (`G…` account or `C…` contract). */\n address: string;\n /**\n * the delegate's signature value. Defaults to a `scvVoid` placeholder, which\n * you can fill afterwards with {@link authorizeEntry} (passing this address\n * as `forAddress`) or by editing the entry directly.\n */\n signature?: xdr.ScVal;\n /** signers this delegate in turn delegates to (recursive). */\n nestedDelegates?: DelegateSignature[];\n}\n\n/** Parameters for {@link buildWithDelegatesEntry}. */\nexport interface BuildWithDelegatesParams {\n /**\n * an existing `SOROBAN_CREDENTIALS_ADDRESS` or\n * `SOROBAN_CREDENTIALS_ADDRESS_V2` entry — typically one returned by\n * simulation — whose address credentials should be wrapped.\n */\n entry: xdr.SorobanAuthorizationEntry;\n /** the expiration ledger sequence stored on the top-level credentials. */\n validUntilLedgerSeq: number;\n /** the delegate signers to attach. */\n delegates: DelegateSignature[];\n /**\n * the top-level account's signature. Defaults to `scvVoid`, which is valid\n * for accounts that authorize purely via delegated signers (CAP-71-01).\n */\n signature?: xdr.ScVal;\n}\n\n/**\n * Builds a `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES` authorization entry by\n * wrapping the address credentials of an existing `ADDRESS`/`ADDRESS_V2` entry\n * (e.g. one returned by simulation) together with a caller-provided set of\n * delegate signers.\n *\n * Simulation never emits the delegates variant on its own — which accounts use\n * delegated authentication is account-specific policy known only to the client\n * (much like a multisig policy). This helper just assembles the wrapper XDR;\n * you supply the delegate tree (addresses and, optionally, signatures). To\n * produce the signatures, build the shared payload with\n * {@link buildAuthorizationEntryPreimage} on the returned entry and sign it,\n * or fill each node afterwards with {@link authorizeEntry} (passing the\n * signer's address as `forAddress`).\n *\n * Each delegates array (the top-level set and every `nestedDelegates`) is\n * sorted by address in ascending order, and duplicate addresses within an array\n * are rejected, as the protocol requires (CAP-71-01) — otherwise the host\n * rejects the entry.\n *\n * @param params - see {@link BuildWithDelegatesParams}\n * @throws `Error` if `entry` is not an `ADDRESS`/`ADDRESS_V2` entry, or if any\n * delegates array contains a duplicate address.\n */\nexport function buildWithDelegatesEntry(\n params: BuildWithDelegatesParams,\n): xdr.SorobanAuthorizationEntry {\n const { entry, validUntilLedgerSeq, delegates, signature } = params;\n const credentials = entry.credentials();\n const addrAuth = getAddressCredentials(credentials);\n if (\n addrAuth === null ||\n credentials.switch().value ===\n xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value\n ) {\n throw new Error(\n `buildWithDelegatesEntry expects ADDRESS or ADDRESS_V2 credentials, got ${\n credentials.switch().name\n }`,\n );\n }\n\n return new xdr.SorobanAuthorizationEntry({\n rootInvocation: entry.rootInvocation(),\n credentials: xdr.SorobanCredentials.sorobanCredentialsAddressWithDelegates(\n new xdr.SorobanAddressCredentialsWithDelegates({\n addressCredentials: new xdr.SorobanAddressCredentials({\n address: addrAuth.address(),\n nonce: addrAuth.nonce(),\n signatureExpirationLedger: validUntilLedgerSeq,\n signature: signature ?? xdr.ScVal.scvVoid(),\n }),\n delegates: buildDelegateNodes(delegates),\n }),\n ),\n });\n}\n\n/**\n * Recursively converts {@link DelegateSignature} descriptors into\n * {@link xdr.SorobanDelegateSignature} nodes, sorting each level by address and\n * rejecting duplicates (CAP-71-01).\n */\nfunction buildDelegateNodes(\n delegates: DelegateSignature[],\n): xdr.SorobanDelegateSignature[] {\n const nodes = delegates.map(\n (delegate) =>\n new xdr.SorobanDelegateSignature({\n address: new Address(delegate.address).toScAddress(),\n signature: delegate.signature ?? xdr.ScVal.scvVoid(),\n nestedDelegates: buildDelegateNodes(delegate.nestedDelegates ?? []),\n }),\n );\n\n nodes.sort((a, b) =>\n Buffer.compare(a.address().toXDR(), b.address().toXDR()),\n );\n\n for (let i = 1; i < nodes.length; i++) {\n if (\n Buffer.compare(\n nodes[i - 1].address().toXDR(),\n nodes[i].address().toXDR(),\n ) === 0\n ) {\n throw new Error(\n `duplicate delegate address ${Address.fromScAddress(\n nodes[i].address(),\n ).toString()}`,\n );\n }\n }\n\n return nodes;\n}\n\n/**\n * Internal helper — intentionally NOT re-exported from `base/index.js`, so it\n * is not part of the public SDK API. Shared with the contract package, which\n * imports it directly from this module. If a public need arises, add it to the\n * explicit auth re-exports in `base/index.ts`.\n *\n * Extracts the {@link xdr.SorobanAddressCredentials} from any address-based\n * Soroban credential, regardless of which credential type variant is used.\n *\n * This unifies access across `SOROBAN_CREDENTIALS_ADDRESS`,\n * `SOROBAN_CREDENTIALS_ADDRESS_V2` (which carries identical fields but binds\n * the address into the signature payload), and\n * `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES` (which wraps the same address\n * credentials alongside a set of delegate signatures).\n *\n * @param credentials - the credentials to inspect\n * @returns the inner address credentials, or `null` for source-account\n * credentials (which carry no address payload)\n */\nexport function getAddressCredentials(\n credentials: xdr.SorobanCredentials,\n): xdr.SorobanAddressCredentials | null {\n switch (credentials.switch().value) {\n case xdr.SorobanCredentialsType.sorobanCredentialsAddress().value:\n return credentials.address();\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressV2().value:\n return credentials.addressV2();\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates()\n .value:\n return credentials.addressWithDelegates().addressCredentials();\n default:\n return null;\n }\n}\n\n/**\n * The common shape of every node in an authorization entry that can carry a\n * signature: the top-level {@link xdr.SorobanAddressCredentials} and, for the\n * delegates variant, each {@link xdr.SorobanDelegateSignature}. Both expose an\n * `address()` and a `signature()` accessor.\n */\ninterface SignableCredential {\n address(value?: xdr.ScAddress): xdr.ScAddress;\n signature(value?: xdr.ScVal): xdr.ScVal;\n}\n\n/**\n * Internal helper. Returns every node in an address-based credential that can\n * carry a signature, in a stable order: the top-level address credentials\n * first, then (only for `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES`) the\n * delegates and their nested delegates, depth-first. Returns an empty array\n * for source-account credentials, which carry no signature.\n *\n * Per CAP-71-01 all of these nodes commit to the same payload (the one bound to\n * the top-level address), so the caller can fill any of them with a signature\n * produced from that shared payload.\n */\nfunction collectSignatureNodes(\n credentials: xdr.SorobanCredentials,\n): SignableCredential[] {\n switch (credentials.switch().value) {\n case xdr.SorobanCredentialsType.sorobanCredentialsAddress().value:\n return [credentials.address()];\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressV2().value:\n return [credentials.addressV2()];\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates()\n .value: {\n const withDelegates = credentials.addressWithDelegates();\n const nodes: SignableCredential[] = [withDelegates.addressCredentials()];\n const walk = (delegates: xdr.SorobanDelegateSignature[]) => {\n delegates.forEach((delegate) => {\n nodes.push(delegate);\n walk(delegate.nestedDelegates());\n });\n };\n walk(withDelegates.delegates());\n return nodes;\n }\n default:\n return [];\n }\n}\n\n/** The credential arm of a {@link xdr.SorobanAuthorizationEntry}. */\nexport type AuthEntryCredentialType =\n | \"sourceAccount\"\n | \"address\"\n | \"addressV2\"\n | \"addressWithDelegates\";\n\n/**\n * A single ed25519 signature parsed out of a credential node's signature\n * value, in the map format written by {@link authorizeEntry}.\n */\nexport interface AuthEntrySignature {\n /** the signer's public key, as a `G…` strkey. */\n publicKey: string;\n /** the raw 64-byte ed25519 signature. */\n signature: Buffer;\n}\n\n/**\n * One node of an authorization entry that can carry a signature: the top-level\n * address credentials and, for `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES`,\n * each (possibly nested) delegate.\n */\nexport interface AuthEntrySigner {\n /** the node's address (`G…` account or `C…` contract). */\n address: string;\n /**\n * whether a signature payload is present on this node (i.e. its signature is\n * neither `scvVoid` nor an empty `scvVec`). For contract (`C…`) addresses\n * this only means *something* is attached — whether it satisfies the\n * contract's `__check_auth` cannot be verified client-side.\n */\n signed: boolean;\n /**\n * the signature payload parsed as the SDK's standard ed25519 format (a vec\n * of `{public_key, signature}` maps, see {@link authorizeEntry}), or `null`\n * when the payload has some other, signer-defined shape (as custom accounts\n * such as WebAuthn/passkey wallets use). Of the two unsigned placeholder\n * forms, an empty `scvVec` parses as `[]` while `scvVoid` (not a vec at all)\n * parses as `null` — check `signed` rather than this field to tell whether a\n * node is unsigned.\n */\n signatures: AuthEntrySignature[] | null;\n /** the raw signature value, whatever its shape. */\n rawSignature: xdr.ScVal;\n}\n\n/**\n * A structured, read-only view of a {@link xdr.SorobanAuthorizationEntry},\n * returned by {@link inspectAuthEntry}.\n */\nexport interface AuthEntryInfo {\n credentialType: AuthEntryCredentialType;\n /** the authorizing address, or `null` for source-account credentials. */\n address: string | null;\n /** the credential nonce, or `null` for source-account credentials. */\n nonce: bigint | null;\n /**\n * the (exclusive) ledger sequence until which the signature is valid, or\n * `null` for source-account credentials. Note that unsigned entries commonly\n * carry a placeholder (often `0`) until {@link authorizeEntry} sets it.\n */\n signatureExpirationLedger: number | null;\n /**\n * every node that can carry a signature: the top-level credentials first,\n * then (for the delegates variant) each delegate, depth-first. Empty for\n * source-account credentials.\n */\n signers: AuthEntrySigner[];\n /**\n * whether every signer node carries a signature payload. Always `false` for\n * source-account credentials (which have no signature nodes — they are\n * instead covered by the transaction envelope signature; use\n * {@link checkAuthEntryReadiness} for a submit check). For the delegates\n * variant note that an account's policy may accept an unsigned top-level\n * node when its delegates have signed (CAP-71-01) — consult `signers` if you\n * support that.\n */\n signed: boolean;\n /** the invocation tree this entry authorizes. */\n invocation: xdr.SorobanAuthorizedInvocation;\n}\n\n/** The result of {@link checkAuthEntryReadiness}. */\nexport interface AuthEntryReadiness {\n /** `true` when the entry is fully signed and not expired. */\n ready: boolean;\n /**\n * `true` when `currentLedgerSeq >= signatureExpirationLedger` (expiration is\n * exclusive). Always `false` for source-account credentials.\n */\n expired: boolean;\n /** addresses of signer nodes that carry no signature payload. */\n unsignedBy: string[];\n}\n\n/**\n * Decodes a {@link xdr.SorobanAuthorizationEntry} into a plain, typed summary:\n * which credential variant it uses, which address authorizes it, its nonce and\n * expiration ledger, and — for every node that can carry a signature (the\n * top-level credentials plus any CAP-71 delegates) — whether it is signed and,\n * when the payload uses the SDK's standard ed25519 format, by which keys.\n *\n * This is the read-side complement to {@link authorizeEntry} /\n * {@link authorizeInvocation}: those fill entries with signatures, this\n * inspects what an entry (e.g. one returned by transaction simulation, or\n * received from a counterparty in a multi-party signing flow) requires and\n * already carries, without reaching into raw XDR accessors.\n *\n * @param entry - the authorization entry to inspect\n * @returns a {@link AuthEntryInfo} summary of the entry\n *\n * @see checkAuthEntryReadiness\n * @example\n * ```ts\n * const info = inspectAuthEntry(entry);\n * if (!info.signed && info.address !== null) {\n * console.log(`${info.address} still needs to sign`, info.signers);\n * }\n * ```\n */\nexport function inspectAuthEntry(\n entry: xdr.SorobanAuthorizationEntry,\n): AuthEntryInfo {\n const credentials = entry.credentials();\n const addrAuth = getAddressCredentials(credentials);\n\n let credentialType: AuthEntryCredentialType;\n switch (credentials.switch().value) {\n case xdr.SorobanCredentialsType.sorobanCredentialsSourceAccount().value:\n credentialType = \"sourceAccount\";\n break;\n case xdr.SorobanCredentialsType.sorobanCredentialsAddress().value:\n credentialType = \"address\";\n break;\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressV2().value:\n credentialType = \"addressV2\";\n break;\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates()\n .value:\n credentialType = \"addressWithDelegates\";\n break;\n default:\n throw new Error(\n `unsupported credential type ${credentials.switch().name}`,\n );\n }\n\n const signers = collectSignatureNodes(credentials).map(\n (node): AuthEntrySigner => {\n const rawSignature = node.signature();\n return {\n address: Address.fromScAddress(node.address()).toString(),\n signed: signaturePresent(rawSignature),\n signatures: parseEd25519Signatures(rawSignature),\n rawSignature,\n };\n },\n );\n\n return {\n credentialType,\n address:\n addrAuth === null\n ? null\n : Address.fromScAddress(addrAuth.address()).toString(),\n nonce: addrAuth === null ? null : addrAuth.nonce().toBigInt(),\n signatureExpirationLedger:\n addrAuth === null ? null : addrAuth.signatureExpirationLedger(),\n signers,\n signed: signers.length > 0 && signers.every((signer) => signer.signed),\n invocation: entry.rootInvocation(),\n };\n}\n\n/**\n * Reports whether an authorization entry is ready to submit at a given ledger:\n * fully signed and not yet expired.\n *\n * Source-account entries are always ready — they carry no signature or\n * expiration of their own and are instead covered by the transaction envelope\n * signature.\n *\n * The current ledger sequence is taken as a parameter (fetch it from a source\n * you trust, e.g. `rpc.Server.getLatestLedger`) rather than looked up here, so\n * this stays a pure decode with no network dependency.\n *\n * For `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES`, this conservatively\n * requires *every* node (top-level and all delegates) to be signed. An\n * account's policy may accept an unsigned top-level node when its delegates\n * have signed (CAP-71-01); if you support that, check\n * {@link inspectAuthEntry}'s `signers` yourself.\n *\n * @param entry - the authorization entry to check\n * @param currentLedgerSeq - the network's current ledger sequence, compared\n * (exclusively) against the entry's `signatureExpirationLedger`\n * @returns a {@link AuthEntryReadiness}: `ready`, `expired`, and which\n * addresses are still `unsignedBy`\n * @throws `Error` if `currentLedgerSeq` cannot represent a uint32 ledger\n * sequence (non-integer, negative, or above 2^32 - 1), which would make the\n * expiration comparison unreliable\n */\nexport function checkAuthEntryReadiness(\n entry: xdr.SorobanAuthorizationEntry,\n currentLedgerSeq: number,\n): AuthEntryReadiness {\n if (\n !Number.isInteger(currentLedgerSeq) ||\n currentLedgerSeq < 0 ||\n currentLedgerSeq > 0xffffffff\n ) {\n throw new Error(\n `currentLedgerSeq must be a uint32 ledger sequence, got ${currentLedgerSeq}`,\n );\n }\n\n const info = inspectAuthEntry(entry);\n if (info.credentialType === \"sourceAccount\") {\n return { ready: true, expired: false, unsignedBy: [] };\n }\n\n const expired = currentLedgerSeq >= (info.signatureExpirationLedger ?? 0);\n const unsignedBy = info.signers\n .filter((signer) => !signer.signed)\n .map((signer) => signer.address);\n\n return { ready: !expired && unsignedBy.length === 0, expired, unsignedBy };\n}\n\n/**\n * Internal helper. A node counts as unsigned when its signature is `scvVoid`\n * (the delegate/CAP-71 placeholder) or an empty `scvVec` (the placeholder\n * {@link authorizeInvocation} writes); anything else is a signature payload.\n */\nfunction signaturePresent(signature: xdr.ScVal): boolean {\n switch (signature.switch().value) {\n case xdr.ScValType.scvVoid().value:\n return false;\n case xdr.ScValType.scvVec().value:\n return (signature.vec() ?? []).length > 0;\n default:\n return true;\n }\n}\n\n/**\n * Internal helper. Parses a signature value in the SDK's standard format — an\n * `scvVec` of `scvMap`s with symbol keys `public_key` (32 raw ed25519 key\n * bytes) and `signature` — back into typed pairs. Returns `null` when the\n * value has any other shape (e.g. a custom account's signer-defined payload).\n */\nfunction parseEd25519Signatures(\n signature: xdr.ScVal,\n): AuthEntrySignature[] | null {\n if (signature.switch().value !== xdr.ScValType.scvVec().value) {\n return null;\n }\n\n const parsed: AuthEntrySignature[] = [];\n for (const element of signature.vec() ?? []) {\n if (element.switch().value !== xdr.ScValType.scvMap().value) {\n return null;\n }\n let publicKey: Buffer | null = null;\n let sig: Buffer | null = null;\n for (const mapEntry of element.map() ?? []) {\n const key = mapEntry.key();\n const val = mapEntry.val();\n if (\n key.switch().value !== xdr.ScValType.scvSymbol().value ||\n val.switch().value !== xdr.ScValType.scvBytes().value\n ) {\n return null;\n }\n switch (key.sym().toString()) {\n case \"public_key\":\n publicKey = val.bytes();\n break;\n case \"signature\":\n sig = val.bytes();\n break;\n default:\n return null;\n }\n }\n if (\n publicKey === null ||\n sig === null ||\n publicKey.length !== 32 ||\n sig.length !== 64\n ) {\n return null;\n }\n parsed.push({\n publicKey: StrKey.encodeEd25519PublicKey(publicKey),\n signature: sig,\n });\n }\n\n return parsed;\n}\n\nfunction bytesToInt64(bytes: Uint8Array): bigint {\n const buf = bytes.subarray(0, 8);\n if (buf.length < 8) {\n throw new Error(\n `need at least 8 bytes to convert to Int64, got ${bytes.length}`,\n );\n }\n const view = new DataView(buf.buffer, buf.byteOffset, 8);\n const value = view.getBigInt64(0, false);\n\n return value;\n}\n"],"names":["Buffer","xdr","hash","Address","Keypair","nativeToScVal","StrKey"],"mappings":";;;;;;;;;;AAaA,SAAS,SAAS,KAAA,EAA2B;AAC3C,EAAA,IAAI,iBAAiB,WAAA,EAAa;AAChC,IAAA,OAAOA,aAAA,CAAO,IAAA,CAAK,IAAI,UAAA,CAAW,KAAK,CAAC,CAAA;AAAA,EAC1C;AACA,EAAA,OAAOA,aAAA,CAAO,KAAK,KAAK,CAAA;AAC1B;AAgJA,eAAsB,cAAA,CACpB,KAAA,EACA,MAAA,EACA,mBAAA,EACA,mBACA,UAAA,EACwC;AAExC,EAAA,IACE,KAAA,CAAM,WAAA,EAAY,CAAE,MAAA,EAAO,CAAE,UAC7BC,sBAAA,CAAI,sBAAA,CAAuB,+BAAA,EAAgC,CAAE,KAAA,EAC7D;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,MAAM,QAAQA,sBAAA,CAAI,yBAAA,CAA0B,OA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