Authentication and authorisation
Numeralens ships working authentication and server-enforced authorisation, not a placeholder. Sessions are signed cookies, every data route checks a permission before it answers, and the demo exists to let you see that happen.
It is still not auth-opinionated: there is no bundled identity provider to fight with. The session layer is one small file you can replace outright.
How it fits together
| Layer | File | Job |
|---|---|---|
| Session | src/lib/auth/session.ts |
Sign, verify and read a session cookie |
| Directory | src/lib/auth/users.ts |
Verify credentials, return a SessionUser |
| Enforcement | src/lib/auth/dal.ts |
requireSession / requirePermission — the security boundary |
| Pages | src/proxy.ts |
Send signed-out visitors to /login; answer 403 for pages the role lacks |
| Presentation | src/providers/auth-provider.tsx |
can() — decides what to render |
The split matters. dal.ts decides what a user may receive. The provider
decides what they see. The two are independent on purpose: the client copy of
the role lives in a cookie the user holds, so it is a hint, not an authority.
Editing the provider changes the UI and nothing about access.
proxy.ts guards pages, not data. It verifies the session and sends signed-out
visitors to /login. For a signed-in role it looks up the page's permission in
routePermissionMap (derived from src/config/navigation.ts) and answers 403
with an access-denied page when the role lacks it, so a report hidden from the
menu can't be opened by typing its URL. Data still has its own boundary in
dal.ts: when you connect your own backend, enforce permissions there too.
Search and notifications span every entity, so they use the same rule item by
item: canOpen(role, href) keeps a result only if the role could open the page
it links to. /api/search and /api/notifications apply it on the server, and
the Ctrl+K palette and notification bell apply it again in the browser for
demo mode, where those lists are computed client-side.
Next.js 16 note. The
middleware.tsconvention is deprecated and renamed toproxy.ts, exportingproxy. A file namedmiddleware.tswill not run.
Signing in
/login posts to a server action that verifies credentials and issues the
session. Passwords are hashed with scrypt and a per-password salt, compared in
constant time, and a wrong password and an unknown address return the same
message — otherwise the form becomes a way to enumerate your users. Attempts are
rate limited to ten per five minutes per address.
Demo accounts
Demo mode seeds one account per role, all with the password demo1234, listed
on the sign-in screen. Sign in as Viewer and the ledger, transactions,
budget and inventory pages disappear — then try curling /api/general-ledger
with that session and you get 403, not data. That is the point of shipping
the demo with real auth rather than an auto-login.
The role switcher in the top bar re-issues the session with a new role, so the server enforces the switch too. It refuses when demo mode is off; without that check it would be a privilege-escalation endpoint.
Enforcing permissions on a route
Data routes declare what they require. handle() and aiRoute() check it
against the verified session before the handler runs:
// src/app/api/general-ledger/route.ts
export const GET = handle((req) => engine.getGeneralLedger(parseFilters(req)), "view:ledger");
A route that passes no permission still requires a signed-in session. Failures
return 401 unauthenticated or 403 forbidden as JSON — never a redirect to an
HTML page, which would break every fetch in the app.
In a Server Component or Server Action, call the DAL directly:
import { requirePermission } from "@/lib/auth/dal";
export default async function LedgerPage() {
await requirePermission("view:ledger");
// ...
}
Roles and permissions
Five roles ship in src/config/roles.ts:
| Role | Intent |
|---|---|
admin |
Everything, including user management |
finance_manager |
Everything except user management |
accountant |
Reports, ledger, transactions, customers, vendors |
analyst |
Analytics and dashboards; no ledger detail |
viewer |
Read-only dashboard and reports |
Permissions are strings such as view:ledger, edit:dashboard, export:data,
manage:settings. rolePermissions maps one to the other; the matrix is visible
in the app at Settings → Users & roles.
To add one: extend the Permission union, add it to the roles that should have
it, tag the navigation entry, and pass it to the route that serves the data —
the last step is the one that actually protects anything.
{ label: "Payroll", href: "/payroll", permission: "view:payroll" }
export const GET = handle((req) => getPayroll(req), "view:payroll");
Multi-tenant data isolation
The demo is one organisation (Northstar Holdings) with several legal entities.
The entity switcher, companyId, branchId and departmentId are reporting
filters inside that organisation, not security boundaries.
When you connect your own backend, the browser calls your API directly with
the user's credentials (NEXT_PUBLIC_AUTH_MODE bearer or cookie). Your API
must decide the tenant from the authenticated principal, never from anything
the browser sends. Query parameters, headers like X-Tenant-Id and record
ids are all attacker-controlled. Concretely:
- Resolve the tenant from the verified token or session on every request.
- Scope every query by that tenant, including lookups by id
(
/transactions/:id), search and exports. - Check that a requested
companyIdbelongs to the tenant before filtering by it. - For a record in another tenant, answer 404 rather than 403, so ids can't be probed.
Run a contract test like this against your API before going live. It's the
API-level version of tests/route-matrix.test.ts:
// Two real tenants, each with one known record. Tokens come from your IdP's test users.
const A = { token: process.env.TENANT_A_TOKEN!, txId: "…a transaction in A…", companyId: "…an entity in A…" };
const B = { token: process.env.TENANT_B_TOKEN!, txId: "…a transaction in B…", companyId: "…an entity in B…" };
const get = (who: typeof A, path: string) => fetch(`${API}${path}`, { headers: { Authorization: `Bearer ${who.token}` } });
it("never returns another tenant's record by id", async () => {
expect((await get(A, `/transactions/${B.txId}`)).status).toBe(404);
});
it("ignores a company id from another tenant", async () => {
const res = await get(A, `/general-ledger?companyId=${B.companyId}`);
expect([403, 404]).toContain(res.status); // or 200 with zero B rows, if you scope silently
});
it("ignores a spoofed tenant header", async () => {
const res = await fetch(`${API}/general-ledger`, { headers: { Authorization: `Bearer ${A.token}`, "X-Tenant-Id": "B" } });
const body = await res.json();
expect(JSON.stringify(body)).not.toContain(B.txId);
});
it("keeps search and lists inside the tenant", async () => {
for (const path of ["/search?q=a", "/transactions?pageSize=500", "/customers"]) {
expect(JSON.stringify(await (await get(A, path)).json())).not.toContain(B.txId);
}
});
Connecting your own identity provider
Replace src/lib/auth/users.ts with a query against your user table, or replace
src/lib/auth/session.ts wholesale if you already issue sessions. Everything
downstream depends only on getSession() returning a SessionUser, so nothing
else changes — including the 26 route guards.
Map your provider's roles onto Role at that boundary. If your roles do not fit
the five here, change the union in src/config/roles.ts; it is a plain type.
Before you deploy
- Set
AUTH_SECRET—openssl rand -base64 32. With demo mode off in production the app refuses to start without it, rather than falling back to the public development key. - Replace the demo directory.
src/lib/auth/users.tscontains five accounts with a published password. - Decide about revocation. Sessions are stateless JWTs, so signing out
clears the cookie but cannot invalidate an already-issued token before it
expires (8 hours). If you need immediate revocation, move to database
sessions — keep
getSession()'s signature and nothing else changes. - Keep enforcement server-side. If you add a route, give it a permission.
tests/auth.test.tscovers the session and the matrix, but it cannot know about a route you forgot to guard. - Filter cross-entity endpoints in your backend. If your API serves search
or notifications, drop the items a role can't open before you return them,
as
src/app/api/search/route.tsdoes. Filtering only in the browser is presentation, not access control.