1
0
silverbullet/server/http_server.ts

627 lines
20 KiB
TypeScript
Raw Normal View History

import {
2024-01-13 17:07:02 +00:00
cors,
deleteCookie,
getCookie,
Hono,
HonoRequest,
setCookie,
} from "./deps.ts";
2022-10-12 09:47:13 +00:00
import { AssetBundle } from "../plugos/asset_bundle/bundle.ts";
2023-08-20 15:51:00 +00:00
import { FileMeta } from "$sb/types.ts";
2024-01-13 17:07:02 +00:00
import { ShellRequest } from "./rpc.ts";
import { determineShellBackend } from "./shell_backend.ts";
import { SpaceServer, SpaceServerConfig } from "./instance.ts";
2023-12-11 11:11:56 +00:00
import { KvPrimitives } from "../plugos/lib/kv_primitives.ts";
import { PrefixedKvPrimitives } from "../plugos/lib/prefixed_kv_primitives.ts";
import { base64Encode } from "../plugos/asset_bundle/base64.ts";
2023-12-11 11:11:56 +00:00
const authenticationExpirySeconds = 60 * 60 * 24 * 7; // 1 week
export type ServerOptions = {
hostname: string;
port: number;
clientAssetBundle: AssetBundle;
plugAssetBundle: AssetBundle;
baseKvPrimitives: KvPrimitives;
certFile?: string;
keyFile?: string;
configs: Map<string, SpaceServerConfig>;
};
export class HttpServer {
abortController?: AbortController;
clientAssetBundle: AssetBundle;
plugAssetBundle: AssetBundle;
hostname: string;
port: number;
2024-01-13 17:07:02 +00:00
app: Hono;
keyFile: string | undefined;
certFile: string | undefined;
spaceServers = new Map<string, Promise<SpaceServer>>();
baseKvPrimitives: KvPrimitives;
configs: Map<string, SpaceServerConfig>;
constructor(options: ServerOptions) {
2024-01-13 17:07:02 +00:00
this.app = new Hono();
this.clientAssetBundle = options.clientAssetBundle;
this.plugAssetBundle = options.plugAssetBundle;
this.hostname = options.hostname;
this.port = options.port;
this.keyFile = options.keyFile;
this.certFile = options.certFile;
this.baseKvPrimitives = options.baseKvPrimitives;
this.configs = options.configs;
}
2023-05-29 07:53:49 +00:00
async bootSpaceServer(config: SpaceServerConfig): Promise<SpaceServer> {
const spaceServer = new SpaceServer(
config,
determineShellBackend(config.pagesPath),
this.plugAssetBundle,
new PrefixedKvPrimitives(this.baseKvPrimitives, [
config.namespace,
]),
2023-05-29 07:53:49 +00:00
);
await spaceServer.init();
return spaceServer;
}
2024-01-13 17:07:02 +00:00
determineConfig(req: HonoRequest): [string, SpaceServerConfig] {
const url = new URL(req.url);
let hostname = url.host; // hostname:port
// First try a full match
let config = this.configs.get(hostname);
if (config) {
return [hostname, config];
}
// Then rip off the port and try again
hostname = hostname.split(":")[0];
config = this.configs.get(hostname);
if (config) {
return [hostname, config];
}
// If all else fails, try the wildcard
config = this.configs.get("*");
if (config) {
return ["*", config];
}
throw new Error(`No space server config found for hostname ${hostname}`);
}
2024-01-13 17:07:02 +00:00
ensureSpaceServer(req: HonoRequest): Promise<SpaceServer> {
const [matchedHostname, config] = this.determineConfig(req);
const spaceServer = this.spaceServers.get(matchedHostname);
if (spaceServer) {
return spaceServer;
}
// And then boot the thing, async
const spaceServerPromise = this.bootSpaceServer(config);
// But immediately write the promise to the map so that we don't boot it twice
this.spaceServers.set(matchedHostname, spaceServerPromise);
return spaceServerPromise;
}
// Replaces some template variables in index.html in a rather ad-hoc manner, but YOLO
renderIndexHtml(spaceServer: SpaceServer) {
return this.clientAssetBundle.readTextFileSync(".client/index.html")
.replaceAll(
"{{SPACE_PATH}}",
spaceServer.pagesPath.replaceAll("\\", "\\\\"),
2023-08-29 19:17:29 +00:00
// );
).replaceAll(
2023-08-30 15:25:54 +00:00
"{{SYNC_ONLY}}",
spaceServer.syncOnly ? "true" : "false",
).replaceAll(
"{{CLIENT_ENCRYPTION}}",
spaceServer.clientEncryption ? "true" : "false",
2023-08-29 19:17:29 +00:00
);
}
start() {
// Serve static files (javascript, css, html)
2024-01-13 17:07:02 +00:00
this.serveStatic();
this.addAuth();
this.addFsRoutes();
// Fallback, serve the UI index.html
2024-01-13 17:07:02 +00:00
this.app.use("*", async (c) => {
const spaceServer = await this.ensureSpaceServer(c.req);
return c.html(this.renderIndexHtml(spaceServer), 200, {
"Cache-Control": "no-cache",
});
});
this.abortController = new AbortController();
const listenOptions: any = {
2022-12-14 19:32:26 +00:00
hostname: this.hostname,
port: this.port,
signal: this.abortController.signal,
};
if (this.keyFile) {
listenOptions.key = Deno.readTextFileSync(this.keyFile);
}
if (this.certFile) {
listenOptions.cert = Deno.readTextFileSync(this.certFile);
}
2024-01-13 17:07:02 +00:00
// Start the actual server
Deno.serve(listenOptions, this.app.fetch);
2022-12-14 19:32:26 +00:00
const visibleHostname = this.hostname === "0.0.0.0"
? "localhost"
: this.hostname;
console.log(
`SilverBullet is now running: http://${visibleHostname}:${this.port}`,
);
2022-11-26 13:15:38 +00:00
}
2024-01-13 17:07:02 +00:00
serveStatic() {
this.app.use("*", async (c, next) => {
const req = c.req;
const spaceServer = await this.ensureSpaceServer(req);
const url = new URL(req.url);
// console.log("URL", url);
if (
2024-01-13 17:07:02 +00:00
url.pathname === "/"
) {
2024-01-13 17:07:02 +00:00
// Serve the UI (index.html)
// Note: we're explicitly not setting Last-Modified and If-Modified-Since header here because this page is dynamic
return c.html(this.renderIndexHtml(spaceServer), 200, {
"Cache-Control": "no-cache",
});
}
2024-01-13 17:07:02 +00:00
try {
const assetName = url.pathname.slice(1);
if (!this.clientAssetBundle.has(assetName)) {
return next();
}
if (
this.clientAssetBundle.has(assetName) &&
req.header("If-Modified-Since") ===
utcDateString(this.clientAssetBundle.getMtime(assetName)) &&
assetName !== "service_worker.js"
) {
return c.body(null, 304);
}
c.status(200);
c.header("Content-type", this.clientAssetBundle.getMimeType(assetName));
let data: Uint8Array | string = this.clientAssetBundle.readFileSync(
assetName,
);
2024-01-13 17:07:02 +00:00
c.header("Cache-Control", "no-cache");
c.header("Content-length", "" + data.length);
if (assetName !== "service_worker.js") {
c.header(
"Last-Modified",
utcDateString(this.clientAssetBundle.getMtime(assetName)),
);
}
2024-01-13 17:07:02 +00:00
if (req.method === "GET") {
if (assetName === "service_worker.js") {
const textData = new TextDecoder().decode(data);
// console.log(
// "Swapping out config hash in service worker",
// );
data = textData.replaceAll(
"{{CONFIG_HASH}}",
base64Encode(
JSON.stringify([
spaceServer.clientEncryption,
spaceServer.syncOnly,
]),
),
);
}
return c.body(data);
} // else e.g. HEAD, OPTIONS, don't send body
} catch {
return next();
}
2024-01-13 17:07:02 +00:00
});
}
2024-01-13 17:07:02 +00:00
private addAuth() {
2022-12-22 10:21:12 +00:00
const excludedPaths = [
"/manifest.json",
"/favicon.png",
"/logo.png",
"/.auth",
];
// Middleware handling the /.auth page and flow
2024-01-13 17:07:02 +00:00
this.app.all("/.auth", async (c) => {
const url = new URL(c.req.url);
const req = c.req;
const host = url.host; // e.g. localhost:3000
if (url.search === "?logout") {
deleteCookie(c, authCookieName(host));
}
if (req.method === "GET") {
return c.html(
this.clientAssetBundle.readTextFileSync(".client/auth.html"),
);
} else if (req.method === "POST") {
const values = await c.req.parseBody();
const username = values["username"];
const password = values["password"];
const spaceServer = await this.ensureSpaceServer(req);
const { user: expectedUser, pass: expectedPassword } = spaceServer
.auth!;
if (username === expectedUser && password === expectedPassword) {
// Generate a JWT and set it as a cookie
const jwt = await spaceServer.jwtIssuer.createJWT(
{ username },
authenticationExpirySeconds,
);
2024-01-13 17:07:02 +00:00
console.log("Successful auth");
setCookie(c, authCookieName(host), jwt, {
expires: new Date(
Date.now() + authenticationExpirySeconds * 1000,
), // in a week
// sameSite: "Strict",
// httpOnly: true,
});
return c.redirect("/");
} else {
2024-01-13 17:07:02 +00:00
return c.redirect("/.auth?error=1");
}
} else {
2024-01-13 17:07:02 +00:00
return c.redirect("/.auth");
}
});
// Check auth
2024-01-13 17:07:02 +00:00
this.app.use("*", async (c, next) => {
const req = c.req;
const spaceServer = await this.ensureSpaceServer(req);
if (!spaceServer.auth) {
// Auth disabled in this config, skip
return next();
}
2024-01-13 17:07:02 +00:00
const url = new URL(req.url);
const host = url.host;
if (!excludedPaths.includes(url.pathname)) {
const authCookie = getCookie(c, authCookieName(host));
2024-01-13 17:07:02 +00:00
if (!authCookie && spaceServer.authToken) {
// Attempt Bearer Authorization based authentication
2024-01-13 17:07:02 +00:00
const authHeader = req.header("Authorization");
if (authHeader && authHeader.startsWith("Bearer ")) {
const authToken = authHeader.slice("Bearer ".length);
if (authToken === spaceServer.authToken) {
// All good, let's proceed
return next();
} else {
console.log(
"Unauthorized token access, redirecting to auth page",
);
2024-01-13 17:07:02 +00:00
return c.text("Unauthorized", 401);
}
}
}
2024-01-13 17:07:02 +00:00
if (!authCookie) {
2023-12-11 12:53:08 +00:00
console.log("Unauthorized access, redirecting to auth page");
2024-01-13 17:07:02 +00:00
return c.redirect("/.auth");
2022-12-22 10:21:12 +00:00
}
const { user: expectedUser } = spaceServer.auth!;
2023-12-11 11:11:56 +00:00
try {
const verifiedJwt = await spaceServer.jwtIssuer.verifyAndDecodeJWT(
2024-01-13 17:07:02 +00:00
authCookie,
2023-12-11 11:11:56 +00:00
);
if (verifiedJwt.username !== expectedUser) {
throw new Error("Username mismatch");
}
} catch (e: any) {
console.error(
"Error verifying JWT, redirecting to auth page",
e.message,
);
2024-01-13 17:07:02 +00:00
return c.redirect("/.auth");
}
}
return next();
});
2022-10-17 18:35:38 +00:00
}
2024-01-13 17:07:02 +00:00
private addFsRoutes() {
this.app.use(
"*",
cors({
origin: "*",
allowHeaders: ["*"],
exposeHeaders: ["*"],
allowMethods: ["GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"],
}),
);
// For when the day comes...
// this.app.use("*", async (c, next) => {
// // if (["POST", "PUT", "DELETE"].includes(c.req.method)) {
// const spaceServer = await this.ensureSpaceServer(c.req);
// return runWithSystemLock(spaceServer.system!, async () => {
// await next();
// });
// // }
// });
2022-10-17 18:35:38 +00:00
// File list
2024-01-13 17:07:02 +00:00
this.app.get(
"/index.json",
2024-01-13 17:07:02 +00:00
async (c) => {
const req = c.req;
const spaceServer = await this.ensureSpaceServer(req);
if (req.header("X-Sync-Mode")) {
// Only handle direct requests for a JSON representation of the file list
const files = await spaceServer.spacePrimitives.fetchFileList();
2024-01-13 17:07:02 +00:00
return c.json(files, 200, {
"X-Space-Path": spaceServer.pagesPath,
});
} else {
// Otherwise, redirect to the UI
// The reason to do this is to handle authentication systems like Authelia nicely
2024-01-13 17:07:02 +00:00
return c.redirect("/");
}
},
);
2022-10-17 18:35:38 +00:00
2024-01-13 17:07:02 +00:00
// RPC shell
this.app.post("/.rpc/shell", async (c) => {
const req = c.req;
const spaceServer = await this.ensureSpaceServer(req);
const body = await req.json();
try {
2024-01-13 17:07:02 +00:00
const shellCommand: ShellRequest = body;
const shellResponse = await spaceServer.shellBackend.handle(
shellCommand,
);
return c.json(shellResponse);
} catch (e: any) {
console.log("Shell error", e);
return c.text(e.message, 500);
}
});
// RPC syscall
this.app.post("/.rpc/:plugName/:syscall", async (c) => {
2024-01-13 17:07:02 +00:00
const req = c.req;
const syscall = req.param("syscall")!;
const plugName = req.param("plugName")!;
2024-01-13 17:07:02 +00:00
const spaceServer = await this.ensureSpaceServer(req);
const body = await req.json();
try {
if (spaceServer.syncOnly) {
return c.text("Sync only mode, no syscalls allowed", 400);
}
const args: string[] = body;
try {
const result = await spaceServer.system!.syscall(
{ plug: plugName },
syscall,
args,
);
2024-01-13 17:07:02 +00:00
return c.json({
result: result,
});
} catch (e: any) {
return c.json({
error: e.message,
}, 500);
}
} catch (e: any) {
console.log("Error", e);
2024-01-13 17:07:02 +00:00
return c.text(e.message, 500);
}
});
2024-01-13 17:07:02 +00:00
const filePathRegex = "/:path{[^!].+\\.[a-zA-Z]+}";
this.app.get(
filePathRegex,
async (c) => {
const req = c.req;
const name = req.param("path")!;
const spaceServer = await this.ensureSpaceServer(req);
console.log(
"Requested file",
name,
);
if (
name.endsWith(".md") &&
// This header signififies the requests comes directly from the http_space_primitives client (not the browser)
!req.header("X-Sync-Mode") &&
// This Accept header is used by federation to still work with CORS
req.header("Accept") !==
"application/octet-stream" &&
req.header("sec-fetch-mode") !== "cors"
) {
// It can happen that during a sync, authentication expires, this may result in a redirect to the login page and then back to this particular file. This particular file may be an .md file, which isn't great to show so we're redirecting to the associated SB UI page.
console.warn(
"Request was without X-Sync-Mode nor a CORS request, redirecting to page",
2023-12-22 10:45:32 +00:00
);
2024-01-13 17:07:02 +00:00
return c.redirect(`/${name.slice(0, -3)}`);
}
if (name.startsWith(".")) {
// Don't expose hidden files
return c.notFound();
}
// Handle federated links through a simple redirect, only used for attachments loads with service workers disabled
if (name.startsWith("!")) {
let url = name.slice(1);
console.log("Handling this as a federated link", url);
if (url.startsWith("localhost")) {
url = `http://${url}`;
} else {
url = `https://${url}`;
2023-07-29 15:06:32 +00:00
}
try {
2024-01-13 17:07:02 +00:00
const req = await fetch(url);
// Override X-Permssion header to always be "ro"
const newHeaders = new Headers();
for (const [key, value] of req.headers.entries()) {
newHeaders.set(key, value);
}
2024-01-13 17:07:02 +00:00
newHeaders.set("X-Permission", "ro");
return new Response(req.body, {
status: req.status,
headers: newHeaders,
});
2023-08-08 13:00:18 +00:00
} catch (e: any) {
2024-01-13 17:07:02 +00:00
console.error("Error fetching federated link", e);
return c.text(e.message, 500);
}
2024-01-13 17:07:02 +00:00
}
try {
if (req.header("X-Get-Meta")) {
// Getting meta via GET request
const fileData = await spaceServer.spacePrimitives.getFileMeta(
name,
);
2024-01-13 17:07:02 +00:00
return c.text("", 200, this.fileMetaToHeaders(fileData));
}
const fileData = await spaceServer.spacePrimitives.readFile(name);
const lastModifiedHeader = new Date(fileData.meta.lastModified)
.toUTCString();
if (
req.header("If-Modified-Since") === lastModifiedHeader
) {
return c.body(null, 304);
}
2024-01-13 17:07:02 +00:00
return c.body(fileData.data, 200, {
...this.fileMetaToHeaders(fileData.meta),
"Last-Modified": lastModifiedHeader,
});
} catch (e: any) {
console.error("Error GETting file", name, e.message);
return c.notFound();
}
},
).put(
async (c) => {
const req = c.req;
const name = req.param("path")!;
const spaceServer = await this.ensureSpaceServer(req);
console.log("Saving file", name);
if (name.startsWith(".")) {
// Don't expose hidden files
2024-01-13 17:07:02 +00:00
return c.text("Forbidden", 403);
}
2024-01-13 17:07:02 +00:00
const body = await req.arrayBuffer();
2022-10-17 18:35:38 +00:00
try {
2024-01-13 17:07:02 +00:00
const meta = await spaceServer.spacePrimitives.writeFile(
name,
new Uint8Array(body),
);
return c.text("OK", 200, this.fileMetaToHeaders(meta));
} catch (err) {
console.error("Write failed", err);
return c.text("Write failed", 500);
2022-10-17 18:35:38 +00:00
}
2024-01-13 17:07:02 +00:00
},
).delete(async (c) => {
const req = c.req;
const name = req.param("path")!;
const spaceServer = await this.ensureSpaceServer(req);
console.log("Deleting file", name);
if (name.startsWith(".")) {
// Don't expose hidden files
return c.text("Forbidden", 403);
}
try {
await spaceServer.spacePrimitives.deleteFile(name);
return c.text("OK");
} catch (e: any) {
console.error("Error deleting attachment", e);
return c.text(e.message, 500);
}
}).options();
2023-11-16 12:55:02 +00:00
// Federation proxy
2024-01-13 17:07:02 +00:00
const proxyPathRegex = "/:uri{!.+}";
this.app.all(
2023-11-16 12:55:02 +00:00
proxyPathRegex,
2024-01-13 17:07:02 +00:00
async (c, next) => {
const req = c.req;
let url = req.param("uri")!.slice(1);
if (!req.header("X-Proxy-Request")) {
2023-11-16 12:55:02 +00:00
// Direct browser request, not explicity fetch proxy request
if (!/\.[a-zA-Z0-9]+$/.test(url)) {
console.log("Directly loading federation page via URL:", url);
// This is not a direct file reference so LIKELY a page request, fall through and load the SB UI
return next();
2023-08-23 18:00:40 +00:00
}
}
2023-11-16 12:55:02 +00:00
if (url.startsWith("localhost")) {
url = `http://${url}`;
} else {
url = `https://${url}`;
}
try {
const safeRequestHeaders = new Headers();
for (
const headerName of ["Authorization", "Accept", "Content-Type"]
) {
2024-01-13 17:07:02 +00:00
if (req.header(headerName)) {
2023-11-16 12:55:02 +00:00
safeRequestHeaders.set(
headerName,
2024-01-13 17:07:02 +00:00
req.header(headerName)!,
2023-11-16 12:55:02 +00:00
);
}
}
2024-01-13 17:07:02 +00:00
const body = await req.arrayBuffer();
const fetchReq = await fetch(url, {
method: req.method,
2023-11-16 12:55:02 +00:00
headers: safeRequestHeaders,
2024-01-13 17:07:02 +00:00
body: body.byteLength > 0 ? body : undefined,
2023-11-16 12:55:02 +00:00
});
2024-01-13 17:07:02 +00:00
const responseHeaders: Record<string, any> = {};
for (const [key, value] of fetchReq.headers.entries()) {
responseHeaders[key] = value;
}
return c.body(fetchReq.body, fetchReq.status, responseHeaders);
2023-11-16 12:55:02 +00:00
} catch (e: any) {
console.error("Error fetching federated link", e);
2024-01-13 17:07:02 +00:00
return c.text(e.message, 500);
2023-11-16 12:55:02 +00:00
}
},
);
}
2024-01-13 17:07:02 +00:00
private fileMetaToHeaders(fileMeta: FileMeta) {
return {
"Content-Type": fileMeta.contentType,
"X-Last-Modified": "" + fileMeta.lastModified,
"X-Created": "" + fileMeta.created,
"Cache-Control": "no-cache",
"X-Permission": fileMeta.perm,
"X-Content-Length": "" + fileMeta.size,
};
}
stop() {
if (this.abortController) {
this.abortController.abort();
console.log("stopped server");
}
}
}
function utcDateString(mtime: number): string {
return new Date(mtime).toUTCString();
}
2023-08-17 10:43:08 +00:00
function authCookieName(host: string) {
2024-01-13 17:07:02 +00:00
return `auth_${host.replaceAll(/\W/g, "_")}`;
2023-08-17 10:43:08 +00:00
}