---
title: "Sample integration"
description: "A complete integration to read and to copy from: a front desk agent on signed webhooks, an app a person connects through OAuth, and a Python digest, each with its full source."
url: https://doorman.fyi/docs/sample
markdown: https://doorman.fyi/docs/sample.md
area: "SDKs and tools"
section: "Examples"
---

# Sample integration

A complete integration to read and to copy from: a front desk agent on signed webhooks, an app a person connects through OAuth, and a Python digest, each with its full source.

Source: https://doorman.fyi/docs/sample

## What it is

Three small programs that use the API the way an integration does. Each one is complete: it reads its settings from the environment, handles the refusals and failures it can meet, and never writes a credential to its output. The two TypeScript programs import the packages by name and compile with strict settings and Node's own types. The Python one passes a strict type check.

| Program | What it is | What it uses |
| --- | --- | --- |
| `desk.ts` | A front desk for one support address. It answers personal mail and leaves automated mail alone. | [The agent runtime](https://doorman.fyi/docs/agent.md) on a signed webhook, an inbox-scoped key, a durable rule and the stream. |
| `connector.ts` | An app a person connects to their account, with read-only access. | [OAuth](https://doorman.fyi/docs/oauth.md) with S256 PKCE, token rotation and revocation. |
| `digest.py` | A digest of every inbox a key reaches. | [The Python SDK](https://doorman.fyi/docs/python.md): pages, raw mail, attachment text, labels, the stream and the event log. |

The files on this page are the repository's own, character for character. [How it is checked](https://doorman.fyi/docs/sample.md#checked) says what is run against them, and what is not.

> Note: The packages are not on a registry yet, so the sample cannot be installed from one today: [Installing the packages](https://doorman.fyi/docs/sdk.md#install). Until then, read it for the calls, their order and the failure handling.

## The front desk agent

`desk.ts` issues one address, `front-desk@doorman.example`, and answers what arrives there. It is one long-running Node process with a single HTTP route for deliveries.

- It starts listening before it issues the address. The API delivers `inbox.created` to a new webhook at once, so a receiver that starts afterwards misses its first delivery and waits for a retry.
- One call issues the address with its webhook and an inbox-scoped key: [A ready-to-use inbox in one call](https://doorman.fyi/docs/inboxes.md#one-call). The account key is used for setup and for the final report. The agent answers with the inbox key, which reaches that one address and nothing else.
- Started again, it finds the address by its `externalId` instead of issuing a second one: [Your own identifier](https://doorman.fyi/docs/inboxes.md#external-id). The webhook secret and the key were shown once and kept in memory, so it sets the webhook again for a new secret and replaces the key.
- A rule files mail whose subject mentions an invoice under the label `billing`: [Inbound rules](https://doorman.fyi/docs/rules.md). The rule runs in the API, whether the process is up or not.
- `agent.fetch` verifies each delivery's signature over its exact bytes, deduplicates on `event_id` and runs the handler: [Verifying a delivery](https://doorman.fyi/docs/webhooks.md#verify). A delivery nobody signed is answered with `400`.
- Mail that is not auto-replyable (automated mail, bounces, anything suspicious) is marked read and never answered, so two machines cannot write to each other without end: [Categories, verdicts and the auto-replyable flag](https://doorman.fyi/docs/receiving.md#classification).
- The reply's idempotency key is the event id. When the same delivery arrives twice, the agent recognizes it and the handler does not run. When the agent has lost its memory in a restart, the handler runs again and the API answers the send with the reply that already left: [Idempotent retries](https://doorman.fyi/docs/sending.md#idempotency).
- A reply marks the thread read. The desk marks it unread again, because a person still has to follow up. Unread then means one thing: it still needs someone.
- The desk calls no model. `ctx.fencedBody()` is what one would be given: the sender's words fenced as third-party data. An instruction inside a message is content, never a command.
- The stream reports the desk's own replies and every change to a thread as they happen: [The stream](https://doorman.fyi/docs/sdk.md#stream).

src/desk.ts:
```ts
/**
 * A sample integration with the Doorman Inbox API: a front desk for one
 * support address.
 *
 * On start it issues the address with a webhook and a key scoped to it, and
 * files anything that mentions an invoice under a label with a durable rule.
 * Started again, it finds the address it issued and replaces its secrets
 * instead of issuing a second one. It then answers personal mail from the
 * signed webhook, leaves automated mail alone, and watches its own replies
 * and label changes on the stream. When it is asked to stop it prints what
 * the address holds.
 *
 *   DOORMAN_API_URL   the API origin, for example https://api.doorman.example
 *   DOORMAN_API_KEY   an account key (dm_...), used for setup and the final report
 *   DESK_PORT         the port to listen on (default 8788)
 *   DESK_HOST         the interface to listen on (default 127.0.0.1)
 *   DESK_PUBLIC_URL   where the API reaches this process (default http://127.0.0.1:DESK_PORT);
 *                     a deployed API needs an https address it can reach
 *   DESK_MAILBOX      the mailbox name to issue (default front-desk)
 *
 * It writes one JSON object per line and never writes a credential.
 */
import { Buffer } from "node:buffer";
import { createServer } from "node:http";
import type { IncomingMessage, ServerResponse } from "node:http";
import process from "node:process";

import { createInboxAgent } from "@doorman/inbox-agent";
import type { InboxAgent } from "@doorman/inbox-agent";
import { DoormanInbox, isApiError, isHeldSend } from "@doorman/inbox-sdk";
import type { Rule, StreamEvent, StreamSubscription } from "@doorman/inbox-sdk";

const JSON_HEADERS = { "content-type": "application/json; charset=utf-8" };
const MAX_DELIVERY_BYTES = 2 * 1024 * 1024;
/** The desk's own name for its address: how it finds the address again after a restart. */
const EXTERNAL_ID = "front-desk";
const KEY_NAME = "front desk agent";
const RULE_NAME = "File invoices";

function setting(name: string, fallback?: string): string {
  const value = process.env[name]?.trim();
  if (value !== undefined && value !== "") return value;
  if (fallback !== undefined) return fallback;
  throw new Error(`Set ${name} before starting the desk.`);
}

function log(entry: Record<string, unknown>): void {
  process.stdout.write(`${JSON.stringify(entry)}\n`);
}

const baseUrl = setting("DOORMAN_API_URL");
const port = Number(setting("DESK_PORT", "8788"));
if (!Number.isInteger(port) || port < 1 || port > 65_535) throw new Error("DESK_PORT must be a port number.");
const publicUrl = new URL(setting("DESK_PUBLIC_URL", `http://127.0.0.1:${String(port)}`));
const hookUrl = new URL("/hooks/doorman", publicUrl).href;
const counts = { replied: 0, leftAlone: 0 };
const streamed: string[] = [];

interface Desk {
  /** The account key's client: setup and the final report. */
  owner: DoormanInbox;
  /** The inbox key's client: it reads and answers this address and nothing else. */
  client: DoormanInbox;
  inbox: { id: string; address: string };
  rule: Rule;
  agent: InboxAgent;
}

/* The webhook receiver. `agent.fetch` takes a web-standard Request, so Node's request is copied into one. */
async function toRequest(request: IncomingMessage): Promise<Request | null> {
  const chunks: Buffer[] = [];
  let size = 0;
  for await (const chunk of request) {
    const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk as Buffer;
    size += bytes.byteLength;
    // An oversized body is read to its end and dropped, so the refusal still reaches the sender.
    if (size <= MAX_DELIVERY_BYTES) chunks.push(bytes);
  }
  if (size > MAX_DELIVERY_BYTES) return null;
  const headers = new Headers();
  for (const [name, value] of Object.entries(request.headers)) {
    if (typeof value === "string") headers.set(name, value);
    else if (Array.isArray(value)) headers.set(name, value.join(", "));
  }
  const method = request.method ?? "GET";
  // The signature covers the body's bytes exactly as they arrived, so they are passed on untouched.
  return new Request(new URL(request.url ?? "/", publicUrl), {
    method, headers, ...(method === "GET" || method === "HEAD" ? {} : { body: Buffer.concat(chunks) }),
  });
}

async function answer(request: IncomingMessage, response: ServerResponse): Promise<void> {
  if (new URL(request.url ?? "/", publicUrl).pathname !== "/hooks/doorman") {
    response.writeHead(404, JSON_HEADERS);
    response.end(JSON.stringify({ error: "not_found" }));
    return;
  }
  const delivery = await toRequest(request);
  if (delivery === null) {
    response.writeHead(413, JSON_HEADERS);
    response.end(JSON.stringify({ error: "too_large" }));
    return;
  }
  // A delivery that arrives while the desk is still setting up waits for the agent.
  const { agent } = await settingUp;
  // Verifies the Standard Webhooks signature, deduplicates on event_id, then runs the handler.
  const result = await agent.fetch(delivery);
  const body = await result.text();
  const outcome = JSON.parse(body) as { duplicate?: boolean };
  log({ step: "delivery", status: result.status, duplicate: outcome.duplicate === true });
  response.writeHead(result.status, JSON_HEADERS);
  response.end(body);
}

const server = createServer((request, response) => {
  // A handler that throws answers 500, and the API delivers the event again later: deliveries are at least once.
  void answer(request, response).catch((error: unknown) => {
    log({ step: "error", message: error instanceof Error ? error.message : String(error) });
    if (response.writableEnded) return;
    if (!response.headersSent) response.writeHead(500, JSON_HEADERS);
    response.end(JSON.stringify({ error: "internal_error" }));
  });
});

/** The address with its two secrets: issued the first time, found again by `externalId` after that. */
async function provision(owner: DoormanInbox): Promise<{ inbox: { id: string; address: string }; secret: string; token: string }> {
  const existing = await owner.inboxes.findByExternalId(EXTERNAL_ID);
  if (existing === null) {
    const issued = await owner.inboxes.create({
      mailboxName: setting("DESK_MAILBOX", "front-desk"),
      displayName: "Front desk",
      externalId: EXTERNAL_ID,
      metadata: { team: "support", sample: true },
      webhookUrl: hookUrl,
      key: { name: KEY_NAME },
    });
    // Both secrets are shown once, in this answer. A real deployment stores them; the sample keeps them in memory.
    if (issued.webhook === null || issued.key === null) throw new Error("The inbox was issued without its webhook or key.");
    return { inbox: issued, secret: issued.webhook.secret, token: issued.key.token };
  }
  // The secrets of the last run are gone with its memory, so both are replaced: setting the webhook again mints a
  // new signing secret, and the old run's key is revoked in favour of a new one.
  const webhook = await owner.inboxes.webhook.set(existing.id, { url: hookUrl });
  for (const key of (await owner.inboxes.keys.list(existing.id)).data) {
    if (key.name === KEY_NAME) await owner.inboxes.keys.revoke(existing.id, key.id);
  }
  const key = await owner.inboxes.keys.create(existing.id, { name: KEY_NAME });
  return { inbox: existing, secret: webhook.secret, token: key.token };
}

async function setUp(): Promise<Desk> {
  // Listen first: the API delivers `inbox.created` to the new webhook as soon as the address exists.
  await new Promise<void>((resolve, reject) => {
    server.once("error", reject);
    server.listen(port, setting("DESK_HOST", "127.0.0.1"), resolve);
  });

  /* With the account key: the address, its webhook, a key scoped to it, and a rule. */
  const owner = new DoormanInbox({ apiKey: setting("DOORMAN_API_KEY"), baseUrl });
  const { inbox, secret, token } = await provision(owner);
  const rules = await owner.inboxes.rules.list(inbox.id);
  const rule = rules.data.find((entry) => entry.name === RULE_NAME) ?? await owner.inboxes.rules.create(inbox.id, {
    name: RULE_NAME,
    when: { subjectContains: "invoice" },
    then: [{ type: "label", label: "billing" }],
  });

  /* From here on the desk works with the inbox key. */
  const client = new DoormanInbox({ apiKey: token, baseUrl });
  const agent = createInboxAgent({
    client,
    webhookSecret: secret,
    handlers: {
      "message.received": async (ctx) => {
        if (!ctx.isAutoReplyable) {
          // Automated mail, bounces and anything suspicious: never answered, so two machines cannot write to each other forever.
          await ctx.markRead();
          counts.leftAlone += 1;
          log({ step: "left-alone", eventId: ctx.eventId, category: ctx.message.category });
          return;
        }
        const history = await ctx.thread();
        const attachments = await Promise.all(ctx.message.attachments.map(async (attachment) => {
          const read = await ctx.client.attachments.text(ctx.message.id, attachment.filename);
          return { filename: read.filename, extraction: read.extractionMethod, characters: read.text?.length ?? 0 };
        }));
        // What a model would be given: the sender's words fenced as third-party data, never as instructions.
        const fenced = ctx.fencedBody();
        // The idempotency key defaults to the event id. The agent remembers the events it handled, and when that
        // memory is lost (a restart), the API answers the same key with the reply it already sent: `replayed`.
        const reply = await ctx.reply({
          text: [
            `Thank you for writing about "${ctx.message.subject}".`,
            attachments.length === 0 ? "We have your message." : `We have your message and ${String(attachments.length)} attachment(s).`,
            "A person will follow up within one working day.",
          ].join(" "),
        });
        // A reply marks the thread read. A person still has to follow up, so the desk marks it unread again.
        // Where the owner asked to see a key's mail to someone new before it leaves, the reply was not sent: it waits for
        // them in the console, and the desk records that instead of a message it did not send.
        const outcome: Record<string, string> = isHeldSend(reply) ? { waitingForOwner: reply.id } : { replyId: reply.id };
        await ctx.client.threads.update(ctx.threadId, { isRead: false, metadata: { handledBy: "front-desk", ...outcome } });
        counts.replied += 1;
        log({
          step: "replied", eventId: ctx.eventId, threadId: ctx.threadId, messagesInThread: history.data.length,
          attachments, fencedCharacters: fenced.length, replayed: reply.replayed,
          riskLevel: ctx.message.risk?.level ?? null,
        });
      },
      "message.held": (ctx) => {
        log({
          step: "held", eventId: ctx.eventId, messageId: ctx.event.message.id,
          riskLevel: ctx.event.message.risk.level, reasons: ctx.event.message.risk.reasons,
        });
      },
    },
  });
  return { owner, client, inbox, rule, agent };
}

const settingUp = setUp();
const desk = await settingUp.catch((error: unknown) => {
  log({ step: "error", message: error instanceof Error ? error.message : String(error) });
  process.exit(1);
});

/* The stream: the desk's own replies and the rule's label changes, as they happen. */
const subscription: StreamSubscription = { inboxIds: [desk.inbox.id], eventTypes: ["message.sent", "thread.updated", "message.held"] };
const stream = desk.client.stream({
  subscribe: subscription,
  onEvent: (event: StreamEvent) => {
    streamed.push(event.event);
    // The payload is a union: narrow on `event` before reading what only one type carries.
    if (event.event === "message.sent") log({ step: "stream", event: event.event, to: event.message.to, subject: event.message.subject });
    else if (event.event === "thread.updated") log({ step: "stream", event: event.event, threadId: event.thread_id, labels: event.thread.labels });
    else if (event.event === "message.held") log({ step: "stream", event: event.event, messageId: event.message.id, risk: event.message.risk.level });
  },
  onError: (error) => {
    log({ step: "stream-error", message: error.message });
  },
});

/* What the address holds, read back through the API. */
async function report(): Promise<Record<string, unknown>> {
  const { owner, client, inbox, rule } = desk;
  const threads: Record<string, unknown>[] = [];
  // One thread per page, to walk the pagination the iterator hides.
  for await (const thread of client.inboxes.threads.iterate(inbox.id, { limit: 1 })) {
    const { data } = await client.threads.messages(thread.id);
    threads.push({
      subject: thread.subject, labels: thread.labels, isRead: thread.isRead, metadata: thread.metadata,
      riskLevel: thread.riskLevel ?? null,
      messages: data.map((message) => message.direction),
    });
  }
  const billing = await client.inboxes.threads.list(inbox.id, { label: "billing" });
  const events = await client.events.poll(0, { inboxId: inbox.id });
  const runs = await owner.inboxes.rules.runs(inbox.id, rule.id);
  const deliveries = await owner.inboxes.webhook.deliveries(inbox.id);
  // The desk's key reaches one inbox: the API refuses the account's overview with a typed error.
  const scoped = await client.overview().then(() => false, (error: unknown) => isApiError(error, "forbidden"));
  return {
    handled: counts, streamed, threads, billingThreads: billing.total,
    eventTypes: [...new Set(events.data.map((event) => event.type))].sort(), latestSeq: events.latestSeq,
    ruleRuns: runs.data.map((run) => run.status),
    deliveries: deliveries.data.map((delivery) => ({ status: delivery.status, attempts: delivery.attempts })),
    inboxKeyIsScoped: scoped,
  };
}

let stopping = false;
async function stop(): Promise<void> {
  if (stopping) return;
  stopping = true;
  server.close();
  server.closeAllConnections();
  try {
    log({ step: "report", ...(await report()) });
  } catch (error) {
    log({ step: "error", message: error instanceof Error ? error.message : String(error) });
    process.exitCode = 1;
  }
  stream.close();
}
process.on("SIGTERM", () => { void stop(); });
process.on("SIGINT", () => { void stop(); });

// Resolves once the socket is open and the subscription is in force.
await stream.subscribe(subscription);
log({ step: "ready", address: desk.inbox.address, inboxId: desk.inbox.id, ruleId: desk.rule.id, webhook: hookUrl });
```

- `DOORMAN_API_URL`: The API origin, `https://api.doorman.fyi`.
- `DOORMAN_API_KEY`: An account key, used for setup and the final report: [Where keys come from](https://doorman.fyi/docs/authentication.md#minting).
- `DESK_PUBLIC_URL`: Where the API reaches the process. A deployed API needs an https address it can reach. The default is the loopback address the desk listens on, which suits an API on the same machine.
- `DESK_PORT`, `DESK_HOST`: Where it listens: port 8788 on 127.0.0.1 unless set.
- `DESK_MAILBOX`: The mailbox name to issue, `front-desk` unless set.

It writes one line per step. This is the start of a run, and one message from a person with one attachment. The identifiers are examples.

Output:
```json
{"step":"delivery","status":200,"duplicate":false}
{"step":"ready","address":"front-desk@doorman.example","inboxId":"inb_01jc4q7w9k2m5n8p3r6t1v4x7z","ruleId":"rul_01jc5f1a2b3c4d5e6f7g8h9j0k","webhook":"https://desk.example.net/hooks/doorman"}
{"step":"stream","event":"thread.updated","threadId":"thr_01jc5a1b2c3d4e5f6g7h8j9k0m","labels":["billing"]}
{"step":"stream","event":"thread.updated","threadId":"thr_01jc5a1b2c3d4e5f6g7h8j9k0m","labels":["billing"]}
{"step":"stream","event":"message.sent","to":["dana@customer.example"],"subject":"Re: Question about invoice 2847"}
{"step":"stream","event":"thread.updated","threadId":"thr_01jc5a1b2c3d4e5f6g7h8j9k0m","labels":["billing"]}
{"step":"replied","eventId":"evt_01jc5e5f6g7h8j9k0m1n2p3q4r","threadId":"thr_01jc5a1b2c3d4e5f6g7h8j9k0m","messagesInThread":1,"attachments":[{"filename":"order.txt","extraction":"text","characters":30}],"fencedCharacters":541,"replayed":false}
{"step":"delivery","status":200,"duplicate":false}
```

- The first `delivery` is `inbox.created`, which arrives while the desk is still setting up and waits for the agent.
- The three `thread.updated` lines are the rule's label, the reply marking the thread read, and the desk marking it unread again.
- The last `delivery` is the message itself, answered once its handler has finished. An inbox webhook receives every event of its inbox, so four more follow for the three changes and the reply. The desk has no handler for those and answers `200`.

Asked to stop, it prints a report read back through the API: the threads with their labels and read state, the event types in the log, the rule's runs, the webhook's delivery log, and whether its own key was refused the account's overview, which shows the key is scoped to the one inbox.

## The app a person connects

`connector.ts` reads a person's inboxes on their behalf. It never holds an API key. The person allows it in the console and can take the access back there.

- It asks for three read-only permissions, `account:read`, `inboxes:read`, `mail:read`, the least it needs: [Permissions and account boundaries](https://doorman.fyi/docs/oauth.md#scopes).
- `/connect` makes a new verifier and state for each attempt with `createPkce`. The verifier stays on the server. The challenge and the state travel in the address: [Authorize with S256 PKCE](https://doorman.fyi/docs/oauth.md#authorize). The state also goes to the browser in a cookie, so a callback started in another browser is refused.
- `/oauth/callback` checks the callback address, the state and the issuer with `parseOAuthCallback` before it reads the code, then exchanges the code once. A refusal by the person arrives as `access_denied`, and nothing is connected.
- The access token goes where an API key would. Every call is checked against the permissions the person allowed.
- A refresh token is single use. The renewal is tried once, when less than a minute of the access token is left. When the API refuses it, or the answer is lost on the way, the token is not sent again and the person connects again. Only an answer that asks the app to wait leaves the pair in place: [Refresh and revocation](https://doorman.fyi/docs/oauth.md#tokens).
- A `401` on a read means the access was taken back or ran out. The app forgets the grant and says so.
- One grant is kept, in memory. A real app keeps one per user, encrypted at rest.

src/connector.ts:
```ts
/**
 * A sample third-party app for the Doorman Inbox API. It asks a person for
 * read-only access to their inboxes through OAuth (authorization code with
 * S256 PKCE), then reads on their behalf with a short-lived access token.
 * It never holds an API key, and the person can take the access back.
 *
 *   DOORMAN_API_URL                the API origin, for example https://api.doorman.example
 *   CONNECTOR_CLIENT_ID            the app's client id, from Apps in the console (a public client)
 *   CONNECTOR_PORT                 the port to listen on (default 8789)
 *   CONNECTOR_HOST                 the interface to listen on (default 127.0.0.1)
 *   CONNECTOR_PUBLIC_URL           where the person's browser reaches this process
 *                                  (default http://127.0.0.1:CONNECTOR_PORT); its /oauth/callback
 *                                  must be one of the app's registered callback URLs
 *   CONNECTOR_SYNC_SECONDS         how often to read on the person's behalf (default 60)
 *   CONNECTOR_REFRESH_EVERY_SYNC   set to 1 to rotate the token pair on every sync, for a demonstration
 *
 * Open /connect in a browser to start. It writes one JSON object per line
 * and never writes a token. One grant is kept, in memory: a real app keeps
 * one per user, encrypted at rest.
 */
import { createServer } from "node:http";
import type { IncomingMessage, ServerResponse } from "node:http";
import process from "node:process";

import { createPkce, DoormanInbox, InboxOAuth, isApiError, OAuthProtocolError, parseOAuthCallback } from "@doorman/inbox-sdk";
import type { OAuthTokens } from "@doorman/inbox-sdk";

/** The least the app needs: who the account is, its inboxes, and reading mail. Nothing that sends or changes. */
const SCOPES = ["account:read", "inboxes:read", "mail:read"];
const STATE_COOKIE = "connector_state";
const ATTEMPT_MS = 10 * 60_000;
const TEXT_HEADERS = { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" };

function setting(name: string, fallback?: string): string {
  const value = process.env[name]?.trim();
  if (value !== undefined && value !== "") return value;
  if (fallback !== undefined) return fallback;
  throw new Error(`Set ${name} before starting the connector.`);
}

function log(entry: Record<string, unknown>): void {
  process.stdout.write(`${JSON.stringify(entry)}\n`);
}

const oauth = new InboxOAuth({ baseUrl: setting("DOORMAN_API_URL") });
// The API's origin is the issuer of its tokens and the resource they are for.
const issuer = oauth.baseUrl;
const clientId = setting("CONNECTOR_CLIENT_ID");
const port = Number(setting("CONNECTOR_PORT", "8789"));
if (!Number.isInteger(port) || port < 1 || port > 65_535) throw new Error("CONNECTOR_PORT must be a port number.");
const publicUrl = new URL(setting("CONNECTOR_PUBLIC_URL", `http://127.0.0.1:${String(port)}`));
const redirectUri = new URL("/oauth/callback", publicUrl).href;
const syncSeconds = Number(setting("CONNECTOR_SYNC_SECONDS", "60"));
if (!Number.isFinite(syncSeconds) || syncSeconds < 1) throw new Error("CONNECTOR_SYNC_SECONDS must be a number of seconds, 1 or more.");
const refreshEverySync = setting("CONNECTOR_REFRESH_EVERY_SYNC", "0") === "1";

interface Grant {
  accessToken: string;
  refreshToken: string;
  expiresAt: number;
}

let grant: Grant | null = null;
/** Sign-in attempts in flight: the PKCE verifier for each state, until its callback or its expiry. */
const attempts = new Map<string, { verifier: string; expiresAt: number }>();

function toGrant(tokens: OAuthTokens): Grant {
  return { accessToken: tokens.access_token, refreshToken: tokens.refresh_token, expiresAt: Date.now() + tokens.expires_in * 1000 };
}

function cookie(request: IncomingMessage, name: string): string | null {
  for (const part of (request.headers.cookie ?? "").split(";")) {
    const [key, ...value] = part.trim().split("=");
    if (key === name) return value.join("=");
  }
  return null;
}

/** Sends the person to the consent screen. Nothing is granted here: only they can allow it, signed in to their account. */
async function connect(response: ServerResponse): Promise<void> {
  for (const [state, attempt] of attempts) if (attempt.expiresAt < Date.now()) attempts.delete(state);
  if (attempts.size >= 100) {
    response.writeHead(503, TEXT_HEADERS);
    response.end("Too many sign-in attempts are in progress. Try again in a few minutes.");
    return;
  }
  const pkce = await createPkce();
  attempts.set(pkce.state, { verifier: pkce.verifier, expiresAt: Date.now() + ATTEMPT_MS });
  const location = oauth.authorizationUrl({
    response_type: "code", client_id: clientId, redirect_uri: redirectUri, resource: issuer,
    scope: SCOPES.join(" "), state: pkce.state, code_challenge: pkce.challenge, code_challenge_method: pkce.method,
  });
  response.writeHead(302, {
    location, "cache-control": "no-store",
    // The state also goes to this browser alone, so a callback started in someone else's browser is refused.
    "set-cookie": `${STATE_COOKIE}=${pkce.state}; Path=/oauth/callback; Max-Age=${String(ATTEMPT_MS / 1000)}; HttpOnly; SameSite=Lax${publicUrl.protocol === "https:" ? "; Secure" : ""}`,
  });
  response.end();
}

/** The person comes back with a code, or with a refusal. */
async function callback(request: IncomingMessage, response: ServerResponse, url: URL): Promise<void> {
  const state = url.searchParams.get("state") ?? "";
  const attempt = attempts.get(state);
  attempts.delete(state);
  if (attempt === undefined || attempt.expiresAt < Date.now() || cookie(request, STATE_COOKIE) !== state) {
    response.writeHead(400, TEXT_HEADERS);
    response.end("This sign-in attempt is not known here. Start again from /connect.");
    return;
  }
  try {
    // Checks the callback address, the state and the issuer before the code is read at all.
    const code = parseOAuthCallback(url.href, { redirectUri, state, issuer });
    // A code is single use: one exchange, never retried.
    const tokens = await oauth.token({
      grant_type: "authorization_code", client_id: clientId, code, redirect_uri: redirectUri,
      resource: issuer, code_verifier: attempt.verifier,
    });
    grant = toGrant(tokens);
    log({ step: "connected", scope: tokens.scope, expiresIn: tokens.expires_in });
    response.writeHead(200, TEXT_HEADERS);
    response.end("Connected. You can close this window.");
    // The first read does not keep the person's browser waiting.
    void sync().catch(failed);
  } catch (error) {
    if (!(error instanceof OAuthProtocolError)) throw error;
    log({ step: "refused", code: error.code });
    response.writeHead(400, TEXT_HEADERS);
    response.end(error.code === "access_denied" ? "Access was not granted. Nothing was connected." : "The sign-in could not be completed. Start again from /connect.");
  }
}

function disconnect(reason: string): void {
  grant = null;
  log({ step: "disconnected", reason });
}

/**
 * Replaces the token pair, once. A refresh token is single use: after an attempt whose outcome is not known for
 * certain it is never sent again, because presenting a spent one revokes everything the grant issued.
 */
async function refresh(current: Grant): Promise<Grant | "wait" | null> {
  try {
    return toGrant(await oauth.token({
      grant_type: "refresh_token", client_id: clientId, refresh_token: current.refreshToken, resource: issuer,
    }));
  } catch (error) {
    // The API asked for patience before it looked at the token: the pair is untouched and still good.
    if (error instanceof OAuthProtocolError && error.code === "temporarily_unavailable") return "wait";
    // Refused (the person took the access back, or the pair is spent), or the answer was lost on the way.
    return null;
  }
}

let syncing = false;
/** Reads on the person's behalf, refreshing the short-lived access token first when it is about to run out. */
async function sync(): Promise<void> {
  if (grant === null || syncing) return;
  syncing = true;
  try {
    let refreshed = false;
    if (refreshEverySync || grant.expiresAt - Date.now() < 60_000) {
      const next = await refresh(grant);
      if (next === null) {
        disconnect("The access could not be renewed: it was taken back, or the renewal's answer was lost. The person can connect again from /connect.");
        return;
      }
      if (next === "wait") {
        log({ step: "waiting", reason: "The API asked to slow down. The next sync tries again." });
        return;
      }
      // The new pair replaces the old one in one step.
      grant = next;
      refreshed = true;
    }
    // The access token goes where an API key would: every call is checked against the scopes the person allowed.
    const client = new DoormanInbox({ apiKey: grant.accessToken, baseUrl: issuer });
    const me = await client.me();
    const inboxes: string[] = [];
    let unreadThreads = 0;
    let recentThreads = 0;
    for await (const inbox of client.inboxes.iterate()) {
      inboxes.push(inbox.id);
      unreadThreads += inbox.unreadThreads;
      recentThreads += (await client.inboxes.threads.list(inbox.id, { limit: 5 })).data.length;
    }
    log({
      step: "synced", account: me.account.id, app: me.oauth?.appId ?? null, scopes: me.oauth?.scopes ?? [],
      inboxes, unreadThreads, recentThreads, refreshed,
    });
  } catch (error) {
    // 401: the access token no longer stands for anything, because the access was taken back or ran out.
    if (!(isApiError(error) && error.status === 401)) throw error;
    disconnect("Access was taken back or ran out. The person can connect again from /connect.");
  } finally {
    syncing = false;
  }
}

async function answer(request: IncomingMessage, response: ServerResponse): Promise<void> {
  const url = new URL(request.url ?? "/", publicUrl);
  if (request.method === "GET" && url.pathname === "/connect") return connect(response);
  if (request.method === "GET" && url.pathname === "/oauth/callback") return callback(request, response, url);
  response.writeHead(404, TEXT_HEADERS);
  response.end("Not found.");
}

function failed(error: unknown): void {
  log({ step: "error", message: error instanceof Error ? error.message : String(error) });
}

const server = createServer((request, response) => {
  void answer(request, response).catch((error: unknown) => {
    failed(error);
    if (response.writableEnded) return;
    if (!response.headersSent) response.writeHead(500, TEXT_HEADERS);
    response.end("Something went wrong.");
  });
});
const timer = setInterval(() => { void sync().catch(failed); }, syncSeconds * 1000);

function stop(): void {
  clearInterval(timer);
  server.close();
  server.closeAllConnections();
}
process.on("SIGTERM", stop);
process.on("SIGINT", stop);

await new Promise<void>((resolve, reject) => {
  server.once("error", reject);
  server.listen(port, setting("CONNECTOR_HOST", "127.0.0.1"), resolve);
}).catch((error: unknown) => {
  failed(error);
  process.exit(1);
});
log({ step: "ready", connect: new URL("/connect", publicUrl).href, callback: redirectUri, scopes: SCOPES });
```

- `DOORMAN_API_URL`: The API origin, `https://api.doorman.fyi`. It is also the issuer of the tokens and the resource they are for.
- `CONNECTOR_CLIENT_ID`: The app's client id from [OAuth clients in the console](https://doorman.fyi/console/apps): a public client that may ask for the three permissions above, with the callback below among its redirects.
- `CONNECTOR_PUBLIC_URL`: Where the person's browser reaches the process, `http://127.0.0.1:8789` unless set. The callback is this address followed by `/oauth/callback`. Plain HTTP is accepted for loopback addresses only: [Register an app](https://doorman.fyi/docs/oauth.md#register).
- `CONNECTOR_PORT`, `CONNECTOR_HOST`: Where it listens: port 8789 on 127.0.0.1 unless set.
- `CONNECTOR_SYNC_SECONDS`: How often it reads, 60 unless set.
- `CONNECTOR_REFRESH_EVERY_SYNC`: Set to `1` to rotate the token pair on every read, to watch rotation happen.

A person connects, the app reads, and the person takes the access back. The identifiers are examples.

Output:
```json
{"step":"ready","connect":"http://127.0.0.1:8789/connect","callback":"http://127.0.0.1:8789/oauth/callback","scopes":["account:read","inboxes:read","mail:read"]}
{"step":"connected","scope":"account:read inboxes:read mail:read","expiresIn":900}
{"step":"synced","account":"acc_01jc4q3x6k9m2n8p4r7t5v1w3y","app":"app_01jc5f1a2b3c4d5e6f7g8h9j0k","scopes":["account:read","inboxes:read","mail:read"],"inboxes":["inb_01jc4q7w9k2m5n8p3r6t1v4x7z"],"unreadThreads":1,"recentThreads":2,"refreshed":false}
{"step":"disconnected","reason":"Access was taken back or ran out. The person can connect again from /connect."}
```

## The Python digest

`digest.py` reads every inbox its key reaches, summarizes each thread, labels the threads it covered and watches that change arrive on the stream. It works with an account key, or with an inbox key for that one inbox.

- `iterate` walks every page of a list. The sample asks for one row per page to show that it does.
- `messages.raw` is the original message, byte for byte. `attachments.text` is what was read out of a file and how: [Attachments and extracted text](https://doorman.fyi/docs/receiving.md#attachments).
- Labels replace the whole list, so the existing ones are sent back with the new one.
- Entering the stream waits for the subscription, so a change made inside the block cannot be missed: [Context-managed event streams](https://doorman.fyi/docs/python.md#stream). An event is a union, so the sample narrows on its type before reading what only that type carries.
- `events.list(after=...)` reads the log forward and answers `latestSeq` for the next call: [Polling forward: after](https://doorman.fyi/docs/events.md#polling). The method is typed as a page or a poll, so the sample tells a type checker which one it asked for.
- A thread that does not exist is an `ApiError` with a status and a code, not text to parse.

python/digest.py:
```python
"""A sample digest for the Doorman Inbox API, written with the Python client.

It reads every inbox the key reaches, summarizes each thread, labels the
threads it covered and watches that change arrive on the event stream.

    DOORMAN_API_URL   the API origin, for example https://api.doorman.example
    DOORMAN_API_KEY   an account key or an inbox key (dm_...)

It prints one JSON object and never prints a credential.
"""

import json
import os
import sys
from typing import TypedDict, cast

from doorman_inbox import ApiError, DoormanInbox, models

LABEL = "digested"


class AttachmentSummary(TypedDict):
    filename: str
    extraction: str


class ThreadSummary(TypedDict, total=False):
    subject: str
    labels: list[str]
    riskLevel: str | None
    messages: list[str]
    attachments: list[AttachmentSummary]
    rawBytes: int


class InboxDigest(TypedDict):
    id: str
    threads: list[ThreadSummary]
    labelled: int


def summarize(client: DoormanInbox, thread: models.Thread) -> ThreadSummary:
    messages = client.threads.messages(thread["id"])["data"]
    inbound = [message for message in messages if message["direction"] == "inbound"]
    entry: ThreadSummary = {
        "subject": thread["subject"],
        "labels": thread["labels"],
        "riskLevel": thread.get("riskLevel"),
        "messages": [message["direction"] for message in messages],
        "attachments": [],
    }
    if inbound:
        newest = inbound[-1]
        # The original message, byte for byte, and what was read out of each attachment.
        entry["rawBytes"] = len(client.messages.raw(newest["id"]))
        for attachment in newest["attachments"]:
            text = client.attachments.text(newest["id"], attachment["filename"])
            entry["attachments"].append(
                {"filename": text["filename"], "extraction": text["extractionMethod"]}
            )
    return entry


def label(client: DoormanInbox, inbox_id: str, threads: list[models.Thread]) -> int:
    """Label the threads the digest covered, and count the changes it then sees on the stream."""
    seen = 0
    # Entering the stream waits for the subscription, so the changes below cannot be missed.
    with client.stream(inbox_ids=[inbox_id], event_types=["thread.updated"], reconnect=False) as stream:
        for thread in threads:
            if LABEL in thread["labels"]:
                continue
            # Labels replace the whole list, so the existing ones are sent back with the new one.
            client.threads.update(thread["id"], {"labels": [*thread["labels"], LABEL]})
            # Other changes to the inbox arrive on the same stream; wait for this one.
            for event in stream:
                # An event is a union: narrow on its type before reading what only that type carries.
                if event["event"] != "thread.updated":
                    continue
                if event["thread_id"] == thread["id"] and LABEL in event["thread"]["labels"]:
                    seen += 1
                    break
    return seen


def main() -> int:
    with DoormanInbox(
        base_url=os.environ["DOORMAN_API_URL"], api_key=os.environ["DOORMAN_API_KEY"]
    ) as client:
        inboxes: list[InboxDigest] = []
        # One row per page, to walk the pagination the iterators hide.
        for inbox in client.inboxes.iterate(limit=1):
            threads = list(client.inboxes.threads.iterate(inbox["id"], limit=1))
            summaries = [summarize(client, thread) for thread in threads]
            inboxes.append(
                {"id": inbox["id"], "threads": summaries, "labelled": label(client, inbox["id"], threads)}
            )
        digest: dict[str, object] = {
            "account": client.me()["account"]["id"],
            "inboxes": inboxes,
            "issuer": client.oauth.metadata()["issuer"],
        }
        # Reading the event log forward: with `after` the answer is a poll, and its latestSeq is the next
        # `after`. `list` is typed as a page or a poll, so a type checker is told which one this call returns.
        poll = cast(models.EventPoll, client.events.list(after="0"))
        digest["eventTypes"] = sorted({event["type"] for event in poll["data"]})
        digest["latestSeq"] = poll["latestSeq"]
        # A thread that does not exist: a typed error, not an exception to parse.
        try:
            client.threads.get("thr_" + "0" * 26)
        except ApiError as error:
            digest["missingThread"] = {"status": error.status, "code": error.code}
    print(json.dumps(digest))
    return 0


if __name__ == "__main__":
    sys.exit(main())
```

It prints one JSON object on one line, indented here for reading. This one covers an inbox with two threads.

Output:
```json
{
  "account": "acc_01jc4q3x6k9m2n8p4r7t5v1w3y",
  "inboxes": [
    {
      "id": "inb_01jc4q7w9k2m5n8p3r6t1v4x7z",
      "threads": [
        {
          "subject": "Quarterly figures",
          "labels": [
            "billing"
          ],
          "messages": [
            "inbound",
            "outbound"
          ],
          "attachments": [
            {
              "filename": "figures.csv",
              "extraction": "csv"
            }
          ],
          "rawBytes": 765
        },
        {
          "subject": "Your code is 123456",
          "labels": [],
          "messages": [
            "inbound"
          ],
          "attachments": [],
          "rawBytes": 274
        }
      ],
      "labelled": 2
    }
  ],
  "issuer": "https://api.doorman.fyi",
  "eventTypes": [
    "inbox.created",
    "message.received",
    "message.sent",
    "thread.updated"
  ],
  "latestSeq": 29,
  "missingThread": {
    "status": 404,
    "code": "not_found"
  }
}
```

## Running it

> Note: These commands install from a registry, which waits for the first release of the packages. Until then the packages are built from the repository: [Installing the packages](https://doorman.fyi/docs/sdk.md#install) and [Installation and wire types](https://doorman.fyi/docs/python.md#install).

The two TypeScript programs need Node 22 or later and an ES module project, because they use top-level `await`. The digest needs Python 3.11 or later.

1. Make an empty project, mark it as an ES module and install the packages and the compiler.
2. Put `desk.ts` and `connector.ts` in `src/`, and the `tsconfig.json` below beside `package.json`.
3. Compile, then start a program with its settings in the environment.

Set up and compile:
```sh
npm init -y
npm pkg set type=module
npm install @doorman/inbox-sdk @doorman/inbox-agent
npm install --save-dev typescript @types/node
npx tsc -p .
```

tsconfig.json:
```json
{
  "$schema": "https://json.schemastore.org/tsconfig",
  "compilerOptions": {
    // What a Node project that installs the packages would use: Node's own
    // types and no browser library. The packages' declaration files are
    // checked too, so a type they need and Node does not have shows up here.
    "target": "es2022",
    "module": "nodenext",
    "moduleResolution": "nodenext",
    "lib": ["es2023"],
    "types": ["node"],
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": false,
    "rootDir": "src",
    "outDir": "dist"
  },
  "include": ["src"]
}
```

The front desk:
```sh
export DOORMAN_API_URL="https://api.doorman.fyi"
export DOORMAN_API_KEY=dm_...

# The API must be able to reach this address.
DESK_PUBLIC_URL="https://desk.example.net" node dist/desk.js
```

The connector:
```sh
export DOORMAN_API_URL="https://api.doorman.fyi"

# The client id of an app whose redirects include http://127.0.0.1:8789/oauth/callback
CONNECTOR_CLIENT_ID=app_... node dist/connector.js

# Then open http://127.0.0.1:8789/connect in a browser and allow or refuse the access.
```

The digest:
```sh
pip install doorman-inbox

export DOORMAN_API_URL="https://api.doorman.fyi"
export DOORMAN_API_KEY=dm_...
python digest.py
```

- The Free plan has room for the desk's inbox, and the desk's replies count toward that plan's 3000 sends a month: [Plans](https://doorman.fyi/docs/limits.md#plans).
- Every plan also caps what an account sends from the shared domain in a UTC day, at 500, and at 20 while the account is younger than 7 days: [Limits](https://doorman.fyi/docs/sending.md#limits).
- A webhook address must be https, so the desk needs a public address or a tunnel to one. Plain HTTP is accepted only by an API in local development. The connector's callback may be plain HTTP on a loopback address, so it runs on a laptop as it is.
- The desk leaves its inbox in place when it stops, so the next start continues with it. The digest adds the label `digested` to every thread its key reaches.

## What to take from it

- Listen before you register a webhook address. The first delivery follows the registration at once.
- Give an agent the narrowest credential that does its work: an inbox key. Keep the account key for provisioning: [Account scope and inbox scope](https://doorman.fyi/docs/authentication.md#scopes).
- Tag what you issue with your own `externalId`, so a restart or a retry finds it instead of issuing it again.
- Treat deliveries as at least once. Deduplicate on `event_id`, and put an idempotency key on every send, so a lost memory cannot send twice.
- Verify every delivery over the bytes exactly as they arrived, and refuse what is not signed.
- Do not answer mail that is not auto-replyable.
- Hand mail to a model fenced as data. Its text comes from a stranger.
- Secrets are shown once. Store them, and keep them out of output and logs. The sample prints identifiers and outcomes, never a key, a token or a signing secret.
- For other people's accounts, use OAuth with the fewest permissions. Send a refresh token once, and expect the access to be taken back.

## How it is checked

The repository checks the packages and this sample together with one command, against the API running on the same machine. No real mail is sent, and every key and token it makes ends with the run.

- It packs the packages and installs them in an empty project outside the repository, as a registry would hand them over.
- It compiles the sample against the installed declarations with strict settings, Node's types and no browser library.
- It runs the desk over HTTP and WebSocket: a person's message with an attachment, an automated message, the same delivery twice, a delivery nobody signed, and a restart.
- It runs the connector through consent, token rotation, a refusal, a replayed callback and a revocation, playing the person in the console.
- It runs the digest from the Python wheel with an account key and with an inbox key, and checks it with a strict type checker.
- It runs the client inside the Workers runtime without Node compatibility: REST calls, OAuth discovery, PKCE and the stream.

What it does not check: delivery of real mail in either direction, browsers, runtimes other than Node and Workers, and installation from a registry.
