diff --git a/docs/api/account-manager.md b/docs/api/account-manager.md index 01ba163..7d88adb 100644 --- a/docs/api/account-manager.md +++ b/docs/api/account-manager.md @@ -179,6 +179,35 @@ console.log(`Funded with ${balance} XLM`); --- +### `signMultiSigTransaction(transaction, signerSecrets, requiredThreshold?, signerWeights?)` + +Validate threshold and signer weights, deduplicate signers by public key, verify that accumulated weight meets `requiredThreshold`, and sign `transaction` atomically. + +**Signature:** +```typescript +signMultiSigTransaction( + transaction: Transaction, + signerSecrets: string[], + requiredThreshold?: number, + signerWeights?: Record, +): Transaction +``` + +**Parameters:** +- `transaction` (`Transaction`): Stellar SDK `Transaction` instance to sign. +- `signerSecrets` (`string[]`): Non-empty array of Stellar secret keys (`S...`). Duplicate secrets resolving to the same public key are counted and applied once. +- `requiredThreshold` (`number`, default `1`): Required operation threshold; must be a finite integer between `1` and `255`. +- `signerWeights` (`Record`, optional): Map of Stellar public keys (`G...`) to active integer weights (`1`–`255`). + - **Omitted policy**: When `signerWeights` is `undefined`, every unique signer contributes weight `1`. + - **Explicit map policy**: When `signerWeights` is provided, every entry must be a finite integer in `1..255` and every participating signer must have an own property in `signerWeights`. Unlisted signers throw `ValidationError` rather than defaulting to `1` (preventing silent threshold inflation and `tx_bad_auth_extra` rejections). + +**Throws:** +- `ToolkitError` (`ERR_INVALID_THRESHOLD`) if `requiredThreshold` is outside `1..255` or non-integer. +- `ValidationError` (`ERR_VALIDATION_FAILED`) if `transaction`, `signerSecrets`, or `signerWeights` is invalid or omits a participating signer. +- `ToolkitError` (`ERR_INSUFFICIENT_SIGNATURES`) if total unique signer weight is less than `requiredThreshold`. On any validation or threshold error, `transaction` is never mutated. + +--- + ## Error Handling All async methods can throw errors. Common error scenarios: diff --git a/src/__tests__/account.test.ts b/src/__tests__/account.test.ts index da8633d..b7f0244 100644 --- a/src/__tests__/account.test.ts +++ b/src/__tests__/account.test.ts @@ -7,7 +7,7 @@ import { Operation, TransactionBuilder, } from 'stellar-sdk'; -import { StellarToolkit } from '../index'; +import { ErrorCode, StellarToolkit, ToolkitError, ValidationError } from '../index'; describe('StellarToolkit - Account & Multi-Sig Operations', () => { let toolkit: StellarToolkit; @@ -253,5 +253,169 @@ describe('StellarToolkit - Account & Multi-Sig Operations', () => { }); expect(signed.signatures.length).toBe(1); }); + + describe('signMultiSigTransaction security validation (#31)', () => { + const buildSampleTx = (sourceKey: Keypair) => { + const dest = Keypair.random(); + const account = new Account(sourceKey.publicKey(), '200'); + return new TransactionBuilder(account, { + fee: BASE_FEE, + networkPassphrase: Networks.TESTNET, + }) + .addOperation( + Operation.payment({ + destination: dest.publicKey(), + asset: Asset.native(), + amount: '5', + }), + ) + .setTimeout(180) + .build(); + }; + + it('rejects zero, negative, fractional, non-finite, and excessive requiredThreshold without mutating transaction', () => { + const s1 = Keypair.random(); + const invalidThresholds = [ + 0, + -1, + -255, + 1.5, + 2.01, + Number.NaN, + Number.POSITIVE_INFINITY, + 256, + 1000, + ]; + + for (const threshold of invalidThresholds) { + const tx = buildSampleTx(s1); + expect(() => toolkit.signMultiSigTransaction(tx, [s1.secret()], threshold)).toThrow( + ToolkitError, + ); + try { + toolkit.signMultiSigTransaction(tx, [s1.secret()], threshold); + } catch (err) { + expect((err as ToolkitError).code).toBe(ErrorCode.INVALID_THRESHOLD); + } + expect(tx.signatures).toHaveLength(0); + } + }); + + it('rejects zero, negative, fractional, non-finite, and excessive signerWeights without mutating transaction', () => { + const s1 = Keypair.random(); + const invalidWeights = [ + 0, + -1, + -10, + 0.5, + 2.75, + Number.NaN, + Number.POSITIVE_INFINITY, + 256, + 999, + ]; + + for (const weight of invalidWeights) { + const tx = buildSampleTx(s1); + expect(() => + toolkit.signMultiSigTransaction(tx, [s1.secret()], 1, { + [s1.publicKey()]: weight, + }), + ).toThrow(ValidationError); + expect(tx.signatures).toHaveLength(0); + } + }); + + it('counts duplicate signers (including whitespace-padded secrets) only once and leaves tx unsigned on failure', () => { + const s1 = Keypair.random(); + const txFail = buildSampleTx(s1); + + expect(() => + toolkit.signMultiSigTransaction( + txFail, + [s1.secret(), s1.secret(), ` ${s1.secret()} `], + 2, + { [s1.publicKey()]: 1 }, + ), + ).toThrow(/Insufficient signatures/i); + expect(txFail.signatures).toHaveLength(0); + + const txPass = buildSampleTx(s1); + const signed = toolkit.signMultiSigTransaction( + txPass, + [s1.secret(), s1.secret(), ` ${s1.secret()} `], + 2, + { [s1.publicKey()]: 2 }, + ); + expect(signed.signatures).toHaveLength(1); + }); + + it('rejects missing signer weights when signerWeights is provided instead of silently inflating weight', () => { + const authorized = Keypair.random(); + const unlisted = Keypair.random(); + const tx = buildSampleTx(authorized); + + expect(() => + toolkit.signMultiSigTransaction(tx, [authorized.secret(), unlisted.secret()], 2, { + [authorized.publicKey()]: 1, + }), + ).toThrow(ValidationError); + expect(tx.signatures).toHaveLength(0); + }); + + it('does not use inherited Object.prototype properties as signer weights', () => { + const s1 = Keypair.random(); + const tx = buildSampleTx(s1); + const proto = { [s1.publicKey()]: 5 }; + const weightsWithInherited = Object.create(proto) as Record; + + expect(() => + toolkit.signMultiSigTransaction(tx, [s1.secret()], 1, weightsWithInherited), + ).toThrow(ValidationError); + expect(tx.signatures).toHaveLength(0); + }); + + it('leaves transaction completely untouched when accumulated weight is insufficient', () => { + const s1 = Keypair.random(); + const s2 = Keypair.random(); + const tx = buildSampleTx(s1); + + try { + toolkit.signMultiSigTransaction(tx, [s1.secret(), s2.secret()], 5, { + [s1.publicKey()]: 2, + [s2.publicKey()]: 2, + }); + throw new Error('Expected signMultiSigTransaction to throw'); + } catch (err) { + expect(err).toBeInstanceOf(ToolkitError); + expect((err as ToolkitError).code).toBe(ErrorCode.INSUFFICIENT_SIGNATURES); + } + + expect(tx.signatures).toHaveLength(0); + }); + + it('rejects empty signerSecrets, malformed secrets, invalid transaction, and non-object signerWeights', () => { + const s1 = Keypair.random(); + const tx = buildSampleTx(s1); + + expect(() => toolkit.signMultiSigTransaction(tx, [], 1)).toThrow(ValidationError); + expect(() => toolkit.signMultiSigTransaction(tx, [''], 1)).toThrow(ValidationError); + expect(() => toolkit.signMultiSigTransaction(tx, ['not-a-valid-secret'], 1)).toThrow( + ValidationError, + ); + expect(() => + toolkit.signMultiSigTransaction(null as unknown as never, [s1.secret()], 1), + ).toThrow(ValidationError); + expect(() => + toolkit.signMultiSigTransaction( + tx, + [s1.secret()], + 1, + [] as unknown as Record, + ), + ).toThrow(ValidationError); + expect(tx.signatures).toHaveLength(0); + }); + }); }); }); diff --git a/src/core/account.ts b/src/core/account.ts index 0a1ad0f..b777b3a 100644 --- a/src/core/account.ts +++ b/src/core/account.ts @@ -6,13 +6,17 @@ import { BASE_FEE, Transaction, } from 'stellar-sdk'; -import { AccountInfo, Balance, MultiSigConfig } from '../types'; +import { AccountInfo, Balance, ErrorCode, MultiSigConfig } from '../types'; import { Server } from '../utils/network'; -import { AccountNotFoundError, ValidationError } from '../errors'; +import { AccountNotFoundError, ToolkitError, ValidationError } from '../errors'; export type AccountResponse = Horizon.AccountResponse; export const MAX_STELLAR_SIGNERS = 20; +export const MIN_SIGNING_THRESHOLD = 1; +export const MAX_SIGNING_THRESHOLD = 255; +export const MIN_SIGNER_WEIGHT = 1; +export const MAX_SIGNER_WEIGHT = 255; export class AccountManager { constructor( @@ -234,7 +238,16 @@ export class AccountManager { } /** - * Sign a transaction with multiple signers and verify threshold satisfaction + * Sign a transaction with multiple signers and verify threshold satisfaction. + * + * Validation & missing-weight policy: + * - `requiredThreshold` must be a finite integer in `1..255`. + * - When `signerWeights` is omitted, each unique signer contributes weight `1`. + * - When `signerWeights` is provided, every entry must be a finite integer in `1..255`, + * and every participating signer must have an explicit own property in `signerWeights` + * (missing signer weights throw `ValidationError` rather than defaulting to `1`). + * - Duplicate secrets resolving to the same public key are counted and applied once. + * - `transaction` is never mutated unless all validations and threshold checks succeed. */ signMultiSigTransaction( transaction: Transaction, @@ -242,22 +255,109 @@ export class AccountManager { requiredThreshold = 1, signerWeights?: Record, ): Transaction { - const uniqueSecrets = Array.from(new Set(signerSecrets)); - let accumulatedWeight = 0; + if (!transaction || typeof transaction.sign !== 'function') { + throw new ValidationError('transaction', 'A valid Stellar Transaction instance is required'); + } - for (const secret of uniqueSecrets) { - const kp = Keypair.fromSecret(secret); - const weight = signerWeights ? (signerWeights[kp.publicKey()] ?? 1) : 1; - accumulatedWeight += weight; - transaction.sign(kp); + if ( + !Number.isInteger(requiredThreshold) || + requiredThreshold < MIN_SIGNING_THRESHOLD || + requiredThreshold > MAX_SIGNING_THRESHOLD + ) { + throw new ToolkitError( + `Invalid requiredThreshold (${String(requiredThreshold)}): threshold out of range (must be an integer between ${MIN_SIGNING_THRESHOLD} and ${MAX_SIGNING_THRESHOLD}).`, + { + code: ErrorCode.INVALID_THRESHOLD, + category: 'validation', + recoverySuggestion: `Provide an integer requiredThreshold between ${MIN_SIGNING_THRESHOLD} and ${MAX_SIGNING_THRESHOLD} matching the Stellar operation threshold.`, + retryable: false, + details: { requiredThreshold }, + }, + ); + } + + if (!Array.isArray(signerSecrets) || signerSecrets.length === 0) { + throw new ValidationError('signerSecrets', 'At least one signer secret is required'); + } + + if (signerWeights !== undefined) { + if ( + typeof signerWeights !== 'object' || + signerWeights === null || + Array.isArray(signerWeights) + ) { + throw new ValidationError( + 'signerWeights', + 'Signer weights must be a plain object mapping Stellar public keys to integer weights', + ); + } + + for (const [publicKey, weight] of Object.entries(signerWeights)) { + if (!Number.isInteger(weight) || weight < MIN_SIGNER_WEIGHT || weight > MAX_SIGNER_WEIGHT) { + throw new ValidationError( + 'signerWeights', + `Weight for signer ${publicKey} out of range (must be an integer between ${MIN_SIGNER_WEIGHT} and ${MAX_SIGNER_WEIGHT})`, + ); + } + } + } + + const seenPublicKeys = new Set(); + const uniqueKeypairs: Keypair[] = []; + + for (const rawSecret of signerSecrets) { + if (typeof rawSecret !== 'string' || rawSecret.trim().length === 0) { + throw new ValidationError('signerSecrets', 'Each signer secret must be a non-empty string'); + } + + let kp: Keypair; + try { + kp = Keypair.fromSecret(rawSecret.trim()); + } catch { + throw new ValidationError('signerSecrets', 'Invalid Stellar secret key'); + } + + const publicKey = kp.publicKey(); + if (!seenPublicKeys.has(publicKey)) { + seenPublicKeys.add(publicKey); + uniqueKeypairs.push(kp); + } + } + + let accumulatedWeight = 0; + for (const kp of uniqueKeypairs) { + const publicKey = kp.publicKey(); + if (signerWeights !== undefined) { + if (!Object.prototype.hasOwnProperty.call(signerWeights, publicKey)) { + throw new ValidationError( + 'signerWeights', + `Missing signer weight for public key ${publicKey}; all participating signers must be explicitly listed when signerWeights is provided`, + ); + } + accumulatedWeight += signerWeights[publicKey]; + } else { + accumulatedWeight += 1; + } } if (accumulatedWeight < requiredThreshold) { - throw new Error( + throw new ToolkitError( `Insufficient signatures: accumulated weight ${accumulatedWeight} is below required threshold ${requiredThreshold}`, + { + code: ErrorCode.INSUFFICIENT_SIGNATURES, + category: 'transaction', + recoverySuggestion: + 'Provide additional authorized signers whose combined unique weights meet or exceed the required threshold.', + retryable: false, + details: { accumulatedWeight, requiredThreshold }, + }, ); } + for (const kp of uniqueKeypairs) { + transaction.sign(kp); + } + return transaction; } }