omgkit 2.1.1 → 2.3.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.
Files changed (56) hide show
  1. package/package.json +1 -1
  2. package/plugin/skills/databases/mongodb/SKILL.md +81 -28
  3. package/plugin/skills/databases/prisma/SKILL.md +87 -32
  4. package/plugin/skills/databases/redis/SKILL.md +80 -27
  5. package/plugin/skills/devops/aws/SKILL.md +80 -26
  6. package/plugin/skills/devops/github-actions/SKILL.md +84 -32
  7. package/plugin/skills/devops/kubernetes/SKILL.md +94 -32
  8. package/plugin/skills/devops/performance-profiling/SKILL.md +59 -863
  9. package/plugin/skills/frameworks/django/SKILL.md +158 -24
  10. package/plugin/skills/frameworks/express/SKILL.md +153 -33
  11. package/plugin/skills/frameworks/fastapi/SKILL.md +153 -34
  12. package/plugin/skills/frameworks/laravel/SKILL.md +146 -33
  13. package/plugin/skills/frameworks/nestjs/SKILL.md +137 -25
  14. package/plugin/skills/frameworks/rails/SKILL.md +594 -28
  15. package/plugin/skills/frameworks/react/SKILL.md +94 -962
  16. package/plugin/skills/frameworks/spring/SKILL.md +528 -35
  17. package/plugin/skills/frameworks/vue/SKILL.md +147 -25
  18. package/plugin/skills/frontend/accessibility/SKILL.md +145 -36
  19. package/plugin/skills/frontend/frontend-design/SKILL.md +114 -29
  20. package/plugin/skills/frontend/responsive/SKILL.md +131 -28
  21. package/plugin/skills/frontend/shadcn-ui/SKILL.md +133 -43
  22. package/plugin/skills/frontend/tailwindcss/SKILL.md +105 -37
  23. package/plugin/skills/frontend/threejs/SKILL.md +110 -35
  24. package/plugin/skills/languages/javascript/SKILL.md +195 -34
  25. package/plugin/skills/methodology/brainstorming/SKILL.md +98 -30
  26. package/plugin/skills/methodology/defense-in-depth/SKILL.md +83 -37
  27. package/plugin/skills/methodology/dispatching-parallel-agents/SKILL.md +92 -31
  28. package/plugin/skills/methodology/executing-plans/SKILL.md +117 -28
  29. package/plugin/skills/methodology/finishing-development-branch/SKILL.md +111 -32
  30. package/plugin/skills/methodology/problem-solving/SKILL.md +65 -311
  31. package/plugin/skills/methodology/receiving-code-review/SKILL.md +76 -27
  32. package/plugin/skills/methodology/requesting-code-review/SKILL.md +93 -22
  33. package/plugin/skills/methodology/root-cause-tracing/SKILL.md +75 -40
  34. package/plugin/skills/methodology/sequential-thinking/SKILL.md +75 -224
  35. package/plugin/skills/methodology/systematic-debugging/SKILL.md +81 -35
  36. package/plugin/skills/methodology/test-driven-development/SKILL.md +120 -26
  37. package/plugin/skills/methodology/testing-anti-patterns/SKILL.md +88 -35
  38. package/plugin/skills/methodology/token-optimization/SKILL.md +73 -34
  39. package/plugin/skills/methodology/verification-before-completion/SKILL.md +128 -28
  40. package/plugin/skills/methodology/writing-plans/SKILL.md +105 -20
  41. package/plugin/skills/omega/omega-architecture/SKILL.md +178 -40
  42. package/plugin/skills/omega/omega-coding/SKILL.md +247 -41
  43. package/plugin/skills/omega/omega-sprint/SKILL.md +208 -46
  44. package/plugin/skills/omega/omega-testing/SKILL.md +253 -42
  45. package/plugin/skills/omega/omega-thinking/SKILL.md +263 -51
  46. package/plugin/skills/security/better-auth/SKILL.md +83 -34
  47. package/plugin/skills/security/oauth/SKILL.md +118 -35
  48. package/plugin/skills/security/owasp/SKILL.md +112 -35
  49. package/plugin/skills/testing/playwright/SKILL.md +141 -38
  50. package/plugin/skills/testing/pytest/SKILL.md +137 -38
  51. package/plugin/skills/testing/vitest/SKILL.md +124 -39
  52. package/plugin/skills/tools/document-processing/SKILL.md +111 -838
  53. package/plugin/skills/tools/image-processing/SKILL.md +126 -659
  54. package/plugin/skills/tools/mcp-development/SKILL.md +85 -758
  55. package/plugin/skills/tools/media-processing/SKILL.md +118 -735
  56. package/plugin/stdrules/SKILL_STANDARDS.md +490 -0
@@ -1,54 +1,266 @@
1
1
  ---
2
- name: omega-thinking
3
- description: 7 modes of Omega thinking. Use for deep analysis, problem solving, finding 10x improvements.
2
+ name: thinking-in-omega-modes
3
+ description: Applies 7 systematic thinking modes for breakthrough problem-solving and 10x improvements. Use when tackling complex problems, seeking transformative insights, or escaping conventional thinking traps.
4
+ category: omega
5
+ triggers:
6
+ - omega thinking
7
+ - deep analysis
8
+ - 10x improvement
9
+ - transformative thinking
10
+ - breakthrough ideas
4
11
  ---
5
12
 
6
- # Omega Thinking Skill
7
-
8
- ## The 7 Modes
9
-
10
- ### 🔭 TELESCOPIC
11
- Zoom out to see the big picture.
12
- - Task → Feature → Product → Market → Industry → World
13
- - **Ask**: "What's the ultimate impact?"
14
-
15
- ### 🔬 MICROSCOPIC
16
- First principles analysis.
17
- - Why? Why? Why? Why? → Why?
18
- - **Ask**: "What's fundamentally true?"
19
-
20
- ### ↔️ LATERAL
21
- Different angles and approaches.
22
- - How would [X industry] solve this?
23
- - What's the opposite approach?
24
- - **Ask**: "What are we not seeing?"
25
-
26
- ### 🔄 INVERSION
27
- Learn through failure.
28
- - How to guarantee failure?
29
- - Avoid those things.
30
- - **Ask**: "What would make this fail?"
31
-
32
- ### ⏳ TEMPORAL
33
- Time dimension analysis.
34
- - Historical patterns?
35
- - Relevant in 10 years?
36
- - **Ask**: "How does time affect this?"
37
-
38
- ### 🕸️ SYSTEMIC
39
- Interconnections and emergence.
40
- - Components and connections?
41
- - Feedback loops?
42
- - **Ask**: "What system dynamics are at play?"
43
-
44
- ### ⚛️ QUANTUM
45
- Multiple possibilities.
46
- - All possible solutions?
47
- - How to test quickly?
48
- - **Ask**: "What are all the possibilities?"
49
-
50
- ## Application
51
- For any problem:
52
- 1. Apply all 7 modes
53
- 2. Synthesize insights
54
- 3. Find the 10x opportunity
13
+ # Thinking in Omega Modes
14
+
15
+ Master the **7 modes of Omega thinking** for breakthrough problem-solving, transformative insights, and 10x improvements.
16
+
17
+ ## Quick Start
18
+
19
+ ```yaml
20
+ # Apply all 7 modes to any significant problem
21
+ Problem: "API performance issues"
22
+
23
+ Modes:
24
+ Telescopic: "Zoom out - what's the biggest picture?"
25
+ Microscopic: "First principles - what's fundamentally true?"
26
+ Lateral: "Different angle - how would Netflix solve this?"
27
+ Inversion: "Failure mode - how to guarantee failure?"
28
+ Temporal: "Time dimension - past, present, future impact?"
29
+ Systemic: "Connections - what are the feedback loops?"
30
+ Quantum: "Possibilities - what are ALL options?"
31
+
32
+ Synthesis:
33
+ 10x_Opportunity: "Shift from request-response to event-driven real-time"
34
+ ```
35
+
36
+ ## Features
37
+
38
+ | Feature | Description | Guide |
39
+ |---------|-------------|-------|
40
+ | Telescopic | Zoom out to biggest picture | Task to ultimate impact |
41
+ | Microscopic | First principles analysis | 5 Whys to root cause |
42
+ | Lateral | Different angles and perspectives | Industry translation |
43
+ | Inversion | Learn through failure analysis | Pre-mortem planning |
44
+ | Temporal | Time dimension analysis | Past, present, future effects |
45
+ | Systemic | Interconnections and emergence | Feedback loops mapping |
46
+ | Quantum | Multiple possibilities simultaneously | Scenario planning |
47
+
48
+ ## Common Patterns
49
+
50
+ ### The 7 Omega Thinking Modes
51
+
52
+ ```
53
+ TELESCOPIC - Zoom out to see the big picture
54
+ MICROSCOPIC - First principles analysis
55
+ LATERAL - Different angles and approaches
56
+ INVERSION - Learn through failure analysis
57
+ TEMPORAL - Time dimension analysis
58
+ SYSTEMIC - Interconnections and emergence
59
+ QUANTUM - Multiple possibilities simultaneously
60
+ ```
61
+
62
+ ### Telescopic: Zoom Out
63
+
64
+ ```markdown
65
+ ## The Zoom Ladder
66
+
67
+ Current task -> What feature does this enable?
68
+ Feature -> What product capability?
69
+ Product -> What business outcome?
70
+ Business -> What market need?
71
+ Market -> What industry trend?
72
+ Industry -> What societal shift?
73
+
74
+ ## Example
75
+ Task: Optimize database query
76
+ -> Feature: Faster page load
77
+ -> Product: Better UX
78
+ -> Business: Higher conversion
79
+ -> Market: Real-time expectation
80
+ -> Insight: Need real-time architecture, not just query fixes
81
+ ```
82
+
83
+ ### Microscopic: First Principles
84
+
85
+ ```markdown
86
+ ## The 5 Whys
87
+
88
+ Problem: Users complain about slow app
89
+
90
+ Why 1? -> Page load takes 5 seconds
91
+ Why 2? -> Large JavaScript bundle
92
+ Why 3? -> All dependencies loaded upfront
93
+ Why 4? -> No code splitting implemented
94
+ Why 5? -> Architecture assumed fast connections
95
+
96
+ Root cause: Architecture assumptions don't match reality
97
+
98
+ ## Fundamental Truths Checklist
99
+ - Physics constraints (speed of light)
100
+ - Mathematical certainties (complexity bounds)
101
+ - Human constants (attention span, cognitive load)
102
+ - Economic principles (supply/demand)
103
+ - Network effects (Metcalfe's law)
104
+ ```
105
+
106
+ ### Lateral: Different Angles
107
+
108
+ ```markdown
109
+ ## Industry Translation
110
+ How would [other industry] solve this?
111
+
112
+ - Netflix: Aggressive caching, CDN, predictive loading
113
+ - Tesla: OTA updates, feature flagging, A/B testing
114
+ - Amazon: Predictive stocking, distributed warehouses
115
+ - Spotify: Collaborative filtering, taste profiles
116
+
117
+ ## Opposite Day Analysis
118
+ Current: Push notifications to users
119
+ Opposite: Let users pull when ready
120
+ Insight: Less is more - reduce notification fatigue
121
+
122
+ ## Random Stimulus
123
+ Pick random word: "Butterfly"
124
+ - Metamorphosis -> Transform architecture gradually
125
+ - Wings -> Lightweight, distributed components
126
+ - Effect -> Small changes, big impact
127
+ ```
128
+
129
+ ### Inversion: Failure Analysis
130
+
131
+ ```markdown
132
+ ## How to Guarantee Failure
133
+
134
+ Goal: Build a highly reliable system
135
+
136
+ Guaranteed Failures:
137
+ 1. No monitoring -> Add comprehensive monitoring
138
+ 2. Single points of failure -> Build redundancy
139
+ 3. No testing -> Implement thorough testing
140
+ 4. Hardcode secrets -> Use secret management
141
+ 5. No backups -> Implement backup strategy
142
+
143
+ ## Pre-Mortem Template
144
+ Imagine it's 6 months from now and the project failed.
145
+
146
+ Technical Failures: [List what went wrong]
147
+ Process Failures: [List what went wrong]
148
+ People Failures: [List what went wrong]
149
+ External Failures: [List what went wrong]
150
+
151
+ Prevention Plan: [For each, identify prevention]
152
+ ```
153
+
154
+ ### Temporal: Time Dimension
155
+
156
+ ```markdown
157
+ ## Time Horizon Analysis
158
+
159
+ Past: Has this been tried before? What patterns repeat?
160
+ Present: What is true today? What constraints exist?
161
+ Near (1yr): What trends are emerging?
162
+ Medium (5yr): What technologies will mature?
163
+ Long (10yr+): What is inevitable? What will endure?
164
+
165
+ ## Second-Order Effects
166
+
167
+ First-order: [Immediate effect]
168
+ Second-order (1yr): [Effects of first-order effects]
169
+ Third-order (3yr): [Effects of second-order effects]
170
+ Fourth-order (5yr+): [Long-term cascading effects]
171
+
172
+ Example: Choosing microservices
173
+ - First: More deployment complexity
174
+ - Second: Team reorganization
175
+ - Third: Different hiring needs (DevOps)
176
+ - Fourth: Company culture shifts
177
+ ```
178
+
179
+ ### Systemic: Interconnections
180
+
181
+ ```markdown
182
+ ## Feedback Loop Analysis
183
+
184
+ Reinforcing Loops (Amplify):
185
+ A increases -> B increases -> A increases more
186
+ Type: Virtuous or Vicious?
187
+
188
+ Balancing Loops (Stabilize):
189
+ A increases -> B decreases -> A stabilizes
190
+
191
+ Intervention Points:
192
+ Where can we intervene for maximum effect?
193
+ 1. High leverage point
194
+ 2. Medium leverage point
195
+ 3. Low leverage point
196
+
197
+ ## Emergent Properties
198
+ What appears only when components combine:
199
+ - Properties no single component has
200
+ - Behaviors that emerge from interaction
201
+ - Capabilities that only exist as whole
202
+ ```
203
+
204
+ ### Quantum: Multiple Possibilities
205
+
206
+ ```markdown
207
+ ## Possibility Explosion
208
+
209
+ Conventional: Option A or Option B
210
+
211
+ Expanded:
212
+ - A + B: Combination
213
+ - Neither: Completely different approach
214
+ - Sequence: A then B
215
+ - Parallel: Both simultaneously
216
+ - Delegate: Someone else decides
217
+ - Defer: Decide later with more info
218
+ - Eliminate: Remove need for decision
219
+
220
+ ## Scenario Planning Matrix
221
+ Uncertainty 2
222
+ Low High
223
+ +-------------+-------------+
224
+ High | Scenario A | Scenario B |
225
+ Uncertainty 1 | | |
226
+ +-------------+-------------+
227
+ Low | Scenario C | Scenario D |
228
+ | | |
229
+ +-------------+-------------+
230
+
231
+ Robust Strategies: What works in ALL scenarios?
232
+ Contingent Strategies: If Scenario X, do Y
233
+ ```
234
+
235
+ ### Full Omega Analysis Example
236
+
237
+ ```markdown
238
+ ## Problem: API Performance
239
+
240
+ TELESCOPIC: Need real-time first, not request-response
241
+ MICROSCOPIC: Architecture drift from evolving requirements
242
+ LATERAL: Consider push-based architecture with caching
243
+ INVERSION: Add monitoring, caching, go async
244
+ TEMPORAL: Solve for future scale, not just current pain
245
+ SYSTEMIC: Cache layer breaks bottleneck loop
246
+ QUANTUM: Start with caching, plan for rearchitecture
247
+
248
+ ## Synthesis
249
+ 10x Opportunity: Shift from request-response to
250
+ event-driven real-time architecture with edge caching.
251
+ ```
252
+
253
+ ## Best Practices
254
+
255
+ | Do | Avoid |
256
+ |----|-------|
257
+ | Apply ALL 7 modes systematically | Stopping at surface level |
258
+ | Document insights from each mode | Using only one thinking mode |
259
+ | Look for 10x opportunities, not 10% | Accepting first solution |
260
+ | Synthesize across modes | Ignoring temporal effects |
261
+ | Challenge assumptions explicitly | Missing systemic connections |
262
+ | Consider unintended consequences | Limiting possibilities too early |
263
+ | Map systems and feedback loops | Forgetting to zoom out |
264
+ | Think across time horizons | Forgetting to zoom in |
265
+ | Generate many possibilities | Skipping the inversion check |
266
+ | Seek first principles truths | Rushing the analysis |
@@ -1,53 +1,102 @@
1
1
  ---
2
- name: better-auth
3
- description: Better Auth library. Use for authentication in TypeScript projects.
2
+ name: Implementing Better Auth
3
+ description: Claude implements enterprise TypeScript authentication with Better Auth. Use when building auth systems, adding OAuth providers, enabling MFA, or managing sessions in TypeScript/Next.js projects.
4
4
  ---
5
5
 
6
- # Better Auth Skill
6
+ # Implementing Better Auth
7
+
8
+ ## Quick Start
7
9
 
8
- ## Setup
9
10
  ```typescript
10
- import { betterAuth } from 'better-auth';
11
+ // lib/auth.ts
12
+ import { betterAuth } from "better-auth";
13
+ import { prismaAdapter } from "better-auth/adapters/prisma";
11
14
 
12
15
  export const auth = betterAuth({
13
- database: {
14
- provider: 'postgresql',
15
- url: process.env.DATABASE_URL,
16
- },
17
- emailAndPassword: {
18
- enabled: true,
19
- },
16
+ database: prismaAdapter(prisma, { provider: "postgresql" }),
17
+ emailAndPassword: { enabled: true, requireEmailVerification: true },
18
+ session: { expiresIn: 60 * 60 * 24 * 7 },
20
19
  socialProviders: {
21
- google: {
22
- clientId: process.env.GOOGLE_CLIENT_ID,
23
- clientSecret: process.env.GOOGLE_CLIENT_SECRET,
24
- },
20
+ google: { clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET! },
25
21
  },
26
22
  });
27
23
  ```
28
24
 
29
- ## Client Usage
30
- ```typescript
31
- import { createAuthClient } from 'better-auth/client';
25
+ ## Features
32
26
 
33
- const authClient = createAuthClient();
27
+ | Feature | Description | Reference |
28
+ |---------|-------------|-----------|
29
+ | Email/Password Auth | Secure registration, login, password validation | [Auth Guide](https://www.better-auth.com/docs/authentication/email-password) |
30
+ | Social OAuth | Google, GitHub, Discord provider integration | [Social Providers](https://www.better-auth.com/docs/authentication/social-providers) |
31
+ | Two-Factor Auth | TOTP-based MFA with backup codes | [2FA Plugin](https://www.better-auth.com/docs/plugins/two-factor) |
32
+ | Session Management | Secure cookie-based sessions with refresh | [Sessions](https://www.better-auth.com/docs/concepts/sessions) |
33
+ | Rate Limiting | Configurable limits per endpoint | [Rate Limiting](https://www.better-auth.com/docs/concepts/rate-limit) |
34
+ | Organizations | Multi-tenant support with roles | [Organizations Plugin](https://www.better-auth.com/docs/plugins/organization) |
34
35
 
35
- // Sign up
36
- await authClient.signUp.email({
37
- email: 'user@example.com',
38
- password: 'password',
39
- name: 'User',
40
- });
36
+ ## Common Patterns
37
+
38
+ ### Client Setup with Plugins
41
39
 
42
- // Sign in
43
- await authClient.signIn.email({
44
- email: 'user@example.com',
45
- password: 'password',
40
+ ```typescript
41
+ // lib/auth-client.ts
42
+ import { createAuthClient } from "better-auth/client";
43
+ import { twoFactorClient, organizationClient } from "better-auth/client/plugins";
44
+
45
+ export const authClient = createAuthClient({
46
+ baseURL: process.env.NEXT_PUBLIC_API_URL,
47
+ plugins: [twoFactorClient(), organizationClient()],
46
48
  });
49
+
50
+ export const { signIn, signUp, signOut, useSession } = authClient;
51
+ ```
52
+
53
+ ### Protected Routes Middleware
54
+
55
+ ```typescript
56
+ // middleware.ts
57
+ import { auth } from "@/lib/auth";
58
+ import { NextRequest, NextResponse } from "next/server";
59
+
60
+ export async function middleware(request: NextRequest) {
61
+ const session = await auth.api.getSession({ headers: request.headers });
62
+
63
+ if (!session && !request.nextUrl.pathname.startsWith("/login")) {
64
+ return NextResponse.redirect(new URL("/login", request.url));
65
+ }
66
+ return NextResponse.next();
67
+ }
68
+ ```
69
+
70
+ ### Two-Factor Authentication Flow
71
+
72
+ ```typescript
73
+ // Handle 2FA during sign-in
74
+ const { data, error } = await authClient.signIn.email({ email, password });
75
+
76
+ if (error?.code === "TWO_FACTOR_REQUIRED") {
77
+ // Show 2FA input
78
+ const { data: verified } = await authClient.twoFactor.verify({ code: totpCode });
79
+ }
80
+
81
+ // Enable 2FA for user
82
+ const { data } = await authClient.twoFactor.enable();
83
+ // data.totpURI contains QR code data
84
+ // data.backupCodes contains recovery codes
47
85
  ```
48
86
 
49
87
  ## Best Practices
50
- - Enable rate limiting
51
- - Use secure cookies
52
- - Implement email verification
53
- - Add MFA option
88
+
89
+ | Do | Avoid |
90
+ |----|-------|
91
+ | Require email verification for new accounts | Storing plain-text passwords |
92
+ | Enable rate limiting on auth endpoints | Exposing detailed error messages |
93
+ | Use httpOnly, secure cookies | Using predictable session tokens |
94
+ | Set strong password requirements (12+ chars) | Allowing unlimited login attempts |
95
+ | Implement proper session expiration | Storing sensitive data in JWT |
96
+ | Log authentication events for auditing | Skipping CSRF protection |
97
+
98
+ ## References
99
+
100
+ - [Better Auth Documentation](https://www.better-auth.com/docs)
101
+ - [Better Auth Plugins](https://www.better-auth.com/docs/plugins)
102
+ - [OWASP Authentication Guidelines](https://owasp.org/www-project-web-security-testing-guide/)
@@ -1,50 +1,133 @@
1
1
  ---
2
- name: oauth
3
- description: OAuth 2.0 / OIDC. Use for third-party authentication, social login.
2
+ name: Implementing OAuth
3
+ description: Claude implements OAuth 2.0 and OpenID Connect authorization flows. Use when adding social login, integrating OAuth providers, managing tokens, or securing APIs with OAuth.
4
4
  ---
5
5
 
6
- # OAuth Skill
6
+ # Implementing OAuth
7
7
 
8
- ## Authorization Code Flow
8
+ ## Quick Start
9
+
10
+ ```typescript
11
+ // lib/oauth/client.ts
12
+ import crypto from "crypto";
13
+
14
+ export function generatePKCE() {
15
+ const codeVerifier = crypto.randomBytes(32).toString("base64url");
16
+ const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url");
17
+ const state = crypto.randomBytes(16).toString("hex");
18
+ return { codeVerifier, codeChallenge, state };
19
+ }
20
+
21
+ export function buildAuthUrl(config: OAuthConfig, pkce: PKCEPair) {
22
+ const params = new URLSearchParams({
23
+ client_id: config.clientId,
24
+ redirect_uri: config.redirectUri,
25
+ response_type: "code",
26
+ scope: config.scopes.join(" "),
27
+ state: pkce.state,
28
+ code_challenge: pkce.codeChallenge,
29
+ code_challenge_method: "S256",
30
+ });
31
+ return `${config.authorizationEndpoint}?${params}`;
32
+ }
9
33
  ```
10
- 1. Redirect to provider
11
- /authorize?client_id=X&redirect_uri=Y&scope=Z&response_type=code
12
34
 
13
- 2. User authorizes
35
+ ## Features
36
+
37
+ | Feature | Description | Reference |
38
+ |---------|-------------|-----------|
39
+ | Authorization Code + PKCE | Secure flow for public/confidential clients | [RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636) |
40
+ | Token Management | Access/refresh token handling and storage | [RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749) |
41
+ | OpenID Connect | Identity layer with ID tokens and claims | [OIDC Core](https://openid.net/specs/openid-connect-core-1_0.html) |
42
+ | Provider Integration | Google, GitHub, Microsoft configurations | [OIDC Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html) |
43
+ | JWT Validation | ID token signature and claims verification | [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519) |
44
+
45
+ ## Common Patterns
46
+
47
+ ### Token Exchange
48
+
49
+ ```typescript
50
+ async function exchangeCodeForTokens(code: string, codeVerifier: string) {
51
+ const response = await fetch(config.tokenEndpoint, {
52
+ method: "POST",
53
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
54
+ body: new URLSearchParams({
55
+ grant_type: "authorization_code",
56
+ code,
57
+ redirect_uri: config.redirectUri,
58
+ client_id: config.clientId,
59
+ code_verifier: codeVerifier,
60
+ }),
61
+ });
62
+
63
+ const data = await response.json();
64
+ return {
65
+ accessToken: data.access_token,
66
+ refreshToken: data.refresh_token,
67
+ expiresIn: data.expires_in,
68
+ idToken: data.id_token,
69
+ };
70
+ }
71
+ ```
14
72
 
15
- 3. Callback with code
16
- /callback?code=ABC
73
+ ### Provider Configuration
17
74
 
18
- 4. Exchange code for token
19
- POST /token
20
- { code, client_id, client_secret, redirect_uri }
75
+ ```typescript
76
+ // Google OAuth
77
+ const googleConfig = {
78
+ authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
79
+ tokenEndpoint: "https://oauth2.googleapis.com/token",
80
+ userInfoEndpoint: "https://openidconnect.googleapis.com/v1/userinfo",
81
+ scopes: ["openid", "email", "profile"],
82
+ };
21
83
 
22
- 5. Use access token
23
- Authorization: Bearer <token>
84
+ // GitHub OAuth
85
+ const githubConfig = {
86
+ authorizationEndpoint: "https://github.com/login/oauth/authorize",
87
+ tokenEndpoint: "https://github.com/login/oauth/access_token",
88
+ userInfoEndpoint: "https://api.github.com/user",
89
+ scopes: ["read:user", "user:email"],
90
+ };
24
91
  ```
25
92
 
26
- ## Implementation
93
+ ### Token Refresh Middleware
94
+
27
95
  ```typescript
28
- // Redirect to OAuth provider
29
- app.get('/auth/google', (req, res) => {
30
- const url = new URL('https://accounts.google.com/o/oauth2/v2/auth');
31
- url.searchParams.set('client_id', CLIENT_ID);
32
- url.searchParams.set('redirect_uri', REDIRECT_URI);
33
- url.searchParams.set('response_type', 'code');
34
- url.searchParams.set('scope', 'openid email profile');
35
- res.redirect(url.toString());
36
- });
37
-
38
- // Handle callback
39
- app.get('/auth/callback', async (req, res) => {
40
- const { code } = req.query;
41
- const tokens = await exchangeCodeForTokens(code);
42
- // Create session
43
- });
96
+ async function ensureFreshToken(req: Request, res: Response, next: NextFunction) {
97
+ const token = await tokenStore.get(req.session.userId);
98
+ if (!token) return next();
99
+
100
+ const timeUntilExpiry = token.expiresAt - Date.now();
101
+ if (timeUntilExpiry > 5 * 60 * 1000) {
102
+ req.accessToken = token.accessToken;
103
+ return next();
104
+ }
105
+
106
+ // Refresh token
107
+ const newTokens = await client.refreshTokens(token.refreshToken);
108
+ await tokenStore.save(req.session.userId, {
109
+ ...newTokens,
110
+ expiresAt: Date.now() + newTokens.expiresIn * 1000,
111
+ });
112
+ req.accessToken = newTokens.accessToken;
113
+ next();
114
+ }
44
115
  ```
45
116
 
46
117
  ## Best Practices
47
- - Use PKCE for public clients
48
- - Validate state parameter
49
- - Use short-lived tokens
50
- - Store tokens securely
118
+
119
+ | Do | Avoid |
120
+ |----|-------|
121
+ | Always use PKCE for authorization code flow | Using implicit flow for new apps |
122
+ | Validate state parameter to prevent CSRF | Storing tokens in localStorage |
123
+ | Store tokens securely (encrypted, httpOnly) | Exposing client secrets in frontend |
124
+ | Implement token refresh before expiration | Ignoring token expiration |
125
+ | Validate ID token signatures with JWKS | Trusting unverified ID tokens |
126
+ | Use short-lived access tokens | Reusing authorization codes |
127
+
128
+ ## References
129
+
130
+ - [OAuth 2.0 RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749)
131
+ - [OAuth 2.0 PKCE RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636)
132
+ - [OpenID Connect Core](https://openid.net/specs/openid-connect-core-1_0.html)
133
+ - [OAuth 2.0 Security Best Practices](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics)