Give a script an API token
For: an app developer whose users run scripts, CLIs, or CI jobs against the app.
What it does: a person with a session creates a tk_ token. A script sends it as a bearer token to the routes that allow it.
Before you start
Section titled “Before you start”- A working setup from a getting started tutorial.
- Nothing in the config. The token routes exist in every deployment.
- On a settings page, call
client.tokens.create({ name, expiresInDays }). - Show the
tokenof the answer once. Core stores its SHA-256 only, and no route shows it again. - List the tokens with
client.tokens.list(). Thehinttells them apart. - In each app route that a script may call, read the caller with
auth.caller(request). - In each app route that a token must not reach, read the caller with
auth.session(request).
import { type Auth, createAuth, type MailPort, type ResolvedSession, type StorageAdapter,} from "@authtempo/core";
/** API tokens need no config key: the token routes exist in every deployment. */export function createTokensAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string;}) { return createAuth({ baseURL: "https://api.example.com", trustedOrigins: [], secret: deps.secret, storage: deps.storage, mail: deps.mail, });}
/** * A route of the app that a script may call. `auth.caller` answers a session, * an API token, or an OAuth access token. `auth.session` answers sessions only, * so use it in a route that a token must not reach. */export async function whoami(auth: Auth, request: Request): Promise<Response> { const c = await auth.caller(request); // A client_credentials token and an organization token act for no user, so this route has no one to name. if (!c || c.kind === "oauth-client" || c.kind === "organizationToken") return Response.json({ error: "unauthorized" }, { status: 401 }); const res = Response.json({ kind: c.kind, email: c.user.email }); // After a sliding refresh, renew the cookie, or the browser drops it early. const renewed = c.kind === "session" ? auth.sessionCookie(request, c) : null; if (renewed) res.headers.append("set-cookie", renewed); return res;}
/** * A token with a quota of calls. No route takes a quota, so the app sets it * in process, for the session of the person. `api.tokens.create` applies no * fresh rule: the settings page calls `api.session.requireFresh` first. */export function createMeteredToken(auth: Auth, session: ResolvedSession, calls: number) { return auth.api.tokens.create({ session, name: "metered", quota: { remaining: calls } });}
/** * A route that answers the code of a refused token. `auth.caller` answers * null for each failure; `auth.authenticate` names it, such as * `token_exhausted` when the quota is spent. */export async function metered(auth: Auth, request: Request): Promise<Response> { const r = await auth.authenticate(request); if (!r.ok) return Response.json({ error: r.code }, { status: r.status }); return Response.json({ kind: r.value.kind });}- In the CLI, make a client with
credentials: "omit"and the token.
import { createClient } from "@authtempo/client";
/** * The client of a CLI. The token is the `tk_…` value that the person copied * from the app once. `credentials: "omit"`: a CLI has no cookie jar. */export function createCliClient(token: string, fetchImpl: typeof fetch = globalThis.fetch) { return createClient({ baseURL: "https://api.example.com", credentials: "omit", token: () => token, fetch: fetchImpl, });}- To meter a token, set its quota in process with
auth.api.tokens.create. - In a metered route, read the caller with
auth.authenticate(request)to answer the code of a refusal.
import { describe, expect, it } from "vitest";import { API, call, harness, signIn } from "../support/harness.ts";import { createMeteredToken, createTokensAuth, metered, whoami } from "./api-tokens.ts";import { createCliClient } from "./api-tokens-cli.ts";
describe("give a script an API token", () => { it("creates a token from a session, and the script reads who it is", async () => { const h = harness(); const auth = createTokensAuth(h); const ada = await signIn(auth, h, "ada@example.com"); const created = await call( auth, "POST", "/auth/tokens", { name: "ci", expiresInDays: 30 }, { cookie: ada }, ); const { token, apiToken } = (await created.json()) as { token: string; apiToken: { hint: string }; }; expect(token.startsWith("tk_")).toBe(true); expect(apiToken.hint).toBe(token.slice(3, 11));
const me = await whoami( auth, new Request(`${API}/whoami`, { headers: { authorization: `Bearer ${token}` } }), ); expect(await me.json()).toEqual({ kind: "token", email: "ada@example.com" });
const cli = createCliClient(token, ((input: RequestInfo | URL, init?: RequestInit) => auth.handle(new Request(input, init))) as typeof fetch); const current = await cli.tokens.current(); expect(current.ok && current.value.user.email).toBe("ada@example.com"); });
it("refuses a token where core needs a session, so a token cannot mint a token", async () => { const h = harness(); const auth = createTokensAuth(h); const ada = await signIn(auth, h, "ada@example.com"); const { token } = (await ( await call(auth, "POST", "/auth/tokens", { name: "ci" }, { cookie: ada }) ).json()) as { token: string; }; const again = await call( auth, "POST", "/auth/tokens", { name: "two" }, { authorization: `Bearer ${token}` }, ); expect(again.status).toBe(401); });
it("a token with a quota of 2 acts twice", async () => { const h = harness(); const auth = createTokensAuth(h); const ada = await signIn(auth, h, "ada@example.com"); const resolved = await auth.session( new Request(`${API}/settings`, { headers: { cookie: ada } }), ); if (!resolved) throw new Error("no session"); const created = await createMeteredToken(auth, resolved, 2); if (!created.ok) throw new Error(created.code); expect(created.value.apiToken.remaining).toBe(2);
const send = () => metered( auth, new Request(`${API}/report`, { headers: { authorization: `Bearer ${created.value.token}` }, }), ); expect(await (await send()).json()).toEqual({ kind: "token" }); expect(await (await send()).json()).toEqual({ kind: "token" }); const third = await send(); expect(third.status).toBe(429); expect(await third.json()).toEqual({ error: "token_exhausted" }); });});How it behaves
Section titled “How it behaves”- A token is
tk_plus 43 base64url characters. It belongs to one verified user and is never a session. auth.sessionanswers null to a token, so every core route that needs a session answers 401 to it. A token cannot create a token.- A token counts only in the
Authorizationheader, never in a cookie. expiresInDaysis 1 to 3650, and the default is 90.nullmeans no expiry.organizationIdbinds the token to one organization. When the membership ends,calleranswers null, and the token stays in the list.- A user holds at most 50 tokens.
- Create has one limit:
token-create:user:<userId>20 per hour. - A password reset, a password change, and a sign-out delete no token. The person revokes a token from the list.
- The create needs a fresh session. A stale one answers
session_not_fresh. Wrap the call inclient.withFresh. api.tokens.createtakes the session, and it applies no fresh rule. Callapi.session.requireFreshfirst. A session from before the proof of its address answersemail_unverified.
Scopes
Section titled “Scopes”permissionsnarrows a token to a statement set, such as{ project: ["read"] }. Each name must be a known action of Roles and permissions.nullor nopermissionsmeans the user’s own rights. A set needsorganizationsin the config.- A bound token holds a subset of its user’s set in the organization at its create. Else the create answers
forbidden_rank. - At each request, the token’s set is the intersection of its
permissionsand its user’s role now. So a demotion narrows the token at the next request. metadataholds the app’s own data, at most 4096 bytes as JSON. It never grants a right, and core never reads it.
The narrow-only update
Section titled “The narrow-only update”client.tokens.update({ id, name?, permissions?, expiresAt? }) changes a token, and it narrows only. A token has no refresh.
- A new set is a subset of the old one. A set over
nullis a narrow. nullover a set, a wider set, and a later expiry answerinvalid_body. So doesnullover a date.- The update needs a fresh session. A write that crosses another write of the token answers
conflict.
The window and the quota
Section titled “The window and the quota”These two limits are set in process only, with auth.api.tokens.create or auth.api.tokens.update. For an organization token, use auth.api.organizationTokens.create or auth.api.organizationTokens.update. No route takes them.
- The window
rateLimit: { seconds, max }counts each call of one token under the limittoken-use:tk:<tokenId>. An organization token counts undertoken-use:to:<tokenId>. Over the window, a call answersrate_limited. tokens.defaultRateLimitgives a window to each new token that names none. A token fromPOST /tokensalways gets it.- The quota
quota: { remaining, refillAmount?, refillSeconds? }counts the calls that the token has left. Each call spends one. At zero, a call answerstoken_exhausted. - A refill sets the count to
refillAmountwhenrefillSecondspassed since the last refill. It does not add to the count. - The window runs before the spend, so a refused call spends nothing.
- An update may lower
remainingor drop the refill, and nothing more.
The race rule
Section titled “The race rule”Each spend is one conditional write on the count. No spend takes the count below zero, also when calls arrive at the same moment.
- A spend that loses to another spend reads the row again and tries again, up to 20 tries.
- A lost try that sees no change answers
conflictat once. So does a spend after 20 lost tries. auth.callerandauth.authenticateon one request spend once.- On D1, one call of a user token runs at most 45 statements, and one call of an organization token at most 44. Both stay under the 50 queries of one Workers Free invocation.
Organization tokens
Section titled “Organization tokens”A to_ token belongs to an organization, not to a person. It acts with its own fixed permissions, never with the role of its creator.
client.organizations.tokens.create({ organizationId, name, permissions })needsapiToken:create, a fresh session, and a set that is a subset of yours.permissionsis required.{}grants nothing.nullanswersinvalid_body.- The list needs
apiToken:read, the updateapiToken:update, and the revokeapiToken:revoke. - An organization holds at most 50 live tokens. The create shares the limit
token-create:user:<userId>with user tokens. - The create reads the creator’s member row again under a lock of the organization. A create that crosses the creator’s removal answers
forbidden_rank. auth.calleranswers it askind: "organizationToken", withorganizationand nouser. Narrow the kind before you readcaller.user.GET /organizations/tokens/currenttakes ato_bearer only.
The creator rule
Section titled “The creator rule”- An organization token stays when its creator leaves the organization or deletes the account. The list shows
creatorIsMember: false. - The creator has no right of their own on the token. Only a member with
apiToken:revokerevokes it. client.organizations.members.remove({ organizationId, userId, revokeTokens: true })deletes the person’s organization tokens in the same write.revokeTokens: trueneedsapiToken:revokeand a fresh session. The removal of another member also needsmember:delete. A leave needs no other action.
Authenticate and its codes
Section titled “Authenticate and its codes”auth.authenticate(request) answers the caller of auth.caller as a result, or the code of the failure. auth.caller answers null for each code.
| Code | When |
|---|---|
unauthorized |
The token is unknown, expired, or revoked, or its user or membership is gone |
rate_limited |
The call is over the token’s window |
token_exhausted |
The token’s quota is zero |
token_retired |
The key has a prefix of tokens.movedPrefixes and no row |
conflict |
A lost spend saw no other spend, or 20 spends lost |
If it fails
Section titled “If it fails”unauthorized: the token is unknown, expired, or revoked, or a route needs a session.email_unverified: only a verified user creates a token.token_limit: the user holds 50 tokens. Revoke one first.organization_token_limit: the organization holds 50 live tokens. Revoke one first.not_found: the organization or the token does not belong to the caller.rate_limited: more than 20 creates in one hour, or a call over the token’s window.session_not_fresh: the session is older than the fresh window. Re-authenticate, then send it again.invalid_body: an unknown action, a set withorganizationsoff, or an update that widens.forbidden_rank: the set is wider than yours, or you lack theapiTokenaction. A create also answers it when its creator is no longer a member.token_exhausted: the quota is spent. Wait for the refill, or give a new quota.token_retired: a moved key has no row. Issue a new token.conflict: another write or spend changed the token at the same moment. Retry.last_owner:members.removewithrevokeTokens: truecannot remove the last owner.hook_refusedandhook_failed: thebeforeRemoveMemberhook ofmembers.removerefused the removal or threw.