Repository navigation
feat(lightning): support custodial user auth key resets #10099
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,17 @@ | ||
| # BitGo abstract-lightning | ||
| # @bitgo/abstract-lightning | ||
|
|
||
| ## Custodial userAuth key reset | ||
|
|
||
| For a custody Lightning wallet, call `requestUserAuthKeyReset` with the new wallet | ||
| passphrase and optional `encryptionVersion`. The SDK creates and encrypts a new | ||
| userAuth key locally, registers the encrypted key, and signs the reset request. | ||
| The returned verification code is calculated locally; the customer reads it to | ||
| support. The unencrypted private key and passphrase are never sent to the API. | ||
|
|
||
| Use `getUserAuthKeyResetRequest` to retrieve the latest request (a missing request | ||
| returns HTTP 404), and `cancelUserAuthKeyResetRequest` with its request ID to | ||
| cancel it. After a successful reset, other wallet members must be re-shared the | ||
| new key before they can regain access. | ||
|
|
||
| `computeUserAuthResetVerificationCode` and `compareUserAuthResetVerificationCodes` | ||
| are also exported for independent verification. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| import * as t from 'io-ts'; | ||
|
|
||
| const SignedRequestFields = t.type({ | ||
| walletId: t.string, | ||
| oldUserAuthKeyPub: t.string, | ||
| newUserAuthKeyPub: t.string, | ||
| newUserAuthKeyId: t.string, | ||
| createdAt: t.string, | ||
| }); | ||
|
|
||
| export type UserAuthKeyResetSignedRequest = t.TypeOf<typeof SignedRequestFields>; | ||
|
|
||
| export const UserAuthKeyResetSignedRequest = new t.Type<UserAuthKeyResetSignedRequest>( | ||
| 'UserAuthKeyResetSignedRequest', | ||
| (value): value is UserAuthKeyResetSignedRequest => | ||
| SignedRequestFields.is(value) && | ||
| Object.keys(value).every((key) => Object.prototype.hasOwnProperty.call(SignedRequestFields.props, key)), | ||
| (value, context) => { | ||
| const result = SignedRequestFields.validate(value, context); | ||
| if (result._tag === 'Left') { | ||
| return result; | ||
| } | ||
| return Object.keys(result.right).every((key) => | ||
| Object.prototype.hasOwnProperty.call(SignedRequestFields.props, key) | ||
| ) | ||
| ? result | ||
| : t.failure(value, context); | ||
| }, | ||
| t.identity | ||
| ); | ||
|
|
||
| export const UserAuthKeyResetRequest = t.type({ | ||
| newUserAuthKeyId: t.string, | ||
| signedRequest: UserAuthKeyResetSignedRequest, | ||
| signature: t.string, | ||
| }); | ||
| export type UserAuthKeyResetRequest = t.TypeOf<typeof UserAuthKeyResetRequest>; | ||
|
|
||
| export const UserAuthKeyResetResponse = t.type({ | ||
| requestId: t.string, | ||
| status: t.string, | ||
| createdAt: t.string, | ||
| }); | ||
| export type UserAuthKeyResetResponse = t.TypeOf<typeof UserAuthKeyResetResponse>; | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,6 +2,14 @@ import * as utxolib from '@bitgo/utxo-lib'; | |
| import * as sdkcore from '@bitgo/sdk-core'; | ||
| import { canonicalizeObject, Signable } from './signableJson'; | ||
|
|
||
| function parseLightningKey(key: string, network: utxolib.Network): utxolib.BIP32Interface { | ||
| // Lightning auth keys use Bitcoin BIP32 versions on both networks. | ||
| if (key.startsWith('xpub') || key.startsWith('xprv')) { | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I parse Bitcoin-versioned keys independently of the signing network: existing Lightning key generation returns xpub/xprv on testnet too, while the signature still uses the coin network. |
||
| return utxolib.bip32.fromBase58(key, utxolib.networks.bitcoin); | ||
| } | ||
| return utxolib.bip32.fromBase58(key, network); | ||
| } | ||
|
|
||
| /** | ||
| * Verifies a signature for a given message. | ||
| * | ||
|
|
@@ -18,7 +26,7 @@ export function verifyMessageSignature( | |
| network: utxolib.Network = utxolib.networks.bitcoin | ||
| ): boolean { | ||
| const messageString = JSON.stringify(canonicalizeObject(message)); | ||
| const pubKey = utxolib.bip32.fromBase58(pub, network).publicKey; | ||
| const pubKey = parseLightningKey(pub, network).publicKey; | ||
| const signatureBuffer = Buffer.from(signature, 'hex'); | ||
| return sdkcore.verifyMessage(messageString, pubKey, signatureBuffer, network); | ||
| } | ||
|
|
@@ -37,6 +45,6 @@ export function createMessageSignature( | |
| network: utxolib.Network = utxolib.networks.bitcoin | ||
| ): string { | ||
| const requestString = JSON.stringify(canonicalizeObject(message)); | ||
| const prvKey = utxolib.bip32.fromBase58(xprv, network); | ||
| const prvKey = parseLightningKey(xprv, network); | ||
| return sdkcore.signMessage(requestString, prvKey, network).toString('hex'); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,17 @@ | ||
| import { ILightningWallet, LightningWallet } from './lightning'; | ||
| import { getLightningAuthKeychains, ILightningWallet, LightningWallet } from './lightning'; | ||
| import * as sdkcore from '@bitgo/sdk-core'; | ||
| import { createMessageSignature, getUtxolibNetwork } from '../lightning'; | ||
| import { UserAuthKeyResetRequest, UserAuthKeyResetResponse, UserAuthKeyResetSignedRequest } from '../codecs'; | ||
| import { computeUserAuthResetVerificationCode } from './userAuthKeyReset'; | ||
|
|
||
| export type ICustodialLightningWallet = ILightningWallet; | ||
| export interface ICustodialLightningWallet extends ILightningWallet { | ||
| requestUserAuthKeyReset(params: { | ||
| passphrase: string; | ||
| encryptionVersion?: sdkcore.EncryptionVersion; | ||
| }): Promise<{ requestId: string; status: string; verificationCode: string }>; | ||
| getUserAuthKeyResetRequest(): Promise<UserAuthKeyResetResponse>; | ||
| cancelUserAuthKeyResetRequest(requestId: string): Promise<unknown>; | ||
| } | ||
|
|
||
| export class CustodialLightningWallet extends LightningWallet implements ICustodialLightningWallet { | ||
| constructor(wallet: sdkcore.IWallet) { | ||
|
|
@@ -10,4 +20,71 @@ export class CustodialLightningWallet extends LightningWallet implements ICustod | |
| throw new Error(`Invalid lightning wallet type for custodial lightning: ${wallet.subType()}`); | ||
| } | ||
| } | ||
|
|
||
| async requestUserAuthKeyReset(params: { | ||
| passphrase: string; | ||
| encryptionVersion?: sdkcore.EncryptionVersion; | ||
| }): Promise<{ requestId: string; status: string; verificationCode: string }> { | ||
| const { userAuthKey } = await getLightningAuthKeychains(this.wallet); | ||
| const coin = this.wallet.baseCoin; | ||
| const { pub, prv } = coin.keychains().create(); | ||
| if (!pub || !prv) { | ||
| throw new Error('Failed to generate user auth key'); | ||
| } | ||
| const encryptedPrv = await this.wallet.bitgo.encrypt({ | ||
| password: params.passphrase, | ||
| input: prv, | ||
| encryptionVersion: params.encryptionVersion, | ||
| }); | ||
| const { id: newUserAuthKeyId } = await coin.keychains().add({ | ||
| pub, | ||
| encryptedPrv, | ||
| source: 'user', | ||
| keyType: 'independent', | ||
| coinSpecific: { [coin.getChain()]: { purpose: 'userAuth' } }, | ||
| }); | ||
| const signedRequest: UserAuthKeyResetSignedRequest = { | ||
| walletId: this.wallet.id(), | ||
| oldUserAuthKeyPub: userAuthKey.pub, | ||
| newUserAuthKeyPub: pub, | ||
| newUserAuthKeyId, | ||
| createdAt: new Date().toISOString(), | ||
| }; | ||
| const request: UserAuthKeyResetRequest = { | ||
| newUserAuthKeyId, | ||
| signedRequest, | ||
| signature: createMessageSignature(signedRequest, prv, getUtxolibNetwork(coin.getChain())), | ||
| }; | ||
| const response = await this.wallet.bitgo | ||
| .post(coin.url(`/wallet/${this.wallet.id()}/lightning/userAuthKey/resetRequest`)) | ||
| .send(UserAuthKeyResetRequest.encode(request)) | ||
| .result(); | ||
| const result = sdkcore.decodeOrElse(UserAuthKeyResetResponse.name, UserAuthKeyResetResponse, response, () => { | ||
| throw new Error('Invalid user auth key reset response'); | ||
| }); | ||
| return { | ||
| requestId: result.requestId, | ||
| status: result.status, | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I compute this from the locally generated public key instead of trusting any server-provided code, so support verification binds to the key the customer actually generated. |
||
| verificationCode: computeUserAuthResetVerificationCode(this.wallet.id(), pub), | ||
| }; | ||
| } | ||
|
|
||
| async getUserAuthKeyResetRequest(): Promise<UserAuthKeyResetResponse> { | ||
| const response = await this.wallet.bitgo | ||
| .get(this.wallet.baseCoin.url(`/wallet/${this.wallet.id()}/lightning/userAuthKey/resetRequest`)) | ||
| .result(); | ||
| return sdkcore.decodeOrElse(UserAuthKeyResetResponse.name, UserAuthKeyResetResponse, response, () => { | ||
| throw new Error('Invalid user auth key reset response'); | ||
| }); | ||
| } | ||
|
|
||
| async cancelUserAuthKeyResetRequest(requestId: string): Promise<unknown> { | ||
| return await this.wallet.bitgo | ||
| .del( | ||
| this.wallet.baseCoin.url( | ||
| `/wallet/${this.wallet.id()}/lightning/userAuthKey/resetRequest/${encodeURIComponent(requestId)}` | ||
| ) | ||
| ) | ||
| .result(); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| import { createHash } from 'crypto'; | ||
|
|
||
| const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; | ||
|
|
||
| export function computeUserAuthResetVerificationCode(walletId: string, newUserAuthKeyPub: string): string { | ||
| const digest = createHash('sha256') | ||
| .update(`lightning-userauth-reset:v1:${walletId}:${newUserAuthKeyPub}`, 'utf8') | ||
| .digest(); | ||
| let bits = 0; | ||
| let value = 0; | ||
| let code = ''; | ||
| for (const byte of digest) { | ||
| value = (value << 8) | byte; | ||
| bits += 8; | ||
| while (bits >= 5 && code.length < 10) { | ||
| bits -= 5; | ||
| code += BASE32_ALPHABET[(value >>> bits) & 31]; | ||
| } | ||
| if (code.length === 10) { | ||
| break; | ||
| } | ||
| } | ||
| return `${code.slice(0, 5)}-${code.slice(5)}`; | ||
| } | ||
|
|
||
| export function compareUserAuthResetVerificationCodes(left: string, right: string): boolean { | ||
| const normalize = (code: string): string => code.replace(/[- ]/g, '').toUpperCase(); | ||
| return normalize(left) === normalize(right); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I reject unknown fields rather than using io-ts exact, which strips them. A verifier must not silently accept a different signed payload.