Skip to content

Commit d61be7e

Browse files
authored
feat: Handling to detect API Endpoints in next.js framework (#287)
1 parent 13ae0aa commit d61be7e

File tree

1 file changed

+52
-0
lines changed
  • lib/instrumentation-security/hooks/nextjs

1 file changed

+52
-0
lines changed

lib/instrumentation-security/hooks/nextjs/nr-next.js

+52
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,38 @@
66
'use strict'
77
const requestManager = require("../../core/request-manager");
88
const API = require("../../../nr-security-api");
9+
const routeManager = require('../../core/route-manager');
910
const logger = API.getLogger();
11+
const lodash = require('lodash');
12+
const { ATTHERATE, DOUBLE_DOLLAR, EMPTY_STR } = require('../../core/constants');
1013

1114
const semver = require('semver')
15+
const fs = require('fs');
16+
const path = require('path');
1217

1318
module.exports = function initialize(shim, nextjs) {
1419
const nextVersion = shim.require('./package.json').version
1520
logger.info("Instrumenting nextjs", nextVersion);
1621

1722
const nextServer = nextjs.default;
1823
hookRunAPI(shim, nextServer.prototype, nextVersion);
24+
25+
//TODO need to update for API endpoints
26+
try {
27+
const appRoot = process.env.PWD;
28+
const searchPath = appRoot + '/.next/server/pages/api';
29+
const allAPIEndpoints = getAllAPIEndpoints(searchPath);
30+
logger.debug("allAPIEndpoints:", allAPIEndpoints);
31+
for (let index = 0; index < allAPIEndpoints.length; index++) {
32+
const element = allAPIEndpoints[index];
33+
let key = "*" + ATTHERATE + element;
34+
routeManager.setRoute(key, EMPTY_STR);
35+
}
36+
} catch (error) {
37+
logger.debug("Error while getting all API end points for next.js", error);
38+
}
39+
40+
1941
}
2042

2143
/**
@@ -91,3 +113,33 @@ function extractParams(shim, page, params) {
91113
}
92114
}
93115

116+
117+
/**
118+
* Utility to scan pages directory to get all avaible routes
119+
* @param {*} dir
120+
* @returns
121+
*/
122+
const getAllAPIEndpoints = (dir) => {
123+
logger.debug("dir is:", dir)
124+
const apiEndpoints = [];
125+
126+
const scanDirectory = (currentDir) => {
127+
logger.debug("currentDir is:", currentDir)
128+
const files = fs.readdirSync(currentDir);
129+
130+
files.forEach((file) => {
131+
const filePath = path.join(currentDir, file);
132+
const isDirectory = fs.statSync(filePath).isDirectory();
133+
134+
if (isDirectory) {
135+
scanDirectory(filePath);
136+
} else {
137+
const apiEndpoint = filePath.replace(`${dir}/`, '/api/').replace(/\.js*.*/, '');
138+
apiEndpoints.push(apiEndpoint);
139+
}
140+
});
141+
};
142+
143+
scanDirectory(dir);
144+
return apiEndpoints;
145+
};

0 commit comments

Comments
 (0)