Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Fix merge conflicts
Tuan Dang8c0d643a3713
diff --cc backend/src/controllers/v1/authController.tsindex 8793815066,eef1c9ad3f..8a70e016ed--- a/backend/src/controllers/v1/authController.ts+++ b/backend/src/controllers/v1/authController.ts@@@ -1,7 -1,4 +1,6 @@@- import * as Sentry from '@sentry/node';import { Request, Response } from 'express';+import fs from 'fs';+import path from 'path';import jwt from 'jsonwebtoken';import * as bigintConversion from 'bigint-conversion';// eslint-disable-next-line @typescript-eslint/no-var-requires@@@ -96,88 -76,76 +87,80 @@@ export const login1 = async (req: Reque* @returns*/export const login2 = async (req: Request, res: Response) => {- try {- const { email, clientProof } = req.body;- const user = await User.findOne({- }).select('+salt +verifier +publicKey +encryptedPrivateKey +iv +tag +devices');+ const { email, clientProof } = req.body;+ const user = await User.findOne({+ }).select('+salt +verifier +publicKey +encryptedPrivateKey +iv +tag');- if (!user) throw new Error('Failed to find user');+ if (!user) throw new Error('Failed to find user');- const loginSRPDetailFromDB = await LoginSRPDetail.findOneAndDelete({ email: email })+ const loginSRPDetailFromDB = await LoginSRPDetail.findOneAndDelete({ email: email })- if (!loginSRPDetailFromDB) {- return BadRequestError(Error("It looks like some details from the first login are not found. Please try login one again"))- }+ if (!loginSRPDetailFromDB) {+ return BadRequestError(Error("It looks like some details from the first login are not found. Please try login one again"))+ }++ const server = new jsrp.server();+ server.init(+ {+ salt: user.salt,+ verifier: user.verifier,+ b: loginSRPDetailFromDB.serverBInt+ },+ async () => {+ server.setClientPublicKey(loginSRPDetailFromDB.clientPublicKey);++ // compare server and client shared keys+ if (server.checkClientProof(clientProof)) {+ // issue tokens++ await checkUserDevice({+ user,- ip: req.ip,++ ip: req.realIP,+ userAgent: req.headers['user-agent'] ?? ''+ });+- const tokens = await issueAuthTokens({ userId: user._id.toString() });++ const tokens = await issueAuthTokens({++ userId: user._id,++ ip: req.realIP,++ userAgent: req.headers['user-agent'] ?? ''++ });++ // store (refresh) token in httpOnly cookie+ res.cookie('jid', tokens.refreshToken, {+ httpOnly: true,+ path: '/',+ sameSite: 'strict',+ secure: await getHttpsEnabled()+ });- const server = new jsrp.server();- server.init(- {- salt: user.salt,- verifier: user.verifier,- b: loginSRPDetailFromDB.serverBInt- },- async () => {- server.setClientPublicKey(loginSRPDetailFromDB.clientPublicKey);-- // compare server and client shared keys- if (server.checkClientProof(clientProof)) {- // issue tokens-- await checkUserDevice({- user,- ip: req.realIP,- userAgent: req.headers['user-agent'] ?? ''- });-- const tokens = await issueAuthTokens({- userId: user._id,- ip: req.realIP,- userAgent: req.headers['user-agent'] ?? ''- });-- // store (refresh) token in httpOnly cookie- res.cookie('jid', tokens.refreshToken, {- httpOnly: true,- path: '/',- sameSite: 'strict',- secure: await getHttpsEnabled()- });-- const loginAction = await EELogService.createAction({- name: ACTION_LOGIN,- userId: user._id- });-- loginAction && await EELogService.createLog({- userId: user._id,- actions: [loginAction],- channel: getChannelFromUserAgent(req.headers['user-agent']),- ipAddress: req.realIP- });-- // return (access) token in response- return res.status(200).send({- token: tokens.token,- publicKey: user.publicKey,- encryptedPrivateKey: user.encryptedPrivateKey,- iv: user.iv,- tag: user.tag- });- }-- return res.status(400).send({- message: 'Failed to authenticate. Try again?'+ const loginAction = await EELogService.createAction({+ name: ACTION_LOGIN,+ userId: user._id+ });++ loginAction && await EELogService.createLog({+ userId: user._id,+ actions: [loginAction],+ channel: getChannelFromUserAgent(req.headers['user-agent']),- ipAddress: req.ip++ ipAddress: req.realIP+ });++ // return (access) token in response+ return res.status(200).send({+ token: tokens.token,+ publicKey: user.publicKey,+ encryptedPrivateKey: user.encryptedPrivateKey,+ iv: user.iv,+ tag: user.tag});}- );- } catch (err) {- Sentry.setUser(null);- Sentry.captureException(err);- return res.status(400).send({- message: 'Failed to authenticate. Try again?'- });- }++ return res.status(400).send({+ message: 'Failed to authenticate. Try again?'+ });+ }+ );};/**@@@ -187,40 -155,30 +170,30 @@@* @returns*/export const logout = async (req: Request, res: Response) => {- try {-- if (req.authData.authMode === AUTH_MODE_JWT && req.authData.authPayload instanceof User && req.authData.tokenVersionId) {- await clearTokens(req.authData.tokenVersionId)- }-- // clear httpOnly cookie- res.cookie('jid', '', {- httpOnly: true,- path: '/',- sameSite: 'strict',- secure: (await getHttpsEnabled()) as boolean- });-- const logoutAction = await EELogService.createAction({- name: ACTION_LOGOUT,- userId: req.user._id- });-- logoutAction && await EELogService.createLog({- userId: req.user._id,- actions: [logoutAction],- channel: getChannelFromUserAgent(req.headers['user-agent']),- ipAddress: req.realIP- });-- } catch (err) {- Sentry.setUser({ email: req.user.email });- Sentry.captureException(err);- return res.status(400).send({- message: 'Failed to logout'- });- await clearTokens({- userId: req.user._id.toString()- });++ if (req.authData.authMode === AUTH_MODE_JWT && req.authData.authPayload instanceof User && req.authData.tokenVersionId) {++ await clearTokens(req.authData.tokenVersionId)+ }+ // clear httpOnly cookie+ res.cookie('jid', '', {+ httpOnly: true,+ path: '/',+ sameSite: 'strict',+ secure: (await getHttpsEnabled()) as boolean+ });++ const logoutAction = await EELogService.createAction({+ name: ACTION_LOGOUT,+ userId: req.user._id+ });++ logoutAction && await EELogService.createLog({+ userId: req.user._id,+ actions: [logoutAction],+ channel: getChannelFromUserAgent(req.headers['user-agent']),- ipAddress: req.ip++ ipAddress: req.realIP+ });+return res.status(200).send({message: 'Successfully logged out.'});@@@ -269,55 -203,35 +242,47 @@@ export const checkAuth = async (req: Re* @returns*/export const getNewToken = async (req: Request, res: Response) => {- try {- const refreshToken = req.cookies.jid;+ const refreshToken = req.cookies.jid;- if (!refreshToken) {- throw new Error('Failed to find refresh token in request cookies');- }-- const decodedToken = <jwt.UserIDJwtPayload>(- jwt.verify(refreshToken, await getJwtRefreshSecret())- );-- const user = await User.findOne({- _id: decodedToken.userId- }).select('+publicKey +refreshVersion +accessVersion');-- if (!user) throw new Error('Failed to authenticate unfound user');- if (!user?.publicKey)- throw new Error('Failed to authenticate not fully set up account');-- const tokenVersion = await TokenVersion.findById(decodedToken.tokenVersionId);-- if (!tokenVersion) throw UnauthorizedRequestError({- message: 'Failed to validate refresh token'- });-- if (decodedToken.refreshVersion !== tokenVersion.refreshVersion) throw BadRequestError({- message: 'Failed to validate refresh token'- });-- const token = createToken({- payload: {- userId: decodedToken.userId,- tokenVersionId: tokenVersion._id.toString(),- accessVersion: tokenVersion.refreshVersion- },- expiresIn: await getJwtAuthLifetime(),- secret: await getJwtAuthSecret()- });-- return res.status(200).send({- token- });- } catch (err) {- Sentry.setUser(null);- Sentry.captureException(err);- return res.status(400).send({- message: 'Invalid request'- });+ if (!refreshToken) {- throw new Error('Failed to find token in request cookies');++ throw new Error('Failed to find refresh token in request cookies');}++ const decodedToken = <jwt.UserIDJwtPayload>(+ jwt.verify(refreshToken, await getJwtRefreshSecret())+ );++ const user = await User.findOne({+ _id: decodedToken.userId- }).select('+publicKey');++ }).select('+publicKey +refreshVersion +accessVersion');++ if (!user) throw new Error('Failed to authenticate unfound user');+ if (!user?.publicKey)+ throw new Error('Failed to authenticate not fully set up account');++++ const tokenVersion = await TokenVersion.findById(decodedToken.tokenVersionId);++++ if (!tokenVersion) throw UnauthorizedRequestError({++ message: 'Failed to validate refresh token'++ });++++ if (decodedToken.refreshVersion !== tokenVersion.refreshVersion) throw BadRequestError({++ message: 'Failed to validate refresh token'++ });++ const token = createToken({+ payload: {- userId: decodedToken.userId++ userId: decodedToken.userId,++ tokenVersionId: tokenVersion._id.toString(),++ accessVersion: tokenVersion.refreshVersion+ },+ expiresIn: await getJwtAuthLifetime(),+ secret: await getJwtAuthSecret()+ });++ return res.status(200).send({+ token+ });};export const handleAuthProviderCallback = (req: Request, res: Response) => {diff --cc backend/src/controllers/v1/membershipOrgController.tsindex 51f89b8ebb,f6b0ee3ccb..eafd7fae2a--- a/backend/src/controllers/v1/membershipOrgController.ts+++ b/backend/src/controllers/v1/membershipOrgController.ts@@@ -103,122 -83,98 +85,114 @@@ export const changeMembershipOrgRole =*/export const inviteUserToOrganization = async (req: Request, res: Response) => {let invitee, inviteeMembershipOrg, completeInviteLink;- try {- const { organizationId, inviteeEmail } = req.body;- const host = req.headers.host;- const siteUrl = `${req.protocol}://${host}`;-- // validate membership- const membershipOrg = await MembershipOrg.findOne({- user: req.user._id,- organization: organizationId- });-- if (!membershipOrg) {- throw new Error('Failed to validate organization membership');- }-- const plan = await EELicenseService.getOrganizationPlan(organizationId);-- if (plan.memberLimit !== null) {- // case: limit imposed on number of members allowed-- if (plan.membersUsed >= plan.memberLimit) {- // case: number of members used exceeds the number of members allowed- return res.status(400).send({- message: 'Failed to invite member due to member limit reached. Upgrade plan to invite more members.'- });- }- }-- invitee = await User.findOne({- email: inviteeEmail- }).select('+publicKey');-- if (invitee) {- // case: invitee is an existing user-- inviteeMembershipOrg = await MembershipOrg.findOne({- user: invitee._id,- organization: organizationId- });-- if (inviteeMembershipOrg && inviteeMembershipOrg.status === ACCEPTED) {- throw new Error(- 'Failed to invite an existing member of the organization'- );- }-- if (!inviteeMembershipOrg) {-- await new MembershipOrg({- user: invitee,- inviteEmail: inviteeEmail,- organization: organizationId,- role: MEMBER,- status: INVITED- }).save();- }- } else {- // check if invitee has been invited before- inviteeMembershipOrg = await MembershipOrg.findOne({- inviteEmail: inviteeEmail,- organization: organizationId- });-- if (!inviteeMembershipOrg) {- // case: invitee has never been invited before-- // validate that email is not disposable- validateUserEmail(inviteeEmail);-- await new MembershipOrg({- inviteEmail: inviteeEmail,- organization: organizationId,- role: MEMBER,- status: INVITED- }).save();- }- }-- const organization = await Organization.findOne({ _id: organizationId });-- if (organization) {-- const token = await TokenService.createToken({- type: TOKEN_EMAIL_ORG_INVITATION,- email: inviteeEmail,- organizationId: organization._id- });-- await sendMail({- template: 'organizationInvitation.handlebars',- subjectLine: 'Infisical organization invitation',- recipients: [inviteeEmail],- substitutions: {- inviterFirstName: req.user.firstName,- inviterEmail: req.user.email,- organizationName: organization.name,- email: inviteeEmail,- organizationId: organization._id.toString(),- token,- callback_url: (await getSiteURL()) + '/signupinvite'- }- });-- if (!(await getSmtpConfigured())) {- completeInviteLink = `${siteUrl + '/signupinvite'}?token=${token}&to=${inviteeEmail}&organization_id=${organization._id}`- }- }-- await updateSubscriptionOrgQuantity({ organizationId });- } catch (err) {- Sentry.setUser(null);- Sentry.captureException(err);- return res.status(400).send({- message: 'Failed to send organization invite'- });- }+ const { organizationId, inviteeEmail } = req.body;+ const host = req.headers.host;+ const siteUrl = `${req.protocol}://${host}`;++ // validate membership+ const membershipOrg = await MembershipOrg.findOne({+ user: req.user._id,+ organization: organizationId+ });++ if (!membershipOrg) {+ throw new Error('Failed to validate organization membership');+ }++++ const plan = await EELicenseService.getOrganizationPlan(organizationId);++++ if (plan.memberLimit !== null) {++ // case: limit imposed on number of members allowed++++ if (plan.membersUsed >= plan.memberLimit) {++ // case: number of members used exceeds the number of members allowed++ return res.status(400).send({++ message: 'Failed to invite member due to member limit reached. Upgrade plan to invite more members.'++ });++ }++ }++ invitee = await User.findOne({+ email: inviteeEmail+ }).select('+publicKey');++ if (invitee) {+ // case: invitee is an existing user++ inviteeMembershipOrg = await MembershipOrg.findOne({+ user: invitee._id,+ organization: organizationId+ });++ if (inviteeMembershipOrg && inviteeMembershipOrg.status === ACCEPTED) {+ throw new Error(+ 'Failed to invite an existing member of the organization'+ );+ }++ if (!inviteeMembershipOrg) {++ await new MembershipOrg({+ user: invitee,+ inviteEmail: inviteeEmail,+ organization: organizationId,+ role: MEMBER,+ status: INVITED+ }).save();+ }+ } else {+ // check if invitee has been invited before+ inviteeMembershipOrg = await MembershipOrg.findOne({+ inviteEmail: inviteeEmail,+ organization: organizationId+ });++ if (!inviteeMembershipOrg) {+ // case: invitee has never been invited before++++ // validate that email is not disposable++ validateUserEmail(inviteeEmail);++ await new MembershipOrg({+ inviteEmail: inviteeEmail,+ organization: organizationId,+ role: MEMBER,+ status: INVITED+ }).save();+ }+ }++ const organization = await Organization.findOne({ _id: organizationId });++ if (organization) {++ const token = await TokenService.createToken({+ type: TOKEN_EMAIL_ORG_INVITATION,+ email: inviteeEmail,+ organizationId: organization._id+ });++ await sendMail({+ template: 'organizationInvitation.handlebars',+ subjectLine: 'Infisical organization invitation',+ recipients: [inviteeEmail],+ substitutions: {+ inviterFirstName: req.user.firstName,+ inviterEmail: req.user.email,+ organizationName: organization.name,+ email: inviteeEmail,+ organizationId: organization._id.toString(),+ token,+ callback_url: (await getSiteURL()) + '/signupinvite'+ }+ });++ if (!(await getSmtpConfigured())) {+ completeInviteLink = `${siteUrl + '/signupinvite'}?token=${token}&to=${inviteeEmail}&organization_id=${organization._id}`+ }+ }++ await updateSubscriptionOrgQuantity({ organizationId });return res.status(200).send({message: `Sent an invite link to ${req.body.inviteeEmail}`,diff --cc backend/src/controllers/v1/passwordController.tsindex a8d2bae858,5ce092038d..bdeae0fd46--- a/backend/src/controllers/v1/passwordController.ts+++ b/backend/src/controllers/v1/passwordController.ts@@@ -30,44 -18,35 +29,36 @@@ import* @returns*/export const emailPasswordReset = async (req: Request, res: Response) => {- const email = req.body.email;+ let email: string;- try {- email = req.body.email;-- const user = await User.findOne({ email }).select('+publicKey');- if (!user || !user?.publicKey) {- // case: user has already completed account-- return res.status(403).send({- message: "If an account exists with this email, a password reset link has been sent"- });- }-- const token = await TokenService.createToken({- type: TOKEN_EMAIL_PASSWORD_RESET,- });-- await sendMail({- template: 'passwordReset.handlebars',- subjectLine: 'Infisical password reset',- recipients: [email],- substitutions: {- email,- token,- callback_url: (await getSiteURL()) + '/password-reset'- }- });- } catch (err) {- Sentry.setUser(null);- Sentry.captureException(err);- return res.status(400).send({- message: 'Failed to send email for account recovery'- });- }++ email = req.body.email;++ const user = await User.findOne({ email }).select('+publicKey');+ if (!user || !user?.publicKey) {+ // case: user has already completed account++ return res.status(403).send({- error: 'Failed to send email verification for password reset'++ message: "If an account exists with this email, a password reset link has been sent"+ });+ }++ const token = await TokenService.createToken({+ type: TOKEN_EMAIL_PASSWORD_RESET,+ });++ await sendMail({+ template: 'passwordReset.handlebars',+ subjectLine: 'Infisical password reset',+ recipients: [email],+ substitutions: {+ email,+ token,+ callback_url: (await getSiteURL()) + '/password-reset'+ }+ });return res.status(200).send({- message: `Sent an email for account recovery to ${email}`+ message:"If an account exists with this email, a password reset link has been sent"});}@@@ -128,45 -98,36 +110,38 @@@ export const emailPasswordResetVerify*/export const srp1 = async (req: Request, res: Response) => {// return salt, serverPublicKey as part of first step of SRP protocol+- try {- const { clientPublicKey } = req.body;- const user = await User.findOne({- email: req.user.email- }).select('+salt +verifier');-- if (!user) throw new Error('Failed to find user');-- const server = new jsrp.server();- server.init(- {- salt: user.salt,- verifier: user.verifier- },- async () => {- // generate server-side public key- const serverPublicKey = server.getPublicKey();-- await LoginSRPDetail.findOneAndReplace({ email: req.user.email }, {- email: req.user.email,- clientPublicKey: clientPublicKey,- serverBInt: bigintConversion.bigintToBuf(server.bInt),- }, { upsert: true, returnNewDocument: false })-- return res.status(200).send({- serverPublicKey,- salt: user.salt- });- }- );- } catch (err) {- Sentry.setUser({ email: req.user.email });- Sentry.captureException(err);- return res.status(400).send({- error: 'Failed to start change password process'- });- }- };+ const { clientPublicKey } = req.body;+ const user = await User.findOne({+ email: req.user.email+ }).select('+salt +verifier');++ if (!user) throw new Error('Failed to find user');++ const server = new jsrp.server();+ server.init(+ {+ salt: user.salt,+ verifier: user.verifier+ },+ async () => {+ // generate server-side public key+ const serverPublicKey = server.getPublicKey();++ await LoginSRPDetail.findOneAndReplace({ email: req.user.email }, {+ email: req.user.email,+ clientPublicKey: clientPublicKey,+ serverBInt: bigintConversion.bigintToBuf(server.bInt),+ }, { upsert: true, returnNewDocument: false })++ return res.status(200).send({+ serverPublicKey,+ salt: user.salt+ });+ }+ );-};++}++/*** Change account SRP authentication information for user@@@ -177,93 -138,72 +152,85 @@@* @returns*/export const changePassword = async (req: Request, res: Response) => {- try {- const {- clientProof,- protectedKey,- protectedKeyIV,- protectedKeyTag,- encryptedPrivateKey,- encryptedPrivateKeyIV,- encryptedPrivateKeyTag,- salt,- verifier- } = req.body;-- const user = await User.findOne({- email: req.user.email- }).select('+salt +verifier');-- if (!user) throw new Error('Failed to find user');-- const loginSRPDetailFromDB = await LoginSRPDetail.findOneAndDelete({ email: req.user.email })-- if (!loginSRPDetailFromDB) {- return BadRequestError(Error("It looks like some details from the first login are not found. Please try login one again"))- }-- const server = new jsrp.server();- server.init(- {- salt: user.salt,- verifier: user.verifier,- b: loginSRPDetailFromDB.serverBInt- },- async () => {- server.setClientPublicKey(loginSRPDetailFromDB.clientPublicKey);-- // compare server and client shared keys- if (server.checkClientProof(clientProof)) {- // change password-- await User.findByIdAndUpdate(- req.user._id.toString(),- {- encryptionVersion: 2,- protectedKey,- protectedKeyIV,- protectedKeyTag,- encryptedPrivateKey,- iv: encryptedPrivateKeyIV,- tag: encryptedPrivateKeyTag,- salt,- verifier- },- {- new: true- }- );-- if (req.authData.authMode === AUTH_MODE_JWT && req.authData.authPayload instanceof User && req.authData.tokenVersionId) {- await clearTokens(req.authData.tokenVersionId)- }-- // clear httpOnly cookie-- res.cookie('jid', '', {- httpOnly: true,- path: '/',- sameSite: 'strict',- secure: (await getHttpsEnabled()) as boolean- });-- return res.status(200).send({- message: 'Successfully changed password'- });- }-- return res.status(400).send({- error: 'Failed to change password. Try again?'- });- }- );- } catch (err) {- Sentry.setUser({ email: req.user.email });- Sentry.captureException(err);- return res.status(400).send({- error: 'Failed to change password. Try again?'- });- }+ const {+ clientProof,+ protectedKey,+ protectedKeyIV,+ protectedKeyTag,+ encryptedPrivateKey,+ encryptedPrivateKeyIV,+ encryptedPrivateKeyTag,+ salt,+ verifier+ } = req.body;++ const user = await User.findOne({+ email: req.user.email+ }).select('+salt +verifier');++ if (!user) throw new Error('Failed to find user');++ const loginSRPDetailFromDB = await LoginSRPDetail.findOneAndDelete({ email: req.user.email })++ if (!loginSRPDetailFromDB) {+ return BadRequestError(Error("It looks like some details from the first login are not found. Please try login one again"))+ }++ const server = new jsrp.server();+ server.init(+ {+ salt: user.salt,+ verifier: user.verifier,+ b: loginSRPDetailFromDB.serverBInt+ },+ async () => {+ server.setClientPublicKey(loginSRPDetailFromDB.clientPublicKey);++ // compare server and client shared keys+ if (server.checkClientProof(clientProof)) {+ // change password++ await User.findByIdAndUpdate(+ req.user._id.toString(),+ {+ encryptionVersion: 2,+ protectedKey,+ protectedKeyIV,+ protectedKeyTag,+ encryptedPrivateKey,+ iv: encryptedPrivateKeyIV,+ tag: encryptedPrivateKeyTag,+ salt,+ verifier+ },+ {+ new: true+ }+ );++++ if (req.authData.authMode === AUTH_MODE_JWT && req.authData.authPayload instanceof User && req.authData.tokenVersionId) {++ await clearTokens(req.authData.tokenVersionId)++ }++++ // clear httpOnly cookie++++ res.cookie('jid', '', {++ httpOnly: true,++ path: '/',++ sameSite: 'strict',++ secure: (await getHttpsEnabled()) as boolean++ });++ return res.status(200).send({+ message: 'Successfully changed password'+ });+ }++ return res.status(400).send({+ error: 'Failed to change password. Try again?'+ });+ }+ );};/**diff --cc backend/src/controllers/v1/secretController.tsindex 2733f80117,e3d6818ae0..074e294548--- a/backend/src/controllers/v1/secretController.ts+++ b/backend/src/controllers/v1/secretController.ts@@@ -111,59 -100,50 +100,52 @@@ export const pushSecrets = async (req:* @returns*/export const pullSecrets = async (req: Request, res: Response) => {- const postHogClient = await TelemetryService.getPostHogClient();- const environment: string = req.query.environment as string;- const channel: string = req.query.channel as string;- const { workspaceId } = req.params;-- // validate environment- const workspaceEnvs = req.membership.workspace.environments;- if (!workspaceEnvs.find(({ slug }: { slug: string }) => slug === environment)) {- throw new Error('Failed to validate environment');- }-- let secrets = await pull({- userId: req.user._id.toString(),- workspaceId,- environment,- channel: channel ? channel : 'cli',- ipAddress: req.ip- });+ let secrets;+ let key;- try {- const postHogClient = await TelemetryService.getPostHogClient();- const environment: string = req.query.environment as string;- const channel: string = req.query.channel as string;- const { workspaceId } = req.params;-- // validate environment- const workspaceEnvs = req.membership.workspace.environments;- if (!workspaceEnvs.find(({ slug }: { slug: string }) => slug === environment)) {- throw new Error('Failed to validate environment');- }-- secrets = await pull({- userId: req.user._id.toString(),- workspaceId,- environment,- channel: channel ? channel : 'cli',- ipAddress: req.realIP- });+- key = await Key.findOne({- workspace: workspaceId,- receiver: req.user._id- })- .sort({ createdAt: -1 })- .populate('sender', '+publicKey');-- if (channel !== 'cli') {- secrets = reformatPullSecrets({ secrets });- }-- if (postHogClient) {- // capture secrets pushed event in production- postHogClient.capture({- distinctId: req.user.email,- event: 'secrets pulled',- properties: {- numberOfSecrets: secrets.length,- environment,- workspaceId,- channel: channel ? channel : 'cli'- }- });- }- } catch (err) {- Sentry.setUser({ email: req.user.email });- Sentry.captureException(err);- return res.status(400).send({- message: 'Failed to pull workspace secrets'++ const postHogClient = await TelemetryService.getPostHogClient();++ const environment: string = req.query.environment as string;++ const channel: string = req.query.channel as string;++ const { workspaceId } = req.params;++++ // validate environment++ const workspaceEnvs = req.membership.workspace.environments;++ if (!workspaceEnvs.find(({ slug }: { slug: string }) => slug === environment)) {++ throw new Error('Failed to validate environment');++ }++++ secrets = await pull({++ userId: req.user._id.toString(),++ workspaceId,++ environment,++ channel: channel ? channel : 'cli',++ ipAddress: req.realIP++ });+- const key = await Key.findOne({- workspace: workspaceId,- receiver: req.user._id- })- .sort({ createdAt: -1 })- .populate('sender', '+publicKey');-- if (channel !== 'cli') {- // FIX: Fix this any- secrets = reformatPullSecrets({ secrets }) as any;- }-- if (postHogClient) {- // capture secrets pushed event in production- postHogClient.capture({- distinctId: req.user.email,- event: 'secrets pulled',- properties: {- numberOfSecrets: secrets.length,- environment,- workspaceId,- channel: channel ? channel : 'cli'- }- });- }++ key = await Key.findOne({++ workspace: workspaceId,++ receiver: req.user._id++ })++ .sort({ createdAt: -1 })++ .populate('sender', '+publicKey');++++ if (channel !== 'cli') {++ secrets = reformatPullSecrets({ secrets });++ }++++ if (postHogClient) {++ // capture secrets pushed event in production++ postHogClient.capture({++ distinctId: req.user.email,++ event: 'secrets pulled',++ properties: {++ numberOfSecrets: secrets.length,++ environment,++ workspaceId,++ channel: channel ? channel : 'cli'++ }+ });+ }return res.status(200).send({secrets,@@@ -180,58 -160,48 +162,51 @@@* @returns*/export const pullSecretsServiceToken = async (req: Request, res: Response) => {- const postHogClient = await TelemetryService.getPostHogClient();- const environment: string = req.query.environment as string;- const channel: string = req.query.channel as string;- const { workspaceId } = req.params;-- // validate environment- const workspaceEnvs = req.membership.workspace.environments;- if (!workspaceEnvs.find(({ slug }: { slug: string }) => slug === environment)) {- throw new Error('Failed to validate environment');- }-- const secrets = await pull({- userId: req.serviceToken.user._id.toString(),- workspaceId,- environment,- channel: 'cli',- ipAddress: req.ip- });-- const key = {- encryptedKey: req.serviceToken.encryptedKey,- nonce: req.serviceToken.nonce,- sender: {- publicKey: req.serviceToken.publicKey- },- receiver: req.serviceToken.user,- workspace: req.serviceToken.workspace- };+ let secrets;+ let key;- try {- const postHogClient = await TelemetryService.getPostHogClient();- const environment: string = req.query.environment as string;- const channel: string = req.query.channel as string;- const { workspaceId } = req.params;-- // validate environment- const workspaceEnvs = req.membership.workspace.environments;- if (!workspaceEnvs.find(({ slug }: { slug: string }) => slug === environment)) {- throw new Error('Failed to validate environment');- }-- secrets = await pull({- userId: req.serviceToken.user._id.toString(),- workspaceId,- environment,- channel: 'cli',- ipAddress: req.realIP- });+- key = {- encryptedKey: req.serviceToken.encryptedKey,- nonce: req.serviceToken.nonce,- sender: {- publicKey: req.serviceToken.publicKey- },- receiver: req.serviceToken.user,- workspace: req.serviceToken.workspace- };-- if (postHogClient) {- // capture secrets pulled event in production- postHogClient.capture({- distinctId: req.serviceToken.user.email,- event: 'secrets pulled',- properties: {- numberOfSecrets: secrets.length,- environment,- workspaceId,- channel: channel ? channel : 'cli'- }- });- }- } catch (err) {- Sentry.setUser({ email: req.serviceToken.user.email });- Sentry.captureException(err);- return res.status(400).send({- message: 'Failed to pull workspace secrets'++ const postHogClient = await TelemetryService.getPostHogClient();++ const environment: string = req.query.environment as string;++ const channel: string = req.query.channel as string;++ const { workspaceId } = req.params;++++ // validate environment++ const workspaceEnvs = req.membership.workspace.environments;++ if (!workspaceEnvs.find(({ slug }: { slug: string }) => slug === environment)) {++ throw new Error('Failed to validate environment');++ }++++ secrets = await pull({++ userId: req.serviceToken.user._id.toString(),++ workspaceId,++ environment,++ channel: 'cli',++ ipAddress: req.realIP++ });+- if (postHogClient) {- // capture secrets pulled event in production- postHogClient.capture({- distinctId: req.serviceToken.user.email,- event: 'secrets pulled',- properties: {- numberOfSecrets: secrets.length,- environment,- workspaceId,- channel: channel ? channel : 'cli'- }- });- }++ key = {++ encryptedKey: req.serviceToken.encryptedKey,++ nonce: req.serviceToken.nonce,++ sender: {++ publicKey: req.serviceToken.publicKey++ },++ receiver: req.serviceToken.user,++ workspace: req.serviceToken.workspace++ };++++ if (postHogClient) {++ // capture secrets pulled event in production++ postHogClient.capture({++ distinctId: req.serviceToken.user.email,++ event: 'secrets pulled',++ properties: {++ numberOfSecrets: secrets.length,++ environment,++ workspaceId,++ channel: channel ? channel : 'cli'++ }+ });+ }return res.status(200).send({secrets: reformatPullSecrets({ secrets }),diff --cc backend/src/controllers/v1/signupController.tsindex 17e0125f44,9fede9b1a4..19bf94e611--- a/backend/src/controllers/v1/signupController.ts+++ b/backend/src/controllers/v1/signupController.ts@@@ -18,32 -16,20 +17,24 @@@ import { validateUserEmail } from '../.* @returns*/export const beginEmailSignup = async (req: Request, res: Response) => {- const email = req.body.email;+ let email: string;- try {- email = req.body.email;-- // validate that email is not disposable- validateUserEmail(email);++ email = req.body.email;++++ // validate that email is not disposable++ validateUserEmail(email);- const user = await User.findOne({ email }).select('+publicKey');- if (user && user?.publicKey) {- // case: user has already completed account+ const user = await User.findOne({ email }).select('+publicKey');+ if (user && user?.publicKey) {+ // case: user has already completed account- return res.status(403).send({- error: 'Failed to send email verification code for complete account'- });- }+ return res.status(403).send({+ error: 'Failed to send email verification code for complete account'+ });+ }++ // send send verification email+ await sendEmailVerification({ email });- // send send verification email- await sendEmailVerification({ email });- } catch (err) {- Sentry.setUser(null);- Sentry.captureException(err);- return res.status(400).send({- error: 'Failed to send email verification code'- });- }-return res.status(200).send({message: `Sent an email verification code to ${email}`});diff --cc backend/src/controllers/v1/workspaceController.tsindex a914fa9c26,92ae52b11f..796a7bebce--- a/backend/src/controllers/v1/workspaceController.ts+++ b/backend/src/controllers/v1/workspaceController.ts@@@ -141,56 -103,34 +104,46 @@@ export const getWorkspace = async (req* @returns*/export const createWorkspace = async (req: Request, res: Response) => {- let workspace;-- try {- const { workspaceName, organizationId } = req.body;+ const { workspaceName, organizationId } = req.body;- // validate organization membership- const membershipOrg = await MembershipOrg.findOne({- user: req.user._id,- organization: organizationId,- });+ // validate organization membership+ const membershipOrg = await MembershipOrg.findOne({+ user: req.user._id,+ organization: organizationId,+ });- if (!membershipOrg) {- throw new Error("Failed to validate organization membership");- }+ if (!membershipOrg) {+ throw new Error("Failed to validate organization membership");+ }- const plan = await EELicenseService.getOrganizationPlan(organizationId);++ const plan = await EELicenseService.getOrganizationPlan(organizationId);+- if (plan.workspaceLimit !== null) {- // case: limit imposed on number of workspaces allowed- if (plan.workspacesUsed >= plan.workspaceLimit) {- // case: number of workspaces used exceeds the number of workspaces allowed- return res.status(400).send({- message: 'Failed to create workspace due to plan limit reached. Upgrade plan to add more workspaces.'- });- }- }-- if (workspaceName.length < 1) {- throw new Error("Workspace names must be at least 1-character long");++ if (plan.workspaceLimit !== null) {++ // case: limit imposed on number of workspaces allowed++ if (plan.workspacesUsed >= plan.workspaceLimit) {++ // case: number of workspaces used exceeds the number of workspaces allowed++ return res.status(400).send({++ message: 'Failed to create workspace due to plan limit reached. Upgrade plan to add more workspaces.'++ });+ }++ }+- // create workspace and add user as member- workspace = await create({- name: workspaceName,- organizationId,- });-- await addMemberships({- userIds: [req.user._id],- workspaceId: workspace._id.toString(),- roles: [ADMIN],- });- } catch (err) {- Sentry.setUser({ email: req.user.email });- Sentry.captureException(err);- return res.status(400).send({- message: "Failed to create workspace",- });+ if (workspaceName.length < 1) {+ throw new Error("Workspace names must be at least 1-character long");}+ // create workspace and add user as member+ const workspace = await create({+ name: workspaceName,+ organizationId,+ });++ await addMemberships({+ userIds: [req.user._id],+ workspaceId: workspace._id.toString(),+ roles: [ADMIN],+ });+return res.status(200).send({workspace,});diff --cc backend/src/controllers/v2/authController.tsindex 26e514dca1,62735d05ca..daf9ca3410--- a/backend/src/controllers/v2/authController.ts+++ b/backend/src/controllers/v2/authController.ts@@@ -86,153 -78,140 +78,225 @@@ export const login1 = async (req: Reque* @returns*/export const login2 = async (req: Request, res: Response) => {- try {+ if (!req.headers['user-agent']) throw InternalServerError({ message: 'User-Agent header is required' });++<<<<<<< HEAD+ if (!req.headers['user-agent']) throw InternalServerError({ message: 'User-Agent header is required' });++ const { email, clientProof } = req.body;+ const user = await User.findOne({+ }).select('+salt +verifier +encryptionVersion +protectedKey +protectedKeyIV +protectedKeyTag +publicKey +encryptedPrivateKey +iv +tag +devices');++=======+ const { email, clientProof } = req.body;+ const user = await User.findOne({+ }).select('+salt +verifier +encryptionVersion +protectedKey +protectedKeyIV +protectedKeyTag +publicKey +encryptedPrivateKey +iv +tag');++>>>>>>> origin/main- if (!user) throw new Error('Failed to find user');+ if (!user) throw new Error('Failed to find user');- const loginSRPDetail = await LoginSRPDetail.findOneAndDelete({ email: email })+ const loginSRPDetail = await LoginSRPDetail.findOneAndDelete({ email: email })- if (!loginSRPDetail) {- return BadRequestError(Error("Failed to find login details for SRP"))- }+ if (!loginSRPDetail) {+ return BadRequestError(Error("Failed to find login details for SRP"))+ }++<<<<<<< HEAD+ const server = new jsrp.server();+ server.init(+ {+ salt: user.salt,+ verifier: user.verifier,+ b: loginSRPDetail.serverBInt+ },+ async () => {+ server.setClientPublicKey(loginSRPDetail.clientPublicKey);++ // compare server and client shared keys+ if (server.checkClientProof(clientProof)) {++ if (user.isMfaEnabled) {+ // case: user has MFA enabled++ // generate temporary MFA token+ const token = createToken({+ payload: {+ userId: user._id.toString()+ },+ expiresIn: await getJwtMfaLifetime(),+ secret: await getJwtMfaSecret()+ });++ const code = await TokenService.createToken({+ type: TOKEN_EMAIL_MFA,+ });++ // send MFA code [code] to [email]+ await sendMail({+ template: 'emailMfa.handlebars',+ subjectLine: 'Infisical MFA code',+ recipients: [email],+ substitutions: {+ code+ }+ });++ return res.status(200).send({+ mfaEnabled: true,+ token+ });+ }++ await checkUserDevice({+ user,+ ip: req.realIP,+ userAgent: req.headers['user-agent'] ?? ''+ });++ // issue tokens+ const tokens = await issueAuthTokens({+ userId: user._id,+ ip: req.realIP,+ userAgent: req.headers['user-agent'] ?? ''+ });++ // store (refresh) token in httpOnly cookie+ res.cookie('jid', tokens.refreshToken, {+ httpOnly: true,+ path: '/',+ sameSite: 'strict',+ secure: await getHttpsEnabled()++=======+ const server = new jsrp.server();+ server.init(+ {+ salt: user.salt,+ verifier: user.verifier,+ b: loginSRPDetail.serverBInt+ },+ async () => {+ server.setClientPublicKey(loginSRPDetail.clientPublicKey);++ // compare server and client shared keys+ if (server.checkClientProof(clientProof)) {++ if (user.isMfaEnabled) {+ // case: user has MFA enabled++ // generate temporary MFA token+ const token = createToken({+ payload: {+ userId: user._id.toString()+ },+ expiresIn: await getJwtMfaLifetime(),+ secret: await getJwtMfaSecret()});- // case: user does not have MFA enablgged- // return (access) token in response-- interface ResponseData {- mfaEnabled: boolean;- encryptionVersion: any;- protectedKey?: string;- protectedKeyIV?: string;- protectedKeyTag?: string;- token: string;- publicKey?: string;- encryptedPrivateKey?: string;- iv?: string;- tag?: string;- }-- const response: ResponseData = {- mfaEnabled: false,- encryptionVersion: user.encryptionVersion,- token: tokens.token,- publicKey: user.publicKey,- encryptedPrivateKey: user.encryptedPrivateKey,- iv: user.iv,- tag: user.tag- }-- if (- user?.protectedKey &&- user?.protectedKeyIV &&- user?.protectedKeyTag- ) {- response.protectedKey = user.protectedKey;- response.protectedKeyIV = user.protectedKeyIV- response.protectedKeyTag = user.protectedKeyTag;- }+ const code = await TokenService.createToken({+ type: TOKEN_EMAIL_MFA,++>>>>>>> origin/main+ });- const loginAction = await EELogService.createAction({- name: ACTION_LOGIN,- userId: user._id+ // send MFA code [code] to [email]+ await sendMail({+ template: 'emailMfa.handlebars',+ subjectLine: 'Infisical MFA code',+ recipients: [email],+ substitutions: {+ code+ }});++<<<<<<< HEAD+ loginAction && await EELogService.createLog({+ userId: user._id,+ actions: [loginAction],+ channel: getChannelFromUserAgent(req.headers['user-agent']),+ ipAddress: req.realIP++=======+ return res.status(200).send({+ mfaEnabled: true,+ token++>>>>>>> origin/main});+ }++ await checkUserDevice({+ user,+ ip: req.ip,+ userAgent: req.headers['user-agent'] ?? ''+ });++ // issue tokens+ const tokens = await issueAuthTokens({ userId: user._id.toString() });++ // store (refresh) token in httpOnly cookie+ res.cookie('jid', tokens.refreshToken, {+ httpOnly: true,+ path: '/',+ sameSite: 'strict',+ secure: await getHttpsEnabled()+ });- return res.status(200).send(response);+ // case: user does not have MFA enablgged+ // return (access) token in response++ interface ResponseData {+ mfaEnabled: boolean;+ encryptionVersion: any;+ protectedKey?: string;+ protectedKeyIV?: string;+ protectedKeyTag?: string;+ token: string;+ publicKey?: string;+ encryptedPrivateKey?: string;+ iv?: string;+ tag?: string;}- return res.status(400).send({- message: 'Failed to authenticate. Try again?'+ const response: ResponseData = {+ mfaEnabled: false,+ encryptionVersion: user.encryptionVersion,+ token: tokens.token,+ publicKey: user.publicKey,+ encryptedPrivateKey: user.encryptedPrivateKey,+ iv: user.iv,+ tag: user.tag+ }++ if (+ user?.protectedKey &&+ user?.protectedKeyIV &&+ user?.protectedKeyTag+ ) {+ response.protectedKey = user.protectedKey;+ response.protectedKeyIV = user.protectedKeyIV+ response.protectedKeyTag = user.protectedKeyTag;+ }++ const loginAction = await EELogService.createAction({+ name: ACTION_LOGIN,+ userId: user._id+ });++ loginAction && await EELogService.createLog({+ userId: user._id,+ actions: [loginAction],+ channel: getChannelFromUserAgent(req.headers['user-agent']),+ ipAddress: req.ip});++ return res.status(200).send(response);}- );- } catch (err) {- Sentry.setUser(null);- Sentry.captureException(err);- return res.status(400).send({- message: 'Failed to authenticate. Try again?'- });- }++ return res.status(400).send({+ message: 'Failed to authenticate. Try again?'+ });+ }+ );};/**diff --cc backend/src/controllers/v2/signupController.tsindex 8f1e928ffc,cbaa7a6b6b..9e10e2f3e5--- a/backend/src/controllers/v2/signupController.ts+++ b/backend/src/controllers/v2/signupController.ts@@@ -20,138 -19,128 +19,137 @@@ import { updateSubscriptionOrgQuantity*/export const completeAccountSignup = async (req: Request, res: Response) => {let user, token, refreshToken;- try {- const {- email,- firstName,- lastName,- protectedKey,- protectedKeyIV,- protectedKeyTag,- publicKey,- encryptedPrivateKey,- encryptedPrivateKeyIV,- encryptedPrivateKeyTag,- salt,- verifier,- organizationName- }: {- email: string;- firstName: string;- lastName: string;- protectedKey: string;- protectedKeyIV: string;- protectedKeyTag: string;- publicKey: string;- encryptedPrivateKey: string;- encryptedPrivateKeyIV: string;- encryptedPrivateKeyTag: string;- salt: string;- verifier: string;- organizationName: string;- } = req.body;+ const {+ email,+ firstName,+ lastName,+ protectedKey,+ protectedKeyIV,+ protectedKeyTag,+ publicKey,+ encryptedPrivateKey,+ encryptedPrivateKeyIV,+ encryptedPrivateKeyTag,+ salt,+ verifier,+ organizationName+ }: {+ email: string;+ firstName: string;+ lastName: string;+ protectedKey: string;+ protectedKeyIV: string;+ protectedKeyTag: string;+ publicKey: string;+ encryptedPrivateKey: string;+ encryptedPrivateKeyIV: string;+ encryptedPrivateKeyTag: string;+ salt: string;+ verifier: string;+ organizationName: string;+ } = req.body;- // get user- user = await User.findOne({ email });+ // get user+ user = await User.findOne({ email });- if (!user || (user && user?.publicKey)) {- // case 1: user doesn't exist.- // case 2: user has already completed account- return res.status(403).send({- error: 'Failed to complete account for complete user'- });- }+ if (!user || (user && user?.publicKey)) {+ // case 1: user doesn't exist.+ // case 2: user has already completed account+ return res.status(403).send({+ error: 'Failed to complete account for complete user'+ });+ }- // complete setting up user's account- user = await completeAccount({- userId: user._id.toString(),- firstName,- lastName,- encryptionVersion: 2,- protectedKey,- protectedKeyIV,- protectedKeyTag,- publicKey,- encryptedPrivateKey,- encryptedPrivateKeyIV,- encryptedPrivateKeyTag,- salt,- verifier- });+ // complete setting up user's account+ user = await completeAccount({+ userId: user._id.toString(),+ firstName,+ lastName,+ encryptionVersion: 2,+ protectedKey,+ protectedKeyIV,+ protectedKeyTag,+ publicKey,+ encryptedPrivateKey,+ encryptedPrivateKeyIV,+ encryptedPrivateKeyTag,+ salt,+ verifier+ });- if (!user)- throw new Error('Failed to complete account for non-existent user'); // ensure user is non-null+ if (!user)+ throw new Error('Failed to complete account for non-existent user'); // ensure user is non-null- // initialize default organization and workspace- await initializeDefaultOrg({- organizationName,- user- });+ // initialize default organization and workspace+ await initializeDefaultOrg({+ organizationName,+ user+ });- // update organization membership statuses that are- // invited to completed with user attached- const membershipsToUpdate = await MembershipOrg.find({- inviteEmail: email,- status: INVITED- });-- membershipsToUpdate.forEach(async (membership) => {- await updateSubscriptionOrgQuantity({- organizationId: membership.organization.toString()- });- });+ // update organization membership statuses that are+ // invited to completed with user attached+ const membershipsToUpdate = await MembershipOrg.find({+ inviteEmail: email,+ status: INVITED+ });++ membershipsToUpdate.forEach(async (membership) => {+ await updateSubscriptionOrgQuantity({+ organizationId: membership.organization.toString()+ });+ });- // update organization membership statuses that are- // invited to completed with user attached- await MembershipOrg.updateMany(- {- inviteEmail: email,- status: INVITED- },- {- user,- status: ACCEPTED- }- );+ // update organization membership statuses that are+ // invited to completed with user attached+ await MembershipOrg.updateMany(+ {+ inviteEmail: email,+ status: INVITED+ },+ {+ user,+ status: ACCEPTED+ }+ );++<<<<<<< HEAD+ // issue tokens+ const tokens = await issueAuthTokens({+ userId: user._id,+ ip: req.realIP,+ userAgent: req.headers['user-agent'] ?? ''+ });++=======+ // issue tokens+ const tokens = await issueAuthTokens({+ userId: user._id.toString()+ });++>>>>>>> origin/main- token = tokens.token;+ token = tokens.token;- // sending a welcome email to new users- if (await getLoopsApiKey()) {- await standardRequest.post("https://app.loops.so/api/v1/events/send", {- "email": email,- "eventName": "Sign Up",- "firstName": firstName,- "lastName": lastName- }, {- headers: {- "Accept": "application/json",- "Authorization": "Bearer " + (await getLoopsApiKey())- },- });- }+ // sending a welcome email to new users+ if (await getLoopsApiKey()) {+ await standardRequest.post("https://app.loops.so/api/v1/events/send", {+ "email": email,+ "eventName": "Sign Up",+ "firstName": firstName,+ "lastName": lastName+ }, {+ headers: {+ "Accept": "application/json",+ "Authorization": "Bearer " + (await getLoopsApiKey())+ },+ });+ }- // store (refresh) token in httpOnly cookie- res.cookie('jid', tokens.refreshToken, {- httpOnly: true,- path: '/',- sameSite: 'strict',- secure: await getHttpsEnabled()- });- } catch (err) {- Sentry.setUser(null);- Sentry.captureException(err);- return res.status(400).send({- message: 'Failed to complete account setup'- });- }+ // store (refresh) token in httpOnly cookie+ res.cookie('jid', tokens.refreshToken, {+ httpOnly: true,+ path: '/',+ sameSite: 'strict',+ secure: await getHttpsEnabled()+ });return res.status(200).send({message: 'Successfully set up account',@@@ -169,107 -158,97 +167,106 @@@*/export const completeAccountInvite = async (req: Request, res: Response) => {let user, token, refreshToken;- try {- const {- email,- firstName,- lastName,- protectedKey,- protectedKeyIV,- protectedKeyTag,- publicKey,- encryptedPrivateKey,- encryptedPrivateKeyIV,- encryptedPrivateKeyTag,- salt,- verifier- } = req.body;+ const {+ email,+ firstName,+ lastName,+ protectedKey,+ protectedKeyIV,+ protectedKeyTag,+ publicKey,+ encryptedPrivateKey,+ encryptedPrivateKeyIV,+ encryptedPrivateKeyTag,+ salt,+ verifier+ } = req.body;- // get user- user = await User.findOne({ email });+ // get user+ user = await User.findOne({ email });- if (!user || (user && user?.publicKey)) {- // case 1: user doesn't exist.- // case 2: user has already completed account- return res.status(403).send({- error: 'Failed to complete account for complete user'- });- }+ if (!user || (user && user?.publicKey)) {+ // case 1: user doesn't exist.+ // case 2: user has already completed account+ return res.status(403).send({+ error: 'Failed to complete account for complete user'+ });+ }- const membershipOrg = await MembershipOrg.findOne({- inviteEmail: email,- status: INVITED- });+ const membershipOrg = await MembershipOrg.findOne({+ inviteEmail: email,+ status: INVITED+ });- if (!membershipOrg) throw new Error('Failed to find invitations for email');+ if (!membershipOrg) throw new Error('Failed to find invitations for email');- // complete setting up user's account- user = await completeAccount({- userId: user._id.toString(),- firstName,- lastName,- encryptionVersion: 2,- protectedKey,- protectedKeyIV,- protectedKeyTag,- publicKey,- encryptedPrivateKey,- encryptedPrivateKeyIV,- encryptedPrivateKeyTag,- salt,- verifier- });+ // complete setting up user's account+ user = await completeAccount({+ userId: user._id.toString(),+ firstName,+ lastName,+ encryptionVersion: 2,+ protectedKey,+ protectedKeyIV,+ protectedKeyTag,+ publicKey,+ encryptedPrivateKey,+ encryptedPrivateKeyIV,+ encryptedPrivateKeyTag,+ salt,+ verifier+ });- if (!user)- throw new Error('Failed to complete account for non-existent user');-- // update organization membership statuses that are- // invited to completed with user attached- const membershipsToUpdate = await MembershipOrg.find({- inviteEmail: email,- status: INVITED- });-- membershipsToUpdate.forEach(async (membership) => {- await updateSubscriptionOrgQuantity({- organizationId: membership.organization.toString()- });- });+ if (!user)+ throw new Error('Failed to complete account for non-existent user');++ // update organization membership statuses that are+ // invited to completed with user attached+ const membershipsToUpdate = await MembershipOrg.find({+ inviteEmail: email,+ status: INVITED+ });++ membershipsToUpdate.forEach(async (membership) => {+ await updateSubscriptionOrgQuantity({+ organizationId: membership.organization.toString()+ });+ });- await MembershipOrg.updateMany(- {- inviteEmail: email,- status: INVITED- },- {- user,- status: ACCEPTED- }- );+ await MembershipOrg.updateMany(+ {+ inviteEmail: email,+ status: INVITED+ },+ {+ user,+ status: ACCEPTED+ }+ );++<<<<<<< HEAD+ // issue tokens+ const tokens = await issueAuthTokens({+ userId: user._id,+ ip: req.realIP,+ userAgent: req.headers['user-agent'] ?? ''+ });++=======+ // issue tokens+ const tokens = await issueAuthTokens({+ userId: user._id.toString()+ });++>>>>>>> origin/main- token = tokens.token;+ token = tokens.token;- // store (refresh) token in httpOnly cookie- res.cookie('jid', tokens.refreshToken, {- httpOnly: true,- path: '/',- sameSite: 'strict',- secure: await getHttpsEnabled()- });- } catch (err) {- Sentry.setUser(null);- Sentry.captureException(err);- return res.status(400).send({- message: 'Failed to complete account setup'- });- }+ // store (refresh) token in httpOnly cookie+ res.cookie('jid', tokens.refreshToken, {+ httpOnly: true,+ path: '/',+ sameSite: 'strict',+ secure: await getHttpsEnabled()+ });return res.status(200).send({message: 'Successfully set up account',diff --cc backend/src/controllers/v2/workspaceController.tsindex 4b3816b4a4,2f67bea86b..27c732de0c--- a/backend/src/controllers/v2/workspaceController.ts+++ b/backend/src/controllers/v2/workspaceController.ts@@@ -47,66 -46,57 +46,120 @@@ interface V2PushSecret*/export const pushWorkspaceSecrets = async (req: Request, res: Response) => {// upload (encrypted) secrets to workspace with id [workspaceId]++<<<<<<< HEAD+ try {+ const postHogClient = await TelemetryService.getPostHogClient();+ let { secrets }: { secrets: V2PushSecret[] } = req.body;+ const { keys, environment, channel } = req.body;+ const { workspaceId } = req.params;++ // validate environment+ const workspaceEnvs = req.membership.workspace.environments;+ if (!workspaceEnvs.find(({ slug }: { slug: string }) => slug === environment)) {+ throw new Error('Failed to validate environment');+ }++ // sanitize secrets+ secrets = secrets.filter(+ (s: V2PushSecret) => s.secretKeyCiphertext !== '' && s.secretValueCiphertext !== ''+ );++ await push({+ userId: req.user._id,+ workspaceId,+ environment,+ secrets,+ channel: channel ? channel : 'cli',+ ipAddress: req.realIP+ });++ await pushKeys({+ userId: req.user._id,+ workspaceId,+ keys+ });++ if (postHogClient) {+ postHogClient.capture({+ event: 'secrets pushed',+ distinctId: req.user.email,+ properties: {+ numberOfSecrets: secrets.length,+ environment,+ workspaceId,+ channel: channel ? channel : 'cli'+ }+ });+ }++ // trigger event - push secrets+ EventService.handleEvent({+ event: eventPushSecrets({+ workspaceId: new Types.ObjectId(workspaceId),+ environment+ })+ });++ } catch (err) {+ Sentry.setUser({ email: req.user.email });+ Sentry.captureException(err);+ return res.status(400).send({+ message: 'Failed to upload workspace secrets'+ });+ }++=======+ const postHogClient = await TelemetryService.getPostHogClient();+ let { secrets }: { secrets: V2PushSecret[] } = req.body;+ const { keys, environment, channel } = req.body;+ const { workspaceId } = req.params;++ // validate environment+ const workspaceEnvs = req.membership.workspace.environments;+ if (!workspaceEnvs.find(({ slug }: { slug: string }) => slug === environment)) {+ throw new Error('Failed to validate environment');+ }++ // sanitize secrets+ secrets = secrets.filter(+ (s: V2PushSecret) => s.secretKeyCiphertext !== '' && s.secretValueCiphertext !== ''+ );++ await push({+ userId: req.user._id,+ workspaceId,+ environment,+ secrets,+ channel: channel ? channel : 'cli',+ ipAddress: req.ip+ });++ await pushKeys({+ userId: req.user._id,+ workspaceId,+ keys+ });++ if (postHogClient) {+ postHogClient.capture({+ event: 'secrets pushed',+ distinctId: req.user.email,+ properties: {+ numberOfSecrets: secrets.length,+ environment,+ workspaceId,+ channel: channel ? channel : 'cli'+ }+ });+ }++ // trigger event - push secrets+ EventService.handleEvent({+ event: eventPushSecrets({+ workspaceId: new Types.ObjectId(workspaceId),+ environment+ })+ });++>>>>>>> origin/mainreturn res.status(200).send({message: 'Successfully uploaded workspace secrets'@@@ -121,57 -111,49 +174,103 @@@* @returns*/export const pullSecrets = async (req: Request, res: Response) => {++<<<<<<< HEAD+ let secrets;+ try {+ const postHogClient = await TelemetryService.getPostHogClient();+ const environment: string = req.query.environment as string;+ const channel: string = req.query.channel as string;+ const { workspaceId } = req.params;++ let userId;+ if (req.user) {+ userId = req.user._id.toString();+ } else if (req.serviceTokenData) {+ userId = req.serviceTokenData.user.toString();+ }+ // validate environment+ const workspaceEnvs = req.membership.workspace.environments;+ if (!workspaceEnvs.find(({ slug }: { slug: string }) => slug === environment)) {+ throw new Error('Failed to validate environment');+ }++ secrets = await pull({+ userId,+ workspaceId,+ environment,+ channel: channel ? channel : 'cli',+ ipAddress: req.realIP+ });++ if (channel !== 'cli') {+ secrets = reformatPullSecrets({ secrets });+ }++ if (postHogClient) {+ // capture secrets pushed event in production+ postHogClient.capture({+ distinctId: req.user.email,+ event: 'secrets pulled',+ properties: {+ numberOfSecrets: secrets.length,+ environment,+ workspaceId,+ channel: channel ? channel : 'cli'+ }+ });+ }+ } catch (err) {+ Sentry.setUser({ email: req.user.email });+ Sentry.captureException(err);+ return res.status(400).send({+ message: 'Failed to pull workspace secrets'+ });+ }++=======+ const postHogClient = await TelemetryService.getPostHogClient();+ const environment: string = req.query.environment as string;+ const channel: string = req.query.channel as string;+ const { workspaceId } = req.params;++ let userId;+ if (req.user) {+ userId = req.user._id.toString();+ } else if (req.serviceTokenData) {+ userId = req.serviceTokenData.user.toString();+ }+ // validate environment+ const workspaceEnvs = req.membership.workspace.environments;+ if (!workspaceEnvs.find(({ slug }: { slug: string }) => slug === environment)) {+ throw new Error('Failed to validate environment');+ }++ let secrets = await pull({+ userId,+ workspaceId,+ environment,+ channel: channel ? channel : 'cli',+ ipAddress: req.ip+ });++ if (channel !== 'cli') {+ // FIX: Fix this any+ secrets = reformatPullSecrets({ secrets }) as any;+ }++ if (postHogClient) {+ // capture secrets pushed event in production+ postHogClient.capture({+ distinctId: req.user.email,+ event: 'secrets pulled',+ properties: {+ numberOfSecrets: secrets.length,+ environment,+ workspaceId,+ channel: channel ? channel : 'cli'+ }+ });+ }++>>>>>>> origin/mainreturn res.status(200).send({secretsdiff --cc backend/src/helpers/integration.tsindex 316ce1c890,90f8b8bdb7..b6f4b0915d--- a/backend/src/helpers/integration.ts+++ b/backend/src/helpers/integration.ts@@@ -16,7 -15,7 +15,6 @@@ importimport {UnauthorizedRequestError,} from '../utils/errors';--import RequestError from '../utils/requestError';interface Update {workspace: string;@@@ -177,31 -162,19 +161,19 @@@ export const syncIntegrationsHelper = a* @param {String} obj.integrationAuthId - id of integration auth* @param {String} refreshToken - decrypted refresh token*/- const getIntegrationAuthRefreshHelper = async ({ integrationAuthId }: { integrationAuthId: Types.ObjectId }) => {+export const getIntegrationAuthRefreshHelper = async ({ integrationAuthId }: { integrationAuthId: Types.ObjectId }) => {- let refreshToken;-- try {- const integrationAuth = await IntegrationAuth- .findById(integrationAuthId)- .select('+refreshCiphertext +refreshIV +refreshTag');+ const integrationAuth = await IntegrationAuth+ .findById(integrationAuthId)+ .select('+refreshCiphertext +refreshIV +refreshTag');- if (!integrationAuth) throw UnauthorizedRequestError({message: 'Failed to locate Integration Authentication credentials'});+ if (!integrationAuth) throw UnauthorizedRequestError({message: 'Failed to locate Integration Authentication credentials'});- refreshToken = await BotService.decryptSymmetric({- workspaceId: integrationAuth.workspace,- ciphertext: integrationAuth.refreshCiphertext as string,- iv: integrationAuth.refreshIV as string,- tag: integrationAuth.refreshTag as string- });-- } catch (err) {- Sentry.setUser(null);- Sentry.captureException(err);- if(err instanceof RequestError)- throw err- else- throw new Error('Failed to get integration refresh token');- }+ const refreshToken = await BotService.decryptSymmetric({+ workspaceId: integrationAuth.workspace,+ ciphertext: integrationAuth.refreshCiphertext as string,+ iv: integrationAuth.refreshIV as string,+ tag: integrationAuth.refreshTag as string+ });return refreshToken;}@@@ -214,53 -187,43 +186,43 @@@* @param {String} obj.integrationAuthId - id of integration auth* @returns {String} accessToken - decrypted access token*/-const getIntegrationAuthAccessHelper = async ({ integrationAuthId }: { integrationAuthId: Types.ObjectId }) => {+export const getIntegrationAuthAccessHelper = async ({ integrationAuthId }: { integrationAuthId: Types.ObjectId }) => {let accessId;let accessToken;- try {- const integrationAuth = await IntegrationAuth- .findById(integrationAuthId)- .select('workspace integration +accessCiphertext +accessIV +accessTag +accessExpiresAt + refreshCiphertext +accessIdCiphertext +accessIdIV +accessIdTag');+ const integrationAuth = await IntegrationAuth+ .findById(integrationAuthId)+ .select('workspace integration +accessCiphertext +accessIV +accessTag +accessExpiresAt + refreshCiphertext +accessIdCiphertext +accessIdIV +accessIdTag');- if (!integrationAuth) throw UnauthorizedRequestError({message: 'Failed to locate Integration Authentication credentials'});+ if (!integrationAuth) throw UnauthorizedRequestError({message: 'Failed to locate Integration Authentication credentials'});- accessToken = await BotService.decryptSymmetric({- workspaceId: integrationAuth.workspace,- ciphertext: integrationAuth.accessCiphertext as string,- iv: integrationAuth.accessIV as string,- tag: integrationAuth.accessTag as string- });+ accessToken = await BotService.decryptSymmetric({+ workspaceId: integrationAuth.workspace,+ ciphertext: integrationAuth.accessCiphertext as string,+ iv: integrationAuth.accessIV as string,+ tag: integrationAuth.accessTag as string+ });- if (integrationAuth?.accessExpiresAt && integrationAuth?.refreshCiphertext) {- // there is a access token expiration date- // and refresh token to exchange with the OAuth2 server-- if (integrationAuth.accessExpiresAt < new Date()) {- // access token is expired- const refreshToken = await getIntegrationAuthRefreshHelper({ integrationAuthId });- accessToken = await exchangeRefresh({- integrationAuth,- refreshToken- });- }- }+ if (integrationAuth?.accessExpiresAt && integrationAuth?.refreshCiphertext) {+ // there is a access token expiration date+ // and refresh token to exchange with the OAuth2 server- if (integrationAuth?.accessIdCiphertext && integrationAuth?.accessIdIV && integrationAuth?.accessIdTag) {- accessId = await BotService.decryptSymmetric({- workspaceId: integrationAuth.workspace,- ciphertext: integrationAuth.accessIdCiphertext as string,- iv: integrationAuth.accessIdIV as string,- tag: integrationAuth.accessIdTag as string+ if (integrationAuth.accessExpiresAt < new Date()) {+ // access token is expired+ const refreshToken = await getIntegrationAuthRefreshHelper({ integrationAuthId });+ accessToken = await exchangeRefresh({+ integrationAuth,+ refreshToken});}-- } catch (err) {- Sentry.setUser(null);- Sentry.captureException(err);- if(err instanceof RequestError)- throw err- else- throw new Error('Failed to get integration access token');+ }++ if (integrationAuth?.accessIdCiphertext && integrationAuth?.accessIdIV && integrationAuth?.accessIdTag) {+ accessId = await BotService.decryptSymmetric({+ workspaceId: integrationAuth.workspace,+ ciphertext: integrationAuth.accessIdCiphertext as string,+ iv: integrationAuth.accessIdIV as string,+ tag: integrationAuth.accessIdTag as string+ });}return ({@@@ -337,45 -293,47 +292,38 @@@ export const setIntegrationAuthAccessHeaccessToken: string;accessExpiresAt: Date | undefined;}) => {- let integrationAuth;- try {- integrationAuth = await IntegrationAuth.findById(integrationAuthId);-- if (!integrationAuth) throw new Error('Failed to find integration auth');-- const encryptedAccessTokenObj = await BotService.encryptSymmetric({+ let integrationAuth = await IntegrationAuth.findById(integrationAuthId);++ if (!integrationAuth) throw new Error('Failed to find integration auth');++ const encryptedAccessTokenObj = await BotService.encryptSymmetric({+ workspaceId: integrationAuth.workspace,+ plaintext: accessToken+ });++ let encryptedAccessIdObj;+ if (accessId) {+ encryptedAccessIdObj = await BotService.encryptSymmetric({workspaceId: integrationAuth.workspace,- plaintext: accessToken- });-- let encryptedAccessIdObj;- if (accessId) {- encryptedAccessIdObj = await BotService.encryptSymmetric({- workspaceId: integrationAuth.workspace,- plaintext: accessId- });- }-- integrationAuth = await IntegrationAuth.findOneAndUpdate({- _id: integrationAuthId- }, {- accessIdCiphertext: encryptedAccessIdObj?.ciphertext ?? undefined,- accessIdIV: encryptedAccessIdObj?.iv ?? undefined,- accessIdTag: encryptedAccessIdObj?.tag ?? undefined,- accessCiphertext: encryptedAccessTokenObj.ciphertext,- accessIV: encryptedAccessTokenObj.iv,- accessTag: encryptedAccessTokenObj.tag,- accessExpiresAt,- algorithm: ALGORITHM_AES_256_GCM,- keyEncoding: ENCODING_SCHEME_UTF8- }, {- new: true- });- } catch (err) {- Sentry.setUser(null);- Sentry.captureException(err);- throw new Error('Failed to save integration auth access token');+ plaintext: accessId+ });}+ integrationAuth = await IntegrationAuth.findOneAndUpdate({+ _id: integrationAuthId+ }, {+ accessIdCiphertext: encryptedAccessIdObj?.ciphertext ?? undefined,+ accessIdIV: encryptedAccessIdObj?.iv ?? undefined,+ accessIdTag: encryptedAccessIdObj?.tag ?? undefined,+ accessCiphertext: encryptedAccessTokenObj.ciphertext,+ accessIV: encryptedAccessTokenObj.iv,+ accessTag: encryptedAccessTokenObj.tag,+ accessExpiresAt,+ algorithm: ALGORITHM_AES_256_GCM,+ keyEncoding: ENCODING_SCHEME_UTF8+ }, {+ new: true+ });+return integrationAuth;-}--export {- handleOAuthExchangeHelper,- syncIntegrationsHelper,- getIntegrationAuthRefreshHelper,- getIntegrationAuthAccessHelper,- setIntegrationAuthRefreshHelper,- setIntegrationAuthAccessHelper-}+}diff --cc backend/src/helpers/membership.tsindex 0853a11545,074ebe777d..9762975129--- a/backend/src/helpers/membership.ts+++ b/backend/src/helpers/membership.ts@@@ -47,16 -46,8 +46,8 @@@ export const validateMembership = asyn* @param {Object} queryObj - query object* @return {Object} membership - membership*/-const findMembership = async (queryObj: any) => {- const membership = await Membership.findOne(queryObj);+export const findMembership = async (queryObj: any) => {- let membership;- try {- membership = await Membership.findOne(queryObj);- } catch (err) {- Sentry.setUser(null);- Sentry.captureException(err);- throw new Error('Failed to find membership');- }-++ const membership = await Membership.findOne(queryObj);return membership;};@@@ -109,26 -93,21 +93,19 @@@ export const addMemberships = async (* @param {Object} obj* @param {String} obj.membershipId - id of membership to delete*/-const deleteMembership = async ({ membershipId }: { membershipId: string }) => {- const deletedMembership = await Membership.findOneAndDelete({- _id: membershipId,+export const deleteMembership = async ({ membershipId }: { membershipId: string }) => {- let deletedMembership;- try {- deletedMembership = await Membership.findOneAndDelete({- _id: membershipId- });++ const deletedMembership = await Membership.findOneAndDelete({++ _id: membershipId+ });- // delete keys associated with the membership- if (deletedMembership?.user) {- // case: membership had a registered user- await Key.deleteMany({- receiver: deletedMembership.user,- workspace: deletedMembership.workspace,- });- }- } catch (err) {- Sentry.setUser(null);- Sentry.captureException(err);- throw new Error('Failed to delete membership');+ // delete keys associated with the membership+ if (deletedMembership?.user) {+ // case: membership had a registered user+ await Key.deleteMany({+ receiver: deletedMembership.user,+ workspace: deletedMembership.workspace,+ });}- return deletedMembership;+ return deletedMembership;};--export { validateMembership, addMemberships, findMembership, deleteMembership };diff --cc backend/src/helpers/signup.tsindex 7a97463b24,9a70d0a57b..d747de20de--- a/backend/src/helpers/signup.ts+++ b/backend/src/helpers/signup.ts@@@ -14,29 -13,21 +13,21 @@@ import { TOKEN_EMAIL_CONFIRMATION } fro* @param {String} obj.email - email* @returns {Boolean} success - whether or not operation was successful*/-const sendEmailVerification = async ({ email }: { email: string }) => {- const token = await TokenService.createToken({- type: TOKEN_EMAIL_CONFIRMATION,- });+export const sendEmailVerification = async ({ email }: { email: string }) => {- try {- const token = await TokenService.createToken({- type: TOKEN_EMAIL_CONFIRMATION,- });++ const token = await TokenService.createToken({++ type: TOKEN_EMAIL_CONFIRMATION,++ });- // send mail- await sendMail({- template: 'emailVerification.handlebars',- subjectLine: 'Infisical confirmation code',- recipients: [email],- substitutions: {- code: token- }- });- } catch (err) {- Sentry.setUser(null);- Sentry.captureException(err);- throw new Error(- "Ouch. We weren't able to send your email verification code"- );- }+ // send mail+ await sendMail({+ template: 'emailVerification.handlebars',+ subjectLine: 'Infisical confirmation code',+ recipients: [email],+ substitutions: {+ code: token+ }+ });};/**diff --cc backend/src/helpers/workspace.tsindex 701bc94bf2,eb74bf06dc..a1d71e920d--- a/backend/src/helpers/workspace.ts+++ b/backend/src/helpers/workspace.ts@@@ -58,24 -50,23 +50,18 @@@ export const createWorkspace = async (* @param {Object} obj* @param {String} obj.id - id of workspace to delete*/-const deleteWorkspace = async ({ id }: { id: string }) => {- await Workspace.deleteOne({ _id: id });- await Bot.deleteOne({- workspace: id- });- await Membership.deleteMany({- workspace: id- });- await Secret.deleteMany({- workspace: id- });- await Key.deleteMany({- workspace: id- });-};--export {- createWorkspace,- deleteWorkspace+export const deleteWorkspace = async ({ id }: { id: string }) => {- try {- await Workspace.deleteOne({ _id: id });- await Bot.deleteOne({- workspace: id- });- await Membership.deleteMany({- workspace: id- });- await Secret.deleteMany({- workspace: id- });- await Key.deleteMany({- workspace: id- });- } catch (err) {- Sentry.setUser(null);- Sentry.captureException(err);- throw new Error('Failed to delete workspace');- }- };++ await Workspace.deleteOne({ _id: id });++ await Bot.deleteOne({++ workspace: id++ });++ await Membership.deleteMany({++ workspace: id++ });++ await Secret.deleteMany({++ workspace: id++ });++ await Key.deleteMany({++ workspace: id++ });+ };