Phase 1: identity, sessions, audit, frontend shell
AD sign-in over LDAPS (search with the service account, bind as the user, nested groups through LDAP_MATCHING_RULE_IN_CHAIN, disabled accounts refused), roles as the union of PS-* groups mapped by a table derived from the seeded departments. Server-side sessions with idle, lock and absolute timeouts, Origin and X-Requested-With check, step-up unlock. Optional Argon2id PIN set with the domain password; PIN sign-in by employee ID on registered devices only; five wrong attempts disable the PIN, three wrong at unlock or signature end the session. Rate limits per account and per address before any bind. Devices, signatures table and sign helper, audit rows for every identity event, SSE over LISTEN/NOTIFY with presence. Account settings and Admin APIs and screens (AD view, devices, PIN clearing, group map with missing-group flags, refresh from AD now). CLI ad-groups --list and ad-refresh. Migration 0002. Frontend: real sign-in (password tab, PIN keypad on registered devices), lock screen, role switcher, Account settings, Admin shell, screen placeholders. CI: Samba AD DC container (PSTEST.LOCAL) with a generated CA, 49 of the 50 groups plus one extra, 17 test users; wired into the CI compose overlay and the Gitea workflow; Playwright sign-in scenario. Verified on docker-1: 171 server tests green inside the CI stack against PostgreSQL and the Samba DC, 48 frontend tests, 8 Playwright scenarios against the live stack (password and PIN sign-in, lock and unlock, Admin group map). Findings recorded in the docs: the DC needs CAP_SYS_ADMIN, a hidden tab locks only after a minute as the old build did, and the app uses the alias ps-app for Playwright because "app" is on Chromium's HSTS preload list. Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
@@ -0,0 +1,231 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { ApiError, errorCode, onApiError } from "../api/client";
|
||||
import { authApi, departmentsApi } from "./api";
|
||||
import { AuthCtx, type AuthState, type AuthStatus } from "./context";
|
||||
import { roleLabel as labelFor } from "./roles";
|
||||
import type { Department, Factor, Me } from "./types";
|
||||
import { useEvents } from "./useEvents";
|
||||
|
||||
/** The old build's screen lock. The server locks at SESSION_LOCK_MINUTES too; it is the authority. */
|
||||
export const IDLE_LOCK_MS = 3 * 60_000;
|
||||
/** A tab hidden for longer than this comes back locked (the old build's rule). */
|
||||
export const HIDDEN_LOCK_MS = 60_000;
|
||||
const IDLE_CHECK_MS = 15_000;
|
||||
const ACTIVITY_EVENTS = ["pointerdown", "keydown", "wheel", "touchstart"] as const;
|
||||
|
||||
/** 401 codes that mean this browser's session is gone. Other 401s (a wrong unlock PIN) are not. */
|
||||
const SESSION_GONE = new Set(["no_session", "session_expired", "session_ended"]);
|
||||
|
||||
function goneNotice(err: ApiError): string {
|
||||
const code = errorCode(err);
|
||||
if (code === "no_session") return "Your session ended. Sign in again.";
|
||||
return err.message || "Your session ended. Sign in again.";
|
||||
}
|
||||
|
||||
interface AuthProviderProps {
|
||||
children: ReactNode;
|
||||
/** Idle time before the local lock. Tests pass a small value. */
|
||||
idleLockMs?: number;
|
||||
/** How often the idle timer checks. */
|
||||
idleCheckMs?: number;
|
||||
/** Hidden time after which the tab comes back locked. Tests pass a small value. */
|
||||
hiddenLockMs?: number;
|
||||
}
|
||||
|
||||
export function AuthProvider({ children, idleLockMs = IDLE_LOCK_MS, idleCheckMs = IDLE_CHECK_MS, hiddenLockMs = HIDDEN_LOCK_MS }: AuthProviderProps) {
|
||||
const [status, setStatusState] = useState<AuthStatus>("loading");
|
||||
const [me, setMeState] = useState<Me | null>(null);
|
||||
const [departments, setDepartments] = useState<Department[]>([]);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
const statusRef = useRef<AuthStatus>("loading");
|
||||
const lastActivity = useRef(Date.now());
|
||||
const deptsFor = useRef<string | null>(null);
|
||||
|
||||
const setStatus = useCallback((s: AuthStatus) => {
|
||||
statusRef.current = s;
|
||||
setStatusState(s);
|
||||
}, []);
|
||||
|
||||
const accept = useCallback(
|
||||
(m: Me) => {
|
||||
setMeState(m);
|
||||
setNotice(null);
|
||||
lastActivity.current = Date.now();
|
||||
setStatus(m.session.locked ? "locked" : "ready");
|
||||
},
|
||||
[setStatus],
|
||||
);
|
||||
|
||||
const endSession = useCallback(
|
||||
(msg: string | null) => {
|
||||
setMeState(null);
|
||||
setDepartments([]);
|
||||
deptsFor.current = null;
|
||||
setNotice(msg);
|
||||
setStatus("anonymous");
|
||||
},
|
||||
[setStatus],
|
||||
);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
accept(await authApi.me());
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 423) setStatus("locked");
|
||||
else if (err instanceof ApiError && err.status === 401) endSession(null);
|
||||
else endSession(err instanceof Error ? err.message : "Could not reach the server.");
|
||||
}
|
||||
}, [accept, endSession, setStatus]);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
// 401 and 423 from any call, not only the auth calls.
|
||||
useEffect(
|
||||
() =>
|
||||
onApiError((err, path) => {
|
||||
if (path.startsWith("/api/auth/signin")) return;
|
||||
const st = statusRef.current;
|
||||
if (st === "loading" || st === "anonymous") return;
|
||||
if (err.status === 423) {
|
||||
setStatus("locked");
|
||||
} else if (err.status === 401 && SESSION_GONE.has(errorCode(err) ?? "")) {
|
||||
endSession(goneNotice(err));
|
||||
}
|
||||
}),
|
||||
[endSession, setStatus],
|
||||
);
|
||||
|
||||
// Department names for the role labels, once per signed-in user.
|
||||
const userId = me?.user.id ?? null;
|
||||
useEffect(() => {
|
||||
if (status !== "ready" || !userId || deptsFor.current === userId) return;
|
||||
deptsFor.current = userId;
|
||||
departmentsApi
|
||||
.list()
|
||||
.then((d) => setDepartments(Array.isArray(d) ? d : []))
|
||||
.catch(() => {
|
||||
deptsFor.current = null;
|
||||
});
|
||||
}, [status, userId]);
|
||||
|
||||
const signInPassword = useCallback(
|
||||
async (login: string, password: string) => {
|
||||
const m = await authApi.signInPassword(login, password);
|
||||
accept(m);
|
||||
return m;
|
||||
},
|
||||
[accept],
|
||||
);
|
||||
|
||||
const signInPin = useCallback(
|
||||
async (empNo: string, pin: string) => {
|
||||
const m = await authApi.signInPin(empNo, pin);
|
||||
accept(m);
|
||||
return m;
|
||||
},
|
||||
[accept],
|
||||
);
|
||||
|
||||
const signOut = useCallback(async () => {
|
||||
try {
|
||||
await authApi.signOut();
|
||||
} catch {
|
||||
// The cookie may already be gone. Signing out locally is what matters here.
|
||||
}
|
||||
endSession(null);
|
||||
}, [endSession]);
|
||||
|
||||
const unlock = useCallback(
|
||||
async (factor: Factor, secret: string) => {
|
||||
const m = await authApi.unlock(factor, secret);
|
||||
accept({ ...m, session: { ...m.session, locked: false } });
|
||||
return m;
|
||||
},
|
||||
[accept],
|
||||
);
|
||||
|
||||
const lock = useCallback(async () => {
|
||||
if (statusRef.current !== "ready") return;
|
||||
setStatus("locked");
|
||||
try {
|
||||
await authApi.lock();
|
||||
} catch {
|
||||
// A 401 here signs out through the listener. Otherwise the local lock stands.
|
||||
}
|
||||
}, [setStatus]);
|
||||
|
||||
// Hidden is reported, never locked at once: a reload or navigation fires hidden on the old page.
|
||||
// Coming back is reported, then Me decides. Hidden longer than hiddenLockMs locks locally right away.
|
||||
const hiddenAt = useRef<number | null>(null);
|
||||
useEffect(() => {
|
||||
const onVisibility = () => {
|
||||
const st = statusRef.current;
|
||||
if (st !== "ready" && st !== "locked") return;
|
||||
if (document.hidden) {
|
||||
hiddenAt.current = Date.now();
|
||||
authApi.visibility(true).catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
const since = hiddenAt.current;
|
||||
hiddenAt.current = null;
|
||||
if (since !== null && Date.now() - since > hiddenLockMs && st === "ready") setStatus("locked");
|
||||
authApi
|
||||
.visibility(false)
|
||||
.catch(() => undefined)
|
||||
.then(() => refresh());
|
||||
};
|
||||
document.addEventListener("visibilitychange", onVisibility);
|
||||
return () => document.removeEventListener("visibilitychange", onVisibility);
|
||||
}, [setStatus, refresh, hiddenLockMs]);
|
||||
|
||||
// Local idle lock.
|
||||
useEffect(() => {
|
||||
const bump = () => {
|
||||
lastActivity.current = Date.now();
|
||||
};
|
||||
for (const ev of ACTIVITY_EVENTS) document.addEventListener(ev, bump, { capture: true, passive: true });
|
||||
return () => {
|
||||
for (const ev of ACTIVITY_EVENTS) document.removeEventListener(ev, bump, { capture: true });
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (status !== "ready") return;
|
||||
lastActivity.current = Date.now();
|
||||
const id = window.setInterval(() => {
|
||||
if (Date.now() - lastActivity.current >= idleLockMs) void lock();
|
||||
}, idleCheckMs);
|
||||
return () => window.clearInterval(id);
|
||||
}, [status, idleLockMs, idleCheckMs, lock]);
|
||||
|
||||
const sessionId = status === "ready" || status === "locked" ? (me?.session.id ?? null) : null;
|
||||
const presence = useEvents(sessionId, {
|
||||
onRevoked: () => endSession("This session was signed out from another place."),
|
||||
});
|
||||
|
||||
const roleLabel = useCallback((role: string) => labelFor(role, departments), [departments]);
|
||||
|
||||
const value = useMemo<AuthState>(
|
||||
() => ({
|
||||
status,
|
||||
me,
|
||||
departments,
|
||||
notice,
|
||||
presence,
|
||||
refresh,
|
||||
signInPassword,
|
||||
signInPin,
|
||||
signOut,
|
||||
endSession,
|
||||
unlock,
|
||||
lock,
|
||||
setMe: setMeState,
|
||||
roleLabel,
|
||||
}),
|
||||
[status, me, departments, notice, presence, refresh, signInPassword, signInPin, signOut, endSession, unlock, lock, roleLabel],
|
||||
);
|
||||
|
||||
return <AuthCtx.Provider value={value}>{children}</AuthCtx.Provider>;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// Typed calls for the phase 1 endpoints. Paths and shapes follow the design contract.
|
||||
import { api } from "../api/client";
|
||||
import type {
|
||||
AccessLogRow,
|
||||
AccountInfo,
|
||||
AdLookup,
|
||||
AdRefreshResult,
|
||||
AdminDevice,
|
||||
AdminUser,
|
||||
AdminUserDetail,
|
||||
AuthContextInfo,
|
||||
Department,
|
||||
DeviceRef,
|
||||
Factor,
|
||||
GroupMap,
|
||||
Me,
|
||||
PinState,
|
||||
SessionRow,
|
||||
SigninAttempt,
|
||||
} from "./types";
|
||||
|
||||
const enc = encodeURIComponent;
|
||||
|
||||
export const authApi = {
|
||||
context: (signal?: AbortSignal) => api.get<AuthContextInfo>("/api/auth/context", signal),
|
||||
me: (signal?: AbortSignal) => api.get<Me>("/api/auth/me", signal),
|
||||
signInPassword: (login: string, password: string) =>
|
||||
api.post<Me>("/api/auth/signin/password", { login, password }),
|
||||
signInPin: (emp_no: string, pin: string) => api.post<Me>("/api/auth/signin/pin", { emp_no, pin }),
|
||||
signOut: () => api.post<null>("/api/auth/signout"),
|
||||
lock: () => api.post<null>("/api/auth/lock"),
|
||||
visibility: (hidden: boolean) => api.post<null>("/api/auth/visibility", { hidden }),
|
||||
unlock: (factor: Factor, secret: string) => api.post<Me>("/api/auth/unlock", { factor, secret }),
|
||||
};
|
||||
|
||||
export const accountApi = {
|
||||
get: (signal?: AbortSignal) => api.get<AccountInfo>("/api/account", signal),
|
||||
setPin: (password: string, pin: string) =>
|
||||
api.post<{ pin: PinState }>("/api/account/pin", { password, pin }),
|
||||
sessions: (signal?: AbortSignal) => api.get<SessionRow[]>("/api/account/sessions", signal),
|
||||
signOutOthers: () => api.post<{ revoked: number }>("/api/account/sessions/signout-others"),
|
||||
accessLog: (limit = 50, signal?: AbortSignal) =>
|
||||
api.get<AccessLogRow[]>(`/api/account/access-log?limit=${limit}`, signal),
|
||||
registerDevice: (name: string) => api.post<{ device: DeviceRef }>("/api/account/device", { name }),
|
||||
};
|
||||
|
||||
export const adminApi = {
|
||||
users: (q: string, signal?: AbortSignal) =>
|
||||
api.get<AdminUser[]>(q ? `/api/admin/users?q=${enc(q)}` : "/api/admin/users", signal),
|
||||
user: (id: string, signal?: AbortSignal) => api.get<AdminUserDetail>(`/api/admin/users/${enc(id)}`, signal),
|
||||
lookup: (login: string, signal?: AbortSignal) =>
|
||||
api.get<AdLookup>(`/api/admin/ad/lookup?login=${enc(login)}`, signal),
|
||||
clearPin: (id: string, reason: string) =>
|
||||
api.delWithBody<null>(`/api/admin/users/${enc(id)}/pin`, { reason }),
|
||||
devices: (signal?: AbortSignal) => api.get<AdminDevice[]>("/api/admin/devices", signal),
|
||||
revokeDevice: (id: string) => api.del<null>(`/api/admin/devices/${enc(id)}`),
|
||||
groups: (signal?: AbortSignal) => api.get<GroupMap>("/api/admin/groups", signal),
|
||||
refresh: () => api.post<AdRefreshResult>("/api/admin/ad/refresh"),
|
||||
signinAttempts: (limit = 100, signal?: AbortSignal) =>
|
||||
api.get<SigninAttempt[]>(`/api/admin/signin-attempts?limit=${limit}`, signal),
|
||||
};
|
||||
|
||||
export const departmentsApi = {
|
||||
list: (signal?: AbortSignal) => api.get<Department[]>("/api/departments", signal),
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import { createContext } from "react";
|
||||
import type { Department, Factor, Me, PresenceUser } from "./types";
|
||||
|
||||
export type AuthStatus = "loading" | "anonymous" | "ready" | "locked";
|
||||
|
||||
export interface AuthState {
|
||||
status: AuthStatus;
|
||||
/** Null while loading, when signed out, and when a 423 arrived before /me answered. */
|
||||
me: Me | null;
|
||||
departments: Department[];
|
||||
/** Shown on the sign-in page once, for example after a session ended. */
|
||||
notice: string | null;
|
||||
presence: PresenceUser[];
|
||||
refresh: () => Promise<void>;
|
||||
signInPassword: (login: string, password: string) => Promise<Me>;
|
||||
signInPin: (empNo: string, pin: string) => Promise<Me>;
|
||||
signOut: () => Promise<void>;
|
||||
/** Drops the session in the browser without calling the server, with a notice for the sign-in page. */
|
||||
endSession: (notice: string | null) => void;
|
||||
unlock: (factor: Factor, secret: string) => Promise<Me>;
|
||||
lock: () => Promise<void>;
|
||||
/** Replaces the cached Me, for example after a PIN change. */
|
||||
setMe: (me: Me) => void;
|
||||
roleLabel: (role: string) => string;
|
||||
}
|
||||
|
||||
export const AuthCtx = createContext<AuthState | null>(null);
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DEPARTMENTS } from "../test/auth";
|
||||
import type { Department } from "./types";
|
||||
import { firstScreen, homePath, roleChipClass, roleFromKind, roleLabel, screensFor } from "./roles";
|
||||
|
||||
const depts = DEPARTMENTS as Department[];
|
||||
|
||||
describe("roles", () => {
|
||||
it("labels shop and office roles", () => {
|
||||
expect(roleLabel("shop:03:supervisor", depts)).toBe("03 Weld Parts · Supervisor");
|
||||
expect(roleLabel("shop:09:lead")).toBe("09 · Lead");
|
||||
expect(roleLabel("clerical_supervisor")).toBe("Clerical supervisor");
|
||||
expect(roleLabel("qc")).toBe("Q.C.");
|
||||
expect(roleLabel("pm")).toBe("Project Management");
|
||||
expect(roleLabel("admin")).toBe("Admin");
|
||||
});
|
||||
|
||||
it("maps roles to screens", () => {
|
||||
expect(screensFor(["clerical", "shop:06:supervisor"])).toEqual(["clerical", "supervisor", "stall"]);
|
||||
expect(screensFor(["shop:03:worker"])).toEqual(["stall"]);
|
||||
expect(screensFor(["warehouse_supervisor", "qc"])).toEqual(["warehouse", "qc"]);
|
||||
expect(screensFor(["admin"])).toHaveLength(7);
|
||||
});
|
||||
|
||||
it("lands on the first non-admin screen", () => {
|
||||
expect(firstScreen(["admin", "clerical"])).toBe("clerical");
|
||||
expect(firstScreen(["admin"])).toBe("admin");
|
||||
expect(homePath(["stall", "supervisor"])).toBe("/supervisor");
|
||||
expect(homePath([])).toBe("/account");
|
||||
});
|
||||
|
||||
it("builds role strings from kinds and picks chip colours", () => {
|
||||
expect(roleFromKind("shop_lead", "03")).toBe("shop:03:lead");
|
||||
expect(roleFromKind("qc_supervisor", "QC")).toBe("qc_supervisor");
|
||||
expect(roleChipClass("shop:03:supervisor")).toBe("rchip supervisor");
|
||||
expect(roleChipClass("admin")).toBe("rchip admin");
|
||||
expect(roleChipClass("clerical")).toBe("rchip");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
// Role strings, the static role-to-screen map and the labels.
|
||||
// The server decides access on every request. This file only shapes the screens.
|
||||
import type { Department } from "./types";
|
||||
|
||||
/** Screens in the order the role switcher shows them (the old build's order). */
|
||||
export const SCREENS = ["clerical", "warehouse", "supervisor", "stall", "qc", "pm", "admin"] as const;
|
||||
export type Screen = (typeof SCREENS)[number];
|
||||
|
||||
export const SCREEN_LABELS: Record<Screen, string> = {
|
||||
clerical: "Clerical",
|
||||
warehouse: "Warehouse",
|
||||
supervisor: "Supervisor",
|
||||
stall: "Weld Stall",
|
||||
qc: "Q.C.",
|
||||
pm: "Project Mgmt",
|
||||
admin: "Admin",
|
||||
};
|
||||
|
||||
/** The phase in which each placeholder screen gets its real content. */
|
||||
export const SCREEN_PHASE: Record<Exclude<Screen, "admin">, number> = {
|
||||
clerical: 2,
|
||||
warehouse: 4,
|
||||
supervisor: 5,
|
||||
stall: 5,
|
||||
qc: 6,
|
||||
pm: 8,
|
||||
};
|
||||
|
||||
export function isScreen(s: string | undefined): s is Screen {
|
||||
return s !== undefined && (SCREENS as readonly string[]).includes(s);
|
||||
}
|
||||
|
||||
export type ShopLevel = "worker" | "lead" | "supervisor";
|
||||
|
||||
export type ParsedRole =
|
||||
| { shop: false; kind: string }
|
||||
| { shop: true; dept: string; level: ShopLevel };
|
||||
|
||||
const SHOP_LEVELS: readonly ShopLevel[] = ["worker", "lead", "supervisor"];
|
||||
|
||||
/** "shop:03:supervisor" -> shop role; anything else is an office role kind. */
|
||||
export function parseRole(role: string): ParsedRole {
|
||||
const m = /^shop:([^:]+):(worker|lead|supervisor)$/.exec(role);
|
||||
if (m && m[1] !== undefined && m[2] !== undefined) {
|
||||
return { shop: true, dept: m[1], level: m[2] as ShopLevel };
|
||||
}
|
||||
return { shop: false, kind: role };
|
||||
}
|
||||
|
||||
/** Turns a role kind and department ("shop_lead", "03") into the role string ("shop:03:lead"). */
|
||||
export function roleFromKind(kind: string, dept: string | null): string {
|
||||
if (kind.includes(":")) return kind;
|
||||
const m = /^shop_(worker|lead|supervisor)$/.exec(kind);
|
||||
if (m && m[1] && dept) return `shop:${dept}:${m[1]}`;
|
||||
return kind;
|
||||
}
|
||||
|
||||
/** The static map. Same rule as the server's screens_for(roles). */
|
||||
export function screensFor(roles: readonly string[]): Screen[] {
|
||||
const out = new Set<Screen>();
|
||||
for (const r of roles) {
|
||||
const p = parseRole(r);
|
||||
if (p.shop) {
|
||||
out.add("stall");
|
||||
if (p.level !== "worker") out.add("supervisor");
|
||||
continue;
|
||||
}
|
||||
if (p.kind === "clerical" || p.kind === "clerical_supervisor") out.add("clerical");
|
||||
else if (p.kind.startsWith("warehouse")) out.add("warehouse");
|
||||
else if (p.kind.startsWith("qc")) out.add("qc");
|
||||
else if (p.kind === "pm") out.add("pm");
|
||||
else if (p.kind === "admin") SCREENS.forEach((s) => out.add(s));
|
||||
}
|
||||
return SCREENS.filter((s) => out.has(s));
|
||||
}
|
||||
|
||||
/** Known screens from a server list, in switcher order. */
|
||||
export function orderScreens(list: readonly string[]): Screen[] {
|
||||
return SCREENS.filter((s) => list.includes(s));
|
||||
}
|
||||
|
||||
/** The screen a user lands on: the first non-admin screen, else admin, else null. */
|
||||
export function firstScreen(list: readonly string[]): Screen | null {
|
||||
const ordered = orderScreens(list);
|
||||
return ordered.find((s) => s !== "admin") ?? ordered[0] ?? null;
|
||||
}
|
||||
|
||||
export function homePath(list: readonly string[]): string {
|
||||
const s = firstScreen(list);
|
||||
return s ? `/${s}` : "/account";
|
||||
}
|
||||
|
||||
const OFFICE_LABELS: Record<string, string> = {
|
||||
admin: "Admin",
|
||||
clerical: "Clerical",
|
||||
clerical_supervisor: "Clerical supervisor",
|
||||
warehouse: "Warehouse",
|
||||
warehouse_supervisor: "Warehouse supervisor",
|
||||
qc: "Q.C.",
|
||||
qc_supervisor: "Q.C. supervisor",
|
||||
pm: "Project Management",
|
||||
};
|
||||
|
||||
const LEVEL_LABELS: Record<ShopLevel, string> = { worker: "Worker", lead: "Lead", supervisor: "Supervisor" };
|
||||
|
||||
/** "shop:03:supervisor" -> "03 Weld Parts · Supervisor". Office roles get their plain name. */
|
||||
export function roleLabel(role: string, departments: readonly Department[] = []): string {
|
||||
const p = parseRole(role);
|
||||
if (!p.shop) return OFFICE_LABELS[p.kind] ?? p.kind;
|
||||
const dept = departments.find((d) => d.code === p.dept);
|
||||
const where = dept ? `${p.dept} ${dept.name}` : p.dept;
|
||||
return `${where} · ${LEVEL_LABELS[p.level]}`;
|
||||
}
|
||||
|
||||
/** The .rchip variant for a role: supervisors pink, leads green, admin amber. */
|
||||
export function roleChipClass(role: string): string {
|
||||
const p = parseRole(role);
|
||||
if (p.shop) return p.level === "worker" ? "rchip" : `rchip ${p.level}`;
|
||||
if (p.kind === "admin") return "rchip admin";
|
||||
if (p.kind.endsWith("_supervisor")) return "rchip supervisor";
|
||||
return "rchip";
|
||||
}
|
||||
|
||||
/** Office roles first in a fixed order, then shop roles by department and level. */
|
||||
export function sortRoles(roles: readonly string[]): string[] {
|
||||
const office = Object.keys(OFFICE_LABELS);
|
||||
const rank = (r: string): [number, string, number] => {
|
||||
const p = parseRole(r);
|
||||
if (!p.shop) return [0, "", office.includes(p.kind) ? office.indexOf(p.kind) : office.length];
|
||||
return [1, p.dept, SHOP_LEVELS.indexOf(p.level)];
|
||||
};
|
||||
return [...roles].sort((a, b) => {
|
||||
const [a0, a1, a2] = rank(a);
|
||||
const [b0, b1, b2] = rank(b);
|
||||
return a0 - b0 || a1.localeCompare(b1) || a2 - b2;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
// API shapes from the phase 1 design contract. IDs stay text. Timestamps are ISO strings.
|
||||
|
||||
export type SessionKind = "password" | "pin";
|
||||
export type Factor = "password" | "pin";
|
||||
|
||||
export interface DeviceRef {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface UserInfo {
|
||||
id: string;
|
||||
sam_account: string;
|
||||
upn: string | null;
|
||||
display_name: string;
|
||||
emp_no: string | null;
|
||||
email: string | null;
|
||||
}
|
||||
|
||||
export interface PinState {
|
||||
set: boolean;
|
||||
disabled: boolean;
|
||||
}
|
||||
|
||||
export interface SessionInfo {
|
||||
id: string;
|
||||
kind: SessionKind;
|
||||
created_at: string;
|
||||
expires_at: string;
|
||||
locked: boolean;
|
||||
locked_since: string | null;
|
||||
device: DeviceRef | null;
|
||||
}
|
||||
|
||||
/** GET /api/auth/me and every sign-in or unlock answer. */
|
||||
export interface Me {
|
||||
user: UserInfo;
|
||||
roles: string[];
|
||||
screens: string[];
|
||||
groups: string[];
|
||||
session: SessionInfo;
|
||||
pin: PinState;
|
||||
can_register_device: boolean;
|
||||
}
|
||||
|
||||
/** GET /api/auth/context. No session needed. */
|
||||
export interface AuthContextInfo {
|
||||
device: DeviceRef | null;
|
||||
stack: string;
|
||||
insecure_ldap: boolean;
|
||||
pin_digits: { min: number; max: number };
|
||||
}
|
||||
|
||||
/** GET /api/account. */
|
||||
export interface AccountInfo {
|
||||
user: UserInfo;
|
||||
groups: string[];
|
||||
roles: string[];
|
||||
pin: PinState;
|
||||
ad_synced_at: string | null;
|
||||
}
|
||||
|
||||
/** One row of GET /api/account/sessions. Admin user detail uses the same shape. */
|
||||
export interface SessionRow {
|
||||
id: string;
|
||||
kind: SessionKind;
|
||||
created_at: string;
|
||||
last_seen_at: string;
|
||||
ip: string | null;
|
||||
user_agent: string | null;
|
||||
device: DeviceRef | null;
|
||||
current?: boolean;
|
||||
}
|
||||
|
||||
/** One row of GET /api/account/access-log. */
|
||||
export interface AccessLogRow {
|
||||
at: string;
|
||||
action: string;
|
||||
detail: unknown;
|
||||
ip: string | null;
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
export interface UserFlags {
|
||||
emp_missing: boolean;
|
||||
emp_duplicate: boolean;
|
||||
disabled: boolean;
|
||||
}
|
||||
|
||||
/** One row of GET /api/admin/users. */
|
||||
export interface AdminUser {
|
||||
id: string;
|
||||
sam_account: string;
|
||||
display_name: string;
|
||||
emp_no: string | null;
|
||||
email: string | null;
|
||||
active: boolean;
|
||||
roles: string[];
|
||||
pin: PinState;
|
||||
flags: UserFlags;
|
||||
last_signin_at: string | null;
|
||||
ad_synced_at: string | null;
|
||||
}
|
||||
|
||||
/** GET /api/admin/users/{id}. */
|
||||
export interface AdminUserDetail extends AdminUser {
|
||||
groups: string[];
|
||||
/** "cache" when AD was unreachable. Absent or "live" otherwise. */
|
||||
groups_source?: string;
|
||||
sessions: SessionRow[];
|
||||
note: string;
|
||||
}
|
||||
|
||||
/** GET /api/admin/ad/lookup. */
|
||||
export interface AdLookup {
|
||||
found: boolean;
|
||||
user?: Partial<UserInfo> | null;
|
||||
groups?: string[];
|
||||
roles?: string[];
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
/** One row of GET /api/admin/devices. */
|
||||
export interface AdminDevice {
|
||||
id: string;
|
||||
name: string;
|
||||
registered_by: { id: string; display_name: string } | null;
|
||||
registered_at: string | null;
|
||||
last_seen_at: string | null;
|
||||
revoked_at: string | null;
|
||||
active_sessions: number;
|
||||
}
|
||||
|
||||
export interface GroupRow {
|
||||
name: string;
|
||||
/** A role kind ("shop_supervisor") or a role string ("shop:03:supervisor"). Both are handled. */
|
||||
role: string;
|
||||
dept_code: string | null;
|
||||
in_ad: boolean | null;
|
||||
}
|
||||
|
||||
/** GET /api/admin/groups. */
|
||||
export interface GroupMap {
|
||||
checked_at: string | null;
|
||||
ad_reachable: boolean;
|
||||
groups: GroupRow[];
|
||||
extra_in_ou: string[];
|
||||
}
|
||||
|
||||
/** POST /api/admin/ad/refresh. */
|
||||
export interface AdRefreshResult {
|
||||
groups_checked: number;
|
||||
groups_missing: string[];
|
||||
users_seen: number;
|
||||
created: number;
|
||||
updated: number;
|
||||
deactivated: number;
|
||||
emp_missing: string[];
|
||||
emp_duplicate: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* One row of GET /api/admin/signin-attempts. The contract does not list the fields.
|
||||
* These are the signin_attempts columns.
|
||||
*/
|
||||
export interface SigninAttempt {
|
||||
id?: number | string;
|
||||
at: string;
|
||||
account: string;
|
||||
ip: string | null;
|
||||
kind: string;
|
||||
ok: boolean;
|
||||
reason: string | null;
|
||||
}
|
||||
|
||||
/** Stations may come as names or as rows. */
|
||||
export type StationEntry = string | { name: string; active?: boolean };
|
||||
|
||||
/** One row of GET /api/departments. */
|
||||
export interface Department {
|
||||
code: string;
|
||||
slug: string;
|
||||
name: string;
|
||||
kind: "support" | "shop";
|
||||
stations: StationEntry[];
|
||||
}
|
||||
|
||||
/** Payload of an SSE `presence` event. */
|
||||
export interface PresenceUser {
|
||||
user_id: string;
|
||||
display_name: string;
|
||||
screen: string | null;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { useContext } from "react";
|
||||
import { AuthCtx, type AuthState } from "./context";
|
||||
|
||||
/** The auth state. Must be used under AuthProvider. */
|
||||
export function useAuth(): AuthState {
|
||||
const ctx = useContext(AuthCtx);
|
||||
if (!ctx) throw new Error("useAuth must be used inside AuthProvider");
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { PresenceUser } from "./types";
|
||||
|
||||
interface EventHandlers {
|
||||
/** Called when the server revokes this browser's own session. */
|
||||
onRevoked: () => void;
|
||||
/** Called for every `changed` event. Later phases refresh their data from it. */
|
||||
onChanged?: (payload: unknown) => void;
|
||||
}
|
||||
|
||||
function parse(data: unknown): unknown {
|
||||
if (typeof data !== "string") return null;
|
||||
try {
|
||||
return JSON.parse(data) as unknown;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens /api/events with EventSource while `sessionId` is set.
|
||||
* A `session` event with this session id and action "revoked" calls onRevoked.
|
||||
* `presence` is kept in state for later phases.
|
||||
*/
|
||||
export function useEvents(sessionId: string | null, handlers: EventHandlers): PresenceUser[] {
|
||||
const [presence, setPresence] = useState<PresenceUser[]>([]);
|
||||
const ref = useRef(handlers);
|
||||
useEffect(() => {
|
||||
ref.current = handlers;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!sessionId || typeof EventSource === "undefined") return;
|
||||
const es = new EventSource("/api/events", { withCredentials: true });
|
||||
|
||||
es.addEventListener("session", (ev) => {
|
||||
const p = parse((ev as MessageEvent).data);
|
||||
if (p && typeof p === "object") {
|
||||
const o = p as { session_id?: unknown; action?: unknown };
|
||||
if (o.session_id === sessionId && o.action === "revoked") ref.current.onRevoked();
|
||||
}
|
||||
});
|
||||
es.addEventListener("presence", (ev) => {
|
||||
const p = parse((ev as MessageEvent).data);
|
||||
if (p && typeof p === "object" && Array.isArray((p as { users?: unknown }).users)) {
|
||||
setPresence((p as { users: PresenceUser[] }).users);
|
||||
}
|
||||
});
|
||||
es.addEventListener("changed", (ev) => {
|
||||
ref.current.onChanged?.(parse((ev as MessageEvent).data));
|
||||
});
|
||||
|
||||
return () => {
|
||||
es.close();
|
||||
setPresence([]);
|
||||
};
|
||||
}, [sessionId]);
|
||||
|
||||
return presence;
|
||||
}
|
||||
Reference in New Issue
Block a user