@kiln-js/auth#
@kiln-js/auth adds accounts and sessions to a Kiln app. It supports email and password sign-up and sign-in, GitHub and Google sign-in, secure session cookies, lifecycle hooks, and an authorization check. You bring your own storage through an adapter, or use the built-in memory or SQLite adapters.
bun add @kiln-js/authPeer dependency: @kiln-js/core, which the package imports for HttpError.
Quick example#
// app/lib/auth.ts
import { createAuth, memoryAdapter, github } from "@kiln-js/auth";
export const auth = createAuth({
adapter: memoryAdapter(),
oauth: [
github({
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
}),
],
});// app/api/auth/[...action].ts
import { auth } from "../../lib/auth";
export function GET({ request, params }: { request: Request; params: { action: string } }) {
return auth.route(request, params.action);
}
export function POST({ request, params }: { request: Request; params: { action: string } }) {
return auth.route(request, params.action);
}Every auth endpoint is then available under /api/auth/…. See Authentication for the full setup.
createAuth(config)#
Returns an object with the auth methods. Call it once and export the result.
interface AuthConfig {
adapter: AuthAdapter;
hooks?: AuthHooks;
oauth?: OAuthProvider[];
session?: SessionOptions;
passwords?: { minLength?: number };
basePath?: string;
redirects?: {
signedIn?: string;
signedOut?: string;
signIn?: string;
register?: string;
};
}| Option | Default | Meaning |
|---|---|---|
adapter | required | Storage for users and sessions. |
hooks | none | Functions called at each step. See Hooks (opens in a new tab). |
oauth | [] | OAuth providers, such as github() and google(). |
session | see below | Cookie name and lifetime. |
passwords.minLength | 8 | Minimum password length. |
basePath | /api/auth | Prefix for the auth routes. |
redirects.signedIn | / | Where form sign-in and sign-up send the user. |
redirects.signedOut | / | Where form sign-out sends the user. |
redirects.signIn | /login | Where a failed form sign-in returns to. |
redirects.register | /register | Where a failed form sign-up returns to. |
What it returns#
| Member | Purpose |
|---|---|
route(request, path) | Handles every auth route. Mount it from a catch-all API file. |
session(request) | Returns { user, expiresAt } for the request, or null. Runs the onSession hook. |
requireUser(request) | Returns the signed-in user, or throws HttpError(401, "Sign in required"). |
can(request, action, resource?) | Runs the authorize hook for the signed-in user. |
revokeSessions(userId) | Signs a user out everywhere. Use it after a password change. |
signUp(request), signIn(request), signOut(request) | The individual handlers, if you route them yourself. |
sessions | The session manager. |
adapter | The storage adapter you passed in. |
Routes#
route(request, path) handles these paths, relative to basePath:
| Method | Path | Purpose |
|---|---|---|
GET | /session | The current user. 200 with { user, expiresAt }, or 401 with { user: null }. |
POST | /signup | Create an account with email, name, and password. |
POST | /signin | Sign in with email and password. |
POST | /signout | Delete the current session and clear the cookie. |
GET | /oauth/:provider | Start sign-in with an OAuth provider. Redirects to the provider. |
GET | /oauth/:provider/callback | The provider redirects here. Completes sign-in. |
Any other method on these paths returns 405. Unknown paths return 404 with { "error": "Not found" }.
Request bodies#
Sign-up and sign-in accept form posts or JSON. Form posts get a redirect. JSON requests (with accept: application/json) get JSON.
signup fields: email, name, password.
signin fields: email, password.
Success and failure#
| Result | Form request | JSON request |
|---|---|---|
| Success | 303 to redirects.signedIn, with the session cookie | 200 with { user } and the cookie |
| Failure | 303 to the matching form page with ?error=… | 4xx with { error, field? } |
Failure statuses and messages:
| Case | Status | Message |
|---|---|---|
| Invalid email | 400 | Enter a valid email address. (field email) |
| Name under 2 characters | 400 | Name must be at least 2 characters. (field name) |
| Password too short | 400 | Password must be at least N characters. (field password) |
| Email already registered | 409 | That email is already registered. (field email) |
| Wrong email or password | 401 | Invalid email or password. |
Refused by beforeSignUp | 403 or the error's own status | The error's message |
| Email already used by a password account during OAuth | 409 | An account with this email already exists. Sign in with your password. |
The sign-in message is the same for an unknown email and a wrong password, so a form cannot be used to find accounts.
Emails are trimmed and lowercased before they are checked or stored.
Sessions#
A session is created on sign-up, sign-in, and OAuth sign-in.
- The cookie is named
kiln_sessionby default. It isHttpOnly,SameSite=Lax, andPath=/, withSecureon HTTPS. - The token is a random 32-byte value. Only its SHA-256 hash is stored. A stolen database cannot be used to sign in.
- A session lasts 30 days by default.
- When a session is less than half used up, it is extended to the full lifetime on the next check.
- An expired session is deleted when it is checked.
- Signing out deletes the session and clears the cookie.
session options#
interface SessionOptions {
cookieName?: string; // default "kiln_session"
maxAgeDays?: number; // default 30
}Passwords#
Passwords are hashed with PBKDF2, using SHA-256 and 100,000 iterations, with a random 16-byte salt per password. The stored value looks like pbkdf2$100000$<salt>$<hash>. Verification compares the hashes in constant time.
The minimum length defaults to 8 and is set with passwords.minLength.
Two helpers are exported for your own use:
import { hashPassword, verifyPassword } from "@kiln-js/auth";
const stored = await hashPassword("correct horse");
await verifyPassword("correct horse", stored); // truerandomToken(bytes?) returns a URL-safe random string, for password reset links and similar tokens.
OAuth providers#
| Helper | Provider | Requirements |
|---|---|---|
github({ clientId, clientSecret }) | GitHub | The account must have a verified primary email. Scope read:user user:email. |
google({ clientId, clientSecret }) | Google (OpenID Connect) | The email must be verified. |
Each provider is a plain object with id, clientId, clientSecret, authorizeUrl, tokenUrl, scope, and a profile(accessToken) function. You can add your own provider with the same shape.
Flow#
GET /api/auth/oauth/githubsets a state cookie,kiln_oauth_state, and redirects to the provider with a randomstate.- The provider redirects to
/api/auth/oauth/github/callback?code=…&state=…. - The callback checks that
statematches the cookie. A mismatch is refused. - The code is exchanged for an access token.
profile(token)returns the provider's user, ornullwhen the email is missing or not verified. Anullprofile is refused.- If a user with that provider id exists, that user signs in. Otherwise, if an account with the same email exists, the sign-in is refused, so that controlling an email address at a provider cannot take over a password account. Otherwise a new user is created with no password.
Adapters#
An adapter is the storage the auth system uses. It implements this interface:
interface AuthAdapter {
findUserByEmail(email: string): Promise<UserRecord | null>;
findUserById(id: string): Promise<UserRecord | null>;
findUserByProvider(provider: string, providerId: string): Promise<UserRecord | null>;
createUser(input: {
email: string;
name: string;
passwordHash: string | null;
provider: string | null;
providerId: string | null;
}): Promise<UserRecord>;
createSession(session: SessionRecord): Promise<void>;
findSession(id: string): Promise<SessionRecord | null>;
extendSession(id: string, expiresAt: Date): Promise<void>;
deleteSession(id: string): Promise<void>;
deleteUserSessions(userId: string): Promise<void>;
}memoryAdapter()#
Keeps users and sessions in memory. Data is lost when the process restarts. Use it for development and tests.
sqliteAdapter(file)#
const adapter = await sqliteAdapter("data/auth.db");Creates the kiln_users and kiln_sessions tables if they do not exist. It uses bun:sqlite under Bun and node:sqlite under Node 22 or later. The adapter is async, so await it before passing it to createAuth.
The SQLite adapter needs a runtime with a local file system. It does not run on Vercel's Edge runtime.
Drizzle#
A Drizzle adapter is in development and is not available yet. Until it ships, write your own adapter against the interface above for any database that is not covered by the built-in adapters.
Hooks#
Hooks run at each step. Every hook is optional.
interface AuthHooks {
beforeSignUp?(input: { email: string; name: string }): void | Promise<void>;
onSignUp?(user: AuthUser, method: string): void | Promise<void>;
onSignIn?(user: AuthUser, method: string): void | Promise<void>;
onSignOut?(user: AuthUser | null): void | Promise<void>;
onSession?(user: AuthUser): void | Promise<void>;
authorize?(user: AuthUser | null, action: string, resource?: unknown): boolean | Promise<boolean>;
}beforeSignUpruns after the email and password checks and before the user is created. Throw anAuthErrorto refuse the sign-up with that status and message. Any other thrown error refuses it with status 403 and the error's message.onSignUpruns after a user is created.methodis"password"or"oauth:<provider>".onSignInruns after a successful sign-in.methodis the same as above.onSignOutruns when the sign-out route is called.userisnullwhen no one was signed in.onSessionruns each timesession()orrequireUser()finds a user.authorizedecides whether a user may perform an action. Without this hook, any signed-in user may perform any action.
AuthUser is the public user: { id, email, name }. Password hashes and provider ids are never sent to the browser.
const auth = createAuth({
adapter,
hooks: {
async beforeSignUp({ email }) {
if (!email.endsWith("@example.com")) {
throw new AuthError(403, "Sign-up is limited to example.com accounts.");
}
},
authorize(user, action, post) {
if (action === "post.edit") return user?.id === (post as { authorId: string }).authorId;
return user !== null;
},
},
});Errors#
export class AuthError extends Error {
readonly status: number;
readonly field?: string;
}Throw AuthError from hooks to produce a specific status and message. The auth routes turn it into a response. Outside the auth routes, requireUser throws an HttpError with status 401, which the page handler turns into a 401 response.
Exports#
| Export | Kind | Purpose |
|---|---|---|
createAuth | function | Build the auth object. |
createSessionManager | function | Build a session manager on its own. |
memoryAdapter | function | In-memory storage. |
sqliteAdapter | async function | SQLite storage. |
github, google | functions | OAuth provider definitions. |
hashPassword, verifyPassword, randomToken | functions | Crypto helpers. |
AuthError | class | Error with status and optional field. |
Auth, SessionManager | types | Return types of the factories. |
AuthAdapter, AuthConfig, AuthHooks, AuthUser, OAuthProvider, SessionOptions, SessionRecord, UserRecord | types | Interfaces described above. |

