5. Add accounts and start one application

The game rules and UI are ready. Now protect them. The initializer already selected the authentication dependencies; add the account store and authentication service used by the finished project:

ts
import { createHash, randomBytes, randomUUID } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';

export interface Card { id: string; title: string; }
export interface Session { account: string; expires: number; }
export interface Credentials { salt: string; hash: string; }
export const MAX_CARDS = 100;
export const USERNAME = /^[a-z][a-z0-9_-]{2,31}$/;
const digest = (token: string) => createHash('sha256').update(token).digest('hex');

/** Recipe-local persistence. Every private query derives its owner from a live session. */
export class DashboardStore {
    private readonly db: DatabaseSync;
    private closed = false;

    constructor(filename: string) {
        this.db = new DatabaseSync(filename);
        try {
            this.db.exec('PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL; PRAGMA busy_timeout = 1000;');
            const version = this.db.prepare('PRAGMA user_version').get()!.user_version;
            if (version !== 0 && version !== 1) throw new Error('Unsupported dashboard database version.');
            this.db.exec(`
                BEGIN IMMEDIATE;
                CREATE TABLE IF NOT EXISTS accounts (
                    id TEXT PRIMARY KEY, salt TEXT NOT NULL, hash TEXT NOT NULL, epoch INTEGER NOT NULL DEFAULT 0
                ) STRICT;
                CREATE TABLE IF NOT EXISTS sessions (
                    token TEXT PRIMARY KEY, account TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
                    expires INTEGER NOT NULL
                ) STRICT;
                CREATE INDEX IF NOT EXISTS sessions_owner ON sessions(account);
                CREATE INDEX IF NOT EXISTS sessions_expiry ON sessions(expires);
                CREATE TABLE IF NOT EXISTS cards (
                    id TEXT PRIMARY KEY, account TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
                    title TEXT NOT NULL CHECK(length(title) BETWEEN 1 AND 80)
                ) STRICT;
                CREATE INDEX IF NOT EXISTS cards_owner ON cards(account);
                PRAGMA user_version = 1;
                COMMIT;
            `);
        } catch (error) { this.db.close(); throw error; }
    }

    provision(account: string, credentials: Credentials) {
        if (!USERNAME.test(account) || !/^[a-f0-9]{32}$/.test(credentials.salt) || !/^[a-f0-9]{128}$/.test(credentials.hash)) {
            throw new TypeError('Invalid account credentials.');
        }
        this.db.prepare('INSERT INTO accounts(id, salt, hash) VALUES (?, ?, ?)').run(account, credentials.salt, credentials.hash);
    }

    credentials(account: string): (Credentials & { epoch: number }) | undefined {
        return this.db.prepare('SELECT salt, hash, epoch FROM accounts WHERE id = ?').get(account) as unknown as (Credentials & { epoch: number }) | undefined;
    }

    issue(account: string, ttlMs: number, expectedEpoch?: number): string {
        if (!Number.isInteger(ttlMs) || ttlMs < 100 || ttlMs > 86400000) throw new RangeError('Session lifetime must be 100ms–24h.');
        return this.transaction(() => {
            if (expectedEpoch !== undefined && this.credentials(account)?.epoch !== expectedEpoch) throw new Error('Sign-out occurred during sign-in. Try again.');
            this.db.prepare('DELETE FROM sessions WHERE expires <= ?').run(Date.now());
            const count = this.db.prepare('SELECT COUNT(*) AS count FROM sessions WHERE account = ?').get(account)!.count as number;
            if (count >= 32) throw new Error('Sign out existing sessions before signing in again.');
            const token = randomBytes(32).toString('base64url');
            this.db.prepare('INSERT INTO sessions(token, account, expires) VALUES (?, ?, ?)').run(digest(token), account, Date.now() + ttlMs);
            return token;
        });
    }

    session(token: string): Session | undefined {
        if (!/^[A-Za-z0-9_-]{43}$/.test(token)) return undefined;
        return this.db.prepare('SELECT account, expires FROM sessions WHERE token = ? AND expires > ?').get(digest(token), Date.now()) as unknown as Session | undefined;
    }

    list(token: string): Card[] {
        const { account } = this.requireSession(token);
        return this.db.prepare('SELECT id, title FROM cards WHERE account = ? ORDER BY rowid').all(account) as unknown as Card[];
    }

    add(token: string, title: string): string {
        if (typeof title !== 'string' || !title.trim() || title.length > 80 || /[\p{Cc}\p{Cf}]/u.test(title)) throw new TypeError('Invalid card title.');
        return this.transaction(() => {
            const { account } = this.requireSession(token);
            const count = this.db.prepare('SELECT COUNT(*) AS count FROM cards WHERE account = ?').get(account)!.count as number;
            if (count >= MAX_CARDS) throw new Error('Card limit reached.');
            this.db.prepare('INSERT INTO cards(id, account, title) VALUES (?, ?, ?)').run(randomUUID(), account, title.trim());
            return account;
        });
    }

    remove(token: string, id: string): string {
        return this.transaction(() => {
            const { account } = this.requireSession(token);
            this.db.prepare('DELETE FROM cards WHERE id = ? AND account = ?').run(id, account);
            return account;
        });
    }

    signOut(token: string): string | undefined {
        return this.transaction(() => {
            const session = this.session(token);
            if (!session) return undefined;
            this.db.prepare('DELETE FROM sessions WHERE account = ?').run(session.account);
            this.db.prepare('UPDATE accounts SET epoch = epoch + 1 WHERE id = ?').run(session.account);
            return session.account;
        });
    }

    close() { if (!this.closed) { this.closed = true; this.db.close(); } }

    private requireSession(token: string): Session {
        const session = this.session(token);
        if (!session) throw new Error('Session expired. Sign in again.');
        return session;
    }

    private transaction<T>(operation: () => T): T {
        this.db.exec('BEGIN IMMEDIATE');
        try { const result = operation(); this.db.exec('COMMIT'); return result; }
        catch (error) { this.db.exec('ROLLBACK'); throw error; }
    }
}
ts
import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto';
import { promisify } from 'node:util';
import type { Application, Request, Response } from 'express';
import { DashboardStore, USERNAME, type Credentials } from './store.js';

const COOKIE = 'redweb_dashboard';
const DUMMY: Credentials = { salt: '00'.repeat(16), hash: '00'.repeat(64) };

export function sessionToken(cookie: string | undefined): string {
    const matches = (cookie ?? '').split(';').map(part => part.trim()).filter(part => part.startsWith(`${COOKIE}=`));
    const token = matches.length === 1 ? matches[0].slice(COOKIE.length + 1) : '';
    return /^[A-Za-z0-9_-]{43}$/.test(token) ? token : '';
}

const passwordHash = promisify(scrypt);

export async function credentials(password: string): Promise<Credentials> {
    if (typeof password !== 'string' || password.length < 16 || password.length > 128) throw new TypeError('Use a password of 16–128 characters.');
    const salt = randomBytes(16).toString('hex');
    return { salt, hash: (await passwordHash(password, salt, 64) as Buffer).toString('hex') };
}

/** Bounded asynchronous password work; neither proxy headers nor browser input establish identity. */
export class DashboardAuth {
    private active = 0;
    private closed = false;
    private readonly attempts = new Map<string, { count: number; expires: number }>();

    constructor(private readonly store: DashboardStore, private readonly ttlMs = 3600000,
        private readonly attemptWindowMs = 60000) {
        if (!Number.isInteger(ttlMs) || ttlMs < 100 || ttlMs > 86400000) throw new RangeError('Invalid session lifetime.');
        if (!Number.isInteger(attemptWindowMs) || attemptWindowMs < 20 || attemptWindowMs > 60000) throw new RangeError('Invalid login attempt window.');
    }

    async login(ip: string, account: unknown, password: unknown): Promise<string | undefined> {
        if (this.closed) return undefined;
        const now = Date.now();
        for (const [key, entry] of this.attempts) if (entry.expires <= now) this.attempts.delete(key);
        let attempt = this.attempts.get(ip);
        if (!attempt) {
            if (this.attempts.size >= 1024) return undefined;
            attempt = { count: 0, expires: now + this.attemptWindowMs };
            this.attempts.set(ip, attempt);
        }
        if (++attempt.count > 10 || this.active >= 4) return undefined;
        if (typeof account !== 'string' || !USERNAME.test(account) || typeof password !== 'string' || password.length < 16 || password.length > 128) return undefined;
        this.active++;
        try {
            const stored = this.store.credentials(account);
            const expected = stored ?? DUMMY;
            const actual = await passwordHash(password, expected.salt, 64) as Buffer;
            if (this.closed) return undefined;
            if (!timingSafeEqual(actual, Buffer.from(expected.hash, 'hex')) || !stored) return undefined;
            return this.store.issue(account, this.ttlMs, stored.epoch);
        } finally { this.active--; }
    }

    close() { this.closed = true; this.attempts.clear(); }

    mount(app: Application, origin: () => string, allowsOrigin: (candidate: string | undefined, request: Request) => boolean, revoke: (account: string) => Promise<unknown>) {
        const cookie = (token: string) => `${COOKIE}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${token ? Math.ceil(this.ttlMs / 1000) : 0}${origin().startsWith('https:') ? '; Secure' : ''}`;
        const post = (route: string, handler: (request: Request, response: Response) => Promise<void>) => {
            app.post(route, (request, response) => {
                response.set('Cache-Control', 'private, no-store');
                if (!allowsOrigin(request.get('origin'), request)) { response.status(403).send('This form must be submitted from this site.'); return; }
                void handler(request, response).catch(() => response.status(503).send('Unable to complete the request. Try again later.'));
            });
        };
        post('/login', async (request, response) => {
            const token = await this.login(String(request.socket.remoteAddress), request.body?.account, request.body?.password);
            if (!token) { response.status(401).send('Unable to sign in. Check your credentials or try again later.'); return; }
            response.setHeader('Set-Cookie', cookie(token));
            response.redirect(303, '/');
        });
        post('/logout', async (request, response) => {
            const account = this.store.signOut(sessionToken(request.headers.cookie));
            response.setHeader('Set-Cookie', cookie(''));
            if (account) await revoke(account);
            response.redirect(303, '/login');
        });
    }
}

Passwords use asynchronous salted scrypt. Sessions are random opaque tokens stored as hashes in SQLite and carried in HttpOnly, SameSite=Strict cookies. Login work and concurrent password work are bounded. There is no default password or browser-stored bearer secret.

Create src/server.tsx to connect authentication, the page, /match, and resource ownership:

tsx
import express from 'express';
import { mkdirSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineApp, page } from 'redweb';
import { DashboardAuth, sessionToken } from './shared/auth.js';
import { DashboardStore } from './shared/store.js';
import { matchRoute } from './routes.js';

export const databasePath = () => resolve(process.env.GAME_DATABASE ?? 'data/game.sqlite');
export interface Options { port?: number; database?: string; origin?: string; signals?: boolean; }

export function gameApp(options: Options = {}) {
    let store: DashboardStore;
    let auth: DashboardAuth;
    const configured = options.origin ?? process.env.GAME_ORIGIN;
    if (configured && (!/^https?:$/.test(new URL(configured).protocol) || new URL(configured).origin !== configured)) throw new Error('GAME_ORIGIN must be an exact HTTP(S) origin.');
    if (process.env.NODE_ENV === 'production' && !configured?.startsWith('https://')) throw new Error('Set an HTTPS GAME_ORIGIN for production.');
    const origin = () => configured ?? `http://localhost:${(app.server!.address() as { port: number }).port}`;
    // Exact browser origin: do not derive trust from forwarded headers.
    const origins = (candidate: string | undefined) => candidate === origin();
    const account = (request: { headers: { cookie?: string | readonly string[] } }) =>
        store.session(sessionToken(typeof request.headers.cookie === 'string' ? request.headers.cookie : undefined))?.account;
    const { MatchRoute, GamePage } = matchRoute(account, origins);

    @page('/login', { live: false })
    class Login {
        render() { return <main><h1>Sign in to play</h1><p>Use an account created with npm run add-user.</p>
            <form method="post" action="/login"><label>Account <input name="account" autocomplete="username" required /></label>
                <label>Password <input name="password" type="password" autocomplete="current-password" required /></label>
                <button>Sign in</button></form></main>; }
    }
    class Accounts {
        onInit() {
            const filename = options.database ?? databasePath();
            mkdirSync(dirname(filename), { recursive: true });
            store = new DashboardStore(filename);
            auth = new DashboardAuth(store);
            app.app!.use(express.urlencoded({ extended: false, limit: '4kb', parameterLimit: 4 }));
            app.app!.get('/game.css', (_request, response) => response.sendFile(fileURLToPath(new URL('../src/game.css', import.meta.url))));
            auth.mount(app.app!, origin, origins, async user => {
                await app.revoke(user);
                const route = app.sockets!.routes.find(route => route.path === '/match')!;
                for (const socket of route.clients.values()) if (socket.context?.principal === user) socket.close(1008, 'Signed out.');
            });
        }
        onShutdown() { auth?.close(); store?.close(); }
    }
    const app = defineApp({ pages: [Login, GamePage], sockets: [MatchRoute], services: [Accounts],
        port: options.port ?? Number(process.env.PORT ?? 8181), bind: '127.0.0.1', signals: options.signals, logger: null,
        authenticate: request => request.url?.split('?')[0] === '/login' ? true : account(request),
        origins,
    });
    return app;
}

The same account lookup protects the initial HTTP page and socket admission. Login/logout forms and socket upgrades require the exact trusted origin. In production, configure an explicit HTTPS origin; never infer trust from forwarded headers.

Accounts.onInit() opens the store and mounts ordinary Express routes before the listener opens. onShutdown() closes them. defineApp then owns the pages, socket route, service, listener, cancellation, and bounded shutdown together—there is no separately stored HTTP server followed by separate socket initialization.

The gameApp factory only provides isolated configuration for tests. The actual process entry in src/app.tsx stays tiny:

tsx
import { gameApp } from './server.js';

const app = gameApp();

await app.run();

Add src/admin.ts for deliberate account provisioning:

ts
import { randomBytes } from 'node:crypto';
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import { credentials } from './shared/auth.js';
import { DashboardStore, USERNAME } from './shared/store.js';
import { databasePath } from './server.js';

const account = process.argv[2];
if (!account || !USERNAME.test(account) || process.argv.length !== 3) throw new Error('Usage: npm run add-user -- alice');
mkdirSync(dirname(databasePath()), { recursive: true });
const store = new DashboardStore(databasePath());
try {
    const password = randomBytes(24).toString('base64url');
    store.provision(account, await credentials(password));
    console.log(`Created ${account}. Save this password; it is shown only once:\n${password}`);
} finally { store.close(); }

Build and create two players:

sh
npm run build
npm run add-user -- alice
npm run add-user -- bob

Each command prints one random password. Save it; the application stores only its hash.

Checkpoint: start the app and verify an incorrect password is rejected, a correct one opens the board, an unsigned or cross-origin socket is denied, and logout invalidates sessions before closing that account's live connections.

Download the complete project Setup, optional configuration, and limits