@bsv/wallet-toolbox
Version:
BRC100 conforming wallet, wallet storage and wallet signer components
69 lines • 3.08 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocalCdnServer = void 0;
const express_1 = __importDefault(require("express"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const cors_1 = __importDefault(require("cors"));
const http_1 = __importDefault(require("http"));
class LocalCdnServer {
constructor(port, folder) {
this.port = port;
this.folder = folder;
// Ensure the files directory exists
if (!fs_1.default.existsSync(this.folder)) {
fs_1.default.mkdirSync(this.folder);
}
}
async start() {
this.app = (0, express_1.default)();
this.server = http_1.default.createServer(this.app);
// Enable CORS for all routes
this.app.use((0, cors_1.default)());
// Serve static files from the files directory
this.app.use('/blockheaders', express_1.default.static(this.folder));
// List all files in the directory
this.app.get('/files', (req, res) => {
fs_1.default.readdir(this.folder, (err, files) => {
if (err) {
return res.status(500).json({ error: 'Unable to read directory' });
}
res.json({ files });
});
});
// Download specific file
this.app.get('/download/:filename', (req, res) => {
const filePath = path_1.default.join(this.folder, req.params.filename);
// Ensure filePath stays within the allowed folder (prevent directory traversal)
const resolvedFolder = path_1.default.resolve(this.folder);
const resolvedFilePath = path_1.default.resolve(filePath);
if (!resolvedFilePath.startsWith(resolvedFolder + path_1.default.sep)) {
// Prevent access to files outside the allowed directory
return res.status(403).json({ error: 'Access denied' });
}
if (!fs_1.default.existsSync(resolvedFilePath)) {
return res.status(404).json({ error: 'File not found' });
}
res.download(resolvedFilePath, err => {
if (err) {
res.status(500).json({ error: 'Error downloading file' });
}
});
});
this.server.listen(this.port, () => {
// console.log(`Server running at http://localhost:${this.port}`)
// console.log(`Serving files from: ${this.folder}`)
// console.log(`Access files at: http://localhost:${this.port}/blockheaders`)
// console.log(`List files at: http://localhost:${this.port}/files`)
});
}
async stop() {
var _a;
await ((_a = this.server) === null || _a === void 0 ? void 0 : _a.close());
}
}
exports.LocalCdnServer = LocalCdnServer;
//# sourceMappingURL=LocalCdnServer.js.map