{"id":28855930,"url":"https://github.com/sametcn99/sql-query-safety-checker","last_synced_at":"2026-04-04T13:39:39.961Z","repository":{"id":298486779,"uuid":"1000144451","full_name":"sametcn99/sql-query-safety-checker","owner":"sametcn99","description":"A comprehensive TypeScript library for analyzing SQL queries and detecting potential security threats, including SQL injection patterns, dangerous operations, and data modification commands. Perfect for applications that need to validate user-provided SQL queries before execution.","archived":false,"fork":false,"pushed_at":"2025-06-19T06:53:18.000Z","size":78,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-06-19T06:55:59.895Z","etag":null,"topics":["bunjs","bunup","npm-package","sql-query-analysis"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/sql-query-safety-checker","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sametcn99.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-06-11T10:30:49.000Z","updated_at":"2025-06-19T06:53:22.000Z","dependencies_parsed_at":"2025-06-11T11:29:12.992Z","dependency_job_id":"3c6a326d-c331-4623-a9b3-0fe710ec6f82","html_url":"https://github.com/sametcn99/sql-query-safety-checker","commit_stats":null,"previous_names":["sametcn99/sql-query-safety-checker"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/sametcn99/sql-query-safety-checker","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sametcn99%2Fsql-query-safety-checker","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sametcn99%2Fsql-query-safety-checker/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sametcn99%2Fsql-query-safety-checker/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sametcn99%2Fsql-query-safety-checker/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sametcn99","download_url":"https://codeload.github.com/sametcn99/sql-query-safety-checker/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sametcn99%2Fsql-query-safety-checker/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260852151,"owners_count":23072604,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bunjs","bunup","npm-package","sql-query-analysis"],"created_at":"2025-06-20T00:09:28.427Z","updated_at":"2026-04-04T13:39:39.946Z","avatar_url":"https://github.com/sametcn99.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# SQL Query Safety Checker\n\n[![npm version](https://badge.fury.io/js/sql-query-safety-checker.svg)](https://badge.fury.io/js/sql-query-safety-checker)\n[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)\n[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)\n\nA comprehensive TypeScript library for analyzing SQL queries and detecting potential security threats, including SQL injection patterns, dangerous operations, and data modification commands. Perfect for applications that need to validate user-provided SQL queries before execution.\n\n## 🚀 Features\n\n- **🔍 SQL Injection Detection**: Identifies common SQL injection patterns including UNION attacks, boolean-based injections, and comment-based evasion\n- **⚠️ Risk Assessment**: Categorizes operations by security level (Safe, Low Risk, Medium Risk, High Risk, Critical)\n- **📊 Comprehensive Analysis**: Detailed threat analysis with descriptions and recommendations\n- **🛡️ Policy Validation**: Validate queries against custom security policies\n- **🎯 Operation Categorization**: Classifies operations into DML, DDL, DCL, Administrative, and System categories\n- **✅ Read-Only Detection**: Identifies safe SELECT-only queries\n- **💡 Smart Recommendations**: Provides context-aware security recommendations\n- **🎨 UI-Ready**: Includes color codes for security levels for easy UI integration\n- **📝 TypeScript Support**: Full TypeScript definitions included\n\n## 📦 Installation\n\n```bash\n# Using npm\nnpm install sql-query-safety-checker\n\n# Using yarn\nyarn add sql-query-safety-checker\n\n# Using bun\nbun add sql-query-safety-checker\n```\n\n## 🔧 Quick Start\n\n### Basic Usage\n\n```typescript\nimport {\n  SQLQuerySafetyChecker,\n  analyzeQuerySecurity,\n} from \"sql-query-safety-checker\";\n\n// Create a checker instance\nconst checker = new SQLQuerySafetyChecker();\n\n// Analyze a query\nconst query = \"SELECT * FROM users WHERE id = 1\";\nconst analysis = checker.analyzeQuery(query);\n\nconsole.log(\"Security Level:\", analysis.securityLevel);\nconsole.log(\"Is Dangerous:\", analysis.isDangerous);\nconsole.log(\"Is Read-Only:\", analysis.isSelectOnly);\nconsole.log(\"Threats:\", analysis.threats);\nconsole.log(\"Recommendations:\", analysis.recommendations);\n```\n\n### Quick Safety Check\n\n```typescript\nimport { isQuerySafe } from \"sql-query-safety-checker\";\n\nconst safeQuery = \"SELECT name, email FROM users\";\nconst dangerousQuery = \"DROP TABLE users\";\n\nconsole.log(\"Safe query:\", isQuerySafe(safeQuery)); // true\nconsole.log(\"Dangerous query:\", isQuerySafe(dangerousQuery)); // false\n```\n\n## 📚 API Reference\n\n### Core Classes\n\n#### `SQLQuerySafetyChecker`\n\nThe main class for analyzing SQL queries.\n\n```typescript\nconst checker = new SQLQuerySafetyChecker();\n```\n\n**Methods:**\n\n- `analyzeQuery(query: string): QueryAnalysis` - Complete security analysis\n- `checkQuerySafety(query: string): QuerySafetyResult` - Basic safety check\n- `isSelectOnlyQuery(query: string): boolean` - Check if query is read-only\n- `requiresConfirmation(query: string): ConfirmationResult` - Check if user confirmation needed\n- `validateAgainstPolicy(query: string, policy: SecurityPolicy): PolicyValidationResult` - Validate against policy\n- `getSecuritySummary(query: string): string` - Get human-readable summary\n- `isSafe(query: string): boolean` - Quick safety check\n\n### Security Levels\n\n```typescript\nenum SecurityLevel {\n  SAFE = \"safe\",\n  LOW_RISK = \"low_risk\",\n  MEDIUM_RISK = \"medium_risk\",\n  HIGH_RISK = \"high_risk\",\n  CRITICAL = \"critical\",\n}\n```\n\n### Utility Functions\n\n#### `analyzeQuerySecurity(query: string): QueryAnalysis`\n\nPerforms comprehensive security analysis of a SQL query.\n\n```typescript\nconst analysis = analyzeQuerySecurity(\"DELETE FROM users WHERE id = 1\");\nconsole.log(analysis);\n// {\n//   securityLevel: \"high_risk\",\n//   isDangerous: true,\n//   isSelectOnly: false,\n//   threats: [\n//     {\n//       name: \"DELETE\",\n//       description: \"Data deletion operation\",\n//       level: \"high_risk\",\n//       category: \"DML\"\n//     }\n//   ],\n//   recommendations: [...],\n//   allowExecution: false\n// }\n```\n\n#### `needsConfirmation(query: string): ConfirmationResult`\n\nChecks if a query needs user confirmation before execution.\n\n```typescript\nconst confirmation = needsConfirmation(\"DELETE FROM users WHERE id = 1\");\nconsole.log(confirmation);\n// {\n//   required: true,\n//   level: \"high_risk\",\n//   reason: \"Query contains high-risk operations...\"\n// }\n```\n\n## 🛡️ Security Categories\n\nThe library categorizes SQL operations into different security categories:\n\n- **DML (Data Manipulation Language)**: INSERT, UPDATE, DELETE, MERGE operations\n- **DDL (Data Definition Language)**: CREATE, ALTER, DROP, TRUNCATE operations\n- **DCL (Data Control Language)**: GRANT, REVOKE operations\n- **INJECTION**: SQL injection patterns and suspicious constructs\n- **ADMIN**: Administrative operations like BACKUP, RESTORE\n- **SYSTEM**: System-level operations that could compromise security\n\n## 🔍 Detection Patterns\n\n### SQL Injection Detection\n\nThe library detects various SQL injection patterns:\n\n```typescript\n// Union-based injection\n\"SELECT * FROM users UNION SELECT password FROM admin\";\n\n// Boolean-based injection\n\"SELECT * FROM users WHERE id = 1 OR 1=1\";\n\n// Time-based injection\n\"SELECT * FROM users WHERE id = 1; WAITFOR DELAY '00:00:05'\";\n\n// Comment-based evasion\n\"SELECT * FROM users WHERE id = 1 /* comment */ OR 1=1\";\n```\n\n### Dangerous Operations\n\n```typescript\n// Critical operations\n\"DROP TABLE users\";\n\"EXEC xp_cmdshell 'format c:'\";\n\"GRANT ALL PRIVILEGES TO 'user'@'%'\";\n\n// High-risk operations\n\"DELETE FROM users\";\n\"CREATE TABLE sensitive_data\";\n\"ALTER TABLE users DROP COLUMN password\";\n\n// Medium-risk operations\n\"INSERT INTO logs VALUES (1, 'action')\";\n\"UPDATE users SET last_login = NOW()\";\n```\n\n## 🎯 Use Cases\n\n### 1. Query Validation Before Execution\n\n```typescript\nimport { SQLQuerySafetyChecker } from \"sql-query-safety-checker\";\n\nconst checker = new SQLQuerySafetyChecker();\n\nfunction executeQuery(sql: string) {\n  const analysis = checker.analyzeQuery(sql);\n\n  if (!analysis.allowExecution) {\n    throw new Error(`Query rejected: ${analysis.recommendations.join(\", \")}`);\n  }\n\n  if (analysis.securityLevel === \"critical\") {\n    throw new Error(\"Critical security threat detected\");\n  }\n\n  // Safe to execute\n  return database.query(sql);\n}\n```\n\n### 2. User Interface Integration\n\n```typescript\nimport {\n  analyzeQuerySecurity,\n  getSecurityLevelColor,\n} from \"sql-query-safety-checker\";\n\nfunction displayQueryAnalysis(query: string) {\n  const analysis = analyzeQuerySecurity(query);\n  const color = getSecurityLevelColor(analysis.securityLevel);\n\n  return {\n    level: analysis.securityLevel,\n    color: color,\n    warnings: analysis.threats.map((t) =\u003e t.description),\n    recommendations: analysis.recommendations,\n    canExecute: analysis.allowExecution,\n  };\n}\n```\n\n### 3. Policy Enforcement\n\n```typescript\nimport { validateQueryAgainstPolicy } from \"sql-query-safety-checker\";\n\nconst readOnlyPolicy = {\n  allowedOperations: [\"SELECT\", \"WITH\", \"EXPLAIN\", \"DESCRIBE\", \"SHOW\"],\n  maxRiskLevel: \"low_risk\",\n  blockInjectionPatterns: true,\n  requireConfirmationFor: [\"medium_risk\", \"high_risk\"],\n};\n\nfunction enforcePolicy(query: string) {\n  const validation = validateQueryAgainstPolicy(\n    query,\n    readOnlyPolicy.allowedOperations,\n  );\n\n  if (!validation.isValid) {\n    console.error(\"Policy violations:\", validation.violations);\n    return false;\n  }\n\n  return true;\n}\n```\n\n### 4. Security Monitoring\n\n```typescript\nimport { analyzeQuerySecurity } from \"sql-query-safety-checker\";\n\nfunction logSecurityEvents(query: string, userId: string) {\n  const analysis = analyzeQuerySecurity(query);\n\n  if (analysis.threats.length \u003e 0) {\n    console.warn(\"Security threat detected:\", {\n      userId,\n      query: query.substring(0, 100), // Log first 100 chars\n      threats: analysis.threats,\n      securityLevel: analysis.securityLevel,\n    });\n  }\n}\n```\n\n## 🧪 Testing\n\nThe library includes comprehensive tests covering various scenarios:\n\n```bash\n# Run tests\nbun test\n\n# Run specific test file\nbun test injection.test.ts\n```\n\nTest categories:\n\n- Basic functionality tests\n- SQL injection detection tests\n- Security policy validation tests\n- Performance benchmarks\n- Edge cases and malformed queries\n\n## 🔧 Configuration\n\n### Custom Security Policies\n\nYou can define custom security policies for different environments:\n\n```typescript\n// Development environment - more permissive\nconst devPolicy = {\n  allowedOperations: [\"SELECT\", \"INSERT\", \"UPDATE\", \"CREATE\", \"DROP\"],\n  maxRiskLevel: \"high_risk\",\n  blockInjectionPatterns: true,\n  requireConfirmationFor: [\"critical\"],\n};\n\n// Production environment - restrictive\nconst prodPolicy = {\n  allowedOperations: [\"SELECT\", \"WITH\", \"EXPLAIN\"],\n  maxRiskLevel: \"low_risk\",\n  blockInjectionPatterns: true,\n  requireConfirmationFor: [\"medium_risk\", \"high_risk\", \"critical\"],\n};\n```\n\n## ⚡ Performance\n\nThe library is optimized for performance:\n\n- **Fast Analysis**: Typical query analysis completes in \u003c1ms\n- **Memory Efficient**: Minimal memory footprint\n- **RegExp Optimization**: Efficient pattern matching with proper regex handling\n- **No Dependencies**: Zero external dependencies for maximum compatibility\n\n## 🤝 Contributing\n\nContributions are welcome! Please read our contributing guidelines and submit pull requests to our GitHub repository.\n\n### Development Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/sametcn99/sql-query-safety-checker.git\n\n# Install dependencies\nbun install\n\n# Run tests\nbun test\n\n# Build the project\nbun run build\n\n# Watch mode for development\nbun run dev\n```\n\n## 📄 License\n\nThis project is licensed under the GPL-3.0 License - see the [LICENSE](LICENSE) file for details.\n\n## 🔗 Links\n\n- [GitHub Repository](https://github.com/sametcn99/sql-query-safety-checker)\n- [npm Package](https://www.npmjs.com/package/sql-query-safety-checker)\n- [Issue Tracker](https://github.com/sametcn99/sql-query-safety-checker/issues)\n\n## 📈 Roadmap\n\n- [ ] Support for more SQL dialects (PostgreSQL, MySQL, Oracle)\n- [ ] Integration with popular ORMs\n- [ ] Real-time query monitoring dashboard\n- [ ] Custom threat pattern definitions\n\n---\n\n**⚠️ Security Notice**: This library helps identify potential security threats but should not be your only line of defense. Always use parameterized queries, proper input validation, and follow security best practices when working with databases.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsametcn99%2Fsql-query-safety-checker","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsametcn99%2Fsql-query-safety-checker","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsametcn99%2Fsql-query-safety-checker/lists"}