Sign in with a phone code
For: an app developer whose users expect a code by SMS, and who accepts ASVS 5.0.0 6.6.1 level 2.
What it does: phone adds POST /phone/request and POST /phone/verify, and the routes that add or remove a number. Core makes and checks each code. Your SMS supplier only sends the text.
Before you start
Section titled “Before you start”- A limiter that counts for the whole deployment: the D1, Postgres, or MySQL limiter. Limits names each one.
- An SMS port for your supplier: one call,
send({ to, text }). Phone codes gives its shape. - The
waitUntilof your host, passed toauth.handle, as in Start on Workers with D1.
- Write the SMS port. It answers
"sent"or"unavailable". Make it never make, check, or limit a code. - Set
phone.smsto the port andphone.regionsto the calling-code prefixes that may get an SMS. - Set
phone.signUp: trueif a code to an unknown number may make a user. - Pass the limiter of your adapter as
limiter. - On Workers, pass
{ waitUntil: (p) => ctx.waitUntil(p) }toauth.handle, or mount a binding that passes it. - Post
{ phone }toPOST /phone/request. Then post{ phone, code }toPOST /phone/verify. - In a browser app, call
client.phone.requestandclient.phone.verifyof the client package in place of the posts. - On a public site, add the captcha flow
phone-requesttocaptcha.flows.
import { createAuth, type LimiterPort, type MailPort, type SmsPort, type StorageAdapter,} from "@authtempo/core";
/** A placeholder port that sends nothing. Write the port of your SMS supplier. */const NO_SMS: SmsPort = { send: async () => "unavailable" };
/** * Sign-in by a code over SMS. Core makes, keys, and counts each code. The * port of your SMS supplier only sends text. Pass the limiter of your D1, * Postgres, or MySQL adapter: the daily cap counts per deployment. Only a * test passes "isolate-for-tests", and its cap then counts per isolate. */export function createPhoneAuth( deps: { storage: StorageAdapter; mail: MailPort; secret: string; limiter: LimiterPort | "isolate-for-tests"; }, sms: SmsPort = NO_SMS,) { const forTests = deps.limiter === "isolate-for-tests"; return createAuth({ baseURL: "https://api.example.com", appURL: "https://app.example.com", trustedOrigins: ["https://app.example.com"], secret: deps.secret, storage: deps.storage, mail: deps.mail, ...(deps.limiter === "isolate-for-tests" ? {} : { limiter: deps.limiter }), phone: { sms, // Required, with no default: each country prefix that may get an SMS. regions: ["+44", "+353"], // A code to an unknown number makes a user with no address. signUp: true, // The SMS of the whole deployment per 24 hours. 1000 is the default. dailyCap: 1000, // Tests only. With a limiter that counts per isolate, createAuth refuses phone. ...(forTests ? { isolateLimiter: "allow" as const } : {}), }, });}import { createMemoryLimiter, systemClock } from "@authtempo/core";import { createRecordingSms } from "@authtempo/core/testing";import { describe, expect, it } from "vitest";import { API, call, harness, sessionCookieOf } from "../support/harness.ts";import { createPhoneAuth } from "./phone.ts";
const json = (path: string, body: unknown) => new Request(`${API}/auth${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), });
/** A test passes the test value. An app passes the limiter of its adapter. */const forTests = () => ({ ...harness(), limiter: "isolate-for-tests" as const });
describe("sign in with a phone code", () => { it("sends a code after the answer, and the code opens the session", async () => { const sms = createRecordingSms(); const auth = createPhoneAuth(forTests(), sms); const phone = "+447700900123"; // The SMS goes out after the answer: give handle the waitUntil of your host. const work: Promise<unknown>[] = []; const asked = await auth.handle(json("/phone/request", { phone }), { waitUntil: (p) => void work.push(p), }); expect(await asked.json()).toEqual({ sent: true }); // At the answer, the send waits in the after-answer work. expect(sms.sent).toEqual([]); expect(work.length).toBe(1); await Promise.all(work); expect(sms.sent.length).toBe(1); const code = /\d{6}/.exec(sms.sent.at(-1)?.text ?? "")?.[0] ?? ""; const res = await call(auth, "POST", "/auth/phone/verify", { phone, code }); expect(res.status).toBe(200); const { user } = (await res.json()) as { user: { email: string | null } }; expect(user.email).toBeNull(); expect(sessionCookieOf(res)).not.toBe(""); });
it("refuses a number outside the regions before any SMS", async () => { const sms = createRecordingSms(); const auth = createPhoneAuth(forTests(), sms); const res = await call(auth, "POST", "/auth/phone/request", { phone: "+15550100123" }); expect(await res.json()).toEqual({ error: "phone_region" }); expect(sms.sent).toEqual([]); });
it("refuses a memory limiter outside tests: the cap is per deployment", () => { const limiter = createMemoryLimiter(systemClock); expect(() => createPhoneAuth({ ...harness(), limiter })).toThrow( "phone needs a shared limiter: the daily cap is per deployment", ); });
it("refuses a call with no limiter, as from plain JavaScript", () => { // The type needs a limiter. A call that skips the type check gets the refusal. expect(() => createPhoneAuth(harness() as never)).toThrow( "phone needs a shared limiter: the daily cap is per deployment", ); });});How it behaves
Section titled “How it behaves”- A number is E.164: a plus sign and 8 to 15 digits, the first not 0. A bad form answers
phone_invalid. A number outside every prefix ofphone.regionsanswersphone_region, and gets no SMS. phone.regionsis required and has no default. It holds 1 to 50 prefixes, each a plus sign and 1 to 4 digits.- A code has 6 digits by default (
phone.length: 6 or 8) and lives 5 minutes by default (phone.ttlMinutes: 1 to 10). - Core keys the hash of each code under the current secret, and binds it to its number and its purpose. A wrong guess counts one try. Try number
phone.maxAttempts(3 by default) spends the code. POST /phone/requestanswers{ sent: true }for a known and an unknown number. A known number gets a code. An unknown number gets a code only withphone.signUp.- A number whose account has an address in a domain with SSO
enforceon gets no code, and the same answer.POST /phone/verifyanswerssso_requiredfor such an account. - The code goes out after the answer, under the
waitUntilof the host. So the answer time does not tell whether a number has an account. - A send after the answer has a time limit of 10 seconds. A cap refusal, an outage, or a timeout then gives one
sms.not_sentline with the reasoncapped,unavailable, ortimeout. Watch that line: the person got{ sent: true }and no code. - With no
waitUntilon Workers,auth.handlewaits for the send before it answers, and writes oneobserve.wait_until_missingline. On other runtimes the work runs detached. POST /phone/verifyopens a session withvia: "phone". For a user with the second factor on,totp.gate.phone(on by default) answers a challenge with no email method.- With
phone.signUp, a right code for a new number makes a user with no address. See The account with no address. phone.dailyCapcounts each SMS of the deployment for 24 hours, 1000 by default. A send over the cap makes no call to the port.createAuthrefusesphonewith a limiter that counts per isolate, with the text “phone needs a shared limiter: the daily cap is per deployment”. For tests only, setphone.isolateLimiter: "allow". The cap is then per isolate.POST /phone/addneeds a fresh session and a proved handle. A free number gets a code. A number that another account holds gets a note with no code, and the same answer.- The code and the note of an add go out after the answer, as at
POST /phone/request. So the answer time does not tell a number that another account holds. POST /phone/add/verifystores the number and sends a notice to the address of the user. Of two users who add one number at the same time, one getsphone_taken.POST /phone/removeneeds a fresh session. It refuses the last way into the account withlast_credential.- The password sign-in takes
{ phone, password }too. See Passwords. - A proof of the address on an unverified account clears its phone, also at the confirm of the sign-up. The claim rule tells why.
- A phone code from an anonymous session links that anonymous user only when the verify carries the same anonymous session.
- The limits:
phone-otp:ip10,phone-otp:phone3,phone-verify:ip30, andphone-verify:phone10, each per 15 minutes. Alsophone-otp:phone-day10 per 24 hours, andphone-add:user3 per 15 minutes.
Residuals
Section titled “Residuals”- Number recycling and SIM swap. A carrier gives the number to a new person, or an attacker moves it to a new SIM. The new holder of the number then signs in with a code.
- For an account with an address, core sends no mail at a phone sign-in. The session is fresh, so the routes with the fresh rule open to the new holder. Turn on the second factor, and keep
totp.gate.phoneon. - A user with no address who moves to a new number gets no notice on any channel. The old number gets no text.
api.phone.requestandapi.phone.addin process send before they answer. Their time can tell an account. They answer 429 for the cap and 503 for an outage.- The work after the answer starts in the task of the answer. A known number answers about 0.3 to 0.8 ms later than an unknown one, in process on the memory store.
- On Workers with no
waitUntil, the answer waits for the cap, the code row, and the SMS of a known number. Its time then tells an account. PasswaitUntilto close it. - An outage of the supplier shows in no answer of
POST /phone/requestorPOST /phone/add. The person gets{ sent: true }and no code. Only thesms.not_sentline shows it. - A region of one digit, such as
+1, admits every country of that zone, with numbers of a high cost. List narrow prefixes. - The per-number limits read the number as given. Two E.164 forms of one handset, such as
+4407700900123and+447700900123, each get their own count. - The daily cap counts in a fixed window. Up to 2 ×
dailyCapsends can go out in a short span across the end of a window. A newdailyCapstarts a new count. - Each kind of identifier has its own password limit. One account with an address, a username, and a phone takes up to 30 password guesses per 15 minutes.
Before you go live
Section titled “Before you go live”Send one real SMS through the port of your supplier. Then sign in with its code. Core’s tests use a recording port, not a supplier.
If it fails
Section titled “If it fails”phone_invalid: the number is not E.164.phone_region: the number is outside every prefix ofphone.regions.invalid_code: the code is wrong, expired, or spent. Ask for a new code.too_many_attempts:phone.maxAttemptswrong tries spent the code. Ask for a new code.rate_limited: too many requests from the IP or for the number. Wait 15 minutes, or a day after 10 codes to one number.phone_taken: another account stored the number first.sign_up_closed: the sign-up rule refused a new user for an unknown number.captcha_required,captcha_failed, andcaptcha_unavailable: the captcha flowphone-requestrefused the request.invalid_body: the body is not JSON, or a field has the wrong type.account_banned: an operator banned the account of the number.sso_required: the account of the number has an address of a domain that signs in by SSO only. Send the browser to the start URL indetail.hook_refusedandhook_failed: a hook of your app refused the sign-in or the change, or threw.unauthorized:POST /phone/add,POST /phone/add/verify, andPOST /phone/removeneed a session.email_unverified: at an add, the user has no proved handle. Confirm the address first.session_not_fresh: an add or a remove needs a fresh session. Sign in again, then send it again.last_credential: the number is the last way into the account. Add another way in first.conflict: another write changed the user at the same moment. Send the request again.anonymous_refused: an anonymous session tried to add a number. Sign in first.impersonation_session: an operator who impersonates a user cannot add or remove a number.