@qazuor/claude-code-config 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1248 -0
- package/dist/bin.cjs +11886 -0
- package/dist/bin.cjs.map +1 -0
- package/dist/bin.d.cts +1 -0
- package/dist/bin.d.ts +1 -0
- package/dist/bin.js +11869 -0
- package/dist/bin.js.map +1 -0
- package/dist/index.cjs +3887 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1325 -0
- package/dist/index.d.ts +1325 -0
- package/dist/index.js +3835 -0
- package/dist/index.js.map +1 -0
- package/package.json +86 -0
- package/templates/.log/notifications.log +1775 -0
- package/templates/agents/README.md +164 -0
- package/templates/agents/_registry.json +443 -0
- package/templates/agents/design/content-writer.md +353 -0
- package/templates/agents/design/ux-ui-designer.md +382 -0
- package/templates/agents/engineering/astro-engineer.md +293 -0
- package/templates/agents/engineering/db-drizzle-engineer.md +360 -0
- package/templates/agents/engineering/express-engineer.md +316 -0
- package/templates/agents/engineering/fastify-engineer.md +399 -0
- package/templates/agents/engineering/hono-engineer.md +263 -0
- package/templates/agents/engineering/mongoose-engineer.md +473 -0
- package/templates/agents/engineering/nestjs-engineer.md +429 -0
- package/templates/agents/engineering/nextjs-engineer.md +451 -0
- package/templates/agents/engineering/node-typescript-engineer.md +347 -0
- package/templates/agents/engineering/prisma-engineer.md +432 -0
- package/templates/agents/engineering/react-senior-dev.md +394 -0
- package/templates/agents/engineering/tanstack-start-engineer.md +447 -0
- package/templates/agents/engineering/tech-lead.md +269 -0
- package/templates/agents/product/product-functional.md +329 -0
- package/templates/agents/product/product-technical.md +578 -0
- package/templates/agents/quality/debugger.md +514 -0
- package/templates/agents/quality/qa-engineer.md +390 -0
- package/templates/agents/specialized/enrichment-agent.md +277 -0
- package/templates/agents/specialized/i18n-specialist.md +322 -0
- package/templates/agents/specialized/seo-ai-specialist.md +387 -0
- package/templates/agents/specialized/tech-writer.md +300 -0
- package/templates/code-style/.editorconfig +27 -0
- package/templates/code-style/.prettierignore +25 -0
- package/templates/code-style/.prettierrc +12 -0
- package/templates/code-style/biome.json +78 -0
- package/templates/code-style/commitlint.config.js +44 -0
- package/templates/commands/README.md +175 -0
- package/templates/commands/_registry.json +420 -0
- package/templates/commands/add-new-entity.md +211 -0
- package/templates/commands/audit/accessibility-audit.md +360 -0
- package/templates/commands/audit/performance-audit.md +290 -0
- package/templates/commands/audit/security-audit.md +231 -0
- package/templates/commands/code-check.md +127 -0
- package/templates/commands/five-why.md +225 -0
- package/templates/commands/formatting/format-markdown.md +197 -0
- package/templates/commands/git/commit.md +247 -0
- package/templates/commands/meta/create-agent.md +257 -0
- package/templates/commands/meta/create-command.md +312 -0
- package/templates/commands/meta/create-skill.md +321 -0
- package/templates/commands/meta/help.md +318 -0
- package/templates/commands/planning/check-completed-tasks.md +224 -0
- package/templates/commands/planning/cleanup-issues.md +248 -0
- package/templates/commands/planning/planning-cleanup.md +251 -0
- package/templates/commands/planning/sync-planning-github.md +133 -0
- package/templates/commands/planning/sync-todos-github.md +203 -0
- package/templates/commands/quality-check.md +211 -0
- package/templates/commands/run-tests.md +159 -0
- package/templates/commands/start-feature-plan.md +232 -0
- package/templates/commands/start-refactor-plan.md +244 -0
- package/templates/commands/sync-planning.md +176 -0
- package/templates/commands/update-docs.md +242 -0
- package/templates/docs/CHECKPOINT-SYSTEM.md +504 -0
- package/templates/docs/INDEX.md +677 -0
- package/templates/docs/RECOMMENDED-HOOKS.md +415 -0
- package/templates/docs/_registry.json +329 -0
- package/templates/docs/diagrams/README.md +220 -0
- package/templates/docs/diagrams/agent-hierarchy.mmd +55 -0
- package/templates/docs/diagrams/documentation-map.mmd +61 -0
- package/templates/docs/diagrams/tools-relationship.mmd +55 -0
- package/templates/docs/diagrams/workflow-decision-tree.mmd +38 -0
- package/templates/docs/doc-sync.md +533 -0
- package/templates/docs/examples/end-to-end-workflow.md +1505 -0
- package/templates/docs/glossary.md +495 -0
- package/templates/docs/guides/mockup-prompt-engineering.md +644 -0
- package/templates/docs/guides/mockup-setup.md +737 -0
- package/templates/docs/learnings/README.md +250 -0
- package/templates/docs/learnings/common-architectural-patterns.md +123 -0
- package/templates/docs/learnings/common-mistakes-to-avoid.md +149 -0
- package/templates/docs/learnings/markdown-formatting-standards.md +104 -0
- package/templates/docs/learnings/monorepo-command-execution.md +64 -0
- package/templates/docs/learnings/optimization-tips.md +146 -0
- package/templates/docs/learnings/planning-linear-sync-workflow.md +70 -0
- package/templates/docs/learnings/shell-compatibility-fish.md +46 -0
- package/templates/docs/learnings/test-organization-structure.md +68 -0
- package/templates/docs/mcp-installation.md +613 -0
- package/templates/docs/mcp-servers.md +989 -0
- package/templates/docs/notification-installation.md +570 -0
- package/templates/docs/quick-start.md +354 -0
- package/templates/docs/standards/architecture-patterns.md +1064 -0
- package/templates/docs/standards/atomic-commits.md +513 -0
- package/templates/docs/standards/code-standards.md +993 -0
- package/templates/docs/standards/design-standards.md +656 -0
- package/templates/docs/standards/documentation-standards.md +1160 -0
- package/templates/docs/standards/testing-standards.md +969 -0
- package/templates/docs/system-maintenance.md +604 -0
- package/templates/docs/templates/PDR-template.md +561 -0
- package/templates/docs/templates/TODOs-template.md +534 -0
- package/templates/docs/templates/tech-analysis-template.md +800 -0
- package/templates/docs/workflows/README.md +519 -0
- package/templates/docs/workflows/atomic-task-protocol.md +955 -0
- package/templates/docs/workflows/decision-tree.md +482 -0
- package/templates/docs/workflows/edge-cases.md +856 -0
- package/templates/docs/workflows/phase-1-planning.md +957 -0
- package/templates/docs/workflows/phase-2-implementation.md +896 -0
- package/templates/docs/workflows/phase-3-validation.md +792 -0
- package/templates/docs/workflows/phase-4-finalization.md +927 -0
- package/templates/docs/workflows/quick-fix-protocol.md +505 -0
- package/templates/docs/workflows/task-atomization.md +537 -0
- package/templates/docs/workflows/task-completion-protocol.md +448 -0
- package/templates/hooks/on-notification.sh +28 -0
- package/templates/schemas/checkpoint.schema.json +97 -0
- package/templates/schemas/code-registry.schema.json +84 -0
- package/templates/schemas/pdr.schema.json +314 -0
- package/templates/schemas/problems.schema.json +55 -0
- package/templates/schemas/tech-analysis.schema.json +404 -0
- package/templates/schemas/telemetry.schema.json +298 -0
- package/templates/schemas/todos.schema.json +234 -0
- package/templates/schemas/workflows.schema.json +69 -0
- package/templates/scripts/add-changelogs.sh +105 -0
- package/templates/scripts/generate-code-registry.ts +270 -0
- package/templates/scripts/health-check.sh +343 -0
- package/templates/scripts/sync-registry.sh +40 -0
- package/templates/scripts/telemetry-report.ts +36 -0
- package/templates/scripts/validate-docs.sh +224 -0
- package/templates/scripts/validate-registry.sh +225 -0
- package/templates/scripts/validate-schemas.ts +283 -0
- package/templates/scripts/validate-structure.sh +165 -0
- package/templates/scripts/worktree-cleanup.sh +81 -0
- package/templates/scripts/worktree-create.sh +63 -0
- package/templates/sessions/planning/.gitkeep +0 -0
- package/templates/sessions/planning/archived/.gitkeep +0 -0
- package/templates/settings.json +202 -0
- package/templates/settings.local.json +138 -0
- package/templates/skills/README.md +197 -0
- package/templates/skills/_registry.json +473 -0
- package/templates/skills/audit/accessibility-audit.md +309 -0
- package/templates/skills/audit/performance-audit.md +257 -0
- package/templates/skills/audit/security-audit.md +217 -0
- package/templates/skills/auth/nextauth-patterns.md +308 -0
- package/templates/skills/brand-guidelines.md +240 -0
- package/templates/skills/documentation/markdown-formatter.md +302 -0
- package/templates/skills/git/git-commit-helper.md +321 -0
- package/templates/skills/i18n/i18n-patterns.md +251 -0
- package/templates/skills/patterns/error-handling-patterns.md +242 -0
- package/templates/skills/patterns/tdd-methodology.md +342 -0
- package/templates/skills/qa/qa-criteria-validator.md +383 -0
- package/templates/skills/qa/web-app-testing.md +398 -0
- package/templates/skills/react/react-hook-form-patterns.md +359 -0
- package/templates/skills/state/redux-toolkit-patterns.md +272 -0
- package/templates/skills/state/tanstack-query-patterns.md +299 -0
- package/templates/skills/state/zustand-patterns.md +301 -0
- package/templates/skills/tech/mermaid-diagram-specialist.md +195 -0
- package/templates/skills/tech/shadcn-specialist.md +252 -0
- package/templates/skills/tech/vercel-specialist.md +297 -0
- package/templates/skills/testing/api-app-testing.md +254 -0
- package/templates/skills/testing/performance-testing.md +275 -0
- package/templates/skills/testing/security-testing.md +348 -0
- package/templates/skills/utils/add-memory.md +295 -0
- package/templates/skills/utils/json-data-auditor.md +283 -0
- package/templates/skills/utils/pdf-creator-editor.md +342 -0
- package/templates/tools/format-markdown.sh +185 -0
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: security-audit
|
|
3
|
+
category: audit
|
|
4
|
+
description: Comprehensive security audit covering OWASP Top 10, authentication, authorization, data protection, and penetration testing
|
|
5
|
+
usage: Use for comprehensive security review before deployment, after major changes, or as part of regular security assessments
|
|
6
|
+
input: Codebase, API endpoints, authentication system, database schema, infrastructure configuration
|
|
7
|
+
output: Security audit report with severity-categorized findings, remediation steps, and compliance status
|
|
8
|
+
config_required:
|
|
9
|
+
- target_environment: "Environment to audit (dev/staging/production)"
|
|
10
|
+
- compliance_requirements: "GDPR, PCI-DSS, HIPAA, SOC2, etc."
|
|
11
|
+
- security_tools: "OWASP ZAP, Snyk, npm audit, etc."
|
|
12
|
+
- authentication_system: "JWT, OAuth, Session-based, etc."
|
|
13
|
+
- scan_depth: "quick (30min), standard (60min), comprehensive (90min)"
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
# Security Audit
|
|
17
|
+
|
|
18
|
+
## Purpose
|
|
19
|
+
|
|
20
|
+
Comprehensive security audit combining vulnerability assessment, code review, and penetration testing simulation.
|
|
21
|
+
|
|
22
|
+
**Category**: Audit
|
|
23
|
+
**Primary Users**: tech-lead
|
|
24
|
+
**Coordinates**: Security reviews and vulnerability assessments
|
|
25
|
+
|
|
26
|
+
## When to Use
|
|
27
|
+
|
|
28
|
+
- Before production deployment
|
|
29
|
+
- After implementing security-critical features
|
|
30
|
+
- Regular security assessments (quarterly recommended)
|
|
31
|
+
- After security incidents or breaches
|
|
32
|
+
- Before handling sensitive data (PII, payments)
|
|
33
|
+
- When compliance requirements mandate audits
|
|
34
|
+
|
|
35
|
+
## Configuration
|
|
36
|
+
|
|
37
|
+
| Setting | Description | Example |
|
|
38
|
+
|---------|-------------|---------|
|
|
39
|
+
| target_environment | Environment to audit | `production`, `staging` |
|
|
40
|
+
| compliance_requirements | Required compliance standards | `GDPR, PCI-DSS, HIPAA` |
|
|
41
|
+
| security_tools | Tools available for scanning | `npm audit, Snyk, OWASP ZAP` |
|
|
42
|
+
| authentication_system | Auth implementation type | `JWT, OAuth2, session-based` |
|
|
43
|
+
| scan_depth | Audit thoroughness level | `quick`, `standard`, `comprehensive` |
|
|
44
|
+
| previous_audit_date | Last audit date for comparison | `2024-09-15` |
|
|
45
|
+
|
|
46
|
+
## Audit Areas
|
|
47
|
+
|
|
48
|
+
| Area | Key Checks | Output |
|
|
49
|
+
|------|------------|--------|
|
|
50
|
+
| **Authentication & Authorization** | Password hashing, session management, token security, RBAC, MFA, brute-force protection | Auth security score, vulnerabilities, recommendations |
|
|
51
|
+
| **Input Validation** | Schema validation, SQL injection prevention, XSS prevention, CSRF protection, file upload validation | Coverage %, vulnerabilities, gaps |
|
|
52
|
+
| **Data Protection** | Encryption at rest/transit, secrets management, PII handling, GDPR compliance, secure deletion | Compliance %, privacy issues, encryption gaps |
|
|
53
|
+
| **API Security** | Rate limiting, authentication, CORS, versioning, error messages, security headers | API security score, exposed endpoints |
|
|
54
|
+
| **Infrastructure** | Environment variables, secrets management, container security, dependency vulnerabilities, TLS/SSL | Configuration issues, dependencies audit |
|
|
55
|
+
| **Code Security** | Error handling, hardcoded secrets, secure patterns, type safety, safe deserialization | Code security score, pattern violations |
|
|
56
|
+
| **Frontend Security** | XSS prevention, CSP, SRI, third-party scripts, cookie security, clickjacking protection | Frontend security score, browser vulnerabilities |
|
|
57
|
+
| **Penetration Testing** | Auth bypass, privilege escalation, injection probes, CSRF simulation, session hijacking | Exploitable vulnerabilities, risk assessment |
|
|
58
|
+
|
|
59
|
+
## Workflow
|
|
60
|
+
|
|
61
|
+
### 1. Preparation (10min)
|
|
62
|
+
|
|
63
|
+
- Review codebase structure and critical endpoints
|
|
64
|
+
- Map authentication flows
|
|
65
|
+
- List third-party integrations
|
|
66
|
+
- Configure security scanners
|
|
67
|
+
|
|
68
|
+
### 2. Automated Scanning (15min)
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
# Dependency audit
|
|
72
|
+
npm audit --audit-level moderate
|
|
73
|
+
pnpm audit --audit-level moderate
|
|
74
|
+
|
|
75
|
+
# Code scanning
|
|
76
|
+
# Run ESLint security rules
|
|
77
|
+
# Check for hardcoded secrets
|
|
78
|
+
# Analyze dependencies
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### 3. Manual Review (30min)
|
|
82
|
+
|
|
83
|
+
**Authentication Review:**
|
|
84
|
+
- Inspect password hashing
|
|
85
|
+
- Review session management
|
|
86
|
+
- Validate RBAC implementation
|
|
87
|
+
|
|
88
|
+
**API Security Review:**
|
|
89
|
+
- Check rate limiting and CORS
|
|
90
|
+
- Validate input validation
|
|
91
|
+
- Test error handling
|
|
92
|
+
|
|
93
|
+
**Data Protection Review:**
|
|
94
|
+
- Verify encryption usage
|
|
95
|
+
- Check secrets management
|
|
96
|
+
- Review logging practices
|
|
97
|
+
|
|
98
|
+
### 4. Penetration Testing (20min)
|
|
99
|
+
|
|
100
|
+
**Authentication Tests:**
|
|
101
|
+
- Try common passwords, session fixation, token manipulation
|
|
102
|
+
|
|
103
|
+
**Injection Tests:**
|
|
104
|
+
- SQL injection, XSS payloads, command injection
|
|
105
|
+
|
|
106
|
+
**Authorization Tests:**
|
|
107
|
+
- Privilege escalation, direct object reference, path traversal
|
|
108
|
+
|
|
109
|
+
### 5. Reporting (15min)
|
|
110
|
+
|
|
111
|
+
**Categorize Findings:**
|
|
112
|
+
- **Critical:** Immediate fix required (RCE, SQLi, auth bypass)
|
|
113
|
+
- **High:** Fix before deployment (XSS, sensitive data leak)
|
|
114
|
+
- **Medium:** Fix soon (weak encryption, missing headers)
|
|
115
|
+
- **Low:** Best practice improvements
|
|
116
|
+
|
|
117
|
+
## Report Template
|
|
118
|
+
|
|
119
|
+
```markdown
|
|
120
|
+
# Security Audit Report
|
|
121
|
+
|
|
122
|
+
**Date:** YYYY-MM-DD
|
|
123
|
+
**Environment:** [environment]
|
|
124
|
+
**OWASP Compliance Target:** Top 10 2021
|
|
125
|
+
|
|
126
|
+
## Executive Summary
|
|
127
|
+
|
|
128
|
+
- Overall Security Score: X/100
|
|
129
|
+
- Critical Issues: X
|
|
130
|
+
- High Issues: X
|
|
131
|
+
- Medium Issues: X
|
|
132
|
+
- Low Issues: X
|
|
133
|
+
|
|
134
|
+
## Findings by Severity
|
|
135
|
+
|
|
136
|
+
### Critical (Immediate Action Required)
|
|
137
|
+
|
|
138
|
+
1. **[Finding Title]**
|
|
139
|
+
- Severity: Critical
|
|
140
|
+
- Location: [File/Endpoint]
|
|
141
|
+
- Description: [Details]
|
|
142
|
+
- Impact: [Security risk]
|
|
143
|
+
- Remediation: [Fix steps]
|
|
144
|
+
- References: [OWASP/CVE links]
|
|
145
|
+
|
|
146
|
+
## OWASP Top 10 Compliance
|
|
147
|
+
|
|
148
|
+
- [ ] A01:2021 - Broken Access Control
|
|
149
|
+
- [ ] A02:2021 - Cryptographic Failures
|
|
150
|
+
- [ ] A03:2021 - Injection
|
|
151
|
+
- [ ] A04:2021 - Insecure Design
|
|
152
|
+
- [ ] A05:2021 - Security Misconfiguration
|
|
153
|
+
- [ ] A06:2021 - Vulnerable Components
|
|
154
|
+
- [ ] A07:2021 - Identification & Authentication Failures
|
|
155
|
+
- [ ] A08:2021 - Software & Data Integrity Failures
|
|
156
|
+
- [ ] A09:2021 - Security Logging & Monitoring Failures
|
|
157
|
+
- [ ] A10:2021 - Server-Side Request Forgery
|
|
158
|
+
|
|
159
|
+
## Recommendations
|
|
160
|
+
|
|
161
|
+
1. **Immediate Actions** (Critical/High)
|
|
162
|
+
2. **Short-term Improvements** (Medium)
|
|
163
|
+
3. **Long-term Enhancements** (Low)
|
|
164
|
+
|
|
165
|
+
## Next Steps
|
|
166
|
+
|
|
167
|
+
1. Address critical issues immediately
|
|
168
|
+
2. Schedule high-priority fixes
|
|
169
|
+
3. Create issues for medium/low items
|
|
170
|
+
4. Re-audit after fixes
|
|
171
|
+
5. Schedule next audit (quarterly)
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
## Severity Definitions
|
|
175
|
+
|
|
176
|
+
| Severity | Definition | Examples | Timeframe |
|
|
177
|
+
|----------|------------|----------|-----------|
|
|
178
|
+
| **Critical** | Allows unauthorized access or data breach | RCE, SQL injection, auth bypass | Immediate |
|
|
179
|
+
| **High** | Significant security impact | XSS, sensitive data leak, broken access control | Before deployment |
|
|
180
|
+
| **Medium** | Moderate security risk | Weak encryption, missing headers, info disclosure | Next sprint |
|
|
181
|
+
| **Low** | Best practice violation | Logging issues, monitoring gaps, hardening | Backlog |
|
|
182
|
+
|
|
183
|
+
## OWASP Top 10 Checklist
|
|
184
|
+
|
|
185
|
+
1. **Broken Access Control** - RBAC enforcement, direct object references
|
|
186
|
+
2. **Cryptographic Failures** - Strong encryption, secure key management
|
|
187
|
+
3. **Injection** - Input validation, parameterized queries, output encoding
|
|
188
|
+
4. **Insecure Design** - Threat modeling, secure architecture patterns
|
|
189
|
+
5. **Security Misconfiguration** - Secure defaults, minimal features enabled
|
|
190
|
+
6. **Vulnerable Components** - Dependency updates, CVE monitoring
|
|
191
|
+
7. **Authentication Failures** - Strong passwords, session security, MFA
|
|
192
|
+
8. **Data Integrity Failures** - Secure deserialization, signed updates
|
|
193
|
+
9. **Logging Failures** - Comprehensive logging, tamper-proof logs
|
|
194
|
+
10. **SSRF** - URL validation, network segmentation
|
|
195
|
+
|
|
196
|
+
## Success Criteria
|
|
197
|
+
|
|
198
|
+
- All critical and high-severity issues identified
|
|
199
|
+
- OWASP Top 10 compliance validated
|
|
200
|
+
- Remediation steps provided for all findings
|
|
201
|
+
- Security score calculated and documented
|
|
202
|
+
- Report delivered in actionable format
|
|
203
|
+
|
|
204
|
+
## Best Practices
|
|
205
|
+
|
|
206
|
+
1. Run audits regularly, not just before deployment
|
|
207
|
+
2. Track remediation with issues/tickets
|
|
208
|
+
3. Compare with previous audits for trend analysis
|
|
209
|
+
4. Automate security scans in CI/CD
|
|
210
|
+
5. Document accepted risks and exceptions
|
|
211
|
+
6. Re-audit after fixes to verify effectiveness
|
|
212
|
+
|
|
213
|
+
## Related Skills
|
|
214
|
+
|
|
215
|
+
- [security-testing](../testing/security-testing.md) - Development testing
|
|
216
|
+
- [qa-criteria-validator](../qa/qa-criteria-validator.md) - Acceptance validation
|
|
217
|
+
- [tdd-methodology](../patterns/tdd-methodology.md) - Secure development
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: auth-patterns
|
|
3
|
+
category: auth
|
|
4
|
+
description: Authentication patterns for Next.js and React applications
|
|
5
|
+
usage: Use when implementing authentication with OAuth, credentials, or session management
|
|
6
|
+
input: Auth provider, session strategy, protected routes
|
|
7
|
+
output: Auth configuration, middleware, hooks, components
|
|
8
|
+
config_required:
|
|
9
|
+
auth_library: "Authentication library being used"
|
|
10
|
+
auth_providers: "OAuth providers (GitHub, Google, etc.) or credentials"
|
|
11
|
+
session_strategy: "Session strategy (JWT, database, etc.)"
|
|
12
|
+
protected_routes: "Routes requiring authentication"
|
|
13
|
+
database_adapter: "Database adapter if using database sessions"
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
# Auth Patterns
|
|
17
|
+
|
|
18
|
+
## ⚙️ Configuration
|
|
19
|
+
|
|
20
|
+
| Setting | Description | Example |
|
|
21
|
+
|---------|-------------|---------|
|
|
22
|
+
| `auth_library` | Authentication library | NextAuth.js, Auth0, Clerk, Supabase Auth |
|
|
23
|
+
| `auth_providers` | OAuth providers or credentials | GitHub, Google, Credentials |
|
|
24
|
+
| `session_strategy` | How sessions are stored | JWT, database |
|
|
25
|
+
| `protected_routes` | Routes requiring auth | `/dashboard`, `/admin/*` |
|
|
26
|
+
| `database_adapter` | Database adapter for sessions | Prisma, Drizzle, none |
|
|
27
|
+
|
|
28
|
+
## Purpose
|
|
29
|
+
|
|
30
|
+
Implement secure authentication with:
|
|
31
|
+
- Multiple authentication providers
|
|
32
|
+
- Protected routes and middleware
|
|
33
|
+
- Role-based access control
|
|
34
|
+
- Type-safe session management
|
|
35
|
+
|
|
36
|
+
## Core Setup
|
|
37
|
+
|
|
38
|
+
### Auth Configuration
|
|
39
|
+
|
|
40
|
+
```typescript
|
|
41
|
+
// lib/auth.ts
|
|
42
|
+
import NextAuth from 'next-auth';
|
|
43
|
+
import GitHub from 'next-auth/providers/github';
|
|
44
|
+
import Credentials from 'next-auth/providers/credentials';
|
|
45
|
+
import { PrismaAdapter } from '@auth/prisma-adapter';
|
|
46
|
+
import { db } from '@/lib/db';
|
|
47
|
+
|
|
48
|
+
export const { handlers, signIn, signOut, auth } = NextAuth({
|
|
49
|
+
adapter: PrismaAdapter(db),
|
|
50
|
+
session: { strategy: 'jwt' }, // or 'database'
|
|
51
|
+
pages: {
|
|
52
|
+
signIn: '/login',
|
|
53
|
+
error: '/auth/error',
|
|
54
|
+
},
|
|
55
|
+
providers: [
|
|
56
|
+
GitHub({
|
|
57
|
+
clientId: process.env.GITHUB_ID!,
|
|
58
|
+
clientSecret: process.env.GITHUB_SECRET!,
|
|
59
|
+
}),
|
|
60
|
+
Credentials({
|
|
61
|
+
credentials: {
|
|
62
|
+
email: { type: 'email' },
|
|
63
|
+
password: { type: 'password' },
|
|
64
|
+
},
|
|
65
|
+
async authorize(credentials) {
|
|
66
|
+
const user = await validateCredentials(credentials);
|
|
67
|
+
return user ?? null;
|
|
68
|
+
},
|
|
69
|
+
}),
|
|
70
|
+
],
|
|
71
|
+
callbacks: {
|
|
72
|
+
async jwt({ token, user }) {
|
|
73
|
+
if (user) {
|
|
74
|
+
token.id = user.id;
|
|
75
|
+
token.role = user.role;
|
|
76
|
+
}
|
|
77
|
+
return token;
|
|
78
|
+
},
|
|
79
|
+
async session({ session, token }) {
|
|
80
|
+
if (session.user) {
|
|
81
|
+
session.user.id = token.id as string;
|
|
82
|
+
session.user.role = token.role as string;
|
|
83
|
+
}
|
|
84
|
+
return session;
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### Type Extensions
|
|
91
|
+
|
|
92
|
+
```typescript
|
|
93
|
+
// types/auth.d.ts
|
|
94
|
+
declare module 'next-auth' {
|
|
95
|
+
interface Session {
|
|
96
|
+
user: {
|
|
97
|
+
id: string;
|
|
98
|
+
role: string;
|
|
99
|
+
} & DefaultSession['user'];
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Route Protection
|
|
105
|
+
|
|
106
|
+
### Middleware
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
// middleware.ts
|
|
110
|
+
import { auth } from '@/lib/auth';
|
|
111
|
+
import { NextResponse } from 'next/server';
|
|
112
|
+
|
|
113
|
+
export default auth((req) => {
|
|
114
|
+
const { pathname } = req.nextUrl;
|
|
115
|
+
const isLoggedIn = !!req.auth;
|
|
116
|
+
const isAdmin = req.auth?.user?.role === 'admin';
|
|
117
|
+
|
|
118
|
+
// Public routes
|
|
119
|
+
const publicRoutes = ['/', '/login', '/register'];
|
|
120
|
+
if (publicRoutes.some((route) => pathname.startsWith(route))) {
|
|
121
|
+
return NextResponse.next();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Redirect unauthenticated users
|
|
125
|
+
if (!isLoggedIn) {
|
|
126
|
+
const url = new URL('/login', req.url);
|
|
127
|
+
url.searchParams.set('callbackUrl', pathname);
|
|
128
|
+
return NextResponse.redirect(url);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Admin-only routes
|
|
132
|
+
if (pathname.startsWith('/admin') && !isAdmin) {
|
|
133
|
+
return NextResponse.redirect(new URL('/unauthorized', req.url));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return NextResponse.next();
|
|
137
|
+
});
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### Server Components
|
|
141
|
+
|
|
142
|
+
```typescript
|
|
143
|
+
// app/dashboard/page.tsx
|
|
144
|
+
import { auth } from '@/lib/auth';
|
|
145
|
+
import { redirect } from 'next/navigation';
|
|
146
|
+
|
|
147
|
+
export default async function DashboardPage() {
|
|
148
|
+
const session = await auth();
|
|
149
|
+
if (!session) redirect('/login');
|
|
150
|
+
|
|
151
|
+
return <div>Welcome, {session.user.name}</div>;
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## Client Components
|
|
156
|
+
|
|
157
|
+
### Session Provider
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
// app/providers.tsx
|
|
161
|
+
'use client';
|
|
162
|
+
import { SessionProvider } from 'next-auth/react';
|
|
163
|
+
|
|
164
|
+
export function Providers({ children }: { children: React.ReactNode }) {
|
|
165
|
+
return <SessionProvider>{children}</SessionProvider>;
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
### Login Form
|
|
170
|
+
|
|
171
|
+
```typescript
|
|
172
|
+
'use client';
|
|
173
|
+
import { signIn } from 'next-auth/react';
|
|
174
|
+
import { useRouter } from 'next/navigation';
|
|
175
|
+
|
|
176
|
+
export function LoginForm() {
|
|
177
|
+
const router = useRouter();
|
|
178
|
+
const [error, setError] = useState<string | null>(null);
|
|
179
|
+
|
|
180
|
+
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
|
181
|
+
e.preventDefault();
|
|
182
|
+
const formData = new FormData(e.currentTarget);
|
|
183
|
+
|
|
184
|
+
const result = await signIn('credentials', {
|
|
185
|
+
email: formData.get('email'),
|
|
186
|
+
password: formData.get('password'),
|
|
187
|
+
redirect: false,
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
if (result?.error) {
|
|
191
|
+
setError('Invalid credentials');
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
router.push('/dashboard');
|
|
196
|
+
router.refresh();
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
return (
|
|
200
|
+
<form onSubmit={handleSubmit}>
|
|
201
|
+
{error && <div className="error">{error}</div>}
|
|
202
|
+
<input name="email" type="email" required />
|
|
203
|
+
<input name="password" type="password" required />
|
|
204
|
+
<button type="submit">Sign in</button>
|
|
205
|
+
<button type="button" onClick={() => signIn('github')}>
|
|
206
|
+
GitHub
|
|
207
|
+
</button>
|
|
208
|
+
</form>
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
## Role-Based Access
|
|
214
|
+
|
|
215
|
+
### Permission Check
|
|
216
|
+
|
|
217
|
+
```typescript
|
|
218
|
+
// lib/permissions.ts
|
|
219
|
+
export async function checkPermission(permission: string): Promise<boolean> {
|
|
220
|
+
const session = await auth();
|
|
221
|
+
if (!session) return false;
|
|
222
|
+
|
|
223
|
+
const rolePermissions: Record<string, string[]> = {
|
|
224
|
+
admin: ['read', 'write', 'delete', 'manage_users'],
|
|
225
|
+
moderator: ['read', 'write', 'delete'],
|
|
226
|
+
user: ['read', 'write'],
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
return rolePermissions[session.user.role]?.includes(permission) ?? false;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Usage
|
|
233
|
+
export default async function ManageUsersPage() {
|
|
234
|
+
const canManage = await checkPermission('manage_users');
|
|
235
|
+
if (!canManage) redirect('/unauthorized');
|
|
236
|
+
// ...
|
|
237
|
+
}
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
### Higher-Order Component
|
|
241
|
+
|
|
242
|
+
```typescript
|
|
243
|
+
export function withAuth<P extends object>(
|
|
244
|
+
Component: ComponentType<P>,
|
|
245
|
+
allowedRoles?: string[]
|
|
246
|
+
) {
|
|
247
|
+
return async function AuthenticatedComponent(props: P) {
|
|
248
|
+
const session = await auth();
|
|
249
|
+
if (!session) redirect('/login');
|
|
250
|
+
if (allowedRoles && !allowedRoles.includes(session.user.role)) {
|
|
251
|
+
redirect('/unauthorized');
|
|
252
|
+
}
|
|
253
|
+
return <Component {...props} session={session} />;
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Usage
|
|
258
|
+
const AdminPage = withAuth(AdminDashboard, ['admin']);
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
## Server Actions
|
|
262
|
+
|
|
263
|
+
```typescript
|
|
264
|
+
'use server';
|
|
265
|
+
import { signIn, signOut } from '@/lib/auth';
|
|
266
|
+
import { AuthError } from 'next-auth';
|
|
267
|
+
|
|
268
|
+
export async function authenticate(formData: FormData) {
|
|
269
|
+
try {
|
|
270
|
+
await signIn('credentials', formData);
|
|
271
|
+
} catch (error) {
|
|
272
|
+
if (error instanceof AuthError) {
|
|
273
|
+
return error.type === 'CredentialsSignin'
|
|
274
|
+
? 'Invalid credentials'
|
|
275
|
+
: 'Something went wrong';
|
|
276
|
+
}
|
|
277
|
+
throw error;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export async function handleSignOut() {
|
|
282
|
+
await signOut({ redirectTo: '/' });
|
|
283
|
+
}
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
## Best Practices
|
|
287
|
+
|
|
288
|
+
| Practice | Description |
|
|
289
|
+
|----------|-------------|
|
|
290
|
+
| **JWT for Stateless** | Use JWT for stateless auth, database sessions for revocable sessions |
|
|
291
|
+
| **Type Safety** | Extend auth types for custom properties |
|
|
292
|
+
| **Middleware Protection** | Use middleware for route-level protection |
|
|
293
|
+
| **Environment Variables** | Store secrets securely in env vars |
|
|
294
|
+
| **Callbacks** | Customize tokens and sessions via callbacks |
|
|
295
|
+
| **Error Handling** | Handle auth errors gracefully with user feedback |
|
|
296
|
+
|
|
297
|
+
## When to Use
|
|
298
|
+
|
|
299
|
+
- Next.js applications requiring authentication
|
|
300
|
+
- OAuth integration (GitHub, Google, etc.)
|
|
301
|
+
- Role-based access control
|
|
302
|
+
- Multi-tenant applications
|
|
303
|
+
- Session management
|
|
304
|
+
|
|
305
|
+
## Related Skills
|
|
306
|
+
|
|
307
|
+
- `error-handling-patterns` - Handle auth errors
|
|
308
|
+
- `web-app-testing` - Test auth flows
|