AliasKit
Docs/TypeScript SDK

TypeScript SDK {#overview}

The aliaskit package is the official TypeScript SDK for AliasKit. It wraps every API endpoint, extracts verification codes and magic links via realtime WebSocket subscriptions, handles card encryption client-side, and supports live event streaming.

Installation

bash
npm install aliaskit

Constructor

The simplest way to create a client is to set the ALIASKIT_API_KEY environment variable and call the constructor with no arguments:

typescript
import { AliasKit } from "aliaskit";

const ak = new AliasKit();

The SDK reads ALIASKIT_API_KEY from the environment automatically.

For explicit configuration, pass an options object:

typescript
const ak = new AliasKit({
  apiKey: "ak_live_...",
  baseUrl: "https://aliaskit.com",  // optional, defaults to production
  cardKey: "ak_ck_...",             // optional, for virtual card encryption
});

Browser usage: Omit apiKey entirely. The SDK switches to cookie-based auth using credentials: "include", relying on the session cookie from aliaskit.com.

typescript
const ak = new AliasKit(); // in browser, uses session cookie

Quick Start

typescript
import { AliasKit } from "aliaskit";

const ak = new AliasKit();

// Create a persistent identity with a real email inbox
const identity = await ak.identities.create({
  display_name: "Checkout Agent",
  metadata: { team: "payments" },
});

// Use the identity's email to sign up on any service
await yourApp.signup(identity.email);

// Wait for the verification email to arrive
const email = await ak.emails.waitForCode(identity.id);

// The agent reads email.body_text and extracts the code
console.log(email.body_text);

// The identity persists. Reference it by ID in future runs.
const same = await ak.identities.get(identity.id);

Core Resources

These are the primary resources you will use day-to-day.

ak.identities

Create and manage persistent agent identities. Each identity gets a unique email address and can optionally be provisioned with a phone number. Identities persist across sessions. Create once, reference by ID later.

MethodHTTPDescription
create(params?)POST /identitiesCreate a new identity
list()GET /identitiesList all identities
get(id)GET /identities/:idGet a single identity by ID
delete(id)DELETE /identities/:idDelete an identity
provisionPhone(id, opts?)POST /identities/:id/phoneProvision a phone number
listEvents(id, params?)GET /identities/:id/eventsList identity events
listMessages(id, params?)GET /identities/:id/messagesUnified inbox (email + SMS)

Create with custom fields:

typescript
const identity = await ak.identities.create({
  display_name: "Test Agent",
  metadata: { team: "qa", run_id: "abc-123" },
});

console.log(identity.id);    // "ident_abc123..."
console.log(identity.email); // "test-agent-abc@aliaskit.com"

Provision a phone number:

typescript
const phone = await ak.identities.provisionPhone(identity.id, {
  country: "US",
});
console.log(phone.phone_number); // +1555...

Unified inbox:

typescript
const messages = await ak.identities.listMessages(identity.id);
// Returns both email and SMS messages in chronological order

List events:

typescript
const events = await ak.identities.listEvents(identity.id, {
  type: "email.received",
  limit: 50,
});

Re-use an identity across runs:

typescript
// First run: create and store the ID
const identity = await ak.identities.create({ display_name: "My Agent" });
saveToConfig(identity.id); // persist however you like

// Later runs: retrieve by ID
const id = loadFromConfig();
const identity = await ak.identities.get(id);
// Same email, same phone, same history

ak.emails

Read, send, search, and react to email for any identity.

MethodHTTPDescription
list(identityId, params?)GET /identities/:id/emailsList emails for an identity
get(identityId, emailId)GET /identities/:id/emails/:eidGet a single email by ID
markRead(identityId, eid, read)PATCH /identities/:id/emails/:eidMark an email as read or unread
delete(identityId, emailId)DELETE /identities/:id/emails/:eidDelete an email
search(identityId, params)GET /identities/:id/emails/searchSearch emails by query, sender, date, etc.
send(identityId, params)POST /identities/:id/emails/sendSend an email from the identity
waitForCode(identityId, opts?)realtimeWait for the next inbound email and return it
waitForMagicLink(identityId, opts?)realtimeWait for the next inbound email and return it
getAttachmentUrl(emailId, index)-Get a signed URL for an email attachment

Wait for an inbound email:

waitForCode checks existing unread emails first, then subscribes via realtime WebSocket. It returns the full EmailMessage object so your agent can parse the verification code, magic link, or any other content itself.

typescript
const email = await ak.emails.waitForCode(identity.id, {
  timeout: 60_000,
});
console.log(email.from, email.subject);
console.log(email.body_text); // agent parses the code from this

Options: timeout (ms, default 60000), after (Date, only consider emails after this time).

Send an email:

typescript
await ak.emails.send(identity.id, {
  to: "someone@example.com",
  subject: "Hello from my agent",
  body: "This is a test email sent by an AliasKit identity.",
});

Search emails:

typescript
const results = await ak.emails.search(identity.id, {
  query: "verification",
  from: "noreply@example.com",
});

List emails:

typescript
const emails = await ak.emails.list(identity.id, {
  limit: 20,
  unread: true,
});

Get a single email:

typescript
const email = await ak.emails.get(identity.id, emailId);
console.log(email.subject, email.from, email.body);

Mark as read:

typescript
await ak.emails.markRead(identity.id, emailId, true);

Delete an email:

typescript
await ak.emails.delete(identity.id, emailId);

Get an attachment URL:

typescript
const url = await ak.emails.getAttachmentUrl(emailId, 0);
// Returns a signed URL you can fetch directly

ak.sms

Read and send SMS messages for identities with provisioned phone numbers.

MethodHTTPDescription
list(identityId, params?)GET /identities/:id/smsList SMS messages
markRead(identityId, smsId, read)PATCH /identities/:id/sms/:sidMark an SMS as read or unread
delete(identityId, smsId)DELETE /identities/:id/sms/:sidDelete an SMS message
send(identityId, params)POST /identities/:id/sms/sendSend an SMS from the identity
waitForCode(identityId, opts?)realtimeWait for the next inbound SMS and return it

Wait for an inbound SMS:

Returns the full SmsMessage so your agent can parse the verification code itself.

typescript
const sms = await ak.sms.waitForCode(identity.id, {
  timeout: 60_000,
});
console.log(sms.from, sms.body); // agent parses the code from sms.body

Send an SMS:

typescript
await ak.sms.send(identity.id, {
  to: "+15551234567",
  body: "Hello from AliasKit",
});

List SMS messages:

typescript
const messages = await ak.sms.list(identity.id, {
  limit: 10,
});

Mark as read:

typescript
await ak.sms.markRead(identity.id, smsId, true);

Delete an SMS:

typescript
await ak.sms.delete(identity.id, smsId);

ak.cards

Zero-knowledge virtual cards using the BYOC (Bring Your Own Card) model. You supply a real virtual card from your bank. Card details are encrypted client-side with your cardKey before they ever reach AliasKit servers. If you lose your card key, the card data is irrecoverable.

MethodHTTPDescription
create(identityId, params)POST /identities/:id/cardsCreate an encrypted card
list(identityId)GET /identities/:id/cardsList cards (metadata only, no plaintext)
reveal(cardId, options?)GET /cards/:id/revealDecrypt and reveal full card details
freeze(cardId)POST /cards/:id/freezeTemporarily freeze a card
unfreeze(cardId)POST /cards/:id/unfreezeUnfreeze a frozen card
cancel(cardId)POST /cards/:id/cancelPermanently cancel a card
budget(cardId)GET /cards/:id/limitsGet current card budget
updateBudget(cardId, params)PATCH /cards/:id/limitsUpdate card budget
activity(cardId)GET /cards/:id/transactionsGet card transaction history

See also: AliasKit.generateCardKey() for generating the encryption key.

Generate a card key (required before creating cards):

typescript
const cardKey = AliasKit.generateCardKey();
// Returns: "ak_ck_..."
// Store this securely. It is irrecoverable if lost.

Create an encrypted card:

typescript
const ak = new AliasKit({ cardKey });

const card = await ak.cards.create(identity.id, {
  card_number: "4242424242424242",
  exp_month: 12,
  exp_year: 2028,
  cvc: "123",
  label: "Testing card",
  budget: { amount: 5000, currency: "USD", period: "monthly" },
});

Reveal card details:

typescript
// Server checks budget/status, SDK decrypts locally with your cardKey
const details = await ak.cards.reveal(card.id);
console.log(details.card_number, details.exp_month, details.cvc);

List cards:

typescript
const cards = await ak.cards.list(identity.id);
// Returns metadata (label, last4, brand, status) but not plaintext details

Get and update budget:

typescript
const limits = await ak.cards.budget(card.id);
console.log(limits.amount, limits.currency, limits.period);

await ak.cards.updateBudget(card.id, {
  amount: 10000,
  period: "monthly",
});

View transaction activity:

typescript
const txns = await ak.cards.activity(card.id);

Freeze and cancel:

typescript
await ak.cards.freeze(card.id);     // temporarily disable
await ak.cards.unfreeze(card.id);   // re-enable a frozen card
await ak.cards.cancel(card.id);     // permanent, cannot be undone
Cards use zero-knowledge encryption. See Virtual Cards for how BYOC works.

ak.totp

Register and manage TOTP 2FA secrets for identities. Generate valid codes on demand without needing an authenticator app.

MethodHTTPDescription
register(identityId, params)POST /identities/:id/totpRegister a TOTP secret
list(identityId)GET /identities/:id/totpList registered TOTP entries
getCode(identityId, totpId)GET /identities/:id/totp/:tid/codeGet the current valid TOTP code
delete(identityId, totpId)DELETE /identities/:id/totp/:tidDelete a TOTP entry

Register and use a TOTP secret:

typescript
const totp = await ak.totp.register(identity.id, {
  secret: "JBSWY3DPEHPK3PXP",
  serviceName: "MyApp",
  algorithm: "SHA1",
  digits: 6,
  period: 30,
});

const { code, remaining_seconds } = await ak.totp.getCode(identity.id, totp.id);
console.log(`Code: ${code}, expires in ${remaining_seconds}s`);

List registered TOTP entries:

typescript
const entries = await ak.totp.list(identity.id);

Delete a TOTP entry:

typescript
await ak.totp.delete(identity.id, totpId);

ak.realtime

Supabase Realtime WebSocket subscriptions. Get instant push notifications for incoming messages and events.

MethodDescription
subscribe(identityId, cb)Subscribe to all agent_events for an identity
subscribeToEmails(identityId, cb)Subscribe to email_messages for an identity
subscribeToSms(identityId, cb)Subscribe to sms_messages for an identity

All methods return { unsubscribe() }.

typescript
const sub = ak.realtime.subscribeToEmails(identity.id, (email) => {
  console.log("New email from:", email.from);
  console.log("Subject:", email.subject);
});

// Subscribe to SMS
const smsSub = ak.realtime.subscribeToSms(identity.id, (sms) => {
  console.log("SMS from:", sms.from, sms.body);
});

// Subscribe to all events
const allSub = ak.realtime.subscribe(identity.id, (event) => {
  console.log("Event:", event.type, event.data);
});

// Clean up when done
sub.unsubscribe();
smsSub.unsubscribe();
allSub.unsubscribe();

Account Management

Resources for managing your AliasKit account, billing, API keys, webhooks, and custom domains.

ak.billing

Subscription info.

MethodHTTPDescription
getSubscription()GET /billing/subscriptionGet current subscription plan and status
typescript
const sub = await ak.billing.getSubscription();
console.log(sub.plan, sub.status);

Check subscription:

typescript
const sub = await ak.billing.getSubscription();
console.log(sub.plan, sub.status);

ak.apiKeys

Manage API keys programmatically. The plaintext key is only returned once at creation time.

MethodHTTPDescription
list()GET /api-keysList all API keys (masked)
create(params?)POST /api-keysCreate a new API key
revoke(id)DELETE /api-keys/:idRevoke an API key
typescript
const key = await ak.apiKeys.create({
  label: "CI pipeline",
  scopes: ["identities:write", "emails:read"],
});
console.log(key.key); // ak_live_... (shown only once, store it)

// List existing keys
const keys = await ak.apiKeys.list();

// Revoke when no longer needed
await ak.apiKeys.revoke(key.id);

ak.webhooks

Outbound webhooks with HMAC-SHA256 signature verification. Get notified when emails arrive, SMS messages come in, or identity events fire.

MethodHTTPDescription
create(params)POST /webhooksCreate a webhook endpoint
list()GET /webhooksList all webhooks
get(webhookId)GET /webhooks/:idGet webhook details
update(webhookId, params)PATCH /webhooks/:idUpdate a webhook
delete(webhookId)DELETE /webhooks/:idDelete a webhook
deliveries(webhookId, params?)GET /webhooks/:id/deliveriesList delivery attempts and their status
verify(payload, sigHeader, secret)localVerify HMAC-SHA256 signature (no HTTP call)

Create a webhook:

typescript
const webhook = await ak.webhooks.create({
  url: "https://your-app.com/webhooks/aliaskit",
  secret: "whsec_...",
  events: ["email.received", "sms.received", "identity.created"],
  active: true,
});

Update a webhook:

typescript
await ak.webhooks.update(webhook.id, {
  events: ["email.received", "sms.received"],
  active: false,
});

Check delivery history:

typescript
const deliveries = await ak.webhooks.deliveries(webhook.id, {
  limit: 20,
});

Verify a webhook signature (Express example):

typescript
app.post("/webhooks/aliaskit", (req, res) => {
  const signature = req.headers["x-aliaskit-signature"];
  const valid = ak.webhooks.verify(req.body, signature, "whsec_...");

  if (!valid) return res.status(401).send("Invalid signature");

  // Process the event
  console.log(req.body.event, req.body.data);
  res.sendStatus(200);
});

ak.domains

Coming soon. Custom email domains are under active development. The SDK methods below are defined but not yet available. This section will be updated when the feature launches.
MethodHTTPDescription
add(domain)POST /domainsAdd a custom domain
list()GET /domainsList all domains
get(id)GET /domains/:idGet domain details and DNS records
verify(id)POST /domains/:id/verifyRe-check DNS record configuration
delete(id)DELETE /domains/:idRemove a domain
typescript
const domain = await ak.domains.add("agents.yourcompany.com");
// Configure DNS records shown in domain.dns_records (MX, SPF, DKIM)

// After configuring DNS, verify:
const verified = await ak.domains.verify(domain.id);
console.log(verified.status); // "verified" or "pending"

// List all domains
const domains = await ak.domains.list();

// Remove a domain
await ak.domains.delete(domain.id);
Custom domains require the Pro plan. After adding a domain, configure the MX, SPF, and DKIM records shown in the response, then call verify() to confirm.

Advanced Features

These resources are implemented but not part of the core offering. Most agents only need identities, email, SMS, cards, and TOTP. You can safely ignore this section unless you have a specific use case for these features.

ak.threads

Email conversation threads.

MethodHTTPDescription
list(identityId, params?)GET /identities/:id/threadsList email threads
get(identityId, threadId, params?)GET /identities/:id/threads/:tidGet a thread with its messages

ak.identities.getToken

Issue a signed JWT for an identity.

MethodHTTPDescription
getToken(id, params?)POST /identities/:id/tokenIssue an Agent Identity Token

ak.verify

Verify an Agent Identity Token.

MethodHTTPDescription
token(token, params?)POST /verify/tokenVerify a token

ak.agents

Agent profiles with handles and display names.

MethodHTTPDescription
create(params)POST /agentsCreate an agent profile
list()GET /agentsList all agents
get(agentId)GET /agents/:idGet an agent
update(agentId, params)PATCH /agents/:idUpdate an agent
delete(agentId)DELETE /agents/:idDelete an agent
getReputation(agentId)GET /agents/:id/reputationGet agent reputation
getDidDocument(agentId)GET /agents/:id/did.jsonGet W3C DID document
linkErc8004(agentId, params)POST /agents/:id/erc8004Link on-chain identity
listErc8004Links(agentId)GET /agents/:id/erc8004List on-chain links
unlinkErc8004(agentId, linkId)DELETE /agents/:id/erc8004/:linkIdRemove on-chain link

ak.reputation

Identity reputation scoring.

MethodHTTPDescription
get(identityId)GET /identities/:id/reputationGet reputation score
issueCredential(identityId, params?)POST /identities/:id/reputation/credentialIssue signed credential
reportEvent(identityId, params)POST /identities/:id/eventsReport a reputation event

ak.trust

Trust evaluation.

MethodHTTPDescription
evaluate(params)POST /trust/evaluateEvaluate trust for an identity or token

Error Classes

All errors extend AliasKitError and include structured metadata for programmatic handling.

ErrorDescription
AliasKitErrorBase class for all SDK errors
AuthErrorInvalid or missing API key, expired session
ApiErrorNon-2xx response from the API
EmailTimeoutErrorwaitForCode timed out waiting for an email
SmsTimeoutErrorSMS waitForCode timed out waiting for an SMS
BillingErrorBilling or subscription issue
typescript
import {
  AliasKitError,
  EmailTimeoutError,
} from "aliaskit";

For detailed error codes, response format, and handling patterns, see Error Handling.


Card Crypto

Standalone functions for card encryption and decryption. Used internally by ak.cards but also exported for advanced use cases.

typescript
import {
  AliasKit,
  encryptCard,
  decryptCard,
  extractCardMeta,
} from "aliaskit";

AliasKit.generateCardKey()

Generate a new card encryption key. Store this securely. It is irrecoverable if lost.

typescript
const cardKey = AliasKit.generateCardKey();
// "ak_ck_..."

encryptCard(details, cardKey)

Encrypt card details using AES-256-GCM. Returns an opaque encrypted string.

typescript
const encrypted = encryptCard({
  card_number: "4242424242424242",
  exp_month: 12,
  exp_year: 2028,
  cvc: "123",
}, cardKey);

decryptCard(encrypted, cardKey)

Decrypt card details back to plaintext.

typescript
const plaintext = decryptCard(encrypted, cardKey);
console.log(plaintext.card_number, plaintext.cvc);

extractCardMeta(details)

Extract non-sensitive metadata from card details without encryption.

typescript
const meta = extractCardMeta({
  card_number: "4242424242424242",
  exp_month: 12,
  exp_year: 2028,
});
// { last4: "4242", brand: "visa", expiry: "12/2028" }