/** * @file Types for HTTP download + checksum-fetch operations. Split out of * `http-request/types.ts` for size hygiene. * * - `HttpDownloadOptions` / `HttpDownloadResult` — file-download surface * - `ChecksumFile` / `FetchChecksumFileOptions` — checksum-file helpers */ import type { IncomingHttpHeaders } from 'node:http'; import type { Writable } from 'node:stream'; import type { Logger } from '../logger/node.js'; export interface HttpDownloadWriteStreamOptions { /** * Validated response Content-Length. The factory is bypassed in favor of a * regular file stream when the server does not provide an exact length. */ size: number; } /** * Injectable destination stream used for direct-to-filesystem transforms. */ export type HttpDownloadWriteStreamFactory = (path: string, options: HttpDownloadWriteStreamOptions) => Writable; /** * Configuration options for file downloads. */ export interface HttpDownloadOptions { /** * Custom CA certificates for TLS connections. When provided, these * certificates are used for the download request. See `HttpRequestOptions.ca` * for details. */ ca?: string[] | undefined; /** * Create the stream that receives response bytes. The path is the download's * sibling temp path, not the final destination, so hash verification and the * final atomic rename retain their existing safety guarantees. Responses * without a valid Content-Length use the regular file writer instead. */ createWriteStream?: HttpDownloadWriteStreamFactory | undefined; /** * Whether to automatically follow HTTP redirects (3xx status codes). This is * essential for downloading from services that use CDN redirects, such as * GitHub release assets which return HTTP 302 to their CDN. * * @example * ;```ts * // Follow redirects (default) - works with GitHub releases * await httpDownload( * 'https://github.com/org/repo/releases/download/v1.0.0/file.zip', * '/tmp/file.zip', * ) * ``` * * @default true */ followRedirects?: boolean | undefined; /** * HTTP headers to send with the download request. A `User-Agent` header is * automatically added if not provided. * * @example * ;```ts * await httpDownload('https://example.com/file.zip', '/tmp/file.zip', { * headers: { * Authorization: 'Bearer token123', * }, * }) * ``` */ headers?: Record | undefined; /** * Expected SHA-512 SRI string. If provided, the download fails before * publication when the streamed digest does not match. */ integrity?: string | undefined; /** * Logger instance for automatic progress logging. When provided with * `progressInterval`, will automatically log download progress. If both * `onProgress` and `logger` are provided, `onProgress` takes precedence. * * @example * ;```ts * import { getDefaultLogger } from '@socketsecurity/lib/logger/node' * * const logger = getDefaultLogger() * await httpDownload('https://example.com/file.zip', '/tmp/file.zip', { * logger, * progressInterval: 10, // Log every 10% * }) * ``` */ logger?: Logger | undefined; /** * Maximum number of redirects to follow before throwing an error. Only * relevant when `followRedirects` is `true`. * * @default 5 */ maxRedirects?: number | undefined; /** * Callback for tracking download progress. Called periodically as data is * received. Takes precedence over `logger` if both are provided. * * @example * ```ts * await httpDownload( * 'https://example.com/large-file.zip', * '/tmp/file.zip', * { * onProgress: (downloaded, total) => { * const percent = ((downloaded / total) * 100).toFixed(1) * console.log(`Progress: ${percent}%`) * }, * }, * ) * ``` * * @param downloaded - Number of bytes downloaded so far. * @param total - Total file size in bytes, from the Content-Length header. */ onProgress?: ((downloaded: number, total: number) => void) | undefined; /** * Progress reporting interval as a percentage (0-100). Only used when * `logger` is provided. Progress will be logged each time the download * advances by this percentage. * * @default 10 */ progressInterval?: number | undefined; /** * Number of retry attempts for failed downloads. Uses exponential backoff: * delay = `retryDelay` * 2^attempt. * * @example * ;```ts * await httpDownload('https://example.com/file.zip', '/tmp/file.zip', { * retries: 3, * retryDelay: 2000, * }) * ``` * * @default 0 */ retries?: number | undefined; /** * Initial delay in milliseconds before first retry. Subsequent retries use * exponential backoff. * * @default 1000 */ retryDelay?: number | undefined; /** * Download timeout in milliseconds. If the download takes longer than this, * it will be aborted. * * @default 120000 */ timeout?: number | undefined; /** * Expected SHA256 hash of the downloaded file. If provided, the download will * fail if the computed hash doesn't match. The hash should be a lowercase hex * string (64 characters). * * Pair with `fetchChecksumFile()` + `parseHash(x).hex` when working from a * checksums URL, since `fetchChecksumFile()` returns SRI strings. * * @example * ;```ts * // Verify download with a sha256 hex digest * await httpDownload('https://example.com/file.zip', '/tmp/file.zip', { * sha256: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', * }) * ``` */ sha256?: string | undefined; } /** * Result of a successful file download. */ export interface HttpDownloadResult { /** * HTTP response headers from the final response after any redirects. */ headers: IncomingHttpHeaders; /** * SHA-512 SRI digest computed while the response streamed. */ integrity: string; /** * Whether the download succeeded (status 200-299). Always true on success * (non-2xx throws). */ ok: true; /** * Absolute path where the file was saved. */ path: string; /** * Lowercase SHA-256 digest computed while the response streamed. */ sha256: string; /** * Total size of downloaded file in bytes. */ size: number; /** * HTTP status code from the final response after any redirects. */ status: number; /** * HTTP status message from the final response after any redirects. */ statusText: string; } /** * Map of filenames to SRI integrity strings (`sha256-=`). Returned by * `parseChecksumFile` / `fetchChecksumFile`. Pass through `parseHash(x).hex` * to feed `httpDownload({ sha256 })`, or pass the SRI string directly to * consumers that accept SRI. * * @example * ;```ts * const sums: ChecksumFile = { * 'file.zip': 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=', * 'other.tar.gz': 'sha256-...', * } * ``` */ export type ChecksumFile = Record; /** * Options for fetching a checksum file from a URL. */ export interface FetchChecksumFileOptions { /** * Custom CA certificates for TLS connections. See `HttpRequestOptions.ca` for * details. */ ca?: string[] | undefined; /** * HTTP headers to send with the request. */ headers?: Record | undefined; /** * Request timeout in milliseconds. * * @default 30000 */ timeout?: number | undefined; }