Authentication & Timing-Safe Security

Katal v3 provides a zero-dependency, timing-safe authentication subsystem powered by the Web Cryptography API (crypto.subtle). It operates consistently across Bun, Node.js (18+), and Edge runtimes without native bindings or third-party packages.


1. Quick Start

import { Application, Auth, createAuthMiddleware } from "katal";

const app = new Application({ port: 3000 });

// 1. Initialize Auth instance with secret key
export const auth = new Auth({
    secret: process.env.JWT_SECRET ?? "change-this-secret-in-production-32-chars",
    expiresIn: "2h", // Accepts string duration ("15m", "2h", "7d") or seconds (7200)
});

// 2. Register named auth middleware
app.middleware("auth", createAuthMiddleware(auth));

// 3. Protect routes with the "auth" middleware
app.getRouter().get("/api/v1/me", ProfileController, {
    middleware: ["auth"],
});

await app.listen();

2. Token Lifecycle & The Auth Class

A. Generating Signed JWT Tokens

Signs a cryptographically verifiable JWT containing custom user claims:

const token = await auth.generateToken({
    id: "usr-101",
    email: "sarah@company.com",
    role: "admin",
});
// Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

B. Verifying Tokens

Validates signature integrity and checks expiration timestamps. Returns the decoded User payload or null if expired, malformed, or tampered with:

const user = await auth.verifyToken(token);
if (!user) {
    // Token is either expired or has an invalid signature
}

C. Extracting & Authenticating from Web Requests

Convenience method extracting Bearer <token> from the HTTP Authorization header:

const user = await auth.authenticate(request);

D. Password Hashing & Timing-Safe Verification

Uses WebCrypto PBKDF2 with SHA-256 (or Bun's native bcrypt when running on Bun) with constant-time equality checks (timingSafeEqual) to prevent timing side-channel attacks:

// 1. Hash password with secure salt
const passwordHash = await auth.hashPassword("super-secret-user-password");

// 2. Verify password with constant-time comparison
const isValid = await auth.verifyPassword("super-secret-user-password", passwordHash);
// Returns true or false

3. Real-World Authentication Flow

User Login Controller

import { Controller } from "katal";
import type { RequestContext } from "katal";
import { z } from "zod";
import { auth } from "./auth";
import { UserRepository } from "./repositories/UserRepository";

const loginSchema = z.object({
    email: z.string().email(),
    password: z.string().min(8),
});

export class LoginController extends Controller {
    static schema = { body: loginSchema };

    constructor(private readonly userRepo: UserRepository) {
        super();
    }

    async handle(ctx: RequestContext) {
        const { email, password } = ctx.valid<z.infer<typeof loginSchema>>("body");

        // 1. Lookup user
        const user = await this.userRepo.findByEmail(email);
        if (!user) {
            return this.unauthorized("Invalid credentials.");
        }

        // 2. Verify password
        const passwordMatches = await auth.verifyPassword(password, user.passwordHash);
        if (!passwordMatches) {
            return this.unauthorized("Invalid credentials.");
        }

        // 3. Issue JWT Token
        const token = await auth.generateToken({
            id: user.id,
            email: user.email,
            role: user.role,
        });

        return this.success({
            token,
            user: { id: user.id, email: user.email, role: user.role },
        });
    }
}

Protected Profile Controller

export class ProfileController extends Controller {
    async handle(ctx: RequestContext) {
        // ctx.user is automatically populated by createAuthMiddleware
        const currentUser = ctx.user;
        return this.success({ user: currentUser });
    }
}

4. Middleware Variants

createAuthMiddleware(auth) — Required Authentication

Rejects unauthenticated or expired requests immediately with HTTP 401 Unauthorized:

app.middleware("auth", createAuthMiddleware(auth));

Failure Response (application/problem+json):

{
  "type": "https://tools.ietf.org/html/rfc9457",
  "title": "Unauthorized",
  "status": 401,
  "detail": "Authentication required to access this resource."
}

createOptionalAuthMiddleware(auth) — Optional Authentication

Allows requests to proceed whether a token is present or not. If a valid token exists, ctx.user is populated; otherwise, ctx.user is undefined:

app.middleware("auth:optional", createOptionalAuthMiddleware(auth));

class ArticleListController extends Controller {
    async handle(ctx: RequestContext) {
        if (ctx.user) {
            // Include user-specific bookmarks or liked statuses
            return this.success(await getPersonalizedFeed(ctx.user.id));
        }
        // Public feed for anonymous visitors
        return this.success(await getPublicFeed());
    }
}

5. Refresh Token Pattern

To maintain short-lived access tokens (e.g. 15 minutes) with long-lived refresh tokens:

export class RefreshTokenController extends Controller {
    constructor(private readonly refreshTokenStore: RefreshTokenStore) {
        super();
    }

    async handle(ctx: RequestContext) {
        const rawHeader = ctx.request.headers.get("x-refresh-token");
        if (!rawHeader) {
            return this.unauthorized("Missing refresh token.");
        }

        const validSession = await this.refreshTokenStore.verify(rawHeader);
        if (!validSession) {
            return this.unauthorized("Expired or revoked refresh token.");
        }

        // Issue new short-lived access token
        const newAccessToken = await auth.generateToken({
            id: validSession.userId,
            role: validSession.role,
        }, { expiresIn: "15m" });

        return this.success({ token: newAccessToken });
    }
}

6. Testing with Synthetic Tokens

Use createTestToken from the Testing Kit to generate signed test tokens instantly without calling login endpoints:

import { describe, it, expect } from "bun:test";
import { createTestToken } from "katal/testing";
import { app } from "../src/app";

describe("Protected Routes", () => {
    it("allows access with valid test token", async () => {
        const token = await createTestToken({
            id: "usr-42",
            role: "admin",
        }, process.env.JWT_SECRET ?? "change-this-secret-in-production-32-chars");

        const res = await app.handle(new Request("http://localhost/api/v1/me", {
            headers: { Authorization: `Bearer ${token}` },
        }));

        expect(res.status).toBe(200);
        const body = await res.json();
        expect(body.data.user.id).toBe("usr-42");
    });
});

See Also