Files
plainleaf/client/boot.ts
T

375 lines
13 KiB
TypeScript

import { race, safeRun, sleep } from "@silverbulletmd/silverbullet/lib/async";
import {
notAuthenticatedError,
offlineError,
} from "@silverbulletmd/silverbullet/constants";
import { initLogger } from "./lib/logger.ts";
import { extractSpaceLuaFromPageText, loadConfig } from "./boot_config.ts";
import { Client } from "./client.ts";
import type { Config } from "./config.ts";
import {
flushCachesAndUnregisterServiceWorker,
unregisterServiceWorkers,
} from "./service_worker/util.ts";
import "./lib/polyfills.ts";
import type { BootConfig, ServiceWorkerTargetMessage } from "./types/ui.ts";
import { BoxProxy } from "./lib/box_proxy.ts";
import { importKey } from "@silverbulletmd/silverbullet/lib/crypto";
import "./debug.ts";
const logger = initLogger("[Client]");
if (!crypto.subtle) {
alert(
"You are likely accessing SilverBullet via HTTP (rather than HTTPS or localhost), this is not a supported configuration. See https://silverbullet.md/TLS",
);
}
safeRun(async () => {
// First we attempt to fetch the config from the server
let bootConfig: BootConfig | undefined;
let config: Config | undefined;
// Placeholder proxy for Client object to be swapped in later
const clientProxy = new BoxProxy({});
let bootstrapLuaScriptPages: string[] = [];
// Try loading config and scripts
try {
let configJSONText: string;
[configJSONText, ...bootstrapLuaScriptPages] = await Promise.all([
cachedFetch(".config"),
// Some minimal bootstrap Lua: schema definition
cachedFetch(".fs/Library/Std/APIs/Schema.md"),
// Configuration option definitions and defaults
cachedFetch(".fs/Library/Std/Config.md"),
// Tag definition API
cachedFetch(".fs/Library/Std/APIs/Tag.md"),
// Custom configuration
cachedFetch(".fs/CONFIG.md"),
]);
bootConfig = JSON.parse(configJSONText);
} catch (e: any) {
if (e.message === offlineError.message) {
alert(
"Could not process config and no cached copy, please connect to the Internet",
);
// Not recoverable
return;
}
}
// Concatenate and evaluate
try {
config = await loadConfig(
bootstrapLuaScriptPages.map(extractSpaceLuaFromPageText).join("\n"),
clientProxy.buildProxy(),
!!bootConfig?.readOnly,
);
} catch (e: any) {
alert(
`Failed to run Space Lua code (likely CONFIG), will attempt to boot without. Error: ${e.message}`,
);
console.error("Error evaluating Space Lua script on boot:", e);
try {
config = await loadConfig(
// Everything but CONFIG (at the end)
bootstrapLuaScriptPages
.slice(0, bootstrapLuaScriptPages.length - 1)
.map(extractSpaceLuaFromPageText)
.join("\n"),
clientProxy.buildProxy(),
false,
);
} catch (e: any) {
console.error("Boot error", e);
alert(
"Could not load boot scripts, even without CONFIG, check your browser's logs",
);
return;
}
}
let encryptionKey: CryptoKey | undefined;
// If client encryption is enabled (from auth page) AND the server signals it
if (
localStorage.getItem("enableEncryption") &&
bootConfig?.enableClientEncryption
) {
// Init encryption
console.log("Initializing encryption");
const swController = navigator.serviceWorker.controller;
if (swController) {
// Service is already running, let's see if has an encryption key for me
console.log(
"Service worker already running, querying it for an encryption key",
);
swController.postMessage({
type: "get-encryption-key",
} as ServiceWorkerTargetMessage);
await race([
new Promise<void>((resolve) => {
function keyListener(e: any) {
if (e.data.type === "encryption-key") {
navigator.serviceWorker.removeEventListener(
"message",
keyListener,
);
void importKey(e.data.key).then((key) => {
encryptionKey = key;
resolve();
});
}
}
navigator.serviceWorker.addEventListener("message", keyListener);
}),
sleep(200),
]);
if (!encryptionKey) {
// No encryption key, redirecting to the auth page
console.warn("Not authenticated, redirecting to auth page");
location.href = ".auth";
throw new Error("Not authenticated");
}
} else {
// No service worker, no encryption key, redirecting to the auth page
console.warn("Not authenticated, redirecting to auth page");
location.href = ".auth";
throw new Error("Not authenticated");
}
} else {
bootConfig!.enableClientEncryption = false;
}
await augmentBootConfig(bootConfig!, config!);
const isHeadless = new URLSearchParams(location.search).has("headless");
// Expose headless flag globally so client.init() can detect it after URL params are stripped
if (isHeadless) {
(globalThis as any).__sbHeadless = true;
}
// Update the browser URL to no longer contain the query parameters using pushState
if (location.search) {
const newURL = new URL(location.href);
newURL.search = "";
history.pushState({}, "", newURL.toString());
}
console.log("Booting SilverBullet client");
console.log("Boot config", bootConfig, config.values);
// Skip (and tear down) the service worker when headless, when the server
// forbids it via BootConfig.disableServiceWorker, or when the user opted
// out locally with ?enableSW=0 (persisted to localStorage).
const swDisabled = !!bootConfig?.disableServiceWorker ||
localStorage.getItem("enableSW") === "0";
if (swDisabled && navigator.serviceWorker) {
await flushCachesAndUnregisterServiceWorker();
}
if (
!isHeadless &&
!swDisabled &&
navigator.serviceWorker
) {
// Register service worker
const workerURL = new URL("service_worker.js", document.baseURI);
let startNotificationCount = 0;
let lastStartNotification = 0;
navigator.serviceWorker.addEventListener("message", (event) => {
if (event.data.type === "service-worker-started") {
// Service worker started, let's make sure it has the current config
console.log(
"Got notified that service worker has just started, sending config",
bootConfig,
);
navigator.serviceWorker.ready.then((registration) => {
registration.active!.postMessage({
type: "config",
config: bootConfig,
});
});
// Check for weird restart behavior
startNotificationCount++;
if (Date.now() - lastStartNotification > 5000) {
// Last restart was longer than 5s ago: this is fine
startNotificationCount = 0;
}
if (startNotificationCount > 2) {
// This is not normal. Safari sometimes gets stuck on a database connection if the service worker is updated which means it cannot boot properly
// the only know fix is to quit the browser and restart it
console.warn(
"Something is wrong with the sync engine, please quit your browser and restart it.",
);
}
lastStartNotification = Date.now();
}
});
navigator.serviceWorker
.register(workerURL, {
type: "module",
//limit the scope of the service worker to any potential URL prefix
scope: workerURL.pathname.substring(
0,
workerURL.pathname.lastIndexOf("/") + 1,
),
})
.then((registration) => {
console.log("Service worker registered...");
// Send the config
registration.active?.postMessage({
type: "config",
config: bootConfig,
});
// Set up update detection
registration.addEventListener("updatefound", () => {
const newWorker = registration.installing;
console.log("New service worker installing...");
if (newWorker) {
newWorker.addEventListener("statechange", () => {
if (
newWorker.state === "installed" &&
navigator.serviceWorker.controller
) {
console.log(
"New service worker installed and ready to take over.",
);
// Force the new service worker to activate immediately
newWorker.postMessage({ type: "skip-waiting" });
}
});
}
});
});
} else {
console.info("Service worker disabled.");
}
const client = new Client(
document.getElementById("sb-root")!,
bootConfig!,
config!,
);
if (bootConfig!.logPush) {
setInterval(() => {
void logger.postToServer(".logs", "client");
}, 1000);
}
globalThis.client = client;
clientProxy.setTarget(client);
await client.init(encryptionKey);
if (navigator.serviceWorker) {
navigator.serviceWorker.addEventListener("message", (event) => {
void client.handleServiceWorkerMessage(event.data);
});
}
});
/**
* Augments the boot config with values from the page's search params
* as well as well as Lua-based configuration from CONFIG
*/
async function augmentBootConfig(bootConfig: BootConfig, config: Config) {
// Pull out sync configuration
bootConfig.syncDocuments = config.get<boolean>(["sync", "documents"], false);
let syncIgnore = config!.get<string | string[]>(["sync", "ignore"], "");
if (Array.isArray(syncIgnore)) {
syncIgnore = syncIgnore.join("\n");
}
bootConfig.syncIgnore = syncIgnore;
// Then we augment the config based on the URL arguments
const urlParams = new URLSearchParams(location.search);
if (urlParams.has("readOnly")) {
bootConfig.readOnly = true;
}
if (urlParams.has("disableSpaceLua")) {
bootConfig.disableSpaceLua = true;
}
if (urlParams.has("disablePlugs")) {
bootConfig.disablePlugs = true;
}
if (urlParams.has("disableSpaceStyle")) {
bootConfig.disableSpaceStyle = true;
}
if (urlParams.has("wipeClient")) {
bootConfig.performWipe = true;
}
if (urlParams.has("resetClient")) {
bootConfig.performReset = true;
}
if (urlParams.has("enableSW")) {
const val = urlParams.get("enableSW")!;
localStorage.setItem("enableSW", val);
if (val === "0") {
await flushCachesAndUnregisterServiceWorker();
}
}
}
if (!globalThis.indexedDB) {
alert(
"SilverBullet requires IndexedDB to operate and it is not available in your browser. Please use a recent version of Chrome, Firefox (not in private mode) or Safari.",
);
}
async function cachedFetch(path: string): Promise<string> {
const cacheKey = `silverbullet.${document.baseURI}.${path}`;
try {
const response = await fetch(path, {
// We don't want to follow redirects, we want to get the redirect header in case of auth issues
redirect: "manual",
// Tinyauth/forward-auth can take longer than 1s on cold or remote auth checks.
// Keep this bounded, but do not abort normal authenticated startup requests too aggressively.
signal: AbortSignal.timeout(10000),
headers: {
"X-Sync-Mode": "1",
},
});
if (response.status >= 500 && response.status < 600) {
const text = localStorage.getItem(cacheKey);
if (text) {
console.info("Falling back to cache for", path);
return text;
} else {
throw offlineError;
}
}
if (response.status === 404) {
// File doesn't exist yet (e.g., CONFIG.md before first sync)
// Return empty string without caching, so next boot re-fetches
return "";
}
if (response.type === "opaqueredirect") {
// We received an opaque redirect, there's little sensible we can do than unregister service workers and reload
console.log(
"Got opaque redirect, going to unregister service workers and reload",
);
await unregisterServiceWorkers();
console.log("Ok, now going to reload, let's hope for the best");
location.reload();
throw notAuthenticatedError;
}
const redirectHeader = response.headers.get("location");
if (redirectHeader) {
console.info(
"Received an (authentication) redirect, redirecting to URL: " +
redirectHeader,
);
location.href = redirectHeader;
throw notAuthenticatedError;
}
const text = await response.text();
// Persist to localStorage
localStorage.setItem(cacheKey, text);
return text;
} catch (e: any) {
console.info("Falling back to cache for", path);
// We may be offline, let's see if we have a cached config
const text = localStorage.getItem(cacheKey);
if (text) {
// Yep! Let's use it
return text;
} else {
throw e;
}
}
}