Compare commits

...

5 Commits

Author SHA1 Message Date
cbd2559169 🐛 fix: normalize AI-generated dates to valid ISO offset datetimes
- add normalizeAiDateString() to coerce bare ISO datetimes, date-only
  strings, and fractional-second variants into offset-aware format
- apply via z.preprocess in AiEventResponseItemSchema so Zod validation
  no longer rejects AI responses missing a timezone offset
- fix system prompt to use toISOString() (unambiguous UTC) and clarify
  expected datetime format for the AI model
- install bun-types and add to tsconfig so bun:test resolves cleanly
- add 8 behaviour-driven tests covering all normalizer edge cases
2026-04-07 23:01:42 -04:00
f3ccbf5db5 fix: ignore .chrome dir that breaks turbopack
Signed-off-by: Dmytro Stanchiev <git@dmytros.dev>
2026-04-07 22:59:41 -04:00
735350a4d1 chore: create .chrome directory
Signed-off-by: Dmytro Stanchiev <git@dmytros.dev>
2026-04-07 17:06:19 -04:00
685241c92f chore: update skills
Signed-off-by: Dmytro Stanchiev <git@dmytros.dev>
2026-04-07 17:06:08 -04:00
7ffcb4dc43 chore: add dokploy mcp
Signed-off-by: Dmytro Stanchiev <git@dmytros.dev>
2026-04-07 16:12:28 -04:00
22 changed files with 175 additions and 537 deletions

View File

@@ -1,6 +0,0 @@
{
"source": "/tmp/skill-selector-curated-3423638041",
"sourceType": "local",
"localPath": "/tmp/skill-selector-curated-3423638041/broken-authentication",
"installedAt": "2026-04-07T00:45:24.780Z"
}

View File

@@ -1,480 +0,0 @@
---
name: broken-authentication
description: "Identify and exploit authentication and session management vulnerabilities in web applications. Broken authentication consistently ranks in the OWASP Top 10 and can lead to account takeover, identity theft, and unauthorized access to sensitive systems."
risk: unknown
source: community
author: zebbern
date_added: "2026-02-27"
---
# Broken Authentication Testing
## Purpose
Identify and exploit authentication and session management vulnerabilities in web applications. Broken authentication consistently ranks in the OWASP Top 10 and can lead to account takeover, identity theft, and unauthorized access to sensitive systems. This skill covers testing methodologies for password policies, session handling, multi-factor authentication, and credential management.
## Prerequisites
### Required Knowledge
- HTTP protocol and session mechanisms
- Authentication types (SFA, 2FA, MFA)
- Cookie and token handling
- Common authentication frameworks
### Required Tools
- Burp Suite Professional or Community
- Hydra or similar brute-force tools
- Custom wordlists for credential testing
- Browser developer tools
### Required Access
- Target application URL
- Test account credentials
- Written authorization for testing
## Outputs and Deliverables
1. **Authentication Assessment Report** - Document all identified vulnerabilities
2. **Credential Testing Results** - Brute-force and dictionary attack outcomes
3. **Session Security Analysis** - Token randomness and timeout evaluation
4. **Remediation Recommendations** - Security hardening guidance
## Core Workflow
### Phase 1: Authentication Mechanism Analysis
Understand the application's authentication architecture:
```
# Identify authentication type
- Password-based (forms, basic auth, digest)
- Token-based (JWT, OAuth, API keys)
- Certificate-based (mutual TLS)
- Multi-factor (SMS, TOTP, hardware tokens)
# Map authentication endpoints
/login, /signin, /authenticate
/register, /signup
/forgot-password, /reset-password
/logout, /signout
/api/auth/*, /oauth/*
```
Capture and analyze authentication requests:
```http
POST /login HTTP/1.1
Host: target.com
Content-Type: application/x-www-form-urlencoded
username=test&password=test123
```
### Phase 2: Password Policy Testing
Evaluate password requirements and enforcement:
```bash
# Test minimum length (a, ab, abcdefgh)
# Test complexity (password, password1, Password1!)
# Test common weak passwords (123456, password, qwerty, admin)
# Test username as password (admin/admin, test/test)
```
Document policy gaps: Minimum length <8, no complexity, common passwords allowed, username as password.
### Phase 3: Credential Enumeration
Test for username enumeration vulnerabilities:
```bash
# Compare responses for valid vs invalid usernames
# Invalid: "Invalid username" vs Valid: "Invalid password"
# Check timing differences, response codes, registration messages
```
# Password reset
"Email sent if account exists" (secure)
"No account with that email" (leaks info)
# API responses
{"error": "user_not_found"}
{"error": "invalid_password"}
```
### Phase 4: Brute Force Testing
Test account lockout and rate limiting:
```bash
# Using Hydra for form-based auth
hydra -l admin -P /usr/share/wordlists/rockyou.txt \
target.com http-post-form \
"/login:username=^USER^&password=^PASS^:Invalid credentials"
# Using Burp Intruder
1. Capture login request
2. Send to Intruder
3. Set payload positions on password field
4. Load wordlist
5. Start attack
6. Analyze response lengths/codes
```
Check for protections:
```bash
# Account lockout
- After how many attempts?
- Duration of lockout?
- Lockout notification?
# Rate limiting
- Requests per minute limit?
- IP-based or account-based?
- Bypass via headers (X-Forwarded-For)?
# CAPTCHA
- After failed attempts?
- Easily bypassable?
```
### Phase 5: Credential Stuffing
Test with known breached credentials:
```bash
# Credential stuffing differs from brute force
# Uses known email:password pairs from breaches
# Using Burp Intruder with Pitchfork attack
1. Set username and password as positions
2. Load email list as payload 1
3. Load password list as payload 2 (matched pairs)
4. Analyze for successful logins
# Detection evasion
- Slow request rate
- Rotate source IPs
- Randomize user agents
- Add delays between attempts
```
### Phase 6: Session Management Testing
Analyze session token security:
```bash
# Capture session cookie
Cookie: SESSIONID=abc123def456
# Test token characteristics
1. Entropy - Is it random enough?
2. Length - Sufficient length (128+ bits)?
3. Predictability - Sequential patterns?
4. Secure flags - HttpOnly, Secure, SameSite?
```
Session token analysis:
```python
#!/usr/bin/env python3
import requests
import hashlib
# Collect multiple session tokens
tokens = []
for i in range(100):
response = requests.get("https://target.com/login")
token = response.cookies.get("SESSIONID")
tokens.append(token)
# Analyze for patterns
# Check for sequential increments
# Calculate entropy
# Look for timestamp components
```
### Phase 7: Session Fixation Testing
Test if session is regenerated after authentication:
```bash
# Step 1: Get session before login
GET /login HTTP/1.1
Response: Set-Cookie: SESSIONID=abc123
# Step 2: Login with same session
POST /login HTTP/1.1
Cookie: SESSIONID=abc123
username=valid&password=valid
# Step 3: Check if session changed
# VULNERABLE if SESSIONID remains abc123
# SECURE if new session assigned after login
```
Attack scenario:
```bash
# Attacker workflow:
1. Attacker visits site, gets session: SESSIONID=attacker_session
2. Attacker sends link to victim with fixed session:
https://target.com/login?SESSIONID=attacker_session
3. Victim logs in with attacker's session
4. Attacker now has authenticated session
```
### Phase 8: Session Timeout Testing
Verify session expiration policies:
```bash
# Test idle timeout
1. Login and note session cookie
2. Wait without activity (15, 30, 60 minutes)
3. Attempt to use session
4. Check if session is still valid
# Test absolute timeout
1. Login and continuously use session
2. Check if forced logout after set period (8 hours, 24 hours)
# Test logout functionality
1. Login and note session
2. Click logout
3. Attempt to reuse old session cookie
4. Session should be invalidated server-side
```
### Phase 9: Multi-Factor Authentication Testing
Assess MFA implementation security:
```bash
# OTP brute force
- 4-digit OTP = 10,000 combinations
- 6-digit OTP = 1,000,000 combinations
- Test rate limiting on OTP endpoint
# OTP bypass techniques
- Skip MFA step by direct URL access
- Modify response to indicate MFA passed
- Null/empty OTP submission
- Previous valid OTP reuse
# API Version Downgrade Attack (crAPI example)
# If /api/v3/check-otp has rate limiting, try older versions:
POST /api/v2/check-otp
{"otp": "1234"}
# Older API versions may lack security controls
# Using Burp for OTP testing
1. Capture OTP verification request
2. Send to Intruder
3. Set OTP field as payload position
4. Use numbers payload (0000-9999)
5. Check for successful bypass
```
Test MFA enrollment:
```bash
# Forced enrollment
- Can MFA be skipped during setup?
- Can backup codes be accessed without verification?
# Recovery process
- Can MFA be disabled via email alone?
- Social engineering potential?
```
### Phase 10: Password Reset Testing
Analyze password reset security:
```bash
# Token security
1. Request password reset
2. Capture reset link
3. Analyze token:
- Length and randomness
- Expiration time
- Single-use enforcement
- Account binding
# Token manipulation
https://target.com/reset?token=abc123&user=victim
# Try changing user parameter while using valid token
# Host header injection
POST /forgot-password HTTP/1.1
Host: attacker.com
email=victim@email.com
# Reset email may contain attacker's domain
```
## Quick Reference
### Common Vulnerability Types
| Vulnerability | Risk | Test Method |
|--------------|------|-------------|
| Weak passwords | High | Policy testing, dictionary attack |
| No lockout | High | Brute force testing |
| Username enumeration | Medium | Differential response analysis |
| Session fixation | High | Pre/post-login session comparison |
| Weak session tokens | High | Entropy analysis |
| No session timeout | Medium | Long-duration session testing |
| Insecure password reset | High | Token analysis, workflow bypass |
| MFA bypass | Critical | Direct access, response manipulation |
### Credential Testing Payloads
```bash
# Default credentials
admin:admin
admin:password
admin:123456
root:root
test:test
user:user
# Common passwords
123456
password
12345678
qwerty
abc123
password1
admin123
# Breached credential databases
- Have I Been Pwned dataset
- SecLists passwords
- Custom targeted lists
```
### Session Cookie Flags
| Flag | Purpose | Vulnerability if Missing |
|------|---------|------------------------|
| HttpOnly | Prevent JS access | XSS can steal session |
| Secure | HTTPS only | Sent over HTTP |
| SameSite | CSRF protection | Cross-site requests allowed |
| Path | URL scope | Broader exposure |
| Domain | Domain scope | Subdomain access |
| Expires | Lifetime | Persistent sessions |
### Rate Limiting Bypass Headers
```http
X-Forwarded-For: 127.0.0.1
X-Real-IP: 127.0.0.1
X-Originating-IP: 127.0.0.1
X-Client-IP: 127.0.0.1
X-Remote-IP: 127.0.0.1
True-Client-IP: 127.0.0.1
```
## Constraints and Limitations
### Legal Requirements
- Only test with explicit written authorization
- Avoid testing with real breached credentials
- Do not access actual user accounts
- Document all testing activities
### Technical Limitations
- CAPTCHA may prevent automated testing
- Rate limiting affects brute force timing
- MFA significantly increases attack difficulty
- Some vulnerabilities require victim interaction
### Scope Considerations
- Test accounts may behave differently than production
- Some features may be disabled in test environments
- Third-party authentication may be out of scope
- Production testing requires extra caution
## Examples
### Example 1: Account Lockout Bypass
**Scenario:** Test if account lockout can be bypassed
```bash
# Step 1: Identify lockout threshold
# Try 5 wrong passwords for admin account
# Result: "Account locked for 30 minutes"
# Step 2: Test bypass via IP rotation
# Use X-Forwarded-For header
POST /login HTTP/1.1
X-Forwarded-For: 192.168.1.1
username=admin&password=attempt1
# Increment IP for each attempt
X-Forwarded-For: 192.168.1.2
# Continue until successful or confirmed blocked
# Step 3: Test bypass via case manipulation
username=Admin (vs admin)
username=ADMIN
# Some systems treat these as different accounts
```
### Example 2: JWT Token Attack
**Scenario:** Exploit weak JWT implementation
```bash
# Step 1: Capture JWT token
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoidGVzdCJ9.signature
# Step 2: Decode and analyze
# Header: {"alg":"HS256","typ":"JWT"}
# Payload: {"user":"test","role":"user"}
# Step 3: Try "none" algorithm attack
# Change header to: {"alg":"none","typ":"JWT"}
# Remove signature
eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJ1c2VyIjoiYWRtaW4iLCJyb2xlIjoiYWRtaW4ifQ.
# Step 4: Submit modified token
Authorization: Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJ1c2VyIjoiYWRtaW4ifQ.
```
### Example 3: Password Reset Token Exploitation
**Scenario:** Test password reset functionality
```bash
# Step 1: Request reset for test account
POST /forgot-password
email=test@example.com
# Step 2: Capture reset link
https://target.com/reset?token=a1b2c3d4e5f6
# Step 3: Test token properties
# Reuse: Try using same token twice
# Expiration: Wait 24+ hours and retry
# Modification: Change characters in token
# Step 4: Test for user parameter manipulation
https://target.com/reset?token=a1b2c3d4e5f6&email=admin@example.com
# Check if admin's password can be reset with test user's token
```
## Troubleshooting
| Issue | Solutions |
|-------|-----------|
| Brute force too slow | Identify rate limit scope; IP rotation; add delays; use targeted wordlists |
| Session analysis inconclusive | Collect 1000+ tokens; use statistical tools; check for timestamps; compare accounts |
| MFA cannot be bypassed | Document as secure; test backup/recovery mechanisms; check MFA fatigue; verify enrollment |
| Account lockout prevents testing | Request multiple test accounts; test threshold first; use slower timing |
## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

View File

@@ -145,7 +145,7 @@ bun install # or 'bun i'
# Add dependencies # Add dependencies
bun add express # Regular dependency bun add express # Regular dependency
bun add -d typescript # Dev dependency bun add -d typescript # Dev dependency
bun add -D @types/node # Dev dependency (alias) bun add -D @types/bun # Dev dependency (alias)
bun add --optional pkg # Optional dependency bun add --optional pkg # Optional dependency
# From specific registry # From specific registry
@@ -176,7 +176,7 @@ bun update --latest # Update to latest (ignore ranges)
bun outdated bun outdated
``` ```
### 3.3 bunx (npx equivalent) ### 3.3 bunx (bunx --bun equivalent)
```bash ```bash
# Execute package binaries # Execute package binaries
@@ -595,7 +595,7 @@ rm -rf node_modules package-lock.json
bun install bun install
# 3. Update scripts in package.json # 3. Update scripts in package.json
# "start": "node index.js" → "start": "bun run index.ts" # "start": "bun --bun index.js" → "start": "bun run index.ts"
# "test": "jest" → "test": "bun test" # "test": "jest" → "test": "bun test"
# 4. Add Bun types # 4. Add Bun types

View File

@@ -205,16 +205,16 @@ export default defineConfig({
```bash ```bash
# Generate migration SQL from schema changes # Generate migration SQL from schema changes
npx drizzle-kit generate bunx --bun drizzle-kit generate
# Push schema directly to database (development only — skips migration files) # Push schema directly to database (development only — skips migration files)
npx drizzle-kit push bunx --bun drizzle-kit push
# Run pending migrations (production) # Run pending migrations (production)
npx drizzle-kit migrate bunx --bun drizzle-kit migrate
# Open Drizzle Studio (GUI database browser) # Open Drizzle Studio (GUI database browser)
npx drizzle-kit studio bunx --bun drizzle-kit studio
``` ```
## Database Client Setup ## Database Client Setup
@@ -357,7 +357,7 @@ export async function createUser(formData: FormData) {
**Solution:** Pass all schema objects (including relations) to `drizzle()`: `drizzle(client, { schema })` **Solution:** Pass all schema objects (including relations) to `drizzle()`: `drizzle(client, { schema })`
**Problem:** Migration conflicts after schema changes **Problem:** Migration conflicts after schema changes
**Solution:** Run `npx drizzle-kit generate` to create a new migration, then `npx drizzle-kit migrate` **Solution:** Run `bunx --bun drizzle-kit generate` to create a new migration, then `bunx --bun drizzle-kit migrate`
**Problem:** Type errors on `.returning()` with MySQL **Problem:** Type errors on `.returning()` with MySQL
**Solution:** MySQL does not support `RETURNING`. Use `.execute()` and read `insertId` from the result instead. **Solution:** MySQL does not support `RETURNING`. Use `.execute()` and read `insertId` from the result instead.

View File

@@ -6,7 +6,7 @@
```bash ```bash
# Install Vercel CLI # Install Vercel CLI
npm i -g vercel bun --bun i -g vercel
# Deploy # Deploy
vercel vercel
@@ -21,7 +21,7 @@ vercel --prod
{ {
"buildCommand": "next build", "buildCommand": "next build",
"devCommand": "next dev", "devCommand": "next dev",
"installCommand": "npm install", "installCommand": "bun --bun install",
"framework": "nextjs", "framework": "nextjs",
"regions": ["iad1"], "regions": ["iad1"],
"env": { "env": {
@@ -88,7 +88,7 @@ module.exports = nextConfig
```bash ```bash
# Build # Build
npm run build bun --bun run build
# The standalone folder contains everything needed # The standalone folder contains everything needed
# Copy these to your server: # Copy these to your server:
@@ -97,20 +97,20 @@ npm run build
# - public/ # - public/
# Run on server # Run on server
node .next/standalone/server.js bun --bun .next/standalone/server.js
``` ```
### Node.js Server ### Node.js Server
```bash ```bash
# Build # Build
npm run build bun --bun run build
# Start production server # Start production server
npm start bun --bun start
# With PM2 for process management # With PM2 for process management
pm2 start npm --name "nextjs" -- start pm2 start bun --bun --name "nextjs" -- start
pm2 startup pm2 startup
pm2 save pm2 save
``` ```
@@ -126,7 +126,7 @@ RUN apk add --no-cache libc6-compat
WORKDIR /app WORKDIR /app
COPY package.json package-lock.json ./ COPY package.json package-lock.json ./
RUN npm ci RUN bun --bun ci
# Stage 2: Builder # Stage 2: Builder
FROM node:20-alpine AS builder FROM node:20-alpine AS builder
@@ -136,7 +136,7 @@ COPY . .
ENV NEXT_TELEMETRY_DISABLED 1 ENV NEXT_TELEMETRY_DISABLED 1
RUN npm run build RUN bun --bun run build
# Stage 3: Runner # Stage 3: Runner
FROM node:20-alpine AS runner FROM node:20-alpine AS runner
@@ -298,13 +298,13 @@ module.exports = nextConfig
```bash ```bash
# Install analyzer # Install analyzer
npm install -D @next/bundle-analyzer bun --bun install -D @next/bundle-analyzer
# Analyze # Analyze
ANALYZE=true npm run build ANALYZE=true bun --bun run build
# Or use built-in # Or use built-in
npm run build -- --experimental-build-mode=compile bun --bun run build -- --experimental-build-mode=compile
``` ```
### Performance Monitoring ### Performance Monitoring
@@ -474,13 +474,13 @@ jobs:
cache: 'npm' cache: 'npm'
- name: Install dependencies - name: Install dependencies
run: npm ci run: bun --bun ci
- name: Run tests - name: Run tests
run: npm test run: bun --bun test
- name: Build - name: Build
run: npm run build run: bun --bun run build
env: env:
DATABASE_URL: ${{ secrets.DATABASE_URL }} DATABASE_URL: ${{ secrets.DATABASE_URL }}
NEXTAUTH_SECRET: ${{ secrets.NEXTAUTH_SECRET }} NEXTAUTH_SECRET: ${{ secrets.NEXTAUTH_SECRET }}

View File

@@ -13,7 +13,7 @@ A comprehensive TypeScript SDK for interacting with OpenRouter's unified API, pr
## Installation ## Installation
```bash ```bash
npm install @openrouter/sdk bun --bun install @openrouter/sdk
``` ```
## Setup ## Setup

View File

@@ -27,10 +27,10 @@ You are an advanced TypeScript expert with deep, practical knowledge of type-lev
```bash ```bash
# Core versions and configuration # Core versions and configuration
npx tsc --version bunx --bun tsc --version
node -v bun --bun -v
# Detect tooling ecosystem (prefer parsing package.json) # Detect tooling ecosystem (prefer parsing package.json)
node -e "const p=require('./package.json');console.log(Object.keys({...p.devDependencies,...p.dependencies}||{}).join('\n'))" 2>/dev/null | grep -E 'biome|eslint|prettier|vitest|jest|turborepo|nx' || echo "No tooling detected" bun --bun -e "const p=require('./package.json');console.log(Object.keys({...p.devDependencies,...p.dependencies}||{}).join('\n'))" 2>/dev/null | grep -E 'biome|eslint|prettier|vitest|jest|turborepo|nx' || echo "No tooling detected"
# Check for monorepo (fixed precedence) # Check for monorepo (fixed precedence)
(test -f pnpm-workspace.yaml || test -f lerna.json || test -f nx.json || test -f turbo.json) && echo "Monorepo detected" (test -f pnpm-workspace.yaml || test -f lerna.json || test -f nx.json || test -f turbo.json) && echo "Monorepo detected"
``` ```
@@ -48,10 +48,10 @@ You are an advanced TypeScript expert with deep, practical knowledge of type-lev
4. Validate thoroughly: 4. Validate thoroughly:
```bash ```bash
# Fast fail approach (avoid long-lived processes) # Fast fail approach (avoid long-lived processes)
npm run -s typecheck || npx tsc --noEmit bun --bun run -s typecheck || bunx --bun tsc --noEmit
npm test -s || npx vitest run --reporter=basic --no-watch bun --bun test -s || bunx --bun vitest run --reporter=basic --no-watch
# Only if needed and build affects outputs/config # Only if needed and build affects outputs/config
npm run -s build bun --bun run -s build
``` ```
**Safety note:** Avoid watch/serve processes in validation. Use one-shot diagnostics only. **Safety note:** Avoid watch/serve processes in validation. Use one-shot diagnostics only.
@@ -110,7 +110,7 @@ type Route = typeof routes[number]; // '/home' | '/about' | '/contact'
**Type Checking Performance** **Type Checking Performance**
```bash ```bash
# Diagnose slow type checking # Diagnose slow type checking
npx tsc --extendedDiagnostics --incremental false | grep -E "Check time|Files:|Lines:|Nodes:" bunx --bun tsc --extendedDiagnostics --incremental false | grep -E "Check time|Files:|Lines:|Nodes:"
# Common fixes for "Type instantiation is excessively deep" # Common fixes for "Type instantiation is excessively deep"
# 1. Replace type intersections with interfaces # 1. Replace type intersections with interfaces
@@ -197,8 +197,8 @@ type NestedArray<T, D extends number = 5> =
# 4. Enable strict mode features one by one # 4. Enable strict mode features one by one
# Automated helpers (if installed/needed) # Automated helpers (if installed/needed)
command -v ts-migrate >/dev/null 2>&1 && npx ts-migrate migrate . --sources 'src/**/*.js' command -v ts-migrate >/dev/null 2>&1 && bunx --bun ts-migrate migrate . --sources 'src/**/*.js'
command -v typesync >/dev/null 2>&1 && npx typesync # Install missing @types packages command -v typesync >/dev/null 2>&1 && bunx --bun typesync # Install missing @types packages
``` ```
**Tool Migration Decisions** **Tool Migration Decisions**
@@ -275,20 +275,20 @@ test('Avatar props are correctly typed', () => {
### CLI Debugging Tools ### CLI Debugging Tools
```bash ```bash
# Debug TypeScript files directly (if tools installed) # Debug TypeScript files directly (if tools installed)
command -v tsx >/dev/null 2>&1 && npx tsx --inspect src/file.ts command -v tsx >/dev/null 2>&1 && bunx --bun tsx --inspect src/file.ts
command -v ts-node >/dev/null 2>&1 && npx ts-node --inspect-brk src/file.ts command -v ts-node >/dev/null 2>&1 && bunx --bun ts-node --inspect-brk src/file.ts
# Trace module resolution issues # Trace module resolution issues
npx tsc --traceResolution > resolution.log 2>&1 bunx --bun tsc --traceResolution > resolution.log 2>&1
grep "Module resolution" resolution.log grep "Module resolution" resolution.log
# Debug type checking performance (use --incremental false for clean trace) # Debug type checking performance (use --incremental false for clean trace)
npx tsc --generateTrace trace --incremental false bunx --bun tsc --generateTrace trace --incremental false
# Analyze trace (if installed) # Analyze trace (if installed)
command -v @typescript/analyze-trace >/dev/null 2>&1 && npx @typescript/analyze-trace trace command -v @typescript/analyze-trace >/dev/null 2>&1 && bunx --bun @typescript/analyze-trace trace
# Memory usage analysis # Memory usage analysis
node --max-old-space-size=8192 node_modules/typescript/lib/tsc.js bun --bun --max-old-space-size=8192 node_modules/typescript/lib/tsc.js
``` ```
### Custom Error Classes ### Custom Error Classes

View File

@@ -23,8 +23,8 @@ def check_versions():
print("\n📦 Versions:") print("\n📦 Versions:")
print("-" * 40) print("-" * 40)
ts_version = run_cmd("npx tsc --version 2>/dev/null").strip() ts_version = run_cmd("bunx --bun tsc --version 2>/dev/null").strip()
node_version = run_cmd("node -v 2>/dev/null").strip() node_version = run_cmd("bun --bun -v 2>/dev/null").strip()
print(f" TypeScript: {ts_version or 'Not found'}") print(f" TypeScript: {ts_version or 'Not found'}")
print(f" Node.js: {node_version or 'Not found'}") print(f" Node.js: {node_version or 'Not found'}")
@@ -134,7 +134,7 @@ def check_type_errors():
print("\n🔍 Type Check:") print("\n🔍 Type Check:")
print("-" * 40) print("-" * 40)
result = run_cmd("npx tsc --noEmit 2>&1 | head -20") result = run_cmd("bunx --bun tsc --noEmit 2>&1 | head -20")
if "error TS" in result: if "error TS" in result:
errors = result.count("error TS") errors = result.count("error TS")
print(f"{errors}+ type errors found") print(f"{errors}+ type errors found")
@@ -174,7 +174,7 @@ def check_performance():
print("\n⏱️ Type Check Performance:") print("\n⏱️ Type Check Performance:")
print("-" * 40) print("-" * 40)
result = run_cmd("npx tsc --extendedDiagnostics --noEmit 2>&1 | grep -E 'Check time|Files:|Lines:|Nodes:'") result = run_cmd("bunx --bun tsc --extendedDiagnostics --noEmit 2>&1 | grep -E 'Check time|Files:|Lines:|Nodes:'")
if result.strip(): if result.strip():
for line in result.strip().split('\n'): for line in result.strip().split('\n'):
print(f" {line}") print(f" {line}")

View File

@@ -424,7 +424,7 @@ tsc --extendedDiagnostics
tsc --generateTrace trace tsc --generateTrace trace
# Analyze with @typescript/analyze-trace # Analyze with @typescript/analyze-trace
npx @typescript/analyze-trace trace bunx --bun @typescript/analyze-trace trace
``` ```
## Quick Reference ## Quick Reference

1
.gitignore vendored
View File

@@ -77,3 +77,4 @@ public/workbox-*.js
# END Ruler Generated Files # END Ruler Generated Files
/debug.log /debug.log
/.tmp/external-context /.tmp/external-context
/.chrome/profile

View File

@@ -29,8 +29,8 @@ Usage notes:
</skill> </skill>
<skill> <skill>
<name>broken-authentication</name> <name>bun-development</name>
<description>"Identify and exploit authentication and session management vulnerabilities in web applications. Broken authentication consistently ranks in the OWASP Top 10 and can lead to account takeover, identity theft, and unauthorized access to sensitive systems."</description> <description>"Fast, modern JavaScript/TypeScript development with the Bun runtime, inspired by [oven-sh/bun](https://github.com/oven-sh/bun)."</description>
<location>project</location> <location>project</location>
</skill> </skill>
@@ -70,6 +70,12 @@ Usage notes:
<location>project</location> <location>project</location>
</skill> </skill>
<skill>
<name>openrouter-typescript-sdk</name>
<description>Complete reference for integrating with 300+ AI models through the OpenRouter TypeScript SDK using the callModel pattern</description>
<location>project</location>
</skill>
<skill> <skill>
<name>react-nextjs-development</name> <name>react-nextjs-development</name>
<description>"React and Next.js 14+ application development with App Router, Server Components, TypeScript, Tailwind CSS, and modern frontend patterns."</description> <description>"React and Next.js 14+ application development with App Router, Server Components, TypeScript, Tailwind CSS, and modern frontend patterns."</description>
@@ -100,6 +106,12 @@ Usage notes:
<location>project</location> <location>project</location>
</skill> </skill>
<skill>
<name>zod-validation-expert</name>
<description>"Expert in Zod — TypeScript-first schema validation. Covers parsing, custom errors, refinements, type inference, and integration with React Hook Form, Next.js, and tRPC."</description>
<location>project</location>
</skill>
</available_skills> </available_skills>
<!-- SKILLS_TABLE_END --> <!-- SKILLS_TABLE_END -->

View File

@@ -103,3 +103,10 @@ command = "mcp-nixos"
# [mcp_servers.kagi] # [mcp_servers.kagi]
# command = "kagimcp" # command = "kagimcp"
# env.KAGI_API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # env.KAGI_API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
#
[mcp_servers.dokploy]
type = "stdio"
command = "bunx"
args = ["-y", "@ahdev/dokploy-mcp@latest"]
env.DOKPLOY_URL = "https://dokploy.cloud.dmytros.dev/api"
env.DOKPLOY_API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

View File

@@ -41,6 +41,7 @@
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
"@typescript/native-preview": "^7.0.0-dev.20260407.1", "@typescript/native-preview": "^7.0.0-dev.20260407.1",
"bun-types": "^1.3.11",
"drizzle-kit": "^0.31.4", "drizzle-kit": "^0.31.4",
"eslint": "^9", "eslint": "^9",
"eslint-config-next": "15.4.6", "eslint-config-next": "15.4.6",
@@ -521,6 +522,8 @@
"buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="], "buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="],
"bun-types": ["bun-types@1.3.11", "", { "dependencies": { "@types/node": "*" } }, "sha512-1KGPpoxQWl9f6wcZh57LvrPIInQMn2TQ7jsgxqpRzg+l0QPOFvJVH7HmvHo/AiPgwXy+/Thf6Ov3EdVn1vOabg=="],
"call-bind": ["call-bind@1.0.8", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.0", "es-define-property": "^1.0.0", "get-intrinsic": "^1.2.4", "set-function-length": "^1.2.2" } }, "sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww=="], "call-bind": ["call-bind@1.0.8", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.0", "es-define-property": "^1.0.0", "get-intrinsic": "^1.2.4", "set-function-length": "^1.2.2" } }, "sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww=="],
"call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="], "call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],

View File

@@ -46,6 +46,7 @@
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
"@typescript/native-preview": "^7.0.0-dev.20260407.1", "@typescript/native-preview": "^7.0.0-dev.20260407.1",
"bun-types": "^1.3.11",
"drizzle-kit": "^0.31.4", "drizzle-kit": "^0.31.4",
"eslint": "^9", "eslint": "^9",
"eslint-config-next": "15.4.6", "eslint-config-next": "15.4.6",

View File

@@ -17,7 +17,7 @@ TypeScript type:
description?: string, description?: string,
location?: string, location?: string,
url?: string, url?: string,
start: string, // ISO datetime start: string, // ISO 8601 datetime with timezone, e.g. "2025-04-10T10:00:00-04:00"
end?: string, end?: string,
allDay?: boolean, allDay?: boolean,
recurrenceRule?: string // valid iCal RRULE string like FREQ=WEEKLY;BYDAY=MO;INTERVAL=1 recurrenceRule?: string // valid iCal RRULE string like FREQ=WEEKLY;BYDAY=MO;INTERVAL=1
@@ -26,7 +26,7 @@ TypeScript type:
Rules: Rules:
- If the user describes multiple events in one prompt, return multiple objects (one per event). - If the user describes multiple events in one prompt, return multiple objects (one per event).
- Always return a valid JSON array of objects, even if there's only one event. - Always return a valid JSON array of objects, even if there's only one event.
- Today is ${new Date().toLocaleString()}. - Today is ${new Date().toISOString()}.
- If no time is given, assume allDay event. - If no time is given, assume allDay event.
- If no end time is given (and event is not allDay), default to 1 hour after start. - If no end time is given (and event is not allDay), default to 1 hour after start.
- If multiple events are described, return multiple. - If multiple events are described, return multiple.

View File

@@ -0,0 +1,10 @@
import { formatISO, parseISO } from "date-fns";
const ISO_DATETIME_WITH_OFFSET =
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(Z|[+-]\d{2}:\d{2})$/;
export const normalizeAiDateString = (input: string): string => {
if (ISO_DATETIME_WITH_OFFSET.test(input)) return input;
const parsed = parseISO(input);
return formatISO(parsed);
};

View File

@@ -1,5 +1,6 @@
import { z } from "zod"; import { z } from "zod";
import { MAX_IMAGE_SIZE_BYTES } from "@/lib/constants"; import { MAX_IMAGE_SIZE_BYTES } from "@/lib/constants";
import { normalizeAiDateString } from "@/lib/date-normalizer";
/** Validates that a base64 data URL string decodes to binary under the max size. */ /** Validates that a base64 data URL string decodes to binary under the max size. */
const isValidImageSize = (val: string | undefined): boolean => { const isValidImageSize = (val: string | undefined): boolean => {
@@ -29,14 +30,19 @@ export const AiEventRequestSchema = z
export type AiEventRequest = z.infer<typeof AiEventRequestSchema>; export type AiEventRequest = z.infer<typeof AiEventRequestSchema>;
const aiDatetime = z.preprocess(
(val) => (typeof val === "string" ? normalizeAiDateString(val) : val),
z.string().datetime({ offset: true }),
);
export const AiEventResponseItemSchema = z.object({ export const AiEventResponseItemSchema = z.object({
id: z.string().optional(), id: z.string().optional(),
title: z.string().min(1), title: z.string().min(1),
description: z.string().optional(), description: z.string().optional(),
location: z.string().optional(), location: z.string().optional(),
url: z.string().optional(), url: z.string().optional(),
start: z.string().datetime({ offset: true }), start: aiDatetime,
end: z.string().datetime({ offset: true }).optional(), end: aiDatetime.optional(),
allDay: z.boolean().optional(), allDay: z.boolean().optional(),
recurrenceRule: z.string().optional(), recurrenceRule: z.string().optional(),
}); });

View File

@@ -0,0 +1,83 @@
import { describe, expect, test } from "bun:test";
import { normalizeAiDateString } from "@/lib/date-normalizer";
import { AiEventResponseSchema } from "@/lib/types";
describe("normalizeAiDateString", () => {
test("converts bare ISO datetime (no offset) to valid offset datetime accepted by Zod", () => {
const input = "2025-04-10T10:00:00";
const result = normalizeAiDateString(input);
expect(result).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(Z|[+-]\d{2}:\d{2})$/);
expect(new Date(result).getHours()).toBe(10);
});
test("converts date-only string to midnight datetime with offset", () => {
const input = "2025-04-10";
const result = normalizeAiDateString(input);
expect(result).toMatch(/^\d{4}-\d{2}-\d{2}T00:00:00(Z|[+-]\d{2}:\d{2})$/);
});
test("passes through already-valid datetime with offset unchanged", () => {
const input = "2025-04-10T10:00:00-04:00";
const result = normalizeAiDateString(input);
expect(result).toBe("2025-04-10T10:00:00-04:00");
});
test("passes through datetime with Z suffix unchanged", () => {
const input = "2025-04-10T10:00:00Z";
const result = normalizeAiDateString(input);
expect(result).toBe("2025-04-10T10:00:00Z");
});
test("handles datetime with fractional seconds", () => {
const input = "2025-04-10T10:00:00.000Z";
const result = normalizeAiDateString(input);
expect(result).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/);
expect(new Date(result).getHours()).toBe(10);
});
});
describe("AiEventResponseSchema date normalization", () => {
test("accepts event with bare ISO datetime (no offset) by normalizing it", () => {
const raw = [
{
title: "Team Meeting",
start: "2025-04-10T10:00:00",
end: "2025-04-10T11:00:00",
},
];
const result = AiEventResponseSchema.safeParse(raw);
expect(result.success).toBe(true);
if (result.success) {
expect(result.data[0].start).toMatch(
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(Z|[+-]\d{2}:\d{2})$/,
);
}
});
test("accepts event with date-only start and no end", () => {
const raw = [
{
title: "All-day workshop",
start: "2025-07-20",
allDay: true,
},
];
const result = AiEventResponseSchema.safeParse(raw);
expect(result.success).toBe(true);
});
test("accepts event with already-valid offset datetime", () => {
const raw = [
{
title: "Standup",
start: "2025-04-10T09:00:00-05:00",
end: "2025-04-10T09:30:00-05:00",
},
];
const result = AiEventResponseSchema.safeParse(raw);
expect(result.success).toBe(true);
if (result.success) {
expect(result.data[0].start).toBe("2025-04-10T09:00:00-05:00");
}
});
});

View File

@@ -20,7 +20,8 @@
], ],
"paths": { "paths": {
"@/*": ["./src/*"] "@/*": ["./src/*"]
} },
"types": ["bun-types"]
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"] "exclude": ["node_modules"]