All files inputFiles.ts

88.86% Statements 351/395
74.59% Branches 138/185
96.15% Functions 25/26
88.86% Lines 351/395

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 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 5301x 1x 1x 1x 1x 1x   1x     1x     1x                                                                                           1x 34x   1x 21x     21x 21x   1x 1x 1x 1x 1x 1x 1x 1x   1x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x   1x   1x 1x 1x 1x 1x 1x 1x 1x   1x 8x 8x 8x 8x 8x           1x 15x   1x 13x 13x 13x 13x 13x   1x   1x 5x 5x 4x 4x 4x   1x 5x 5x 1x 4x   4x   5x 4x 4x   1x 3x       1x 3x       1x 3x       1x 1x   1x 27x 27x 27x 27x 27x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 9x 9x 27x 6x 6x 6x 5x 6x 1x 1x 6x 6x 4x 4x 5x 5x   1x 14x 14x 14x 14x 14x 3x 11x 14x     14x 5x 5x   9x 9x 9x 4x 5x 5x 5x 5x 14x 3x 3x   14x       6x 9x 9x 6x 6x   1x 6x 6x 6x   6x 1x       1x 1x                                         6x 2x 2x       2x     2x 2x                           2x 2x 1x 1x 2x 1x 1x         1x 1x 2x 2x 2x 1x 1x 1x 1x   2x 2x 2x             1x 1x 1x 1x 1x 2x   6x 6x   1x 12x 12x 12x 12x       12x 12x   12x 13x 13x 13x 5x   5x 13x   13x 13x 13x 13x 13x 13x   13x   13x 5x 5x 5x       5x 5x 5x 13x   13x 13x 1x 1x 1x     1x 1x 1x   13x         4x 4x 4x   1x 1x   1x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x   17x 17x 17x 17x   17x 1x 1x 1x 1x 1x 1x 1x 1x   17x 17x 17x 17x 17x 17x 17x   17x 17x 17x 15x 15x 15x 15x 17x 17x   17x 17x 21x 21x 1x 1x 1x 21x 7x 1x 1x 1x 1x 1x 6x 7x     7x 5x 5x 5x 5x 5x 7x 1x 1x 6x 6x 13x 13x 13x 13x 13x   13x 1x 1x 1x 1x 1x 1x   12x 12x 13x 8x   13x 12x 12x 12x 12x 12x 4x 4x 21x 17x 9x 9x 9x   17x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   8x 8x 8x 8x 8x 8x 8x  
import * as dnsPromises from 'node:dns/promises'
import { createWriteStream } from 'node:fs'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { isIP } from 'node:net'
import { tmpdir } from 'node:os'
import { basename, join, parse } from 'node:path'
import type { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import type CacheableLookup from 'cacheable-lookup'
import type { EntryObject, IPFamily } from 'cacheable-lookup'
import got from 'got'
import type { Input as IntoStreamInput } from 'into-stream'
import type { CreateAssemblyParams } from './apiTypes.ts'
import { ensureUniqueCounterValue } from './ensureUniqueCounter.ts'
 
export type InputFile =
  | {
      kind: 'path'
      field: string
      path: string
    }
  | {
      kind: 'base64'
      field: string
      base64: string
      filename: string
      contentType?: string
    }
  | {
      kind: 'url'
      field: string
      url: string
      filename?: string
      contentType?: string
    }
 
export type UploadInput = Readable | IntoStreamInput
 
export type Base64Strategy = 'buffer' | 'tempfile'
export type UrlStrategy = 'import' | 'download' | 'import-if-present'
 
export type PrepareInputFilesOptions = {
  inputFiles?: InputFile[]
  params?: CreateAssemblyParams
  fields?: Record<string, unknown>
  base64Strategy?: Base64Strategy
  urlStrategy?: UrlStrategy
  maxBase64Bytes?: number
  allowPrivateUrls?: boolean
  tempDir?: string
}
 
export type PrepareInputFilesResult = {
  params: CreateAssemblyParams
  files: Record<string, string>
  uploads: Record<string, UploadInput>
  cleanup: Array<() => Promise<void>>
}
 
const isRecord = (value: unknown): value is Record<string, unknown> =>
  typeof value === 'object' && value !== null
 
const ensureUnique = (field: string, used: Set<string>): void => {
  if (used.has(field)) {
    throw new Error(`Duplicate file field: ${field}`)
  }
  used.add(field)
}
 
const ensureUniqueStepName = async (baseName: string, used: Set<string>): Promise<string> =>
  await ensureUniqueCounterValue({
    initialValue: baseName,
    isTaken: (candidate) => used.has(candidate),
    reserve: (candidate) => used.add(candidate),
    nextValue: (counter) => `${baseName}_${counter}`,
    scope: used,
  })
 
const ensureUniqueTempFilePath = async (
  root: string,
  filename: string,
  used: Set<string>,
): Promise<string> => {
  const parsedFilename = parse(basename(filename))
  return await ensureUniqueCounterValue({
    initialValue: join(root, parsedFilename.base),
    isTaken: (candidate) => used.has(candidate),
    reserve: (candidate) => used.add(candidate),
    nextValue: (counter) => join(root, `${parsedFilename.name}-${counter}${parsedFilename.ext}`),
    scope: used,
  })
}
 
const decodeBase64 = (value: string): Buffer => Buffer.from(value, 'base64')
 
const estimateBase64DecodedBytes = (value: string): number => {
  const trimmed = value.trim()
  if (!trimmed) return 0
  let padding = 0
  if (trimmed.endsWith('==')) padding = 2
  else if (trimmed.endsWith('=')) padding = 1
  return Math.floor((trimmed.length * 3) / 4) - padding
}
 
const getFilenameFromUrl = (value: string): string | null => {
  try {
    const pathname = new URL(value).pathname
    const base = basename(pathname)
    if (base && base !== '/' && base !== '.') return base
  } catch {
    return null
  }
  return null
}
 
const isHttpImportStep = (value: unknown): value is Record<string, unknown> =>
  isRecord(value) && value.robot === '/http/import'
 
const findImportStepName = (field: string, steps: Record<string, unknown>): string | null => {
  if (isHttpImportStep(steps[field])) return field
  const matches = Object.entries(steps).filter(([, step]) => isHttpImportStep(step))
  if (matches.length === 1) return matches[0]?.[0] ?? null
  return null
}
 
const MAX_URL_REDIRECTS = 10
 
const isRedirectStatusCode = (statusCode: number): boolean =>
  statusCode === 301 ||
  statusCode === 302 ||
  statusCode === 303 ||
  statusCode === 307 ||
  statusCode === 308
 
const ipv4FromMappedIpv6 = (address: string): string | null => {
  const lowerAddress = address.toLowerCase()
  const mappedPrefix = lowerAddress.startsWith('::ffff:')
    ? '::ffff:'
    : lowerAddress.startsWith('0:0:0:0:0:ffff:')
      ? '0:0:0:0:0:ffff:'
      : null
 
  if (mappedPrefix == null) {
    return null
  }
 
  const mappedValue = lowerAddress.slice(mappedPrefix.length)
  if (mappedValue.includes('.')) {
    return mappedValue
  }
 
  const segments = mappedValue.split(':')
  if (segments.length !== 2) {
    return null
  }
 
  const values = segments.map((segment) => Number.parseInt(segment, 16))
  if (values.some((value) => Number.isNaN(value) || value < 0 || value > 0xffff)) {
    return null
  }
 
  return values.flatMap((value) => [(value >> 8) & 0xff, value & 0xff]).join('.')
}
 
const isPrivateIp = (address: string): boolean => {
  const normalizedAddress =
    address.startsWith('[') && address.endsWith(']') ? address.slice(1, -1) : address
  if (normalizedAddress === 'localhost') return true
  const family = isIP(normalizedAddress)
  if (family === 4) {
    const parts = normalizedAddress.split('.').map((chunk) => Number(chunk))
    const [a, b] = parts
    if (a === 10) return true
    if (a === 127) return true
    if (a === 0) return true
    if (a === 100 && b >= 64 && b <= 127) return true
    if (a === 169 && b === 254) return true
    if (a === 172 && b >= 16 && b <= 31) return true
    if (a === 192 && b === 0 && parts[2] === 0) return true
    if (a === 192 && b === 168) return true
    if (a === 198 && (b === 18 || b === 19)) return true
    return false
  }
  if (family === 6) {
    const normalized = normalizedAddress.toLowerCase().split('%')[0]
    if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') return true
    if (normalized === '::' || normalized === '0:0:0:0:0:0:0:0') return true
    const mappedAddress = ipv4FromMappedIpv6(normalized)
    if (mappedAddress != null && isPrivateIp(mappedAddress)) {
      return true
    }
    if (normalized.startsWith('fe80:')) return true
    if (normalized.startsWith('fc') || normalized.startsWith('fd')) return true
    return false
  }
  return false
}
 
export const resolvePublicDownloadAddresses = async (
  value: string,
): Promise<Array<{ address: string; family: 4 | 6 }>> => {
  const parsed = new URL(value)
  const hostname =
    parsed.hostname.startsWith('[') && parsed.hostname.endsWith(']')
      ? parsed.hostname.slice(1, -1)
      : parsed.hostname
  if (!['http:', 'https:'].includes(parsed.protocol)) {
    throw new Error(`URL downloads are limited to http/https: ${value}`)
  }
  if (isPrivateIp(hostname)) {
    throw new Error(`URL downloads are limited to public hosts: ${value}`)
  }
 
  const literalFamily = isIP(hostname)
  const resolvedAddresses =
    literalFamily !== 0
      ? [{ address: hostname, family: literalFamily as 4 | 6 }]
      : await dnsPromises.lookup(hostname, {
          all: true,
          verbatim: true,
        })
  if (resolvedAddresses.some((address) => isPrivateIp(address.address))) {
    throw new Error(`URL downloads are limited to public hosts: ${value}`)
  }
 
  if (resolvedAddresses.length === 0) {
    throw new Error(`Unable to resolve URL hostname: ${value}`)
  }
 
  return resolvedAddresses.map((address) => ({
    address: address.address,
    family: address.family as 4 | 6,
  }))
}
 
export function createPinnedDnsLookup(
  validatedAddresses: Array<{ address: string; family: 4 | 6 }>,
): CacheableLookup['lookup'] {
  const pinnedAddresses = [...validatedAddresses]
 
  function pickAddress(family?: IPFamily): { address: string; family: 4 | 6 } | null {
    if (family == null) {
      return pinnedAddresses[0] ?? null
    }
 
    return pinnedAddresses.find((address) => address.family === family) ?? null
  }
 
  function pinnedDnsLookup(
    _hostname: string,
    family: IPFamily,
    callback: (error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void,
  ): void
  function pinnedDnsLookup(
    _hostname: string,
    callback: (error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void,
  ): void
  function pinnedDnsLookup(
    _hostname: string,
    options: { all: true },
    callback: (error: NodeJS.ErrnoException | null, result: ReadonlyArray<EntryObject>) => void,
  ): void
  function pinnedDnsLookup(
    _hostname: string,
    options: object,
    callback: (error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void,
  ): void
  function pinnedDnsLookup(
    _hostname: string,
    familyOrCallback:
      | IPFamily
      | object
      | ((error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void),
    callback?:
      | ((error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void)
      | ((error: NodeJS.ErrnoException | null, result: ReadonlyArray<EntryObject>) => void),
  ): void {
    if (typeof familyOrCallback === 'function') {
      const address = pickAddress()
      if (address == null) {
        familyOrCallback(
          new Error('No validated addresses available') as NodeJS.ErrnoException,
          '',
          4,
        )
        return
      }
      familyOrCallback(null, address.address, address.family)
      return
    }
 
    if (
      typeof familyOrCallback === 'object' &&
      familyOrCallback != null &&
      'all' in familyOrCallback
    ) {
      ;(
        callback as (
          error: NodeJS.ErrnoException | null,
          result: ReadonlyArray<EntryObject>,
        ) => void
      )(
        null,
        pinnedAddresses.map((address) => ({
          address: address.address,
          family: address.family,
          expires: 0,
        })),
      )
      return
    }
 
    const family = typeof familyOrCallback === 'number' ? familyOrCallback : undefined
    const address = pickAddress(family)
    if (address == null) {
      ;(
        callback as (error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void
      )(new Error('No validated addresses available') as NodeJS.ErrnoException, '', family ?? 4)
      return
    }
 
    ;(callback as (error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void)(
      null,
      address.address,
      address.family,
    )
  }
 
  return pinnedDnsLookup
}
 
const downloadUrlToFile = async ({
  allowPrivateUrls,
  filePath,
  url,
}: {
  allowPrivateUrls: boolean
  filePath: string
  url: string
}): Promise<void> => {
  let currentUrl = url
 
  for (let redirectCount = 0; redirectCount <= MAX_URL_REDIRECTS; redirectCount += 1) {
    let validatedAddresses: Array<{ address: string; family: 4 | 6 }> | null = null
    if (!allowPrivateUrls) {
      validatedAddresses = await resolvePublicDownloadAddresses(currentUrl)
    }
 
    const dnsLookup: CacheableLookup['lookup'] | undefined =
      validatedAddresses == null ? undefined : createPinnedDnsLookup(validatedAddresses)
 
    const responseStream = got.stream(currentUrl, {
      dnsLookup,
      followRedirect: false,
      retry: { limit: 0 },
      throwHttpErrors: false,
    })
 
    const response = await new Promise<
      Readable & { headers: Record<string, string>; statusCode?: number }
    >((resolvePromise, reject) => {
      responseStream.once('response', (incomingResponse) => {
        resolvePromise(
          incomingResponse as Readable & {
            headers: Record<string, string>
            statusCode?: number
          },
        )
      })
      responseStream.once('error', reject)
    })
 
    const statusCode = response.statusCode ?? 0
    if (isRedirectStatusCode(statusCode)) {
      responseStream.destroy()
      const location = response.headers.location
      if (location == null) {
        throw new Error(`Redirect response missing Location header: ${currentUrl}`)
      }
      currentUrl = new URL(location, currentUrl).toString()
      continue
    }
 
    if (statusCode >= 400) {
      responseStream.destroy()
      throw new Error(`Failed to download URL: ${currentUrl} (${statusCode})`)
    }
 
    await pipeline(responseStream, createWriteStream(filePath))
    return
  }
 
  throw new Error(`Too many redirects while downloading URL input: ${url}`)
}
 
export const prepareInputFiles = async (
  options: PrepareInputFilesOptions = {},
): Promise<PrepareInputFilesResult> => {
  const {
    inputFiles = [],
    params = {},
    fields,
    base64Strategy = 'buffer',
    urlStrategy = 'import',
    maxBase64Bytes,
    allowPrivateUrls = true,
    tempDir,
  } = options
 
  let nextParams: CreateAssemblyParams = { ...params }
  const files: Record<string, string> = {}
  const uploads: Record<string, UploadInput> = {}
  const cleanup: Array<() => Promise<void>> = []
 
  if (fields && Object.keys(fields).length > 0) {
    nextParams = {
      ...nextParams,
      fields: {
        ...(isRecord(nextParams.fields) ? nextParams.fields : {}),
        ...fields,
      },
    }
  }
 
  const steps = isRecord(nextParams.steps) ? { ...nextParams.steps } : {}
  const usedSteps = new Set(Object.keys(steps))
  const usedFields = new Set<string>()
  const usedTempPaths = new Set<string>()
  const importUrlsByStep = new Map<string, string[]>()
  const importStepNames = Object.keys(steps).filter((name) => isHttpImportStep(steps[name]))
  const sharedImportStep = importStepNames.length === 1 ? importStepNames[0] : null
 
  let tempRoot: string | null = null
  const ensureTempRoot = async (): Promise<string> => {
    if (!tempRoot) {
      const root = await mkdtemp(join(tempDir ?? tmpdir(), 'transloadit-input-'))
      tempRoot = root
      cleanup.push(() => rm(root, { recursive: true, force: true }))
    }
    return tempRoot
  }
 
  try {
    for (const file of inputFiles) {
      ensureUnique(file.field, usedFields)
      if (file.kind === 'path') {
        files[file.field] = file.path
        continue
      }
      if (file.kind === 'base64') {
        if (maxBase64Bytes) {
          const estimated = estimateBase64DecodedBytes(file.base64)
          if (estimated > maxBase64Bytes) {
            throw new Error(`Base64 payload exceeds ${maxBase64Bytes} bytes.`)
          }
        }
        const buffer = decodeBase64(file.base64)
        if (maxBase64Bytes && buffer.length > maxBase64Bytes) {
          throw new Error(`Base64 payload exceeds ${maxBase64Bytes} bytes.`)
        }
        if (base64Strategy === 'tempfile') {
          const root = await ensureTempRoot()
          const filename = file.filename ? basename(file.filename) : `${file.field}.bin`
          const filePath = await ensureUniqueTempFilePath(root, filename, usedTempPaths)
          await writeFile(filePath, buffer)
          files[file.field] = filePath
        } else {
          uploads[file.field] = buffer
        }
        continue
      }
      if (file.kind === 'url') {
        const matchedStep = findImportStepName(file.field, steps)
        const targetStep = matchedStep ?? sharedImportStep
        const shouldImport =
          urlStrategy === 'import' || (urlStrategy === 'import-if-present' && targetStep)
 
        if (shouldImport) {
          const stepName = targetStep ?? (await ensureUniqueStepName(file.field, usedSteps))
          const urls = importUrlsByStep.get(stepName) ?? []
          urls.push(file.url)
          importUrlsByStep.set(stepName, urls)
          continue
        }
 
        const root = await ensureTempRoot()
        const filename =
          (file.filename ? basename(file.filename) : null) ??
          getFilenameFromUrl(file.url) ??
          `${file.field}.bin`
        const filePath = await ensureUniqueTempFilePath(root, filename, usedTempPaths)
        await downloadUrlToFile({
          allowPrivateUrls,
          filePath,
          url: file.url,
        })
        files[file.field] = filePath
      }
    }
  } catch (error) {
    await Promise.all(cleanup.map((fn) => fn()))
    throw error
  }
 
  if (Object.keys(steps).length > 0 || importUrlsByStep.size > 0) {
    if (importUrlsByStep.size > 0) {
      for (const [stepName, urls] of importUrlsByStep.entries()) {
        const existing = isRecord(steps[stepName]) ? steps[stepName] : {}
        steps[stepName] = {
          ...existing,
          robot: '/http/import',
          url: urls.length === 1 ? urls[0] : urls,
        }
      }
    }
 
    nextParams = {
      ...nextParams,
      steps,
    }
  }
 
  return {
    params: nextParams,
    files,
    uploads,
    cleanup,
  }
}