690517:1449 204 and 302 refactor #03
This commit is contained in:
+14
-11
@@ -1,6 +1,6 @@
|
||||
# `.agents/skills/` — LCBP3 Agent Skill Pack
|
||||
|
||||
**Version:** 1.8.9 | **Last Updated:** 2026-04-22 | **Total Skills:** 20
|
||||
**Version:** 1.9.0 | **Last Updated:** 2026-05-17 | **Total Skills:** 23
|
||||
|
||||
Agent skills for AI-assisted development in **Windsurf IDE** (and compatible agents: Codex CLI, opencode, Amp, Antigravity, AGENTS.md-aware tools).
|
||||
|
||||
@@ -16,12 +16,15 @@ Agent skills for AI-assisted development in **Windsurf IDE** (and compatible age
|
||||
├── README.md # (this file)
|
||||
├── nestjs-best-practices/ # Backend rules (40 rules across 10 categories)
|
||||
├── next-best-practices/ # Frontend rules (Next.js 15+)
|
||||
├── e2e-testing/ # Playwright E2E testing patterns (POM, flaky tests, CI/CD)
|
||||
├── verification-loop/ # Comprehensive verification (build, typecheck, lint, test, security)
|
||||
├── security-review/ # OWASP Top 10 + ADR compliance checklist
|
||||
└── speckit-*/ # 18 workflow skills (spec → plan → tasks → implement → …)
|
||||
```
|
||||
|
||||
Each skill directory contains:
|
||||
|
||||
- `SKILL.md` — frontmatter (`name`, `description`, `version: 1.8.9`, `scope`, `depends-on`, `handoffs`) + instructions
|
||||
- `SKILL.md` — frontmatter (`name`, `description`, `version: 1.9.0`, `scope`, `depends-on`, `handoffs`) + instructions
|
||||
- `templates/` _(optional)_ — artifact templates (spec/plan/tasks/checklist)
|
||||
- `rules/` _(nestjs only)_ — individual rule files grouped by prefix (`arch-`, `security-`, `db-`, etc.)
|
||||
|
||||
@@ -62,14 +65,14 @@ Use `/00-speckit.all` to run specify → clarify → plan → tasks → analyze
|
||||
|
||||
From repo root:
|
||||
|
||||
| Script | Purpose |
|
||||
| --- | --- |
|
||||
| `./.agents/scripts/bash/check-prerequisites.sh --json` | Emit `FEATURE_DIR` + `AVAILABLE_DOCS` for a feature branch |
|
||||
| `./.agents/scripts/bash/setup-plan.sh --json` | Emit `FEATURE_SPEC`, `IMPL_PLAN`, `SPECS_DIR`, `BRANCH` |
|
||||
| `./.agents/scripts/bash/update-agent-context.sh windsurf` | Append tech entries to `AGENTS.md` |
|
||||
| `./.agents/scripts/bash/audit-skills.sh` | Validate all `SKILL.md` frontmatter + presence |
|
||||
| `./.agents/scripts/bash/validate-versions.sh` | Version consistency check |
|
||||
| `./.agents/scripts/bash/sync-workflows.sh` | Verify every skill has a `.windsurf/workflows/*.md` wrapper |
|
||||
| Script | Purpose |
|
||||
| --------------------------------------------------------- | ----------------------------------------------------------- |
|
||||
| `./.agents/scripts/bash/check-prerequisites.sh --json` | Emit `FEATURE_DIR` + `AVAILABLE_DOCS` for a feature branch |
|
||||
| `./.agents/scripts/bash/setup-plan.sh --json` | Emit `FEATURE_SPEC`, `IMPL_PLAN`, `SPECS_DIR`, `BRANCH` |
|
||||
| `./.agents/scripts/bash/update-agent-context.sh windsurf` | Append tech entries to `AGENTS.md` |
|
||||
| `./.agents/scripts/bash/audit-skills.sh` | Validate all `SKILL.md` frontmatter + presence |
|
||||
| `./.agents/scripts/bash/validate-versions.sh` | Version consistency check |
|
||||
| `./.agents/scripts/bash/sync-workflows.sh` | Verify every skill has a `.windsurf/workflows/*.md` wrapper |
|
||||
|
||||
All scripts mirror to `.agents/scripts/powershell/*.ps1` for Windows.
|
||||
|
||||
@@ -92,7 +95,7 @@ See [`_LCBP3-CONTEXT.md`](./_LCBP3-CONTEXT.md) for the complete list.
|
||||
|
||||
To add a new skill:
|
||||
|
||||
1. Create `NAME/SKILL.md` with frontmatter: `name`, `description`, `version: 1.8.9`, `scope`, `depends-on`.
|
||||
1. Create `NAME/SKILL.md` with frontmatter: `name`, `description`, `version: 1.9.0`, `scope`, `depends-on`.
|
||||
2. Append an LCBP3 context reference pointing to `_LCBP3-CONTEXT.md`.
|
||||
3. Wrap with `.windsurf/workflows/NAME.md` so it becomes a slash command.
|
||||
4. Update [`skills.md`](./skills.md) dependency matrix.
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
## 🔴 Tier 1 Non-Negotiables
|
||||
|
||||
- **ADR-019 UUID:** `publicId: string` exposed directly — **no** `@Expose({ name: 'id' })` rename; **no** `parseInt`/`Number`/`+` on UUID; **no** `id ?? ''` fallback in frontend.
|
||||
- **ADR-009:** No TypeORM migrations — edit `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` or add a `deltas/*.sql` file.
|
||||
- **ADR-009:** No TypeORM migrations — edit `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql` or add a `deltas/*.sql` file.
|
||||
- **ADR-016 Security:** JWT + CASL 4-Level RBAC; `@UseGuards(JwtAuthGuard, CaslAbilityGuard)` on every mutation controller; `ThrottlerGuard` on auth; bcrypt 12 rounds; `Idempotency-Key` required on POST/PUT/PATCH.
|
||||
- **ADR-002 Document Numbering:** Redis Redlock + TypeORM `@VersionColumn` (double-lock). Never use application-side counter alone.
|
||||
- **ADR-008 Notifications:** BullMQ queue — never inline email/notification in a request thread.
|
||||
@@ -59,7 +59,7 @@
|
||||
| A plan | `.agents/skills/speckit-plan/templates/plan-template.md` + relevant ADRs |
|
||||
| Task breakdown | `.agents/skills/speckit-tasks/templates/tasks-template.md` + existing patterns in `specs/08-Tasks/` |
|
||||
| Acceptance criteria / UAT | `specs/01-Requirements/01-05-acceptance-criteria.md` |
|
||||
| Schema / table definition | `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` + `03-01-data-dictionary.md` |
|
||||
| Schema / table definition | `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql` + `03-01-data-dictionary.md` |
|
||||
| RBAC / permissions | `specs/03-Data-and-Storage/lcbp3-v1.8.0-seed-permissions.sql` + `01-02-01-rbac-matrix.md` |
|
||||
| Release / hotfix | `specs/04-Infrastructure-OPS/04-08-release-management-policy.md` |
|
||||
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
---
|
||||
name: e2e-testing
|
||||
description: Playwright E2E testing patterns, Page Object Model, configuration, CI/CD integration, artifact management, and flaky test strategies for LCBP3-DMS.
|
||||
version: 1.9.0
|
||||
scope: testing
|
||||
depends-on: []
|
||||
handoffs-to: [speckit-tester]
|
||||
user-invocable: true
|
||||
---
|
||||
|
||||
# E2E Testing Skill
|
||||
|
||||
Playwright E2E testing patterns adapted for LCBP3-DMS (NestJS + Next.js + MariaDB stack).
|
||||
|
||||
## LCBP3 Context
|
||||
|
||||
See [`_LCBP3-CONTEXT.md`](../_LCBP3-CONTEXT.md) for project-specific testing requirements:
|
||||
- Backend: Jest (Unit + Integration + E2E)
|
||||
- Frontend: Vitest (Unit) + Playwright (E2E)
|
||||
- E2E test location: `frontend/e2e/workflow-adr021.spec.ts`
|
||||
- Coverage goals: Backend 70%+, Business Logic 80%+
|
||||
|
||||
## When to Use
|
||||
|
||||
Invoke this skill when:
|
||||
- Creating new E2E tests for frontend features
|
||||
- Debugging flaky Playwright tests
|
||||
- Setting up CI/CD integration for E2E tests
|
||||
- Optimizing test performance and reliability
|
||||
- Implementing Page Object Model (POM) patterns
|
||||
|
||||
## Test File Organization
|
||||
|
||||
```
|
||||
frontend/
|
||||
├── e2e/
|
||||
│ ├── auth/
|
||||
│ │ ├── login.spec.ts
|
||||
│ │ └── logout.spec.ts
|
||||
│ ├── correspondence/
|
||||
│ │ ├── create.spec.ts
|
||||
│ │ └── workflow.spec.ts
|
||||
│ ├── transmittals/
|
||||
│ │ ├── create.spec.ts
|
||||
│ │ └── submit.spec.ts
|
||||
│ ├── circulation/
|
||||
│ │ ├── routing.spec.ts
|
||||
│ │ └── approval.spec.ts
|
||||
│ └── workflow-adr021.spec.ts # Existing ADR-021 integration test
|
||||
├── playwright.config.ts
|
||||
└── tests/
|
||||
└── fixtures/
|
||||
├── auth.ts
|
||||
└── data.ts
|
||||
```
|
||||
|
||||
## Page Object Model (POM)
|
||||
|
||||
```typescript
|
||||
// frontend/e2e/pages/CorrespondencePage.ts
|
||||
import { Page, Locator } from '@playwright/test'
|
||||
|
||||
export class CorrespondencePage {
|
||||
readonly page: Page
|
||||
readonly createButton: Locator
|
||||
readonly subjectInput: Locator
|
||||
readonly recipientSelect: Locator
|
||||
readonly submitButton: Locator
|
||||
readonly successMessage: Locator
|
||||
|
||||
constructor(page: Page) {
|
||||
this.page = page
|
||||
this.createButton = page.getByTestId('create-correspondence')
|
||||
this.subjectInput = page.getByTestId('subject-input')
|
||||
this.recipientSelect = page.getByTestId('recipient-select')
|
||||
this.submitButton = page.getByTestId('submit-button')
|
||||
this.successMessage = page.getByTestId('success-message')
|
||||
}
|
||||
|
||||
async goto() {
|
||||
await this.page.goto('/admin/doc-control/correspondences')
|
||||
await this.page.waitForLoadState('networkidle')
|
||||
}
|
||||
|
||||
async createCorrespondence(data: {
|
||||
subject: string
|
||||
recipientId: string
|
||||
}) {
|
||||
await this.createButton.click()
|
||||
await this.subjectInput.fill(data.subject)
|
||||
await this.recipientSelect.selectOption(data.recipientId)
|
||||
await this.submitButton.click()
|
||||
}
|
||||
|
||||
async verifySuccess() {
|
||||
await expect(this.successMessage).toBeVisible()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Test Structure
|
||||
|
||||
```typescript
|
||||
// frontend/e2e/correspondence/create.spec.ts
|
||||
import { test, expect } from '@playwright/test'
|
||||
import { CorrespondencePage } from '../pages/CorrespondencePage'
|
||||
|
||||
test.describe('Correspondence Creation', () => {
|
||||
let correspondencePage: CorrespondencePage
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
correspondencePage = new CorrespondencePage(page)
|
||||
await correspondencePage.goto()
|
||||
})
|
||||
|
||||
test('should create correspondence successfully', async ({ page }) => {
|
||||
await correspondencePage.createCorrespondence({
|
||||
subject: 'Test Correspondence',
|
||||
recipientId: 'test-recipient-id'
|
||||
})
|
||||
|
||||
await correspondencePage.verifySuccess()
|
||||
await page.screenshot({ path: 'artifacts/correspondence-created.png' })
|
||||
})
|
||||
|
||||
test('should validate required fields', async ({ page }) => {
|
||||
await correspondencePage.createButton.click()
|
||||
await correspondencePage.submitButton.click()
|
||||
|
||||
await expect(page.getByTestId('subject-error')).toBeVisible()
|
||||
await expect(page.getByTestId('recipient-error')).toBeVisible()
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## Playwright Configuration
|
||||
|
||||
```typescript
|
||||
// frontend/playwright.config.ts
|
||||
import { defineConfig, devices } from '@playwright/test'
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
fullyParallel: true,
|
||||
forbidOnly: !!process.env.CI,
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
workers: process.env.CI ? 1 : undefined,
|
||||
reporter: [
|
||||
['html', { outputFolder: 'playwright-report' }],
|
||||
['junit', { outputFile: 'playwright-results.xml' }],
|
||||
['json', { outputFile: 'playwright-results.json' }]
|
||||
],
|
||||
use: {
|
||||
baseURL: process.env.BASE_URL || 'http://localhost:3000',
|
||||
trace: 'on-first-retry',
|
||||
screenshot: 'only-on-failure',
|
||||
video: 'retain-on-failure',
|
||||
actionTimeout: 10000,
|
||||
navigationTimeout: 30000,
|
||||
},
|
||||
projects: [
|
||||
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
|
||||
],
|
||||
webServer: {
|
||||
command: 'pnpm dev',
|
||||
url: 'http://localhost:3000',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 120000,
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Flaky Test Patterns
|
||||
|
||||
### Quarantine
|
||||
|
||||
```typescript
|
||||
test('flaky: complex workflow', async ({ page }) => {
|
||||
test.fixme(true, 'Flaky - Issue #123')
|
||||
// test code...
|
||||
})
|
||||
|
||||
test('conditional skip', async ({ page }) => {
|
||||
test.skip(process.env.CI, 'Flaky in CI - Issue #123')
|
||||
// test code...
|
||||
})
|
||||
```
|
||||
|
||||
### Identify Flakiness
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npx playwright test e2e/correspondence/create.spec.ts --repeat-each=10
|
||||
npx playwright test e2e/correspondence/create.spec.ts --retries=3
|
||||
```
|
||||
|
||||
### Common Causes & Fixes
|
||||
|
||||
**Race conditions:**
|
||||
```typescript
|
||||
// Bad: assumes element is ready
|
||||
await page.click('[data-testid="submit-button"]')
|
||||
|
||||
// Good: auto-wait locator
|
||||
await page.locator('[data-testid="submit-button"]').click()
|
||||
```
|
||||
|
||||
**Network timing:**
|
||||
```typescript
|
||||
// Bad: arbitrary timeout
|
||||
await page.waitForTimeout(5000)
|
||||
|
||||
// Good: wait for specific condition
|
||||
await page.waitForResponse(resp =>
|
||||
resp.url().includes('/api/correspondences') && resp.status() === 201
|
||||
)
|
||||
```
|
||||
|
||||
**Animation timing:**
|
||||
```typescript
|
||||
// Bad: click during animation
|
||||
await page.click('[data-testid="menu-item"]')
|
||||
|
||||
// Good: wait for stability
|
||||
await page.locator('[data-testid="menu-item"]').waitFor({ state: 'visible' })
|
||||
await page.waitForLoadState('networkidle')
|
||||
await page.locator('[data-testid="menu-item"]').click()
|
||||
```
|
||||
|
||||
## Artifact Management
|
||||
|
||||
### Screenshots
|
||||
|
||||
```typescript
|
||||
await page.screenshot({ path: 'artifacts/after-login.png' })
|
||||
await page.screenshot({ path: 'artifacts/full-page.png', fullPage: true })
|
||||
await page.locator('[data-testid="workflow-banner"]').screenshot({
|
||||
path: 'artifacts/workflow-banner.png'
|
||||
})
|
||||
```
|
||||
|
||||
### Traces
|
||||
|
||||
```typescript
|
||||
// In playwright.config.ts
|
||||
use: {
|
||||
trace: 'on-first-retry'
|
||||
}
|
||||
|
||||
// View trace
|
||||
npx playwright show-trace trace.zip
|
||||
```
|
||||
|
||||
### Video
|
||||
|
||||
```typescript
|
||||
// In playwright.config.ts
|
||||
use: {
|
||||
video: 'retain-on-failure',
|
||||
videosPath: 'artifacts/videos/'
|
||||
}
|
||||
```
|
||||
|
||||
## CI/CD Integration
|
||||
|
||||
```yaml
|
||||
# .github/workflows/e2e.yml
|
||||
name: E2E Tests
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
- run: pnpm install
|
||||
- run: cd frontend && npx playwright install --with-deps
|
||||
- run: cd frontend && npx playwright test
|
||||
env:
|
||||
BASE_URL: ${{ vars.STAGING_URL }}
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: playwright-report
|
||||
path: frontend/playwright-report/
|
||||
retention-days: 30
|
||||
```
|
||||
|
||||
## Test Report Template
|
||||
|
||||
```markdown
|
||||
# E2E Test Report
|
||||
|
||||
**Date:** YYYY-MM-DD HH:MM
|
||||
**Duration:** Xm Ys
|
||||
**Status:** PASSING / FAILING
|
||||
|
||||
## Summary
|
||||
- Total: X | Passed: Y (Z%) | Failed: A | Flaky: B | Skipped: C
|
||||
|
||||
## Failed Tests
|
||||
|
||||
### correspondence-create
|
||||
**File:** `frontend/e2e/correspondence/create.spec.ts:45`
|
||||
**Error:** Expected element to be visible
|
||||
**Screenshot:** artifacts/failed.png
|
||||
**Recommended Fix:** Add waitForLoadState after form submission
|
||||
|
||||
## Artifacts
|
||||
- HTML Report: frontend/playwright-report/index.html
|
||||
- Screenshots: frontend/artifacts/*.png
|
||||
- Videos: frontend/artifacts/videos/*.webm
|
||||
- Traces: frontend/artifacts/*.zip
|
||||
```
|
||||
|
||||
## Critical Flow Testing
|
||||
|
||||
```typescript
|
||||
// frontend/e2e/workflow/adr021.spec.ts
|
||||
test('workflow: correspondence → rfa → approval', async ({ page }) => {
|
||||
// Create correspondence
|
||||
await createCorrespondence(page)
|
||||
await expect(page.getByTestId('correspondence-created')).toBeVisible()
|
||||
|
||||
// Submit for RFA
|
||||
await page.getByTestId('submit-rfa').click()
|
||||
await expect(page.getByTestId('rfa-submitted')).toBeVisible()
|
||||
|
||||
// Approve RFA
|
||||
await page.goto('/admin/doc-control/rfa/123')
|
||||
await page.getByTestId('approve-button').click()
|
||||
await expect(page.getByTestId('approval-success')).toBeVisible()
|
||||
|
||||
// Verify workflow state
|
||||
await expect(page.getByTestId('workflow-state')).toContainText('APPROVED')
|
||||
})
|
||||
```
|
||||
|
||||
## LCBP3-Specific Considerations
|
||||
|
||||
- **UUID Handling:** Use `publicId` (string UUID) in E2E tests, never `parseInt()` (ADR-019)
|
||||
- **Authentication:** Mock auth tokens for E2E tests to avoid real auth flows
|
||||
- **Workflow States:** Test ADR-021 workflow transitions (DRAFT → PENDING → APPROVED)
|
||||
- **i18n:** Test with Thai language to verify i18n key resolution
|
||||
- **RBAC:** Test different user roles (admin, user, reviewer) for permission checks
|
||||
|
||||
## References
|
||||
|
||||
- LCBP3 Testing Strategy: `specs/05-Engineering-Guidelines/05-04-testing-strategy.md`
|
||||
- ADR-021 Workflow Context: `specs/06-Decision-Records/ADR-021-workflow-context.md`
|
||||
- Existing E2E test: `frontend/e2e/workflow-adr021.spec.ts`
|
||||
@@ -126,7 +126,7 @@ These rules override general NestJS best practices for the NAP-DMS project:
|
||||
### ADR-009: No TypeORM Migrations
|
||||
|
||||
- **ห้ามสร้างไฟล์ migration ของ TypeORM**
|
||||
- แก้ไข schema โดยตรงที่: `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql`
|
||||
- แก้ไข schema โดยตรงที่: `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql`
|
||||
- ใช้ n8n workflow สำหรับ data migration ถ้าจำเป็น
|
||||
|
||||
### ADR-019: Hybrid Identifier Strategy (CRITICAL — March 2026 Pattern)
|
||||
|
||||
@@ -0,0 +1,517 @@
|
||||
---
|
||||
name: security-review
|
||||
description: Comprehensive security review for LCBP3-DMS with OWASP Top 10 checklist, ADR compliance, and automated security testing patterns.
|
||||
version: 1.9.0
|
||||
scope: security
|
||||
depends-on: []
|
||||
handoffs-to: [speckit-reviewer, speckit-security-audit]
|
||||
user-invocable: true
|
||||
---
|
||||
|
||||
# Security Review Skill
|
||||
|
||||
Comprehensive security review for LCBP3-DMS ensuring all code follows security best practices and identifies potential vulnerabilities.
|
||||
|
||||
## LCBP3 Context
|
||||
|
||||
See [`_LCBP3-CONTEXT.md`](../_LCBP3-CONTEXT.md) for project-specific security requirements:
|
||||
- **ADR-016**: Security & Authentication (JWT, CASL, RBAC, file upload)
|
||||
- **ADR-018**: AI Boundary (Ollama on Admin Desktop only, no direct DB/storage access)
|
||||
- **ADR-019**: UUID Strategy (no parseInt/Number/+ on UUID)
|
||||
- **ADR-023**: Unified AI Architecture (AI via DMS API only)
|
||||
- **ADR-007**: Error Handling (layered error classification)
|
||||
|
||||
## When to Activate
|
||||
|
||||
Invoke this skill:
|
||||
- Implementing authentication or authorization
|
||||
- Handling user input or file uploads
|
||||
- Creating new API endpoints
|
||||
- Working with secrets or credentials
|
||||
- Integrating AI features (Ollama/Qdrant)
|
||||
- Storing or transmitting sensitive data
|
||||
- Integrating third-party APIs
|
||||
|
||||
## Security Checklist
|
||||
|
||||
### 1. Secrets Management
|
||||
|
||||
#### FAIL: NEVER Do This
|
||||
```typescript
|
||||
const apiKey = "sk-proj-xxxxx" // Hardcoded secret
|
||||
const dbPassword = "password123" // In source code
|
||||
```
|
||||
|
||||
#### PASS: ALWAYS Do This
|
||||
```typescript
|
||||
const apiKey = process.env.OPENAI_API_KEY
|
||||
const dbUrl = process.env.DATABASE_URL
|
||||
|
||||
// Verify secrets exist
|
||||
if (!apiKey) {
|
||||
throw new Error('OPENAI_API_KEY not configured')
|
||||
}
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] No hardcoded API keys, tokens, or passwords
|
||||
- [ ] All secrets in environment variables
|
||||
- [ ] `.env.local` in .gitignore
|
||||
- [ ] No secrets in git history
|
||||
- [ ] Production secrets in QNAP docker-compose environment section (not .env files)
|
||||
|
||||
### 2. Input Validation
|
||||
|
||||
#### Always Validate User Input
|
||||
```typescript
|
||||
import { z } from 'zod'
|
||||
|
||||
// Define validation schema
|
||||
const CreateCorrespondenceSchema = z.object({
|
||||
subject: z.string().min(1).max(500),
|
||||
recipientId: z.string().uuid(),
|
||||
typeCode: z.string().min(1).max(50)
|
||||
})
|
||||
|
||||
// Validate before processing
|
||||
export async function createCorrespondence(input: unknown) {
|
||||
try {
|
||||
const validated = CreateCorrespondenceSchema.parse(input)
|
||||
return await correspondenceService.create(validated)
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
throw new BadRequestException(error.errors)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### File Upload Validation (ADR-016)
|
||||
```typescript
|
||||
function validateFileUpload(file: Express.Multer.File) {
|
||||
// Size check (50MB max per ADR-016)
|
||||
const maxSize = 50 * 1024 * 1024
|
||||
if (file.size > maxSize) {
|
||||
throw new BadRequestException('File too large (max 50MB)')
|
||||
}
|
||||
|
||||
// Type check (whitelist: PDF, DWG, DOCX, XLSX, ZIP)
|
||||
const allowedTypes = [
|
||||
'application/pdf',
|
||||
'application/vnd.dwg',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/zip'
|
||||
]
|
||||
if (!allowedTypes.includes(file.mimetype)) {
|
||||
throw new BadRequestException('Invalid file type')
|
||||
}
|
||||
|
||||
// Extension check
|
||||
const allowedExtensions = ['.pdf', '.dwg', '.docx', '.xlsx', '.zip']
|
||||
const extension = path.extname(file.originalname).toLowerCase()
|
||||
if (!allowedExtensions.includes(extension)) {
|
||||
throw new BadRequestException('Invalid file extension')
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] All user inputs validated with Zod (frontend) + class-validator (backend)
|
||||
- [ ] File uploads restricted (50MB max, whitelist types)
|
||||
- [ ] No direct use of user input in queries
|
||||
- [ ] Whitelist validation (not blacklist)
|
||||
- [ ] Error messages don't leak sensitive info
|
||||
|
||||
### 3. SQL Injection Prevention
|
||||
|
||||
#### FAIL: NEVER Concatenate SQL
|
||||
```typescript
|
||||
// DANGEROUS - SQL Injection vulnerability
|
||||
const query = `SELECT * FROM correspondences WHERE uuid = '${correspondenceUuid}'`
|
||||
await this.connection.query(query)
|
||||
```
|
||||
|
||||
#### PASS: ALWAYS Use TypeORM Parameterized Queries
|
||||
```typescript
|
||||
// Safe - TypeORM parameterized query
|
||||
const correspondence = await this.correspondenceRepository.findOne({
|
||||
where: { publicId: correspondenceUuid }
|
||||
})
|
||||
|
||||
// Or with QueryBuilder
|
||||
const result = await this.correspondenceRepository
|
||||
.createQueryBuilder('c')
|
||||
.where('c.publicId = :uuid', { uuid: correspondenceUuid })
|
||||
.getOne()
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] All database queries use TypeORM parameterized queries
|
||||
- [ ] No string concatenation in SQL
|
||||
- [ ] TypeORM query builder used correctly
|
||||
- [ ] Schema verified before writing queries (ADR-009)
|
||||
|
||||
### 4. Authentication & Authorization (ADR-016)
|
||||
|
||||
#### JWT Token Handling
|
||||
```typescript
|
||||
// FAIL: WRONG: localStorage (vulnerable to XSS)
|
||||
localStorage.setItem('token', token)
|
||||
|
||||
// PASS: CORRECT: httpOnly cookies
|
||||
response.setHeader('Set-Cookie',
|
||||
`token=${token}; HttpOnly; Secure; SameSite=Strict; Max-Age=3600`
|
||||
)
|
||||
```
|
||||
|
||||
#### Authorization Checks (CASL)
|
||||
```typescript
|
||||
// Controller with CASL guard
|
||||
@Post()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard, AbilitiesGuard)
|
||||
@CheckAbilities({ action: 'create', subject: 'Correspondence' })
|
||||
async create(@Body() dto: CreateCorrespondenceDto, @Request() req) {
|
||||
// Service logic
|
||||
}
|
||||
```
|
||||
|
||||
#### RBAC Matrix (ADR-016)
|
||||
- [ ] 4-Level RBAC matrix implemented (Admin, Manager, User, Viewer)
|
||||
- [ ] CASL AbilityFactory configured with correct permissions
|
||||
- [ ] JwtAuthGuard on all protected routes
|
||||
- [ ] RolesGuard for role-based access
|
||||
- [ ] AuditLogInterceptor on all mutation endpoints
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] Tokens stored in httpOnly cookies (not localStorage)
|
||||
- [ ] Authorization checks before sensitive operations
|
||||
- [ ] CASL abilities configured correctly
|
||||
- [ ] Role-based access control implemented
|
||||
- [ ] Session management secure
|
||||
|
||||
### 5. XSS Prevention
|
||||
|
||||
#### Sanitize HTML
|
||||
```typescript
|
||||
import DOMPurify from 'isomorphic-dompurify'
|
||||
|
||||
// ALWAYS sanitize user-provided HTML
|
||||
function renderUserContent(html: string) {
|
||||
const clean = DOMPurify.sanitize(html, {
|
||||
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'],
|
||||
ALLOWED_ATTR: []
|
||||
})
|
||||
return <div dangerouslySetInnerHTML={{ __html: clean }} />
|
||||
}
|
||||
```
|
||||
|
||||
#### Content Security Policy (Next.js)
|
||||
```typescript
|
||||
// next.config.js
|
||||
const securityHeaders = [
|
||||
{
|
||||
key: 'Content-Security-Policy',
|
||||
value: `
|
||||
default-src 'self';
|
||||
script-src 'self' 'unsafe-eval' 'unsafe-inline';
|
||||
style-src 'self' 'unsafe-inline';
|
||||
img-src 'self' data: https:;
|
||||
font-src 'self';
|
||||
connect-src 'self' http://localhost:3001 https://192.168.10.8;
|
||||
`.replace(/\s{2,}/g, ' ').trim()
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] User-provided HTML sanitized
|
||||
- [ ] CSP headers configured
|
||||
- [ ] No unvalidated dynamic content rendering
|
||||
- [ ] React's built-in XSS protection used
|
||||
|
||||
### 6. CSRF Protection
|
||||
|
||||
#### CSRF Tokens
|
||||
```typescript
|
||||
import { csrf } from '@/lib/csrf'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const token = request.headers.get('X-CSRF-Token')
|
||||
|
||||
if (!csrf.verify(token)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid CSRF token' },
|
||||
{ status: 403 }
|
||||
)
|
||||
}
|
||||
|
||||
// Process request
|
||||
}
|
||||
```
|
||||
|
||||
#### SameSite Cookies
|
||||
```typescript
|
||||
response.setHeader('Set-Cookie',
|
||||
`session=${sessionId}; HttpOnly; Secure; SameSite=Strict`
|
||||
)
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] CSRF tokens on state-changing operations
|
||||
- [ ] SameSite=Strict on all cookies
|
||||
- [ ] Double-submit cookie pattern implemented
|
||||
|
||||
### 7. Rate Limiting (ADR-016)
|
||||
|
||||
#### API Rate Limiting
|
||||
```typescript
|
||||
import { ThrottlerGuard } from '@nestjs/throttler'
|
||||
|
||||
// Apply to auth endpoints
|
||||
@UseGuards(ThrottlerGuard)
|
||||
@Throttle({ default: { limit: 10, ttl: 60000 } })
|
||||
async login(@Body() dto: LoginDto) {
|
||||
// Login logic
|
||||
}
|
||||
```
|
||||
|
||||
#### Expensive Operations
|
||||
```typescript
|
||||
// Aggressive rate limiting for AI endpoints
|
||||
@Throttle({ default: { limit: 5, ttl: 60000 } })
|
||||
async extractMetadata(@Body() dto: ExtractMetadataDto) {
|
||||
// AI extraction logic
|
||||
}
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] Rate limiting on all auth endpoints (ADR-016)
|
||||
- [ ] Rate limiting on AI endpoints (ADR-018/023)
|
||||
- [ ] IP-based rate limiting
|
||||
- [ ] User-based rate limiting (authenticated)
|
||||
|
||||
### 8. Sensitive Data Exposure
|
||||
|
||||
#### Logging
|
||||
```typescript
|
||||
// FAIL: WRONG: Logging sensitive data
|
||||
this.logger.log('User login:', { email, password })
|
||||
this.logger.log('Payment:', { cardNumber, cvv })
|
||||
|
||||
// PASS: CORRECT: Redact sensitive data
|
||||
this.logger.log('User login:', { email, userId })
|
||||
this.logger.log('Payment:', { last4: card.last4, userId })
|
||||
```
|
||||
|
||||
#### Error Messages (ADR-007)
|
||||
```typescript
|
||||
// FAIL: WRONG: Exposing internal details
|
||||
catch (error) {
|
||||
return { error: error.message, stack: error.stack }
|
||||
}
|
||||
|
||||
// PASS: CORRECT: Generic error messages
|
||||
catch (error) {
|
||||
this.logger.error('Internal error:', error)
|
||||
throw new BadRequestException('An error occurred. Please try again.')
|
||||
}
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] No passwords, tokens, or secrets in logs
|
||||
- [ ] Error messages generic for users
|
||||
- [ ] Detailed errors only in server logs
|
||||
- [ ] No stack traces exposed to users
|
||||
|
||||
### 9. AI Boundary Enforcement (ADR-018/023)
|
||||
|
||||
#### FAIL: NEVER Do This
|
||||
```typescript
|
||||
// Direct AI access - FORBIDDEN
|
||||
import ollama from 'ollama'
|
||||
const response = await ollama.chat({ model: 'gemma4', messages })
|
||||
|
||||
// Direct Qdrant access - FORBIDDEN
|
||||
import { QdrantClient } from '@qdrant/js-client-rest'
|
||||
const client = new QdrantClient({ url: 'http://localhost:6333' })
|
||||
```
|
||||
|
||||
#### PASS: ALWAYS Do This
|
||||
```typescript
|
||||
// AI via DMS API only
|
||||
const response = await fetch('http://localhost:3001/api/ai/extract-metadata', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ documentId })
|
||||
})
|
||||
|
||||
// Qdrant via DMS API only
|
||||
const response = await fetch('http://localhost:3001/api/ai/search', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ query, projectPublicId })
|
||||
})
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] AI processing on Admin Desktop only (Desk-5439)
|
||||
- [ ] No direct Ollama calls from backend/frontend
|
||||
- [ ] No direct Qdrant calls from backend/frontend
|
||||
- [ ] All AI interactions via DMS API endpoints
|
||||
- [ ] AI audit logging implemented (ADR-020)
|
||||
- [ ] Human-in-the-loop validation for AI outputs
|
||||
|
||||
### 10. UUID Handling (ADR-019)
|
||||
|
||||
#### FAIL: NEVER Do This
|
||||
```typescript
|
||||
// parseInt on UUID - FORBIDDEN
|
||||
const projectId = parseInt(projectUuid) // "0195..." → 19 (WRONG!)
|
||||
|
||||
// Number on UUID - FORBIDDEN
|
||||
const projectId = Number(projectUuid)
|
||||
|
||||
// + operator on UUID - FORBIDDEN
|
||||
const projectId = +projectUuid
|
||||
|
||||
// id ?? '' fallback - FORBIDDEN
|
||||
const value = c.publicId ?? c.id ?? ''
|
||||
```
|
||||
|
||||
#### PASS: ALWAYS Do This
|
||||
```typescript
|
||||
// Use UUID string directly
|
||||
const projectId = projectUuid // "019505a1-7c3e-7000-8000-abc123def456"
|
||||
|
||||
// Backend: findOneByUuid returns entity with publicId
|
||||
const project = await this.projectService.findOneByUuid(projectUuid)
|
||||
const projectId = project.id // Internal INT for DB operations
|
||||
|
||||
// Frontend: use publicId only
|
||||
interface ProjectOption {
|
||||
publicId?: string; // No uuid fallback
|
||||
projectName?: string;
|
||||
}
|
||||
const value = c.publicId // "019505a1-7c3e-7000-8000-abc123def456"
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] No `parseInt()` on UUID values
|
||||
- [ ] No `Number()` on UUID values
|
||||
- [ ] No `+` operator on UUID values
|
||||
- [ ] No `id ?? ''` fallback patterns
|
||||
- [ ] Use `publicId` (string UUID) in API responses
|
||||
- [ ] Internal INT `id` marked with `@Exclude()` in entities
|
||||
|
||||
### 11. Dependency Security
|
||||
|
||||
#### Regular Updates
|
||||
```bash
|
||||
# Check for vulnerabilities
|
||||
pnpm audit
|
||||
|
||||
# Fix automatically fixable issues
|
||||
pnpm audit fix
|
||||
|
||||
# Update dependencies
|
||||
pnpm update
|
||||
|
||||
# Check for outdated packages
|
||||
pnpm outdated
|
||||
```
|
||||
|
||||
#### Lock Files
|
||||
```bash
|
||||
# ALWAYS commit lock files
|
||||
git add pnpm-lock.yaml
|
||||
|
||||
# Use in CI/CD for reproducible builds
|
||||
pnpm install --frozen-lockfile
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] Dependencies up to date
|
||||
- [ ] No known vulnerabilities (pnpm audit clean)
|
||||
- [ ] Lock files committed
|
||||
- [ ] Regular security updates
|
||||
|
||||
## Security Testing
|
||||
|
||||
### Automated Security Tests
|
||||
|
||||
```typescript
|
||||
// Test authentication
|
||||
test('requires authentication', async () => {
|
||||
const response = await fetch('/api/correspondences')
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
// Test authorization
|
||||
test('requires admin role', async () => {
|
||||
const response = await fetch('/api/admin/users', {
|
||||
headers: { Authorization: `Bearer ${userToken}` }
|
||||
})
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
|
||||
// Test input validation
|
||||
test('rejects invalid input', async () => {
|
||||
const response = await fetch('/api/correspondences', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ subject: '', recipientId: 'invalid' })
|
||||
})
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
// Test rate limiting
|
||||
test('enforces rate limits', async () => {
|
||||
const requests = Array(11).fill(null).map(() =>
|
||||
fetch('/api/auth/login', { method: 'POST' })
|
||||
)
|
||||
|
||||
const responses = await Promise.all(requests)
|
||||
const tooManyRequests = responses.filter(r => r.status === 429)
|
||||
|
||||
expect(tooManyRequests.length).toBeGreaterThan(0)
|
||||
})
|
||||
```
|
||||
|
||||
## Pre-Deployment Security Checklist
|
||||
|
||||
Before ANY production deployment:
|
||||
|
||||
- [ ] **Secrets**: No hardcoded secrets, all in env vars
|
||||
- [ ] **Input Validation**: All user inputs validated (Zod + class-validator)
|
||||
- [ ] **SQL Injection**: All queries parameterized (TypeORM)
|
||||
- [ ] **XSS**: User content sanitized
|
||||
- [ ] **CSRF**: Protection enabled
|
||||
- [ ] **Authentication**: Proper token handling (httpOnly cookies)
|
||||
- [ ] **Authorization**: RBAC + CASL checks in place
|
||||
- [ ] **Rate Limiting**: Enabled on auth and AI endpoints
|
||||
- [ ] **HTTPS**: Enforced in production
|
||||
- [ ] **Security Headers**: CSP, X-Frame-Options configured
|
||||
- [ ] **Error Handling**: No sensitive data in errors (ADR-007)
|
||||
- [ ] **Logging**: No sensitive data logged
|
||||
- [ ] **Dependencies**: Up to date, no vulnerabilities
|
||||
- [ ] **UUID Handling**: No parseInt/Number/+ on UUID (ADR-019)
|
||||
- [ ] **AI Boundary**: AI via DMS API only (ADR-018/023)
|
||||
- [ ] **File Uploads**: Validated (50MB max, whitelist types)
|
||||
- [ ] **AI Audit**: All AI interactions logged (ADR-020)
|
||||
|
||||
## Resources
|
||||
|
||||
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
|
||||
- [NestJS Security](https://docs.nestjs.com/security)
|
||||
- [Next.js Security](https://nextjs.org/docs/security)
|
||||
- [ADR-016 Security Authentication](../../specs/06-Decision-Records/ADR-016-security-authentication.md)
|
||||
- [ADR-018 AI Boundary](../../specs/06-Decision-Records/ADR-018-ai-boundary.md)
|
||||
- [ADR-019 UUID Strategy](../../specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md)
|
||||
- [ADR-023 AI Architecture](../../specs/06-Decision-Records/ADR-023-unified-ai-architecture.md)
|
||||
|
||||
---
|
||||
|
||||
**Remember**: Security is not optional. One vulnerability can compromise the entire platform. When in doubt, err on the side of caution.
|
||||
+30
-27
@@ -1,8 +1,8 @@
|
||||
# 🧠 NAP-DMS Agent Skills (v1.8.9)
|
||||
# 🧠 NAP-DMS Agent Skills (v1.9.0)
|
||||
|
||||
ไฟล์นี้กำหนดทักษะและความสามารถเฉพาะทางของ Document Intelligence Engine สำหรับโครงการ LCBP3 v1.8.9 เพื่อรักษามาตรฐานสูงสุดด้าน Security และ Data Integrity
|
||||
ไฟล์นี้กำหนดทักษะและความสามารถเฉพาะทางของ Document Intelligence Engine สำหรับโครงการ LCBP3 v1.9.0 เพื่อรักษามาตรฐานสูงสุดด้าน Security และ Data Integrity
|
||||
|
||||
**Status**: Production Ready | **Last Updated**: 2026-04-22 | **Total Skills**: 20
|
||||
**Status**: Production Ready | **Last Updated**: 2026-05-17 | **Total Skills**: 23
|
||||
|
||||
> 📌 Shared context for all speckit-\* skills: see [`_LCBP3-CONTEXT.md`](./_LCBP3-CONTEXT.md).
|
||||
|
||||
@@ -57,28 +57,31 @@
|
||||
|
||||
## 🔄 Skill Dependency Matrix
|
||||
|
||||
| Skill | Dependencies | Handoffs To | Notes |
|
||||
| -------------------------- | -------------------- | -------------------------------- | ----------------------------- |
|
||||
| **speckit-constitution** | None | speckit-specify | Project governance foundation |
|
||||
| **speckit-specify** | speckit-constitution | speckit-clarify | Feature specification |
|
||||
| **speckit-clarify** | speckit-specify | speckit-plan | Resolve ambiguities |
|
||||
| **speckit-plan** | speckit-clarify | speckit-tasks, speckit-checklist | Technical design |
|
||||
| **speckit-tasks** | speckit-plan | speckit-implement | Task breakdown |
|
||||
| **speckit-implement** | speckit-tasks | speckit-checker | Code implementation |
|
||||
| **speckit-checker** | speckit-implement | speckit-tester | Static analysis |
|
||||
| **speckit-tester** | speckit-checker | speckit-reviewer | Test execution |
|
||||
| **speckit-reviewer** | speckit-tester | speckit-validate | Code review |
|
||||
| **speckit-validate** | speckit-reviewer | None | Requirements validation |
|
||||
| **speckit-analyze** | speckit-tasks | None | Cross-artifact consistency |
|
||||
| **speckit-migrate** | None | speckit-plan | Legacy code import |
|
||||
| **speckit-quizme** | speckit-specify | speckit-plan | Logic validation |
|
||||
| **speckit-diff** | None | speckit-plan | Version comparison |
|
||||
| **speckit-status** | None | None | Progress tracking |
|
||||
| **speckit-taskstoissues** | speckit-tasks | None | Issue sync |
|
||||
| **speckit-checklist** | speckit-plan | None | Requirements validation |
|
||||
| **nestjs-best-practices** | None | speckit-implement | Backend patterns |
|
||||
| **next-best-practices** | None | speckit-implement | Frontend patterns |
|
||||
| **speckit-security-audit** | None | speckit-reviewer | Security validation |
|
||||
| Skill | Dependencies | Handoffs To | Notes |
|
||||
| -------------------------- | -------------------- | ---------------------------------------- | ----------------------------- |
|
||||
| **speckit-constitution** | None | speckit-specify | Project governance foundation |
|
||||
| **speckit-specify** | speckit-constitution | speckit-clarify | Feature specification |
|
||||
| **speckit-clarify** | speckit-specify | speckit-plan | Resolve ambiguities |
|
||||
| **speckit-plan** | speckit-clarify | speckit-tasks, speckit-checklist | Technical design |
|
||||
| **speckit-tasks** | speckit-plan | speckit-implement | Task breakdown |
|
||||
| **speckit-implement** | speckit-tasks | speckit-checker | Code implementation |
|
||||
| **speckit-checker** | speckit-implement | speckit-tester | Static analysis |
|
||||
| **speckit-tester** | speckit-checker | speckit-reviewer | Test execution |
|
||||
| **speckit-reviewer** | speckit-tester | speckit-validate | Code review |
|
||||
| **speckit-validate** | speckit-reviewer | None | Requirements validation |
|
||||
| **speckit-analyze** | speckit-tasks | None | Cross-artifact consistency |
|
||||
| **speckit-migrate** | None | speckit-plan | Legacy code import |
|
||||
| **speckit-quizme** | speckit-specify | speckit-plan | Logic validation |
|
||||
| **speckit-diff** | None | speckit-plan | Version comparison |
|
||||
| **speckit-status** | None | None | Progress tracking |
|
||||
| **speckit-taskstoissues** | speckit-tasks | None | Issue sync |
|
||||
| **speckit-checklist** | speckit-plan | None | Requirements validation |
|
||||
| **nestjs-best-practices** | None | speckit-implement | Backend patterns |
|
||||
| **next-best-practices** | None | speckit-implement | Frontend patterns |
|
||||
| **speckit-security-audit** | None | speckit-reviewer | Security validation |
|
||||
| **e2e-testing** | None | speckit-tester | Playwright E2E patterns |
|
||||
| **verification-loop** | None | speckit-checker, speckit-tester | Comprehensive verification |
|
||||
| **security-review** | None | speckit-reviewer, speckit-security-audit | OWASP Top 10 + ADR compliance |
|
||||
|
||||
---
|
||||
|
||||
@@ -96,8 +99,8 @@
|
||||
|
||||
### Health Metrics
|
||||
|
||||
- **Total Skills**: 20 implemented
|
||||
- **Version Alignment**: v1.8.9 across all skills
|
||||
- **Total Skills**: 23 implemented
|
||||
- **Version Alignment**: v1.9.0 across all skills
|
||||
- **Template Coverage**: 100% for skills requiring templates
|
||||
- **Documentation**: Complete front matter + shared `_LCBP3-CONTEXT.md` appendix
|
||||
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
---
|
||||
name: verification-loop
|
||||
description: A comprehensive verification system for LCBP3-DMS development sessions with build, type check, lint, test, security scan, and diff review phases.
|
||||
version: 1.9.0
|
||||
scope: verification
|
||||
depends-on: []
|
||||
handoffs-to: [speckit-checker, speckit-tester]
|
||||
user-invocable: true
|
||||
---
|
||||
|
||||
# Verification Loop Skill
|
||||
|
||||
A comprehensive verification system for LCBP3-DMS development sessions.
|
||||
|
||||
## LCBP3 Context
|
||||
|
||||
See [`_LCBP3-CONTEXT.md`](../_LCBP3-CONTEXT.md) for project-specific verification requirements:
|
||||
- Backend: NestJS with TypeScript strict mode
|
||||
- Frontend: Next.js with TypeScript strict mode
|
||||
- Package manager: pnpm
|
||||
- Coverage goals: Backend 70%+, Business Logic 80%+
|
||||
- Security: ADR-016, ADR-018, ADR-019, ADR-023 compliance
|
||||
|
||||
## When to Use
|
||||
|
||||
Invoke this skill:
|
||||
- After completing a feature or significant code change
|
||||
- Before creating a PR
|
||||
- When you want to ensure quality gates pass
|
||||
- After refactoring
|
||||
- Before deploying to staging/production
|
||||
|
||||
## Verification Phases
|
||||
|
||||
### Phase 1: Build Verification
|
||||
|
||||
```bash
|
||||
# Backend build
|
||||
cd backend
|
||||
pnpm build 2>&1 | tail -20
|
||||
|
||||
# Frontend build
|
||||
cd frontend
|
||||
pnpm build 2>&1 | tail -20
|
||||
```
|
||||
|
||||
If build fails, STOP and fix before continuing.
|
||||
|
||||
### Phase 2: Type Check
|
||||
|
||||
```bash
|
||||
# Backend TypeScript
|
||||
cd backend
|
||||
pnpm typecheck 2>&1 | head -30
|
||||
|
||||
# Frontend TypeScript
|
||||
cd frontend
|
||||
pnpm typecheck 2>&1 | head -30
|
||||
```
|
||||
|
||||
Report all type errors. Fix critical ones before continuing.
|
||||
|
||||
### Phase 3: Lint Check
|
||||
|
||||
```bash
|
||||
# Backend lint
|
||||
cd backend
|
||||
pnpm lint 2>&1 | head -30
|
||||
|
||||
# Frontend lint
|
||||
cd frontend
|
||||
pnpm lint 2>&1 | head -30
|
||||
```
|
||||
|
||||
### Phase 4: Test Suite
|
||||
|
||||
```bash
|
||||
# Backend tests with coverage
|
||||
cd backend
|
||||
pnpm test -- --coverage 2>&1 | tail -50
|
||||
|
||||
# Frontend unit tests
|
||||
cd frontend
|
||||
pnpm test 2>&1 | tail -50
|
||||
|
||||
# Frontend E2E tests (if applicable)
|
||||
cd frontend
|
||||
npx playwright test 2>&1 | tail -50
|
||||
```
|
||||
|
||||
Report:
|
||||
- Total tests: X
|
||||
- Passed: X
|
||||
- Failed: X
|
||||
- Coverage: X%
|
||||
|
||||
### Phase 5: Security Scan
|
||||
|
||||
```bash
|
||||
# Check for hardcoded secrets
|
||||
grep -rn "sk-" --include="*.ts" --include="*.tsx" . 2>/dev/null | head -10
|
||||
grep -rn "api_key" --include="*.ts" --include="*.tsx" . 2>/dev/null | head -10
|
||||
grep -rn "password" --include="*.ts" --include="*.tsx" . 2>/dev/null | head -10
|
||||
|
||||
# Check for console.log (forbidden in committed code)
|
||||
grep -rn "console.log" --include="*.ts" --include="*.tsx" backend/src/ frontend/src/ 2>/dev/null | head -10
|
||||
|
||||
# Check for any types (forbidden)
|
||||
grep -rn ": any" --include="*.ts" --include="*.tsx" backend/src/ frontend/src/ 2>/dev/null | head -10
|
||||
|
||||
# Check for parseInt on UUID (ADR-019 violation)
|
||||
grep -rn "parseInt(" --include="*.ts" --include="*.tsx" backend/src/ frontend/src/ 2>/dev/null | head -10
|
||||
```
|
||||
|
||||
### Phase 6: ADR Compliance Check
|
||||
|
||||
```bash
|
||||
# Check for id ?? '' fallback (ADR-019 violation)
|
||||
grep -rn "id ?? ''" --include="*.ts" --include="*.tsx" frontend/src/ 2>/dev/null | head -10
|
||||
|
||||
# Check for Number() on UUID (ADR-019 violation)
|
||||
grep -rn "Number(" --include="*.ts" --include="*.tsx" frontend/src/ 2>/dev/null | head -10
|
||||
|
||||
# Check for + operator on UUID (ADR-019 violation)
|
||||
grep -rn "+ publicId\|+ id" --include="*.ts" --include="*.tsx" frontend/src/ 2>/dev/null | head -10
|
||||
```
|
||||
|
||||
### Phase 7: Diff Review
|
||||
|
||||
```bash
|
||||
# Show what changed
|
||||
git diff --stat
|
||||
git diff HEAD~1 --name-only
|
||||
|
||||
# Show detailed changes
|
||||
git diff
|
||||
```
|
||||
|
||||
Review each changed file for:
|
||||
- Unintended changes
|
||||
- Missing error handling (ADR-007)
|
||||
- Potential edge cases
|
||||
- UUID handling (ADR-019)
|
||||
- Security vulnerabilities (ADR-016)
|
||||
- AI boundary violations (ADR-018/023)
|
||||
|
||||
## Output Format
|
||||
|
||||
After running all phases, produce a verification report:
|
||||
|
||||
```
|
||||
VERIFICATION REPORT
|
||||
==================
|
||||
|
||||
Build: [PASS/FAIL]
|
||||
Types: [PASS/FAIL] (X errors)
|
||||
Lint: [PASS/FAIL] (X warnings)
|
||||
Tests: [PASS/FAIL] (X/Y passed, Z% coverage)
|
||||
Security: [PASS/FAIL] (X issues)
|
||||
ADR: [PASS/FAIL] (X violations)
|
||||
Diff: [X files changed]
|
||||
|
||||
Overall: [READY/NOT READY] for PR
|
||||
|
||||
Issues to Fix:
|
||||
1. ...
|
||||
2. ...
|
||||
```
|
||||
|
||||
## Continuous Mode
|
||||
|
||||
For long sessions, run verification every 15 minutes or after major changes:
|
||||
|
||||
```markdown
|
||||
Set a mental checkpoint:
|
||||
- After completing each function
|
||||
- After finishing a component
|
||||
- Before moving to next task
|
||||
|
||||
Run: /verify
|
||||
```
|
||||
|
||||
## Integration with LCBP3 Skills
|
||||
|
||||
This skill complements:
|
||||
- **speckit-checker**: Runs static analysis (lint, typecheck)
|
||||
- **speckit-tester**: Runs tests with coverage verification
|
||||
- **speckit-security-audit**: Performs security review against OWASP Top 10
|
||||
|
||||
This skill provides a unified verification loop that combines all checks into a single report.
|
||||
|
||||
## LCBP3-Specific Checks
|
||||
|
||||
### Tier 1 — CRITICAL (CI BLOCKER)
|
||||
|
||||
- [ ] **Security**: Auth, RBAC, Validation implemented
|
||||
- [ ] **UUID Strategy (ADR-019)**: No `parseInt` / `Number` / `+` on UUID
|
||||
- [ ] **Database correctness**: Schema verified before writing queries
|
||||
- [ ] **File upload security**: ClamAV + whitelist implemented
|
||||
- [ ] **AI validation boundary (ADR-018/023)**: AI via DMS API only
|
||||
- [ ] **Error handling (ADR-007)**: Layered error classification
|
||||
- [ ] **Forbidden patterns**: Zero `any`, zero `console.log`, UUID misuse
|
||||
|
||||
### Tier 2 — IMPORTANT (CODE REVIEW)
|
||||
|
||||
- [ ] **Architecture patterns**: Thin controller, business logic in service
|
||||
- [ ] **Test coverage**: 80%+ business logic, 70%+ backend overall
|
||||
- [ ] **Cache invalidation**: Implemented when data modified
|
||||
- [ ] **Naming conventions**: Follow domain terminology
|
||||
|
||||
### Tier 3 — GUIDELINES
|
||||
|
||||
- [ ] **Code style**: Prettier formatting
|
||||
- [ ] **Comment completeness**: Thai comments, JSDoc on public methods
|
||||
- [ ] **Minor optimizations**: Performance improvements where applicable
|
||||
|
||||
## References
|
||||
|
||||
- LCBP3 AGENTS.md: `AGENTS.md` (repo root)
|
||||
- ADR-007 Error Handling: `specs/06-Decision-Records/ADR-007-error-handling-strategy.md`
|
||||
- ADR-016 Security: `specs/06-Decision-Records/ADR-016-security-authentication.md`
|
||||
- ADR-019 UUID: `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md`
|
||||
- ADR-018 AI Boundary: `specs/06-Decision-Records/ADR-018-ai-boundary.md`
|
||||
- ADR-023 AI Architecture: `specs/06-Decision-Records/ADR-023-unified-ai-architecture.md`
|
||||
Reference in New Issue
Block a user