Sign in with a password
For: an app developer who wants people to sign in with an address and a password.
What it does: core adds the password routes, a password form on its sign-in page, and api.password.
Before you start
Section titled “Before you start”- A working setup from a getting started tutorial.
- Workers Paid on Cloudflare. One hash needs more CPU than Workers Free gives one request.
- Add
password: {}to the config. With nopasswordkey, the password routes answer 404. - Set
password.minLengthwhen 8 code points is too few for your app. - Set
password.breachChecktocreateBreachCheck()of@authtempo/breach-check. Check passwords against breaches gives the steps.
import { createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
/** Known breached passwords. In an app, use `createBreachCheck()` of @authtempo/breach-check. */const BREACHED = new Set(["password1234", "qwertyuiop12"]);
export function createPasswordAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string;}) { 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, password: { // The lower bound in code points, 8 to 128. The default is 8; the upper bound is 128. minLength: 12, // True refuses the password with password_breached. The default is no check. breachCheck: async (plain) => BREACHED.has(plain), }, });}- On the sign-up form, call
client.password.signUp({ email, password, name }). - Tell the person to open the link in the mail, in the same browser. The sign-up answers
{ sent: true, signUpProof }for every address, and the link signs the person in. - When the link lands on your app with
password=set, show a first-password form. It callsclient.password.change({ newPassword })with no current password. - On the sign-in form, call
client.password.signIn({ email, password }). - On the “Forgot password” button, call
client.password.requestReset({ email }). - On a settings page, call
client.password.change({ currentPassword, newPassword }).
import { describe, expect, it } from "vitest";import { call, callSettled, harness, lastMailTo } from "../support/harness.ts";import { createPasswordAuth } from "./password.ts";
describe("sign in with a password", () => { it("signs up, mails the verify link, answers the same for every address, and signs in with the right password only", async () => { const h = harness(); const auth = createPasswordAuth(h); const up = await callSettled(auth, "POST", "/auth/password/sign-up", { email: "ada@example.com", password: "correct horse battery", }); expect(up.status).toBe(200); // The sign-up proof: a browser keeps it as a cookie, and its confirm keeps the password. expect(await up.json()).toEqual({ sent: true, signUpProof: expect.stringMatching(/^sp_/) }); expect(lastMailTo(h, "ada@example.com").subject).toBe("Confirm your email for api.example.com"); // A second sign-up of the address gets the same answer, and the owner gets a mail. const again = await callSettled(auth, "POST", "/auth/password/sign-up", { email: "ada@example.com", password: "correct horse battery", }); expect(await again.json()).toEqual({ sent: true, signUpProof: expect.stringMatching(/^sp_/) }); expect(lastMailTo(h, "ada@example.com").subject).toBe("Your account at api.example.com");
const right = await call(auth, "POST", "/auth/password/sign-in", { email: "ada@example.com", password: "correct horse battery", }); expect(right.status).toBe(200); const wrong = await call(auth, "POST", "/auth/password/sign-in", { email: "ada@example.com", password: "wrong horse battery", }); expect(wrong.status).toBe(401); expect(await wrong.json()).toEqual({ error: "invalid_credentials" }); });
it("refuses a short password and a breached password", async () => { const auth = createPasswordAuth(harness()); const short = await callSettled(auth, "POST", "/auth/password/sign-up", { email: "bo@example.com", password: "short pw", }); expect(await short.json()).toEqual({ error: "password_policy" }); const breached = await callSettled(auth, "POST", "/auth/password/sign-up", { email: "bo@example.com", password: "password1234", }); expect(await breached.json()).toEqual({ error: "password_breached" }); });});How it behaves
Section titled “How it behaves”- The default hash is PBKDF2-HMAC-SHA256 on Web Crypto with 100000 iterations, the highest count that Workers takes.
- A password is 8 to 128 code points. It has no control character, and it does not equal the address.
- Core stores the password as the person typed it, with no Unicode normalization.
- The sign-in takes exactly one of
email,username, orphone, withpassword. A body with two of them or none answersinvalid_body.usernameneeds theusernameconfig.phoneneeds thephoneconfig, elseinvalid_body.phoneis an E.164 number. - An unknown address, username, or phone runs a dummy hash, so the answer takes the same time. A username or a phone of a bad form does the same, and so does a phone outside
phone.regions. Every failure answersinvalid_credentials. - A username is public, so it tells a guesser which account to try. Each kind of identifier has its own limit, so the limits add up. One account takes up to 20 guesses per 15 minutes by address and username, and 30 with a phone.
password:ipbounds each IP at 20. - A reset ends every session of the user. A change ends every other session. Neither deletes an API token.
- A reset of a user with the second factor on sets the password and answers a challenge, not a session.
- A user with the second factor on gets a challenge from the sign-in and from a reset, not a session. Turn on the second factor tells the next step.
- The sign-in has four limits:
password:ip:<ip>20 per 15 minutes, and 10 per 15 minutes for each ofpassword:email:<email>,password:username:<username>, andpassword:phone:<phone>. - A sign-in by username or phone to an account in a domain that needs SSO answers
sso_requiredafter a right password. A sign-in by address answers it before the password check. - With
password.requireVerifiedon, a right password of an unverified address answersemail_unverified, and a new link goes out. The limitpassword-resend:email:<email>allows 3 links per 15 minutes. A wrong password still answersinvalid_credentials. - With
signUp: "invited", the sign-in does the same check, so a person who signs up at an invited address signs in only after the link. - Each sign-up answer holds the sign-up proof
signUpProof, and sets it as the HttpOnly cookie__Host-tempo_signup. The verify link keeps the password only in a browser with that cookie. - A link opened anywhere else is a claim: the password goes, and the link lands on
/?password=set. The confirm of a sign-up tells why. - A native app whose link opens in the system browser loses the password at the confirm. Use
password.verifyBy: "code", and sendsignUpProofwith the code. - A native app that posts the link token itself keeps no session and no password. The link form reads the proof from the cookie only, and its answer holds no token. That is the safe side, but the person must prove the address again.
- An app on another site than the auth origin uses the code form too, and sends
signUpProofwith the code. Its proof cookie is a third-party cookie, and many browsers drop it. Then the link is a claim, and the password goes. - Such an app also sends
signUpProofin the body of a sign-in and of a resend before the confirm. Then the new link or code keeps the proof. - By default every sign-up answers
{ sent: true, signUpProof }and sets no session cookie, so the answer does not tell which addresses have an account. A new address gets the verify link. A known address gets a mail that says it has an account (password.existingAccountMail). The limitpassword-sign-up:email:<email>allows 5 sign-ups per hour. - With
password.verifyBy: "code", the sign-up mails a code in place of the link. See Prove the address by a code. - With
password.uniformSignUp: false, a sign-up opens a session, and a known address answersemail_taken. Withpassword.requireVerifiedon too, or withsignUp: "invited", a sign-up answers{ user, verifyRequired: true }and sets no session cookie. - A first password needs a fresh session. A change while the second factor is on needs one too. A stale one answers
session_not_fresh. - A change with no second factor needs no fresh session, because the current password is the proof.
- Limits lists the other limits of the password routes.
If it fails
Section titled “If it fails”invalid_body: a field is missing or has the wrong type.password_policy: the password is too short, too long, holds a control character, or equals the address.password_breached:breachCheckanswered true. Ask for another password.breach_check_unavailable: the breach check gave no answer. Try again in a few minutes.sign_up_closed:signUpisfalse. Withpassword.uniformSignUp: false, an address with no invitation undersignUp: "invited"gets it too.email_taken: only withpassword.uniformSignUp: false. A verified account or a password account has the address. Offer the sign-in.email_taken_unverified: only withpassword.uniformSignUp: false. An unverified account has the address. Offer the sign-in.invalid_credentials: the address or the password is wrong.email_unverified: a change needs a verified address. Withpassword.requireVerifiedon or withsignUp: "invited", a sign-in needs one too. Ask the person to open the new link.invalid_tokenandtoken_expired: the verify link or the reset link is spent or old.rate_limited: a limit of the flow is full. Wait 15 minutes.session_not_fresh: the session is older than the fresh window. Re-authenticate, then send it again.