-
Notifications
You must be signed in to change notification settings - Fork 384
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
- Loading branch information
1 parent
a67be7f
commit 4e71064
Showing
20 changed files
with
884 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
10 changes: 10 additions & 0 deletions
10
infra/migrations/1725497855500_alter-table-users-add-mfa-totp-secret.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,10 @@ | ||
exports.up = (pgm) => { | ||
pgm.addColumns('users', { | ||
totp_secret: { | ||
type: 'varchar(128)', | ||
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
import crypto from 'crypto'; | ||
import * as OTPAuth from 'otpauth'; | ||
|
||
import user from 'models/user'; | ||
|
||
const defaultTOTPConfigurations = { | ||
issuer: 'TabNews', | ||
algorithm: 'SHA1', | ||
digits: 6, | ||
}; | ||
|
||
const cryptoConfigurations = { | ||
algorithm: process.env.TOTP_ENCRYPTION_METHOD, | ||
key: crypto.createHash('sha512').update(process.env.TOTP_SECRET_KEY).digest('hex').substring(0, 32), | ||
}; | ||
|
||
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 }); | ||
} | ||
|
||
function encryptData(data) { | ||
const iv = crypto.randomBytes(16); | ||
const cipher = crypto.createCipheriv(cryptoConfigurations.algorithm, cryptoConfigurations.key, iv); | ||
const encryptedData = Buffer.concat([cipher.update(data, 'utf8'), cipher.final()]); | ||
|
||
return Buffer.concat([iv, encryptedData]).toString('hex'); | ||
} | ||
|
||
function decryptData(encrypted) { | ||
const data = Buffer.from(encrypted, 'hex'); | ||
const iv = data.subarray(0, 16); | ||
const encryptedData = data.subarray(16); | ||
const decipher = crypto.createDecipheriv(cryptoConfigurations.algorithm, cryptoConfigurations.key, iv); | ||
|
||
return decipher.update(encryptedData, 'binary', 'utf-8') + decipher.final('utf-8'); | ||
} | ||
|
||
function validateUserTotp(userEncryptedSecret, token) { | ||
const userSecret = decryptData(userEncryptedSecret); | ||
const userTOTP = createTotp(userSecret); | ||
|
||
return userTOTP.validate({ token }) !== null; | ||
} | ||
|
||
function validateTotp(secret, token) { | ||
const totp = createTotp(secret); | ||
|
||
return totp.validate({ token }) !== null; | ||
} | ||
|
||
function makeCode(length = 10) { | ||
const characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; | ||
let code = ''; | ||
|
||
for (let i = 0; i < length; i++) { | ||
code += characters.charAt(Math.floor(Math.random() * characters.length)); | ||
} | ||
|
||
return code; | ||
} | ||
|
||
function createRecoveryCodes() { | ||
const RECOVERY_CODES_LENTGH = 10; | ||
const RECOVERY_CODES_AMOUNT = 10; | ||
|
||
const recoveryCodesObject = {}; | ||
|
||
for (let i = 0; i < RECOVERY_CODES_AMOUNT; i++) { | ||
const newCode = makeCode(RECOVERY_CODES_LENTGH); | ||
recoveryCodesObject[newCode] = true; | ||
} | ||
|
||
return recoveryCodesObject; | ||
} | ||
|
||
async function validateAndMarkRecoveryCode(targetUser, recoveryCode) { | ||
const recoveryCodes = JSON.parse(decryptData(targetUser.totp_recovery_codes)); | ||
|
||
if (recoveryCodes[recoveryCode]) { | ||
recoveryCodes[recoveryCode] = false; | ||
|
||
await user.update(targetUser, { totp_recovery_codes: recoveryCodes }); | ||
|
||
return true; | ||
} | ||
|
||
return false; | ||
} | ||
|
||
export default Object.freeze({ | ||
createTotp, | ||
createSecret, | ||
decryptData, | ||
encryptData, | ||
validateUserTotp, | ||
validateTotp, | ||
makeCode, | ||
createRecoveryCodes, | ||
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 otp from 'models/otp'; | ||
|
||
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, | ||
); | ||
|
||
function getHandler(request, response) { | ||
const username = request.context.user.username; | ||
const totp = otp.createTotp(null, username); | ||
|
||
try { | ||
response.status(200).json({ totp: totp.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:GET_HANDLER:GENERATE_TOTP', | ||
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.