canina/docs/audit/MASTER-TASK-BACKLOG.md
2026-08-06 20:54:44 +03:30

467 lines
29 KiB
Markdown

# Master Task Backlog (Phase 3.3 Final Canonical Specification)
- **Audit Phase**: Phase 3.3 — Finalized Architecture & Backlog Revision
- **Repository HEAD**: `715873b2ecc3a72ba974bb2a2be87c5ba82bd4e7`
- **Canonical Verified Findings Source**: `docs/audit/20-verified-findings-index.json`
- **Total Verified Findings Processed**: 14 (100% Traceability Coverage)
- **Total Backlog Tasks**: 10 (9 Implementation Tasks + 1 Verification Task)
- **Finalized Architecture Split**: Storefront (Next.js SSR/SEO) vs Admin Panel (Pure React SPA Performance & Security)
- **Finalized Product Decisions**: 2 (`DECISION-001`, `DECISION-003` Finalized) | Future Scope: 1 (`DECISION-002`)
---
## Executive Summary & Backlog Overview
| Priority | Task ID | Title | Category | Source Findings | Target Subsystem | Status |
|---|---|---|---|---|---|---|
| **P0** | `TASK-SEC-001` | Mandatory Dual-Secret Startup Enforcement (`JWT_ACCESS_SECRET` & `JWT_REFRESH_SECRET`) | Security | `SEC-001` | Backend (`main.ts`) | `READY_FOR_IMPLEMENTATION` |
| **P0** | `TASK-SEC-002` | Cryptographically Secure OTP Generation & Response Payload Hardening | Security | `SEC-002`, `SEC-003` | Backend (`auth`) | `READY_FOR_IMPLEMENTATION` |
| **P0** | `TASK-SEC-003` | Role-Based Access Control (RBAC) Enforcement on Administrative Settings API | Security | `ADM-001` | Backend (`settings`) | `READY_FOR_IMPLEMENTATION` |
| **P0** | `TASK-FIN-001` | Arbitrary-Precision Decimal Accounting & Prisma.Decimal Payload Serialization | Financial / DB | `BE-001`, `BE-002` | Backend (`orders`) | `READY_FOR_IMPLEMENTATION` |
| **P1** | `TASK-BUILD-001` | NestJS Compiler Diagnostic Remediation & Spec Return Type Alignment | Build / Code Quality | `TS-002`, `TS-003`, `TEST-001` | Backend (`prisma`/`spec`) | `READY_FOR_IMPLEMENTATION` |
| **P1** | `TASK-AUTH-001` | Dual-Token Auth Contract Integration for Standalone Admin Panel | Architecture | `ARCH-001` | Admin Panel / Auth | `BLOCKED_BY_DEPENDENCY` (`TASK-SEC-002`) |
| **P1** | `TASK-VERIFY-001` | End-to-End Authentication, Authorization, Order, and Regression Verification | Verification | All 14 Findings | Entire System | `BLOCKED_BY_DEPENDENCY` (`TASK-AUTH-001`, `TASK-SEC-003`, `TASK-FIN-001`) |
| **P2** | `TASK-FE-001` | Admin Panel Router Architecture (`createBrowserRouter`), Lazy Loading & Type Safety | Admin SPA | `FE-001`, `TS-001` | Admin Panel SPA | `READY_FOR_IMPLEMENTATION` |
| **P2** | `TASK-DEVOPS-001` | Continuous Integration Pipeline & Automated Quality Gate Setup | DevOps | `DEVOPS-001` | CI Workflow | `BLOCKED_BY_DEPENDENCY` (`TASK-BUILD-001`) |
| **P3** | `TASK-DOC-001` | OpenAPI Documentation Synchronization & Non-Listener Schema Export | Documentation | `DOC-001` | Docs / Backend | `READY_FOR_IMPLEMENTATION` |
---
## Detailed Task Specifications
---
### TASK-SEC-001
- **TASK-ID**: `TASK-SEC-001`
- **Title**: Mandatory Dual-Secret Startup Enforcement (`JWT_ACCESS_SECRET` & `JWT_REFRESH_SECRET`)
- **Status**: `READY_FOR_IMPLEMENTATION`
- **Priority**: `P0`
- **Severity**: `HIGH`
- **Category**: `Security / Cryptographic Hardening`
- **Source Findings**: `SEC-001`
- **Objective**: Ensure NestJS application fails startup (`process.exit(1)`) if EITHER `JWT_ACCESS_SECRET` OR `JWT_REFRESH_SECRET` is missing, empty, or less than 32 characters, completely eliminating hardcoded secret fallback strings.
- **Root Cause Addressed**: Developer fallback string embedded in `jwt.strategy.ts` and `auth.module.ts` as a default parameter instead of validating mandatory environment variables during application startup.
- **Current State**:
- `backend/src/auth/jwt.strategy.ts`: Line 12 uses `secretOrKey: process.env.JWT_SECRET || 'super-secret-key'`.
- `backend/src/auth/auth.module.ts`: Uses `process.env.JWT_SECRET || 'super-secret-key'`.
- **Required Changes**:
1. Remove hardcoded fallback strings from `jwt.strategy.ts` and `auth.module.ts`.
2. In `backend/src/main.ts` `bootstrap()`, implement explicit startup validation for TWO separate environment variables: `JWT_ACCESS_SECRET` and `JWT_REFRESH_SECRET`. If either variable is undefined, empty, or `length < 32` characters (minimum 32 bytes ASCII entropy), log fatal error and throw an exception before `app.listen()`, terminating process bootstrap with exit code 1.
3. Ensure `.env.example` includes placeholders `JWT_ACCESS_SECRET=` and `JWT_REFRESH_SECRET=` with instructions for production key generation.
- **Affected Files / Areas**:
- `backend/src/main.ts`
- `backend/src/auth/jwt.strategy.ts`
- `backend/src/auth/auth.module.ts`
- `backend/.env.example`
- **Implementation Approach**:
Read both `process.env.JWT_ACCESS_SECRET` and `process.env.JWT_REFRESH_SECRET` cleanly in `main.ts` bootstrap. Throw explicit `Error('FATAL: JWT_ACCESS_SECRET or JWT_REFRESH_SECRET environment variable is missing or insecure.')` on bootstrap.
- **Dependencies**: None.
- **Blocked By**: None.
- **Risk Assessment**: LOW technical risk. Fail-closed security design for dual-token authentication.
- **Testing Requirements**:
- Unit test in `jwt.strategy.spec.ts` asserting error thrown when either secret is omitted.
- Integration test confirming application boots successfully when both valid secrets (>= 32 chars each) are supplied.
- **Validation Commands**:
- `cd backend && npm run test -- backend/src/auth/jwt.strategy.spec.ts`
- `cd backend && cross-env JWT_ACCESS_SECRET= npm run start:dev` (Verify immediate crash with explicit error message)
- **Acceptance Criteria**:
- Zero occurrences of string `'super-secret-key'` or `'super-secret-key-canina'` in repository source files.
- Backend startup terminates with process exit code 1 when either `JWT_ACCESS_SECRET` or `JWT_REFRESH_SECRET` is absent or < 32 chars.
- **Definition of Done**: Code edited, unit tests passing, dual-secret startup validation verified.
- **Rollback / Recovery Considerations**: Set both secret environment variables in deployment configuration if startup fails.
---
### TASK-SEC-002
- **TASK-ID**: `TASK-SEC-002`
- **Title**: Cryptographically Secure OTP Generation & Response Payload Hardening
- **Status**: `READY_FOR_IMPLEMENTATION`
- **Priority**: `P0`
- **Severity**: `HIGH`
- **Category**: `Security / Authentication Hardening`
- **Source Findings**: `SEC-002`, `SEC-003`
- **Objective**: Re-engineer NestJS SMS OTP generation to use Node.js CSPRNG (`crypto.randomInt`), separate OTP generation from delivery via an `IOtpDeliveryService` interface abstraction, and remove plaintext OTP code disclosure from public API response payloads.
- **Root Cause Addressed**:
1. `AuthService.sendOtp` used non-cryptographic `Math.random()` to generate 5-digit verification codes.
2. `AuthController.sendOtp` returned `{ success: true, code: '12345' }` in the public response body.
- **Current State**:
- `backend/src/auth/auth.service.ts`: `const code = Math.floor(10000 + Math.random() * 90000).toString();`
- Returns `{ success: true, message: '...', code }`.
- **Required Changes**:
1. Replace `Math.random()` in `backend/src/auth/auth.service.ts` with `crypto.randomInt(10000, 100000).toString()`.
2. Create `IOtpDeliveryService` / `OtpDeliveryService` dependency injection token with `ConsoleOtpDeliveryService` (dev/test logger) and `SmsGatewayOtpDeliveryService` (production adapter).
3. Remove `code` field from returned object of `sendOtp` in `AuthService` and `AuthController`. Response body must only return `{ success: true, message: 'کد تایید ارسال شد' }`.
- **Affected Files / Areas**:
- `backend/src/auth/auth.service.ts`
- `backend/src/auth/auth.controller.ts`
- `backend/src/auth/auth.service.spec.ts`
- `backend/src/auth/otp-delivery.service.ts` [NEW]
- **Implementation Approach**:
Import native `crypto`. Generate 5-digit integer via `crypto.randomInt(10000, 100000)`. Inject `ConsoleOtpDeliveryService`. Sanitize DTO to omit `code`.
- **Dependencies**: None.
- **Blocked By**: None.
- **Risk Assessment**: LOW risk. Highly isolated changes within `AuthService`.
- **Testing Requirements**:
- Unit test verifying CSPRNG usage via `crypto.randomInt`.
- Unit test asserting `/api/auth/send-otp` response payload JSON structure does NOT contain key `code`.
- Tests use mock/console delivery service without requiring real SMS delivery.
- **Validation Commands**:
- `cd backend && npm run test -- backend/src/auth/auth.service.spec.ts`
- `cd backend && npm run test -- backend/src/auth/auth.controller.spec.ts`
- **Acceptance Criteria**:
- `sendOtp` response body structure contains ONLY `{ success: boolean, message: string }`.
- OTP generation relies on `crypto.randomInt`.
- **Definition of Done**: Clean unit tests passing, response sanitized, CSPRNG implemented.
- **Rollback / Recovery Considerations**: Standard git revert.
---
### TASK-SEC-003
- **TASK-ID**: `TASK-SEC-003`
- **Title**: Role-Based Access Control (RBAC) Enforcement on Administrative Settings API
- **Status**: `READY_FOR_IMPLEMENTATION`
- **Priority**: `P0`
- **Severity**: `HIGH`
- **Category**: `Security / Authorization & Access Control`
- **Source Findings**: `ADM-001`
- **Objective**: Protect all administrative settings endpoints (`/api/settings/*`) with `RolesGuard` and `@Roles('Admin')` decorator.
- **Root Cause Addressed**: `SettingsController` applied `@UseGuards(JwtAuthGuard)` but omitted `RolesGuard` and `@Roles('Admin')`. `RolesGuard` and `@Roles` decorator were missing from the codebase.
- **Current State**:
- `backend/src/settings/settings.controller.ts`: Lacks `@UseGuards(RolesGuard)` and `@Roles('Admin')`.
- **Required Changes**:
1. Create `backend/src/common/decorators/roles.decorator.ts` (`SetMetadata('roles', roles)`).
2. Create `backend/src/common/guards/roles.guard.ts` using `Reflector` to validate `req.user.role === 'Admin'`.
3. Apply `@UseGuards(JwtAuthGuard, RolesGuard)` and `@Roles('Admin')` to `SettingsController`.
- **Affected Files / Areas**:
- `backend/src/common/decorators/roles.decorator.ts` [NEW]
- `backend/src/common/guards/roles.guard.ts` [NEW]
- `backend/src/settings/settings.controller.ts`
- `backend/src/settings/settings.controller.spec.ts`
- **Implementation Approach**:
Implement `@Roles` decorator and `RolesGuard` -> annotate `SettingsController` with `@UseGuards(JwtAuthGuard, RolesGuard)` and `@Roles('Admin')`.
- **Dependencies**: None.
- **Blocked By**: None.
- **Risk Assessment**: LOW technical risk. Prevents unauthorized settings modifications.
- **Testing Requirements**:
- Unit test verifying non-admin users (`User_PetOwner`) receive `403 Forbidden` on settings endpoints.
- Unit test verifying admin users with `role: 'Admin'` receive `200 OK`.
- **Validation Commands**:
- `cd backend && npm run test -- backend/src/settings/settings.controller.spec.ts`
- **Acceptance Criteria**:
- Requests with `User_PetOwner` JWT receive HTTP 403 Forbidden when calling `/api/settings`.
- Requests with `Admin` JWT receive HTTP 200 OK.
- **Definition of Done**: RBAC guards created and applied, unit tests passing.
- **Rollback / Recovery Considerations**: Standard git revert.
---
### TASK-FIN-001
- **TASK-ID**: `TASK-FIN-001`
- **Title**: Arbitrary-Precision Decimal Accounting & Prisma.Decimal Payload Serialization
- **Status**: `READY_FOR_IMPLEMENTATION`
- **Priority**: `P0`
- **Severity**: `HIGH`
- **Category**: `Backend / Financial Integrity & Database Optimization`
- **Source Findings**: `BE-001`, `BE-002`
- **Objective**: Fix monetary calculation floating-point precision loss, eliminate N+1 database queries in `OrdersService.create`, and enforce global `Prisma.Decimal` serialization to prevent client-side parsing crashes.
- **Root Cause Addressed**:
1. `OrdersService.create` converted Prisma `Decimal` prices into JS numbers (`Number(product.priceValue)`).
2. `OrdersService.create` iterated over `dto.items` executing individual `findUnique` queries per line item.
3. Raw `Prisma.Decimal` objects serialized to JSON without string/number transformation, causing parsing errors on frontend/client apps.
- **Current State**:
- `backend/src/orders/orders.service.ts`: N+1 query loop + primitive number arithmetic (`totalAmount += Number(...) * quantity`).
- **Required Changes**:
1. Replace iterative `findUnique` calls with single batched query: `this.prisma.product.findMany({ where: { id: { in: productIds } } })`.
2. Map products by ID; throw `NotFoundException` (404) if any product ID is missing.
3. Throw `BadRequestException` (400) if `dto.items` contains duplicate product IDs or invalid quantities (`quantity <= 0`).
4. Perform monetary subtotal and total calculations using Prisma `Decimal` instance methods (`Decimal.add()`, `Decimal.mul()`). Example: `19.99 * 3 + 5.01 = 64.98`.
5. Implement global NestJS `DecimalInterceptor` (or DTO `Transform` decorators) to convert all `Prisma.Decimal` instances in outbound API response payloads into exact Strings (e.g., `"64.98"`) or precise Numbers before sending to clients.
- **Affected Files / Areas**:
- `backend/src/orders/orders.service.ts`
- `backend/src/orders/orders.service.spec.ts`
- `backend/src/common/interceptors/decimal.interceptor.ts` [NEW]
- `backend/src/main.ts`
- **Implementation Approach**:
Batched `findMany` -> Map lookup -> Prisma `Decimal` arithmetic -> global `DecimalInterceptor` registration in `main.ts`.
- **Dependencies**: None.
- **Blocked By**: None.
- **Risk Assessment**: MEDIUM risk. Core financial order pipeline and response serialization.
- **Testing Requirements**:
- Unit test with multi-item order verifying exactly 1 product query is executed.
- Unit test asserting exact decimal total calculation (`19.99 * 3 + 5.01 = 64.98` without floating-point rounding artifacts).
- Interceptor unit test verifying `Prisma.Decimal` properties are serialized to formatted strings/numbers in JSON response.
- **Validation Commands**:
- `cd backend && npm run test -- backend/src/orders/orders.service.spec.ts`
- `cd backend && npm run test -- backend/src/common/interceptors/decimal.interceptor.spec.ts`
- **Acceptance Criteria**:
- Zero `Number(product.priceValue)` conversions in order calculation logic.
- Single database query fetched for all cart products during checkout.
- Order total accumulated using Decimal arithmetic (`19.99 * 3 + 5.01 = 64.98`).
- All `Prisma.Decimal` fields in API JSON response payloads are serialized as exact Strings/Numbers.
- **Definition of Done**: Clean unit tests passing, Decimal math implemented, DecimalInterceptor registered, query batching verified.
- **Rollback / Recovery Considerations**: Standard git revert.
---
### TASK-BUILD-001
- **TASK-ID**: `TASK-BUILD-001`
- **Title**: NestJS Compiler Diagnostic Remediation & Spec Return Type Alignment
- **Status**: `READY_FOR_IMPLEMENTATION`
- **Priority**: `P1`
- **Severity**: `MEDIUM`
- **Category**: `Code Quality / Compilation & Test Suite Stability`
- **Source Findings**: `TS-002`, `TS-003`, `TEST-001`
- **Objective**: Fix TypeScript compiler errors in `seed.ts` and `metrics.controller.ts`, and resolve spec test suite compilation failures caused by stale controller assertions.
- **Root Cause Addressed**:
1. `backend/prisma/seed.ts` product payload missing required `slug` field (TS2322).
2. `backend/src/common/metrics.controller.ts` imported Express `Response` directly instead of type-only import under `isolatedModules` (TS1272).
3. Controller spec files asserted obsolete `result.success` wrapper property.
- **Required Changes**:
1. `backend/prisma/seed.ts`: Add `slug` string property to all product seed objects.
2. `backend/src/common/metrics.controller.ts`: Change to `import type { Response } from 'express';`.
3. Controller specs (`pets`, `settings`, `users`): Update spec expectations to match current controller method return signatures without deleting assertions.
- **Affected Files / Areas**:
- `backend/prisma/seed.ts`
- `backend/src/common/metrics.controller.ts`
- `backend/src/pets/pets.controller.spec.ts`
- `backend/src/settings/settings.controller.spec.ts`
- `backend/src/users/users.controller.spec.ts`
- **Implementation Approach**:
Fix type imports, add missing seed properties, update controller spec return assertions.
- **Dependencies**: None.
- **Blocked By**: None.
- **Risk Assessment**: LOW risk. Restores build and test pipeline hygiene.
- **Testing Requirements**:
- Full TypeScript compilation check (`npx tsc --noEmit`).
- Execution of backend Jest test suite (`npm run test`).
- **Validation Commands**:
- `cd backend && npx tsc --noEmit`
- `cd backend && npm run test`
- **Acceptance Criteria**:
- `cd backend && npx tsc --noEmit` succeeds with 0 compilation errors.
- `cd backend && npm run test` completes with 100% passing tests.
- **Definition of Done**: Clean `tsc` compilation and all test suites passing green.
- **Rollback / Recovery Considerations**: Standard git revert.
---
### TASK-AUTH-001
- **TASK-ID**: `TASK-AUTH-001`
- **Title**: Dual-Token Auth Contract Integration for Standalone Admin Panel
- **Status**: `BLOCKED_BY_DEPENDENCY`
- **Priority**: `P1`
- **Severity**: `HIGH`
- **Category**: `Architecture / Auth Integration`
- **Source Findings**: `ARCH-001`
- **Objective**: Re-architect authentication state and login flow specifically for the standalone **Admin Panel SPA** to consume NestJS auth endpoints according to [`ADR-AUTH-001`](file:///c:/Users/parsa/Desktop/work/caninairan/docs/audit/ADR-AUTH-001.md) (Dual-Token Hybrid: In-Memory Access Token + HttpOnly `refreshToken` Cookie signed with `JWT_REFRESH_SECRET`).
- **Root Cause Addressed**: Application used mock auth state and vulnerable `localStorage` token storage.
- **Current State**:
- `src/store/userStore.ts`: Mock email/password auth state.
- `src/services/authService.ts`: Uses `localStorage.setItem('accessToken', ...)`.
- **Required Changes**:
1. Implement Dual-Token Hybrid architecture per [`ADR-AUTH-001`](file:///c:/Users/parsa/Desktop/work/caninairan/docs/audit/ADR-AUTH-001.md) for the standalone Admin Panel: Hold `accessToken` strictly in-memory in Zustand store / Axios interceptor; issue `HttpOnly`, `Secure`, `SameSite=Strict` `refreshToken` cookie on successful authentication.
2. Configure Axios client with `withCredentials: true` and add background silent token refresh interceptor on HTTP 401 Unauthorized responses.
3. Build Admin Login component collecting mobile number / credentials and OTP verification code.
- **Affected Files / Areas**:
- `src/store/adminAuthStore.ts` [NEW]
- `src/components/AdminLogin.tsx` [NEW]
- `src/services/adminAuthService.ts` [NEW]
- `src/services/api.ts`
- **Implementation Approach**:
Follow [`ADR-AUTH-001`](file:///c:/Users/parsa/Desktop/work/caninairan/docs/audit/ADR-AUTH-001.md) contract -> implement `adminAuthService` & `adminAuthStore` -> wire Admin Login component.
- **Dependencies**: `TASK-SEC-002` (OTP API payload hardening must be completed prior to frontend wiring).
- **Blocked By**: `TASK-SEC-002`
- **Risk Assessment**: MEDIUM risk. Admin Panel authentication boundary.
- **Testing Requirements**:
- Unit test `adminAuthStore` state machine transitions and token handling.
- Component integration test for Admin Login.
- **Validation Commands**:
- `npm run test`
- `npm run build`
- **Acceptance Criteria**:
- Admin Panel login triggers NestJS backend auth endpoints successfully.
- Access token is held in-memory and automatically attached to `api` request headers.
- Session persists seamlessly across page refreshes via background refresh with `refreshToken` HttpOnly cookie.
- **Definition of Done**: Admin Panel dual-token auth flow fully functional per `ADR-AUTH-001`, unit tests passing, build clean.
- **Rollback / Recovery Considerations**: Standard git revert.
---
### TASK-FE-001
- **TASK-ID**: `TASK-FE-001`
- **Title**: Admin Panel Router Architecture (`createBrowserRouter`), Lazy Loading & Type Safety
- **Status**: `READY_FOR_IMPLEMENTATION`
- **Priority**: `P2`
- **Severity**: `MEDIUM`
- **Category**: `Admin SPA / Routing & Performance`
- **Source Findings**: `FE-001`, `TS-001`
- **Objective**: Implement `react-router-dom` (`createBrowserRouter`) specifically for the standalone **Admin Panel SPA** to enable Lazy Loading, optimize performance for heavy admin modules (`Products`, `Orders`, `Settings`, `Users`), and enforce strict Type Safety. (SEO is completely irrelevant for Admin Panel).
- **Root Cause Addressed**:
1. Legacy state-driven view rendering caused navigation failures.
2. Sub-view state variables used explicit `any` escape hatches.
- **Current State**:
- Storefront customer-facing application is built with Next.js (SSR/SEO).
- Admin Panel SPA requires dedicated router setup.
- **Required Changes**:
1. Configure `react-router-dom` `createBrowserRouter` for Admin Panel matching [`frontend-route-map.md`](file:///c:/Users/parsa/Desktop/work/caninairan/docs/audit/frontend-route-map.md) (`/admin/login`, `/admin/dashboard`, `/admin/settings`, `/admin/products/*`, `/admin/orders/*`, `/admin/users/*`, `/admin/pets/*`).
2. Implement React `<Suspense>` lazy-loading for heavy administrative module chunks (`AdminProductsManager`, `AdminOrdersManager`, `AdminSettings`).
3. Define explicit TypeScript interfaces for all admin route parameters and state structures, eliminating all `any` annotations.
- **Affected Files / Areas**:
- `src/App.tsx` / Admin SPA root
- `src/routes/adminRoutes.tsx` [NEW]
- `src/types/admin.ts` [NEW]
- `package.json`
- **Implementation Approach**:
Setup `createBrowserRouter` -> define lazy-loaded admin module routes -> enforce strict TypeScript interfaces.
- **Dependencies**: None.
- **Blocked By**: None.
- **Risk Assessment**: MEDIUM risk. Admin SPA routing architecture.
- **Testing Requirements**:
- Unit test admin component route navigation and lazy loading.
- Typecheck validation (`npx tsc --noEmit`).
- **Validation Commands**:
- `npx tsc --noEmit`
- `npm run build`
- **Acceptance Criteria**:
- Admin Panel routes render target views directly on page refresh via `createBrowserRouter`.
- Admin modules are lazy-loaded via dynamic imports (`lazy()`).
- Zero explicit `any` type declarations in Admin Panel codebase.
- **Definition of Done**: React Router `createBrowserRouter` integrated for Admin Panel per `frontend-route-map.md`, lazy loading verified, 0 type errors.
- **Rollback / Recovery Considerations**: Standard git revert.
---
### TASK-DEVOPS-001
- **TASK-ID**: `TASK-DEVOPS-001`
- **Title**: Continuous Integration Pipeline & Automated Quality Gate Setup
- **Status**: `BLOCKED_BY_DEPENDENCY`
- **Priority**: `P2`
- **Severity**: `MEDIUM`
- **Category**: `DevOps / Continuous Integration Workflow`
- **Source Findings**: `DEVOPS-001`
- **Objective**: Create committed Gitea/GitHub Actions workflow (`.github/workflows/ci.yml`) enforcing automated build, lint, typecheck, and test execution on pull requests.
- **Root Cause Addressed**: Absence of committed `.github/workflows/` directory in repository.
- **Current State**: No `.github/workflows/` directory exists.
- **Required Changes**:
1. Create `.github/workflows/ci.yml`.
2. Configure triggers: `on: [push, pull_request]`.
3. Define job matrix for Frontend quality gate (`npm ci`, `npm run lint`, `npx tsc --noEmit`, `npm run build`) and Backend quality gate (`cd backend && npm ci`, `npx prisma generate`, `npx tsc --noEmit`, `npm run test`).
- **Affected Files / Areas**:
- `.github/workflows/ci.yml` [NEW]
- **Implementation Approach**:
Write Gitea/GitHub Actions workflow file tailored specifically to this repository.
- **Dependencies**: `TASK-BUILD-001` (Backend compiler errors must be resolved so CI pipeline passes green).
- **Blocked By**: `TASK-BUILD-001`
- **Risk Assessment**: LOW risk. Purely additive DevOps configuration file.
- **Testing Requirements**:
- Workflow YAML syntax validation.
- **Validation Commands**:
- `npx actionlint .github/workflows/ci.yml`
- **Acceptance Criteria**:
- `.github/workflows/ci.yml` is committed and syntactically valid.
- Automated CI workflow executes build, lint, typecheck, and unit test checks on PRs.
- **Definition of Done**: Workflow file created, validated, and passing on pull requests.
- **Rollback / Recovery Considerations**: Delete workflow file if necessary.
---
### TASK-DOC-001
- **TASK-ID**: `TASK-DOC-001`
- **Title**: OpenAPI Documentation Synchronization & Automated Schema Export
- **Status**: `READY_FOR_IMPLEMENTATION`
- **Priority**: `P3`
- **Severity**: `MEDIUM`
- **Category**: `Documentation / API Specification Alignment`
- **Source Findings**: `DOC-001`
- **Objective**: Reconcile root `swagger.yml` with active NestJS controllers and configure automated OpenAPI spec generation via a non-listener CLI tool.
- **Root Cause Addressed**: `swagger.yml` documents obsolete `/login` and `/register` endpoints.
- **Current State**: `swagger.yml` out of sync with active backend auth routes.
- **Required Changes**:
1. Create non-listener CLI script `backend/scripts/generate-openapi.ts` instantiating NestJS application without calling `app.listen()`. Add `npm run docs:generate` script in `backend/package.json`.
2. Update root `swagger.yml` to accurately document `POST /api/auth/send-otp` and `POST /api/auth/verify-otp`.
- **Affected Files / Areas**:
- `swagger.yml`
- `backend/scripts/generate-openapi.ts` [NEW]
- `backend/package.json`
- **Implementation Approach**:
Create non-listener OpenAPI generator CLI script -> execute `npm run docs:generate` -> sync `swagger.yml`.
- **Dependencies**: None.
- **Blocked By**: None.
- **Risk Assessment**: LOW risk. Documentation only.
- **Testing Requirements**:
- Validate OpenAPI YAML syntax.
- **Validation Commands**:
- `cd backend && npm run docs:generate && git diff --exit-code ../swagger.yml`
- **Acceptance Criteria**:
- `swagger.yml` endpoints match active NestJS Auth and Settings controller routes 100%.
- `npm run docs:generate` completes without opening a live HTTP listening port.
- **Definition of Done**: `swagger.yml` updated, script configured, validation clean.
- **Rollback / Recovery Considerations**: Standard git revert.
---
### TASK-VERIFY-001
- **TASK-ID**: `TASK-VERIFY-001`
- **Title**: End-to-End Authentication, Authorization, Order, and Regression Verification
- **Status**: `BLOCKED_BY_DEPENDENCY`
- **Priority**: `P1`
- **Severity**: `INFO` (Verification Task)
- **Category**: `Verification / Automated Integration & E2E Suite`
- **Source Findings**: All 14 Verified Findings
- **Objective**: Execute a 7-domain behavior-oriented verification matrix across all 14 verified findings after implementation tasks complete.
- **Root Cause Addressed**: Cross-cutting audit verification ensuring no regressions were introduced and all 14 findings have been remediated.
- **Current State**: Post-remediation verification suite.
- **Required Changes**:
1. Create automated integration test suite in `backend/test/app-audit-verification.e2e-spec.ts`.
2. Assert 7-domain behavior-oriented verification matrix:
- **A. Unit Verification**: `BE-001` (`19.99 * 3 + 5.01 = 64.98`), `BE-002` (single batch query), `SEC-002` (`crypto.randomInt`), `TEST-001` (full green Jest suite).
- **B. Integration / E2E Verification**: `ARCH-001` (`send-otp` -> `verify-otp`), `SEC-003` (payload omits `code`), `ADM-001` (non-admin 403 vs admin 200).
- **C. Startup Smoke Verification**: `SEC-001` (process exits with code 1 when either `JWT_ACCESS_SECRET` or `JWT_REFRESH_SECRET` is omitted or < 32 chars).
- **D. Frontend Verification**: `FE-001` (`createBrowserRouter` admin navigation & lazy loading), `TS-001` (zero `any` types).
- **E. Build / Type / Lint Verification**: `TS-002` (`seed.ts` compiles), `TS-003` (`metrics.controller.ts` type-only `Response` import).
- **F. CI Verification**: `DEVOPS-001` (`.github/workflows/ci.yml` syntax & PR trigger).
- **G. Documentation Verification**: `DOC-001` (`npm run docs:generate && git diff --exit-code swagger.yml`).
- **Affected Files / Areas**:
- `backend/test/app-audit-verification.e2e-spec.ts`
- **Implementation Approach**:
Write automated integration test suite in `backend/test/app-audit-verification.e2e-spec.ts`.
- **Dependencies**: `TASK-SEC-001`, `TASK-SEC-002`, `TASK-SEC-003`, `TASK-FIN-001`, `TASK-BUILD-001`, `TASK-AUTH-001`.
- **Blocked By**: `TASK-AUTH-001`, `TASK-SEC-003`, `TASK-FIN-001`
- **Risk Assessment**: LOW risk. Verification script execution only.
- **Testing Requirements**:
- 7-Domain behavior-oriented E2E test suite execution.
- **Validation Commands**:
- `cd backend && npm run test:e2e`
- **Acceptance Criteria**:
- All 14 verified findings pass 7-domain verification assertions 100% green.
- Zero findings remaining in OPEN status.
- **Definition of Done**: Verification report generated, 100% pass rate confirmed.
- **Rollback / Recovery Considerations**: N/A.
---
## Product Decisions & Future Scope
1. **`DECISION-001` (SMS Gateway Provider Selection)**
- **Category**: `PRODUCT_DECISION`
- **Status**: `PENDING_PRODUCT_INPUT`
- **Description**: Selection of production SMS gateway provider for NestJS `AuthService.sendOtp`. Non-production environments strictly use stdout logger / mock dispatch interface.
2. **`DECISION-003` (Storefront vs Admin Sub-Application Architecture Roadmap)**
- **Category**: `FINALIZED_PRODUCT_DECISION`
- **Status**: `FINALIZED_PRODUCT_DECISION`
- **Decision Outcome**: The Admin Panel is a completely standalone, isolated application (React SPA) and will NOT be hosted within the main Storefront (Next.js SSR/SEO).
3. **`FUTURE_SCOPE` Items**:
- **`DECISION-002` (Live Payment Gateway Provider Selection)**: `FUTURE_SCOPE` Selection of merchant payment gateway provider (e.g. ZarinPal, IdPay, Shaparak) for wallet deposits and checkout. Excluded from core audit remediation backlog as no verified finding requires payment gateway implementation.