All files / src/internal runtime.ts

94.87% Statements 37/39
82.75% Branches 24/29
100% Functions 14/14
94.87% Lines 37/39

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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128                        15x     15x 15x 15x     15x 1x       598x 598x         34x 34x       19x       11x       3x               16x 16x 16x       16x 16x                         16x       16x     16x 16x 6x     9x       17x 17x       17x                 6x 6x 1x     5x 5x 5x     2x         6x       17x       16x    
import type * as ChildProcess from 'node:child_process'
import type * as Crypto from 'node:crypto'
import type * as FsPromises from 'node:fs/promises'
 
interface RuntimeGlobals {
  process?: {
    env?: Partial<Record<string, string>>
    platform?: string
    versions?: { node?: string }
  }
}
 
const runtime: RuntimeGlobals = globalThis
 
// Built at runtime so edge bundlers don't try to resolve the Node builtin.
const childProcessModule = ['node', ['child', 'process'].join('_')].join(':')
const cryptoModule = ['node', 'crypto'].join(':')
const fsPromisesModule = ['node', ['fs', 'promises'].join('/')].join(':')
 
/** Uses the global `fetch` at call time, bound to the global object as browsers and workers require. */
export const defaultFetch: typeof globalThis.fetch = async (input, init) =>
  await globalThis.fetch(input, init)
 
/** Reads a non-empty environment variable; runtimes without `process` have none. */
export function getEnv(name: string): string | undefined {
  const value = runtime.process?.env?.[name]?.trim()
  return value === '' ? undefined : value
}
 
/** Reads a non-empty environment variable unchanged, as passwords may start or end with whitespace. */
export function getRawEnv(name: string): string | undefined {
  const value = runtime.process?.env?.[name]
  return value === '' ? undefined : value
}
 
export function hasCommandExecution(): boolean {
  return runtime.process?.versions?.node !== undefined
}
 
export function isWindows(): boolean {
  return runtime.process?.platform === 'win32'
}
 
export function isCommandUnavailable(error: unknown): boolean {
  return error instanceof Error && 'code' in error && error.code === 'ENOENT'
}
 
export async function executeCommand(
  command: string,
  args: string[],
  options: { signal?: AbortSignal; shell?: boolean } = {},
): Promise<string> {
  options.signal?.throwIfAborted()
  const childProcess: unknown = await import(childProcessModule)
  Iif (!isChildProcessModule(childProcess)) {
    throw new Error('Command execution is unavailable')
  }
 
  const result = await new Promise<{ error: Error | null; stdout: string }>((resolve) => {
    const child = childProcess.execFile(
      command,
      args,
      {
        signal: options.signal,
        shell: options.shell,
        windowsHide: true,
        env:
          options.shell === true
            ? { ...runtime.process?.env, NoDefaultCurrentDirectoryInExePath: '1' }
            : undefined,
      },
      (error, stdout) => {
        resolve({ error, stdout })
      },
    )
    // Commands must not wait for input that never comes.
    child.stdin?.end()
  })
 
  options.signal?.throwIfAborted()
  if (result.error !== null) {
    throw result.error
  }
 
  return result.stdout
}
 
export async function readTextFile(path: string): Promise<string> {
  const fs: unknown = await import(fsPromisesModule)
  Iif (!isFsPromisesModule(fs)) {
    throw new Error('File system access is unavailable')
  }
 
  return await fs.readFile(path, 'utf8')
}
 
/** Decrypts a password-protected PEM private key to PKCS#8 DER; Web Crypto can't. */
export async function decryptPrivateKey(
  pem: string,
  password: string,
): Promise<Uint8Array<ArrayBuffer>> {
  // Runtimes that can execute commands are the ones that provide node:crypto.
  const nodeCrypto: unknown = hasCommandExecution() ? await import(cryptoModule) : undefined
  if (!isCryptoModule(nodeCrypto)) {
    throw new Error('Encrypted private keys need a Node-compatible runtime')
  }
 
  try {
    const key = nodeCrypto.createPrivateKey({ key: pem, format: 'pem', passphrase: password })
    return new Uint8Array(key.export({ format: 'der', type: 'pkcs8' }))
  } catch (error) {
    // Each runtime's crypto library reports a wrong password differently.
    throw new Error('Unable to decrypt the private key with the given password', { cause: error })
  }
}
 
function isCryptoModule(value: unknown): value is typeof Crypto {
  return typeof value === 'object' && value !== null && 'createPrivateKey' in value
}
 
function isFsPromisesModule(value: unknown): value is typeof FsPromises {
  return typeof value === 'object' && value !== null && 'readFile' in value
}
 
function isChildProcessModule(value: unknown): value is typeof ChildProcess {
  return typeof value === 'object' && value !== null && 'execFile' in value
}