Offer desktop client downloads and let a proxy end Lore's gRPC TLS

- scripts/build-desktop-dist.sh cross-compiles the desktop client for
  Linux (glibc 2.39) and Windows with Zig and Cargo, bundles liblore
  from the pinned release, and writes the archives, SHA256SUMS and BUILD
  to run/downloads/.
- lore-forge serves them to signed-in users at /download and
  /downloads/{file} (LORE_FORGE_DOWNLOADS_DIR), with a Desktop tab in
  the nav and a panel on the home page. Only plain names of known types
  are served; download and downloads are reserved names.
- fetch-lore.sh takes LORE_TARGET for --liblore and unpacks the Windows
  zip.
- loreserver-config --grpc-tls-at-proxy (LORE_GRPC_TLS_AT_PROXY=1 for
  start.sh) gives the certificate to QUIC only, for a proxy that ends
  TLS on TCP 41337 and relays to loreserver over a private link.
- shell.nix: an FHS shell with Rust, protoc, Zig and the other build
  tools, for NixOS.
This commit is contained in:
Peterino2 2026-11-27 04:16:36 +00:00
parent 2174cc97e4
commit 9dd11c3011
20 changed files with 731 additions and 24 deletions

View File

@ -34,6 +34,16 @@ loreserver :41337 udp+tcp (TLS) ── /var/lib/loreserver/store
- `loreserver` only *wants* lore-forge, so restarting lore-forge does not restart it and
drop its locks.
## TLS ending at a proxy
A deployment whose proxy ends TLS on TCP 41337 (one public host relaying to `loreserver` on
another over a private link) sets `LORE_GRPC_TLS_AT_PROXY=1` for `scripts/start.sh`, or passes
`lore-forge loreserver-config --grpc-tls-at-proxy`. The certificate is then written for
`[server.quic]` only: QUIC cannot be ended at an ordinary proxy, so its TLS stays at
`loreserver`, while gRPC is plaintext behind the proxy and lore-forge's browser reads it at
`http://127.0.0.1:41337` (owner, 2026-11-27). Checked by a unit test of the generated
configuration; the e2e test does not run this shape.
## Verified
In Lore v0.14.0's `docs/reference/lore-server-config.md` and `lore-cli-config.md`:

View File

@ -373,13 +373,25 @@ goes on when its warm-up sync is refused, so such a state can be captured.
again after each rebuild) before liblore may read the store's key. `LORE_AUTH_STORE=fallback`
avoids that; the e2e uses it.
On Linux (NixOS 25.11, x86-64), 2026-11-27, from the archives `scripts/build-desktop-dist.sh`
packs (see [Packaging](#packaging)):
- `forge-service`, linked by `zig cc` against glibc 2.39, loads the bundled `liblore.so`
(`0.14.0+2389`) and listens on its socket.
- `forge-desktop --test` did not finish a frame from the shell it was run in, with the
bundled GUI or a native debug build alike, so the window is untried on Linux. A run from a
terminal in the desktop session is the next check.
Compiled and linked only, not run:
- **GUI:** `zig build -Dtarget=x86_64-windows-gnu` (a GUI-subsystem PE) and `x86_64-linux-gnu`.
- **liblore on Windows and Linux:** `zig build` fetches and installs liblore on macOS and
Linux only; the Windows release is a zip, and nothing unpacks it yet.
- **Service on Windows:** the named-pipe code path has not been compiled; the Rust Windows
target is not installed here.
- **Service on Windows:** cross-compiled for `x86_64-pc-windows-gnu` with Cargo, linked by
`zig cc` against Zig's MinGW (UCRT) and LLVM libunwind, with Zig's `dlltool`. It imports
only system DLLs; the named-pipe code path has never run.
- **liblore on Windows:** `LORE_TARGET=x86_64-pc-windows-msvc scripts/fetch-lore.sh --liblore`
fetches and unpacks the release zip (`lore.dll`, `lore.h`). The DLL links the C runtime
statically, so it needs no Visual C++ redistributable. A MinGW-linked service loading an
MSVC-built DLL is expected to work through the C ABI, but has not been tried.
- **GUI pipe client:** the Windows code path compiles, but no Windows run has exercised it.
Found while building:
@ -388,6 +400,30 @@ Found while building:
Linux. The default locations fit. A long `LORE_FORGE_DESKTOP_DIR` does not, and both sides
then say so rather than failing vaguely.
## Packaging
`scripts/build-desktop-dist.sh` builds, on one Linux machine, an archive per platform into
`run/downloads/`, which lore-forge offers at `/download` to signed-in users (owner,
2026-11-27):
| Archive | Contents |
| --- | --- |
| `lore-forge-desktop-linux-x86_64.tar.gz` | `forge-desktop`, `forge-service`, `liblore.so` |
| `lore-forge-desktop-windows-x86_64.zip` | `forge-desktop.exe`, `forge-service.exe`, `lore.dll` |
Each also holds Lore's MIT licence and third-party notices, and a `README.txt`. Beside them,
`SHA256SUMS` and a one-line `BUILD` (commit, Lore version, date).
- The GUI is built with `zig build -Doptimize=ReleaseSafe -Dservice=false`; Windows' `.pdb`
is left out.
- The service is built with Cargo for each target, linked by `zig cc` through wrappers the
script writes: on Linux against glibc 2.39 (liblore's own floor) and the standard
`/lib64` loader rather than the build machine's, on Windows as described under
[Verified so far](#verified-so-far).
- liblore comes from the release pinned in `lore.lock`.
- The archives are not signed. macOS is not packaged yet; whether it can be built from Linux
(the GUI links Apple's frameworks) is untried.
## Milestones
1. **GUI and tray shell.** Done.
@ -420,6 +456,7 @@ Found while building:
them. Enforcing them would need a hook in Lore or a check in lore-forge's authorizer.
- Whether the service should start at login (launch agent, systemd user unit, Run key), and
who installs that.
- Packaging and signing per platform.
- Signing the archives, installers, and a macOS package. Unsigned archives exist; see
[Packaging](#packaging).
- Whether to adopt Epic's desktop client once it is open source. Lore's roadmap promises it
for 2027; today it is a closed binary.

View File

@ -106,6 +106,7 @@ Built in phase 1:
| `/<owner>/<repo>/revision/<signature>` | One revision and its diffs |
| `/<owner>/<repo>/access` | Grants, for holders of the `admin` action |
| `/licenses` | Third-party licences |
| `/download`, `/downloads/<file>` | The desktop client's archives, signed in only (owner, 2026-11-27): the files in `LORE_FORGE_DOWNLOADS_DIR` with size and SHA-256, served only by plain name and known type (`.tar.gz`, `.zip`, `SHA256SUMS`) |
| `/api/v1/user`, `/api/v1/repos` | JSON API, API tokens with the `api` scope |
Planned:

View File

@ -68,6 +68,7 @@ tokens Lore verifies, per-repository permissions, and a self-hosted forge UI on
| `scripts/fetch-lore.sh`, `lore.lock` | Downloads the pinned Lore release into `.lore/` (git-ignored), checking SHA-256; `--liblore` fetches liblore and `lore.h` |
| `scripts/e2e-lore.sh`, `scripts/desktop-e2e.py` | End-to-end test against real Lore, including the desktop service |
| `scripts/backup.sh`, `scripts/restore.sh` | Back up and restore the database and loreserver's store together |
| `scripts/build-desktop-dist.sh` | Cross-compiles the desktop client for Linux and Windows with Zig and packs the archives `/download` serves |
| `deploy/` | Production on Linux: `install.sh`, systemd units, the Caddy site, the settings template, `README.md` for operators |
| `desktop/` | The desktop client: `gui/` (C++ tray app), `service/` and `protocol/` (Rust), `lore-sys/` (liblore bindings; `gen/` regenerates them), `vendor/` (UHDK, Dear ImGui) |

2
Cargo.lock generated
View File

@ -753,8 +753,10 @@ dependencies = [
"serde",
"serde_json",
"similar",
"tempfile",
"tokio",
"tokio-stream",
"tokio-util",
"tonic",
"tower",
"tracing",

View File

@ -43,6 +43,7 @@ tempfile = "3"
thiserror = "2"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "signal", "time", "sync"] }
tokio-stream = "0.1"
tokio-util = { version = "0.7", features = ["io"] }
tonic = { version = "0.14", default-features = false, features = ["codegen", "router", "server"] }
tonic-prost = "0.14"
tonic-prost-build = "0.14"

View File

@ -49,11 +49,18 @@ Ctrl-C stops both servers. Later runs reuse everything in `run/`, which is git-i
| `lore-store/` | `loreserver`'s repository storage |
| `lore-config/` | The `loreserver` configuration, regenerated on every start |
| `logs/` | Both servers' logs |
| `downloads/` | Desktop client archives for `/download`, from `scripts/build-desktop-dist.sh` |
To serve other machines, set `PUBLIC_URL` to lore-forge's https URL. Behind a reverse proxy, the
proxy must pass HTTP/2 through so gRPC works. Also set `LORE_URL` and `LORE_REMOTE` to the host
clients use for Lore, and `LORE_TLS_CERT`/`LORE_TLS_KEY` to a real certificate. Without one,
`loreserver` makes a self-signed certificate on every start.
`loreserver` makes a self-signed certificate on every start. `LORE_REMOTE` is also the remote
the pages tell people to use; make it `lores://`, since `lore://` neither checks the
certificate nor encrypts gRPC.
If a proxy in front ends TLS on TCP 41337 and forwards Lore's gRPC over a private link, set
`LORE_GRPC_TLS_AT_PROXY=1`: the certificate then serves only QUIC, whose TLS always ends at
`loreserver`, and gRPC stays plaintext behind the proxy.
`PUBLIC_URL` is the token issuer, so do not change it once people have logged in.
@ -81,8 +88,11 @@ asks for it until you choose **Always Allow**.
## Desktop client
[desktop/](desktop/README.md) holds a tray application and the per-user service it talks to.
They are early: the service simulates sync for now. It builds with Zig and Cargo, separately
from the server.
It builds with Zig and Cargo, separately from the server.
`scripts/build-desktop-dist.sh` cross-compiles it for Linux and Windows and packs an archive
for each into `run/downloads/`, which lore-forge offers to signed-in users at `/download`. Both
builds are experimental: neither window has yet been run on that platform.
## Testing

View File

@ -3,7 +3,7 @@
/// Words that occupy the top level of the web UI's paths, so no user or organisation may be
/// named after them.
const RESERVED: &[&str] = &[
".well-known", "about", "admin", "api", "assets", "device", "explore", "favicon.ico",
".well-known", "about", "admin", "api", "assets", "device", "download", "downloads", "explore", "favicon.ico",
"health", "help", "licenses", "login", "logout", "new", "oauth", "org", "orgs", "raw", "robots.txt",
"settings", "setup", "signup", "static", "user", "users",
];

View File

@ -233,6 +233,10 @@ pub struct LoreserverSettings {
/// self-signed certificate made at each start, and gRPC is plaintext, which is fine only on
/// one machine.
pub tls: Option<(PathBuf, PathBuf)>,
/// Keep gRPC plaintext even with `tls`, which then serves QUIC only: for a deployment whose
/// proxy ends TLS on the gRPC port and forwards it to `loreserver` over a private link.
/// QUIC's TLS always ends at `loreserver`.
pub grpc_tls_at_proxy: bool,
/// The QUIC (UDP) and gRPC (TCP) port, 41337 by default.
pub port: Option<u16>,
/// The HTTP port, 41339 by default. It is plaintext and bound to loopback.
@ -281,8 +285,10 @@ pub fn loreserver_config(config: &forge_id::IssuerConfig, settings: &LoreserverS
if let Some((cert, key)) = &settings.tls {
let files = [format!("cert_file = {}", path(cert)), format!("pkey_file = {}", path(key))];
table("server.quic.certificate", &files);
if !settings.grpc_tls_at_proxy {
table("server.grpc.certificate", &files);
}
}
// The HTTP endpoint has no TLS setting, and Lore clients do not use it: only lore-forge's
// repository browser reads file content there, from the same machine.
let mut http = vec!["host = \"127.0.0.1\"".to_owned()];
@ -337,6 +343,7 @@ mod tests {
tls: Some(("/etc/loreserver/tls/cert.pem".into(), "/etc/loreserver/tls/key \"x\".pem".into())),
port: Some(42337),
http_port: Some(42339),
grpc_tls_at_proxy: false,
};
let toml = loreserver_config(&config, &settings);
for table in ["server.quic.certificate", "server.grpc.certificate"] {
@ -350,4 +357,21 @@ mod tests {
assert!(toml.contains("[immutable_store.local]\npath = \"/var/lib/loreserver/store\"\n"));
assert!(toml.contains("[mutable_store.local]\npath = \"/var/lib/loreserver/store\"\n"));
}
#[test]
fn a_proxy_can_end_grpc_tls() {
let config = forge_id::IssuerConfig::new(
&"https://lore.example.com".parse().unwrap(),
&"https://lore.example.com".parse().unwrap(),
"lore-cli",
);
let settings = LoreserverSettings {
tls: Some(("/tls/cert.pem".into(), "/tls/key.pem".into())),
grpc_tls_at_proxy: true,
..LoreserverSettings::default()
};
let toml = loreserver_config(&config, &settings);
assert!(toml.contains("[server.quic.certificate]\ncert_file = \"/tls/cert.pem\"\n"));
assert!(!toml.contains("server.grpc.certificate"), "{toml}");
}
}

View File

@ -16,11 +16,13 @@ maud.workspace = true
serde.workspace = true
serde_json.workspace = true
similar.workspace = true
tokio.workspace = true
tokio = { workspace = true, features = ["fs"] }
tokio-util.workspace = true
tracing.workspace = true
url.workspace = true
[dev-dependencies]
tempfile.workspace = true
tokio-stream.workspace = true
tonic.workspace = true
base64.workspace = true

View File

@ -13,6 +13,8 @@ mod limiter;
mod pages;
mod security;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use axum::Router;
@ -40,6 +42,8 @@ struct Inner {
/// `scheme://host[:port]` of the canonical URL, for checking `Origin`.
public_origin: String,
secure_cookies: bool,
/// The desktop client archives offered at `/download`, if any.
downloads: Option<PathBuf>,
}
impl AppState {
@ -63,10 +67,25 @@ impl AppState {
limiter: limiter::Limiter::default(),
public_origin,
secure_cookies,
downloads: None,
}),
}
}
fn configure(mut self, change: impl FnOnce(&mut Inner)) -> Self {
change(Arc::get_mut(&mut self.inner).expect("configured before the state is shared"));
self
}
/// Offers the desktop client archives in `dir` at `/download`.
pub fn with_downloads(self, dir: Option<PathBuf>) -> Self {
self.configure(|inner| inner.downloads = dir)
}
fn downloads(&self) -> Option<&Path> {
self.inner.downloads.as_deref()
}
fn pool(&self) -> &SqlitePool {
&self.inner.pool
}
@ -117,6 +136,7 @@ pub fn router(state: AppState) -> Router {
use pages::admin;
use pages::auth;
use pages::browse;
use pages::downloads;
use pages::orgs;
use pages::repos;
use pages::service_accounts as sa;
@ -139,6 +159,8 @@ pub fn router(state: AppState) -> Router {
.route("/static/app.css", get(pages::stylesheet))
.route("/static/vga-8x16.ttf", get(pages::font))
.route("/licenses", get(pages::licences))
.route("/download", get(downloads::page_handler))
.route("/downloads/{file}", get(downloads::file))
// Getting in.
.route("/setup", get(auth::setup_form).post(auth::setup))
.route("/login", get(auth::login_form).post(auth::login))

View File

@ -0,0 +1,251 @@
//! The desktop client's downloads: `/download` lists the archives in the configured downloads
//! directory, and `/downloads/{file}` serves them. Both need a session.
//!
//! The directory is written by `scripts/build-desktop-dist.sh`: one archive per platform, a
//! `SHA256SUMS` in `sha256sum`'s format and a one-line `BUILD`. Only plain file names with a
//! known type are served, so nothing else that lands in the directory is exposed.
use std::collections::HashMap;
use std::path::Path;
use axum::body::Body;
use axum::extract::Path as UrlPath;
use axum::extract::State;
use axum::http::HeaderValue;
use axum::http::StatusCode;
use axum::http::header;
use axum::response::IntoResponse;
use axum::response::Response;
use maud::Markup;
use maud::html;
use super::Nav;
use super::Viewer;
use super::not_found_page;
use super::page;
use super::panel;
use super::server_error;
use crate::AppState;
const CHECKSUMS: &str = "SHA256SUMS";
const BUILD: &str = "BUILD";
/// The type a file is served as, for the names that may be served.
fn content_type(name: &str) -> Option<&'static str> {
if name.ends_with(".tar.gz") {
Some("application/gzip")
} else if name.ends_with(".zip") {
Some("application/zip")
} else if name == CHECKSUMS {
Some("text/plain; charset=utf-8")
} else {
None
}
}
/// Whether `name` may be served: a plain, visible file name of a known type. It cannot name a
/// path: no separators, and a leading `.` (which `..` has) is refused.
fn servable(name: &str) -> bool {
!name.starts_with('.')
&& name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'))
&& content_type(name).is_some()
}
fn is_archive(name: &str) -> bool {
servable(name) && name != CHECKSUMS
}
/// The platform an archive is for, from its name, and what to know before downloading it.
fn platform(name: &str) -> (&'static str, &'static str) {
if name.contains("linux") {
("Linux x86-64", "glibc 2.39 or newer (Ubuntu 24.04, Fedora 40 or later) and a Wayland session. Experimental: the window has not yet been tried on Linux.")
} else if name.contains("windows") {
("Windows x86-64", "Windows 10 or later. Experimental: cross-compiled, and not yet run on Windows.")
} else if name.contains("macos") || name.contains("darwin") {
("macOS", "")
} else {
("Other", "")
}
}
struct Archive {
name: String,
size: u64,
sha256: Option<String>,
}
struct Listing {
archives: Vec<Archive>,
build: Option<String>,
has_checksums: bool,
}
/// `sha256sum` output: `<hash> <name>`, or `<hash> *<name>` for binary mode.
fn parse_checksums(text: &str) -> HashMap<String, String> {
text.lines()
.filter_map(|line| {
let (hash, name) = line.split_once(char::is_whitespace)?;
let name = name.trim_start().trim_start_matches('*');
(hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit())).then(|| (name.to_owned(), hash.to_ascii_lowercase()))
})
.collect()
}
async fn list(dir: &Path) -> std::io::Result<Listing> {
let checksums = tokio::fs::read_to_string(dir.join(CHECKSUMS)).await.ok();
let sums = checksums.as_deref().map(parse_checksums).unwrap_or_default();
let build = tokio::fs::read_to_string(dir.join(BUILD)).await.ok().map(|text| text.trim().to_owned()).filter(|text| !text.is_empty());
let mut archives = Vec::new();
let mut entries = match tokio::fs::read_dir(dir).await {
Ok(entries) => entries,
// Not built yet: the page says so.
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok(Listing { archives, build: None, has_checksums: false });
}
Err(error) => return Err(error),
};
while let Some(entry) = entries.next_entry().await? {
let Ok(name) = entry.file_name().into_string() else { continue };
if !is_archive(&name) {
continue;
}
let metadata = tokio::fs::metadata(entry.path()).await?;
if metadata.is_file() {
let sha256 = sums.get(&name).cloned();
archives.push(Archive { name, size: metadata.len(), sha256 });
}
}
archives.sort_by(|a, b| a.name.cmp(&b.name));
Ok(Listing { archives, build, has_checksums: checksums.is_some() })
}
fn size(bytes: u64) -> String {
match bytes {
0..1_024 => format!("{bytes} B"),
1_024..1_048_576 => format!("{:.0} KiB", bytes as f64 / 1_024.0),
_ => format!("{:.1} MiB", bytes as f64 / 1_048_576.0),
}
}
pub async fn page_handler(State(state): State<AppState>, viewer: Viewer) -> Response {
let listing = match state.downloads() {
Some(dir) => match list(dir).await {
Ok(listing) => Some(listing),
Err(error) => return server_error(format!("listing {}: {error}", dir.display())),
},
None => None,
};
let remote = super::lore_remote(&state);
page(StatusCode::OK, "Desktop client", viewer.chrome(Nav::Desktop), html! {
h1 { "Desktop client" }
p.muted {
"A tray application for working in Lore repositories. Each archive holds "
code { "forge-desktop" } ", the " code { "forge-service" } " it starts, and the Lore "
"library the service loads. Unpack it, keep the files together and run "
code { "forge-desktop" } "."
}
@match &listing {
Some(listing) if !listing.archives.is_empty() => (table(listing)),
_ => (panel("Not published", html! {
p { "No desktop builds are published on this server yet." }
@if viewer.is_admin() {
p.muted {
"Build them with " code { "scripts/build-desktop-dist.sh" } " and set "
code { "LORE_FORGE_DOWNLOADS_DIR" } " to the directory it writes."
}
}
})),
}
(panel("Workspaces", html! {
p.muted { "A workspace's remote names this server's Lore endpoint and the repository:" }
pre { code { (remote) "/" (viewer.session.user.username) "/my-game" } }
}))
})
}
fn table(listing: &Listing) -> Markup {
html! {
table.list {
thead { tr { th { "Platform" } th { "Download" } th { "Size" } th { "SHA-256" } } }
tbody {
@for archive in &listing.archives {
@let (label, note) = platform(&archive.name);
tr {
td {
(label)
@if !note.is_empty() { br; span.muted { (note) } }
}
td { a href={ "/downloads/" (archive.name) } download { (archive.name) } }
td { (size(archive.size)) }
td { code { (archive.sha256.as_deref().unwrap_or("-")) } }
}
}
}
}
p.muted {
@if let Some(build) = &listing.build { (build) ". " }
@if listing.has_checksums {
"Check a download with " code { "sha256sum -c" } " against "
a href={ "/downloads/" (CHECKSUMS) } { (CHECKSUMS) } "."
}
}
}
}
pub async fn file(State(state): State<AppState>, viewer: Viewer, UrlPath(name): UrlPath<String>) -> Response {
let (Some(dir), Some(content_type)) = (state.downloads(), content_type(&name)) else {
return not_found_page(Some(&viewer));
};
if !servable(&name) {
return not_found_page(Some(&viewer));
}
let path = dir.join(&name);
let opened = async {
let file = tokio::fs::File::open(&path).await?;
let metadata = file.metadata().await?;
Ok::<_, std::io::Error>((file, metadata))
};
let (file, metadata) = match opened.await {
Ok((file, metadata)) if metadata.is_file() => (file, metadata),
Ok(_) => return not_found_page(Some(&viewer)),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return not_found_page(Some(&viewer)),
Err(error) => return server_error(format!("opening {}: {error}", path.display())),
};
let mut response = Body::from_stream(tokio_util::io::ReaderStream::new(file)).into_response();
let headers = response.headers_mut();
headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
headers.insert(header::CONTENT_LENGTH, HeaderValue::from(metadata.len()));
// The name is plain ASCII without quotes (see servable), so it needs no escaping.
if let Ok(value) = HeaderValue::from_str(&format!("attachment; filename=\"{name}\"")) {
headers.insert(header::CONTENT_DISPOSITION, value);
}
// Behind a session: no shared caches.
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("private, no-cache"));
response
}
#[cfg(test)]
mod tests {
use super::parse_checksums;
use super::servable;
#[test]
fn only_plain_names_of_known_types_are_served() {
assert!(servable("lore-forge-desktop-linux-x86_64.tar.gz"));
assert!(servable("lore-forge-desktop-windows-x86_64.zip"));
assert!(servable("SHA256SUMS"));
for name in ["BUILD", "../secret.tar.gz", "..", ".hidden.zip", "a/b.zip", "a\\b.zip", "x.exe", "", "a b.zip", "a\".zip"] {
assert!(!servable(name), "{name}");
}
}
#[test]
fn checksums_in_both_sha256sum_modes() {
let hash = "a".repeat(64);
let sums = parse_checksums(&format!("{hash} one.tar.gz\n{hash} *two.zip\nnot a line\n"));
assert_eq!(sums.get("one.tar.gz"), Some(&hash));
assert_eq!(sums.get("two.zip"), Some(&hash));
assert_eq!(sums.len(), 2);
}
}

View File

@ -96,6 +96,12 @@ pub async fn home(State(state): State<AppState>, viewer: Result<Viewer, Response
"lore clone " (remote) "/" (username) "/my-game"
} }
}))
(super::panel("Desktop client", html! {
p.muted {
"A tray app that keeps workspaces in sync. "
a href="/download" { "Download it for Linux or Windows" } "."
}
}))
}
}
})

View File

@ -4,6 +4,7 @@
pub mod admin;
pub mod auth;
pub mod browse;
pub mod downloads;
pub mod graph;
pub mod home;
pub mod orgs;
@ -43,6 +44,7 @@ pub enum Nav {
None,
Repos,
Orgs,
Desktop,
Settings,
Admin,
}
@ -125,6 +127,7 @@ fn layout(title: &str, chrome: &Chrome<'_>, narrow: bool, body: Markup) -> Marku
@if let Some(session) = chrome.session {
(tab(Nav::Repos, "/", "Repos"))
(tab(Nav::Orgs, "/orgs", "Orgs"))
(tab(Nav::Desktop, "/download", "Desktop"))
(tab(Nav::Settings, "/settings", "Settings"))
@if matches!(session.user.role, InstanceRole::Owner | InstanceRole::Admin) {
(tab(Nav::Admin, "/admin", "Admin"))

View File

@ -29,6 +29,20 @@ async fn app_with(provider_base: Option<&str>) -> App {
}
async fn build(provider_base: Option<&str>, lore: forge_lore::reader::Lore) -> App {
build_with(provider_base, lore, |state| state).await
}
/// An app whose state `configure` adjusts, such as to offer downloads.
async fn app_configured(configure: impl FnOnce(super::AppState) -> super::AppState) -> App {
let (grpc, content) = crate::fake_lore::start("author-id").await;
build_with(None, forge_lore::reader::Lore::new(&grpc, &content).unwrap(), configure).await
}
async fn build_with(
provider_base: Option<&str>,
lore: forge_lore::reader::Lore,
configure: impl FnOnce(super::AppState) -> super::AppState,
) -> App {
let store = forge_store::testing::store().await;
let pool = store.pool().clone();
let secret = SecretKey::from_base64(&SecretKey::generate_base64()).unwrap();
@ -44,7 +58,7 @@ async fn build(provider_base: Option<&str>, lore: forge_lore::reader::Lore) -> A
oauth = oauth.with_test_base(base);
}
let remote = super::default_lore_remote(&issuer.config().lore_url);
App { router: super::router(super::AppState::new(pool, issuer, oauth, lore, remote)), store }
App { router: super::router(configure(super::AppState::new(pool, issuer, oauth, lore, remote))), store }
}
struct Reply {
@ -649,3 +663,76 @@ fn lore_remote_checks_certificates_except_on_loopback() {
assert_eq!(remote("https://localhost"), "lore://localhost");
assert_eq!(remote("https://127.0.0.1:42337"), "lore://127.0.0.1:42337");
}
#[tokio::test]
async fn downloads_need_a_session_and_serve_only_offered_files() {
// The offered directory sits inside the temporary one, so a file beside it can stand for
// what a path escaping the directory would reach.
let root = tempfile::tempdir().unwrap();
std::fs::create_dir(root.path().join("offered")).unwrap();
std::fs::write(root.path().join("outside.zip"), b"outside").unwrap();
let dir = root.path().join("offered");
let linux = "lore-forge-desktop-linux-x86_64.tar.gz";
let hash = "ab".repeat(32);
std::fs::write(dir.join(linux), b"linux archive").unwrap();
std::fs::write(dir.join("lore-forge-desktop-windows-x86_64.zip"), b"windows archive").unwrap();
std::fs::write(dir.join("SHA256SUMS"), format!("{hash} {linux}\n")).unwrap();
std::fs::write(dir.join("BUILD"), "lore-forge abc1234, Lore v0.14.0, built 2026-11-27T01:19Z\n").unwrap();
std::fs::write(dir.join(".lore-forge-desktop-linux-x86_64.tar.gz.new"), b"half written").unwrap();
std::fs::write(dir.join("notes.txt"), b"not offered").unwrap();
let offered = dir.clone();
let app = app_configured(move |state| state.with_downloads(Some(offered))).await;
let cookies = app.set_up().await;
// Signed out, both the page and the files send the visitor to sign in.
let page = app.get("/download", "").await;
assert_eq!(page.status, StatusCode::SEE_OTHER);
assert_eq!(page.location(), "/login?next=%2Fdownload");
let file = app.get(&format!("/downloads/{linux}"), "").await;
assert_eq!(file.status, StatusCode::SEE_OTHER);
assert!(file.location().starts_with("/login?next="), "{}", file.location());
let page = app.get("/download", &cookies).await;
assert_eq!(page.status, StatusCode::OK);
assert!(page.body.contains(&format!("href=\"/downloads/{linux}\"")), "{}", page.body);
assert!(page.body.contains("lore-forge-desktop-windows-x86_64.zip"), "{}", page.body);
assert!(page.body.contains(&hash), "the checksum is shown");
assert!(page.body.contains("Lore v0.14.0, built"), "the build line is shown");
assert!(page.body.contains("Experimental"), "the Windows build is marked");
assert!(!page.body.contains(".new") && !page.body.contains("notes.txt"), "{}", page.body);
let file = app.get(&format!("/downloads/{linux}"), &cookies).await;
assert_eq!(file.status, StatusCode::OK);
assert_eq!(file.body, "linux archive");
assert_eq!(file.headers[header::CONTENT_TYPE], "application/gzip");
assert_eq!(file.headers[header::CONTENT_LENGTH], "13");
assert_eq!(file.headers[header::CONTENT_DISPOSITION], format!("attachment; filename=\"{linux}\""));
assert_eq!(file.headers[header::CACHE_CONTROL], "private, no-cache");
let sums = app.get("/downloads/SHA256SUMS", &cookies).await;
assert_eq!(sums.status, StatusCode::OK);
assert!(sums.body.contains(linux));
for refused in [
"/downloads/BUILD",
"/downloads/notes.txt",
"/downloads/.lore-forge-desktop-linux-x86_64.tar.gz.new",
"/downloads/..%2Foutside.zip",
"/downloads/%2E%2E%2Foutside.zip",
"/downloads/missing.zip",
] {
assert_eq!(app.get(refused, &cookies).await.status, StatusCode::NOT_FOUND, "{refused}");
}
}
#[tokio::test]
async fn downloads_page_without_builds() {
let app = app().await;
let cookies = app.set_up().await;
let page = app.get("/download", &cookies).await;
assert_eq!(page.status, StatusCode::OK);
assert!(page.body.contains("No desktop builds are published"), "{}", page.body);
assert_eq!(app.get("/downloads/x.zip", &cookies).await.status, StatusCode::NOT_FOUND);
// The nav and the home page lead to it.
assert!(page.body.contains("href=\"/download\""));
assert!(app.get("/", &cookies).await.body.contains("href=\"/download\""));
}

View File

@ -60,6 +60,10 @@ struct LoreserverConfigArgs {
/// The certificate's PEM private key.
#[arg(long, env = "LORE_FORGE_LORESERVER_TLS_KEY", requires = "tls_cert")]
tls_key: Option<PathBuf>,
/// Use the certificate for QUIC only and keep gRPC plaintext, because a proxy in front ends
/// TLS on the gRPC port. lore-forge then reads loreserver's gRPC over plain http.
#[arg(long, env = "LORE_FORGE_LORESERVER_GRPC_TLS_AT_PROXY", requires = "tls_cert")]
grpc_tls_at_proxy: bool,
/// loreserver's QUIC and gRPC port (default 41337).
#[arg(long)]
port: Option<u16>,
@ -75,6 +79,7 @@ fn loreserver_config(args: LoreserverConfigArgs) -> anyhow::Result<()> {
let settings = forge_lore::LoreserverSettings {
store: args.store,
tls: args.tls_cert.zip(args.tls_key),
grpc_tls_at_proxy: args.grpc_tls_at_proxy,
port: args.port,
http_port: args.http_port,
};
@ -218,6 +223,10 @@ struct ServeArgs {
/// `lore://` for a loopback host.
#[arg(long, env = "LORE_FORGE_LORE_REMOTE")]
lore_remote: Option<String>,
/// Directory of desktop client archives offered at /download, as written by
/// scripts/build-desktop-dist.sh. Unset: the page says none are published.
#[arg(long, env = "LORE_FORGE_DOWNLOADS_DIR")]
downloads_dir: Option<PathBuf>,
}
/// Whether a request is gRPC, which goes to Lore's directory services rather than the web
@ -278,7 +287,9 @@ async fn serve(args: ServeArgs) -> anyhow::Result<()> {
let grpc = Directory::new(pool.clone(), issuer.clone()).routes().into_axum_router();
let lore = forge_lore::reader::Lore::new(&args.lore_grpc_url, &args.lore_http_url).map_err(anyhow::Error::msg)?;
let remote = args.lore_remote.unwrap_or_else(|| forge_web::default_lore_remote(&issuer.config().lore_url));
let web = forge_web::router(forge_web::AppState::new(pool, issuer.clone(), oauth, lore, remote));
let state =
forge_web::AppState::new(pool, issuer.clone(), oauth, lore, remote).with_downloads(args.downloads_dir);
let web = forge_web::router(state);
let app = axum::Router::new()
.fallback_service(tower::service_fn(move |request: axum::extract::Request| {
let target = if is_grpc(&request) { grpc.clone() } else { web.clone() };

171
scripts/build-desktop-dist.sh Executable file
View File

@ -0,0 +1,171 @@
#!/usr/bin/env bash
# Builds the desktop client for Linux and Windows and packs one archive per platform, for
# lore-forge to offer at /download:
#
# scripts/build-desktop-dist.sh [OUT_DIR]
#
# OUT_DIR defaults to run/downloads/ (LORE_FORGE_RUN_DIR/downloads), which scripts/start.sh
# serves. It receives:
#
# lore-forge-desktop-linux-x86_64.tar.gz forge-desktop, forge-service, liblore.so
# lore-forge-desktop-windows-x86_64.zip forge-desktop.exe, forge-service.exe, lore.dll
# SHA256SUMS both archives' SHA-256
# BUILD one line: commit, Lore version, build date
#
# Each archive unpacks to one directory holding the three programs side by side (the GUI starts
# the service beside it, which loads liblore beside itself), Lore's licence and notices, and a
# README.txt.
#
# Everything is cross-compiled with Zig, so one Linux machine builds both:
# - the GUI with `zig build -Dtarget=...`;
# - the service with Cargo, linked by `zig cc` (and Zig's dlltool for Windows import
# libraries), so the Linux build uses the standard /lib64 loader and glibc 2.39 like
# liblore, rather than this machine's;
# - liblore from the Lore release pinned in lore.lock (scripts/fetch-lore.sh).
#
# Needs zig, cargo with rustup's x86_64-pc-windows-gnu target (added if missing), curl, tar,
# unzip and zip. Run it inside the repository's nix-shell on NixOS.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
RUN="${LORE_FORGE_RUN_DIR:-$ROOT/run}"
OUT="${1:-$RUN/downloads}"
DESKTOP="$ROOT/desktop"
GLIBC=2.39 # liblore's own floor
say() { echo "build-desktop-dist: $*" >&2; }
die() { say "$*"; exit 1; }
for tool in zig cargo tar unzip zip; do
command -v "$tool" >/dev/null || die "needs $tool on PATH"
done
if command -v rustup >/dev/null && ! rustup target list --installed | grep -qx x86_64-pc-windows-gnu; then
say "adding the x86_64-pc-windows-gnu Rust target"
rustup target add x86_64-pc-windows-gnu
fi
WORK="$(mktemp -d "${TMPDIR:-/tmp}/build-desktop-dist.XXXXXX")"
trap 'rm -rf "$WORK"' EXIT
# Linker wrappers for Cargo. rustc passes GCC's runtime libraries; Zig ships LLVM's libunwind
# instead, and its MinGW links its own C runtime (UCRT).
mkdir -p "$WORK/bin"
cat >"$WORK/bin/cc-linux" <<EOF
#!/usr/bin/env bash
args=()
for a in "\$@"; do
case "\$a" in
-lgcc_s) args+=(-lunwind) ;;
*) args+=("\$a") ;;
esac
done
exec zig cc -target x86_64-linux-gnu.$GLIBC "\${args[@]}"
EOF
cat >"$WORK/bin/cc-windows" <<'EOF'
#!/usr/bin/env bash
args=()
for a in "$@"; do
case "$a" in
-lgcc_eh) args+=(-lunwind) ;;
-lgcc_s | -lgcc | -l:libpthread.a | -lpthread | -lmsvcrt) ;;
*) args+=("$a") ;;
esac
done
exec zig cc -target x86_64-windows-gnu "${args[@]}"
EOF
printf '#!/bin/sh\nexec zig dlltool "$@"\n' >"$WORK/bin/dlltool"
chmod +x "$WORK/bin/"*
export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER="$WORK/bin/cc-linux"
export CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER="$WORK/bin/cc-windows"
export CARGO_TARGET_X86_64_PC_WINDOWS_GNU_RUSTFLAGS="-C dlltool=$WORK/bin/dlltool"
LORE_VERSION=$(awk '$1 == "version" { print $2 }' "$ROOT/lore.lock")
LORE_DIR="$("$ROOT/scripts/fetch-lore.sh")" # Lore's licence files
COMMIT=$(git -C "$ROOT" rev-parse --short HEAD 2>/dev/null || echo unknown)
git -C "$ROOT" diff --quiet HEAD -- desktop 2>/dev/null || COMMIT="$COMMIT+changes"
# package NAME ZIG_TARGET RUST_TARGET LORE_TARGET EXE LIBRARY FORMAT
package() {
local name=$1 zig_target=$2 rust_target=$3 lore_target=$4 exe=$5 library=$6 format=$7
local stage="$WORK/$name" lib_dir
say "$name: GUI (zig build -Dtarget=$zig_target)"
(cd "$DESKTOP" && zig build -Dtarget="$zig_target" -Doptimize=ReleaseSafe -Dservice=false \
--prefix "$WORK/gui-$zig_target")
say "$name: service (cargo --target $rust_target)"
cargo build --quiet --release --package forge-service --target "$rust_target" \
--manifest-path "$DESKTOP/Cargo.toml"
say "$name: liblore $LORE_VERSION ($lore_target)"
lib_dir="$(LORE_TARGET="$lore_target" "$ROOT/scripts/fetch-lore.sh" --liblore)"
mkdir -p "$stage"
cp "$WORK/gui-$zig_target/bin/forge-desktop$exe" "$stage/"
cp "$DESKTOP/target/$rust_target/release/forge-service$exe" "$stage/"
cp "$lib_dir/$library" "$stage/"
install -m 644 "$LORE_DIR/LICENSE.txt" "$stage/LORE-LICENSE.txt"
install -m 644 "$LORE_DIR/THIRD-PARTY-NOTICES.txt" "$stage/LORE-THIRD-PARTY-NOTICES.txt"
readme "$name" "$exe" "$library" >"$stage/README.txt"
chmod 644 "$stage/README.txt"
chmod 755 "$stage/forge-desktop$exe" "$stage/forge-service$exe"
case "$format" in
tar.gz) tar -czf "$WORK/$name.tar.gz" -C "$WORK" --owner=0 --group=0 "$name" ;;
zip) (cd "$WORK" && zip -qr -X "$name.zip" "$name") ;;
esac
}
readme() {
local name=$1 exe=$2 library=$3
cat <<EOF
lore-forge desktop client ($name)
Built from lore-forge $COMMIT with Lore $LORE_VERSION on $(date -u +%Y-%m-%d).
forge-desktop$exe the tray application; run this one
forge-service$exe the per-user service it starts; does the Lore work
$library$(printf '%*s' $((16 - ${#library})) '')the Lore library the service loads
Keep the three files together: forge-desktop starts the forge-service beside it, which loads
$library from beside itself.
Run forge-desktop. The service keeps its desktop.toml (the workspaces it syncs) and its
service.log in ~/.config/lore-forge/ on Linux and %APPDATA%\lore-forge\ on Windows.
forge-desktop --licenses prints the licences of what it compiles in. Lore is MIT-licensed:
see LORE-LICENSE.txt and LORE-THIRD-PARTY-NOTICES.txt.
EOF
case "$name" in
*linux*) cat <<'EOF'
Linux: x86-64 with glibc 2.39 or newer (Ubuntu 24.04, Fedora 40 or later) and a Wayland session.
The tray icon needs a StatusNotifier host. This build is experimental: the service has run on
Linux, but the window has not yet been tried there.
EOF
;;
*windows*) cat <<'EOF'
Windows: x86-64, Windows 10 or later. This build is experimental: it is cross-compiled and has
not yet been run on Windows.
EOF
;;
esac
}
package lore-forge-desktop-linux-x86_64 "x86_64-linux-gnu.$GLIBC" x86_64-unknown-linux-gnu \
x86_64-unknown-linux-gnu "" liblore.so tar.gz
package lore-forge-desktop-windows-x86_64 x86_64-windows-gnu x86_64-pc-windows-gnu \
x86_64-pc-windows-msvc .exe lore.dll zip
mkdir -p "$OUT"
(cd "$WORK" && sha256sum lore-forge-desktop-*.tar.gz lore-forge-desktop-*.zip >SHA256SUMS)
echo "lore-forge $COMMIT, Lore $LORE_VERSION, built $(date -u +%Y-%m-%dT%H:%MZ)" >"$WORK/BUILD"
# Replace each file in one rename, so a download in progress never sees half an archive.
for f in lore-forge-desktop-linux-x86_64.tar.gz lore-forge-desktop-windows-x86_64.zip SHA256SUMS BUILD; do
cp "$WORK/$f" "$OUT/.$f.new"
mv -f "$OUT/.$f.new" "$OUT/$f"
done
say "wrote $OUT:"
(cd "$OUT" && ls -l lore-forge-desktop-* SHA256SUMS BUILD >&2 && cat BUILD >&2)

View File

@ -6,6 +6,10 @@
# desktop client's service loads
# scripts/fetch-lore.sh --liblore-to FILE
# fetch liblore, then copy the library to FILE (for zig build)
# LORE_TARGET=x86_64-pc-windows-msvc scripts/fetch-lore.sh --liblore
# liblore for another platform, into .lore/<version>/<target>/
# (for packaging the desktop client; lore and loreserver are
# always this machine's)
# scripts/fetch-lore.sh --pin vX.Y.Z re-pin lore.lock to another release (needs `gh`)
#
# The version and the SHA-256 of every archive are pinned in lore.lock, so a download that does
@ -100,26 +104,30 @@ fetch() {
echo "$dir"
}
# The library's file name in the release archive for this machine.
# The library's file name in the release archive for a platform (default: this machine's).
library_file() {
case "$(uname -s)" in
Darwin) echo liblore.dylib ;;
case "${1:-$(target)}" in
*-windows-*) echo lore.dll ;;
*-apple-darwin) echo liblore.dylib ;;
*) echo liblore.so ;;
esac
}
fetch_liblore() {
[ -f "$LOCK" ] || die "$LOCK is missing"
local version target dir file
local version target dir file ext
version=$(awk '$1 == "version" { print $2 }' "$LOCK")
target=$(target)
target=${LORE_TARGET:-$(target)}
dir="$ROOT/.lore/$version"
file=$(library_file)
# Another platform's library goes beside this machine's, not over it.
[ -z "${LORE_TARGET:-}" ] || [ "$LORE_TARGET" = "$(target)" ] || dir="$dir/$target"
file=$(library_file "$target")
if [ -f "$dir/$file" ] && [ -f "$dir/lore.h" ]; then
echo "$dir"
return
fi
local archive="liblore-$version-$target.tar.gz" expected actual
case "$target" in *-windows-*) ext=zip ;; *) ext=tar.gz ;; esac
local archive="liblore-$version-$target.$ext" expected actual
expected=$(awk -v a="$archive" '$1 == "sha256" && $2 == a { print $3 }' "$LOCK")
[ -n "$expected" ] || die "$LOCK pins no $archive; re-pin with --pin $version"
WORK_DIR=$(mktemp -d "${TMPDIR:-/tmp}/fetch-lore.XXXXXX")
@ -129,7 +137,12 @@ fetch_liblore() {
actual=$(sha256 "$WORK_DIR/$archive")
[ "$actual" = "$expected" ] || die "$archive has SHA-256 $actual, but lore.lock pins $expected"
mkdir -p "$WORK_DIR/lib"
if [ "$ext" = zip ]; then
command -v unzip >/dev/null || die "unpacking $archive needs unzip"
unzip -q "$WORK_DIR/$archive" -d "$WORK_DIR/lib"
else
tar -xzf "$WORK_DIR/$archive" -C "$WORK_DIR/lib"
fi
[ -f "$WORK_DIR/lib/$file" ] && [ -f "$WORK_DIR/lib/lore.h" ] || die "$archive holds no $file and lore.h"
mkdir -p "$dir"
cp "$WORK_DIR/lib/$file" "$WORK_DIR/lib/lore.h" "$dir/"

View File

@ -11,6 +11,7 @@
# run/lore-config/ the loreserver configuration this script generates on every start
# run/lore-store/ loreserver's repository storage
# run/logs/ both processes' logs
# run/downloads/ desktop client archives offered at /download (scripts/build-desktop-dist.sh)
#
# Needs Rust and protoc to build lore-forge, and curl and tar to fetch Lore. Ctrl-C stops both.
@ -52,6 +53,10 @@ LORE_REMOTE=lore://localhost:41337
# real deployment on Linux, see deploy/README.md instead of this script.
LORE_TLS_CERT=
LORE_TLS_KEY=
# 1 when a proxy in front ends TLS on TCP 41337 and forwards gRPC to loreserver over a private
# link: the certificate above then serves QUIC only, and gRPC stays plaintext behind the proxy.
LORE_GRPC_TLS_AT_PROXY=
EOF
say "wrote $ENV_FILE with local defaults"
fi
@ -77,12 +82,20 @@ export LORE_FORGE_PUBLIC_URL="$PUBLIC_URL"
export LORE_FORGE_LORE_URL="$LORE_URL"
export LORE_FORGE_DATA_DIR="$RUN/forge-data"
export LORE_FORGE_LORE_REMOTE="$LORE_REMOTE"
# Desktop client archives for /download, from scripts/build-desktop-dist.sh.
export LORE_FORGE_DOWNLOADS_DIR="$RUN/downloads"
TLS_ARGS=()
if [ -n "${LORE_TLS_CERT:-}" ]; then
TLS_ARGS=(--tls-cert "$LORE_TLS_CERT" --tls-key "${LORE_TLS_KEY:?set LORE_TLS_KEY beside LORE_TLS_CERT}")
if [ "${LORE_GRPC_TLS_AT_PROXY:-}" = 1 ]; then
# A proxy ends gRPC's TLS, so loreserver's gRPC stays plaintext and lore-forge reads it
# here, at the default http://127.0.0.1:41337.
TLS_ARGS+=(--grpc-tls-at-proxy)
else
# With a certificate gRPC is TLS too, reached by the name the certificate is for.
REMOTE_HOST="${LORE_REMOTE#*://}"
export LORE_FORGE_LORE_GRPC_URL="https://${REMOTE_HOST%%/*}"
fi
fi
FORGE_PID=""

42
shell.nix Normal file
View File

@ -0,0 +1,42 @@
{
pkgs ? import <nixpkgs> { },
}:
let
fhsEnv = pkgs.buildFHSEnv {
name = "kilo-fhs";
targetPkgs =
pkgs: with pkgs; [
nodejs_20
stdenv.cc.cc.lib
zlib
git-lfs
fzf
cloc
tinycc
gleam
erlang
# Wayland development
wayland
wayland.dev
wayland-protocols
nmap
wayland-scanner
pkg-config
libxkbcommon
clang
# lore-forge: Rust (rustup uses the toolchains in ~/.rustup; default stable),
# protoc for Lore's user.proto, sqlite3 for inspecting run/forge-data,
# openssl for run/pull-tls.sh's certificate checks, zip and unzip for
# scripts/build-desktop-dist.sh.
rustup
protobuf
sqlite
openssl
zip
unzip
];
runScript = "bash";
};
in
fhsEnv.env