All files / src/internal storage-encoding.ts

100% Statements 14/14
75% Branches 3/4
100% Functions 8/8
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 4315x     108x       46563x         236x     20012x         16x       8x 8x               8x       16x 8x 8x      
const textEncoder = new TextEncoder()
 
export function encodeUtf8(value: string): Uint8Array<ArrayBuffer> {
  return textEncoder.encode(value)
}
 
export function decodeBase64ToBytes(base64: string): Uint8Array<ArrayBuffer> {
  return Uint8Array.from(atob(base64), (character) => character.codePointAt(0) ?? 0)
}
 
export function encodeBytesToBase64(bytes: ArrayBuffer | ArrayBufferView): string {
  const view =
    bytes instanceof ArrayBuffer
      ? new Uint8Array(bytes)
      : new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)
  return btoa(Array.from(view, (byte) => String.fromCodePoint(byte)).join(''))
}
 
/** Signs text with HMAC-SHA256 and a base64 key, as Azure Storage and App Configuration expect. */
export function createHmacSigner(base64Key: string): (text: string) => Promise<string> {
  const keyBytes = decodeBase64ToBytes(base64Key)
  let key: Promise<CryptoKey> | undefined
 
  async function importKey(): Promise<CryptoKey> {
    try {
      return await crypto.subtle.importKey(
        'raw',
        keyBytes,
        { name: 'HMAC', hash: 'SHA-256' },
        false,
        ['sign'],
      )
    } finally {
      keyBytes.fill(0)
    }
  }
 
  return async (text) => {
    key ??= importKey()
    return encodeBytesToBase64(await crypto.subtle.sign('HMAC', await key, encodeUtf8(text)))
  }
}