-
Notifications
You must be signed in to change notification settings - Fork 73.1k
Expand file tree
/
Copy pathenclave.js
More file actions
81 lines (65 loc) · 2.24 KB
/
enclave.js
File metadata and controls
81 lines (65 loc) · 2.24 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
'use strict;'
const path = require('path');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const fs = require('fs');
// this is a class for holding potentially sensitive data in the app
// the class also implement functions to use the data, so the data is not shared outside the class
const init = function init () {
const enclave = {};
const secrets = {};
const apiKey = Symbol('api-secret');
const apiKeySHA1 = Symbol('api-secretSHA1');
const apiKeySHA512 = Symbol('api-secretSHA512');
const jwtKey = Symbol('jwtkey');
let apiKeySet = false;
function readKey (filename) {
let filePath = path.resolve(__dirname + '/../../node_modules/.cache/_ns_cache/' + filename);
if (fs.existsSync(filePath)) {
return fs.readFileSync(filePath).toString().trim();
}
console.error('Key file ', filePath, 'not found');
return null;
}
secrets[jwtKey] = readKey('randomString');
function genHash(data, algorihtm) {
const hash = crypto.createHash(algorihtm);
data = hash.update(data, 'utf-8');
return data.digest('hex').toLowerCase();
}
enclave.setApiKey = function setApiKey (keyValue) {
if (keyValue.length < 12) return;
apiKeySet = true;
secrets[apiKey] = keyValue;
secrets[apiKeySHA1] = genHash(keyValue,'sha1');
secrets[apiKeySHA512] = genHash(keyValue,'sha512');
}
enclave.isApiKeySet = function isApiKeySet () {
return apiKeySet;
}
enclave.isApiKey = function isApiKey (keyValue) {
return keyValue.toLowerCase() == secrets[apiKeySHA1] || keyValue == secrets[apiKeySHA512];
}
enclave.setJWTKey = function setJWTKey (keyValue) {
secrets[jwtKey] = keyValue;
}
enclave.signJWT = function signJWT(token, lifetime) {
const lt = lifetime ? lifetime : '8h';
return jwt.sign(token, secrets[jwtKey], { expiresIn: lt });
}
enclave.verifyJWT = function verifyJWT(tokenString) {
try {
return jwt.verify(tokenString, secrets[jwtKey]);
} catch(err) {
return null;
}
}
enclave.getSubjectHash = function getSubjectHash(id) {
var shasum = crypto.createHash('sha1');
shasum.update(secrets[apiKeySHA1]);
shasum.update(id);
return shasum.digest('hex').toLowerCase();
}
return enclave;
}
module.exports = init;