-
-
Notifications
You must be signed in to change notification settings - Fork 491
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·247 lines (200 loc) · 8.41 KB
/
index.js
File metadata and controls
executable file
·247 lines (200 loc) · 8.41 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
#!/usr/bin/env node
"use strict";
// check node version before anything else
const nodeVersion = process.versions.node.split(".");
if (nodeVersion[0] < 16) {
console.log("ERROR: Node version 16 or higher is required.");
process.exit(1);
}
// parse .env file into process.env
require("dotenv").config();
const pathModule = require("path");
const fs = require("fs");
const cryptoEngine = require("../lib/cryptoEngine.js");
const codec = require("../lib/codec.js");
const { generateRandomSaltString } = cryptoEngine;
const { decode, encodeWithHashedPassword } = codec.init(cryptoEngine);
const {
OUTPUT_DIRECTORY_DEFAULT_PATH,
buildStaticryptJS,
exitWithError,
genFile,
getConfig,
getFileContent,
getFileContentBytes,
getPasswordString,
getValidatedSaltString,
isOptionSetByUser,
parseCommandLineArguments,
recursivelyApplyCallbackToHtmlFiles,
validatePasswordString,
writeConfig,
writeFile,
getFullOutputPath,
} = require("./helpers.js");
// parse arguments
const yargs = parseCommandLineArguments();
const namedArgs = yargs.argv;
async function runStatiCrypt() {
const hasSaltFlag = isOptionSetByUser("s", yargs);
const hasShareFlag = isOptionSetByUser("share", yargs);
const positionalArguments = namedArgs._;
// require at least one positional argument unless some specific flags are passed
if (!hasShareFlag && !(hasSaltFlag && !namedArgs.salt)) {
if (positionalArguments.length === 0) {
console.log("ERROR: Invalid number of arguments. Please provide an input file.\n");
yargs.showHelp();
process.exit(1);
}
}
// get config file
const configPath = namedArgs.config.toLowerCase() === "false" ? null : "./" + namedArgs.config;
const config = getConfig(configPath);
// if the 's' flag is passed without parameter, generate a salt, display & exit
if (hasSaltFlag && !namedArgs.salt) {
const generatedSaltString = generateRandomSaltString();
// show salt
console.log(generatedSaltstring);
// write to config file if it doesn't exist
if (!config.salt) {
config.salt = generatedSaltstring;
writeConfig(configPath, config);
}
return;
}
// get the salt & password
const saltString = getValidatedSaltString(namedArgs, config);
const salt = cryptoEngine.HexEncoder.parse(saltString);
const passwordString = await getPasswordString(namedArgs.password);
const password = cryptoEngine.UTF8Encoder.parse(passwordString);
const hashedPassword = await cryptoEngine.hashPassword(password, salt);
const hashedPasswordString = cryptoEngine.HexEncoder.stringify(hashedPassword);
// display the share link with the hashed password if the --share flag is set
if (hasShareFlag) {
await validatePasswordString(passwordString, namedArgs.short);
let url = namedArgs.share || "";
url += "#staticrypt_pwd=" + hashedPasswordString;
if (namedArgs.shareRemember) {
url += `&remember_me`;
}
console.log(url);
return;
}
// only process a directory if the --recursive flag is set
const directoriesInArguments = positionalArguments.filter((path) => fs.statSync(path).isDirectory());
if (directoriesInArguments.length > 0 && !namedArgs.recursive) {
exitWithError(
`'${directoriesInArguments[0].toString()}' is a directory. Use the -r|--recursive flag to process directories.`
);
}
// if asking for decryption, decrypt all the files
if (namedArgs.decrypt) {
const isOutputDirectoryDefault =
namedArgs.directory === OUTPUT_DIRECTORY_DEFAULT_PATH && !isOptionSetByUser("d", yargs);
const outputDirectory = isOutputDirectoryDefault ? "decrypted" : namedArgs.directory;
positionalArguments.forEach((path) => {
recursivelyApplyCallbackToHtmlFiles(
(fullPath, fullRootDirectory) => {
decodeAndGenerateFile(fullPath, fullRootDirectory, hashedPassword, outputDirectory);
},
path,
namedArgs.directory
);
});
return;
}
await validatePasswordString(passwordString, namedArgs.short);
// write salt to config file
if (config.salt !== saltString) {
config.salt = saltString;
writeConfig(configPath, config);
}
const isRememberEnabled = namedArgs.remember !== "false";
const baseTemplateData = {
is_remember_enabled: JSON.stringify(isRememberEnabled),
js_staticrypt: buildStaticryptJS(),
template_button: namedArgs.templateButton,
template_color_primary: namedArgs.templateColorPrimary,
template_color_secondary: namedArgs.templateColorSecondary,
template_error: namedArgs.templateError,
template_instructions: namedArgs.templateInstructions,
template_placeholder: namedArgs.templatePlaceholder,
template_remember: namedArgs.templateRemember,
template_title: namedArgs.templateTitle,
template_toggle_show: namedArgs.templateToggleShow,
template_toggle_hide: namedArgs.templateToggleHide,
};
// encode all the files
positionalArguments.forEach((path) => {
recursivelyApplyCallbackToHtmlFiles(
(fullPath, fullRootDirectory) => {
encodeAndGenerateFile(
fullPath,
fullRootDirectory,
hashedPassword,
saltString,
baseTemplateData,
isRememberEnabled,
namedArgs
);
},
path,
namedArgs.directory
);
});
}
async function decodeAndGenerateFile(path, fullRootDirectory, hashedPassword, outputDirectory) {
// get the file content
const encryptedFileContent = getFileContent(path);
// extract the cipher text from the encrypted file
let encryptedMatch = encryptedFileContent.match(/"staticryptEncryptedUniqueVariableName":\s*"([^"]+)"/);
const ivMatch = encryptedFileContent.match(/"staticryptIvUniqueVariableName":\s*"([^"]+)"/);
const hmacMatch = encryptedFileContent.match(/"staticryptHmacUniqueVariableName":\s*"([^"]+)"/);
const saltMatch = encryptedFileContent.match(/"staticryptSaltUniqueVariableName":\s*"([^"]+)"/);
if (!encryptedMatch || !ivMatch || !hmacMatch || !saltMatch) {
return console.log(`ERROR: could not extract cipher text, iv, hmac, or salt from ${path}`);
}
const encrypted = cryptoEngine.HexEncoder.parse(encryptedMatch[1]);
encryptedMatch = null;
const iv = cryptoEngine.HexEncoder.parse(ivMatch[1]);
const hmac = cryptoEngine.HexEncoder.parse(hmacMatch[1]);
const salt = cryptoEngine.HexEncoder.parse(saltMatch[1]);
// decrypt input
const { success, decoded } = await decode(iv, encrypted, hmac, hashedPassword, salt);
if (!success) {
return console.log(`ERROR: could not decrypt ${path}`);
}
const outputFilepath = getFullOutputPath(path, fullRootDirectory, outputDirectory);
writeFile(outputFilepath, decoded);
}
async function encodeAndGenerateFile(
path,
rootDirectoryFromArguments,
hashedPassword,
saltString,
baseTemplateData,
isRememberEnabled,
namedArgs
) {
// encrypt input
const encryptedMsg = await encodeWithHashedPassword(getFileContentBytes(path), hashedPassword);
let rememberDurationInDays = parseInt(namedArgs.remember);
rememberDurationInDays = isNaN(rememberDurationInDays) ? 0 : rememberDurationInDays;
const staticryptConfig = {
staticryptIvUniqueVariableName: cryptoEngine.HexEncoder.stringify(encryptedMsg.iv),
staticryptEncryptedUniqueVariableName: cryptoEngine.HexEncoder.stringify(encryptedMsg.encrypted),
staticryptHmacUniqueVariableName: cryptoEngine.HexEncoder.stringify(encryptedMsg.hmac),
isRememberEnabled,
rememberDurationInDays,
staticryptSaltUniqueVariableName: saltString,
};
const templateData = {
...baseTemplateData,
staticrypt_config: staticryptConfig,
};
// remove the base path so that the actual output path is relative to the base path
const relativePath = pathModule.relative(rootDirectoryFromArguments, path);
const outputFilepath = namedArgs.directory + "/" + relativePath;
genFile(templateData, outputFilepath, namedArgs.template);
}
runStatiCrypt();