Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 30 additions & 84 deletions scripts/check-all-personal-paths.cjs
Original file line number Diff line number Diff line change
@@ -1,89 +1,35 @@
#!/usr/bin/env node

const fs = require('fs');
const { execFileSync } = require('node:child_process');
const path = require('path');
const { personalPatterns } = require('./check-personal-paths.cjs');

// File extensions to check
const extensions = [
'md', 'ts', 'js', 'cjs', 'mjs', 'json', 'yml', 'yaml', 'txt',
'sh', 'cmd', 'bat', 'ps1', 'py', 'tsx', 'jsx', 'env', 'config'
];

// Directories to exclude
// `.dart_tool` is `dart pub get` output (gitignored); its package_config.json holds absolute file: URIs.
const excludeDirs = ['node_modules', 'dist', 'coverage', '.git', 'build', '.husky', 'logs', 'sessions', 'vendor', '.dart_tool'];

// Binary file extensions to skip
const binaryExtensions = [
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'ico', 'svg',
'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx',
'zip', 'tar', 'gz', 'rar', '7z',
'exe', 'dll', 'so', 'dylib',
'mp3', 'mp4', 'avi', 'mov', 'wav',
'ttf', 'otf', 'woff', 'woff2', 'eot'
];

// Check if file is binary based on extension
function isBinaryFile(filename) {
const ext = path.extname(filename).slice(1).toLowerCase();
return binaryExtensions.includes(ext);
}

// Recursively get all files in a directory
function getAllFiles(dirPath, arrayOfFiles = []) {
const {
GIT_MAX_BUFFER,
checkFile,
isAuditablePath,
resolveRepoRoot
} = require('./check-personal-paths.cjs');

// Include work in progress alongside indexed files. Git applies the same
// nested ignore rules used by git add, including each CodeLLDB package's payload.
function getAuditFiles() {
try {
const files = fs.readdirSync(dirPath);

files.forEach(file => {
const filePath = path.join(dirPath, file);

// Skip excluded directories
if (excludeDirs.includes(file)) {
return;
}

if (fs.statSync(filePath).isDirectory()) {
arrayOfFiles = getAllFiles(filePath, arrayOfFiles);
} else {
// Check if file has a valid extension and is not binary
const ext = path.extname(file).slice(1);
if (extensions.includes(ext) && !isBinaryFile(file)) {
arrayOfFiles.push(filePath);
}
const repoRoot = resolveRepoRoot();
const paths = execFileSync(
'git',
['ls-files', '-z', '--cached', '--others', '--exclude-standard'],
{
cwd: repoRoot,
encoding: 'utf8',
windowsHide: true,
maxBuffer: GIT_MAX_BUFFER
}
});
);
return [...new Set(paths.split('\0'))]
.filter(file => isAuditablePath(file))
.map(relPath => ({ relPath, absPath: path.join(repoRoot, relPath) }));
} catch (error) {
console.error(`Error reading directory ${dirPath}:`, error.message);
}

return arrayOfFiles;
}

// Check file for personal information
function checkFile(filePath) {
if (!fs.existsSync(filePath)) {
return null;
}

try {
const content = fs.readFileSync(filePath, 'utf8');
const findings = [];

personalPatterns.forEach(pattern => {
const matches = content.match(pattern);
if (matches) {
findings.push({
pattern: pattern.source,
matches: [...new Set(matches)]
});
}
});

return findings.length > 0 ? findings : null;
} catch (error) {
// Skip files that can't be read as UTF-8
return null;
console.error('Error listing repository audit files:', error.message);
process.exit(1);
}
}

Expand All @@ -110,24 +56,24 @@ function main() {
console.log('🔍 Running full audit for personal information in all files...\n');

const startTime = Date.now();
const allFiles = getAllFiles('.');
const allFiles = getAuditFiles();

console.log(`Found ${allFiles.length} file(s) to check...\n`);

let foundPersonalInfo = false;
const allFindings = [];
let checkedCount = 0;

allFiles.forEach(file => {
allFiles.forEach(({ relPath, absPath }) => {
checkedCount++;
if (checkedCount % 100 === 0) {
process.stdout.write(`\rChecking file ${checkedCount}/${allFiles.length}...`);
}

const findings = checkFile(file);
const findings = checkFile(absPath);
if (findings) {
foundPersonalInfo = true;
allFindings.push({ file, findings });
allFindings.push({ file: relPath, findings });
}
});

Expand Down
82 changes: 60 additions & 22 deletions scripts/check-personal-paths.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const { execFileSync } = require('node:child_process');

const GIT_MAX_BUFFER = 16 * 1024 * 1024;

// Generic patterns to detect personal information without containing it
const personalPatterns = [
Expand Down Expand Up @@ -48,33 +50,63 @@ const binaryExtensions = [
'ttf', 'otf', 'woff', 'woff2', 'eot'
];

// Get staged files
// Resolve the Git worktree root for the given directory.
function resolveRepoRoot(cwd = process.cwd()) {
return execFileSync('git', ['rev-parse', '--show-toplevel'], {
cwd,
encoding: 'utf8',
windowsHide: true,
maxBuffer: GIT_MAX_BUFFER
}).trim();
}

// Check if file is binary based on extension
function isBinaryFile(filename) {
const ext = path.extname(filename).slice(1).toLowerCase();
return binaryExtensions.includes(ext);
}

// Check whether a candidate path has an auditable text extension or .env basename
function isAuditablePath(filePath) {
if (!filePath || isBinaryFile(filePath)) {
return false;
}
const base = path.posix.basename(filePath.replace(/\\/g, '/')).toLowerCase();
if (base === '.env' || base.startsWith('.env.')) {
return true;
}
const ext = path.extname(base).slice(1);
return extensions.includes(ext);
}

// Get staged files as { relPath, absPath } entries rooted at the Git worktree.
// Uses -z so non-ASCII or special characters are never C-quoted and skipped.
function getStagedFiles() {
try {
const output = execSync('git diff --cached --name-only --diff-filter=ACM', { windowsHide: true, encoding: 'utf8' });
return output
.split('\n')
.filter(file => file && !isBinaryFile(file))
.filter(file => {
const ext = path.extname(file).slice(1);
return extensions.includes(ext);
})
const repoRoot = resolveRepoRoot();
const output = execFileSync(
'git',
['diff', '--cached', '-z', '--name-only', '--diff-filter=ACM'],
{
cwd: repoRoot,
windowsHide: true,
encoding: 'utf8',
maxBuffer: GIT_MAX_BUFFER
}
);
return [...new Set(output.split('\0'))]
.filter(file => isAuditablePath(file))
.filter(file => {
const segments = file.split(path.sep);
const segments = file.split(/[\\/]/);
return !segments.some(segment => excludeDirs.includes(segment));
});
})
.map(relPath => ({ relPath, absPath: path.join(repoRoot, relPath) }));
} catch (error) {
console.error('Error getting staged files:', error.message);
process.exit(1);
}
}

// Check if file is binary based on extension
function isBinaryFile(filename) {
const ext = path.extname(filename).slice(1).toLowerCase();
return binaryExtensions.includes(ext);
}

// Check file for personal information
function checkFile(filePath) {
if (!fs.existsSync(filePath)) {
Expand Down Expand Up @@ -136,11 +168,11 @@ function main() {
let foundPersonalInfo = false;
const allFindings = [];

stagedFiles.forEach(file => {
const findings = checkFile(file);
stagedFiles.forEach(({ relPath, absPath }) => {
const findings = checkFile(absPath);
if (findings) {
foundPersonalInfo = true;
allFindings.push({ file, findings });
allFindings.push({ file: relPath, findings });
}
});

Expand Down Expand Up @@ -176,4 +208,10 @@ if (require.main === module) {
main();
}

module.exports = { checkFile, personalPatterns };
module.exports = {
GIT_MAX_BUFFER,
checkFile,
isAuditablePath,
personalPatterns,
resolveRepoRoot
};
83 changes: 83 additions & 0 deletions tests/unit/scripts/check-all-personal-paths.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { execFileSync, spawnSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { expect, it } from 'vitest';

const audit = fileURLToPath(new URL('../../../scripts/check-all-personal-paths.cjs', import.meta.url));
const stagedAudit = fileURLToPath(new URL('../../../scripts/check-personal-paths.cjs', import.meta.url));

function cleanGitEnv(): NodeJS.ProcessEnv {
// A test run from a Git hook may inherit the real repository's index.
return Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')));
}

it('audits tracked files and untracked candidates while skipping a locally installed payload', () => {
const cwd = mkdtempSync(path.join(tmpdir(), 'personal-path-audit-'));
const env = cleanGitEnv();
const options = { cwd, env, windowsHide: true, encoding: 'utf8' as const };
try {
execFileSync('git', ['init', '-q'], options);
const pkg = path.join(cwd, 'packages', 'adapter');
const payload = path.join(pkg, 'lldb');
mkdirSync(payload, { recursive: true });
const personalPath = ['', 'home', 'example-developer', 'file'].join('/');
writeFileSync(path.join(pkg, '.gitignore'), 'lldb/\n');
writeFileSync(path.join(payload, 'installed.py'), personalPath);
const clean = spawnSync(process.execPath, [audit], options);
expect(clean.status, clean.stderr).toBe(0);

// Even a path matching an ignore rule is in scope once Git tracks it.
writeFileSync(path.join(payload, 'tracked.py'), personalPath);
execFileSync('git', ['add', '-f', '--', 'packages/adapter/lldb/tracked.py'], options);
writeFileSync(path.join(cwd, 'new source.ts'), personalPath);
const dirty = spawnSync(process.execPath, [audit], options);
expect(dirty.status, dirty.stderr).toBe(1);
expect(dirty.stderr).toContain('tracked.py');
expect(dirty.stderr).toContain('new source.ts');
expect(dirty.stderr).not.toContain('installed.py');
} finally {
rmSync(cwd, { recursive: true, force: true });
}
});

it('scans .env variants, uppercase extensions, non-ASCII staged paths, and nested working directories', () => {
const cwd = mkdtempSync(path.join(tmpdir(), 'personal-path-audit-edges-'));
const env = cleanGitEnv();
const options = { cwd, env, windowsHide: true, encoding: 'utf8' as const };
try {
execFileSync('git', ['init', '-q'], options);
const nestedDir = path.join(cwd, 'packages', 'subpkg');
const vendorDir = path.join(cwd, 'vendor');
mkdirSync(nestedDir, { recursive: true });
mkdirSync(vendorDir, { recursive: true });

const personalPath = ['', 'home', 'example-developer', 'secret'].join('/');
writeFileSync(path.join(cwd, '.env'), `DATA_DIR=${personalPath}\n`);
writeFileSync(path.join(cwd, '.env.local'), `CACHE_DIR=${personalPath}\n`);
writeFileSync(path.join(cwd, 'NOTES.MD'), personalPath);
writeFileSync(path.join(cwd, 'café notes.ts'), `const p = "${personalPath}";\n`);
writeFileSync(path.join(vendorDir, 'vendored.js'), `const p = "${personalPath}";\n`);

// Running full audit from a nested directory still audits the entire repository.
const nestedOptions = { ...options, cwd: nestedDir, windowsHide: true };
const fullFromNested = spawnSync(process.execPath, [audit], nestedOptions);
expect(fullFromNested.status, fullFromNested.stderr).toBe(1);
expect(fullFromNested.stderr).toContain('.env');
expect(fullFromNested.stderr).toContain('.env.local');
expect(fullFromNested.stderr).toContain('NOTES.MD');
expect(fullFromNested.stderr).toContain('café notes.ts');

// Stage a non-ASCII filename, .env, and an excluded vendor/ file; run staged audit from nested cwd.
execFileSync('git', ['add', '--', '.env', 'café notes.ts', 'vendor/vendored.js'], options);
const stagedFromNested = spawnSync(process.execPath, [stagedAudit], nestedOptions);
expect(stagedFromNested.status, stagedFromNested.stderr).toBe(1);
expect(stagedFromNested.stderr).toContain('.env');
expect(stagedFromNested.stderr).toContain('café notes.ts');
// Excluded directories (forward-slash Git output on Windows and POSIX) stay excluded in staged scan.
expect(stagedFromNested.stderr).not.toContain('vendored.js');
} finally {
rmSync(cwd, { recursive: true, force: true });
}
});
Loading