This repository was archived by the owner on Aug 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
478 lines (442 loc) · 13.9 KB
/
index.js
File metadata and controls
478 lines (442 loc) · 13.9 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
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
/**
* node-ms-passport
*
* MIT License
*
* Copyright (c) 2020 - 2021 MarkusJx
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
const fs = require('fs');
const path = require('path');
const passport_native = loadNativeModule();
const dummies = require('./dummies');
let csModuleLocation = path.join(__dirname, 'bin/');
// Set the location for the C# dll
if (passport_native) {
passport_native.setCSharpDllLocation(csModuleLocation);
}
function isWindows10() {
try {
const version = require('child_process')
.execSync('ver', {encoding: 'utf-8'})
.toString()
.trim()
.split('[')[1]
.split(' ')[1]
.split('.')[0];
return Number(version) >= 10;
} catch (_) {
return false;
}
}
function loadNativeModule() {
const p = path.join(__dirname, 'bin', 'passport.node');
function checkPlatform() {
if (process.platform === 'win32' && isWindows10()) {
throw new Error("The platform is windows 10 but the native module could not be found");
}
return null;
}
if (fs.existsSync(p) && process.platform === 'win32') {
try {
return require(p);
} catch (e) {
return checkPlatform();
}
} else {
return checkPlatform();
}
}
/**
* A passport error
*/
class PassportError extends Error {
/**
* Create a passport error
*
* @param {string} message the error message
* @param {number} code the error code
*/
constructor(message, code) {
super(message);
this.name = "PassportError";
this.code = code;
if (typeof code !== 'number') {
throw new Error("Parameter 'code' must be typeof 'number'");
} else if (typeof message !== 'string') {
throw new Error("Parameter 'message' must be typeof 'string'");
}
}
/**
* Get the error code
*
* @returns {number} the error code
*/
getCode() {
return this.code;
}
}
/**
* Rethrow an error
*
* @param {Error} e the error to rethrow
*/
function rethrowError(e) {
const regex = /^.+#-?\d{1,2}$/g;
if (regex.test(e.message)) {
const parts = e.message.split('#');
throw new PassportError(parts[0], Number(parts[1]));
} else {
throw e;
}
}
const PassportErrorCode = {
ERR_ANY: -1,
ERR_UNKNOWN: 1,
ERR_MISSING_PIN: 2,
ERR_USER_CANCELLED: 3,
ERR_USER_PREFERS_PASSWORD: 4,
ERR_ACCOUNT_NOT_FOUND: 5,
ERR_SIGN_OP_FAILED: 6,
ERR_KEY_ALREADY_DELETED: 7,
ERR_ACCESS_DENIED: 8
};
const PublicKeyEncoding = {
X509SubjectPublicKeyInfo: "X509SubjectPublicKeyInfo",
Pkcs1RsaPublicKey: "Pkcs1RsaPublicKey",
BCryptPublicKey: "BCryptPublicKey",
Capi1PublicKey: "Capi1PublicKey",
BCryptEccFullPublicKey: "BCryptEccFullPublicKey"
};
const VerificationResult = {
Verified: 0,
DeviceNotPresent: 1,
NotConfiguredForUser: 2,
DisabledByPolicy: 3,
DeviceBusy: 4,
RetriesExhausted: 5,
Canceled: 6
}
/**
* Microsoft passport for node js
*/
class Passport {
/**
* Create a passport instance
*
* @param {string} accountId the id of the passport account
*/
constructor(accountId) {
if (typeof accountId !== 'string') {
throw new Error("Parameter 'accountId' must be typeof 'string'");
} else if (accountId.length === 0) {
throw new Error("Parameter 'accountId' must not be empty");
}
this.accountExists = this.constructor.passportAccountExists(accountId);
Object.defineProperty(this, 'accountId', {
value: accountId,
enumerable: true,
configurable: true,
writable: false
});
}
/**
* Create a microsoft passport key asynchronously
*
* @returns {Promise<void>}
*/
async createPassportKey() {
try {
await passport_native.createPassportKey(this.accountId);
this.accountExists = true;
} catch (e) {
rethrowError(e);
}
}
/**
* Sign a challenge
*
* @param {string} challenge the challenge to sign
* @returns {Promise<string>} the signature as a hex string
*/
async passportSignHex(challenge) {
if (!this.accountExists)
throw new PassportError("The passport account does not exist", errorCodes.ERR_ACCOUNT_NOT_FOUND);
try {
return await passport_native.passportSignHex(this.accountId, challenge);
} catch (e) {
rethrowError(e);
}
}
/**
* Sign a challenge
*
* @param {Buffer} challenge the challenge to sign
* @returns {Promise<Buffer>} the signature in a buffer
*/
async passportSign(challenge) {
if (!this.accountExists)
throw new PassportError("The passport account does not exist", errorCodes.ERR_ACCOUNT_NOT_FOUND);
try {
return await passport_native.passportSign(this.accountId, challenge);
} catch (e) {
rethrowError(e);
}
}
/**
* Delete a passport account
*
* @returns {Promise<void>}
*/
async deletePassportAccount() {
if (!this.accountExists)
throw new PassportError("The passport account does not exist", errorCodes.ERR_ACCOUNT_NOT_FOUND);
try {
await passport_native.deletePassportAccount(this.accountId);
} catch (e) {
rethrowError(e);
}
}
/**
* Get the public key
*
* @returns {Promise<string>} the public key as a hex string
*/
async getPublicKeyHex(encoding = null) {
if (!this.accountExists)
throw new PassportError("The passport account does not exist", errorCodes.ERR_ACCOUNT_NOT_FOUND);
try {
return await passport_native.getPublicKeyHex(this.accountId, encoding);
} catch (e) {
rethrowError(e);
}
}
/**
* Get the public key
*
* @returns {Promise<Buffer>} the public key in a buffer
*/
async getPublicKey(encoding = null) {
if (!this.accountExists)
throw new PassportError("The passport account does not exist", errorCodes.ERR_ACCOUNT_NOT_FOUND);
try {
return await passport_native.getPublicKey(this.accountId, encoding);
} catch (e) {
rethrowError(e);
}
}
/**
* Get a SHA-256 hash of the public key
*
* @returns {Promise<string>} the hashed public key as a hex string
*/
async getPublicKeyHashHex() {
if (!this.accountExists)
throw new PassportError("The passport account does not exist", errorCodes.ERR_ACCOUNT_NOT_FOUND);
try {
return await passport_native.getPublicKeyHashHex(this.accountId);
} catch (e) {
rethrowError(e);
}
}
/**
* Get a SHA-256 hash of the public key
*
* @returns {Promise<Buffer>} the hashed public key in a buffer
*/
async getPublicKeyHash() {
if (!this.accountExists)
throw new PassportError("The passport account does not exist", errorCodes.ERR_ACCOUNT_NOT_FOUND);
try {
return await passport_native.getPublicKeyHash(this.accountId);
} catch (e) {
rethrowError(e);
}
}
static requestVerification(message) {
try {
return passport_native.requestVerification(message);
} catch (e) {
rethrowError(e);
}
}
/**
* Check if a passport account exists
*
* @param {string} accountId the id of the account to check
* @returns {boolean} true, if the account with the given id exists
*/
static passportAccountExists(accountId) {
try {
return passport_native.passportAccountExists(accountId);
} catch (e) {
rethrowError(e);
}
}
/**
* Check if ms passport is available on this machine
*
* @returns {boolean} true if passport is available
*/
static passportAvailable() {
if (!isWindows10()) return false;
try {
return passport_native.passportAvailable();
} catch (e) {
rethrowError(e);
}
}
/**
* Verify a challenge signed by passport
*
* @param {string} challenge the challenge used
* @param {string} signature the signature returned
* @param {string} publicKey the public key of the application
* @returns {boolean} true, if the signature matches
*/
static async verifySignatureHex(challenge, signature, publicKey) {
try {
return await passport_native.verifySignatureHex(challenge, signature, publicKey);
} catch (e) {
rethrowError(e);
}
}
/**
* Verify a challenge signed by passport
*
* @param {Buffer} challenge the challenge used
* @param {Buffer} signature the signature returned
* @param {Buffer} publicKey the public key of the application
* @returns {boolean} true, if the signature matches
*/
static async verifySignature(challenge, signature, publicKey) {
try {
return await passport_native.verifySignature(challenge, signature, publicKey);
} catch (e) {
rethrowError(e);
}
}
}
/**
* Password encryption using windows APIs
*/
const passwords = {
/**
* Encrypt a password using CredProtect. Throws on error
*
* @param {string} data the data to encrypt
* @returns {Promise<string>} the result as hex string or null if unsuccessful
*/
encryptHex: async function (data) {
return await passport_native.encryptPasswordHex(data);
},
/**
* Encrypt a password using CredProtect. Throws on error
*
* @param {string} data the data to encrypt
* @returns {Promise<Buffer>} the result in a buffer or null if unsuccessful
*/
encrypt: async function (data) {
return await passport_native.encryptPassword(data);
},
/**
* Decrypt a password using CredUnprotect. Throws on error
*
* @param {string} data the data to decrypt as hex string
* @returns {Promise<string>} the result as string or null if unsuccessful
*/
decryptHex: async function (data) {
return await passport_native.decryptPasswordHex(data);
},
/**
* Decrypt a password using CredUnprotect. Throws on error
*
* @param {Buffer} data the data to decrypt as hex string
* @returns {Promise<string>} the result as string or null if unsuccessful
*/
decrypt: async function (data) {
return await passport_native.decryptPassword(data);
},
/**
* Check if data was encrypted using CredProtect. Throws an error on error
*
* @param {string} data the data as hex string
* @returns {Promise<boolean>} if the password is encrypted
*/
isEncryptedHex: async function (data) {
return await passport_native.passwordEncryptedHex(data);
},
/**
* Check if data was encrypted using CredProtect. Throws an error on error
*
* @param {Buffer} data the data in a buffer
* @returns {Promise<boolean>} if the password is encrypted
*/
isEncrypted: async function (data) {
return await passport_native.passwordEncrypted(data);
}
}
class PassportModule {
static set csModuleLocation(location) {
if (PassportModule.available()) {
passport_native.setCSharpDllLocation(location);
csModuleLocation = location;
} else {
dummies.dummy();
}
}
static get csModuleLocation() {
if (PassportModule.available()) {
return csModuleLocation;
} else {
dummies.dummy();
}
}
static available() {
return !!passport_native;
}
static electronAsarFix() {
if (!PassportModule.available()) return;
const regex = /[\/\\]app\.asar[\/\\]/g;
if (regex.test(PassportModule.csModuleLocation)) {
PassportModule.csModuleLocation = PassportModule.csModuleLocation
.replace(regex, `${path.sep}app.asar.unpacked${path.sep}`);
}
}
}
module.exports = {
PassportError: passport_native ? PassportError : dummies.PassportError,
PassportErrorCode: PassportErrorCode,
PublicKeyEncoding: PublicKeyEncoding,
VerificationResult: VerificationResult,
Passport: passport_native ? Passport : dummies.Passport,
CredentialStore: passport_native ? passport_native.CredentialStore : dummies.CredentialStore,
Credential: passport_native ? passport_native.Credential : dummies.Credential,
passwords: passport_native ? passwords : dummies.passwords,
PassportModule: PassportModule,
/**
* Passport C++ library variables
*/
passport_lib: {
include_dir: path.join(__dirname, 'cpp_src'),
library_dir: path.join(__dirname, 'lib'),
library: path.join(__dirname, 'lib', 'NodeMsPassport.lib')
}
}