-
Notifications
You must be signed in to change notification settings - Fork 2
/
store.js
268 lines (220 loc) · 6.91 KB
/
store.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
'use strict'
/**
* Node modules.
*/
var fs = require('fs')
, path = require('path')
/**
* NPM modules.
*/
var crc = require('crc')
, lineReader = require('line-reader')
, Promise = require('bluebird')
, walk = require('walk')
, unorm = require('unorm')
/**
* Local modules.
*/
var logger = require('./logger')
/**
* Singleton Store.
*/
var Store = function Store() {
if (Store.prototype.store) {
return Store.prototype.store
}
Store.prototype.store = this
Store.prototype.store.init()
}
/**
* Initialize the store: perform some sanity checks.
*/
Store.prototype.init = function init() {
// make sure passwordDir points to a directory
this.passwordDir = process.env.npm_config_password_store_dir ||
process.env.PASSWORD_STORE_DIR ||
process.env.npm_package_config_password_store_dir
if (!this.passwordDir) {
throw new Error('No password store directory specified.')
}
// expand tilde to $HOME
if (this.passwordDir.split(path.sep)[0] == '~') {
this.passwordDir = path.join(process.env.HOME,
this.passwordDir.split(path.sep).slice(1).join(path.sep))
}
if (!path.isAbsolute(this.passwordDir)) {
this.passwordDir = path.resolve(this.passwordDir)
}
var stats = fs.lstatSync(this.passwordDir)
if (!stats.isDirectory()) {
throw new Error("'" + this.passwordDir + "' is not a directory.")
}
// make sure passwordDir is accessible
fs.accessSync(this.passwordDir, fs.R_OK | fs.X_OK)
// make sure passwordDir/.gpg-id is accessible
this.keyFile = path.join(this.passwordDir, '.gpg-id')
fs.accessSync(this.keyFile, fs.R_OK)
logger.info('Reading from "' + this.passwordDir + '".')
// log current available keys
var data = fs.readFileSync(this.keyFile, 'ascii')
var keyIds = data.trim().split('\n')
logger.info('Store keys: ' + keyIds.join(', ') + '.')
}
/**
* Build an ascii armored pgp message.
*/
Store.prototype.buildPgpMessage = function buildPgpMessage(data) {
var pgpMessage = ''
pgpMessage += '-----BEGIN PGP MESSAGE-----\n\n'
pgpMessage += data.toString('base64') + '\n'
pgpMessage += '=' + this.getChecksum(data) + '\n'
pgpMessage += '-----END PGP MESSAGE-----'
return pgpMessage
}
/**
* Calculate the checksum for given data.
*/
Store.prototype.getChecksum = function getChecksum(data) {
var hash = crc.crc24(data)
return new Buffer('' +
String.fromCharCode(hash >> 16) +
String.fromCharCode((hash >> 8) & 0xFF) +
String.fromCharCode(hash & 0xFF),
'ascii').toString('base64')
}
/**
* Get the file data from a secret's file (.gpg).
*/
Store.prototype.getGpg = function getGpg(relPath, username, done) {
var secretFilename = username + '.gpg'
var secretRelPath = path.join(relPath, secretFilename)
var secretPath = path.resolve(path.join(this.passwordDir, secretRelPath))
if (path.relative(this.passwordDir, secretPath).substr(0, 2) === '..') {
logger.debug('Requested secret points to a file located outside the ' +
'password store.')
var e = new Error('No such secret exists.')
e.status = 400
throw e
}
if (!fs.existsSync(secretPath)) {
logger.debug('Requested secret points to a file that does not exist: "' +
secretPath + '".')
var e = new Error('No such secret exists.')
e.status = 400
throw e
}
var stats = fs.lstatSync(secretPath)
if (!stats.isFile()) {
logger.debug('Requested secret points to a directory: "' +
secretPath + '".')
var e = new Error('No such secret exists.')
e.status = 400
throw e
}
// make sure secretPath can be read
try {
fs.accessSync(secretPath, fs.R_OK)
} catch (ex) {
logger.error('Requested secret could be read: "' + secretPath + '".')
ex.status = 503
throw ex
}
try {
var data = fs.readFileSync(secretPath)
try {
done(null, data)
} catch (ex) {
logger.error('Requested secret could be read: "' + secretPath + '".')
ex.status = 500
done(ex)
}
} catch (ex) {
logger.error('Requested secret could be read: "' + secretPath + '".')
ex.status = 500
done(ex)
}
}
/**
* Get a list of secrets currently on disk.
*/
Store.prototype.getList = function getList(done) {
var passwordDir = this.passwordDir
var secrets = []
var walker = walk.walk(passwordDir, {
followLinks: false
})
logger.debug('Building list of secrets.')
walker.on('file', function onFile(root, fileStats, next) {
if (root === passwordDir) {
// skip everything in the root directory
logger.debug('Skipping from "./": "' + fileStats.name + '".')
next()
} else {
var domain = path.basename(root)
var extension = path.extname(fileStats.name)
var username = path.basename(fileStats.name, extension)
var relPath = path.relative(passwordDir, root)
if (extension == '.gpg') {
logger.debug('Add from "./' + relPath + '": "' + domain + '/' +
username + '".')
// add file to secrets
secrets.push(
{ domain: domain
, path: relPath
, username: username
, username_normalized: unorm.nfkd(username)
.replace(/[^\u0000-\u00FF]/g, '')
})
} else {
logger.debug('Skip from "./' + relPath + '": "' +
fileStats.name + '".')
}
next()
}
})
walker.on('end', function onFinished() {
// sort case insensitive and accent insensitive
secrets = secrets.sort(function compareSecret(secret1, secret2) {
return (secret1.domain.localeCompare(secret2.domain) ||
secret1.username_normalized
.localeCompare(secret2.username_normalized))
})
done(secrets)
})
}
Store.prototype.validateKey = function validateKey(longKeyId, done) {
if (longKeyId.length != 16) {
var e = new Error('Please provide a proper keyId.')
e.status = 400
throw e
} else {
// validate variations also
var longKeyId0 = '0' + longKeyId
var longKeyId0x = '0x' + longKeyId
var shortKeyId = longKeyId.substr(-8)
var shortKeyId0 = '0' + shortKeyId
var shortKeyId0x = '0x' + shortKeyId
var keys = [ longKeyId
, longKeyId0
, longKeyId0x
, shortKeyId
, shortKeyId0
, shortKeyId0x
]
logger.debug('Validating key from request and all its variations: "' +
keys.slice(1).join(', ') + '".')
var isAuthenticated = false
var eachLine = Promise.promisify(lineReader.eachLine)
eachLine(this.keyFile, function handleLine(line) {
isAuthenticated = (keys.indexOf(line) !== -1)
logger.debug('Key "' + line + '" ' +
(isAuthenticated ? 'is a match' : 'is not a match'))
return !isAuthenticated
}).then(function onFulfilled() {
done(isAuthenticated)
}, function onRejected(reason) {
throw new Error(reason)
})
}
}
module.exports = new Store()