@secrez/core 1.0.6 → 1.1.0

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,19 @@ 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 20 or later (`engines.node >=20.0.0`)
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
+
32
+ **1.0.7**
33
+
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
35
+
23
36
  **0.8.5**
24
37
 
25
38
  - improve \_Secrez and Secrez encapsulation of private data
@@ -28,21 +41,22 @@ API documentation
28
41
  ## Test coverage
29
42
 
30
43
  ```
31
- 60 passing (889ms)
32
-
33
- -----------------|---------|----------|---------|---------|-------------------
34
- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
35
- -----------------|---------|----------|---------|---------|-------------------
36
- All files | 99.75 | 94.31 | 100 | 99.75 |
37
- src | 100 | 96.06 | 100 | 100 |
38
- Entry.js | 100 | 95.65 | 100 | 100 | 39
39
- Secrez.js | 100 | 96.94 | 100 | 100 | 154,319,442
40
- _Secrez.js | 100 | 91.66 | 100 | 100 | 14,226
41
- src/config | 98.57 | 84.84 | 100 | 98.57 |
42
- ConfigUtils.js | 98.48 | 84.84 | 100 | 98.48 | 137
43
- booleans.js | 100 | 100 | 100 | 100 |
44
- index.js | 100 | 100 | 100 | 100 |
45
- -----------------|---------|----------|---------|---------|-------------------
44
+ 63 passing (502ms)
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
+ ----------------------|---------|----------|---------|---------|----------------------
46
60
  ```
47
61
 
48
62
  ## Copyright
package/coverage.report CHANGED
@@ -1,112 +1,117 @@
1
1
 
2
- > @secrez/core@1.0.6 test /Users/francescosullo/Projects/Secrez/secrez/packages/core
2
+ > @secrez/core@1.1.0 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
- ✓ should instantiate the Entry
13
- ✓ should ignore wrong parameters
9
+ ✔ should instantiate the Entry
10
+ ✔ should ignore wrong parameters
14
11
  #set
15
- ✓ should set some options for the Entry
16
- ✓ should skip invalid options
12
+ ✔ should set some options for the Entry
13
+ ✔ should skip invalid options
17
14
  #unset
18
- ✓ should unset some options
19
- ✓ should skip invalid or undefined options
15
+ ✔ should unset some options
16
+ ✔ should skip invalid or undefined options
20
17
  #sanitizeName
21
- ✓ should sanitize names
18
+ ✔ should sanitize names
22
19
  #sanitizePath
23
- ✓ should sanitize path
20
+ ✔ should sanitize path
24
21
 
25
22
  #Secrez
26
23
  default secrez dir
27
- ✓ should throw trying to test in the default ~/.secrez folder
24
+ ✔ should throw trying to test in the default ~/.secrez folder
28
25
  custom (testing) secrez dir
29
26
  derivePassword
30
- ✓ should derive a password and obtain a predeterminded hash
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 (41ms)
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
36
- ✓ should signup the user, change password and signin
37
- ✓ should signup the user, change iterations and signin
38
- ✓ should signup the user, change password and iterations and signin (42ms)
29
+ ✔ should signup the user and signin without saving the iterations
30
+ ✔ should signup in two instances without conflicts
31
+ ✔ should signup the user and signin saved the iterations
32
+ ✔ should signup with version one, and signin and upgrade to version two
33
+ ✔ should signup the user, change password and signin
34
+ ✔ should signup the user, change iterations and signin
35
+ ✔ should signup the user, change password and iterations and signin
36
+ ✔ should clear secrets from memory on signout
39
37
  should throw an error
40
- ✓ trying to signup if Secrez has not been initiated
41
- ✓ trying to signin if Secrez has not been initiated
42
- ✓ trying to signup if account already exists
43
- ✓ trying to signin if account is not set yet
44
- ✓ 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
48
- ✓ trying to sign out if never signed-in
38
+ ✔ trying to signup if Secrez has not been initiated
39
+ ✔ trying to signin if Secrez has not been initiated
40
+ ✔ trying to signup if account already exists
41
+ ✔ trying to signin if account is not set yet
42
+ ✔ trying to signin with missed iterations
43
+ ✔ trying to signin with the wrong password
44
+ ✔ trying to signin with the right password but wrong number of iterations
45
+ ✔ trying to signin with the right password but using a wrong hash on file
46
+ ✔ trying to sign out if never signed-in
49
47
  encryptEntry and decryptEntry
50
- ✓ should encrypt a name and decrypt it
51
- ✓ should encrypt a very long name and decrypt it
52
- ✓ should encrypt name and content and decrypt it
53
- ✓ should encrypt only the content and decrypt it
54
- ✓ should re-encrypt the content and decrypt it
55
- ✓ should throw if the user is not logged in
56
- ✓ should throw if wrong type
57
- ✓ should throw if no entry is passed
58
- ✓ should throw if encrypted data are corrupted
59
- ✓ should throw if content has not the same id of the name
60
- ✓ should throw if parameters are missed
48
+ ✔ should encrypt a name and decrypt it
49
+ ✔ should encrypt a very long name and decrypt it
50
+ ✔ should encrypt name and content and decrypt it
51
+ ✔ should encrypt only the content and decrypt it
52
+ ✔ should decrypt content-only entry with the bound timestamp
53
+ ✔ should re-encrypt the content and decrypt it
54
+ ✔ should throw if the user is not logged in
55
+ ✔ should throw if wrong type
56
+ ✔ should throw if no entry is passed
57
+ ✔ should throw if encrypted data are corrupted
58
+ ✔ should throw if content has not the same id of the name
59
+ ✔ should throw if parameters are missed
61
60
  encryptData and decryptData
62
- ✓ should encrypt some data and decrypt it
63
- ✓ should throw trying to get box and sign secret keys
61
+ ✔ should encrypt some data and decrypt it
62
+ ✔ should throw trying to get box and sign secret keys
64
63
  preEncryptData and preDecryptData
65
- ✓ should encrypt some data with the derivedPassword and decrypt it
66
- ✓ should throw trying to get the master key
67
- generateSharedSecrets && recoverSharedSecrets
68
- ✓ should set up a second factor (43ms)
69
- ✓ should set up a second factor and then upgrade from derivationVersion 1 to 2
70
- ✓ should set up a second factor and a recovery code and remove them (40ms)
71
- ✓ should set up a second factor and a recovery code and remove the recovery code (43ms)
72
- ✓ should throw if wrong secret
73
- ✓ should throw if wrong authenticator
64
+ ✔ should encrypt some data with the derivedPassword and decrypt it
65
+ ✔ should throw trying to get the master key
74
66
  #readConf
75
- ✓ should encrypt some data with the derivedPassword and decrypt it
76
- ✓ should throw trying to get the master key
77
- ✓ should throw trying to get the master key
67
+ ✔ should encrypt some data with the derivedPassword and decrypt it
68
+ ✔ should throw trying to get the master key
69
+ ✔ should throw trying to get the master key
78
70
  #signMessage
79
- ✓ should sign a message and verify it
71
+ ✔ should sign a message and verify it
80
72
  #getPublicKey
81
- ✓ should sign a message and verify it
73
+ ✔ should sign a message and verify it
82
74
  #encrypt and decrypt shared data
83
- ✓ should get a shared ket
75
+ ✔ should get a shared ket
76
+
77
+ #config
78
+ ✔ all field should be correctly configured
84
79
 
85
80
  #ConfigUtils
86
- ✓ should check if a type is valid
87
- ✓ #setSecrez should configure a secrez environment
88
- ✓ #setAndGetDataset should set and get a secondary db
89
- ✓ #deleteDataset should delete a dataset path
90
- ✓ #getDatasetPath should get a dataset path
91
- ✓ #getEnv should return the environment
81
+ ✔ should check if a type is valid
82
+ ✔ #setSecrez should configure a secrez environment
83
+ ✔ #setAndGetDataset should set and get a secondary db
84
+ ✔ #deleteDataset should delete a dataset path
85
+ ✔ #getDatasetPath should get a dataset path
86
+ ✔ #getEnv should return the environment
87
+
88
+ #VaultPermissions
89
+ ✔ should create directories with mode 0o700
90
+ ✔ should chmod directories synchronously
91
+ ✔ should probe the keys directory before an account exists
92
+ ✔ should create files with mode 0o600
93
+ ✔ should detect secure vault permissions via probe
94
+ ✔ should secure legacy permissions on login
95
+ ✔ should skip securing when probe is already secure
92
96
 
93
97
 
94
- 60 passing (889ms)
98
+ 63 passing (502ms)
95
99
 
96
- -----------------|---------|----------|---------|---------|-------------------
97
- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
98
- -----------------|---------|----------|---------|---------|-------------------
99
- All files | 99.75 | 94.31 | 100 | 99.75 |
100
- src | 100 | 96.06 | 100 | 100 |
101
- Entry.js | 100 | 95.65 | 100 | 100 | 39
102
- Secrez.js | 100 | 96.94 | 100 | 100 | 154,319,442
103
- _Secrez.js | 100 | 91.66 | 100 | 100 | 14,226
104
- src/config | 98.57 | 84.84 | 100 | 98.57 |
105
- ConfigUtils.js | 98.48 | 84.84 | 100 | 98.48 | 137
106
- booleans.js | 100 | 100 | 100 | 100 |
107
- index.js | 100 | 100 | 100 | 100 |
108
- -----------------|---------|----------|---------|---------|-------------------
100
+ ----------------------|---------|----------|---------|---------|----------------------
101
+ File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
102
+ ----------------------|---------|----------|---------|---------|----------------------
103
+ All files | 98.3 | 91.57 | 98.76 | 98.3 |
104
+ src | 97.92 | 94.28 | 98.33 | 97.92 |
105
+ Entry.js | 100 | 95.65 | 100 | 100 | 39
106
+ Secrez.js | 100 | 97.72 | 100 | 100 | 226
107
+ _Secrez.js | 94.54 | 82.75 | 96 | 94.54 | 11,14-15,114,249-250
108
+ src/config | 99.19 | 84 | 100 | 99.19 |
109
+ ConfigUtils.js | 98.57 | 84.84 | 100 | 98.57 | 143
110
+ VaultPermissions.js | 100 | 82.35 | 100 | 100 | 53,79,102
111
+ booleans.js | 100 | 100 | 100 | 100 |
112
+ index.js | 100 | 100 | 100 | 100 |
113
+ ----------------------|---------|----------|---------|---------|----------------------
109
114
 
110
- > @secrez/core@1.0.6 posttest /Users/francescosullo/Projects/Secrez/secrez/packages/core
111
- > nyc check-coverage --statements 99 --branches 94 --functions 99 --lines 99
115
+ > @secrez/core@1.1.0 posttest /Users/francescosullo/Projects/Secrez/secrez/packages/core
116
+ > nyc check-coverage --statements 98 --branches 91 --functions 98 --lines 98
112
117
 
package/package.json CHANGED
@@ -1,22 +1,21 @@
1
1
  {
2
2
  "name": "@secrez/core",
3
- "version": "1.0.6",
3
+ "version": "1.1.0",
4
4
  "license": "MIT",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
8
8
  "dependencies": {
9
- "@secrez/crypto": "~1.0.5",
10
- "@secrez/utils": "~1.0.5",
9
+ "@secrez/crypto": "~1.1.0",
10
+ "@secrez/utils": "~1.1.0",
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.1",
15
+ "@secrez/test-helpers": "~2.0.3",
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": ">=20.0.0"
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 94 --functions 99 --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");
@@ -83,45 +84,10 @@ module.exports = function () {
83
84
  _secrez = new _Secrez(this);
84
85
  await _secrez.init(password, iterations);
85
86
  /* istanbul ignore if */
86
- if (!data.key && !data.keys) {
87
+ if (!data.key) {
87
88
  throw new Error("No valid data found");
88
89
  }
89
- if (data.key) {
90
- let masterKeyHash = await _secrez.signin(data);
91
- this.setMasterKeyHash(conf, masterKeyHash);
92
- } else {
93
- throw new Error("A second factor is required");
94
- }
95
- return 0;
96
- }
97
-
98
- async sharedSignin(authenticator, secret) {
99
- if (
100
- !this.config ||
101
- !this.config.keysPath ||
102
- !_secrez ||
103
- !_secrez.isInitiated()
104
- ) {
105
- throw new Error(
106
- "A standard sign in must be run before to initiate Secrez"
107
- );
108
- }
109
- const conf = await this.readConf();
110
- const data = conf.data;
111
- /* istanbul ignore if */
112
- if (!data.keys) {
113
- throw new Error("No second factor registered");
114
- }
115
- if (!data.keys[authenticator]) {
116
- throw new Error(
117
- `No second factor registered with the authenticator ${authenticator}`
118
- );
119
- }
120
- let masterKeyHash = await _secrez.sharedSignin(
121
- data,
122
- authenticator,
123
- secret
124
- );
90
+ let masterKeyHash = await _secrez.signin(data);
125
91
  this.setMasterKeyHash(conf, masterKeyHash);
126
92
  return 0;
127
93
  }
@@ -132,7 +98,10 @@ module.exports = function () {
132
98
 
133
99
  async signAndSave(data) {
134
100
  const conf = _secrez.signData(data);
135
- await fs.writeFile(this.config.keysPath, JSON.stringify(conf));
101
+ await VaultPermissions.writeFile(
102
+ this.config.keysPath,
103
+ JSON.stringify(conf)
104
+ );
136
105
  return conf;
137
106
  }
138
107
 
@@ -142,66 +111,13 @@ module.exports = function () {
142
111
  await ConfigUtils.putEnv(this.config, env);
143
112
  }
144
113
 
145
- generateSharedSecrets(secret) {
146
- return _secrez.generateSharedSecrets(secret);
147
- }
148
-
149
- async removeSharedSecret(authenticator, all) {
150
- let data = _secrez.conf.data;
151
- let code = 1;
152
- let removeAll = true;
153
- if (!all) {
154
- if (data.keys && data.keys[authenticator]) {
155
- delete data.keys[authenticator];
156
- }
157
- for (let authenticator in data.keys) {
158
- if (
159
- data.keys[authenticator].type === this.config.sharedKeys.FIDO2_KEY
160
- ) {
161
- removeAll = false;
162
- break;
163
- }
164
- }
165
- }
166
- if (removeAll) {
167
- code = 2;
168
- _secrez.restoreKey();
169
- }
170
- let conf = await this.signAndSave(data);
171
- _secrez.setConf(conf, DO_NOT_VERIFY);
172
- return code;
173
- }
174
-
175
- async saveSharedSecrets(sharedData) {
176
- let conf = await this.readConf();
177
- if (!conf.data.keys) {
178
- conf.data.keys = {};
179
- }
180
- let authenticator = sharedData.authenticator;
181
- delete sharedData.authenticator;
182
- if (sharedData.id) {
183
- sharedData.id = this.preEncryptData(sharedData.id);
184
- }
185
- if (sharedData.salt) {
186
- sharedData.salt = this.preEncryptData(sharedData.salt);
187
- }
188
- if (sharedData.credential) {
189
- sharedData.credential = this.preEncryptData(sharedData.credential);
190
- }
191
- conf.data.keys[authenticator] = sharedData;
192
- if (conf.data.key) {
193
- delete conf.data.key;
194
- }
195
- conf = await this.signAndSave(conf.data);
196
- _secrez.setConf(conf, DO_NOT_VERIFY);
197
- return conf;
198
- }
199
-
200
114
  getConf() {
115
+ this.assertLoggedIn();
201
116
  return _secrez.conf;
202
117
  }
203
118
 
204
119
  getPublicKey() {
120
+ this.assertLoggedIn();
205
121
  return (
206
122
  _secrez.conf.data.box.publicKey + "$" + _secrez.conf.data.sign.publicKey
207
123
  );
@@ -228,6 +144,7 @@ module.exports = function () {
228
144
  }
229
145
 
230
146
  signMessage(message) {
147
+ this.assertLoggedIn();
231
148
  return _secrez.signMessage(message);
232
149
  }
233
150
 
@@ -239,28 +156,6 @@ module.exports = function () {
239
156
  );
240
157
  }
241
158
 
242
- async getSecondFactorData(authenticator) {
243
- if (
244
- !this.config ||
245
- !this.config.keysPath ||
246
- !_secrez ||
247
- !_secrez.isInitiated()
248
- ) {
249
- throw new Error(
250
- "A standard sign in must be run before to initiate Secrez"
251
- );
252
- }
253
- const conf = await this.readConf();
254
- let data = conf.data.keys[authenticator];
255
- if (data) {
256
- return data;
257
- } else {
258
- throw new Error(
259
- `No registered data with the authenticator ${authenticator}`
260
- );
261
- }
262
- }
263
-
264
159
  setMasterKeyHash(conf, masterKeyHash) {
265
160
  /* istanbul ignore if */
266
161
  if (!_secrez.setConf(conf)) {
@@ -269,6 +164,12 @@ module.exports = function () {
269
164
  this.masterKeyHash = masterKeyHash;
270
165
  }
271
166
 
167
+ assertLoggedIn() {
168
+ if (!this.masterKeyHash) {
169
+ throw new Error("User not logged");
170
+ }
171
+ }
172
+
272
173
  preserveEntry(prev, next) {
273
174
  let options = prev.get();
274
175
  for (let o in options) {
@@ -280,26 +181,32 @@ module.exports = function () {
280
181
  }
281
182
 
282
183
  encryptData(data, urlSafe) {
184
+ this.assertLoggedIn();
283
185
  return _secrez.encrypt(data, urlSafe);
284
186
  }
285
187
 
286
188
  decryptData(encryptedData, urlSafe, returnUint8Array) {
189
+ this.assertLoggedIn();
287
190
  return _secrez.decrypt(encryptedData, urlSafe, returnUint8Array);
288
191
  }
289
192
 
290
193
  preEncryptData(data) {
194
+ this.assertLoggedIn();
291
195
  return _secrez.preEncrypt(data);
292
196
  }
293
197
 
294
198
  preDecryptData(encryptedData) {
199
+ this.assertLoggedIn();
295
200
  return _secrez.preDecrypt(encryptedData);
296
201
  }
297
202
 
298
203
  encryptSharedData(data, publicKey) {
204
+ this.assertLoggedIn();
299
205
  return _secrez.encryptShared(data, publicKey);
300
206
  }
301
207
 
302
208
  decryptSharedData(encryptedData, publicKey) {
209
+ this.assertLoggedIn();
303
210
  return _secrez.decryptShared(encryptedData, publicKey);
304
211
  }
305
212
 
@@ -310,64 +217,61 @@ module.exports = function () {
310
217
 
311
218
  const { type, name, content, preserveContent, id } = entry.get();
312
219
 
313
- if (this.masterKeyHash) {
314
- if (!ConfigUtils.isValidType(type)) {
315
- 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) + "$";
316
249
  }
317
250
 
318
- let ts =
319
- useTs && entry.ts
320
- ? entry.ts
321
- : Crypto.getTimestampWithMicroseconds().join(".");
322
- let encryptedEntry = new Entry({
323
- id,
324
- type,
325
- ts,
251
+ encryptedEntry.set({
252
+ encryptedName,
253
+ extraName,
326
254
  });
327
- if (name) {
328
- let encryptedName =
329
- type +
330
- _secrez.encrypt(
331
- JSON.stringify({
332
- i: id,
333
- t: ts,
334
- n: name,
335
- }),
336
- URL_SAFE
337
- );
338
- let extraName;
339
- if (encryptedName.length > 255) {
340
- extraName = encryptedName.substring(254);
341
- encryptedName = encryptedName.substring(0, 254) + "$";
342
- }
343
-
344
- encryptedEntry.set({
345
- encryptedName,
346
- extraName,
347
- });
348
255
 
349
- if (preserveContent) {
350
- encryptedEntry = this.preserveEntry(entry, encryptedEntry);
351
- }
256
+ if (preserveContent) {
257
+ encryptedEntry = this.preserveEntry(entry, encryptedEntry);
352
258
  }
353
- if (content) {
354
- encryptedEntry.set({
355
- encryptedContent: _secrez.encrypt(
356
- JSON.stringify({
357
- i: id,
358
- t: ts,
359
- c: content,
360
- })
361
- ),
362
- });
363
- if (preserveContent) {
364
- encryptedEntry = this.preserveEntry(entry, encryptedEntry);
365
- }
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);
366
272
  }
367
- return encryptedEntry;
368
- } else {
369
- throw new Error("User not logged");
370
273
  }
274
+ return encryptedEntry;
371
275
  }
372
276
 
373
277
  decryptEntry(encryptedEntry, urlSafe) {
@@ -384,87 +288,79 @@ module.exports = function () {
384
288
  nameTs,
385
289
  } = encryptedEntry.get();
386
290
 
387
- if (this.masterKeyHash) {
388
- try {
389
- if (encryptedName) {
390
- let data = encryptedName;
391
- if (extraName) {
392
- data = encryptedName.substring(0, 254) + extraName;
393
- }
394
- let type = parseInt(data[0]);
395
- let e = JSON.parse(_secrez.decrypt(data.substring(1), URL_SAFE));
396
- let id = e.i;
397
- let ts = e.t;
398
- let name = e.n;
399
- let content = "";
400
-
401
- // during the indexing internalFS reads only the names of the files
402
- if (encryptedContent) {
403
- let e = JSON.parse(_secrez.decrypt(encryptedContent));
404
- if (id !== e.i || ts !== e.t) {
405
- throw new Error("Data is corrupted");
406
- }
407
- 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");
408
310
  }
311
+ content = e.c;
312
+ }
409
313
 
410
- let decryptedEntry = new Entry({
411
- id,
412
- type,
413
- ts,
414
- name,
415
- content,
416
- });
417
-
418
- if (preserveContent) {
419
- decryptedEntry = this.preserveEntry(
420
- encryptedEntry,
421
- decryptedEntry
422
- );
423
- }
314
+ let decryptedEntry = new Entry({
315
+ id,
316
+ type,
317
+ ts,
318
+ name,
319
+ content,
320
+ });
424
321
 
425
- return decryptedEntry;
322
+ if (preserveContent) {
323
+ decryptedEntry = this.preserveEntry(encryptedEntry, decryptedEntry);
426
324
  }
427
325
 
428
- // when the encryptedName has been already decrypted and we need only the content
429
- if (encryptedContent) {
430
- let e = JSON.parse(_secrez.decrypt(encryptedContent));
326
+ return decryptedEntry;
327
+ }
431
328
 
432
- if ((nameId && e.i !== nameId) || (nameTs && e.t !== nameTs)) {
433
- throw new Error("Content is corrupted");
434
- }
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));
435
332
 
436
- let decryptedEntry = new Entry({
437
- id: e.i,
438
- ts: e.i,
439
- content: e.c,
440
- });
441
-
442
- if (preserveContent) {
443
- decryptedEntry = this.preserveEntry(
444
- encryptedEntry,
445
- decryptedEntry
446
- );
447
- }
448
-
449
- return decryptedEntry;
333
+ if ((nameId && e.i !== nameId) || (nameTs && e.t !== nameTs)) {
334
+ throw new Error("Content is corrupted");
450
335
  }
451
- } catch (e) {
452
- if (e.message === "Data is corrupted") {
453
- throw e;
454
- } else if (e.message === "Content is corrupted") {
455
- 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);
456
345
  }
457
- throw new Error("Fatal error during decryption");
458
- }
459
346
 
460
- throw new Error("Missing parameters");
461
- } else {
462
- 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");
463
356
  }
357
+
358
+ throw new Error("Missing parameters");
464
359
  }
465
360
 
466
361
  signout() {
467
362
  if (this.masterKeyHash) {
363
+ _secrez.clearSecrets();
468
364
  delete this.masterKeyHash;
469
365
  _secrez = undefined;
470
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: {},
@@ -122,11 +135,6 @@ module.exports = function () {
122
135
  return data;
123
136
  }
124
137
 
125
- async restoreKey() {
126
- delete this.conf.data.keys;
127
- this.conf.data.key = this.preEncrypt(__.masterKey);
128
- }
129
-
130
138
  setConf(conf, doNotVerify) {
131
139
  /* istanbul ignore if */
132
140
  if (!doNotVerify && !this.verifySavedData(conf)) {
@@ -200,50 +208,12 @@ module.exports = function () {
200
208
  }
201
209
  }
202
210
 
203
- async sharedSignin(data, authenticator, secret) {
204
- let key = data.keys[authenticator];
205
- try {
206
- let masterKey = this.recoverSharedSecrets(key.parts, secret);
207
- /* istanbul ignore if */
208
- if (!utils.secureCompare(Crypto.b64Hash(masterKey), data.hash)) {
209
- throw new Error("Hash on file does not match the master key");
210
- }
211
- __.masterKey = masterKey;
212
- __.masterKeyArray = Crypto.bs64.decode(__.masterKey);
213
- __.masterKeyHash = data.hash;
214
- __.boxPublicKey = Crypto.bs64.decode(data.box.secretKey);
215
- __.boxPrivateKey = __.decrypt(data.box.secretKey, RETURN_UINT8_ARRAY);
216
- __.signPublicKey = Crypto.bs64.decode(data.sign.secretKey);
217
- __.signPrivateKey = __.decrypt(data.sign.secretKey, RETURN_UINT8_ARRAY);
218
- __.encryptedBoxPrivateKey = data.box.secretKey;
219
- __.encryptedSignPrivateKey = data.sign.secretKey;
220
- return data.hash;
221
- } catch (e) {
222
- throw new Error("Wrong data/secret");
223
- }
224
- }
225
-
226
211
  static async derivePassword(password = __.password, iterations) {
227
212
  password = Crypto.SHA3(password);
228
213
  let salt = Crypto.SHA3(password + iterations.toString());
229
214
  return bs64.encode(Crypto.deriveKey(password, salt, iterations, 32));
230
215
  }
231
216
 
232
- generateSharedSecrets(secret) {
233
- let parts = Crypto.splitSecret(__.masterKey, 2, 2);
234
- parts[1] = this.preEncrypt(parts["1"]);
235
- parts[2] = Crypto.encrypt(parts["2"], Crypto.SHA3(secret));
236
- return parts;
237
- }
238
-
239
- recoverSharedSecrets(parts, secret) {
240
- parts = {
241
- 1: __.preDecrypt(parts[1], RETURN_UINT8_ARRAY),
242
- 2: Crypto.decrypt(parts[2], Crypto.SHA3(secret), RETURN_UINT8_ARRAY),
243
- };
244
- return Crypto.joinSecret(parts);
245
- }
246
-
247
217
  signData(data) {
248
218
  const signature = this.signMessage(JSON.stringify(this.sortObj(data)));
249
219
  const conf = {
@@ -263,6 +233,36 @@ module.exports = function () {
263
233
  }
264
234
  return sortedData;
265
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
+ }
266
266
  }
267
267
 
268
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;
@@ -21,11 +21,6 @@ const config = {
21
21
  RECOVERED: "REC",
22
22
  },
23
23
 
24
- sharedKeys: {
25
- FIDO2_KEY: 1,
26
- RECOVERY_CODE: 2,
27
- },
28
-
29
24
  secrez: {},
30
25
 
31
26
  VERSION: 3,
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
  };