-
Notifications
You must be signed in to change notification settings - Fork 402
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(2fa): implementing backend code for TOTP with recovery codes
- Loading branch information
1 parent
cdfc5c4
commit 223c83f
Showing
20 changed files
with
735 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
14 changes: 14 additions & 0 deletions
14
infra/migrations/1715307937886_alter-table-users-add-mfa-totp.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
exports.up = (pgm) => { | ||
pgm.addColumns('users', { | ||
totp_secret: { | ||
type: 'varchar(128)', | ||
notNull: false, | ||
}, | ||
totp_recovery_codes: { | ||
type: 'varchar(472)', | ||
notNull: false, | ||
}, | ||
}); | ||
}; | ||
|
||
exports.down = false; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
import crypto from 'crypto'; | ||
import * as OTPAuth from 'otpauth'; | ||
|
||
import user from 'models/user'; | ||
|
||
const defaultTOTPConfigurations = { | ||
issuer: 'TabNews', | ||
algorithm: 'SHA1', | ||
digits: 6, | ||
}; | ||
|
||
function createSecret() { | ||
return new OTPAuth.Secret({ size: 20 }).base32; | ||
} | ||
|
||
function createTotp(secret, username) { | ||
if (!secret) { | ||
secret = createSecret(); | ||
} | ||
return new OTPAuth.TOTP({ ...defaultTOTPConfigurations, secret, label: username }); | ||
} | ||
|
||
const cryptoConfigurations = { | ||
algorithm: process.env.TOTP_ENCRYPTION_METHOD, | ||
key: crypto.createHash('sha512').update(process.env.TOTP_SECRET_KEY).digest('hex').substring(0, 32), | ||
encryptionIV: crypto.createHash('sha512').update(process.env.TOTP_SECRET_IV).digest('hex').substring(0, 16), | ||
}; | ||
|
||
function encryptData(data) { | ||
const cipher = crypto.createCipheriv( | ||
cryptoConfigurations.algorithm, | ||
cryptoConfigurations.key, | ||
cryptoConfigurations.encryptionIV, | ||
); | ||
return Buffer.from(cipher.update(data, 'utf8', 'hex') + cipher.final('hex')).toString('base64'); | ||
} | ||
|
||
function decryptData(encryptedData) { | ||
const buff = Buffer.from(encryptedData, 'base64'); | ||
const decipher = crypto.createDecipheriv( | ||
cryptoConfigurations.algorithm, | ||
cryptoConfigurations.key, | ||
cryptoConfigurations.encryptionIV, | ||
); | ||
return decipher.update(buff.toString('utf8'), 'hex', 'utf8') + decipher.final('utf8'); | ||
} | ||
|
||
function createRecoveryCodes() { | ||
const RECOVERY_CODES_LENTGH = 8; | ||
const RECOVERY_CODES_AMOUNT = 10; | ||
|
||
function makeCode(length) { | ||
let code = ''; | ||
const characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; | ||
const charactersLength = characters.length; | ||
let counter = 0; | ||
while (counter < length) { | ||
code += characters.charAt(Math.floor(Math.random() * charactersLength)); | ||
counter += 1; | ||
} | ||
return code; | ||
} | ||
|
||
const recoveryCodesObject = {}; | ||
|
||
for (let i = 0; i < RECOVERY_CODES_AMOUNT; i++) { | ||
const newCode = makeCode(RECOVERY_CODES_LENTGH); | ||
recoveryCodesObject[newCode] = true; | ||
} | ||
|
||
return JSON.stringify(recoveryCodesObject); | ||
} | ||
|
||
function validateTotp(userSecret, token) { | ||
const userTOTP = createTotp(userSecret); | ||
return userTOTP.validate({ token }) !== null; | ||
} | ||
|
||
async function validateAndMarkRecoveryCode(targetUser, recoveryCode) { | ||
const recoveryCodes = JSON.parse(decryptData(targetUser.totp_recovery_codes)); | ||
|
||
if (recoveryCodes[recoveryCode]) { | ||
recoveryCodes[recoveryCode] = false; | ||
|
||
await user.update(targetUser.username, { totp_recovery_codes: encryptData(JSON.stringify(recoveryCodes)) }); | ||
|
||
return true; | ||
} | ||
|
||
return false; | ||
} | ||
|
||
export default Object.freeze({ | ||
createTotp, | ||
createSecret, | ||
decryptData, | ||
encryptData, | ||
createRecoveryCodes, | ||
validateTotp, | ||
validateAndMarkRecoveryCode, | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import nextConnect from 'next-connect'; | ||
|
||
import { ServiceError } from 'errors'; | ||
import authentication from 'models/authentication.js'; | ||
import authorization from 'models/authorization.js'; | ||
import cacheControl from 'models/cache-control'; | ||
import controller from 'models/controller.js'; | ||
import totp from 'models/totp'; | ||
|
||
export default nextConnect({ | ||
attachParams: true, | ||
onNoMatch: controller.onNoMatchHandler, | ||
onError: controller.onErrorHandler, | ||
}) | ||
.use(controller.injectRequestMetadata) | ||
.use(controller.logRequest) | ||
.get( | ||
cacheControl.noCache, | ||
authentication.injectAnonymousOrUser, | ||
authorization.canRequest('read:session'), | ||
getHandler, | ||
); | ||
|
||
async function getHandler(request, response) { | ||
const username = request.context.user.username; | ||
const otp = totp.createTotp(null, username); | ||
|
||
try { | ||
response.status(200).json({ totp: otp.toString() }); | ||
} catch (err) { | ||
throw new ServiceError({ | ||
message: 'Não foi possível gerar um TOTP no momento.', | ||
action: 'Tente novamente mais tarde.', | ||
stack: new Error().stack, | ||
errorLocationCode: 'CONTROLLER:MFA:TOTP:ENABLE_GET', | ||
key: 'totp', | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.