-
Notifications
You must be signed in to change notification settings - Fork 1
/
cipherToken.js
226 lines (198 loc) · 6.34 KB
/
cipherToken.js
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
var crypto = require('crypto');
var ERRORS = {
settingsRequired: {
err: 'Settings required',
des: 'Settings must have at least cipherKey and firmKey'
},
cipherKeyRequired: {
err: 'CipherKey required',
des: 'CipherKey parameter is mandatory'
},
firmKeyRequired: {
err: 'FirmKey required',
des: 'FirmKey parameter is mandatory'
},
badCredentials: {
err: 'Bad credentials',
des: 'Credentials are not valid'
},
badToken: {
err: 'Bad token',
des: 'Token is not valid'
},
serializationError: {
err: 'Serialization error',
des: 'Error during data serialization'
},
unserializationError: {
err: 'Unserialization error',
des: 'Error during data unserialization'
}
};
const DEFAULT_SETTINGS = {
cipherAlgorithm: 'aes-256-cbc',
hmacAlgorithm: 'md5',
hmacDigestEncoding: 'hex',
plainEncoding: 'utf8',
tokenEncoding: 'base64',
tokenExpirationMinutes: 90,
enableSessionId: false
};
function enrichSettings(settings, ckb){
if (typeof settings === 'undefined' || isEmpty(settings)){
return ckb(ERRORS.settingsRequired);
} else if (!settings.hasOwnProperty('cipherKey')) {
return ckb(ERRORS.cipherKeyRequired);
} else if (!settings.hasOwnProperty('firmKey')) {
return ckb(ERRORS.firmKeyRequired);
}
for (var p in DEFAULT_SETTINGS){
if (settings.hasOwnProperty(p) == false) {
settings[p] = DEFAULT_SETTINGS[p];
}
}
ckb(null, settings);
}
function isEmpty(obj) {
return !Object.keys(obj).length > 0;
}
function serialize(data, cbk) {
var res;
try {
res = JSON.stringify(data);
} catch (e) {
return cbk(ERRORS.serializationError);
}
cbk(null, res);
}
function unserialize(data, cbk) {
var res;
try {
res = JSON.parse(data);
} catch (e) {
return cbk(ERRORS.unserializationError);
}
cbk(null,res);
}
function standarizeToken(token){
return token.
replace(/\+/g, '-'). // Convert '+' to '-'
replace(/\//g, '_'). // Convert '/' to '_'
replace(/=+$/, '') // Remove ending '='
;
}
function firmToken(settings, userId, expiresAtTimestamp, data, cbk) {
var dataToSerialize = {
'userId': userId,
'expiresAtTimestamp': expiresAtTimestamp,
'data': data
};
serialize(dataToSerialize, function(err, notFirmedToken){
if(err){
return cbk(err, null);
}
var firmedToken = crypto.createHmac(settings.hmacAlgorithm, settings.firmKey)
.update(notFirmedToken)
.digest(settings.hmacDigestEncoding);
cbk(null, firmedToken);
});
}
function checkTokenFirm(settings, cipheredToken, cbk){
decipherToken(settings, cipheredToken, function(err, tokenSet){
firmToken(settings, tokenSet.userId, tokenSet.expiresAtTimestamp, tokenSet.data, function(err, firm){
if(err){
return cbk(err, null);
}
cbk(null, firm === tokenSet.firm);
});
});
}
function decipherToken(settings, cipheredToken, cbk){
var decipher = crypto.createDecipher(settings.cipherAlgorithm, settings.cipherKey);
var decodedToken = decipher.update(cipheredToken, settings.tokenEncoding, settings.plainEncoding);
if (!decodedToken){
return cbk(ERRORS.badToken, null);
}
try{
decodedToken = (decodedToken + decipher.final(settings.plainEncoding));
}catch (err) {
return cbk(null, ERRORS.badCredentials)
}
unserialize(decodedToken, function(err, decodedToken){
if(err){
return cbk(err, null);
}
cbk(null, decodedToken);
});
}
function createToken(settings, userId, sessionId, data, cbk) {
enrichSettings(settings, function(err, settings){
if(err){
return cbk(err, null);
}
var expiresAtTimestamp = new Date().getTime() + settings.tokenExpirationMinutes*60*1000;
data = data || {};
firmToken(settings, userId, expiresAtTimestamp, data, function(err, firm){
if(err){
return cbk(err, null);
}
var cipher = crypto.createCipher(settings.cipherAlgorithm, settings.cipherKey);
var tokenSet = {
userId: userId,
expiresAtTimestamp: expiresAtTimestamp,
data: data,
firm: firm
};
if (settings.enableSessionId) {
if (sessionId == null) {
tokenSet.sessionId = userId + '-' + crypto.pseudoRandomBytes(12).toString('hex');
} else {
tokenSet.sessionId = sessionId;
}
}
serialize(tokenSet, function(err, notFirmedToken){
if(err){
return cbk(err, null);
}
var encodedData = cipher.update(notFirmedToken, settings.plainEncoding, settings.tokenEncoding);
cbk(null, standarizeToken(encodedData + cipher.final(settings.tokenEncoding)));
});
});
});
}
function decodeToken(settings, cipheredToken, cbk){
enrichSettings(settings, function(err, settings){
if (err) {
return cbk(err, null);
}
decipherToken(settings, cipheredToken, function(err, token){
if(err){
return cbk(err, null);
}
checkTokenFirm(settings, cipheredToken, function(err, isValid){
if(err){
return cbk(err, null);
}
if(!isValid) {
return cbk(ERRORS.badCredentials, null);
}
var tokenSet = {
userId: token.userId,
expiresAtTimestamp: token.expiresAtTimestamp,
data: token.data
};
if (settings.enableSessionId) {
tokenSet.sessionId = token.sessionId
}
cbk(null, tokenSet);
});
});
});
}
module.exports = {
encode: createToken,
decode: decodeToken,
getTokenSet: decodeToken,
createToken: createToken
};
// TODO: Use jwt instead of crypto for token encoding