Edit: /tmp/tsx-0/17887-fb82f89c4c722bf6bbe671de5ab386cf1904d5d5 (12311B)
{"code":"__filename=\"/opt/canhelp/node_modules/better-auth/dist/plugins/two-factor/otp/index.mjs\";(()=>{\nvar __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,\"name\",{value,configurable:true});var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from===\"object\"||typeof from===\"function\"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,\"default\",{value:mod,enumerable:true}):target,mod));var __toCommonJS=mod=>__copyProps(__defProp({},\"__esModule\",{value:true}),mod);var otp_exports={};__export(otp_exports,{otp2fa:()=>otp2fa});module.exports=__toCommonJS(otp_exports);var import_schema=require(\"../../../db/schema.mjs\");var import_buffer=require(\"../../../crypto/buffer.mjs\");var import_random=require(\"../../../crypto/random.mjs\");var import_crypto=require(\"../../../crypto/index.mjs\");var import_cookies=require(\"../../../cookies/index.mjs\");var import_error_code=require(\"../error-code.mjs\");var import_verify_two_factor=require(\"../verify-two-factor.mjs\");var import_utils=require(\"../utils.mjs\");var import_error=require(\"@better-auth/core/error\");var import_api=require(\"@better-auth/core/api\");var z=__toESM(require(\"zod\"));const verifyOTPBodySchema=z.object({code:z.string().meta({description:'The otp code to verify. Eg: \"012345\"'}),trustDevice:z.boolean().optional().meta({description:\"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true\"})});const send2FaOTPBodySchema=z.object({trustDevice:z.boolean().optional().meta({description:\"If true, the device will be trusted for 30 days. It'll be refreshed on every sign in request within this time. Eg: true\"})}).optional();const otp2fa=__name(options=>{const opts={storeOTP:\"plain\",digits:6,...options,period:(options?.period||3)*60*1e3};async function storeOTP(ctx,otp){if(opts.storeOTP===\"hashed\")return await(0,import_utils.defaultKeyHasher)(otp);if(typeof opts.storeOTP===\"object\"&&\"hash\"in opts.storeOTP)return await opts.storeOTP.hash(otp);if(typeof opts.storeOTP===\"object\"&&\"encrypt\"in opts.storeOTP)return await opts.storeOTP.encrypt(otp);if(opts.storeOTP===\"encrypted\")return await(0,import_crypto.symmetricEncrypt)({key:ctx.context.secretConfig,data:otp});return otp}__name(storeOTP,\"storeOTP\");async function decryptOrHashForComparison(ctx,storedOtp,userInput){if(opts.storeOTP===\"hashed\")return[storedOtp,await(0,import_utils.defaultKeyHasher)(userInput)];if(opts.storeOTP===\"encrypted\")return[await(0,import_crypto.symmetricDecrypt)({key:ctx.context.secretConfig,data:storedOtp}),userInput];if(typeof opts.storeOTP===\"object\"&&\"encrypt\"in opts.storeOTP)return[await opts.storeOTP.decrypt(storedOtp),userInput];if(typeof opts.storeOTP===\"object\"&&\"hash\"in opts.storeOTP)return[storedOtp,await opts.storeOTP.hash(userInput)];return[storedOtp,userInput]}__name(decryptOrHashForComparison,\"decryptOrHashForComparison\");return{id:\"otp\",endpoints:{sendTwoFactorOTP:(0,import_api.createAuthEndpoint)(\"/two-factor/send-otp\",{method:\"POST\",body:send2FaOTPBodySchema,metadata:{openapi:{summary:\"Send two factor OTP\",description:\"Send two factor OTP to the user\",responses:{200:{description:\"Successful response\",content:{\"application/json\":{schema:{type:\"object\",properties:{status:{type:\"boolean\"}}}}}}}}}},async ctx=>{if(!options||!options.sendOTP){ctx.context.logger.error(\"send otp isn't configured. Please configure the send otp function on otp options.\");throw import_error.APIError.from(\"BAD_REQUEST\",{message:\"otp isn't configured\",code:\"OTP_NOT_CONFIGURED\"})}const{session,key}=await(0,import_verify_two_factor.verifyTwoFactor)(ctx);const code=(0,import_random.generateRandomString)(opts.digits,\"0-9\");const hashedCode=await storeOTP(ctx,code);await ctx.context.internalAdapter.createVerificationValue({value:`${hashedCode}:0`,identifier:`2fa-otp-${key}`,expiresAt:new Date(Date.now()+opts.period)});const sendOTPResult=options.sendOTP({user:session.user,otp:code},ctx);if(sendOTPResult instanceof Promise)await ctx.context.runInBackgroundOrAwait(sendOTPResult.catch(e=>{ctx.context.logger.error(\"Failed to send two-factor OTP\",e)}));return ctx.json({status:true})}),verifyTwoFactorOTP:(0,import_api.createAuthEndpoint)(\"/two-factor/verify-otp\",{method:\"POST\",body:verifyOTPBodySchema,metadata:{openapi:{summary:\"Verify two factor OTP\",description:\"Verify two factor OTP\",responses:{\"200\":{description:\"Two-factor OTP verified successfully\",content:{\"application/json\":{schema:{type:\"object\",properties:{token:{type:\"string\",description:\"Session token for the authenticated session\"},user:{type:\"object\",properties:{id:{type:\"string\",description:\"Unique identifier of the user\"},email:{type:\"string\",format:\"email\",nullable:true,description:\"User's email address\"},emailVerified:{type:\"boolean\",nullable:true,description:\"Whether the email is verified\"},name:{type:\"string\",nullable:true,description:\"User's name\"},image:{type:\"string\",format:\"uri\",nullable:true,description:\"User's profile image URL\"},createdAt:{type:\"string\",format:\"date-time\",description:\"Timestamp when the user was created\"},updatedAt:{type:\"string\",format:\"date-time\",description:\"Timestamp when the user was last updated\"}},required:[\"id\",\"createdAt\",\"updatedAt\"],description:\"The authenticated user object\"}},required:[\"token\",\"user\"]}}}}}}}},async ctx=>{const{session,key,valid,invalid}=await(0,import_verify_two_factor.verifyTwoFactor)(ctx);const toCheckOtp=await ctx.context.internalAdapter.findVerificationValue(`2fa-otp-${key}`);const[otp,counter]=toCheckOtp?.value?.split(\":\")??[];if(!toCheckOtp||toCheckOtp.expiresAt
=allowedAttempts){await ctx.context.internalAdapter.deleteVerificationByIdentifier(`2fa-otp-${key}`);throw import_error.APIError.from(\"BAD_REQUEST\",import_error_code.TWO_FACTOR_ERROR_CODES.TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE)}const[storedValue,inputValue]=await decryptOrHashForComparison(ctx,otp,ctx.body.code);if((0,import_buffer.constantTimeEqual)(new TextEncoder().encode(storedValue),new TextEncoder().encode(inputValue))){if(!session.user.twoFactorEnabled){if(!session.session)throw import_error.APIError.from(\"BAD_REQUEST\",import_error.BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION);const updatedUser=await ctx.context.internalAdapter.updateUser(session.user.id,{twoFactorEnabled:true});const newSession=await ctx.context.internalAdapter.createSession(session.user.id,false,session.session);await ctx.context.internalAdapter.deleteSession(session.session.token);await(0,import_cookies.setSessionCookie)(ctx,{session:newSession,user:updatedUser});return ctx.json({token:newSession.token,user:(0,import_schema.parseUserOutput)(ctx.context.options,updatedUser)})}return valid(ctx)}else{await ctx.context.internalAdapter.updateVerificationByIdentifier(`2fa-otp-${key}`,{value:`${otp}:${(parseInt(counter,10)||0)+1}`});return invalid(\"INVALID_CODE\")}})}}},\"otp2fa\");0&&(module.exports={otp2fa});\n})()\n","warnings":[],"map":{"version":3,"mappings":";i/BAAA,wHAAgC,kCAChC,kBAAkC,sCAClC,kBAAqC,sCACrC,kBAAmD,qCACnD,mBAAiC,sCACjC,sBAAuC,6BACvC,6BAAgC,oCAChC,iBAAiC,wBACjC,iBAA2C,mCAC3C,eAAmC,iCACnC,MAAmB,wBAGnB,MAAM,oBAAsB,EAAE,OAAO,CACpC,KAAM,EAAE,OAAO,EAAE,KAAK,CAAE,YAAa,sCAAyC,CAAC,EAC/E,YAAa,EAAE,QAAQ,EAAE,SAAS,EAAE,KAAK,CAAE,YAAa,yHAA0H,CAAC,CACpL,CAAC,EACD,MAAM,qBAAuB,EAAE,OAAO,CAAE,YAAa,EAAE,QAAQ,EAAE,SAAS,EAAE,KAAK,CAAE,YAAa,yHAA0H,CAAC,CAAE,CAAC,EAAE,SAAS,EAIzO,MAAM,OAAS,OAAC,SAAY,CAC3B,M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