Dashboard: complete application
Documentation for Redweb 0.16.4. Install that exact version when following these examples.
Persistent private dashboard
This recipe combines decorator-first pages, reusable live cards, validated actions, and real SQLite persistence. It is an application example, not an authentication framework or managed database.
Run it
Requires Node 22.13 or newer (native node:sqlite, experimental in Node 22) and npm. Other Redweb starters retain their own Node requirements. Use a supported Node release in production.
After installing dependencies, create your account:
npm run add-user -- alice
npm test
npm run devThe provisioning command displays a randomly generated password once. Save it securely; there are no default accounts or passwords. Open http://127.0.0.1:8181/login or http://localhost:8181/login, sign in, and add a card. A second signed-in tab updates immediately. Restart the app: your cards and unexpired credentials remain valid. Sign out all sessions to close every connected tab for that account and invalidate all its cookies.
npm test provisions temporary test accounts and a real temporary database, then exercises HTTP, WebSockets, isolation, restart, and session expiry. It never modifies your application database. Integration tests use no mocks, including hostile cross-loopback form and socket origins. Redweb's release gate also signs in with both valid and invalid credentials through a visible Chromium window, using localhost so synthetic request headers cannot hide browser-origin bugs. CI supplies a virtual display for that same headed test. A separately labelled unit test injects a cleanup error after closing a real SQLite database to verify rejection handling; it does not simulate a real operating-system failure.
npm run test:coverage measures the TypeScript application through source maps, separately from Redweb's own instrumented-library coverage. Login-window expiry uses the same real limiter with an explicitly short test configuration; it never waits through the production one-minute default. The report includes TypeScript-generated decorator accessor functions; inspect that distinction rather than assuming a library coverage figure applies to this recipe. The generated npm configuration enforces this recipe's Node engine requirement before installation.
Where the behavior lives
app.tsx: composition, login page, protected dashboard, listener and shutdown.cards.tsx: reusableCardscomponent and account-scoped live subscriptions. Normal TSX expressions update automatically. Forms call typed actions; feedback requires no browser glue.store.ts: prepared SQL, bounded cards/sessions, owner-filtered operations and synchronous transactions.auth.ts: asynchronous scrypt, bounded login attempts, hashed session tokens, cookies and sign-out.admin.ts: explicit local account provisioning.
Production boundaries
Set DASHBOARD_DATABASE to a writable persistent file path (default data/dashboard.sqlite). Protect the directory with OS permissions: the database contains password hashes, private card text, and session metadata. It, its WAL/SHM files, and backups must never be served as public assets or committed. Stop the process cleanly before copying the database for a backup, or use a proper SQLite online backup facility; copying only the main file during live WAL writes is not a backup plan.
Set NODE_ENV=production and DASHBOARD_ORIGIN=https://your-domain.example behind an HTTPS reverse proxy. The origin must have no path or trailing slash. This enables Secure cookies; all session cookies are HttpOnly and SameSite=Strict. Both login/logout forms and socket upgrades require the exact trusted origin. The application does not trust Host or forwarded headers to establish origin or identity. The HTTP listener must not be publicly reachable around your TLS proxy.
Provision accounts on the same persistent volume before serving requests. Passwords use salted scrypt; only hashes of random session tokens are stored. Default sessions last one hour. Up to 32 unexpired sessions and 100 cards per account are supported. Login work is limited to four simultaneous checks and ten attempts per minute per direct peer IP, with at most 1,024 tracked IPs; clients behind one proxy share its bucket. Add appropriate proxy-level abuse controls for an Internet deployment. There is no registration, password reset, MFA, or account recovery; integrate a dedicated identity provider if your product needs those features.
SQL checks the current session and card owner inside each write transaction. Private subscriptions recheck session validity before publishing and close at expiry. Sign-out invalidates credentials before revoking Redweb sessions. An expired or disconnected page may need a reload/sign-in; the recipe does not silently retry actions with uncertain outcomes.
This is a single-process live-update model. SQLite transactions are synchronous and kept small; this is not a claim of unlimited concurrency. Do not put multiple app workers behind a load balancer and expect cross-worker notifications or revocation. Add a deliberate shared notification/session-revocation design before scaling horizontally. Static export cannot include protected dashboards.
Build and deploy using the shared instructions above, including the persistent data volume and the environment settings here. Neither npm run dev nor a process restart should erase durable cards. Redweb itself does not depend on SQLite.
Setup and acceptance
npx --yes redweb@0.16.4 init my-dashboard --template dashboard
cd my-dashboard
npm install --save-exact redweb@0.16.4
npm run add-user -- alice
npm test
npm run devRequirements: Node.js 18 or newer and npm for the realtime, chat, site, socket and http-ws templates; the dashboard template requires Node.js 22.13+ for native SQLite. Use a currently supported Node.js release in production.
For an unreleased checkout or tarball, first run npm install --save-exact TARBALL, replacing TARBALL with the absolute path to the same tested Redweb tarball used to generate this app (quote paths containing spaces). This installs the matching package and its published client dependency. Do not substitute an older registry release or latest. Published Redweb releases can use the installation command below directly.
npm install
npm test
npm run devHTTP starters open at http://localhost:8181; the authenticated dashboard uses http://127.0.0.1:8181/login and requires account provisioning described below. Set the PORT environment variable to change the listener.
npm test builds and runs real HTTP/WebSocket integration tests on an ephemeral loopback port. No mocks or external service are needed.
npm run test:coverage runs the same tests with application coverage mapped back to TypeScript. Reports are written to the ignored coverage/ directory; this is separate from Redweb library coverage. TypeScript-generated decorator accessors can appear in function counts even when the framework does not call them. The report exposes remaining gaps; it does not certify complete application coverage. Source maps are generated during the build for diagnostics and coverage, but no coverage collector is loaded by npm start.
Development and production
Edit src/app.tsx. npm run dev watches TypeScript, TSX, CSS, HTML, and the root TypeScript configuration,
then rebuilds and restarts the server. A type error stops startup until you fix it. On direct localhost access,
HTML pages refresh automatically when a new server revision is ready. If edits were detected, a keyboard-accessible
notice keeps the old document until you choose Reload and discard drafts. This is a conservative edit guard,
not autosave or browser hot-module replacement: restarts reset in-memory state and old socket sessions.
The generated development command sets REDWEB_DEV_REFRESH=1; development: { refresh: false } overrides it.
The refresh feature is refused under NODE_ENV=production, applies only to served HTML (not raw sockets or static exports),
and creates no local/session-storage copy of form contents. Use direct localhost, 127.x.x.x, or [::1] access;
custom hostnames, tunnels and proxy-forwarded origins are not supported by this development helper.
npm run build checks types and copies CSS/HTML beside the compiled classes in dist/.
Run npm start to serve the compiled app. For deployment, build first, ship dist/, package.json, and the lockfile,
then install runtime dependencies with npm ci --omit=dev. The application does not require TypeScript or src/ at runtime.
The standalone entrypoint calls app.run() on a defineApp definition. Importing it opens no listener and installs no process handlers. Redweb owns HTTP and WebSocket startup together, including signal handling and bounded shutdown; no generated run-app.ts helper is needed. Configure startupTimeoutMs and shutdownTimeoutMs on the definition (both default to five seconds). App-wide service classes acquire resources in onInit(app, signal) and release them in onShutdown(); the dashboard uses this for its auth/database resources. The dashboard's factory configures an independent private workspace but does not start it.
Repeated signals do not bypass cleanup. Failed process-owned cleanup sets a failure exit status and retains a deadline for surviving handles. Explicit shutdown() rejects on cleanup failures without terminating its caller. Deadlines cannot preempt synchronous code blocking Node's event loop or arbitrary operations that ignore cancellation. Tests can define an independent application from { ...app.options, port: 0, signals: false } and await run(); app-owned state is isolated, but objects deliberately captured by page class closures remain shared unless a new class/room is created.
The shipped lifecycle tests exercise actual processes, HTTP/TCP/WebSocket peers and timers. Linux uses actual OS signals; Windows tests explicitly emit signal events inside the process because killing a Windows child does not exercise graceful POSIX signal delivery. This is not a claim that Windows console/service managers forward the same signals. Deploy with a supervisor that forwards the supported termination signal and allows longer than the configured cleanup deadline.
For public deployment, configure HTTPS/WSS at your Node server or reverse proxy, authentication, trusted origins,
and application-specific rate limits. These starters are demonstrations, not a hosted identity or database service.
Never commit secrets; .env is ignored but is not loaded automatically.
npx --no-install redweb doctor --json reports configuration problems without changing your files.
Dependency security
This starter includes an application-root npm override for Express 4's qs
dependency, selecting patched qs@6.16.0. Keep the override when merging this
starter into an existing application, refresh its lockfile and run npm audit.
Overrides in Redweb's own package do not apply to installed consumers. Recheck
upstream Express/body-parser releases before removing this temporary mitigation.
Exact generated files
These files come from the initializer itself. The tests below run real listeners; they are not illustrative pseudocode. The generated manifest uses the package metadata version; the installation step above pins the matching artifact or release.
package.json
{
"name": "redweb-app",
"private": true,
"version": "0.0.0",
"scripts": {
"build": "tsc && node scripts/copy-assets.cjs",
"start": "node dist/app.js",
"dev": "nodemon",
"test": "npm run build && node --test test/app.test.cjs test/lifecycle.test.cjs",
"test:coverage": "npm run build && c8 --all --src=dist --include=dist/** --reporter=text --reporter=json node --test test/app.test.cjs test/lifecycle.test.cjs test/rate-window.test.cjs",
"add-user": "npm run build && node dist/admin.js"
},
"dependencies": {
"redweb": "^0.16.4",
"zod": "^4.4.3",
"express": "^4.22.2"
},
"overrides": {
"express": {
"qs": "6.16.0"
}
},
"devDependencies": {
"typescript": "^5.9.3",
"nodemon": "^3.1.11",
"ws": "^8.21.3",
"c8": "^10.1.3",
"@types/node": "^22.20.1",
"@types/express": "^4.17.21"
},
"nodemonConfig": {
"env": {
"REDWEB_DEV_REFRESH": "1"
},
"watch": [
"src",
"tsconfig.json"
],
"ext": "ts,tsx,css,html,json",
"exec": "npm run build && npm start || exit 1",
"delay": 200
},
"engines": {
"node": ">=22.13.0"
}
}tsconfig.json
{
"extends": "redweb/tsconfig.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "dist",
"sourceMap": true
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
}src/app.tsx
import express, { type ErrorRequestHandler } from 'express';
import { mkdirSync } from 'node:fs';
import type { IncomingMessage } from 'node:http';
import { dirname, resolve } from 'node:path';
import { defineApp, page, type LivePageRequestContext } from 'redweb';
import { DashboardAuth, sessionToken } from './auth';
import { Cards, PrivateCards } from './cards';
import { DashboardStore } from './store';
export interface DashboardOptions { port?: number; database?: string; origin?: string; sessionLifetimeMs?: number; signals?: boolean; shutdownTimeoutMs?: number; }
export function databasePath() {
return process.env.DASHBOARD_DATABASE === ':memory:' ? ':memory:' : resolve(process.env.DASHBOARD_DATABASE ?? 'data/dashboard.sqlite');
}
const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']);
/** Development is loopback-only, so its equivalent browser hostnames share one trust boundary. */
export function allowsDashboardOrigin(candidate: string | undefined, expected: string, configured: boolean, host?: string) {
if (!candidate) return false;
if (configured) return candidate === expected;
if (!host || /[\/@?#\\]/.test(host)) return false;
try {
const actual = new URL(candidate);
const local = new URL(expected);
const target = new URL(`http://${host}`);
return actual.origin === candidate && actual.protocol === 'http:'
&& actual.origin === target.origin && actual.port === local.port
&& LOOPBACK_HOSTS.has(actual.hostname);
} catch { return false; }
}
export function createApp(options: DashboardOptions = {}) {
const port = options.port ?? Number(process.env.PORT ?? 8181);
const configuredOrigin = options.origin ?? process.env.DASHBOARD_ORIGIN;
if (configuredOrigin && (!/^https?:$/.test(new URL(configuredOrigin).protocol) || new URL(configuredOrigin).origin !== configuredOrigin)) {
throw new Error('DASHBOARD_ORIGIN must be an exact HTTP(S) origin without a path.');
}
if (process.env.NODE_ENV === 'production' && !configuredOrigin?.startsWith('https://')) throw new Error('Production requires an explicit HTTPS DASHBOARD_ORIGIN.');
const filename = options.database ?? databasePath();
let store: DashboardStore | undefined;
let cards: PrivateCards;
let auth: DashboardAuth | undefined;
const app = express();
app.disable('x-powered-by');
app.use(express.urlencoded({ extended: false, limit: '4kb', parameterLimit: 4 }));
const invalidBody: ErrorRequestHandler = (_error, _request, response, _next) => {
if (!response.destroyed) response.status(400).send('Invalid form submission.');
};
app.use(invalidBody);
const origin = () => configuredOrigin ?? `http://127.0.0.1:${(server.server!.address() as { port: number }).port}`;
const allowsOrigin = (candidate: string | undefined, request: IncomingMessage) =>
allowsDashboardOrigin(candidate, origin(), Boolean(configuredOrigin), request.headers.host);
@page('/login', { live: false, css: 'app.css', head: { title: 'Sign in · Your cards' } })
class Login {
render() {
return <main class="home"><h1>Your private workspace</h1>
<p>Sign in with the credentials created by your administrator.</p>
<form method="post" action="/login">
<label for="account">Account</label><input id="account" name="account" autocomplete="username" required />
<label for="password">Password</label><input id="password" name="password" type="password" autocomplete="current-password" required />
<button type="submit">Sign in</button>
</form>
</main>;
}
}
@page('/', { css: 'app.css', authorize: context => cards.allowed(context), head: { title: 'Your cards' } })
class Dashboard {
private readonly workspace = new Cards(cards);
render(context: LivePageRequestContext) {
return <main class="home"><header><div><h1>Your cards</h1><p>Signed in as {context.principal}</p></div>
<form method="post" action="/logout"><button type="submit">Sign out all sessions</button></form>
</header>{this.workspace}<p>Open another tab to see your changes instantly.</p></main>;
}
}
class Workspace {
onInit() {
mkdirSync(dirname(filename), { recursive: true });
store = new DashboardStore(filename);
cards = new PrivateCards(store);
auth = new DashboardAuth(store, options.sessionLifetimeMs);
auth.mount(app, origin, allowsOrigin, account => server.revoke(account));
}
onShutdown() {
try { auth?.close(); }
finally { store?.close(); }
}
}
const server = defineApp({
pages: [Login, Dashboard], services: [Workspace], signals: options.signals, shutdownTimeoutMs: options.shutdownTimeoutMs,
server: app, port, bind: configuredOrigin ? '0.0.0.0' : '127.0.0.1', logger: null, templateRoot: __dirname,
origins: allowsOrigin,
authenticate: request => request.method === 'GET' && request.url?.split('?')[0] === '/login'
? true : store!.session(sessionToken(request.headers.cookie))?.account,
});
return server;
}
if (require.main === module) {
const app = createApp();
void app.run().then(running => console.log(`Dashboard: ${process.env.DASHBOARD_ORIGIN ?? `http://127.0.0.1:${(running.server.address() as { port: number }).port}`}/login`))
.catch(error => { console.error(error); process.exitCode = 1; });
}src/app.css
:root { font-family: system-ui, sans-serif; color: #e8edf5; background: #111827; color-scheme: dark; }
* { box-sizing: border-box; }
body { margin: 0; }
.home { width: min(64rem, 100%); margin: 3rem auto; padding: 0 1.5rem; }
header { display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; }
form { display: flex; align-items: center; flex-wrap: wrap; gap: .75rem; }
input, button { font: inherit; border: 1px solid #526179; border-radius: .5rem; padding: .75rem; }
input { background: #1f2937; max-width: 100%; }
button { background: #a7f3d0; color: #102c23; cursor: pointer; }
button:disabled { opacity: .5; cursor: default; }
:focus-visible { outline: 3px solid #60a5fa; outline-offset: 3px; }
.cards { margin-top: 2rem; }
.card-grid { padding: 0; list-style: none; display: grid; grid-template-columns: repeat(auto-fit, minmax(min(15rem, 100%), 1fr)); gap: 1rem; }
.card-grid li { border: 1px solid #526179; border-radius: .75rem; padding: 1.25rem; overflow-wrap: anywhere; }
h2 { font-size: 1.25rem; }
[role="alert"] { color: #fca5a5; }README.md
# Your Redweb application
Requirements: Node.js 18 or newer and npm for the realtime, chat, site, socket and http-ws templates; the dashboard template requires Node.js 22.13+ for native SQLite. Use a currently supported Node.js release in production.
For an unreleased checkout or tarball, first run `npm install --save-exact TARBALL`, replacing `TARBALL` with the absolute path to the same tested Redweb tarball used to generate this app (quote paths containing spaces). This installs the matching package and its published client dependency. Do not substitute an older registry release or `latest`. Published Redweb releases can use the installation command below directly.
```sh
npm install
npm test
npm run dev
```
HTTP starters open at http://localhost:8181; the authenticated dashboard uses http://127.0.0.1:8181/login and requires account provisioning described below. Set the `PORT` environment variable to change the listener.
`npm test` builds and runs real HTTP/WebSocket integration tests on an ephemeral loopback port. No mocks or external service are needed.
`npm run test:coverage` runs the same tests with application coverage mapped back to TypeScript. Reports are written to the ignored `coverage/` directory; this is separate from Redweb library coverage. TypeScript-generated decorator accessors can appear in function counts even when the framework does not call them. The report exposes remaining gaps; it does not certify complete application coverage. Source maps are generated during the build for diagnostics and coverage, but no coverage collector is loaded by `npm start`.
## Development and production
Edit `src/app.tsx`. `npm run dev` watches TypeScript, TSX, CSS, HTML, and the root TypeScript configuration,
then rebuilds and restarts the server. A type error stops startup until you fix it. On direct localhost access,
HTML pages refresh automatically when a new server revision is ready. If edits were detected, a keyboard-accessible
notice keeps the old document until you choose **Reload and discard drafts**. This is a conservative edit guard,
not autosave or browser hot-module replacement: restarts reset in-memory state and old socket sessions.
The generated development command sets `REDWEB_DEV_REFRESH=1`; `development: { refresh: false }` overrides it.
The refresh feature is refused under `NODE_ENV=production`, applies only to served HTML (not raw sockets or static exports),
and creates no local/session-storage copy of form contents. Use direct `localhost`, `127.x.x.x`, or `[::1]` access;
custom hostnames, tunnels and proxy-forwarded origins are not supported by this development helper.
`npm run build` checks types and copies CSS/HTML beside the compiled classes in `dist/`.
Run `npm start` to serve the compiled app. For deployment, build first, ship `dist/`, `package.json`, and the lockfile,
then install runtime dependencies with `npm ci --omit=dev`. The application does not require TypeScript or `src/` at runtime.
The standalone entrypoint calls `app.run()` on a `defineApp` definition. Importing it opens no listener and installs no process handlers. Redweb owns HTTP and WebSocket startup together, including signal handling and bounded shutdown; no generated `run-app.ts` helper is needed. Configure `startupTimeoutMs` and `shutdownTimeoutMs` on the definition (both default to five seconds). App-wide service classes acquire resources in `onInit(app, signal)` and release them in `onShutdown()`; the dashboard uses this for its auth/database resources. The dashboard's factory configures an independent private workspace but does not start it.
Repeated signals do not bypass cleanup. Failed process-owned cleanup sets a failure exit status and retains a deadline for surviving handles. Explicit `shutdown()` rejects on cleanup failures without terminating its caller. Deadlines cannot preempt synchronous code blocking Node's event loop or arbitrary operations that ignore cancellation. Tests can define an independent application from `{ ...app.options, port: 0, signals: false }` and await `run()`; app-owned state is isolated, but objects deliberately captured by page class closures remain shared unless a new class/room is created.
The shipped lifecycle tests exercise actual processes, HTTP/TCP/WebSocket peers and timers. Linux uses actual OS signals; Windows tests explicitly emit signal events inside the process because killing a Windows child does not exercise graceful POSIX signal delivery. This is not a claim that Windows console/service managers forward the same signals. Deploy with a supervisor that forwards the supported termination signal and allows longer than the configured cleanup deadline.
For public deployment, configure HTTPS/WSS at your Node server or reverse proxy, authentication, trusted origins,
and application-specific rate limits. These starters are demonstrations, not a hosted identity or database service.
Never commit secrets; `.env` is ignored but is not loaded automatically.
`npx --no-install redweb doctor --json` reports configuration problems without changing your files.
## Dependency security
This starter includes an application-root npm override for Express 4's `qs`
dependency, selecting patched `qs@6.16.0`. Keep the override when merging this
starter into an existing application, refresh its lockfile and run `npm audit`.
Overrides in Redweb's own package do not apply to installed consumers. Recheck
upstream Express/body-parser releases before removing this temporary mitigation.
# Persistent private dashboard
This recipe combines decorator-first pages, reusable live cards, validated actions, and real SQLite persistence. It is an application example, not an authentication framework or managed database.
## Run it
Requires **Node 22.13 or newer** (native `node:sqlite`, experimental in Node 22) and npm. Other Redweb starters retain their own Node requirements. Use a supported Node release in production.
After installing dependencies, create your account:
```sh
npm run add-user -- alice
npm test
npm run dev
```
The provisioning command displays a randomly generated password once. Save it securely; there are no default accounts or passwords. Open **http://127.0.0.1:8181/login** or **http://localhost:8181/login**, sign in, and add a card. A second signed-in tab updates immediately. Restart the app: your cards and unexpired credentials remain valid. Sign out all sessions to close every connected tab for that account and invalidate all its cookies.
`npm test` provisions temporary test accounts and a real temporary database, then exercises HTTP, WebSockets, isolation, restart, and session expiry. It never modifies your application database. Integration tests use no mocks, including hostile cross-loopback form and socket origins. Redweb's release gate also signs in with both valid and invalid credentials through a visible Chromium window, using `localhost` so synthetic request headers cannot hide browser-origin bugs. CI supplies a virtual display for that same headed test. A separately labelled unit test injects a cleanup error after closing a real SQLite database to verify rejection handling; it does not simulate a real operating-system failure.
`npm run test:coverage` measures the TypeScript application through source maps, separately from Redweb's own instrumented-library coverage. Login-window expiry uses the same real limiter with an explicitly short test configuration; it never waits through the production one-minute default. The report includes TypeScript-generated decorator accessor functions; inspect that distinction rather than assuming a library coverage figure applies to this recipe. The generated npm configuration enforces this recipe's Node engine requirement before installation.
## Where the behavior lives
- `app.tsx`: composition, login page, protected dashboard, listener and shutdown.
- `cards.tsx`: reusable `Cards` component and account-scoped live subscriptions. Normal TSX expressions update automatically. Forms call typed actions; feedback requires no browser glue.
- `store.ts`: prepared SQL, bounded cards/sessions, owner-filtered operations and synchronous transactions.
- `auth.ts`: asynchronous scrypt, bounded login attempts, hashed session tokens, cookies and sign-out.
- `admin.ts`: explicit local account provisioning.
## Production boundaries
Set `DASHBOARD_DATABASE` to a writable persistent file path (default `data/dashboard.sqlite`). Protect the directory with OS permissions: the database contains password hashes, private card text, and session metadata. It, its WAL/SHM files, and backups must never be served as public assets or committed. Stop the process cleanly before copying the database for a backup, or use a proper SQLite online backup facility; copying only the main file during live WAL writes is not a backup plan.
Set `NODE_ENV=production` and `DASHBOARD_ORIGIN=https://your-domain.example` behind an HTTPS reverse proxy. The origin must have no path or trailing slash. This enables Secure cookies; all session cookies are HttpOnly and SameSite=Strict. Both login/logout forms and socket upgrades require the exact trusted origin. The application does not trust Host or forwarded headers to establish origin or identity. The HTTP listener must not be publicly reachable around your TLS proxy.
Provision accounts on the same persistent volume before serving requests. Passwords use salted scrypt; only hashes of random session tokens are stored. Default sessions last one hour. Up to 32 unexpired sessions and 100 cards per account are supported. Login work is limited to four simultaneous checks and ten attempts per minute per direct peer IP, with at most 1,024 tracked IPs; clients behind one proxy share its bucket. Add appropriate proxy-level abuse controls for an Internet deployment. There is no registration, password reset, MFA, or account recovery; integrate a dedicated identity provider if your product needs those features.
SQL checks the current session and card owner inside each write transaction. Private subscriptions recheck session validity before publishing and close at expiry. Sign-out invalidates credentials before revoking Redweb sessions. An expired or disconnected page may need a reload/sign-in; the recipe does not silently retry actions with uncertain outcomes.
This is a **single-process live-update model**. SQLite transactions are synchronous and kept small; this is not a claim of unlimited concurrency. Do not put multiple app workers behind a load balancer and expect cross-worker notifications or revocation. Add a deliberate shared notification/session-revocation design before scaling horizontally. Static export cannot include protected dashboards.
Build and deploy using the shared instructions above, including the persistent data volume and the environment settings here. Neither `npm run dev` nor a process restart should erase durable cards. Redweb itself does not depend on SQLite..gitignore
node_modules/
dist/
coverage/
.env
data/
*.sqlite
*.sqlite-wal
*.sqlite-shm.npmrc
engine-strict=truesrc/store.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; }
}
}src/auth.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';
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');
});
}
}src/cards.tsx
import { action, component, state, type ActionInput, type LivePageConnectionContext, type LivePageRequestContext } from 'redweb';
import { z } from 'zod';
import { sessionToken } from './auth';
import { DashboardStore, MAX_CARDS, type Card } from './store';
const addInput = z.object({ title: z.string().trim().min(1).max(80).regex(/^[^\p{Cc}\p{Cf}]+$/u) }).strict();
const removeInput = z.object({ id: z.string().uuid() }).strict();
const tokenOf = (context: LivePageRequestContext) => sessionToken(context.request.get('cookie'));
interface Subscriber { token: string; update(): void; close(): void; }
/** Single-process notifications; SQLite remains the source of truth on every connection. */
export class PrivateCards {
private readonly accounts = new Map<string, Set<Subscriber>>();
constructor(readonly store: DashboardStore) {}
allowed(context: LivePageRequestContext) {
const session = this.store.session(tokenOf(context));
return !!session && session.account === context.principal && !context.signal.aborted;
}
subscribe(context: LivePageConnectionContext, update: (cards: Card[]) => void): () => void {
const token = tokenOf(context);
const session = this.store.session(token);
if (!session || !this.allowed(context)) throw new Error('Sign in again.');
let group = this.accounts.get(session.account);
if (!group) this.accounts.set(session.account, group = new Set());
let closed = false;
const subscriber: Subscriber = {
token, update: () => update(this.store.list(token)),
close: () => { unsubscribe(); context.socket.close(1008, 'Sign in again.'); },
};
const unsubscribe = () => {
if (closed) return;
closed = true;
clearTimeout(expiry);
context.signal.removeEventListener('abort', unsubscribe);
group.delete(subscriber);
if (!group.size && this.accounts.get(session.account) === group) this.accounts.delete(session.account);
};
const expiry = setTimeout(subscriber.close, Math.max(1, session.expires - Date.now()));
expiry.unref();
group.add(subscriber);
context.signal.addEventListener('abort', unsubscribe, { once: true });
try { subscriber.update(); }
catch (error) { unsubscribe(); throw error; }
return unsubscribe;
}
publish(account: string) {
for (const subscriber of this.accounts.get(account) ?? []) {
try {
if (this.store.session(subscriber.token)?.account === account) subscriber.update();
else subscriber.close();
} catch { subscriber.close(); }
}
}
}
@component()
export class Cards {
@state() items: Card[] = [];
private unsubscribe?: () => void;
constructor(private readonly cards: PrivateCards) {}
loading(context: LivePageRequestContext) { this.items = this.cards.store.list(tokenOf(context)); }
connected(context: LivePageConnectionContext) {
this.disconnected();
this.unsubscribe = this.cards.subscribe(context, items => { this.items = items; });
}
disconnected() { this.unsubscribe?.(); this.unsubscribe = undefined; }
disposed() { this.disconnected(); }
@action({ input: addInput })
add({ title }: ActionInput<typeof addInput>, context: LivePageConnectionContext) {
this.cards.publish(this.cards.store.add(tokenOf(context), title));
}
@action({ input: removeInput })
remove({ id }: ActionInput<typeof removeInput>, context: LivePageConnectionContext) {
this.cards.publish(this.cards.store.remove(tokenOf(context), id));
}
render() {
return <section class="cards" aria-label="Your saved cards">
<form rw-submit="add">
<label for="card-title">New card</label>
<input id="card-title" name="title" maxlength="80" required autocomplete="off" />
<button type="submit" disabled={this.items.length >= MAX_CARDS}>Add card</button>
</form>
<p>{this.items.length} / {MAX_CARDS} cards · saved automatically</p>
<ul class="card-grid">{this.items.map(card => <li key={card.id} data-card-id={card.id}>
<h2>{card.title}</h2>
<form rw-submit="remove">
<input type="hidden" name="id" value={card.id} />
<button type="submit" aria-label={`Delete ${card.title}`}>Delete</button>
</form>
</li>)}</ul>
{!this.items.length && <p>No cards yet. Add your first one above.</p>}
</section>;
}
}src/admin.ts
import { randomBytes } from 'node:crypto';
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import { credentials } from './auth';
import { databasePath } from './app';
import { DashboardStore, USERNAME } from './store';
async function main() {
const account = process.argv[2];
if (!account || !USERNAME.test(account) || process.argv.length !== 3) throw new Error('Usage: npm run add-user -- alice (3–32 lowercase letters, digits, _ or -; starts with a letter).');
const filename = databasePath();
mkdirSync(dirname(filename), { recursive: true });
const store = new DashboardStore(filename);
try {
const password = randomBytes(24).toString('base64url');
store.provision(account, await credentials(password));
console.log(`Created ${account}. Store this password safely; it is displayed only once:\n${password}`);
} finally { store.close(); }
}
void main().catch(error => { console.error(error.message); process.exitCode = 1; });