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
npm install aliaskitConstructor
The simplest way to create a client is to set the ALIASKIT_API_KEY environment variable and call the constructor with no arguments:
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:
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.
const ak = new AliasKit(); // in browser, uses session cookieQuick Start
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.
| Method | HTTP | Description |
|---|---|---|
create(params?) | POST /identities | Create a new identity |
list() | GET /identities | List all identities |
get(id) | GET /identities/:id | Get a single identity by ID |
delete(id) | DELETE /identities/:id | Delete an identity |
provisionPhone(id, opts?) | POST /identities/:id/phone | Provision a phone number |
listEvents(id, params?) | GET /identities/:id/events | List identity events |
listMessages(id, params?) | GET /identities/:id/messages | Unified inbox (email + SMS) |
Create with custom fields:
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:
const phone = await ak.identities.provisionPhone(identity.id, {
country: "US",
});
console.log(phone.phone_number); // +1555...Unified inbox:
const messages = await ak.identities.listMessages(identity.id);
// Returns both email and SMS messages in chronological orderList events:
const events = await ak.identities.listEvents(identity.id, {
type: "email.received",
limit: 50,
});Re-use an identity across runs:
// 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 historyak.emails
Read, send, search, and react to email for any identity.
| Method | HTTP | Description |
|---|---|---|
list(identityId, params?) | GET /identities/:id/emails | List emails for an identity |
get(identityId, emailId) | GET /identities/:id/emails/:eid | Get a single email by ID |
markRead(identityId, eid, read) | PATCH /identities/:id/emails/:eid | Mark an email as read or unread |
delete(identityId, emailId) | DELETE /identities/:id/emails/:eid | Delete an email |
search(identityId, params) | GET /identities/:id/emails/search | Search emails by query, sender, date, etc. |
send(identityId, params) | POST /identities/:id/emails/send | Send an email from the identity |
waitForCode(identityId, opts?) | realtime | Wait for the next inbound email and return it |
waitForMagicLink(identityId, opts?) | realtime | Wait 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.
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 thisOptions: timeout (ms, default 60000), after (Date, only consider emails after this time).
Send an email:
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:
const results = await ak.emails.search(identity.id, {
query: "verification",
from: "noreply@example.com",
});List emails:
const emails = await ak.emails.list(identity.id, {
limit: 20,
unread: true,
});Get a single email:
const email = await ak.emails.get(identity.id, emailId);
console.log(email.subject, email.from, email.body);Mark as read:
await ak.emails.markRead(identity.id, emailId, true);Delete an email:
await ak.emails.delete(identity.id, emailId);Get an attachment URL:
const url = await ak.emails.getAttachmentUrl(emailId, 0);
// Returns a signed URL you can fetch directlyak.sms
Read and send SMS messages for identities with provisioned phone numbers.
| Method | HTTP | Description |
|---|---|---|
list(identityId, params?) | GET /identities/:id/sms | List SMS messages |
markRead(identityId, smsId, read) | PATCH /identities/:id/sms/:sid | Mark an SMS as read or unread |
delete(identityId, smsId) | DELETE /identities/:id/sms/:sid | Delete an SMS message |
send(identityId, params) | POST /identities/:id/sms/send | Send an SMS from the identity |
waitForCode(identityId, opts?) | realtime | Wait 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.
const sms = await ak.sms.waitForCode(identity.id, {
timeout: 60_000,
});
console.log(sms.from, sms.body); // agent parses the code from sms.bodySend an SMS:
await ak.sms.send(identity.id, {
to: "+15551234567",
body: "Hello from AliasKit",
});List SMS messages:
const messages = await ak.sms.list(identity.id, {
limit: 10,
});Mark as read:
await ak.sms.markRead(identity.id, smsId, true);Delete an SMS:
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.
| Method | HTTP | Description |
|---|---|---|
create(identityId, params) | POST /identities/:id/cards | Create an encrypted card |
list(identityId) | GET /identities/:id/cards | List cards (metadata only, no plaintext) |
reveal(cardId, options?) | GET /cards/:id/reveal | Decrypt and reveal full card details |
freeze(cardId) | POST /cards/:id/freeze | Temporarily freeze a card |
unfreeze(cardId) | POST /cards/:id/unfreeze | Unfreeze a frozen card |
cancel(cardId) | POST /cards/:id/cancel | Permanently cancel a card |
budget(cardId) | GET /cards/:id/limits | Get current card budget |
updateBudget(cardId, params) | PATCH /cards/:id/limits | Update card budget |
activity(cardId) | GET /cards/:id/transactions | Get card transaction history |
See also: AliasKit.generateCardKey() for generating the encryption key.
Generate a card key (required before creating cards):
const cardKey = AliasKit.generateCardKey();
// Returns: "ak_ck_..."
// Store this securely. It is irrecoverable if lost.Create an encrypted card:
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:
// 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:
const cards = await ak.cards.list(identity.id);
// Returns metadata (label, last4, brand, status) but not plaintext detailsGet and update budget:
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:
const txns = await ak.cards.activity(card.id);Freeze and cancel:
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 undoneak.totp
Register and manage TOTP 2FA secrets for identities. Generate valid codes on demand without needing an authenticator app.
| Method | HTTP | Description |
|---|---|---|
register(identityId, params) | POST /identities/:id/totp | Register a TOTP secret |
list(identityId) | GET /identities/:id/totp | List registered TOTP entries |
getCode(identityId, totpId) | GET /identities/:id/totp/:tid/code | Get the current valid TOTP code |
delete(identityId, totpId) | DELETE /identities/:id/totp/:tid | Delete a TOTP entry |
Register and use a TOTP secret:
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:
const entries = await ak.totp.list(identity.id);Delete a TOTP entry:
await ak.totp.delete(identity.id, totpId);ak.realtime
Supabase Realtime WebSocket subscriptions. Get instant push notifications for incoming messages and events.
| Method | Description |
|---|---|
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() }.
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.
| Method | HTTP | Description |
|---|---|---|
getSubscription() | GET /billing/subscription | Get current subscription plan and status |
const sub = await ak.billing.getSubscription();
console.log(sub.plan, sub.status);Check subscription:
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.
| Method | HTTP | Description |
|---|---|---|
list() | GET /api-keys | List all API keys (masked) |
create(params?) | POST /api-keys | Create a new API key |
revoke(id) | DELETE /api-keys/:id | Revoke an API key |
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.
| Method | HTTP | Description |
|---|---|---|
create(params) | POST /webhooks | Create a webhook endpoint |
list() | GET /webhooks | List all webhooks |
get(webhookId) | GET /webhooks/:id | Get webhook details |
update(webhookId, params) | PATCH /webhooks/:id | Update a webhook |
delete(webhookId) | DELETE /webhooks/:id | Delete a webhook |
deliveries(webhookId, params?) | GET /webhooks/:id/deliveries | List delivery attempts and their status |
verify(payload, sigHeader, secret) | local | Verify HMAC-SHA256 signature (no HTTP call) |
Create a webhook:
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:
await ak.webhooks.update(webhook.id, {
events: ["email.received", "sms.received"],
active: false,
});Check delivery history:
const deliveries = await ak.webhooks.deliveries(webhook.id, {
limit: 20,
});Verify a webhook signature (Express example):
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
| Method | HTTP | Description |
|---|---|---|
add(domain) | POST /domains | Add a custom domain |
list() | GET /domains | List all domains |
get(id) | GET /domains/:id | Get domain details and DNS records |
verify(id) | POST /domains/:id/verify | Re-check DNS record configuration |
delete(id) | DELETE /domains/:id | Remove a domain |
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);verify() to confirm.Advanced Features
ak.threads
Email conversation threads.
| Method | HTTP | Description |
|---|---|---|
list(identityId, params?) | GET /identities/:id/threads | List email threads |
get(identityId, threadId, params?) | GET /identities/:id/threads/:tid | Get a thread with its messages |
ak.identities.getToken
Issue a signed JWT for an identity.
| Method | HTTP | Description |
|---|---|---|
getToken(id, params?) | POST /identities/:id/token | Issue an Agent Identity Token |
ak.verify
Verify an Agent Identity Token.
| Method | HTTP | Description |
|---|---|---|
token(token, params?) | POST /verify/token | Verify a token |
ak.agents
Agent profiles with handles and display names.
| Method | HTTP | Description |
|---|---|---|
create(params) | POST /agents | Create an agent profile |
list() | GET /agents | List all agents |
get(agentId) | GET /agents/:id | Get an agent |
update(agentId, params) | PATCH /agents/:id | Update an agent |
delete(agentId) | DELETE /agents/:id | Delete an agent |
getReputation(agentId) | GET /agents/:id/reputation | Get agent reputation |
getDidDocument(agentId) | GET /agents/:id/did.json | Get W3C DID document |
linkErc8004(agentId, params) | POST /agents/:id/erc8004 | Link on-chain identity |
listErc8004Links(agentId) | GET /agents/:id/erc8004 | List on-chain links |
unlinkErc8004(agentId, linkId) | DELETE /agents/:id/erc8004/:linkId | Remove on-chain link |
ak.reputation
Identity reputation scoring.
| Method | HTTP | Description |
|---|---|---|
get(identityId) | GET /identities/:id/reputation | Get reputation score |
issueCredential(identityId, params?) | POST /identities/:id/reputation/credential | Issue signed credential |
reportEvent(identityId, params) | POST /identities/:id/events | Report a reputation event |
ak.trust
Trust evaluation.
| Method | HTTP | Description |
|---|---|---|
evaluate(params) | POST /trust/evaluate | Evaluate trust for an identity or token |
Error Classes
All errors extend AliasKitError and include structured metadata for programmatic handling.
| Error | Description |
|---|---|
AliasKitError | Base class for all SDK errors |
AuthError | Invalid or missing API key, expired session |
ApiError | Non-2xx response from the API |
EmailTimeoutError | waitForCode timed out waiting for an email |
SmsTimeoutError | SMS waitForCode timed out waiting for an SMS |
BillingError | Billing or subscription issue |
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.
import {
AliasKit,
encryptCard,
decryptCard,
extractCardMeta,
} from "aliaskit";AliasKit.generateCardKey()
Generate a new card encryption key. Store this securely. It is irrecoverable if lost.
const cardKey = AliasKit.generateCardKey();
// "ak_ck_..."encryptCard(details, cardKey)
Encrypt card details using AES-256-GCM. Returns an opaque encrypted string.
const encrypted = encryptCard({
card_number: "4242424242424242",
exp_month: 12,
exp_year: 2028,
cvc: "123",
}, cardKey);decryptCard(encrypted, cardKey)
Decrypt card details back to plaintext.
const plaintext = decryptCard(encrypted, cardKey);
console.log(plaintext.card_number, plaintext.cvc);extractCardMeta(details)
Extract non-sensitive metadata from card details without encryption.
const meta = extractCardMeta({
card_number: "4242424242424242",
exp_month: 12,
exp_year: 2028,
});
// { last4: "4242", brand: "visa", expiry: "12/2028" }