Receiving 2FA codes inline

Operations

The flagship WebSocket use case: an agent fills out a signup form, waits for the verification email, extracts the code, enters it — all in one turn without a public webhook receiver.

The problem

An agent needs to sign up for a third-party service on behalf of its user. The service requires email verification. Three bad options:

  • Use the user's real email — leaks the agent into the user's personal inbox and requires them to hand off the code mid-flow.
  • Use a shared catch-all — multiple signups race each other for the inbox.
  • Spin up a webhook receiver — means you need a public URL for every agent instance, which defeats the point of running agents in ephemeral environments.

The solution

Create a fresh inbox, open a WebSocket subscribed to it, fill the form with the inbox's address, and wait for the message.received event. Extract the code, close the socket, continue.

import WebSocket from "ws";

async function signUpFor3rdParty(siteUrl: string) {
  // 1. Create a one-off inbox for this signup
  const inbox = await fetch("https://myagentmail.com/v1/inboxes", {
    method: "POST",
    headers: {
      "X-API-Key": process.env.MYAGENTMAIL_KEY!,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ username: `signup-${crypto.randomUUID()}` }),
  }).then(r => r.json());

  // 2. Open a WebSocket subscribed to this inbox
  const ws = new WebSocket("wss://myagentmail.com/v1/ws", {
    headers: { "X-API-Key": process.env.MYAGENTMAIL_KEY! },
  });

  const codePromise = new Promise<string>((resolve, reject) => {
    const timer = setTimeout(() => reject(new Error("2FA timeout")), 60_000);
    ws.on("open", () => {
      ws.send(JSON.stringify({
        type: "subscribe",
        event_types: ["message.received"],
        inbox_ids: [inbox.id],
      }));
    });
    ws.on("message", (raw) => {
      const frame = JSON.parse(raw.toString());
      if (frame.type !== "event") return;
      const body = frame.message.plain_body || "";
      const code = body.match(/\b\d{4,8}\b/)?.[0];
      if (code) {
        clearTimeout(timer);
        ws.close();
        resolve(code);
      }
    });
  });

  // 3. Fill the signup form with inbox.email (using your browser automation)
  await fillSignupForm(siteUrl, inbox.email);

  // 4. Wait for the code email
  const code = await codePromise;

  // 5. Enter the code to complete verification
  await submitVerificationCode(siteUrl, code);

  return inbox; // keep the inbox around if you need future mail for this account
}

This pattern works without any public URL. The WebSocket is outbound-only — you can run it from a container, a Lambda, a laptop, anywhere.