on b78a856 help sign in
bridge/src/lib/authToken.ts
50 lines 1.5 kB history raw
1import { ecdsaSign } from 'secp256k1';
2import { keccak256 } from 'web3-utils';
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 // TODO: Signing function expects 32 length Buffer,
13 // confirm if it is okay / expected to slice it like this?
14 // Based on reading docs and comment threads, it seems that
15 // this limit is sometimes enforced, and varies depending on
16 // the implementation
17 const msgHash = Buffer.from(keccak256(msg)).slice(0, 32);
18 const { signature } = ecdsaSign(msgHash, privateKey);
20 // add key recovery parameter
21 const ethSignature = new Uint8Array(65);
22 ethSignature.set(signature);
23 const v = (ethSignature[32] & 1) + 27;
24 ethSignature[64] = v;
26 return ethSignature;
29export const getAuthToken = async ({
30 wallet,
31 walletType,
32 walletHdPath,
33 web3,
34}) => {
35 if (walletType === WALLET_TYPES.METAMASK) {
36 return web3.eth.personal.sign(MESSAGE, wallet.address, '');
37 }
38 if (walletType === WALLET_TYPES.LEDGER) {
39 return ledgerSignMessage(MESSAGE, walletHdPath);
40 }
41 if (walletType === WALLET_TYPES.TREZOR) {
42 return trezorSignMessage(MESSAGE, walletHdPath);
43 }
45 const signature = signMessage(wallet.privateKey);
47 const token = `0x${Buffer.from(signature).toString('hex')}`;
49 return token;
50};