Skip to content

Commit

Permalink
[CHANGE] #84, writing key check to be simpler, introduced scripts for…
Browse files Browse the repository at this point in the history
… setting up environment variables
  • Loading branch information
Type-Style committed Sep 3, 2024
1 parent b083e02 commit 0521170
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 13 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@
//"@typescript-eslint/no-unused-vars": "warn"
"jest/no-conditional-expect": "off"
},
"ignorePatterns": ["dist", "jest.config.js", "httpdocs", "webpack.config.js", "src/client"]
"ignorePatterns": ["dist", "jest.config.js", "httpdocs", "webpack.config.js", "src/client", "init"]

}
7 changes: 3 additions & 4 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ jobs:
NODE_ENV: ${{ vars.NODE_ENV }}
LOCALHOST: ${{ vars.LOCALHOST }}
LOCALHOSTV6: ${{ vars.LOCALHOSTV6 }}
KEYA: ${{ secrets.KEYA }}
KEYB: ${{ secrets.KEYB }}
KEY: ${{ secrets.KEY }}
USER_TEST: ${{ secrets.USER_TEST }}

steps:
Expand All @@ -30,8 +29,8 @@ jobs:
- run: npm run build --if-present
- name: Start server
run: |
sudo NODE_ENV=$NODE_ENV LOCALHOST=$LOCALHOST LOCALHOSTV6=$LOCALHOSTV6 KEYA=$KEYA KEYB=$KEYB USER_TEST=$USER_TEST npm start &
sleep 15 # Give server some time to start
sudo NODE_ENV=$NODE_ENV LOCALHOST=$LOCALHOST LOCALHOSTV6=$LOCALHOSTV6 KEY=$KEY USER_TEST=$USER_TEST npm start &
sleep 16 # Give server some time to start
- name: Check if server is running
run: |
curl --fail http://localhost:80 || exit 1
Expand Down
30 changes: 30 additions & 0 deletions init/generateKey.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* Usage: open console run: node init/generateKey.js
* type desired key and hit enter
* copy output to .env add a line starting with:
* KEY=
* directly followed by your output
*/

// Import required modules
const readline = require('readline');

// set up readline to read input from the console
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

// Prompt user for input
rl.question('Enter the string to be encoded: ', (input) => {
// encode to escape special chars
const escapedString = encodeURIComponent(input);

// convert the escaped string to base64
const base64String = Buffer.from(escapedString).toString('base64');

// print the result
console.log('Base64 Encoded String:', base64String);

rl.close();
});
29 changes: 29 additions & 0 deletions init/generatePassword.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* This is used to setup Passwords initially
* You can create passwords using the same logic as in the environment
* Prerequisite: You need to have KEY already generated!
* Run the build command from the package.json (npm run build)
* Then call the compiled version of this script using the key as environment variable like so:
* KEY=your-key node ./init/generatePassword.js
* Enter your password
* Copy that to the Environment Variables and .env file
* USER_WHATEVER=
* followed by the output of the console
*/

// Import required modules
const readline = require('readline');
const { crypt } = require('../dist/scripts/crypt');

// Set up readline to read input from the console
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

// Prompt user for input
rl.question('Enter Password to be generated: ', async (input) => {
const cryptedPassword = await crypt(input);
console.log(cryptedPassword);
rl.close();
});
5 changes: 2 additions & 3 deletions src/models/entry.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { NextFunction, Request, Response } from 'express';
import { checkExact, query } from 'express-validator';
import { compare } from '@src/scripts/crypt';
import { create as createError } from '@src/middleware/error';
import * as file from '@src/scripts/file';
import { getTime } from '@src/scripts/time';
Expand Down Expand Up @@ -138,12 +137,12 @@ export function checkTime(value: string) {

async function checkKey(value: string) {
if (!value) { throw new Error('Key required'); }
if (!process.env.KEYB) { throw new Error('Configuration wrong'); }
if (!process.env.KEY) { throw new Error('Configuration wrong: KEY is missing in environment variables'); }
if (process.env.NODE_ENV != "production" && value == "test") {
return true; // dev testing convenience
}

const result = await compare(decodeURIComponent(value), process.env.KEYB);
const result = Buffer.from(encodeURIComponent(value)).toString('base64') == process.env.KEY;

if (!result) {
throw new Error('Key does not match');
Expand Down
4 changes: 2 additions & 2 deletions src/scripts/crypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const compare = async function (password: string, hash: string) {
}

function pepper(password: string) {
const key = process.env.KEYA;
if (!key) { throw new Error('KEYA is not defined in the environment variables'); }
const key = process.env.KEY;
if (!key) { throw new Error('KEY is not defined in the environment variables'); }
return password + crypto.createHmac('sha256', key).digest("base64");
}
4 changes: 2 additions & 2 deletions src/scripts/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export function cleanupCSRF() {
}

export function validateJWT(req: Request) {
const key = process.env.KEYA;
const key = process.env.KEY;
const header = req.header('Authorization');
const [type, token] = header ? header.split(' ') : "";
let payload: string | jwt.JwtPayload = "";
Expand Down Expand Up @@ -78,7 +78,7 @@ export function validateJWT(req: Request) {
}

export function createJWT(req: Request, res: Response) {
const key = process.env.KEYA;
const key = process.env.KEY;
if (!key) { throw new Error('Configuration is wrong'); }
const today = new Date();
const dateString = today.toLocaleDateString("de-DE", { weekday: "short", year: 'numeric', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' });
Expand Down
1 change: 0 additions & 1 deletion src/tests/login.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ describe('Login', () => {
it('test invalid credentials to return error', async () => {
try {
userDataWithToken.csrfToken = csrfToken;
console.log("csrfToken %o", userDataWithToken.csrfToken);
await axios.post('http://localhost:80/login', qs.stringify(userDataWithToken));
} catch (error) {
const axiosError = error as AxiosError;
Expand Down

0 comments on commit 0521170

Please sign in to comment.