feat: authenticate against Authentik with admin and viewer roles
Sign-in goes through Authentik over OIDC with PKCE. Verified against the live provider: the discovery issuer matches the configured one exactly, and the authorize redirect carries code_challenge_method=S256. Sessions are JWTs with no database adapter, which keeps the module usable from edge middleware and makes a sign-in cost no query. The trade-off is stated in the code: the role travels in the token, so removing someone from the admin group takes effect at the next sign-in or when the eight-hour session expires, not instantly. Immediate revocation would mean asking Authentik on every request, which is what api_llm_loxi does and what this application deliberately does not — it drives a shop window, not a fleet. Group matching is trimmed and case-insensitive. Authentik group names are case-sensitive, but a capitalisation mismatch between the group and the environment variable locks the shop owner out silently, and that is the worse of the two failures. An empty variable never promotes anyone. Authorisation is enforced twice. The middleware covers every /admin page and /api/admin route at the edge; a guard inside the handlers repeats the check, because a matcher is a string, strings get edited, and a route falling outside one should not be the same thing as a route with no access control. The rule itself lives in its own framework-free module so it can be tested directly. Unknown HTTP verbs count as writes: new methods arrive locked. Pages get a redirect to the sign-in screen, API routes get a status code — a fetch that receives an HTML login page is a confusing way to learn you are signed out. The device API stays outside the matcher, as the panel cannot sign in and carries its own bearer token; this is covered by a check that /api/display still answers 401 rather than redirecting. The audit diff compares values by their JSON form, so slot arrays and dates compare by value rather than identity, and a save that changed nothing writes no entry. Recording never throws: losing the trail is bad, refusing the user's change because the trail could not be written is worse. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012cSY9pVhZmJUKNN7wf1Myd
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* The audit trail: who changed what, and when.
|
||||
*
|
||||
* The diff is computed here rather than by each caller so every entry has the
|
||||
* same shape, and so a field can never be recorded as "changed" when only its
|
||||
* representation moved.
|
||||
*/
|
||||
|
||||
import type { InputJsonValue } from '@/lib/generated/prisma/internal/prismaNamespace';
|
||||
|
||||
import { prisma } from '@/lib/db';
|
||||
|
||||
export type FieldChange = { before: unknown; after: unknown };
|
||||
export type Diff = Record<string, FieldChange>;
|
||||
|
||||
/**
|
||||
* Field-by-field difference between two snapshots.
|
||||
*
|
||||
* Returns `null` when nothing moved, so a no-op save leaves no entry: a log
|
||||
* full of empty changes is a log nobody reads.
|
||||
*
|
||||
* Values are compared by their JSON form, which is what makes `slots` arrays
|
||||
* and dates compare sensibly rather than by identity.
|
||||
*/
|
||||
export function diffOf(
|
||||
before: Record<string, unknown> | null,
|
||||
after: Record<string, unknown> | null,
|
||||
): Diff | null {
|
||||
const keys = new Set([...Object.keys(before ?? {}), ...Object.keys(after ?? {})]);
|
||||
const diff: Diff = {};
|
||||
|
||||
for (const key of keys) {
|
||||
const previous = before?.[key];
|
||||
const next = after?.[key];
|
||||
if (!sameValue(previous, next)) {
|
||||
diff[key] = { before: normalise(previous), after: normalise(next) };
|
||||
}
|
||||
}
|
||||
|
||||
return Object.keys(diff).length > 0 ? diff : null;
|
||||
}
|
||||
|
||||
function sameValue(a: unknown, b: unknown): boolean {
|
||||
return JSON.stringify(normalise(a)) === JSON.stringify(normalise(b));
|
||||
}
|
||||
|
||||
/** Dates are compared and stored in ISO form; undefined and null are the same absence. */
|
||||
function normalise(value: unknown): unknown {
|
||||
if (value === undefined) {
|
||||
return null;
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
return value.toISOString();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export type AuditEntry = {
|
||||
userEmail: string;
|
||||
action: string;
|
||||
entity: string;
|
||||
entityId?: string | null;
|
||||
diff?: Diff | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Records an entry. Never throws: losing the trail is bad, but refusing the
|
||||
* user's change because the trail could not be written is worse.
|
||||
*/
|
||||
export async function recordAudit(entry: AuditEntry): Promise<void> {
|
||||
try {
|
||||
await prisma.auditLog.create({
|
||||
data: {
|
||||
userEmail: entry.userEmail,
|
||||
action: entry.action,
|
||||
entity: entry.entity,
|
||||
entityId: entry.entityId ?? null,
|
||||
// Prisma's JSON input type does not accept an arbitrary record; the
|
||||
// diff is plain JSON by construction, so the assertion is safe.
|
||||
diff: entry.diff ? (entry.diff as unknown as InputJsonValue) : undefined,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Could not write the audit entry', entry.action, entry.entity, error);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user