Edit: /tmp/tsx-0/17887-2835c39830fc752e14850e2f525dec680a5a3f63 (15167B)
{"code":"__filename=\"/opt/canhelp/node_modules/better-auth/dist/plugins/two-factor/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 two_factor_exports={};__export(two_factor_exports,{TWO_FACTOR_ERROR_CODES:()=>import_error_code.TWO_FACTOR_ERROR_CODES,twoFactor:()=>twoFactor,twoFactorClient:()=>import_client.twoFactorClient});module.exports=__toCommonJS(two_factor_exports);var import_schema=require(\"../../db/schema.mjs\");var import_random=require(\"../../crypto/random.mjs\");var import_crypto=require(\"../../crypto/index.mjs\");var import_cookies=require(\"../../cookies/index.mjs\");var import_session=require(\"../../api/routes/session.mjs\");var import_password=require(\"../../utils/password.mjs\");var import_api=require(\"../../api/index.mjs\");var import_error_code=require(\"./error-code.mjs\");var import_client=require(\"./client.mjs\");var import_constant=require(\"./constant.mjs\");var import_backup_codes=require(\"./backup-codes/index.mjs\");var import_otp=require(\"./otp/index.mjs\");var import_schema2=require(\"./schema.mjs\");var import_totp=require(\"./totp/index.mjs\");var import_error=require(\"@better-auth/core/error\");var import_api2=require(\"@better-auth/core/api\");var z=__toESM(require(\"zod\"));var import_hmac=require(\"@better-auth/utils/hmac\");var import_otp2=require(\"@better-auth/utils/otp\");const enableTwoFactorBodySchema=z.object({password:z.string().meta({description:\"User password\"}),issuer:z.string().meta({description:\"Custom issuer for the TOTP URI\"}).optional()});const disableTwoFactorBodySchema=z.object({password:z.string().meta({description:\"User password\"})});const twoFactor=__name(options=>{const opts={twoFactorTable:\"twoFactor\"};const trustDeviceMaxAge=options?.trustDeviceMaxAge??import_constant.TRUST_DEVICE_COOKIE_MAX_AGE;const backupCodeOptions={storeBackupCodes:\"encrypted\",...options?.backupCodeOptions};const totp=(0,import_totp.totp2fa)(options?.totpOptions);const backupCode=(0,import_backup_codes.backupCode2fa)(backupCodeOptions);const otp=(0,import_otp.otp2fa)(options?.otpOptions);return{id:\"two-factor\",endpoints:{...totp.endpoints,...otp.endpoints,...backupCode.endpoints,enableTwoFactor:(0,import_api2.createAuthEndpoint)(\"/two-factor/enable\",{method:\"POST\",body:enableTwoFactorBodySchema,use:[import_session.sessionMiddleware],metadata:{openapi:{summary:\"Enable two factor authentication\",description:\"Use this endpoint to enable two factor authentication. This will generate a TOTP URI and backup codes. Once the user verifies the TOTP URI, the two factor authentication will be enabled.\",responses:{200:{description:\"Successful response\",content:{\"application/json\":{schema:{type:\"object\",properties:{totpURI:{type:\"string\",description:\"TOTP URI\"},backupCodes:{type:\"array\",items:{type:\"string\"},description:\"Backup codes\"}}}}}}}}}},async ctx=>{const user=ctx.context.session.user;const{password,issuer}=ctx.body;if(!await(0,import_password.validatePassword)(ctx,{password,userId:user.id}))throw import_error.APIError.from(\"BAD_REQUEST\",import_error.BASE_ERROR_CODES.INVALID_PASSWORD);const secret=(0,import_random.generateRandomString)(32);const encryptedSecret=await(0,import_crypto.symmetricEncrypt)({key:ctx.context.secretConfig,data:secret});const backupCodes=await(0,import_backup_codes.generateBackupCodes)(ctx.context.secretConfig,backupCodeOptions);if(options?.skipVerificationOnEnable){const updatedUser=await ctx.context.internalAdapter.updateUser(user.id,{twoFactorEnabled:true});await(0,import_cookies.setSessionCookie)(ctx,{session:await ctx.context.internalAdapter.createSession(updatedUser.id,false,ctx.context.session.session),user:updatedUser});await ctx.context.internalAdapter.deleteSession(ctx.context.session.session.token)}await ctx.context.adapter.deleteMany({model:opts.twoFactorTable,where:[{field:\"userId\",value:user.id}]});await ctx.context.adapter.create({model:opts.twoFactorTable,data:{secret:encryptedSecret,backupCodes:backupCodes.encryptedBackupCodes,userId:user.id}});const totpURI=(0,import_otp2.createOTP)(secret,{digits:options?.totpOptions?.digits||6,period:options?.totpOptions?.period}).url(issuer||options?.issuer||ctx.context.appName,user.email);return ctx.json({totpURI,backupCodes:backupCodes.backupCodes})}),disableTwoFactor:(0,import_api2.createAuthEndpoint)(\"/two-factor/disable\",{method:\"POST\",body:disableTwoFactorBodySchema,use:[import_session.sessionMiddleware],metadata:{openapi:{summary:\"Disable two factor authentication\",description:\"Use this endpoint to disable two factor authentication.\",responses:{200:{description:\"Successful response\",content:{\"application/json\":{schema:{type:\"object\",properties:{status:{type:\"boolean\"}}}}}}}}}},async ctx=>{const user=ctx.context.session.user;const{password}=ctx.body;if(!await(0,import_password.validatePassword)(ctx,{password,userId:user.id}))throw import_error.APIError.from(\"BAD_REQUEST\",import_error.BASE_ERROR_CODES.INVALID_PASSWORD);const updatedUser=await ctx.context.internalAdapter.updateUser(user.id,{twoFactorEnabled:false});await ctx.context.adapter.delete({model:opts.twoFactorTable,where:[{field:\"userId\",value:updatedUser.id}]});await(0,import_cookies.setSessionCookie)(ctx,{session:await ctx.context.internalAdapter.createSession(updatedUser.id,false,ctx.context.session.session),user:updatedUser});await ctx.context.internalAdapter.deleteSession(ctx.context.session.session.token);const disableTrustCookie=ctx.context.createAuthCookie(import_constant.TRUST_DEVICE_COOKIE_NAME,{maxAge:trustDeviceMaxAge});const disableTrustValue=await ctx.getSignedCookie(disableTrustCookie.name,ctx.context.secret);if(disableTrustValue){const[,trustId]=disableTrustValue.split(\"!\");if(trustId)await ctx.context.internalAdapter.deleteVerificationByIdentifier(trustId);(0,import_cookies.expireCookie)(ctx,disableTrustCookie)}return ctx.json({status:true})})},options,hooks:{after:[{matcher(context){return context.path===\"/sign-in/email\"||context.path===\"/sign-in/username\"||context.path===\"/sign-in/phone-number\"},handler:(0,import_api2.createAuthMiddleware)(async ctx=>{const data=ctx.context.newSession;if(!data)return;if(!data?.user.twoFactorEnabled)return;const trustDeviceCookieAttrs=ctx.context.createAuthCookie(import_constant.TRUST_DEVICE_COOKIE_NAME,{maxAge:trustDeviceMaxAge});const trustDeviceCookie=await ctx.getSignedCookie(trustDeviceCookieAttrs.name,ctx.context.secret);if(trustDeviceCookie){const[token,trustIdentifier]=trustDeviceCookie.split(\"!\");if(token&&trustIdentifier){if(token===await(0,import_hmac.createHMAC)(\"SHA-256\",\"base64urlnopad\").sign(ctx.context.secret,`${data.user.id}!${trustIdentifier}`)){const verificationRecord=await ctx.context.internalAdapter.findVerificationValue(trustIdentifier);if(verificationRecord&&verificationRecord.value===data.user.id&&verificationRecord.expiresAt>new Date){await ctx.context.internalAdapter.deleteVerificationByIdentifier(trustIdentifier);const newTrustIdentifier=`trust-device-${(0,import_random.generateRandomString)(32)}`;const newToken=await(0,import_hmac.createHMAC)(\"SHA-256\",\"base64urlnopad\").sign(ctx.context.secret,`${data.user.id}!${newTrustIdentifier}`);await ctx.context.internalAdapter.createVerificationValue({value:data.user.id,identifier:newTrustIdentifier,expiresAt:new Date(Date.now()+trustDeviceMaxAge*1e3)});const newTrustDeviceCookie=ctx.context.createAuthCookie(import_constant.TRUST_DEVICE_COOKIE_NAME,{maxAge:trustDeviceMaxAge});await ctx.setSignedCookie(newTrustDeviceCookie.name,`${newToken}!${newTrustIdentifier}`,ctx.context.secret,trustDeviceCookieAttrs.attributes);return}}}(0,import_cookies.expireCookie)(ctx,trustDeviceCookieAttrs)}(0,import_cookies.deleteSessionCookie)(ctx,true);await ctx.context.internalAdapter.deleteSession(data.session.token);const maxAge=options?.twoFactorCookieMaxAge??600;const twoFactorCookie=ctx.context.createAuthCookie(import_constant.TWO_FACTOR_COOKIE_NAME,{maxAge});const identifier=`2fa-${(0,import_random.generateRandomString)(20)}`;await ctx.context.internalAdapter.createVerificationValue({value:data.user.id,identifier,expiresAt:new Date(Date.now()+maxAge*1e3)});await ctx.setSignedCookie(twoFactorCookie.name,identifier,ctx.context.secret,twoFactorCookie.attributes);return ctx.json({twoFactorRedirect:true})})}]},schema:(0,import_schema.mergeSchema)(import_schema2.schema,{...options?.schema,twoFactor:{...options?.schema?.twoFactor,...options?.twoFactorTable?{modelName:options.twoFactorTable}:{}}}),rateLimit:[{pathMatcher(path){return path.startsWith(\"/two-factor/\")},window:10,max:3}],$ERROR_CODES:import_error_code.TWO_FACTOR_ERROR_CODES}},\"twoFactor\");0&&(module.exports={TWO_FACTOR_ERROR_CODES,twoFactor,twoFactorClient});\n})()\n","warnings":[],"map":{"version":3,"mappings":";i/BAAA,yQAA4B,+BAC5B,kBAAqC,mCACrC,kBAAiC,kCACjC,mBAAoE,mCACpE,mBAAkC,wCAClC,oBAAiC,oCACjC,eAAO,+BACP,sBAAuC,4BACvC,kBAAgC,wBAChC,oBAA8F,0BAC9F,wBAAmD,oCACnD,eAAuB,2BACvB,IAAAA,eAAuB,wBACvB,gBAAwB,4BACxB,iBAA2C,mCAC3C,IAAAC,YAAyD,iCACzD,MAAmB,wBACnB,gBAA2B,mCAC3B,IAAAC,YAA0B,kCAG1B,MAAM,0BAA4B,EAAE,OAAO,CAC1C,SAAU,EAAE,OAAO,EAAE,KAAK,CAAE,YAAa,eAAgB,CAAC,EAC1D,OAAQ,EAAE,OAAO,EAAE,KAAK,CAAE,YAAa,gCAAiC,CAAC,EAAE,SAAS,CACrF,CAAC,EACD,MAAM,2BAA6B,EAAE,OAAO,CAAE,SAAU,EAAE,OAAO,EAAE,KAAK,CAAE,YAAa,eAAgB,CAAC,CAAE,CAAC,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EAAE,CAAC,GAClD,MAAM,IAAI,QAAQ,gBAAgB,wBAAwB,CACzD,MAAO,KAAK,KAAK,GACjB,WACA,UAAW,IAAI,KAAK,KAAK,IAAI,EAAI,OAAS,GAAG,CAC9C,CAAC,EACD,MAAM,IAAI,gBAAgB,gBAAgB,KAAM,WAAY,IAAI,QAAQ,OAAQ,gBAAgB,UAAU,EAC1G,OAAO,IAAI,KAAK,CAAE,kBAAmB,IAAK,CAAC,CAC5C,CAAC,CACF,CAAC,CAAE,EACH,UAAQ,2BAAY,sBAAQ,CAC3B,GAAG,SAAS,OACZ,UAAW,CACV,GAAG,SAAS,QAAQ,UACpB,GAAG,SAAS,eAAiB,CAAE,UAAW,QAAQ,cAAe,EAAI,CAAC,CACvE,CACD,CAAC,EACD,UAAW,CAAC,CACX,YAAY,KAAM,CACjB,OAAO,KAAK,WAAW,cAAc,CACtC,EACA,OAAQ,GACR,IAAK,CACN,CAAC,EACD,aAAc,wCACf,CACD,EA3MkB","names":["import_schema","import_api","import_otp"],"ignoreList":[],"sources":["/opt/canhelp/node_modules/better-auth/dist/plugins/two-factor/index.mjs"],"sourcesContent":[null]}}