Skip to content

Commit c455361

Browse files
authored
Merge pull request #66 from Luen/Uncontrolled-data-used-in-path-expression
Potential fix for code scanning alert no. 7: Uncontrolled data used in path expression
2 parents 9075604 + b4666e5 commit c455361

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

index.js

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const port = process.env.PORT || 8080
1212

1313
const accepted = ['jpg', 'jpeg', 'png']
1414
const logoPath = path.join(__dirname, 'Wanderstories-logo.png')
15+
const imagesRoot = path.resolve(__dirname, 'content', 'images')
1516

1617
const app = express()
1718
app.set('trust proxy', 1) // trust first proxy
@@ -55,9 +56,13 @@ app.use(
5556
const allowedOrigins = [
5657
'https://images.wanderstories.space',
5758
'https://wanderstories.space',
59+
'http://localhost:8080',
5860
]
5961
const corsOptions = {
6062
origin: function (origin, callback) {
63+
// Allow requests with no origin (like mobile apps or curl requests)
64+
if (!origin) return callback(null, true)
65+
6166
if (allowedOrigins.includes(origin)) {
6267
callback(null, true)
6368
} else {
@@ -117,11 +122,15 @@ app.get('/content/images/*', async (req, res, next) => {
117122
'images',
118123
relativePath
119124
)
125+
const resolvedImagePath = path.resolve(imagePath)
126+
if (!resolvedImagePath.startsWith(imagesRoot + path.sep)) {
127+
return res.status(403).send('Forbidden')
128+
}
120129

121130
try {
122131
// await fs.promises.access(imagePath, fs.constants.F_OK);
123-
await fs.promises.access(imagePath)
124-
return res.sendFile(imagePath)
132+
await fs.promises.access(resolvedImagePath)
133+
return res.sendFile(resolvedImagePath)
125134
} catch (err) {
126135
// File doesn't exist (this is expected), continue processing
127136
// console.error("File does not exist, proceeding with processing: ", err);
@@ -210,14 +219,14 @@ app.get('/content/images/*', async (req, res, next) => {
210219
const directoryPath = path.dirname(imagePath)
211220
try {
212221
await fs.promises.mkdir(directoryPath, { recursive: true })
213-
await fs.promises.writeFile(imagePath, outputBuffer)
222+
await fs.promises.writeFile(resolvedImagePath, outputBuffer)
214223
} catch (err) {
215224
// Handle file writing error
216225
// console.error("Error writing file: ", err);
217226
return res.status(500).send('Internal Server Error')
218227
}
219228

220-
return res.sendFile(imagePath)
229+
return res.sendFile(resolvedImagePath)
221230
} catch (err) {
222231
//console.error(err);
223232
return res.status(500).send('Internal Server Error')

0 commit comments

Comments
 (0)