Skip to content

Commit

Permalink
fix: cookie session
Browse files Browse the repository at this point in the history
  • Loading branch information
liorzblrn committed Feb 8, 2025
1 parent 9f31b28 commit d06607b
Show file tree
Hide file tree
Showing 10 changed files with 594 additions and 259 deletions.
1 change: 1 addition & 0 deletions deploy/.env
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ BACKOFFICE_PORT=5137
HEADLESS_SVC_PORT=5173
HASHING_KEY_SECRET_BASE64=JDJiJDEwJFRYNjhmQi5JMlRCWHN0aGowakFHSi4=
SECRETS_MANAGER_PROVIDER=in-memory
SESSION_ENCRYPTION_SECRET=6286e1615f7485f46dda7d63cc39505ac14536d07d20a194697613f22b074ebe
742 changes: 492 additions & 250 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

12 changes: 12 additions & 0 deletions scripts/generate-salt.sh
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ fi
# Generate a new bcrypt salt using Node.js and TypeScript
cd $WF_FOLDER
secret_value=$(npx tsx "$WF_FOLDER/scripts/generate-salt.ts")
encryption_key_value=$(npx tsx "$WF_FOLDER/scripts/generate-encryption-key.ts")
cd $PARENT_DIR

# Check if secret_value is empty
Expand All @@ -28,6 +29,11 @@ if [[ -z "$secret_value" ]]; then
exit 1
fi

if [[ -z "$encryption_key_value" ]]; then
echo "Error: Unable to generate encryption key. Exiting..."
exit 1
fi


# Function to set the environment variable for Unix-based OS
set_bcrypt_salt_unix() {
Expand All @@ -52,9 +58,15 @@ update_env_file() {
for file in "$env_file" "$env_example_file" "$deploy_env_file"; do
grep -v '^HASHING_KEY_SECRET_BASE64=' "$file" > "${file}.tmp" && mv "${file}.tmp" "$file"
echo -e "HASHING_KEY_SECRET_BASE64=$sanitized_value" >> "$file"

grep -v '^SESSION_ENCRYPTION_SECRET=' "$file" > "${file}.tmp" && mv "${file}.tmp" "$file"
echo -e "SESSION_ENCRYPTION_SECRET=$encryption_key_value" >> "$file"

done

echo "HASHING_KEY_SECRET_BASE64 has been set in the .env file with value: $adjusted_value"
echo "SESSION_ENCRYPTION_SECRET has been set in the .env file with value: $encryption_key_value"

}

# Detect the operating system
Expand Down
9 changes: 7 additions & 2 deletions services/workflows-service/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ DB_PORT=5432
DB_URL=postgres://admin:admin@localhost:5432/postgres
SESSION_SECRET=iGdnj4A0YOhj8dHJK7IWSvQKEZsG7P70FFehuddhFPjtg/bSkzFejYILk4Xue6Ilx9y3IAwzR8pV1gb4
SESSION_EXPIRATION_IN_MINUTES=60
SESSION_HTTP_ONLY=false
SESSION_SAME_SITE=false
SESSION_SECURE_COOKIE=false
SESSION_SECURE_PROXY=false
WORKFLOW_DASHBOARD_CORS_ORIGIN=http://localhost:5200
BACKOFFICE_CORS_ORIGIN=http://localhost:5137
KYB_EXAMPLE_CORS_ORIGIN=http://localhost:5201
Expand Down Expand Up @@ -34,6 +38,7 @@ COLLECTION_FLOW_URL=http://localhost:5201
WEB_UI_SDK_URL=http://localhost:5202
#HASHING_KEY_SECRET="$2b$10$FovZTB91/QQ4Yu28nvL8e."
NOTION_API_KEY=secret
HASHING_KEY_SECRET_BASE64=JDJiJDEwJFRYNjhmQi5JMlRCWHN0aGowakFHSi4=
SECRETS_MANAGER_PROVIDER=in-memory
SYNC_UNIFIED_API=false
SYNC_UNIFIED_API=false
HASHING_KEY_SECRET_BASE64=JDJiJDEwJDFzT1VQckUxeWdsZEFZZ3I3MjRaaC4=
SESSION_ENCRYPTION_SECRET=6286e1615f7485f46dda7d63cc39505ac14536d07d20a194697613f22b074ebe
2 changes: 2 additions & 0 deletions services/workflows-service/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
"class-validator": "0.14.0",
"concat-stream": "^2.0.0",
"cookie-session": "^2.0.0",
"crypto-js": "^4.2.0",
"csv-parse": "^5.5.6",
"dayjs": "^1.11.6",
"deep-diff": "^1.0.2",
Expand Down Expand Up @@ -123,6 +124,7 @@
"@types/bcrypt": "5.0.0",
"@types/concat-stream": "^2.0.3",
"@types/cookie-session": "^2.0.44",
"@types/crypto-js": "^4.2.2",
"@types/deep-diff": "^1.0.5",
"@types/express": "4.17.9",
"@types/jest": "^26.0.19",
Expand Down
3 changes: 3 additions & 0 deletions services/workflows-service/scripts/generate-encryption-key.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import crypto from 'crypto';

console.log(crypto.randomBytes(32).toString('hex'));
17 changes: 17 additions & 0 deletions services/workflows-service/src/auth/crypto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { env } from '@/env';
import CryptoJS from 'crypto-js';

export const encryptData = (data: string): string => {
// Encrypt the data using AES encryption
const encrypted = CryptoJS.AES.encrypt(data, env.SESSION_ENCRYPTION_SECRET).toString();

return encrypted;
};

export const decryptData = (encryptedData: string): string => {
// Decrypt the data using AES decryption
const bytes = CryptoJS.AES.decrypt(encryptedData, env.SESSION_ENCRYPTION_SECRET);
const decrypted = bytes.toString(CryptoJS.enc.Utf8); // Convert decrypted bytes back to UTF-8 string

return decrypted;
};
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ import type { Request } from 'express';

export class LocalAuthGuard extends AuthGuard('local') {
async canActivate(context: ExecutionContext) {
const result = await super.canActivate(context);
const request = context.switchToHttp().getRequest<Request>();

await super.logIn(request);

return result as boolean;
return (await super.canActivate(context)) as boolean;
}
}
42 changes: 42 additions & 0 deletions services/workflows-service/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,48 @@ export const serverEnvSchema = {
BCRYPT_SALT: z.coerce.number().int().nonnegative().or(z.string()),
PORT: z.coerce.number(),
DB_URL: z.string().url(),

SESSION_ENCRYPTION_SECRET: z.string(),
SESSION_SAME_SITE: z
.union([
z.literal('strict'),
z.literal('lax'),
z.literal('none'),
z.literal('true'),
z.literal('false'),
z.boolean(),
])
.transform(val => {
if (val === 'true') {
return true;
}

if (val === 'false') {
return false;
}

return val;
})
.default(false),

SESSION_HTTP_ONLY: z
.union([z.literal('true'), z.literal('false'), z.boolean()])
.transform(val => {
return val === 'true';
})
.default(false),

SESSION_SECURE_COOKIE: z
.union([z.literal('true'), z.literal('false'), z.boolean()])
.transform((val: unknown) => val === 'true')
.default(false),

SESSION_SECURE_PROXY: z
.union([z.literal('true'), z.literal('false'), z.boolean()])
.transform(val => {
return val === 'true';
})
.default(false),
SESSION_SECRET: z.string(),
HASHING_KEY_SECRET: z.string().optional(),
HASHING_KEY_SECRET_BASE64: z.string().refine(Base64.isValid).optional(),
Expand Down
22 changes: 17 additions & 5 deletions services/workflows-service/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,26 @@ const main = async () => {

app.use(json({ limit: '50mb' }));
app.use(urlencoded({ limit: '50mb', extended: true }));

const cookieSessionConfig = {
name: 'session',
httpOnly: env.SESSION_SECURE_COOKIE,
secure: env.SESSION_SECURE_COOKIE,
sameSite: env.SESSION_SAME_SITE,
maxAge: 1000 * 60 * env.SESSION_EXPIRATION_IN_MINUTES,
};

logger.log(`Cookie session config`, { cookieSessionConfig });

if (env.SESSION_SECURE_PROXY) {
// Trust the first proxy (ALB)
app.getHttpAdapter().getInstance().set('trust proxy', 1);
}

app.use(
cookieSession({
name: 'session',
...cookieSessionConfig,
keys: [env.SESSION_SECRET],
httpOnly: env.ENVIRONMENT_NAME === 'production',
secure: false,
sameSite: env.ENVIRONMENT_NAME === 'production' ? 'strict' : false,
maxAge: 1000 * 60 * env.SESSION_EXPIRATION_IN_MINUTES,
}),
);

Expand Down

0 comments on commit d06607b

Please sign in to comment.