All files / src/issue-reporting/obfuscation index.ts

100% Statements 131/131
95.45% Branches 21/22
100% Functions 5/5
100% Lines 131/131

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 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214              1x 1x   1x   1x                                       1x 1x 2x 2x 2x 1x         3x 3x 3x 2x 3x 1x 1x 3x             4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x     4x   4x   2x 2x 1x 1x 1x 1x 1x 1x   3x 3x     3x 3x     3x     3x 3x 3x 3x 3x 3x 3x     3x 3x 3x 3x     3x     4x 1x 1x 4x 1x 1x   3x 3x 3x 3x 5x 5x 5x 3x 3x 3x 3x 3x 4x         4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x               4x 4x 4x 4x 4x   4x   4x   4x   2x 2x 1x 1x 1x 1x 1x   3x 3x     3x     3x     3x 3x 3x 3x 3x 3x 3x     2x 2x 2x 2x   2x 4x 3x 3x 4x 1x 1x 1x 4x  
/**
 * Code Obfuscation via VS Code Language Model API
 *
 * Uses VS Code's built-in LLM capabilities to obfuscate code for privacy.
 * If LLM is not available, obfuscation fails and code should NOT be sent.
 */
 
import * as vscode from "vscode";
import * as path from "node:path";
import { ObfuscatedCodeContext } from "../models";
import { Logger } from "../../logger";
 
const OBFUSCATION_PROMPT = `You are a code obfuscator. Obfuscate the following code for privacy:
 
RULES:
- Replace variable names with v1, v2, v3... (in order of appearance)
- Replace function/method names with fn1, fn2, fn3... (in order of appearance)
- Replace class names with Cls1, Cls2... (in order of appearance)
- Replace ALL string literals with "str_1", "str_2"... (in order of appearance)
- Remove ALL comments (single-line and multi-line)
- PRESERVE: language keywords, operators, numbers, indentation, code structure
 
OUTPUT FORMAT:
Return ONLY the obfuscated code lines, one per line, with NO explanations, NO markdown, NO code fences.
Keep the exact same number of lines as input.
 
CODE TO OBFUSCATE:
`;
 
/**
 * Error thrown when obfuscation is not available
 */
export class ObfuscationUnavailableError extends Error {
    constructor(message: string) {
        super(message);
        this.name = "ObfuscationUnavailableError";
    }
}
 
/**
 * Check if LLM-based obfuscation is available
 */
export async function isObfuscationAvailable(): Promise<boolean> {
    try {
        const models = await vscode.lm.selectChatModels();
        return models.length > 0;
    } catch {
        return false;
    }
}
 
/**
 * Obfuscate code using VS Code's Language Model API
 *
 * @throws {ObfuscationUnavailableError} If no LLM is available - code should NOT be sent
 */
export async function obfuscateCode(
    filePath: string,
    lines: string[],
    startLineNumber: number,
    targetLineNumber: number,
    totalLinesInFile?: number
): Promise<ObfuscatedCodeContext> {
    const logger = Logger.getInstance();
    const ext = path.extname(filePath).toLowerCase();
    const language = getLanguageFromExtension(ext);
 
    logger.info(
        `Obfuscating ${lines.length} lines of ${language} code via LLM`
    );
 
    // Get available chat models
    const models = await vscode.lm.selectChatModels({ vendor: "copilot" });
 
    if (models.length === 0) {
        // Try any available model
        const allModels = await vscode.lm.selectChatModels();
        if (allModels.length === 0) {
            throw new ObfuscationUnavailableError(
                "No language models available for code obfuscation. Code will not be included in the report."
            );
        }
        models.push(allModels[0]);
    }
 
    const model = models[0];
    logger.info(`Using language model: ${model.name} (${model.vendor})`);
 
    // Build the prompt
    const codeBlock = lines.join("\n");
    const fullPrompt = `${OBFUSCATION_PROMPT}Language: ${language}\n\n${codeBlock}`;
 
    // Create chat messages
    const messages = [vscode.LanguageModelChatMessage.User(fullPrompt)];
 
    // Send request with proper token disposal
    const tokenSource = new vscode.CancellationTokenSource();
    try {
        const response = await model.sendRequest(
            messages,
            {},
            tokenSource.token
        );
 
        // Collect the response
        let result = "";
        for await (const chunk of response.text) {
            result += chunk;
        }
 
        // Parse response - split by lines and ensure same count
        const obfuscatedLines = result.trim().split("\n");
 
        // If line count doesn't match, pad or truncate
        while (obfuscatedLines.length < lines.length) {
            obfuscatedLines.push("");
        }
        if (obfuscatedLines.length > lines.length) {
            obfuscatedLines.length = lines.length;
        }
 
        return {
            fileExtension: ext,
            totalLinesInFile,
            lines: obfuscatedLines.map((content, index) => ({
                lineNumber: startLineNumber + index,
                obfuscatedContent: content,
                isTargetLine: startLineNumber + index === targetLineNumber,
            })),
        };
    } finally {
        tokenSource.dispose();
    }
}
 
/**
 * Get language name from file extension
 */
function getLanguageFromExtension(ext: string): string {
    const languageMap: Record<string, string> = {
        ".py": "Python",
        ".pyw": "Python",
        ".scala": "Scala",
        ".sc": "Scala",
        ".java": "Java",
        ".kt": "Kotlin",
        ".js": "JavaScript",
        ".ts": "TypeScript",
        ".sql": "SQL",
        ".r": "R",
    };
    return languageMap[ext] || "code";
}
 
/**
 * Simple obfuscation function for use by MCP tools.
 * Takes raw code string and language, returns obfuscated code or null if unavailable.
 *
 * This is the handler signature expected by ObfuscateCodeHandler type.
 */
export async function obfuscateCodeString(
    code: string,
    language: string
): Promise<string | null> {
    const logger = Logger.getInstance();
 
    try {
        // Get available chat models
        const models = await vscode.lm.selectChatModels({ vendor: "copilot" });
 
        if (models.length === 0) {
            // Try any available model
            const allModels = await vscode.lm.selectChatModels();
            if (allModels.length === 0) {
                logger.warn("No language models available for obfuscation");
                return null;
            }
            models.push(allModels[0]);
        }
 
        const model = models[0];
        logger.debug(`Obfuscating code via LLM: ${model.name}`);
 
        // Build the prompt
        const fullPrompt = `${OBFUSCATION_PROMPT}Language: ${language}\n\n${code}`;
 
        // Create chat messages
        const messages = [vscode.LanguageModelChatMessage.User(fullPrompt)];
 
        // Send request with proper token disposal
        const tokenSource = new vscode.CancellationTokenSource();
        try {
            const response = await model.sendRequest(
                messages,
                {},
                tokenSource.token
            );
 
            // Collect the response
            let result = "";
            for await (const chunk of response.text) {
                result += chunk;
            }
 
            return result.trim();
        } finally {
            tokenSource.dispose();
        }
    } catch (error) {
        logger.warn(`Obfuscation failed: ${error}`);
        return null;
    }
}