bada-terminal / scripts /mask-data-file.js
VanyaJ's picture
Release BADA Terminal v2.1.0 (Enterprise Ontology, NVIDIA auto-ontology, Release Preflight)
d739b1b verified
Raw History Blame Contribute Delete
4.41 kB
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
// Command line arguments parsing
const args = {};
process.argv.slice(2).forEach((val, index, array) => {
if (val.startsWith('--')) {
const key = val.substring(2);
const nextVal = array[index + 1];
if (nextVal && !nextVal.startsWith('--')) {
args[key] = nextVal;
} else {
args[key] = true;
}
}
});
const filePath = args.file;
const columnName = args.col;
const mode = args.mode || 'mask'; // mask, hash, encrypt
const secretKey = args.key || 'default-secret-key';
const outputPath = args.out || (filePath ? filePath.replace('.csv', '_processed.csv') : null);
if (!filePath || !columnName) {
console.log(`
BADA ๋ฐ์ดํ„ฐ ํŒŒ์ผ ์ปฌ๋Ÿผ ๋งˆ์Šคํ‚น/์•”ํ˜ธํ™” ๋„๊ตฌ (CSV ์ „์šฉ)
Usage:
node mask-data-file.js --file <input_path> --col <column_name> --mode <mask|hash|encrypt> [--key <key>] [--out <output_path>]
Modes:
mask : ๊ธฐ๋ฐ€ ์ •๋ณด ์ค‘๊ฐ„ ๊ฐ’์„ ๋ณ„ํ‘œ(*)๋กœ ์น˜ํ™˜ (์˜ˆ: 010-1234-5678 -> 010-****-5678)
hash : SHA-256 ๋‹จ๋ฐฉํ–ฅ ํ•ด์‹œํ™”ํ•˜์—ฌ ์›๋ณธ ์œ ์‹ค ๋ฐ ๋งค์นญ์šฉ ์‹๋ณ„์ž๋กœ ๋ณ€ํ™˜
encrypt : AES-256-CBC ๋Œ€์นญํ‚ค ์•”ํ˜ธํ™”ํ•˜์—ฌ ๋ณต๊ตฌ ๊ฐ€๋Šฅํ•œ ํ—ฅ์‚ฌ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜
`);
process.exit(0);
}
if (!fs.existsSync(filePath)) {
console.error(`Error: File not found at ${filePath}`);
process.exit(1);
}
try {
const content = fs.readFileSync(filePath, 'utf-8');
const lines = content.split('\n').map(l => l.trim()).filter(Boolean);
if (lines.length === 0) {
console.error('Error: Empty CSV file.');
process.exit(1);
}
// Parse header
const headers = lines[0].split(',').map(h => h.trim());
const colIndex = headers.indexOf(columnName);
if (colIndex === -1) {
console.error(`Error: Column "${columnName}" not found in CSV headers: [${headers.join(', ')}]`);
process.exit(1);
}
console.log(`- File loaded: ${path.basename(filePath)} (${lines.length - 1} rows)`);
console.log(`- Target Column: "${columnName}" (index ${colIndex})`);
console.log(`- Mode: ${mode.toUpperCase()}`);
const processedLines = [lines[0]]; // start with header
for (let i = 1; i < lines.length; i++) {
const row = lines[i].split(',').map(cell => cell.trim());
// Safety check if row length matches headers
if (row.length < headers.length) {
processedLines.push(lines[i]);
continue;
}
const originalValue = row[colIndex];
let processedValue = originalValue;
if (mode === 'mask') {
processedValue = applyVisualMask(originalValue);
} else if (mode === 'hash') {
processedValue = crypto.createHash('sha256').update(originalValue).digest('hex').substring(0, 16); // limit length for readability
} else if (mode === 'encrypt') {
processedValue = encryptAES256(originalValue, secretKey);
}
row[colIndex] = processedValue;
processedLines.push(row.join(','));
}
fs.writeFileSync(outputPath, processedLines.join('\n'), 'utf-8');
console.log(`- Processed file saved to: ${outputPath}`);
console.log('=== Column Processing Completed Successfully ===');
} catch (err) {
console.error('Error processing CSV:', err.message);
process.exit(1);
}
// โ”€โ”€โ”€ Utility functions โ”€โ”€โ”€
function applyVisualMask(val) {
if (val.length <= 2) return '**';
// Phone number pattern check (010-1234-5678)
if (/^\d{2,3}-\d{3,4}-\d{4}$/.test(val)) {
const parts = val.split('-');
return `${parts[0]}-${'*'.repeat(parts[1].length)}-${parts[2]}`;
}
// Email address check
if (val.includes('@')) {
const parts = val.split('@');
const name = parts[0];
if (name.length <= 3) {
return `***@${parts[1]}`;
}
return `${name.substring(0, 2)}${'*'.repeat(name.length - 2)}@${parts[1]}`;
}
// Normal text mask (keep first 1-2 chars, mask rest)
const keep = Math.min(2, Math.floor(val.length / 3)) || 1;
return val.substring(0, keep) + '*'.repeat(val.length - keep);
}
function encryptAES256(val, key) {
try {
const keyHash = crypto.createHash('sha256').update(key).digest();
const iv = keyHash.slice(0, 16);
const cipher = crypto.createCipheriv('aes-256-cbc', keyHash, iv);
let encrypted = cipher.update(val, 'utf8', 'hex');
encrypted += cipher.final('hex');
return 'enc_' + encrypted; // prefix to distinguish
} catch (e) {
return '[ENCRYPTION_ERROR]';
}
}