Skip to content

@caido/sdk-backend

This is the reference for the backend SDK used by backend plugins. SDK is the main interface that provides access to various services and functionalities.

SDK

SDK<API, Events>

The SDK object available to all scripts.

Type Parameters

Type ParameterDefault type
APIobject
Eventsobject

Properties

api

api: APISDK<API, Events>

The SDK for the API RPC service.

console

console: Console

The console.

This is currently the same as the global console.

events

events: EventsSDK<API, Events>

The SDK for the Events service.

findings

findings: FindingsSDK

The SDK for the Findings service.

meta

meta: MetaSDK

The SDK for metadata information about the plugin.

projects

projects: ProjectsSDK

The SDK for the Projects service.

replay

replay: ReplaySDK

The SDK for the Replay service.

requests

requests: RequestsSDK

The SDK for the Requests service.

Meta

MetaSDK

MetaSDK: object

The SDK for metadata information about the plugin.

Type declaration

db()

Get a sqlite database for the plugin stored in Caido Data. You can use this to store data related to your plugin.

Returns

Promise<Database>

path()

The directory of the plugin in Caido Data. You can store data related to your plugin in this directory.

Returns

string

API

APISDK<API, Events>

APISDK<API, Events>: object

The SDK for the API RPC service.

Type Parameters

Type ParameterDefault type
APIobject
Eventsobject

Type declaration

register()

Registers a new backend function for the RPC.

Parameters
ParameterType
namekeyof API
callback(sdk: SDK<object, object>, ...args: any[]) => any
Returns

void

Example
ts
sdk.api.register("multiply", (sdk: SDK, a: number, b: number) => {
   return a * b;
});
send()

Sends an event to the frontend plugin.

Parameters
ParameterType
eventkeyof Events
...argsany[]
Returns

void

Example
ts
sdk.api.send("myEvent", 5, "hello");

Events

EventsSDK<API, Events>

EventsSDK<API, Events>: object

The SDK for the API RPC service.

Type Parameters

Type ParameterDefault type
APIobject
Eventsobject

Type declaration

onInterceptRequest()

Registers an callback on new intercepted requests.

This callback is called asynchronously and cannot modify requests.

Parameters
ParameterType
callback(sdk: SDK<API, Events>, request: Request) => MaybePromise<void>
Returns

void

Example
ts
sdk.events.onInterceptRequest((sdk, request) => {
   // Do something with the request
});
onInterceptResponse()

Registers an callback on new intercepted responses.

This callback is called asynchronously and cannot modify responses.

Parameters
ParameterType
callback(sdk: SDK<API, Events>, request: Request, response: Response) => MaybePromise<void>
Returns

void

Example
ts
sdk.events.onInterceptResponse((sdk, request, response) => {
   // Do something with the request/response
});

Requests

Body

The body of a Request or Response.

Calling to<FORMAT> will try to convert the body to the desired format.

Constructors

new Body()

new Body(data: string | number[] | Uint8Array): Body

Parameters
ParameterType
datastring | number[] | Uint8Array
Returns

Body

Methods

toJson()

toJson(): any

Try to parse the body as JSON.

Returns

any

Throws

If the body is not valid JSON.

toRaw()

toRaw(): Uint8Array

Get the raw body as an array of bytes.

Returns

Uint8Array

toText()

toText(): string

Parse the body as a string.

Unprintable characters will be replaced with .

Returns

string


RequestSpec

A mutable Request that has not yet been sent.

Constructors

new RequestSpec()

new RequestSpec(url: string): RequestSpec

Build a new RequestSpec from a URL string. Only the host, port and scheme will be parsed.

You can convert a saved immutable Request object into a RequestSpec object by using the toSpec() method.

By default:

  • Method is GET.
  • Path is /.
Parameters
ParameterType
urlstring
Returns

RequestSpec

Throws

If the URL is invalid.

Example
js
const spec = new RequestSpec("https://example.com");

Methods

getBody()

getBody(): undefined | Body

The body of the request.

Returns

undefined | Body

getHeader()

getHeader(name: string): undefined | string[]

Get a header value.

Header name is case-insensitive. The header might have multiple values.

Parameters
ParameterType
namestring
Returns

undefined | string[]

getHeaders()

getHeaders(): Record<string, string[]>

The headers of the request.

Header names are case-insensitive. Each header might have multiple values.

Returns

Record<string, string[]>

Example
json
{
  "Host": ["caido.io"],
  "Connection": ["keep-alive"],
  "Content-Length": ["95"]
}
getHost()

getHost(): string

Get the host of the request.

Returns

string

getMethod()

getMethod(): string

Get the HTTP method of the request.

Returns

string

getPath()

getPath(): string

Get the path of the request.

Returns

string

getPort()

getPort(): number

Get the port of the request.

Returns

number

getQuery()

getQuery(): string

Get the unparsed query of the request.

Excludes the leading ?.

Returns

string

getRaw()

getRaw(): RequestSpecRaw

This methods converts the RequestSpec to a RequestSpecRaw.

This is useful to retrieve the raw bytes of the request.

Returns

RequestSpecRaw

Example
js
const spec = new RequestSpec("https://example.com");
const specRaw = spec.getRaw();
const bytes = specRaw.getRaw(); // GET / HTTP/1.1\r\nHost: example.com\r\n\r\n
getTls()

getTls(): boolean

Get if the request uses TLS (HTTPS).

Returns

boolean

removeHeader()

removeHeader(name: string): void

Removes a header.

Parameters
ParameterType
namestring
Returns

void

setBody()

setBody(body: Body | Bytes, options?: SetBodyOptions): void

Set the body of the request.

The body can either be a Body or any type that can be converted to Bytes.

Parameters
ParameterType
bodyBody | Bytes
options?SetBodyOptions
Returns

void

Example
js
const body = new Body("Hello world.");
const options = { updateContentLength: true };
request.setBody(body, options);
setHeader()

setHeader(name: string, value: string): void

Set a header value.

This will overwrite any existing values.

Parameters
ParameterType
namestring
valuestring
Returns

void

setHost()

setHost(host: string): void

Set the host of the request.

It will also update the Host header.

Parameters
ParameterType
hoststring
Returns

void

setMethod()

setMethod(method: string): void

Set the HTTP method of the request.

All strings are accepted.

Parameters
ParameterType
methodstring
Returns

void

setPath()

setPath(path: string): void

Set the path of the request.

Parameters
ParameterType
pathstring
Returns

void

setPort()

setPort(port: number): void

Set the port of the request.

The port number must be between 1 and 65535.

Parameters
ParameterType
portnumber
Returns

void

setQuery()

setQuery(query: string): void

Set the unparsed query of the request.

The query string should not include the leading ?.

Parameters
ParameterType
querystring
Returns

void

Example
js
spec.setQuery("q=hello");
setRaw()

setRaw(raw: Bytes): RequestSpecRaw

This method sets the raw Bytes of the request and converts it to a RequestSpecRaw.

This is useful when you have a prepared RequestSpec and you just want to modify the raw data.

Parameters
ParameterType
rawBytes
Returns

RequestSpecRaw

Example
js
const rawBytes = []; // RAW BYTES HERE
const request = new RequestSpec("https://example.com");
const rawRequest = request.setRaw(rawBytes);
setTls()

setTls(tls: boolean): void

Set if the request uses TLS (HTTPS).

Parameters
ParameterType
tlsboolean
Returns

void

parse()

static parse(bytes: Bytes): RequestSpec

Parses raw bytes into a RequestSpec.

Parameters
ParameterType
bytesBytes
Returns

RequestSpec

Throws

If the bytes are not a valid HTTP request.

Example
js
const rawInput = 'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n';
const spec = RequestSpec.parse(rawInput);
spec.setHeader('x-caido', 'test');
const specRaw = spec.getRaw();
const rawOutput = specRaw.getRaw(); // Will contain the new header

RequestSpecRaw

A mutable raw Request that has not yet been sent.

Constructors

new RequestSpecRaw()

new RequestSpecRaw(url: string): RequestSpecRaw

Build a new RequestSpecRaw from a URL string. Only the host, port and scheme will be parsed.

You can convert a saved immutable Request object into a RequestSpecRaw object by using the toSpecRaw() method.

You MUST use setRaw to set the raw bytes of the request.

Parameters
ParameterType
urlstring
Returns

RequestSpecRaw

Example
js
const spec = new RequestSpecRaw("https://example.com");

Methods

getHost()

getHost(): string

Get the host of the request.

Returns

string

getPort()

getPort(): number

Get the port of the request.

Returns

number

getRaw()

getRaw(): Uint8Array

Get the raw bytes of the request.

Returns

Uint8Array

getTls()

getTls(): boolean

Get if the request uses TLS (HTTPS).

Returns

boolean

setHost()

setHost(host: string): void

Set the host of the request.

It will NOT update the Host header.

Parameters
ParameterType
hoststring
Returns

void

setPort()

setPort(port: number): void

Set the port of the request.

The port number must be between 1 and 65535.

Parameters
ParameterType
portnumber
Returns

void

setRaw()

setRaw(raw: Bytes): void

Set the raw Bytes of the request.

Parameters
ParameterType
rawBytes
Returns

void

setTls()

setTls(tls: boolean): void

Set if the request uses TLS (HTTPS).

Parameters
ParameterType
tlsboolean
Returns

void


Request

Request: object

An immutable saved Request.

To modify, use toSpec to get a RequestSpec object.

Type declaration

getBody()

The body of the request.

Returns

undefined | Body

getCreatedAt()

The datetime the request was recorded by the proxy.

Returns

Date

getHeader()

Get a header value.

Header name is case-insensitive. The header might have multiple values.

Parameters
ParameterType
namestring
Returns

undefined | string[]

getHeaders()

The headers of the request.

Header names are case-insensitive. Each header might have multiple values.

Returns

Record<string, string[]>

Example
json
{
  "Host": ["caido.io"],
  "Connection": ["keep-alive"],
  "Content-Length": ["95"]
}
getHost()

The target host of the request.

Returns

string

getId()

The unique Caido ID of the request.

Returns

ID

getMethod()

The HTTP method of the request.

Returns

string

getPath()

The path of the request.

Returns

string

getPort()

The target port of the request.

Returns

number

getQuery()

The unparsed query of the request.

Excludes the leading ?.

Returns

string

getRaw()

The raw version of the request.

Used to access the bytes directly.

Returns

RequestRaw

getTls()

If the request uses TLS (HTTPS).

Returns

boolean

getUrl()

The full URL of the request.

Returns

string

toSpec()

Copied the request to a mutable un-saved RequestSpec. This enables you to make modify a request before re-sending it.

Returns

RequestSpec

toSpecRaw()

Copied the request to a mutable un-saved RequestSpecRaw. The raw requests are not parsed and can be used to send invalid HTTP Requests.

Returns

RequestSpecRaw


RequestOrderField

RequestOrderField: "ext" | "host" | "id" | "method" | "path" | "query" | "created_at" | "source"

Field to order requests by.


RequestRaw

RequestRaw: object

An immutable saved raw Request.

Type declaration

toBytes()

Get the raw request as an array of bytes.

Returns

Uint8Array

toText()

Parse the raw request as a string.

Unprintable characters will be replaced with .

Returns

string


RequestResponse

RequestResponse: object

An immutable saved Request and Response pair.

Type declaration

request

request: Request

response

response: Response


RequestResponseOpt

RequestResponseOpt: object

An immutable saved Request and optional Response pair.

Type declaration

request

request: Request

response?

optional response: Response


RequestsConnection

RequestsConnection: object

A connection of requests.

Type declaration

items

items: RequestsConnectionItem[]

pageInfo

pageInfo: PageInfo


RequestsConnectionItem

RequestsConnectionItem: object

An item in a connection of requests.

Type declaration

cursor

cursor: Cursor

request

request: Request

response?

optional response: Response


RequestsQuery

RequestsQuery: object

Query builder to fetch requests.

Type declaration

after()

Requests after a given cursor.

Parameters
ParameterTypeDescription
cursorCursorCursor of the request
Returns

RequestsQuery

ascending()
ascending(target, field)

Ascending ordering.

Parameters
ParameterTypeDescription
target"req"Target of the ordering: req or resp.
fieldRequestOrderFieldField to order by.
Returns

RequestsQuery

ascending(target, field)
Parameters
ParameterType
target"resp"
fieldResponseOrderField
Returns

RequestsQuery

before()

Requests before a given cursor.

Parameters
ParameterTypeDescription
cursorCursorCursor of the request
Returns

RequestsQuery

descending()
descending(target, field)

Descending ordering.

Parameters
ParameterTypeDescription
target"req"Target of the ordering: req or resp.
fieldRequestOrderFieldField to order by.
Returns

RequestsQuery

descending(target, field)
Parameters
ParameterType
target"resp"
fieldResponseOrderField
Returns

RequestsQuery

execute()

Execute the query.

Returns

Promise<RequestsConnection>

Throws

If a query parameter is invalid or the query cannot be executed.

filter()

Filter requests.

Parameters
ParameterTypeDescription
filterstringHTTPQL filter
Returns

RequestsQuery

first()

First n requests.

Parameters
ParameterTypeDescription
nnumberNumber of requests to return
Returns

RequestsQuery

last()

Last n requests.

Parameters
ParameterTypeDescription
nnumberNumber of requests to return
Returns

RequestsQuery


RequestsSDK

RequestsSDK: object

The SDK for the Requests service.

Type declaration

get()

Get a request by its unique ID.

Parameters
ParameterType
idID
Returns

Promise<undefined | RequestResponseOpt>

Example
js
await sdk.requests.get("1");
inScope()

Checks if a request is in scope.

Parameters
ParameterType
requestRequest | RequestSpec
Returns

boolean

Example
js
if (sdk.requests.inScope(request)) {
 sdk.console.log("In scope");
}
query()

Query requests of the current project.

Returns

RequestsQuery

Example
js
const page = await sqk.requests.query().first(2).execute();
sdk.console.log(`ID: ${page.items[1].request.getId()}`);
send()

Sends an HTTP request, either a RequestSpec or RequestSpecRaw.

This respects the upstream proxy settings.

Parameters
ParameterType
requestRequestSpec | RequestSpecRaw
Returns

Promise<RequestResponse>

Throws

If the request cannot be sent.

Example
js
const spec = new RequestSpec("https://example.com");
try {
  const res = await sdk.requests.send(request)
  sdk.console.log(res.request.getId());
  sdk.console.log(res.response.getCode());
} catch (err) {
  sdk.console.error(err);
}

Response

Response: object

An immutable saved Response.

Type declaration

getBody()

The body of the response

Returns

undefined | Body

getCode()

The status code of the response.

Returns

number

getCreatedAt()

The datetime the response was recorded by the proxy.

Returns

Date

getHeader()

Get a header value.

Header name is case-insensitive. The header might have multiple values.

Parameters
ParameterType
namestring
Returns

undefined | string[]

getHeaders()

The headers of the response.

Header names are case-insensitive. Each header might have multiple values.

Returns

Record<string, string[]>

Example
json
{
  "Date": ["Sun, 26 May 2024 10:59:21 GMT"],
  "Content-Type": ["text/html"]
}
getId()

The unique Caido ID of the response.

Returns

ID

getRaw()

The raw version of the response.

Used to access the bytes directly.

Returns

ResponseRaw

getRoundtripTime()

The time it took to send the request and receive the response in milliseconds.

Returns

number


ResponseOrderField

ResponseOrderField: "length" | "roundtrip" | "code"

Field to order responses by.


ResponseRaw

ResponseRaw: object

An immutable saved raw Response.

Type declaration

toBytes()

Get the raw response as an array of bytes.

Returns

Uint8Array

toText()

Parse the raw response as a string.

Unprintable characters will be replaced with .

Returns

string


SetBodyOptions

SetBodyOptions: object

Options when setting the body of a Request.

Type declaration

updateContentLength

updateContentLength: boolean

Should update the Content-export type header.

Default
ts
true

Findings

Finding

Finding: object

A saved immutable Finding.

Type declaration

getDescription()

The description of the finding.

Returns

undefined | string

getId()

The unique Caido ID of the finding.

Returns

ID

getReporter()

The name of the reporter.

Returns

string

getTitle()

The title of the finding.

Returns

string


FindingSpec

FindingSpec: object

A mutable Finding not yet created.

Type declaration

dedupeKey?

optional dedupeKey: string

Deduplication key for findings. If a finding with the same dedupe key already exists, it will not be created.

description?

optional description: string

The description of the finding.

reporter

reporter: string

The name of the reporter. It will be used to group findings.

request

request: Request

The associated Request.

title

title: string

The title of the finding.


FindingsSDK

FindingsSDK: object

The SDK for the Findings service.

Type declaration

create()

Creates a new Finding.

Parameters
ParameterType
specFindingSpec
Returns

Promise<Finding>

Throws

If the request cannot be saved.

Example
js
await sdk.findings.create({
  title: "Title",
  description: "Description",
  reporter: "Reporter",
  dedupe: `${request.getHost()}-${request.getPath()}`,
  request,
});
get()

Try to get a Finding for a request. Since a request can have multiple findings, this will return the first one found. You can also filter by reporter to get a specific finding.

Parameters
ParameterType
inputGetFindingInput
Returns

Promise<undefined | Finding>

Example
js
await sdk.findings.get({
 reporter: "Reporter",
 request,
});

GetFindingInput

GetFindingInput: object

Input to get a Finding.

Type declaration

reporter?

optional reporter: string

The name of the reporter.

request

request: Request

The associated Request.

Replay

ReplayCollection

ReplayCollection: object

A collection of replay sessions.

Type declaration

getId()

The unique Caido ID of the replay collection.

Returns

ID

getName()

The name of the replay collection.

Returns

string


ReplaySDK

ReplaySDK: object

The SDK for the Replay service.

Type declaration

createSession()
Parameters
ParameterType
source?RequestSource
collection?ID | ReplayCollection
Returns

Promise<ReplaySession>

getCollections()
Returns

Promise<ReplayCollection[]>


ReplaySession

ReplaySession: object

A replay session.

Type declaration

getId()

The unique Caido ID of the replay session.

Returns

ID

getName()

The name of the replay session.

Returns

string

Projects

Project

Project: object

A saved immutable Project.

Type declaration

getId()

The unique Caido ID of the project.

Returns

ID

getName()

The name of the project.

Returns

string

getStatus()

The status of the project.

Returns

ProjectStatus

getVersion()

The version of the project. The format is MAJOR.MINOR.PATCH.

Returns

string


ProjectsSDK

ProjectsSDK: object

The SDK for the Projects service.

Type declaration

getCurrent()

Get the currently selected Project if any.

Returns

Promise<undefined | Project>

Example
js
await sdk.projects.getCurrent();

ProjectStatus

ProjectStatus: "ready" | "restoring" | "error"

A Project status.

Shared

Bytes

Bytes: string | number[] | Uint8Array

Types that can be converted to bytes in inputs.


Cursor

Cursor: string & object

A cursor for pagination.

Type declaration

__cursor?

optional __cursor: never


DefineAPI<API>

DefineAPI<API>: { [K in keyof API]: DefineAPICallback<API[K]> }

Define a Plugin backend functions that are callable from the frontend.

Type Parameters

Type Parameter
API extends Record<string, (...args: any[]) => MaybePromise<any>>

Example

typescript
function generateNumber(sdk: SDK, min: number, max: number): number {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

export type API = DefineAPI<{
  generateNumber: typeof generateNumber;
}>;

export function init(sdk: SDK<API>) {
  sdk.api.register("generateNumber", generateNumber);
}

DefineAPICallback<F>

DefineAPICallback<F>: F extends (sdk: SDK, ...args: infer A) => infer R ? (...args: A) => R : "Your callback must respect the format (sdk: SDK, ...args: unknown[]) => MaybePromise<unknown>"

Parser for Plugin backend callable functions

Type Parameters

Type Parameter
F

DefineEventCallback<F>

DefineEventCallback<F>: F extends (...args: infer A) => MaybePromise<void> ? (...args: A) => MaybePromise<void> : "Your callback must respect the format (...args: unknown[]) => MaybePromise<void>"

Parser for Plugin backend events callbacks.

Type Parameters

Type Parameter
F

DefineEvents<Events>

DefineEvents<Events>: { [K in keyof Events]: DefineEventCallback<Events[K]> }

Define a Plugin backend events that the frontend can receive.

Type Parameters

Type Parameter
Events extends Record<string, (...args: any[]) => MaybePromise<void>>

Example

typescript
type MyEventData = { id: string; name: string };

export type BackendEvents = DefineEvents<{
  "myevent": (data: MyEventData) => void;
}>;

export function init(sdk: SDK<{}, BackendEvents>) {
  sdk.api.send("myevent", { id: "1", name: "hello" });
}

ID

ID: string & object

A unique identifier.

Type declaration

__id?

optional __id: never


MaybePromise<T>

MaybePromise<T>: T | Promise<T>

Promise or value.

Type Parameters

Type Parameter
T

MaybePromise<T>

MaybePromise<T>: T | Promise<T>

Promise or value.

Type Parameters

Type Parameter
T

RequestSource

RequestSource: ID | Request | RequestSpec | RequestSpecRaw

The source of a request.

Other

Database

A SQLite database.

The implementation uses a connection pool and is fully asynchronous. Each connection will be spawned in a worker thread.

Example

ts
const db = await open({ filename: "path/to/database.sqlite" });
await db.exec("CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT);");
await db.exec("INSERT INTO test (name) VALUES ('foo');");

Constructors

new Database()

new Database(): Database

Returns

Database

Methods

exec()

exec(sql: string): Promise<void>

This method allows one or more SQL statements to be executed without returning any results.

Parameters
ParameterType
sqlstring
Returns

Promise<void>

prepare()

prepare(sql: string): Promise<Statement>

Compiles a SQL statement into a prepared statement.

Parameters
ParameterType
sqlstring
Returns

Promise<Statement>


Statement

This class represents a single prepared statement. This class cannot be instantiated via its constructor. Instead, instances are created via the database.prepare() method.

Constructors

new Statement()

new Statement(): Statement

Returns

Statement

Methods

all()

all<T>(...params: Parameter[]): Promise<T[]>

This method executes a prepared statement and returns all results as an array of objects. If the prepared statement does not return any results, this method returns an empty array. The prepared statement parameters are bound using the values in params.

Type Parameters
Type ParameterDefault type
T extends objectobject
Parameters
ParameterTypeDescription
...paramsParameter[]The values to bind to the prepared statement. Named parameters are not supported.
Returns

Promise<T[]>

get()

get<T>(...params: Parameter[]): Promise<undefined | T>

This method executes a prepared statement and returns the first result as an object. If the prepared statement does not return any results, this method returns undefined. The prepared statement parameters are bound using the values in params.

Type Parameters
Type ParameterDefault type
T extends objectobject
Parameters
ParameterTypeDescription
...paramsParameter[]The values to bind to the prepared statement. Named parameters are not supported.
Returns

Promise<undefined | T>

run()

run(...params: Parameter[]): Promise<Result>

This method executes a prepared statement and returns an object summarizing the resulting changes. The prepared statement parameters are bound using the values in params.

Parameters
ParameterTypeDescription
...paramsParameter[]The values to bind to the prepared statement. Named parameters are not supported.
Returns

Promise<Result>


Console

Console: object

Console interface for logging.

Currently logs are only available in the backend logs. See https://docs.caido.io/report_bug.html#1-backend-logs

Type declaration

debug()

Log a message with the debug level.

Usually used for troubleshooting purposes.

Parameters
ParameterType
messageany
Returns

void

error()

Log a message with the error level.

Usually used for critical errors.

Parameters
ParameterType
messageany
Returns

void

log()

Log a message with the info level.

Usually used for general information.

Parameters
ParameterType
messageany
Returns

void

warn()

Log a message with the warn level.

Usually used for unexpected behaviors.

Parameters
ParameterType
messageany
Returns

void


PageInfo

PageInfo: object

Information on the current page of paginated data.

Type declaration

endCursor

endCursor: Cursor

hasNextPage

hasNextPage: boolean

hasPreviousPage

hasPreviousPage: boolean

startCursor

startCursor: Cursor


Parameter

Parameter: null | number | bigint | string | Uint8Array


Result

Result: object

Type declaration

changes

changes: number

lastInsertRowid

lastInsertRowid: number