入门 eslint-plugin-pg

发布: (2026年1月1日 GMT+8 02:45)
2 min read
原文: Dev.to

Source: Dev.to

快速安装

npm install --save-dev eslint-plugin-pg

扁平配置

// eslint.config.js
import pg from 'eslint-plugin-pg';

export default [pg.configs.recommended];

运行 ESLint

npx eslint .

示例输出:

src/users.ts
  15:3  error  🔒 CWE-89 OWASP:A03 CVSS:9.8 | Unsafe SQL query detected
               Fix: Use parameterized query: client.query('SELECT * FROM users WHERE id = $1', [id])

src/orders.ts
  28:5  error  🔒 CWE-772 | pool.connect() without client.release()
               Fix: Add client.release() in finally block

规则概览

规则CWE检测内容
no-unsafe-queryCWE-89SQL 注入(通过字符串拼接)
no-missing-client-releaseCWE-772连接池泄漏
prevent-double-releaseCWE-415双重释放导致崩溃
no-transaction-on-poolCWE-362事务竞争条件
prefer-pool-queryCWE-400不必要的 connect/release
no-unsafe-copy-fromCWE-22COPY FROM 中的路径遍历
no-unsafe-search-pathCWE-426search_path 劫持
no-n-plus-one-queryPerfN+1 查询模式
另加 5 条…

快速收益

之前(SQL 注入)

// ❌ SQL Injection
const query = `SELECT * FROM users WHERE id = '${userId}'`;
await pool.query(query);

之后(参数化查询)

// ✅ Parameterized Query
const query = 'SELECT * FROM users WHERE id = $1';
await pool.query(query, [userId]);

之前(连接泄漏)

// ❌ Connection Leak
const client = await pool.connect();
const result = await client.query('SELECT * FROM users');
return result.rows;
// Missing client.release()!

之后(确保释放)

// ✅ Guaranteed Release
const client = await pool.connect();
try {
  const result = await client.query('SELECT * FROM users');
  return result.rows;
} finally {
  client.release();
}

可用预设

// Security + best practices
pg.configs.recommended;

// All rules enabled
pg.configs.all;

自定义规则

// eslint.config.js
import pg from 'eslint-plugin-pg';

export default [
  pg.configs.recommended,
  {
    rules: {
      // Downgrade to warning
      'pg/prefer-pool-query': 'warn',

      // Increase strictness
      'pg/no-unsafe-query': [
        'error',
        {
          allowLiteral: false,
        },
      ],
    },
  },
];

性能

┌─────────────────────────────────────────────────────┐
│ Benchmark: 1000 files                               │
├─────────────────────────────────────────────────────┤
│ eslint-plugin-pg:          785ms                    │
│ 100% precision (0 false positives in tests)         │
└─────────────────────────────────────────────────────┘

与其他插件结合

import pg from 'eslint-plugin-pg';
import secureCoding from 'eslint-plugin-secure-coding';

export default [pg.configs.recommended, secureCoding.configs.recommended];

快速参考

# Install
npm install --save-dev eslint-plugin-pg

# Config (eslint.config.js)
import pg from 'eslint-plugin-pg';
export default [pg.configs.recommended];

# Run
npx eslint .

链接

Back to Blog

相关文章

阅读更多 »

入门 eslint-plugin-secure-coding

封面图片:Getting Started with eslint-plugin-secure-coding https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/ht...