Files
cloudron-box/src/routes/filemanager.js
T

57 lines
2.1 KiB
JavaScript
Raw Normal View History

import assert from 'node:assert';
import BoxError from '../boxerror.js';
import http from 'node:http';
import { HttpError } from '@cloudron/connect-lastmile';
import safe from 'safetydance';
import services from '../services.js';
2020-07-10 14:13:16 +02:00
function proxy(kind) {
assert(kind === 'mail' || kind === 'volume' || kind === 'app');
2020-07-10 14:13:16 +02:00
return async function (req, res, next) {
req.clearTimeout();
2020-07-13 16:26:42 +02:00
let id = null;
switch (kind) {
case 'app': id = `app-${req.params.id}`; break;
case 'volume': id = `volume-${req.params.id}`; break;
case 'mail': id = 'mail'; break;
}
2020-07-10 14:13:16 +02:00
2024-07-30 12:11:07 +02:00
const [error, addonDetails] = await safe(services.getContainerDetails('sftp', 'CLOUDRON_SFTP_TOKEN'));
if (error) return next(BoxError.toHttpError(error));
2020-07-10 14:13:16 +02:00
2024-07-30 12:11:07 +02:00
const searchParams = new URLSearchParams(req.url.slice(req.url.indexOf('?')+1));
searchParams.delete('access_token');
searchParams.append('access_token', addonDetails.token);
2025-06-06 16:22:46 +02:00
const filepath = req.params.filepath.join('/');
2024-07-30 12:11:07 +02:00
const opts = {
hostname: addonDetails.ip,
port: 3000,
2025-06-06 16:22:46 +02:00
path: `/files/${id}/${encodeURIComponent(filepath)}?${searchParams.toString()}`, // params[0] already contains leading '/'
2024-07-30 12:11:07 +02:00
method: req.method,
headers: req.headers
};
const sftpReq = http.request(opts, function (sftpRes) {
2025-02-17 14:26:17 +01:00
res.writeHead(sftpRes.statusCode, sftpRes.headers);
2024-08-08 15:20:50 +02:00
// note: these are intentionally not handled. response has already been written. do not forward to connect-lastmile
// sftpRes.on('error', (error) => next(new HttpError(500, `filemanager error: ${error.message} ${error.code}`)));
// sftpRes.on('end', () => next());
2024-07-30 12:11:07 +02:00
sftpRes.pipe(res);
});
2026-02-18 08:18:37 +01:00
sftpReq.on('error', (reqError) => next(new HttpError(424, `Unable to connect to filemanager: ${reqError.message} ${reqError.code}`)));
2024-07-30 12:11:07 +02:00
if (!req.readable) {
sftpReq.end();
} else {
req.pipe(sftpReq);
}
};
2021-09-25 23:27:25 -07:00
}
2026-02-14 15:43:24 +01:00
export default {
proxy,
};