import { betterAuth } from 'better-auth/minimal'; import { drizzleAdapter } from 'better-auth/adapters/drizzle'; import { sveltekitCookies } from 'better-auth/svelte-kit'; import { APIError } from 'better-auth/api'; import { admin } from 'better-auth/plugins/admin'; import { defaultAc } from 'better-auth/plugins/admin/access'; import { getRequestEvent } from '$app/server'; import { BETTER_AUTH_SECRET } from '$app/env/private'; import { DEFAULT_BODY_FONT } from '#lib/body-font.ts'; import { addAuthTransactionValidator, authDb } from './auth-transaction.ts'; import { tables } from './db/index.ts'; import { getMailer, resetLink, resetMessage } from './mail.ts'; import { isFirstAccount, signupAllowed } from './instance.ts'; import { passkeyPlugin } from './passkeys.ts'; import { declaredAddress, declaredOrigin } from './trusted-origin.ts'; /** * A missing secret gets a random value for this process: sessions then end on * restart, the honest trade for an operator who set none. The container writes a * persistent secret on first start, so a real deployment never reaches this path. */ const secret = BETTER_AUTH_SECRET ?? (() => { console.warn( '[fablewright] BETTER_AUTH_SECRET is not set. Sessions will not survive a restart.' ); return crypto.randomUUID() + crypto.randomUUID(); })(); /* * The instance console creates accounts, sets a password, disables an account * and changes a role; nothing in the app impersonates, lists another writer's * sessions or deletes an account through the plugin. Granting only those five * permissions turns a call the route gate missed into a 403 rather than a way * around the project and account rules. */ const ADMIN_ROLES = { admin: defaultAc.newRole({ user: ['create', 'ban', 'set-password', 'set-role'], session: ['revoke'] }), user: defaultAc.newRole({ user: [], session: [] }) }; const ADMIN_PATHS = [ '/admin/set-role', '/admin/get-user', '/admin/create-user', '/admin/update-user', '/admin/list-users', '/admin/list-user-sessions', '/admin/unban-user', '/admin/ban-user', '/admin/impersonate-user', '/admin/stop-impersonating', '/admin/revoke-user-session', '/admin/revoke-user-sessions', '/admin/remove-user', '/admin/set-user-password', '/admin/has-permission' ]; function assertSignupOpenOrThrow() { if (!signupAllowed()) { throw new APIError('FORBIDDEN', { message: 'Sign-up is closed on this instance. Ask the admin for an account.' }); } } export const auth = betterAuth({ appName: 'Fablewright', advanced: { disableOriginCheck: false, /* * `server.js` rewrites this header to one address from the socket or the * trusted proxy chain, so a client cannot choose its own rate-limit bucket or * the address a session records. Pinned here so an upgrade that changes the * default cannot quietly start reading a different header. */ ipAddress: { ipAddressHeaders: ['x-forwarded-for'] } }, // With no declared origin, better-auth derives one per request, which is what // makes a bare `docker run -p 3000:3000` work. ...(declaredOrigin() ? { baseURL: declaredOrigin() } : {}), /* * A sign-in request carries an `Origin` header, and the instance must accept the * origin the request actually arrived on, or a fresh install with no `ORIGIN` set * refuses every login from its own address. A declared origin is the only one * trusted; without one, the adapter's request URL supplies the scheme and host, * so a TLS-terminating proxy must forward the public scheme for it to be right. */ trustedOrigins: (request) => { const declared = declaredOrigin(); if (declared) return [declared]; return request ? [new URL(request.url).origin] : []; }, secret, database: drizzleAdapter(authDb, { provider: 'sqlite', /* * No `transaction: true`. The library's transactions need an adapter that can * await, and this driver is the synchronous `node-sqlite` one: `db.transaction` * calls the callback and commits before an async callback settles, so the * setting would open a `begin` around nothing and make a broken guarantee look * kept. `auth-transaction.ts` joins the pairs of writes that must land together * by hand instead. See `docs/landmines.md`. */ schema: { user: tables.user, session: tables.session, account: tables.account, verification: tables.verification, passkey: tables.passkey } }), user: { additionalFields: { /** The prose face. `src/lib/body-font.ts` decides what the value means. */ bodyFont: { type: 'string', required: false, defaultValue: DEFAULT_BODY_FONT }, /** * Whether unsaved words carry heat. No value means the device's * reduced-motion setting decides; `src/lib/preferences.ts` reads it. */ heat: { type: 'string', required: false } } }, emailAndPassword: { enabled: true, minPasswordLength: 10, // Verification stays off. A mailer can be absent, and an instance behind a // closed relay must still be usable the moment it is claimed. requireEmailVerification: false, /* * A new password through the reset link ends every session: recovery is the * moment to evict whoever else was signed in, and the only moment a password * changes without the old one being known. */ revokeSessionsOnPasswordReset: true, /* * Mail is optional. With a mailer and a declared address the link arrives by * email; without either it goes to the server log, which is why the accounts * screen can also set a password directly. This must never throw: a failed send * turns an endpoint that always answers 200 into a way to learn which * addresses have accounts. */ sendResetPassword: async ({ user, token }) => { /* * The link is built from the declared address, never from better-auth's * `url`, which carries the host the reset request arrived on. That request * proves nothing about the person who will open the mail. */ const address = declaredAddress(); const link = resetLink(token, address); const mailer = getMailer(); if (!mailer || !address) { console.info(`[fablewright] password reset for ${user.email}: ${link}`); return; } try { await mailer.send({ ...resetMessage(link), to: user.email }); } catch (error) { console.error('[fablewright] could not send the reset email:', error); console.info(`[fablewright] password reset for ${user.email}: ${link}`); } } }, /* * Every account passes through the `user.create.before` hook, so the sign-up * rule lives here rather than in a page. The first account is always accepted * and made admin, which is what makes a fresh install claimable by whoever * runs it. After that, sign-up follows the instance setting, and only an * admin can add people to a closed instance. */ databaseHooks: { user: { create: { before: async (data, context) => { const first = isFirstAccount(); const byAdmin = context?.path === '/admin/create-user'; if (first) { addAuthTransactionValidator(() => { if (!isFirstAccount()) { if (!byAdmin) assertSignupOpenOrThrow(); throw new APIError('CONFLICT', { message: 'The instance was already claimed. Please try signing up again.' }); } }); return { data: { ...data, role: 'admin' } }; } if (!byAdmin) { assertSignupOpenOrThrow(); addAuthTransactionValidator(assertSignupOpenOrThrow); } return { data }; } } } }, /* * Every path `admin()` registers, refused inside better-auth's router. * `disabledPaths` filters the router only, so the console's own `auth.api.*` * calls still work; a request the hook lets through by mistake still 404s. * The hook's allowlist is the primary gate, and this is the layer that holds * when a future change forwards `/api/auth` wholesale again. */ disabledPaths: ADMIN_PATHS, plugins: [ admin({ roles: ADMIN_ROLES }), passkeyPlugin(), // Must stay last: it wires better-auth's cookies into SvelteKit's request. sveltekitCookies(getRequestEvent) ] }); export type Auth = typeof auth;