Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/validate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile

- name: Run linting
run: pnpm lint

- name: Type checking
run: pnpm type-check

Expand Down
6 changes: 4 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,10 @@ node_modules
# Users Environment Variables
.lock-wscript

# IDEs and editors (shim for help)
.vscode/
# IDEs and editors
.vscode/*
!.vscode/settings.json
!.vscode/extensions.json
.idea/
*.swp
*.swo
Expand Down
3 changes: 2 additions & 1 deletion .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
{
"recommendations": [
"dbaeumer.vscode-eslint",
"bierner.markdown-preview-github-styles",
"bierner.github-markdown-preview",
"bierner.markdown-shiki",
"bierner.color-info",
"oderwat.indent-rainbow",
"warengonzaga.bini-theme",
"warengonzaga.bini-theme"
]
}
24 changes: 24 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"editor.formatOnSave": false,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"eslint.validate": [
"javascript",
"typescript"
],
"eslint.workingDirectories": [
{
"mode": "auto"
}
],
"eslint.lintTask.enable": true,
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"[typescript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"[javascript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
}
}
81 changes: 80 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ pnpm build
# Type checking only
pnpm type-check

# Linting
pnpm lint # Run ESLint on all source files
pnpm lint:fix # Run ESLint with auto-fix
pnpm lint:security # Focus on security-related issues
pnpm lint:ci # CI-friendly linting (fails on warnings)

# Clean build artifacts
pnpm clean

Expand Down Expand Up @@ -101,6 +107,7 @@ src/
#### 🎯 Development Guidelines

- **TypeScript First**: All code must be written in TypeScript with strict type checking
- **Code Quality**: Follow ESLint rules and security best practices enforced by automated linting
- **Structured Logging**: Use `@wgtechlabs/log-engine` for all logging with built-in PII protection and security features
- **Error Handling**: Implement comprehensive error handling with detailed logging
- **Package Manager**: Use pnpm exclusively (enforced via preinstall script)
Expand All @@ -109,6 +116,75 @@ src/
- **Redis Integration**: Ensure Redis connectivity for all webhook-related features
- **Webhook Integration**: Ensure compatibility with [`wgtechlabs/unthread-telegram-bot`](https://github.com/wgtechlabs/unthread-telegram-bot)

#### 🔍 Code Quality and Linting

This project uses **ESLint** with comprehensive security plugins to maintain code quality and prevent common security vulnerabilities.

**Security Plugins Enabled:**

- **eslint-plugin-security** - Detects common security vulnerabilities
- **eslint-plugin-no-secrets** - Prevents hardcoded secrets and credentials
- **eslint-plugin-n** - Node.js best practices and deprecated API detection
- **eslint-plugin-import** - Validates ES6 import/export syntax
- **eslint-plugin-promise** - Ensures proper promise handling

**Running Linting:**

```bash
# Check for issues
pnpm lint

# Automatically fix issues
pnpm lint:fix

# Security-focused check
pnpm lint:security

# CI mode (fails on warnings)
pnpm lint:ci
```

**Comprehensive ESLint Configuration:**

This project uses a modern flat config format (`eslint.config.js`) with the following capabilities:
- **TypeScript-first**: Full TypeScript-ESLint integration with strict type checking
- **Security-focused**: Multiple security plugins working together to prevent vulnerabilities
- **Customizable**: Tailored rules for webhook server security requirements
- **IDE Integration**: Works seamlessly with VSCode ESLint extension

For complete configuration details, see [ESLINT.md](./ESLINT.md).

**Key Security Rules:**

- **No hardcoded secrets** - Detects API keys, tokens, passwords, webhook secrets in code
- **Safe regular expressions** - Prevents ReDoS attacks
- **Secure random generation** - Enforces crypto.randomBytes over Math.random
- **Object injection protection** - Warns about unsafe object property access
- **Child process security** - Flags potentially unsafe child process usage
- **Promise handling** - Ensures all promises are properly handled

**Best Practices:**

- **Fix all linting errors** before submitting PRs (required)
- **Address security warnings** unless there's a documented reason to ignore them
- **Use ESLint disable comments sparingly** and only with proper justification
- **Run `pnpm lint:fix`** to auto-fix style issues before committing
- **Test security rules** with `pnpm lint:security` for security-focused checks
- **VSCode users** get automatic linting and auto-fix on save with ESLint extension
- **Document any rule disables** in code comments explaining why they're necessary

**When to Disable Rules:**

```typescript
// ✅ Good - documented reason
// eslint-disable-next-line security/detect-object-injection
const value = obj[key]; // key is from typed enum, safe

// ❌ Bad - no justification
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const data: any = response;
```

#### 🧪 Testing Guidelines

While this project doesn't currently have a test suite, when contributing:
Expand All @@ -124,16 +200,19 @@ While this project doesn't currently have a test suite, when contributing:
1. **Pre-submission checks**:
- [ ] Code builds without errors (`pnpm build`)
- [ ] TypeScript type checking passes (`pnpm type-check`)
- [ ] Linting passes without errors (`pnpm lint`)
- [ ] Development server starts successfully (`pnpm dev`)
- [ ] Redis integration works properly
- [ ] Error handling is comprehensive
- [ ] No security warnings from `pnpm lint:security`

2. **Pull Request Requirements**:
- [ ] Target the `dev` branch (PRs to `main` will be rejected)
- [ ] Include clear description of changes
- [ ] Follow existing code patterns
- [ ] Follow existing code patterns and ESLint rules
- [ ] Update documentation if needed
- [ ] Test webhook functionality manually
- [ ] All linting issues resolved or properly justified

### 📖 Documentation

Expand Down
182 changes: 182 additions & 0 deletions ESLINT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
# ESLint Configuration Guide

This project uses ESLint with comprehensive security plugins to maintain code quality and prevent common security vulnerabilities.

## 📦 Installed Plugins

### Core
- **@eslint/js** - ESLint's recommended JavaScript rules
- **@typescript-eslint/eslint-plugin** - TypeScript-specific linting rules
- **@typescript-eslint/parser** - TypeScript parser for ESLint

### Security Plugins
- **eslint-plugin-security** - Detects common security vulnerabilities
- Object injection prevention
- RegEx DoS protection
- Buffer security checks
- Eval detection
- CSRF protection

- **eslint-plugin-no-secrets** - Prevents hardcoded secrets and credentials
- API keys detection
- Passwords and tokens
- Custom patterns for webhook secrets

### Best Practices
- **eslint-plugin-n** - Node.js best practices and deprecated API detection
- **eslint-plugin-import** - Validates ES6 import/export syntax
- **eslint-plugin-promise** - Ensures proper promise handling

## 🚀 Usage

### Run Linting

```bash
# Check for issues
yarn lint

# Automatically fix issues
yarn lint:fix

# Security-focused check
yarn lint:security

# CI mode (fails on warnings)
yarn lint:ci
```

### VSCode Integration

ESLint is automatically integrated with VSCode:
- Real-time linting feedback
- Auto-fix on save (configurable)
- Inline error/warning display

Make sure you have the ESLint extension installed:
```
ext install dbaeumer.vscode-eslint
```

## 🔒 Key Security Rules

### Critical (Error Level)

- ✅ **No hardcoded secrets** - Detects API keys, tokens, passwords
- ✅ **Safe regular expressions** - Prevents ReDoS attacks
- ✅ **Secure random generation** - Enforces crypto.randomBytes
- ✅ **No eval** - Prevents code injection via eval()
- ✅ **Buffer security** - Checks for unsafe buffer operations
- ✅ **Promise handling** - All promises must be properly handled

### Warnings

- ⚠️ **Object injection** - Warns about dynamic property access
- ⚠️ **Child processes** - Flags subprocess creation
- ⚠️ **File system operations** - Non-literal file paths
- ⚠️ **Timing attacks** - Potential timing-based vulnerabilities
- ⚠️ **process.exit()** - Suggests throwing errors instead

## ⚙️ Configuration

The ESLint configuration uses the modern flat config format (`eslint.config.js`).

### Ignored Patterns

The following are automatically ignored:
- `node_modules/`
- `dist/`
- `build/`
- `coverage/`
- `*.min.js`
- `.yarn/`
- `tmp/`, `temp/`

### Custom Rules

Some rules are customized for this project:

```javascript
// Security rules - adjusted for false positives
'security/detect-object-injection': 'warn', // Warn instead of error
'security/detect-non-literal-fs-filename': 'warn',
'security/detect-non-literal-require': 'warn',

// TypeScript rules
'@typescript-eslint/no-explicit-any': 'warn', // Allow with justification
'@typescript-eslint/no-unused-vars': ['error', {
argsIgnorePattern: '^_', // Allow unused vars prefixed with _
varsIgnorePattern: '^_',
}],
```

## 💡 Best Practices

### When to Disable Rules

Use ESLint disable comments sparingly and only with justification:

```typescript
// Good - documented reason
// eslint-disable-next-line security/detect-object-injection
if (!event[field]) { // field is from typed array, safe
// ...
}

// Bad - no justification
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const data: any = response;
```

### Acceptable Uses of `any`

The `any` type is acceptable in these cases:
- External API responses (Unthread webhook payloads)
- Dynamic data structures where type is truly unknown
- Express.js Request generics
- Always document why `any` is necessary

### Handling Warnings

- **Fix all errors** before committing
- **Address warnings** unless there's a documented reason
- **Security warnings** should be taken seriously
- Use `yarn lint:fix` to auto-fix style issues

## 🔄 CI/CD Integration

ESLint runs automatically in GitHub Actions:

```yaml
- name: Run linting
run: yarn lint
```

Builds will fail if there are linting errors. Warnings are allowed but should be minimized.

## 🔧 Troubleshooting

### "Parsing error: parserOptions.project"

Make sure `tsconfig.json` exists and is valid.

### "Cannot find module 'eslint-plugin-xxx'"

Run `yarn install` to ensure all dependencies are installed.

### Too many warnings

Use `yarn lint:fix` to automatically fix style issues.

### False positives

For security false positives:
1. Verify the code is actually safe
2. Add ESLint disable comment with justification
3. Document in PR why the disable is necessary

## 📚 Resources

- [ESLint Documentation](https://eslint.org/)
- [TypeScript ESLint](https://typescript-eslint.io/)
- [eslint-plugin-security](https://github.com/eslint-community/eslint-plugin-security)
- [eslint-plugin-no-secrets](https://github.com/nickdeis/eslint-plugin-no-secrets)
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ Server runs on `http://localhost:3000` with endpoints:
- **Comprehensive Logging**: Detailed operation logs with emoji indicators
- **Health Monitoring**: Built-in health checks for system status
- **TypeScript**: Full type safety throughout the codebase
- **Security-First Linting**: ESLint with comprehensive security plugins (security, no-secrets, promise handling)
- **Code Quality**: Automated code quality checks with TypeScript-ESLint integration

## 🚂 One-Click Deploy

Expand Down Expand Up @@ -222,6 +224,26 @@ pnpm dev # Development with hot-reload
pnpm start # Run production build
```

### Code Quality & Linting

This project enforces strict code quality and security standards using ESLint with comprehensive security plugins.

```bash
pnpm lint # Run ESLint on all source files
pnpm lint:fix # Run ESLint with auto-fix
pnpm lint:security # Focus on security-related issues
pnpm lint:ci # CI-friendly linting (fails on warnings)
```

**Security Plugins Enabled:**
- `eslint-plugin-security` - Detects common security vulnerabilities
- `eslint-plugin-no-secrets` - Prevents hardcoded secrets and credentials
- `eslint-plugin-n` - Node.js best practices and deprecated API detection
- `eslint-plugin-import` - Validates ES6 import/export syntax
- `eslint-plugin-promise` - Ensures proper promise handling

For detailed ESLint configuration and security rules, see [ESLINT.md](./ESLINT.md).

### Project Structure

```
Expand Down
Loading