on 832e643 help sign in
bridge/src/lib/authToken.ts
46 lines 1.3 kB history raw
1import { crypto } from 'bitcoinjs-lib';
2import { ecdsaSign } from 'secp256k1';
4import { WALLET_TYPES } from './constants';
5import { ledgerSignMessage } from './ledger';
6import { trezorSignMessage } from './trezor';
8const MESSAGE = 'Bridge Authentication Token';
10function signMessage(privateKey: Buffer) {
11 const msg = '\x19Ethereum Signed Message:\n' + MESSAGE.length + MESSAGE;
12 // #ecdsaSign requires a 32-byte buffer, hence sha256
13 const hashed = crypto.sha256(Buffer.from(msg));
14 const { signature } = ecdsaSign(Buffer.from(hashed), privateKey);
16 // add key recovery parameter
17 const ethSignature = new Uint8Array(65);
18 ethSignature.set(signature);
19 const v = (ethSignature[32] & 1) + 27;
20 ethSignature[64] = v;
22 return ethSignature;
25export const getAuthToken = async ({
26 wallet,
27 walletType,
28 walletHdPath,
29 web3,
30}) => {
31 if (walletType === WALLET_TYPES.METAMASK) {
32 return web3.eth.personal.sign(MESSAGE, wallet.address, '');
33 }
34 if (walletType === WALLET_TYPES.LEDGER) {
35 return ledgerSignMessage(MESSAGE, walletHdPath);
36 }
37 if (walletType === WALLET_TYPES.TREZOR) {
38 return trezorSignMessage(MESSAGE, walletHdPath);
39 }
41 const signature = signMessage(wallet.privateKey);
43 const token = `0x${Buffer.from(signature).toString('hex')}`;
45 return token;
46};