AliasKit
Docs/Examples

Examples & Use Cases

Practical recipes you can copy into your codebase. Each example shows a complete workflow using persistent identities that your agent creates once and references by ID forever.

One-time identity setup

Create a persistent identity for your agent and store the ID. You only do this once. Every future operation references the identity by its ID.

typescript
import AliasKit from "aliaskit";

const ak = new AliasKit();

// Create the identity once
const identity = await ak.identities.create({
  phone: true,
  metadata: { agent: "booking-assistant", purpose: "service-signups" },
});

console.log(`Identity ID: ${identity.id}`);
console.log(`Email: ${identity.email}`);
console.log(`Phone: ${identity.phone}`);

// Store identity.id in your database or config.
// You will use this ID for all future operations.
// Example: save to your agent's config
// await db.agents.update("booking-assistant", { identityId: identity.id });

Later, retrieve the identity by ID whenever you need it:

typescript
const identity = await ak.identities.get("id_abc123");
console.log(`Email: ${identity.email}`);
console.log(`Phone: ${identity.phone}`);

Service signup with email verification

Use a stored identity ID to sign up for a third-party service and retrieve the verification code from the confirmation email.

typescript
import AliasKit from "aliaskit";

const ak = new AliasKit();

async function signUpForService(identityId: string, signupUrl: string) {
  // 1. Retrieve the persistent identity
  const identity = await ak.identities.get(identityId);

  // 2. POST to the service's signup form
  const res = await fetch(signupUrl, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      email: identity.email,
      name: identity.name,
      password: "AgentPass_2026!",
    }),
  });

  if (!res.ok) {
    throw new Error(`Signup failed with status ${res.status}`);
  }

  // 3. Wait for the confirmation email and extract the OTP
  const code = await ak.emails.waitForCode(identity.id, {
    timeout: 30_000,
  });

  console.log(`Verification code received: ${code}`);

  // 4. Confirm the account
  const confirmRes = await fetch(`${signupUrl}/verify`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email: identity.email, code }),
  });

  if (!confirmRes.ok) {
    throw new Error(`Verification failed with status ${confirmRes.status}`);
  }

  console.log("Account verified successfully.");
}

// Use the stored identity ID from setup
await signUpForService("id_abc123", "https://your-app.com/api/auth/signup");

Multi-channel verification

Some services require both email and phone verification. Use a single identity with both channels and wait for both codes in parallel.

typescript
import AliasKit from "aliaskit";

const ak = new AliasKit();

async function verifyBothChannels(identityId: string) {
  const identity = await ak.identities.get(identityId);

  // Trigger the signup that sends both email and SMS
  await fetch("https://your-app.com/api/auth/signup", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      email: identity.email,
      phone: identity.phone,
      password: "AgentPass_2026!",
    }),
  });

  // Wait for both codes in parallel
  const [emailCode, smsCode] = await Promise.all([
    ak.emails.waitForCode(identity.id, { timeout: 30_000 }),
    ak.sms.waitForCode(identity.id, { timeout: 30_000 }),
  ]);

  console.log(`Email code: ${emailCode}`);
  console.log(`SMS code: ${smsCode}`);

  // Verify both channels
  await fetch("https://your-app.com/api/auth/verify", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      email: identity.email,
      emailCode,
      smsCode,
    }),
  });

  console.log("Both channels verified.");
}

await verifyBothChannels("id_abc123");

TOTP 2FA

Register a TOTP secret from a service's MFA setup, then read codes on demand whenever you need to authenticate.

typescript
import AliasKit from "aliaskit";

const ak = new AliasKit();

async function setupTotp(identityId: string) {
  // Register the TOTP secret (from the service's QR code or setup key)
  const totp = await ak.identities.registerTotp(identityId, {
    secret: "JBSWY3DPEHPK3PXP",
    issuer: "YourApp",
    algorithm: "SHA1",
    digits: 6,
    period: 30,
  });

  console.log(`TOTP registered: ${totp.uri}`);
}

async function loginWithTotp(identityId: string) {
  const identity = await ak.identities.get(identityId);

  // Read the current TOTP code on demand
  const code = await ak.identities.getTotpCode(identityId);
  console.log(`Current TOTP code: ${code.code}`);
  console.log(`Valid for: ${code.remainingSeconds}s`);

  // Use the code to complete MFA verification
  await fetch("https://your-app.com/api/auth/mfa/verify", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      email: identity.email,
      totpCode: code.code,
    }),
  });

  console.log("MFA verification complete.");
}

// One-time setup
await setupTotp("id_abc123");

// Every time your agent needs to log in
await loginWithTotp("id_abc123");

Virtual card for purchases

Set up a virtual card on your identity, then reveal card details when your agent needs to make a purchase.

typescript
import AliasKit from "aliaskit";

const ak = new AliasKit();

// Step 1: Generate a cardholder key (one-time setup)
async function setupCard(identityId: string) {
  const key = await ak.cards.generateKey(identityId);
  console.log(`Cardholder key ID: ${key.id}`);

  // Create a virtual card with a spending limit
  const card = await ak.cards.create(identityId, {
    keyId: key.id,
    label: "SaaS subscriptions",
    spendingLimit: {
      amount: 5000, // $50.00 in cents
      interval: "monthly",
    },
  });

  console.log(`Card created: ${card.id}`);
  console.log(`Last four: ${card.lastFour}`);

  // Store card.id for later use
  return card.id;
}

// Step 2: Reveal card details when making a purchase
async function makePurchase(identityId: string, cardId: string) {
  const details = await ak.cards.reveal(identityId, cardId);

  console.log(`Card number: ${details.number}`);
  console.log(`Expiry: ${details.expMonth}/${details.expYear}`);
  console.log(`CVC: ${details.cvc}`);

  // Use these details to complete a checkout
  await fetch("https://store.example.com/api/checkout", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      cardNumber: details.number,
      expMonth: details.expMonth,
      expYear: details.expYear,
      cvc: details.cvc,
      amount: 1999, // $19.99
    }),
  });

  console.log("Purchase complete.");
}

const cardId = await setupCard("id_abc123");
await makePurchase("id_abc123", cardId);

Realtime event handling

Subscribe to incoming emails and SMS in real time instead of polling. React immediately when messages arrive.

typescript
import AliasKit from "aliaskit";

const ak = new AliasKit();

async function listenForMessages(identityId: string) {
  // Subscribe to all incoming messages for this identity
  const subscription = ak.realtime.subscribe(identityId, {
    events: ["email.received", "sms.received"],
    onEvent: (event) => {
      switch (event.type) {
        case "email.received":
          console.log(`Email from ${event.data.from}: ${event.data.subject}`);
          break;
        case "sms.received":
          console.log(`SMS from ${event.data.from}: ${event.data.body}`);
          break;
      }
    },
    onError: (err) => {
      console.error("Realtime connection error:", err.message);
    },
  });

  // Trigger your signup flow or wait for expected messages...

  // Wait for a specific email using a promise-based helper
  const email = await ak.realtime.waitFor(identityId, "email.received", {
    timeout: 30_000,
    filter: (event) => event.data.subject.includes("Verify"),
  });

  console.log(`Got verification email: ${email.data.subject}`);

  // Clean up the subscription when done
  subscription.unsubscribe();
}

await listenForMessages("id_abc123");

Sending messages

Send email and SMS from your agent's identity.

typescript
import AliasKit from "aliaskit";

const ak = new AliasKit();

async function sendFromIdentity(identityId: string) {
  // Send an email
  const email = await ak.emails.send(identityId, {
    to: "support@example.com",
    subject: "Account inquiry",
    body: "Hi, I need help resetting my password. My account email is on file.",
  });

  console.log(`Email sent: ${email.id}`);

  // Send an SMS
  const sms = await ak.sms.send(identityId, {
    to: "+14155551234",
    body: "Confirming my appointment for tomorrow at 3 PM.",
  });

  console.log(`SMS sent: ${sms.id}`);
}

await sendFromIdentity("id_abc123");

Webhook integration

Register a webhook to receive events at your server. Useful for background processing and CI/CD pipelines.

typescript
import AliasKit from "aliaskit";
import crypto from "node:crypto";

const ak = new AliasKit();

// 1. Create a webhook
const webhook = await ak.webhooks.create({
  url: "https://your-server.com/api/aliaskit/webhook",
  events: ["email.received", "sms.received"],
  secret: "whsec_your_signing_secret",
});

console.log(`Webhook created: ${webhook.id}`);

// 2. Handle incoming webhook events on your server
function handleWebhook(req: Request, signingSecret: string) {
  const signature = req.headers.get("x-aliaskit-signature");
  const timestamp = req.headers.get("x-aliaskit-timestamp");
  const body = req.body;

  // Verify the signature
  const expected = crypto
    .createHmac("sha256", signingSecret)
    .update(`${timestamp}.${body}`)
    .digest("hex");

  if (signature !== expected) {
    throw new Error("Invalid webhook signature");
  }

  const event = JSON.parse(body as string);

  switch (event.type) {
    case "email.received":
      console.log(`Email received for identity ${event.identityId}`);
      break;
    case "sms.received":
      console.log(`SMS received for identity ${event.identityId}`);
      break;
  }
}