Refactor infisical-node to config file for birds eye view of envars

This commit is contained in:
Tuan Dang
2023-03-15 00:09:40 +07:00
parent 31111fc63b
commit a6c8638345
33 changed files with 264 additions and 262 deletions
+11 -6
View File
@@ -1,5 +1,4 @@
import * as Sentry from '@sentry/node';
import infisical from 'infisical-node';
import { Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import * as bigintConversion from 'bigint-conversion';
@@ -15,6 +14,12 @@ import {
import { BadRequestError } from '../../utils/errors';
import { EELogService } from '../../ee/services';
import { getChannelFromUserAgent } from '../../utils/posthog'; // TODO: move this
import {
getNodeEnv,
getJwtRefreshSecret,
getJwtAuthLifetime,
getJwtAuthSecret
} from '../../config';
declare module 'jsonwebtoken' {
export interface UserIDJwtPayload extends jwt.JwtPayload {
@@ -121,7 +126,7 @@ export const login2 = async (req: Request, res: Response) => {
httpOnly: true,
path: '/',
sameSite: 'strict',
secure: infisical.get('NODE_ENV')! === 'production' ? true : false
secure: getNodeEnv() === 'production' ? true : false
});
const loginAction = await EELogService.createAction({
@@ -177,7 +182,7 @@ export const logout = async (req: Request, res: Response) => {
httpOnly: true,
path: '/',
sameSite: 'strict',
secure: infisical.get('NODE_ENV') === 'production' ? true : false
secure: getNodeEnv() === 'production' ? true : false
});
const logoutAction = await EELogService.createAction({
@@ -232,7 +237,7 @@ export const getNewToken = async (req: Request, res: Response) => {
}
const decodedToken = <jwt.UserIDJwtPayload>(
jwt.verify(refreshToken, infisical.get('JWT_REFRESH_SECRET')!)
jwt.verify(refreshToken, getJwtRefreshSecret())
);
const user = await User.findOne({
@@ -247,8 +252,8 @@ export const getNewToken = async (req: Request, res: Response) => {
payload: {
userId: decodedToken.userId
},
expiresIn: infisical.get('JWT_AUTH_LIFETIME')!,
secret: infisical.get('JWT_AUTH_SECRET')!
expiresIn: getJwtAuthLifetime(),
secret: getJwtAuthSecret()
});
return res.status(200).send({
@@ -1,4 +1,3 @@
import infisical from 'infisical-node';
import * as Sentry from '@sentry/node';
import { Request, Response } from 'express';
import { Membership, MembershipOrg, User, Key } from '../../models';
@@ -8,6 +7,7 @@ import {
} from '../../helpers/membership';
import { sendMail } from '../../helpers/nodemailer';
import { ADMIN, MEMBER, ACCEPTED } from '../../variables';
import { getSiteURL } from '../../config';
/**
* Check that user is a member of workspace with id [workspaceId]
@@ -215,7 +215,7 @@ export const inviteUserToWorkspace = async (req: Request, res: Response) => {
inviterFirstName: req.user.firstName,
inviterEmail: req.user.email,
workspaceName: req.membership.workspace.name,
callback_url: infisical.get('SITE_URL')! + '/login'
callback_url: getSiteURL() + '/login'
}
});
} catch (err) {
@@ -1,4 +1,3 @@
import infisical from 'infisical-node';
import { Request, Response } from 'express';
import * as Sentry from '@sentry/node';
import { MembershipOrg, Organization, User } from '../../models';
@@ -8,6 +7,7 @@ import { updateSubscriptionOrgQuantity } from '../../helpers/organization';
import { sendMail } from '../../helpers/nodemailer';
import { TokenService } from '../../services';
import { OWNER, ADMIN, MEMBER, ACCEPTED, INVITED, TOKEN_EMAIL_ORG_INVITATION } from '../../variables';
import { getSiteURL, getJwtSignupLifetime, getJwtSignupSecret } from '../../config';
/**
* Delete organization membership with id [membershipOrgId] from organization
@@ -178,7 +178,7 @@ export const inviteUserToOrganization = async (req: Request, res: Response) => {
organizationName: organization.name,
email: inviteeEmail,
token,
callback_url: infisical.get('SITE_URL') + '/signupinvite'
callback_url: getSiteURL() + '/signupinvite'
}
});
}
@@ -250,8 +250,8 @@ export const verifyUserToOrganization = async (req: Request, res: Response) => {
payload: {
userId: user._id.toString()
},
expiresIn: infisical.get('JWT_SIGNUP_LIFETIME')!,
secret: infisical.get('JWT_SIGNUP_SECRET')!
expiresIn: getJwtSignupLifetime(),
secret: getJwtSignupSecret()
});
} catch (err) {
Sentry.setUser(null);
@@ -1,4 +1,3 @@
import infisical from 'infisical-node';
import * as Sentry from '@sentry/node';
import { Request, Response } from 'express';
import Stripe from 'stripe';
@@ -13,6 +12,7 @@ import { createOrganization as create } from '../../helpers/organization';
import { addMembershipsOrg } from '../../helpers/membershipOrg';
import { OWNER, ACCEPTED } from '../../variables';
import _ from 'lodash';
import { getStripeSecretKey, getSiteURL } from '../../config';
export const getOrganizations = async (req: Request, res: Response) => {
let organizations;
@@ -317,7 +317,7 @@ export const createOrganizationPortalSession = async (
) => {
let session;
try {
const stripe = new Stripe(infisical.get('STRIPE_SECRET_KEY')!, {
const stripe = new Stripe(getStripeSecretKey(), {
apiVersion: '2022-08-01'
});
@@ -333,13 +333,13 @@ export const createOrganizationPortalSession = async (
customer: req.membershipOrg.organization.customerId,
mode: 'setup',
payment_method_types: ['card'],
success_url: infisical.get('SITE_URL')! + '/dashboard',
cancel_url: infisical.get('SITE_URL')! + '/dashboard'
success_url: getSiteURL() + '/dashboard',
cancel_url: getSiteURL() + '/dashboard'
});
} else {
session = await stripe.billingPortal.sessions.create({
customer: req.membershipOrg.organization.customerId,
return_url: infisical.get('SITE_URL') + '/dashboard'
return_url: getSiteURL() + '/dashboard'
});
}
@@ -365,7 +365,7 @@ export const getOrganizationSubscriptions = async (
) => {
let subscriptions;
try {
const stripe = new Stripe(infisical.get('STRIPE_SECRET_KEY')!, {
const stripe = new Stripe(getStripeSecretKey(), {
apiVersion: '2022-08-01'
});
@@ -1,4 +1,3 @@
import infisical from 'infisical-node';
import { Request, Response } from 'express';
import * as Sentry from '@sentry/node';
// eslint-disable-next-line @typescript-eslint/no-var-requires
@@ -10,6 +9,7 @@ import { sendMail } from '../../helpers/nodemailer';
import { TokenService } from '../../services';
import { TOKEN_EMAIL_PASSWORD_RESET } from '../../variables';
import { BadRequestError } from '../../utils/errors';
import { getSiteURL, getJwtSignupLifetime, getJwtSignupSecret } from '../../config';
/**
* Password reset step 1: Send email verification link to email [email]
@@ -44,7 +44,7 @@ export const emailPasswordReset = async (req: Request, res: Response) => {
substitutions: {
email,
token,
callback_url: infisical.get('SITE_URL')! + '/password-reset'
callback_url: getSiteURL() + '/password-reset'
}
});
} catch (err) {
@@ -91,8 +91,8 @@ export const emailPasswordResetVerify = async (req: Request, res: Response) => {
payload: {
userId: user._id.toString()
},
expiresIn: infisical.get('JWT_SIGNUP_LIFETIME')!,
secret: infisical.get('JWT_SIGNUP_SECRET')!
expiresIn: getJwtSignupLifetime(),
secret: getJwtSignupSecret()
});
} catch (err) {
Sentry.setUser(null);
@@ -1,7 +1,7 @@
import infisical from 'infisical-node';
import { Request, Response } from 'express';
import { ServiceToken } from '../../models';
import { createToken } from '../../helpers/auth';
import { getJwtServiceSecret } from '../../config';
/**
* Return service token on request
@@ -61,7 +61,7 @@ export const createServiceToken = async (req: Request, res: Response) => {
workspaceId
},
expiresIn: expiresIn,
secret: infisical.get('JWT_SERVICE_SECRET')!
secret: getJwtServiceSecret()
});
} catch (err) {
return res.status(400).send({
@@ -1,4 +1,3 @@
import infisical from 'infisical-node';
import { Request, Response } from 'express';
import * as Sentry from '@sentry/node';
import { User } from '../../models';
@@ -8,6 +7,7 @@ import {
} from '../../helpers/signup';
import { createToken } from '../../helpers/auth';
import { BadRequestError } from '../../utils/errors';
import { getInviteOnlySignup, getJwtSignupLifetime, getJwtSignupSecret } from '../../config';
/**
* Signup step 1: Initialize account for user under email [email] and send a verification code
@@ -21,7 +21,7 @@ export const beginEmailSignup = async (req: Request, res: Response) => {
try {
email = req.body.email;
if (infisical.get('INVITE_ONLY_SIGNUP') || false) {
if (getInviteOnlySignup() || false) {
// Only one user can create an account without being invited. The rest need to be invited in order to make an account
const userCount = await User.countDocuments({})
if (userCount != 0) {
@@ -91,8 +91,8 @@ export const verifyEmailSignup = async (req: Request, res: Response) => {
payload: {
userId: user._id.toString()
},
expiresIn: infisical.get('JWT_SIGNUP_LIFETIME')!,
secret: infisical.get('JWT_SIGNUP_SECRET')!
expiresIn: getJwtSignupLifetime(),
secret: getJwtSignupSecret()
});
} catch (err) {
Sentry.setUser(null);
@@ -1,7 +1,7 @@
import infisical from 'infisical-node';
import { Request, Response } from 'express';
import * as Sentry from '@sentry/node';
import Stripe from 'stripe';
import { getStripeSecretKey, getStripeWebhookSecret } from '../../config';
/**
* Handle service provisioning/un-provisioning via Stripe
@@ -13,7 +13,7 @@ export const handleWebhook = async (req: Request, res: Response) => {
let event;
try {
// check request for valid stripe signature
const stripe = new Stripe(infisical.get('STRIPE_SECRET_KEY')!, {
const stripe = new Stripe(getStripeSecretKey(), {
apiVersion: '2022-08-01'
});
@@ -21,7 +21,7 @@ export const handleWebhook = async (req: Request, res: Response) => {
event = stripe.webhooks.constructEvent(
req.body,
sig,
infisical.get('STRIPE_WEBHOOK_SECRET')!
getStripeWebhookSecret()
);
} catch (err) {
Sentry.setUser({ email: req.user.email });
@@ -1,11 +1,11 @@
import * as Sentry from '@sentry/node';
import infisical from 'infisical-node';
import { Request, Response } from 'express';
import crypto from 'crypto';
import bcrypt from 'bcrypt';
import {
APIKeyData
} from '../../models';
import { getSaltRounds } from '../../config';
/**
* Return API key data for user with id [req.user_id]
@@ -43,7 +43,7 @@ export const createAPIKeyData = async (req: Request, res: Response) => {
const { name, expiresIn } = req.body;
const secret = crypto.randomBytes(16).toString('hex');
const secretHash = await bcrypt.hash(secret, parseInt(infisical.get('SALT_ROUNDS')!) || 10);
const secretHash = await bcrypt.hash(secret, getSaltRounds());
const expiresAt = new Date();
expiresAt.setSeconds(expiresAt.getSeconds() + expiresIn);
+10 -7
View File
@@ -1,4 +1,3 @@
import infisical from 'infisical-node';
/* eslint-disable @typescript-eslint/no-var-requires */
import { Request, Response } from 'express';
import jwt from 'jsonwebtoken';
@@ -17,6 +16,11 @@ import {
ACTION_LOGIN
} from '../../variables';
import { getChannelFromUserAgent } from '../../utils/posthog'; // TODO: move this
import {
getNodeEnv,
getJwtMfaLifetime,
getJwtMfaSecret
} from '../../config';
declare module 'jsonwebtoken' {
export interface UserIDJwtPayload extends jwt.JwtPayload {
@@ -120,8 +124,8 @@ export const login2 = async (req: Request, res: Response) => {
payload: {
userId: user._id.toString()
},
expiresIn: infisical.get('JWT_MFA_LIFETIME')!,
secret: infisical.get('JWT_MFA_SECRET')!
expiresIn: getJwtMfaLifetime(),
secret: getJwtMfaSecret()
});
const code = await TokenService.createToken({
@@ -159,7 +163,7 @@ export const login2 = async (req: Request, res: Response) => {
httpOnly: true,
path: '/',
sameSite: 'strict',
secure: infisical.get('NODE_ENV')! === 'production' ? true : false
secure: getNodeEnv() === 'production' ? true : false
});
// case: user does not have MFA enablgged
@@ -298,7 +302,7 @@ export const verifyMfaToken = async (req: Request, res: Response) => {
httpOnly: true,
path: '/',
sameSite: 'strict',
secure: infisical.get('NODE_ENV')! === 'production' ? true : false
secure: getNodeEnv() === 'production' ? true : false
});
interface VerifyMfaTokenRes {
@@ -341,5 +345,4 @@ export const verifyMfaToken = async (req: Request, res: Response) => {
});
return res.status(200).send(resObj);
}
}
@@ -1,5 +1,4 @@
import * as Sentry from '@sentry/node';
import infisical from 'infisical-node';
import { Request, Response } from 'express';
import crypto from 'crypto';
import bcrypt from 'bcrypt';
@@ -8,6 +7,7 @@ import {
} from '../../models';
import { userHasWorkspaceAccess } from '../../ee/helpers/checkMembershipPermissions';
import { ABILITY_READ } from '../../variables/organization';
import { getSaltRounds } from '../../config';
/**
* Return service token data associated with service token on request
@@ -73,7 +73,7 @@ export const createServiceTokenData = async (req: Request, res: Response) => {
}
const secret = crypto.randomBytes(16).toString('hex');
const secretHash = await bcrypt.hash(secret, parseInt(infisical.get('SALT_ROUNDS')!) || 10);
const secretHash = await bcrypt.hash(secret, getSaltRounds());
const expiresAt = new Date();
expiresAt.setSeconds(expiresAt.getSeconds() + expiresIn);
@@ -140,4 +140,4 @@ export const deleteServiceTokenData = async (req: Request, res: Response) => {
function UnauthorizedRequestError(arg0: { message: string; }) {
throw new Error('Function not implemented.');
}
}
@@ -1,4 +1,3 @@
import infisical from 'infisical-node';
import { Request, Response } from 'express';
import * as Sentry from '@sentry/node';
import { User, MembershipOrg } from '../../models';
@@ -9,6 +8,7 @@ import {
import { issueAuthTokens } from '../../helpers/auth';
import { INVITED, ACCEPTED } from '../../variables';
import request from '../../config/request';
import { getNodeEnv } from '../../config';
/**
* Complete setting up user by adding their personal and auth information as part of the
@@ -127,7 +127,7 @@ export const completeAccountSignup = async (req: Request, res: Response) => {
httpOnly: true,
path: '/',
sameSite: 'strict',
secure: infisical.get('NODE_ENV')! === 'production' ? true : false
secure: getNodeEnv() === 'production' ? true : false
});
} catch (err) {
Sentry.setUser(null);
@@ -232,7 +232,7 @@ export const completeAccountInvite = async (req: Request, res: Response) => {
httpOnly: true,
path: '/',
sameSite: 'strict',
secure: infisical.get('NODE_ENV')! === 'production' ? true : false
secure: getNodeEnv() === 'production' ? true : false
});
} catch (err) {
Sentry.setUser(null);