import { split , combine } from '@stablelib/tss' ; import { Encoding , encoders , decoders , utf8 } from '@47ng/codec' ; import * as NodeCrypto from 'crypto' ; let nodeCrypto ; if ( typeof window === 'undefined' ) { nodeCrypto = require ( 'crypto' ) ; } export function generateRandomBytes ( length ) { if ( typeof window === 'undefined' ) { return nodeCrypto . randomBytes ( length ) ; } else { return window . crypto . getRandomValues ( new Uint8Array ( length ) ) ; } } param secret param numShards param threshold param outputEncoding export function splitSecret ( secret , numShards , threshold , outputEncoding = 'base64' ) { const encode = encoders [ outputEncoding ] ; const identifier = generateRandomBytes ( 16 ) ; const shards = split ( utf8 . encode ( secret ) , threshold , numShards , identifier ) ; return shards . map ( shard => encode ( shard ) ) ; } export function detectEncoding ( text ) { const hex = /^[\dabcdef]+$/ ; const b64 = /^[\w-]+(?:[=]{0,2})?$/ ; if ( text . toLowerCase ( ) . match ( hex ) ) { return 'hex' ; } if ( text . match ( b64 ) ) { return 'base64' ; } return 'utf8' ; } param shards export function assembleSecret ( shards ) { const secret = combine ( shards . map ( shard => { const decode = decoders [ detectEncoding ( shard ) ] ; return decode ( shard ) ; } ) ) ; return utf8 . decode ( secret ) ; } param shard export function cleanupShard ( shard ) { return shard . replace ( /\s/g , '' ) ; }