TypeScript SDK: the client, errors, stream and helpers

What @doorman/inbox-sdk exports besides the resources of the API: the client and its options, the parameters of lists and sends, pagination, errors, the stream, webhook verification, OAuth and the transport.

On this page
  1. The client
  2. Parameters of lists and sends
  3. Pagination
  4. Errors
  5. The stream
  6. Verifying webhooks
  7. OAuth
  8. The transport

The client

One DoormanInbox holds the credential and the API origin, and every call goes through it. apiKey takes an API key or an app's access token; the client refuses an empty one when it is constructed. baseUrl is always given: the client never assumes a deployment. fetch and WebSocket replace the platform's own, for a test or a runtime that has neither.

TypeScript

import { DoormanInbox } from "@doorman/inbox-sdk";

const client = new DoormanInbox({
  apiKey: process.env.DOORMAN_API_KEY ?? "",
  baseUrl: "https://api.doorman.fyi",
});

The properties below are the resources of the API. Each one's methods are on the page of its tag, listed in the index.

DoormanInbox

The Doorman Inbox API, one method per operation, grouped as the contract's registry ids them: inboxes.create is client.inboxes.create(...).

Class

new DoormanInbox(options: DoormanInboxOptions)

Properties

PropertyTypeDescription
inboxesInboxes
domainsDomains
passportPassport
servicesServices
threadsThreads
messagesMessages
attachmentsAttachments
eventsEvents
webhooksWebhooks
deliveriesDeliveries
apiKeysApiKeys
securitySecurity
senderRulesSenderRules
heldSendsHeldSends
draftsDrafts
appsApps
installsInstalls
oauthRequestsOAuthRequests
signInSignIn
billingBilling
baaBaa
guardrailsGuardrails
pushPush
membersMembers
invitationsInvitations
organizationOrganizationResource
oauthInboxOAuth
transportTransport
baseUrlstringThe API's base URL as the client uses it: no trailing slash.

DoormanInboxOptions

Fields

FieldTypeRequiredDescription
apiKeystringyesA dm_ API key, a REST-resource app access token, or a console session token.
baseUrlstringyesThe API's origin, for example https://api.doorman.example. Required: the client never assumes a deployment.
accountIdstringnoThe account this client is meant for, acc_.... When given, every request names it in the x-doorman-account header, and the API refuses the request with 409 account_mismatch unless the credential acts for that account. It is for a caller that holds credentials for several accounts, so that a credential picked by mistake does nothing. The stream does not carry it.
fetchFetchLikenoThe fetch to send requests with. Defaults to the global one.
WebSocketWebSocketConstructornoThe WebSocket the stream opens connections with. Defaults to the global one.

Parameters of lists and sends

The shapes the list methods and send take. A request body and an answer are the contract's own types, described under Schemas and exported from this package by the same names. A send answers the stored message, or a held send where the security policy keeps it for the owner: isHeldSend(result) tells the two apart. See Sends that wait for the owner.

PageParams

Fields

FieldTypeRequiredDescription
limitnumbernoPage size, 1 to 100. Defaults to 50.
offsetnumbernoRows to skip. Defaults to 0.

CursorParams

Fields

FieldTypeRequiredDescription
limitnumbernoPage size, 1 to 100. Defaults to 50.
cursorstringnoWhere to continue from: the previous page's nextCursor.

ListInboxesParams

Extends PageParams: every field of it is a field here.

Fields

FieldTypeRequiredDescription
qstringnoKeep the inboxes whose address or display name contains this text, case-insensitively.
externalIdstringnoKeep the inbox with exactly this externalId: at most one.

ListThreadsParams

Extends PageParams: every field of it is a field here.

Fields

FieldTypeRequiredDescription
isReadbooleannoOnly read or only unread threads.
labelstringnoOnly threads carrying this exact, case-sensitive label.
qstringnoKeep the threads whose subject or a participant address contains this text, case-insensitively.

ListMessagesParams

Extends PageParams: every field of it is a field here.

Fields

FieldTypeRequiredDescription
direction"inbound" | "outbound"noOnly received or only sent messages.

EventFilters

Fields

FieldTypeRequiredDescription
inboxIdstringnoOnly this inbox.
threadIdstringnoOnly this thread's events, across all stored history within the caller's scope.
typeEventTypenoOnly this event type.

ListEventsParams

Extends CursorParams, EventFilters: every field of it is a field here.

PollEventsParams

Extends EventFilters: every field of it is a field here.

Fields

FieldTypeRequiredDescription
limitnumbernoPage size, 1 to 100. Defaults to 50.

MetricsParams

Fields

FieldTypeRequiredDescription
fromstring | DatenoStart of the range. Defaults to 7 days before to.
tostring | DatenoEnd of the range. Defaults to now.
interval"hour" | "day"noBucket size. Defaults to day.
inboxIdstringnoOnly this inbox; omit for the whole account.

ListApiKeysParams

Fields

FieldTypeRequiredDescription
scope"all"noall adds the inbox-scoped keys; every item then carries inboxAddress.

ListServicesParams

Extends PageParams: every field of it is a field here.

Fields

FieldTypeRequiredDescription
inboxIdstringnoOnly this inbox's services.
statusServiceStatusnoOnly services with this status. Without it, every status but archived.
attentionbooleannoOnly services with (true) or without (false) an active warning.
qstringnoKeep the services whose domain or name contains this text, case-insensitively.

ListVerificationsParams

Fields

FieldTypeRequiredDescription
domainstringnoOnly codes and links from this service's domain, or a host under it.
sincestring | DatenoOnly those that arrived after this instant.
waitSecondsnumbernoWhen none has arrived yet, wait up to this many seconds (0 to 20) for one.

ListSendersParams

Extends PageParams: every field of it is a field here.

Fields

FieldTypeRequiredDescription
standingSenderStandingnoOnly senders with this standing.
qstringnoKeep senders whose address or display name contains this text, case-insensitively.

ListSenderRulesParams

Extends PageParams: every field of it is a field here.

Fields

FieldTypeRequiredDescription
inboxIdstringnoOnly rules scoped to this inbox; omit for every rule of the account.
standing"trusted" | "blocked"noOnly trusted or only blocked rules.
qstringnoKeep rules whose address or domain contains this text.

ListSecurityAuditParams

Extends PageParams: every field of it is a field here.

Fields

FieldTypeRequiredDescription
inboxIdstringnoOnly audit entries concerning this inbox.

ListHeldSendsParams

Extends PageParams: every field of it is a field here.

Fields

FieldTypeRequiredDescription
statusHeldSendStatusnoOnly held sends in this state. Defaults to the ones still waiting.
kindHeldSendKindnoOnly the sends the security policy kept (held) or only drafts (draft). Both when left out.

ListGuardrailRulesParams

Fields

FieldTypeRequiredDescription
inboxIdstringnoOnly the guardrails that apply to this inbox alone.

SendOptions

Fields

FieldTypeRequiredDescription
idempotencyKeystringno1 to 255 printable ASCII characters that make a retry replay the original answer instead of sending twice.

SendMessageInput

A message to send: the contract's SendMessage, with attachment contents as bytes or base64.

Extends Omit<SendMessage, "attachments">: every field of it is a field here.

Fields

FieldTypeRequiredDescription
attachmentsreadonly SendAttachmentInput[]no

SendAttachmentInput

A file to attach: the contract's attachment, with the content as bytes or as base64.

Extends Omit<SendAttachment, "content">: every field of it is a field here.

Fields

FieldTypeRequiredDescription
contentstring | Uint8Array | ArrayBufferyesThe file's bytes, or their base64 encoding.

ReplyInput

Type

type ReplyInput = Omit<SendMessageInput, "threadId">

A reply: everything a send takes except the thread, which is given separately.

SendResult

Type

type SendResult = (SentMessage | HeldSend) & { replayed: boolean }

What a send answers, plus whether the answer was replayed for an Idempotency-Key seen before: the stored outbound message, or, where the security policy asks for the owner's word (sendApproval), a held send. A held send was not sent. Tell the two apart with isHeldSend().

isHeldSend

Function

isHeldSend<T extends SentMessage | HeldSend>(result: T): result is Extract<T, HeldSend>

Whether a send's answer is a held send: the message waits for the owner and was not sent. Do not send it again; read where it stands with client.heldSends.get(result.id).

Pagination

Every list that pages has an iterate method beside it, built on the two functions below. They ask for the next page only when the loop reaches it. An offset walk ends at the first page shorter than its limit, and a cursor walk when nextCursor is null. See Pagination.

iterateOffsetPages

Function

iterateOffsetPages<T>(fetchPage: (offset: number) => Promise<OffsetPage<T>>, start = 0): AsyncGenerator<T, void, undefined>

Every item of an offset-paginated list, page by page, from start. The walk ends at the first page shorter than its applied limit. Items that arrive while walking can shift the pages; a cursor list does not have that problem.

iterateCursorPages

Function

iterateCursorPages<T>(fetchPage: (cursor: string | undefined) => Promise<CursorPage<T>>, start?: string): AsyncGenerator<T, void, undefined>

Every item of a cursor-paginated list, page by page, from start (the first page when absent).

OffsetPage

A page of an offset-paginated list, as inboxes, threads and messages are listed.

Fields

FieldTypeRequiredDescription
dataT[]yes
limitnumberyesThe page size that was applied.
offsetnumberyesThe offset that was applied.

CursorPage

A page of a cursor-paginated list, as events and deliveries are listed.

Fields

FieldTypeRequiredDescription
dataT[]yes
nextCursorstring | nullyesThe cursor of the next page; null on the last one.

Errors

An answer of 400 or more is thrown as an ApiError. The type guards narrow a caught value, and isApiError takes a code to match. See Errors.

ApiError

An answer with a status of 400 or more. code is one of the contract's error codes (ERROR_CODES in @doorman/inbox-api), or unexpected_response when the body was not an error the contract describes.

Class, extends Error

new ApiError(input: ApiErrorInput)

Properties

PropertyTypeDescription
name
operationstringThe operation's id in the contract's registry, for example inboxes.send.
statusnumber
codestring
detailsErrorDetails
retryAfterSecondsnumber | nullSeconds from the Retry-After header, when the answer carried one.
guard"reply" | "recipient" | "content" | nullOn a 403 risk_blocked error: which guard refused (reply, recipient or content), or null otherwise.
isSessionRequiredbooleanTrue when the operation requires a console session because loosening protection is restricted (403 session_required).

ErrorDetails

The fields some error codes add beside error and message; see the contract's Error schema. Anything else the API adds in the future is kept under its own name.

Fields

FieldTypeRequiredDescription
permissionOrgPermissionnopermission_denied: the permission the signed-in member's role in the organization lacks.
scope"inboxes" | "account" | "inbox"noplan_limit_reached: inboxes or account. rate_limit_exceeded on a send: inbox.
planstringnoplan_limit_reached: the account's plan.
limitnumbernoplan_limit_reached and rate_limit_exceeded: the limit that applied.
usednumbernoplan_limit_reached: how much of the allowance is used.
resetsAtstringnoplan_limit_reached (sends) and rate_limit_exceeded: when the count starts again.
providerCodestringnosend_rejected and send_failed: the sending provider's own code.
guard"reply" | "recipient" | "content"norisk_blocked: which guard refused (reply, recipient, or content when an attachment or a link did not pass its check).
reasonsstring[]norisk_blocked with the content guard: the reason codes for what was found.

isApiError

Function

isApiError(value: unknown, code?: string): value is ApiError

Whether value is an ApiError, and with code given, one with that code.

isRiskBlockedError

Function

isRiskBlockedError(value: unknown): value is ApiError

Whether value is a 403 risk_blocked error: a send or a download one of the guards refused.

isSessionRequiredError

Function

isSessionRequiredError(value: unknown): value is ApiError

Whether value is a 403 session_required error indicating the owner must act in the console.

UNEXPECTED_RESPONSE

Constant

UNEXPECTED_RESPONSE = "unexpected_response"

The code the client uses when an answer is not an error the contract describes (a proxy's HTML page, say).

The stream

client.stream(options) returns an InboxStream: the WebSocket of The WebSocket stream with the subscription, the keepalive and the reconnect handled. Events go to onEvent when given, otherwise to the async iterator.

InboxStream

One connection to /v1/ws, kept alive with pings and reopened after an unexpected close, where it subscribes again with the last event it saw so nothing is missed. Events go to onEvent when given, otherwise to the async iterator (for await (const event of stream)); leaving that loop closes the stream.

Class

new InboxStream(url: string, WebSocket: WebSocketConstructor, options: StreamOptions = {})

Properties

PropertyTypeDescription
stateStreamState
lastEventIdstring | nullThe id of the last event received (or asked to replay from): what a reconnect resumes with.

Methods

MethodDescription
subscribe(subscription: StreamSubscription = {}): Promise<StreamSubscribed>Sends a subscribe frame and resolves with the subscription in force; rejects when the server refuses it.
unsubscribe(inboxIds: readonly string[] = []): Promise<StreamUnsubscribed>Stops receiving: everything, or the given inboxes.
close(): voidCloses the socket, stops reconnecting and ends the iterator.
[Symbol.asyncIterator](): AsyncIterator<StreamEvent, undefined, undefined>The events as an async iterator, for for await. Leaving the loop closes the stream.

StreamOptions

Fields

FieldTypeRequiredDescription
subscribeStreamSubscriptionnoSubscribe as soon as the socket opens, and again after every reconnect.
reconnectbooleannoReconnect after an unexpected close, resuming with last_event_id. Defaults to true.
pingIntervalMsnumbernoHow often to send a keepalive ping. Defaults to 45 seconds, inside the window the API asks for.
onEvent(event: StreamEvent) => voidnoReceives every event. Without it, events queue for the async iterator.
onError(error: Error) => voidnoReceives a frame the server could not honour, an unreadable frame, or an exception thrown by onEvent.
onOpen() => voidnoCalled every time the socket opens, the first time and after each reconnect.
onClose(info: StreamCloseInfo) => voidnoCalled every time the socket closes, with whether a reconnect follows.

StreamSubscription

What to receive. Subscriptions accumulate on the server, as they do here.

Fields

FieldTypeRequiredDescription
inboxIdsreadonly string[]noOnly these inboxes (all of them the key's); absent or empty means every inbox the key can see.
eventTypesreadonly EventType[]noOnly these event types; absent or empty means all.
lastEventIdstringnoReplay the events after this one before live events, up to the stream's replay limit.

StreamState

Type

type StreamState = "connecting" | "open" | "closed"

StreamCloseInfo

Fields

FieldTypeRequiredDescription
codenumberyes
reasonstringyes
reconnectingbooleanyesWhether the stream will reconnect on its own.

StreamClosedError

The socket closed while a request was waiting for its answer, or the stream was closed by the caller.

Class, extends Error

new StreamClosedError(code: number, reason: string)

Properties

PropertyTypeDescription
name
codenumber
reasonstring

StreamFrameError

A frame the server could not honour ({ "type": "error" }), or one the client could not read.

Extends Error.

Properties

PropertyTypeDescription
name

WebSocketLike

The part of a WebSocket the stream uses; the platform WebSocket has it.

Fields

FieldTypeRequiredDescription
readyStatenumberyes

Methods

MethodDescription
send(data: string): void
close(code?: number, reason?: string): void
addEventListener(type: "open", listener: () => void): void
addEventListener(type: "message", listener: (event: { data: unknown }) => void): void
addEventListener(type: "close", listener: (event: { code: number; reason: string }) => void): void
addEventListener(type: "error", listener: () => void): void

WebSocketConstructor

Type

type WebSocketConstructor = new (url: string) => WebSocketLike

Verifying webhooks

The check a receiver makes before it trusts a delivery, over the body exactly as it arrived. See Verifying a delivery.

verifyWebhook

Function

verifyWebhook(headers: WebhookHeaders, body: string | Uint8Array | ArrayBuffer, secret: string, options: VerifyWebhookOptions = {}): Promise<WebhookEvent>

Verifies a supported event delivery and returns its discriminated payload. The headers are the request's, the body its bytes or text exactly as received, the secret the one the API returned when the webhook or endpoint was set up (whsec_...). Deliveries are at least once: deduplicate on event_id.

verifyWebhookSignature

Function

verifyWebhookSignature(headers: WebhookHeaders, body: string | Uint8Array | ArrayBuffer, secret: string, options: VerifyWebhookOptions = {}): Promise<string>

Verifies a delivery's Standard Webhooks signature (webhook-id, webhook-timestamp, webhook-signature; HMAC-SHA256 over id.timestamp.body with the decoded secret) and returns the body as text. The body must be the bytes exactly as they arrived, not re-serialized JSON. The comparison runs inside WebCrypto, in constant time.

VerifyWebhookOptions

Fields

FieldTypeRequiredDescription
toleranceSecondsnumbernoHow far from now webhook-timestamp may be, in seconds. Defaults to 300.
nownumbernoThe current time in milliseconds, for tests. Defaults to Date.now().

WebhookHeaders

Type

type WebhookHeaders = | { get(name: string): string | null | undefined } | Readonly<Record<string, string | readonly string[] | undefined>>

Headers as a Headers object, or as the plain record Node's IncomingMessage and most frameworks expose.

WebhookVerificationReason

Type

type WebhookVerificationReason = | "missing_headers" | "invalid_timestamp" | "timestamp_out_of_tolerance" | "invalid_secret" | "invalid_signature" | "invalid_payload"

WebhookVerificationError

Why a delivery was refused. Treat every reason the same way: answer 4xx and do not act on the payload.

Class, extends Error

new WebhookVerificationError(reason: WebhookVerificationReason, message: string)

Properties

PropertyTypeDescription
name
reasonWebhookVerificationReason

OAuth

What an app uses to be approved by a person: discovery, the authorization address, registration and the token exchange. These requests carry no API credential and no cookie. client.oauth is an InboxOAuth for the client's origin. See Apps and OAuth.

InboxOAuth

Public protocol requests never carry API bearer tokens, browser cookies or automatic retries, and never follow a redirect.

Class

new InboxOAuth(options: InboxOAuthOptions)

Properties

PropertyTypeDescription
baseUrlstring

Methods

MethodDescription
metadata(): Promise<OAuthServerMetadata>The authorization server's metadata: where to authorize, exchange a code and register, and what it supports.
resource(): Promise<OAuthResourceMetadata>The protected resource metadata of the REST API: its resource identifier, its authorization server and its scopes.
mcpResource(): Promise<OAuthResourceMetadata>The protected resource metadata of the MCP address, which is a resource of its own: a token for one is refused by the other.
authorizationUrl(input: OAuthAuthorization): stringThe URL to open in the person's browser. Leave scope out to ask for the default agent permissions.
token(input: OAuthTokenRequest): Promise<OAuthTokens>Single-use code exchange or refresh rotation. Never automatically retry an ambiguous result.
register(input: RegisterOAuthClient): Promise<RegisteredOAuthClient>Dynamic client registration: a public client that registers itself and is given a client id.

InboxOAuthOptions

Fields

FieldTypeRequiredDescription
baseUrlstringyesAn explicitly trusted API origin. Discovery never redirects or changes this origin.
fetchFetchLikeno

createPkce

Function

createPkce(): Promise<{ verifier: string; challenge: string; method: "S256"; state: string }>

Store the verifier and state in your session until the callback; never send the verifier in the authorization URL.

parseOAuthCallback

Function

parseOAuthCallback(value: string, expected: { redirectUri: string; state: string; issuer: string }): string

Validate state, issuer and the registered callback before returning a code.

OAuthProtocolError

Class, extends Error

new OAuthProtocolError(status: number, code: string, retryAfterSeconds: number | null = null)

Properties

PropertyTypeDescription
name
statusnumber
codestring
retryAfterSecondsnumber | null

The transport

What every resource sends through: one attempt per call, the credential as a bearer header, and an ApiError for an answer of 400 or more. A program rarely uses it directly. client.transport is the client's own.

Transport

Sends requests with the credential, where the operation takes one, and turns error answers into ApiErrors.

Class

new Transport(options: TransportOptions)

Properties

PropertyTypeDescription
baseUrlstring

Methods

MethodDescription
url(path: string, options: Pick<CallOptions, "params" | "query"> = {}): stringThe absolute URL of a path template with its parameters and query.
streamUrl(path: string): stringThe stream's URL: the same origin over ws(s), with the credential as token.
call(operation: string, method: HttpMethod, path: string, options: CallOptions = {}): Promise<ResponseLike>One request. Answers of 400 and above are thrown as ApiError; anything else is returned as it is.
json<T>(operation: string, method: HttpMethod, path: string, options: CallOptions = {}): Promise<T>An operation that answers JSON: the parsed body.
empty(operation: string, method: HttpMethod, path: string, options: CallOptions = {}): Promise<void>An operation that answers without a body (204).
text(operation: string, method: HttpMethod, path: string, options: CallOptions = {}): Promise<string>An operation that answers text, such as a message's HTML body.
bytes(operation: string, method: HttpMethod, path: string, options: CallOptions = {}): Promise<Uint8Array>An operation that answers bytes, such as a raw message or an attachment.

TransportOptions

Fields

FieldTypeRequiredDescription
apiKeystringyes
baseUrlstringyes
fetchFetchLikeno
accountIdstringnoThe account every request is meant for, named in x-doorman-account; see DoormanInboxOptions.accountId.

CallOptions

Fields

FieldTypeRequiredDescription
paramsRecord<string, string>noValues for the {param} placeholders of the path, encoded for the URL.
queryQuerynoQuery parameters; undefined entries are left out.
bodyunknownnoA JSON body.
headersRecord<string, string>noExtra headers, lowercase names.
acceptstringnoThe Accept header; application/json by default.
authenticatedfalsenofalse for an operation that takes no credential and answers to a secret in its body: the request then carries no Authorization header.

FetchLike

Type

type FetchLike = (url: string, init: RequestInitLike) => Promise<ResponseLike>

The shape of fetch the client needs: the global one, or anything with the same shape (a test harness's dispatcher, a fetch with retries, a recorder).

RequestInitLike

What the client passes to fetch: always a method, headers and at most a string body. The OAuth protocol requests add the last three: a redirect is handed back instead of followed (manual is the one mode every runtime accepts), no cookie is sent, and the answer stays out of any HTTP cache where the runtime takes that option.

Fields

FieldTypeRequiredDescription
methodstringyes
headersRecord<string, string>yes
bodystringno
redirect"manual"no
credentials"omit"no
cache"no-store"no

ResponseLike

What the client reads from an answer. The platform Response has all of it.

Fields

FieldTypeRequiredDescription
statusnumberyes
headers{ get(name: string): string | null }yes

Methods

MethodDescription
text(): Promise<string>
arrayBuffer(): Promise<ArrayBuffer>

Query

Type

type Query = Record<string, QueryValue>

QueryValue

Type

type QueryValue = string | number | boolean | undefined

normalizeBaseUrl

Function

normalizeBaseUrl(value: string): string

The base URL as the client keeps it: an http(s) origin plus an optional path, no trailing slash, no query or fragment.

fillPath

Function

fillPath(template: string, params: Record<string, string> = {}): string

/v1/inboxes/{inboxId} with its placeholders filled and encoded; a missing or empty value is a programming error.

buildQuery

Function

buildQuery(query: Query | undefined): string

A query string from its parameters, with its leading ?, or the empty string when there is none to send. An undefined value is left out.

readJson

Function

readJson<T>(operation: string, response: ResponseLike): Promise<T>

The JSON body of a successful answer; a body that is not JSON is an unexpected_response.

Up Down to move, Enter to open, Esc to close