mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
feat: production-grade RBAC with editor role, custom roles, API key scoping, and audit log (#89)
* feat(rbac): add editor role, 3 new permissions, ownership helper * feat(rbac): add audit_log table, apiKeys.permissions column, editor role to schema * feat(rbac): wire requirePermission into all routes, add editor role support * refactor(rbac): replace ad-hoc role checks with permission-based ownership * feat(rbac): add audit log DB writes + query endpoint Dual-write audit events to stdout (existing) and SQLite audit_log table. Add GET /api/v1/audit-log with pagination, action filter, and date range filtering, gated behind audit:read permission. * feat(rbac): add API key permission scoping with ceiling enforcement * feat(rbac): add escalation prevention and last-admin protection * feat(rbac): add editor role to UI, API key permission scoping in settings * test(rbac): add full permission matrix integration test * test(rbac): add editor role E2E tests * feat(rbac): add custom roles with CRUD API and DB-backed permission lookup * feat(rbac): add API key expiration * feat(rbac): add roles management UI and API key expiration to settings * feat(rbac): add audit log UI to settings * fix: remove any cast in API key permission validation * test(rbac): add unit tests for username validation rules * test(rbac): add unit tests for effective permissions and ownership * test(rbac): add comprehensive route permission matrix (all routes × all roles) * test(rbac): add auth route edge case tests (login failures, session expiry, password side effects) * test(rbac): add escalation prevention tests (register, update, self-demote, last-admin) * test(rbac): add ownership enforcement tests (files, pipelines, editor access, cross-user isolation) * test(rbac): add API key edge cases (name validation, delete behavior, key revocation) * test(rbac): add audit log edge cases (all events, pagination clamping, structure) * test(rbac): add custom roles edge case tests (validation, CRUD, functional permissions) * test(rbac): add comprehensive E2E tests (roles UI, audit log, custom role, API key scoping)
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
-- Add permissions column to api_keys for scoped API keys
|
||||
ALTER TABLE `api_keys` ADD COLUMN `permissions` text;
|
||||
--> statement-breakpoint
|
||||
-- Create audit_log table for queryable audit trail
|
||||
CREATE TABLE IF NOT EXISTS `audit_log` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`actor_id` text REFERENCES `users`(`id`) ON DELETE SET NULL,
|
||||
`actor_username` text NOT NULL,
|
||||
`action` text NOT NULL,
|
||||
`target_type` text,
|
||||
`target_id` text,
|
||||
`details` text,
|
||||
`ip_address` text,
|
||||
`created_at` integer NOT NULL DEFAULT (unixepoch())
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX IF NOT EXISTS `audit_log_action_idx` ON `audit_log` (`action`);
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX IF NOT EXISTS `audit_log_created_at_idx` ON `audit_log` (`created_at`);
|
||||
@@ -0,0 +1,19 @@
|
||||
-- Create roles table
|
||||
CREATE TABLE IF NOT EXISTS `roles` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`description` text NOT NULL DEFAULT '',
|
||||
`permissions` text NOT NULL,
|
||||
`is_builtin` integer NOT NULL DEFAULT 0,
|
||||
`created_by` text REFERENCES `users`(`id`) ON DELETE SET NULL,
|
||||
`created_at` integer NOT NULL DEFAULT (unixepoch()),
|
||||
`updated_at` integer NOT NULL DEFAULT (unixepoch())
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS `roles_name_unique` ON `roles` (`name`);
|
||||
--> statement-breakpoint
|
||||
-- Seed built-in roles
|
||||
INSERT OR IGNORE INTO `roles` (`id`, `name`, `description`, `permissions`, `is_builtin`) VALUES
|
||||
('builtin-admin', 'admin', 'Full administrative access', '["tools:use","files:own","files:all","apikeys:own","apikeys:all","pipelines:own","pipelines:all","settings:read","settings:write","users:manage","teams:manage","branding:manage","features:manage","system:health","audit:read"]', 1),
|
||||
('builtin-editor', 'editor', 'Can see all files and pipelines', '["tools:use","files:own","files:all","apikeys:own","pipelines:own","pipelines:all","settings:read"]', 1),
|
||||
('builtin-user', 'user', 'Basic tool access', '["tools:use","files:own","apikeys:own","pipelines:own","settings:read"]', 1);
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `api_keys` ADD COLUMN `expires_at` integer;
|
||||
@@ -43,6 +43,27 @@
|
||||
"when": 1774700000000,
|
||||
"tag": "0005_add_teams_table",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 6,
|
||||
"version": "6",
|
||||
"when": 1745366400000,
|
||||
"tag": "0006_rbac_revamp",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 7,
|
||||
"version": "6",
|
||||
"when": 1745366500000,
|
||||
"tag": "0007_custom_roles",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 8,
|
||||
"version": "6",
|
||||
"when": 1745366600000,
|
||||
"tag": "0008_api_key_expiration",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -4,9 +4,7 @@ export const users = sqliteTable("users", {
|
||||
id: text("id").primaryKey(),
|
||||
username: text("username").notNull().unique(),
|
||||
passwordHash: text("password_hash").notNull(),
|
||||
role: text("role", { enum: ["admin", "user"] })
|
||||
.notNull()
|
||||
.default("user"),
|
||||
role: text("role").notNull().default("user"),
|
||||
team: text("team").notNull().default("Default"),
|
||||
mustChangePassword: integer("must_change_password", { mode: "boolean" }).notNull().default(true),
|
||||
createdAt: integer("created_at", { mode: "timestamp" })
|
||||
@@ -69,10 +67,12 @@ export const apiKeys = sqliteTable("api_keys", {
|
||||
keyHash: text("key_hash").notNull(),
|
||||
keyPrefix: text("key_prefix"),
|
||||
name: text("name").notNull().default("Default API Key"),
|
||||
permissions: text("permissions"),
|
||||
createdAt: integer("created_at", { mode: "timestamp" })
|
||||
.notNull()
|
||||
.$defaultFn(() => new Date()),
|
||||
lastUsedAt: integer("last_used_at", { mode: "timestamp" }),
|
||||
expiresAt: integer("expires_at", { mode: "timestamp" }),
|
||||
});
|
||||
|
||||
export const pipelines = sqliteTable("pipelines", {
|
||||
@@ -86,6 +86,35 @@ export const pipelines = sqliteTable("pipelines", {
|
||||
.$defaultFn(() => new Date()),
|
||||
});
|
||||
|
||||
export const auditLog = sqliteTable("audit_log", {
|
||||
id: text("id").primaryKey(),
|
||||
actorId: text("actor_id").references(() => users.id, { onDelete: "set null" }),
|
||||
actorUsername: text("actor_username").notNull(),
|
||||
action: text("action").notNull(),
|
||||
targetType: text("target_type"),
|
||||
targetId: text("target_id"),
|
||||
details: text("details"),
|
||||
ipAddress: text("ip_address"),
|
||||
createdAt: integer("created_at", { mode: "timestamp" })
|
||||
.notNull()
|
||||
.$defaultFn(() => new Date()),
|
||||
});
|
||||
|
||||
export const roles = sqliteTable("roles", {
|
||||
id: text("id").primaryKey(),
|
||||
name: text("name").notNull().unique(),
|
||||
description: text("description").notNull().default(""),
|
||||
permissions: text("permissions").notNull(),
|
||||
isBuiltin: integer("is_builtin", { mode: "boolean" }).notNull().default(false),
|
||||
createdBy: text("created_by").references(() => users.id, { onDelete: "set null" }),
|
||||
createdAt: integer("created_at", { mode: "timestamp" })
|
||||
.notNull()
|
||||
.$defaultFn(() => new Date()),
|
||||
updatedAt: integer("updated_at", { mode: "timestamp" })
|
||||
.notNull()
|
||||
.$defaultFn(() => new Date()),
|
||||
});
|
||||
|
||||
export const userFiles = sqliteTable("user_files", {
|
||||
id: text("id").primaryKey(),
|
||||
userId: text("user_id").references(() => users.id, { onDelete: "cascade" }),
|
||||
|
||||
+11
-2
@@ -9,10 +9,12 @@ import { runMigrations } from "./db/migrate.js";
|
||||
import { startCleanupCron } from "./lib/cleanup.js";
|
||||
import { ensureAiDirs, recoverInterruptedInstalls } from "./lib/feature-status.js";
|
||||
import { shutdownWorkerPool } from "./lib/worker-pool.js";
|
||||
import { authMiddleware, authRoutes, ensureDefaultAdmin, requireAdmin } from "./plugins/auth.js";
|
||||
import { requirePermission } from "./permissions.js";
|
||||
import { authMiddleware, authRoutes, ensureDefaultAdmin } from "./plugins/auth.js";
|
||||
import { registerStatic } from "./plugins/static.js";
|
||||
import { registerUpload } from "./plugins/upload.js";
|
||||
import { apiKeyRoutes } from "./routes/api-keys.js";
|
||||
import { auditLogRoutes } from "./routes/audit-log.js";
|
||||
import { registerBatchRoutes } from "./routes/batch.js";
|
||||
import { brandingRoutes } from "./routes/branding.js";
|
||||
import { docsRoutes } from "./routes/docs.js";
|
||||
@@ -20,6 +22,7 @@ import { registerFeatureRoutes } from "./routes/features.js";
|
||||
import { fileRoutes } from "./routes/files.js";
|
||||
import { registerPipelineRoutes } from "./routes/pipeline.js";
|
||||
import { recoverStaleJobs, registerProgressRoutes } from "./routes/progress.js";
|
||||
import { rolesRoutes } from "./routes/roles.js";
|
||||
import { settingsRoutes } from "./routes/settings.js";
|
||||
import { teamsRoutes } from "./routes/teams.js";
|
||||
import { registerToolRoutes } from "./routes/tools/index.js";
|
||||
@@ -134,6 +137,12 @@ await brandingRoutes(app);
|
||||
// Teams routes
|
||||
await teamsRoutes(app);
|
||||
|
||||
// Audit log routes
|
||||
await auditLogRoutes(app);
|
||||
|
||||
// Roles management routes
|
||||
await rolesRoutes(app);
|
||||
|
||||
// API docs (Scalar)
|
||||
await docsRoutes(app);
|
||||
|
||||
@@ -157,7 +166,7 @@ app.get("/api/v1/health", async (_request, reply) => {
|
||||
|
||||
// Admin health check (full diagnostics)
|
||||
app.get("/api/v1/admin/health", async (request, reply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("system:health")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
let dbOk = false;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { FastifyBaseLogger } from "fastify";
|
||||
import { db, schema } from "../db/index.js";
|
||||
|
||||
type AuditEvent =
|
||||
| "LOGIN_SUCCESS"
|
||||
@@ -12,13 +14,16 @@ type AuditEvent =
|
||||
| "FILE_UPLOADED"
|
||||
| "FILE_DELETED"
|
||||
| "API_KEY_CREATED"
|
||||
| "API_KEY_DELETED";
|
||||
| "API_KEY_DELETED"
|
||||
| "ROLE_CREATED"
|
||||
| "ROLE_UPDATED"
|
||||
| "ROLE_DELETED"
|
||||
| "SETTINGS_UPDATED";
|
||||
|
||||
/**
|
||||
* Emit a structured audit log entry for security-relevant events.
|
||||
*
|
||||
* Logs are written at INFO level with `audit: true` so they can be
|
||||
* filtered by log aggregators (e.g. `jq 'select(.audit)'`).
|
||||
* Dual-writes: structured stdout log (for aggregators) + SQLite row.
|
||||
*/
|
||||
export function auditLog(
|
||||
logger: FastifyBaseLogger,
|
||||
@@ -26,4 +31,41 @@ export function auditLog(
|
||||
details: Record<string, unknown> = {},
|
||||
): void {
|
||||
logger.info({ audit: true, event, ...details }, `[AUDIT] ${event}`);
|
||||
|
||||
const actorId = (details.userId as string) ?? (details.adminId as string) ?? null;
|
||||
const actorUsername = (details.username as string) ?? (details.newUsername as string) ?? "system";
|
||||
const targetId = (details.targetUserId as string) ?? (details.keyId as string) ?? null;
|
||||
const targetType = deriveTargetType(event);
|
||||
|
||||
try {
|
||||
db.insert(schema.auditLog)
|
||||
.values({
|
||||
id: randomUUID(),
|
||||
actorId,
|
||||
actorUsername,
|
||||
action: event,
|
||||
targetType,
|
||||
targetId,
|
||||
details: JSON.stringify(details),
|
||||
ipAddress: null,
|
||||
})
|
||||
.run();
|
||||
} catch {
|
||||
logger.warn({ event }, "Failed to write audit log to DB");
|
||||
}
|
||||
}
|
||||
|
||||
function deriveTargetType(event: AuditEvent): string | null {
|
||||
if (
|
||||
event.startsWith("USER_") ||
|
||||
event.startsWith("LOGIN") ||
|
||||
event.startsWith("PASSWORD") ||
|
||||
event === "LOGOUT"
|
||||
)
|
||||
return "user";
|
||||
if (event.startsWith("API_KEY")) return "api_key";
|
||||
if (event.startsWith("FILE")) return "file";
|
||||
if (event.startsWith("ROLE")) return "role";
|
||||
if (event === "SETTINGS_UPDATED") return "setting";
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { Permission, Role } from "@ashim/shared";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { FastifyReply, FastifyRequest } from "fastify";
|
||||
import { getAuthUser } from "./plugins/auth.js";
|
||||
import { db, schema } from "./db/index.js";
|
||||
import { type AuthUser, getAuthUser } from "./plugins/auth.js";
|
||||
|
||||
const ROLE_PERMISSIONS: Record<Role, Permission[]> = {
|
||||
admin: [
|
||||
@@ -16,18 +18,53 @@ const ROLE_PERMISSIONS: Record<Role, Permission[]> = {
|
||||
"users:manage",
|
||||
"teams:manage",
|
||||
"branding:manage",
|
||||
"features:manage",
|
||||
"system:health",
|
||||
"audit:read",
|
||||
],
|
||||
editor: [
|
||||
"tools:use",
|
||||
"files:own",
|
||||
"files:all",
|
||||
"apikeys:own",
|
||||
"pipelines:own",
|
||||
"pipelines:all",
|
||||
"settings:read",
|
||||
],
|
||||
user: ["tools:use", "files:own", "apikeys:own", "pipelines:own", "settings:read"],
|
||||
};
|
||||
|
||||
export function getPermissions(role: Role): Permission[] {
|
||||
return ROLE_PERMISSIONS[role] ?? [];
|
||||
export function getPermissions(role: Role | string): Permission[] {
|
||||
if (role in ROLE_PERMISSIONS) {
|
||||
return ROLE_PERMISSIONS[role as Role];
|
||||
}
|
||||
try {
|
||||
const customRole = db
|
||||
.select()
|
||||
.from(schema.roles)
|
||||
.where(eq(schema.roles.name, role as string))
|
||||
.get();
|
||||
if (customRole) {
|
||||
return JSON.parse(customRole.permissions) as Permission[];
|
||||
}
|
||||
} catch {
|
||||
// DB not yet available during early startup
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export function hasPermission(role: Role, permission: Permission): boolean {
|
||||
export function hasPermission(role: Role | string, permission: Permission): boolean {
|
||||
return getPermissions(role).includes(permission);
|
||||
}
|
||||
|
||||
export function hasEffectivePermission(user: AuthUser, permission: Permission): boolean {
|
||||
if (!hasPermission(user.role, permission)) return false;
|
||||
if (user.apiKeyPermissions) {
|
||||
return user.apiKeyPermissions.includes(permission);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function requirePermission(permission: Permission) {
|
||||
return (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const user = getAuthUser(request);
|
||||
@@ -35,10 +72,27 @@ export function requirePermission(permission: Permission) {
|
||||
reply.status(401).send({ error: "Authentication required", code: "AUTH_REQUIRED" });
|
||||
return null;
|
||||
}
|
||||
if (!hasPermission(user.role as Role, permission)) {
|
||||
if (!hasEffectivePermission(user, permission)) {
|
||||
reply.status(403).send({ error: "Insufficient permissions", code: "FORBIDDEN" });
|
||||
return null;
|
||||
}
|
||||
return user;
|
||||
};
|
||||
}
|
||||
|
||||
export function requireOwnershipOrPermission(
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
resourceUserId: string | null,
|
||||
allPermission: Permission,
|
||||
) {
|
||||
const user = getAuthUser(request);
|
||||
if (!user) {
|
||||
reply.status(401).send({ error: "Authentication required", code: "AUTH_REQUIRED" });
|
||||
return null;
|
||||
}
|
||||
if (resourceUserId !== user.id && !hasEffectivePermission(user, allPermission)) {
|
||||
return null;
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { createHash, randomBytes, randomUUID, scrypt, timingSafeEqual } from "node:crypto";
|
||||
import { promisify } from "node:util";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { env } from "../config.js";
|
||||
import { db, schema } from "../db/index.js";
|
||||
import { auditLog } from "../lib/audit.js";
|
||||
import { getPermissions } from "../permissions.js";
|
||||
import { getPermissions, requirePermission } from "../permissions.js";
|
||||
|
||||
const scryptAsync = promisify(scrypt);
|
||||
|
||||
@@ -14,7 +14,8 @@ const scryptAsync = promisify(scrypt);
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
username: string;
|
||||
role: "admin" | "user";
|
||||
role: string;
|
||||
apiKeyPermissions?: string[];
|
||||
}
|
||||
|
||||
const MAX_USERS = env.MAX_USERS;
|
||||
@@ -205,7 +206,7 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
|
||||
username: user.username,
|
||||
role: user.role,
|
||||
mustChangePassword: env.SKIP_MUST_CHANGE_PASSWORD ? false : user.mustChangePassword,
|
||||
permissions: getPermissions(user.role as "admin" | "user"),
|
||||
permissions: getPermissions(user.role),
|
||||
teamName: teamRow?.name ?? user.team,
|
||||
},
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
@@ -253,7 +254,7 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
|
||||
username: user.username,
|
||||
role: user.role,
|
||||
mustChangePassword: env.SKIP_MUST_CHANGE_PASSWORD ? false : user.mustChangePassword,
|
||||
permissions: getPermissions(user.role as "admin" | "user"),
|
||||
permissions: getPermissions(user.role),
|
||||
},
|
||||
expiresAt: session.expiresAt.toISOString(),
|
||||
});
|
||||
@@ -327,7 +328,7 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
|
||||
|
||||
// GET /api/auth/users (admin only)
|
||||
app.get("/api/auth/users", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("users:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const users = db
|
||||
@@ -357,7 +358,7 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
|
||||
|
||||
// POST /api/auth/register (admin only)
|
||||
app.post("/api/auth/register", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("users:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const body = request.body as {
|
||||
@@ -389,7 +390,33 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
const role = body.role === "admin" ? "admin" : "user";
|
||||
const validBuiltinRoles = ["admin", "editor", "user"];
|
||||
let role: string = "user";
|
||||
if (body.role) {
|
||||
if (validBuiltinRoles.includes(body.role)) {
|
||||
role = body.role;
|
||||
} else {
|
||||
const customRole = db
|
||||
.select()
|
||||
.from(schema.roles)
|
||||
.where(eq(schema.roles.name, body.role))
|
||||
.get();
|
||||
if (customRole) {
|
||||
role = body.role;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Escalation prevention
|
||||
const roleHierarchy: Record<string, number> = { admin: 3, editor: 2, user: 1 };
|
||||
const actorLevel = roleHierarchy[admin.role] ?? 0;
|
||||
const targetLevel = roleHierarchy[role] ?? 0;
|
||||
if (targetLevel > actorLevel) {
|
||||
return reply.status(403).send({
|
||||
error: "Cannot create a user with a higher role than your own",
|
||||
code: "ESCALATION_DENIED",
|
||||
});
|
||||
}
|
||||
|
||||
// Resolve team — frontend sends team name (e.g. "Default"), not ID
|
||||
const requestedTeam = (body as { team?: string }).team;
|
||||
@@ -477,7 +504,7 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.put(
|
||||
"/api/auth/users/:id",
|
||||
async (request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("users:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const { id } = request.params;
|
||||
@@ -489,19 +516,54 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
|
||||
return reply.status(404).send({ error: "User not found", code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
const updates: { role?: "admin" | "user"; team?: string; updatedAt: Date } = {
|
||||
const updates: { role?: string; team?: string; updatedAt: Date } = {
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
if (body?.role === "admin" || body?.role === "user") {
|
||||
// Prevent removing your own admin role
|
||||
if (id === admin.id && body.role !== "admin") {
|
||||
return reply.status(400).send({
|
||||
error: "Cannot remove your own admin role",
|
||||
code: "SELF_DEMOTE",
|
||||
// Escalation prevention
|
||||
if (body?.role) {
|
||||
const roleHierarchy: Record<string, number> = { admin: 3, editor: 2, user: 1 };
|
||||
const actorLevel = roleHierarchy[admin.role] ?? 0;
|
||||
const targetLevel = roleHierarchy[body.role] ?? 0;
|
||||
if (targetLevel > actorLevel) {
|
||||
return reply.status(403).send({
|
||||
error: "Cannot assign a role higher than your own",
|
||||
code: "ESCALATION_DENIED",
|
||||
});
|
||||
}
|
||||
updates.role = body.role;
|
||||
}
|
||||
|
||||
if (body?.role) {
|
||||
const validBuiltinRoles = ["admin", "editor", "user"];
|
||||
const isValid =
|
||||
validBuiltinRoles.includes(body.role) ||
|
||||
db.select().from(schema.roles).where(eq(schema.roles.name, body.role)).get();
|
||||
if (isValid) {
|
||||
// Prevent removing your own admin role
|
||||
if (id === admin.id && body.role !== "admin") {
|
||||
return reply.status(400).send({
|
||||
error: "Cannot remove your own admin role",
|
||||
code: "SELF_DEMOTE",
|
||||
});
|
||||
}
|
||||
|
||||
// Last admin protection
|
||||
if (user.role === "admin" && body.role !== "admin") {
|
||||
const adminCount = db
|
||||
.select({ count: sql<number>`COUNT(*)` })
|
||||
.from(schema.users)
|
||||
.where(eq(schema.users.role, "admin"))
|
||||
.get();
|
||||
if (adminCount && adminCount.count <= 1) {
|
||||
return reply.status(400).send({
|
||||
error: "Cannot demote the last admin",
|
||||
code: "LAST_ADMIN",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
updates.role = body.role;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof body?.team === "string" && body.team.trim()) {
|
||||
@@ -537,7 +599,7 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.post(
|
||||
"/api/auth/users/:id/reset-password",
|
||||
async (request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("users:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const { id } = request.params;
|
||||
@@ -591,7 +653,7 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.delete(
|
||||
"/api/auth/users/:id",
|
||||
async (request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("users:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const { id } = request.params;
|
||||
@@ -707,6 +769,11 @@ export async function authMiddleware(app: FastifyInstance): Promise<void> {
|
||||
for (const key of keysToCheck) {
|
||||
const matches = await verifyPassword(token, key.keyHash);
|
||||
if (matches) {
|
||||
// Check expiration
|
||||
if (key.expiresAt && key.expiresAt < new Date()) {
|
||||
// Key expired — skip it
|
||||
continue;
|
||||
}
|
||||
// Backfill prefix for legacy keys
|
||||
if (!key.keyPrefix) {
|
||||
db.update(schema.apiKeys)
|
||||
@@ -726,10 +793,14 @@ export async function authMiddleware(app: FastifyInstance): Promise<void> {
|
||||
.where(eq(schema.users.id, key.userId))
|
||||
.get();
|
||||
if (apiUser) {
|
||||
const keyPermissions = key.permissions
|
||||
? JSON.parse(key.permissions as string)
|
||||
: undefined;
|
||||
(request as FastifyRequest & { user?: AuthUser }).user = {
|
||||
id: apiUser.id,
|
||||
username: apiUser.username,
|
||||
role: apiUser.role as "admin" | "user",
|
||||
role: apiUser.role,
|
||||
apiKeyPermissions: keyPermissions,
|
||||
};
|
||||
return;
|
||||
}
|
||||
@@ -754,7 +825,7 @@ export async function authMiddleware(app: FastifyInstance): Promise<void> {
|
||||
(request as FastifyRequest & { user?: AuthUser }).user = {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
role: user.role as "admin" | "user",
|
||||
role: user.role,
|
||||
};
|
||||
|
||||
// Enforce mustChangePassword — block non-auth API calls
|
||||
|
||||
@@ -10,6 +10,7 @@ import { and, eq } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { db, schema } from "../db/index.js";
|
||||
import { auditLog } from "../lib/audit.js";
|
||||
import { getPermissions, hasEffectivePermission } from "../permissions.js";
|
||||
import { computeKeyPrefix, hashPassword, requireAuth } from "../plugins/auth.js";
|
||||
|
||||
export async function apiKeyRoutes(app: FastifyInstance): Promise<void> {
|
||||
@@ -18,7 +19,11 @@ export async function apiKeyRoutes(app: FastifyInstance): Promise<void> {
|
||||
const user = requireAuth(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const body = request.body as { name?: string } | null;
|
||||
const body = request.body as {
|
||||
name?: string;
|
||||
permissions?: string[];
|
||||
expiresAt?: string;
|
||||
} | null;
|
||||
const name = body?.name?.trim() || "Default API Key";
|
||||
|
||||
if (name.length > 100) {
|
||||
@@ -28,6 +33,36 @@ export async function apiKeyRoutes(app: FastifyInstance): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
let scopedPermissions: string[] | null = null;
|
||||
if (Array.isArray(body?.permissions) && body.permissions.length > 0) {
|
||||
const userPerms = getPermissions(user.role);
|
||||
const permSet = new Set<string>(userPerms);
|
||||
const invalid = body.permissions.filter((p: string) => !permSet.has(p));
|
||||
if (invalid.length > 0) {
|
||||
return reply.status(400).send({
|
||||
error: `Cannot scope key with permissions you don't have: ${invalid.join(", ")}`,
|
||||
code: "VALIDATION_ERROR",
|
||||
});
|
||||
}
|
||||
scopedPermissions = body.permissions;
|
||||
}
|
||||
|
||||
let expiresAt: Date | null = null;
|
||||
if (body?.expiresAt) {
|
||||
const parsed = new Date(body.expiresAt);
|
||||
if (Number.isNaN(parsed.getTime())) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "Invalid expiresAt date", code: "VALIDATION_ERROR" });
|
||||
}
|
||||
if (parsed <= new Date()) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "expiresAt must be in the future", code: "VALIDATION_ERROR" });
|
||||
}
|
||||
expiresAt = parsed;
|
||||
}
|
||||
|
||||
// Generate a raw API key: "si_" prefix + 48 random bytes as hex
|
||||
const rawKey = `si_${randomBytes(48).toString("hex")}`;
|
||||
const keyHash = await hashPassword(rawKey);
|
||||
@@ -41,6 +76,8 @@ export async function apiKeyRoutes(app: FastifyInstance): Promise<void> {
|
||||
keyHash,
|
||||
keyPrefix,
|
||||
name,
|
||||
permissions: scopedPermissions ? JSON.stringify(scopedPermissions) : null,
|
||||
expiresAt,
|
||||
})
|
||||
.run();
|
||||
|
||||
@@ -51,6 +88,8 @@ export async function apiKeyRoutes(app: FastifyInstance): Promise<void> {
|
||||
id,
|
||||
key: rawKey,
|
||||
name,
|
||||
permissions: scopedPermissions,
|
||||
expiresAt: expiresAt?.toISOString() ?? null,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
@@ -63,24 +102,27 @@ export async function apiKeyRoutes(app: FastifyInstance): Promise<void> {
|
||||
const selectFields = {
|
||||
id: schema.apiKeys.id,
|
||||
name: schema.apiKeys.name,
|
||||
permissions: schema.apiKeys.permissions,
|
||||
createdAt: schema.apiKeys.createdAt,
|
||||
lastUsedAt: schema.apiKeys.lastUsedAt,
|
||||
expiresAt: schema.apiKeys.expiresAt,
|
||||
};
|
||||
const keys =
|
||||
user.role === "admin"
|
||||
? db.select(selectFields).from(schema.apiKeys).all()
|
||||
: db
|
||||
.select(selectFields)
|
||||
.from(schema.apiKeys)
|
||||
.where(eq(schema.apiKeys.userId, user.id))
|
||||
.all();
|
||||
const keys = hasEffectivePermission(user, "apikeys:all")
|
||||
? db.select(selectFields).from(schema.apiKeys).all()
|
||||
: db
|
||||
.select(selectFields)
|
||||
.from(schema.apiKeys)
|
||||
.where(eq(schema.apiKeys.userId, user.id))
|
||||
.all();
|
||||
|
||||
return reply.send({
|
||||
apiKeys: keys.map((k) => ({
|
||||
id: k.id,
|
||||
name: k.name,
|
||||
permissions: k.permissions ? JSON.parse(k.permissions) : null,
|
||||
createdAt: k.createdAt.toISOString(),
|
||||
lastUsedAt: k.lastUsedAt?.toISOString() ?? null,
|
||||
expiresAt: k.expiresAt?.toISOString() ?? null,
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { and, desc, eq, gte, lte, sql } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { db, schema } from "../db/index.js";
|
||||
import { requirePermission } from "../permissions.js";
|
||||
|
||||
export async function auditLogRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.get(
|
||||
"/api/v1/audit-log",
|
||||
async (
|
||||
request: FastifyRequest<{
|
||||
Querystring: {
|
||||
page?: string;
|
||||
limit?: string;
|
||||
action?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
};
|
||||
}>,
|
||||
reply: FastifyReply,
|
||||
) => {
|
||||
const user = requirePermission("audit:read")(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const page = Math.max(1, parseInt(request.query.page ?? "1", 10) || 1);
|
||||
const limit = Math.min(100, Math.max(1, parseInt(request.query.limit ?? "50", 10) || 50));
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const conditions = [];
|
||||
|
||||
if (request.query.action) {
|
||||
conditions.push(eq(schema.auditLog.action, request.query.action));
|
||||
}
|
||||
if (request.query.from) {
|
||||
const fromDate = new Date(request.query.from);
|
||||
if (!Number.isNaN(fromDate.getTime())) {
|
||||
conditions.push(gte(schema.auditLog.createdAt, fromDate));
|
||||
}
|
||||
}
|
||||
if (request.query.to) {
|
||||
const toDate = new Date(request.query.to);
|
||||
if (!Number.isNaN(toDate.getTime())) {
|
||||
conditions.push(lte(schema.auditLog.createdAt, toDate));
|
||||
}
|
||||
}
|
||||
|
||||
const where = conditions.length > 0 ? and(...conditions) : undefined;
|
||||
|
||||
const entries = db
|
||||
.select()
|
||||
.from(schema.auditLog)
|
||||
.where(where)
|
||||
.orderBy(desc(schema.auditLog.createdAt))
|
||||
.limit(limit)
|
||||
.offset(offset)
|
||||
.all();
|
||||
|
||||
const countResult = db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(schema.auditLog)
|
||||
.where(where)
|
||||
.get();
|
||||
|
||||
return reply.send({
|
||||
entries: entries.map((e) => ({
|
||||
id: e.id,
|
||||
actorId: e.actorId,
|
||||
actorUsername: e.actorUsername,
|
||||
action: e.action,
|
||||
targetType: e.targetType,
|
||||
targetId: e.targetId,
|
||||
details: e.details ? JSON.parse(e.details) : null,
|
||||
ipAddress: e.ipAddress,
|
||||
createdAt: e.createdAt.toISOString(),
|
||||
})),
|
||||
total: countResult?.count ?? 0,
|
||||
page,
|
||||
limit,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
app.log.info("Audit log routes registered");
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import sharp from "sharp";
|
||||
import { env } from "../config.js";
|
||||
import { db, schema } from "../db/index.js";
|
||||
import { ensureSharpCompat } from "../lib/heic-converter.js";
|
||||
import { requireAdmin } from "../plugins/auth.js";
|
||||
import { requirePermission } from "../permissions.js";
|
||||
|
||||
const BRANDING_DIR = join(process.cwd(), "data", "branding");
|
||||
const LOGO_PATH = join(BRANDING_DIR, "logo.png");
|
||||
@@ -35,7 +35,7 @@ function upsertSetting(key: string, value: string): void {
|
||||
export async function brandingRoutes(app: FastifyInstance): Promise<void> {
|
||||
// POST /api/v1/settings/logo — Upload logo (admin only)
|
||||
app.post("/api/v1/settings/logo", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("branding:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const file = await request.file();
|
||||
@@ -90,7 +90,7 @@ export async function brandingRoutes(app: FastifyInstance): Promise<void> {
|
||||
|
||||
// DELETE /api/v1/settings/logo — Remove logo (admin only)
|
||||
app.delete("/api/v1/settings/logo", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("branding:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
if (existsSync(LOGO_PATH)) {
|
||||
|
||||
@@ -27,7 +27,8 @@ import {
|
||||
releaseInstallLock,
|
||||
setInstallProgress,
|
||||
} from "../lib/feature-status.js";
|
||||
import { requireAdmin, requireAuth } from "../plugins/auth.js";
|
||||
import { requirePermission } from "../permissions.js";
|
||||
import { requireAuth } from "../plugins/auth.js";
|
||||
import { updateSingleFileProgress } from "./progress.js";
|
||||
|
||||
const venvPath = process.env.PYTHON_VENV_PATH || "/opt/venv";
|
||||
@@ -110,7 +111,7 @@ export async function registerFeatureRoutes(app: FastifyInstance): Promise<void>
|
||||
app.post(
|
||||
"/api/v1/admin/features/:bundleId/install",
|
||||
async (request: FastifyRequest<{ Params: BundleIdParams }>, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("features:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const { bundleId } = request.params;
|
||||
@@ -215,7 +216,7 @@ export async function registerFeatureRoutes(app: FastifyInstance): Promise<void>
|
||||
app.post(
|
||||
"/api/v1/admin/features/:bundleId/uninstall",
|
||||
async (request: FastifyRequest<{ Params: BundleIdParams }>, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("features:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const { bundleId } = request.params;
|
||||
@@ -271,7 +272,7 @@ export async function registerFeatureRoutes(app: FastifyInstance): Promise<void>
|
||||
app.get(
|
||||
"/api/v1/admin/features/disk-usage",
|
||||
async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("features:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const totalBytes = getDirSize(getAiDir());
|
||||
|
||||
@@ -26,6 +26,7 @@ import { sanitizeFilename } from "../lib/filename.js";
|
||||
import { decodeToSharpCompat, needsCliDecode } from "../lib/format-decoders.js";
|
||||
import { decodeHeic } from "../lib/heic-converter.js";
|
||||
import { createWorkspace } from "../lib/workspace.js";
|
||||
import { hasEffectivePermission } from "../permissions.js";
|
||||
import { requireAuth } from "../plugins/auth.js";
|
||||
import { type JobProgress, updateJobProgress } from "./progress.js";
|
||||
import { getRegisteredToolIds, getToolConfig } from "./tool-factory.js";
|
||||
@@ -335,10 +336,9 @@ export async function registerPipelineRoutes(app: FastifyInstance): Promise<void
|
||||
|
||||
// Admins see all pipelines; regular users see their own + legacy (no owner)
|
||||
const allRows = db.select().from(schema.pipelines).all();
|
||||
const rows =
|
||||
user.role === "admin"
|
||||
? allRows
|
||||
: allRows.filter((row) => !row.userId || row.userId === user.id);
|
||||
const rows = hasEffectivePermission(user, "pipelines:all")
|
||||
? allRows
|
||||
: allRows.filter((row) => !row.userId || row.userId === user.id);
|
||||
|
||||
const pipelines = rows.map((row) => ({
|
||||
id: row.id,
|
||||
@@ -371,7 +371,11 @@ export async function registerPipelineRoutes(app: FastifyInstance): Promise<void
|
||||
}
|
||||
|
||||
// Only the owner (or admin) can delete; legacy pipelines (no owner) can be deleted by anyone
|
||||
if (existing.userId && existing.userId !== user.id && user.role !== "admin") {
|
||||
if (
|
||||
existing.userId &&
|
||||
existing.userId !== user.id &&
|
||||
!hasEffectivePermission(user, "pipelines:all")
|
||||
) {
|
||||
return reply.status(403).send({ error: "Not authorized to delete this pipeline" });
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { Permission } from "@ashim/shared";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { db, schema } from "../db/index.js";
|
||||
import { auditLog } from "../lib/audit.js";
|
||||
import { requirePermission } from "../permissions.js";
|
||||
|
||||
const ALL_PERMISSIONS: Permission[] = [
|
||||
"tools:use",
|
||||
"files:own",
|
||||
"files:all",
|
||||
"apikeys:own",
|
||||
"apikeys:all",
|
||||
"pipelines:own",
|
||||
"pipelines:all",
|
||||
"settings:read",
|
||||
"settings:write",
|
||||
"users:manage",
|
||||
"teams:manage",
|
||||
"branding:manage",
|
||||
"features:manage",
|
||||
"system:health",
|
||||
"audit:read",
|
||||
];
|
||||
|
||||
export async function rolesRoutes(app: FastifyInstance): Promise<void> {
|
||||
// GET /api/v1/roles — List all roles (requires audit:read to view)
|
||||
app.get("/api/v1/roles", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const user = requirePermission("audit:read")(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const roles = db.select().from(schema.roles).all();
|
||||
const userCounts = db
|
||||
.select({
|
||||
role: schema.users.role,
|
||||
count: sql<number>`COUNT(*)`,
|
||||
})
|
||||
.from(schema.users)
|
||||
.groupBy(schema.users.role)
|
||||
.all();
|
||||
const countMap = new Map(userCounts.map((r) => [r.role, r.count]));
|
||||
|
||||
return reply.send({
|
||||
roles: roles.map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
description: r.description,
|
||||
permissions: JSON.parse(r.permissions),
|
||||
isBuiltin: r.isBuiltin,
|
||||
userCount: countMap.get(r.name) ?? 0,
|
||||
createdAt: r.createdAt.toISOString(),
|
||||
updatedAt: r.updatedAt.toISOString(),
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
// POST /api/v1/roles — Create custom role
|
||||
app.post("/api/v1/roles", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const user = requirePermission("users:manage")(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const body = request.body as {
|
||||
name?: string;
|
||||
description?: string;
|
||||
permissions?: string[];
|
||||
} | null;
|
||||
if (!body?.name || !Array.isArray(body?.permissions)) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "Name and permissions are required", code: "VALIDATION_ERROR" });
|
||||
}
|
||||
|
||||
const name = body.name.trim().toLowerCase();
|
||||
if (name.length < 2 || name.length > 30) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "Role name must be 2-30 characters", code: "VALIDATION_ERROR" });
|
||||
}
|
||||
if (!/^[a-z0-9_-]+$/.test(name)) {
|
||||
return reply.status(400).send({
|
||||
error: "Role name can only contain lowercase letters, numbers, hyphens, and underscores",
|
||||
code: "VALIDATION_ERROR",
|
||||
});
|
||||
}
|
||||
|
||||
const invalid = body.permissions.filter((p) => !ALL_PERMISSIONS.includes(p as Permission));
|
||||
if (invalid.length > 0) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: `Invalid permissions: ${invalid.join(", ")}`, code: "VALIDATION_ERROR" });
|
||||
}
|
||||
|
||||
const existing = db.select().from(schema.roles).where(eq(schema.roles.name, name)).get();
|
||||
if (existing) {
|
||||
return reply.status(409).send({ error: "Role name already exists", code: "CONFLICT" });
|
||||
}
|
||||
|
||||
const id = randomUUID();
|
||||
db.insert(schema.roles)
|
||||
.values({
|
||||
id,
|
||||
name,
|
||||
description: body.description?.trim() ?? "",
|
||||
permissions: JSON.stringify(body.permissions),
|
||||
isBuiltin: false,
|
||||
createdBy: user.id,
|
||||
})
|
||||
.run();
|
||||
|
||||
auditLog(request.log, "ROLE_CREATED", { adminId: user.id, roleId: id, roleName: name });
|
||||
|
||||
return reply.status(201).send({
|
||||
id,
|
||||
name,
|
||||
description: body.description?.trim() ?? "",
|
||||
permissions: body.permissions,
|
||||
isBuiltin: false,
|
||||
});
|
||||
});
|
||||
|
||||
// PUT /api/v1/roles/:id — Update custom role
|
||||
app.put(
|
||||
"/api/v1/roles/:id",
|
||||
async (request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) => {
|
||||
const user = requirePermission("users:manage")(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const { id } = request.params;
|
||||
const role = db.select().from(schema.roles).where(eq(schema.roles.id, id)).get();
|
||||
if (!role) {
|
||||
return reply.status(404).send({ error: "Role not found", code: "NOT_FOUND" });
|
||||
}
|
||||
if (role.isBuiltin) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "Cannot modify built-in roles", code: "VALIDATION_ERROR" });
|
||||
}
|
||||
|
||||
const body = request.body as {
|
||||
name?: string;
|
||||
description?: string;
|
||||
permissions?: string[];
|
||||
} | null;
|
||||
const updates: Record<string, unknown> = { updatedAt: new Date() };
|
||||
|
||||
if (body?.name) {
|
||||
const name = body.name.trim().toLowerCase();
|
||||
if (name.length < 2 || name.length > 30) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "Role name must be 2-30 characters", code: "VALIDATION_ERROR" });
|
||||
}
|
||||
const dup = db.select().from(schema.roles).where(eq(schema.roles.name, name)).get();
|
||||
if (dup && dup.id !== id) {
|
||||
return reply.status(409).send({ error: "Role name already exists", code: "CONFLICT" });
|
||||
}
|
||||
// Update users on old role name to new name
|
||||
db.update(schema.users).set({ role: name }).where(eq(schema.users.role, role.name)).run();
|
||||
updates.name = name;
|
||||
}
|
||||
if (body?.description !== undefined) {
|
||||
updates.description = body.description.trim();
|
||||
}
|
||||
if (Array.isArray(body?.permissions)) {
|
||||
const invalid = body.permissions.filter((p) => !ALL_PERMISSIONS.includes(p as Permission));
|
||||
if (invalid.length > 0) {
|
||||
return reply.status(400).send({
|
||||
error: `Invalid permissions: ${invalid.join(", ")}`,
|
||||
code: "VALIDATION_ERROR",
|
||||
});
|
||||
}
|
||||
updates.permissions = JSON.stringify(body.permissions);
|
||||
}
|
||||
|
||||
db.update(schema.roles).set(updates).where(eq(schema.roles.id, id)).run();
|
||||
auditLog(request.log, "ROLE_UPDATED", { adminId: user.id, roleId: id });
|
||||
|
||||
return reply.send({ ok: true });
|
||||
},
|
||||
);
|
||||
|
||||
// DELETE /api/v1/roles/:id — Delete custom role
|
||||
app.delete(
|
||||
"/api/v1/roles/:id",
|
||||
async (request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) => {
|
||||
const user = requirePermission("users:manage")(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const { id } = request.params;
|
||||
const role = db.select().from(schema.roles).where(eq(schema.roles.id, id)).get();
|
||||
if (!role) {
|
||||
return reply.status(404).send({ error: "Role not found", code: "NOT_FOUND" });
|
||||
}
|
||||
if (role.isBuiltin) {
|
||||
return reply
|
||||
.status(400)
|
||||
.send({ error: "Cannot delete built-in roles", code: "VALIDATION_ERROR" });
|
||||
}
|
||||
|
||||
db.update(schema.users)
|
||||
.set({ role: "user", updatedAt: new Date() })
|
||||
.where(eq(schema.users.role, role.name))
|
||||
.run();
|
||||
|
||||
db.delete(schema.roles).where(eq(schema.roles.id, id)).run();
|
||||
auditLog(request.log, "ROLE_DELETED", {
|
||||
adminId: user.id,
|
||||
roleId: id,
|
||||
roleName: role.name,
|
||||
});
|
||||
|
||||
return reply.send({ ok: true });
|
||||
},
|
||||
);
|
||||
|
||||
app.log.info("Roles routes registered");
|
||||
}
|
||||
@@ -9,7 +9,8 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { db, schema } from "../db/index.js";
|
||||
import { requireAdmin, requireAuth } from "../plugins/auth.js";
|
||||
import { requirePermission } from "../permissions.js";
|
||||
import { requireAuth } from "../plugins/auth.js";
|
||||
|
||||
const HTML_TAG_PATTERN = /<[a-z/!][^>]*>/i;
|
||||
|
||||
@@ -31,7 +32,7 @@ export async function settingsRoutes(app: FastifyInstance): Promise<void> {
|
||||
|
||||
// PUT /api/v1/settings — Save settings (admin only)
|
||||
app.put("/api/v1/settings", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("settings:write")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const body = request.body as Record<string, unknown> | null;
|
||||
|
||||
@@ -11,7 +11,7 @@ import { randomUUID } from "node:crypto";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { db, schema } from "../db/index.js";
|
||||
import { requireAdmin } from "../plugins/auth.js";
|
||||
import { requirePermission } from "../permissions.js";
|
||||
|
||||
function validateTeamName(name: unknown): string | null {
|
||||
if (typeof name !== "string") return "Team name is required";
|
||||
@@ -24,7 +24,7 @@ function validateTeamName(name: unknown): string | null {
|
||||
export async function teamsRoutes(app: FastifyInstance): Promise<void> {
|
||||
// GET /api/v1/teams — List all teams with member count (admin only)
|
||||
app.get("/api/v1/teams", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const user = requireAdmin(request, reply);
|
||||
const user = requirePermission("teams:manage")(request, reply);
|
||||
if (!user) return;
|
||||
|
||||
const teams = db
|
||||
@@ -47,7 +47,7 @@ export async function teamsRoutes(app: FastifyInstance): Promise<void> {
|
||||
|
||||
// POST /api/v1/teams — Create team (admin only)
|
||||
app.post("/api/v1/teams", async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("teams:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const body = request.body as { name?: string } | null;
|
||||
@@ -81,7 +81,7 @@ export async function teamsRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.put(
|
||||
"/api/v1/teams/:id",
|
||||
async (request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("teams:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const { id } = request.params;
|
||||
@@ -122,7 +122,7 @@ export async function teamsRoutes(app: FastifyInstance): Promise<void> {
|
||||
app.delete(
|
||||
"/api/v1/teams/:id",
|
||||
async (request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply) => {
|
||||
const admin = requireAdmin(request, reply);
|
||||
const admin = requirePermission("teams:manage")(request, reply);
|
||||
if (!admin) return;
|
||||
|
||||
const { id } = request.params;
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
import { validateImageBuffer } from "../lib/file-validation.js";
|
||||
import { sanitizeFilename } from "../lib/filename.js";
|
||||
import { ensureSharpCompat } from "../lib/heic-converter.js";
|
||||
import { hasEffectivePermission } from "../permissions.js";
|
||||
import { getAuthUser, requireAuth } from "../plugins/auth.js";
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────
|
||||
@@ -115,8 +116,8 @@ export async function userFileRoutes(app: FastifyInstance): Promise<void> {
|
||||
// Build the where clauses
|
||||
const conditions = [latestCondition];
|
||||
|
||||
// Non-admin users only see their own files; admins see all
|
||||
if (user.role !== "admin") {
|
||||
// Users without files:all only see their own files
|
||||
if (!hasEffectivePermission(user, "files:all")) {
|
||||
conditions.push(eq(schema.userFiles.userId, user.id));
|
||||
}
|
||||
|
||||
@@ -241,7 +242,7 @@ export async function userFileRoutes(app: FastifyInstance): Promise<void> {
|
||||
|
||||
const file = db.select().from(schema.userFiles).where(eq(schema.userFiles.id, id)).get();
|
||||
|
||||
if (!file || (user.role !== "admin" && file.userId !== user.id)) {
|
||||
if (!file || (file.userId !== user.id && !hasEffectivePermission(user, "files:all"))) {
|
||||
return reply.status(404).send({ error: "File not found" });
|
||||
}
|
||||
|
||||
@@ -321,7 +322,7 @@ export async function userFileRoutes(app: FastifyInstance): Promise<void> {
|
||||
|
||||
const file = db.select().from(schema.userFiles).where(eq(schema.userFiles.id, id)).get();
|
||||
|
||||
if (!file || (user.role !== "admin" && file.userId !== user.id)) {
|
||||
if (!file || (file.userId !== user.id && !hasEffectivePermission(user, "files:all"))) {
|
||||
return reply.status(404).send({ error: "File not found" });
|
||||
}
|
||||
|
||||
@@ -422,7 +423,8 @@ export async function userFileRoutes(app: FastifyInstance): Promise<void> {
|
||||
for (const id of ids) {
|
||||
// Ownership check: non-admin users can only delete their own files
|
||||
const file = db.select().from(schema.userFiles).where(eq(schema.userFiles.id, id)).get();
|
||||
if (!file || (user.role !== "admin" && file.userId !== user.id)) continue;
|
||||
if (!file || (file.userId !== user.id && !hasEffectivePermission(user, "files:all")))
|
||||
continue;
|
||||
// Collect all files in the chain using a recursive CTE
|
||||
const chainRows = sqlite
|
||||
.prepare(`
|
||||
|
||||
@@ -4,13 +4,16 @@ import {
|
||||
Copy,
|
||||
Eye,
|
||||
EyeOff,
|
||||
FileText,
|
||||
Info,
|
||||
Key,
|
||||
Loader2,
|
||||
Lock,
|
||||
LogOut,
|
||||
Monitor,
|
||||
MoreVertical,
|
||||
Pencil,
|
||||
Plus,
|
||||
RotateCcw,
|
||||
Search,
|
||||
Settings,
|
||||
@@ -23,7 +26,7 @@ import {
|
||||
Wrench,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Fragment, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { apiDelete, apiGet, apiPost, apiPut, clearToken, formatHeaders } from "@/lib/api";
|
||||
import { cn, copyToClipboard } from "@/lib/utils";
|
||||
@@ -42,6 +45,8 @@ type Section =
|
||||
| "security"
|
||||
| "people"
|
||||
| "teams"
|
||||
| "roles"
|
||||
| "audit-log"
|
||||
| "api-keys"
|
||||
| "ai-features"
|
||||
| "tools"
|
||||
@@ -60,6 +65,8 @@ const NAV_ITEMS: NavItem[] = [
|
||||
{ id: "security", label: "Security", icon: Shield },
|
||||
{ id: "people", label: "People", icon: Users, requiredPermission: "users:manage" },
|
||||
{ id: "teams", label: "Teams", icon: UsersRound, requiredPermission: "teams:manage" },
|
||||
{ id: "roles", label: "Roles", icon: Shield, requiredPermission: "users:manage" },
|
||||
{ id: "audit-log", label: "Audit Log", icon: FileText, requiredPermission: "audit:read" },
|
||||
{ id: "api-keys", label: "API Keys", icon: Key },
|
||||
{ id: "ai-features", label: "AI Features", icon: Sparkles, requiredPermission: "settings:write" },
|
||||
{ id: "tools", label: "Tools", icon: Wrench },
|
||||
@@ -135,6 +142,8 @@ export function SettingsDialog({ open, onClose }: SettingsDialogProps) {
|
||||
{section === "security" && <SecuritySection />}
|
||||
{section === "people" && <PeopleSection />}
|
||||
{section === "teams" && <TeamsSection />}
|
||||
{section === "roles" && <RolesSection />}
|
||||
{section === "audit-log" && <AuditLogSection />}
|
||||
{section === "api-keys" && <ApiKeysSection />}
|
||||
{section === "ai-features" && <AiFeaturesSection />}
|
||||
{section === "tools" && <ToolsSection />}
|
||||
@@ -158,6 +167,17 @@ interface ApiKeyEntry {
|
||||
name: string;
|
||||
prefix: string;
|
||||
createdAt: string;
|
||||
permissions: string[] | null;
|
||||
expiresAt: string | null;
|
||||
}
|
||||
|
||||
interface RoleEntry {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
permissions: string[];
|
||||
isBuiltin: boolean;
|
||||
userCount: number;
|
||||
}
|
||||
|
||||
interface UserEntry {
|
||||
@@ -704,6 +724,7 @@ function PeopleSection() {
|
||||
null,
|
||||
);
|
||||
const [teams, setTeams] = useState<TeamEntry[]>([]);
|
||||
const [availableRoles, setAvailableRoles] = useState<RoleEntry[]>([]);
|
||||
|
||||
const loadTeams = useCallback(async () => {
|
||||
try {
|
||||
@@ -729,6 +750,9 @@ function PeopleSection() {
|
||||
useEffect(() => {
|
||||
loadUsers();
|
||||
loadTeams();
|
||||
apiGet<{ roles: RoleEntry[] }>("/v1/roles")
|
||||
.then((data) => setAvailableRoles(data.roles))
|
||||
.catch(() => setAvailableRoles([]));
|
||||
}, [loadUsers, loadTeams]);
|
||||
|
||||
// Close dropdown when clicking outside
|
||||
@@ -934,8 +958,20 @@ function PeopleSection() {
|
||||
onChange={(e) => setNewRole(e.target.value)}
|
||||
className="px-3 py-2 rounded-lg border border-border bg-background text-sm text-foreground"
|
||||
>
|
||||
<option value="user">User</option>
|
||||
<option value="admin">Admin</option>
|
||||
{availableRoles.length > 0 ? (
|
||||
availableRoles.map((r) => (
|
||||
<option key={r.name} value={r.name}>
|
||||
{r.name.charAt(0).toUpperCase() + r.name.slice(1)} —{" "}
|
||||
{r.description || "No description"}
|
||||
</option>
|
||||
))
|
||||
) : (
|
||||
<>
|
||||
<option value="user">User — Basic tool access</option>
|
||||
<option value="editor">Editor — All files & pipelines</option>
|
||||
<option value="admin">Admin — Full access</option>
|
||||
</>
|
||||
)}
|
||||
</select>
|
||||
<select
|
||||
value={newTeam}
|
||||
@@ -984,8 +1020,20 @@ function PeopleSection() {
|
||||
onChange={(e) => setEditRole(e.target.value)}
|
||||
className="px-3 py-2 rounded-lg border border-border bg-background text-sm text-foreground"
|
||||
>
|
||||
<option value="user">User</option>
|
||||
<option value="admin">Admin</option>
|
||||
{availableRoles.length > 0 ? (
|
||||
availableRoles.map((r) => (
|
||||
<option key={r.name} value={r.name}>
|
||||
{r.name.charAt(0).toUpperCase() + r.name.slice(1)} —{" "}
|
||||
{r.description || "No description"}
|
||||
</option>
|
||||
))
|
||||
) : (
|
||||
<>
|
||||
<option value="user">User — Basic tool access</option>
|
||||
<option value="editor">Editor — All files & pipelines</option>
|
||||
<option value="admin">Admin — Full access</option>
|
||||
</>
|
||||
)}
|
||||
</select>
|
||||
<select
|
||||
value={editTeam}
|
||||
@@ -1178,6 +1226,10 @@ function ApiKeysSection() {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [generating, setGenerating] = useState(false);
|
||||
const [keyName, setKeyName] = useState("");
|
||||
const [showScoping, setShowScoping] = useState(false);
|
||||
const [scopedPerms, setScopedPerms] = useState<string[]>([]);
|
||||
const [expiresAt, setExpiresAt] = useState("");
|
||||
const { permissions } = useAuth();
|
||||
|
||||
const loadKeys = useCallback(async () => {
|
||||
try {
|
||||
@@ -1198,18 +1250,26 @@ function ApiKeysSection() {
|
||||
setGenerating(true);
|
||||
setNewKey(null);
|
||||
try {
|
||||
const data = await apiPost<{ key: string }>("/v1/api-keys", {
|
||||
name: keyName || "default",
|
||||
});
|
||||
const payload: Record<string, unknown> = { name: keyName || "default" };
|
||||
if (showScoping && scopedPerms.length > 0) {
|
||||
payload.permissions = scopedPerms;
|
||||
}
|
||||
if (expiresAt) {
|
||||
payload.expiresAt = new Date(expiresAt).toISOString();
|
||||
}
|
||||
const data = await apiPost<{ key: string }>("/v1/api-keys", payload);
|
||||
setNewKey(data.key);
|
||||
setKeyName("");
|
||||
setScopedPerms([]);
|
||||
setShowScoping(false);
|
||||
setExpiresAt("");
|
||||
await loadKeys();
|
||||
} catch {
|
||||
// Silently fail
|
||||
} finally {
|
||||
setGenerating(false);
|
||||
}
|
||||
}, [keyName, loadKeys]);
|
||||
}, [keyName, showScoping, scopedPerms, expiresAt, loadKeys]);
|
||||
|
||||
const copyKey = useCallback(async (key: string) => {
|
||||
const ok = await copyToClipboard(key);
|
||||
@@ -1269,6 +1329,62 @@ function ApiKeysSection() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Permission scoping */}
|
||||
<div className="space-y-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowScoping(!showScoping)}
|
||||
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{showScoping ? "Remove permission scoping" : "Restrict permissions (optional)"}
|
||||
</button>
|
||||
|
||||
{showScoping && (
|
||||
<div className="flex flex-wrap gap-2 p-3 rounded-lg border border-border bg-muted/20">
|
||||
{permissions.map((perm) => (
|
||||
<label key={perm} className="flex items-center gap-1.5 text-xs cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={scopedPerms.includes(perm)}
|
||||
onChange={(e) => {
|
||||
if (e.target.checked) {
|
||||
setScopedPerms([...scopedPerms, perm]);
|
||||
} else {
|
||||
setScopedPerms(scopedPerms.filter((p) => p !== perm));
|
||||
}
|
||||
}}
|
||||
className="rounded border-border"
|
||||
/>
|
||||
<span className="font-mono">{perm}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Expiration date */}
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-muted-foreground flex items-center gap-2">
|
||||
Expires:
|
||||
<input
|
||||
type="datetime-local"
|
||||
value={expiresAt}
|
||||
onChange={(e) => setExpiresAt(e.target.value)}
|
||||
className="px-2 py-1 rounded border border-border bg-background text-xs text-foreground"
|
||||
min={new Date().toISOString().slice(0, 16)}
|
||||
/>
|
||||
</label>
|
||||
{expiresAt && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpiresAt("")}
|
||||
className="text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Newly generated key display */}
|
||||
{newKey && (
|
||||
<div className="space-y-2">
|
||||
@@ -1305,6 +1421,16 @@ function ApiKeysSection() {
|
||||
<p className="text-xs text-muted-foreground font-mono">
|
||||
{k.prefix}... · Created {new Date(k.createdAt).toLocaleDateString()}
|
||||
</p>
|
||||
{k.permissions && (
|
||||
<p className="text-xs text-muted-foreground font-mono mt-0.5">
|
||||
Scoped: {k.permissions.join(", ")}
|
||||
</p>
|
||||
)}
|
||||
{k.expiresAt && (
|
||||
<span className="text-xs text-amber-500">
|
||||
Expires {new Date(k.expiresAt).toLocaleDateString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
@@ -1601,6 +1727,552 @@ function TeamsSection() {
|
||||
);
|
||||
}
|
||||
|
||||
/* ────────────────────── Roles ────────────────────── */
|
||||
|
||||
const PERMISSION_GROUPS = [
|
||||
{ label: "Tools", permissions: ["tools:use"] },
|
||||
{ label: "Files", permissions: ["files:own", "files:all"] },
|
||||
{ label: "API Keys", permissions: ["apikeys:own", "apikeys:all"] },
|
||||
{ label: "Pipelines", permissions: ["pipelines:own", "pipelines:all"] },
|
||||
{ label: "Settings", permissions: ["settings:read", "settings:write"] },
|
||||
{ label: "Users", permissions: ["users:manage"] },
|
||||
{ label: "Teams", permissions: ["teams:manage"] },
|
||||
{ label: "Branding", permissions: ["branding:manage"] },
|
||||
{
|
||||
label: "System",
|
||||
permissions: ["features:manage", "system:health", "audit:read"],
|
||||
},
|
||||
];
|
||||
|
||||
function RolesSection() {
|
||||
const [roles, setRoles] = useState<RoleEntry[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showCreateForm, setShowCreateForm] = useState(false);
|
||||
const [newName, setNewName] = useState("");
|
||||
const [newDescription, setNewDescription] = useState("");
|
||||
const [newPermissions, setNewPermissions] = useState<string[]>([]);
|
||||
const [editingRole, setEditingRole] = useState<RoleEntry | null>(null);
|
||||
const [editPermissions, setEditPermissions] = useState<string[]>([]);
|
||||
const [editName, setEditName] = useState("");
|
||||
const [editDescription, setEditDescription] = useState("");
|
||||
const [actionMsg, setActionMsg] = useState<{ type: "success" | "error"; text: string } | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const loadRoles = useCallback(async () => {
|
||||
try {
|
||||
const data = await apiGet<{ roles: RoleEntry[] }>("/v1/roles");
|
||||
setRoles(data.roles);
|
||||
} catch {
|
||||
setRoles([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadRoles();
|
||||
}, [loadRoles]);
|
||||
|
||||
const handleCreate = useCallback(
|
||||
async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!newName.trim()) return;
|
||||
try {
|
||||
await apiPost("/v1/roles", {
|
||||
name: newName.trim().toLowerCase(),
|
||||
description: newDescription.trim(),
|
||||
permissions: newPermissions,
|
||||
});
|
||||
setNewName("");
|
||||
setNewDescription("");
|
||||
setNewPermissions([]);
|
||||
setShowCreateForm(false);
|
||||
setActionMsg({ type: "success", text: "Role created successfully" });
|
||||
await loadRoles();
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : "Failed to create role";
|
||||
setActionMsg({
|
||||
type: "error",
|
||||
text: msg.includes("409") ? "A role with that name already exists" : msg,
|
||||
});
|
||||
}
|
||||
setTimeout(() => setActionMsg(null), 3000);
|
||||
},
|
||||
[newName, newDescription, newPermissions, loadRoles],
|
||||
);
|
||||
|
||||
const handleUpdate = useCallback(
|
||||
async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!editingRole) return;
|
||||
try {
|
||||
await apiPut(`/v1/roles/${editingRole.id}`, {
|
||||
name: editName.trim().toLowerCase(),
|
||||
description: editDescription.trim(),
|
||||
permissions: editPermissions,
|
||||
});
|
||||
setEditingRole(null);
|
||||
setActionMsg({ type: "success", text: "Role updated" });
|
||||
await loadRoles();
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : "Failed to update role";
|
||||
setActionMsg({ type: "error", text: msg });
|
||||
}
|
||||
setTimeout(() => setActionMsg(null), 3000);
|
||||
},
|
||||
[editingRole, editName, editDescription, editPermissions, loadRoles],
|
||||
);
|
||||
|
||||
const handleDelete = useCallback(
|
||||
async (role: RoleEntry) => {
|
||||
const msg =
|
||||
role.userCount > 0
|
||||
? `Delete role "${role.name}"? ${role.userCount} user${role.userCount !== 1 ? "s" : ""} will need to be reassigned.`
|
||||
: `Delete role "${role.name}"?`;
|
||||
if (!confirm(msg)) return;
|
||||
try {
|
||||
await apiDelete(`/v1/roles/${role.id}`);
|
||||
setActionMsg({ type: "success", text: `Role "${role.name}" deleted` });
|
||||
await loadRoles();
|
||||
} catch (err) {
|
||||
const errMsg = err instanceof Error ? err.message : "Failed to delete role";
|
||||
setActionMsg({ type: "error", text: errMsg });
|
||||
}
|
||||
setTimeout(() => setActionMsg(null), 3000);
|
||||
},
|
||||
[loadRoles],
|
||||
);
|
||||
|
||||
const togglePermission = (perm: string, list: string[], setter: (v: string[]) => void) => {
|
||||
setter(list.includes(perm) ? list.filter((p) => p !== perm) : [...list, perm]);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-foreground">Roles</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Manage roles and their permissions. Built-in roles cannot be modified.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{actionMsg && (
|
||||
<div
|
||||
className={cn(
|
||||
"text-sm px-3 py-2 rounded-lg",
|
||||
actionMsg.type === "error"
|
||||
? "bg-destructive/10 text-destructive"
|
||||
: "bg-green-500/10 text-green-600 dark:text-green-400",
|
||||
)}
|
||||
>
|
||||
{actionMsg.text}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowCreateForm(!showCreateForm)}
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90 transition-colors"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
Create Custom Role
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Create role form */}
|
||||
{showCreateForm && (
|
||||
<form
|
||||
onSubmit={handleCreate}
|
||||
className="p-4 rounded-lg border border-border bg-muted/20 space-y-3"
|
||||
>
|
||||
<h4 className="text-sm font-medium text-foreground">New Role</h4>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<input
|
||||
type="text"
|
||||
value={newName}
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
placeholder="Role name"
|
||||
required
|
||||
className="px-3 py-2 rounded-lg border border-border bg-background text-sm text-foreground"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={newDescription}
|
||||
onChange={(e) => setNewDescription(e.target.value)}
|
||||
placeholder="Description (optional)"
|
||||
className="px-3 py-2 rounded-lg border border-border bg-background text-sm text-foreground"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground mb-2">Permissions</p>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{PERMISSION_GROUPS.map((group) => (
|
||||
<div key={group.label} className="space-y-1">
|
||||
<p className="text-xs font-semibold text-foreground">{group.label}</p>
|
||||
{group.permissions.map((perm) => (
|
||||
<label key={perm} className="flex items-center gap-1.5 text-xs cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={newPermissions.includes(perm)}
|
||||
onChange={() => togglePermission(perm, newPermissions, setNewPermissions)}
|
||||
className="rounded border-border"
|
||||
/>
|
||||
<span className="font-mono">{perm}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
type="submit"
|
||||
className="flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90 transition-colors"
|
||||
>
|
||||
Create
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setShowCreateForm(false);
|
||||
setNewName("");
|
||||
setNewDescription("");
|
||||
setNewPermissions([]);
|
||||
}}
|
||||
className="px-4 py-2 rounded-lg border border-border text-sm text-muted-foreground hover:bg-muted transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{/* Edit role form */}
|
||||
{editingRole && (
|
||||
<form
|
||||
onSubmit={handleUpdate}
|
||||
className="p-4 rounded-lg border border-primary/30 bg-primary/5 space-y-3"
|
||||
>
|
||||
<h4 className="text-sm font-medium text-foreground">Edit Role: {editingRole.name}</h4>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<input
|
||||
type="text"
|
||||
value={editName}
|
||||
onChange={(e) => setEditName(e.target.value)}
|
||||
placeholder="Role name"
|
||||
required
|
||||
className="px-3 py-2 rounded-lg border border-border bg-background text-sm text-foreground"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={editDescription}
|
||||
onChange={(e) => setEditDescription(e.target.value)}
|
||||
placeholder="Description (optional)"
|
||||
className="px-3 py-2 rounded-lg border border-border bg-background text-sm text-foreground"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground mb-2">Permissions</p>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{PERMISSION_GROUPS.map((group) => (
|
||||
<div key={group.label} className="space-y-1">
|
||||
<p className="text-xs font-semibold text-foreground">{group.label}</p>
|
||||
{group.permissions.map((perm) => (
|
||||
<label key={perm} className="flex items-center gap-1.5 text-xs cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={editPermissions.includes(perm)}
|
||||
onChange={() => togglePermission(perm, editPermissions, setEditPermissions)}
|
||||
className="rounded border-border"
|
||||
/>
|
||||
<span className="font-mono">{perm}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
type="submit"
|
||||
className="px-4 py-2 rounded-lg bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90 transition-colors"
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEditingRole(null)}
|
||||
className="px-4 py-2 rounded-lg border border-border text-sm text-muted-foreground hover:bg-muted transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{/* Role cards */}
|
||||
<div className="space-y-3">
|
||||
{roles.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-8">No roles found.</p>
|
||||
) : (
|
||||
roles.map((role) => (
|
||||
<div
|
||||
key={role.id}
|
||||
className="p-4 rounded-lg border border-border bg-muted/20 space-y-2"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-semibold text-foreground capitalize">
|
||||
{role.name}
|
||||
</span>
|
||||
{role.isBuiltin && (
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-muted text-xs font-medium text-muted-foreground">
|
||||
<Lock className="h-3 w-3" />
|
||||
Built-in
|
||||
</span>
|
||||
)}
|
||||
<span className="inline-block px-2 py-0.5 rounded-full bg-primary/10 text-xs font-medium text-primary">
|
||||
{role.userCount} user{role.userCount !== 1 ? "s" : ""}
|
||||
</span>
|
||||
</div>
|
||||
{!role.isBuiltin && (
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setEditingRole(role);
|
||||
setEditName(role.name);
|
||||
setEditDescription(role.description);
|
||||
setEditPermissions([...role.permissions]);
|
||||
}}
|
||||
className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
|
||||
title="Edit role"
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleDelete(role)}
|
||||
className="p-1.5 rounded-lg hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors"
|
||||
title="Delete role"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{role.description && (
|
||||
<p className="text-xs text-muted-foreground">{role.description}</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{role.permissions.map((perm) => (
|
||||
<span
|
||||
key={perm}
|
||||
className="inline-block px-2 py-0.5 rounded-full bg-muted text-xs font-mono text-muted-foreground"
|
||||
>
|
||||
{perm}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ────────────────────── Audit Log ────────────────────── */
|
||||
|
||||
const AUDIT_ACTIONS = [
|
||||
"LOGIN_SUCCESS",
|
||||
"LOGIN_FAILED",
|
||||
"USER_CREATED",
|
||||
"USER_UPDATED",
|
||||
"USER_DELETED",
|
||||
"PASSWORD_CHANGED",
|
||||
"PASSWORD_RESET",
|
||||
"API_KEY_CREATED",
|
||||
"API_KEY_DELETED",
|
||||
"ROLE_CREATED",
|
||||
"ROLE_UPDATED",
|
||||
"ROLE_DELETED",
|
||||
"SETTINGS_UPDATED",
|
||||
] as const;
|
||||
|
||||
interface AuditEntry {
|
||||
id: string;
|
||||
actorUsername: string;
|
||||
action: string;
|
||||
targetType: string | null;
|
||||
targetId: string | null;
|
||||
details: Record<string, unknown> | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
function formatRelativeTime(iso: string): string {
|
||||
const diff = Date.now() - new Date(iso).getTime();
|
||||
const mins = Math.floor(diff / 60_000);
|
||||
if (mins < 1) return "just now";
|
||||
if (mins < 60) return `${mins}m ago`;
|
||||
const hrs = Math.floor(mins / 60);
|
||||
if (hrs < 24) return `${hrs}h ago`;
|
||||
const days = Math.floor(hrs / 24);
|
||||
if (days < 7) return `${days}d ago`;
|
||||
return new Date(iso).toLocaleDateString();
|
||||
}
|
||||
|
||||
function AuditLogSection() {
|
||||
const [entries, setEntries] = useState<AuditEntry[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [page, setPage] = useState(1);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [actionFilter, setActionFilter] = useState("");
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null);
|
||||
const limit = 25;
|
||||
|
||||
const fetchEntries = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params = new URLSearchParams({ page: String(page), limit: String(limit) });
|
||||
if (actionFilter) params.set("action", actionFilter);
|
||||
const data = await apiGet<{ entries: AuditEntry[]; total: number }>(
|
||||
`/v1/audit-log?${params}`,
|
||||
);
|
||||
setEntries(data.entries);
|
||||
setTotal(data.total);
|
||||
} catch {
|
||||
setEntries([]);
|
||||
setTotal(0);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [page, actionFilter]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchEntries();
|
||||
}, [fetchEntries]);
|
||||
|
||||
const totalPages = Math.max(1, Math.ceil(total / limit));
|
||||
|
||||
const handleFilterChange = (value: string) => {
|
||||
setActionFilter(value);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold text-foreground">Audit Log</h3>
|
||||
<select
|
||||
value={actionFilter}
|
||||
onChange={(e) => handleFilterChange(e.target.value)}
|
||||
className="text-sm border border-border rounded-lg px-2 py-1.5 bg-background text-foreground"
|
||||
>
|
||||
<option value="">All actions</option>
|
||||
{AUDIT_ACTIONS.map((a) => (
|
||||
<option key={a} value={a}>
|
||||
{a.replaceAll("_", " ")}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : entries.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-8">No audit log entries.</p>
|
||||
) : (
|
||||
<div className="border border-border rounded-lg overflow-hidden">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-border bg-muted/30">
|
||||
<th className="text-left px-3 py-2 font-medium text-muted-foreground">Time</th>
|
||||
<th className="text-left px-3 py-2 font-medium text-muted-foreground">User</th>
|
||||
<th className="text-left px-3 py-2 font-medium text-muted-foreground">Action</th>
|
||||
<th className="text-left px-3 py-2 font-medium text-muted-foreground">Target</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{entries.map((entry) => (
|
||||
<Fragment key={entry.id}>
|
||||
<tr
|
||||
className="border-b border-border last:border-0 hover:bg-muted/20 cursor-pointer transition-colors"
|
||||
onClick={() => setExpandedId(expandedId === entry.id ? null : entry.id)}
|
||||
>
|
||||
<td className="px-3 py-2 text-muted-foreground whitespace-nowrap">
|
||||
{formatRelativeTime(entry.createdAt)}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-foreground">{entry.actorUsername}</td>
|
||||
<td className="px-3 py-2">
|
||||
<span className="font-mono text-xs bg-muted px-1.5 py-0.5 rounded">
|
||||
{entry.action}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-3 py-2 text-muted-foreground">
|
||||
{entry.targetType
|
||||
? `${entry.targetType}${entry.targetId ? ` #${entry.targetId}` : ""}`
|
||||
: "—"}
|
||||
</td>
|
||||
</tr>
|
||||
{expandedId === entry.id && entry.details && (
|
||||
<tr className="border-b border-border last:border-0">
|
||||
<td colSpan={4} className="px-3 py-2 bg-muted/10">
|
||||
<pre className="text-xs text-muted-foreground whitespace-pre-wrap font-mono overflow-x-auto">
|
||||
{JSON.stringify(entry.details, null, 2)}
|
||||
</pre>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pagination */}
|
||||
{totalPages > 1 && (
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span className="text-muted-foreground">
|
||||
Page {page} of {totalPages} ({total} entries)
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={page <= 1}
|
||||
onClick={() => setPage((p) => p - 1)}
|
||||
className="px-3 py-1 rounded-lg border border-border text-foreground hover:bg-muted disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
Previous
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={page >= totalPages}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
className="px-3 py-1 rounded-lg border border-border text-foreground hover:bg-muted disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
Next
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ────────────────────── Tools ────────────────────── */
|
||||
|
||||
function ToolsSection() {
|
||||
|
||||
Reference in New Issue
Block a user