Add static file serve for resources inside of data-directory (#19)
This commit is contained in:
@ -4,8 +4,11 @@ import { Server, ServerOptions } from "@coder/protocol/src/node/server";
|
||||
import { NewSessionMessage } from '@coder/protocol/src/proto';
|
||||
import { ChildProcess } from "child_process";
|
||||
import * as express from "express";
|
||||
import * as fs from "fs";
|
||||
import * as http from "http";
|
||||
import * as mime from "mime-types";
|
||||
import * as path from "path";
|
||||
import * as util from "util";
|
||||
import * as ws from "ws";
|
||||
import { forkModule } from "./vscode/bootstrapFork";
|
||||
|
||||
@ -63,6 +66,43 @@ export const createApp = (registerMiddleware?: (app: express.Application) => voi
|
||||
|
||||
app.use(express.static(path.join(__dirname, "../build/web")));
|
||||
|
||||
app.get("/resource/:url(*)", async (req, res) => {
|
||||
try {
|
||||
const fullPath = `/${req.params.url}`;
|
||||
const relative = path.relative(options!.dataDirectory, fullPath);
|
||||
if (relative.startsWith("..")) {
|
||||
return res.status(403).end();
|
||||
}
|
||||
const exists = await util.promisify(fs.exists)(fullPath);
|
||||
if (!exists) {
|
||||
res.status(404).end();
|
||||
return;
|
||||
}
|
||||
const stat = await util.promisify(fs.stat)(fullPath);
|
||||
if (!stat.isFile()) {
|
||||
res.write("Resource must be a file.");
|
||||
res.status(422);
|
||||
res.end();
|
||||
|
||||
return;
|
||||
}
|
||||
let mimeType = mime.lookup(fullPath);
|
||||
if (mimeType === false) {
|
||||
mimeType = "application/octet-stream";
|
||||
}
|
||||
const content = await util.promisify(fs.readFile)(fullPath);
|
||||
|
||||
res.header("Content-Type", mimeType as string);
|
||||
res.write(content);
|
||||
res.status(200);
|
||||
res.end();
|
||||
} catch (ex) {
|
||||
res.write(ex.toString());
|
||||
res.status(500);
|
||||
res.end();
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
express: app,
|
||||
server,
|
||||
|
Reference in New Issue
Block a user