Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(rest-api): API gateway for rfq-indexer API and rfq API + swagger merge [SLT-339] #3323

Merged
merged 13 commits into from
Oct 29, 2024
4 changes: 2 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"editor.defaultFormatter": "JuanBlanco.solidity"
},
"[typescript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
Expand All @@ -26,4 +26,4 @@
".*Class.*",
".*Properties.*",
]
}
}
2 changes: 1 addition & 1 deletion docs/bridge/docs/04-Routers/RFQ/API/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ The RFQ API expects the signatures to have V values as 0/1 rather than 27/28. Th

### API Urls

- Mainnet: `rfq-api.omnirpc.io`
- Mainnet: `api.synapseprotocol.com/quotes`
- Testnet: `rfq-api-testnet.omnirpc.io`
Comment on lines +53 to 54
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

API endpoint inconsistency detected in configuration

There's an inconsistency in the API endpoints across the documentation. While the RFQ API documentation has been updated to use api.synapseprotocol.com/quotes for mainnet, the docusaurus.config.ts file still contains a reference to the old endpoint: baseUrl: 'https://rfq-api.omnirpc.io/'.

  • docs/bridge/docusaurus.config.ts: Update the baseUrl configuration to use the new API endpoint
  • Ensure the testnet endpoint rfq-api-testnet.omnirpc.io is still valid and intended to be used
🔗 Analysis chain

Verify API endpoint consistency across documentation.

The mainnet API URL has been updated to use the new base URL. Let's ensure this change is consistently reflected across all related documentation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to the old API URL and verify consistency of the new URL
# across documentation files

echo "Checking for old API URL references..."
rg -i "rfq-api\.omnirpc\.io" docs/

echo "Verifying consistency of new API URL..."
rg -i "api\.synapseprotocol\.com/quotes" docs/

Length of output: 430


Script:

#!/bin/bash
# Let's check for any other variations of the API endpoints to ensure complete coverage

echo "Checking for variations of omnirpc domain..."
rg -i "omnirpc" docs/

echo "Checking for variations of synapseprotocol domain..."
rg -i "synapseprotocol" docs/

echo "Checking for any API endpoint configurations in code..."
fd -e ts -e js -e json --exec grep -l -i "api\." {} \;

Length of output: 12309

🧰 Tools
🪛 Markdownlint

53-53: Expected: 0; Actual: 1
Unordered list indentation

(MD007, ul-indent)


54-54: Expected: 0; Actual: 1
Unordered list indentation

(MD007, ul-indent)



Expand Down
2 changes: 1 addition & 1 deletion docs/bridge/docs/06-Services/06-RFQ-Indexer-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ The RFQ Indexer API is a service designed to provide access to indexed RFQ bridg

## API-docs

[`https://triumphant-magic-production.up.railway.app/api-docs/`](https://triumphant-magic-production.up.railway.app/api-docs/)
[`api.synapseprotocol.com/api-docs/`](https://api.synapseprotocol.com/api-docs/)

## Key Features
1. **Real-Time and Historical Data** Indexes from a specified start block up to real-time events.
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,15 @@
"copyfiles": "^2.3.0",
"depcheck": "^1.4.3",
"doctoc": "^2.2.0",
"eslint": "^8.16.0",
"eslint": "^8.53.0",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

⚠️ Missing required peer dependency for eslint-config-standard

The version updates are mostly compatible, but there's one important issue:

  • [email protected] requires eslint-plugin-n as a peer dependency, which is not present in your package.json
  • All other peer dependencies are satisfied with current versions:
    • eslint@^8.53.0 satisfies the requirements
    • eslint-plugin-import@^2.26.0 satisfies the requirement
    • eslint-plugin-promise@^6.0.0 is exactly the version required

Please add the missing peer dependency:

"eslint-plugin-n": "^15.0.0"
🔗 Analysis chain

Verify compatibility with major version updates.

The updates include major version bumps that might introduce breaking changes:

  • eslint-config-standard: 16 -> 17
  • eslint-plugin-promise: 5 -> 6

Also applies to: 54-54, 60-60


Let me gather more information about the ESLint configuration and potential peer dependency issues.


Let me check one more thing to verify the peer dependencies of the updated packages.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for peer dependency warnings in package.json files
echo "Checking for peer dependency requirements..."
rg -A 5 '"peerDependencies"' 

# Check if there are any existing ESLint configuration files
echo "Checking for ESLint config files..."
fd -e .eslintrc.js -e .eslintrc.json -e .eslintrc.yml

Length of output: 685


Script:

#!/bin/bash
# Check for ESLint configuration
echo "Checking ESLint configuration..."
fd '.eslintrc' --type f --exec cat {}

# Check package.json for ESLint related dependencies
echo -e "\nChecking ESLint related dependencies..."
rg '"eslint.*":' package.json

# Check for any existing ESLint errors with current config
echo -e "\nChecking for potential ESLint configuration issues..."
fd '.js' --type f --exec grep -l "eslint-disable" {} \;

Length of output: 876


Script:

#!/bin/bash
# Check npm registry for peer dependencies of the updated packages
echo "Checking peer dependencies for [email protected]..."
curl -s https://registry.npmjs.org/eslint-config-standard/17.0.0 | jq '.peerDependencies'

echo -e "\nChecking peer dependencies for [email protected]..."
curl -s https://registry.npmjs.org/eslint-plugin-promise/6.0.0 | jq '.peerDependencies'

Length of output: 619

"eslint-config-prettier": "^8.3.0",
"eslint-config-standard": "^16.0.3",
"eslint-config-standard": "^17.0.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-jsdoc": "^35.1.2",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prefer-arrow": "^1.2.3",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-promise": "^5.1.0",
"eslint-plugin-promise": "^6.0.0",
"eslint-plugin-react": "^7.24.0",
"eslint-plugin-unicorn": "^42.0.0",
"lerna": "^4.0.0",
Expand Down
2 changes: 2 additions & 0 deletions packages/rest-api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"ethers": "5.7.2",
"express": "^4.18.2",
"express-validator": "^7.2.0",
"http-proxy-middleware": "^3.0.3",
"jest": "^29.7.0",
"lodash": "^4.17.21",
"supertest": "^6.3.3",
Expand All @@ -48,6 +49,7 @@
"lodash": "^4.17.21",
"nodemon": "^3.0.1",
"swagger-jsdoc": "^6.2.8",
"swagger-merge": "^0.4.0",
"swagger-ui-express": "^5.0.1",
"ts-jest": "^29.2.5",
"ts-node": "^10.9.2"
Expand Down
17 changes: 15 additions & 2 deletions packages/rest-api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ import swaggerUi from 'swagger-ui-express'
import { specs } from './swagger'
import routes from './routes'
import { logger } from './middleware/logger'
import {
isRFQAPIRequest,
isRFQIndexerRequest,
rfqApiProxy,
rfqIndexerProxy,
} from './utils/isGatewayRoute'

const app = express()
const port = process.env.PORT || 3000
Expand All @@ -20,7 +26,6 @@ app.use((req, res, next) => {
})

const originalPath = req.path

const originalJson = res.json
res.json = function (body) {
logger.info({
Expand All @@ -36,7 +41,15 @@ app.use((req, res, next) => {
return originalJson.call(this, body)
}

next()
if (isRFQAPIRequest(originalPath)) {
return rfqApiProxy(req, res, next)
}

if (isRFQIndexerRequest(originalPath)) {
return rfqIndexerProxy(req, res, next)
}

return next()
})

app.listen(port, () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/rest-api/src/routes/bridgeLimitsRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { normalizeNativeTokenAddress } from '../middleware/normalizeNativeTokenA
import { checksumAddresses } from '../middleware/checksumAddresses'
import { validateRouteExists } from '../validations/validateRouteExists'

const router = express.Router()
const router: express.Router = express.Router()

/**
* @openapi
Expand Down
2 changes: 1 addition & 1 deletion packages/rest-api/src/routes/bridgeRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { checksumAddresses } from '../middleware/checksumAddresses'
import { normalizeNativeTokenAddress } from '../middleware/normalizeNativeTokenAddress'
import { validateRouteExists } from '../validations/validateRouteExists'

const router = express.Router()
const router: express.Router = express.Router()

/**
* @openapi
Expand Down
2 changes: 1 addition & 1 deletion packages/rest-api/src/routes/bridgeTxInfoRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { checksumAddresses } from '../middleware/checksumAddresses'
import { normalizeNativeTokenAddress } from '../middleware/normalizeNativeTokenAddress'
import { validateRouteExists } from '../validations/validateRouteExists'

const router = express.Router()
const router: express.Router = express.Router()

/**
* @openapi
Expand Down
2 changes: 1 addition & 1 deletion packages/rest-api/src/routes/bridgeTxStatusRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { bridgeTxStatusController } from '../controllers/bridgeTxStatusControlle
import { CHAINS_ARRAY } from '../constants/chains'
import { VALID_BRIDGE_MODULES } from '../constants'

const router = express.Router()
const router: express.Router = express.Router()

/**
* @openapi
Expand Down
2 changes: 1 addition & 1 deletion packages/rest-api/src/routes/destinationTokensRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { isTokenSupportedOnChain } from '../utils/isTokenSupportedOnChain'
import { checksumAddresses } from '../middleware/checksumAddresses'
import { normalizeNativeTokenAddress } from '../middleware/normalizeNativeTokenAddress'

const router = express.Router()
const router: express.Router = express.Router()

/**
* @openapi
Expand Down
2 changes: 1 addition & 1 deletion packages/rest-api/src/routes/destinationTxRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { check } from 'express-validator'
import { showFirstValidationError } from '../middleware/showFirstValidationError'
import { destinationTxController } from '../controllers/destinationTxController'

const router = express.Router()
const router: express.Router = express.Router()

/**
* @openapi
Expand Down
2 changes: 1 addition & 1 deletion packages/rest-api/src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import tokenListRoute from './tokenListRoute'
import destinationTokensRoute from './destinationTokensRoute'
import bridgeLimitsRoute from './bridgeLimitsRoute'

const router = express.Router()
const router: express.Router = express.Router()

router.use('/', indexRoute)
router.use('/swap', swapRoute)
Expand Down
2 changes: 1 addition & 1 deletion packages/rest-api/src/routes/indexRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import express from 'express'

import { indexController } from '../controllers/indexController'

const router = express.Router()
const router: express.Router = express.Router()

/**
* @openapi
Expand Down
2 changes: 1 addition & 1 deletion packages/rest-api/src/routes/swapRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { normalizeNativeTokenAddress } from '../middleware/normalizeNativeTokenA
import { validSwapTokens } from '../validations/validSwapTokens'
import { validSwapChain } from '../validations/validSwapChain'

const router = express.Router()
const router: express.Router = express.Router()

/**
* @openapi
Expand Down
2 changes: 1 addition & 1 deletion packages/rest-api/src/routes/swapTxInfoRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { isTokenSupportedOnChain } from '../utils/isTokenSupportedOnChain'
import { checksumAddresses } from '../middleware/checksumAddresses'
import { normalizeNativeTokenAddress } from '../middleware/normalizeNativeTokenAddress'

const router = express.Router()
const router: express.Router = express.Router()

/**
* @openapi
Expand Down
2 changes: 1 addition & 1 deletion packages/rest-api/src/routes/synapseTxIdRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { showFirstValidationError } from '../middleware/showFirstValidationError
import { synapseTxIdController } from '../controllers/synapseTxIdController'
import { VALID_BRIDGE_MODULES } from '../constants'

const router = express.Router()
const router: express.Router = express.Router()

/**
* @openapi
Expand Down
2 changes: 1 addition & 1 deletion packages/rest-api/src/routes/tokenListRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import express from 'express'

import { tokenListController } from '../controllers/tokenListController'

const router = express.Router()
const router: express.Router = express.Router()

/**
* @openapi
Expand Down
33 changes: 8 additions & 25 deletions packages/rest-api/src/swagger.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,11 @@
import swaggerJsdoc from 'swagger-jsdoc'
import fs from 'fs'
import path from 'path'

// eslint-disable-next-line @typescript-eslint/no-var-requires
const packageJson = require('../package.json')
// Define the path to your static swagger.json file
const swaggerFilePath = path.join(__dirname, '../swagger.json')

const isDevelopment = process.env.NODE_ENV === 'development'
const serverUrl = isDevelopment
? 'http://localhost:3000'
: 'https://api.synapseprotocol.com'
// Read the static swagger.json file
const specs = JSON.parse(fs.readFileSync(swaggerFilePath, 'utf8'))

Comment on lines +4 to +8
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling and consider asynchronous file reading.

The current implementation has several potential issues:

  1. Synchronous file reading can block the Node.js event loop
  2. No error handling for missing file or invalid JSON
  3. No validation of the parsed swagger specification

Consider implementing this more robust approach:

-// Define the path to your static swagger.json file
-const swaggerFilePath = path.join(__dirname, '../swagger.json')
-
-// Read the static swagger.json file
-const specs = JSON.parse(fs.readFileSync(swaggerFilePath, 'utf8'))
+import { OpenAPIV3 } from 'openapi-types'
+
+const swaggerFilePath = path.join(__dirname, '../swagger.json')
+
+function loadSwaggerSpec(): OpenAPIV3.Document {
+  try {
+    const fileContent = fs.readFileSync(swaggerFilePath, 'utf8')
+    const parsedSpec = JSON.parse(fileContent)
+    
+    // Basic validation of the OpenAPI spec
+    if (!parsedSpec.openapi || !parsedSpec.info || !parsedSpec.paths) {
+      throw new Error('Invalid OpenAPI specification format')
+    }
+    
+    return parsedSpec
+  } catch (error) {
+    if (error instanceof Error) {
+      throw new Error(`Failed to load Swagger specification: ${error.message}`)
+    }
+    throw error
+  }
+}
+
+const specs = loadSwaggerSpec()

Committable suggestion was skipped due to low confidence.

const options: swaggerJsdoc.Options = {
definition: {
openapi: '3.0.0',
info: {
title: 'Synapse Protocol REST API',
version: packageJson.version,
description: 'API documentation for the Synapse Protocol REST API',
},
servers: [
{
url: serverUrl,
},
],
},
apis: ['./src/routes/*.ts', './src/*.ts'],
}

export const specs = swaggerJsdoc(options)
// Export the specs for use in your application
export { specs }
34 changes: 34 additions & 0 deletions packages/rest-api/src/utils/isGatewayRoute.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { createProxyMiddleware } from 'http-proxy-middleware'

export const isRFQIndexerRequest = (route: string): boolean => {
return (
route.includes('/conflicting-proofs') ||
route.includes('/disputes') ||
route.includes('/invalid-relaus') ||
route.includes('/pending-transactions') ||
route.includes('/refunded-and-relayed') ||
route.includes('/transaction-id')
)
}
Comment on lines +3 to +12
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Security and reliability improvements needed in route checking.

The current implementation has several issues:

  1. Using includes() is vulnerable to partial matches (e.g., /my-disputes-api would match /disputes)
  2. There's a typo in /invalid-relaus (should be /invalid-relays)
  3. Missing input validation for null/undefined routes

Consider this safer implementation:

 export const isRFQIndexerRequest = (route: string): boolean => {
+  if (!route) return false;
+  const validPaths = [
+    '/conflicting-proofs',
+    '/disputes',
+    '/invalid-relays',
+    '/pending-transactions',
+    '/refunded-and-relayed',
+    '/transaction-id'
+  ];
+  return validPaths.some(path => 
+    route === path || route.startsWith(`${path}/`)
+  );
-  return (
-    route.includes('/conflicting-proofs') ||
-    route.includes('/disputes') ||
-    route.includes('/invalid-relaus') ||
-    route.includes('/pending-transactions') ||
-    route.includes('/refunded-and-relayed') ||
-    route.includes('/transaction-id')
-  )
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const isRFQIndexerRequest = (route: string): boolean => {
return (
route.includes('/conflicting-proofs') ||
route.includes('/disputes') ||
route.includes('/invalid-relaus') ||
route.includes('/pending-transactions') ||
route.includes('/refunded-and-relayed') ||
route.includes('/transaction-id')
)
}
export const isRFQIndexerRequest = (route: string): boolean => {
if (!route) return false;
const validPaths = [
'/conflicting-proofs',
'/disputes',
'/invalid-relays',
'/pending-transactions',
'/refunded-and-relayed',
'/transaction-id'
];
return validPaths.some(path =>
route === path || route.startsWith(`${path}/`)
);
}


export const isRFQAPIRequest = (route: string): boolean => {
return (
route.includes('/ack') ||
route.includes('/bulk_quotes') ||
route.includes('/contracts') ||
route.includes('/open_quote_requests') ||
route.includes('/quotes') ||
route.includes('/rfq') ||
route.includes('/rfq_stream')
)
}
Comment on lines +14 to +24
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Apply the same security improvements to RFQ API route checking.

The function has the same security vulnerabilities as isRFQIndexerRequest.

Apply similar improvements:

 export const isRFQAPIRequest = (route: string): boolean => {
+  if (!route) return false;
+  const validPaths = [
+    '/ack',
+    '/bulk_quotes',
+    '/contracts',
+    '/open_quote_requests',
+    '/quotes',
+    '/rfq',
+    '/rfq_stream'
+  ];
+  return validPaths.some(path => 
+    route === path || route.startsWith(`${path}/`)
+  );
-  return (
-    route.includes('/ack') ||
-    route.includes('/bulk_quotes') ||
-    route.includes('/contracts') ||
-    route.includes('/open_quote_requests') ||
-    route.includes('/quotes') ||
-    route.includes('/rfq') ||
-    route.includes('/rfq_stream')
-  )
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const isRFQAPIRequest = (route: string): boolean => {
return (
route.includes('/ack') ||
route.includes('/bulk_quotes') ||
route.includes('/contracts') ||
route.includes('/open_quote_requests') ||
route.includes('/quotes') ||
route.includes('/rfq') ||
route.includes('/rfq_stream')
)
}
export const isRFQAPIRequest = (route: string): boolean => {
if (!route) return false;
const validPaths = [
'/ack',
'/bulk_quotes',
'/contracts',
'/open_quote_requests',
'/quotes',
'/rfq',
'/rfq_stream'
];
return validPaths.some(path =>
route === path || route.startsWith(`${path}/`)
);
}


export const rfqApiProxy = createProxyMiddleware({
target: 'https://rfq-api.omnirpc.io',
changeOrigin: true,
})

export const rfqIndexerProxy = createProxyMiddleware({
target: 'https://rfq-indexer.synapseprotocol.com/api',
changeOrigin: true,
})
Comment on lines +26 to +34
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

⚠️ Potential issue

Security enhancements needed for proxy middleware configuration

The codebase analysis reveals:

  • Environment variables are already in use for other configurations (OMNIRPC_BASE_URL, NODE_ENV, PORT)
  • No existing error handling in proxy routes
  • Rate limiting exists in bridge-related components but not for proxy routes

Recommended changes:

  • Move proxy URLs to environment variables following existing patterns
  • Add error handling for proxy failures
  • Extend existing rate limiting to proxy routes
  • Add security headers
export const rfqApiProxy = createProxyMiddleware({
  target: process.env.RFQ_API_URL || 'https://rfq-api.omnirpc.io',
  changeOrigin: true,
  headers: {
    'X-Forwarded-Proto': 'https',
  },
  onError: (err, req, res) => {
    logger.error('RFQ API Proxy Error:', err);
    res.status(502).json({ error: 'Gateway Error' });
  },
})

export const rfqIndexerProxy = createProxyMiddleware({
  target: process.env.RFQ_INDEXER_URL || 'https://rfq-indexer.synapseprotocol.com/api',
  changeOrigin: true,
  headers: {
    'X-Forwarded-Proto': 'https',
  },
  onError: (err, req, res) => {
    logger.error('RFQ Indexer Proxy Error:', err);
    res.status(502).json({ error: 'Gateway Error' });
  },
})
🔗 Analysis chain

Enhance proxy middleware security and configuration.

The current proxy setup lacks several important security features and best practices:

  1. Hardcoded URLs should be environment variables
  2. Missing security headers and options
  3. No rate limiting or request validation
  4. No error handling

Consider this improved implementation:

+const RFQ_API_URL = process.env.RFQ_API_URL || 'https://rfq-api.omnirpc.io';
+const RFQ_INDEXER_URL = process.env.RFQ_INDEXER_URL || 'https://rfq-indexer.synapseprotocol.com/api';

 export const rfqApiProxy = createProxyMiddleware({
-  target: 'https://rfq-api.omnirpc.io',
+  target: RFQ_API_URL,
   changeOrigin: true,
+  pathRewrite: {
+    '^/api': '', // remove /api prefix if needed
+  },
+  headers: {
+    'X-Forwarded-Proto': 'https',
+  },
+  onError: (err, req, res) => {
+    console.error('Proxy Error:', err);
+    res.status(500).json({ error: 'Proxy Error' });
+  },
 })

 export const rfqIndexerProxy = createProxyMiddleware({
-  target: 'https://rfq-indexer.synapseprotocol.com/api',
+  target: RFQ_INDEXER_URL,
   changeOrigin: true,
+  pathRewrite: {
+    '^/api': '',
+  },
+  headers: {
+    'X-Forwarded-Proto': 'https',
+  },
+  onError: (err, req, res) => {
+    console.error('Proxy Error:', err);
+    res.status(500).json({ error: 'Proxy Error' });
+  },
 })

Additionally, consider implementing rate limiting middleware and request validation before proxying requests.

Let's verify the environment configuration in the project:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if environment variables are properly configured
rg -l "RFQ_API_URL|RFQ_INDEXER_URL" --type yaml --type env

Length of output: 88


Script:

#!/bin/bash
# Check for environment variable configurations in various config files
rg -l "RFQ_API_URL|RFQ_INDEXER_URL"

# Check for any existing environment configuration patterns
rg -l "process\.env\." packages/rest-api/src/

# Look for any configuration files
fd -e yaml -e yml -e env -e config.js -e config.ts packages/rest-api/

# Check the proxy middleware implementation details
ast-grep --pattern 'createProxyMiddleware({$$$})'

Length of output: 1349


Script:

#!/bin/bash
# Check how environment variables are used in the existing files
rg -A 5 "process\.env\." packages/rest-api/src/app.ts packages/rest-api/src/utils/getOmniRpcUrl.ts packages/rest-api/src/middleware/logger.ts

# Check if there's any existing error handling in proxy routes
rg -A 5 "onError|error" packages/rest-api/src/utils/isGatewayRoute.ts

# Look for any rate limiting implementations
rg -l "rate|limit" packages/rest-api/src/

Length of output: 1465

Loading
Loading