Adding support for hosting with URL prefix (#1357)

* Adding support for hosting with URL prefix to make reverse-proxy setup on sub-path possible

* Adjusting recent changes to auth.html (changing to relative URLs)  after rebasing from upstream

* Adjusting service_worker and application manifest to support URL-prefix

* Add notes on Space Lua Pattern Matching (#1366)

* Remove common/space_lua/stdlib/math.md (#1371)

* Escape pipe symbol in string.gsub (#1370)

* feat: configure vim in CONFIG (#1369)

* Fix week calculation (#1368)

* Add more tests for week calculation

* Fix week calculation

* Add more tests

* Implement Lua built-in function os.difftime (#1367)

* Implement Lua built-in function os.difftime

* Test os.difftime

---------

Co-authored-by: Zef Hemel <zef@zef.me>

* Fix index page naming during server initialization (#1365)

* Allow non-zero shell exit codes (#1377)

* Generate version from git describe at build time (#1374)

* Generate version from git describe at build time

* Add 2.0-beta prefix

* Use Deno.Command instead of Deno.run

* Add missing case to math.random and check arguments (#1372)

* Fix paragraphs for the tag page (#1376)

* Render a predefined string for empty markdown table instead of pipe characters (#1387)

* Fix string.find (#1390)

* Fetch tags and history for proper version string generation (#1388)

* Fix support for disabling shortcuts (#1393)

* Add GitHub Actions Cache to reduce build times (#1394)

* Order strings in queries using collation algorithm (#1391)

Configurable with queryCollation, default value maintains old behaviour.
Added tests, schema, example settings, and documentation to query page.

Close: #614
Close: #1316

* Utility function to handle empty query results and templates (#1386)

* Add global Lua function 'some'

Moved documentation for 'each' function to non-standard section.

* Revert "Add optional argument to template.each for empty collection output (#1359)"

This reverts commit b73dadec67.

* Reimplement #1359 using 'some' function

* Update Lua to event.listEvents to match plugos syscall (#1397)

The documentation, example, and other function names use
`event.listEvents`, but `event.list` is being registered with the
client.

* Update widget header to not overflow container (#1410)

Also add a 10px margin below the header to maintain consistent spacing
around the widget contents.

* fix: case insensitive admonitions by default (#1409)

* fix: closing bracket is missing (#1408)

* Add optional priority attribute to PageCreatingContent (#1392)

* Add optional priority attribute to PageCreatingContent

* Minor simplification

* Fix comments

* Revert changes

* Add pageEventHandlers

* Use UTC year, month, and date for strings lacking time components (#1403)

* feat: allow CONFIG.md in any directory (#1398)

* fix: bundle external dependencies (#1379)

* Deno bump

* Copy-edit splash screen text (#1413)

* Fixes #1401 by implementing Lua's select

* Fixes offline capability of PWA (I hope).

Now storing config in localStorage.

* fix lint

* Reduce blast radius of Lua errors

* Fixes #1411: adds 'priority' setting for space style

* Refactor: Merging common/ into web/

* Fixes #1400

* Improves #1312 by rendering Lua expressions (but not widgets)

* Fix minor typos, add configuration to the docs

---------

Co-authored-by: wbhouston <wmbhouston@gmail.com>
Co-authored-by: Lennart Ochel <lennart.ochel@outlook.com>
Co-authored-by: Matthias Benaets <89214559+MatthiasBenaets@users.noreply.github.com>
Co-authored-by: Zef Hemel <zef@zef.me>
Co-authored-by: Marek S. Łukasiewicz <marek@lukasiewicz.tech>
Co-authored-by: Ivan Alejandro <ivanalejandro0@gmail.com>
Co-authored-by: Albert-Jan de Vries <aj+github@albert-jandevries.nl>
Co-authored-by: Cole Stowell <121599022+costowell@users.noreply.github.com>
Co-authored-by: Jim Tittsler <jimt@onjapan.net>
This commit is contained in:
flowkclav
2025-06-04 15:15:14 +02:00
committed by GitHub
co-authored by wbhouston Lennart Ochel Matthias Benaets Zef Hemel Marek S. Łukasiewicz Ivan Alejandro Albert-Jan de Vries Cole Stowell Jim Tittsler
parent e217f64d36
commit 766fb96ff2
19 changed files with 392 additions and 60 deletions
+25 -1
View File
@@ -62,6 +62,22 @@ export async function serveCommand(
);
}
let hostUrlPrefix = Deno.env.get("SB_URL_PREFIX");
if (hostUrlPrefix) {
if (!hostUrlPrefix.startsWith("/")) {
hostUrlPrefix = "/" + hostUrlPrefix;
}
if (hostUrlPrefix.endsWith("/")) {
hostUrlPrefix = hostUrlPrefix.replace(/\/*$/, "");
}
if (hostUrlPrefix !== "") {
console.log(`Host URL Prefix: ${hostUrlPrefix}`);
} else {
hostUrlPrefix = undefined;
}
}
const userAuth = options.user ?? Deno.env.get("SB_USER");
let userCredentials: AuthOptions | undefined;
@@ -100,7 +116,7 @@ export async function serveCommand(
const manifestName = Deno.env.get("SB_NAME");
const manifestDescription = Deno.env.get("SB_DESCRIPTION");
if (manifestName || manifestDescription) {
if (manifestName || manifestDescription || hostUrlPrefix) {
const manifestData = JSON.parse(
clientAssets.readTextFileSync(".client/manifest.json"),
);
@@ -110,6 +126,13 @@ export async function serveCommand(
if (manifestDescription) {
manifestData.description = manifestDescription;
}
if (hostUrlPrefix) {
for (const icon of manifestData.icons) {
if (icon.src) icon.src = hostUrlPrefix + icon.src;
}
manifestData.start_url = hostUrlPrefix + manifestData.start_url;
manifestData.scope = hostUrlPrefix + manifestData.scope;
}
clientAssets.writeTextFileSync(
".client/manifest.json",
"application/json",
@@ -131,6 +154,7 @@ export async function serveCommand(
shellBackend: backendConfig,
enableSpaceScript,
pagesPath: folder,
hostUrlPrefix,
});
await httpServer.start();
+204
View File
@@ -0,0 +1,204 @@
import { assertEquals } from "@std/assert";
import { applyUrlPrefix, removeUrlPrefix } from "$lib/url_prefix.ts";
Deno.test("url_prefix - removeUrlPrefix - with value", async (t) => {
await t.step("Absolute URL, present, should be removed", () => {
assertEquals(
removeUrlPrefix("http://myserver/sb/relevant", "/sb"),
"http://myserver/relevant",
);
assertEquals(
removeUrlPrefix("https://myserver/sb/relevant", "/sb"),
"https://myserver/relevant",
);
});
await t.step("Absolute URL, present, should only remove leading", () => {
assertEquals(
removeUrlPrefix("http://myserver/sb/sb/relevant/sb", "/sb"),
"http://myserver/sb/relevant/sb",
);
assertEquals(
removeUrlPrefix("http://myserver/relevant/sb", "/sb"),
"http://myserver/relevant/sb",
);
});
await t.step("Absolute URL, absent, should be untouched", () => {
assertEquals(
removeUrlPrefix("http://myserver/other/relevant", "/sb"),
"http://myserver/other/relevant",
);
assertEquals(
removeUrlPrefix("https://myserver/other/relevant", "/sb"),
"https://myserver/other/relevant",
);
});
await t.step("Absolute URL, queryString, should be preserved", () => {
assertEquals(
removeUrlPrefix("http://myserver/sb/sb/relevant/sb?param=arg", "/sb"),
"http://myserver/sb/relevant/sb?param=arg",
);
});
await t.step("Absolute URL, unsupported, should be untouched", () => {
assertEquals(
removeUrlPrefix("ftp://myserver/sb/relevant", "/sb"),
"ftp://myserver/sb/relevant",
);
});
await t.step("Host-Relative URL, present, should be removed", () => {
assertEquals(removeUrlPrefix("/sb/relevant", "/sb"), "/relevant");
});
await t.step("Host-Relative URL, present, should only remove leading", () => {
assertEquals(
removeUrlPrefix("/sb/sb/relevant/sb", "/sb"),
"/sb/relevant/sb",
);
assertEquals(removeUrlPrefix("/relevant/sb", "/sb"), "/relevant/sb");
});
await t.step("Host-Relative URL, queryString, should be preserved", () => {
assertEquals(
removeUrlPrefix("/sb/sb/relevant/sb?param=arg", "/sb"),
"/sb/relevant/sb?param=arg",
);
assertEquals(
removeUrlPrefix("/relevant/sb?param=arg", "/sb"),
"/relevant/sb?param=arg",
);
});
await t.step("Host-Relative URL, absent, should be untouched", () => {
assertEquals(removeUrlPrefix("/other/relevant", "/sb"), "/other/relevant");
});
await t.step("Page-Relative URL, should be untouched", () => {
assertEquals(removeUrlPrefix("sb/relevant", "/sb"), "sb/relevant");
});
});
Deno.test("url_prefix - removeUrlPrefix - no value", async (t) => {
await t.step("Absolute URL, should be untouched", () => {
assertEquals(
removeUrlPrefix("http://myserver/sb/relevant", ""),
"http://myserver/sb/relevant",
);
assertEquals(
removeUrlPrefix("https://myserver/sb/relevant"),
"https://myserver/sb/relevant",
);
});
await t.step("Host-Relative URL, should be untouched", () => {
assertEquals(removeUrlPrefix("/sb/relevant", ""), "/sb/relevant");
assertEquals(removeUrlPrefix("/sb/relevant"), "/sb/relevant");
});
await t.step("Page-Relative URL, should be untouched", () => {
assertEquals(removeUrlPrefix("sb/relevant", ""), "sb/relevant");
assertEquals(removeUrlPrefix("sb/relevant"), "sb/relevant");
});
});
Deno.test("url_prefix - applyUrlPrefix - with value", async (t) => {
await t.step("string, Absolute URL, should be prefixed", () => {
assertEquals(
applyUrlPrefix("http://myserver/relevant", "/sb"),
"http://myserver/sb/relevant",
);
assertEquals(
applyUrlPrefix("https://myserver/relevant", "/sb"),
"https://myserver/sb/relevant",
);
});
await t.step("string, Absolute URL, should not care about dups", () => {
assertEquals(
applyUrlPrefix("http://myserver/sb/relevant/sb", "/sb"),
"http://myserver/sb/sb/relevant/sb",
);
});
await t.step("string, Absolute URL, queryString should be preserved", () => {
assertEquals(
applyUrlPrefix("http://myserver/sb/relevant/sb?param=arg", "/sb"),
"http://myserver/sb/sb/relevant/sb?param=arg",
);
});
await t.step("string, Absolute URL, unsupported, should be untouched", () => {
assertEquals(
applyUrlPrefix("ftp://myserver/relevant", "/sb"),
"ftp://myserver/relevant",
);
});
await t.step("string, Host-Relative URL, should be prefixed", () => {
assertEquals(applyUrlPrefix("/relevant", "/sb"), "/sb/relevant");
});
await t.step("string, Host-Relative URL, should not care about dups", () => {
assertEquals(
applyUrlPrefix("/sb/relevant/sb", "/sb"),
"/sb/sb/relevant/sb",
);
});
await t.step(
"string, Host-Relative URL, queryString should be preserved",
() => {
assertEquals(
applyUrlPrefix("/sb/relevant/sb?param=arg", "/sb"),
"/sb/sb/relevant/sb?param=arg",
);
},
);
await t.step("string, Page-Relative URL, should be untouched", () => {
assertEquals(applyUrlPrefix("relevant", "/sb"), "relevant");
});
await t.step("URL object, Absolute URL, should be prefixed", () => {
assertEquals(
applyUrlPrefix(new URL("http://myserver/relevant"), "/sb"),
new URL("http://myserver/sb/relevant"),
);
});
await t.step(
"URL object, Absolute URL, queryString should be preserved",
() => {
assertEquals(
applyUrlPrefix(new URL("http://myserver/relevant?param=arg"), "/sb"),
new URL("http://myserver/sb/relevant?param=arg"),
);
},
);
});
Deno.test("url_prefix - applyUrlPrefix - no value", async (t) => {
await t.step("Absolute URL, should be untouched", () => {
assertEquals(
applyUrlPrefix("http://myserver/relevant", ""),
"http://myserver/relevant",
);
assertEquals(
applyUrlPrefix("https://myserver/relevant"),
"https://myserver/relevant",
);
});
await t.step("Host-Relative URL, should be untouched", () => {
assertEquals(applyUrlPrefix("/relevant", ""), "/relevant");
assertEquals(applyUrlPrefix("/relevant"), "/relevant");
});
await t.step("Page-Relative URL, should be untouched", () => {
assertEquals(applyUrlPrefix("relevant", ""), "relevant");
assertEquals(applyUrlPrefix("relevant"), "relevant");
});
});
+44
View File
@@ -0,0 +1,44 @@
export function removeUrlPrefix(url: string, prefix?: string): string {
if (!prefix || prefix === "") return url;
if (url.startsWith("http://") || url.startsWith("https://")) {
const parsedUrl = new URL(url);
if (parsedUrl.pathname.startsWith(prefix)) {
parsedUrl.pathname = parsedUrl.pathname.substring(
prefix.length,
);
return parsedUrl.href;
} else {
return url;
}
} else if (url.startsWith(prefix)) {
return url.substring(prefix.length);
} else {
return url;
}
}
export function applyUrlPrefix<T extends (string | URL)>(
url: T,
prefix?: string,
): T {
if (!prefix || prefix === "") return url;
if (typeof url === "string") {
const urlString = url as string;
if (urlString.startsWith("http://") || urlString.startsWith("https://")) {
return applyUrlPrefix(new URL(urlString), prefix).href as T;
} else if (urlString.startsWith("/")) {
return (prefix + urlString) as T;
} else {
return url; //return page-relative paths as-is
}
} else if (url.protocol === "http:" || url.protocol === "https:") {
const urlObj = new URL(url);
urlObj.pathname = prefix + urlObj.pathname;
return urlObj as T;
} else {
return url;
}
}
+1 -2
View File
@@ -3,7 +3,6 @@ import {
clientStore,
editor,
markdown,
system,
} from "@silverbulletmd/silverbullet/syscalls";
import { renderMarkdownToHtml } from "./markdown_render.ts";
import {
@@ -38,7 +37,7 @@ export async function updateMarkdownPreview() {
"rhs",
2,
`
<link rel="stylesheet" href="/.client/main.css" />
<link rel="stylesheet" href=".client/main.css" />
<style>
${css}
${customStyles ?? ""}
+53 -22
View File
@@ -20,6 +20,7 @@ import { LockoutTimer } from "./lockout.ts";
import type { AuthOptions } from "../cmd/server.ts";
import type { ClientConfig } from "../web/client.ts";
import { htmlEscape } from "../plugs/markdown/html_render.ts";
import { applyUrlPrefix, removeUrlPrefix } from "$lib/url_prefix.ts";
const authenticationExpirySeconds = 60 * 60 * 24 * 7; // 1 week
@@ -39,6 +40,7 @@ export type ServerOptions = {
readOnly: boolean;
indexPage: string;
enableSpaceScript: boolean;
hostUrlPrefix: string | undefined;
};
export class HttpServer {
@@ -56,7 +58,7 @@ export class HttpServer {
baseKvPrimitives: KvPrimitives;
constructor(private options: ServerOptions) {
this.app = new Hono();
this.app = new Hono().basePath(options.hostUrlPrefix ?? "");
this.clientAssetBundle = options.clientAssetBundle;
this.plugAssetBundle = options.plugAssetBundle;
this.hostname = options.hostname;
@@ -111,6 +113,7 @@ export class HttpServer {
TITLE: pageName,
DESCRIPTION: stripHtml(html).substring(0, 255),
CONTENT: html,
HOST_URL_PREFIX: this.options.hostUrlPrefix ?? "",
};
html = this.clientAssetBundle.readTextFileSync(".client/index.html");
@@ -148,7 +151,7 @@ export class HttpServer {
// Fallback, serve the UI index.html
this.app.use("*", (c) => {
const url = new URL(c.req.url);
const url = new URL(this.unprefixedUrl(c.req.url));
const pageName = decodePageURI(url.pathname.slice(1));
return this.renderHtmlPage(this.spaceServer, pageName, c);
});
@@ -180,7 +183,7 @@ export class HttpServer {
serveStatic() {
this.app.use("*", (c, next): Promise<void | Response> => {
const req = c.req;
const url = new URL(req.url);
const url = new URL(this.unprefixedUrl(req.url));
// console.log("URL", url);
if (
url.pathname === "/"
@@ -240,16 +243,21 @@ export class HttpServer {
: new LockoutTimer(0, 0); // disabled
this.app.get("/.logout", (c) => {
const url = new URL(c.req.url);
deleteCookie(c, authCookieName(url.host));
deleteCookie(c, "refreshLogin");
const url = new URL(this.unprefixedUrl(c.req.url));
deleteCookie(c, authCookieName(url.host), {
path: `${this.options.hostUrlPrefix ?? ""}/`,
});
deleteCookie(c, "refreshLogin", {
path: `${this.options.hostUrlPrefix ?? ""}/`,
});
return c.redirect("/.auth");
return c.redirect(this.prefixedUrl("/.auth"));
});
// Authentication endpoints
this.app.get("/.auth", (c) => {
const html = this.clientAssetBundle.readTextFileSync(".client/auth.html");
const html = this.clientAssetBundle.readTextFileSync(".client/auth.html")
.replaceAll("{{HOST_URL_PREFIX}}", this.options.hostUrlPrefix ?? "");
return c.html(html);
}).post(
@@ -263,14 +271,14 @@ export class HttpServer {
!password || typeof password !== "string" ||
(rememberMe && typeof rememberMe !== "string")
) {
return c.redirect("/.auth?error=0");
return c.redirect(this.prefixedUrl("/.auth?error=0"));
}
return { username, password, rememberMe };
}),
async (c) => {
const req = c.req;
const url = new URL(req.url);
const url = new URL(this.unprefixedUrl(req.url));
const { username, password, rememberMe } = req.valid("form");
const {
@@ -280,7 +288,7 @@ export class HttpServer {
if (lockoutTimer.isLocked()) {
console.error("Authentication locked out, redirecting to auth page.");
return c.redirect("/.auth?error=2");
return c.redirect(this.prefixedUrl("/.auth?error=2"));
}
if (username === expectedUser && password === expectedPassword) {
@@ -296,24 +304,30 @@ export class HttpServer {
Date.now() + authenticationExpirySeconds * 1000,
);
setCookie(c, authCookieName(url.host), jwt, {
path: `${this.options.hostUrlPrefix ?? ""}/`,
expires: inAWeek,
// sameSite: "Strict",
// httpOnly: true,
});
if (rememberMe) {
setCookie(c, "refreshLogin", "true", { expires: inAWeek });
setCookie(c, "refreshLogin", "true", {
path: `${this.options.hostUrlPrefix ?? ""}/`,
expires: inAWeek,
});
}
const values = await req.parseBody();
const from = values["from"];
return c.redirect(typeof from === "string" ? from : "/");
return c.redirect(
this.prefixedUrl(typeof from === "string" ? from : "/"),
);
} else {
console.error("Authentication failed, redirecting to auth page.");
lockoutTimer.addCount();
return c.redirect("/.auth?error=1");
return c.redirect(this.prefixedUrl("/.auth?error=1"));
}
},
).all((c) => {
return c.redirect("/.auth");
return c.redirect(this.prefixedUrl("/.auth"));
});
// Check auth
@@ -323,14 +337,18 @@ export class HttpServer {
// Auth disabled in this config, skip
return next();
}
const url = new URL(req.url);
const url = new URL(this.unprefixedUrl(req.url));
const path = this.unprefixedUrl(req.path);
const host = url.host;
const redirectToAuth = () => {
// Try filtering api paths
if (req.path.startsWith("/.") || req.path.endsWith(".md")) {
return c.redirect("/.auth", 401 as any);
if (path.startsWith("/.") || path.endsWith(".md")) {
return c.redirect(this.prefixedUrl("/.auth"), 401 as any);
} else {
return c.redirect(`/.auth?from=${req.path}`, 401 as any);
return c.redirect(
this.prefixedUrl(`/.auth?from=${path}`),
302 as any,
);
}
};
if (!excludedPaths.includes(url.pathname)) {
@@ -414,6 +432,7 @@ export class HttpServer {
c,
this.spaceServer.pagesPath,
this.spaceServer.readOnly,
this.options.hostUrlPrefix,
);
});
@@ -484,11 +503,15 @@ export class HttpServer {
const jwt = getCookie(c, authCookieName(host));
if (jwt) {
setCookie(c, authCookieName(host), jwt, {
path: `${this.options.hostUrlPrefix ?? ""}/`,
expires: inAWeek,
// sameSite: "Strict",
// httpOnly: true,
});
setCookie(c, "refreshLogin", "true", { expires: inAWeek });
setCookie(c, "refreshLogin", "true", {
path: `${this.options.hostUrlPrefix ?? ""}/`,
expires: inAWeek,
});
}
}
}
@@ -506,7 +529,7 @@ export class HttpServer {
} else {
// Otherwise, redirect to the UI
// The reason to do this is to handle authentication systems like Authelia nicely
return c.redirect("/");
return c.redirect(this.prefixedUrl("/"));
}
});
@@ -528,7 +551,7 @@ export class HttpServer {
console.warn(
"Request was without X-Sync-Mode nor a CORS request, redirecting to page",
);
return c.redirect(`/${name.slice(0, -mdExt.length)}`);
return c.redirect(this.prefixedUrl(`/${name.slice(0, -mdExt.length)}`));
}
// This is a good guess that the request comes directly from a user
if (
@@ -625,6 +648,14 @@ export class HttpServer {
};
}
private prefixedUrl(url: string): string {
return applyUrlPrefix(url, this.options.hostUrlPrefix);
}
private unprefixedUrl(url: string): string {
return removeUrlPrefix(url, this.options.hostUrlPrefix);
}
stop() {
if (this.abortController) {
this.abortController.abort();
+1
View File
@@ -93,6 +93,7 @@ async function setupTestServer(
readOnly: false,
indexPage: "index",
enableSpaceScript: false,
hostUrlPrefix: undefined,
};
// Create and start the server
+3 -1
View File
@@ -2,6 +2,7 @@ import type { Context } from "hono";
import type { ShellRequest } from "@silverbulletmd/silverbullet/type/rpc";
import type { ShellBackend } from "./shell_backend.ts";
import { StreamingShell } from "./shell_backend.ts";
import { removeUrlPrefix } from "$lib/url_prefix.ts";
/**
* Handles the /.shell endpoint for non-streaming shell commands
@@ -34,9 +35,10 @@ export function handleShellStreamEndpoint(
c: Context,
cwd: string,
readOnly: boolean,
hostUrlPrefix?: string,
): Response {
const req = c.req;
const url = new URL(req.url);
const url = new URL(removeUrlPrefix(req.url, hostUrlPrefix));
// Check if read-only mode is enabled
if (readOnly) {
+6 -5
View File
@@ -4,7 +4,8 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<link rel="icon" type="image/x-icon" href="/favicon.png" />
<base href="{{HOST_URL_PREFIX}}/" />
<link rel="icon" type="image/x-icon" href="favicon.png" />
<title>Login to SilverBullet</title>
<style>
*,
@@ -139,10 +140,10 @@
<div class="center">
<div class="flow floating-island">
<h1>
Login to <img src="/.client/logo.png" style="height: 1ch" />
Login to <img src=".client/logo.png" style="height: 1ch" />
SilverBullet
</h1>
<form action="/.auth" method="POST" id="login" class="flow">
<form action=".auth" method="POST" id="login" class="flow">
<div class="error-message"></div>
<div>
<label for="username">
@@ -197,7 +198,7 @@
}
// Fetch the app name from the manifest file
fetch('/.client/manifest.json')
fetch('.client/manifest.json')
.then(response => {
if (!response.ok) {
throw new Error('Failed to load manifest');
@@ -211,7 +212,7 @@
// Update the header text
const header = document.querySelector('h1');
if (header) {
header.innerHTML = `Login to <img src="/.client/logo.png" style="height: 1ch" /> ${appName}`;
header.innerHTML = `Login to <img src=".client/logo.png" style="height: 1ch" /> ${appName}`;
}
})
.catch(error => {
+2 -2
View File
@@ -7,7 +7,7 @@ safeRun(async () => {
// First we attempt to fetch the config from the server
let clientConfig: ClientConfig | undefined;
try {
const configResponse = await fetch("/.config", {
const configResponse = await fetch(".config", {
// We don't want to follow redirects, we want to get the redirect header in case of auth issues
redirect: "manual",
// Add short timeout in case of a bad internet connection, this would block loading of the UI
@@ -51,7 +51,7 @@ safeRun(async () => {
if (navigator.serviceWorker) {
// Register service worker
navigator.serviceWorker
.register(new URL("/service_worker.js", location.href), {
.register(new URL("service_worker.js", document.baseURI), {
type: "module",
})
.then((registration) => {
+3 -3
View File
@@ -472,7 +472,7 @@ export class Client {
initSpace(): SpacePrimitives {
this.httpSpacePrimitives = new HttpSpacePrimitives(
location.origin,
document.baseURI.replace(/\/*$/, ""),
this.clientConfig.spaceFolderPath,
);
@@ -1079,10 +1079,10 @@ export class Client {
if (newWindow) {
console.log(
"Navigating to new page in new window",
`${location.origin}/${encodePageURI(encodeRef(ref))}`,
`${document.baseURI}${encodePageURI(encodeRef(ref))}`,
);
const win = globalThis.open(
`${location.origin}/${encodePageURI(encodeRef(ref))}`,
`${document.baseURI}${encodePageURI(encodeRef(ref))}`,
"_blank",
);
if (win) {
+7 -2
View File
@@ -143,7 +143,7 @@ export class ClientSystem {
this.system.unload(path);
await this.system.load(
plugName,
createSandbox(new URL(`/${path}`, location.href)),
createSandbox(new URL(`${path}`, document.baseURI)),
newHash,
);
}
@@ -274,7 +274,12 @@ export class ClientSystem {
const plugName = plugNameExtractRegex.exec(plugMeta.name)![1];
await this.system.load(
plugName,
createSandbox(new URL(plugMeta.name, location.origin)),
createSandbox(
new URL(
plugMeta.name,
document.baseURI, // We're NOT striping trailing '/', this used to be `location.origin`
),
),
plugMeta.lastModified,
);
} catch (e: any) {
+1 -1
View File
@@ -97,7 +97,7 @@ export function cleanWikiLinkPlugin(client: Client) {
title: fileExists
? `Navigate to ${encodeRef(pageRef)}`
: `Create ${pageRef.page}`,
href: `/${encodePageURI(encodeRef(pageRef))}`,
href: `${encodePageURI(encodeRef(pageRef))}`,
cssClass,
from,
callback: (e) => {
+7 -7
View File
@@ -6,8 +6,8 @@
name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"
/>
<base href="/" />
<link rel="apple-touch-icon" href="/.client/logo.png" />
<base href="{{HOST_URL_PREFIX}}/" />
<link rel="apple-touch-icon" href=".client/logo.png" />
<meta
name="theme-color"
content="#e1e1e1"
@@ -21,7 +21,7 @@
<meta name="referrer" content="no-referrer" />
<title>{{TITLE}}</title>
<meta property="og:image" content="/.client/logo.png" />
<meta property="og:image" content=".client/logo.png" />
<meta property="og:description" content="{{DESCRIPTION}}" />
<script>
@@ -50,11 +50,11 @@
},
};
</script>
<link rel="stylesheet" href="/.client/main.css" />
<link rel="stylesheet" href=".client/main.css" />
<style id="custom-styles"></style>
<script type="module" src="/.client/client.js"></script>
<link rel="manifest" href="/.client/manifest.json" crossorigin="use-credentials"/>
<link rel="icon" type="image/x-icon" href="/.client/favicon.png" />
<script type="module" src=".client/client.js"></script>
<link rel="manifest" href=".client/manifest.json" crossorigin="use-credentials"/>
<link rel="icon" type="image/x-icon" href=".client/favicon.png" />
</head>
<body>
+4 -4
View File
@@ -57,18 +57,18 @@ export class PathPageNavigator {
globalThis.history.replaceState(
cleanState,
"",
`/${encodePageURI(currentState.page)}`,
`${document.baseURI}${encodePageURI(currentState.page)}`,
);
globalThis.history.pushState(
ref,
"",
`/${encodePageURI(ref.page)}`,
`${document.baseURI}${encodePageURI(ref.page)}`,
);
} else {
globalThis.history.replaceState(
ref,
"",
`/${encodePageURI(ref.page)}`,
`${document.baseURI}${encodePageURI(ref.page)}`,
);
}
@@ -157,7 +157,7 @@ export class PathPageNavigator {
export function parseRefFromURI(): Ref {
const locationRef = parseRef(decodeURIComponent(
location.pathname.substring(1),
location.href.substring(document.baseURI.length), //this essentially returns location with prefix and leading slash removed (equivalent to location.pathname.substring(prefix.length).substring(1)),
));
if (location.hash && locationRef.kind === "page") {
+23 -4
View File
@@ -9,6 +9,23 @@ import {
const CACHE_NAME = "{{CACHE_NAME}}";
//`location.href` minus this worker's filename will be our base URL, including any URL prefix
//(-1 is to remove the trailing '/')
const workerFilename = location.pathname.substring(
location.pathname.lastIndexOf("/") + 1,
);
const baseURI = location.href.substring(
0,
location.href.length - workerFilename.length - 1,
);
const basePathName = location.pathname.substring(
0,
location.pathname.length - workerFilename.length - 1,
);
console.log(
`[Service Worker] Established baseURI=[${baseURI}]; basePathName=[${basePathName}]`,
);
const precacheFiles = Object.fromEntries([
"/",
"/.client/client.js",
@@ -21,7 +38,7 @@ const precacheFiles = Object.fromEntries([
"/.client/logo-dock.png",
"/.client/main.css",
"/.client/manifest.json",
].map((path) => [path, path + "?v=" + CACHE_NAME, path])); // Cache busting
].map((path) => [path, `${baseURI}${path}?v=${CACHE_NAME}`, path])); // Cache busting
self.addEventListener("install", (event: any) => {
console.log("[Service worker]", "Installing service worker...");
@@ -71,8 +88,10 @@ const filesContentPrefix = ["file", "content"];
self.addEventListener("fetch", (event: any) => {
const url = new URL(event.request.url);
const pathname = url.pathname.substring(basePathName.length); //url.pathname with any URL prefix removed
// Use the custom cache key if available, otherwise use the request URL
const cacheKey = precacheFiles[url.pathname] || event.request.url;
const cacheKey = precacheFiles[pathname] || event.request.url;
event.respondWith(
(async () => {
@@ -80,7 +99,7 @@ self.addEventListener("fetch", (event: any) => {
const requestUrl = new URL(request.url);
// Are we fetching a URL from the same origin as the app? If not, we don't handle it and pass it on
if (location.host !== requestUrl.host) {
if (!requestUrl.href.startsWith(baseURI)) {
return fetch(request);
}
@@ -101,7 +120,7 @@ self.addEventListener("fetch", (event: any) => {
return fetch(request);
}
const pathname = requestUrl.pathname;
const pathname = requestUrl.pathname.substring(basePathName.length); //requestUrl.pathname without with any URL prefix removed
if (
pathname === "/.auth" ||
+2 -1
View File
@@ -146,7 +146,8 @@ export const spaceluaApi = new LuaTable({
if (typeof location === "undefined") {
return null;
} else {
return location.protocol + "//" + location.host;
//NOTE: Removing trailing slash to stay compatible with original code: `location.protocol + "//" + location.host;`
return document.baseURI.replace(/\/*$/, "");
}
},
),
+4 -4
View File
@@ -6,28 +6,28 @@
@font-face {
font-family: "iA-Mono";
src: url("/.client/iAWriterMonoS-Regular.woff2");
src: url("iAWriterMonoS-Regular.woff2");
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: "iA-Mono";
src: url("/.client/iAWriterMonoS-Bold.woff2");
src: url("iAWriterMonoS-Bold.woff2");
font-weight: bold;
font-style: normal;
}
@font-face {
font-family: "iA-Mono";
src: url("/.client/iAWriterMonoS-Italic.woff2");
src: url("iAWriterMonoS-Italic.woff2");
font-weight: normal;
font-style: italic;
}
@font-face {
font-family: "iA-Mono";
src: url("/.client/iAWriterMonoS-BoldItalic.woff2");
src: url("iAWriterMonoS-BoldItalic.woff2");
font-weight: bold;
font-style: italic;
}
+1 -1
View File
@@ -158,7 +158,7 @@ export function systemSyscalls(
await client.ds.batchDelete(allKeys);
}
if (logout) {
location.href = "/.logout";
location.href = ".logout";
} else {
alert("Client wiped, feel free to navigate elsewhere");
}
+1
View File
@@ -8,6 +8,7 @@ SilverBullet is primarily configured via environment variables. This page gives
# Network
* `SB_HOSTNAME`: Set to the hostname to bind to (defaults to `127.0.0.0`, set to `0.0.0.0` to accept outside connections for the local deno setup, defaults to `0.0.0.0` for docker)
* `SB_PORT`: Sets the port to listen to, e.g. `SB_PORT=1234`, default is `3000`
* `SB_URL_PREFIX`: Host SilverBullet on a particular URL prefix, e.g. `SB_URL_PREFIX=/notes`
# Authentication
SilverBullet supports basic authentication for a single user.