How to enable trust proxy in express. Nestjs app - proxy

I am learning nestjs and, building an app but my ip is behind the proxy,
Nestjs documentation says enable the trust proxy in express,
https://docs.nestjs.com/security/rate-limiting
I am getting trouble how to do that and then how to find the IP.

Try this
import { NestExpressApplication } from "#nestjs/platform-express"
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.set('trust proxy', 1);
Credit:
Nestjs Docs Offical
Nestjs Docs But Not Offical
Express behind proxies

for Fastify adapter trustProxy accept true, number, array of CIDRs, and string of comma separated CIDRs and should be passed like that:
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({
// #see https://www.fastify.io/docs/latest/Reference/Server/#trustproxy
trustProxy: process.env.TRUST_PROXY?.match(/\d/)
? +process.env.TRUST_PROXY
: process.env.TRUST_PROXY,
}),
);
await app.listen(port, process.env.ADDRESS); // ADDRES = "undefined" or "0.0.0.0"

Related

NextJS - how to configure proxy to log api requests and responses?

I am having an issue with the Cloudinary Node SDK where the Admin Resources endpoint is occasionally throwing a 302 error. Their support suggested that I proxy the request so that I can log the response between my api and their SDK and ultimately get a better idea of what might be causing the problem (in the end they're hoping to see the Location headers that are in the Response).
One of their suggestions was to use Charles Proxy, however I'm very new to how this works and am unable to figure it out. I've read through the Charles docs and spent a full day googling, but I can't find any info related to proxying between the NextJS API and Cloudinary SDK specifically.
How do I go about setting up Charles Proxy so that I can see the request and response in this way? Is there another way that I don't know of that would work instead? Since I'm using the newest version of NextJS v12, could I use the new _middleware option instead? In a later suggestion, their Support made this comment too:
if you can't proxy requests to localhost, you may be able to use a local DNS server or a local override so you can access your local IP using a different hostname (e.g. using /etc/hosts on a unix environment, or C:\Windows\System32\Drivers\etc\hosts on a windows PC) and have that proxied - that said, there's probably an easier way using a Node project or adjusting the settings of the Node server.
but I have no idea where to begin with this either.
Here is the api code I have:
pages/api/auth/images.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import cloudinary from 'cloudinary';
require('dotenv').config();
export default async function handler(_: NextApiRequest, res: NextApiResponse) {
cloudinary.v2.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
secure: true,
});
try {
// fetch cloudinary auth images
const response = await cloudinary.v2.api.resources({
type: 'upload',
prefix: 'my_app/auth_pages',
max_results: 20,
});
// fetch random image
const randImage =
response.resources[~~(response?.resources?.length * Math.random())];
// return image
return res.status(200).json({ image: randImage });
} catch (error) {
console.dir({ error }, { colors: true, depth: null });
return res.status(500).json({ error });
}
}
Note: I'm on a Mac.
Try the following:
export default async function handler(_: NextApiRequest, res: NextApiResponse) {
cloudinary.v2.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
api_proxy: 'http://<local_ip>:<charles_port>', //change accordingly
secure: true,
});
To get the port number, In Charles Proxy go to Proxy > Proxy Settings.

How to subscribe to `newBlockHeaders` on local RSK node over websockets?

I'm connecting to RSKj using the following endpoint:
ws://localhost:4444/
... However, I am unable to connect.
Note that the equivalent HTTP endpoint http://localhost:4444/
work for me, so I know that my RSKj node is running properly.
I need to listen for newBlockHeaders, so I prefer to use WebSockets (instead of HTTP).
How can I do this?
RSKj by default uses 4444 as the port for the HTTP transport;
and 4445 as the port for the Websockets transport.
Also note that the websockets endpoint is not at /,
but rather at websocket.
Therefore use ws://localhost:4445/websocket as your endpoint.
If you're using web3.js,
you can create a web3 instance that connects over Websockets
using the following:
const Web3 = require('web3');
const wsEndpoint = 'ws://localhost:4445/websocket';
const wsProvider =
new Web3.providers.WebsocketProvider(wsEndpoint);
const web3 = new Web3(wsProvider);
The second part of your question can be done
using eth_subscribe on newBlockHeaders.
Using the web3 instance from above like so:
// eth_subscribe newBlockHeaders
web3.eth.subscribe('newBlockHeaders', function(error, blockHeader) {
if (!error) {
// TODO something with blockHeader
} else {
// TODO something with error
}
});

WebSocketLink and self-signed certificates giving net::ERR_CERT_AUTHORITY_INVALID error

I am using apollo graphql to make https-based calls to my graphene backend. Queries and mutations work fine. In trying to add support for graphql subscriptions, I tried modifying my client setup code to include:
// Create a WebSocket link:
const wsLink = new WebSocketLink({
uri: "wss://" + hostname + "/graphql/",
options: {
reconnect: true,
}
});
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink,
);
But I end up getting this error in the client:
WebSocket connection to 'wss://localhost/graphql/' failed: Error in connection establishment: net::ERR_CERT_AUTHORITY_INVALID
In looking at the docs (and exploring the APIs), I could not figure out how to configure WebSocketLink to accept a self-signed certificate. I am pretty sure that for development environments, all developers code with self signed certificates, so I know this should be doable. Any help in getting this working is much appreciated.
Interestingly, the HttpLink that I use for queries and mutations does not complain of the same self-signed certificates. If anyone from the apollo team sees this question, they should consider unifying the behavior of the two link types.

Is there analog of express's app.set( 'something', something ) in koa?

I need socket.io instance in several places in my app. To achieve this in express i can do this:
app.set('io', io);
In koa right now i have this:
app.use( async ( ctx, next ) => {
ctx.io = io;
await next();
});
This works, but this middleware executes every time my server recieves request. Is there a better way to do this?
I don't know how you are fully implementing but there are a couple things that you can do is you can either pass an addition argument and upgrade the connection to a websocket that will bypass the rest of the middlewares. Or, what I do personally is just have any websocket connection go to a different end point. This will help with any future scalability issues. for example, if you need to create clusters of your server then you will have more control as well will help you testing your backend easier. That's what I would do atleast. My socket.io back end looks like this:
server.ts
oh yea I'm using typescript in the back end
require('dotenv').config({ path: __dirname + '/.env' });
import Koa from 'koa';
const koa = new Koa();
import cors from '#koa/cors';
const PORT = process.env.CHAT_PORT || 3000;
const ENV = process.env.NODE_ENV || 'development';
const server = require('http').createServer(app, { origins: 'http://server.ip' });
const io = (module.exports.io = require('socket.io')(server));
import SocketManager from './lib/SocketManager';
app.use(
cors({
origin: '*',
optionsSuccessStatus: 200,
}),
);
// server setup
server.listen(PORT, (err: ErrorEvent): void => {
if (err) console.error('❌ Unable to connect the server: ', err);
console.log(`💻 Chat server listening on port ${PORT} - ${ENV} environment`);
});
io.on('connection', SocketManager);
then just create a socket manager that imports the io instance and you can then go ahead and handle all the connections.
I hope this is the answer you were looking for/gave you some better insight.

Nuxt Axios Dynamic url

I manage to learn nuxt by using following tutorial
https://scotch.io/tutorials/implementing-authentication-in-nuxtjs-app
In the tutorial, it show that
axios: {
baseURL: 'http://127.0.0.1:3000/api'
},
it is point to localhost, it is not a problem for my development,
but when come to deployment, how do I change the URL based on the browser URL,
if the system use in LAN, it will be 192.168.8.1:3000/api
if the system use at outside, it will be example.com:3000/api
On the other hand, Currently i using adonuxt (adonis + nuxt), both listen on same port (3000).
In future, I might separate it to server(3333) and client(3000)
Therefore the api links will be
localhost:3333/api
192.168.8.1:3333/api
example.com:3333/api
How do I achieve dynamic api url based on browser and switch port?
You don't need baseURL in nuxt.config.js.
Create a plugins/axios.js file first (Look here) and write like this.
export default function({ $axios }) {
if (process.client) {
const protocol = window.location.protocol
const hostname = window.location.hostname
const port = 8000
const url = `${protocol}//${hostname}:${port}`
$axios.defaults.baseURL = url
}
A late contribution, but this question and answers were helpful for getting to this more concise approach. I've tested it for localhost and deploying to a branch url at Netlify. Tested only with Windows Chrome.
In client mode, windows.location.origin contains what we need for the baseURL.
# /plugins/axios-host.js
export default function ({$axios}) {
if (process.client) {
$axios.defaults.baseURL = window.location.origin
}
}
Add the plugin to nuxt.config.js.
# /nuxt.config.js
...
plugins: [
...,
"~/plugins/axios-host.js",
],
...
This question is a year and a half old now, but I wanted to answer the second part for anyone that would find it helpful, which is doing it on the server-side.
I stored a reference to the server URL that I wanted to call as a Cookie so that the server can determine which URL to use as well. I use cookie-universal-nuxt and just do something simple like $cookies.set('api-server', 'some-server') and then pull the cookie value with $cookies.get('api-server') .. map that cookie value to a URL then you can do something like this using an Axios interceptor:
// plguins/axios.js
const axiosPlugin = ({ store, app: { $axios, $cookies } }) => {
$axios.onRequest ((config) => {
const server = $cookies.get('api-server')
if (server && server === 'some-server') {
config.baseURL = 'https://some-server.com'
}
return config
})
}
Of course you could also store the URL in the cookie itself, but it's probably best to have a whitelist of allowed URLs.
Don't forget to enable the plugin as well.
// nuxt.config.js
plugins: [
'~/plugins/axios',
This covers both the client-side and server-side since the cookie is "universal"

Resources