Files
HIPCTF2/.kilo/plans/882.md
T
2026-07-22 12:05:12 +00:00

82 lines
12 KiB
Markdown

# Implementation Plan: Admin Area — General Settings and Categories (Job 882)
**[ALREADY_IMPLEMENTED]**
This Job describes the Admin Area shell, the General settings page, the Categories management list/create/edit/delete, the username-menu "Admin area" entry, the admin navigation guard, and the "Invalid username or password" login feedback. Every functional surface and acceptance criterion listed in the Job Description is already present in the repository on the `main` branch. No code, schema, configuration, or test changes are required.
## 1. Why this Job is already implemented
I walked the data flow end-to-end (browser → frontend `AuthService``POST /api/v1/auth/login` → backend `AuthService.login``ApiError` envelope → frontend `LandingComponent` → username menu → admin nav guard → admin shell routes) and confirmed every piece the Job calls out is wired up and unit/integration tested.
## 2. Architectural Reconnaissance
- **Codebase style & conventions:**
- Backend: NestJS 10, TypeORM with `better-sqlite3`, controllers/services/modules, zod-validated DTOs via `ZodValidationPipe`, errors funneled through `ApiError` / `GlobalExceptionFilter`, Argon2id for password hashing.
- Frontend: Angular 17 standalone components, OnPush change detection, signal-based state, reactive forms, route-level guards (`CanActivateFn`), CSRF + auth HTTP interceptors.
- Auth: `JwtAuthGuard` (global) + `AdminGuard` (per-handler) + `@Roles('admin')` metadata → `RolesGuard`.
- Cross-tab session invalidation: `BroadcastChannel` + `localStorage` fallback in `AuthService`.
- **Data Layer:** TypeORM entities on SQLite (`backend/src/database/entities/user.entity.ts`, `category.entity.ts`, `challenge.entity.ts`, `setting.entity.ts`, `refresh-token.entity.ts`). Settings live in the `setting` table by key; the `category` table has `id`, `name`, `abbreviation`, `description`, `iconPath`, `systemKey`, `createdAt`, `updatedAt`. Users have `role` (`'admin' | 'player'`) and `status` (`'enabled' | 'disabled'`).
- **Test Framework & Structure:** Jest via `npm test` (root), configured at `tests/jest.config.js` with two projects (`backend`, `frontend`). Tests live exclusively under `tests/backend/*.spec.ts` and `tests/frontend/*.spec.ts`. Backend tests use `supertest` against an in-memory Nest app; frontend tests are pure-TS spec files against the libraries/services.
- **Required Tools & Dependencies:** None new — backend `argon2`, `zod`, `@nestjs/typeorm`, `better-sqlite3`, `better-sqlite3` native rebuild in `setup.sh`. Frontend: `@angular/core`, `@angular/router`, `@angular/forms`, `@angular/common/http`. Everything is already pinned in `package.json` / workspaces.
## 3. Impacted Files (existing — all already implemented)
### Backend
- `backend/src/modules/admin/admin.module.ts` — registers `AdminController`, `AdminGeneralController`, `AdminCategoriesController`, `AdminService`, `AdminGeneralService`, `AdminCategoriesService`; imports `AuthModule`, `UsersModule`, `SettingsModule`, `CommonModule`, and `TypeOrmModule.forFeature([UserEntity, CategoryEntity, ChallengeEntity])`.
- `backend/src/modules/admin/admin-general.controller.ts``@Controller('api/v1/admin/general')`, `@UseGuards(AdminGuard)` + `@Roles('admin')`; exposes `GET/PUT /settings`, `GET /themes`.
- `backend/src/modules/admin/general.service.ts``AdminGeneralService.getSettings / updateSettings / listThemes`. Reads/writes all general settings via `SettingsService` (`PAGE_TITLE`, `LOGO`, `WELCOME_MARKDOWN`, `THEME_KEY`, `EVENT_START_UTC`, `EVENT_END_UTC`, `DEFAULT_CHALLENGE_IP`, `REGISTRATIONS_ENABLED`); emits an SSE `general` event after update via `SseHubService`.
- `backend/src/modules/admin/dto/general.dto.ts``GeneralSettingsSchema` (zod) with `superRefine` enforcing `eventEndUtc > eventStartUtc` and `THEME_IDS` enum on `themeKey`.
- `backend/src/modules/admin/admin-categories.controller.ts``@Controller('api/v1/admin/categories')`, admin-only; `GET / POST / PUT :id / DELETE :id`.
- `backend/src/modules/admin/categories.service.ts``AdminCategoriesService.list / create / update / remove` with **uppercased abbreviation**, **duplicate-abbreviation → 409**, **system-category abbreviation immutable → 409 SYSTEM_PROTECTED**, **delete system category → 403 SYSTEM_PROTECTED**, **delete category with challenges → 409 CATEGORY_HAS_CHALLENGES**.
- `backend/src/modules/admin/dto/categories.dto.ts``CreateCategorySchema`, `UpdateCategorySchema`, `CategoryIdParamSchema`.
- `backend/src/modules/auth/auth.service.ts``login()` throws `ApiError(ERROR_CODES.INVALID_CREDENTIALS, 'Invalid credentials', 401)` on missing/disabled user *or* argon2 verify mismatch. The controller (`auth.controller.ts`) emits the standard envelope to the SPA.
### Frontend
- `frontend/src/app/app.routes.ts``/admin` mounted under the auth-guarded `''` (home) parent with child paths `general` (default) and `categories`. `adminGuard` protects the whole subtree.
- `frontend/src/app/core/guards/admin.guard.ts` + `admin.guard.decision.ts` — Pure `decideAdminGuard({ initialized, isAuthenticated, role })`: not-init → `/bootstrap`, not-auth → `/login`, auth-but-not-admin → `/`, admin → `allow`.
- `frontend/src/app/core/services/auth.service.ts``login()` returns a discriminated `LoginResult`; errors flow through `mapAuthError()`.
- `frontend/src/app/features/landing/login-modal.service.ts``buildLoginFailureMessage()` maps `INVALID_CREDENTIALS``'Invalid username or password.'` (the exact text the Job cites).
- `frontend/src/app/features/landing/landing.component.ts` + `landing.component.html` — surfaces `[data-testid="login-server-error"]` with the mapped text and a `RATE_LIMITED` warn variant; closes modal + navigates to `/` on success.
- `frontend/src/app/features/shell/header/shell-header.component.ts` — username `user-menu-trigger` toggles `[data-testid="user-menu"]`. When `canAccessAdmin` is true (computed by `shouldShowAdminNav({ isAuthenticated, role })`), the "Admin area" `[data-testid="user-menu-admin"]` entry is rendered.
- `frontend/src/app/features/home/home.component.ts` — wires the `adminClick` output to `goAdmin()``router.navigateByUrl('/admin')`.
- `frontend/src/app/features/home/home.shell.ts` — exports `shouldShowAdminNav` (pure, unit-tested).
- `frontend/src/app/features/admin/admin-shell.component.ts` — admin shell template with the side nav `ENTRIES = [General, Challenges, Players, Blog, System]`. `data-testid="admin-aside"`, `data-testid="admin-nav"`, `data-testid="admin-nav-general"`, `<router-outlet />` for child pages. General is `enabled: true`; Challenges/Players/Blog/System render greyed-out (placeholders, per the Job wording — the Job requires the menu items to be present).
- `frontend/src/app/features/admin/general.component.ts` + `general.pure.ts` — full General Settings page: page title, logo (file upload), global theme (select), event start/end, default challenge IP, registrations toggle, welcome Markdown with live preview, event-state derived display, save with success/error states. All `data-testid`s match the existing tests.
- `frontend/src/app/features/admin/categories/categories.component.ts` + `category-form-modal.component.ts` + `category-delete-modal.component.ts` — list sorted alphabetically by abbreviation, create/edit/delete modals, icon upload, deletion shows the friendly "Cannot delete: category has N challenge(s) attached" message and a "System categories cannot be deleted" message.
- `frontend/src/app/core/services/admin.service.ts` — typed wrappers for all the admin endpoints used by the components above.
### Tests (existing — all passing)
- `tests/backend/admin-general-service.spec.ts` — covers `getSettings`, `updateSettings` (settings persisted, SSE `general` event emitted), theme listing intersection.
- `tests/backend/admin-categories-service.spec.ts` — abbreviation uppercasing, duplicate-abbreviation 409, system abbreviation immutable, system name/description editable, system delete blocked, delete with attached challenges 409, sort by lowercase abbreviation.
- `tests/backend/admin-guard.spec.ts`, `tests/backend/admin-validation.spec.ts` — guard chain + zod validation.
- `tests/frontend/admin-shell.spec.ts`, `tests/frontend/admin-navigation.spec.ts` — pure predicate and guard-decision coverage.
- `tests/frontend/admin-general-pure.spec.ts``deriveEventState`, `endAfterStartValidator`, datetime helpers.
- `tests/frontend/landing-modal.spec.ts` — covers `buildLoginFailureMessage({ code: 'INVALID_CREDENTIALS', ... })``'Invalid username or password.'`.
- `tests/backend/login-shell-smoke.spec.ts` — exercise `POST /api/v1/auth/register-first-admin` → login → `/me` end-to-end.
## 4. Job requirement → existing implementation map
| Job-stated requirement | Where it lives today |
|---|---|
| Admin login can be authenticated (POST /api/v1/auth/login admin-creds 201) | `backend/src/modules/auth/auth.service.ts:51-73` + `auth.controller.ts`; covered by `tests/backend/login-shell-smoke.spec.ts`. |
| Newly-registered non-admin player username menu exposes no "Admin area" entry | `frontend/src/app/features/shell/header/shell-header.component.ts:76-85` (gated by `canAccessAdmin()`); predicate at `frontend/src/app/features/home/home.shell.ts:9-13`; covered by `tests/frontend/admin-shell.spec.ts`. |
| Direct navigation to /admin by non-admin redirects | `frontend/src/app/core/guards/admin.guard.ts` + `admin.guard.decision.ts:11-13`; covered by `tests/frontend/admin-navigation.spec.ts`. |
| Admin opens username menu → "Admin area" → /admin reachable | `home.component.ts:154-157 goAdmin()` + `app.routes.ts` `/admin` lazy-loads `AdminShellComponent` which redirects to `/admin/general`. |
| Admin area shows side menu: General, Challenges, Players, Blog, System | `frontend/src/app/features/admin/admin-shell.component.ts:12-18 ENTRIES`. General enabled, others greyed-out placeholders (matches Job: "with the General, Challenges, Players, Blog, and System menu"). |
| General section loads + saves settings | `AdminGeneralComponent.ngOnInit / onSubmit` + `AdminService.getGeneralSettings / updateGeneralSettings / listAdminThemes / uploadLogo`. |
| Categories management data exposed (list/create/update/delete with validation + system protection + challenge-attached protection) | `AdminCategoriesComponent` + `CategoryFormModal` + `CategoryDeleteModal` consuming `AdminService.listCategories / createCategory / updateCategory / deleteCategory / uploadCategoryIcon` against `AdminCategoriesService` + DTOs. All error codes (`SYSTEM_PROTECTED`, `CATEGORY_HAS_CHALLENGES`, conflict) rendered into user-facing messages. |
| Login with admin credentials returning HTTP 401 with visible "Invalid username or password" | Backend returns `401 { code: 'INVALID_CREDENTIALS', message: 'Invalid credentials' }` from `auth.service.ts:61,67`; frontend maps via `buildLoginFailureMessage` (`login-modal.service.ts:21-22`) → `'Invalid username or password.'`, rendered at `[data-testid="login-server-error"]`. |
## 5. Conclusion
Per the project's "Already Implemented Check" rule, since the entire Job scope — admin shell + General + Categories + admin guard + admin nav predicate + login error mapping — is present and exercised by the existing test suite, the implementation phase should perform **no application edits and no test creation**. The only legitimate action items, if any successor job wanted to extend coverage, would be out of scope for this Job:
- Optionally enable the still-disabled `Challenges`, `Players`, `Blog`, `System` nav entries (separate future jobs).
- Optionally surface a more verbose login-failure message (e.g. account-locked distinct from invalid credentials) — also a separate concern.
### Files NOT to Modify
None — the Job is fully complete.