Skip to content

Instantly share code, notes, and snippets.

@DarkSeraphim
Created March 10, 2021 12:26
Show Gist options
  • Save DarkSeraphim/0e12c33c835e9123cb227de9e08b61f2 to your computer and use it in GitHub Desktop.
Save DarkSeraphim/0e12c33c835e9123cb227de9e08b61f2 to your computer and use it in GitHub Desktop.
Pluggable PUT/GET service for Nexus testing
const Fastify = require('fastify');
const fastify = new Fastify();
const fs = require('fs');
const path = require('path');
const uploads = path.resolve(process.env.UPLOAD_DIR);
fs.mkdirSync(uploads, { recursive: true });
fastify.addContentTypeParser('*', function (request, payload, done) {
const buffers = [];
payload.on('data', chunk => buffers.push(chunk))
payload.on('end', () => {
done(null, Buffer.concat(buffers))
})
})
const FORBIDDEN = ['.\\', '..\\', './', '../'];
fastify.put('*', async (req, res) => {
let url = req.url;
if (FORBIDDEN.some(nope => url.startsWith(nope))) {
res.status(400).send({error: 'Invalid path'});
return;
}
while (url[0] === '/') {
url = url.slice(1); // Ensure we don't have a leading /
}
let localPath = path.resolve(uploads, url);
// TODO: check if this path ends up outside of uploads
await fs.promises.mkdir(path.dirname(localPath), { recursive: true });
await fs.promises.writeFile(localPath, req.body);
res.send();
});
fastify.get('*', async (req, res) => {
let url = req.url;
while (url[0] === '/') {
url = url.slice(1); // Ensure we don't have a leading /
}
let localPath = path.resolve(uploads, url);
res.send(fs.createReadStream(localPath));
});
fastify.listen(process.env.PORT, process.env.BIND_HOST || '0.0.0.0');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment