@babylonlabs-io/ts-sdk 3.0.1 → 3.1.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/dist/ApplicationRegistry.abi-s8cQ1ooR.js +160 -0
- package/dist/ApplicationRegistry.abi-s8cQ1ooR.js.map +1 -0
- package/dist/ApplicationRegistry.abi-sMiTWmnL.cjs +2 -0
- package/dist/ApplicationRegistry.abi-sMiTWmnL.cjs.map +1 -0
- package/dist/{BTCVaultRegistry.abi-BQ5tFNSu.cjs → BTCVaultRegistry.abi-CohlJX7c.cjs} +2 -2
- package/dist/{BTCVaultRegistry.abi-BQ5tFNSu.cjs.map → BTCVaultRegistry.abi-CohlJX7c.cjs.map} +1 -1
- package/dist/{BTCVaultRegistry.abi-B0x9_Bza.js → BTCVaultRegistry.abi-DBW0dyqH.js} +63 -1
- package/dist/{BTCVaultRegistry.abi-B0x9_Bza.js.map → BTCVaultRegistry.abi-DBW0dyqH.js.map} +1 -1
- package/dist/{PayoutManager-BSwbUQeF.js → PayoutManager-BZ212yml.js} +124 -123
- package/dist/PayoutManager-BZ212yml.js.map +1 -0
- package/dist/PayoutManager-DOdsgcUR.cjs +2 -0
- package/dist/PayoutManager-DOdsgcUR.cjs.map +1 -0
- package/dist/PeginManager-8EUlm10F.cjs +2 -0
- package/dist/{PeginManager-IgDHy_eU.cjs.map → PeginManager-8EUlm10F.cjs.map} +1 -1
- package/dist/{PeginManager-D8WGB8eN.js → PeginManager-QRwMUxZg.js} +45 -43
- package/dist/{PeginManager-D8WGB8eN.js.map → PeginManager-QRwMUxZg.js.map} +1 -1
- package/dist/{ProtocolParams.abi-q0AidvYX.js → ProtocolParams.abi-CKOVqFJP.js} +2 -158
- package/dist/ProtocolParams.abi-CKOVqFJP.js.map +1 -0
- package/dist/ProtocolParams.abi-CjrT0545.cjs +2 -0
- package/dist/ProtocolParams.abi-CjrT0545.cjs.map +1 -0
- package/dist/btcTxHash-BRZ8_EZq.js +9 -0
- package/dist/btcTxHash-BRZ8_EZq.js.map +1 -0
- package/dist/btcTxHash-CGb5BqFL.cjs +2 -0
- package/dist/btcTxHash-CGb5BqFL.cjs.map +1 -0
- package/dist/buildAndBroadcastReclaim-DjX7wVb2.cjs +2 -0
- package/dist/buildAndBroadcastReclaim-DjX7wVb2.cjs.map +1 -0
- package/dist/buildAndBroadcastReclaim-DoprHX7o.js +3077 -0
- package/dist/buildAndBroadcastReclaim-DoprHX7o.js.map +1 -0
- package/dist/buildVaultContextInputForClaim-9XZaqIiw.cjs +2 -0
- package/dist/buildVaultContextInputForClaim-9XZaqIiw.cjs.map +1 -0
- package/dist/buildVaultContextInputForClaim-DhBoQKyN.js +25 -0
- package/dist/buildVaultContextInputForClaim-DhBoQKyN.js.map +1 -0
- package/dist/constants-BeYquVd-.js +36 -0
- package/dist/constants-BeYquVd-.js.map +1 -0
- package/dist/constants-BwCg5K6R.cjs +2 -0
- package/dist/constants-BwCg5K6R.cjs.map +1 -0
- package/dist/{index-D2mybjXD.js → index-CVBtBjQ5.js} +2 -2
- package/dist/{index-D2mybjXD.js.map → index-CVBtBjQ5.js.map} +1 -1
- package/dist/{index-MRdle0fs.cjs → index-DpjYs5yr.cjs} +2 -2
- package/dist/{index-MRdle0fs.cjs.map → index-DpjYs5yr.cjs.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +288 -260
- package/dist/index.js.map +1 -1
- package/dist/{noPayout-qBXWKwav.js → noPayout-B-vGXJ-V.js} +3 -3
- package/dist/{noPayout-qBXWKwav.js.map → noPayout-B-vGXJ-V.js.map} +1 -1
- package/dist/{noPayout-DAWBQ0eG.cjs → noPayout-DOHak0ui.cjs} +2 -2
- package/dist/{noPayout-DAWBQ0eG.cjs.map → noPayout-DOHak0ui.cjs.map} +1 -1
- package/dist/pegin-registration-client-BWMwxtr8.js +718 -0
- package/dist/pegin-registration-client-BWMwxtr8.js.map +1 -0
- package/dist/pegin-registration-client-D4EguWaz.cjs +2 -0
- package/dist/pegin-registration-client-D4EguWaz.cjs.map +1 -0
- package/dist/{primeVpAuth-BDWBKYhv.cjs → primeVpAuth-BPj2TPdD.cjs} +2 -2
- package/dist/{primeVpAuth-BDWBKYhv.cjs.map → primeVpAuth-BPj2TPdD.cjs.map} +1 -1
- package/dist/{primeVpAuth-D0ZnsjRi.js → primeVpAuth-CiCdRNGf.js} +2 -2
- package/dist/{primeVpAuth-D0ZnsjRi.js.map → primeVpAuth-CiCdRNGf.js.map} +1 -1
- package/dist/registration-records-CKLAv3gw.js +447 -0
- package/dist/registration-records-CKLAv3gw.js.map +1 -0
- package/dist/registration-records-DFQgBaYi.cjs +2 -0
- package/dist/registration-records-DFQgBaYi.cjs.map +1 -0
- package/dist/{secp256k1-D-H9jmd7.js → secp256k1-BuxBFUHm.js} +3 -3
- package/dist/{secp256k1-D-H9jmd7.js.map → secp256k1-BuxBFUHm.js.map} +1 -1
- package/dist/signer-set-reader-C1VmC9_U.js +264 -0
- package/dist/signer-set-reader-C1VmC9_U.js.map +1 -0
- package/dist/signer-set-reader-C6g47hdk.cjs +2 -0
- package/dist/signer-set-reader-C6g47hdk.cjs.map +1 -0
- package/dist/{signing-Dhr2t0Z6.js → signing-C1rR4tqs.js} +9 -15
- package/dist/signing-C1rR4tqs.js.map +1 -0
- package/dist/signing-DvISftFk.cjs +2 -0
- package/dist/signing-DvISftFk.cjs.map +1 -0
- package/dist/tbv/core/clients/eth/__tests__/registration-records.test.d.ts +2 -0
- package/dist/tbv/core/clients/eth/__tests__/registration-records.test.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/claimable-event-error.d.ts +14 -0
- package/dist/tbv/core/clients/eth/claimable-event-error.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/index.cjs +1 -1
- package/dist/tbv/core/clients/eth/index.d.ts +3 -1
- package/dist/tbv/core/clients/eth/index.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/index.js +27 -21
- package/dist/tbv/core/clients/eth/index.js.map +1 -1
- package/dist/tbv/core/clients/eth/payout-script.d.ts +8 -0
- package/dist/tbv/core/clients/eth/payout-script.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts +13 -0
- package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/registration-logs-error.d.ts +11 -1
- package/dist/tbv/core/clients/eth/registration-logs-error.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/registration-records.d.ts +29 -0
- package/dist/tbv/core/clients/eth/registration-records.d.ts.map +1 -0
- package/dist/tbv/core/clients/eth/types.d.ts +120 -3
- package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +9 -10
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +56 -50
- package/dist/tbv/core/clients/index.js.map +1 -1
- package/dist/tbv/core/clients/vault-provider/status/index.cjs +1 -1
- package/dist/tbv/core/clients/vault-provider/status/index.js +1 -1
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +45 -0
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
- package/dist/tbv/core/contracts/index.cjs +1 -1
- package/dist/tbv/core/contracts/index.js +16 -15
- package/dist/tbv/core/contracts/index.js.map +1 -1
- package/dist/tbv/core/deposit-terms/__tests__/claimSiblings.test.d.ts +2 -0
- package/dist/tbv/core/deposit-terms/__tests__/claimSiblings.test.d.ts.map +1 -0
- package/dist/tbv/core/deposit-terms/__tests__/fixtures/realFundedPrePegin.d.ts +29 -0
- package/dist/tbv/core/deposit-terms/__tests__/fixtures/realFundedPrePegin.d.ts.map +1 -0
- package/dist/tbv/core/deposit-terms/__tests__/fundedPrePeginFee.test.d.ts +2 -0
- package/dist/tbv/core/deposit-terms/__tests__/fundedPrePeginFee.test.d.ts.map +1 -0
- package/dist/tbv/core/deposit-terms/__tests__/rebuildDepositTermsForClaim.golden.test.d.ts +2 -0
- package/dist/tbv/core/deposit-terms/__tests__/rebuildDepositTermsForClaim.golden.test.d.ts.map +1 -0
- package/dist/tbv/core/deposit-terms/__tests__/rebuildDepositTermsForClaim.test.d.ts +2 -0
- package/dist/tbv/core/deposit-terms/__tests__/rebuildDepositTermsForClaim.test.d.ts.map +1 -0
- package/dist/tbv/core/deposit-terms/claimSiblings.d.ts +23 -0
- package/dist/tbv/core/deposit-terms/claimSiblings.d.ts.map +1 -0
- package/dist/tbv/core/deposit-terms/fundedPrePeginFee.d.ts +15 -0
- package/dist/tbv/core/deposit-terms/fundedPrePeginFee.d.ts.map +1 -0
- package/dist/tbv/core/deposit-terms/index.d.ts +3 -0
- package/dist/tbv/core/deposit-terms/index.d.ts.map +1 -1
- package/dist/tbv/core/deposit-terms/rebuildDepositTermsForClaim.d.ts +40 -0
- package/dist/tbv/core/deposit-terms/rebuildDepositTermsForClaim.d.ts.map +1 -0
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +287 -259
- package/dist/tbv/core/index.js.map +1 -1
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +2 -2
- package/dist/tbv/core/managers/pegin/signPsbtsWithFallback.d.ts +6 -2
- package/dist/tbv/core/managers/pegin/signPsbtsWithFallback.d.ts.map +1 -1
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.js +4 -4
- package/dist/tbv/core/primitives/psbt/constants.d.ts +54 -6
- package/dist/tbv/core/primitives/psbt/constants.d.ts.map +1 -1
- package/dist/tbv/core/services/delegated-claim/__tests__/assembleWatchtowerArtifactsFromSignatures.test.d.ts +2 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/assembleWatchtowerArtifactsFromSignatures.test.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/assertBinding.test.d.ts +2 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/assertBinding.test.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/assertPayoutFeeAndTimelocks.test.d.ts +2 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/assertPayoutFeeAndTimelocks.test.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/fixtures/delegatedClaimPsbts.d.ts +49 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/fixtures/delegatedClaimPsbts.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/payoutBinding.test.d.ts +2 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/payoutBinding.test.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/payoutInputLeaf.test.d.ts +2 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/payoutInputLeaf.test.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/planDelegatedClaimSigning.test.d.ts +2 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/planDelegatedClaimSigning.test.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/readDelegatedClaimVaultContext.test.d.ts +2 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/readDelegatedClaimVaultContext.test.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/realSchnorrVerification.test.d.ts +2 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/realSchnorrVerification.test.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/signDelegatedClaimPlan.test.d.ts +2 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/signDelegatedClaimPlan.test.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/signingRequests.test.d.ts +2 -0
- package/dist/tbv/core/services/delegated-claim/__tests__/signingRequests.test.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.d.ts +34 -9
- package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifacts.d.ts.map +1 -1
- package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifactsFromSignatures.d.ts +36 -0
- package/dist/tbv/core/services/delegated-claim/assembleWatchtowerArtifactsFromSignatures.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/assertBinding.d.ts +37 -0
- package/dist/tbv/core/services/delegated-claim/assertBinding.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/assertPayoutFeeAndTimelocks.d.ts +35 -0
- package/dist/tbv/core/services/delegated-claim/assertPayoutFeeAndTimelocks.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/index.d.ts +22 -4
- package/dist/tbv/core/services/delegated-claim/index.d.ts.map +1 -1
- package/dist/tbv/core/services/delegated-claim/payoutBinding.d.ts +10 -4
- package/dist/tbv/core/services/delegated-claim/payoutBinding.d.ts.map +1 -1
- package/dist/tbv/core/services/delegated-claim/payoutInputLeaf.d.ts +34 -0
- package/dist/tbv/core/services/delegated-claim/payoutInputLeaf.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/planDelegatedClaimSigning.d.ts +43 -0
- package/dist/tbv/core/services/delegated-claim/planDelegatedClaimSigning.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/readDelegatedClaimVaultContext.d.ts +70 -0
- package/dist/tbv/core/services/delegated-claim/readDelegatedClaimVaultContext.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/readWatchtowerArtifacts.d.ts +31 -2
- package/dist/tbv/core/services/delegated-claim/readWatchtowerArtifacts.d.ts.map +1 -1
- package/dist/tbv/core/services/delegated-claim/signDelegatedClaimPlan.d.ts +110 -0
- package/dist/tbv/core/services/delegated-claim/signDelegatedClaimPlan.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/signingRequests.d.ts +24 -0
- package/dist/tbv/core/services/delegated-claim/signingRequests.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/types.d.ts +110 -9
- package/dist/tbv/core/services/delegated-claim/types.d.ts.map +1 -1
- package/dist/tbv/core/services/delegated-claim/vaultIdBinding.d.ts +16 -1
- package/dist/tbv/core/services/delegated-claim/vaultIdBinding.d.ts.map +1 -1
- package/dist/tbv/core/services/delegated-claim/verifySignatureForRequest.d.ts +19 -0
- package/dist/tbv/core/services/delegated-claim/verifySignatureForRequest.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/verifyingKeyBinding.d.ts +40 -0
- package/dist/tbv/core/services/delegated-claim/verifyingKeyBinding.d.ts.map +1 -0
- package/dist/tbv/core/services/delegated-claim/walletIdentity.d.ts +23 -0
- package/dist/tbv/core/services/delegated-claim/walletIdentity.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/graphFingerprint.d.ts +39 -0
- package/dist/tbv/core/services/deposit/graphFingerprint.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +89 -76
- package/dist/tbv/core/services/participants/__tests__/readStampedParticipantKeys.test.d.ts +2 -0
- package/dist/tbv/core/services/participants/__tests__/readStampedParticipantKeys.test.d.ts.map +1 -0
- package/dist/tbv/core/services/participants/index.d.ts +1 -0
- package/dist/tbv/core/services/participants/index.d.ts.map +1 -1
- package/dist/tbv/core/services/participants/readStampedParticipantKeys.d.ts +29 -0
- package/dist/tbv/core/services/participants/readStampedParticipantKeys.d.ts.map +1 -0
- package/dist/tbv/core/services/participants/resolveParticipantKeys.d.ts +1 -1
- package/dist/tbv/core/services/participants/resolveParticipantKeys.d.ts.map +1 -1
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +47 -46
- package/dist/tbv/core/utils/index.js.map +1 -1
- package/dist/tbv/core/vault-secrets/__tests__/buildVaultContextInputForClaim.test.d.ts +2 -0
- package/dist/tbv/core/vault-secrets/__tests__/buildVaultContextInputForClaim.test.d.ts.map +1 -0
- package/dist/tbv/core/vault-secrets/buildVaultContextInputForClaim.d.ts +18 -0
- package/dist/tbv/core/vault-secrets/buildVaultContextInputForClaim.d.ts.map +1 -0
- package/dist/tbv/core/vault-secrets/index.cjs +1 -1
- package/dist/tbv/core/vault-secrets/index.d.ts +1 -0
- package/dist/tbv/core/vault-secrets/index.d.ts.map +1 -1
- package/dist/tbv/core/vault-secrets/index.js +12 -10
- package/dist/tbv/core/vault-secrets/index.js.map +1 -1
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +287 -259
- package/dist/tbv/index.js.map +1 -1
- package/dist/toRefundInputs-BZXvuOMY.cjs +2 -0
- package/dist/toRefundInputs-BZXvuOMY.cjs.map +1 -0
- package/dist/toRefundInputs-dKDSvpVI.js +698 -0
- package/dist/toRefundInputs-dKDSvpVI.js.map +1 -0
- package/dist/types-Bda75Od0.cjs +2 -0
- package/dist/types-Bda75Od0.cjs.map +1 -0
- package/dist/types-C5jj3Cc-.js +198 -0
- package/dist/types-C5jj3Cc-.js.map +1 -0
- package/dist/{verifyKeyPathSchnorrSignature-Gm9EmZkx.cjs → verifyKeyPathSchnorrSignature-CQUut2-O.cjs} +2 -2
- package/dist/{verifyKeyPathSchnorrSignature-Gm9EmZkx.cjs.map → verifyKeyPathSchnorrSignature-CQUut2-O.cjs.map} +1 -1
- package/dist/{verifyKeyPathSchnorrSignature-BQHNhRj6.js → verifyKeyPathSchnorrSignature-DxPbeSdQ.js} +2 -2
- package/dist/{verifyKeyPathSchnorrSignature-BQHNhRj6.js.map → verifyKeyPathSchnorrSignature-DxPbeSdQ.js.map} +1 -1
- package/dist/{verifyScriptPathSchnorrSignature-CpjSTfMj.js → verifyScriptPathSchnorrSignature-B3-VkvnK.js} +6 -4
- package/dist/{verifyScriptPathSchnorrSignature-CpjSTfMj.js.map → verifyScriptPathSchnorrSignature-B3-VkvnK.js.map} +1 -1
- package/dist/{verifyScriptPathSchnorrSignature-BKZihCjk.cjs → verifyScriptPathSchnorrSignature-D2t1yACC.cjs} +2 -2
- package/dist/{verifyScriptPathSchnorrSignature-BKZihCjk.cjs.map → verifyScriptPathSchnorrSignature-D2t1yACC.cjs.map} +1 -1
- package/package.json +3 -3
- package/dist/PayoutManager-B6GFbG3X.cjs +0 -2
- package/dist/PayoutManager-B6GFbG3X.cjs.map +0 -1
- package/dist/PayoutManager-BSwbUQeF.js.map +0 -1
- package/dist/PeginManager-IgDHy_eU.cjs +0 -2
- package/dist/ProtocolParams.abi-Db2USqQm.cjs +0 -2
- package/dist/ProtocolParams.abi-Db2USqQm.cjs.map +0 -1
- package/dist/ProtocolParams.abi-q0AidvYX.js.map +0 -1
- package/dist/buildAndBroadcastReclaim-C55KaRJF.js +0 -2139
- package/dist/buildAndBroadcastReclaim-C55KaRJF.js.map +0 -1
- package/dist/buildAndBroadcastReclaim-CefzR6i_.cjs +0 -2
- package/dist/buildAndBroadcastReclaim-CefzR6i_.cjs.map +0 -1
- package/dist/constants-BTZdyOuk.cjs +0 -2
- package/dist/constants-BTZdyOuk.cjs.map +0 -1
- package/dist/constants-D5vORbQE.js +0 -29
- package/dist/constants-D5vORbQE.js.map +0 -1
- package/dist/onChainBtcPubkey-BlzxYImF.cjs +0 -2
- package/dist/onChainBtcPubkey-BlzxYImF.cjs.map +0 -1
- package/dist/onChainBtcPubkey-CCTdl53s.js +0 -159
- package/dist/onChainBtcPubkey-CCTdl53s.js.map +0 -1
- package/dist/pegin-registration-client-B0j6ugt9.cjs +0 -2
- package/dist/pegin-registration-client-B0j6ugt9.cjs.map +0 -1
- package/dist/pegin-registration-client-ilkV1mLP.js +0 -878
- package/dist/pegin-registration-client-ilkV1mLP.js.map +0 -1
- package/dist/signing-3l5Aqd-H.cjs +0 -2
- package/dist/signing-3l5Aqd-H.cjs.map +0 -1
- package/dist/signing-Dhr2t0Z6.js.map +0 -1
- package/dist/toRefundInputs-10RYIfh1.js +0 -559
- package/dist/toRefundInputs-10RYIfh1.js.map +0 -1
- package/dist/toRefundInputs-a-0HRyrl.cjs +0 -2
- package/dist/toRefundInputs-a-0HRyrl.cjs.map +0 -1
- package/dist/types-BueQoMjO.cjs +0 -2
- package/dist/types-BueQoMjO.cjs.map +0 -1
- package/dist/types-DGkejGZH.js +0 -456
- package/dist/types-DGkejGZH.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"primeVpAuth-D0ZnsjRi.js","sources":["../src/tbv/core/clients/vault-provider/auth/cbor.ts","../src/tbv/core/clients/vault-provider/auth/serverIdentity.ts","../src/tbv/core/clients/vault-provider/auth/gatedMethods.ts","../src/tbv/core/clients/vault-provider/auth/innerTokenClient.ts","../src/tbv/core/clients/vault-provider/auth/cborDecode.ts","../src/tbv/core/clients/vault-provider/auth/verifyDepositorCwt.ts","../src/tbv/core/clients/vault-provider/auth/tokenProvider.ts","../src/tbv/core/clients/vault-provider/auth/tokenRegistry.ts","../src/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.ts","../src/tbv/core/clients/vault-provider/auth/primeVpAuth.ts"],"sourcesContent":["/**\n * Minimal CBOR encoder for the server-identity payload shape.\n *\n * We only need to encode one specific CBOR structure — the 3-tuple\n * `(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey_bytes, expires_at_u64)` —\n * byte-for-byte identical to what the Rust `ciborium` crate produces\n * for the corresponding tuple, because that's the exact message the\n * VP signs with BIP-322.\n *\n * IMPORTANT encoding quirk: the Rust side passes the domain and\n * pubkey as `&[u8]` / `Vec<u8>` without a `#[serde(with = \"serde_bytes\")]`\n * attribute, so serde/ciborium encodes them as **CBOR arrays of u8**\n * (major type 4, one item per byte) — NOT as CBOR byte strings (major\n * type 2). A naive byte-string encoding would produce the wrong bytes\n * and signature verification would fail.\n *\n * Rather than pull in a full CBOR dependency for this one shape, we\n * implement the exact subset inline (~40 LOC) and pin it with golden\n * vectors against the Rust reference output.\n *\n * @module tbv/core/clients/vault-provider/auth/cbor\n */\n\n/**\n * Encode a small CBOR unsigned-integer \"head\" byte for major type\n * `major` (0..7) with argument `arg` (0..2^64-1).\n *\n * Returns the header bytes; the caller concatenates any trailing data\n * (e.g. array elements). Encoding rules:\n * arg < 24 → single byte `(major << 5) | arg`\n * arg < 256 → `(major << 5) | 24` + 1-byte arg\n * arg < 65536 → `(major << 5) | 25` + 2-byte BE arg\n * arg < 2^32 → `(major << 5) | 26` + 4-byte BE arg\n * arg < 2^64 → `(major << 5) | 27` + 8-byte BE arg\n */\nfunction cborHead(major: number, arg: number | bigint): Uint8Array {\n const tag = (major & 0x07) << 5;\n const n = typeof arg === \"bigint\" ? arg : BigInt(arg);\n if (n < 0n) throw new Error(\"cborHead: negative argument\");\n\n if (n < 24n) return new Uint8Array([tag | Number(n)]);\n if (n < 0x100n) return new Uint8Array([tag | 24, Number(n)]);\n if (n < 0x10000n) {\n const v = Number(n);\n return new Uint8Array([tag | 25, (v >>> 8) & 0xff, v & 0xff]);\n }\n if (n < 0x1_0000_0000n) {\n const v = Number(n);\n return new Uint8Array([\n tag | 26,\n (v >>> 24) & 0xff,\n (v >>> 16) & 0xff,\n (v >>> 8) & 0xff,\n v & 0xff,\n ]);\n }\n // 8-byte BE for u64 range\n const out = new Uint8Array(9);\n out[0] = tag | 27;\n for (let i = 7; i >= 0; i--) {\n out[1 + i] = Number(n >> BigInt((7 - i) * 8)) & 0xff;\n }\n return out;\n}\n\nfunction concat(...parts: Uint8Array[]): Uint8Array {\n const total = parts.reduce((s, p) => s + p.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const p of parts) {\n out.set(p, offset);\n offset += p.length;\n }\n return out;\n}\n\n/**\n * Encode a `Vec<u8>` / `&[u8]` the way ciborium does by default — as a\n * CBOR array of u8 (major type 4), one element per byte.\n *\n * Each byte becomes a CBOR unsigned integer (major type 0): bytes\n * < 24 are encoded as single bytes, bytes 24..255 as `0x18 XX`.\n */\nfunction encodeBytesAsArrayOfU8(bytes: Uint8Array): Uint8Array {\n const header = cborHead(4, bytes.length);\n const items: Uint8Array[] = [header];\n for (const b of bytes) {\n items.push(cborHead(0, b));\n }\n return concat(...items);\n}\n\n/**\n * Encode the server-identity payload the Rust side signs:\n *\n * ciborium::into_writer(\n * &(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey.serialize().to_vec(), expires_at),\n * buf\n * )\n *\n * Output bytes are byte-for-byte identical to the Rust reference,\n * pinned by the golden vector in the corresponding test file.\n *\n * @internal Exposed only for the golden-vector test that pins this\n * encoding against ciborium's output. Production callers reach this\n * via `verifyServerIdentity` from `./serverIdentity`.\n *\n * @param domain - Must be `\"btc-auth.server-identity.v1\"` (27 bytes)\n * — the constant from btc-vault's `server_identity.rs`.\n * @param ephemeralPubkeyCompressed - 33-byte SEC1-compressed pubkey.\n * @param expiresAt - Unix timestamp (seconds). Must be a safe integer.\n */\nexport function encodeServerIdentityPayload(\n domain: Uint8Array,\n ephemeralPubkeyCompressed: Uint8Array,\n expiresAt: number,\n): Uint8Array {\n if (!Number.isSafeInteger(expiresAt) || expiresAt < 0) {\n throw new Error(\n `encodeServerIdentityPayload: expires_at must be a non-negative safe integer, got ${expiresAt}`,\n );\n }\n const arrayHeader = cborHead(4, 3); // 3-tuple encoded as array of 3\n const domainBytes = encodeBytesAsArrayOfU8(domain);\n const pubkeyBytes = encodeBytesAsArrayOfU8(ephemeralPubkeyCompressed);\n const expiresAtBytes = cborHead(0, expiresAt);\n return concat(arrayHeader, domainBytes, pubkeyBytes, expiresAtBytes);\n}\n","/**\n * Server-identity verification for the vault provider's\n * `auth_createDepositorToken` response.\n *\n * The VP returns a `ServerIdentityResponse` bundled with every issued\n * token:\n *\n * - `server_pubkey`: VP's persistent x-only pubkey (HEX, 32B)\n * - `ephemeral_pubkey`: VP's ephemeral token-signing key (HEX, 33B compressed)\n * - `expires_at`: Unix timestamp when the ephemeral key expires\n * - `signature`: BIP-322 signature by the persistent key over\n * `(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey, expires_at)`\n *\n * The FE pins `server_pubkey` against the on-chain `VaultProvider.btcPubKey`\n * it reads from the registry contract. A mismatch rejects the token.\n *\n * @module tbv/core/clients/vault-provider/auth/serverIdentity\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\n\nimport {\n SCHNORR_SIG_HEX_LEN,\n stripHexPrefix,\n} from \"../../../primitives/utils/bitcoin\";\nimport {\n COMPRESSED_PUBKEY_HEX_LEN,\n HEX_RE,\n X_ONLY_PUBKEY_HEX_LEN,\n} from \"../../../utils/validation\";\n\nimport { verifyBip322Simple } from \"./bip322Verify\";\nimport { encodeServerIdentityPayload } from \"./cbor\";\n\n/**\n * Byte-string domain the btc-vault Rust reference passes as the first\n * element of the CBOR tuple signed over for server-identity proofs.\n * Must match `SERVER_IDENTITY_DOMAIN` in\n * `btc-vault/crates/btc-auth/src/server_identity.rs`.\n */\nconst SERVER_IDENTITY_DOMAIN = new TextEncoder().encode(\n \"btc-auth.server-identity.v1\",\n);\n\n/**\n * Cap on `proof.expires_at - now`. Bounds how long a leaked VP\n * ephemeral key stays usable; the bearer token's own TTL does not\n * (different trust boundary). 2h = Rust ref VP's 1h rotation × 2 for\n * clock skew. Override per call via `maxLifetimeSecs`.\n */\nconst DEFAULT_MAX_PROOF_LIFETIME_SECS = 2 * 3600;\n\n/**\n * Wire representation from btc-vault's `ServerIdentityResponse`.\n */\nexport interface ServerIdentityResponse {\n /** Hex-encoded x-only (32-byte) persistent server pubkey. */\n server_pubkey: string;\n /** Hex-encoded compressed (33-byte) ephemeral token-signing pubkey. */\n ephemeral_pubkey: string;\n /** Unix timestamp at which the ephemeral key expires. */\n expires_at: number;\n /** Hex-encoded 64-byte BIP-322 Schnorr signature. */\n signature: string;\n}\n\nexport interface VerifyServerIdentityInput {\n /** The proof returned by `auth_createDepositorToken`. */\n proof: ServerIdentityResponse;\n /**\n * The x-only persistent server pubkey the FE expects (sourced from\n * the on-chain `VaultProvider.btcPubKey` via the vault registry\n * reader). 64-char lowercase hex, no `0x` prefix.\n */\n pinnedServerPubkey: string;\n /** Current Unix timestamp in seconds. Injected for testability. */\n now: number;\n /** Cap on `proof.expires_at - now` (seconds). Defaults to {@link DEFAULT_MAX_PROOF_LIFETIME_SECS}. */\n maxLifetimeSecs?: number;\n}\n\nexport class ServerIdentityError extends Error {\n constructor(\n message: string,\n public readonly reason:\n | \"pinned_pubkey_mismatch\"\n | \"expired\"\n | \"expires_too_far\"\n | \"invalid_expires_at\"\n | \"invalid_max_lifetime\"\n | \"invalid_pubkey_encoding\"\n | \"invalid_ephemeral_pubkey\"\n | \"invalid_signature_encoding\"\n | \"signature_verification_failed\",\n ) {\n super(message);\n this.name = \"ServerIdentityError\";\n }\n}\n\n/** Parse a lowercase-hex string to bytes. Expects even length, already validated. */\nfunction hexToBytes(hex: string): Uint8Array {\n const out = new Uint8Array(hex.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\n/**\n * Verify a server identity proof against a pinned server pubkey.\n *\n * Checks:\n * 1. `server_pubkey` matches the pin.\n * 2. `now < expires_at <= now + maxLifetimeSecs` (with integer guards).\n * 3. `ephemeral_pubkey` is a well-formed 33-byte compressed pubkey.\n * 4. `signature` is a well-formed 64-byte Schnorr hex string.\n * 5. The BIP-322 Schnorr signature cryptographically verifies\n * against `server_pubkey` over the CBOR-encoded tuple\n * `(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey, expires_at)`.\n *\n * Step 5 is what actually binds the ephemeral key to the persistent\n * pubkey — without it, a TLS-MITM attacker who reads the pinned\n * pubkey from the on-chain registry could substitute an arbitrary\n * ephemeral pubkey paired with any lexically-valid signature.\n *\n * @throws ServerIdentityError on any validation failure.\n */\nexport function verifyServerIdentity(input: VerifyServerIdentityInput): void {\n const { proof, pinnedServerPubkey, now } = input;\n const maxLifetimeSecs =\n input.maxLifetimeSecs ?? DEFAULT_MAX_PROOF_LIFETIME_SECS;\n\n const pinned = stripHexPrefix(pinnedServerPubkey).toLowerCase();\n if (pinned.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(pinned)) {\n throw new ServerIdentityError(\n `pinnedServerPubkey must be 32-byte hex; got ${pinned.length} chars`,\n \"invalid_pubkey_encoding\",\n );\n }\n\n const actual = stripHexPrefix(proof.server_pubkey).toLowerCase();\n if (actual.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(actual)) {\n throw new ServerIdentityError(\n `server_pubkey must be 32-byte hex; got ${actual.length} chars`,\n \"invalid_pubkey_encoding\",\n );\n }\n\n if (actual !== pinned) {\n throw new ServerIdentityError(\n `server_pubkey does not match pinned value: expected ${pinned}, got ${actual}`,\n \"pinned_pubkey_mismatch\",\n );\n }\n\n // Validate both sides of the comparison are well-formed integers\n // BEFORE comparing — untrusted JSON-RPC input can supply\n // undefined/NaN/string values for `expires_at`, and relational\n // comparisons with those silently evaluate to `false` (accepting the\n // proof). Caller's `now` is injected but we still sanity-check it.\n // Garbage data and \"valid but past\" both render the proof unusable\n // but mean different things to a caller — keep the reasons distinct.\n if (!Number.isSafeInteger(proof.expires_at)) {\n throw new ServerIdentityError(\n `expires_at must be a finite integer; got ${JSON.stringify(proof.expires_at)}`,\n \"invalid_expires_at\",\n );\n }\n if (!Number.isSafeInteger(now)) {\n throw new ServerIdentityError(\n `now must be a finite integer; got ${JSON.stringify(now)}`,\n \"invalid_expires_at\",\n );\n }\n if (proof.expires_at <= now) {\n throw new ServerIdentityError(\n `server identity proof expired at ${proof.expires_at}, now ${now}`,\n \"expired\",\n );\n }\n if (!Number.isSafeInteger(maxLifetimeSecs) || maxLifetimeSecs <= 0) {\n throw new ServerIdentityError(\n `maxLifetimeSecs must be a positive safe integer; got ${JSON.stringify(maxLifetimeSecs)}`,\n \"invalid_max_lifetime\",\n );\n }\n if (proof.expires_at - now > maxLifetimeSecs) {\n throw new ServerIdentityError(\n `server identity proof expires too far in the future: ` +\n `expires_at=${proof.expires_at}, now=${now}, max lifetime=${maxLifetimeSecs}s`,\n \"expires_too_far\",\n );\n }\n\n const eph = stripHexPrefix(proof.ephemeral_pubkey).toLowerCase();\n if (eph.length !== COMPRESSED_PUBKEY_HEX_LEN || !HEX_RE.test(eph)) {\n throw new ServerIdentityError(\n `ephemeral_pubkey must be 33-byte compressed hex; got ${eph.length} chars`,\n \"invalid_ephemeral_pubkey\",\n );\n }\n const prefix = eph.slice(0, 2);\n if (prefix !== \"02\" && prefix !== \"03\") {\n throw new ServerIdentityError(\n `ephemeral_pubkey must be compressed (prefix 02/03); got ${prefix}`,\n \"invalid_ephemeral_pubkey\",\n );\n }\n // Curve validation. The BIP-322 signature attests to the byte string\n // of `ephemeral_pubkey` only, not to its curve validity. Without\n // this check, a server could sign a structurally-valid byte string\n // that doesn't decode to a secp256k1 point — passing verification\n // here and surfacing as an obscure crypto error later when the\n // depositor tries to use the key. Reject up front.\n const ephBytes = hexToBytes(eph);\n if (!ecc.isPoint(ephBytes)) {\n throw new ServerIdentityError(\n \"ephemeral_pubkey is not a valid secp256k1 point\",\n \"invalid_ephemeral_pubkey\",\n );\n }\n\n const sig = stripHexPrefix(proof.signature).toLowerCase();\n if (sig.length !== SCHNORR_SIG_HEX_LEN || !HEX_RE.test(sig)) {\n throw new ServerIdentityError(\n `signature must be 64-byte Schnorr hex; got ${sig.length} chars`,\n \"invalid_signature_encoding\",\n );\n }\n\n // Cryptographic verification of the BIP-322 signature over the\n // CBOR-encoded payload. Without this, the ephemeral-key binding is\n // unenforced and a TLS-MITM could substitute a fake ephemeral key\n // alongside the real (publicly-readable) pinned pubkey.\n const payload = encodeServerIdentityPayload(\n SERVER_IDENTITY_DOMAIN,\n hexToBytes(eph),\n proof.expires_at,\n );\n const verified = verifyBip322Simple(\n payload,\n hexToBytes(actual),\n hexToBytes(sig),\n );\n if (!verified) {\n throw new ServerIdentityError(\n \"BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey\",\n \"signature_verification_failed\",\n );\n }\n}\n","/**\n * VP RPC methods that require `Authorization: Bearer <token>`.\n * Protocol invariant — must be kept in sync with the VP server.\n *\n * Split into two sets by the CWT subject the VP demands:\n *\n * - {@link AUTH_GATED_METHODS} — bearer minted by\n * `auth_createDepositorToken` (Subject::VaultdJsonRpc). These run\n * through the proxy's plain JSON-RPC forward path.\n * - {@link GRPC_AUTH_GATED_METHODS} — bearer minted by\n * `auth_createDepositorTokenGrpc` (Subject::VaultdGrpc). The proxy\n * translates these into gRPC calls to vaultd's daemon gRPC server,\n * so a JSON-RPC-subject token would be rejected by\n * `GrpcAuthInterceptor`.\n *\n * @stability frozen\n *\n * @module tbv/core/clients/vault-provider/auth/gatedMethods\n */\n\nexport const AUTH_GATED_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_submitDepositorWotsKey\",\n \"vaultProvider_submitDepositorPresignatures\",\n \"vaultProvider_requestDepositorPresignTransactions\",\n]);\n\nexport const GRPC_AUTH_GATED_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_requestDepositorClaimerArtifacts\",\n]);\n","/**\n * Shared internals for the unauthenticated token-issuing JSON-RPC\n * client. The \"inner\" client is dedicated to `auth_createDepositorToken`\n * — it MUST NOT carry a `tokenProvider`, else the JSON-RPC header\n * builder would recurse into token acquisition.\n *\n * @module tbv/core/clients/vault-provider/auth/innerTokenClient\n */\n\nimport { JsonRpcClient } from \"../json-rpc-client\";\n\nconst TOKEN_RPC_TIMEOUT_MS = 60_000;\n\nexport const TOKEN_ISSUE_METHOD = \"auth_createDepositorToken\";\n/**\n * gRPC-subject sibling of {@link TOKEN_ISSUE_METHOD}. The proxy bridges\n * this call to vaultd's `VaultProviderDepositorAuthService.CreateDepositorToken`\n * so the resulting CWT is bound to `Subject::VaultdGrpc` — required to\n * pass vaultd's `GrpcAuthInterceptor` on methods the proxy translates to\n * gRPC (currently just the artifact stream).\n */\nexport const GRPC_TOKEN_ISSUE_METHOD = \"auth_createDepositorTokenGrpc\";\n\nexport function buildInnerTokenClient(\n baseUrl: string,\n headers?: Record<string, string>,\n): JsonRpcClient {\n return new JsonRpcClient({\n baseUrl,\n timeout: TOKEN_RPC_TIMEOUT_MS,\n headers,\n retryableFor: (method) =>\n method === TOKEN_ISSUE_METHOD || method === GRPC_TOKEN_ISSUE_METHOD,\n });\n}\n","/**\n * Minimal CBOR decoder — the read-side counterpart to {@link ./cbor}.\n *\n * Decodes only the subset needed to verify a vault-provider CWT bearer\n * token (RFC 8392) wrapped in a COSE Sign1 envelope (RFC 8152): tagged\n * values, definite-length arrays and maps, byte/text strings, and\n * unsigned/negative integers. Indefinite-length items, floats, and\n * big-number tags are intentionally rejected — the issuer\n * (btc-vault's `coset`/`ciborium` stack) never emits them for this\n * shape, so accepting them would only widen the parser's attack\n * surface.\n *\n * The decoder is a cursor over a single buffer. {@link CborReader.pos}\n * is public so callers can slice the exact encoded byte range of an\n * item (head + content) — required to reconstruct the COSE\n * `Sig_structure` byte-for-byte from the token's own protected-header\n * and payload byte strings.\n *\n * @module tbv/core/clients/vault-provider/auth/cborDecode\n */\n\n/** CBOR major types (the high 3 bits of the initial byte). */\nconst MAJOR_UNSIGNED_INT = 0;\nconst MAJOR_NEGATIVE_INT = 1;\nconst MAJOR_BYTE_STRING = 2;\nconst MAJOR_TEXT_STRING = 3;\nconst MAJOR_ARRAY = 4;\nconst MAJOR_MAP = 5;\nconst MAJOR_TAG = 6;\nconst MAJOR_SIMPLE = 7;\n\n/**\n * Smallest additional-info value that introduces a multi-byte argument\n * (24 ⇒ 1 byte, 25 ⇒ 2, 26 ⇒ 4, 27 ⇒ 8 — i.e. `1 << (info - 24)`).\n */\nconst ARG_IN_NEXT_1_BYTE = 24;\n/** Additional-info ≥ this (28..31) is reserved/indefinite — unsupported. */\nconst ARG_RESERVED_MIN = 28;\n\n/** Major-7 simple values we accept. */\nconst SIMPLE_FALSE = 20;\nconst SIMPLE_TRUE = 21;\nconst SIMPLE_NULL = 22;\n\n/**\n * Maximum CBOR nesting depth. Mirrors the issuer's recursion cap (256 in\n * btc-vault's `ciborium` stack). The COSE protected header is decoded\n * *before* the signature is verified, so without this bound a\n * malicious/MITM'd VP could send a deeply-nested blob and crash token\n * acquisition with an uncatchable stack overflow. Far below the JS call\n * stack limit, so it converts that DoS into a catchable decode error.\n */\nconst MAX_NESTING_DEPTH = 256;\n\n/** A decoded CBOR data item. Maps preserve key insertion order. */\nexport type CborValue =\n | number\n | bigint\n | string\n | Uint8Array\n | boolean\n | null\n | CborValue[]\n | Map<CborValue, CborValue>\n | CborTagged;\n\n/** A CBOR tagged value (major type 6). */\nexport interface CborTagged {\n tag: number;\n value: CborValue;\n}\n\n/** Parsed initial-byte header: major type plus its decoded argument. */\nexport interface CborHead {\n major: number;\n /** The header argument (length, value, tag number, …) as a number. */\n arg: number;\n}\n\nexport class CborDecodeError extends Error {\n constructor(message: string) {\n super(`CBOR decode: ${message}`);\n this.name = \"CborDecodeError\";\n }\n}\n\n/**\n * Cursor-based reader over a CBOR buffer. Not reusable across buffers —\n * construct one per decode.\n */\nexport class CborReader {\n readonly buf: Uint8Array;\n /** Current read offset. Public so callers can slice encoded sub-ranges. */\n pos = 0;\n\n constructor(buf: Uint8Array) {\n this.buf = buf;\n }\n\n private nextByte(): number {\n if (this.pos >= this.buf.length) {\n throw new CborDecodeError(\"unexpected end of input\");\n }\n return this.buf[this.pos++];\n }\n\n /**\n * Read an initial byte and its argument. Rejects indefinite-length\n * and reserved additional-info encodings. Arguments wider than\n * {@link Number.MAX_SAFE_INTEGER} are rejected — none of the token's\n * lengths, tags, or timestamps approach that bound.\n */\n readHead(): CborHead {\n const initial = this.nextByte();\n const major = initial >> 5;\n const info = initial & 0x1f;\n\n if (info < ARG_IN_NEXT_1_BYTE) {\n return { major, arg: info };\n }\n if (info >= ARG_RESERVED_MIN) {\n throw new CborDecodeError(\n `unsupported additional info ${info} (indefinite-length or reserved)`,\n );\n }\n\n const byteCount = 1 << (info - ARG_IN_NEXT_1_BYTE);\n\n let value = 0n;\n for (let i = 0; i < byteCount; i++) {\n value = (value << 8n) | BigInt(this.nextByte());\n }\n if (value > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new CborDecodeError(`argument ${value} exceeds safe integer range`);\n }\n return { major, arg: Number(value) };\n }\n\n /** Read `length` raw bytes as a sub-array view into the backing buffer. */\n private readBytes(length: number): Uint8Array {\n if (this.pos + length > this.buf.length) {\n throw new CborDecodeError(\"length overruns end of input\");\n }\n const slice = this.buf.subarray(this.pos, this.pos + length);\n this.pos += length;\n return slice;\n }\n\n /**\n * Read a byte string (major type 2), returning its content bytes.\n * Throws if the next item is not a byte string.\n */\n readByteString(): Uint8Array {\n const head = this.readHead();\n if (head.major !== MAJOR_BYTE_STRING) {\n throw new CborDecodeError(\n `expected byte string (major ${MAJOR_BYTE_STRING}), got major ${head.major}`,\n );\n }\n return this.readBytes(head.arg);\n }\n\n /**\n * Read the next complete data item as a decoded {@link CborValue}.\n *\n * `depth` tracks the current nesting level so a deeply-nested blob is\n * rejected with a {@link CborDecodeError} rather than overflowing the\n * native call stack (see {@link MAX_NESTING_DEPTH}).\n */\n readValue(depth = 0): CborValue {\n if (depth > MAX_NESTING_DEPTH) {\n throw new CborDecodeError(\n `nesting exceeds maximum depth ${MAX_NESTING_DEPTH}`,\n );\n }\n const head = this.readHead();\n switch (head.major) {\n case MAJOR_UNSIGNED_INT:\n return head.arg;\n case MAJOR_NEGATIVE_INT:\n // RFC 8949 §3.1: the encoded argument n represents -1 - n.\n return -1 - head.arg;\n case MAJOR_BYTE_STRING:\n return this.readBytes(head.arg);\n case MAJOR_TEXT_STRING:\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(\n this.readBytes(head.arg),\n );\n case MAJOR_ARRAY: {\n const items: CborValue[] = [];\n for (let i = 0; i < head.arg; i++) {\n items.push(this.readValue(depth + 1));\n }\n return items;\n }\n case MAJOR_MAP: {\n const map = new Map<CborValue, CborValue>();\n for (let i = 0; i < head.arg; i++) {\n const key = this.readValue(depth + 1);\n const value = this.readValue(depth + 1);\n map.set(key, value);\n }\n return map;\n }\n case MAJOR_TAG:\n return { tag: head.arg, value: this.readValue(depth + 1) };\n case MAJOR_SIMPLE:\n if (head.arg === SIMPLE_FALSE) return false;\n if (head.arg === SIMPLE_TRUE) return true;\n if (head.arg === SIMPLE_NULL) return null;\n throw new CborDecodeError(\n `unsupported simple/float value ${head.arg}`,\n );\n default:\n throw new CborDecodeError(`unsupported major type ${head.major}`);\n }\n }\n}\n\n/**\n * Decode a single CBOR item from `bytes`, rejecting any trailing bytes.\n *\n * Used to parse the COSE protected header and CWT claims set — both are\n * exactly one top-level item, so a valid prefix followed by extra bytes\n * is a malformed structure, not a benign tail. Strict consumption keeps\n * the parser from silently accepting a token a stricter CWT/COSE\n * consumer would interpret differently.\n */\nexport function decodeCbor(bytes: Uint8Array): CborValue {\n const reader = new CborReader(bytes);\n const value = reader.readValue();\n if (reader.pos !== bytes.length) {\n throw new CborDecodeError(\"trailing bytes after top-level item\");\n }\n return value;\n}\n","/**\n * Verify a vault-provider CWT bearer (RFC 8392 / COSE Sign1, ES256K): checks the\n * signature against the VP's attested ephemeral key (see {@link ./serverIdentity})\n * and binds `iss`/`sub`/`aud` to the pinned VP, subject, and depositor. TS port\n * of btc-vault `client.rs::validate_token_with_public_key_at_time`.\n *\n * Divergence from that reference: the FE does NOT clock-gate `nbf`/`iat`. The VP\n * server is the temporal authority and re-checks `nbf`/`exp` on every gated call;\n * re-checking `nbf` against the browser clock only bricked freshly minted tokens\n * on benign skew. `exp` (wide window) and the structural `iat <= exp` are kept.\n *\n * @module tbv/core/clients/vault-provider/auth/verifyDepositorCwt\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\n\nimport {\n hexToUint8Array,\n stripHexPrefix,\n} from \"../../../primitives/utils/bitcoin\";\nimport {\n COMPRESSED_PUBKEY_HEX_LEN,\n HEX_RE,\n X_ONLY_PUBKEY_HEX_LEN,\n} from \"../../../utils/validation\";\n\nimport { CborReader, decodeCbor } from \"./cborDecode\";\n\n/** CWT `sub` value for JSON-RPC-subject tokens (`auth_createDepositorToken`). */\nexport const CWT_SUBJECT_JSONRPC = \"vaultd-jsonrpc\";\n/** CWT `sub` value for gRPC-subject tokens (`auth_createDepositorTokenGrpc`). */\nexport const CWT_SUBJECT_GRPC = \"vaultd-grpc\";\n\n/** CBOR tag wrapping a COSE_Sign1 structure (RFC 8152 §2). */\nconst COSE_SIGN1_TAG = 18;\n/** A COSE_Sign1 is a 4-element array: [protected, unprotected, payload, signature]. */\nconst COSE_SIGN1_ARRAY_LEN = 4;\n/** COSE algorithm id for ES256K (ECDSA w/ secp256k1 + SHA-256), RFC 8812. */\nconst COSE_ALG_ES256K = -47;\n/** COSE header label for the algorithm (RFC 8152 §3.1). */\nconst COSE_HEADER_LABEL_ALG = 1;\n/** ECDSA signature length in COSE compact (r‖s) form. */\nconst ECDSA_COMPACT_SIG_LEN = 64;\n\n/** CBOR major-type 4 (array) high bits, for the Sig_structure header. */\nconst CBOR_ARRAY_HEAD = 0x80;\n/** CBOR major-type 3 (text string) high bits, for the context string head. */\nconst CBOR_TEXT_STRING_HEAD = 0x60;\n/** CBOR encoding of an empty byte string (major type 2, length 0). */\nconst CBOR_EMPTY_BYTE_STRING = 0x40;\n\n/** CWT registered claim keys (RFC 8392 §4 / IANA CWT registry). */\nconst CWT_CLAIM_ISS = 1;\nconst CWT_CLAIM_SUB = 2;\nconst CWT_CLAIM_AUD = 3;\nconst CWT_CLAIM_EXP = 4;\nconst CWT_CLAIM_NBF = 5;\nconst CWT_CLAIM_IAT = 6;\nconst CWT_CLAIM_CTI = 7;\n\n/**\n * Context string for a COSE_Sign1 Sig_structure (RFC 8152 §4.4). 10\n * bytes, so it encodes with a single-byte CBOR text-string head.\n */\nconst SIG_STRUCTURE_CONTEXT = new TextEncoder().encode(\"Signature1\");\n\nexport type CwtVerificationReason =\n | \"invalid_input\"\n | \"invalid_token_structure\"\n | \"unexpected_algorithm\"\n | \"signature_verification_failed\"\n | \"invalid_claims\"\n | \"issuer_mismatch\"\n | \"subject_mismatch\"\n | \"audience_mismatch\"\n | \"token_expired\"\n | \"expiry_mismatch\"\n | \"server_identity_expires_before_token\";\n\nexport class CwtVerificationError extends Error {\n constructor(\n message: string,\n public readonly reason: CwtVerificationReason,\n ) {\n super(message);\n this.name = \"CwtVerificationError\";\n }\n}\n\nexport interface VerifyDepositorCwtInput {\n /** Base64url (no padding) COSE Sign1 token from `auth_createDepositorToken`. */\n token: string;\n /**\n * VP ephemeral token-signing pubkey (33-byte compressed hex) from the\n * bundled `server_identity` proof — MUST already be verified by\n * {@link verifyServerIdentity} before being passed here.\n */\n ephemeralPubkeyHex: string;\n /** Pinned VP persistent x-only pubkey (on-chain). Asserted against the token `iss`. */\n expectedIssuerXOnlyPubkey: string;\n /** Expected `sub` — {@link CWT_SUBJECT_JSONRPC} or {@link CWT_SUBJECT_GRPC}. */\n expectedSubject: string;\n /** Depositor x-only pubkey. Asserted against the token `aud`. */\n expectedAudienceXOnlyPubkey: string;\n /** Outer wire `expires_at`. Must equal the token's `exp` exactly. */\n responseExpiresAt: number;\n /** `server_identity.expires_at`. Must be ≥ the token's `exp`. */\n serverIdentityExpiresAt: number;\n /** Current Unix time (seconds). Injected for testability. */\n now: number;\n}\n\nexport interface VerifiedCwtClaims {\n issuer: string;\n subject: string;\n audience: string;\n expiresAt: number;\n notBefore: number;\n issuedAt: number;\n}\n\n/**\n * Verify a depositor CWT and return its claims, or throw\n * {@link CwtVerificationError}.\n *\n * Steps (mirroring the Rust reference; see the divergence note above):\n * 1. Decode the COSE Sign1 envelope and assert the protected header\n * pins ES256K.\n * 2. Verify the ECDSA signature over the reconstructed Sig_structure\n * against the (already server-identity-verified) ephemeral key.\n * 3. Decode the CWT claims and assert `iss`/`sub`/`aud` bindings, the\n * structural `iat <= exp`, `exp` validity, `cti` presence, and the\n * outer-vs-inner expiry cross-checks. `nbf`/`iat` are intentionally not\n * clock-gated here (see the module note above).\n */\nexport function verifyDepositorCwt(\n input: VerifyDepositorCwtInput,\n): VerifiedCwtClaims {\n const expectedIssuer = normalizeXOnly(\n input.expectedIssuerXOnlyPubkey,\n \"expectedIssuerXOnlyPubkey\",\n );\n const expectedAudience = normalizeXOnly(\n input.expectedAudienceXOnlyPubkey,\n \"expectedAudienceXOnlyPubkey\",\n );\n const ephemeral = decodeCompressedPubkey(input.ephemeralPubkeyHex);\n\n const tokenBytes = base64UrlToBytes(input.token);\n\n // --- 1. COSE Sign1 structural decode -------------------------------\n // Capture the exact encoded byte ranges of the protected header and\n // payload so the Sig_structure can be rebuilt byte-for-byte from the\n // token's own bytes (any re-encoding risks a non-canonical mismatch).\n const reader = new CborReader(tokenBytes);\n const tag = reader.readHead();\n if (tag.major !== 6 || tag.arg !== COSE_SIGN1_TAG) {\n throw new CwtVerificationError(\n `token is not a COSE Sign1 tagged value (tag ${COSE_SIGN1_TAG})`,\n \"invalid_token_structure\",\n );\n }\n const array = reader.readHead();\n if (array.major !== 4 || array.arg !== COSE_SIGN1_ARRAY_LEN) {\n throw new CwtVerificationError(\n `COSE Sign1 must be a ${COSE_SIGN1_ARRAY_LEN}-element array`,\n \"invalid_token_structure\",\n );\n }\n\n const protectedStart = reader.pos;\n const protectedContent = reader.readByteString();\n const protectedBstr = tokenBytes.subarray(protectedStart, reader.pos);\n\n // Unprotected header map: present in the envelope but unused here.\n reader.readValue();\n\n const payloadStart = reader.pos;\n const payloadContent = reader.readByteString();\n const payloadBstr = tokenBytes.subarray(payloadStart, reader.pos);\n\n const signature = reader.readByteString();\n if (signature.length !== ECDSA_COMPACT_SIG_LEN) {\n throw new CwtVerificationError(\n `COSE signature must be ${ECDSA_COMPACT_SIG_LEN} bytes, got ${signature.length}`,\n \"invalid_token_structure\",\n );\n }\n // Reject anything after the COSE_Sign1 structure. The bearer we verify\n // must be the exact bytes attached to authenticated calls; a stricter\n // CWT/COSE consumer could interpret trailing bytes differently.\n if (reader.pos !== tokenBytes.length) {\n throw new CwtVerificationError(\n \"COSE Sign1 token has trailing bytes after the signature\",\n \"invalid_token_structure\",\n );\n }\n\n // --- 2a. Algorithm pin --------------------------------------------\n const alg = readProtectedAlgorithm(protectedContent);\n if (alg !== COSE_ALG_ES256K) {\n throw new CwtVerificationError(\n `unexpected COSE algorithm ${alg} (expected ES256K ${COSE_ALG_ES256K})`,\n \"unexpected_algorithm\",\n );\n }\n\n // --- 2b. Signature verification -----------------------------------\n const sigStructure = buildSigStructure(protectedBstr, payloadBstr);\n const digest = sha256(sigStructure);\n // strict = true enforces low-S, matching libsecp256k1's `verify_ecdsa`.\n if (!ecc.verify(digest, ephemeral, signature, true)) {\n throw new CwtVerificationError(\n \"COSE signature does not verify against the server's ephemeral key\",\n \"signature_verification_failed\",\n );\n }\n\n // --- 3. Claims -----------------------------------------------------\n const claims = decodeClaims(payloadContent);\n\n const audience = claims.audience.toLowerCase();\n if (audience.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(audience)) {\n throw new CwtVerificationError(\n \"token `aud` is not a 32-byte x-only pubkey hex\",\n \"invalid_claims\",\n );\n }\n if (claims.issuedAt > claims.expiresAt) {\n throw new CwtVerificationError(\n `token iat (${claims.issuedAt}) is after exp (${claims.expiresAt})`,\n \"invalid_claims\",\n );\n }\n\n if (claims.issuer.toLowerCase() !== expectedIssuer) {\n throw new CwtVerificationError(\n `token issuer does not match pinned server pubkey: expected ${expectedIssuer}, got ${claims.issuer.toLowerCase()}`,\n \"issuer_mismatch\",\n );\n }\n if (claims.subject !== input.expectedSubject) {\n throw new CwtVerificationError(\n `token subject mismatch: expected ${input.expectedSubject}, got ${claims.subject}`,\n \"subject_mismatch\",\n );\n }\n if (audience !== expectedAudience) {\n throw new CwtVerificationError(\n `token audience does not match depositor pubkey: expected ${expectedAudience}, got ${audience}`,\n \"audience_mismatch\",\n );\n }\n // No nbf/iat clock-gate on purpose — the VP server is the temporal authority\n // (re-checks nbf/exp per call). See the module-level divergence note.\n if (claims.expiresAt <= input.now) {\n throw new CwtVerificationError(\n `token expired: exp ${claims.expiresAt} <= now ${input.now}`,\n \"token_expired\",\n );\n }\n if (input.responseExpiresAt !== claims.expiresAt) {\n throw new CwtVerificationError(\n `response expires_at (${input.responseExpiresAt}) does not equal token exp (${claims.expiresAt})`,\n \"expiry_mismatch\",\n );\n }\n if (input.serverIdentityExpiresAt < claims.expiresAt) {\n throw new CwtVerificationError(\n `server identity expires (${input.serverIdentityExpiresAt}) before token exp (${claims.expiresAt})`,\n \"server_identity_expires_before_token\",\n );\n }\n\n return {\n issuer: claims.issuer,\n subject: claims.subject,\n audience,\n expiresAt: claims.expiresAt,\n notBefore: claims.notBefore,\n issuedAt: claims.issuedAt,\n };\n}\n\n/** Read the algorithm label from the COSE protected-header byte string. */\nfunction readProtectedAlgorithm(protectedContent: Uint8Array): number {\n if (protectedContent.length === 0) {\n throw new CwtVerificationError(\n \"empty COSE protected header (no algorithm)\",\n \"unexpected_algorithm\",\n );\n }\n const header = decodeCbor(protectedContent);\n if (!(header instanceof Map)) {\n throw new CwtVerificationError(\n \"COSE protected header is not a map\",\n \"invalid_token_structure\",\n );\n }\n const alg = header.get(COSE_HEADER_LABEL_ALG);\n if (typeof alg !== \"number\") {\n throw new CwtVerificationError(\n \"COSE protected header missing integer algorithm label\",\n \"unexpected_algorithm\",\n );\n }\n return alg;\n}\n\n/**\n * Rebuild the COSE_Sign1 Sig_structure (RFC 8152 §4.4):\n *\n * [ \"Signature1\", body_protected (bstr), external_aad = h'' , payload (bstr) ]\n *\n * `body_protected` and `payload` are spliced verbatim from the token's\n * own encoded byte strings, so the result is byte-identical to what the\n * issuer signed regardless of CBOR canonicalization choices.\n */\nfunction buildSigStructure(\n protectedBstr: Uint8Array,\n payloadBstr: Uint8Array,\n): Uint8Array {\n return concatBytes(\n Uint8Array.of(CBOR_ARRAY_HEAD | COSE_SIGN1_ARRAY_LEN),\n Uint8Array.of(CBOR_TEXT_STRING_HEAD | SIG_STRUCTURE_CONTEXT.length),\n SIG_STRUCTURE_CONTEXT,\n protectedBstr,\n Uint8Array.of(CBOR_EMPTY_BYTE_STRING),\n payloadBstr,\n );\n}\n\ninterface DecodedClaims {\n issuer: string;\n subject: string;\n audience: string;\n expiresAt: number;\n notBefore: number;\n issuedAt: number;\n}\n\n/** Decode and type-check the CWT registered claims from the payload. */\nfunction decodeClaims(payloadContent: Uint8Array): DecodedClaims {\n const root = decodeCbor(payloadContent);\n if (!(root instanceof Map)) {\n throw new CwtVerificationError(\n \"CWT claims root is not a map\",\n \"invalid_claims\",\n );\n }\n const cti = requireBytes(root, CWT_CLAIM_CTI, \"cti\");\n if (cti.length === 0) {\n throw new CwtVerificationError(\"token cti is empty\", \"invalid_claims\");\n }\n return {\n issuer: requireString(root, CWT_CLAIM_ISS, \"iss\"),\n subject: requireString(root, CWT_CLAIM_SUB, \"sub\"),\n audience: requireString(root, CWT_CLAIM_AUD, \"aud\"),\n expiresAt: requireTimestamp(root, CWT_CLAIM_EXP, \"exp\"),\n notBefore: requireTimestamp(root, CWT_CLAIM_NBF, \"nbf\"),\n issuedAt: requireTimestamp(root, CWT_CLAIM_IAT, \"iat\"),\n };\n}\n\nfunction requireString(\n claims: Map<unknown, unknown>,\n key: number,\n name: string,\n): string {\n const value = claims.get(key);\n if (typeof value !== \"string\") {\n throw new CwtVerificationError(\n `token claim ${name} is missing or not a text string`,\n \"invalid_claims\",\n );\n }\n return value;\n}\n\nfunction requireBytes(\n claims: Map<unknown, unknown>,\n key: number,\n name: string,\n): Uint8Array {\n const value = claims.get(key);\n if (!(value instanceof Uint8Array)) {\n throw new CwtVerificationError(\n `token claim ${name} is missing or not a byte string`,\n \"invalid_claims\",\n );\n }\n return value;\n}\n\nfunction requireTimestamp(\n claims: Map<unknown, unknown>,\n key: number,\n name: string,\n): number {\n const value = claims.get(key);\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n throw new CwtVerificationError(\n `token claim ${name} is missing or not a non-negative integer timestamp`,\n \"invalid_claims\",\n );\n }\n return value;\n}\n\n/** Validate and normalize a 32-byte x-only pubkey to lowercase hex. */\nfunction normalizeXOnly(pubkey: string, label: string): string {\n const normalized = stripHexPrefix(pubkey).toLowerCase();\n if (normalized.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(normalized)) {\n throw new CwtVerificationError(\n `${label} must be 32-byte x-only hex; got ${normalized.length} chars`,\n \"invalid_input\",\n );\n }\n return normalized;\n}\n\n/** Validate a 33-byte compressed pubkey hex and return its bytes. */\nfunction decodeCompressedPubkey(pubkeyHex: string): Uint8Array {\n const normalized = stripHexPrefix(pubkeyHex).toLowerCase();\n const prefix = normalized.slice(0, 2);\n if (\n normalized.length !== COMPRESSED_PUBKEY_HEX_LEN ||\n !HEX_RE.test(normalized) ||\n (prefix !== \"02\" && prefix !== \"03\")\n ) {\n throw new CwtVerificationError(\n \"ephemeralPubkeyHex must be 33-byte compressed pubkey hex (prefix 02/03)\",\n \"invalid_input\",\n );\n }\n return hexToUint8Array(normalized);\n}\n\nconst B64URL_LOOKUP = (() => {\n const table = new Int16Array(128).fill(-1);\n const alphabet =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n for (let i = 0; i < alphabet.length; i++) {\n table[alphabet.charCodeAt(i)] = i;\n }\n return table;\n})();\n\n/** Decode a base64url (no-padding) string to bytes. */\nfunction base64UrlToBytes(input: string): Uint8Array {\n const len = input.length;\n const fullGroups = Math.floor(len / 4);\n const remainder = len % 4;\n if (remainder === 1) {\n throw new CwtVerificationError(\n \"invalid base64url length\",\n \"invalid_token_structure\",\n );\n }\n const outLen = fullGroups * 3 + (remainder === 0 ? 0 : remainder - 1);\n const out = new Uint8Array(outLen);\n\n const sextet = (charCode: number): number => {\n const value = charCode < 128 ? B64URL_LOOKUP[charCode] : -1;\n if (value < 0) {\n throw new CwtVerificationError(\n \"invalid base64url character\",\n \"invalid_token_structure\",\n );\n }\n return value;\n };\n\n let inPos = 0;\n let outPos = 0;\n for (let g = 0; g < fullGroups; g++) {\n const a = sextet(input.charCodeAt(inPos++));\n const b = sextet(input.charCodeAt(inPos++));\n const c = sextet(input.charCodeAt(inPos++));\n const d = sextet(input.charCodeAt(inPos++));\n out[outPos++] = (a << 2) | (b >> 4);\n out[outPos++] = ((b & 0x0f) << 4) | (c >> 2);\n out[outPos++] = ((c & 0x03) << 6) | d;\n }\n if (remainder === 2) {\n const a = sextet(input.charCodeAt(inPos++));\n const b = sextet(input.charCodeAt(inPos++));\n out[outPos++] = (a << 2) | (b >> 4);\n } else if (remainder === 3) {\n const a = sextet(input.charCodeAt(inPos++));\n const b = sextet(input.charCodeAt(inPos++));\n const c = sextet(input.charCodeAt(inPos++));\n out[outPos++] = (a << 2) | (b >> 4);\n out[outPos++] = ((b & 0x0f) << 4) | (c >> 2);\n }\n return out;\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n const total = parts.reduce((sum, part) => sum + part.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n","/**\n * `VpTokenProvider` — caches CWT bearer tokens issued by the vault\n * provider's `auth_createDepositorToken` RPC, with lazy expiry check\n * and single-flight concurrent acquire.\n *\n * Usage:\n *\n * ```ts\n * const provider = new VpTokenProvider({\n * client,\n * peginTxid,\n * authAnchorHex,\n * pinnedServerPubkey,\n * authGatedMethods,\n * });\n * const bearer = await provider.getToken(method); // null if not gated\n * ```\n *\n * The provider implements the `BearerTokenProvider` interface expected\n * by `JsonRpcClient`. Plug directly:\n *\n * ```ts\n * const client = new JsonRpcClient({ ..., tokenProvider: provider });\n * ```\n *\n * @module tbv/core/clients/vault-provider/auth/tokenProvider\n */\n\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\nimport type { BearerTokenProvider, JsonRpcClient } from \"../json-rpc-client\";\nimport {\n GRPC_TOKEN_ISSUE_METHOD,\n TOKEN_ISSUE_METHOD,\n} from \"./innerTokenClient\";\nimport {\n ServerIdentityError,\n type ServerIdentityResponse,\n verifyServerIdentity,\n} from \"./serverIdentity\";\nimport {\n CWT_SUBJECT_GRPC,\n CWT_SUBJECT_JSONRPC,\n CwtVerificationError,\n verifyDepositorCwt,\n} from \"./verifyDepositorCwt\";\n\n/**\n * Maximum reasonable `expires_at` value (seconds since epoch). Guards\n * against a bogus far-future timestamp that would lock the cache on a\n * bad token forever. Jan 1, 2100 in Unix seconds.\n */\nconst MAX_EXPIRES_AT_SECS = 4_102_444_800;\n\n/**\n * Default safety margin before `expires_at` — we treat a token as\n * expired this many seconds before its stated expiry so that in-flight\n * requests don't race the expiry boundary.\n */\nconst DEFAULT_REFRESH_SKEW_SECS = 30;\n\n/**\n * Wire response shape of `auth_createDepositorToken`.\n */\nexport interface CreateDepositorTokenResponse {\n /** Base64url-encoded COSE Sign1 CWT bearer token. */\n token: string;\n /** Unix timestamp at which the token expires. */\n expires_at: number;\n /** Server identity proof bundled with every token response. */\n server_identity: ServerIdentityResponse;\n}\n\nexport interface VpTokenProviderConfig {\n client: JsonRpcClient;\n /** Per-vault depositor-signed PegIn tx id. NOT shared across sibling vaults in a batch. */\n peginTxid: string;\n /** 64-char hex of the 32-byte OP_RETURN auth-anchor preimage. */\n authAnchorHex: string;\n /** Live JSON-RPC-subject VP pubkey from chain; branded so mirrors can't substitute it. */\n pinnedServerPubkey: OnChainBtcPubkey;\n /**\n * Pin for the gRPC-subject bootstrap. This must be the operation key at the\n * vault's frozen VP epoch: vaultd signs this subject with that key.\n */\n grpcPinnedServerPubkey: OnChainBtcPubkey;\n /**\n * Re-read the authoritative current operation key after a JSON-RPC-subject\n * identity mismatch. The provider retries at most once, and only when the\n * chain returns a key different from the stale pin.\n */\n refreshJsonRpcPinnedServerPubkey?: () => Promise<OnChainBtcPubkey>;\n /**\n * Depositor x-only pubkey (32-byte hex). Asserted against every\n * issued token's CWT `aud` claim so a token minted for a different\n * depositor — or mis-issued by a buggy/compromised VP — is rejected\n * before it can authenticate a mutation.\n */\n expectedAudienceXOnlyPubkey: string;\n /**\n * Methods that need a JSON-RPC-subject bearer (minted via\n * `auth_createDepositorToken`). Forwarded over plain HTTP JSON-RPC by\n * the proxy. `getToken` returns `null` for any method outside this and\n * {@link grpcGatedMethods}.\n */\n authGatedMethods: ReadonlySet<string>;\n /**\n * Methods that need a gRPC-subject bearer (minted via\n * `auth_createDepositorTokenGrpc`). The proxy translates these into\n * gRPC calls to vaultd; the JSON-RPC bearer is rejected with a\n * `Subject` mismatch.\n */\n grpcGatedMethods: ReadonlySet<string>;\n /** Default {@link DEFAULT_REFRESH_SKEW_SECS}. */\n refreshSkewSecs?: number;\n /** Clock source for testability. */\n now?: () => number;\n}\n\ninterface CachedToken {\n token: string;\n expiresAt: number;\n}\n\n/**\n * Acquire, cache, and refresh VP bearer tokens.\n *\n * Implements {@link BearerTokenProvider}. Safe to pass directly into\n * `JsonRpcClient` as `tokenProvider`.\n */\nexport class VpTokenProvider implements BearerTokenProvider {\n // Most identity-bearing fields remain readonly and are checked against\n // re-registration in the registry's `getOrCreate`. The JSON-RPC pin is the\n // one exception: RFC-006 explicitly permits it to move, but only to a value\n // re-read through the caller's authoritative chain resolver.\n private client: JsonRpcClient;\n private readonly peginTxid: string;\n private readonly authAnchorHex: string;\n private jsonRpcPinnedServerPubkey: OnChainBtcPubkey;\n private readonly grpcPinnedServerPubkey: OnChainBtcPubkey;\n private readonly refreshJsonRpcPinnedServerPubkey?: () => Promise<OnChainBtcPubkey>;\n private readonly expectedAudienceXOnlyPubkey: string;\n private readonly authGatedMethods: ReadonlySet<string>;\n private readonly grpcGatedMethods: ReadonlySet<string>;\n private readonly refreshSkewSecs: number;\n private readonly now: () => number;\n\n /** Cached JSON-RPC-subject bearer (auth_createDepositorToken). */\n private cachedJsonRpc: CachedToken | null = null;\n private inFlightJsonRpc: Promise<CachedToken> | null = null;\n /** Cached gRPC-subject bearer (auth_createDepositorTokenGrpc). */\n private cachedGrpc: CachedToken | null = null;\n private inFlightGrpc: Promise<CachedToken> | null = null;\n\n constructor(config: VpTokenProviderConfig) {\n this.client = config.client;\n this.peginTxid = config.peginTxid;\n this.authAnchorHex = config.authAnchorHex;\n this.jsonRpcPinnedServerPubkey = config.pinnedServerPubkey;\n this.grpcPinnedServerPubkey = config.grpcPinnedServerPubkey;\n this.refreshJsonRpcPinnedServerPubkey =\n config.refreshJsonRpcPinnedServerPubkey;\n this.expectedAudienceXOnlyPubkey = config.expectedAudienceXOnlyPubkey;\n this.authGatedMethods = config.authGatedMethods;\n this.grpcGatedMethods = config.grpcGatedMethods;\n this.refreshSkewSecs = config.refreshSkewSecs ?? DEFAULT_REFRESH_SKEW_SECS;\n this.now = config.now ?? (() => Math.floor(Date.now() / 1000));\n }\n\n /**\n * Return a bearer token for `method`, or `null` if `method` is not\n * auth-gated.\n *\n * Routes by subject: `authGatedMethods` → JSON-RPC bearer (issued via\n * `auth_createDepositorToken`); `grpcGatedMethods` → gRPC bearer\n * (`auth_createDepositorTokenGrpc`). Either path acquires lazily and\n * single-flights concurrent callers; the two cache slots are\n * independent.\n *\n * Both token-issuing methods are hard-exempted from the gate — if\n * either were ever included in the gated sets (caller misconfiguration)\n * the provider would recurse into `acquireSingleFlight` from inside the\n * JSON-RPC header builder before `inFlight` is assigned, defeating the\n * single-flight guard. Returning `null` here breaks that recursion\n * deterministically.\n */\n async getToken(method: string): Promise<string | null> {\n if (method === TOKEN_ISSUE_METHOD || method === GRPC_TOKEN_ISSUE_METHOD) {\n return null;\n }\n\n if (this.grpcGatedMethods.has(method)) {\n return this.getTokenForSubject(\"grpc\");\n }\n if (this.authGatedMethods.has(method)) {\n return this.getTokenForSubject(\"jsonrpc\");\n }\n return null;\n }\n\n /**\n * Drop both cached tokens. Next `getToken` call re-acquires the slot\n * that's actually needed. Called by `JsonRpcClient` on wire\n * `auth_expired` responses; the client doesn't tell us which subject\n * expired, so we evict both to stay correct under either.\n *\n * Worst case is one extra round-trip on the slot that was still fresh,\n * which is cheaper than carrying a `Subject` argument through\n * `BearerTokenProvider`.\n */\n invalidate(): void {\n this.cachedJsonRpc = null;\n this.cachedGrpc = null;\n // Do NOT clear `inFlight*` — a concurrent acquire is still valid;\n // the invalidator is saying \"the cached token is bad\", not \"any\n // in-flight acquire is bad\". The in-flight acquire will populate\n // a fresh `cached*` on completion.\n }\n\n private async getTokenForSubject(\n subject: \"jsonrpc\" | \"grpc\",\n ): Promise<string> {\n const cached = subject === \"grpc\" ? this.cachedGrpc : this.cachedJsonRpc;\n if (cached && this.now() + this.refreshSkewSecs < cached.expiresAt) {\n return cached.token;\n }\n const fresh = await this.acquireSingleFlight(subject);\n return fresh.token;\n }\n\n /**\n * Swap in a different transport for subsequent token-issuing calls.\n * Used by the registry when a later caller registers the same\n * `peginTxid` against a different `baseUrl` — the cached token\n * (bound to identity, not transport) stays valid, but future\n * refreshes hit the new URL. An in-flight acquire keeps using the\n * old client (it captured the reference); next call uses the new.\n */\n setClient(client: JsonRpcClient): void {\n this.client = client;\n }\n\n /** Current subject-specific pin, exposed for registry identity checks. */\n getPinnedServerPubkey(subject: \"jsonrpc\" | \"grpc\"): OnChainBtcPubkey {\n return subject === \"grpc\"\n ? this.grpcPinnedServerPubkey\n : this.jsonRpcPinnedServerPubkey;\n }\n\n private acquireSingleFlight(\n subject: \"jsonrpc\" | \"grpc\",\n ): Promise<CachedToken> {\n const existing =\n subject === \"grpc\" ? this.inFlightGrpc : this.inFlightJsonRpc;\n if (existing) return existing;\n\n const issueMethod =\n subject === \"grpc\" ? GRPC_TOKEN_ISSUE_METHOD : TOKEN_ISSUE_METHOD;\n\n const p = (async () => {\n try {\n const fresh = await this.acquireAndVerify(subject, issueMethod, true);\n if (subject === \"grpc\") {\n this.cachedGrpc = fresh;\n } else {\n this.cachedJsonRpc = fresh;\n }\n return fresh;\n } finally {\n if (subject === \"grpc\") {\n this.inFlightGrpc = null;\n } else {\n this.inFlightJsonRpc = null;\n }\n }\n })();\n\n if (subject === \"grpc\") {\n this.inFlightGrpc = p;\n } else {\n this.inFlightJsonRpc = p;\n }\n return p;\n }\n\n private async acquireAndVerify(\n subject: \"jsonrpc\" | \"grpc\",\n issueMethod: string,\n allowPinRefresh: boolean,\n ): Promise<CachedToken> {\n const response = await this.client.call<\n { pegin_txid: string; auth_anchor: string },\n CreateDepositorTokenResponse\n >(issueMethod, {\n pegin_txid: this.peginTxid,\n auth_anchor: this.authAnchorHex,\n });\n const pinnedServerPubkey = this.getPinnedServerPubkey(subject);\n\n try {\n verifyServerIdentity({\n proof: response.server_identity,\n pinnedServerPubkey,\n now: this.now(),\n });\n\n // Validate wire payload before caching so a malformed response\n // from a compromised VP or proxy can't poison the cache with\n // unusable values (non-string token, non-integer expiry, etc.).\n if (typeof response.token !== \"string\" || response.token.length === 0) {\n throw new Error(\n `VpTokenProvider: invalid token in acquire response (expected non-empty string, got ${typeof response.token})`,\n );\n }\n const now = this.now();\n if (\n !Number.isSafeInteger(response.expires_at) ||\n response.expires_at <= now ||\n response.expires_at > MAX_EXPIRES_AT_SECS\n ) {\n throw new Error(\n `VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(response.expires_at)}; must be a safe integer in (${now}, ${MAX_EXPIRES_AT_SECS}])`,\n );\n }\n\n // Cryptographically verify the token itself — not just the wire\n // envelope. The COSE Sign1 signature is checked against the\n // (server-identity-verified) ephemeral key, and the inner CWT\n // claims are bound to this depositor (`aud`), this VP (`iss`),\n // and this subject. Without this the bearer is an opaque blob the\n // FE would attach to mutations on the VP's word alone.\n verifyDepositorCwt({\n token: response.token,\n ephemeralPubkeyHex: response.server_identity.ephemeral_pubkey,\n expectedIssuerXOnlyPubkey: pinnedServerPubkey,\n expectedSubject:\n subject === \"grpc\" ? CWT_SUBJECT_GRPC : CWT_SUBJECT_JSONRPC,\n expectedAudienceXOnlyPubkey: this.expectedAudienceXOnlyPubkey,\n responseExpiresAt: response.expires_at,\n serverIdentityExpiresAt: response.server_identity.expires_at,\n now,\n });\n\n return {\n token: response.token,\n expiresAt: response.expires_at,\n };\n } catch (error) {\n if (\n allowPinRefresh &&\n subject === \"jsonrpc\" &&\n this.refreshJsonRpcPinnedServerPubkey &&\n isPinnedIdentityMismatch(error)\n ) {\n const refreshed = await this.refreshJsonRpcPinnedServerPubkey();\n if (refreshed !== this.jsonRpcPinnedServerPubkey) {\n this.jsonRpcPinnedServerPubkey = refreshed;\n return this.acquireAndVerify(subject, issueMethod, false);\n }\n }\n throw error;\n }\n }\n}\n\nfunction isPinnedIdentityMismatch(error: unknown): boolean {\n return (\n (error instanceof ServerIdentityError &&\n error.reason === \"pinned_pubkey_mismatch\") ||\n (error instanceof CwtVerificationError &&\n error.reason === \"issuer_mismatch\")\n );\n}\n","/**\n * In-memory registry of {@link VpTokenProvider} instances keyed by\n * the per-vault depositor-signed PegIn tx hash. Module-level\n * singleton, per-tab, never persisted.\n *\n * @module tbv/core/clients/vault-provider/auth/tokenRegistry\n */\n\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\nimport type { JsonRpcClient } from \"../json-rpc-client\";\n\nimport { AUTH_GATED_METHODS, GRPC_AUTH_GATED_METHODS } from \"./gatedMethods\";\nimport { VpTokenProvider } from \"./tokenProvider\";\n\nexport interface VpTokenRegistryInput {\n client: JsonRpcClient;\n peginTxid: string;\n authAnchorHex: string;\n /** Stable provider identity used to prevent cross-provider cache reuse. */\n providerAddress: string;\n pinnedServerPubkey: OnChainBtcPubkey;\n /** Frozen-epoch issuer used only by the gRPC token subject. */\n grpcPinnedServerPubkey: OnChainBtcPubkey;\n /** Frozen VP epoch that selected `grpcPinnedServerPubkey`. */\n grpcKeyEpoch: bigint;\n /** Authoritative live-key resolver for bounded JSON-RPC pin recovery. */\n refreshJsonRpcPinnedServerPubkey?: () => Promise<OnChainBtcPubkey>;\n /** Depositor x-only pubkey (32-byte hex), asserted against each token's CWT `aud`. */\n expectedAudienceXOnlyPubkey: string;\n}\n\nexport interface VpTokenRegistryLookup {\n peginTxid: string;\n providerAddress: string;\n expectedAudienceXOnlyPubkey: string;\n}\n\ninterface RegistryEntry {\n provider: VpTokenProvider;\n authAnchorHex: string;\n providerAddress: string;\n grpcKeyEpoch: bigint;\n expectedAudienceXOnlyPubkey: string;\n}\n\nexport class VpTokenRegistry {\n private readonly entries = new Map<string, RegistryEntry>();\n\n /**\n * Return the cached `VpTokenProvider` for `peginTxid` if one exists\n * with matching anchor, provider, audience, and subject-specific issuer\n * bindings, otherwise construct and cache a fresh provider. A mismatch\n * throws — silent overwrite would mask derivation drift or cross-provider\n * cache reuse. A legitimate live JSON-RPC key rotation is handled inside\n * `VpTokenProvider` through its chain-backed refresh callback.\n */\n getOrCreate(input: VpTokenRegistryInput): VpTokenProvider {\n const existing = this.entries.get(input.peginTxid);\n if (existing) {\n if (existing.authAnchorHex !== input.authAnchorHex) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to authAnchorHex ${existing.authAnchorHex.slice(0, 8)}…; got ${input.authAnchorHex.slice(0, 8)}…`,\n );\n }\n // Case-insensitive, as in `peek`: callers prime with the indexer's\n // lowercase address or the contract's checksummed one.\n if (\n existing.providerAddress.toLowerCase() !==\n input.providerAddress.toLowerCase()\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to providerAddress ${existing.providerAddress}; got ${input.providerAddress}`,\n );\n }\n if (\n existing.provider.getPinnedServerPubkey(\"jsonrpc\") !==\n input.pinnedServerPubkey\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to JSON-RPC pinnedServerPubkey ${existing.provider.getPinnedServerPubkey(\"jsonrpc\").slice(0, 8)}…; got ${input.pinnedServerPubkey.slice(0, 8)}…`,\n );\n }\n if (\n existing.provider.getPinnedServerPubkey(\"grpc\") !==\n input.grpcPinnedServerPubkey\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to gRPC pinnedServerPubkey ${existing.provider.getPinnedServerPubkey(\"grpc\").slice(0, 8)}…; got ${input.grpcPinnedServerPubkey.slice(0, 8)}…`,\n );\n }\n if (existing.grpcKeyEpoch !== input.grpcKeyEpoch) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to gRPC key epoch ${existing.grpcKeyEpoch.toString()}; got ${input.grpcKeyEpoch.toString()}`,\n );\n }\n if (\n existing.expectedAudienceXOnlyPubkey.toLowerCase() !==\n input.expectedAudienceXOnlyPubkey.toLowerCase()\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to expectedAudienceXOnlyPubkey ${existing.expectedAudienceXOnlyPubkey.slice(0, 8)}…; got ${input.expectedAudienceXOnlyPubkey.slice(0, 8)}…`,\n );\n }\n // Refresh the inner transport on every reuse so a VP URL\n // change between calls doesn't leave the cached provider\n // pinned to a dead URL for token refresh.\n existing.provider.setClient(input.client);\n return existing.provider;\n }\n\n const provider = new VpTokenProvider({\n client: input.client,\n peginTxid: input.peginTxid,\n authAnchorHex: input.authAnchorHex,\n pinnedServerPubkey: input.pinnedServerPubkey,\n grpcPinnedServerPubkey: input.grpcPinnedServerPubkey,\n refreshJsonRpcPinnedServerPubkey: input.refreshJsonRpcPinnedServerPubkey,\n expectedAudienceXOnlyPubkey: input.expectedAudienceXOnlyPubkey,\n authGatedMethods: AUTH_GATED_METHODS,\n grpcGatedMethods: GRPC_AUTH_GATED_METHODS,\n });\n this.entries.set(input.peginTxid, {\n provider,\n authAnchorHex: input.authAnchorHex,\n providerAddress: input.providerAddress,\n grpcKeyEpoch: input.grpcKeyEpoch,\n expectedAudienceXOnlyPubkey: input.expectedAudienceXOnlyPubkey,\n });\n return provider;\n }\n\n /**\n * Return the cached provider only when its request-facing identity matches.\n * A missing entry is a normal cold-cache result; a binding mismatch throws\n * so callers cannot attach one provider's bearer to another provider or\n * depositor request.\n */\n peek(input: VpTokenRegistryLookup): VpTokenProvider | undefined {\n const existing = this.entries.get(input.peginTxid);\n if (!existing) return undefined;\n\n if (\n existing.providerAddress.toLowerCase() !==\n input.providerAddress.toLowerCase()\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to providerAddress ${existing.providerAddress}; got ${input.providerAddress}`,\n );\n }\n if (\n existing.expectedAudienceXOnlyPubkey.toLowerCase() !==\n input.expectedAudienceXOnlyPubkey.toLowerCase()\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to expectedAudienceXOnlyPubkey ${existing.expectedAudienceXOnlyPubkey.slice(0, 8)}…; got ${input.expectedAudienceXOnlyPubkey.slice(0, 8)}…`,\n );\n }\n\n return existing.provider;\n }\n\n /**\n * Evict the entry for `peginTxid`. Idempotent. Called on terminal\n * paths — activation success, user-cancel, or component unmount —\n * so `authAnchorHex` doesn't outlive the deposit session.\n */\n release(peginTxid: string): void {\n this.entries.delete(peginTxid);\n }\n\n /**\n * Wipe every cached entry. Test-only escape hatch — not exposed on\n * the public {@link VpTokenRegistryPublic} singleton type.\n *\n * @internal\n */\n clear(): void {\n this.entries.clear();\n }\n\n get size(): number {\n return this.entries.size;\n }\n}\n\n/**\n * Public surface of the singleton — excludes the test-only `clear`\n * method.\n */\nexport interface VpTokenRegistryPublic {\n getOrCreate(input: VpTokenRegistryInput): VpTokenProvider;\n peek(input: VpTokenRegistryLookup): VpTokenProvider | undefined;\n release(peginTxid: string): void;\n readonly size: number;\n}\n\nexport const vpTokenRegistry: VpTokenRegistryPublic = new VpTokenRegistry();\n","/**\n * Build a {@link VaultProviderRpcClient} that auto-attaches CWT\n * bearer tokens on auth-gated methods. Caller pre-derives both the\n * `authAnchorHex` (from the wallet) and the `pinnedServerPubkey`\n * (from the on-chain registry) and hands them in — the SDK has no\n * notion of wallets here.\n *\n * @module tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient\n */\n\nimport { processPublicKeyToXOnly } from \"../../../primitives/utils/bitcoin\";\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\nimport {\n VaultProviderRpcClient,\n type VaultProviderRpcClientOptions,\n} from \"../api\";\n\nimport { buildInnerTokenClient } from \"./innerTokenClient\";\nimport { vpTokenRegistry } from \"./tokenRegistry\";\n\nexport interface AuthenticatedVpClientConfig {\n /** Base URL of the VP RPC endpoint (already proxied if applicable). */\n baseUrl: string;\n /** Per-vault depositor-signed PegIn tx id (registry cache key). */\n peginTxid: string;\n /** Already-derived 32-byte auth-anchor preimage (64-char hex, no `0x`). */\n authAnchorHex: string;\n /** Stable vault-provider address used to scope the registry entry. */\n providerAddress: string;\n /** On-chain VP pubkey, branded so it can only come from the registry reader. */\n pinnedServerPubkey: OnChainBtcPubkey;\n /** Frozen-epoch VP pubkey used by the gRPC-subject bootstrap. */\n grpcPinnedServerPubkey: OnChainBtcPubkey;\n /** Vault's frozen VP epoch, paired with `grpcPinnedServerPubkey`. */\n grpcKeyEpoch: bigint;\n /** Re-read the current operation key after a JSON-RPC identity mismatch. */\n refreshJsonRpcPinnedServerPubkey?: () => Promise<OnChainBtcPubkey>;\n /**\n * Depositor BTC pubkey (x-only or compressed hex). Normalized to\n * x-only and asserted against every issued token's CWT `aud` claim.\n */\n depositorBtcPubkey: string;\n /** Optional outer-client tunables (timeout, retries, headers, etc.). */\n options?: VaultProviderRpcClientOptions;\n}\n\nexport function createAuthenticatedVpClient(\n config: AuthenticatedVpClientConfig,\n): VaultProviderRpcClient {\n const innerTokenClient = buildInnerTokenClient(\n config.baseUrl,\n config.options?.headers,\n );\n\n const tokenProvider = vpTokenRegistry.getOrCreate({\n client: innerTokenClient,\n peginTxid: config.peginTxid,\n authAnchorHex: config.authAnchorHex,\n providerAddress: config.providerAddress,\n pinnedServerPubkey: config.pinnedServerPubkey,\n grpcPinnedServerPubkey: config.grpcPinnedServerPubkey,\n grpcKeyEpoch: config.grpcKeyEpoch,\n refreshJsonRpcPinnedServerPubkey: config.refreshJsonRpcPinnedServerPubkey,\n expectedAudienceXOnlyPubkey: processPublicKeyToXOnly(\n config.depositorBtcPubkey,\n ),\n });\n\n return new VaultProviderRpcClient(config.baseUrl, {\n ...config.options,\n tokenProvider,\n });\n}\n","/**\n * Pre-populate {@link vpTokenRegistry} when the caller already has\n * both the auth-anchor preimage and the on-chain VP pubkey. Seeds\n * the cache for a `peginTxid` so a later `createAuthenticatedVpClient`\n * call reuses the cached `VpTokenProvider` instead of rebuilding it.\n *\n * @module tbv/core/clients/vault-provider/auth/primeVpAuth\n */\n\nimport { processPublicKeyToXOnly } from \"../../../primitives/utils/bitcoin\";\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\n\nimport { buildInnerTokenClient } from \"./innerTokenClient\";\nimport { vpTokenRegistry } from \"./tokenRegistry\";\n\nexport interface PrimeVpAuthInput {\n baseUrl: string;\n peginTxid: string;\n authAnchorHex: string;\n /** Stable vault-provider address used to scope the registry entry. */\n providerAddress: string;\n pinnedServerPubkey: OnChainBtcPubkey;\n /** Frozen-epoch VP pubkey used by the gRPC-subject bootstrap. */\n grpcPinnedServerPubkey: OnChainBtcPubkey;\n /** Vault's frozen VP epoch, paired with `grpcPinnedServerPubkey`. */\n grpcKeyEpoch: bigint;\n /** Re-read the current operation key after a JSON-RPC identity mismatch. */\n refreshJsonRpcPinnedServerPubkey?: () => Promise<OnChainBtcPubkey>;\n /**\n * Depositor BTC pubkey (x-only or compressed hex). Normalized to\n * x-only and asserted against every issued token's CWT `aud` claim.\n */\n depositorBtcPubkey: string;\n /** Optional headers forwarded to the inner token client (e.g. gateway auth). */\n headers?: Record<string, string>;\n}\n\nexport function primeVpTokenRegistry(input: PrimeVpAuthInput): void {\n vpTokenRegistry.getOrCreate({\n client: buildInnerTokenClient(input.baseUrl, input.headers),\n peginTxid: input.peginTxid,\n authAnchorHex: input.authAnchorHex,\n providerAddress: input.providerAddress,\n pinnedServerPubkey: input.pinnedServerPubkey,\n grpcPinnedServerPubkey: input.grpcPinnedServerPubkey,\n grpcKeyEpoch: input.grpcKeyEpoch,\n refreshJsonRpcPinnedServerPubkey: input.refreshJsonRpcPinnedServerPubkey,\n expectedAudienceXOnlyPubkey: processPublicKeyToXOnly(\n input.depositorBtcPubkey,\n ),\n });\n}\n"],"names":["cborHead","major","arg","tag","v","out","concat","parts","total","p","offset","encodeBytesAsArrayOfU8","bytes","items","b","encodeServerIdentityPayload","domain","ephemeralPubkeyCompressed","expiresAt","arrayHeader","domainBytes","pubkeyBytes","expiresAtBytes","SERVER_IDENTITY_DOMAIN","DEFAULT_MAX_PROOF_LIFETIME_SECS","ServerIdentityError","message","reason","hexToBytes","hex","i","verifyServerIdentity","input","proof","pinnedServerPubkey","now","maxLifetimeSecs","pinned","stripHexPrefix","X_ONLY_PUBKEY_HEX_LEN","HEX_RE","actual","eph","COMPRESSED_PUBKEY_HEX_LEN","prefix","ephBytes","ecc","sig","SCHNORR_SIG_HEX_LEN","payload","verifyBip322Simple","AUTH_GATED_METHODS","GRPC_AUTH_GATED_METHODS","TOKEN_RPC_TIMEOUT_MS","TOKEN_ISSUE_METHOD","GRPC_TOKEN_ISSUE_METHOD","buildInnerTokenClient","baseUrl","headers","JsonRpcClient","method","MAJOR_UNSIGNED_INT","MAJOR_NEGATIVE_INT","MAJOR_BYTE_STRING","MAJOR_TEXT_STRING","MAJOR_ARRAY","MAJOR_MAP","MAJOR_TAG","MAJOR_SIMPLE","ARG_IN_NEXT_1_BYTE","ARG_RESERVED_MIN","SIMPLE_FALSE","SIMPLE_TRUE","SIMPLE_NULL","MAX_NESTING_DEPTH","CborDecodeError","CborReader","buf","__publicField","initial","info","byteCount","value","length","slice","head","depth","map","key","decodeCbor","reader","CWT_SUBJECT_JSONRPC","CWT_SUBJECT_GRPC","COSE_SIGN1_TAG","COSE_SIGN1_ARRAY_LEN","COSE_ALG_ES256K","COSE_HEADER_LABEL_ALG","ECDSA_COMPACT_SIG_LEN","CBOR_ARRAY_HEAD","CBOR_TEXT_STRING_HEAD","CBOR_EMPTY_BYTE_STRING","CWT_CLAIM_ISS","CWT_CLAIM_SUB","CWT_CLAIM_AUD","CWT_CLAIM_EXP","CWT_CLAIM_NBF","CWT_CLAIM_IAT","CWT_CLAIM_CTI","SIG_STRUCTURE_CONTEXT","CwtVerificationError","verifyDepositorCwt","expectedIssuer","normalizeXOnly","expectedAudience","ephemeral","decodeCompressedPubkey","tokenBytes","base64UrlToBytes","array","protectedStart","protectedContent","protectedBstr","payloadStart","payloadContent","payloadBstr","signature","alg","readProtectedAlgorithm","sigStructure","buildSigStructure","digest","sha256","claims","decodeClaims","audience","header","concatBytes","root","requireBytes","requireString","requireTimestamp","name","pubkey","label","normalized","pubkeyHex","hexToUint8Array","B64URL_LOOKUP","table","alphabet","len","fullGroups","remainder","outLen","sextet","charCode","inPos","outPos","g","a","c","d","sum","part","MAX_EXPIRES_AT_SECS","DEFAULT_REFRESH_SKEW_SECS","VpTokenProvider","config","subject","cached","client","existing","issueMethod","fresh","allowPinRefresh","response","error","isPinnedIdentityMismatch","refreshed","VpTokenRegistry","provider","peginTxid","vpTokenRegistry","createAuthenticatedVpClient","innerTokenClient","_a","tokenProvider","processPublicKeyToXOnly","VaultProviderRpcClient","primeVpTokenRegistry"],"mappings":";;;;;;;;;;AAmCA,SAASA,EAASC,GAAeC,GAAkC;AACjE,QAAMC,KAAOF,IAAQ,MAAS,GACxB,IAAI,OAAOC,KAAQ,WAAWA,IAAM,OAAOA,CAAG;AACpD,MAAI,IAAI,GAAI,OAAM,IAAI,MAAM,6BAA6B;AAEzD,MAAI,IAAI,IAAK,QAAO,IAAI,WAAW,CAACC,IAAM,OAAO,CAAC,CAAC,CAAC;AACpD,MAAI,IAAI,OAAQ,QAAO,IAAI,WAAW,CAACA,IAAM,IAAI,OAAO,CAAC,CAAC,CAAC;AAC3D,MAAI,IAAI,UAAU;AAChB,UAAMC,IAAI,OAAO,CAAC;AAClB,WAAO,IAAI,WAAW,CAACD,IAAM,IAAKC,MAAM,IAAK,KAAMA,IAAI,GAAI,CAAC;AAAA,EAC9D;AACA,MAAI,IAAI,cAAgB;AACtB,UAAMA,IAAI,OAAO,CAAC;AAClB,WAAO,IAAI,WAAW;AAAA,MACpBD,IAAM;AAAA,MACLC,MAAM,KAAM;AAAA,MACZA,MAAM,KAAM;AAAA,MACZA,MAAM,IAAK;AAAA,MACZA,IAAI;A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AAAA;AAAA,EAQA,QAAc;AACZ,SAAK,QAAQ,MAAA;AAAA,EACf;AAAA,EAEA,IAAI,OAAe;AACjB,WAAO,KAAK,QAAQ;AAAA,EACtB;AACF;AAaO,MAAMC,IAAyC,IAAIH,GAAA;ACtJnD,SAASI,GACdhB,GACwB;;AACxB,QAAMiB,IAAmBhI;AAAA,IACvB+G,EAAO;AAAA,KACPkB,IAAAlB,EAAO,YAAP,gBAAAkB,EAAgB;AAAA,EAAA,GAGZC,IAAgBJ,EAAgB,YAAY;AAAA,IAChD,QAAQE;AAAA,IACR,WAAWjB,EAAO;AAAA,IAClB,eAAeA,EAAO;AAAA,IACtB,iBAAiBA,EAAO;AAAA,IACxB,oBAAoBA,EAAO;AAAA,IAC3B,wBAAwBA,EAAO;AAAA,IAC/B,cAAcA,EAAO;AAAA,IACrB,kCAAkCA,EAAO;AAAA,IACzC,6BAA6BoB;AAAA,MAC3BpB,EAAO;AAAA,IAAA;AAAA,EACT,CACD;AAED,SAAO,IAAIqB,GAAuBrB,EAAO,SAAS;AAAA,IAChD,GAAGA,EAAO;AAAA,IACV,eAAAmB;AAAA,EAAA,CACD;AACH;ACnCO,SAASG,GAAqB7J,GAA+B;AAClE,EAAAsJ,EAAgB,YAAY;AAAA,IAC1B,QAAQ9H,EAAsBxB,EAAM,SAASA,EAAM,OAAO;AAAA,IAC1D,WAAWA,EAAM;AAAA,IACjB,eAAeA,EAAM;AAAA,IACrB,iBAAiBA,EAAM;AAAA,IACvB,oBAAoBA,EAAM;AAAA,IAC1B,wBAAwBA,EAAM;AAAA,IAC9B,cAAcA,EAAM;AAAA,IACpB,kCAAkCA,EAAM;AAAA,IACxC,6BAA6B2J;AAAA,MAC3B3J,EAAM;AAAA,IAAA;AAAA,EACR,CACD;AACH;"}
|
|
1
|
+
{"version":3,"file":"primeVpAuth-CiCdRNGf.js","sources":["../src/tbv/core/clients/vault-provider/auth/cbor.ts","../src/tbv/core/clients/vault-provider/auth/serverIdentity.ts","../src/tbv/core/clients/vault-provider/auth/gatedMethods.ts","../src/tbv/core/clients/vault-provider/auth/innerTokenClient.ts","../src/tbv/core/clients/vault-provider/auth/cborDecode.ts","../src/tbv/core/clients/vault-provider/auth/verifyDepositorCwt.ts","../src/tbv/core/clients/vault-provider/auth/tokenProvider.ts","../src/tbv/core/clients/vault-provider/auth/tokenRegistry.ts","../src/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.ts","../src/tbv/core/clients/vault-provider/auth/primeVpAuth.ts"],"sourcesContent":["/**\n * Minimal CBOR encoder for the server-identity payload shape.\n *\n * We only need to encode one specific CBOR structure — the 3-tuple\n * `(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey_bytes, expires_at_u64)` —\n * byte-for-byte identical to what the Rust `ciborium` crate produces\n * for the corresponding tuple, because that's the exact message the\n * VP signs with BIP-322.\n *\n * IMPORTANT encoding quirk: the Rust side passes the domain and\n * pubkey as `&[u8]` / `Vec<u8>` without a `#[serde(with = \"serde_bytes\")]`\n * attribute, so serde/ciborium encodes them as **CBOR arrays of u8**\n * (major type 4, one item per byte) — NOT as CBOR byte strings (major\n * type 2). A naive byte-string encoding would produce the wrong bytes\n * and signature verification would fail.\n *\n * Rather than pull in a full CBOR dependency for this one shape, we\n * implement the exact subset inline (~40 LOC) and pin it with golden\n * vectors against the Rust reference output.\n *\n * @module tbv/core/clients/vault-provider/auth/cbor\n */\n\n/**\n * Encode a small CBOR unsigned-integer \"head\" byte for major type\n * `major` (0..7) with argument `arg` (0..2^64-1).\n *\n * Returns the header bytes; the caller concatenates any trailing data\n * (e.g. array elements). Encoding rules:\n * arg < 24 → single byte `(major << 5) | arg`\n * arg < 256 → `(major << 5) | 24` + 1-byte arg\n * arg < 65536 → `(major << 5) | 25` + 2-byte BE arg\n * arg < 2^32 → `(major << 5) | 26` + 4-byte BE arg\n * arg < 2^64 → `(major << 5) | 27` + 8-byte BE arg\n */\nfunction cborHead(major: number, arg: number | bigint): Uint8Array {\n const tag = (major & 0x07) << 5;\n const n = typeof arg === \"bigint\" ? arg : BigInt(arg);\n if (n < 0n) throw new Error(\"cborHead: negative argument\");\n\n if (n < 24n) return new Uint8Array([tag | Number(n)]);\n if (n < 0x100n) return new Uint8Array([tag | 24, Number(n)]);\n if (n < 0x10000n) {\n const v = Number(n);\n return new Uint8Array([tag | 25, (v >>> 8) & 0xff, v & 0xff]);\n }\n if (n < 0x1_0000_0000n) {\n const v = Number(n);\n return new Uint8Array([\n tag | 26,\n (v >>> 24) & 0xff,\n (v >>> 16) & 0xff,\n (v >>> 8) & 0xff,\n v & 0xff,\n ]);\n }\n // 8-byte BE for u64 range\n const out = new Uint8Array(9);\n out[0] = tag | 27;\n for (let i = 7; i >= 0; i--) {\n out[1 + i] = Number(n >> BigInt((7 - i) * 8)) & 0xff;\n }\n return out;\n}\n\nfunction concat(...parts: Uint8Array[]): Uint8Array {\n const total = parts.reduce((s, p) => s + p.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const p of parts) {\n out.set(p, offset);\n offset += p.length;\n }\n return out;\n}\n\n/**\n * Encode a `Vec<u8>` / `&[u8]` the way ciborium does by default — as a\n * CBOR array of u8 (major type 4), one element per byte.\n *\n * Each byte becomes a CBOR unsigned integer (major type 0): bytes\n * < 24 are encoded as single bytes, bytes 24..255 as `0x18 XX`.\n */\nfunction encodeBytesAsArrayOfU8(bytes: Uint8Array): Uint8Array {\n const header = cborHead(4, bytes.length);\n const items: Uint8Array[] = [header];\n for (const b of bytes) {\n items.push(cborHead(0, b));\n }\n return concat(...items);\n}\n\n/**\n * Encode the server-identity payload the Rust side signs:\n *\n * ciborium::into_writer(\n * &(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey.serialize().to_vec(), expires_at),\n * buf\n * )\n *\n * Output bytes are byte-for-byte identical to the Rust reference,\n * pinned by the golden vector in the corresponding test file.\n *\n * @internal Exposed only for the golden-vector test that pins this\n * encoding against ciborium's output. Production callers reach this\n * via `verifyServerIdentity` from `./serverIdentity`.\n *\n * @param domain - Must be `\"btc-auth.server-identity.v1\"` (27 bytes)\n * — the constant from btc-vault's `server_identity.rs`.\n * @param ephemeralPubkeyCompressed - 33-byte SEC1-compressed pubkey.\n * @param expiresAt - Unix timestamp (seconds). Must be a safe integer.\n */\nexport function encodeServerIdentityPayload(\n domain: Uint8Array,\n ephemeralPubkeyCompressed: Uint8Array,\n expiresAt: number,\n): Uint8Array {\n if (!Number.isSafeInteger(expiresAt) || expiresAt < 0) {\n throw new Error(\n `encodeServerIdentityPayload: expires_at must be a non-negative safe integer, got ${expiresAt}`,\n );\n }\n const arrayHeader = cborHead(4, 3); // 3-tuple encoded as array of 3\n const domainBytes = encodeBytesAsArrayOfU8(domain);\n const pubkeyBytes = encodeBytesAsArrayOfU8(ephemeralPubkeyCompressed);\n const expiresAtBytes = cborHead(0, expiresAt);\n return concat(arrayHeader, domainBytes, pubkeyBytes, expiresAtBytes);\n}\n","/**\n * Server-identity verification for the vault provider's\n * `auth_createDepositorToken` response.\n *\n * The VP returns a `ServerIdentityResponse` bundled with every issued\n * token:\n *\n * - `server_pubkey`: VP's persistent x-only pubkey (HEX, 32B)\n * - `ephemeral_pubkey`: VP's ephemeral token-signing key (HEX, 33B compressed)\n * - `expires_at`: Unix timestamp when the ephemeral key expires\n * - `signature`: BIP-322 signature by the persistent key over\n * `(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey, expires_at)`\n *\n * The FE pins `server_pubkey` against the on-chain `VaultProvider.btcPubKey`\n * it reads from the registry contract. A mismatch rejects the token.\n *\n * @module tbv/core/clients/vault-provider/auth/serverIdentity\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\n\nimport {\n SCHNORR_SIG_HEX_LEN,\n stripHexPrefix,\n} from \"../../../primitives/utils/bitcoin\";\nimport {\n COMPRESSED_PUBKEY_HEX_LEN,\n HEX_RE,\n X_ONLY_PUBKEY_HEX_LEN,\n} from \"../../../utils/validation\";\n\nimport { verifyBip322Simple } from \"./bip322Verify\";\nimport { encodeServerIdentityPayload } from \"./cbor\";\n\n/**\n * Byte-string domain the btc-vault Rust reference passes as the first\n * element of the CBOR tuple signed over for server-identity proofs.\n * Must match `SERVER_IDENTITY_DOMAIN` in\n * `btc-vault/crates/btc-auth/src/server_identity.rs`.\n */\nconst SERVER_IDENTITY_DOMAIN = new TextEncoder().encode(\n \"btc-auth.server-identity.v1\",\n);\n\n/**\n * Cap on `proof.expires_at - now`. Bounds how long a leaked VP\n * ephemeral key stays usable; the bearer token's own TTL does not\n * (different trust boundary). 2h = Rust ref VP's 1h rotation × 2 for\n * clock skew. Override per call via `maxLifetimeSecs`.\n */\nconst DEFAULT_MAX_PROOF_LIFETIME_SECS = 2 * 3600;\n\n/**\n * Wire representation from btc-vault's `ServerIdentityResponse`.\n */\nexport interface ServerIdentityResponse {\n /** Hex-encoded x-only (32-byte) persistent server pubkey. */\n server_pubkey: string;\n /** Hex-encoded compressed (33-byte) ephemeral token-signing pubkey. */\n ephemeral_pubkey: string;\n /** Unix timestamp at which the ephemeral key expires. */\n expires_at: number;\n /** Hex-encoded 64-byte BIP-322 Schnorr signature. */\n signature: string;\n}\n\nexport interface VerifyServerIdentityInput {\n /** The proof returned by `auth_createDepositorToken`. */\n proof: ServerIdentityResponse;\n /**\n * The x-only persistent server pubkey the FE expects (sourced from\n * the on-chain `VaultProvider.btcPubKey` via the vault registry\n * reader). 64-char lowercase hex, no `0x` prefix.\n */\n pinnedServerPubkey: string;\n /** Current Unix timestamp in seconds. Injected for testability. */\n now: number;\n /** Cap on `proof.expires_at - now` (seconds). Defaults to {@link DEFAULT_MAX_PROOF_LIFETIME_SECS}. */\n maxLifetimeSecs?: number;\n}\n\nexport class ServerIdentityError extends Error {\n constructor(\n message: string,\n public readonly reason:\n | \"pinned_pubkey_mismatch\"\n | \"expired\"\n | \"expires_too_far\"\n | \"invalid_expires_at\"\n | \"invalid_max_lifetime\"\n | \"invalid_pubkey_encoding\"\n | \"invalid_ephemeral_pubkey\"\n | \"invalid_signature_encoding\"\n | \"signature_verification_failed\",\n ) {\n super(message);\n this.name = \"ServerIdentityError\";\n }\n}\n\n/** Parse a lowercase-hex string to bytes. Expects even length, already validated. */\nfunction hexToBytes(hex: string): Uint8Array {\n const out = new Uint8Array(hex.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\n/**\n * Verify a server identity proof against a pinned server pubkey.\n *\n * Checks:\n * 1. `server_pubkey` matches the pin.\n * 2. `now < expires_at <= now + maxLifetimeSecs` (with integer guards).\n * 3. `ephemeral_pubkey` is a well-formed 33-byte compressed pubkey.\n * 4. `signature` is a well-formed 64-byte Schnorr hex string.\n * 5. The BIP-322 Schnorr signature cryptographically verifies\n * against `server_pubkey` over the CBOR-encoded tuple\n * `(SERVER_IDENTITY_DOMAIN, ephemeral_pubkey, expires_at)`.\n *\n * Step 5 is what actually binds the ephemeral key to the persistent\n * pubkey — without it, a TLS-MITM attacker who reads the pinned\n * pubkey from the on-chain registry could substitute an arbitrary\n * ephemeral pubkey paired with any lexically-valid signature.\n *\n * @throws ServerIdentityError on any validation failure.\n */\nexport function verifyServerIdentity(input: VerifyServerIdentityInput): void {\n const { proof, pinnedServerPubkey, now } = input;\n const maxLifetimeSecs =\n input.maxLifetimeSecs ?? DEFAULT_MAX_PROOF_LIFETIME_SECS;\n\n const pinned = stripHexPrefix(pinnedServerPubkey).toLowerCase();\n if (pinned.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(pinned)) {\n throw new ServerIdentityError(\n `pinnedServerPubkey must be 32-byte hex; got ${pinned.length} chars`,\n \"invalid_pubkey_encoding\",\n );\n }\n\n const actual = stripHexPrefix(proof.server_pubkey).toLowerCase();\n if (actual.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(actual)) {\n throw new ServerIdentityError(\n `server_pubkey must be 32-byte hex; got ${actual.length} chars`,\n \"invalid_pubkey_encoding\",\n );\n }\n\n if (actual !== pinned) {\n throw new ServerIdentityError(\n `server_pubkey does not match pinned value: expected ${pinned}, got ${actual}`,\n \"pinned_pubkey_mismatch\",\n );\n }\n\n // Validate both sides of the comparison are well-formed integers\n // BEFORE comparing — untrusted JSON-RPC input can supply\n // undefined/NaN/string values for `expires_at`, and relational\n // comparisons with those silently evaluate to `false` (accepting the\n // proof). Caller's `now` is injected but we still sanity-check it.\n // Garbage data and \"valid but past\" both render the proof unusable\n // but mean different things to a caller — keep the reasons distinct.\n if (!Number.isSafeInteger(proof.expires_at)) {\n throw new ServerIdentityError(\n `expires_at must be a finite integer; got ${JSON.stringify(proof.expires_at)}`,\n \"invalid_expires_at\",\n );\n }\n if (!Number.isSafeInteger(now)) {\n throw new ServerIdentityError(\n `now must be a finite integer; got ${JSON.stringify(now)}`,\n \"invalid_expires_at\",\n );\n }\n if (proof.expires_at <= now) {\n throw new ServerIdentityError(\n `server identity proof expired at ${proof.expires_at}, now ${now}`,\n \"expired\",\n );\n }\n if (!Number.isSafeInteger(maxLifetimeSecs) || maxLifetimeSecs <= 0) {\n throw new ServerIdentityError(\n `maxLifetimeSecs must be a positive safe integer; got ${JSON.stringify(maxLifetimeSecs)}`,\n \"invalid_max_lifetime\",\n );\n }\n if (proof.expires_at - now > maxLifetimeSecs) {\n throw new ServerIdentityError(\n `server identity proof expires too far in the future: ` +\n `expires_at=${proof.expires_at}, now=${now}, max lifetime=${maxLifetimeSecs}s`,\n \"expires_too_far\",\n );\n }\n\n const eph = stripHexPrefix(proof.ephemeral_pubkey).toLowerCase();\n if (eph.length !== COMPRESSED_PUBKEY_HEX_LEN || !HEX_RE.test(eph)) {\n throw new ServerIdentityError(\n `ephemeral_pubkey must be 33-byte compressed hex; got ${eph.length} chars`,\n \"invalid_ephemeral_pubkey\",\n );\n }\n const prefix = eph.slice(0, 2);\n if (prefix !== \"02\" && prefix !== \"03\") {\n throw new ServerIdentityError(\n `ephemeral_pubkey must be compressed (prefix 02/03); got ${prefix}`,\n \"invalid_ephemeral_pubkey\",\n );\n }\n // Curve validation. The BIP-322 signature attests to the byte string\n // of `ephemeral_pubkey` only, not to its curve validity. Without\n // this check, a server could sign a structurally-valid byte string\n // that doesn't decode to a secp256k1 point — passing verification\n // here and surfacing as an obscure crypto error later when the\n // depositor tries to use the key. Reject up front.\n const ephBytes = hexToBytes(eph);\n if (!ecc.isPoint(ephBytes)) {\n throw new ServerIdentityError(\n \"ephemeral_pubkey is not a valid secp256k1 point\",\n \"invalid_ephemeral_pubkey\",\n );\n }\n\n const sig = stripHexPrefix(proof.signature).toLowerCase();\n if (sig.length !== SCHNORR_SIG_HEX_LEN || !HEX_RE.test(sig)) {\n throw new ServerIdentityError(\n `signature must be 64-byte Schnorr hex; got ${sig.length} chars`,\n \"invalid_signature_encoding\",\n );\n }\n\n // Cryptographic verification of the BIP-322 signature over the\n // CBOR-encoded payload. Without this, the ephemeral-key binding is\n // unenforced and a TLS-MITM could substitute a fake ephemeral key\n // alongside the real (publicly-readable) pinned pubkey.\n const payload = encodeServerIdentityPayload(\n SERVER_IDENTITY_DOMAIN,\n hexToBytes(eph),\n proof.expires_at,\n );\n const verified = verifyBip322Simple(\n payload,\n hexToBytes(actual),\n hexToBytes(sig),\n );\n if (!verified) {\n throw new ServerIdentityError(\n \"BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey\",\n \"signature_verification_failed\",\n );\n }\n}\n","/**\n * VP RPC methods that require `Authorization: Bearer <token>`.\n * Protocol invariant — must be kept in sync with the VP server.\n *\n * Split into two sets by the CWT subject the VP demands:\n *\n * - {@link AUTH_GATED_METHODS} — bearer minted by\n * `auth_createDepositorToken` (Subject::VaultdJsonRpc). These run\n * through the proxy's plain JSON-RPC forward path.\n * - {@link GRPC_AUTH_GATED_METHODS} — bearer minted by\n * `auth_createDepositorTokenGrpc` (Subject::VaultdGrpc). The proxy\n * translates these into gRPC calls to vaultd's daemon gRPC server,\n * so a JSON-RPC-subject token would be rejected by\n * `GrpcAuthInterceptor`.\n *\n * @stability frozen\n *\n * @module tbv/core/clients/vault-provider/auth/gatedMethods\n */\n\nexport const AUTH_GATED_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_submitDepositorWotsKey\",\n \"vaultProvider_submitDepositorPresignatures\",\n \"vaultProvider_requestDepositorPresignTransactions\",\n]);\n\nexport const GRPC_AUTH_GATED_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_requestDepositorClaimerArtifacts\",\n]);\n","/**\n * Shared internals for the unauthenticated token-issuing JSON-RPC\n * client. The \"inner\" client is dedicated to `auth_createDepositorToken`\n * — it MUST NOT carry a `tokenProvider`, else the JSON-RPC header\n * builder would recurse into token acquisition.\n *\n * @module tbv/core/clients/vault-provider/auth/innerTokenClient\n */\n\nimport { JsonRpcClient } from \"../json-rpc-client\";\n\nconst TOKEN_RPC_TIMEOUT_MS = 60_000;\n\nexport const TOKEN_ISSUE_METHOD = \"auth_createDepositorToken\";\n/**\n * gRPC-subject sibling of {@link TOKEN_ISSUE_METHOD}. The proxy bridges\n * this call to vaultd's `VaultProviderDepositorAuthService.CreateDepositorToken`\n * so the resulting CWT is bound to `Subject::VaultdGrpc` — required to\n * pass vaultd's `GrpcAuthInterceptor` on methods the proxy translates to\n * gRPC (currently just the artifact stream).\n */\nexport const GRPC_TOKEN_ISSUE_METHOD = \"auth_createDepositorTokenGrpc\";\n\nexport function buildInnerTokenClient(\n baseUrl: string,\n headers?: Record<string, string>,\n): JsonRpcClient {\n return new JsonRpcClient({\n baseUrl,\n timeout: TOKEN_RPC_TIMEOUT_MS,\n headers,\n retryableFor: (method) =>\n method === TOKEN_ISSUE_METHOD || method === GRPC_TOKEN_ISSUE_METHOD,\n });\n}\n","/**\n * Minimal CBOR decoder — the read-side counterpart to {@link ./cbor}.\n *\n * Decodes only the subset needed to verify a vault-provider CWT bearer\n * token (RFC 8392) wrapped in a COSE Sign1 envelope (RFC 8152): tagged\n * values, definite-length arrays and maps, byte/text strings, and\n * unsigned/negative integers. Indefinite-length items, floats, and\n * big-number tags are intentionally rejected — the issuer\n * (btc-vault's `coset`/`ciborium` stack) never emits them for this\n * shape, so accepting them would only widen the parser's attack\n * surface.\n *\n * The decoder is a cursor over a single buffer. {@link CborReader.pos}\n * is public so callers can slice the exact encoded byte range of an\n * item (head + content) — required to reconstruct the COSE\n * `Sig_structure` byte-for-byte from the token's own protected-header\n * and payload byte strings.\n *\n * @module tbv/core/clients/vault-provider/auth/cborDecode\n */\n\n/** CBOR major types (the high 3 bits of the initial byte). */\nconst MAJOR_UNSIGNED_INT = 0;\nconst MAJOR_NEGATIVE_INT = 1;\nconst MAJOR_BYTE_STRING = 2;\nconst MAJOR_TEXT_STRING = 3;\nconst MAJOR_ARRAY = 4;\nconst MAJOR_MAP = 5;\nconst MAJOR_TAG = 6;\nconst MAJOR_SIMPLE = 7;\n\n/**\n * Smallest additional-info value that introduces a multi-byte argument\n * (24 ⇒ 1 byte, 25 ⇒ 2, 26 ⇒ 4, 27 ⇒ 8 — i.e. `1 << (info - 24)`).\n */\nconst ARG_IN_NEXT_1_BYTE = 24;\n/** Additional-info ≥ this (28..31) is reserved/indefinite — unsupported. */\nconst ARG_RESERVED_MIN = 28;\n\n/** Major-7 simple values we accept. */\nconst SIMPLE_FALSE = 20;\nconst SIMPLE_TRUE = 21;\nconst SIMPLE_NULL = 22;\n\n/**\n * Maximum CBOR nesting depth. Mirrors the issuer's recursion cap (256 in\n * btc-vault's `ciborium` stack). The COSE protected header is decoded\n * *before* the signature is verified, so without this bound a\n * malicious/MITM'd VP could send a deeply-nested blob and crash token\n * acquisition with an uncatchable stack overflow. Far below the JS call\n * stack limit, so it converts that DoS into a catchable decode error.\n */\nconst MAX_NESTING_DEPTH = 256;\n\n/** A decoded CBOR data item. Maps preserve key insertion order. */\nexport type CborValue =\n | number\n | bigint\n | string\n | Uint8Array\n | boolean\n | null\n | CborValue[]\n | Map<CborValue, CborValue>\n | CborTagged;\n\n/** A CBOR tagged value (major type 6). */\nexport interface CborTagged {\n tag: number;\n value: CborValue;\n}\n\n/** Parsed initial-byte header: major type plus its decoded argument. */\nexport interface CborHead {\n major: number;\n /** The header argument (length, value, tag number, …) as a number. */\n arg: number;\n}\n\nexport class CborDecodeError extends Error {\n constructor(message: string) {\n super(`CBOR decode: ${message}`);\n this.name = \"CborDecodeError\";\n }\n}\n\n/**\n * Cursor-based reader over a CBOR buffer. Not reusable across buffers —\n * construct one per decode.\n */\nexport class CborReader {\n readonly buf: Uint8Array;\n /** Current read offset. Public so callers can slice encoded sub-ranges. */\n pos = 0;\n\n constructor(buf: Uint8Array) {\n this.buf = buf;\n }\n\n private nextByte(): number {\n if (this.pos >= this.buf.length) {\n throw new CborDecodeError(\"unexpected end of input\");\n }\n return this.buf[this.pos++];\n }\n\n /**\n * Read an initial byte and its argument. Rejects indefinite-length\n * and reserved additional-info encodings. Arguments wider than\n * {@link Number.MAX_SAFE_INTEGER} are rejected — none of the token's\n * lengths, tags, or timestamps approach that bound.\n */\n readHead(): CborHead {\n const initial = this.nextByte();\n const major = initial >> 5;\n const info = initial & 0x1f;\n\n if (info < ARG_IN_NEXT_1_BYTE) {\n return { major, arg: info };\n }\n if (info >= ARG_RESERVED_MIN) {\n throw new CborDecodeError(\n `unsupported additional info ${info} (indefinite-length or reserved)`,\n );\n }\n\n const byteCount = 1 << (info - ARG_IN_NEXT_1_BYTE);\n\n let value = 0n;\n for (let i = 0; i < byteCount; i++) {\n value = (value << 8n) | BigInt(this.nextByte());\n }\n if (value > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new CborDecodeError(`argument ${value} exceeds safe integer range`);\n }\n return { major, arg: Number(value) };\n }\n\n /** Read `length` raw bytes as a sub-array view into the backing buffer. */\n private readBytes(length: number): Uint8Array {\n if (this.pos + length > this.buf.length) {\n throw new CborDecodeError(\"length overruns end of input\");\n }\n const slice = this.buf.subarray(this.pos, this.pos + length);\n this.pos += length;\n return slice;\n }\n\n /**\n * Read a byte string (major type 2), returning its content bytes.\n * Throws if the next item is not a byte string.\n */\n readByteString(): Uint8Array {\n const head = this.readHead();\n if (head.major !== MAJOR_BYTE_STRING) {\n throw new CborDecodeError(\n `expected byte string (major ${MAJOR_BYTE_STRING}), got major ${head.major}`,\n );\n }\n return this.readBytes(head.arg);\n }\n\n /**\n * Read the next complete data item as a decoded {@link CborValue}.\n *\n * `depth` tracks the current nesting level so a deeply-nested blob is\n * rejected with a {@link CborDecodeError} rather than overflowing the\n * native call stack (see {@link MAX_NESTING_DEPTH}).\n */\n readValue(depth = 0): CborValue {\n if (depth > MAX_NESTING_DEPTH) {\n throw new CborDecodeError(\n `nesting exceeds maximum depth ${MAX_NESTING_DEPTH}`,\n );\n }\n const head = this.readHead();\n switch (head.major) {\n case MAJOR_UNSIGNED_INT:\n return head.arg;\n case MAJOR_NEGATIVE_INT:\n // RFC 8949 §3.1: the encoded argument n represents -1 - n.\n return -1 - head.arg;\n case MAJOR_BYTE_STRING:\n return this.readBytes(head.arg);\n case MAJOR_TEXT_STRING:\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(\n this.readBytes(head.arg),\n );\n case MAJOR_ARRAY: {\n const items: CborValue[] = [];\n for (let i = 0; i < head.arg; i++) {\n items.push(this.readValue(depth + 1));\n }\n return items;\n }\n case MAJOR_MAP: {\n const map = new Map<CborValue, CborValue>();\n for (let i = 0; i < head.arg; i++) {\n const key = this.readValue(depth + 1);\n const value = this.readValue(depth + 1);\n map.set(key, value);\n }\n return map;\n }\n case MAJOR_TAG:\n return { tag: head.arg, value: this.readValue(depth + 1) };\n case MAJOR_SIMPLE:\n if (head.arg === SIMPLE_FALSE) return false;\n if (head.arg === SIMPLE_TRUE) return true;\n if (head.arg === SIMPLE_NULL) return null;\n throw new CborDecodeError(\n `unsupported simple/float value ${head.arg}`,\n );\n default:\n throw new CborDecodeError(`unsupported major type ${head.major}`);\n }\n }\n}\n\n/**\n * Decode a single CBOR item from `bytes`, rejecting any trailing bytes.\n *\n * Used to parse the COSE protected header and CWT claims set — both are\n * exactly one top-level item, so a valid prefix followed by extra bytes\n * is a malformed structure, not a benign tail. Strict consumption keeps\n * the parser from silently accepting a token a stricter CWT/COSE\n * consumer would interpret differently.\n */\nexport function decodeCbor(bytes: Uint8Array): CborValue {\n const reader = new CborReader(bytes);\n const value = reader.readValue();\n if (reader.pos !== bytes.length) {\n throw new CborDecodeError(\"trailing bytes after top-level item\");\n }\n return value;\n}\n","/**\n * Verify a vault-provider CWT bearer (RFC 8392 / COSE Sign1, ES256K): checks the\n * signature against the VP's attested ephemeral key (see {@link ./serverIdentity})\n * and binds `iss`/`sub`/`aud` to the pinned VP, subject, and depositor. TS port\n * of btc-vault `client.rs::validate_token_with_public_key_at_time`.\n *\n * Divergence from that reference: the FE does NOT clock-gate `nbf`/`iat`. The VP\n * server is the temporal authority and re-checks `nbf`/`exp` on every gated call;\n * re-checking `nbf` against the browser clock only bricked freshly minted tokens\n * on benign skew. `exp` (wide window) and the structural `iat <= exp` are kept.\n *\n * @module tbv/core/clients/vault-provider/auth/verifyDepositorCwt\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\n\nimport {\n hexToUint8Array,\n stripHexPrefix,\n} from \"../../../primitives/utils/bitcoin\";\nimport {\n COMPRESSED_PUBKEY_HEX_LEN,\n HEX_RE,\n X_ONLY_PUBKEY_HEX_LEN,\n} from \"../../../utils/validation\";\n\nimport { CborReader, decodeCbor } from \"./cborDecode\";\n\n/** CWT `sub` value for JSON-RPC-subject tokens (`auth_createDepositorToken`). */\nexport const CWT_SUBJECT_JSONRPC = \"vaultd-jsonrpc\";\n/** CWT `sub` value for gRPC-subject tokens (`auth_createDepositorTokenGrpc`). */\nexport const CWT_SUBJECT_GRPC = \"vaultd-grpc\";\n\n/** CBOR tag wrapping a COSE_Sign1 structure (RFC 8152 §2). */\nconst COSE_SIGN1_TAG = 18;\n/** A COSE_Sign1 is a 4-element array: [protected, unprotected, payload, signature]. */\nconst COSE_SIGN1_ARRAY_LEN = 4;\n/** COSE algorithm id for ES256K (ECDSA w/ secp256k1 + SHA-256), RFC 8812. */\nconst COSE_ALG_ES256K = -47;\n/** COSE header label for the algorithm (RFC 8152 §3.1). */\nconst COSE_HEADER_LABEL_ALG = 1;\n/** ECDSA signature length in COSE compact (r‖s) form. */\nconst ECDSA_COMPACT_SIG_LEN = 64;\n\n/** CBOR major-type 4 (array) high bits, for the Sig_structure header. */\nconst CBOR_ARRAY_HEAD = 0x80;\n/** CBOR major-type 3 (text string) high bits, for the context string head. */\nconst CBOR_TEXT_STRING_HEAD = 0x60;\n/** CBOR encoding of an empty byte string (major type 2, length 0). */\nconst CBOR_EMPTY_BYTE_STRING = 0x40;\n\n/** CWT registered claim keys (RFC 8392 §4 / IANA CWT registry). */\nconst CWT_CLAIM_ISS = 1;\nconst CWT_CLAIM_SUB = 2;\nconst CWT_CLAIM_AUD = 3;\nconst CWT_CLAIM_EXP = 4;\nconst CWT_CLAIM_NBF = 5;\nconst CWT_CLAIM_IAT = 6;\nconst CWT_CLAIM_CTI = 7;\n\n/**\n * Context string for a COSE_Sign1 Sig_structure (RFC 8152 §4.4). 10\n * bytes, so it encodes with a single-byte CBOR text-string head.\n */\nconst SIG_STRUCTURE_CONTEXT = new TextEncoder().encode(\"Signature1\");\n\nexport type CwtVerificationReason =\n | \"invalid_input\"\n | \"invalid_token_structure\"\n | \"unexpected_algorithm\"\n | \"signature_verification_failed\"\n | \"invalid_claims\"\n | \"issuer_mismatch\"\n | \"subject_mismatch\"\n | \"audience_mismatch\"\n | \"token_expired\"\n | \"expiry_mismatch\"\n | \"server_identity_expires_before_token\";\n\nexport class CwtVerificationError extends Error {\n constructor(\n message: string,\n public readonly reason: CwtVerificationReason,\n ) {\n super(message);\n this.name = \"CwtVerificationError\";\n }\n}\n\nexport interface VerifyDepositorCwtInput {\n /** Base64url (no padding) COSE Sign1 token from `auth_createDepositorToken`. */\n token: string;\n /**\n * VP ephemeral token-signing pubkey (33-byte compressed hex) from the\n * bundled `server_identity` proof — MUST already be verified by\n * {@link verifyServerIdentity} before being passed here.\n */\n ephemeralPubkeyHex: string;\n /** Pinned VP persistent x-only pubkey (on-chain). Asserted against the token `iss`. */\n expectedIssuerXOnlyPubkey: string;\n /** Expected `sub` — {@link CWT_SUBJECT_JSONRPC} or {@link CWT_SUBJECT_GRPC}. */\n expectedSubject: string;\n /** Depositor x-only pubkey. Asserted against the token `aud`. */\n expectedAudienceXOnlyPubkey: string;\n /** Outer wire `expires_at`. Must equal the token's `exp` exactly. */\n responseExpiresAt: number;\n /** `server_identity.expires_at`. Must be ≥ the token's `exp`. */\n serverIdentityExpiresAt: number;\n /** Current Unix time (seconds). Injected for testability. */\n now: number;\n}\n\nexport interface VerifiedCwtClaims {\n issuer: string;\n subject: string;\n audience: string;\n expiresAt: number;\n notBefore: number;\n issuedAt: number;\n}\n\n/**\n * Verify a depositor CWT and return its claims, or throw\n * {@link CwtVerificationError}.\n *\n * Steps (mirroring the Rust reference; see the divergence note above):\n * 1. Decode the COSE Sign1 envelope and assert the protected header\n * pins ES256K.\n * 2. Verify the ECDSA signature over the reconstructed Sig_structure\n * against the (already server-identity-verified) ephemeral key.\n * 3. Decode the CWT claims and assert `iss`/`sub`/`aud` bindings, the\n * structural `iat <= exp`, `exp` validity, `cti` presence, and the\n * outer-vs-inner expiry cross-checks. `nbf`/`iat` are intentionally not\n * clock-gated here (see the module note above).\n */\nexport function verifyDepositorCwt(\n input: VerifyDepositorCwtInput,\n): VerifiedCwtClaims {\n const expectedIssuer = normalizeXOnly(\n input.expectedIssuerXOnlyPubkey,\n \"expectedIssuerXOnlyPubkey\",\n );\n const expectedAudience = normalizeXOnly(\n input.expectedAudienceXOnlyPubkey,\n \"expectedAudienceXOnlyPubkey\",\n );\n const ephemeral = decodeCompressedPubkey(input.ephemeralPubkeyHex);\n\n const tokenBytes = base64UrlToBytes(input.token);\n\n // --- 1. COSE Sign1 structural decode -------------------------------\n // Capture the exact encoded byte ranges of the protected header and\n // payload so the Sig_structure can be rebuilt byte-for-byte from the\n // token's own bytes (any re-encoding risks a non-canonical mismatch).\n const reader = new CborReader(tokenBytes);\n const tag = reader.readHead();\n if (tag.major !== 6 || tag.arg !== COSE_SIGN1_TAG) {\n throw new CwtVerificationError(\n `token is not a COSE Sign1 tagged value (tag ${COSE_SIGN1_TAG})`,\n \"invalid_token_structure\",\n );\n }\n const array = reader.readHead();\n if (array.major !== 4 || array.arg !== COSE_SIGN1_ARRAY_LEN) {\n throw new CwtVerificationError(\n `COSE Sign1 must be a ${COSE_SIGN1_ARRAY_LEN}-element array`,\n \"invalid_token_structure\",\n );\n }\n\n const protectedStart = reader.pos;\n const protectedContent = reader.readByteString();\n const protectedBstr = tokenBytes.subarray(protectedStart, reader.pos);\n\n // Unprotected header map: present in the envelope but unused here.\n reader.readValue();\n\n const payloadStart = reader.pos;\n const payloadContent = reader.readByteString();\n const payloadBstr = tokenBytes.subarray(payloadStart, reader.pos);\n\n const signature = reader.readByteString();\n if (signature.length !== ECDSA_COMPACT_SIG_LEN) {\n throw new CwtVerificationError(\n `COSE signature must be ${ECDSA_COMPACT_SIG_LEN} bytes, got ${signature.length}`,\n \"invalid_token_structure\",\n );\n }\n // Reject anything after the COSE_Sign1 structure. The bearer we verify\n // must be the exact bytes attached to authenticated calls; a stricter\n // CWT/COSE consumer could interpret trailing bytes differently.\n if (reader.pos !== tokenBytes.length) {\n throw new CwtVerificationError(\n \"COSE Sign1 token has trailing bytes after the signature\",\n \"invalid_token_structure\",\n );\n }\n\n // --- 2a. Algorithm pin --------------------------------------------\n const alg = readProtectedAlgorithm(protectedContent);\n if (alg !== COSE_ALG_ES256K) {\n throw new CwtVerificationError(\n `unexpected COSE algorithm ${alg} (expected ES256K ${COSE_ALG_ES256K})`,\n \"unexpected_algorithm\",\n );\n }\n\n // --- 2b. Signature verification -----------------------------------\n const sigStructure = buildSigStructure(protectedBstr, payloadBstr);\n const digest = sha256(sigStructure);\n // strict = true enforces low-S, matching libsecp256k1's `verify_ecdsa`.\n if (!ecc.verify(digest, ephemeral, signature, true)) {\n throw new CwtVerificationError(\n \"COSE signature does not verify against the server's ephemeral key\",\n \"signature_verification_failed\",\n );\n }\n\n // --- 3. Claims -----------------------------------------------------\n const claims = decodeClaims(payloadContent);\n\n const audience = claims.audience.toLowerCase();\n if (audience.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(audience)) {\n throw new CwtVerificationError(\n \"token `aud` is not a 32-byte x-only pubkey hex\",\n \"invalid_claims\",\n );\n }\n if (claims.issuedAt > claims.expiresAt) {\n throw new CwtVerificationError(\n `token iat (${claims.issuedAt}) is after exp (${claims.expiresAt})`,\n \"invalid_claims\",\n );\n }\n\n if (claims.issuer.toLowerCase() !== expectedIssuer) {\n throw new CwtVerificationError(\n `token issuer does not match pinned server pubkey: expected ${expectedIssuer}, got ${claims.issuer.toLowerCase()}`,\n \"issuer_mismatch\",\n );\n }\n if (claims.subject !== input.expectedSubject) {\n throw new CwtVerificationError(\n `token subject mismatch: expected ${input.expectedSubject}, got ${claims.subject}`,\n \"subject_mismatch\",\n );\n }\n if (audience !== expectedAudience) {\n throw new CwtVerificationError(\n `token audience does not match depositor pubkey: expected ${expectedAudience}, got ${audience}`,\n \"audience_mismatch\",\n );\n }\n // No nbf/iat clock-gate on purpose — the VP server is the temporal authority\n // (re-checks nbf/exp per call). See the module-level divergence note.\n if (claims.expiresAt <= input.now) {\n throw new CwtVerificationError(\n `token expired: exp ${claims.expiresAt} <= now ${input.now}`,\n \"token_expired\",\n );\n }\n if (input.responseExpiresAt !== claims.expiresAt) {\n throw new CwtVerificationError(\n `response expires_at (${input.responseExpiresAt}) does not equal token exp (${claims.expiresAt})`,\n \"expiry_mismatch\",\n );\n }\n if (input.serverIdentityExpiresAt < claims.expiresAt) {\n throw new CwtVerificationError(\n `server identity expires (${input.serverIdentityExpiresAt}) before token exp (${claims.expiresAt})`,\n \"server_identity_expires_before_token\",\n );\n }\n\n return {\n issuer: claims.issuer,\n subject: claims.subject,\n audience,\n expiresAt: claims.expiresAt,\n notBefore: claims.notBefore,\n issuedAt: claims.issuedAt,\n };\n}\n\n/** Read the algorithm label from the COSE protected-header byte string. */\nfunction readProtectedAlgorithm(protectedContent: Uint8Array): number {\n if (protectedContent.length === 0) {\n throw new CwtVerificationError(\n \"empty COSE protected header (no algorithm)\",\n \"unexpected_algorithm\",\n );\n }\n const header = decodeCbor(protectedContent);\n if (!(header instanceof Map)) {\n throw new CwtVerificationError(\n \"COSE protected header is not a map\",\n \"invalid_token_structure\",\n );\n }\n const alg = header.get(COSE_HEADER_LABEL_ALG);\n if (typeof alg !== \"number\") {\n throw new CwtVerificationError(\n \"COSE protected header missing integer algorithm label\",\n \"unexpected_algorithm\",\n );\n }\n return alg;\n}\n\n/**\n * Rebuild the COSE_Sign1 Sig_structure (RFC 8152 §4.4):\n *\n * [ \"Signature1\", body_protected (bstr), external_aad = h'' , payload (bstr) ]\n *\n * `body_protected` and `payload` are spliced verbatim from the token's\n * own encoded byte strings, so the result is byte-identical to what the\n * issuer signed regardless of CBOR canonicalization choices.\n */\nfunction buildSigStructure(\n protectedBstr: Uint8Array,\n payloadBstr: Uint8Array,\n): Uint8Array {\n return concatBytes(\n Uint8Array.of(CBOR_ARRAY_HEAD | COSE_SIGN1_ARRAY_LEN),\n Uint8Array.of(CBOR_TEXT_STRING_HEAD | SIG_STRUCTURE_CONTEXT.length),\n SIG_STRUCTURE_CONTEXT,\n protectedBstr,\n Uint8Array.of(CBOR_EMPTY_BYTE_STRING),\n payloadBstr,\n );\n}\n\ninterface DecodedClaims {\n issuer: string;\n subject: string;\n audience: string;\n expiresAt: number;\n notBefore: number;\n issuedAt: number;\n}\n\n/** Decode and type-check the CWT registered claims from the payload. */\nfunction decodeClaims(payloadContent: Uint8Array): DecodedClaims {\n const root = decodeCbor(payloadContent);\n if (!(root instanceof Map)) {\n throw new CwtVerificationError(\n \"CWT claims root is not a map\",\n \"invalid_claims\",\n );\n }\n const cti = requireBytes(root, CWT_CLAIM_CTI, \"cti\");\n if (cti.length === 0) {\n throw new CwtVerificationError(\"token cti is empty\", \"invalid_claims\");\n }\n return {\n issuer: requireString(root, CWT_CLAIM_ISS, \"iss\"),\n subject: requireString(root, CWT_CLAIM_SUB, \"sub\"),\n audience: requireString(root, CWT_CLAIM_AUD, \"aud\"),\n expiresAt: requireTimestamp(root, CWT_CLAIM_EXP, \"exp\"),\n notBefore: requireTimestamp(root, CWT_CLAIM_NBF, \"nbf\"),\n issuedAt: requireTimestamp(root, CWT_CLAIM_IAT, \"iat\"),\n };\n}\n\nfunction requireString(\n claims: Map<unknown, unknown>,\n key: number,\n name: string,\n): string {\n const value = claims.get(key);\n if (typeof value !== \"string\") {\n throw new CwtVerificationError(\n `token claim ${name} is missing or not a text string`,\n \"invalid_claims\",\n );\n }\n return value;\n}\n\nfunction requireBytes(\n claims: Map<unknown, unknown>,\n key: number,\n name: string,\n): Uint8Array {\n const value = claims.get(key);\n if (!(value instanceof Uint8Array)) {\n throw new CwtVerificationError(\n `token claim ${name} is missing or not a byte string`,\n \"invalid_claims\",\n );\n }\n return value;\n}\n\nfunction requireTimestamp(\n claims: Map<unknown, unknown>,\n key: number,\n name: string,\n): number {\n const value = claims.get(key);\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n throw new CwtVerificationError(\n `token claim ${name} is missing or not a non-negative integer timestamp`,\n \"invalid_claims\",\n );\n }\n return value;\n}\n\n/** Validate and normalize a 32-byte x-only pubkey to lowercase hex. */\nfunction normalizeXOnly(pubkey: string, label: string): string {\n const normalized = stripHexPrefix(pubkey).toLowerCase();\n if (normalized.length !== X_ONLY_PUBKEY_HEX_LEN || !HEX_RE.test(normalized)) {\n throw new CwtVerificationError(\n `${label} must be 32-byte x-only hex; got ${normalized.length} chars`,\n \"invalid_input\",\n );\n }\n return normalized;\n}\n\n/** Validate a 33-byte compressed pubkey hex and return its bytes. */\nfunction decodeCompressedPubkey(pubkeyHex: string): Uint8Array {\n const normalized = stripHexPrefix(pubkeyHex).toLowerCase();\n const prefix = normalized.slice(0, 2);\n if (\n normalized.length !== COMPRESSED_PUBKEY_HEX_LEN ||\n !HEX_RE.test(normalized) ||\n (prefix !== \"02\" && prefix !== \"03\")\n ) {\n throw new CwtVerificationError(\n \"ephemeralPubkeyHex must be 33-byte compressed pubkey hex (prefix 02/03)\",\n \"invalid_input\",\n );\n }\n return hexToUint8Array(normalized);\n}\n\nconst B64URL_LOOKUP = (() => {\n const table = new Int16Array(128).fill(-1);\n const alphabet =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n for (let i = 0; i < alphabet.length; i++) {\n table[alphabet.charCodeAt(i)] = i;\n }\n return table;\n})();\n\n/** Decode a base64url (no-padding) string to bytes. */\nfunction base64UrlToBytes(input: string): Uint8Array {\n const len = input.length;\n const fullGroups = Math.floor(len / 4);\n const remainder = len % 4;\n if (remainder === 1) {\n throw new CwtVerificationError(\n \"invalid base64url length\",\n \"invalid_token_structure\",\n );\n }\n const outLen = fullGroups * 3 + (remainder === 0 ? 0 : remainder - 1);\n const out = new Uint8Array(outLen);\n\n const sextet = (charCode: number): number => {\n const value = charCode < 128 ? B64URL_LOOKUP[charCode] : -1;\n if (value < 0) {\n throw new CwtVerificationError(\n \"invalid base64url character\",\n \"invalid_token_structure\",\n );\n }\n return value;\n };\n\n let inPos = 0;\n let outPos = 0;\n for (let g = 0; g < fullGroups; g++) {\n const a = sextet(input.charCodeAt(inPos++));\n const b = sextet(input.charCodeAt(inPos++));\n const c = sextet(input.charCodeAt(inPos++));\n const d = sextet(input.charCodeAt(inPos++));\n out[outPos++] = (a << 2) | (b >> 4);\n out[outPos++] = ((b & 0x0f) << 4) | (c >> 2);\n out[outPos++] = ((c & 0x03) << 6) | d;\n }\n if (remainder === 2) {\n const a = sextet(input.charCodeAt(inPos++));\n const b = sextet(input.charCodeAt(inPos++));\n out[outPos++] = (a << 2) | (b >> 4);\n } else if (remainder === 3) {\n const a = sextet(input.charCodeAt(inPos++));\n const b = sextet(input.charCodeAt(inPos++));\n const c = sextet(input.charCodeAt(inPos++));\n out[outPos++] = (a << 2) | (b >> 4);\n out[outPos++] = ((b & 0x0f) << 4) | (c >> 2);\n }\n return out;\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n const total = parts.reduce((sum, part) => sum + part.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n","/**\n * `VpTokenProvider` — caches CWT bearer tokens issued by the vault\n * provider's `auth_createDepositorToken` RPC, with lazy expiry check\n * and single-flight concurrent acquire.\n *\n * Usage:\n *\n * ```ts\n * const provider = new VpTokenProvider({\n * client,\n * peginTxid,\n * authAnchorHex,\n * pinnedServerPubkey,\n * authGatedMethods,\n * });\n * const bearer = await provider.getToken(method); // null if not gated\n * ```\n *\n * The provider implements the `BearerTokenProvider` interface expected\n * by `JsonRpcClient`. Plug directly:\n *\n * ```ts\n * const client = new JsonRpcClient({ ..., tokenProvider: provider });\n * ```\n *\n * @module tbv/core/clients/vault-provider/auth/tokenProvider\n */\n\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\nimport type { BearerTokenProvider, JsonRpcClient } from \"../json-rpc-client\";\nimport {\n GRPC_TOKEN_ISSUE_METHOD,\n TOKEN_ISSUE_METHOD,\n} from \"./innerTokenClient\";\nimport {\n ServerIdentityError,\n type ServerIdentityResponse,\n verifyServerIdentity,\n} from \"./serverIdentity\";\nimport {\n CWT_SUBJECT_GRPC,\n CWT_SUBJECT_JSONRPC,\n CwtVerificationError,\n verifyDepositorCwt,\n} from \"./verifyDepositorCwt\";\n\n/**\n * Maximum reasonable `expires_at` value (seconds since epoch). Guards\n * against a bogus far-future timestamp that would lock the cache on a\n * bad token forever. Jan 1, 2100 in Unix seconds.\n */\nconst MAX_EXPIRES_AT_SECS = 4_102_444_800;\n\n/**\n * Default safety margin before `expires_at` — we treat a token as\n * expired this many seconds before its stated expiry so that in-flight\n * requests don't race the expiry boundary.\n */\nconst DEFAULT_REFRESH_SKEW_SECS = 30;\n\n/**\n * Wire response shape of `auth_createDepositorToken`.\n */\nexport interface CreateDepositorTokenResponse {\n /** Base64url-encoded COSE Sign1 CWT bearer token. */\n token: string;\n /** Unix timestamp at which the token expires. */\n expires_at: number;\n /** Server identity proof bundled with every token response. */\n server_identity: ServerIdentityResponse;\n}\n\nexport interface VpTokenProviderConfig {\n client: JsonRpcClient;\n /** Per-vault depositor-signed PegIn tx id. NOT shared across sibling vaults in a batch. */\n peginTxid: string;\n /** 64-char hex of the 32-byte OP_RETURN auth-anchor preimage. */\n authAnchorHex: string;\n /** Live JSON-RPC-subject VP pubkey from chain; branded so mirrors can't substitute it. */\n pinnedServerPubkey: OnChainBtcPubkey;\n /**\n * Pin for the gRPC-subject bootstrap. This must be the operation key at the\n * vault's frozen VP epoch: vaultd signs this subject with that key.\n */\n grpcPinnedServerPubkey: OnChainBtcPubkey;\n /**\n * Re-read the authoritative current operation key after a JSON-RPC-subject\n * identity mismatch. The provider retries at most once, and only when the\n * chain returns a key different from the stale pin.\n */\n refreshJsonRpcPinnedServerPubkey?: () => Promise<OnChainBtcPubkey>;\n /**\n * Depositor x-only pubkey (32-byte hex). Asserted against every\n * issued token's CWT `aud` claim so a token minted for a different\n * depositor — or mis-issued by a buggy/compromised VP — is rejected\n * before it can authenticate a mutation.\n */\n expectedAudienceXOnlyPubkey: string;\n /**\n * Methods that need a JSON-RPC-subject bearer (minted via\n * `auth_createDepositorToken`). Forwarded over plain HTTP JSON-RPC by\n * the proxy. `getToken` returns `null` for any method outside this and\n * {@link grpcGatedMethods}.\n */\n authGatedMethods: ReadonlySet<string>;\n /**\n * Methods that need a gRPC-subject bearer (minted via\n * `auth_createDepositorTokenGrpc`). The proxy translates these into\n * gRPC calls to vaultd; the JSON-RPC bearer is rejected with a\n * `Subject` mismatch.\n */\n grpcGatedMethods: ReadonlySet<string>;\n /** Default {@link DEFAULT_REFRESH_SKEW_SECS}. */\n refreshSkewSecs?: number;\n /** Clock source for testability. */\n now?: () => number;\n}\n\ninterface CachedToken {\n token: string;\n expiresAt: number;\n}\n\n/**\n * Acquire, cache, and refresh VP bearer tokens.\n *\n * Implements {@link BearerTokenProvider}. Safe to pass directly into\n * `JsonRpcClient` as `tokenProvider`.\n */\nexport class VpTokenProvider implements BearerTokenProvider {\n // Most identity-bearing fields remain readonly and are checked against\n // re-registration in the registry's `getOrCreate`. The JSON-RPC pin is the\n // one exception: RFC-006 explicitly permits it to move, but only to a value\n // re-read through the caller's authoritative chain resolver.\n private client: JsonRpcClient;\n private readonly peginTxid: string;\n private readonly authAnchorHex: string;\n private jsonRpcPinnedServerPubkey: OnChainBtcPubkey;\n private readonly grpcPinnedServerPubkey: OnChainBtcPubkey;\n private readonly refreshJsonRpcPinnedServerPubkey?: () => Promise<OnChainBtcPubkey>;\n private readonly expectedAudienceXOnlyPubkey: string;\n private readonly authGatedMethods: ReadonlySet<string>;\n private readonly grpcGatedMethods: ReadonlySet<string>;\n private readonly refreshSkewSecs: number;\n private readonly now: () => number;\n\n /** Cached JSON-RPC-subject bearer (auth_createDepositorToken). */\n private cachedJsonRpc: CachedToken | null = null;\n private inFlightJsonRpc: Promise<CachedToken> | null = null;\n /** Cached gRPC-subject bearer (auth_createDepositorTokenGrpc). */\n private cachedGrpc: CachedToken | null = null;\n private inFlightGrpc: Promise<CachedToken> | null = null;\n\n constructor(config: VpTokenProviderConfig) {\n this.client = config.client;\n this.peginTxid = config.peginTxid;\n this.authAnchorHex = config.authAnchorHex;\n this.jsonRpcPinnedServerPubkey = config.pinnedServerPubkey;\n this.grpcPinnedServerPubkey = config.grpcPinnedServerPubkey;\n this.refreshJsonRpcPinnedServerPubkey =\n config.refreshJsonRpcPinnedServerPubkey;\n this.expectedAudienceXOnlyPubkey = config.expectedAudienceXOnlyPubkey;\n this.authGatedMethods = config.authGatedMethods;\n this.grpcGatedMethods = config.grpcGatedMethods;\n this.refreshSkewSecs = config.refreshSkewSecs ?? DEFAULT_REFRESH_SKEW_SECS;\n this.now = config.now ?? (() => Math.floor(Date.now() / 1000));\n }\n\n /**\n * Return a bearer token for `method`, or `null` if `method` is not\n * auth-gated.\n *\n * Routes by subject: `authGatedMethods` → JSON-RPC bearer (issued via\n * `auth_createDepositorToken`); `grpcGatedMethods` → gRPC bearer\n * (`auth_createDepositorTokenGrpc`). Either path acquires lazily and\n * single-flights concurrent callers; the two cache slots are\n * independent.\n *\n * Both token-issuing methods are hard-exempted from the gate — if\n * either were ever included in the gated sets (caller misconfiguration)\n * the provider would recurse into `acquireSingleFlight` from inside the\n * JSON-RPC header builder before `inFlight` is assigned, defeating the\n * single-flight guard. Returning `null` here breaks that recursion\n * deterministically.\n */\n async getToken(method: string): Promise<string | null> {\n if (method === TOKEN_ISSUE_METHOD || method === GRPC_TOKEN_ISSUE_METHOD) {\n return null;\n }\n\n if (this.grpcGatedMethods.has(method)) {\n return this.getTokenForSubject(\"grpc\");\n }\n if (this.authGatedMethods.has(method)) {\n return this.getTokenForSubject(\"jsonrpc\");\n }\n return null;\n }\n\n /**\n * Drop both cached tokens. Next `getToken` call re-acquires the slot\n * that's actually needed. Called by `JsonRpcClient` on wire\n * `auth_expired` responses; the client doesn't tell us which subject\n * expired, so we evict both to stay correct under either.\n *\n * Worst case is one extra round-trip on the slot that was still fresh,\n * which is cheaper than carrying a `Subject` argument through\n * `BearerTokenProvider`.\n */\n invalidate(): void {\n this.cachedJsonRpc = null;\n this.cachedGrpc = null;\n // Do NOT clear `inFlight*` — a concurrent acquire is still valid;\n // the invalidator is saying \"the cached token is bad\", not \"any\n // in-flight acquire is bad\". The in-flight acquire will populate\n // a fresh `cached*` on completion.\n }\n\n private async getTokenForSubject(\n subject: \"jsonrpc\" | \"grpc\",\n ): Promise<string> {\n const cached = subject === \"grpc\" ? this.cachedGrpc : this.cachedJsonRpc;\n if (cached && this.now() + this.refreshSkewSecs < cached.expiresAt) {\n return cached.token;\n }\n const fresh = await this.acquireSingleFlight(subject);\n return fresh.token;\n }\n\n /**\n * Swap in a different transport for subsequent token-issuing calls.\n * Used by the registry when a later caller registers the same\n * `peginTxid` against a different `baseUrl` — the cached token\n * (bound to identity, not transport) stays valid, but future\n * refreshes hit the new URL. An in-flight acquire keeps using the\n * old client (it captured the reference); next call uses the new.\n */\n setClient(client: JsonRpcClient): void {\n this.client = client;\n }\n\n /** Current subject-specific pin, exposed for registry identity checks. */\n getPinnedServerPubkey(subject: \"jsonrpc\" | \"grpc\"): OnChainBtcPubkey {\n return subject === \"grpc\"\n ? this.grpcPinnedServerPubkey\n : this.jsonRpcPinnedServerPubkey;\n }\n\n private acquireSingleFlight(\n subject: \"jsonrpc\" | \"grpc\",\n ): Promise<CachedToken> {\n const existing =\n subject === \"grpc\" ? this.inFlightGrpc : this.inFlightJsonRpc;\n if (existing) return existing;\n\n const issueMethod =\n subject === \"grpc\" ? GRPC_TOKEN_ISSUE_METHOD : TOKEN_ISSUE_METHOD;\n\n const p = (async () => {\n try {\n const fresh = await this.acquireAndVerify(subject, issueMethod, true);\n if (subject === \"grpc\") {\n this.cachedGrpc = fresh;\n } else {\n this.cachedJsonRpc = fresh;\n }\n return fresh;\n } finally {\n if (subject === \"grpc\") {\n this.inFlightGrpc = null;\n } else {\n this.inFlightJsonRpc = null;\n }\n }\n })();\n\n if (subject === \"grpc\") {\n this.inFlightGrpc = p;\n } else {\n this.inFlightJsonRpc = p;\n }\n return p;\n }\n\n private async acquireAndVerify(\n subject: \"jsonrpc\" | \"grpc\",\n issueMethod: string,\n allowPinRefresh: boolean,\n ): Promise<CachedToken> {\n const response = await this.client.call<\n { pegin_txid: string; auth_anchor: string },\n CreateDepositorTokenResponse\n >(issueMethod, {\n pegin_txid: this.peginTxid,\n auth_anchor: this.authAnchorHex,\n });\n const pinnedServerPubkey = this.getPinnedServerPubkey(subject);\n\n try {\n verifyServerIdentity({\n proof: response.server_identity,\n pinnedServerPubkey,\n now: this.now(),\n });\n\n // Validate wire payload before caching so a malformed response\n // from a compromised VP or proxy can't poison the cache with\n // unusable values (non-string token, non-integer expiry, etc.).\n if (typeof response.token !== \"string\" || response.token.length === 0) {\n throw new Error(\n `VpTokenProvider: invalid token in acquire response (expected non-empty string, got ${typeof response.token})`,\n );\n }\n const now = this.now();\n if (\n !Number.isSafeInteger(response.expires_at) ||\n response.expires_at <= now ||\n response.expires_at > MAX_EXPIRES_AT_SECS\n ) {\n throw new Error(\n `VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(response.expires_at)}; must be a safe integer in (${now}, ${MAX_EXPIRES_AT_SECS}])`,\n );\n }\n\n // Cryptographically verify the token itself — not just the wire\n // envelope. The COSE Sign1 signature is checked against the\n // (server-identity-verified) ephemeral key, and the inner CWT\n // claims are bound to this depositor (`aud`), this VP (`iss`),\n // and this subject. Without this the bearer is an opaque blob the\n // FE would attach to mutations on the VP's word alone.\n verifyDepositorCwt({\n token: response.token,\n ephemeralPubkeyHex: response.server_identity.ephemeral_pubkey,\n expectedIssuerXOnlyPubkey: pinnedServerPubkey,\n expectedSubject:\n subject === \"grpc\" ? CWT_SUBJECT_GRPC : CWT_SUBJECT_JSONRPC,\n expectedAudienceXOnlyPubkey: this.expectedAudienceXOnlyPubkey,\n responseExpiresAt: response.expires_at,\n serverIdentityExpiresAt: response.server_identity.expires_at,\n now,\n });\n\n return {\n token: response.token,\n expiresAt: response.expires_at,\n };\n } catch (error) {\n if (\n allowPinRefresh &&\n subject === \"jsonrpc\" &&\n this.refreshJsonRpcPinnedServerPubkey &&\n isPinnedIdentityMismatch(error)\n ) {\n const refreshed = await this.refreshJsonRpcPinnedServerPubkey();\n if (refreshed !== this.jsonRpcPinnedServerPubkey) {\n this.jsonRpcPinnedServerPubkey = refreshed;\n return this.acquireAndVerify(subject, issueMethod, false);\n }\n }\n throw error;\n }\n }\n}\n\nfunction isPinnedIdentityMismatch(error: unknown): boolean {\n return (\n (error instanceof ServerIdentityError &&\n error.reason === \"pinned_pubkey_mismatch\") ||\n (error instanceof CwtVerificationError &&\n error.reason === \"issuer_mismatch\")\n );\n}\n","/**\n * In-memory registry of {@link VpTokenProvider} instances keyed by\n * the per-vault depositor-signed PegIn tx hash. Module-level\n * singleton, per-tab, never persisted.\n *\n * @module tbv/core/clients/vault-provider/auth/tokenRegistry\n */\n\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\nimport type { JsonRpcClient } from \"../json-rpc-client\";\n\nimport { AUTH_GATED_METHODS, GRPC_AUTH_GATED_METHODS } from \"./gatedMethods\";\nimport { VpTokenProvider } from \"./tokenProvider\";\n\nexport interface VpTokenRegistryInput {\n client: JsonRpcClient;\n peginTxid: string;\n authAnchorHex: string;\n /** Stable provider identity used to prevent cross-provider cache reuse. */\n providerAddress: string;\n pinnedServerPubkey: OnChainBtcPubkey;\n /** Frozen-epoch issuer used only by the gRPC token subject. */\n grpcPinnedServerPubkey: OnChainBtcPubkey;\n /** Frozen VP epoch that selected `grpcPinnedServerPubkey`. */\n grpcKeyEpoch: bigint;\n /** Authoritative live-key resolver for bounded JSON-RPC pin recovery. */\n refreshJsonRpcPinnedServerPubkey?: () => Promise<OnChainBtcPubkey>;\n /** Depositor x-only pubkey (32-byte hex), asserted against each token's CWT `aud`. */\n expectedAudienceXOnlyPubkey: string;\n}\n\nexport interface VpTokenRegistryLookup {\n peginTxid: string;\n providerAddress: string;\n expectedAudienceXOnlyPubkey: string;\n}\n\ninterface RegistryEntry {\n provider: VpTokenProvider;\n authAnchorHex: string;\n providerAddress: string;\n grpcKeyEpoch: bigint;\n expectedAudienceXOnlyPubkey: string;\n}\n\nexport class VpTokenRegistry {\n private readonly entries = new Map<string, RegistryEntry>();\n\n /**\n * Return the cached `VpTokenProvider` for `peginTxid` if one exists\n * with matching anchor, provider, audience, and subject-specific issuer\n * bindings, otherwise construct and cache a fresh provider. A mismatch\n * throws — silent overwrite would mask derivation drift or cross-provider\n * cache reuse. A legitimate live JSON-RPC key rotation is handled inside\n * `VpTokenProvider` through its chain-backed refresh callback.\n */\n getOrCreate(input: VpTokenRegistryInput): VpTokenProvider {\n const existing = this.entries.get(input.peginTxid);\n if (existing) {\n if (existing.authAnchorHex !== input.authAnchorHex) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to authAnchorHex ${existing.authAnchorHex.slice(0, 8)}…; got ${input.authAnchorHex.slice(0, 8)}…`,\n );\n }\n // Case-insensitive, as in `peek`: callers prime with the indexer's\n // lowercase address or the contract's checksummed one.\n if (\n existing.providerAddress.toLowerCase() !==\n input.providerAddress.toLowerCase()\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to providerAddress ${existing.providerAddress}; got ${input.providerAddress}`,\n );\n }\n if (\n existing.provider.getPinnedServerPubkey(\"jsonrpc\") !==\n input.pinnedServerPubkey\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to JSON-RPC pinnedServerPubkey ${existing.provider.getPinnedServerPubkey(\"jsonrpc\").slice(0, 8)}…; got ${input.pinnedServerPubkey.slice(0, 8)}…`,\n );\n }\n if (\n existing.provider.getPinnedServerPubkey(\"grpc\") !==\n input.grpcPinnedServerPubkey\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to gRPC pinnedServerPubkey ${existing.provider.getPinnedServerPubkey(\"grpc\").slice(0, 8)}…; got ${input.grpcPinnedServerPubkey.slice(0, 8)}…`,\n );\n }\n if (existing.grpcKeyEpoch !== input.grpcKeyEpoch) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to gRPC key epoch ${existing.grpcKeyEpoch.toString()}; got ${input.grpcKeyEpoch.toString()}`,\n );\n }\n if (\n existing.expectedAudienceXOnlyPubkey.toLowerCase() !==\n input.expectedAudienceXOnlyPubkey.toLowerCase()\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to expectedAudienceXOnlyPubkey ${existing.expectedAudienceXOnlyPubkey.slice(0, 8)}…; got ${input.expectedAudienceXOnlyPubkey.slice(0, 8)}…`,\n );\n }\n // Refresh the inner transport on every reuse so a VP URL\n // change between calls doesn't leave the cached provider\n // pinned to a dead URL for token refresh.\n existing.provider.setClient(input.client);\n return existing.provider;\n }\n\n const provider = new VpTokenProvider({\n client: input.client,\n peginTxid: input.peginTxid,\n authAnchorHex: input.authAnchorHex,\n pinnedServerPubkey: input.pinnedServerPubkey,\n grpcPinnedServerPubkey: input.grpcPinnedServerPubkey,\n refreshJsonRpcPinnedServerPubkey: input.refreshJsonRpcPinnedServerPubkey,\n expectedAudienceXOnlyPubkey: input.expectedAudienceXOnlyPubkey,\n authGatedMethods: AUTH_GATED_METHODS,\n grpcGatedMethods: GRPC_AUTH_GATED_METHODS,\n });\n this.entries.set(input.peginTxid, {\n provider,\n authAnchorHex: input.authAnchorHex,\n providerAddress: input.providerAddress,\n grpcKeyEpoch: input.grpcKeyEpoch,\n expectedAudienceXOnlyPubkey: input.expectedAudienceXOnlyPubkey,\n });\n return provider;\n }\n\n /**\n * Return the cached provider only when its request-facing identity matches.\n * A missing entry is a normal cold-cache result; a binding mismatch throws\n * so callers cannot attach one provider's bearer to another provider or\n * depositor request.\n */\n peek(input: VpTokenRegistryLookup): VpTokenProvider | undefined {\n const existing = this.entries.get(input.peginTxid);\n if (!existing) return undefined;\n\n if (\n existing.providerAddress.toLowerCase() !==\n input.providerAddress.toLowerCase()\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to providerAddress ${existing.providerAddress}; got ${input.providerAddress}`,\n );\n }\n if (\n existing.expectedAudienceXOnlyPubkey.toLowerCase() !==\n input.expectedAudienceXOnlyPubkey.toLowerCase()\n ) {\n throw new Error(\n `VpTokenRegistry: peginTxid ${input.peginTxid} already bound to expectedAudienceXOnlyPubkey ${existing.expectedAudienceXOnlyPubkey.slice(0, 8)}…; got ${input.expectedAudienceXOnlyPubkey.slice(0, 8)}…`,\n );\n }\n\n return existing.provider;\n }\n\n /**\n * Evict the entry for `peginTxid`. Idempotent. Called on terminal\n * paths — activation success, user-cancel, or component unmount —\n * so `authAnchorHex` doesn't outlive the deposit session.\n */\n release(peginTxid: string): void {\n this.entries.delete(peginTxid);\n }\n\n /**\n * Wipe every cached entry. Test-only escape hatch — not exposed on\n * the public {@link VpTokenRegistryPublic} singleton type.\n *\n * @internal\n */\n clear(): void {\n this.entries.clear();\n }\n\n get size(): number {\n return this.entries.size;\n }\n}\n\n/**\n * Public surface of the singleton — excludes the test-only `clear`\n * method.\n */\nexport interface VpTokenRegistryPublic {\n getOrCreate(input: VpTokenRegistryInput): VpTokenProvider;\n peek(input: VpTokenRegistryLookup): VpTokenProvider | undefined;\n release(peginTxid: string): void;\n readonly size: number;\n}\n\nexport const vpTokenRegistry: VpTokenRegistryPublic = new VpTokenRegistry();\n","/**\n * Build a {@link VaultProviderRpcClient} that auto-attaches CWT\n * bearer tokens on auth-gated methods. Caller pre-derives both the\n * `authAnchorHex` (from the wallet) and the `pinnedServerPubkey`\n * (from the on-chain registry) and hands them in — the SDK has no\n * notion of wallets here.\n *\n * @module tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient\n */\n\nimport { processPublicKeyToXOnly } from \"../../../primitives/utils/bitcoin\";\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\nimport {\n VaultProviderRpcClient,\n type VaultProviderRpcClientOptions,\n} from \"../api\";\n\nimport { buildInnerTokenClient } from \"./innerTokenClient\";\nimport { vpTokenRegistry } from \"./tokenRegistry\";\n\nexport interface AuthenticatedVpClientConfig {\n /** Base URL of the VP RPC endpoint (already proxied if applicable). */\n baseUrl: string;\n /** Per-vault depositor-signed PegIn tx id (registry cache key). */\n peginTxid: string;\n /** Already-derived 32-byte auth-anchor preimage (64-char hex, no `0x`). */\n authAnchorHex: string;\n /** Stable vault-provider address used to scope the registry entry. */\n providerAddress: string;\n /** On-chain VP pubkey, branded so it can only come from the registry reader. */\n pinnedServerPubkey: OnChainBtcPubkey;\n /** Frozen-epoch VP pubkey used by the gRPC-subject bootstrap. */\n grpcPinnedServerPubkey: OnChainBtcPubkey;\n /** Vault's frozen VP epoch, paired with `grpcPinnedServerPubkey`. */\n grpcKeyEpoch: bigint;\n /** Re-read the current operation key after a JSON-RPC identity mismatch. */\n refreshJsonRpcPinnedServerPubkey?: () => Promise<OnChainBtcPubkey>;\n /**\n * Depositor BTC pubkey (x-only or compressed hex). Normalized to\n * x-only and asserted against every issued token's CWT `aud` claim.\n */\n depositorBtcPubkey: string;\n /** Optional outer-client tunables (timeout, retries, headers, etc.). */\n options?: VaultProviderRpcClientOptions;\n}\n\nexport function createAuthenticatedVpClient(\n config: AuthenticatedVpClientConfig,\n): VaultProviderRpcClient {\n const innerTokenClient = buildInnerTokenClient(\n config.baseUrl,\n config.options?.headers,\n );\n\n const tokenProvider = vpTokenRegistry.getOrCreate({\n client: innerTokenClient,\n peginTxid: config.peginTxid,\n authAnchorHex: config.authAnchorHex,\n providerAddress: config.providerAddress,\n pinnedServerPubkey: config.pinnedServerPubkey,\n grpcPinnedServerPubkey: config.grpcPinnedServerPubkey,\n grpcKeyEpoch: config.grpcKeyEpoch,\n refreshJsonRpcPinnedServerPubkey: config.refreshJsonRpcPinnedServerPubkey,\n expectedAudienceXOnlyPubkey: processPublicKeyToXOnly(\n config.depositorBtcPubkey,\n ),\n });\n\n return new VaultProviderRpcClient(config.baseUrl, {\n ...config.options,\n tokenProvider,\n });\n}\n","/**\n * Pre-populate {@link vpTokenRegistry} when the caller already has\n * both the auth-anchor preimage and the on-chain VP pubkey. Seeds\n * the cache for a `peginTxid` so a later `createAuthenticatedVpClient`\n * call reuses the cached `VpTokenProvider` instead of rebuilding it.\n *\n * @module tbv/core/clients/vault-provider/auth/primeVpAuth\n */\n\nimport { processPublicKeyToXOnly } from \"../../../primitives/utils/bitcoin\";\nimport type { OnChainBtcPubkey } from \"../../eth/types\";\n\nimport { buildInnerTokenClient } from \"./innerTokenClient\";\nimport { vpTokenRegistry } from \"./tokenRegistry\";\n\nexport interface PrimeVpAuthInput {\n baseUrl: string;\n peginTxid: string;\n authAnchorHex: string;\n /** Stable vault-provider address used to scope the registry entry. */\n providerAddress: string;\n pinnedServerPubkey: OnChainBtcPubkey;\n /** Frozen-epoch VP pubkey used by the gRPC-subject bootstrap. */\n grpcPinnedServerPubkey: OnChainBtcPubkey;\n /** Vault's frozen VP epoch, paired with `grpcPinnedServerPubkey`. */\n grpcKeyEpoch: bigint;\n /** Re-read the current operation key after a JSON-RPC identity mismatch. */\n refreshJsonRpcPinnedServerPubkey?: () => Promise<OnChainBtcPubkey>;\n /**\n * Depositor BTC pubkey (x-only or compressed hex). Normalized to\n * x-only and asserted against every issued token's CWT `aud` claim.\n */\n depositorBtcPubkey: string;\n /** Optional headers forwarded to the inner token client (e.g. gateway auth). */\n headers?: Record<string, string>;\n}\n\nexport function primeVpTokenRegistry(input: PrimeVpAuthInput): void {\n vpTokenRegistry.getOrCreate({\n client: buildInnerTokenClient(input.baseUrl, input.headers),\n peginTxid: input.peginTxid,\n authAnchorHex: input.authAnchorHex,\n providerAddress: input.providerAddress,\n pinnedServerPubkey: input.pinnedServerPubkey,\n grpcPinnedServerPubkey: input.grpcPinnedServerPubkey,\n grpcKeyEpoch: input.grpcKeyEpoch,\n refreshJsonRpcPinnedServerPubkey: input.refreshJsonRpcPinnedServerPubkey,\n expectedAudienceXOnlyPubkey: processPublicKeyToXOnly(\n input.depositorBtcPubkey,\n ),\n });\n}\n"],"names":["cborHead","major","arg","tag","v","out","concat","parts","total","p","offset","encodeBytesAsArrayOfU8","bytes","items","b","encodeServerIdentityPayload","domain","ephemeralPubkeyCompressed","expiresAt","arrayHeader","domainBytes","pubkeyBytes","expiresAtBytes","SERVER_IDENTITY_DOMAIN","DEFAULT_MAX_PROOF_LIFETIME_SECS","ServerIdentityError","message","reason","hexToBytes","hex","i","verifyServerIdentity","input","proof","pinnedServerPubkey","now","maxLifetimeSecs","pinned","stripHexPrefix","X_ONLY_PUBKEY_HEX_LEN","HEX_RE","actual","eph","COMPRESSED_PUBKEY_HEX_LEN","prefix","ephBytes","ecc","sig","SCHNORR_SIG_HEX_LEN","payload","verifyBip322Simple","AUTH_GATED_METHODS","GRPC_AUTH_GATED_METHODS","TOKEN_RPC_TIMEOUT_MS","TOKEN_ISSUE_METHOD","GRPC_TOKEN_ISSUE_METHOD","buildInnerTokenClient","baseUrl","headers","JsonRpcClient","method","MAJOR_UNSIGNED_INT","MAJOR_NEGATIVE_INT","MAJOR_BYTE_STRING","MAJOR_TEXT_STRING","MAJOR_ARRAY","MAJOR_MAP","MAJOR_TAG","MAJOR_SIMPLE","ARG_IN_NEXT_1_BYTE","ARG_RESERVED_MIN","SIMPLE_FALSE","SIMPLE_TRUE","SIMPLE_NULL","MAX_NESTING_DEPTH","CborDecodeError","CborReader","buf","__publicField","initial","info","byteCount","value","length","slice","head","depth","map","key","decodeCbor","reader","CWT_SUBJECT_JSONRPC","CWT_SUBJECT_GRPC","COSE_SIGN1_TAG","COSE_SIGN1_ARRAY_LEN","COSE_ALG_ES256K","COSE_HEADER_LABEL_ALG","ECDSA_COMPACT_SIG_LEN","CBOR_ARRAY_HEAD","CBOR_TEXT_STRING_HEAD","CBOR_EMPTY_BYTE_STRING","CWT_CLAIM_ISS","CWT_CLAIM_SUB","CWT_CLAIM_AUD","CWT_CLAIM_EXP","CWT_CLAIM_NBF","CWT_CLAIM_IAT","CWT_CLAIM_CTI","SIG_STRUCTURE_CONTEXT","CwtVerificationError","verifyDepositorCwt","expectedIssuer","normalizeXOnly","expectedAudience","ephemeral","decodeCompressedPubkey","tokenBytes","base64UrlToBytes","array","protectedStart","protectedContent","protectedBstr","payloadStart","payloadContent","payloadBstr","signature","alg","readProtectedAlgorithm","sigStructure","buildSigStructure","digest","sha256","claims","decodeClaims","audience","header","concatBytes","root","requireBytes","requireString","requireTimestamp","name","pubkey","label","normalized","pubkeyHex","hexToUint8Array","B64URL_LOOKUP","table","alphabet","len","fullGroups","remainder","outLen","sextet","charCode","inPos","outPos","g","a","c","d","sum","part","MAX_EXPIRES_AT_SECS","DEFAULT_REFRESH_SKEW_SECS","VpTokenProvider","config","subject","cached","client","existing","issueMethod","fresh","allowPinRefresh","response","error","isPinnedIdentityMismatch","refreshed","VpTokenRegistry","provider","peginTxid","vpTokenRegistry","createAuthenticatedVpClient","innerTokenClient","_a","tokenProvider","processPublicKeyToXOnly","VaultProviderRpcClient","primeVpTokenRegistry"],"mappings":";;;;;;;;;;AAmCA,SAASA,EAASC,GAAeC,GAAkC;AACjE,QAAMC,KAAOF,IAAQ,MAAS,GACxB,IAAI,OAAOC,KAAQ,WAAWA,IAAM,OAAOA,CAAG;AACpD,MAAI,IAAI,GAAI,OAAM,IAAI,MAAM,6BAA6B;AAEzD,MAAI,IAAI,IAAK,QAAO,IAAI,WAAW,CAACC,IAAM,OAAO,CAAC,CAAC,CAAC;AACpD,MAAI,IAAI,OAAQ,QAAO,IAAI,WAAW,CAACA,IAAM,IAAI,OAAO,CAAC,CAAC,CAAC;AAC3D,MAAI,IAAI,UAAU;AAChB,UAAMC,IAAI,OAAO,CAAC;AAClB,WAAO,IAAI,WAAW,CAACD,IAAM,IAAKC,MAAM,IAAK,KAAMA,IAAI,GAAI,CAAC;AAAA,EAC9D;AACA,MAAI,IAAI,cAAgB;AACtB,UAAMA,IAAI,OAAO,CAAC;AAClB,WAAO,IAAI,WAAW;AAAA,MACpBD,IAAM;AAAA,MACLC,MAAM,KAAM;AAAA,MACZA,MAAM,KAAM;AAAA,MACZA,MAAM,IAAK;AAAA,MACZA,IAAI;AAAA,IAAA,CACL;AAAA,EACH;AAEA,QAAMC,IAAM,IAAI,WAAW,CAAC;AAC5B,EAAAA,EAAI,CAAC,IAAIF,IAAM;AACf,WAAS,IAAI,GAAG,KAAK,GAAG;AACtB,IAAAE,EAAI,IAAI,CAAC,IAAI,OAAO,KAAK,QAAQ,IAAI,KAAK,CAAC,CAAC,IAAI;AAElD,SAAOA;AACT;AAEA,SAASC,KAAUC,GAAiC;AAClD,QAAMC,IAAQD,EAAM,OAAO,CAAC,GAAGE,MAAM,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