Skip to content

@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.

bash
bun add @kiln-js/auth

Peer dependency: @kiln-js/core, which the package imports for HttpError.


Quick example

ts
// 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!,
    }),
  ],
});
ts
// 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.

ts
interface AuthConfig {
  adapter: AuthAdapter;
  hooks?: AuthHooks;
  oauth?: OAuthProvider[];
  session?: SessionOptions;
  passwords?: { minLength?: number };
  basePath?: string;
  redirects?: {
    signedIn?: string;
    signedOut?: string;
    signIn?: string;
    register?: string;
  };
}
OptionDefaultMeaning
adapterrequiredStorage for users and sessions.
hooksnoneFunctions called at each step. See Hooks (opens in a new tab).
oauth[]OAuth providers, such as github() and google().
sessionsee belowCookie name and lifetime.
passwords.minLength8Minimum password length.
basePath/api/authPrefix 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/loginWhere a failed form sign-in returns to.
redirects.register/registerWhere a failed form sign-up returns to.

What it returns

MemberPurpose
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.
sessionsThe session manager.
adapterThe storage adapter you passed in.

Routes

route(request, path) handles these paths, relative to basePath:

MethodPathPurpose
GET/sessionThe current user. 200 with { user, expiresAt }, or 401 with { user: null }.
POST/signupCreate an account with email, name, and password.
POST/signinSign in with email and password.
POST/signoutDelete the current session and clear the cookie.
GET/oauth/:providerStart sign-in with an OAuth provider. Redirects to the provider.
GET/oauth/:provider/callbackThe 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

ResultForm requestJSON request
Success303 to redirects.signedIn, with the session cookie200 with { user } and the cookie
Failure303 to the matching form page with ?error=…4xx with { error, field? }

Failure statuses and messages:

CaseStatusMessage
Invalid email400Enter a valid email address. (field email)
Name under 2 characters400Name must be at least 2 characters. (field name)
Password too short400Password must be at least N characters. (field password)
Email already registered409That email is already registered. (field email)
Wrong email or password401Invalid email or password.
Refused by beforeSignUp403 or the error's own statusThe error's message
Email already used by a password account during OAuth409An 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_session by default. It is HttpOnly, SameSite=Lax, and Path=/, with Secure on 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

ts
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:

ts
import { hashPassword, verifyPassword } from "@kiln-js/auth";

const stored = await hashPassword("correct horse");
await verifyPassword("correct horse", stored); // true

randomToken(bytes?) returns a URL-safe random string, for password reset links and similar tokens.


OAuth providers

HelperProviderRequirements
github({ clientId, clientSecret })GitHubThe 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

  1. GET /api/auth/oauth/github sets a state cookie, kiln_oauth_state, and redirects to the provider with a random state.
  2. The provider redirects to /api/auth/oauth/github/callback?code=…&state=….
  3. The callback checks that state matches the cookie. A mismatch is refused.
  4. The code is exchanged for an access token.
  5. profile(token) returns the provider's user, or null when the email is missing or not verified. A null profile is refused.
  6. 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:

ts
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)

ts
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.

ts
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>;
}
  • beforeSignUp runs after the email and password checks and before the user is created. Throw an AuthError to refuse the sign-up with that status and message. Any other thrown error refuses it with status 403 and the error's message.
  • onSignUp runs after a user is created. method is "password" or "oauth:<provider>".
  • onSignIn runs after a successful sign-in. method is the same as above.
  • onSignOut runs when the sign-out route is called. user is null when no one was signed in.
  • onSession runs each time session() or requireUser() finds a user.
  • authorize decides 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.

ts
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

ts
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

ExportKindPurpose
createAuthfunctionBuild the auth object.
createSessionManagerfunctionBuild a session manager on its own.
memoryAdapterfunctionIn-memory storage.
sqliteAdapterasync functionSQLite storage.
github, googlefunctionsOAuth provider definitions.
hashPassword, verifyPassword, randomTokenfunctionsCrypto helpers.
AuthErrorclassError with status and optional field.
Auth, SessionManagertypesReturn types of the factories.
AuthAdapter, AuthConfig, AuthHooks, AuthUser, OAuthProvider, SessionOptions, SessionRecord, UserRecordtypesInterfaces described above.