Skip to content

Commit 838feb7

Browse files
committed
Enhance JSON sorting script, harden for path injection
1 parent f7e11c0 commit 838feb7

File tree

1 file changed

+22
-13
lines changed

1 file changed

+22
-13
lines changed

scripts/sort-json.js

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,28 @@
11
#!/usr/bin/env node
2-
const fs = require("fs");
2+
const fs = require('fs');
3+
const path = require('path');
34

4-
const file = process.argv[2];
5-
if (!file) {
6-
console.error("Usage: node sort-json.js <file.json>");
7-
process.exit(1);
5+
const input = process.argv[2];
6+
if (!input) {
7+
console.error('Usage: node sort-json.js <file.json>');
8+
process.exit(1);
89
}
910

10-
const data = JSON.parse(fs.readFileSync(file, "utf8"));
11+
const baseDir = process.cwd();
12+
const resolvedPath = path.resolve(baseDir, input);
1113

12-
const sorted = Object.keys(data)
13-
.sort((a, b) => a.localeCompare(b))
14-
.reduce((acc, key) => {
15-
acc[key] = data[key];
16-
return acc;
17-
}, {});
14+
if (!resolvedPath.startsWith(baseDir + path.sep) || path.extname(resolvedPath).toLowerCase() !== '.json') {
15+
console.error('Error: Invalid file path or file type.');
16+
process.exit(1);
17+
}
1818

19-
fs.writeFileSync(file, JSON.stringify(sorted, null, 2) + "\n");
19+
try {
20+
const data = JSON.parse(fs.readFileSync(resolvedPath, 'utf8'));
21+
const sorted = Object.fromEntries(
22+
Object.entries(data).sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
23+
);
24+
fs.writeFileSync(resolvedPath, JSON.stringify(sorted, null, 2) + '\n');
25+
} catch (err) {
26+
console.error('Error processing JSON file:', err.message);
27+
process.exit(1);
28+
}

0 commit comments

Comments
 (0)