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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 | 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 22x 22x 22x 22x 22x 22x 6x 6x 6x 6x 6x 3x 3x 3x 3x 3x 25x 2x 2x 2x 2x 2x 2x 25x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 4x 25x 5x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 25x 25x 2x 1x 1x 1x 1x 25x 3x 3x 3x 3x 3x 1x 2x 1x 1x 1x 1x 1x 25x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 25x 1x 1x 1x 1x 1x 1x 25x 3x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 25x 12x 12x 12x 3x 12x 11x 1x 1x | import {
Injectable,
Logger,
BadRequestException,
NotFoundException,
} from '@nestjs/common';
import { Eta } from 'eta';
import * as fs from 'fs/promises';
import { glob } from 'glob';
import * as path from 'path';
import { exec, ExecOptions } from 'child_process';
import { InjectRepository } from '@nestjs/typeorm';
import { ContextTemplate } from '../core-entities';
import { Repository } from 'typeorm';
import { TemplateType } from '../core-entities/context-template.entity';
import { Trace } from '../utils';
@Injectable()
export class ContextGenerationService {
private readonly logger = new Logger(ContextGenerationService.name);
private eta: Eta;
private projectRoot: string =
process.env.REPOBURG_PROJECT_PATH || process.cwd();
private templateHelpers: { [key: string]: (...args: any[]) => Promise<any> };
private partialCache = new Map<string, ContextTemplate | null>();
constructor(
@InjectRepository(ContextTemplate)
private contextTemplatesRepository: Repository<ContextTemplate>,
) {
this.eta = new Eta({
views: this.projectRoot, // Using 'views' path as a security measure for includes/layouts
useWith: true, // Allows using properties of data object as local variables
});
this.templateHelpers = {
readFile: this.secureReadFile.bind(this),
readDir: this.secureReadDir.bind(this),
glob: this.secureGlob.bind(this),
tree: this.secureTree.bind(this),
ripGrep: this.secureRipGrep.bind(this),
gitDiff: this.secureGitDiff.bind(this),
runCommand: this.runCommand.bind(this),
include: this.include.bind(this),
fetchFileContent: this.fetchFileContent.bind(this),
};
}
private execPromise(
command: string,
options: ExecOptions,
): Promise<{ stdout: string; stderr: string }> {
return new Promise((resolve, reject) => {
exec(command, options, (error, stdout, stderr) => {
const stdoutStr = stdout.toString();
const stderrStr = stderr.toString();
if (error) {
// Attach stdout and stderr to the error object for more context in catch block.
// This mirrors the behavior of the promisified exec.
error['stdout'] = stdoutStr;
error['stderr'] = stderrStr;
reject(error);
return;
}
resolve({ stdout: stdoutStr, stderr: stderrStr });
});
});
}
/**
* Gets ripgrep ignore flags based on the presence of .rgignore file.
* If .rgignore exists, it overrides .gitignore behavior.
* Otherwise, ripgrep uses its default .gitignore/.ignore behavior.
*/
@Trace()
public async getRipGrepIgnoreFlags(): Promise<string> {
const rgignorePath = path.join(this.projectRoot, '.rgignore');
try {
await fs.access(rgignorePath, fs.constants.R_OK);
this.logger.log('.rgignore found, using it instead of .gitignore');
return '--ignore-file .rgignore --no-ignore-vcs';
} catch (error) {
Iif (error.code === 'ENOENT') {
this.logger.log(
'.rgignore not found, using default .gitignore behavior',
);
return ''; // Empty string means use default gitignore behavior
}
this.logger.error(`Error checking for .rgignore: ${error.message}`);
return '';
}
}
/**
* Helper function to resolve the command path.
* Tries to find the executable in the local `bin` directory first.
* The path is resolved relative to this file's location, which works for both `src` and `dist`.
*/
@Trace()
public async getCommandPath(commandName: string): Promise<string> {
// Check if running from the compiled 'dist' directory
const inDist = __dirname.includes(path.join('backend', 'dist'));
// In 'dist', bin is a sibling: `dist/context-generation` -> `dist/bin`
// In 'src', bin is in the parent: `src/context-generation` -> `../bin`
const relativePath = inDist
? path.join(__dirname, '..', 'bin', commandName)
: path.join(__dirname, '..', '..', 'src', 'bin', commandName);
const bundledPath = path.resolve(relativePath);
try {
await fs.access(bundledPath, fs.constants.X_OK);
this.logger.log(
`Using bundled executable for '${commandName}' at: ${bundledPath}`,
);
// Return the absolute, quoted path to be safe.
return `'${bundledPath}'`;
} catch (error) {
this.logger.warn(
`Bundled executable for '${commandName}' not found or not executable at '${bundledPath}'. Falling back to system PATH.`,
);
return commandName; // Fallback to system command
}
}
/**
* Resolves a given path against the project root and ensures it does not traverse outside.
* @param unsafePath The user-provided path.
* @returns A validated, absolute path.
* @throws BadRequestException if path traversal is detected.
*/
private resolveAndValidatePath(unsafePath: string): string {
const normalizedPath = path.normalize(unsafePath);
Iif (path.isAbsolute(normalizedPath)) {
throw new BadRequestException(
`Absolute paths are not allowed: ${unsafePath}`,
);
}
const resolvedPath = path.resolve(this.projectRoot, normalizedPath);
if (!resolvedPath.startsWith(this.projectRoot)) {
this.logger.warn(`Path traversal attempt detected: ${unsafePath}`);
throw new BadRequestException(
`Path traversal is not allowed. Access denied for path: ${unsafePath}`,
);
}
return resolvedPath;
}
@Trace()
public async secureReadFile(filePath: string): Promise<string> {
const safePath = this.resolveAndValidatePath(filePath);
try {
const stats = await fs.lstat(safePath);
Iif (!stats.isFile()) {
this.logger.warn(`Path is not a file: ${safePath}`);
return `Error: '${filePath}' is not a file`;
}
const content = await fs.readFile(safePath, 'utf8');
const lines = content.split('\n');
const contentWithLineNumbers = lines
.map((line, index) => `${index + 1}:${line}`)
.join('\n');
return `// File: ${filePath}\n\`\`\`\n${contentWithLineNumbers}\n\`\`\``;
} catch (error) {
if (error.code === 'ENOENT') {
this.logger.warn(`File not found in template render: ${safePath}`);
// Return a user-friendly error message within the template
return `Error: File not found at '${filePath}'`;
}
this.logger.error(`Error reading file ${safePath}: ${error.message}`);
// Re-throwing will cause template rendering to fail, which is appropriate here.
throw error;
}
}
@Trace()
public async fetchFileContent(filePath: string): Promise<string> {
const safePath = this.resolveAndValidatePath(filePath);
try {
const stats = await fs.lstat(safePath);
Iif (!stats.isFile()) {
this.logger.warn(`Path is not a file: ${safePath}`);
throw new NotFoundException(`'${filePath}' is not a file`);
}
const content = await fs.readFile(safePath, 'utf8');
return content;
} catch (error) {
Iif (error.code === 'ENOENT') {
this.logger.warn(
`File not found when fetching raw content: ${safePath}`,
);
throw new NotFoundException(`File not found: ${filePath}`);
}
this.logger.error(
`Error fetching raw file content from ${safePath}: ${error.message}`,
);
throw error;
}
}
private async secureReadDir(dirPath: string): Promise<string[]> {
const safePath = this.resolveAndValidatePath(dirPath);
try {
const entries = await fs.readdir(safePath, { withFileTypes: true });
// Return file names within the directory
return entries.filter((e) => e.isFile()).map((entry) => entry.name);
} catch (error) {
Iif (error.code === 'ENOENT') {
this.logger.warn(`Directory not found in template render: ${safePath}`);
return [`Error: Directory not found at '${dirPath}'`];
}
this.logger.error(
`Error reading directory ${safePath}: ${error.message}`,
);
throw error;
}
}
@Trace()
public async secureGlob(pattern: string): Promise<string[]> {
if (path.isAbsolute(pattern)) {
throw new BadRequestException(
`Absolute paths are not allowed in glob patterns: ${pattern}`,
);
}
try {
const files: string[] = await glob(pattern, {
cwd: this.projectRoot,
nodir: true, // we only want files
absolute: false, // return paths relative to cwd
});
return files;
} catch (error) {
this.logger.error(
`Error resolving glob pattern "${pattern}": ${error.message}`,
);
throw error;
}
}
@Trace()
public async secureTree(args?: string): Promise<string> {
const treeCommand = await this.getCommandPath('tree');
const command = `${treeCommand} ${args || ''}`;
try {
this.logger.log(`Executing command: ${command}`);
const { stdout } = await this.execPromise(command, {
cwd: this.projectRoot,
maxBuffer: 32 * 1024 * 1024,
timeout: 3000,
});
return stdout;
} catch (error) {
if (error.signal === 'SIGTERM') {
this.logger.warn(`'tree' command timed out after 3 seconds.`);
return `'tree' command timed out after 3 seconds.`;
}
if (error.message.includes('command not found')) {
this.logger.warn(
`'tree' command not found. Please ensure it is installed and in your PATH or bundled in 'backend/bin'.`,
);
return `'tree' command not found. Please ensure it is installed and in your PATH or bundled in 'backend/bin'.`;
}
this.logger.error(
`Error executing tree command: ${error.message}`,
error,
);
return `Error executing tree command: ${error.stderr || error.message}`;
}
}
@Trace()
public async secureRipGrep(args?: string): Promise<string> {
const rgCommand = await this.getCommandPath('rg');
const ignoreFlags = await this.getRipGrepIgnoreFlags();
const command = `${rgCommand} ${ignoreFlags} ${args || ''}`;
try {
this.logger.log(`Executing command: ${command}`);
const { stdout } = await this.execPromise(command, {
cwd: this.projectRoot,
maxBuffer: 256 * 1024 * 1024,
timeout: 3000,
});
return stdout;
} catch (error) {
Iif (error.signal === 'SIGTERM') {
this.logger.warn(`'rg' command timed out after 3 seconds.`);
return `'rg' command timed out after 3 seconds.`;
}
if (error.code === 1) {
// Exit code 1 means no matches were found, which is not a failure.
return error.stdout; // Return stdout, which is likely empty.
}
Iif (error.message.includes('command not found')) {
this.logger.warn(
`'rg' (ripgrep) command not found. Please ensure it is installed and in your PATH or bundled in 'backend/bin'.`,
);
return `'rg' (ripgrep) command not found. Please ensure it is installed and in your PATH or bundled in 'backend/bin'.`;
}
this.logger.error(
`Error executing ripgrep command: ${error.message}`,
error,
);
return `Error executing ripgrep command: ${
error.stderr || error.message
}`;
}
}
@Trace()
public async secureGitDiff(args?: string): Promise<string> {
Iif (args && /[`$&|;()<>*]/.test(args)) {
this.logger.warn(
`Potential command injection attempt in gitDiff args: ${args}`,
);
return `Error: Invalid characters in gitDiff arguments.`;
}
const command = `git --no-pager diff ${args || ''}`;
try {
this.logger.log(`Executing command: ${command}`);
const { stdout } = await this.execPromise(command, {
cwd: this.projectRoot,
maxBuffer: 256 * 1024 * 1024,
timeout: 30000,
});
return stdout;
} catch (error) {
Iif (error.signal === 'SIGTERM') {
this.logger.warn(`'git diff' command timed out after 30 seconds.`);
return `'git diff' command timed out after 30 seconds.`;
}
Iif (error.message.includes('command not found')) {
this.logger.warn(
`'git' command not found. Please ensure it is installed and in your PATH.`,
);
return `'git' command not found. Please ensure it is installed and in your PATH.`;
}
this.logger.error(
`Error executing git diff command: ${error.message}`,
error,
);
return `Error executing git diff command: ${
error.stderr || error.message
}`;
}
}
@Trace()
public async runCommand(commandString: string): Promise<string> {
Iif (!commandString) {
return 'Error: command cannot be empty.';
}
try {
this.logger.log(`Executing command from template: ${commandString}`);
const { stdout, stderr } = await this.execPromise(commandString, {
cwd: this.projectRoot,
maxBuffer: 256 * 1024 * 1024, // 256MB buffer
timeout: 30000, // 30 second timeout
});
Iif (stderr) {
this.logger.warn(
`Command "${commandString}" produced stderr: ${stderr}`,
);
return `STDOUT:\n${stdout}\n\nSTDERR:\n${stderr}`;
}
return stdout;
} catch (error) {
Iif (error.signal === 'SIGTERM') {
this.logger.warn(
`Command "${commandString}" timed out after 30 seconds.`,
);
return `Error: Command "${commandString}" timed out after 30 seconds.`;
}
this.logger.error(
`Error executing command "${commandString}": ${error.message}`,
error,
);
return `Error executing command "${commandString}": ${
error.stderr || error.message
}`;
}
}
private async include(templateName: string, data: any): Promise<string> {
// Recursion check
if (data.__included_partials.has(templateName)) {
this.logger.error(
`Recursive inclusion of partial "${templateName}" detected.`,
);
return `[Error: Recursive inclusion of partial "${templateName}" detected]`;
}
let partial = this.partialCache.get(templateName);
if (partial === undefined) {
this.logger.log(
`Cache miss for partial: "${templateName}". Fetching from DB.`,
);
partial = await this.contextTemplatesRepository.findOneBy({
template_name: templateName,
template_type: TemplateType.PARTIAL,
});
this.partialCache.set(templateName, partial || null);
} else E{
this.logger.log(`Cache hit for partial: "${templateName}".`);
}
Iif (!partial) {
this.logger.warn(
`Partial template "${templateName}" not found or is not of type 'partial'.`,
);
return `[Error: Partial template "${templateName}" not found]`;
}
// Add to the set for the duration of this sub-render
data.__included_partials.add(templateName);
// Render the partial with the same data context
const result = await this.eta.renderStringAsync(
partial.template_content,
data,
);
// Backtrack: remove from the set after rendering is complete
data.__included_partials.delete(templateName);
return result;
}
/**
* Renders a context string from an Eta template and provided data.
* @param templateContent The Eta template string.
* @param data An object containing data to be injected into the template.
* @returns The rendered string.
*/
@Trace()
public async render(
templateContent: string,
data: object = {},
): Promise<string> {
try {
const renderData = {
...data,
...this.templateHelpers,
// Add a property to the data object to track included partials and prevent recursion
__included_partials: new Set<string>(),
};
// The `include` helper expects the data object as its second argument.
// The template author must call it like: <%~ await it.include('my-partial', it) %>
// We are binding `this` to the `include` function, so it has access to the repository and cache.
renderData['include'] = (templateName: string) =>
this.include(templateName, renderData);
const result = await this.eta.renderStringAsync(
templateContent,
renderData,
);
return result;
} catch (error) {
this.logger.error(
`Error rendering Eta template: ${error.message}`,
error.stack,
);
throw new Error(`Template rendering failed: ${error.message}`);
}
}
}
|