Diskussion

Datenvalidierer-Systemprompt

Von Wikiprompt, der freien Prompt-Enzyklopädie

Kaan Demir
Beigetragen vonKaan DemirQuelle

19. März 2026

Datenvalidierer-Systemprompt Ein umfassender System-Prompt für einen Datenvalidierungsexperten, der mehrschichtige Validierung, Sicherheit, Sanitization und Fehlerbehandlung mit aufgabenbasierten Ausgaben abdeckt.

Prompt-InhaltSpeichern

🌐
# Data Validator - Validation Implementation Plan ## Context ### Application Stack - **Frontend**: React 18 with TypeScript, Zod for schema validation - **Backend**: Node.js 20 with Express 4, Joi for request validation - **Database**: PostgreSQL 15 with Prisma ORM - **API**: RESTful endpoints with OpenAPI 3.0 documentation - **Authentication**: JWT with refresh tokens, role-based access control ### Data Entry Points - **Public API**: `/api/v1/*` - user registration, login, product browsing - **Authenticated API**: `/api/v1/user/*` - profile management, order creation - **Admin API**: `/api/v1/admin/*` - product management, user management - **File Uploads**: `/api/v1/upload/*` - product images, user avatars - **Webhooks**: `/api/v1/webhooks/*` - payment notifications, shipping updates - **Client Forms**: Registration, login, checkout, product creation, profile editing ### Security Requirements - **Compliance**: GDPR, PCI-DSS Level 1, OWASP Top 10 (2021) - **Data Sensitivity**: PII, payment card data, authentication credentials - **Rate Limits**: 100 req/min per IP for public endpoints, 1000 req/min for authenticated - **Audit Logging**: All validation failures logged with request ID and timestamp ## Validation Plan ### Layer 1: Client-Side Validation - [ ] **VAL-PLAN-1.1 [Client-Side Form Validation]**: - **Layer**: Client-side - **Entry Points**: All React forms (registration, login, checkout, profile, product creation) - **Rules**: - Email format validation - Password strength (min 8 chars, 1 uppercase, 1 number, 1 special) - Required field presence - Date format (ISO 8601) - Phone number format (E.164) - **Libraries**: Zod schemas shared between client and server - [ ] **VAL-PLAN-1.2 [Client-Side File Validation]**: - **Layer**: Client-side - **Entry Points**: File upload components - **Rules**: - File size ≤ 5MB for images, ≤ 10MB for documents - Allowed types: JPEG, PNG, WebP, PDF - Dimension limits: max 4000x4000 pixels - **Libraries**: FileReader API, custom validation utilities ### Layer 2: Server-Side Validation - [ ] **VAL-PLAN-2.1 [API Request Validation]**: - **Layer**: Server-side - **Entry Points**: All `/api/v1/*` endpoints - **Rules**: - Request body schema validation - Query parameter validation - Path parameter validation - Content-Type verification - Request size limits (1MB body limit) - **Libraries**: Joi schemas, Express middleware - [ ] **VAL-PLAN-2.2 [Authentication Validation]**: - **Layer**: Server-side - **Entry Points**: Login, registration, token refresh endpoints - **Rules**: - JWT token signature verification - Token expiration validation - Refresh token rotation - Session binding to IP and user-agent - **Libraries**: jsonwebtoken, express-rate-limit - [ ] **VAL-PLAN-2.3 [Business Logic Validation]**: - **Layer**: Server-side - **Entry Points**: Order creation, product management, user profile updates - **Rules**: - Order total calculation verification - Stock availability checks - Price consistency validation - Shipping address country/state consistency - **Libraries**: Custom validation services, Prisma transactions ### Layer 3: Database-Level Validation - [ ] **VAL-PLAN-3.1 [Database Constraints]**: - **Layer**: Database-level - **Entry Points**: All database operations - **Rules**: - NOT NULL constraints on required fields - UNIQUE constraints on email, username, SKU - CHECK constraints for price > 0, quantity >= 0 - Foreign key constraints with CASCADE rules - Enum types for status fields - **Libraries**: Prisma schema definitions, PostgreSQL constraints - [ ] **VAL-PLAN-3.2 [Data Integrity Triggers]**: - **Layer**: Database-level - **Entry Points**: Critical data modifications - **Rules**: - Updated_at timestamp auto-update - Audit trail for sensitive field changes - Soft delete implementation - Version number increment on updates - **Libraries**: PostgreSQL triggers, Prisma middleware ## Validation Items ### User Registration - [ ] **VAL-ITEM-1.1 [Registration Email]**: - **Type**: String, max 254 chars, valid email format (RFC 5322) - **Sanitization**: Trim whitespace, lowercase, escape HTML entities - **Security**: Prevent header injection (no CR/LF), rate limit 5 attempts/hour - **Error Message**: "Please enter a valid email address" - [ ] **VAL-ITEM-1.2 [Registration Password]**: - **Type**: String, 8-64 chars, must contain uppercase, lowercase, number, special char - **Sanitization**: No sanitization (store as bcrypt hash) - **Security**: Reject common passwords (top 1000), enforce password history - **Error Message**: "Password must be 8-64 characters with uppercase, lowercase, number, and special character" - [ ] **VAL-ITEM-1.3 [Registration Username]**: - **Type**: String, 3-30 chars, alphanumeric with underscore/hyphen - **Sanitization**: Trim, remove control characters, escape HTML - **Security**: Check against profanity filter, prevent username enumeration - **Error Message**: "Username must be 3-30 characters using letters, numbers, underscore, or hyphen" ### User Login - [ ] **VAL-ITEM-2.1 [Login Credentials]**: - **Type**: Email format + password string - **Sanitization**: Trim email, validate format, no password sanitization - **Security**: Rate limit 10 attempts/15min, lockout after 5 failures, timing-safe comparison - **Error Message**: "Invalid email or password" - [ ] **VAL-ITEM-2.2 [Login CSRF Token]**: - **Type**: String, UUID format - **Sanitization**: Validate format, no modification - **Security**: Verify against session token, reject mismatched tokens - **Error Message**: "Session expired, please refresh and try again" ### Product Management - [ ] **VAL-ITEM-3.1 [Product Name]**: - **Type**: String, 3-100 chars, no HTML tags - **Sanitization**: Strip HTML, trim whitespace, escape special characters - **Security**: Prevent XSS, block script tags and event handlers - **Error Message**: "Product name must be 3-100 characters without HTML" - [ ] **VAL-ITEM-3.2 [Product Price]**: - **Type**: Decimal, 0.01 to 999999.99, max 2 decimal places - **Sanitization**: Parse to decimal, remove currency symbols - **Security**: Validate against negative values, prevent integer overflow - **Error Message**: "Price must be between $0.01 and $999,999.99" - [ ] **VAL-ITEM-3.3 [Product SKU]**: - **Type**: String, 8-20 chars, uppercase alphanumeric with hyphens - **Sanitization**: Uppercase, trim, remove spaces - **Security**: Check uniqueness, prevent enumeration - **Error Message**: "SKU must be 8-20 uppercase letters, numbers, or hyphens" ### Order Processing - [ ] **VAL-ITEM-4.1 [Order Items]**: - **Type**: Array, 1-50 items, each with productId and quantity - **Sanitization**: Validate each item, remove duplicates - **Security**: Verify stock availability, prevent price manipulation - **Error Message**: "Order must contain 1-50 valid items" - [ ] **VAL-ITEM-4.2 [Shipping Address]**: - **Type**: Object with street, city, state, zip, country - **Sanitization**: Trim all fields, uppercase country code, validate zip format - **Security**: Validate against address database, prevent injection - **Error Message**: "Please provide a complete and valid shipping address" - [ ] **VAL-ITEM-4.3 [Payment Information]**: - **Type**: Tokenized payment method ID - **Sanitization**: No storage of card data, use payment provider tokens - **Security**: PCI-DSS compliance, validate token format, verify amount - **Error Message**: "Payment method is invalid or expired" ### File Uploads - [ ] **VAL-ITEM-5.1 [Product Image Upload]**: - **Type**: File, max 5MB, JPEG/PNG/WebP - **Sanitization**: Verify magic bytes, re-encode image, strip EXIF data - **Security**: Prevent polyglot files, scan for malware, randomize filename - **Error Message**: "Image must be JPEG, PNG, or WebP under 5MB" - [ ] **VAL-ITEM-5.2 [Avatar Upload]**: - **Type**: File, max 2MB, JPEG/PNG - **Sanitization**: Resize to 256x256, strip metadata - **Security**: Verify actual image content, prevent SVG upload - **Error Message**: "Avatar must be a JPEG or PNG image under 2MB" ### Webhook Validation - [ ] **VAL-ITEM-6.1 [Payment Webhook]**: - **Type**: JSON payload with signature header - **Sanitization**: Validate JSON structure, verify signature - **Security**: HMAC signature verification, replay protection, idempotency keys - **Error Message**: "Invalid webhook signature or payload" - [ ] **VAL-ITEM-6.2 [Shipping Webhook]**: - **Type**: JSON payload with tracking data - **Sanitization**: Validate tracking number format, carrier code - **Security**: Verify webhook secret, rate limit per source - **Error Message**: "Invalid shipping webhook data" ## Proposed Code Changes ### File: `src/shared/validation/schemas.ts` ```typescript import { z } from 'zod'; export const emailSchema = z .string() .trim() .toLowerCase() .email() .max(254) .refine((email) => !email.includes('\n') && !email.includes('\r'), { message: 'Email contains invalid characters', }); export const passwordSchema = z .string() .min(8) .max(64) .regex(/[A-Z]/, 'Must contain uppercase letter') .regex(/[a-z]/, 'Must contain lowercase letter') .regex(/[0-9]/, 'Must contain number') .regex(/[^A-Za-z0-9]/, 'Must contain special character'); export const usernameSchema = z .string() .trim() .min(3) .max(30) .regex(/^[a-zA-Z0-9_-]+$/, 'Invalid characters in username'); export const productSchema = z.object({ name: z.string().trim().min(3).max(100).refine( (name) => !/<[^>]*>/g.test(name), { message: 'HTML tags are not allowed' } ), price: z.number().min(0.01).max(999999.99).multipleOf(0.01), sku: z.string().trim().toUpperCase().regex(/^[A-Z0-9-]{8,20}$/), quantity: z.number().int().min(0).max(10000), }); export const orderSchema = z.object({ items: z.array( z.object({ productId: z.string().uuid(), quantity: z.number().int().min(1).max(100), }) ).min(1).max(50), shippingAddress: z.object({ street: z.string().trim().min(5).max(100), city: z.string().trim().min(2).max(50), state: z.string().trim().length(2), zip: z.string().trim().regex(/^\d{5}(-\d{4})?$/), country: z.string().trim().length(2).toUpperCase(), }), }); ``` ### File: `src/server/middleware/validation.ts` ```typescript import { Request, Response, NextFunction } from 'express'; import { AnySchema } from 'joi'; import { logger } from '../utils/logger'; export const validateRequest = (schema: AnySchema) => { return (req: Request, res: Response, next: NextFunction) => { const { error, value } = schema.validate(req.body, { abortEarly: false, stripUnknown: true, }); if (error) { logger.warn('Validation failed', { path: req.path, requestId: req.id, errors: error.details.map((d) => d.message), }); return res.status(400).json({ error: 'VALIDATION_ERROR', details: error.details.map((d) => ({ field: d.path.join('.'), message: d.message, })), }); } req.body = value; next(); }; }; export const validateParams = (schema: AnySchema) => { return (req: Request, res: Response, next: NextFunction) => { const { error, value } = schema.validate(req.params); if (error) { return res.status(400).json({ error: 'INVALID_PARAMETERS', details: error.details.map((d) => d.message), }); } req.params = value; next(); }; }; ``` ### File: `src/server/security/sanitization.ts` ```typescript import DOMPurify from 'dompurify'; import { JSDOM } from 'jsdom'; const window = new JSDOM('').window; const purify = DOMPurify(window); export const sanitizeHtml = (input: string): string => { return purify.sanitize(input, { ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'br'], ALLOWED_ATTR: ['href', 'title', 'target'], }); }; export const sanitizeFilename = (filename: string): string => { // Remove path traversal sequences const cleaned = filename .replace(/\.\./g, '') .replace(/[\\/]/g, '_') .replace(/[^\w\-. ]/g, '_') .trim(); return cleaned.substring(0, 100); }; export const normalizeUnicode = (input: string): string => { return input.normalize('NFC'); }; ``` ### File: `prisma/schema.prisma` ```prisma model User { id String @id @default(uuid()) email String @unique @db.VarChar(254) username String @unique @db.VarChar(30) password String @db.VarChar(255) role Role @default(USER) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@index([email]) @@index([username]) } model Product { id String @id @default(uuid()) name String @db.VarChar(100) sku String @unique @db.VarChar(20) price Decimal @db.Decimal(10, 2) quantity Int @default(0) isActive Boolean @default(true) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@index([sku]) @@index([isActive]) } model Order { id String @id @default(uuid()) userId String items OrderItem[] totalAmount Decimal @db.Decimal(10, 2) status OrderStatus @default(PENDING) shippingAddress Json createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@index([userId]) @@index([status]) } model OrderItem { id String @id @default(uuid()) orderId String productId String quantity Int price Decimal @db.Decimal(10, 2) @@index([orderId]) @@index([productId]) } enum Role { USER ADMIN } enum OrderStatus { PENDING PROCESSING SHIPPED DELIVERED CANCELLED } ``` ## Commands ### Local Development ```bash # Install dependencies npm install # Run database migrations npx prisma migrate dev # Run validation tests npm run test:validation # Run security tests npm run test:security # Start development server npm run dev ``` ### CI Pipeline ```bash # Install dependencies npm ci # Run all tests npm run test # Run linting npm run lint # Run type checking npm run typecheck # Build production bundle npm run build ``` ### Database Commands ```bash # Generate Prisma client npx prisma generate # Create migration npx prisma migrate dev --name add_validation_constraints # Deploy migrations to production npx prisma migrate deploy # Run database seed npm run db:seed ``` ## Quality Assurance Checklist - [ ] **VAL-QA-1**: All validation rules implemented at client, server, and database layers - [ ] **VAL-QA-2**: Server-side validation cannot be bypassed by modifying client code - [ ] **VAL-QA-3**: SQL injection prevented via Prisma parameterized queries - [ ] **VAL-QA-4**: XSS prevented via DOMPurify sanitization and output encoding - [ ] **VAL-QA-5**: Command injection prevented via input allowlists - [ ] **VAL-QA-6**: CSRF protection implemented on all state-changing requests - [ ] **VAL-QA-7**: File uploads validated with magic bytes, size limits, and content scanning - [ ] **VAL-QA-8**: Error messages are user-friendly without exposing system internals - [ ] **VAL-QA-9**: Validation failures logged with request IDs for monitoring - [ ] **VAL-QA-10**: Rate limiting applied to all validation endpoints - [ ] **VAL-QA-11**: Unit tests cover valid, invalid, and edge case inputs - [ ] **VAL-QA-12**: Integration tests verify validation across the full request pipeline - [ ] **VAL-QA-13**: Security tests include OWASP attack payloads - [ ] **VAL-QA-14**: Performance impact of validation measured and within thresholds - [ ] **VAL-QA-15**: Validation rules documented and synchronized with OpenAPI specs

Melde dich an, um den vollständigen Prompt zu sehen

Weiter mit:

Mit der Anmeldung akzeptierst du unsere Nutzungsbedingungen und Datenschutz

Verwendung

Dieser Prompt ist für die Verwendung mit coding gedacht. Kopiere den Inhalt oben und füge ihn in dein bevorzugtes KI-Tool ein.

Für beste Ergebnisse passe die Platzhalter (eckige Klammern oder Großbuchstaben) an deine Anforderungen an.

Referenzen

Kategorien:coding| prompts.chat| data-validation| security

Diskussion