Skip to content
VaelJS Blog

vael:fetch

SSRF-hardened HTTP/HTTPS client and streaming atomic file downloader.

Available in the vjs (vaeljs) runtime (fetch, fetchSync, download, downloadSync); vjs-lite (vaeljs-lite) exposes synchronous fetchSync and downloadSync only. Never installed on globalThis — import explicitly from "vael:fetch".

Enforces http:/https:-only URLs without embedded credentials, blocks private, loopback, link-local, and cloud-metadata IP ranges unless allowPrivateIps: true is specified, validates every redirect hop and strips sensitive credentials across origins, and bounds response/download memory.

import ... from "vael:fetch"
Since v0.0.0-alpha.2 vjs (V8) vjs-lite (QuickJS)
Cargo feature: vael-fetch (enabled by default in vaeljs-core and vaeljs-lite-core)
Async fetch and download are V8-only (vjs). Synchronous fetchSync and downloadSync run on both vjs and vjs-lite via blocking ureq + rustls.
import { download, fetch, fetchSync } from "vael:fetch";
const res = await fetch("https://example.com/data.json", {
timeoutMs: 10_000,
});
if (res.ok) {
console.log(res.status, res.json());
}
const syncRes = fetchSync("https://example.com/health");
console.log(syncRes.status, syncRes.text());
const dl = await download("https://example.com/archive.tar.gz", "./archive.tar.gz", {
overwrite: true,
});
console.log(dl.bytesWritten, dl.sha256);
functionSince v0.0.0-alpha.2vjs only
export function fetch(url: string, options?: FetchOptions): Promise<FetchResponse>;

Perform an asynchronous SSRF-hardened HTTP/HTTPS request on a worker thread and buffer the bounded response.

Available in vjs (vaeljs) only; use fetchSync in vjs-lite.

Parameters
NameTypeDescription
urlstringTarget http: or https: URL without embedded userinfo.
options optionalFetchOptionsOptional request method, headers, query, body, and limits.
Returns
Promise<FetchResponse> — Promise resolving to the buffered FetchResponse.
Exceptions
  • TypeError — on wrong argument types.
  • FetchError — on invalid URL/options, SSRF block, timeout, redirect limit, body limit, or network error.
import { fetch } from "vael:fetch";
const res = await fetch("https://example.com/api", {
method: "POST",
json: { ping: true },
});
console.log(res.status, res.text());
functionSince v0.0.0-alpha.2vjs & vjs-lite
export function fetchSync(url: string, options?: FetchOptions): FetchResponse;

Perform a synchronous SSRF-hardened HTTP/HTTPS request and buffer the bounded response.

Available in both vjs (vaeljs) and vjs-lite (vaeljs-lite).

Parameters
NameTypeDescription
urlstringTarget http: or https: URL without embedded userinfo.
options optionalFetchOptionsOptional request method, headers, query, body, and limits.
Returns
FetchResponse — Buffered FetchResponse.
Exceptions
  • TypeError — on wrong argument types.
  • FetchError — on invalid URL/options, SSRF block, timeout, redirect limit, body limit, or network error.
import { fetchSync } from "vael:fetch";
const res = fetchSync("https://example.com/health");
console.log(res.ok, res.status);
functionSince v0.0.0-alpha.2vjs only
export function download(
  url: string,
  destPath: string,
  options?: DownloadOptions,
): Promise<DownloadResult>;

Stream an HTTP/HTTPS GET response directly to a sibling temporary file, verify optional SHA-256 integrity, and atomically commit to destPath on a worker thread.

Non-2xx status codes reject with FetchError ("VAEL_FETCH_HTTP_STATUS") without creating or modifying destPath. Available in vjs (vaeljs) only; use downloadSync in vjs-lite.

Parameters
NameTypeDescription
urlstringTarget http: or https: URL without embedded userinfo.
destPathstringDestination regular file path (parent must be a non-symlink directory).
options optionalDownloadOptionsOptional headers, timeout, size limit, SHA-256 digest, overwrite, and progress callback.
Returns
Promise<DownloadResult> — Promise resolving to DownloadResult metadata.
Exceptions
  • TypeError — on wrong argument types.
  • FetchError — on invalid URL/options, SSRF block, non-2xx status, checksum mismatch, existing target, or I/O error.
import { download } from "vael:fetch";
const res = await download("https://example.com/release.bin", "./release.bin", {
expectedSha256: "0".repeat(64),
overwrite: true,
});
console.log(res.bytesWritten, res.sha256);
functionSince v0.0.0-alpha.2vjs & vjs-lite
export function downloadSync(
  url: string,
  destPath: string,
  options?: DownloadOptions,
): DownloadResult;

Synchronously stream an HTTP/HTTPS GET response directly to a sibling temporary file, verify optional SHA-256 integrity, and atomically commit to destPath.

Non-2xx status codes throw FetchError ("VAEL_FETCH_HTTP_STATUS") without creating or modifying destPath. Available in both vjs (vaeljs) and vjs-lite (vaeljs-lite).

Parameters
NameTypeDescription
urlstringTarget http: or https: URL without embedded userinfo.
destPathstringDestination regular file path (parent must be a non-symlink directory).
options optionalDownloadOptionsOptional headers, timeout, size limit, SHA-256 digest, overwrite, and progress callback.
Returns
DownloadResult — DownloadResult metadata.
Exceptions
  • TypeError — on wrong argument types.
  • FetchError — on invalid URL/options, SSRF block, non-2xx status, checksum mismatch, existing target, or I/O error.
import { downloadSync } from "vael:fetch";
const res = downloadSync("https://example.com/release.bin", "./release.bin", {
overwrite: true,
});
console.log(res.bytesWritten, res.sha256);
classSince v0.0.0-alpha.2vjs & vjs-lite
export class FetchError extends Error {
  override name: "FetchError";
  code: FetchErrorCode;
  readonly status?: number;
  readonly url?: string;
  constructor(code: FetchErrorCode, message: string);
}

Redacted HTTP client or download error carrying a stable VAEL_FETCH_* error code.

Error messages redact URL query strings, embedded credentials, bearer tokens, and sensitive header values.

Constructor
constructor(code: FetchErrorCode, message: string);

Construct a FetchError.

Parameters
NameTypeDescription
codeFetchErrorCodeMachine-readable FetchErrorCode.
messagestringHuman-readable redacted error message.
Properties
PropertyTypeDescriptionSince
name "FetchError"Error name ("FetchError").v0.0.0-alpha.2
code FetchErrorCodeMachine-readable VAEL_FETCH_* error classification.v0.0.0-alpha.2
status readonly optionalnumberHTTP status code when the error resulted from a non-2xx download status (VAEL_FETCH_HTTP_STATUS).v0.0.0-alpha.2
url readonly optionalstringRedacted target URL (scheme://host[:port]/path) associated with the failure, when applicable.v0.0.0-alpha.2
interfaceSince v0.0.0-alpha.2vjs & vjs-lite
export interface FetchOptions {
  method?: HttpMethod;
  headers?: Record<string, string> | ReadonlyArray<readonly [string, string]>;
  query?: Record<string, string> | ReadonlyArray<readonly [string, string]>;
  bearerToken?: string;
  body?: string | Uint8Array;
  json?: unknown;
  timeoutMs?: number;
  maxResponseBytes?: number;
  maxRedirects?: number;
  allowPrivateIps?: boolean;
  userAgent?: string | null;
}

Request options accepted by fetch and fetchSync.

body and json are mutually exclusive; specifying both throws FetchError with code "VAEL_FETCH_INVALID_OPTION".

Properties
PropertyTypeDescriptionSince
method optionalHttpMethodHTTP request method (case-insensitive, default "GET").v0.0.0-alpha.2
headers optionalRecord<string, string> | ReadonlyArray<readonly [string, string]>Additional HTTP request headers as a plain object or [name, value] pairs. Header names must be valid RFC 7230 tokens and values must not contain CR, LF, NUL, or ASCII control characters.v0.0.0-alpha.2
query optionalRecord<string, string> | ReadonlyArray<readonly [string, string]>Query parameters safely URL-encoded and appended to the request URL.v0.0.0-alpha.2
bearerToken optionalstringBearer token sent as Authorization: Bearer <token> when no explicit Authorization header is present. Stripped on cross-origin redirects.v0.0.0-alpha.2
body optionalstring | Uint8ArrayRaw UTF-8 text or binary request body. Mutually exclusive with json, and rejected on GET and HEAD requests.v0.0.0-alpha.2
json optionalunknownJSON-serializable request payload. Mutually exclusive with body, rejected on GET and HEAD requests, and sets Content-Type: application/json; charset=utf-8 when absent.v0.0.0-alpha.2
timeoutMs optionalnumberOverall request deadline in milliseconds across redirects and body read (default 30_000, must be > 0 and <= 600_000).v0.0.0-alpha.2
maxResponseBytes optionalnumberMaximum buffered response body size in bytes (default 16_777_216 / 16 MiB, must be > 0 and <= 268_435_456 / 256 MiB).v0.0.0-alpha.2
maxRedirects optionalnumberMaximum number of HTTP redirects (301, 302, 303, 307, 308) to follow (default 10, maximum 20).v0.0.0-alpha.2
allowPrivateIps optionalbooleanAllow connections to private, loopback, link-local, or cloud-metadata IP addresses (default false, SSRF protection active).v0.0.0-alpha.2
userAgent optionalstring | nullCustom User-Agent header value, or null to omit the default vaeljs/<version> header.v0.0.0-alpha.2
interfaceSince v0.0.0-alpha.2vjs & vjs-lite
export interface FetchResponse {
  readonly status: number;
  readonly statusText: string;
  readonly ok: boolean;
  readonly url: string;
  readonly redirected: boolean;
  readonly headers: Readonly<Record<string, string>>;
  readonly body: Uint8Array;
  header(name: string): string | undefined;
  headerValues(name: string): string[];
  bytes(): Uint8Array;
  text(): string;
  json<T = unknown>(): T;
}

Buffered HTTP response returned by fetch and fetchSync.

Properties
PropertyTypeDescriptionSince
status readonlynumberHTTP status code (for example 200 or 404).v0.0.0-alpha.2
statusText readonlystringHTTP status reason phrase (for example "OK").v0.0.0-alpha.2
ok readonlybooleantrue when status is in the 200..=299 range.v0.0.0-alpha.2
url readonlystringFinal resolved URL after following any redirects (without fragment).v0.0.0-alpha.2
redirected readonlybooleantrue if at least one HTTP redirect hop was followed.v0.0.0-alpha.2
headers readonlyReadonly<Record<string, string>>Lowercased response header map.v0.0.0-alpha.2
body readonlyUint8ArrayBuffered response body bytes (bounded by maxResponseBytes).v0.0.0-alpha.2
Methods
methodSince v0.0.0-alpha.2
header(name: string): string | undefined;

Look up the first header value matching name case-insensitively.

Parameters
NameTypeDescription
namestringHTTP header field name.
Returns
string | undefined — Header value, or undefined if absent.
methodSince v0.0.0-alpha.2
headerValues(name: string): string[];

Return all response header values matching name case-insensitively in emission order (useful for multi-value headers like set-cookie).

Parameters
NameTypeDescription
namestringHTTP header field name.
Returns
string[] — Array of matching header values.
methodSince v0.0.0-alpha.2
bytes(): Uint8Array;

Return a defensive copy of the buffered response body bytes.

Returns
Uint8Array — Freshly copied Uint8Array of the response body.
methodSince v0.0.0-alpha.2
text(): string;

Decode body as strict UTF-8 text.

Returns
string — Decoded UTF-8 response body string.
Exceptions
  • FetchError — with code "VAEL_FETCH_INVALID_UTF8" if body is not valid UTF-8.
methodSince v0.0.0-alpha.2
json<T = unknown>(): T;

Parse body as JSON.

Returns
T — Parsed JSON value.
Exceptions
  • FetchError — with code "VAEL_FETCH_INVALID_JSON" if body is not valid JSON.
interfaceSince v0.0.0-alpha.2vjs & vjs-lite
export interface DownloadProgress {
  readonly bytesWritten: number;
  readonly totalBytes: number | null;
}

Incremental streaming download progress snapshot passed to DownloadOptions.onProgress.

Properties
PropertyTypeDescriptionSince
bytesWritten readonlynumberTotal bytes written to the staging temporary file so far.v0.0.0-alpha.2
totalBytes readonlynumber | nullDeclared Content-Length byte count from the server, or null if absent.v0.0.0-alpha.2
interfaceSince v0.0.0-alpha.2vjs & vjs-lite
export interface DownloadOptions {
  headers?: Record<string, string> | ReadonlyArray<readonly [string, string]>;
  query?: Record<string, string> | ReadonlyArray<readonly [string, string]>;
  bearerToken?: string;
  timeoutMs?: number;
  maxRedirects?: number;
  allowPrivateIps?: boolean;
  userAgent?: string | null;
  maxBytes?: number;
  expectedSha256?: string;
  overwrite?: boolean;
  onProgress?: (progress: DownloadProgress) => void;
}

Options accepted by download and downloadSync.

Properties
PropertyTypeDescriptionSince
headers optionalRecord<string, string> | ReadonlyArray<readonly [string, string]>Additional HTTP request headers as a plain object or [name, value] pairs.v0.0.0-alpha.2
query optionalRecord<string, string> | ReadonlyArray<readonly [string, string]>Query parameters safely URL-encoded and appended to the request URL.v0.0.0-alpha.2
bearerToken optionalstringBearer token sent as Authorization: Bearer <token> when no explicit Authorization header is present. Stripped on cross-origin redirects.v0.0.0-alpha.2
timeoutMs optionalnumberOverall download deadline in milliseconds across redirects and disk streaming (default 30_000, must be > 0 and <= 600_000).v0.0.0-alpha.2
maxRedirects optionalnumberMaximum number of HTTP redirects to follow (default 10, maximum 20).v0.0.0-alpha.2
allowPrivateIps optionalbooleanAllow connections to private, loopback, link-local, or cloud-metadata IP addresses (default false, SSRF protection active).v0.0.0-alpha.2
userAgent optionalstring | nullCustom User-Agent header value, or null to omit the default vaeljs/<version> header.v0.0.0-alpha.2
maxBytes optionalnumberMaximum bytes allowed to be written to disk (default 268_435_456 / 256 MiB, must be > 0 and <= 4_294_967_296 / 4 GiB).v0.0.0-alpha.2
expectedSha256 optionalstringOptional 64-character ASCII hexadecimal SHA-256 digest verified in constant time before committing the downloaded file.v0.0.0-alpha.2
overwrite optionalbooleanAtomically replace destPath if it already exists (default false, which fails with "VAEL_FETCH_ALREADY_EXISTS").v0.0.0-alpha.2
onProgress optional(progress: DownloadProgress) => voidOptional callback invoked after each streamed chunk is written to the staging file.v0.0.0-alpha.2
interfaceSince v0.0.0-alpha.2vjs & vjs-lite
export interface DownloadResult {
  readonly path: string;
  readonly status: number;
  readonly url: string;
  readonly bytesWritten: number;
  readonly sha256: string;
  readonly contentType: string | null;
  readonly etag: string | null;
}

Completion metadata returned by download and downloadSync.

Properties
PropertyTypeDescriptionSince
path readonlystringDestination filesystem path written atomically.v0.0.0-alpha.2
status readonlynumberHTTP status code (200..=299).v0.0.0-alpha.2
url readonlystringFinal resolved URL after following any redirects (without fragment).v0.0.0-alpha.2
bytesWritten readonlynumberTotal number of bytes written to path.v0.0.0-alpha.2
sha256 readonlystringLowercase 64-character hexadecimal SHA-256 digest of the downloaded file.v0.0.0-alpha.2
contentType readonlystring | nullResponse Content-Type header value, or null if absent.v0.0.0-alpha.2
etag readonlystring | nullResponse ETag header value, or null if absent.v0.0.0-alpha.2
typeSince v0.0.0-alpha.2vjs & vjs-lite
export type FetchErrorCode =
  | "VAEL_FETCH_INVALID_URL"
  | "VAEL_FETCH_INVALID_OPTION"
  | "VAEL_FETCH_SSRF_BLOCKED"
  | "VAEL_FETCH_DNS_TIMEOUT"
  | "VAEL_FETCH_TIMEOUT"
  | "VAEL_FETCH_TOO_MANY_REDIRECTS"
  | "VAEL_FETCH_BODY_TOO_LARGE"
  | "VAEL_FETCH_HTTP_STATUS"
  | "VAEL_FETCH_CHECKSUM_MISMATCH"
  | "VAEL_FETCH_ALREADY_EXISTS"
  | "VAEL_FETCH_NETWORK"
  | "VAEL_FETCH_IO"
  | "VAEL_FETCH_INVALID_UTF8"
  | "VAEL_FETCH_INVALID_JSON";

Stable machine-readable VAEL_FETCH_* error codes exposed on FetchError.code.

typeSince v0.0.0-alpha.2vjs & vjs-lite
export type HttpMethod = "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS";

Supported HTTP request methods accepted by FetchOptions.method.