Skip to content

notque/vexjoy-agent / skills/programming/programming

programming

Flagged

Language rules, workflows, and tooling: Go, Python, Rust, Kotlin, Swift, PHP, TypeScript type checks and debugging, OpenStack Python, MCP local-docs servers, Node.js backend APIs.

FileKindSize
SKILL.mdskill md19.3 KB
references/go/code-review.mdmarkdown12.0 KB
references/go/code-review/common-review-comments.mdmarkdown6.6 KB
references/go/concurrency.mdmarkdown11.5 KB
references/go/concurrency/concurrency-patterns.mdmarkdown5.7 KB
references/go/error-handling.mdmarkdown10.8 KB
references/go/error-handling/patterns.mdmarkdown4.2 KB
references/go/google-style-guide/SHA256SUMSother313 B
references/go/google-style-guide/UPSTREAM_REVISIONother41 B
references/go/google-style-guide/best-practices/part-01.mdmarkdown10.0 KB
references/go/google-style-guide/best-practices/part-02.mdmarkdown15.0 KB
references/go/google-style-guide/best-practices/part-03.mdmarkdown14.1 KB
references/go/google-style-guide/best-practices/part-04.mdmarkdown13.5 KB
references/go/google-style-guide/best-practices/part-05.mdmarkdown10.5 KB
references/go/google-style-guide/best-practices/part-06.mdmarkdown14.4 KB
references/go/google-style-guide/best-practices/part-07.mdmarkdown16.1 KB
references/go/google-style-guide/best-practices/part-08.mdmarkdown11.4 KB
references/go/google-style-guide/best-practices/part-09.mdmarkdown13.7 KB
references/go/google-style-guide/best-practices/part-10.mdmarkdown16.9 KB
references/go/google-style-guide/decisions/part-01.mdmarkdown15.0 KB
references/go/google-style-guide/decisions/part-02.mdmarkdown12.5 KB
references/go/google-style-guide/decisions/part-03.mdmarkdown11.5 KB
references/go/google-style-guide/decisions/part-04.mdmarkdown8.4 KB
references/go/google-style-guide/decisions/part-05.mdmarkdown9.8 KB
references/go/google-style-guide/decisions/part-06.mdmarkdown14.7 KB
references/go/google-style-guide/decisions/part-07.mdmarkdown13.3 KB
references/go/google-style-guide/decisions/part-08.mdmarkdown14.3 KB
references/go/google-style-guide/decisions/part-09.mdmarkdown15.3 KB
references/go/google-style-guide/decisions/part-10.mdmarkdown8.3 KB
references/go/google-style-guide/guide/part-01.mdmarkdown16.3 KB
references/go/google-style-guide/guide/part-02.mdmarkdown3.0 KB
references/go/google-style-guide/index.mdmarkdown8.4 KB
references/go/preferred-patterns.mdmarkdown12.5 KB
references/go/preferred-patterns/code-examples.mdmarkdown11.6 KB
references/go/quality-gate.mdmarkdown7.3 KB
references/go/quality-gate/common-lint-errors.jsonconfig7.6 KB
references/go/quality-gate/examples.mdmarkdown11.0 KB
references/go/quality-gate/makefile-targets.jsonconfig5.1 KB
references/go/sapcc-conventions.mdmarkdown34.6 KB
references/go/sapcc-conventions/api-design-detailed.mdmarkdown22.7 KB
references/go/sapcc-conventions/architecture-patterns.mdmarkdown18.6 KB
references/go/sapcc-conventions/build-ci-detailed.mdmarkdown18.7 KB
references/go/sapcc-conventions/error-handling-detailed.mdmarkdown20.1 KB
references/go/sapcc-conventions/extended-patterns.mdmarkdown7.1 KB
references/go/sapcc-conventions/go-bits-philosophy-detailed.mdmarkdown24.5 KB
references/go/sapcc-conventions/library-reference.mdmarkdown14.0 KB
references/go/sapcc-conventions/pr-mining-insights.mdmarkdown17.5 KB
references/go/sapcc-conventions/review-standards.mdmarkdown10.5 KB
references/go/sapcc-conventions/sapcc-code-patterns.mdmarkdown46.2 KB
references/go/testing.mdmarkdown9.7 KB
references/go/testing/go-benchmark-and-concurrency.mdmarkdown5.6 KB
references/go/testing/go-test-patterns.mdmarkdown9.0 KB
references/golang-general.mdmarkdown8.9 KB
references/golang-general/go-modern-code.mdmarkdown17.2 KB
references/golang-general/go-verification-workflow.mdmarkdown5.0 KB
references/golang-general/go-version-idioms.mdmarkdown6.8 KB
references/kotlin-general.mdmarkdown7.5 KB
references/kotlin-general/kotlin-patterns.mdmarkdown7.9 KB
references/kotlin-general/kotlin-security-testing.mdmarkdown4.4 KB
references/kotlin-general/kotlin-security.mdmarkdown11.1 KB
references/kotlin/concurrency-patterns.mdmarkdown5.4 KB
references/kotlin/kotlin-testing.mdmarkdown7.9 KB
references/mcp-local-docs.mdmarkdown6.9 KB
references/mcp-local-docs/mcp-patterns.mdmarkdown9.6 KB
references/mcp-local-docs/mcp-preferred-patterns.mdmarkdown6.9 KB
references/mcp-local-docs/server-templates.mdmarkdown4.4 KB
references/mcp-local-docs/typescript-async-patterns.mdmarkdown8.9 KB
references/nodejs-api.mdmarkdown7.3 KB
references/nodejs-api/auth-patterns.mdmarkdown10.0 KB
references/nodejs-api/middleware-patterns.mdmarkdown10.5 KB
references/nodejs-api/nodejs-security.mdmarkdown12.3 KB
references/nodejs-api/webhook-patterns.mdmarkdown9.9 KB
references/php-general.mdmarkdown4.7 KB
references/php-general/php-behaviors.mdmarkdown5.2 KB
references/php-general/php-conventions.mdmarkdown5.8 KB
references/php/modern-php-features.mdmarkdown4.4 KB
references/php/testing-patterns.mdmarkdown7.5 KB
references/python-general.mdmarkdown7.7 KB
references/python-general/flask-jinja-webapp.mdmarkdown5.7 KB
references/python-general/python-local-gates.mdmarkdown4.4 KB
references/python-general/python-modern-code.mdmarkdown23.1 KB
references/python-openstack.mdmarkdown5.2 KB
references/python-openstack/error-handling.mdmarkdown658 B
references/python-openstack/hacking-rules.mdmarkdown4.1 KB
references/python-openstack/openstack-patterns.mdmarkdown1.2 KB
references/python-openstack/oslo-patterns.mdmarkdown6.4 KB
references/python-openstack/output-format.mdmarkdown2.4 KB
references/python-openstack/preferred-patterns.mdmarkdown1.9 KB
references/python-openstack/rpc-versioning.mdmarkdown5.3 KB
references/rust-general.mdmarkdown8.2 KB
references/rust-general/rust-modern-code.mdmarkdown13.4 KB
references/rust-general/rust-verification-workflow.mdmarkdown5.5 KB
references/rust-general/rust-version-idioms.mdmarkdown7.0 KB
references/swift-general.mdmarkdown5.7 KB
references/swift-general/swift-patterns.mdmarkdown6.7 KB
references/swift-general/swift-security-testing.mdmarkdown6.6 KB
references/swift-general/swift-security.mdmarkdown13.3 KB
references/swift/preferred-patterns.mdmarkdown2.4 KB
references/swift/swift-testing.mdmarkdown6.6 KB
references/swift/task-patterns.mdmarkdown3.6 KB
references/typescript-debugging.mdmarkdown9.3 KB
references/typescript-debugging/debugging-workflows-async-memory.mdmarkdown5.8 KB
references/typescript-debugging/debugging-workflows.mdmarkdown5.6 KB
scripts/bench-compare.shscript7.1 KB
scripts/check-errors.shscript7.1 KB
scripts/check-interface-compliance.shscript6.4 KB
scripts/check-sapcc-auth-ordering.shscript5.5 KB
scripts/check-sapcc-httptest.shscript4.4 KB
scripts/check-sapcc-identify-endpoint.shscript5.8 KB
scripts/check-sapcc-json-strict.shscript4.9 KB
scripts/check-sapcc-time-now.shscript4.2 KB
scripts/check-sapcc-todo-format.shscript4.1 KB
scripts/gen-table-test.shscript4.2 KB
scripts/quality_checker.pyscript16.2 KB
scripts/sync-google-style-guide.pyscript2.5 KB
scripts/validate.pyscript6.3 KB

references/nodejs-api/auth-patterns.md

View on GitHub
---
description: JWT, OAuth, session management, and token refresh implementations with security-correct patterns
---

# Authentication Patterns for Node.js APIs

> **Scope**: JWT-based auth, OAuth 2.0 integration, session management, and password security for Express/Next.js APIs. Does not cover frontend auth flows or mobile OAuth.
> **Version range**: Node.js 18+, `jsonwebtoken` 9.0+, `bcrypt` 5.0+
> **Generated**: 2026-04-08

---

## Overview

Auth fails in two ways: insecure defaults (long-lived tokens, weak secrets, missing expiry) and broken error handling (timing attacks via username enumeration, stack traces in 401 responses).

---

## Pattern Table

| Pattern | Version | Use When | Avoid When |
|---------|---------|----------|------------|
| `jwt.sign()` with `expiresIn` | jsonwebtoken 9+ | All access token issuance | Never omit — tokens live forever |
| `jwt.verify()` with `algorithms` | jsonwebtoken 9+ | Token validation | `jwt.decode()` — no signature check |
| `bcrypt.hash()` with cost 12 | bcrypt 5+ | Password storage | `md5`, `sha1`, any fast hash |
| `crypto.timingSafeEqual()` | Node 16+ | Webhook signature comparison | `===` string comparison |
| Refresh token rotation | — | Session persistence beyond 15min | Single long-lived access token |

---

## Correct Patterns

### JWT Issuance with Short Expiry and Refresh

```typescript
import jwt from 'jsonwebtoken';
import { randomUUID } from 'crypto';

const ACCESS_TOKEN_TTL = '15m';
const REFRESH_TOKEN_TTL = '7d';

interface TokenPair {
  accessToken: string;
  refreshToken: string;
  expiresIn: number; // seconds
}

function issueTokenPair(userId: string, roles: string[]): TokenPair {
  const accessToken = jwt.sign(
    { sub: userId, roles },
    process.env.JWT_SECRET!,
    {
      algorithm: 'HS256',
      expiresIn: ACCESS_TOKEN_TTL,
      issuer: 'api.example.com',
      jwtid: randomUUID(), // Unique ID for revocation
    }
  );

  const refreshToken = jwt.sign(
    { sub: userId, type: 'refresh' },
    process.env.REFRESH_SECRET!,
    { algorithm: 'HS256', expiresIn: REFRESH_TOKEN_TTL }
  );

  return { accessToken, refreshToken, expiresIn: 15 * 60 };
}
```

**Why**: 15-minute access tokens limit breach window. `jwtid` enables per-token revocation.

---

### JWT Middleware with Explicit Algorithm Pinning

```typescript
import { Request, Response, NextFunction } from 'express';

export function requireAuth(req: Request, res: Response, next: NextFunction): void {
  const authHeader = req.headers.authorization;
  if (!authHeader?.startsWith('Bearer ')) {
    res.status(401).json({ error: 'Missing authorization header' });
    return;
  }

  const token = authHeader.slice(7);
  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET!, {
      algorithms: ['HS256'], // Explicit — prevents alg:none attack
      issuer: 'api.example.com',
    }) as { sub: string; roles: string[] };

    req.user = { id: payload.sub, roles: payload.roles };
    next();
  } catch (err) {
    if (err instanceof jwt.TokenExpiredError) {
      res.status(401).json({ error: 'Token expired', code: 'TOKEN_EXPIRED' });
    } else {
      res.status(401).json({ error: 'Invalid token' });
      // Do NOT leak err.message — reveals token structure to attackers
    }
  }
}
```

**Why**: Prevents the "algorithm none" attack. Without `algorithms`, `jsonwebtoken` < 9 accepted unsigned tokens.

---

### Webhook Signature Verification (Stripe/GitHub pattern)

```typescript
import { createHmac, timingSafeEqual } from 'crypto';

export function verifyWebhookSignature(
  payload: Buffer,
  signature: string,
  secret: string,
  tolerance = 300 // 5 minutes
): boolean {
  // Stripe format: t=timestamp,v1=signature
  const parts = Object.fromEntries(
    signature.split(',').map((p) => p.split('=') as [string, string])
  );
  const timestamp = parseInt(parts['t'] ?? '0', 10);

  // Reject stale webhooks (replay attack prevention)
  const age = Math.floor(Date.now() / 1000) - timestamp;
  if (age > tolerance) return false;

  const signedPayload = `${timestamp}.${payload.toString('utf-8')}`;
  const expected = createHmac('sha256', secret)
    .update(signedPayload)
    .digest('hex');

  // Timing-safe comparison — prevents timing oracle attacks
  return timingSafeEqual(
    Buffer.from(parts['v1'] ?? '', 'hex'),
    Buffer.from(expected, 'hex')
  );
}
```

**Why**: `timingSafeEqual` takes constant time. Regular `===` returns early on first mismatch, leaking signature bytes via timing oracle.

---

## Pattern Catalog

### Always Use jwt.verify() with Algorithm Pinning
**Detection**:
```bash
grep -rn 'jwt\.decode(' --include="*.ts" --include="*.js" src/
rg 'jwt\.decode\(' --type ts src/
```

**Signal**:
```typescript
// "decode" sounds like "verify" — it isn't
const payload = jwt.decode(req.headers.authorization?.split(' ')[1] ?? '');
if (payload && payload.sub) {
  req.user = { id: payload.sub };
  next();
}
```

**Why this matters**: `jwt.decode()` does NOT verify the signature. Any attacker can craft a token with any `sub` value. Auth completely bypassed.

**Preferred action**: Always use `jwt.verify()` with `algorithms` specified.

---

### Use Constant-Time Auth Responses
**Detection**:
```bash
grep -rn 'return.*null\|return.*false' --include="*.ts" src/auth
# Look for early returns before bcrypt.compare
grep -rn 'findUser\|findByEmail' --include="*.ts" src/ -A10 | grep -v 'compare\|bcrypt'
```

**Signal**:
```typescript
async function login(email: string, password: string) {
  const user = await db.users.findByEmail(email);
  if (!user) {
    return { error: 'User not found' }; // Responds fast — user doesn't exist
  }
  const valid = await bcrypt.compare(password, user.passwordHash); // Responds slow
  if (!valid) {
    return { error: 'Invalid password' }; // Responds after bcrypt delay
  }
  return { token: issueToken(user.id) };
}
```

**Why this matters**: User doesn't exist = ~1ms (DB miss). Wrong password = ~100ms (bcrypt). Attackers enumerate valid emails by timing.

**Preferred action**:
```typescript
async function login(email: string, password: string) {
  const user = await db.users.findByEmail(email);

  // Always run bcrypt.compare — constant time regardless of user existence
  const DUMMY_HASH = '$2b$12$invalidhashpaddingtomakeitthelength'; // pre-computed
  const passwordHash = user?.passwordHash ?? DUMMY_HASH;
  const valid = await bcrypt.compare(password, passwordHash);

  if (!user || !valid) {
    return { error: 'Invalid credentials' }; // Same message for both cases
  }
  return { token: issueToken(user.id) };
}
```

**Version note**: `bcrypt` cost factor 12 is the 2024 recommended minimum. Cost 10 (common default) is acceptable but 12 is better for password storage.

---

### Use Short-Lived Access Tokens with Refresh
**Detection**:
```bash
grep -rn 'expiresIn' --include="*.ts" src/
# Flag anything longer than 1 hour
grep -rn "expiresIn.*['\"].*[0-9][dw]\|expiresIn.*3600[0-9]" --include="*.ts" src/
```

**Signal**:
```typescript
const token = jwt.sign(
  { sub: userId },
  process.env.JWT_SECRET!,
  { expiresIn: '7d' } // 7-day access token
);
```

**Why this matters**: A 7-day access token = 7 days of unauthorized access if stolen. No revocation on logout means sessions survive password changes.

**Preferred action**: `expiresIn: '15m'` for access tokens + `expiresIn: '7d'` for refresh tokens. Implement refresh token rotation and revocation in Redis.

---

### Store Refresh Tokens in httpOnly Cookies
**Detection**: This is a frontend failure mode but confirm with client team.
```bash
grep -rn 'localStorage.*refresh\|localStorage.*token' --include="*.ts" --include="*.tsx" src/
```

**Why this matters**: `localStorage` is accessible to any JS on the page, including XSS-injected scripts.

**Preferred action**: `httpOnly` cookies for refresh tokens — inaccessible to JavaScript:
```typescript
res.cookie('refreshToken', refreshToken, {
  httpOnly: true,    // Not accessible via document.cookie
  secure: true,      // HTTPS only
  sameSite: 'lax',   // CSRF protection
  maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days in ms
  path: '/api/auth', // Limit scope
});
```

---

## Error-Fix Mappings

| Error Message | Root Cause | Fix |
|---------------|------------|-----|
| `JsonWebTokenError: invalid signature` | Wrong JWT_SECRET in environment | Verify env var matches what signed the token |
| `TokenExpiredError: jwt expired` | Access token past `expiresIn` | Implement refresh token flow; return 401 with `code: 'TOKEN_EXPIRED'` |
| `JsonWebTokenError: jwt malformed` | Not a valid JWT string (missing dots) | Check `Authorization: Bearer <token>` format |
| `JsonWebTokenError: invalid algorithm` | Token signed with different algorithm | Pin `algorithms: ['HS256']` in verify options |
| `bcrypt: invalid password` | Empty or null password passed to `compare()` | Validate password field exists before calling `compare()` |
| `Error: data and hash arguments required` | `bcrypt.compare(undefined, hash)` | Check `password` is defined in request body |

---

## Version-Specific Notes

| Version | Change | Impact |
|---------|--------|--------|
| `jsonwebtoken` 9.0 | Breaking: dropped support for `alg: none` without explicit option | Upgrade fixes algorithm confusion attacks |
| `bcrypt` 5.0 | Native bindings rewritten; `bcryptjs` is pure-JS fallback | Use `bcrypt` for performance; `bcryptjs` for Lambda/edge |
| Node.js 19 | `crypto.timingSafeEqual` accepts strings directly | Previously required Buffer conversion |

---

## Detection Commands Reference

```bash
# jwt.decode() used for auth (no signature check)
grep -rn 'jwt\.decode(' --include="*.ts" src/

# Missing algorithm pinning in jwt.verify()
grep -rn 'jwt\.verify(' --include="*.ts" src/ -A5 | grep -v 'algorithms'

# String comparison for signatures (timing attack)
grep -rn 'signature.*===\|hmac.*===' --include="*.ts" src/

# Long-lived access tokens
grep -rn "expiresIn.*'[0-9][dw]'" --include="*.ts" src/

# Bcrypt cost below 12
grep -rn 'bcrypt\.hash.*[0-9]' --include="*.ts" src/ | grep -E '\b[1-9]\b'
```

---

## See Also

- `webhook-patterns.md` — Idempotency and retry handling for webhooks
- `security-headers.md` — CORS, CSP, and rate limiting patterns
rea-changelog-updatemorluto/reaPrepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization.Stars: 469kUpdated Claude CodeCodexVerifiedInstall
academy-guideanthropics/skillsStop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content.Stars: 197kUpdated Claude CodeCodexVerifiedInstall
claude-apianthropics/skillsReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file).Stars: 197kUpdated Claude CodeCodexUnverifiedInstall
doc-coauthoringanthropics/skillsGuide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks.Stars: 197kUpdated Claude CodeCodexVerifiedInstall