import makeFetch from 'fetch-ponyfill' ; import { AES_CBC } from 'asmcrypto.js' ; import { Bytes , Checksum256 , Checksum512 , PrivateKey , PublicKey , Serializer , UInt64 , } from '@greymass/eosio' ; import { CallbackPayload , SigningRequest } from 'eosio-signing-request' ; import { SealedMessage } from './link-types' ; internal export const fetch = makeFetch ( ) . fetch ; internal export function sealMessage ( message , privateKey , publicKey , nonce ? ) { const secret = privateKey . sharedSecret ( publicKey ) ; if ( ! nonce ) { nonce = UInt64 . random ( ) ; } const key = Checksum512 . hash ( Serializer . encode ( { object : nonce } ) . appending ( secret . array ) ) ; const cbc = new AES_CBC ( key . array . slice ( 0 , 32 ) , key . array . slice ( 32 , 48 ) ) ; const ciphertext = Bytes . from ( cbc . encrypt ( Bytes . from ( message , 'utf8' ) . array ) ) ; const checksumView = new DataView ( Checksum256 . hash ( key . array ) . array . buffer ) ; const checksum = checksumView . getUint32 ( 0 , true ) ; return SealedMessage . from ( { from : privateKey . toPublic ( ) , nonce , ciphertext , checksum , } ) ; } internal export function sessionMetadata ( payload , request ) { const metadata = { sameDevice : request . getRawInfo ( ) [ 'return_path' ] !== undefined , } ; if ( payload . link_meta ) { try { const parsed = JSON . parse ( payload . link_meta ) ; for ( const key of Object . keys ( parsed ) ) { metadata [ snakeToCamel ( key ) ] = parsed [ key ] ; } } catch ( error ) { logWarn ( 'Unable to parse link metadata' , error , payload . link_meta ) ; } } return metadata ; } internal function snakeToPascal ( name ) { return name . split ( '_' ) . map ( ( v ) => ( v [ 0 ] ? v [ 0 ] . toUpperCase ( ) : '_' ) + v . slice ( 1 ) ) . join ( '' ) ; } internal function snakeToCamel ( name ) { const pascal = snakeToPascal ( name ) ; return pascal [ 0 ] . toLowerCase ( ) + pascal . slice ( 1 ) ; } internal export function logWarn ( ... args ) { console . warn ( '[anchor-link]' , ... args ) ; }