All files / analyzers PolicyEvaluator.ts

79.16% Statements 38/48
47.36% Branches 9/19
70% Functions 7/10
84.09% Lines 37/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192      1x                                                                     2x 2x 2x 2x 2x 2x 2x                                                             2x 2x 2x 2x 2x                               2x                                                   1x 1x     1x 11x         8x 66x     8x 8x   8x   8x 30x   30x 26x   26x 5x 5x                       30x 4x     30x 23x   7x       8x       8x                                
import { PolicyEvaluationResult, PolicyRule, PolicyViolation } from '../core/interfaces';
import { uuid } from './utils';
 
const BUILT_IN_RULES: PolicyRule[] = [
  {
    id: 'no-hardcoded-secrets',
    name: 'No Hardcoded Secrets',
    description: 'API keys, passwords, and tokens must not be hardcoded in source code.',
    severity: 'critical',
    pattern: /(?:api[_-]?key|password|secret|token|credential)\s*[:=]\s*['"`][A-Za-z0-9_\-!@#$%^&*]{8,}['"`]/gi,
  },
  {
    id: 'no-eval',
    name: 'No eval() Usage',
    description: 'eval() and Function() constructors are forbidden — security risk.',
    severity: 'critical',
    pattern: /\beval\s*\(|new\s+Function\s*\(/g,
  },
  {
    id: 'no-innerHTML',
    name: 'No Unsafe innerHTML',
    description: 'Direct innerHTML assignment with dynamic content is forbidden.',
    severity: 'high',
    pattern: /\.innerHTML\s*=\s*(?!['"`]\s*['"`])/g,
  },
  {
    id: 'no-console-log',
    name: 'No console.log in Production Code',
    description: 'console.log/warn/error statements must not be left in production code.',
    severity: 'low',
    pattern: /console\.(log|warn|error|info|debug)\s*\(/g,
  },
  {
    id: 'license-compliance',
    name: 'License Header Required',
    description: 'Source files must include a license header or SPDX identifier.',
    severity: 'medium',
    check: (code: string, filePath: string): PolicyViolation[] => {
      const extensions = ['.ts', '.js', '.tsx', '.jsx', '.py', '.java', '.cs', '.go', '.rs'];
      const hasExt = extensions.some(e => filePath.endsWith(e));
      Iif (!hasExt) return [];
      const header = code.substring(0, 500);
      const hasLicense = /(?:MIT|Apache|GPL|BSD|LGPL|MPL|ISC|copyright|SPDX-License-Identifier)/i.test(header);
      Iif (hasLicense) return [];
      return [{
        ruleId: 'license-compliance',
        ruleName: 'License Header Required',
        severity: 'medium',
        filePath,
        line: 1,
        snippet: code.split('\n')[0] ?? '',
        message: 'No license header found in source file.',
      }];
    },
  },
  {
    id: 'no-http-external',
    name: 'No HTTP for External URLs',
    description: 'External URLs must use HTTPS, not HTTP.',
    severity: 'medium',
    pattern: /['"`]http:\/\/(?!localhost|127\.0\.0\.1|0\.0\.0\.0)[^'"`]+['"`]/g,
  },
  {
    id: 'no-any-typescript',
    name: 'No TypeScript any Type',
    description: 'Usage of "any" type bypasses TypeScript safety.',
    severity: 'low',
    pattern: /:\s*any\b|\bas\s+any\b/g,
  },
  {
    id: 'no-async-without-await',
    name: 'Async Functions Must Use await',
    description: 'async functions without await are likely bugs.',
    severity: 'low',
    check: (code: string, filePath: string): PolicyViolation[] => {
      Iif (!filePath.match(/\.(ts|js|tsx|jsx)$/)) return [];
      const violations: PolicyViolation[] = [];
      const lines = code.split('\n');
      lines.forEach((line, i) => {
        Iif (/async\s+function|async\s+\(|async\s+\w+\s*=/.test(line)) {
          const blockEnd = Math.min(i + 20, lines.length);
          const block = lines.slice(i, blockEnd).join('\n');
          Iif (!/\bawait\b/.test(block) && !/Promise/.test(block)) {
            violations.push({
              ruleId: 'no-async-without-await',
              ruleName: 'Async Functions Must Use await',
              severity: 'low',
              filePath,
              line: i + 1,
              snippet: line.trim(),
              message: 'async function may be missing await.',
            });
          }
        }
      });
      return violations;
    },
  },
  {
    id: 'gdpr-personal-data-logging',
    name: 'GDPR: No Personal Data in Logs',
    description: 'Personal data (email, phone, name, SSN) must not be logged.',
    severity: 'high',
    pattern: /console\.[a-z]+\([^)]*(?:email|phone|ssn|passport|dob|birthdate|address|creditcard)[^)]*\)/gi,
  },
  {
    id: 'no-synchronous-fs',
    name: 'No Synchronous File Operations',
    description: 'Synchronous fs operations block the event loop.',
    severity: 'medium',
    pattern: /\bfs\.(readFileSync|writeFileSync|readdirSync|statSync|existsSync|unlinkSync|mkdirSync)\b/g,
  },
  {
    id: 'no-weak-crypto',
    name: 'No Weak Cryptography',
    description: 'MD5 and SHA1 are cryptographically broken.',
    severity: 'high',
    pattern: /(?:createHash|hashlib\.new|MessageDigest\.getInstance)\s*\(\s*['"`](?:md5|sha1|sha-1)['"`]/gi,
  },
];
 
export class PolicyEvaluator {
  private rules: Map<string, PolicyRule> = new Map();
 
  constructor() {
    for (const rule of BUILT_IN_RULES) {
      this.rules.set(rule.id, rule);
    }
  }
 
  evaluate(code: string, filePath: string, activeRuleIds?: string[]): PolicyEvaluationResult {
    const activeRules = activeRuleIds
      ? [...this.rules.values()].filter(r => activeRuleIds.includes(r.id))
      : [...this.rules.values()];
 
    const violations: PolicyViolation[] = [];
    const passed: string[] = [];
 
    const lines = code.split('\n');
 
    for (const rule of activeRules) {
      const ruleViolations: PolicyViolation[] = [];
 
      if (rule.pattern) {
        const p = new RegExp(rule.pattern.source, rule.pattern.flags);
        let match: RegExpExecArray | null;
        while ((match = p.exec(code)) !== null) {
          const lineIndex = code.substring(0, match.index).split('\n').length;
          ruleViolations.push({
            ruleId: rule.id,
            ruleName: rule.name,
            severity: rule.severity,
            filePath,
            line: lineIndex,
            snippet: (lines[lineIndex - 1] ?? '').trim(),
            message: rule.description,
          });
        }
      }
 
      if (rule.check) {
        ruleViolations.push(...rule.check(code, filePath));
      }
 
      if (ruleViolations.length === 0) {
        passed.push(rule.id);
      } else {
        violations.push(...ruleViolations);
      }
    }
 
    const score = activeRules.length > 0
      ? Math.round((passed.length / activeRules.length) * 100)
      : 100;
 
    return { filePath, violations, passed, score, analyzedAt: new Date().toISOString() };
  }
 
  addCustomRule(rule: PolicyRule): void {
    this.rules.set(rule.id, rule);
  }
 
  removeRule(id: string): boolean {
    return this.rules.delete(id);
  }
 
  getRules(): PolicyRule[] {
    return [...this.rules.values()];
  }
}