|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +const ethers = require('ethers'); |
| 4 | +const { Base64 } = require('js-base64'); |
| 5 | + |
| 6 | +async function generateKeyPairAndSignature(privateKeyInput) { |
| 7 | + try { |
| 8 | + // Create wallet from provided private key or generate new random wallet |
| 9 | + const wallet = privateKeyInput |
| 10 | + ? new ethers.Wallet(privateKeyInput) |
| 11 | + : ethers.Wallet.createRandom(); |
| 12 | + const publicAddress = wallet.address; |
| 13 | + |
| 14 | + // Sign the public address using the private key |
| 15 | + const signature = await wallet.signMessage(publicAddress); |
| 16 | + |
| 17 | + // Base64 encode the signature before creating the auth string |
| 18 | + const base64Signature = Base64.encode( |
| 19 | + Buffer.from(signature.slice(2), 'hex'), |
| 20 | + ); |
| 21 | + |
| 22 | + // Create the basic auth credential in the format expected by the middleware |
| 23 | + const basicAuthString = `${publicAddress}:${base64Signature}`; |
| 24 | + const basicAuthHeader = `basic ${Base64.encode(basicAuthString)}`; |
| 25 | + |
| 26 | + return { |
| 27 | + privateKey: wallet.privateKey, |
| 28 | + publicAddress, |
| 29 | + signature, |
| 30 | + basicAuthHeader, |
| 31 | + }; |
| 32 | + } catch (error) { |
| 33 | + console.error('Error:', error.message); |
| 34 | + throw error; |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +// Execute the function |
| 39 | +(async () => { |
| 40 | + // Get private key from command line argument if provided |
| 41 | + const providedPrivateKey = process.argv[2]; |
| 42 | + |
| 43 | + const { privateKey, publicAddress, signature, basicAuthHeader } = |
| 44 | + await generateKeyPairAndSignature(providedPrivateKey); |
| 45 | + |
| 46 | + console.log('Authentication Details:'); |
| 47 | + console.log('Private Key:', privateKey); |
| 48 | + console.log('Public Address:', publicAddress); |
| 49 | + console.log('\nFor Basic Auth:'); |
| 50 | + console.log('Authorization Header:', basicAuthHeader); |
| 51 | + console.log('\nFor Manual Construction:'); |
| 52 | + console.log('Username:', publicAddress); |
| 53 | + console.log( |
| 54 | + 'Password:', |
| 55 | + Base64.encode(Buffer.from(signature.slice(2), 'hex')), |
| 56 | + ); |
| 57 | +})(); |
0 commit comments