Skip to content

Node.js API

Generated from the package's public TypeScript declarations. See the Node.js integration guide for examples.

ENGINE_MAJOR

The engine major this package belongs to. A transport whose hello says another, or none, is sent no request.

const ENGINE_MAJOR: number

MAX_REQUEST_BYTES

The most a request can be, in bytes, as the transport reads it: one line of JSON, its newline included, in UTF-8. A longer one would end the transport, and the session in it, so it is refused with a RangeError before it is queued.

const MAX_REQUEST_BYTES: number

ClientOptions

How a client is made. Each option is passed to tls-forge daemon.

Properties

profilestringoptional
The profile to impersonate, by name or as a JSON profile path.
proxystringoptional
An HTTP, HTTPS or SOCKS proxy URL, optionally with credentials. It reaches the transport on its input, never on its command line.
timeoutnumberoptional
The deadline of each request, in milliseconds, counted from the call. Positive and finite, else a RangeError; 45000 when omitted.
binarystringoptional
The path of the transport binary, used as given.
insecurebooleanoptional
Skip upstream certificate verification.
cookieFilestringoptional
A warmed cookie file, as --cookies reads one.
cookieSetstringoptional
A set in that file; one at random when omitted. Needs cookieFile.
onStderr(line: string) => voidoptional
Receives the transport's standard error, a line at a time.
interface ClientOptions

NetworkContext

Actual network metadata; signal null means unavailable, zero is known. generation identifies a network-change epoch and must be a safe integer. Estimates are generated by the profile rather than supplied as headers.

Properties

type'unknown' | 'ethernet' | 'wifi' | '2g' | '3g' | '4g' | '5g' | 'none' | 'bluetooth'
idstring
generationnumber
signalnumber | null
interface NetworkContext
Example
1
2
3
const response = await client.get("https://example.com/", {
  networkContext: { type: "wifi", id: "office", generation: 1, signal: 4 },
});

BrowserContext

What in a browser a request stands for: it goes out as Chrome sends that kind, CORS and all. See GO.md, «Browser contexts».

Properties

kind'navigation' | 'form' | 'fetch' | 'xhr'
What sends the request.
initiatorstringoptional
The URL of the page that sends it. A form, fetch() and an XHR need one; a navigation without one is typed into the address bar.
referrerPolicy'no-referrer' | 'no-referrer-when-downgrade' | 'origin' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url'optional
That page's referrer policy; strict-origin-when-cross-origin when omitted.
mode'cors' | 'no-cors' | 'same-origin'optional
fetch()'s request mode; cors when omitted. Only for fetch().
credentials'same-origin' | 'include' | 'omit'optional
fetch()'s credentials mode; same-origin when omitted. An XHR takes same-origin or include, which is withCredentials.
interface BrowserContext
Example
1
2
3
4
5
6
7
8
const response = await client.get("https://example.com/", {
  browserContext: {
    kind: "fetch",
    initiator: "https://example.com/",
    mode: "cors",
    credentials: "include",
  },
});

RequestOptions

What get and post take besides the URL and the body.

Properties

headersRecord<string, string>optional
The request's own fields: without a browserContext, each where Chrome writes that field, and one Chrome has no place for after user-agent, by the bytes of its name; in one, what the page's script gives.
orderstring[]optional
The order of the headers given, for a profile that lays them out as given; sorted when omitted.
cookiesstring[]optional
name=value pairs put in the jar before the request.
browserContextBrowserContextoptional
The browser context the request is made in. A transport that does not say it applies one rejects the request with Unsupported, unsent.
networkContextNetworkContextoptional
Actual network metadata for this request alone. A transport that does not say it applies it rejects the request with Unsupported, unsent.
interface RequestOptions

Request

A request, as request takes it.

Properties

urlstring
methodstringoptional
GET when omitted.
bodystring | Buffer | Uint8Arrayoptional
Text, or bytes, which travel as base64 and arrive intact.
interface Request extends RequestOptions

Response

What came back: exactly these fields, in this order.

Properties

statusnumber
The HTTP status code. A non-2xx answer still resolves.
urlstring
The final URL, after redirects.
bodystring
The body as text; bytes that are not valid UTF-8 appear as U+FFFD.
contentBuffer
The body as bytes, exactly as they arrived.
headersRecord<string, string[]>
Lower-cased names, each with its values in wire order.
cookiesstring[]
The name=value pairs the jar holds for the final URL.
interface Response
Example
const response = await client.get("https://example.com/");
console.log(response.status, response.content.length, response.cookies);
Response
200 577 []

Hello

What a transport is, as it answers hello.

Properties

engine_majornumberoptional
The engine major it was built as; none from one older than engine majors.
versionstringoptional
Its version; none from one older than engine majors.
protocolnumber
The protocol it speaks: 1 for one older than the question.
capabilitiesstring[]
What it can do that a client has to ask about, such as browser_context.
interface Hello

Client

One browser identity: one transport process, one fingerprint, one cookie jar, one request at a time.

class Client
Example
1
2
3
4
5
6
import { Client } from "tls-forge";

const client = new Client({ profile: "chrome", timeout: 45000 });
const response = await client.get("https://example.com/");
console.log(response.status);
client.close();
Response
200

new Client()

A client, and no transport yet: the first request starts one.

Throws

no transport binary was found
RangeError
a timeout that is not positive and finite
TypeError
an onStderr that is not a function, or a cookieSet without a cookieFile
new Client(options?: ClientOptions)

Client.get()

GET a URL.

client.get(url: string, options?: RequestOptions): Promise<Response>
Example
1
2
3
const response = await client.get("https://example.com/");
console.log(response.status, response.url);
console.log(response.headers["content-type"]);
Response
200 https://example.com/
[ 'text/html; charset=utf-8' ]

Client.post()

POST a body, in the browserContext of the form or script that posts it: a request without one is a navigation typed into the address bar, which posts nothing, and is refused. A Buffer or Uint8Array is sent as base64, so a body that is not text arrives intact.

client.post(
  url: string,
  body: string | Buffer | Uint8Array,
  options?: RequestOptions,
): Promise<Response>
Example
1
2
3
4
5
6
7
8
9
const response = await client.post(
  "https://httpbin.org/post",
  '{"hello":"world"}',
  {
    headers: { "content-type": "application/json" },
    browserContext: { kind: "fetch", initiator: "https://httpbin.org/" },
  },
);
console.log(response.body);
Response
{
  "args": {},
  "headers": {
    …
    "Sec-Fetch-Dest": "empty",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "same-origin",
    …
  },
  "method": "POST",
  …
  "json": {
    "hello": "world"
  }
}

Client.request()

Make a request. One with a browserContext or a networkContext is sent only to a transport that says, when asked with hello(), that it applies one, and to no other: it is refused with Unsupported rather than sent as though it had none. The first such request waits for that answer, and a request made after it may go first.

client.request(request: Request): Promise<Response>
Example
1
2
3
4
5
6
7
8
9
const response = await client.request({
  url: "https://httpbin.org/anything",
  method: "PUT",
  body: '{"id": 1}',
  headers: { "content-type": "application/json" },
  browserContext: { kind: "fetch", initiator: "https://httpbin.org/" },
});
const data = JSON.parse(response.body);
console.log(response.status, data.method, data.json);
Response
200 PUT { id: 1 }

Client.hello()

What the transport is: the protocol it speaks and what it can do, asked without a connection and once. One older than the question speaks protocol 1, and can do nothing a client has to ask about.

client.hello(): Promise<Hello>
Example
1
2
3
const hello = await client.hello();
console.log(hello.protocol, hello.engine_major, hello.version);
console.log(hello.capabilities.includes("browser_context"));
Response
3 1 1.0.1
true

Client.close()

Stop the transport, and reject what waits. Final.

client.close(): void
Example
1
2
3
4
5
6
const client = new Client({ profile: "chrome" });
try {
  const response = await client.get("https://example.com/");
} finally {
  client.close();
}

resolveBinary()

The transport binary: the one given, TLSFORGE_BIN, the platform package, a local build, or the one on PATH, in that order.

Throws

none of them is there, or the one given or named by TLSFORGE_BIN is not a file
resolveBinary(explicit?: string): string
Example
1
2
3
import { resolveBinary } from "tls-forge";

console.log(resolveBinary());
Response
…/node_modules/tls-forge-darwin-arm64/bin/tls-forge

TLSForgeError

The base of every error this package throws or rejects with.

class TLSForgeError extends Error

new TLSForgeError()

new TLSForgeError(message?: string, options?: { cause?: unknown })

BinaryNotFound

No transport binary was found, or the one named is not there: an install problem, which no retry mends.

class BinaryNotFound extends TLSForgeError

TransportError

The transport failed: it would not start, would not take its arguments or its proxy, died, could not be written to, was closed, or answered with something that is not an answer. The request did not happen, or happened and its answer was lost. The client stays usable: the next request starts a fresh transport.

class TransportError extends TLSForgeError

SessionReset

A request that was not sent because the transport the client's session was in has gone: its cookies, TLS sessions and connections went with it. Every request waiting when that happens is rejected with this, and the next one made is when none was waiting; requests after that start a new session in a new transport. The client never promises the identity it had before.

class SessionReset extends TransportError

RequestFailed

The transport made the request, and the request failed: a refused connection, a DNS failure, a TLS error, a proxy that would not tunnel, or a request the transport would not make as it was asked. Nothing is wrong locally, and trying again can make sense.

class RequestFailed extends TLSForgeError
Example
1
2
3
4
5
6
7
import { RequestFailed } from "tls-forge";

try {
  await client.request({ url: "https://example.com/", method: "DELETE" });
} catch (error) {
  if (error instanceof RequestFailed) console.log(error.message);
}
Response
tlsforge: DELETE https://example.com/ needs a browser context: without one it goes as a navigation typed into the address bar, a GET with no body; say the form, fetch() or XHR that sends it, and from which page

Unsupported

A request this client's transport cannot make as asked: it does not do what the request needs, as it says when asked with hello(), or it is older than the question. The request was not sent.

class Unsupported extends TLSForgeError

Timeout

The deadline passed with no answer.

The package's default export is Client.

class Timeout extends TLSForgeError