secrez 2.1.16 → 2.2.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,8 @@ const { authenticator } = require("otplib");
2
2
  const path = require("path");
3
3
  const os = require("os");
4
4
  const fs = require("fs-extra");
5
- const { execSync } = require("child_process");
5
+ const childProcess = require("child_process");
6
+ const { execSync } = childProcess;
6
7
  const {
7
8
  isYaml,
8
9
  yamlParse,
@@ -11,8 +12,8 @@ const {
11
12
  TRUE,
12
13
  } = require("@secrez/utils");
13
14
  const { Node } = require("@secrez/fs");
14
- const QrCode = require("qrcode-reader");
15
- const Jimp = require("jimp");
15
+ const { Jimp } = require("jimp");
16
+ const jsQR = require("jsqr");
16
17
 
17
18
  class Totp extends require("../Command") {
18
19
  setHelpAndCompletion() {
@@ -128,6 +129,31 @@ class Totp extends require("../Command") {
128
129
  }
129
130
  }
130
131
 
132
+ async writeClipboardPngToFile(outputPath) {
133
+ return new Promise((resolve, reject) => {
134
+ const child = childProcess.spawn("xclip", [
135
+ "-selection",
136
+ "clipboard",
137
+ "-t",
138
+ "image/png",
139
+ "-o",
140
+ ]);
141
+ const chunks = [];
142
+ child.stdout.on("data", (data) => chunks.push(data));
143
+ child.on("error", (error) => {
144
+ reject(new Error(error.message));
145
+ });
146
+ child.on("close", async (code) => {
147
+ if (code !== 0) {
148
+ reject(new Error("Wrong content in the clipboard"));
149
+ return;
150
+ }
151
+ await fs.writeFile(outputPath, Buffer.concat(chunks));
152
+ resolve();
153
+ });
154
+ });
155
+ }
156
+
131
157
  async readFromClipboard(options) {
132
158
  /* istanbul ignore if */
133
159
  if (TRUE()) {
@@ -145,13 +171,7 @@ class Totp extends require("../Command") {
145
171
  }
146
172
  break;
147
173
  default:
148
- try {
149
- result = execSync(
150
- `xclip -selection clipboard -t image/png -o > ${p}`
151
- ).toString();
152
- } catch (e) {
153
- throw new Error("Wrong content in the clipboard");
154
- }
174
+ await this.writeClipboardPngToFile(p);
155
175
  }
156
176
  return p;
157
177
  }
@@ -160,26 +180,13 @@ class Totp extends require("../Command") {
160
180
  async readFromImage(options) {
161
181
  let p = this.externalFs.getNormalizedPath(options.fromImage);
162
182
  const buffer = await fs.readFile(p);
163
- return new Promise((resolve, reject) => {
164
- Jimp.read(buffer, (err, image) => {
165
- if (err) {
166
- reject(err.message);
167
- }
168
- const qr = new QrCode();
169
- qr.callback = (err, value) => {
170
- /* istanbul ignore if */
171
- if (err) {
172
- reject(err.message);
173
- }
174
- resolve(value.result);
175
- };
176
- try {
177
- qr.decode(image.bitmap);
178
- } catch (e) {
179
- reject(e.message);
180
- }
181
- });
182
- });
183
+ const image = await Jimp.read(buffer);
184
+ const { data, width, height } = image.bitmap;
185
+ const code = jsQR(new Uint8ClampedArray(data), width, height);
186
+ if (!code) {
187
+ throw new Error("No QR code found in the image");
188
+ }
189
+ return code.data;
183
190
  }
184
191
 
185
192
  async totp(options = {}) {
@@ -0,0 +1,303 @@
1
+ "use strict";
2
+
3
+ /* istanbul ignore file -- interactive TUI editor; tests use prompt.editorProvider */
4
+
5
+ // In-memory terminal editor vendored from tiny-cli-editor (ISC) and prompt-skeleton.
6
+ // https://github.com/derhuerst/tiny-cli-editor
7
+
8
+ const { PassThrough } = require("stream");
9
+ const { EventEmitter } = require("events");
10
+ const esc = require("ansi-escapes");
11
+ const onKeypress = require("./onKeypress");
12
+
13
+ const insert = (s, x, c) => s.slice(0, x) + c + s.slice(x);
14
+
15
+ const EDITOR_STATUS =
16
+ "Ctrl-d save · Ctrl-c abort · Ctrl-k del line · Ctrl-a home · Ctrl-e end · Ctrl-g reset";
17
+
18
+ function terminalRows() {
19
+ return process.stdout.rows || 24;
20
+ }
21
+
22
+ function keyAction(key) {
23
+ if (key.ctrl) {
24
+ if (key.name === "a") return "first";
25
+ if (key.name === "c") return "abort";
26
+ if (key.name === "d") return "abort";
27
+ if (key.name === "e") return "last";
28
+ if (key.name === "g") return "reset";
29
+ if (key.name === "k") return "deleteLine";
30
+ }
31
+ if (key.name === "return" || key.name === "enter") return "submit";
32
+ if (key.name === "backspace") return "delete";
33
+ if (key.name === "abort" || key.name === "escape") return "abort";
34
+ if (key.name === "up") return "up";
35
+ if (key.name === "down") return "down";
36
+ if (key.name === "right") return "right";
37
+ if (key.name === "left") return "left";
38
+ return false;
39
+ }
40
+
41
+ const Editor = {
42
+ update() {
43
+ this.value = this.lines.join("\n");
44
+ this.emit();
45
+ },
46
+
47
+ reset() {
48
+ this.lines = this.initialLines;
49
+ this.cursorX = 0;
50
+ this.cursorY = 0;
51
+ this.update();
52
+ this.render();
53
+ },
54
+
55
+ abort(c) {
56
+ this.done = true;
57
+ this.aborted = !(c.ctrl && c.name === "d");
58
+ this.out.write(esc.clearScreen + esc.cursorTo(0, 0));
59
+ this.close();
60
+ },
61
+
62
+ submit() {
63
+ const line = this.lines[this.cursorY];
64
+ this.lines.splice(
65
+ this.cursorY,
66
+ 1,
67
+ line.slice(0, this.cursorX),
68
+ line.slice(this.cursorX)
69
+ );
70
+ this.cursorY++;
71
+ this.cursorX = 0;
72
+ this.update();
73
+ this.render();
74
+ },
75
+
76
+ up() {
77
+ if (this.cursorY === 0) return;
78
+ this.cursorY--;
79
+ this.cursorX = Math.min(this.cursorX, this.lines[this.cursorY].length);
80
+ this.update();
81
+ this.render();
82
+ },
83
+
84
+ down() {
85
+ if (this.cursorY === this.lines.length - 1) return;
86
+ this.cursorY++;
87
+ this.cursorX = Math.min(this.cursorX, this.lines[this.cursorY].length);
88
+ this.update();
89
+ this.render();
90
+ },
91
+
92
+ left() {
93
+ if (this.cursorX === 0) {
94
+ if (this.cursorY === 0) return;
95
+ this.cursorY--;
96
+ this.cursorX = this.lines[this.cursorY].length;
97
+ return;
98
+ }
99
+ this.cursorX--;
100
+ this.update();
101
+ this.render();
102
+ },
103
+
104
+ right() {
105
+ const line = this.lines[this.cursorY];
106
+ if (this.cursorX === line.length) {
107
+ if (this.cursorY === this.lines.length - 1) return;
108
+ this.cursorY++;
109
+ this.cursorX = 0;
110
+ return;
111
+ }
112
+ this.cursorX++;
113
+ this.update();
114
+ this.render();
115
+ },
116
+
117
+ first() {
118
+ this.cursorX = 0;
119
+ this.update();
120
+ this.render();
121
+ },
122
+
123
+ last() {
124
+ this.cursorX = this.lines[this.cursorY].length;
125
+ this.update();
126
+ this.render();
127
+ },
128
+
129
+ _(c) {
130
+ const { lines, cursorX, cursorY } = this;
131
+ lines[cursorY] = insert(lines[cursorY], cursorX, c);
132
+ this.cursorX++;
133
+ this.update();
134
+ this.render();
135
+ },
136
+
137
+ delete() {
138
+ const { lines, cursorX, cursorY } = this;
139
+ const line = lines[cursorY];
140
+
141
+ if (cursorX > 0) {
142
+ lines[cursorY] = line.slice(0, cursorX - 1) + line.slice(cursorX);
143
+ this.cursorX--;
144
+ } else if (cursorY > 0) {
145
+ const xFromAbove = this.lines[cursorY - 1].length;
146
+ lines.splice(cursorY - 1, 2, lines[cursorY - 1] + lines[cursorY]);
147
+ this.cursorY--;
148
+ this.cursorX = xFromAbove;
149
+ } else {
150
+ return;
151
+ }
152
+
153
+ this.update();
154
+ this.render();
155
+ },
156
+
157
+ deleteLine() {
158
+ const { lines, cursorY } = this;
159
+ if (lines.length === 1) {
160
+ lines[0] = "";
161
+ this.cursorX = 0;
162
+ this.cursorY = 0;
163
+ } else {
164
+ lines.splice(cursorY, 1);
165
+ if (cursorY >= lines.length) {
166
+ this.cursorY = lines.length - 1;
167
+ }
168
+ this.cursorX = 0;
169
+ }
170
+ this.update();
171
+ this.render();
172
+ },
173
+
174
+ bell() {
175
+ this.out.write(esc.beep);
176
+ },
177
+
178
+ render() {
179
+ if (this.firstRender) {
180
+ this.firstRender = false;
181
+ this.out.write("\n".repeat(terminalRows()));
182
+ }
183
+
184
+ const rows = terminalRows();
185
+ const statusRow = Math.max(0, rows - 1);
186
+ const { lines, cursorX, cursorY } = this;
187
+ this.out.write(
188
+ esc.clearScreen +
189
+ lines.join("\n") +
190
+ esc.cursorTo(0, statusRow) +
191
+ "\x1b[2m" +
192
+ EDITOR_STATUS +
193
+ "\x1b[0m" +
194
+ esc.cursorTo(cursorX, cursorY)
195
+ );
196
+ },
197
+ };
198
+
199
+ function createEditor(text) {
200
+ if (typeof text !== "string") {
201
+ throw new Error("Text must be string.");
202
+ }
203
+
204
+ const emitter = new EventEmitter();
205
+ const p = Object.assign(Object.create(Editor), {
206
+ lines: [],
207
+ initialLines: [],
208
+ cursorX: 0,
209
+ cursorY: 0,
210
+ firstRender: true,
211
+ done: false,
212
+ aborted: false,
213
+ value: "",
214
+ out: new PassThrough(),
215
+ });
216
+
217
+ const lb = /\r?\n/;
218
+ p.initialLines = text.split(lb);
219
+ p.lines = text.split(lb);
220
+ p.out.pipe(process.stdout);
221
+
222
+ p.emit = () => {
223
+ emitter.emit("change", {
224
+ value: p.value,
225
+ aborted: !!p.aborted,
226
+ });
227
+ };
228
+
229
+ if (typeof p._ !== "function") {
230
+ p._ = () => p.bell();
231
+ }
232
+
233
+ let offKeypress;
234
+ const pause = () => {
235
+ if (!offKeypress) return;
236
+ offKeypress();
237
+ offKeypress = null;
238
+ };
239
+
240
+ const resume = () => {
241
+ if (offKeypress) return;
242
+ offKeypress = onKeypress(process.stdin, (key) => {
243
+ const action = keyAction(key);
244
+ if (action === false) {
245
+ p._(key.raw);
246
+ } else if (action in p) {
247
+ p[action](key);
248
+ } else {
249
+ p.bell();
250
+ }
251
+ });
252
+ };
253
+
254
+ let isClosed = false;
255
+ p.close = () => {
256
+ if (isClosed) return;
257
+ isClosed = true;
258
+ pause();
259
+ p.out.unpipe(process.stdout);
260
+ process.stdout.write(esc.cursorShow);
261
+ if (p.aborted) {
262
+ emitter.emit("abort", p.value);
263
+ } else {
264
+ emitter.emit("submit", p.value);
265
+ }
266
+ emitter.emit("close");
267
+ };
268
+
269
+ resume();
270
+ p.update();
271
+ p.render();
272
+
273
+ emitter.pause = pause;
274
+ emitter.resume = resume;
275
+ emitter.setText = (nextText) => {
276
+ p.lines = nextText.split(lb);
277
+ if (!p.lines[p.cursorY]) {
278
+ p.cursorY = p.lines.length - 1;
279
+ }
280
+ p.cursorX = Math.min(p.cursorX, p.lines[p.cursorY].length);
281
+ p.update();
282
+ p.render();
283
+ };
284
+
285
+ return emitter;
286
+ }
287
+
288
+ function editInMemory(text) {
289
+ return new Promise((resolve) => {
290
+ const editor = createEditor(text);
291
+ const finish = (value) => {
292
+ editor.pause();
293
+ resolve(value);
294
+ };
295
+ editor.on("submit", finish);
296
+ editor.on("abort", () => finish(undefined));
297
+ });
298
+ }
299
+
300
+ module.exports = {
301
+ createEditor,
302
+ editInMemory,
303
+ };
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+
3
+ /* istanbul ignore file -- keypress helper for MemoryEditor; not unit-tested in CI */
4
+
5
+ const { StringDecoder } = require("string_decoder");
6
+
7
+ // Adapted from prompt-skeleton / keypress (MIT). See MemoryEditor.js for attribution.
8
+
9
+ const metaKeyCodeRe = /^(?:\x1b)([a-zA-Z0-9])$/;
10
+ const functionKeyCodeRe =
11
+ /^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/;
12
+
13
+ function parseKey(s, enc) {
14
+ let ch;
15
+ let parts;
16
+ const key = {
17
+ name: undefined,
18
+ ctrl: false,
19
+ meta: false,
20
+ shift: false,
21
+ sequence: s,
22
+ };
23
+
24
+ if (Buffer.isBuffer(s)) {
25
+ if (s[0] > 127 && s[1] === undefined) {
26
+ s[0] -= 128;
27
+ s = "\x1b" + s.toString(enc || "utf-8");
28
+ } else {
29
+ s = s.toString(enc || "utf-8");
30
+ }
31
+ }
32
+
33
+ if (s === "\r") {
34
+ key.name = "return";
35
+ } else if (s === "\n") {
36
+ key.name = "enter";
37
+ } else if (
38
+ s === "\t" ||
39
+ s === "\b" ||
40
+ s === "\x7f" ||
41
+ s === "\x1b\x7f" ||
42
+ s === "\x1b\b"
43
+ ) {
44
+ if (s === "\t") {
45
+ key.name = "tab";
46
+ } else {
47
+ key.name = "backspace";
48
+ key.meta = s.charAt(0) === "\x1b";
49
+ }
50
+ } else if (s === "\x1b" || s === "\x1b\x1b") {
51
+ key.name = "escape";
52
+ key.meta = s.length === 2;
53
+ } else if (s === " " || s === "\x1b ") {
54
+ key.name = "space";
55
+ key.meta = s.length === 2;
56
+ } else if (s <= "\x1a") {
57
+ key.name = String.fromCharCode(s.charCodeAt(0) + "a".charCodeAt(0) - 1);
58
+ key.ctrl = true;
59
+ } else if (s.length === 1 && s >= "a" && s <= "z") {
60
+ key.name = s;
61
+ } else if (s.length === 1 && s >= "A" && s <= "Z") {
62
+ key.name = s.toLowerCase();
63
+ key.shift = true;
64
+ } else if ((parts = metaKeyCodeRe.exec(s))) {
65
+ key.name = parts[1].toLowerCase();
66
+ key.meta = true;
67
+ key.shift = /^[A-Z]$/.test(parts[1]);
68
+ } else if ((parts = functionKeyCodeRe.exec(s))) {
69
+ const code =
70
+ (parts[1] || "") + (parts[2] || "") + (parts[4] || "") + (parts[6] || "");
71
+ const modifier = (parts[3] || parts[5] || 1) - 1;
72
+ key.ctrl = !!(modifier & 4);
73
+ key.meta = !!(modifier & 10);
74
+ key.shift = !!(modifier & 1);
75
+ key.code = code;
76
+ switch (code) {
77
+ case "[A":
78
+ case "OA":
79
+ key.name = "up";
80
+ break;
81
+ case "[B":
82
+ case "OB":
83
+ key.name = "down";
84
+ break;
85
+ case "[C":
86
+ case "OC":
87
+ key.name = "right";
88
+ break;
89
+ case "[D":
90
+ case "OD":
91
+ key.name = "left";
92
+ break;
93
+ default:
94
+ key.name = "undefined";
95
+ break;
96
+ }
97
+ } else if (s.length > 1 && s[0] !== "\x1b") {
98
+ return Array.prototype.map.call(s, (c) => parseKey(c, enc));
99
+ }
100
+
101
+ if (s.length === 1) {
102
+ ch = s;
103
+ }
104
+ key.raw = ch || s;
105
+ return key;
106
+ }
107
+
108
+ function onKeypress(stream, cb) {
109
+ const decoder = new StringDecoder("utf8");
110
+ const onData = (data) => {
111
+ const parsed = parseKey(decoder.write(data), stream.encoding);
112
+ if (Array.isArray(parsed)) {
113
+ parsed.forEach((c) => cb(c));
114
+ } else {
115
+ cb(parsed);
116
+ }
117
+ };
118
+
119
+ const oldRawMode = stream.isRaw;
120
+ stream.setRawMode(true);
121
+ stream.on("data", onData);
122
+ stream.resume();
123
+
124
+ return () => {
125
+ stream.removeListener("data", onData);
126
+ if (typeof stream.setRawMode === "function") {
127
+ try {
128
+ stream.setRawMode(oldRawMode);
129
+ } catch (e) {
130
+ // ignore
131
+ }
132
+ }
133
+ // Do not stream.pause() here: pausing process.stdin leaves the next
134
+ // inquirer prompt racing a closed/paused readline (ERR_USE_AFTER_CLOSE).
135
+ };
136
+ }
137
+
138
+ module.exports = onKeypress;
@@ -6,13 +6,12 @@ const inquirer = require("inquirer");
6
6
  // eslint-disable-next-line node/no-unpublished-require
7
7
  // const inquirerCommandPrompt = require('../../../../../inquirer-command-prompt')
8
8
  const inquirerCommandPrompt = require("inquirer-command-prompt");
9
- const multiEditorPrompt = require("./MultiEditorPrompt");
10
9
  inquirer.registerPrompt("command", inquirerCommandPrompt);
11
- inquirer.registerPrompt("multiEditor", multiEditorPrompt);
12
10
 
13
11
  const { sleep, getKeyValue } = require("@secrez/utils");
14
12
  const Completion = require("./Completion");
15
13
  const { FsUtils } = require("@secrez/fs");
14
+ const { VaultPermissions } = require("@secrez/core");
16
15
  const Logger = require("../utils/Logger");
17
16
  const cliConfig = require("../cliConfig");
18
17
  const sigintManager = require("./SigintManager");
@@ -148,7 +147,7 @@ class CommandPrompt {
148
147
  async saveHistory() {
149
148
  let histories = JSON.stringify(inquirerCommandPrompt.getHistories(true));
150
149
  let encryptedHistory = this.secrez.encryptData(histories);
151
- await fs.writeFile(this.historyPath, encryptedHistory);
150
+ await VaultPermissions.writeFile(this.historyPath, encryptedHistory);
152
151
  }
153
152
 
154
153
  async loadSavedHistory() {
@@ -2,6 +2,7 @@ const chalk = require("chalk");
2
2
  const _ = require("lodash");
3
3
  const path = require("path");
4
4
  const { InternalFs, ExternalFs, DataCache } = require("@secrez/fs");
5
+ const { VaultPermissions } = require("@secrez/core");
5
6
  const Logger = require("../utils/Logger");
6
7
  const cliConfig = require("../cliConfig");
7
8
  const Commands = require("../commands");
@@ -35,6 +36,7 @@ class MainPrompt extends require("./CommandPrompt") {
35
36
  async preRun(options = {}) {
36
37
  if (!this.loggedIn) {
37
38
  await welcome.start(this.secrez, options);
39
+ await VaultPermissions.secureVaultIfNeeded(this.secrez.config);
38
40
  this.startSigintManager();
39
41
  this.internalFs.init().then(() => delete this.showLoading);
40
42
  this.loadingMessage = "Initializing";
@@ -46,6 +46,10 @@ class MainPromptMock {
46
46
 
47
47
  async run(options) {}
48
48
 
49
+ getRl() {
50
+ return { pause() {}, resume() {} };
51
+ }
52
+
49
53
  async exec(cmds, noRun) {}
50
54
 
51
55
  async loading() {}
@@ -18,6 +18,10 @@ class SigintManager {
18
18
  async onSigint() {
19
19
  this.siginted = true;
20
20
  if (Date.now() - this.lastCalled < 500) {
21
+ const prompt = this.prompts.find((p) => p.secrez);
22
+ if (prompt?.secrez?.masterKeyHash) {
23
+ prompt.secrez.signout();
24
+ }
21
25
  // eslint-disable-next-line no-process-exit
22
26
  process.exit(0);
23
27
  }
@@ -1,23 +0,0 @@
1
- const utils = require("@secrez/utils");
2
-
3
- class Bash extends require("../Command") {
4
- setHelpAndCompletion() {
5
- this.cliConfig.completion.bash = utils.sortKeys({});
6
- this.cliConfig.completion.help.bash = true;
7
- this.optionDefinitions = [];
8
- }
9
-
10
- help() {
11
- return {
12
- description: ['<< deprecated - use "shell" instead'],
13
- examples: [],
14
- };
15
- }
16
-
17
- async exec(options = {}) {
18
- this.Logger.red('"bash" is deprecated. Use "shell" instead');
19
- await this.prompt.run();
20
- }
21
- }
22
-
23
- module.exports = Bash;
@@ -1,41 +0,0 @@
1
- const editAsync = require("external-editor").editAsync;
2
- const EditorPrompt = require("inquirer/lib/prompts/editor");
3
- const chalk = require("chalk");
4
-
5
- class MultiEditorPrompt extends EditorPrompt {
6
- render(error) {
7
- var bottomContent = "";
8
- var message = this.getQuestion();
9
-
10
- if (this.status === "answered") {
11
- message += chalk.dim("Received");
12
- } else {
13
- message += this.opt.extraMessage || "";
14
- }
15
- if (error) {
16
- bottomContent = chalk.red(">> ") + error;
17
- }
18
- this.screen.render(message, bottomContent);
19
- }
20
-
21
- async startExternalEditor() {
22
- this.rl.pause();
23
- editAsync(
24
- this.currentText,
25
- this.endExternalEditor.bind(this),
26
- this.opt.tempDir
27
- ? {
28
- dir: this.opt.tempDir,
29
- }
30
- : undefined
31
- );
32
- }
33
-
34
- close() {
35
- if (this.opt.onClose) {
36
- this.opt.onClose();
37
- }
38
- }
39
- }
40
-
41
- module.exports = MultiEditorPrompt;