generated from ExpTechTW/Example
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
246 lines (208 loc) · 6.81 KB
/
index.js
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
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const SIGNER_VERSION = '1.0.0';
const colors = {
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
reset: '\x1b[0m',
};
const args = process.argv.slice(2);
const command = args[0];
const EXCLUDED_FILES = [
'LICENSE',
'README.md',
'package-lock.json',
'package.json',
'signature.json',
];
const EXCLUDED_EXTENSIONS = ['.trem'];
function isExcluded(filename) {
return EXCLUDED_FILES.includes(filename)
|| EXCLUDED_EXTENSIONS.some((ext) => filename.endsWith(ext))
|| filename.startsWith('.');
}
function getAllFiles(dir, baseDir = dir) {
let results = {};
const list = fs.readdirSync(dir);
for (const file of list) {
if (isExcluded(file)) {
continue;
}
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
Object.assign(results, getAllFiles(filePath, baseDir));
}
else {
const relativePath = path.relative(baseDir, filePath).replace(/\\/g, '/');
const content = normalizeContent(fs.readFileSync(filePath, 'utf8'));
results[relativePath] = content;
}
}
return results;
}
function generateKeyPair(outputPath) {
try {
fs.mkdirSync(outputPath, { recursive: true });
}
catch (err) {
if (err.code !== 'EEXIST') {
throw err;
}
}
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
},
});
const privatePath = path.join(outputPath, 'private.pem');
const publicPath = path.join(outputPath, 'public.pem');
fs.writeFileSync(privatePath, privateKey);
fs.writeFileSync(publicPath, publicKey);
console.log(colors.green + `Keys generated successfully in ${outputPath}!` + colors.reset);
console.log(colors.blue + `Private key: ${privatePath}` + colors.reset);
console.log(colors.blue + `Public key: ${publicPath}` + colors.reset);
}
function normalizeContent(content) {
return content.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
}
function signPlugin(pluginPath, privateKeyPath, keyId) {
if (!fs.existsSync(pluginPath)) {
throw new Error(`Plugin directory not found: ${pluginPath}`);
}
const infoPath = path.join(pluginPath, 'info.json');
if (!fs.existsSync(infoPath)) {
throw new Error('Missing info.json');
}
const info = JSON.parse(fs.readFileSync(infoPath, 'utf8'));
const privateKey = !privateKeyPath ? crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
},
}).privateKey : fs.readFileSync(privateKeyPath, 'utf8');
const fileContents = getAllFiles(pluginPath);
if (Object.keys(fileContents).length === 0) {
throw new Error(`No files found in plugin directory: ${pluginPath}`);
}
const fileHashes = {};
Object.entries(fileContents).forEach(([file, content]) => {
const hash = crypto.createHash('sha256').update(content).digest('hex');
fileHashes[file] = hash;
});
const sign = crypto.createSign('SHA256');
sign.write(JSON.stringify(fileHashes));
sign.end();
const signature = sign.sign(privateKey, 'base64');
const signatureData = {
timestamp: Date.now(),
version: info.version,
fileHashes,
signature,
};
signatureData.keyId = keyId;
const signaturePath = path.join(pluginPath, 'signature.json');
fs.writeFileSync(
signaturePath,
JSON.stringify(signatureData, null, 2),
);
console.log(colors.green + 'Plugin signed successfully!' + colors.reset);
console.log(colors.blue + `Signature file created: ${signaturePath}` + colors.reset);
console.log(colors.yellow + `Plugin version: ${info.version}` + colors.reset);
console.log(colors.yellow + 'Files included in signature:' + colors.reset);
Object.keys(fileHashes).forEach((file) => console.log(colors.blue + ` ${file}` + colors.reset));
}
function verifyPlugin(pluginPath, publicKeyPath) {
if (!fs.existsSync(pluginPath)) {
throw new Error(`Plugin directory not found: ${pluginPath}`);
}
if (!fs.existsSync(publicKeyPath)) {
throw new Error(`Public key not found: ${publicKeyPath}`);
}
const publicKey = fs.readFileSync(publicKeyPath, 'utf8');
const signaturePath = path.join(pluginPath, 'signature.json');
if (!fs.existsSync(signaturePath)) {
throw new Error('Missing signature.json');
}
const signatureData = JSON.parse(fs.readFileSync(signaturePath));
const { fileHashes, signature, timestamp, version } = signatureData;
for (const [file, expectedHash] of Object.entries(fileHashes)) {
const filePath = path.join(pluginPath, file);
if (!fs.existsSync(filePath)) {
throw new Error(`Missing file: ${file}`);
}
const content = normalizeContent(fs.readFileSync(filePath, 'utf8'));
const actualHash = crypto.createHash('sha256')
.update(content)
.digest('hex');
if (actualHash !== expectedHash) {
throw new Error(`File modified: ${file}`);
}
}
const verify = crypto.createVerify('SHA256');
verify.write(JSON.stringify(fileHashes));
verify.end();
const isValid = verify.verify(publicKey, signature, 'base64');
if (!isValid) {
throw new Error('Invalid signature');
}
console.log(colors.green + 'Plugin verification successful!' + colors.reset);
console.log(colors.yellow + `Plugin version: ${version}` + colors.reset);
console.log(colors.blue + `Signature timestamp: ${new Date(timestamp).toLocaleString()}` + colors.reset);
}
function showHelp() {
console.log(colors.blue + `
TREM Plugin Signer v${SIGNER_VERSION}
Usage:
generate <output-path> - Generate new key pair
sign <plugin-path> <private-key> <public-key-name> - Sign a plugin
verify <plugin-path> <public-key> - Verify a plugin signature
help - Show this help
`);
}
try {
switch (command) {
case 'generate':
generateKeyPair(args[1] || '.');
break;
case 'sign':
if (args.length < 2) {
console.error(colors.red + 'Missing plugin path or private key path' + colors.reset);
showHelp();
process.exit(1);
}
signPlugin(args[1], args[2] || null, args[3] || 'official');
break;
case 'verify':
if (args.length < 3) {
console.error(colors.red + 'Missing plugin path or public key path' + colors.reset);
showHelp();
process.exit(1);
}
verifyPlugin(args[1], args[2]);
break;
case 'help':
default:
showHelp();
break;
}
}
catch (error) {
console.error(colors.red + 'Error:', error.message + colors.reset);
process.exit(1);
}