

Also from Kynth Studios


Also from Kynth Studios


Also from Kynth Studios
12345# JavaScript Identification and Authentication Failures (OWASP A07:2021)67<rule>8name: javascript_identification_authentication_failures9description: Detect and prevent identification and authentication failures in JavaScript applications as defined in OWASP Top 10:2021-A071011actions:12 - type: enforce13 conditions:14 # Pattern 1: Weak Password Validation15 - pattern: "(?:password|passwd|pwd)\\s*\\.\\s*(?:length\\s*[<>]=?\\s*(?:[0-9]|10)\\b|match\\(\\s*['\"][^'\"]*['\"]\\s*\\))"16 message: "Weak password validation detected. Implement strong password policies requiring minimum length, complexity, and avoiding common passwords."1718 # Pattern 2: Missing MFA Implementation19 - pattern: "(?:login|signin|authenticate|auth)\\s*\\([^)]*\\)\\s*\\{[^}]*?\\}"20 negative_pattern: "(?:mfa|2fa|two-factor|multi-factor|otp|totp)"21 message: "Authentication implementation without multi-factor authentication (MFA). Consider implementing MFA for enhanced security."2223 # Pattern 3: Hardcoded Credentials24 - pattern: "(?:const|let|var)\\s+(?:password|passwd|pwd|secret|key|token|apiKey)\\s*=\\s*['\"][^'\"]+['\"]"25 message: "Hardcoded credentials detected. Store sensitive authentication data in secure configuration or environment variables."2627 # Pattern 4: Insecure Session Management28 - pattern: "(?:localStorage|sessionStorage)\\.setItem\\(['\"](?:token|jwt|session|auth|user)['\"]"29 message: "Storing authentication tokens in localStorage or sessionStorage. Consider using HttpOnly cookies for sensitive authentication data."3031 # Pattern 5: Missing CSRF Protection32 - pattern: "(?:post|put|delete|patch)\\([^)]*?\\)"33 negative_pattern: "(?:csrf|xsrf|token)"34 location: "(?:src|components|pages|api)"35 message: "Potential missing CSRF protection in API requests. Implement CSRF tokens for state-changing operations."3637 # Pattern 6: Insecure JWT Handling38 - pattern: "jwt\\.sign\\([^)]*?{[^}]*?}\\s*,\\s*[^,)]+\\s*(?:\\)|,\\s*{\\s*(?:expiresIn|algorithm)\\s*:\\s*[^}]*?}\\s*\\))"39 negative_pattern: "(?:expiresIn|exp).*(?:algorithm|alg)"40 message: "Insecure JWT configuration. Ensure JWTs have proper expiration and use secure algorithms (RS256 preferred over HS256)."4142 # Pattern 7: Insecure Password Storage43 - pattern: "(?:bcrypt|argon2|pbkdf2|scrypt)\\.[^(]*\\([^)]*?(?:rounds|iterations|cost|factor)\\s*[:<=>]\\s*(?:[0-9]|1[0-2])\\b"44 message: "Weak password hashing parameters. Use sufficient work factors for password hashing algorithms."4546 # Pattern 8: Missing Account Lockout47 - pattern: "(?:login|signin|authenticate|auth)\\s*\\([^)]*\\)\\s*\\{[^}]*?\\}"48 negative_pattern: "(?:lock|attempt|count|limit|throttle|rate)"49 message: "Authentication implementation without account lockout or rate limiting. Implement account lockout after failed attempts."5051 # Pattern 9: Insecure Password Recovery52 - pattern: "(?:reset|forgot|recover)(?:Password|Pwd)\\s*\\([^)]*\\)\\s*\\{[^}]*?\\}"53 negative_pattern: "(?:expire|timeout|token|verify)"54 message: "Potentially insecure password recovery mechanism. Implement secure, time-limited recovery tokens."5556 # Pattern 10: Missing Brute Force Protection57 - pattern: "(?:login|signin|authenticate|auth)\\s*\\([^)]*\\)\\s*\\{[^}]*?\\}"58 negative_pattern: "(?:captcha|recaptcha|hcaptcha|rate\\s*limit)"59 message: "Authentication without CAPTCHA or rate limiting. Implement protection against brute force attacks."6061 # Pattern 11: Insecure Remember Me Functionality62 - pattern: "(?:rememberMe|keepLoggedIn|staySignedIn)"63 negative_pattern: "(?:secure|httpOnly|sameSite)"64 message: "Potentially insecure 'Remember Me' functionality. Implement with secure, HttpOnly cookies and proper expiration."6566 # Pattern 12: Insecure Logout Implementation67 - pattern: "(?:logout|signout)\\s*\\([^)]*\\)\\s*\\{[^}]*?\\}"68 negative_pattern: "(?:invalidate|revoke|clear|remove).*(?:token|session|cookie)"69 message: "Potentially incomplete logout implementation. Ensure proper invalidation of sessions and tokens on logout."7071 # Pattern 13: Missing Session Timeout72 - pattern: "(?:session|cookie|jwt)\\s*\\.\\s*(?:create|set|sign)"73 negative_pattern: "(?:expire|timeout|maxAge)"74 message: "Missing session timeout configuration. Implement proper session expiration for security."7576 # Pattern 14: Insecure OAuth Implementation77 - pattern: "(?:oauth|openid|oidc).*(?:callback|redirect)"78 negative_pattern: "(?:state|nonce|pkce)"79 message: "Potentially insecure OAuth implementation. Use state parameters, PKCE for authorization code flow, and validate redirect URIs."8081 # Pattern 15: Missing Credential Validation82 - pattern: "(?:email|username|user)\\s*=\\s*(?:req\\.body|req\\.query|req\\.params|formData\\.get)\\(['\"][^'\"]+['\"]\\)"83 negative_pattern: "(?:validate|sanitize|check|trim)"84 message: "Missing input validation for user credentials. Implement proper validation and sanitization."8586 - type: suggest87 message: |88 **JavaScript Identification and Authentication Failures Best Practices:**8990 1. **Strong Password Policies:**91 - Implement minimum length (at least 12 characters)92 - Require complexity (uppercase, lowercase, numbers, special characters)93 - Check against common password lists94 - Example:95```javascript96 // Using a library like zxcvbn for password strength estimation97 import zxcvbn from 'zxcvbn';9899 function validatePassword(password) {100 if (password.length < 12) {101 return { valid: false, message: 'Password must be at least 12 characters' };102 }103104 const strength = zxcvbn(password);105 if (strength.score < 3) {106 return {107 valid: false,108 message: 'Password is too weak. ' + strength.feedback.warning109 };110 }111112 return { valid: true };113 }114```115116 2. **Multi-Factor Authentication (MFA):**117 - Implement TOTP (Time-based One-Time Password)118 - Support hardware security keys (WebAuthn/FIDO2)119 - Example:120```javascript121 // Using speakeasy for TOTP implementation122 import speakeasy from 'speakeasy';123124 // Generate a secret for a user125 const secret = speakeasy.generateSecret({ length: 20 });126127 // Verify a token128 function verifyToken(token, secret) {129 return speakeasy.totp.verify({130 secret: secret.base32,131 encoding: 'base32',132 token: token,133 window: 1 // Allow 1 period before and after for clock drift134 });135 }136```137138 3. **Secure Session Management:**139 - Use HttpOnly, Secure, and SameSite cookies140 - Implement proper session expiration141 - Example:142```javascript143 // Express.js example144 app.use(session({145 secret: process.env.SESSION_SECRET,146 name: '__Host-session', // Prefix with __Host- for added security147 cookie: {148 httpOnly: true,149 secure: true, // Requires HTTPS150 sameSite: 'strict',151 maxAge: 3600000, // 1 hour152 path: '/'153 },154 resave: false,155 saveUninitialized: false156 }));157```158159 4. **CSRF Protection:**160 - Implement CSRF tokens for all state-changing operations161 - Example:162```javascript163 // Using csurf middleware with Express164 import csrf from 'csurf';165166 // Setup CSRF protection167 const csrfProtection = csrf({ cookie: true });168169 // Apply to routes170 app.post('/api/user/profile', csrfProtection, (req, res) => {171 // Handle the request172 });173174 // In your frontend (React example)175 function ProfileForm() {176 // Get CSRF token from cookie or meta tag177 const csrfToken = document.querySelector('meta[name="csrf-token"]').content;178179 return (180 <form method="POST" action="/api/user/profile">181 <input type="hidden" name="_csrf" value={csrfToken} />182 {/* Form fields */}183 <button type="submit">Update Profile</button>184 </form>185 );186 }187```188189 5. **Secure JWT Implementation:**190 - Use strong algorithms (RS256 preferred over HS256)191 - Include proper expiration (exp), issued at (iat), and audience (aud) claims192 - Example:193```javascript194 import jwt from 'jsonwebtoken';195 import fs from 'fs';196197 // Using asymmetric keys (preferred for production)198 const privateKey = fs.readFileSync('private.key');199200 function generateToken(userId) {201 return jwt.sign(202 {203 sub: userId,204 iat: Math.floor(Date.now() / 1000),205 exp: Math.floor(Date.now() / 1000) + (60 * 60), // 1 hour206 aud: 'your-app-name'207 },208 privateKey,209 { algorithm: 'RS256' }210 );211 }212```213214 6. **Secure Password Storage:**215 - Use bcrypt, Argon2, or PBKDF2 with sufficient work factor216 - Example:217```javascript218 import bcrypt from 'bcrypt';219220 async function hashPassword(password) {221 // Cost factor of 12+ for production222 const saltRounds = 12;223 return await bcrypt.hash(password, saltRounds);224 }225226 async function verifyPassword(password, hash) {227 return await bcrypt.compare(password, hash);228 }229```230231 7. **Account Lockout and Rate Limiting:**232 - Implement progressive delays or account lockout after failed attempts233 - Example:234```javascript235 import rateLimit from 'express-rate-limit';236237 // Apply rate limiting to login endpoint238 const loginLimiter = rateLimit({239 windowMs: 15 * 60 * 1000, // 15 minutes240 max: 5, // 5 attempts per window241 message: 'Too many login attempts, please try again after 15 minutes',242 standardHeaders: true,243 legacyHeaders: false,244 });245246 app.post('/api/login', loginLimiter, (req, res) => {247 // Handle login248 });249```250251 8. **Secure Password Recovery:**252 - Use time-limited, single-use tokens253 - Send to verified email addresses only254 - Example:255```javascript256 import crypto from 'crypto';257258 function generatePasswordResetToken() {259 return {260 token: crypto.randomBytes(32).toString('hex'),261 expires: new Date(Date.now() + 3600000) // 1 hour262 };263 }264265 // Store token in database with user ID and expiration266 // Send token via email (never include in URL directly)267 // Verify token is valid and not expired when used268```269270 9. **Brute Force Protection:**271 - Implement CAPTCHA or reCAPTCHA272 - Example:273```javascript274 // Using Google reCAPTCHA v3275 async function verifyRecaptcha(token) {276 const response = await fetch('https://www.google.com/recaptcha/api/siteverify', {277 method: 'POST',278 headers: { 'Content-Type': 'application/x-www-form-urlencoded' },279 body: `secret=${process.env.RECAPTCHA_SECRET_KEY}&response=${token}`280 });281282 const data = await response.json();283 return data.success && data.score >= 0.5; // Adjust threshold as needed284 }285286 app.post('/api/login', async (req, res) => {287 const { recaptchaToken } = req.body;288289 if (!(await verifyRecaptcha(recaptchaToken))) {290 return res.status(400).json({ error: 'CAPTCHA verification failed' });291 }292293 // Continue with login process294 });295```296297 10. **Secure Logout Implementation:**298 - Invalidate sessions on both client and server299 - Example:300```javascript301 app.post('/api/logout', (req, res) => {302 // Clear server-side session303 req.session.destroy((err) => {304 if (err) {305 return res.status(500).json({ error: 'Failed to logout' });306 }307308 // Clear client-side cookie309 res.clearCookie('__Host-session', {310 httpOnly: true,311 secure: true,312 sameSite: 'strict',313 path: '/'314 });315316 res.status(200).json({ message: 'Logged out successfully' });317 });318 });319```320321 11. **Secure OAuth Implementation:**322 - Use state parameter to prevent CSRF323 - Implement PKCE for authorization code flow324 - Validate redirect URIs against whitelist325 - Example:326```javascript327 // Generate state and code verifier for PKCE328 function generateOAuthState() {329 return crypto.randomBytes(32).toString('hex');330 }331332 function generateCodeVerifier() {333 return crypto.randomBytes(43).toString('base64url');334 }335336 function generateCodeChallenge(verifier) {337 const hash = crypto.createHash('sha256').update(verifier).digest('base64url');338 return hash;339 }340341 // Store state and code verifier in session342 // Use code challenge in authorization request343 // Verify state and use code verifier in token request344```345346 12. **Input Validation:**347 - Validate and sanitize all user inputs348 - Example:349```javascript350 import validator from 'validator';351352 function validateCredentials(email, password) {353 const errors = {};354355 if (!validator.isEmail(email)) {356 errors.email = 'Invalid email format';357 }358359 if (!password || password.length < 12) {360 errors.password = 'Password must be at least 12 characters';361 }362363 return {364 isValid: Object.keys(errors).length === 0,365 errors366 };367 }368```369370 13. **Secure Headers:**371 - Implement security headers for authentication-related pages372 - Example:373```javascript374 // Using helmet with Express375 import helmet from 'helmet';376377 app.use(helmet({378 contentSecurityPolicy: {379 directives: {380 defaultSrc: ["'self'"],381 scriptSrc: ["'self'", 'https://www.google.com/recaptcha/', 'https://www.gstatic.com/recaptcha/'],382 frameSrc: ["'self'", 'https://www.google.com/recaptcha/'],383 styleSrc: ["'self'", "'unsafe-inline'"],384 connectSrc: ["'self'"]385 }386 },387 referrerPolicy: { policy: 'same-origin' }388 }));389```390391 14. **Credential Stuffing Protection:**392 - Implement device fingerprinting and anomaly detection393 - Example:394```javascript395 // Simple device fingerprinting396 function getDeviceFingerprint(req) {397 return {398 ip: req.ip,399 userAgent: req.headers['user-agent'],400 acceptLanguage: req.headers['accept-language']401 };402 }403404 // Check if login is from a new device405 async function isNewDevice(userId, fingerprint) {406 // Compare with stored fingerprints for this user407 // Alert or require additional verification for new devices408 }409```410411 15. **Secure Password Change:**412 - Require current password verification413 - Example:414```javascript415 async function changePassword(userId, currentPassword, newPassword) {416 // Retrieve user from database417 const user = await getUserById(userId);418419 // Verify current password420 const isValid = await bcrypt.compare(currentPassword, user.passwordHash);421 if (!isValid) {422 return { success: false, message: 'Current password is incorrect' };423 }424425 // Validate new password strength426 const validation = validatePassword(newPassword);427 if (!validation.valid) {428 return { success: false, message: validation.message };429 }430431 // Hash and store new password432 const newHash = await bcrypt.hash(newPassword, 12);433 await updateUserPassword(userId, newHash);434435 // Invalidate existing sessions (optional but recommended)436 await invalidateUserSessions(userId);437438 return { success: true };439 }440```441442 - type: validate443 conditions:444 # Check 1: Strong Password Validation445 - pattern: "(?:password|pwd).*(?:length\\s*>=\\s*(?:1[2-9]|[2-9][0-9]))"446 message: "Implementing strong password length requirements (12+ characters)."447448 # Check 2: Secure Password Storage449 - pattern: "(?:bcrypt|argon2|pbkdf2|scrypt)\\.[^(]*\\([^)]*?(?:rounds|iterations|cost|factor)\\s*[:<=>]\\s*(?:1[2-9]|[2-9][0-9])"450 message: "Using secure password hashing with appropriate work factor."451452 # Check 3: CSRF Protection453 - pattern: "(?:csrf|xsrf).*(?:token|middleware|protection)"454 message: "Implementing CSRF protection for state-changing operations."455456 # Check 4: Secure Cookie Configuration457 - pattern: "(?:cookie|session).*(?:httpOnly|secure|sameSite)"458 message: "Using secure cookie configuration for sessions."459460 # Check 5: Rate Limiting461 - pattern: "(?:rate|limit|throttle).*(?:login|signin|auth)"462 message: "Implementing rate limiting for authentication endpoints."463464metadata:465 priority: high466 version: 1.0467 tags:468 - security469 - javascript470 - nodejs471 - browser472 - authentication473 - owasp474 - language:javascript475 - framework:express476 - framework:react477 - framework:vue478 - framework:angular479 - category:security480 - subcategory:authentication481 - standard:owasp-top10482 - risk:a07-identification-authentication-failures483 references:484 - "https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures/"485 - "https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html"486 - "https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html"487 - "https://cheatsheetseries.owasp.org/cheatsheets/Credential_Stuffing_Prevention_Cheat_Sheet.html"488 - "https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html"489 - "https://cheatsheetseries.owasp.org/cheatsheets/JSON_Web_Token_for_Java_Cheat_Sheet.html"490 - "https://auth0.com/blog/a-look-at-the-latest-draft-for-jwt-bcp/"491 - "https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Multifactor_Authentication_Cheat_Sheet.md"492 - "https://www.nist.gov/itl/applied-cybersecurity/tig/back-basics-multi-factor-authentication"493</rule>494
One repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| ivangrynenko/cursorrules.cursor/rules/cursor-rules.mdc · 86 | Cursor rules | teststylearchgit+2 | 77/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/behat-steps.mdc · 86 | Cursor rules | lint-formatstyleperformanceagent-behaviour | 42/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/php-drupal-development-standards.mdc · 86 | Cursor rules | no sections | 34/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/python-insecure-design.mdc · 86 | Cursor rules | no sections | 40/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/python-cryptographic-failures.mdc · 86 | Cursor rules | security | 40/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/python-injection.mdc · 86 | Cursor rules | styledo-not | 51/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/node-dependencies.mdc · 86 | Cursor rules | no sections | 16/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/behat-ai-guide.mdc · 86 | Cursor rules | testtesting-strategydo-not | 45/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/new-pull-request.mdc · 86 | Cursor rules | archtesting-strategygitsecurity+3 | 58/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/accessibility-standards.mdc · 86 | Cursor rules | ui | 44/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/api-standards.mdc · 86 | Cursor rules | api | 44/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/build-optimization.mdc · 86 | Cursor rules | build | 48/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/code-generation-standards.mdc · 86 | Cursor rules | lint-formatstyletypesdocs | 52/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/confluence-editing-standards.mdc · 86 | Cursor rules | stylearchsecuritydeployment | 60/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/debugging-standards.mdc · 86 | Cursor rules | no sections | 30/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/docker-compose-standards.mdc · 86 | Cursor rules | style | 62/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/drupal-authentication-failures.mdc · 86 | Cursor rules | security | 48/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/drupal-broken-access-control.mdc · 86 | Cursor rules | stylesecurity | 52/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/drupal-cryptographic-failures.mdc · 86 | Cursor rules | security | 48/100 | 14 days ago | |
| ivangrynenko/cursorrules.cursor/rules/drupal-database-standards.mdc · 86 | Cursor rules | database | 30/100 | 14 days ago |
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| hiromaily/go-crypto-wallet.cursor/rules/typescript.mdc · 126 | Cursor rules | setupbuildtestlint-format+6 | 100/100 | 14 days ago | |
| TechSquidTV/Hermes.cursor/rules/10-hermes-api.mdc · 45 | Cursor rules | testlint-formatstylearch+5 | 100/100 | 14 days ago | |
| langflow-ai/langflow.cursor/rules/docs_development.mdc · 153k | Cursor rules | setupbuildtestlint-format+7 | 97/100 | 14 days ago | |
| TechSquidTV/Hermes.cursor/rules/20-hermes-api-tests.mdc · 45 | Cursor rules | teststyletesting-strategysecurity+3 | 97/100 | 14 days ago | |
| skillrecordings/egghead-next.cursor/rules/gh-task-plan.mdc · 1.4k | Cursor rules | teststylearchtypes+2 | 96/100 | 14 days ago | |
| skillrecordings/egghead-next.cursor/rules/project-update-rules.mdc · 1.4k | Cursor rules | buildtestlint-formatstyle+7 | 96/100 | 14 days ago | |
| skillrecordings/egghead-next.cursor/rules/project-update-user-rules.mdc · 1.4k | Cursor rules | buildtestlint-formatstyle+7 | 96/100 | 14 days ago | |
| hiromaily/go-crypto-wallet.cursor/rules/proto.mdc · 126 | Cursor rules | buildlint-formatstylearch+3 | 96/100 | 14 days ago |
A badge carrying the measured quality of the strongest agent config file in this repository, out of 100. It reads from this index every time somebody loads your page, so it changes when the measurement changes and there is nothing to keep up to date. Free, no account, and the value is not something you or we can set by hand.
[](https://rulestack.kynth.studio/configs/ivangrynenko-cursorrules-cursor-rules-javascript-identification-authentication-failures)Would rather not hotlink us? Every badge is also served in shields.io’s endpoint schema, so shields renders the image and your readers never talk to our domain:
Published by Toolproof, the masthead over this index and eight others. The method behind the number is at toolproof.kynth.studio/methodology, and the whole thing is readable as JSON with no key at /api.