Skip to content

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.

  1. On a settings page, call client.tokens.create({ name, expiresInDays }).
  2. Show the token of the answer once. Core stores its SHA-256 only, and no route shows it again.
  3. List the tokens with client.tokens.list(). The hint tells them apart.
  4. In each app route that a script may call, read the caller with auth.caller(request).
  5. In each app route that a token must not reach, read the caller with auth.session(request).
The config and a route for scripts
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 });
}
  1. In the CLI, make a client with credentials: "omit" and the token.
The client of a CLI
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,
});
}
  1. To meter a token, set its quota in process with auth.api.tokens.create.
  2. In a metered route, read the caller with auth.authenticate(request) to answer the code of a refusal.
Create, use, and meter a token as a test
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" });
});
});
  • A token is tk_ plus 43 base64url characters. It belongs to one verified user and is never a session.
  • auth.session answers 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 Authorization header, never in a cookie.
  • expiresInDays is 1 to 3650, and the default is 90. null means no expiry.
  • organizationId binds the token to one organization. When the membership ends, caller answers 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 in client.withFresh.
  • api.tokens.create takes the session, and it applies no fresh rule. Call api.session.requireFresh first. A session from before the proof of its address answers email_unverified.
  • permissions narrows a token to a statement set, such as { project: ["read"] }. Each name must be a known action of Roles and permissions.
  • null or no permissions means the user’s own rights. A set needs organizations in 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 permissions and its user’s role now. So a demotion narrows the token at the next request.
  • metadata holds the app’s own data, at most 4096 bytes as JSON. It never grants a right, and core never reads it.

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 null is a narrow.
  • null over a set, a wider set, and a later expiry answer invalid_body. So does null over a date.
  • The update needs a fresh session. A write that crosses another write of the token answers conflict.

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 limit token-use:tk:<tokenId>. An organization token counts under token-use:to:<tokenId>. Over the window, a call answers rate_limited.
  • tokens.defaultRateLimit gives a window to each new token that names none. A token from POST /tokens always gets it.
  • The quota quota: { remaining, refillAmount?, refillSeconds? } counts the calls that the token has left. Each call spends one. At zero, a call answers token_exhausted.
  • A refill sets the count to refillAmount when refillSeconds passed 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 remaining or drop the refill, and nothing more.

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 conflict at once. So does a spend after 20 lost tries.
  • auth.caller and auth.authenticate on 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.

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 }) needs apiToken:create, a fresh session, and a set that is a subset of yours.
  • permissions is required. {} grants nothing. null answers invalid_body.
  • The list needs apiToken:read, the update apiToken:update, and the revoke apiToken: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.caller answers it as kind: "organizationToken", with organization and no user. Narrow the kind before you read caller.user.
  • GET /organizations/tokens/current takes a to_ bearer only.
  • 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:revoke revokes it.
  • client.organizations.members.remove({ organizationId, userId, revokeTokens: true }) deletes the person’s organization tokens in the same write.
  • revokeTokens: true needs apiToken:revoke and a fresh session. The removal of another member also needs member:delete. A leave needs no other action.

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
  • 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 with organizations off, or an update that widens.
  • forbidden_rank: the set is wider than yours, or you lack the apiToken action. 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.remove with revokeTokens: true cannot remove the last owner.
  • hook_refused and hook_failed: the beforeRemoveMember hook of members.remove refused the removal or threw.