-
-
Notifications
You must be signed in to change notification settings - Fork 491
Expand file tree
/
Copy pathhelpers.js
More file actions
510 lines (461 loc) · 16.4 KB
/
helpers.js
File metadata and controls
510 lines (461 loc) · 16.4 KB
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
const pathModule = require("path");
const fs = require("fs");
const readline = require("readline");
const { generateRandomSaltString, generateRandomString } = require("../lib/cryptoEngine.js");
const { renderTemplate } = require("../lib/formater.js");
const Yargs = require("yargs");
const PASSWORD_TEMPLATE_DEFAULT_PATH = pathModule.join(__dirname, "..", "lib", "password_template.html");
const OUTPUT_DIRECTORY_DEFAULT_PATH = "encrypted";
exports.OUTPUT_DIRECTORY_DEFAULT_PATH = OUTPUT_DIRECTORY_DEFAULT_PATH;
/**
* @param {string} message
*/
function exitWithError(message) {
console.log("ERROR: " + message);
process.exit(1);
}
exports.exitWithError = exitWithError;
/**
* Check if a particular option has been set by the user. Useful for distinguishing default value with flag without
* parameter.
*
* Ex use case: '-s' means "give me a salt", '-s 1234' means "use 1234 as salt"
*
* From https://github.com/yargs/yargs/issues/513#issuecomment-221412008
*
* @param {string} option
* @param yargs
* @returns {boolean}
*/
function isOptionSetByUser(option, yargs) {
function searchForOption(option) {
return process.argv.indexOf(option) > -1;
}
if (searchForOption(`-${option}`) || searchForOption(`--${option}`)) {
return true;
}
// Handle aliases for same option
for (let aliasIndex in yargs.parsed.aliases[option]) {
const alias = yargs.parsed.aliases[option][aliasIndex];
if (searchForOption(`-${alias}`) || searchForOption(`--${alias}`)) {
return true;
}
}
return false;
}
exports.isOptionSetByUser = isOptionSetByUser;
/**
* Prompts the user for input on the CLI.
*
* @param {string} question
* @returns {Promise<string>}
*/
function prompt(question) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
return rl.question(question, (answer) => {
rl.close();
return resolve(answer);
});
});
}
/**
* @param {string} passwordString
* @param {boolean} isShortAllowed
* @returns {Promise<void>}
*/
async function validatePasswordString(passwordString, isShortAllowed) {
if (passwordString.length < 14 && !isShortAllowed) {
const shouldUseShort = await prompt(
`WARNING: Your password is less than 14 characters (length: ${passwordString.length})` +
" and it's easy to try brute-forcing on public files, so we recommend using a longer one. Here's a generated one: " +
generateRandomString(21) +
"\nYou can hide this warning by increasing your password length or adding the '--short' flag." +
"\nDo you want to still want to use the shorter password? [y/N] "
);
if (!shouldUseShort.match(/^\s*(y|yes)\s*$/i)) {
console.log("Aborting.");
process.exit(0);
}
}
}
exports.validatePasswordString = validatePasswordString;
/**
* Get the config from the config file.
*
* @param {string|null} configPath
* @returns {{}|object}
*/
function getConfig(configPath) {
if (configPath && fs.existsSync(configPath)) {
return JSON.parse(fs.readFileSync(configPath, "utf8"));
}
return {};
}
exports.getConfig = getConfig;
function writeConfig(configPath, config) {
if (configPath) {
fs.writeFileSync(configPath, JSON.stringify(config, null, 4));
}
}
exports.writeConfig = writeConfig;
/**
* Get the password from the command arguments or environment variables.
*
* @param {string} passwordArgument - password from the command line
* @returns {Promise<string>}
*/
async function getPasswordString(passwordArgument) {
// try to get the password from the environment variable
const envPassword = process.env.STATICRYPT_PASSWORD;
const hasEnvPassword = envPassword !== undefined && envPassword !== "";
if (hasEnvPassword) {
return envPassword;
}
// try to get the password from the command line arguments
if (passwordArgument !== null) {
return passwordArgument;
}
// prompt the user for their password
return prompt("Enter your long, unusual password: ");
}
exports.getPasswordString = getPasswordString;
/**
* @param {string} filepath
* @returns {string}
*/
function getFileContent(filepath) {
try {
return fs.readFileSync(filepath, "utf8");
} catch (e) {
exitWithError(`input file '${filepath}' does not exist!`);
}
}
exports.getFileContent = getFileContent;
/**
* @param {string} filepath
* @returns {Uint8Array}
*/
function getFileContentBytes(filepath) {
try {
return new Uint8Array(fs.readFileSync(filepath));
} catch (e) {
exitWithError(`input file '${filepath}' does not exist!`);
}
}
exports.getFileContentBytes = getFileContentBytes;
/**
* @param {object} namedArgs
* @param {object} config
* @returns {string}
*/
function getValidatedSaltString(namedArgs, config) {
const salt = getSaltString(namedArgs, config);
// validate the salt
if (salt.length !== 32 || /[^a-f0-9]/.test(salt)) {
exitWithError(
"the salt should be a 32 character long hexadecimal string (only [0-9a-f] characters allowed)" +
"\nDetected salt: " +
salt
);
}
return salt;
}
exports.getValidatedSaltString = getValidatedSaltString;
/**
* @param {object} namedArgs
* @param {object} config
* @returns {string}
*/
function getSaltString(namedArgs, config) {
// either a salt was provided by the user through the flag --salt
if (namedArgs.salt) {
return String(namedArgs.salt).toLowerCase();
}
// or try to read the salt from config file
if (config.salt) {
return config.salt;
}
return generateRandomSaltString();
}
/**
* A dead-simple alternative to webpack or rollup for inlining simple
* CommonJS modules in a browser <script>.
* - Removes all lines containing require().
* - Wraps the module in an immediately invoked function that returns `exports`.
*
* @param {string} modulePath - path from staticrypt root directory
*/
function convertCommonJSToBrowserJS(modulePath) {
const rootDirectory = pathModule.join(__dirname, "..");
const resolvedPath = pathModule.join(rootDirectory, ...modulePath.split("/")) + ".js";
if (!fs.existsSync(resolvedPath)) {
exitWithError(`could not find module to convert at path "${resolvedPath}"`);
}
const moduleText = fs.readFileSync(resolvedPath, "utf8").replace(/^.*\brequire\(.*$\n/gm, "");
return `
((function(){
const exports = {};
${moduleText}
return exports;
})())
`.trim();
}
exports.convertCommonJSToBrowserJS = convertCommonJSToBrowserJS;
/**
* Build the staticrypt script string to inject in our template.
*
* @returns {string}
*/
function buildStaticryptJS() {
let staticryptJS = convertCommonJSToBrowserJS("lib/staticryptJs");
const scriptsToInject = {
js_codec: convertCommonJSToBrowserJS("lib/codec"),
js_crypto_engine: convertCommonJSToBrowserJS("lib/cryptoEngine"),
};
return renderTemplate(staticryptJS, scriptsToInject);
}
exports.buildStaticryptJS = buildStaticryptJS;
/**
* @param {string} filePath
* @param {string} errorName
* @returns {string}
*/
function readFile(filePath, errorName = "file") {
try {
return fs.readFileSync(filePath, "utf8");
} catch (e) {
console.error(e);
exitWithError(`could not read ${errorName} at path "${filePath}"`);
}
}
/**
* Fill the template with provided data and writes it to output file.
*
* @param {Object} data
* @param {string} outputFilePath
* @param {string} templateFilePath
*/
function genFile(data, outputFilePath, templateFilePath) {
const templateContents = readFile(templateFilePath, "template");
const renderedTemplate = renderTemplate(templateContents, data);
writeFile(outputFilePath, renderedTemplate);
}
exports.genFile = genFile;
/**
* @param {string} path
* @param {string} fullRootDirectory
* @param {string} outputDirectory
* @returns {string}
*/
function getFullOutputPath(path, fullRootDirectory, outputDirectory) {
const relativePath = pathModule.relative(fullRootDirectory, path);
return outputDirectory + "/" + relativePath;
}
exports.getFullOutputPath = getFullOutputPath;
/**
* @param {string} inputFilePath
* @param {string} outputFilePath
*/
function copyFile(inputFilePath, outputFilePath) {
// create output directory if it does not exist
createDirectoryStructureForFile(outputFilePath);
try {
fs.copyFileSync(inputFilePath, outputFilePath, fs.constants.COPYFILE_FICLONE);
} catch (e) {
console.error(e);
exitWithError(`could not write file at path "${filePath}"`);
}
}
/**
* @param {string} filePath
* @param {string} contents
*/
function writeFile(filePath, contents) {
// create output directory if it does not exist
createDirectoryStructureForFile(filePath);
try {
fs.writeFileSync(filePath, contents);
} catch (e) {
console.error(e);
exitWithError(`could not write file at path "${filePath}"`);
}
}
exports.writeFile = writeFile;
/**
* @param {string} filePath
*/
function createDirectoryStructureForFile(filePath) {
const dirname = pathModule.dirname(filePath);
if (!fs.existsSync(dirname)) {
fs.mkdirSync(dirname, { recursive: true });
}
}
/**
* @param {string} templatePathParameter
* @returns {boolean}
*/
function isCustomPasswordTemplateDefault(templatePathParameter) {
// if the user uses the default template, it's up to date
return templatePathParameter === PASSWORD_TEMPLATE_DEFAULT_PATH;
}
exports.isCustomPasswordTemplateDefault = isCustomPasswordTemplateDefault;
/**
* @param {string} path
* @param {string} outputDirectory
* @param {string} rootDirectory
* @param {(fullPath: string, rootDirectoryFromArgument: string) => void} callback
*/
function recursivelyApplyCallbackToHtmlFiles(callback, path, outputDirectory, rootDirectory = "") {
const fullPath = pathModule.resolve(path);
const fullRootDirectory = rootDirectory || pathModule.dirname(fullPath);
if (fs.statSync(fullPath).isDirectory()) {
fs.readdirSync(fullPath).forEach((filePath) => {
const fullFilePath = `${fullPath}/${filePath}`;
recursivelyApplyCallbackToHtmlFiles(callback, fullFilePath, outputDirectory, fullRootDirectory);
});
return;
}
// apply the callback if it's an HTML file
if (fullPath.endsWith(".html") || fullPath.endsWith(".htm")) {
callback(fullPath, fullRootDirectory);
}
// else just copy the file as is
else {
const fullOutputPath = getFullOutputPath(fullPath, fullRootDirectory, outputDirectory);
copyFile(fullPath, fullOutputPath);
}
}
exports.recursivelyApplyCallbackToHtmlFiles = recursivelyApplyCallbackToHtmlFiles;
function parseCommandLineArguments() {
return (
Yargs.usage("Usage: staticrypt <filename> [<filename> ...] [options]")
.option("c", {
alias: "config",
type: "string",
describe: 'Path to the config file. Set to "false" to disable.',
default: ".staticrypt.json",
})
.option("d", {
alias: "directory",
type: "string",
describe:
"Name of the directory where the generated files will be saved. If the '--decrypt' flag is " +
"set, default will be 'decrypted'.",
default: OUTPUT_DIRECTORY_DEFAULT_PATH,
})
.option("decrypt", {
type: "boolean",
describe: "Include this flag to decrypt files instead of encrypt.",
default: false,
})
.option("p", {
alias: "password",
type: "string",
describe:
"The password to encrypt your file with. Leave empty to be prompted for it. If STATICRYPT_PASSWORD" +
" is set in the env, we'll use that instead.",
default: null,
})
.option("r", {
alias: "recursive",
type: "boolean",
describe: "Whether to recursively encrypt the input directory.",
default: false,
})
.option("remember", {
describe:
'Integer: expiration in days of the "Remember me" checkbox that will save the (salted + hashed) password ' +
'in localStorage when entered by the user. Set to "false" to hide the box. Default: "0", no expiration.',
default: 0,
})
// do not give a default option to this parameter - we want to see when the flag is included with no
// value and when it's not included at all
.option("s", {
alias: "salt",
describe:
"Generate a config file or set the salt manually. Pass a 32-character-long hexadecimal string " +
"to use as salt, or leave empty to generate, display and save to config a random salt. This won't" +
" overwrite an existing config file.",
type: "string",
})
// do not give a default option to this parameter - we want to see when the flag is included with no
// value and when it's not included at all
.option("share", {
describe:
"Get a link containing your hashed password that will auto-decrypt the page. Pass your URL as a value to append " +
'"#staticrypt_pwd=<hashed_pwd>", or leave empty to display the hash to append.',
type: "string",
})
.option("share-remember", {
type: "boolean",
describe: "Whether the share link should auto-enable 'Remember-me'.",
default: false,
})
.option("short", {
describe: 'Hide the "short password" warning.',
type: "boolean",
default: false,
})
.option("t", {
alias: "template",
type: "string",
describe: "Path to custom HTML template with password prompt.",
default: PASSWORD_TEMPLATE_DEFAULT_PATH,
})
.option("template-button", {
type: "string",
describe: 'Label to use for the decrypt button. Default: "DECRYPT".',
default: "DECRYPT",
})
.option("template-color-primary", {
type: "string",
describe: "Primary color (button...)",
default: "#4CAF50",
})
.option("template-color-secondary", {
type: "string",
describe: "Secondary color (page background...)",
default: "#76B852",
})
.option("template-instructions", {
type: "string",
describe: "Special instructions to display to the user.",
default: "",
})
.option("template-error", {
type: "string",
describe: "Error message to display on entering wrong password.",
default: "Bad password!",
})
.option("template-placeholder", {
type: "string",
describe: "Placeholder to use for the password input.",
default: "Password",
})
.option("template-remember", {
type: "string",
describe: 'Label to use for the "Remember me" checkbox.',
default: "Remember me",
})
.option("template-title", {
type: "string",
describe: "Title for the output HTML page.",
default: "Protected Page",
})
.option("template-toggle-hide", {
type: "string",
describe: 'Alt text for toggling password visibility - "hide" action.',
default: "Hide password",
})
.option("template-toggle-show", {
type: "string",
describe: 'Alt text for toggling password visibility - "show" action.',
default: "Show password",
})
);
}
exports.parseCommandLineArguments = parseCommandLineArguments;