Link a WhatsApp user to a customer account
Use it when the chat must know who the user is before showing personal data, and the channel doesn't tell you. WhatsApp identifies users by a business-scoped user ID (BSUID), and only shares the phone number under Meta's conditions; users with a username may never share it.
Start from the block. It ships the screen and the security-critical half: links, one-time codes stored hashed, attempt limits per customer, and a code that survives a reload while the user reads their email.
npx ui-calling add link-accountThen fill the three TODOs in link-account.server.ts: findCustomer (look the user up by what they typed), sendCode (email or SMS, never the chat) and nameOf. Replacing a screen of your own? add link-account --replace writes the block's server file over yours.
Users who don't sign in with an email type something else: npx ui-calling add link-account --identifier text (tel for phone numbers) registers <LinkAccount identifier="text" />, with a label, keyboard and intro to match. Set your own words per language with locales={{ en: { identifierLabel: "Employee number" }, es: { identifierLabel: "Número de empleado" } }}. Then check the two places that speak for the server: findCustomer looks up what users type, and the contract's description is what the model reads about the screen ("a one-time code sent outside this chat"), so it must match how you send the code.
In development, link the test user npx ui-calling link uses, once at startup, so every screen opens for it:
if (process.env.NODE_ENV !== "production") identity.link("dev-user", "C-1001");How it fits
The webhook gives you a BSUID. The session subject is
whatsappSubject(portfolioId, bsuid).If Meta shared a phone number that matches a customer, link by phone and skip the screen:
identity.link(subject, customer.id).Otherwise the agent only gets one tool,
show_link_account, until the chat is linked. The adapters take a filter:anthropicTools(ui, (name) => (name === "show_link_account") !== linked). Pass the same filter when you run a tool call (anthropicToolResult(ui, block, who, filter)), so a tool the model wasn't offered is refused.Every other surface checks the link before loading anything.
The system prompt says what's true now, in words that agree with the history. Built every turn, it changes once the code is entered, but the conversation still holds the verification the agent asked for. Write the after-state so both read right:
Before: This chat isn't verified yet. You only have show_link_account: open it before anything personal, with what they asked for in continue_with. After: This chat is verified as Sam Taylor (C-1001), through the verification screen earlier in this conversation (it was needed).Without the last part, a model that reads "verified" may apologise for having asked.
The identity helper
sqliteIdentity(store) from @ui-calling/sqlite keeps its tables next to ui-calling's. add link-account writes identity.ts next to store.ts, so your other surfaces, your webhook and your back office can import it without importing a surface:
import { identity } from "./identity";
resolve: async ({ shift_id }, ctx) => {
const employeeId = identity.customerFor(ctx.subject);
// refused: it isn't an outage, so the screen gets 422 with errorReason "account_not_linked", not a 502.
if (!employeeId) throw new SurfaceError("account_not_linked", "This chat isn't linked to an employee yet", { refused: true });
return loadShift(shift_id, employeeId); // only this employee's shifts
},| Method | What it does |
|---|---|
customerFor(subject) | The linked customer ID, or undefined |
link(subject, customerId) / unlink(subject) | Link directly, e.g. by a phone number Meta shared |
startVerification(subject, customerId) | A new code to send (replaces the previous one); undefined while the customer is locked out |
pending(subject) | A code is waiting: the screen resumes on "enter your code" after a reload |
verify(subject, code) | { ok: true, customerId } and the subject is linked, or { ok: false, reason }: wrong_code (with attemptsLeft), expired, no_code, locked |
cancelVerification(subject) | Drop the waiting code (the user starts over) |
setPin(customerId, pin) / hasPin(customerId) / checkPin(subject, pin) | A PIN for screens with verify: true, hashed with scrypt; wrong ones count towards the same lockout as codes |
pinVerifier() / codeVerifier({ deliver }) | A verifier for createUiCalling (see verify-before-showing) |
moveLink(previousSubject, subject, { keepOld? }) | The user changed number and got a new BSUID: link the new one too. The old one stays linked (links already sent keep working until they expire) unless keepOld: false |
Options: codeTtlMs (10 minutes), maxAttempts (5), lockMs (15 minutes), digits (6).
Contract
Short-lived, and the code never reaches the agent:
export const linkAccount = defineSurface({
name: "link_account",
input: z.object({ continue_with: z.string().max(200).describe("What the user asked for, so you can pick it up after linking") }),
ttlSeconds: 15 * 60, // whoever holds this link can link the chat to an account
data: z.object({ stage: z.enum(["start", "code_sent", "linked"]), name: z.string().nullable(), continueWith: z.string() }),
events: {
code_requested: event(z.object({ identifier: z.string().trim().min(1).max(200) }), { describe: () => "User asked for a verification code" }),
code_entered: event(z.object({ code: z.string().trim().max(12) }), { redact: ["code"], describe: () => "User entered their verification code", wake: true }),
start_over: event(z.object({}), { describe: () => "User started over" }),
},
});summarize ends with "They wanted: …", so the agent picks the original request back up as soon as the link is made.
Watch out
- Same answer for unknown accounts.
code_requestedreturns exactly the same data whether or not the account exists, also after a reload: no masked "we sent it to s***@…", which would tell anyone holding a link which emails or employee numbers are real. If you change the screen, keep it that way. - Link the session's subject, never an ID from the screen. The handler links
ctx.subject; the payload only carries what the user typed. - Attempts count per customer, not per link. The agent can open new links on request; the helper's lock follows the customer across chats and links.
- Restrict tools until linked. Giving the agent every tool and hoping it asks first leaks data the first time it doesn't.
- BSUIDs change when the user changes number. Meta sends the old one (
identityChangefromparseWhatsAppWebhook); callidentity.moveLink(old, new). The old one stays linked, so links already sent keep working until they expire.
In the ui-calling repo
Not in the package; for reading if you have the repo.
- The block:
link-account.surface.ts,link-account.server.ts,link-account.tsx,identity.ts - The helper and its tests:
identity.ts, theidentity:check intest-store.ts - The demo's own version (phone linking, BSUID changes):
identity.ts, theidentity:checks insmoke.ts