Files
plainleaf/cmd/server.ts
T
+1 766fb96ff2 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>
2025-06-04 15:15:14 +02:00

166 lines
4.8 KiB
TypeScript

import { HttpServer } from "../server/http_server.ts";
import clientAssetBundle from "../dist/client_asset_bundle.json" with {
type: "json",
};
import plugAssetBundle from "../dist/plug_asset_bundle.json" with {
type: "json",
};
import { AssetBundle, type AssetJson } from "../lib/asset_bundle/bundle.ts";
import { determineDatabaseBackend } from "../server/db_backend.ts";
import { sleep } from "$lib/async.ts";
export type AuthOptions = {
authToken?: string;
user: string;
pass: string;
lockoutTime: number;
lockoutLimit: number;
};
export async function serveCommand(
options: {
hostname?: string;
port?: number;
user?: string;
auth?: string;
cert?: string;
key?: string;
reindex?: boolean;
},
folder?: string,
) {
const hostname = options.hostname || Deno.env.get("SB_HOSTNAME") ||
"127.0.0.1";
const port = options.port ||
(Deno.env.get("SB_PORT") && +Deno.env.get("SB_PORT")!) || 3000;
const readOnly = !!Deno.env.get("SB_READ_ONLY");
const indexPage = Deno.env.get("SB_INDEX_PAGE") || "index";
if (!folder) {
// Didn't get a folder as an argument, check if we got it as an environment variable
folder = Deno.env.get("SB_FOLDER");
if (!folder) {
console.error(
"No folder specified. Please pass a folder as an argument or set SB_FOLDER environment variable.",
);
Deno.exit(1);
}
}
const baseKvPrimitives = await determineDatabaseBackend(folder);
console.log(
"Going to start SilverBullet binding to",
`${hostname}:${port}`,
);
if (hostname === "127.0.0.1") {
console.info(
`SilverBullet will only be available locally, to allow outside connections, pass -L0.0.0.0 as a flag, and put a TLS terminator on top.`,
);
}
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;
if (userAuth) {
const [user, pass] = userAuth.split(":");
userCredentials = {
user,
pass,
// 10 failed login attempts in 1 minute
lockoutLimit: 10,
lockoutTime: 60,
};
// Override lockout settings if they are set in the environment
if (Deno.env.get("SB_LOCKOUT_LIMIT")) {
userCredentials.lockoutLimit = Number(Deno.env.get("SB_LOCKOUT_LIMIT"));
}
if (Deno.env.get("SB_LOCKOUT_TIME")) {
userCredentials.lockoutTime = Number(Deno.env.get("SB_LOCKOUT_TIME"));
}
if (Deno.env.get("SB_AUTH_TOKEN")) {
userCredentials.authToken = Deno.env.get("SB_AUTH_TOKEN");
}
console.log(
`User authentication enabled for user "${user}" with lockout limit ${userCredentials.lockoutLimit} and lockout time ${userCredentials.lockoutTime}s`,
);
}
const backendConfig = Deno.env.get("SB_SHELL_BACKEND") || "local";
const enableSpaceScript = Deno.env.get("SB_SPACE_SCRIPT") !== "off";
const spaceIgnore = Deno.env.get("SB_SPACE_IGNORE");
const plugAssets = new AssetBundle(plugAssetBundle as AssetJson);
const clientAssets = new AssetBundle(clientAssetBundle as AssetJson);
const manifestName = Deno.env.get("SB_NAME");
const manifestDescription = Deno.env.get("SB_DESCRIPTION");
if (manifestName || manifestDescription || hostUrlPrefix) {
const manifestData = JSON.parse(
clientAssets.readTextFileSync(".client/manifest.json"),
);
if (manifestName) {
manifestData.name = manifestData.short_name = manifestName;
}
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",
JSON.stringify(manifestData),
);
}
const httpServer = new HttpServer({
hostname,
port,
clientAssetBundle: clientAssets,
plugAssetBundle: plugAssets,
baseKvPrimitives,
keyFile: options.key,
certFile: options.cert,
indexPage,
spaceIgnore,
auth: userCredentials,
readOnly,
shellBackend: backendConfig,
enableSpaceScript,
pagesPath: folder,
hostUrlPrefix,
});
await httpServer.start();
// Wait in an infinite loop (to keep the HTTP server running, only cancelable via Ctrl+C or other signal)
while (true) {
await sleep(10000);
}
}