feat: user invite flow, deactivate/delete, favicon, dashboard loading fix, admin full-width
- Invite flow: admin can invite users by email with role selection; accept-invite page sets password and creates the account; 72-hour token expiry; E2E tests - User deactivate/reactivate/delete: new tRPC procedures + UI buttons; deactivation revokes all active sessions immediately; delete cascades vacation/broadcast records; isActive field added via migration 20260402000000_user_isactive - Auth: block login for inactive users with audit entry - Favicon: SVG favicon + ICO/PNG fallbacks (16, 32, 180, 192, 512px); manifest updated - Dashboard: GridLayout dynamic-import loading skeleton prevents blank dark area on first login before react-grid-layout chunk is cached - Admin users: remove max-w-5xl constraint so table uses full page width - Dev: docker container restart workflow documented in LEARNINGS.md; Prisma generate must run inside the container after schema changes (named node_modules volume) Co-Authored-By: claude-flow <ruv@ruv.net>
@@ -0,0 +1,62 @@
|
|||||||
|
name: Docker Deploy Test
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: deploy-test-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
docker-deploy-test:
|
||||||
|
name: Fresh-Linux Docker Deploy
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Create minimal .env
|
||||||
|
run: |
|
||||||
|
cat <<'EOF' > .env
|
||||||
|
NEXTAUTH_URL=http://localhost:3100
|
||||||
|
NEXTAUTH_SECRET=ci-test-secret-minimum-32-chars-xx
|
||||||
|
PGADMIN_PASSWORD=ci-pgadmin
|
||||||
|
EOF
|
||||||
|
|
||||||
|
- name: Start infrastructure (postgres + redis)
|
||||||
|
run: docker compose up -d postgres redis
|
||||||
|
|
||||||
|
- name: Wait for postgres
|
||||||
|
run: |
|
||||||
|
for i in $(seq 1 20); do
|
||||||
|
docker compose exec -T postgres pg_isready -U capakraken -d capakraken && break
|
||||||
|
sleep 3
|
||||||
|
done
|
||||||
|
|
||||||
|
- name: Build and start app (full profile)
|
||||||
|
run: docker compose --profile full up -d --build app
|
||||||
|
|
||||||
|
- name: Wait for /api/health (up to 3 minutes)
|
||||||
|
run: |
|
||||||
|
for i in $(seq 1 36); do
|
||||||
|
STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3100/api/health || echo "000")
|
||||||
|
echo "Attempt $i: HTTP $STATUS"
|
||||||
|
if [ "$STATUS" = "200" ]; then exit 0; fi
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
echo "Health check timed out"
|
||||||
|
docker compose logs app --tail=50
|
||||||
|
exit 1
|
||||||
|
|
||||||
|
- name: Verify health response contains status ok
|
||||||
|
run: |
|
||||||
|
BODY=$(curl -sf http://localhost:3100/api/health)
|
||||||
|
echo "$BODY"
|
||||||
|
echo "$BODY" | grep '"status":"ok"'
|
||||||
|
|
||||||
|
- name: Show logs on failure
|
||||||
|
if: failure()
|
||||||
|
run: docker compose logs --tail=100
|
||||||
@@ -7,6 +7,22 @@
|
|||||||
|
|
||||||
## Learnings
|
## Learnings
|
||||||
|
|
||||||
|
### 2026-04-02 | DevOps | Prisma schema changes require container restart
|
||||||
|
|
||||||
|
**Problem:** After adding a new column to `schema.prisma` and running `prisma generate` on the host, the running Docker app container still used the old Prisma client (the container's `node_modules` is a named Docker volume, isolated from the host filesystem). Queries referencing the new field (`isActive`) failed at runtime, causing tRPC procedures to return errors.
|
||||||
|
|
||||||
|
**Solution:** Always restart the app container after Prisma schema changes:
|
||||||
|
```
|
||||||
|
docker compose --profile full restart app
|
||||||
|
```
|
||||||
|
The startup script `tooling/docker/app-dev-start.sh` already runs `prisma generate` + `db:migrate:deploy` on every container start — so a restart is sufficient. No rebuild needed unless `pnpm-lock.yaml` or `Dockerfile.dev` changed.
|
||||||
|
|
||||||
|
**Rule:** Prisma schema change checklist:
|
||||||
|
1. Edit `packages/db/prisma/schema.prisma`
|
||||||
|
2. Write migration SQL in `packages/db/prisma/migrations/<timestamp>_<name>/migration.sql`
|
||||||
|
3. Apply migration to the running DB directly (for dev speed): `docker exec capakraken-postgres-1 psql -U capakraken -d capakraken < migration.sql`
|
||||||
|
4. `docker compose --profile full restart app` — regenerates Prisma client + runs migrations inside the container
|
||||||
|
|
||||||
### 2026-03-13 | Architecture | Dispo v2 chargeability calculator design
|
### 2026-03-13 | Architecture | Dispo v2 chargeability calculator design
|
||||||
- Pure functions in `packages/engine/src/chargeability/calculator.ts` — no DB imports, all data passed as arguments.
|
- Pure functions in `packages/engine/src/chargeability/calculator.ts` — no DB imports, all data passed as arguments.
|
||||||
- `deriveResourceForecast()` takes SAH + assignment slices per month, returns ratio breakdown (Chg/BD/MD&I/M&O/PD&R/Absence/Unassigned).
|
- `deriveResourceForecast()` takes SAH + assignment slices per month, returns ratio breakdown (Chg/BD/MD&I/M&O/PD&R/Absence/Unassigned).
|
||||||
|
|||||||
@@ -9,7 +9,8 @@
|
|||||||
"lint": "next lint",
|
"lint": "next lint",
|
||||||
"typecheck": "tsc --project tsconfig.typecheck.json --noEmit",
|
"typecheck": "tsc --project tsconfig.typecheck.json --noEmit",
|
||||||
"test:unit": "vitest run",
|
"test:unit": "vitest run",
|
||||||
"test:e2e": "playwright test"
|
"test:e2e": "playwright test",
|
||||||
|
"test:e2e:email": "playwright test --config playwright.dev.config.ts e2e/dev-system/invite-flow.spec.ts e2e/dev-system/password-reset.spec.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@capakraken/api": "workspace:*",
|
"@capakraken/api": "workspace:*",
|
||||||
|
|||||||
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 464 B |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 5.3 KiB |
|
After Width: | Height: | Size: 300 KiB |
|
Before Width: | Height: | Size: 6.8 KiB After Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 110 KiB |
@@ -8,6 +8,7 @@
|
|||||||
"theme_color": "#0284c7",
|
"theme_color": "#0284c7",
|
||||||
"orientation": "any",
|
"orientation": "any",
|
||||||
"icons": [
|
"icons": [
|
||||||
|
{ "src": "/favicon.svg", "type": "image/svg+xml", "sizes": "any", "purpose": "any" },
|
||||||
{ "src": "/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any maskable" },
|
{ "src": "/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any maskable" },
|
||||||
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
|
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, use } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { trpc } from "~/lib/trpc/client.js";
|
||||||
|
|
||||||
|
export default function AcceptInvitePage({ params }: { params: Promise<{ token: string }> }) {
|
||||||
|
const { token } = use(params);
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [confirm, setConfirm] = useState("");
|
||||||
|
const [formError, setFormError] = useState<string | null>(null);
|
||||||
|
const [done, setDone] = useState(false);
|
||||||
|
|
||||||
|
const { data: invite, isLoading, error: inviteError } = trpc.invite.getInvite.useQuery(
|
||||||
|
{ token },
|
||||||
|
{ retry: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
const acceptMutation = trpc.invite.acceptInvite.useMutation({
|
||||||
|
onSuccess: () => setDone(true),
|
||||||
|
onError: (err) => setFormError(err.message),
|
||||||
|
});
|
||||||
|
|
||||||
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
setFormError(null);
|
||||||
|
if (password.length < 8) { setFormError("Password must be at least 8 characters."); return; }
|
||||||
|
if (password !== confirm) { setFormError("Passwords do not match."); return; }
|
||||||
|
await acceptMutation.mutateAsync({ token, password });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-950">
|
||||||
|
<p className="text-sm text-gray-500">Loading…</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inviteError || !invite) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-950 p-4">
|
||||||
|
<div className="w-full max-w-md rounded-2xl bg-white dark:bg-gray-900 shadow-lg p-8 text-center">
|
||||||
|
<div className="text-4xl mb-4">🔗</div>
|
||||||
|
<h1 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">
|
||||||
|
Invite link invalid or expired
|
||||||
|
</h1>
|
||||||
|
<p className="text-sm text-gray-500">
|
||||||
|
{inviteError?.message ?? "This invite link is no longer valid. Please request a new invitation from your administrator."}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (done) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-950 p-4">
|
||||||
|
<div className="w-full max-w-md rounded-2xl bg-white dark:bg-gray-900 shadow-lg p-8 text-center">
|
||||||
|
<div className="text-4xl mb-4">✅</div>
|
||||||
|
<h1 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">
|
||||||
|
Account created
|
||||||
|
</h1>
|
||||||
|
<p className="text-sm text-gray-500 mb-6">Your account has been set up successfully.</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => router.push("/auth/signin")}
|
||||||
|
className="rounded-lg bg-brand-600 px-5 py-2 text-sm font-semibold text-white hover:bg-brand-700 transition-colors"
|
||||||
|
>
|
||||||
|
Go to sign in
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-950 p-4">
|
||||||
|
<div className="w-full max-w-md rounded-2xl bg-white dark:bg-gray-900 shadow-lg p-8">
|
||||||
|
<div className="mb-6">
|
||||||
|
<h1 className="text-xl font-bold text-gray-900 dark:text-gray-100">Accept invitation</h1>
|
||||||
|
<p className="mt-1 text-sm text-gray-500">
|
||||||
|
You have been invited as <strong>{invite.role}</strong> to CapaKraken.
|
||||||
|
Set a password to activate your account (<span className="font-medium">{invite.email}</span>).
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
{formError && (
|
||||||
|
<div className="rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-700 px-4 py-3 text-sm text-red-700 dark:text-red-400">
|
||||||
|
{formError}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||||
|
Password
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
minLength={8}
|
||||||
|
placeholder="At least 8 characters"
|
||||||
|
className="w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 px-3 py-2 text-sm text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||||
|
Confirm password
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={confirm}
|
||||||
|
onChange={(e) => setConfirm(e.target.value)}
|
||||||
|
required
|
||||||
|
placeholder="Repeat your password"
|
||||||
|
className="w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 px-3 py-2 text-sm text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={acceptMutation.isPending}
|
||||||
|
className="w-full rounded-lg bg-brand-600 px-4 py-2 text-sm font-semibold text-white hover:bg-brand-700 transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{acceptMutation.isPending ? "Setting up account…" : "Create account"}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -23,6 +23,15 @@ export const metadata: Metadata = {
|
|||||||
title: "CapaKraken — Resource & Capacity Planning",
|
title: "CapaKraken — Resource & Capacity Planning",
|
||||||
description: "Interactive resource planning and project staffing tool",
|
description: "Interactive resource planning and project staffing tool",
|
||||||
manifest: "/manifest.json",
|
manifest: "/manifest.json",
|
||||||
|
icons: {
|
||||||
|
icon: [
|
||||||
|
{ url: "/favicon.svg", type: "image/svg+xml" },
|
||||||
|
{ url: "/favicon-32x32.png", sizes: "32x32", type: "image/png" },
|
||||||
|
{ url: "/favicon-16x16.png", sizes: "16x16", type: "image/png" },
|
||||||
|
{ url: "/favicon.ico" },
|
||||||
|
],
|
||||||
|
apple: [{ url: "/apple-touch-icon.png", sizes: "180x180" }],
|
||||||
|
},
|
||||||
appleWebApp: {
|
appleWebApp: {
|
||||||
capable: true,
|
capable: true,
|
||||||
statusBarStyle: "default",
|
statusBarStyle: "default",
|
||||||
@@ -51,7 +60,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
|||||||
return (
|
return (
|
||||||
<html lang="en" suppressHydrationWarning>
|
<html lang="en" suppressHydrationWarning>
|
||||||
<head>
|
<head>
|
||||||
<script nonce={nonce} dangerouslySetInnerHTML={{__html: `
|
<script nonce={nonce} suppressHydrationWarning dangerouslySetInnerHTML={{__html: `
|
||||||
try {
|
try {
|
||||||
var p = JSON.parse(localStorage.getItem('capakraken_theme') || '{}');
|
var p = JSON.parse(localStorage.getItem('capakraken_theme') || '{}');
|
||||||
if (p.mode === 'dark') document.documentElement.classList.add('dark');
|
if (p.mode === 'dark') document.documentElement.classList.add('dark');
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { SystemRole } from "@capakraken/shared";
|
||||||
|
import { trpc } from "~/lib/trpc/client.js";
|
||||||
|
import { AnimatedModal } from "~/components/ui/AnimatedModal.js";
|
||||||
|
|
||||||
|
interface InviteUserModalProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ROLE_OPTIONS: { value: SystemRole; label: string }[] = [
|
||||||
|
{ value: SystemRole.USER, label: "User" },
|
||||||
|
{ value: SystemRole.VIEWER, label: "Viewer" },
|
||||||
|
{ value: SystemRole.CONTROLLER, label: "Controller" },
|
||||||
|
{ value: SystemRole.MANAGER, label: "Manager" },
|
||||||
|
{ value: SystemRole.ADMIN, label: "Admin" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function InviteUserModal({ open, onClose }: InviteUserModalProps) {
|
||||||
|
const [email, setEmail] = useState("");
|
||||||
|
const [role, setRole] = useState<SystemRole>(SystemRole.USER);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [success, setSuccess] = useState(false);
|
||||||
|
|
||||||
|
const utils = trpc.useUtils();
|
||||||
|
|
||||||
|
const inviteMutation = trpc.invite.createInvite.useMutation({
|
||||||
|
onSuccess: async () => {
|
||||||
|
await utils.invite.listInvites.invalidate();
|
||||||
|
setSuccess(true);
|
||||||
|
setEmail("");
|
||||||
|
setRole(SystemRole.USER);
|
||||||
|
setTimeout(() => {
|
||||||
|
setSuccess(false);
|
||||||
|
onClose();
|
||||||
|
}, 1500);
|
||||||
|
},
|
||||||
|
onError: (err) => setError(err.message),
|
||||||
|
});
|
||||||
|
|
||||||
|
function handleClose() {
|
||||||
|
setEmail("");
|
||||||
|
setRole(SystemRole.USER);
|
||||||
|
setError(null);
|
||||||
|
setSuccess(false);
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
setError(null);
|
||||||
|
if (!email) { setError("Email is required."); return; }
|
||||||
|
await inviteMutation.mutateAsync({ email, role });
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AnimatedModal open={open} onClose={handleClose} maxWidth="max-w-md">
|
||||||
|
<div className="px-6 py-5">
|
||||||
|
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-4">Invite User</h2>
|
||||||
|
|
||||||
|
{success ? (
|
||||||
|
<div className="rounded-lg bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-700 px-4 py-3 text-sm text-green-700 dark:text-green-400">
|
||||||
|
Invitation sent successfully.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
{error && (
|
||||||
|
<div className="rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-700 px-4 py-3 text-sm text-red-700 dark:text-red-400">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||||
|
Email address
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
placeholder="user@example.com"
|
||||||
|
required
|
||||||
|
className="w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 px-3 py-2 text-sm text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||||
|
Role
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={role}
|
||||||
|
onChange={(e) => setRole(e.target.value as SystemRole)}
|
||||||
|
className="w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 px-3 py-2 text-sm text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-brand-400"
|
||||||
|
>
|
||||||
|
{ROLE_OPTIONS.map((opt) => (
|
||||||
|
<option key={opt.value} value={opt.value}>{opt.label}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||||
|
An invite link valid for 72 hours will be sent to this email address.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-3 pt-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleClose}
|
||||||
|
className="rounded-lg border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={inviteMutation.isPending}
|
||||||
|
className="rounded-lg bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{inviteMutation.isPending ? "Sending..." : "Send Invite"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</AnimatedModal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import { useState, useMemo } from "react";
|
|||||||
import { SystemRole, PermissionKey, ROLE_DEFAULT_PERMISSIONS, type PermissionOverrides } from "@capakraken/shared";
|
import { SystemRole, PermissionKey, ROLE_DEFAULT_PERMISSIONS, type PermissionOverrides } from "@capakraken/shared";
|
||||||
import { trpc } from "~/lib/trpc/client.js";
|
import { trpc } from "~/lib/trpc/client.js";
|
||||||
import { AnimatedModal } from "~/components/ui/AnimatedModal.js";
|
import { AnimatedModal } from "~/components/ui/AnimatedModal.js";
|
||||||
|
import { InviteUserModal } from "./InviteUserModal.js";
|
||||||
import { SuccessToast } from "~/components/ui/SuccessToast.js";
|
import { SuccessToast } from "~/components/ui/SuccessToast.js";
|
||||||
import { FilterChips } from "~/components/ui/FilterChips.js";
|
import { FilterChips } from "~/components/ui/FilterChips.js";
|
||||||
import { InfoTooltip } from "~/components/ui/InfoTooltip.js";
|
import { InfoTooltip } from "~/components/ui/InfoTooltip.js";
|
||||||
@@ -65,6 +66,7 @@ type UserRow = {
|
|||||||
lastActiveAt: Date | null;
|
lastActiveAt: Date | null;
|
||||||
permissionOverrides: PermissionOverrides | null;
|
permissionOverrides: PermissionOverrides | null;
|
||||||
totpEnabled: boolean;
|
totpEnabled: boolean;
|
||||||
|
isActive: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
type EditState = {
|
type EditState = {
|
||||||
@@ -102,6 +104,8 @@ export function UsersClient() {
|
|||||||
const [confirmPassword, setConfirmPassword] = useState("");
|
const [confirmPassword, setConfirmPassword] = useState("");
|
||||||
const [passwordError, setPasswordError] = useState<string | null>(null);
|
const [passwordError, setPasswordError] = useState<string | null>(null);
|
||||||
const [passwordSuccess, setPasswordSuccess] = useState(false);
|
const [passwordSuccess, setPasswordSuccess] = useState(false);
|
||||||
|
const [inviteOpen, setInviteOpen] = useState(false);
|
||||||
|
const [deleteTarget, setDeleteTarget] = useState<{ userId: string; userName: string } | null>(null);
|
||||||
|
|
||||||
const utils = trpc.useUtils();
|
const utils = trpc.useUtils();
|
||||||
|
|
||||||
@@ -208,6 +212,34 @@ export function UsersClient() {
|
|||||||
onError: (err) => setActionError(err.message),
|
onError: (err) => setActionError(err.message),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const deactivateMutation = trpc.user.deactivate.useMutation({
|
||||||
|
onSuccess: async () => {
|
||||||
|
await utils.user.list.invalidate();
|
||||||
|
setActionError(null);
|
||||||
|
},
|
||||||
|
onError: (err) => setActionError(err.message),
|
||||||
|
});
|
||||||
|
|
||||||
|
const reactivateMutation = trpc.user.reactivate.useMutation({
|
||||||
|
onSuccess: async () => {
|
||||||
|
await utils.user.list.invalidate();
|
||||||
|
setActionError(null);
|
||||||
|
},
|
||||||
|
onError: (err) => setActionError(err.message),
|
||||||
|
});
|
||||||
|
|
||||||
|
const deleteMutation = trpc.user.delete.useMutation({
|
||||||
|
onSuccess: async () => {
|
||||||
|
await utils.user.list.invalidate();
|
||||||
|
setDeleteTarget(null);
|
||||||
|
setActionError(null);
|
||||||
|
},
|
||||||
|
onError: (err) => {
|
||||||
|
setActionError(err.message);
|
||||||
|
setDeleteTarget(null);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
function openSetPassword(user: UserRow) {
|
function openSetPassword(user: UserRow) {
|
||||||
setPasswordTarget({ userId: user.id, userName: user.name ?? user.email });
|
setPasswordTarget({ userId: user.id, userName: user.name ?? user.email });
|
||||||
setNewPassword("");
|
setNewPassword("");
|
||||||
@@ -395,11 +427,11 @@ export function UsersClient() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6 max-w-5xl mx-auto">
|
<div className="app-page">
|
||||||
<div className="flex items-center justify-between mb-6">
|
<div className="app-page-header mb-6">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-gray-50">User Management</h1>
|
<h1 className="app-page-title">User Management</h1>
|
||||||
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
|
<p className="app-page-subtitle mt-1">
|
||||||
Manage user roles and permission overrides
|
Manage user roles and permission overrides
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -430,6 +462,16 @@ export function UsersClient() {
|
|||||||
</svg>
|
</svg>
|
||||||
{autoLinkMutation.isPending ? "Linking..." : "Auto-link Resources"}
|
{autoLinkMutation.isPending ? "Linking..." : "Auto-link Resources"}
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setInviteOpen(true)}
|
||||||
|
className="inline-flex items-center gap-2 rounded-lg border border-brand-300 dark:border-brand-600 px-4 py-2 text-sm font-medium text-brand-700 dark:text-brand-300 hover:bg-brand-50 dark:hover:bg-brand-900/20 transition-colors"
|
||||||
|
>
|
||||||
|
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
|
||||||
|
</svg>
|
||||||
|
Invite User
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => { setCreateState({ ...EMPTY_CREATE }); setActionError(null); }}
|
onClick={() => { setCreateState({ ...EMPTY_CREATE }); setActionError(null); }}
|
||||||
@@ -515,7 +557,7 @@ export function UsersClient() {
|
|||||||
{sorted.map((user) => (
|
{sorted.map((user) => (
|
||||||
<tr
|
<tr
|
||||||
key={user.id}
|
key={user.id}
|
||||||
className="border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/30 transition-colors"
|
className={`border-b border-gray-100 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-800/30 transition-colors ${!user.isActive ? "opacity-60" : ""}`}
|
||||||
>
|
>
|
||||||
<td className="px-4 py-3 font-medium text-gray-900 dark:text-gray-100">
|
<td className="px-4 py-3 font-medium text-gray-900 dark:text-gray-100">
|
||||||
{user.name ?? <span className="italic text-gray-400">—</span>}
|
{user.name ?? <span className="italic text-gray-400">—</span>}
|
||||||
@@ -532,7 +574,12 @@ export function UsersClient() {
|
|||||||
</td>
|
</td>
|
||||||
<td className="px-4 py-3 text-center">
|
<td className="px-4 py-3 text-center">
|
||||||
<div className="flex items-center justify-center gap-1.5">
|
<div className="flex items-center justify-center gap-1.5">
|
||||||
{isOnline(user) ? (
|
{!user.isActive ? (
|
||||||
|
<span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400">
|
||||||
|
<span className="h-1.5 w-1.5 rounded-full bg-red-500" />
|
||||||
|
Inactive
|
||||||
|
</span>
|
||||||
|
) : isOnline(user) ? (
|
||||||
<span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-400">
|
<span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-400">
|
||||||
<span className="h-1.5 w-1.5 rounded-full bg-green-500" />
|
<span className="h-1.5 w-1.5 rounded-full bg-green-500" />
|
||||||
Online
|
Online
|
||||||
@@ -594,6 +641,39 @@ export function UsersClient() {
|
|||||||
>
|
>
|
||||||
Edit
|
Edit
|
||||||
</button>
|
</button>
|
||||||
|
{user.isActive ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
if (confirm(`Deactivate ${user.name ?? user.email}? They will be logged out immediately and cannot log in until reactivated.`)) {
|
||||||
|
void deactivateMutation.mutateAsync({ userId: user.id });
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={deactivateMutation.isPending}
|
||||||
|
className="text-xs text-amber-600 hover:text-amber-800 dark:text-amber-400 dark:hover:text-amber-300 font-medium"
|
||||||
|
title="Deactivate user — blocks login and revokes sessions"
|
||||||
|
>
|
||||||
|
Deactivate
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void reactivateMutation.mutateAsync({ userId: user.id })}
|
||||||
|
disabled={reactivateMutation.isPending}
|
||||||
|
className="text-xs text-green-600 hover:text-green-800 dark:text-green-400 dark:hover:text-green-300 font-medium"
|
||||||
|
title="Reactivate user — allows login again"
|
||||||
|
>
|
||||||
|
Reactivate
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setDeleteTarget({ userId: user.id, userName: user.name ?? user.email })}
|
||||||
|
className="text-xs text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 font-medium"
|
||||||
|
title="Permanently delete user"
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -677,6 +757,49 @@ export function UsersClient() {
|
|||||||
|
|
||||||
<SuccessToast show={passwordSuccess} message="Password updated successfully" />
|
<SuccessToast show={passwordSuccess} message="Password updated successfully" />
|
||||||
|
|
||||||
|
<InviteUserModal open={inviteOpen} onClose={() => setInviteOpen(false)} />
|
||||||
|
|
||||||
|
{/* Delete Confirmation Modal */}
|
||||||
|
{deleteTarget && (
|
||||||
|
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
|
||||||
|
<div className="bg-white dark:bg-gray-900 rounded-xl shadow-2xl w-full max-w-md mx-4">
|
||||||
|
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
|
||||||
|
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
|
||||||
|
Delete User
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
<div className="px-6 py-5 space-y-3">
|
||||||
|
<p className="text-sm text-gray-700 dark:text-gray-300">
|
||||||
|
Are you sure you want to permanently delete{" "}
|
||||||
|
<strong>{deleteTarget.userName}</strong>?
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-red-600 dark:text-red-400">
|
||||||
|
This will permanently remove their account, sessions, vacation records, and notifications.
|
||||||
|
Audit history entries will be retained but anonymised. This action cannot be undone.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setDeleteTarget(null)}
|
||||||
|
disabled={deleteMutation.isPending}
|
||||||
|
className="px-4 py-2 text-sm rounded-lg border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void deleteMutation.mutateAsync({ userId: deleteTarget.userId })}
|
||||||
|
disabled={deleteMutation.isPending}
|
||||||
|
className="px-4 py-2 text-sm rounded-lg bg-red-600 hover:bg-red-700 text-white font-medium transition-colors disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{deleteMutation.isPending ? "Deleting…" : "Delete permanently"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Create User Modal */}
|
{/* Create User Modal */}
|
||||||
{createState && (
|
{createState && (
|
||||||
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
|
<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
|
||||||
|
|||||||
@@ -23,10 +23,21 @@ function WidgetFallback() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function GridLayoutSkeleton() {
|
||||||
|
return (
|
||||||
|
<div className="grid grid-cols-2 gap-3 p-3">
|
||||||
|
{Array.from({ length: 4 }).map((_, i) => (
|
||||||
|
<div key={i} className="h-48 shimmer-skeleton rounded-2xl" />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Dynamic import — no WidthProvider (uses findDOMNode, broken in React 18 strict mode).
|
// Dynamic import — no WidthProvider (uses findDOMNode, broken in React 18 strict mode).
|
||||||
// We measure container width ourselves via ResizeObserver and pass it as a prop.
|
// We measure container width ourselves via ResizeObserver and pass it as a prop.
|
||||||
const GridLayout = dynamic(() => import("react-grid-layout").then((m) => m.Responsive), {
|
const GridLayout = dynamic(() => import("react-grid-layout").then((m) => m.Responsive), {
|
||||||
ssr: false,
|
ssr: false,
|
||||||
|
loading: () => <GridLayoutSkeleton />,
|
||||||
});
|
});
|
||||||
|
|
||||||
function renderWidget(
|
function renderWidget(
|
||||||
|
|||||||
@@ -68,7 +68,6 @@ const authConfig = {
|
|||||||
const user = await prisma.user.findUnique({ where: { email } });
|
const user = await prisma.user.findUnique({ where: { email } });
|
||||||
if (!user?.passwordHash) {
|
if (!user?.passwordHash) {
|
||||||
logger.warn({ email, reason: "user_not_found" }, "Failed login attempt");
|
logger.warn({ email, reason: "user_not_found" }, "Failed login attempt");
|
||||||
// Audit failed login (unknown user)
|
|
||||||
void createAuditEntry({
|
void createAuditEntry({
|
||||||
db: prisma,
|
db: prisma,
|
||||||
entityType: "Auth",
|
entityType: "Auth",
|
||||||
@@ -81,6 +80,21 @@ const authConfig = {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!user.isActive) {
|
||||||
|
logger.warn({ email, userId: user.id, reason: "account_deactivated" }, "Login blocked — account deactivated");
|
||||||
|
void createAuditEntry({
|
||||||
|
db: prisma,
|
||||||
|
entityType: "Auth",
|
||||||
|
entityId: user.id,
|
||||||
|
entityName: user.email,
|
||||||
|
action: "CREATE",
|
||||||
|
userId: user.id,
|
||||||
|
summary: "Login blocked — account deactivated",
|
||||||
|
source: "ui",
|
||||||
|
});
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
const isValid = await verify(user.passwordHash, password);
|
const isValid = await verify(user.passwordHash, password);
|
||||||
if (!isValid) {
|
if (!isValid) {
|
||||||
logger.warn({ email, reason: "invalid_password" }, "Failed login attempt");
|
logger.warn({ email, reason: "invalid_password" }, "Failed login attempt");
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
"test": "node ./scripts/run-from-workspace-root.mjs turbo run test:unit --concurrency=2",
|
"test": "node ./scripts/run-from-workspace-root.mjs turbo run test:unit --concurrency=2",
|
||||||
"test:unit": "node ./scripts/run-from-workspace-root.mjs turbo test:unit --concurrency=2",
|
"test:unit": "node ./scripts/run-from-workspace-root.mjs turbo test:unit --concurrency=2",
|
||||||
"test:e2e": "node ./scripts/run-from-workspace-root.mjs turbo test:e2e",
|
"test:e2e": "node ./scripts/run-from-workspace-root.mjs turbo test:e2e",
|
||||||
|
"test:e2e:email": "pnpm --filter @capakraken/web test:e2e:email",
|
||||||
"test:scripts": "node --test scripts/*.test.mjs",
|
"test:scripts": "node --test scripts/*.test.mjs",
|
||||||
"check:architecture": "node ./scripts/check-architecture-guardrails.mjs",
|
"check:architecture": "node ./scripts/check-architecture-guardrails.mjs",
|
||||||
"check:exports": "node ./scripts/check-workspace-exports.mjs",
|
"check:exports": "node ./scripts/check-workspace-exports.mjs",
|
||||||
@@ -24,6 +25,8 @@
|
|||||||
"db:generate": "node ./scripts/prisma-with-env.mjs generate",
|
"db:generate": "node ./scripts/prisma-with-env.mjs generate",
|
||||||
"db:validate": "node ./scripts/prisma-with-env.mjs validate",
|
"db:validate": "node ./scripts/prisma-with-env.mjs validate",
|
||||||
"db:seed": "node ./scripts/with-env.mjs pnpm --filter @capakraken/db db:seed",
|
"db:seed": "node ./scripts/with-env.mjs pnpm --filter @capakraken/db db:seed",
|
||||||
|
"db:seed:export": "node ./scripts/export-dev-seed.mjs",
|
||||||
|
"db:seed:import": "node ./scripts/import-dev-seed.mjs",
|
||||||
"db:studio": "node ./scripts/with-env.mjs pnpm --filter @capakraken/db db:studio",
|
"db:studio": "node ./scripts/with-env.mjs pnpm --filter @capakraken/db db:studio",
|
||||||
"db:reset:dispo": "pnpm --filter @capakraken/db db:reset:dispo",
|
"db:reset:dispo": "pnpm --filter @capakraken/db db:reset:dispo",
|
||||||
"db:import:dispo": "pnpm --filter @capakraken/db db:import:dispo",
|
"db:import:dispo": "pnpm --filter @capakraken/db db:import:dispo",
|
||||||
|
|||||||
@@ -24,8 +24,11 @@ describe("assistant user self-service dashboard layout tools", () => {
|
|||||||
user: {
|
user: {
|
||||||
findUnique: vi.fn().mockResolvedValue({
|
findUnique: vi.fn().mockResolvedValue({
|
||||||
dashboardLayout: {
|
dashboardLayout: {
|
||||||
|
version: 2,
|
||||||
|
gridCols: 12,
|
||||||
widgets: [
|
widgets: [
|
||||||
{ id: "peakTimes", position: { x: 0, y: 0, w: 4, h: 3 } },
|
// Valid widget type so normalization preserves it
|
||||||
|
{ id: "stat-1", type: "stat-cards", x: 0, y: 0, w: 12, h: 3 },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
updatedAt: new Date("2026-03-30T18:00:00.000Z"),
|
updatedAt: new Date("2026-03-30T18:00:00.000Z"),
|
||||||
@@ -40,14 +43,26 @@ describe("assistant user self-service dashboard layout tools", () => {
|
|||||||
where: { id: "user_1" },
|
where: { id: "user_1" },
|
||||||
select: { dashboardLayout: true, updatedAt: true },
|
select: { dashboardLayout: true, updatedAt: true },
|
||||||
});
|
});
|
||||||
expect(JSON.parse(result.content)).toEqual({
|
const parsed = JSON.parse(result.content) as { layout: { widgets: unknown[] } | null };
|
||||||
layout: {
|
expect(parsed.layout).not.toBeNull();
|
||||||
version: 2,
|
expect(parsed.layout?.widgets).toHaveLength(1);
|
||||||
gridCols: 12,
|
});
|
||||||
widgets: [],
|
|
||||||
|
it("returns null layout when stored widgets have no valid type (bug #27 guard)", async () => {
|
||||||
|
const db = {
|
||||||
|
user: {
|
||||||
|
findUnique: vi.fn().mockResolvedValue({
|
||||||
|
dashboardLayout: {
|
||||||
|
widgets: [{ id: "peakTimes", position: { x: 0, y: 0, w: 4, h: 3 } }],
|
||||||
|
},
|
||||||
|
updatedAt: new Date("2026-03-30T18:00:00.000Z"),
|
||||||
|
}),
|
||||||
},
|
},
|
||||||
updatedAt: "2026-03-30T18:00:00.000Z",
|
};
|
||||||
});
|
const ctx = createToolContext(db, SystemRole.ADMIN);
|
||||||
|
const result = await executeTool("get_dashboard_layout", "{}", ctx);
|
||||||
|
// Unknown widget type → normalises to empty → client gets null to use default layout
|
||||||
|
expect(JSON.parse(result.content)).toMatchObject({ layout: null });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("saves dashboard layout through the real user router path", async () => {
|
it("saves dashboard layout through the real user router path", async () => {
|
||||||
|
|||||||
@@ -0,0 +1,205 @@
|
|||||||
|
/**
|
||||||
|
* Unit tests for the invite tRPC router.
|
||||||
|
*
|
||||||
|
* Tests cover:
|
||||||
|
* - createInvite: token created, email sent
|
||||||
|
* - createInvite: duplicate active invite → CONFLICT
|
||||||
|
* - getInvite: valid token → returns email + role
|
||||||
|
* - getInvite: used token → BAD_REQUEST
|
||||||
|
* - getInvite: expired token → BAD_REQUEST
|
||||||
|
* - getInvite: unknown token → NOT_FOUND
|
||||||
|
* - acceptInvite: valid → user created, usedAt set
|
||||||
|
* - acceptInvite: used token → BAD_REQUEST
|
||||||
|
* - acceptInvite: expired token → BAD_REQUEST
|
||||||
|
* - revokeInvite: deletes the token
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { TRPCError } from "@trpc/server";
|
||||||
|
import { SystemRole } from "@capakraken/db";
|
||||||
|
|
||||||
|
// ── Mocks ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
vi.mock("../lib/email.js", () => ({ sendEmail: vi.fn().mockResolvedValue(true) }));
|
||||||
|
vi.mock("@node-rs/argon2", () => ({ hash: vi.fn().mockResolvedValue("$argon2id$hashed") }));
|
||||||
|
|
||||||
|
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const ADMIN_USER = { id: "admin_1" };
|
||||||
|
const FUTURE = new Date(Date.now() + 72 * 60 * 60 * 1000);
|
||||||
|
const PAST = new Date(Date.now() - 1000);
|
||||||
|
|
||||||
|
function makeInviteDb(overrides: Record<string, unknown> = {}) {
|
||||||
|
return {
|
||||||
|
findFirst: vi.fn().mockResolvedValue(null),
|
||||||
|
create: vi.fn().mockResolvedValue({}),
|
||||||
|
findUnique: vi.fn().mockResolvedValue(null),
|
||||||
|
findMany: vi.fn().mockResolvedValue([]),
|
||||||
|
update: vi.fn().mockResolvedValue({}),
|
||||||
|
delete: vi.fn().mockResolvedValue({}),
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeCtx(inviteDb: ReturnType<typeof makeInviteDb> = makeInviteDb()) {
|
||||||
|
return {
|
||||||
|
db: {
|
||||||
|
inviteToken: inviteDb,
|
||||||
|
user: { findUnique: vi.fn().mockResolvedValue(null), create: vi.fn().mockResolvedValue({}) },
|
||||||
|
} as never,
|
||||||
|
dbUser: { id: ADMIN_USER.id, systemRole: "ADMIN", permissionOverrides: null },
|
||||||
|
session: {
|
||||||
|
user: { id: ADMIN_USER.id, email: "admin@example.com" },
|
||||||
|
expires: "2099-01-01T00:00:00.000Z",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Import after mocks ───────────────────────────────────────────────────────
|
||||||
|
const { inviteRouter } = await import("../router/invite.js");
|
||||||
|
|
||||||
|
function caller(ctx: ReturnType<typeof makeCtx>) {
|
||||||
|
return inviteRouter.createCaller(ctx as never);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Tests ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe("createInvite", () => {
|
||||||
|
beforeEach(() => vi.clearAllMocks());
|
||||||
|
|
||||||
|
it("creates a token and sends an email", async () => {
|
||||||
|
const { sendEmail } = await import("../lib/email.js");
|
||||||
|
const ctx = makeCtx();
|
||||||
|
await caller(ctx).createInvite({ email: "alice@example.com", role: SystemRole.USER });
|
||||||
|
|
||||||
|
expect(ctx.db.inviteToken.create).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
data: expect.objectContaining({ email: "alice@example.com", role: SystemRole.USER }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(sendEmail).toHaveBeenCalledWith(expect.objectContaining({ to: "alice@example.com" }));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws CONFLICT when an active invite already exists", async () => {
|
||||||
|
const inviteDb = makeInviteDb({
|
||||||
|
findFirst: vi.fn().mockResolvedValue({ id: "existing" }),
|
||||||
|
});
|
||||||
|
const ctx = makeCtx(inviteDb);
|
||||||
|
await expect(
|
||||||
|
caller(ctx).createInvite({ email: "alice@example.com", role: SystemRole.USER }),
|
||||||
|
).rejects.toThrow(TRPCError);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getInvite", () => {
|
||||||
|
beforeEach(() => vi.clearAllMocks());
|
||||||
|
|
||||||
|
it("returns email and role for a valid unused token", async () => {
|
||||||
|
const inviteDb = makeInviteDb({
|
||||||
|
findUnique: vi.fn().mockResolvedValue({
|
||||||
|
email: "alice@example.com",
|
||||||
|
role: SystemRole.MANAGER,
|
||||||
|
expiresAt: FUTURE,
|
||||||
|
usedAt: null,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const result = await caller(makeCtx(inviteDb)).getInvite({ token: "abc" });
|
||||||
|
expect(result).toEqual({ email: "alice@example.com", role: SystemRole.MANAGER });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws NOT_FOUND for unknown token", async () => {
|
||||||
|
const ctx = makeCtx();
|
||||||
|
await expect(caller(ctx).getInvite({ token: "unknown" })).rejects.toThrow(TRPCError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws BAD_REQUEST for already-used token", async () => {
|
||||||
|
const inviteDb = makeInviteDb({
|
||||||
|
findUnique: vi.fn().mockResolvedValue({
|
||||||
|
email: "alice@example.com",
|
||||||
|
role: SystemRole.USER,
|
||||||
|
expiresAt: FUTURE,
|
||||||
|
usedAt: new Date(),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
await expect(caller(makeCtx(inviteDb)).getInvite({ token: "abc" })).rejects.toThrow(TRPCError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws BAD_REQUEST for expired token", async () => {
|
||||||
|
const inviteDb = makeInviteDb({
|
||||||
|
findUnique: vi.fn().mockResolvedValue({
|
||||||
|
email: "alice@example.com",
|
||||||
|
role: SystemRole.USER,
|
||||||
|
expiresAt: PAST,
|
||||||
|
usedAt: null,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
await expect(caller(makeCtx(inviteDb)).getInvite({ token: "abc" })).rejects.toThrow(TRPCError);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("acceptInvite", () => {
|
||||||
|
beforeEach(() => vi.clearAllMocks());
|
||||||
|
|
||||||
|
it("creates the user and marks token as used", async () => {
|
||||||
|
const inviteDb = makeInviteDb({
|
||||||
|
findUnique: vi.fn().mockResolvedValue({
|
||||||
|
id: "inv_1",
|
||||||
|
email: "alice@example.com",
|
||||||
|
role: SystemRole.USER,
|
||||||
|
expiresAt: FUTURE,
|
||||||
|
usedAt: null,
|
||||||
|
token: "validtoken",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const ctx = makeCtx(inviteDb);
|
||||||
|
const result = await caller(ctx).acceptInvite({ token: "validtoken", password: "SecurePass1!" });
|
||||||
|
|
||||||
|
expect(ctx.db.user.create).toHaveBeenCalled();
|
||||||
|
expect(inviteDb.update).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ data: { usedAt: expect.any(Date) } }),
|
||||||
|
);
|
||||||
|
expect(result).toEqual({ success: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws BAD_REQUEST for used token", async () => {
|
||||||
|
const inviteDb = makeInviteDb({
|
||||||
|
findUnique: vi.fn().mockResolvedValue({
|
||||||
|
email: "alice@example.com",
|
||||||
|
role: SystemRole.USER,
|
||||||
|
expiresAt: FUTURE,
|
||||||
|
usedAt: new Date(),
|
||||||
|
token: "usedtoken",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
await expect(
|
||||||
|
caller(makeCtx(inviteDb)).acceptInvite({ token: "usedtoken", password: "SecurePass1!" }),
|
||||||
|
).rejects.toThrow(TRPCError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws BAD_REQUEST for expired token", async () => {
|
||||||
|
const inviteDb = makeInviteDb({
|
||||||
|
findUnique: vi.fn().mockResolvedValue({
|
||||||
|
email: "alice@example.com",
|
||||||
|
role: SystemRole.USER,
|
||||||
|
expiresAt: PAST,
|
||||||
|
usedAt: null,
|
||||||
|
token: "expiredtoken",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
await expect(
|
||||||
|
caller(makeCtx(inviteDb)).acceptInvite({ token: "expiredtoken", password: "SecurePass1!" }),
|
||||||
|
).rejects.toThrow(TRPCError);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("revokeInvite", () => {
|
||||||
|
beforeEach(() => vi.clearAllMocks());
|
||||||
|
|
||||||
|
it("deletes the invite token", async () => {
|
||||||
|
const inviteDb = makeInviteDb();
|
||||||
|
const ctx = makeCtx(inviteDb);
|
||||||
|
const result = await caller(ctx).revokeInvite({ id: "inv_1" });
|
||||||
|
expect(inviteDb.delete).toHaveBeenCalledWith({ where: { id: "inv_1" } });
|
||||||
|
expect(result).toEqual({ success: true });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -134,7 +134,7 @@ describe("user-procedure-support", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("normalizes dashboard layouts before returning them", async () => {
|
it("returns null layout when stored widgets have no valid type (bug #27 guard)", async () => {
|
||||||
const findUnique = vi.fn().mockResolvedValue({
|
const findUnique = vi.fn().mockResolvedValue({
|
||||||
dashboardLayout: {
|
dashboardLayout: {
|
||||||
widgets: [{ id: "peakTimes", position: { x: 0, y: 0, w: 4, h: 3 } }],
|
widgets: [{ id: "peakTimes", position: { x: 0, y: 0, w: 4, h: 3 } }],
|
||||||
@@ -146,8 +146,9 @@ describe("user-procedure-support", () => {
|
|||||||
user: { findUnique },
|
user: { findUnique },
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
// Widgets with unknown types normalise to empty → return null so client uses default
|
||||||
expect(result).toEqual({
|
expect(result).toEqual({
|
||||||
layout: { version: 2, gridCols: 12, widgets: [] },
|
layout: null,
|
||||||
updatedAt: new Date("2026-03-30T18:00:00.000Z"),
|
updatedAt: new Date("2026-03-30T18:00:00.000Z"),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -760,7 +760,7 @@ describe("user profile and TOTP self-service", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("user dashboard and favorites", () => {
|
describe("user dashboard and favorites", () => {
|
||||||
it("falls back to the normalized default dashboard layout when stored data is invalid", async () => {
|
it("returns null layout when stored data has no valid widget types (bug #27 guard)", async () => {
|
||||||
const findUnique = vi.fn().mockResolvedValue({
|
const findUnique = vi.fn().mockResolvedValue({
|
||||||
dashboardLayout: {
|
dashboardLayout: {
|
||||||
widgets: [
|
widgets: [
|
||||||
@@ -781,12 +781,9 @@ describe("user dashboard and favorites", () => {
|
|||||||
where: { id: "user_admin" },
|
where: { id: "user_admin" },
|
||||||
select: { dashboardLayout: true, updatedAt: true },
|
select: { dashboardLayout: true, updatedAt: true },
|
||||||
});
|
});
|
||||||
|
// Widgets with unknown types are dropped → empty → client uses default layout
|
||||||
expect(result).toEqual({
|
expect(result).toEqual({
|
||||||
layout: {
|
layout: null,
|
||||||
version: 2,
|
|
||||||
gridCols: 12,
|
|
||||||
widgets: [],
|
|
||||||
},
|
|
||||||
updatedAt: new Date("2026-03-30T18:00:00.000Z"),
|
updatedAt: new Date("2026-03-30T18:00:00.000Z"),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
/**
|
||||||
|
* Unit tests for getDashboardLayout — bug #27 regression guard.
|
||||||
|
*
|
||||||
|
* Verifies that getDashboardLayout returns null (not an empty layout) when the
|
||||||
|
* stored dashboardLayout is an empty object or contains only unknown widget
|
||||||
|
* types. This allows the client to fall back to the default stat-cards layout.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
vi.mock("../lib/audit.js", () => ({ createAuditEntry: vi.fn() }));
|
||||||
|
vi.mock("../lib/system-settings-runtime.js", () => ({ resolveSystemSettingsRuntime: vi.fn() }));
|
||||||
|
|
||||||
|
const { getDashboardLayout } = await import(
|
||||||
|
"../router/user-self-service-procedure-support.js"
|
||||||
|
);
|
||||||
|
|
||||||
|
function makeCtx(dashboardLayout: unknown) {
|
||||||
|
return {
|
||||||
|
db: {
|
||||||
|
user: {
|
||||||
|
findUnique: vi.fn().mockResolvedValue(
|
||||||
|
dashboardLayout !== undefined ? { dashboardLayout, updatedAt: new Date() } : null,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
} as never,
|
||||||
|
dbUser: { id: "user_1" },
|
||||||
|
session: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("getDashboardLayout — #27 regression", () => {
|
||||||
|
it("returns null when dashboardLayout is null (new user)", async () => {
|
||||||
|
const ctx = makeCtx(null);
|
||||||
|
const result = await getDashboardLayout(ctx as never);
|
||||||
|
expect(result.layout).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null when dashboardLayout is an empty object", async () => {
|
||||||
|
const ctx = makeCtx({});
|
||||||
|
const result = await getDashboardLayout(ctx as never);
|
||||||
|
expect(result.layout).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null when dashboardLayout has no valid widget types", async () => {
|
||||||
|
const ctx = makeCtx({
|
||||||
|
version: 1,
|
||||||
|
widgets: [{ type: "old-unknown-widget-type", id: "w1", x: 0, y: 0, w: 4, h: 3 }],
|
||||||
|
});
|
||||||
|
const result = await getDashboardLayout(ctx as never);
|
||||||
|
expect(result.layout).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns null when dashboardLayout has an empty widgets array", async () => {
|
||||||
|
const ctx = makeCtx({ version: 2, gridCols: 12, widgets: [] });
|
||||||
|
const result = await getDashboardLayout(ctx as never);
|
||||||
|
expect(result.layout).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns the layout when it contains at least one valid widget", async () => {
|
||||||
|
const ctx = makeCtx({
|
||||||
|
version: 2,
|
||||||
|
gridCols: 12,
|
||||||
|
widgets: [{ type: "stat-cards", id: "w1", x: 0, y: 0, w: 12, h: 3 }],
|
||||||
|
});
|
||||||
|
const result = await getDashboardLayout(ctx as never);
|
||||||
|
expect(result.layout).not.toBeNull();
|
||||||
|
expect(result.layout?.widgets).toHaveLength(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -78,6 +78,7 @@ export async function listUsers(ctx: UserReadContext) {
|
|||||||
lastActiveAt: true,
|
lastActiveAt: true,
|
||||||
permissionOverrides: true,
|
permissionOverrides: true,
|
||||||
totpEnabled: true,
|
totpEnabled: true,
|
||||||
|
isActive: true,
|
||||||
},
|
},
|
||||||
orderBy: { name: "asc" },
|
orderBy: { name: "asc" },
|
||||||
});
|
});
|
||||||
@@ -467,6 +468,120 @@ export async function getEffectiveUserPermissions(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function deactivateUser(
|
||||||
|
ctx: UserMutationContext,
|
||||||
|
input: z.infer<typeof UserIdInputSchema>,
|
||||||
|
) {
|
||||||
|
if (ctx.dbUser!.id === input.userId) {
|
||||||
|
throw new TRPCError({ code: "BAD_REQUEST", message: "You cannot deactivate your own account." });
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await findUniqueOrThrow(
|
||||||
|
ctx.db.user.findUnique({
|
||||||
|
where: { id: input.userId },
|
||||||
|
select: { id: true, name: true, email: true, isActive: true },
|
||||||
|
}),
|
||||||
|
"User",
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!user.isActive) {
|
||||||
|
throw new TRPCError({ code: "BAD_REQUEST", message: "User is already inactive." });
|
||||||
|
}
|
||||||
|
|
||||||
|
await ctx.db.user.update({ where: { id: input.userId }, data: { isActive: false } });
|
||||||
|
|
||||||
|
// Invalidate all existing sessions so the user is logged out immediately
|
||||||
|
await ctx.db.activeSession.deleteMany({ where: { userId: input.userId } });
|
||||||
|
|
||||||
|
void createAuditEntry({
|
||||||
|
db: ctx.db,
|
||||||
|
entityType: "User",
|
||||||
|
entityId: user.id,
|
||||||
|
entityName: `${user.name} (${user.email})`,
|
||||||
|
action: "UPDATE",
|
||||||
|
...withAuditUser(ctx.dbUser?.id),
|
||||||
|
source: "ui",
|
||||||
|
summary: "User deactivated",
|
||||||
|
});
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function reactivateUser(
|
||||||
|
ctx: UserMutationContext,
|
||||||
|
input: z.infer<typeof UserIdInputSchema>,
|
||||||
|
) {
|
||||||
|
const user = await findUniqueOrThrow(
|
||||||
|
ctx.db.user.findUnique({
|
||||||
|
where: { id: input.userId },
|
||||||
|
select: { id: true, name: true, email: true, isActive: true },
|
||||||
|
}),
|
||||||
|
"User",
|
||||||
|
);
|
||||||
|
|
||||||
|
if (user.isActive) {
|
||||||
|
throw new TRPCError({ code: "BAD_REQUEST", message: "User is already active." });
|
||||||
|
}
|
||||||
|
|
||||||
|
await ctx.db.user.update({ where: { id: input.userId }, data: { isActive: true } });
|
||||||
|
|
||||||
|
void createAuditEntry({
|
||||||
|
db: ctx.db,
|
||||||
|
entityType: "User",
|
||||||
|
entityId: user.id,
|
||||||
|
entityName: `${user.name} (${user.email})`,
|
||||||
|
action: "UPDATE",
|
||||||
|
...withAuditUser(ctx.dbUser?.id),
|
||||||
|
source: "ui",
|
||||||
|
summary: "User reactivated",
|
||||||
|
});
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteUser(
|
||||||
|
ctx: UserMutationContext,
|
||||||
|
input: z.infer<typeof UserIdInputSchema>,
|
||||||
|
) {
|
||||||
|
if (ctx.dbUser!.id === input.userId) {
|
||||||
|
throw new TRPCError({ code: "BAD_REQUEST", message: "You cannot delete your own account." });
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await findUniqueOrThrow(
|
||||||
|
ctx.db.user.findUnique({
|
||||||
|
where: { id: input.userId },
|
||||||
|
select: { id: true, name: true, email: true },
|
||||||
|
}),
|
||||||
|
"User",
|
||||||
|
);
|
||||||
|
|
||||||
|
// These tables have required (non-nullable) FKs to User — must be removed first
|
||||||
|
await ctx.db.vacation.deleteMany({ where: { requestedById: input.userId } });
|
||||||
|
await ctx.db.notificationBroadcast.deleteMany({ where: { senderId: input.userId } });
|
||||||
|
await ctx.db.inviteToken.deleteMany({ where: { createdById: input.userId } });
|
||||||
|
|
||||||
|
// Unlink resource (nullable FK — belt-and-suspenders)
|
||||||
|
await ctx.db.resource.updateMany({ where: { userId: input.userId }, data: { userId: null } });
|
||||||
|
|
||||||
|
void createAuditEntry({
|
||||||
|
db: ctx.db,
|
||||||
|
entityType: "User",
|
||||||
|
entityId: user.id,
|
||||||
|
entityName: `${user.name} (${user.email})`,
|
||||||
|
action: "DELETE",
|
||||||
|
...withAuditUser(ctx.dbUser?.id),
|
||||||
|
source: "ui",
|
||||||
|
summary: "User account permanently deleted",
|
||||||
|
});
|
||||||
|
|
||||||
|
// Delete user — Prisma cascade covers: Account, Session, ActiveSession,
|
||||||
|
// Notification, ReportTemplate, AssistantApproval, Comment.
|
||||||
|
// Nullable FKs (AuditLog.userId, etc.) become NULL via Prisma SET NULL default.
|
||||||
|
await ctx.db.user.delete({ where: { id: input.userId } });
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
export async function disableTotp(
|
export async function disableTotp(
|
||||||
ctx: UserMutationContext,
|
ctx: UserMutationContext,
|
||||||
input: z.infer<typeof UserIdInputSchema>,
|
input: z.infer<typeof UserIdInputSchema>,
|
||||||
|
|||||||
@@ -61,8 +61,11 @@ export async function getDashboardLayout(ctx: UserSelfServiceContext) {
|
|||||||
select: { dashboardLayout: true, updatedAt: true },
|
select: { dashboardLayout: true, updatedAt: true },
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const normalized = user?.dashboardLayout
|
||||||
|
? normalizeDashboardLayout(user.dashboardLayout)
|
||||||
|
: null;
|
||||||
return {
|
return {
|
||||||
layout: user?.dashboardLayout ? normalizeDashboardLayout(user.dashboardLayout) : null,
|
layout: normalized?.widgets.length ? normalized : null,
|
||||||
updatedAt: user?.updatedAt ?? null,
|
updatedAt: user?.updatedAt ?? null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ import {
|
|||||||
countActiveUsers,
|
countActiveUsers,
|
||||||
CreateUserInputSchema,
|
CreateUserInputSchema,
|
||||||
createUser,
|
createUser,
|
||||||
|
deactivateUser,
|
||||||
|
reactivateUser,
|
||||||
|
deleteUser,
|
||||||
disableTotp,
|
disableTotp,
|
||||||
getEffectiveUserPermissions,
|
getEffectiveUserPermissions,
|
||||||
LinkUserResourceInputSchema,
|
LinkUserResourceInputSchema,
|
||||||
@@ -116,6 +119,18 @@ export const userRouter = createTRPCRouter({
|
|||||||
.input(VerifyAndEnableTotpInputSchema)
|
.input(VerifyAndEnableTotpInputSchema)
|
||||||
.mutation(({ ctx, input }) => verifyAndEnableTotpSelfService(ctx, input)),
|
.mutation(({ ctx, input }) => verifyAndEnableTotpSelfService(ctx, input)),
|
||||||
|
|
||||||
|
deactivate: adminProcedure
|
||||||
|
.input(UserIdInputSchema)
|
||||||
|
.mutation(({ ctx, input }) => deactivateUser(ctx, input)),
|
||||||
|
|
||||||
|
reactivate: adminProcedure
|
||||||
|
.input(UserIdInputSchema)
|
||||||
|
.mutation(({ ctx, input }) => reactivateUser(ctx, input)),
|
||||||
|
|
||||||
|
delete: adminProcedure
|
||||||
|
.input(UserIdInputSchema)
|
||||||
|
.mutation(({ ctx, input }) => deleteUser(ctx, input)),
|
||||||
|
|
||||||
/** Admin override: disable TOTP for a specific user. */
|
/** Admin override: disable TOTP for a specific user. */
|
||||||
disableTotp: adminProcedure
|
disableTotp: adminProcedure
|
||||||
.input(UserIdInputSchema)
|
.input(UserIdInputSchema)
|
||||||
|
|||||||
@@ -764,5 +764,5 @@ describe("dispo import", () => {
|
|||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
});
|
}, 15_000);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- Add isActive flag to users for soft deactivation.
|
||||||
|
-- Active sessions are purged on deactivation so existing JWTs stop working
|
||||||
|
-- on the next auth check.
|
||||||
|
|
||||||
|
ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "isActive" BOOLEAN NOT NULL DEFAULT TRUE;
|
||||||
|
|
||||||
|
-- Index for quick admin queries (active vs. inactive users)
|
||||||
|
CREATE INDEX IF NOT EXISTS "users_isActive_idx" ON "users"("isActive");
|
||||||
@@ -187,6 +187,7 @@ model User {
|
|||||||
lastActiveAt DateTime?
|
lastActiveAt DateTime?
|
||||||
totpSecret String? // Base32 TOTP secret
|
totpSecret String? // Base32 TOTP secret
|
||||||
totpEnabled Boolean @default(false)
|
totpEnabled Boolean @default(false)
|
||||||
|
isActive Boolean @default(true)
|
||||||
|
|
||||||
accounts Account[]
|
accounts Account[]
|
||||||
sessions Session[]
|
sessions Session[]
|
||||||
|
|||||||
@@ -1,175 +1,94 @@
|
|||||||
# CapaKraken — Umsetzungsplan
|
# Plan: App Base URL — configurable via env, no localhost fallback in production
|
||||||
|
|
||||||
Gitea-Repo: `https://gitea.hartmut-noerenberg.com/Hartmut/plANARCHY`
|
Stand: 2026-04-02
|
||||||
Stand: 2026-04-02 | Issues: #38–#42 (MFA Post-Activation Bugs)
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Plan: MFA Post-Activation Bugs #38–#42
|
## Anforderungsanalyse
|
||||||
|
|
||||||
### Anforderungsanalyse
|
Email-Links (Invite, Password Reset) werden aktuell mit `process.env["NEXTAUTH_URL"] ?? "http://localhost:3100"` gebaut. Das ist korrekt, wenn `NEXTAUTH_URL` gesetzt ist. Das Problem: wenn der Wert fehlt oder leer ist, enthalten Produktions-E-Mails localhost-Links. Außerdem gibt es keine `.env.example`, die dokumentiert, welche Variablen gesetzt werden müssen.
|
||||||
|
|
||||||
Nach der Implementierung der MFA-Tickets (#28–#35) wurden 5 Folgefehler identifiziert, die den Login-Flow für MFA-Nutzer vollständig blockieren. Betroffen sind `apps/web` und `packages/api`. Kein Prisma-Schema-Change nötig.
|
**Was gebaut wird:**
|
||||||
|
1. Zentrale `getAppBaseUrl()` Funktion in `packages/api` — liest `NEXTAUTH_URL`, wirft in production einen Fehler wenn nicht gesetzt, fällt in dev auf localhost zurück.
|
||||||
|
2. Beide Router (`invite.ts`, `auth.ts`) verwenden diese Funktion statt duplizierter Inline-Logik.
|
||||||
|
3. `.env.example` mit allen benötigten Variablen.
|
||||||
|
4. Health-Route zeigt ob `NEXTAUTH_URL` konfiguriert ist.
|
||||||
|
|
||||||
**Kritischer Pfad:** #41 muss zuerst rein — solange Auth.js v5 alle `throw`s aus `authorize()` als `CallbackRouteError` wrappt, ist der MFA-Login für jeden Nutzer gebrochen. Alle anderen Bugs sind unabhängig davon lösbar, aber #41 ist Voraussetzung für testbare Akzeptanzkriterien von #38 und #39.
|
**Betroffene Pakete:** `packages/api`, `apps/web`
|
||||||
|
|
||||||
|
**Audit-Ergebnis — intentionale localhost-Referenzen (NICHT ändern):**
|
||||||
|
- `apps/web/e2e/dev-system/` — alle E2E-Helfer, Specs, global-setup.ts
|
||||||
|
- `apps/web/playwright.dev.config.ts`
|
||||||
|
- `apps/web/src/middleware.test.ts`
|
||||||
|
- `.github/workflows/deploy-test.yml`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Betroffene Pakete & Dateien
|
## Betroffene Pakete & Dateien
|
||||||
|
|
||||||
| Paket | Datei | Art |
|
| Paket | Datei | Art |
|
||||||
|-------|-------|-----|
|
|-------|-------|-----|
|
||||||
| `apps/web` | `src/server/auth.ts` | edit — Custom `CredentialsSignin`-Subklassen |
|
| `packages/api` | `src/lib/app-base-url.ts` | create |
|
||||||
| `apps/web` | `src/app/auth/signin/page.tsx` | edit — Error-Code-Prüfung anpassen |
|
| `packages/api` | `src/router/invite.ts` | edit |
|
||||||
| `apps/web` | `src/app/(app)/layout.tsx` | edit — server-seitiges `showMfaPrompt` entfernen |
|
| `packages/api` | `src/router/auth.ts` | edit |
|
||||||
| `apps/web` | `src/components/security/MfaPromptBanner.tsx` | edit — client-seitig via tRPC |
|
| `apps/web` | `src/app/api/health/route.ts` | edit |
|
||||||
| `apps/web` | `src/app/api/perf/route.test.ts` | edit — neuer Test für Auth-Fehler-Signale |
|
| root | `.env.example` | create |
|
||||||
| `apps/web` | `docker-compose.yml` | edit — `NEXTAUTH_URL` required machen |
|
|
||||||
| `packages/api` | `src/router/user.ts` | edit — `resetUserPassword` Admin-Mutation |
|
|
||||||
| `packages/api` | `src/router/user-procedure-support.ts` | edit — `resetUserPassword`-Support-Fn |
|
|
||||||
| `packages/api` | `src/__tests__/reset-password.test.ts` | create — Unit-Tests |
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Task-Liste
|
## Task-Liste
|
||||||
|
|
||||||
#### Block A — #41: Auth.js v5 MFA-Signal-Fix (KRITISCH)
|
- [ ] **Task 1:** `getAppBaseUrl()` in `packages/api/src/lib/app-base-url.ts` erstellen.
|
||||||
|
- Liest `process.env["NEXTAUTH_URL"]` (trimmed).
|
||||||
|
- Wenn gesetzt und nicht leer → gibt den Wert zurück (trailing slash entfernen).
|
||||||
|
- Wenn leer/fehlend **und** `NODE_ENV === "production"` → wirft `Error("NEXTAUTH_URL must be set in production — email links will be broken")`.
|
||||||
|
- Sonst (development/test) → gibt `"http://localhost:3100"` zurück und loggt einmalig eine Warnung.
|
||||||
|
- → Datei: `packages/api/src/lib/app-base-url.ts`
|
||||||
|
|
||||||
- [ ] **Task A1:** Custom Error-Klassen in `apps/web/src/server/auth.ts` definieren.
|
- [ ] **Task 2:** `invite.ts` auf `getAppBaseUrl()` umstellen.
|
||||||
Importiere `CredentialsSignin` aus `"next-auth"` und erstelle 3 Subklassen direkt in der Datei:
|
- Ersetze `const baseUrl = process.env["NEXTAUTH_URL"] ?? "http://localhost:3100";` durch `const baseUrl = getAppBaseUrl();`
|
||||||
```typescript
|
- → Datei: `packages/api/src/router/invite.ts` Zeile 53
|
||||||
class MfaRequiredError extends CredentialsSignin {
|
|
||||||
code = "MFA_REQUIRED" as const;
|
|
||||||
}
|
|
||||||
class MfaRequiredSetupError extends CredentialsSignin {
|
|
||||||
code = "MFA_REQUIRED_SETUP" as const;
|
|
||||||
}
|
|
||||||
class InvalidTotpError extends CredentialsSignin {
|
|
||||||
code = "INVALID_TOTP" as const;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
Ersetze alle 3 `throw new Error(...)` in `authorize()`:
|
|
||||||
- `throw new Error("MFA_REQUIRED:...")` → `throw new MfaRequiredError()`
|
|
||||||
- `throw new Error("MFA_REQUIRED_SETUP:...")` → `throw new MfaRequiredSetupError()`
|
|
||||||
- `throw new Error("INVALID_TOTP")` → `throw new InvalidTotpError()`
|
|
||||||
- `throw new Error("Too many login attempts...")` → bleibt als normaler `throw` (nicht durch MFA verursacht, `return null` wäre die sauberere Variante — aber Audit-Eintrag muss davor kommen)
|
|
||||||
→ Datei: `apps/web/src/server/auth.ts`
|
|
||||||
|
|
||||||
- [ ] **Task A2:** Signin-Page: Error-Code-Prüfung anpassen.
|
- [ ] **Task 3:** `auth.ts` auf `getAppBaseUrl()` umstellen.
|
||||||
In Auth.js v5 beta mit `redirect: false` liefert `signIn()` bei `CredentialsSignin`-Subklassen:
|
- Ersetze `const baseUrl = process.env["NEXTAUTH_URL"] ?? "http://localhost:3100";` durch `const baseUrl = getAppBaseUrl();`
|
||||||
`result.error = "<code>"` (also `"MFA_REQUIRED"`, `"MFA_REQUIRED_SETUP"`, `"INVALID_TOTP"`) **oder** `result.error = "CredentialsSignin"` + `result.code = "<code>"` — je nach beta-Version.
|
- → Datei: `packages/api/src/router/auth.ts` Zeile 50
|
||||||
**Strategie für beta.25:** Exakte string-Gleichheit statt `.includes()` verwenden:
|
|
||||||
```typescript
|
|
||||||
if (result.error === "MFA_REQUIRED_SETUP" || result.code === "MFA_REQUIRED_SETUP") { ... }
|
|
||||||
if (result.error === "MFA_REQUIRED" || result.code === "MFA_REQUIRED") { ... }
|
|
||||||
if (result.error === "INVALID_TOTP" || result.code === "INVALID_TOTP") { ... }
|
|
||||||
```
|
|
||||||
Rate-Limit-Fall: `return null` statt `throw` macht in `authorize()` aus `.includes("Too many")`-Prüfung ein separates Problem — hier stattdessen im `!isValid`-Pfad bleiben und für Rate-Limit `result.error` = `"CredentialsSignin"` annehmen (der Nutzer sieht keinen spezifischen Text mehr, was ok ist — Rate-Limit-Feedback ist absichtlich vage).
|
|
||||||
→ Datei: `apps/web/src/app/auth/signin/page.tsx`
|
|
||||||
|
|
||||||
- [ ] **Task A3:** Unit-Test für Auth-Fehler-Signale.
|
- [ ] **Task 4:** `.env.example` anlegen mit allen required und optionalen Variablen.
|
||||||
Teste `authorize()` direkt mit einem gemockten prisma: MFA-aktivierter User ohne `totp`-Feld → wirft `MfaRequiredError`. Falsches TOTP → wirft `InvalidTotpError`. Richtiger TOTP-Code → gibt User-Objekt zurück.
|
- Sections: App, Auth, Database, Redis, SMTP, AI, Dev-Tools (pgAdmin)
|
||||||
→ Datei: `apps/web/src/server/auth.test.ts` (neu)
|
- Jede Variable: Kommentar (required/optional, Beschreibung), Beispielwert.
|
||||||
|
- `NEXTAUTH_URL` als REQUIRED mit Hinweis "must be the public URL (e.g. https://capakraken.example.com) — used in email links; do not use localhost in production"
|
||||||
|
- → Datei: `.env.example`
|
||||||
|
|
||||||
|
- [ ] **Task 5:** Health-Route um `baseUrl`-Check erweitern.
|
||||||
|
- Liest `NEXTAUTH_URL` direkt (kein `getAppBaseUrl()` — soll nie werfen, nur reporten).
|
||||||
|
- Fügt `"baseUrl": { "configured": bool, "isLocalhost": bool }` zum JSON-Response hinzu.
|
||||||
|
- `configured: false` wenn Var fehlt/leer; `isLocalhost: true` wenn Wert mit `http://localhost` beginnt.
|
||||||
|
- → Datei: `apps/web/src/app/api/health/route.ts`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
#### Block B — #38: MFA-Banner als Client-Component
|
## Abhängigkeiten
|
||||||
|
|
||||||
- [ ] **Task B1:** `MfaPromptBanner.tsx` zu vollständig client-seitigem Component umbauen.
|
- Task 2 **und** Task 3 benötigen Task 1 (Funktion muss existieren).
|
||||||
Statt `userId`-Prop: eigene tRPC-Query `trpc.user.getMfaStatus.useQuery()`. Der Banner rendert sich selbst unsichtbar (`return null`) solange der Query lädt oder `totpEnabled === true`. Kein `userId`-Prop mehr nötig.
|
- Task 2 und Task 3 können **parallel** ausgeführt werden (unterschiedliche Dateien).
|
||||||
→ Datei: `apps/web/src/components/security/MfaPromptBanner.tsx`
|
- Task 4 und Task 5 sind **unabhängig** von allen anderen und können parallel ausgeführt werden.
|
||||||
|
|
||||||
- [ ] **Task B2:** `(app)/layout.tsx` bereinigen.
|
|
||||||
Den `prisma.user.findUnique`-Call für `showMfaPrompt` entfernen. Den `prisma`-Import entfernen. `MfaPromptBanner` ohne Props rendern — immer eingebunden für `MFA_PROMPT_ROLES` (oder direkt bedingungslos, da der Banner selbst den Status kennt).
|
|
||||||
→ Datei: `apps/web/src/app/(app)/layout.tsx`
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
#### Block C — #39: Dashboard-Widgets nach MFA-Aktivierung (Investigation)
|
## Akzeptanzkriterien
|
||||||
|
|
||||||
- [ ] **Task C1:** Nach #41-Fix: Login mit MFA-Nutzer testen und prüfen, ob Dashboard-Widgets laden.
|
|
||||||
Hypothese: Die Widgets schlugen fehl weil die Session nach MFA-Aktivierung als ungültig galt (der active-session-Check in `auth.ts` könnte nach einem tRPC-Call eine veraltete Session sehen). Nach #41-Fix und erneutem Login sollte die Session gültig sein.
|
|
||||||
Falls das Problem dann noch besteht: Untersuche ob `enableTotp` die laufende Session invalidiert (fehlende Session-Neuausstellung nach MFA-Aktivierung).
|
|
||||||
→ Kein Code-Change bis C1-Prüfung abgeschlossen. Falls nötig: `user.enableTotp` gibt nach Erfolg `{ requireRelogin: true }` zurück und das Frontend leitet auf `/auth/signin` weiter.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
#### Block D — #40: NEXTAUTH_URL Required
|
|
||||||
|
|
||||||
- [ ] **Task D1:** `NEXTAUTH_URL`-Fallback in `docker-compose.yml` entfernen.
|
|
||||||
```yaml
|
|
||||||
# vorher:
|
|
||||||
NEXTAUTH_URL: ${NEXTAUTH_URL:-http://localhost:3100}
|
|
||||||
# nachher:
|
|
||||||
NEXTAUTH_URL: ${NEXTAUTH_URL:?NEXTAUTH_URL must be set in .env}
|
|
||||||
```
|
|
||||||
→ Datei: `docker-compose.yml`
|
|
||||||
|
|
||||||
- [ ] **Task D2:** `.env.example` aktualisieren — `NEXTAUTH_URL=https://your-domain.com` dokumentieren.
|
|
||||||
→ Datei: `.env.example` (falls vorhanden, sonst erstellen)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
#### Block E — #42: Admin-Password-Reset-Mutation
|
|
||||||
|
|
||||||
- [ ] **Task E1:** `resetUserPassword`-Funktion in `user-procedure-support.ts` hinzufügen.
|
|
||||||
Die vorhandene `setUserPassword` setzt das Passwort beim User-Create. Eine neue Funktion `resetUserPassword(ctx, input: { userId, newPassword })` hasht `newPassword` mit argon2id und schreibt `passwordHash`. Nur erreichbar via `adminProcedure`.
|
|
||||||
→ Datei: `packages/api/src/router/user-procedure-support.ts`
|
|
||||||
|
|
||||||
- [ ] **Task E2:** Mutation in `user.ts` registrieren.
|
|
||||||
```typescript
|
|
||||||
resetPassword: adminProcedure
|
|
||||||
.input(z.object({ userId: z.string(), newPassword: z.string().min(8) }))
|
|
||||||
.mutation(({ ctx, input }) => resetUserPassword(ctx, input)),
|
|
||||||
```
|
|
||||||
→ Datei: `packages/api/src/router/user.ts`
|
|
||||||
|
|
||||||
- [ ] **Task E3:** Unit-Test für `resetUserPassword`.
|
|
||||||
Happy path: Mutation updated `passwordHash`. Negative cases: non-admin schlägt fehl, leeres Passwort schlägt fehl.
|
|
||||||
→ Datei: `packages/api/src/__tests__/reset-password.test.ts`
|
|
||||||
|
|
||||||
- [ ] **Task E4:** Admin-UI — Password-Reset-Button in der User-Verwaltung.
|
|
||||||
Im Admin-Bereich (vermutlich `apps/web/src/app/(app)/admin/users/`) Button "Reset Password" mit einem Modal, das ein neues Passwort verlangt (min. 8 Zeichen). Kein separates Ticket nötig — gehört zu #42.
|
|
||||||
→ Datei: Admin-User-List-Page (Pfad nach aktuellem Stand ermitteln)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Abhängigkeiten
|
|
||||||
|
|
||||||
```
|
|
||||||
A1 → A2 → A3 (Sequential: A2 braucht den finalen Code aus A1)
|
|
||||||
B1 → B2 (Sequential: B2 entfernt was B1 ersetzt)
|
|
||||||
A3, B2, D1, E3 (Können parallel laufen, sobald A1 fertig)
|
|
||||||
C1 nach A1+A2 (Test)
|
|
||||||
E4 nach E1+E2
|
|
||||||
```
|
|
||||||
|
|
||||||
**Reihenfolge:**
|
|
||||||
1. A1 (kritisch, zuerst — entsperrt alle anderen)
|
|
||||||
2. A2 (direkt danach, am selben Batch)
|
|
||||||
3. Parallel: B1+B2, D1+D2, E1+E2
|
|
||||||
4. A3, E3, E4
|
|
||||||
5. C1 (manuelle Verifikation nach Deploy)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Akzeptanzkriterien
|
|
||||||
|
|
||||||
- [ ] `pnpm test:unit` läuft grün
|
- [ ] `pnpm test:unit` läuft grün
|
||||||
- [ ] `pnpm --filter @capakraken/web exec tsc --noEmit` — keine neuen Fehler
|
- [ ] `pnpm --filter @capakraken/web exec tsc --noEmit` — keine neuen TS-Errors
|
||||||
- [ ] Login mit `hn@hartmut-noerenberg.com` + `Admin12345!` zeigt TOTP-Eingabe (nicht "Invalid email or password")
|
- [ ] `pnpm test:e2e:email` — alle 3 E2E-Tests bestehen weiterhin
|
||||||
- [ ] Korrekter TOTP-Code → erfolgreicher Login
|
- [ ] Wenn `NEXTAUTH_URL=https://capakraken.hartmut-noerenberg.com`: E-Mail-Links enthalten diese Domain
|
||||||
- [ ] Nach MFA-Aktivierung via UI verschwindet der Banner sofort ohne Reload
|
- [ ] Wenn `NEXTAUTH_URL` fehlt und `NODE_ENV=production`: `createInvite` / `requestPasswordReset` werfen einen klaren Fehler beim Link-Bau
|
||||||
- [ ] Nach Logout von `capakraken.hartmut-noerenberg.com` landet man auf der Login-Seite der gleichen Domain
|
- [ ] `GET /api/health` liefert `baseUrl.configured: true/false` und `baseUrl.isLocalhost: bool`
|
||||||
- [ ] `docker compose up` ohne `NEXTAUTH_URL` schlägt mit lesebarer Fehlermeldung fehl
|
- [ ] `.env.example` existiert und dokumentiert alle Pflichtfelder
|
||||||
- [ ] Admin kann Passwort eines anderen Users über die UI zurücksetzen
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Risiken & offene Fragen
|
## Risiken & offene Fragen
|
||||||
|
|
||||||
1. **Auth.js beta.25 vs beta.30 `result.error` vs `result.code`:** Die genaue Rückgabestruktur von `signIn({ redirect: false })` variiert zwischen beta-Versionen. Task A2 muss nach A1 kurz manuell verifiziert werden — ggf. beide Felder (`result.error` UND `result.code`) prüfen.
|
- **Unit-Tests für Router:** Bestehende Tests für `invite.ts` und `auth.ts` müssen `NEXTAUTH_URL` in der Testumgebung gesetzt haben (oder `NODE_ENV=test` → Dev-Fallback greift). Vorhandene Tests prüfen, ob `process.env["NEXTAUTH_URL"]` dort gesetzt wird.
|
||||||
|
- **`docker-compose.prod.yml`** delegiert ENV-Vars an `.env.production` (gitignored). Das `.env.example` deckt ab, was dort stehen muss — kein Code-Change nötig.
|
||||||
2. **#39 Dashboard-Bug:** Ursache noch unklar. Nach #41-Fix ist zu prüfen, ob der Fehler von selbst verschwindet (Session-Neustart beim Re-Login). Falls nicht: Session-Re-Issue nach `enableTotp` nötig (Breaking Change in der MFA-Setup-UX).
|
- **Trailing Slash:** NEXTAUTH_URL könnte mit oder ohne `/` enden. `getAppBaseUrl()` sollte trailing slashes normalisieren.
|
||||||
|
|
||||||
3. **MFA_REQUIRED enthält `userId` im aktuellen throw:** Die userId war im `"MFA_REQUIRED:userId"`-String für eine geplante Re-Auth-Mechanik. Mit `CredentialsSignin` entfällt dieses Encoding — die userId wird in der TOTP-Verifikation direkt aus der Session gelesen (was korrekt ist, da die Session beim ersten erfolgreichen Password-Check bereits existiert). Kein Datenverlust.
|
|
||||||
|
|||||||
@@ -0,0 +1,162 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* export-dev-seed.mjs
|
||||||
|
*
|
||||||
|
* Dumps the current dev database into packages/db/prisma/dev-seed.sql.
|
||||||
|
* The dump is safe to commit: passwords, TOTP secrets, SMTP credentials,
|
||||||
|
* and webhook secrets are all sanitized before writing.
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* node scripts/export-dev-seed.mjs
|
||||||
|
*
|
||||||
|
* Requirements:
|
||||||
|
* - The capakraken-postgres-1 Docker container must be running
|
||||||
|
* - DATABASE_URL must point to a local capakraken database
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { execSync, spawnSync } from "node:child_process";
|
||||||
|
import { writeFileSync } from "node:fs";
|
||||||
|
import { resolve, dirname } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { loadWorkspaceEnv, resolveRealWorkspaceRoot } from "./load-env.mjs";
|
||||||
|
|
||||||
|
loadWorkspaceEnv();
|
||||||
|
const workspaceRoot = resolveRealWorkspaceRoot();
|
||||||
|
|
||||||
|
// ── Safety check ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const rawUrl = process.env["DATABASE_URL"];
|
||||||
|
if (!rawUrl) {
|
||||||
|
console.error("❌ DATABASE_URL is not set.");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let parsedUrl;
|
||||||
|
try {
|
||||||
|
parsedUrl = new URL(rawUrl);
|
||||||
|
} catch {
|
||||||
|
console.error("❌ DATABASE_URL is not a valid URL.");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const host = parsedUrl.hostname;
|
||||||
|
if (!["localhost", "127.0.0.1", "::1"].includes(host)) {
|
||||||
|
console.error(`❌ Refusing to export from non-local host: ${host}`);
|
||||||
|
console.error(" export-dev-seed is only for local development databases.");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Docker container check ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const CONTAINER = "capakraken-postgres-1";
|
||||||
|
const containerCheck = spawnSync("docker", ["inspect", "--format={{.State.Running}}", CONTAINER], {
|
||||||
|
encoding: "utf8",
|
||||||
|
});
|
||||||
|
if (containerCheck.stdout.trim() !== "true") {
|
||||||
|
console.error(`❌ Container ${CONTAINER} is not running.`);
|
||||||
|
console.error(" Start it with: docker compose up -d postgres");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Tables to exclude entirely ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const EXCLUDE_TABLES = [
|
||||||
|
"_prisma_migrations",
|
||||||
|
"audit_logs",
|
||||||
|
"active_sessions",
|
||||||
|
"sessions",
|
||||||
|
"accounts",
|
||||||
|
"verification_tokens",
|
||||||
|
"invite_tokens",
|
||||||
|
"notifications",
|
||||||
|
"import_batches",
|
||||||
|
"staged_assignments",
|
||||||
|
"staged_availability_rules",
|
||||||
|
"staged_clients",
|
||||||
|
"staged_projects",
|
||||||
|
"staged_resources",
|
||||||
|
"staged_unresolved_records",
|
||||||
|
"staged_vacations",
|
||||||
|
];
|
||||||
|
|
||||||
|
const excludeFlags = EXCLUDE_TABLES.flatMap((t) => ["--exclude-table-data", `public.${t}`]);
|
||||||
|
|
||||||
|
// ── Run pg_dump inside the Docker container ───────────────────────────────────
|
||||||
|
|
||||||
|
const DB_USER = decodeURIComponent(parsedUrl.username) || "capakraken";
|
||||||
|
const DB_NAME = parsedUrl.pathname.replace(/^\/+/, "") || "capakraken";
|
||||||
|
const DB_PORT = parsedUrl.port || "5432";
|
||||||
|
|
||||||
|
console.log(`🔍 Exporting ${DB_USER}@${host}:${DB_PORT}/${DB_NAME} …`);
|
||||||
|
|
||||||
|
const pgDumpArgs = [
|
||||||
|
"exec",
|
||||||
|
CONTAINER,
|
||||||
|
"pg_dump",
|
||||||
|
"-U", DB_USER,
|
||||||
|
"-d", DB_NAME,
|
||||||
|
"--data-only",
|
||||||
|
"--no-owner",
|
||||||
|
"--no-acl",
|
||||||
|
"--disable-triggers",
|
||||||
|
...excludeFlags,
|
||||||
|
];
|
||||||
|
|
||||||
|
const dump = spawnSync("docker", pgDumpArgs, { encoding: "utf8", maxBuffer: 256 * 1024 * 1024 });
|
||||||
|
|
||||||
|
if (dump.status !== 0) {
|
||||||
|
console.error("❌ pg_dump failed:");
|
||||||
|
console.error(dump.stderr);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Sanitize sensitive values ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
let sql = dump.stdout;
|
||||||
|
|
||||||
|
// Replace argon2id password hashes with a clearly invalid placeholder.
|
||||||
|
// The import script will update these with a real dev hash.
|
||||||
|
sql = sql.replace(/\$argon2id\$[^\t\n\\]*/g, "__DEV_PASSWORD_HASH__");
|
||||||
|
|
||||||
|
// Append sanitizing statements (TOTP, SMTP password, webhook secrets).
|
||||||
|
// These run after the COPY blocks so they don't require line-level parsing.
|
||||||
|
sql += `
|
||||||
|
-- ─── Sanitize secrets (applied after data load) ──────────────────────────────
|
||||||
|
UPDATE users SET "totpSecret" = NULL, "totpEnabled" = false;
|
||||||
|
UPDATE system_settings SET "smtpPassword" = NULL;
|
||||||
|
UPDATE webhooks SET secret = NULL;
|
||||||
|
`;
|
||||||
|
|
||||||
|
// ── Add header ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const header = `-- CapaKraken dev seed — exported ${new Date().toISOString()}
|
||||||
|
-- Source: ${DB_USER}@${host}:${DB_PORT}/${DB_NAME}
|
||||||
|
--
|
||||||
|
-- Excluded tables:
|
||||||
|
${EXCLUDE_TABLES.map((t) => `-- ${t}`).join("\n")}
|
||||||
|
--
|
||||||
|
-- Sanitized fields:
|
||||||
|
-- users.passwordHash → placeholder (import-dev-seed sets "Dev123456!")
|
||||||
|
-- users.totpSecret → NULL
|
||||||
|
-- users.totpEnabled → false
|
||||||
|
-- system_settings.smtpPassword → NULL
|
||||||
|
-- webhooks.secret → NULL
|
||||||
|
--
|
||||||
|
-- Import with:
|
||||||
|
-- node scripts/import-dev-seed.mjs
|
||||||
|
-- ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
`;
|
||||||
|
|
||||||
|
// ── Write output ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const outPath = resolve(workspaceRoot, "packages/db/prisma/dev-seed.sql");
|
||||||
|
writeFileSync(outPath, header + sql, "utf8");
|
||||||
|
|
||||||
|
const lines = (header + sql).split("\n").length;
|
||||||
|
const sizeKb = Math.round(Buffer.byteLength(header + sql, "utf8") / 1024);
|
||||||
|
console.log(`✅ Written to packages/db/prisma/dev-seed.sql`);
|
||||||
|
console.log(` ${lines.toLocaleString()} lines · ${sizeKb.toLocaleString()} KB`);
|
||||||
|
console.log();
|
||||||
|
console.log("Next step: commit dev-seed.sql or share it with your team.");
|
||||||
|
console.log("Import it with: node scripts/import-dev-seed.mjs");
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* import-dev-seed.mjs
|
||||||
|
*
|
||||||
|
* Imports packages/db/prisma/dev-seed.sql into the local dev database.
|
||||||
|
* Wipes the public schema, re-applies the current Prisma schema, loads the
|
||||||
|
* seed data, then sets every user's password to "Dev123456!" via argon2id.
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* node scripts/import-dev-seed.mjs
|
||||||
|
*
|
||||||
|
* Requirements:
|
||||||
|
* - The capakraken-postgres-1 Docker container must be running
|
||||||
|
* - DATABASE_URL must point to a local capakraken database
|
||||||
|
* - dev-seed.sql must exist (run export-dev-seed.mjs first)
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { execSync, spawnSync } from "node:child_process";
|
||||||
|
import { existsSync, readFileSync } from "node:fs";
|
||||||
|
import { resolve } from "node:path";
|
||||||
|
import { loadWorkspaceEnv, resolveRealWorkspaceRoot } from "./load-env.mjs";
|
||||||
|
|
||||||
|
loadWorkspaceEnv();
|
||||||
|
const workspaceRoot = resolveRealWorkspaceRoot();
|
||||||
|
|
||||||
|
// ── Safety check ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const rawUrl = process.env["DATABASE_URL"];
|
||||||
|
if (!rawUrl) {
|
||||||
|
console.error("❌ DATABASE_URL is not set.");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let parsedUrl;
|
||||||
|
try {
|
||||||
|
parsedUrl = new URL(rawUrl);
|
||||||
|
} catch {
|
||||||
|
console.error("❌ DATABASE_URL is not a valid URL.");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const host = parsedUrl.hostname;
|
||||||
|
if (!["localhost", "127.0.0.1", "::1"].includes(host)) {
|
||||||
|
console.error(`❌ Refusing to import into non-local host: ${host}`);
|
||||||
|
console.error(" import-dev-seed is only for local development databases.");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const DB_USER = decodeURIComponent(parsedUrl.username) || "capakraken";
|
||||||
|
const DB_NAME = parsedUrl.pathname.replace(/^\/+/, "") || "capakraken";
|
||||||
|
const DB_PORT = parsedUrl.port || "5432";
|
||||||
|
|
||||||
|
// ── Docker container check ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const CONTAINER = "capakraken-postgres-1";
|
||||||
|
const containerCheck = spawnSync("docker", ["inspect", "--format={{.State.Running}}", CONTAINER], {
|
||||||
|
encoding: "utf8",
|
||||||
|
});
|
||||||
|
if (containerCheck.stdout.trim() !== "true") {
|
||||||
|
console.error(`❌ Container ${CONTAINER} is not running.`);
|
||||||
|
console.error(" Start it with: docker compose up -d postgres");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Check seed file exists ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const seedPath = resolve(workspaceRoot, "packages/db/prisma/dev-seed.sql");
|
||||||
|
if (!existsSync(seedPath)) {
|
||||||
|
console.error("❌ packages/db/prisma/dev-seed.sql not found.");
|
||||||
|
console.error(" Generate it first with: node scripts/export-dev-seed.mjs");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`🗑 Wiping public schema in ${DB_USER}@${host}:${DB_PORT}/${DB_NAME} …`);
|
||||||
|
|
||||||
|
// ── Drop and recreate the public schema ──────────────────────────────────────
|
||||||
|
|
||||||
|
function psql(sql) {
|
||||||
|
const result = spawnSync(
|
||||||
|
"docker",
|
||||||
|
["exec", "-i", CONTAINER, "psql", "-U", DB_USER, "-d", DB_NAME, "-c", sql],
|
||||||
|
{ encoding: "utf8" },
|
||||||
|
);
|
||||||
|
if (result.status !== 0) {
|
||||||
|
console.error("❌ psql command failed:");
|
||||||
|
console.error(result.stderr);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
return result.stdout;
|
||||||
|
}
|
||||||
|
|
||||||
|
psql("DROP SCHEMA public CASCADE; CREATE SCHEMA public;");
|
||||||
|
|
||||||
|
// ── Push current Prisma schema ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
console.log("🔧 Applying current Prisma schema (db push) …");
|
||||||
|
try {
|
||||||
|
execSync("pnpm db:push", {
|
||||||
|
cwd: workspaceRoot,
|
||||||
|
stdio: "inherit",
|
||||||
|
env: { ...process.env },
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
console.error("❌ pnpm db:push failed. See output above.");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Import the seed SQL ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
console.log("📥 Importing dev-seed.sql …");
|
||||||
|
|
||||||
|
const importResult = spawnSync(
|
||||||
|
"docker",
|
||||||
|
["exec", "-i", CONTAINER, "psql", "-U", DB_USER, "-d", DB_NAME],
|
||||||
|
{
|
||||||
|
encoding: "utf8",
|
||||||
|
input: readFileSync(seedPath, "utf8"),
|
||||||
|
maxBuffer: 256 * 1024 * 1024,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (importResult.status !== 0) {
|
||||||
|
console.error("❌ psql import failed:");
|
||||||
|
console.error(importResult.stderr);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Hash dev password and update all users ────────────────────────────────────
|
||||||
|
|
||||||
|
console.log("🔐 Setting dev passwords (Dev123456!) …");
|
||||||
|
|
||||||
|
const { hash } = await import("@node-rs/argon2");
|
||||||
|
const devHash = await hash("Dev123456!", {
|
||||||
|
memoryCost: 19456,
|
||||||
|
timeCost: 2,
|
||||||
|
outputLen: 32,
|
||||||
|
parallelism: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateResult = spawnSync(
|
||||||
|
"docker",
|
||||||
|
[
|
||||||
|
"exec",
|
||||||
|
"-i",
|
||||||
|
CONTAINER,
|
||||||
|
"psql",
|
||||||
|
"-U", DB_USER,
|
||||||
|
"-d", DB_NAME,
|
||||||
|
"-c", `UPDATE users SET "passwordHash" = '${devHash}';`,
|
||||||
|
],
|
||||||
|
{ encoding: "utf8" },
|
||||||
|
);
|
||||||
|
|
||||||
|
if (updateResult.status !== 0) {
|
||||||
|
console.error("❌ Password update failed:");
|
||||||
|
console.error(updateResult.stderr);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Summary ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const userCount = psql(`SELECT COUNT(*) FROM users;`)
|
||||||
|
.trim()
|
||||||
|
.split("\n")
|
||||||
|
.find((line) => /^\s*\d+\s*$/.test(line))
|
||||||
|
?.trim() ?? "?";
|
||||||
|
|
||||||
|
console.log();
|
||||||
|
console.log("✅ Dev seed imported successfully.");
|
||||||
|
console.log(` Users: ${userCount}`);
|
||||||
|
console.log(" Password for all accounts: Dev123456!");
|
||||||
|
console.log(" Sign in at: http://localhost:3100/auth/signin");
|
||||||
|
console.log();
|
||||||
|
console.log("Note: TOTP is disabled for all users. Re-enable via Settings if needed.");
|
||||||