@secrez/core 1.0.7 → 1.1.1

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.
package/README.md CHANGED
@@ -20,6 +20,15 @@ API documentation
20
20
 
21
21
  ## History
22
22
 
23
+ **1.1.0**
24
+
25
+ - clear cryptographic secrets from memory on `signout` via `clearSecrets()` (best-effort buffer zeroing)
26
+ - guard crypto APIs with `assertLoggedIn()` after signout
27
+ - replace deprecated `homedir` package with `os.homedir()`
28
+ - require Node.js 22.23.4 or later (`engines.node >=22.23.4`)
29
+ - fix `decryptEntry` content-only path: set `ts` from `e.t` instead of `e.i` (SIG-4)
30
+ - vault permissions (FS-1): `VaultPermissions` — files `0o600`, dirs `0o700` on create; `secureVaultIfNeeded()` at login (probe `keys/default.json` or `keys/`)
31
+
23
32
  **1.0.7**
24
33
 
25
34
  - remove legacy shared-secret / second-factor authentication API (`sharedSignin`, `generateSharedSecrets`, `recoverSharedSecrets`, `removeSharedSecret`, `getSecondFactorData`, and related config); sign-in now requires only the master key
@@ -32,21 +41,22 @@ API documentation
32
41
  ## Test coverage
33
42
 
34
43
  ```
35
- 54 passing (929ms)
36
-
37
- -----------------|---------|----------|---------|---------|-------------------
38
- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
39
- -----------------|---------|----------|---------|---------|-------------------
40
- All files | 99.39 | 93.49 | 98.5 | 99.39 |
41
- src | 99.61 | 95.58 | 98.24 | 99.61 |
42
- Entry.js | 100 | 95.65 | 100 | 100 | 39
43
- Secrez.js | 100 | 96.66 | 100 | 100 | 207,330
44
- _Secrez.js | 98.93 | 91.3 | 95.65 | 98.93 | 101
45
- src/config | 98.57 | 84.84 | 100 | 98.57 |
46
- ConfigUtils.js | 98.48 | 84.84 | 100 | 98.48 | 137
47
- booleans.js | 100 | 100 | 100 | 100 |
48
- index.js | 100 | 100 | 100 | 100 |
49
- -----------------|---------|----------|---------|---------|-------------------
44
+ 63 passing (469ms)
45
+
46
+ ----------------------|---------|----------|---------|---------|----------------------
47
+ File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
48
+ ----------------------|---------|----------|---------|---------|----------------------
49
+ All files | 98.3 | 91.57 | 98.76 | 98.3 |
50
+ src | 97.92 | 94.28 | 98.33 | 97.92 |
51
+ Entry.js | 100 | 95.65 | 100 | 100 | 39
52
+ Secrez.js | 100 | 97.72 | 100 | 100 | 226
53
+ _Secrez.js | 94.54 | 82.75 | 96 | 94.54 | 11,14-15,114,249-250
54
+ src/config | 99.19 | 84 | 100 | 99.19 |
55
+ ConfigUtils.js | 98.57 | 84.84 | 100 | 98.57 | 143
56
+ VaultPermissions.js | 100 | 82.35 | 100 | 100 | 53,79,102
57
+ booleans.js | 100 | 100 | 100 | 100 |
58
+ index.js | 100 | 100 | 100 | 100 |
59
+ ----------------------|---------|----------|---------|---------|----------------------
50
60
  ```
51
61
 
52
62
  ## Copyright
package/coverage.report CHANGED
@@ -1,12 +1,9 @@
1
1
 
2
- > @secrez/core@1.0.7 test /Users/francescosullo/Projects/Secrez/secrez/packages/core
2
+ > @secrez/core@1.0.5 test /Users/francescosullo/Projects/Secrez/secrez/packages/core
3
3
  > cross-env NODE_ENV=test nyc --reporter=lcov --reporter=text mocha test/*.test.js test/**/*.test.js --exit
4
4
 
5
5
 
6
6
 
7
- #config
8
- ✓ all field should be correctly configured
9
-
10
7
  #Entry
11
8
  #constructor
12
9
  ✓ should instantiate the Entry
@@ -29,22 +26,22 @@
29
26
  derivePassword
30
27
  ✓ should derive a password and obtain a predeterminded hash
31
28
  signup and signin
32
- ✓ should signup the user and signin without saving the iterations (46ms)
33
- ✓ should signup in two instances without conflicts
34
- ✓ should signup the user and signin saved the iterations
35
- ✓ should signup with version one, and signin and upgrade to version two (40ms)
36
- ✓ should signup the user, change password and signin
37
- ✓ should signup the user, change iterations and signin (45ms)
38
- ✓ should signup the user, change password and iterations and signin (184ms)
29
+ ✓ should signup the user and signin without saving the iterations (73ms)
30
+ ✓ should signup in two instances without conflicts (50ms)
31
+ ✓ should signup the user and signin saved the iterations (45ms)
32
+ ✓ should signup with version one, and signin and upgrade to version two (66ms)
33
+ ✓ should signup the user, change password and signin (63ms)
34
+ ✓ should signup the user, change iterations and signin (63ms)
35
+ ✓ should signup the user, change password and iterations and signin (81ms)
39
36
  should throw an error
40
37
  ✓ trying to signup if Secrez has not been initiated
41
38
  ✓ trying to signin if Secrez has not been initiated
42
39
  ✓ trying to signup if account already exists
43
40
  ✓ trying to signin if account is not set yet
44
41
  ✓ trying to signin with missed iterations
45
- ✓ trying to signin with the wrong password
46
- ✓ trying to signin with the right password but wrong number of iterations
47
- ✓ trying to signin with the right password but using a wrong hash on file
42
+ ✓ trying to signin with the wrong password (40ms)
43
+ ✓ trying to signin with the right password but wrong number of iterations (41ms)
44
+ ✓ trying to signin with the right password but using a wrong hash on file (41ms)
48
45
  ✓ trying to sign out if never signed-in
49
46
  encryptEntry and decryptEntry
50
47
  ✓ should encrypt a name and decrypt it
@@ -64,16 +61,26 @@
64
61
  preEncryptData and preDecryptData
65
62
  ✓ should encrypt some data with the derivedPassword and decrypt it
66
63
  ✓ should throw trying to get the master key
64
+ generateSharedSecrets && recoverSharedSecrets
65
+ ✓ should set up a second factor (72ms)
66
+ ✓ should set up a second factor and then upgrade from derivationVersion 1 to 2 (46ms)
67
+ ✓ should set up a second factor and a recovery code and remove them (70ms)
68
+ ✓ should set up a second factor and a recovery code and remove the recovery code (69ms)
69
+ ✓ should throw if wrong secret (42ms)
70
+ ✓ should throw if wrong authenticator (43ms)
67
71
  #readConf
68
72
  ✓ should encrypt some data with the derivedPassword and decrypt it
69
73
  ✓ should throw trying to get the master key
70
74
  ✓ should throw trying to get the master key
71
75
  #signMessage
72
- ✓ should sign a message and verify it
76
+ ✓ should sign a message and verify it (47ms)
73
77
  #getPublicKey
74
- ✓ should sign a message and verify it
78
+ ✓ should sign a message and verify it (44ms)
75
79
  #encrypt and decrypt shared data
76
- ✓ should get a shared ket
80
+ ✓ should get a shared ket (52ms)
81
+
82
+ #config
83
+ ✓ all field should be correctly configured
77
84
 
78
85
  #ConfigUtils
79
86
  ✓ should check if a type is valid
@@ -84,22 +91,22 @@
84
91
  ✓ #getEnv should return the environment
85
92
 
86
93
 
87
- 54 passing (929ms)
94
+ 60 passing (2s)
88
95
 
89
96
  -----------------|---------|----------|---------|---------|-------------------
90
97
  File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
91
98
  -----------------|---------|----------|---------|---------|-------------------
92
- All files | 99.39 | 93.49 | 98.5 | 99.39 |
93
- src | 99.61 | 95.58 | 98.24 | 99.61 |
99
+ All files | 99.75 | 94.31 | 100 | 99.75 |
100
+ src | 100 | 96.06 | 100 | 100 |
94
101
  Entry.js | 100 | 95.65 | 100 | 100 | 39
95
- Secrez.js | 100 | 96.66 | 100 | 100 | 207,330
96
- _Secrez.js | 98.93 | 91.3 | 95.65 | 98.93 | 101
102
+ Secrez.js | 100 | 96.94 | 100 | 100 | 154,319,442
103
+ _Secrez.js | 100 | 91.66 | 100 | 100 | 14,226
97
104
  src/config | 98.57 | 84.84 | 100 | 98.57 |
98
105
  ConfigUtils.js | 98.48 | 84.84 | 100 | 98.48 | 137
99
106
  booleans.js | 100 | 100 | 100 | 100 |
100
107
  index.js | 100 | 100 | 100 | 100 |
101
108
  -----------------|---------|----------|---------|---------|-------------------
102
109
 
103
- > @secrez/core@1.0.7 posttest /Users/francescosullo/Projects/Secrez/secrez/packages/core
104
- > nyc check-coverage --statements 99 --branches 93 --functions 98 --lines 99
110
+ > @secrez/core@1.0.5 posttest /Users/francescosullo/Projects/Secrez/secrez/packages/core
111
+ > nyc check-coverage --statements 99 --branches 94 --functions 99 --lines 99
105
112
 
package/package.json CHANGED
@@ -1,22 +1,21 @@
1
1
  {
2
2
  "name": "@secrez/core",
3
- "version": "1.0.7",
3
+ "version": "1.1.1",
4
4
  "license": "MIT",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
8
8
  "dependencies": {
9
- "@secrez/crypto": "~1.0.6",
10
- "@secrez/utils": "~1.0.5",
9
+ "@secrez/crypto": "~1.1.1",
10
+ "@secrez/utils": "~1.1.1",
11
11
  "fs-extra": "^9.1.0",
12
- "homedir": "^0.6.0",
13
12
  "lodash": "^4.17.21"
14
13
  },
15
14
  "devDependencies": {
16
- "@secrez/test-helpers": "~2.0.2",
15
+ "@secrez/test-helpers": "~2.0.4",
17
16
  "chai": "^4.5.0",
18
17
  "cross-env": "^7.0.3",
19
- "mocha": "^7.2.0",
18
+ "mocha": "^10.8.2",
20
19
  "nyc": "^15.1.0"
21
20
  },
22
21
  "description": "The Secrez core library.",
@@ -30,12 +29,12 @@
30
29
  "email": "francesco@sullo.co"
31
30
  },
32
31
  "engines": {
33
- "node": ">=10.0.0"
32
+ "node": ">=22.23.4"
34
33
  },
35
34
  "scripts": {
36
35
  "all-tests": "find test/** -name '*.test.js' | xargs ./node_modules/.bin/mocha -R spec",
37
36
  "test-only": "cross-env NODE_ENV=test ./node_modules/.bin/mocha test/*.test.js test/**/*.test.js --exit",
38
37
  "test": "cross-env NODE_ENV=test nyc --reporter=lcov --reporter=text mocha test/*.test.js test/**/*.test.js --exit",
39
- "posttest": "nyc check-coverage --statements 99 --branches 93 --functions 98 --lines 99"
38
+ "posttest": "nyc check-coverage --statements 98 --branches 91 --functions 98 --lines 98"
40
39
  }
41
40
  }
package/src/Secrez.js CHANGED
@@ -1,8 +1,9 @@
1
- const homedir = require("homedir");
1
+ const { homedir } = require("os");
2
2
  const fs = require("fs-extra");
3
3
  const _ = require("lodash");
4
4
  const Crypto = require("@secrez/crypto");
5
5
  const ConfigUtils = require("./config/ConfigUtils");
6
+ const VaultPermissions = require("./config/VaultPermissions");
6
7
  const Entry = require("./Entry");
7
8
 
8
9
  const { DO_NOT_VERIFY, URL_SAFE } = require("./config/booleans");
@@ -97,7 +98,10 @@ module.exports = function () {
97
98
 
98
99
  async signAndSave(data) {
99
100
  const conf = _secrez.signData(data);
100
- await fs.writeFile(this.config.keysPath, JSON.stringify(conf));
101
+ await VaultPermissions.writeFile(
102
+ this.config.keysPath,
103
+ JSON.stringify(conf)
104
+ );
101
105
  return conf;
102
106
  }
103
107
 
@@ -108,10 +112,12 @@ module.exports = function () {
108
112
  }
109
113
 
110
114
  getConf() {
115
+ this.assertLoggedIn();
111
116
  return _secrez.conf;
112
117
  }
113
118
 
114
119
  getPublicKey() {
120
+ this.assertLoggedIn();
115
121
  return (
116
122
  _secrez.conf.data.box.publicKey + "$" + _secrez.conf.data.sign.publicKey
117
123
  );
@@ -138,6 +144,7 @@ module.exports = function () {
138
144
  }
139
145
 
140
146
  signMessage(message) {
147
+ this.assertLoggedIn();
141
148
  return _secrez.signMessage(message);
142
149
  }
143
150
 
@@ -157,6 +164,12 @@ module.exports = function () {
157
164
  this.masterKeyHash = masterKeyHash;
158
165
  }
159
166
 
167
+ assertLoggedIn() {
168
+ if (!this.masterKeyHash) {
169
+ throw new Error("User not logged");
170
+ }
171
+ }
172
+
160
173
  preserveEntry(prev, next) {
161
174
  let options = prev.get();
162
175
  for (let o in options) {
@@ -168,26 +181,32 @@ module.exports = function () {
168
181
  }
169
182
 
170
183
  encryptData(data, urlSafe) {
184
+ this.assertLoggedIn();
171
185
  return _secrez.encrypt(data, urlSafe);
172
186
  }
173
187
 
174
188
  decryptData(encryptedData, urlSafe, returnUint8Array) {
189
+ this.assertLoggedIn();
175
190
  return _secrez.decrypt(encryptedData, urlSafe, returnUint8Array);
176
191
  }
177
192
 
178
193
  preEncryptData(data) {
194
+ this.assertLoggedIn();
179
195
  return _secrez.preEncrypt(data);
180
196
  }
181
197
 
182
198
  preDecryptData(encryptedData) {
199
+ this.assertLoggedIn();
183
200
  return _secrez.preDecrypt(encryptedData);
184
201
  }
185
202
 
186
203
  encryptSharedData(data, publicKey) {
204
+ this.assertLoggedIn();
187
205
  return _secrez.encryptShared(data, publicKey);
188
206
  }
189
207
 
190
208
  decryptSharedData(encryptedData, publicKey) {
209
+ this.assertLoggedIn();
191
210
  return _secrez.decryptShared(encryptedData, publicKey);
192
211
  }
193
212
 
@@ -198,64 +217,61 @@ module.exports = function () {
198
217
 
199
218
  const { type, name, content, preserveContent, id } = entry.get();
200
219
 
201
- if (this.masterKeyHash) {
202
- if (!ConfigUtils.isValidType(type)) {
203
- throw new Error("Unsupported type");
220
+ this.assertLoggedIn();
221
+ if (!ConfigUtils.isValidType(type)) {
222
+ throw new Error("Unsupported type");
223
+ }
224
+
225
+ let ts =
226
+ useTs && entry.ts
227
+ ? entry.ts
228
+ : Crypto.getTimestampWithMicroseconds().join(".");
229
+ let encryptedEntry = new Entry({
230
+ id,
231
+ type,
232
+ ts,
233
+ });
234
+ if (name) {
235
+ let encryptedName =
236
+ type +
237
+ _secrez.encrypt(
238
+ JSON.stringify({
239
+ i: id,
240
+ t: ts,
241
+ n: name,
242
+ }),
243
+ URL_SAFE
244
+ );
245
+ let extraName;
246
+ if (encryptedName.length > 255) {
247
+ extraName = encryptedName.substring(254);
248
+ encryptedName = encryptedName.substring(0, 254) + "$";
204
249
  }
205
250
 
206
- let ts =
207
- useTs && entry.ts
208
- ? entry.ts
209
- : Crypto.getTimestampWithMicroseconds().join(".");
210
- let encryptedEntry = new Entry({
211
- id,
212
- type,
213
- ts,
251
+ encryptedEntry.set({
252
+ encryptedName,
253
+ extraName,
214
254
  });
215
- if (name) {
216
- let encryptedName =
217
- type +
218
- _secrez.encrypt(
219
- JSON.stringify({
220
- i: id,
221
- t: ts,
222
- n: name,
223
- }),
224
- URL_SAFE
225
- );
226
- let extraName;
227
- if (encryptedName.length > 255) {
228
- extraName = encryptedName.substring(254);
229
- encryptedName = encryptedName.substring(0, 254) + "$";
230
- }
231
-
232
- encryptedEntry.set({
233
- encryptedName,
234
- extraName,
235
- });
236
255
 
237
- if (preserveContent) {
238
- encryptedEntry = this.preserveEntry(entry, encryptedEntry);
239
- }
256
+ if (preserveContent) {
257
+ encryptedEntry = this.preserveEntry(entry, encryptedEntry);
240
258
  }
241
- if (content) {
242
- encryptedEntry.set({
243
- encryptedContent: _secrez.encrypt(
244
- JSON.stringify({
245
- i: id,
246
- t: ts,
247
- c: content,
248
- })
249
- ),
250
- });
251
- if (preserveContent) {
252
- encryptedEntry = this.preserveEntry(entry, encryptedEntry);
253
- }
259
+ }
260
+ if (content) {
261
+ encryptedEntry.set({
262
+ encryptedContent: _secrez.encrypt(
263
+ JSON.stringify({
264
+ i: id,
265
+ t: ts,
266
+ c: content,
267
+ })
268
+ ),
269
+ });
270
+ if (preserveContent) {
271
+ encryptedEntry = this.preserveEntry(entry, encryptedEntry);
254
272
  }
255
- return encryptedEntry;
256
- } else {
257
- throw new Error("User not logged");
258
273
  }
274
+ return encryptedEntry;
259
275
  }
260
276
 
261
277
  decryptEntry(encryptedEntry, urlSafe) {
@@ -272,87 +288,79 @@ module.exports = function () {
272
288
  nameTs,
273
289
  } = encryptedEntry.get();
274
290
 
275
- if (this.masterKeyHash) {
276
- try {
277
- if (encryptedName) {
278
- let data = encryptedName;
279
- if (extraName) {
280
- data = encryptedName.substring(0, 254) + extraName;
281
- }
282
- let type = parseInt(data[0]);
283
- let e = JSON.parse(_secrez.decrypt(data.substring(1), URL_SAFE));
284
- let id = e.i;
285
- let ts = e.t;
286
- let name = e.n;
287
- let content = "";
288
-
289
- // during the indexing internalFS reads only the names of the files
290
- if (encryptedContent) {
291
- let e = JSON.parse(_secrez.decrypt(encryptedContent));
292
- if (id !== e.i || ts !== e.t) {
293
- throw new Error("Data is corrupted");
294
- }
295
- content = e.c;
291
+ this.assertLoggedIn();
292
+ try {
293
+ if (encryptedName) {
294
+ let data = encryptedName;
295
+ if (extraName) {
296
+ data = encryptedName.substring(0, 254) + extraName;
297
+ }
298
+ let type = parseInt(data[0]);
299
+ let e = JSON.parse(_secrez.decrypt(data.substring(1), URL_SAFE));
300
+ let id = e.i;
301
+ let ts = e.t;
302
+ let name = e.n;
303
+ let content = "";
304
+
305
+ // during the indexing internalFS reads only the names of the files
306
+ if (encryptedContent) {
307
+ let e = JSON.parse(_secrez.decrypt(encryptedContent));
308
+ if (id !== e.i || ts !== e.t) {
309
+ throw new Error("Data is corrupted");
296
310
  }
311
+ content = e.c;
312
+ }
297
313
 
298
- let decryptedEntry = new Entry({
299
- id,
300
- type,
301
- ts,
302
- name,
303
- content,
304
- });
305
-
306
- if (preserveContent) {
307
- decryptedEntry = this.preserveEntry(
308
- encryptedEntry,
309
- decryptedEntry
310
- );
311
- }
314
+ let decryptedEntry = new Entry({
315
+ id,
316
+ type,
317
+ ts,
318
+ name,
319
+ content,
320
+ });
312
321
 
313
- return decryptedEntry;
322
+ if (preserveContent) {
323
+ decryptedEntry = this.preserveEntry(encryptedEntry, decryptedEntry);
314
324
  }
315
325
 
316
- // when the encryptedName has been already decrypted and we need only the content
317
- if (encryptedContent) {
318
- let e = JSON.parse(_secrez.decrypt(encryptedContent));
326
+ return decryptedEntry;
327
+ }
319
328
 
320
- if ((nameId && e.i !== nameId) || (nameTs && e.t !== nameTs)) {
321
- throw new Error("Content is corrupted");
322
- }
329
+ // when the encryptedName has been already decrypted and we need only the content
330
+ if (encryptedContent) {
331
+ let e = JSON.parse(_secrez.decrypt(encryptedContent));
323
332
 
324
- let decryptedEntry = new Entry({
325
- id: e.i,
326
- ts: e.i,
327
- content: e.c,
328
- });
329
-
330
- if (preserveContent) {
331
- decryptedEntry = this.preserveEntry(
332
- encryptedEntry,
333
- decryptedEntry
334
- );
335
- }
336
-
337
- return decryptedEntry;
333
+ if ((nameId && e.i !== nameId) || (nameTs && e.t !== nameTs)) {
334
+ throw new Error("Content is corrupted");
338
335
  }
339
- } catch (e) {
340
- if (e.message === "Data is corrupted") {
341
- throw e;
342
- } else if (e.message === "Content is corrupted") {
343
- throw e;
336
+
337
+ let decryptedEntry = new Entry({
338
+ id: e.i,
339
+ ts: e.t,
340
+ content: e.c,
341
+ });
342
+
343
+ if (preserveContent) {
344
+ decryptedEntry = this.preserveEntry(encryptedEntry, decryptedEntry);
344
345
  }
345
- throw new Error("Fatal error during decryption");
346
- }
347
346
 
348
- throw new Error("Missing parameters");
349
- } else {
350
- throw new Error("User not logged");
347
+ return decryptedEntry;
348
+ }
349
+ } catch (e) {
350
+ if (e.message === "Data is corrupted") {
351
+ throw e;
352
+ } else if (e.message === "Content is corrupted") {
353
+ throw e;
354
+ }
355
+ throw new Error("Fatal error during decryption");
351
356
  }
357
+
358
+ throw new Error("Missing parameters");
352
359
  }
353
360
 
354
361
  signout() {
355
362
  if (this.masterKeyHash) {
363
+ _secrez.clearSecrets();
356
364
  delete this.masterKeyHash;
357
365
  _secrez = undefined;
358
366
  } else {
package/src/_Secrez.js CHANGED
@@ -6,6 +6,19 @@ const { RETURN_UINT8_ARRAY } = require("./config/booleans");
6
6
  const Crypto = require("@secrez/crypto");
7
7
  const bs64 = Crypto.bs64;
8
8
 
9
+ function zeroSensitive(value) {
10
+ if (!value) {
11
+ return;
12
+ }
13
+ if (Buffer.isBuffer(value)) {
14
+ value.fill(0);
15
+ return;
16
+ }
17
+ if (value instanceof Uint8Array) {
18
+ value.fill(0);
19
+ }
20
+ }
21
+
9
22
  module.exports = function () {
10
23
  const __ = {
11
24
  sharedKeys: {},
@@ -220,6 +233,36 @@ module.exports = function () {
220
233
  }
221
234
  return sortedData;
222
235
  }
236
+
237
+ clearSecrets() {
238
+ for (const key of [
239
+ "masterKeyArray",
240
+ "boxPrivateKey",
241
+ "signPrivateKey",
242
+ "boxPublicKey",
243
+ "signPublicKey",
244
+ ]) {
245
+ zeroSensitive(__[key]);
246
+ delete __[key];
247
+ }
248
+ for (const publicKey of Object.keys(__.sharedKeys)) {
249
+ zeroSensitive(__.sharedKeys[publicKey]);
250
+ delete __.sharedKeys[publicKey];
251
+ }
252
+ for (const key of [
253
+ "password",
254
+ "derivedPassword",
255
+ "masterKey",
256
+ "encryptedMasterKey",
257
+ "masterKeyHash",
258
+ "encryptedBoxPrivateKey",
259
+ "encryptedSignPrivateKey",
260
+ "iterations",
261
+ ]) {
262
+ delete __[key];
263
+ }
264
+ delete this.conf;
265
+ }
223
266
  }
224
267
 
225
268
  return _Secrez;
@@ -4,6 +4,7 @@ const utils = require("@secrez/utils");
4
4
  const fs = require("fs-extra");
5
5
  const pkg = require("../../package");
6
6
  const config = require(".");
7
+ const VaultPermissions = require("./VaultPermissions");
7
8
 
8
9
  class ConfigUtils {
9
10
  static isValidType(type) {
@@ -24,14 +25,15 @@ class ConfigUtils {
24
25
  config.localDataPath = path.join(container, "local");
25
26
  config.tmpPath = path.join(container, "tmp");
26
27
 
27
- await fs.ensureDir(config.dataPath);
28
- await fs.ensureDir(config.keysDataPath);
29
- await fs.ensureDir(config.localDataPath);
28
+ await VaultPermissions.ensureDir(config.dataPath);
29
+ await VaultPermissions.ensureDir(config.keysDataPath);
30
+ await VaultPermissions.ensureDir(config.localDataPath);
31
+ await VaultPermissions.ensureDir(config.tmpPath);
30
32
 
31
33
  await fs.emptyDir(config.tmpPath);
32
34
 
33
35
  if (!(await fs.pathExists(config.oldKeysPath))) {
34
- await fs.writeFile(
36
+ await VaultPermissions.writeFile(
35
37
  path.join(container, "keys.json"),
36
38
  JSON.stringify(
37
39
  {
@@ -61,36 +63,39 @@ class ConfigUtils {
61
63
  }
62
64
  let readmePath = path.join(container, "README");
63
65
  if (!(await fs.pathExists(readmePath))) {
64
- await fs.writeFile(
66
+ await VaultPermissions.writeFile(
65
67
  readmePath,
66
68
  `
67
69
  This folder has been generated by ${utils.capitalize(pkg.name)} v${pkg.version}.
68
70
  It contains your secret database.
69
71
  Be very careful, and don't touch anything :o)
70
72
  `,
71
- "utf-8"
73
+ { encoding: "utf-8" }
72
74
  );
73
- await fs.writeFile(config.envPath, "{}");
75
+ await VaultPermissions.writeFile(config.envPath, "{}");
74
76
  }
75
77
  let gitignorePath = path.join(container, ".gitignore");
76
78
  if (!(await fs.pathExists(gitignorePath))) {
77
- await fs.writeFile(
79
+ await VaultPermissions.writeFile(
78
80
  gitignorePath,
79
81
  `tmp
80
82
  env.json
81
83
  history
82
84
  local
83
85
  `,
84
- "utf-8"
86
+ { encoding: "utf-8" }
85
87
  );
86
88
  } else {
87
89
  let gitignore = await fs.readFile(gitignorePath, "utf8");
88
90
  /* istanbul ignore if */
89
91
  if (!/local/.test(gitignore)) {
90
92
  gitignore = _.trim(gitignore) + "\nlocal\n";
91
- fs.writeFile(gitignorePath, gitignore);
93
+ await VaultPermissions.writeFile(gitignorePath, gitignore, {
94
+ encoding: "utf-8",
95
+ });
92
96
  }
93
97
  }
98
+ await VaultPermissions.ensureDir(container);
94
99
  return config;
95
100
  }
96
101
 
@@ -112,7 +117,8 @@ local
112
117
  lastData ===
113
118
  path.basename(config.dataPath) + (index > 1 ? "." + (index - 1) : "")
114
119
  ) {
115
- fs.mkdirSync(dataPath);
120
+ fs.mkdirSync(dataPath, { mode: VaultPermissions.dirMode });
121
+ fs.chmodSync(dataPath, VaultPermissions.dirMode);
116
122
  } else {
117
123
  throw new Error("Wrong data index");
118
124
  }
@@ -157,7 +163,10 @@ local
157
163
  }
158
164
 
159
165
  static async putEnv(config, env) {
160
- return await fs.writeFile(config.envPath, JSON.stringify(env));
166
+ return await VaultPermissions.writeFile(
167
+ config.envPath,
168
+ JSON.stringify(env)
169
+ );
161
170
  }
162
171
  }
163
172
 
@@ -0,0 +1,114 @@
1
+ const path = require("path");
2
+ const fs = require("fs-extra");
3
+
4
+ const VAULT_DIR_MODE = 0o700;
5
+ const VAULT_FILE_MODE = 0o600;
6
+
7
+ class VaultPermissions {
8
+ static get dirMode() {
9
+ return VAULT_DIR_MODE;
10
+ }
11
+
12
+ static get fileMode() {
13
+ return VAULT_FILE_MODE;
14
+ }
15
+
16
+ static isSecureDir(mode) {
17
+ return (mode & 0o777) === VAULT_DIR_MODE;
18
+ }
19
+
20
+ static isSecureFile(mode) {
21
+ return (mode & 0o777) === VAULT_FILE_MODE;
22
+ }
23
+
24
+ static async ensureDir(dirPath) {
25
+ await fs.ensureDir(dirPath, { mode: VAULT_DIR_MODE });
26
+ await fs.chmod(dirPath, VAULT_DIR_MODE);
27
+ }
28
+
29
+ static ensureDirSync(dirPath) {
30
+ fs.ensureDirSync(dirPath, { mode: VAULT_DIR_MODE });
31
+ fs.chmodSync(dirPath, VAULT_DIR_MODE);
32
+ }
33
+
34
+ static async writeFile(filePath, content, options = {}) {
35
+ await fs.writeFile(filePath, content, {
36
+ ...options,
37
+ mode: VAULT_FILE_MODE,
38
+ });
39
+ await fs.chmod(filePath, VAULT_FILE_MODE);
40
+ }
41
+
42
+ /**
43
+ * Probe a representative path to guess whether the vault already uses
44
+ * restrictive permissions. Prefer keys/default.json, else keys/, else container.
45
+ */
46
+ static async probe(config) {
47
+ let probePath = config.container;
48
+ let expectDir = true;
49
+
50
+ if (await fs.pathExists(config.keysPath)) {
51
+ probePath = config.keysPath;
52
+ expectDir = false;
53
+ } else if (await fs.pathExists(config.keysDataPath)) {
54
+ probePath = config.keysDataPath;
55
+ expectDir = true;
56
+ }
57
+
58
+ const probeStat = await fs.stat(probePath);
59
+ const probeSecure = expectDir
60
+ ? VaultPermissions.isSecureDir(probeStat.mode)
61
+ : VaultPermissions.isSecureFile(probeStat.mode);
62
+
63
+ const containerStat = await fs.stat(config.container);
64
+ const containerSecure = VaultPermissions.isSecureDir(containerStat.mode);
65
+
66
+ return {
67
+ secure: probeSecure && containerSecure,
68
+ probePath,
69
+ };
70
+ }
71
+
72
+ static async chmodTree(rootPath) {
73
+ const stat = await fs.lstat(rootPath);
74
+ if (stat.isDirectory()) {
75
+ await fs.chmod(rootPath, VAULT_DIR_MODE);
76
+ for (const name of await fs.readdir(rootPath)) {
77
+ await VaultPermissions.chmodTree(path.join(rootPath, name));
78
+ }
79
+ } else if (stat.isFile()) {
80
+ await fs.chmod(rootPath, VAULT_FILE_MODE);
81
+ }
82
+ }
83
+
84
+ static async secureVault(config) {
85
+ await VaultPermissions.chmodTree(config.container);
86
+ const ConfigUtils = require("./ConfigUtils");
87
+ const env = await ConfigUtils.getEnv(config);
88
+ env.vaultSecured = true;
89
+ await ConfigUtils.putEnv(config, env);
90
+ }
91
+
92
+ /**
93
+ * Apply restrictive permissions on legacy vaults at login. Skips when probe
94
+ * shows the vault is already locked down.
95
+ */
96
+ static async secureVaultIfNeeded(config) {
97
+ const ConfigUtils = require("./ConfigUtils");
98
+ const env = await ConfigUtils.getEnv(config);
99
+ const { secure } = await VaultPermissions.probe(config);
100
+
101
+ if (secure) {
102
+ if (!env.vaultSecured) {
103
+ env.vaultSecured = true;
104
+ await ConfigUtils.putEnv(config, env);
105
+ }
106
+ return false;
107
+ }
108
+
109
+ await VaultPermissions.secureVault(config);
110
+ return true;
111
+ }
112
+ }
113
+
114
+ module.exports = VaultPermissions;
package/src/index.js CHANGED
@@ -3,5 +3,6 @@ module.exports = {
3
3
  Entry: require("./Entry"),
4
4
  config: require("./config"),
5
5
  ConfigUtils: require("./config/ConfigUtils"),
6
+ VaultPermissions: require("./config/VaultPermissions"),
6
7
  version: require("../package").version,
7
8
  };