⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
fix(auth): revoke sessions on password reset and expire API keys (#358)
Egor Vasilyev0e6e5b8b19d1
diff --git a/apps/api/src/__tests__/integration/api-keys.test.ts b/apps/api/src/__tests__/integration/api-keys.test.tsnew file mode 100644index 00000000..823d1fa8--- /dev/null+++ b/apps/api/src/__tests__/integration/api-keys.test.ts@@ -0,0 +1,143 @@+import { describe, it, expect, beforeEach } from 'bun:test';+import { auth, API_KEY_DEFAULT_EXPIRES_IN_SEC } from '@repo/auth';+import { apikey, db } from '@repo/db';+import { eq } from 'drizzle-orm';+import { apiKeyApi, app } from '#tests/helpers/app';+import { signUpTestUser } from '#tests/helpers/auth';+import { resetDb } from '#tests/helpers/db';++// A personal API key is a full-account credential, so one that was forgotten has+// to stop working on its own: every key gets an expiry, an expired one is refused,+// and the expiry cannot be changed once the key exists.++const DAY_SEC = 24 * 60 * 60;++// The key endpoints live behind the better-auth catch-all, which Eden Treaty does+// not model. A request carrying the session cookie also has to carry a trusted+// origin, as the browser's does.+const origin = (process.env.APP_URL ?? '').split(',')[0].trim();++function authRequest(path: string, headers: Record<string, string>, body: object) {+ return app.handle(+ new Request(`http://localhost/api/auth/api-key/${path}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', origin, ...headers },+ body: JSON.stringify(body),+ }),+ );+}++// Asserts that the moment is `seconds` from now, give or take the test's own run time.+function expectSecondsFromNow(value: string | Date | null | undefined, seconds: number) {+ expect(value).toBeTruthy();+ const distance = new Date(value!).getTime() - Date.now();+ expect(Math.abs(distance - seconds * 1000)).toBeLessThan(60_000);+}++describe('api keys', () => {+ beforeEach(resetDb);++ it('gives a key created without a lifetime the default one', async () => {+ const user = await signUpTestUser();++ const res = await authRequest('create', { cookie: user.cookie }, { name: 'ci' });++ expect(res.status).toBe(200);+ const created = (await res.json()) as { expiresAt: string | null };+ expectSecondsFromNow(created.expiresAt, API_KEY_DEFAULT_EXPIRES_IN_SEC);+ });++ it('accepts a shorter lifetime and refuses one past the maximum', async () => {+ const user = await signUpTestUser();++ const short = await authRequest(+ 'create',+ { cookie: user.cookie },+ { name: 'short', expiresIn: 30 * DAY_SEC },+ );+ expect(short.status).toBe(200);+ expectSecondsFromNow(((await short.json()) as { expiresAt: string }).expiresAt, 30 * DAY_SEC);++ const long = await authRequest(+ 'create',+ { cookie: user.cookie },+ { name: 'long', expiresIn: 366 * DAY_SEC },+ );+ expect(long.status).toBe(400);+ });++ it('refuses a key past its expiry', async () => {+ const user = await signUpTestUser();+ const created = await auth.api.createApiKey({ body: { userId: user.userId, name: 'ci' } });+ expect((await apiKeyApi(created.key).projects.get()).status).toBe(200);++ await db+ .update(apikey)+ .set({ expiresAt: new Date(Date.now() - 1000) })+ .where(eq(apikey.id, created.id));++ expect((await apiKeyApi(created.key).projects.get()).status).toBe(401);++ // The plugin reports an expired key by throwing, which /me would otherwise+ // answer with a 500 instead of the "not signed in" it documents.+ const me = await apiKeyApi(created.key).me.get();+ expect(me.status).toBe(200);+ expect(me.data).toEqual({ authenticated: false });+ });++ it('refuses creating a key from a key', async () => {+ const user = await signUpTestUser();+ const created = await auth.api.createApiKey({ body: { userId: user.userId, name: 'ci' } });++ const res = await authRequest('create', { 'x-api-key': created.key }, { name: 'second' });++ expect(res.status).toBe(403);+ expect(await db.$count(apikey, eq(apikey.referenceId, user.userId))).toBe(1);+ });++ it('refuses changing the expiry of a key, with the key itself included', async () => {+ const user = await signUpTestUser();+ const created = await auth.api.createApiKey({ body: { userId: user.userId, name: 'ci' } });++ const cleared = await authRequest(+ 'update',+ { cookie: user.cookie },+ { keyId: created.id, expiresIn: null },+ );+ expect(cleared.status).toBe(403);++ const extended = await authRequest(+ 'update',+ { 'x-api-key': created.key },+ { keyId: created.id, expiresIn: 365 * DAY_SEC },+ );+ expect(extended.status).toBe(403);++ const renamed = await authRequest(+ 'update',+ { cookie: user.cookie },+ { keyId: created.id, name: 'renamed' },+ );+ expect(renamed.status).toBe(200);+ expectSecondsFromNow(+ ((await renamed.json()) as { expiresAt: string }).expiresAt,+ API_KEY_DEFAULT_EXPIRES_IN_SEC,+ );+ });++ it('lists a key with its expiry', async () => {+ const user = await signUpTestUser();+ await auth.api.createApiKey({ body: { userId: user.userId, name: 'ci' } });++ const res = await app.handle(+ new Request('http://localhost/api/auth/api-key/list', {+ headers: { cookie: user.cookie, origin },+ }),+ );++ expect(res.status).toBe(200);+ const body = (await res.json()) as { apiKeys: Array<{ expiresAt: string | null }> };+ expect(body.apiKeys).toHaveLength(1);+ expectSecondsFromNow(body.apiKeys[0].expiresAt, API_KEY_DEFAULT_EXPIRES_IN_SEC);+ });+});diff --git a/apps/api/src/__tests__/integration/password-reset.test.ts b/apps/api/src/__tests__/integration/password-reset.test.tsnew file mode 100644index 00000000..fb0d311f--- /dev/null+++ b/apps/api/src/__tests__/integration/password-reset.test.ts@@ -0,0 +1,35 @@+import { describe, it, expect, beforeEach } from 'bun:test';+import { auth } from '@repo/auth';+import { db, verification } from '@repo/db';+import { like } from 'drizzle-orm';+import { authedApi } from '#tests/helpers/app';+import { signUpTestUser } from '#tests/helpers/auth';+import { resetDb } from '#tests/helpers/db';++// The reset link goes out by mail, and no provider is configured in tests, so the+// token is read from the verification row better-auth wrote for it.+async function resetToken(): Promise<string> {+ const rows = await db+ .select({ identifier: verification.identifier })+ .from(verification)+ .where(like(verification.identifier, 'reset-password:%'));+ expect(rows).toHaveLength(1);+ return rows[0].identifier.slice('reset-password:'.length);+}++describe('password reset', () => {+ beforeEach(resetDb);++ it('ends every session opened before the reset', async () => {+ const user = await signUpTestUser({ password: 'old-password-123' });+ const asUser = authedApi(user.cookie);+ expect((await asUser.projects.get()).status).toBe(200);++ await auth.api.requestPasswordReset({ body: { email: user.email } });+ await auth.api.resetPassword({+ body: { token: await resetToken(), newPassword: 'new-password-456' },+ });++ expect((await asUser.projects.get()).status).toBe(401);+ });+});diff --git a/apps/api/src/app.ts b/apps/api/src/app.tsindex 0ffa3423..82cfaf78 100644--- a/apps/api/src/app.ts+++ b/apps/api/src/app.ts@@ -1,5 +1,6 @@import {auth,+ getSessionFromHeaders,oAuthDiscoveryMetadata,oAuthProtectedResourceMetadata,trustedOrigins,@@ -238,7 +239,7 @@ export const app = new Elysia().get('/me',async ({ request }) => {- const session = await auth.api.getSession({ headers: request.headers });+ const session = await getSessionFromHeaders(request.headers);// A deactivated account is not signed in as far as the app is concerned:// every planner route answers 401 for it, and this is what the screens ask// first. Deactivation arrives over SCIM, after the session was opened.diff --git a/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.tsindex ded4f762..96552828 100644--- a/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts+++ b/apps/api/src/modules/agents/core/__tests__/integration/ai-agents.test.ts@@ -1,4 +1,6 @@import { describe, it, expect, beforeEach } from 'bun:test';+import { apikey, db } from '@repo/db';+import { eq } from 'drizzle-orm';import { apiKeyApi, authedApi, type Api } from '#tests/helpers/app';import { createRole, listProjectRoles } from '#tests/helpers/roles';import { addProjectMember } from '#tests/helpers/members';@@ -426,6 +428,28 @@ describe('ai agents', () => {expect(res.data?.apiKey).not.toBe(created.data?.apiKey);});+ // A personal key expires; an agent replays its key with nothing that would renew+ // it, so the one issued at creation and the one regenerate-key issues carry none.+ it('issues the agent key without an expiry', async () => {+ const { asOwner, teamId } = await setup();+ const created = await createAgent(asOwner, 'MKT', {+ name: 'Bot',+ username: 'bot',+ kind: 'external',+ });+ const agent = created.data!.agent;+ const expiries = () =>+ db+ .select({ expiresAt: apikey.expiresAt })+ .from(apikey)+ .where(eq(apikey.referenceId, agent.userId));++ expect(await expiries()).toEqual([{ expiresAt: null }]);++ await agents(asOwner, teamId)({ agentId: agent.id })['regenerate-key'].post();+ expect(await expiries()).toEqual([{ expiresAt: null }]);+ });+it('rejects regenerating the key on an internal agent with 400', async () => {const { asOwner, teamId } = await setup();const created = await createAgent(asOwner, 'MKT', {diff --git a/apps/api/src/modules/agents/core/service.ts b/apps/api/src/modules/agents/core/service.tsindex 2d98cb36..7d802af5 100644--- a/apps/api/src/modules/agents/core/service.ts+++ b/apps/api/src/modules/agents/core/service.ts@@ -560,8 +560,14 @@ async function assertUsernameFree(// Issues a fresh API key owned by the agent's bot user and returns its plaintext// value (only available at creation). The server-side call sets the owner via// userId — better-auth allows this only for a direct (non-request) server call.+//+// The key carries no expiry, unlike a personal one: an internal agent replays its+// stored secret with nothing that would renew it, and an external agent's key is+// rotated by its operator through regenerate-key. The plugin puts its default on+// every key it creates, so the expiry is cleared on the row afterwards.async function issueKey(userId: string, name: string): Promise<string> {const created = await auth.api.createApiKey({ body: { userId, name: `agent:${name}` } });+ await db.update(apikey).set({ expiresAt: null }).where(eq(apikey.id, created.id));return created.key;}diff --git a/apps/api/src/shared/auth-context.ts b/apps/api/src/shared/auth-context.tsindex 3ec16b33..59ef2410 100644--- a/apps/api/src/shared/auth-context.ts+++ b/apps/api/src/shared/auth-context.ts@@ -2,7 +2,7 @@ import { Elysia } from 'elysia';import { db } from '@repo/db';import { user as users } from '@repo/db/schema';import { eq } from 'drizzle-orm';-import { auth } from '@repo/auth';+import { auth, getSessionFromHeaders } from '@repo/auth';import { HttpError } from './lib';import { getMcpOAuthToken } from './mcp-request';@@ -36,7 +36,7 @@ export type SessionUser = SessionResult['user'];export const authContext = new Elysia({ name: 'auth-context' }).resolve({ as: 'scoped' },async ({ request, path }): Promise<{ user: SessionUser | null }> => {- const session = await auth.api.getSession({ headers: request.headers });+ const session = await getSessionFromHeaders(request.headers);if (session) {if (session.user.active === false) throw new HttpError(401, 'This account is deactivated');return { user: session.user };diff --git a/apps/web/messages/ar/apiKeys.json b/apps/web/messages/ar/apiKeys.jsonindex d48fd23b..45526eb6 100644--- a/apps/web/messages/ar/apiKeys.json+++ b/apps/web/messages/ar/apiKeys.json@@ -7,12 +7,17 @@"empty": "مفيش مفاتيح لسه. اعمل واحد عشان توثّق طلباتك لواجهة البرمجة (API).","fallbackName": "مفتاح واجهة برمجة","createdAt": "أُنشئ {date}",+ "expiresAt": "ينتهي {date}",+ "noExpiry": "بدون انتهاء","deleteAction": "حذف المفتاح","createDialog": {"title": "إنشاء مفتاح واجهة برمجة","nameLabel": "الاسم","namePlaceholder": "مثال: خط CI","nameHint": "اسم يعرّفك بالمفتاح ده بعدين.",+ "expiryLabel": "ينتهي بعد",+ "expiresInDays": "{days} يوم",+ "expiryHint": "المفتاح هيقف عن الشغل في اليوم ده. اعمل واحد جديد عشان تكمّل.","submit": "إنشاء المفتاح","submitPending": "جارٍ الإنشاء…","error": "تعذّر إنشاء المفتاح."diff --git a/apps/web/messages/en/apiKeys.json b/apps/web/messages/en/apiKeys.jsonindex c8d95fae..4473ff87 100644--- a/apps/web/messages/en/apiKeys.json+++ b/apps/web/messages/en/apiKeys.json@@ -7,12 +7,17 @@"empty": "No API keys yet. Create one to authenticate requests to the API.","fallbackName": "API key","createdAt": "Created {date}",+ "expiresAt": "Expires {date}",+ "noExpiry": "Does not expire","deleteAction": "Delete API key","createDialog": {"title": "Create API key","nameLabel": "Name","namePlaceholder": "e.g. CI pipeline","nameHint": "A label to recognize this key later.",+ "expiryLabel": "Expires in",+ "expiresInDays": "{days} days",+ "expiryHint": "The key stops working on that day. Create a new one to keep going.","submit": "Create key","submitPending": "Creating…","error": "Could not create API key."diff --git a/apps/web/messages/fr/apiKeys.json b/apps/web/messages/fr/apiKeys.jsonindex cdea0e24..e8634f03 100644--- a/apps/web/messages/fr/apiKeys.json+++ b/apps/web/messages/fr/apiKeys.json@@ -7,12 +7,17 @@"empty": "Aucune clé d'API pour l'instant. Créez-en une pour authentifier vos requêtes à l'API.","fallbackName": "Clé d'API","createdAt": "Créée {date}",+ "expiresAt": "Expire {date}",+ "noExpiry": "N'expire pas","deleteAction": "Supprimer la clé d'API","createDialog": {"title": "Créer une clé d'API","nameLabel": "Nom","namePlaceholder": "ex. pipeline CI","nameHint": "Un libellé pour reconnaître cette clé plus tard.",+ "expiryLabel": "Expire dans",+ "expiresInDays": "{days} jours",+ "expiryHint": "La clé cesse de fonctionner ce jour-là. Créez-en une nouvelle pour continuer.","submit": "Créer la clé","submitPending": "Création…","error": "Impossible de créer la clé d'API."diff --git a/apps/web/messages/pt-BR/apiKeys.json b/apps/web/messages/pt-BR/apiKeys.jsonindex 9d370660..52a65e2f 100644--- a/apps/web/messages/pt-BR/apiKeys.json+++ b/apps/web/messages/pt-BR/apiKeys.json@@ -7,12 +7,17 @@"empty": "Nenhuma chave de API ainda. Crie uma para autenticar requisições à API.","fallbackName": "Chave de API","createdAt": "Criada em {date}",+ "expiresAt": "Expira em {date}",+ "noExpiry": "Não expira","deleteAction": "Excluir chave de API","createDialog": {"title": "Criar chave de API","nameLabel": "Nome","namePlaceholder": "ex. pipeline de CI","nameHint": "Um rótulo para reconhecer esta chave depois.",+ "expiryLabel": "Expira em",+ "expiresInDays": "{days} dias",+ "expiryHint": "A chave deixa de funcionar nesse dia. Crie uma nova para continuar.","submit": "Criar chave","submitPending": "Criando…","error": "Não foi possível criar a chave de API."diff --git a/apps/web/messages/ru/apiKeys.json b/apps/web/messages/ru/apiKeys.jsonindex a4f40942..9288340b 100644--- a/apps/web/messages/ru/apiKeys.json+++ b/apps/web/messages/ru/apiKeys.json@@ -7,12 +7,17 @@"empty": "API-ключей пока нет. Создайте ключ, чтобы аутентифицировать запросы к API.","fallbackName": "API-ключ","createdAt": "Создан {date}",+ "expiresAt": "Истекает {date}",+ "noExpiry": "Бессрочный","deleteAction": "Удалить API-ключ","createDialog": {"title": "Создать API-ключ","nameLabel": "Название","namePlaceholder": "напр. CI pipeline","nameHint": "Подпись, по которой вы узнаете этот ключ позже.",+ "expiryLabel": "Срок действия",+ "expiresInDays": "{days} дней",+ "expiryHint": "В этот день ключ перестанет работать. Чтобы продолжить, создайте новый.","submit": "Создать ключ","submitPending": "Создание…","error": "Не удалось создать API-ключ."diff --git a/apps/web/messages/uk/apiKeys.json b/apps/web/messages/uk/apiKeys.jsonindex e1e73d62..0d84c568 100644--- a/apps/web/messages/uk/apiKeys.json+++ b/apps/web/messages/uk/apiKeys.json@@ -7,12 +7,17 @@"empty": "API-ключів ще немає. Створіть ключ, щоб автентифікувати запити до API.","fallbackName": "API-ключ","createdAt": "Створено {date}",+ "expiresAt": "Діє до {date}",+ "noExpiry": "Безстроковий","deleteAction": "Видалити API-ключ","createDialog": {"title": "Створити API-ключ","nameLabel": "Назва","namePlaceholder": "напр. CI pipeline","nameHint": "Підпис, за яким ви впізнаєте цей ключ згодом.",+ "expiryLabel": "Термін дії",+ "expiresInDays": "{days} днів",+ "expiryHint": "Того дня ключ перестане працювати. Щоб продовжити, створіть новий.","submit": "Створити ключ","submitPending": "Створення…","error": "Не вдалося створити API-ключ."diff --git a/apps/web/messages/zh-CN/apiKeys.json b/apps/web/messages/zh-CN/apiKeys.jsonindex 27878dd9..b460acf4 100644--- a/apps/web/messages/zh-CN/apiKeys.json+++ b/apps/web/messages/zh-CN/apiKeys.json@@ -7,12 +7,17 @@"empty": "暂无 API 密钥。创建密钥以验证 API 请求。","fallbackName": "API 密钥","createdAt": "创建于 {date}",+ "expiresAt": "到期于 {date}",+ "noExpiry": "永不过期","deleteAction": "删除 API 密钥","createDialog": {"title": "创建 API 密钥","nameLabel": "名称","namePlaceholder": "例如:CI 流水线","nameHint": "用于以后识别此密钥的名称。",+ "expiryLabel": "有效期",+ "expiresInDays": "{days} 天",+ "expiryHint": "到期当天密钥将停止工作。如需继续使用,请创建新密钥。","submit": "创建密钥","submitPending": "正在创建…","error": "无法创建 API 密钥。"diff --git a/apps/web/src/features/api-keys/components/ApiKeysCreateDialog.tsx b/apps/web/src/features/api-keys/components/ApiKeysCreateDialog.tsxindex ae7237fd..ebfb8b83 100644--- a/apps/web/src/features/api-keys/components/ApiKeysCreateDialog.tsx+++ b/apps/web/src/features/api-keys/components/ApiKeysCreateDialog.tsx@@ -8,6 +8,19 @@ import { apiKey } from '@/lib/auth-client';import Modal from '@/components/common/overlay/Modal';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';++// Lifetimes offered at creation, in days. The server caps a key at a year, and 90+// days is the default it applies when none is sent.+const EXPIRY_DAYS = [30, 90, 180, 365] as const;+const DEFAULT_EXPIRY_DAYS = 90;+const DAY_SEC = 24 * 60 * 60;// The created key value is kept in this dialog only, never lifted into page state:// it is shown once, right after creation, and cannot be retrieved later.@@ -21,6 +34,7 @@ export default function ApiKeysCreateDialog({const t = useTranslations('apiKeys');const tCommon = useTranslations('common');const [name, setName] = useState('');+ const [expiryDays, setExpiryDays] = useState(String(DEFAULT_EXPIRY_DAYS));const [createdKey, setCreatedKey] = useState<string | null>(null);const [copied, setCopied] = useState(false);@@ -28,7 +42,10 @@ export default function ApiKeysCreateDialog({// Own the error UI inline, so opt out of the global error toast.meta: { suppressErrorToast: true },mutationFn: async () => {- const { data, error } = await apiKey.create({ name: name.trim() });+ const { data, error } = await apiKey.create({+ name: name.trim(),+ expiresIn: Number(expiryDays) * DAY_SEC,+ });if (error) throw new Error(error.message ?? t('createDialog.error'));return data;},@@ -104,6 +121,25 @@ export default function ApiKeysCreateDialog({<p className="text-xs text-muted-foreground">{t('createDialog.nameHint')}</p></div>+ <div className="space-y-1.5">+ <label htmlFor="api-key-expiry" className="text-sm font-medium">+ {t('createDialog.expiryLabel')}+ </label>+ <Select value={expiryDays} onValueChange={setExpiryDays}>+ <SelectTrigger id="api-key-expiry">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {EXPIRY_DAYS.map((days) => (+ <SelectItem key={days} value={String(days)}>+ {t('createDialog.expiresInDays', { days })}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <p className="text-xs text-muted-foreground">{t('createDialog.expiryHint')}</p>+ </div>+{createMutation.error && (<p className="text-sm text-destructive">{createMutation.error.message}</p>)}diff --git a/apps/web/src/features/api-keys/components/ApiKeysItem.tsx b/apps/web/src/features/api-keys/components/ApiKeysItem.tsxindex a3a006d0..169b18ce 100644--- a/apps/web/src/features/api-keys/components/ApiKeysItem.tsx+++ b/apps/web/src/features/api-keys/components/ApiKeysItem.tsx@@ -36,6 +36,10 @@ export default function ApiKeysItem({<ItemDescription>{apiKey.start ? `${apiKey.start}… · ` : ''}{t('createdAt', { date: formatShortDate(apiKey.createdAt) })}+ {' · '}+ {apiKey.expiresAt+ ? t('expiresAt', { date: formatShortDate(apiKey.expiresAt) })+ : t('noExpiry')}</ItemDescription></ItemContent><ItemActions>diff --git a/apps/web/src/features/api-keys/services/apiKeys.service.ts b/apps/web/src/features/api-keys/services/apiKeys.service.tsindex 97ac5262..f89182f5 100644--- a/apps/web/src/features/api-keys/services/apiKeys.service.ts+++ b/apps/web/src/features/api-keys/services/apiKeys.service.ts@@ -11,6 +11,8 @@ export type ApiKeyRow = {name?: string | null;start?: string | null;createdAt: string;+ // Null on a key issued before keys carried an expiry.+ expiresAt: string | null;};// Goes through the auth client, not plain fetch, so better-auth's baseURL and the@@ -24,6 +26,7 @@ async function fetchApiKeys(loadFailed: string): Promise<ApiKeyRow[]> {name: key.name,start: key.start,createdAt: new Date(key.createdAt).toISOString(),+ expiresAt: key.expiresAt ? new Date(key.expiresAt).toISOString() : null,}));}diff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.mdindex 8eac3805..a9c5d2ec 100644--- a/packages/auth/AGENTS.md+++ b/packages/auth/AGENTS.md@@ -7,7 +7,10 @@ The **server-side** better-auth instance. Consumed by `apps/api`. See root `AGEN`requireEmailVerification: false`, `autoSignIn: true`), plus the WebAuthn passkeyplugin (`@better-auth/passkey`).- Exports `auth`, `USER_ROLES` / `UserRole`, `generateUsername` (the SCIM module derives a- handle with the same rule), plus `Auth` / `Session` types.+ handle with the same rule), `getSessionFromHeaders`, plus `Auth` / `Session` types.+- `emailAndPassword.revokeSessionsOnPasswordReset` is `true`: a reset ends every session+ of that account, since a reset is how a stolen password is dealt with. The signed-in+ change-password form in the web app sends `revokeOtherSessions` for the same reason.## User role@@ -167,6 +170,33 @@ social callback turns that into the `?error=` it redirects with; without one thefails the request instead. Agent bot users are written with a direct insert and neverreach the hook.+## API keys++`apiKey({ enableSessionForAPIKeys: true })` makes an `x-api-key` header resolve to the+owner's session, so a key is a full-account credential. It therefore expires:+`keyExpiration.defaultExpiresIn` is 90 days and `maxExpiresIn` is a year, and the create+dialog in the web app offers 30/90/180/365 days. The plugin's option is documented as+milliseconds but its handler passes the value to `getDate(value, "sec")`, so+`API_KEY_DEFAULT_EXPIRES_IN_SEC` is in seconds; `maxExpiresIn` is in days, as the plugin+reads it. Keys issued before this stay `expires_at` NULL and keep working.++The expiry only holds if a key cannot renew itself, and a request carrying one resolves to+the owner's session on every key endpoint. So `hooks.before` refuses both ways round it: an+`/api-key/update` that carries `expiresIn`, and an `/api-key/create` sent with an+`x-api-key` header. Keys are issued from a signed-in session; a longer life is a new key.+The refusal reads `ctx.request`, which a server-side `auth.api.createApiKey` does not+carry, so `issueKey` is unaffected.++An agent's key is the exception and carries no expiry — an agent replays its stored secret+with nothing that would renew it, and an external agent's operator rotates it through+`regenerate-key`. The plugin applies the default to every key it creates, so `issueKey` in+`apps/api/src/modules/agents/core/service.ts` clears `expires_at` on the row afterwards.++A key the plugin will not accept makes it throw out of `auth.api.getSession` rather than+return no session. `getSessionFromHeaders` turns that back into "no session", so an expired+key is answered with a 401 instead of a 500. Use it instead of `auth.api.getSession` where+a request may carry a key.+## OpenAPI referenceThe `openAPI()` plugin (`better-auth/plugins`) documents the auth handler. It serves adiff --git a/packages/auth/src/index.ts b/packages/auth/src/index.tsindex 68d2189d..d373c159 100644--- a/packages/auth/src/index.ts+++ b/packages/auth/src/index.ts@@ -251,6 +251,13 @@ export async function generateUsername(email: string): Promise<string> {return candidate;}+// Personal API key lifetime. The plugin's option is typed as milliseconds but the+// handler applies it as seconds (the same unit as the `expiresIn` a client sends),+// so it is held in seconds here. The maximum is in days, as the plugin reads it.+const DAY_SEC = 24 * 60 * 60;+export const API_KEY_DEFAULT_EXPIRES_IN_SEC = 90 * DAY_SEC;+export const API_KEY_MAX_EXPIRES_IN_DAYS = 365;+export const auth = betterAuth({baseURL,secret: process.env.BETTER_AUTH_SECRET,@@ -277,6 +284,10 @@ export const auth = betterAuth({// lock out every account the moment the setting is flipped off).requireEmailVerification: false,autoSignIn: true,+ // A reset is how a stolen password is dealt with, so every session opened with+ // the old one ends with it. The signed-in change-password form sends+ // revokeOtherSessions for the same reason.+ revokeSessionsOnPasswordReset: true,sendResetPassword: async ({ user, url }) => {await sendAuthEmail({to: user.email,@@ -437,6 +448,29 @@ export const auth = betterAuth({message: 'Username is already taken. Please try another.',});}+ return;+ }++ // A key resolves to its owner's session, so a request carrying a leaked key+ // reaches the key endpoints. It may not issue another one: a new key starts a+ // fresh lifetime, which is the expiry of the leaked key renewed under a+ // different row. Issuing a key is left to a signed-in session. The server-side+ // call that issues an agent's key carries no request and is unaffected.+ if (ctx.path === '/api-key/create' && ctx.request?.headers.get('x-api-key')) {+ throw new APIError('FORBIDDEN', {+ message: 'An API key cannot create another API key. Sign in to create one.',+ });+ }++ // The lifetime is fixed at creation for the same reason; a longer one is a new+ // key, created from a session.+ if (ctx.path === '/api-key/update') {+ const body = ctx.body as { expiresIn?: number | null } | undefined;+ if (body && body.expiresIn !== undefined) {+ throw new APIError('FORBIDDEN', {+ message: 'The expiry of an API key cannot be changed. Create a new key instead.',+ });+ }}}),},@@ -542,6 +576,13 @@ export const auth = betterAuth({// Brand prefix so a leaked key is identifiable by secret scanners and in logs.// The trailing underscore separates it from the random part (itp_<64 chars>).defaultPrefix: 'itp_',+ // A key is a full-account credential, so one that was forgotten stops working+ // on its own. The caller may pick a shorter or longer life up to the maximum;+ // an agent's key is the exception, cleared where it is issued in apps/api.+ keyExpiration: {+ defaultExpiresIn: API_KEY_DEFAULT_EXPIRES_IN_SEC,+ maxExpiresIn: API_KEY_MAX_EXPIRES_IN_DAYS,+ },rateLimit: {enabled: true,timeWindow: 1000,@@ -638,6 +679,25 @@ export const auth = betterAuth({export type Auth = typeof auth;export type Session = Auth['$Infer']['Session'];+// A key the apiKey plugin will not accept — expired, revoked or malformed — makes+// it throw out of getSession instead of returning no session, which a caller can+// only report as a 500. Such a request carries no session, so it is answered as+// one, and a key that reached its expiry is refused like any other unauthenticated+// request. A refusal for another reason, a rate-limited key among them, still+// propagates: it is not the same answer.+export async function getSessionFromHeaders(+ headers: Headers,+): Promise<Awaited<ReturnType<typeof auth.api.getSession>>> {+ try {+ return await auth.api.getSession({ headers });+ } catch (error) {+ if (error instanceof APIError && (error.statusCode === 401 || error.statusCode === 403)) {+ return null;+ }+ throw error;+ }+}+// Instance-wide authentication settings (registration mode, mail provider, invite// links). Read here by the sign-up gate and the mail senders; managed over HTTP by// god mode in apps/api.