Skip to content

Instantly share code, notes, and snippets.

@mrfarhadir
Last active November 24, 2024 00:40
Show Gist options
  • Save mrfarhadir/78216dc946f5b032adb134d6a6814f80 to your computer and use it in GitHub Desktop.
Save mrfarhadir/78216dc946f5b032adb134d6a6814f80 to your computer and use it in GitHub Desktop.
Proxy middleware for Nuxt framework. (usage in the comment)
import crypto from 'crypto';
export function randomHex(length) {
return crypto.randomBytes(length / 2).toString('hex');
}
export function createHash(url, secretKey) {
const randomHexStr = randomHex(64);
const timestamp = Date.now();
const hmacPayload = `${randomHexStr}:${url}:${timestamp}`;
const hmac = crypto.createHmac('sha256', secretKey).update(hmacPayload).digest('hex');
return `${randomHexStr}:${timestamp}:${hmac}`;
}
export function verifyHash(hash, url, secretKey) {
const [randomHexStr, timestamp, hmac] = hash.split(':');
if (!randomHexStr || !timestamp || !hmac) {
console.error('Invalid hash structure');
return false;
}
// Validate timestamp (e.g., within 5 minutes)
const timeDifference = Date.now() - parseInt(timestamp, 10);
const maxAllowedTime = 5 * 60 * 1000; // 5 minutes in milliseconds
if (timeDifference > maxAllowedTime) {
console.error('Hash expired');
return false;
}
// Recompute the HMAC
const hmacPayload = `${randomHexStr}:${url}:${timestamp}`;
const expectedHmac = crypto.createHmac('sha256', secretKey).update(hmacPayload).digest('hex');
// Validate HMAC
if (expectedHmac !== hmac) {
console.error('HMAC mismatch');
return false;
}
return true;
}
import HttpProxy from 'http-proxy';
import { createHash } from '~/utils/hash';
const proxy = new HttpProxy();
export default fromNodeMiddleware((req, res, next) => {
const { apiTarget: API_TARGET, secretKey: SECRET_KEY, useVerifyHash } = useRuntimeConfig();
if (req.url.startsWith('/api')) {
proxy.web(
req,
res,
{
target: API_TARGET,
},
next,
);
proxy.on('proxyReq', (proxyReq, req, res) => {
if (useVerifyHash) {
const hash = createHash(req.url, SECRET_KEY);
proxyReq.setHeader('x-verify-hash', hash)
}
})
}
else next()
})
@mrfarhadir
Copy link
Author

mrfarhadir commented Nov 24, 2024

Install

npm install http-proxy

Usage

Create the following files in your project:
middleware/proxy.js
utils/hash.js

Add the following config to your nuxt.config

runtimeConfig: {
    apiTarget: process.env.API_TARGET || 'http://localhost:4000',
    useVerifyHash: true,
    secretKey: process.env.SECRET_KEY || 'abcdef-123456'
  },

  serverMiddleware: [
    { path: '/api', handler: '~/middleware/proxy.js' },
  ],

Middleware config

apiTarget: Your main endpoint
useVerifyHash: If set to true, proxy will add a hash to the header of each proxy request then in the target server you can check if the verifyHash value In the header, is correct or not.
secretKey: a key is used for hashing

If you use the verifyHash, REMOVE the verifyHash function from your front-end project

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment