Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions docs/lld/17-preview-pane.md
Original file line number Diff line number Diff line change
Expand Up @@ -339,3 +339,15 @@ An admin's REPL listens on the machine's real network, where the site itself is,
A server that the Genie agent starts with its `bash` action does not survive that action (the shell and everything it started are killed when the call ends: its description says to use `terminal_type` for a program that must keep running). The Preview of such a program says "Nothing is listening" or "Your program has stopped" because it is gone.

**The registry names a home by its directory name (2026-11-23).** `SessionRegistry` keeps the home as `donadjdc` (`Config.HomeOf`), while the Preview's token and the route table carry the path `/home/openrepl/donadjdc`. The first version of `homeBackend` asked the registry for the path only, so it never found the session and fell back to the stale route: the Preview still went to the worker after the session moved back to the gateway (reproduced on a local gateway and worker: the worker answered `no process of donadjdc was found`). It now asks for the path and for its base name. The test uses the registry's real naming and fails without the fix.

## The preview host (2026-11-23)

`SiteSettings.PreviewBaseURL` (Site settings > Workspaces > Preview, "Preview base URL"; a host name such as `preview.openrepl.com` (kept as typed and sent to the page as typed; a host name alone takes the scheme and the port of the site the page was opened from, in `previewBase()`; the server derives a scheme only to compare host names) with no path, checked by `cleanPreviewBaseURL`, read as an origin by `previewBaseURL()`, and refused when its host name equals the one of `OPENREPL_PUBLIC_URL` (host names are compared, never scheme or port, so a local test uses `preview.localhost:<port>`); empty by default) moves the frames of the Preview to an origin of their own: `https://preview.openrepl.com/<token>/f/index.html` and `https://preview.openrepl.com/<token>/p/<port>/...` instead of `https://openrepl.com/preview/<token>/...`. Empty keeps every address as it was.

- **A thin layer over the routes that exist** (`server/previewhost.go`, `Server.wrapPreviewHost`, the outermost handler of the site, of the gateway and of a worker): on a request whose Host is the preview host the path is turned into the site's own form (`/preview/<token>/...`) and the request is marked (`gateway.MarkPreviewHost`). The token, the storage (`/s`), the libraries (`/preview/lib/...`), the programs (`/p/<port>`) and the routing to the worker that runs the workspace are the ones of the site. Nothing of the site is reachable on that host: whatever the path, it ends below `/preview/` (a path that is no token is "the preview ended", 410), and the root is 404. `/preview/<token>/...` is accepted on the host too; the site's own `/preview/<token>/...` is unchanged (old links, a worker's own port).
- **The form follows the request,** not a global flag (the same server answers both): `previewPath` makes the prefix a program's links are rewritten to and the storage URL (`/<token>/p/<port>`, `/<token>/s` on the host), `publicPath` the redirect that adds the trailing slash.
- **Gateway and workers:** the gateway forwards the request in the site's form with a trusted header (`X-Openrepl-Preview-Host: 1`, `trusted.HeaderPreviewHost`, set in `RemoteBackend.direct`, stripped from every client request); a worker believes it only on a request that came over the tunnel (`onPreviewHost`). The value of the setting reaches the workers in `WorkerConfig.PreviewBaseURL` like the other site rules.
- **The page** (`js/src/page/27-preview.js`): the history of a tab keeps the site's form; `pub()` makes the address a frame opens (`frame.src`), `popUrl()` the one of "open in a tab" and "copy address", `pathOf()` brings an address the frame reports back to the site's form. `window.site_settings.previewBaseURL` comes from `settings.js` (`SiteSettings.public()`).
- **To use it:** point the host's DNS at the OpenREPL server, give it a certificate, and keep the Host header on the way (a proxy such as Cloudflare must pass it). The frames are sandboxed without cookies and without the site's origin, so the host adds isolation and takes nothing from the site's cookies.
- **Tests:** `server/previewhost_test.go` (host compare, the layer, both forms, the file route on both hosts), `server/preview_base_url_test.go`, `server/worker_config_test.go`, `gateway/previewhost_test.go`, `js/test/preview-host.test.mjs`. Not run: a browser test of the pane on a real second host.
- **Not covered:** a Genie agent step that builds a Preview address itself (none was found in the code); the site's own CSP, if one is set in front (Cloudflare), must allow the preview origin in a frame.
22 changes: 22 additions & 0 deletions src/gateway/previewhost.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package gateway

import (
"context"
"net/http"
)

// A Preview request that arrived on the preview host (SiteSettings.PreviewBaseURL: /<token>/... there). The server rewrites its path to the site's own form
// (/preview/<token>/...) before it routes it; this mark says it came by the host, so that the addresses a program's pages are rewritten to, and a
// worker (which gets the mark as a trusted header), stay in the host's form.
type previewHostKey struct{}

// MarkPreviewHost marks r as a request of the preview host.
func MarkPreviewHost(r *http.Request) *http.Request {
return r.WithContext(context.WithValue(r.Context(), previewHostKey{}, true))
}

// IsPreviewHost says whether r arrived on the preview host.
func IsPreviewHost(r *http.Request) bool {
v, _ := r.Context().Value(previewHostKey{}).(bool)
return v
}
27 changes: 27 additions & 0 deletions src/gateway/previewhost_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package gateway

import (
"net/http/httptest"
"testing"

"trusted"
)

// A worker gets the mark of the preview host only from the gateway: the header a client sent is dropped, the mark of the request is forwarded
func TestTheMarkOfThePreviewHostReachesAWorkerAndAClientsCopyDoesNot(t *testing.T) {
b := &RemoteBackend{cfg: RemoteConfig{ID: "w1"}}
forged := httptest.NewRequest("GET", "/preview/T/f/x", nil)
forged.Header.Set(trusted.HeaderPreviewHost, "1")
b.direct(forged)
if forged.Header.Get(trusted.HeaderPreviewHost) != "" {
t.Error("a client's copy of the header reached the worker")
}
marked := MarkPreviewHost(httptest.NewRequest("GET", "/preview/T/f/x", nil))
b.direct(marked)
if marked.Header.Get(trusted.HeaderPreviewHost) != "1" {
t.Error("the mark did not reach the worker")
}
if IsPreviewHost(httptest.NewRequest("GET", "/", nil)) {
t.Error("an unmarked request is not of the preview host")
}
}
3 changes: 3 additions & 0 deletions src/gateway/remote.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ func (b *RemoteBackend) direct(req *http.Request) {
if id, ok := req.Context().Value(identityKey{}).(trusted.Identity); ok {
trusted.Set(req.Header, id)
}
if IsPreviewHost(req) {
req.Header.Set(trusted.HeaderPreviewHost, "1")
}
if _, ok := req.Header["User-Agent"]; !ok {
req.Header.Set("User-Agent", "") // do not add Go's default
}
Expand Down
48 changes: 34 additions & 14 deletions src/js/src/page/27-preview.js
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,27 @@ function describe(p) {
if (m) return "127.0.0.1:" + m[1] + (m[2] && m[2] !== "/" ? m[2] : "");
return p;
}
function pathOf(href) { try { var u = new URL(href, location.href); return u.pathname + u.search + u.hash; } catch (e) { return href; } }
// The preview host (docs/lld/17-preview-pane.md "The preview host"): when the admin set SiteSettings.PreviewBaseURL the frames and the tabs of the
// Preview open there, as <base>/<token>/f/<path>, not as this site's /preview/<token>/f/<path>. The history of a tab keeps the site's form, so
// that nothing else here has to know: pub() makes the address a frame or a tab opens, and pathOf() brings a reported address back.
function previewBase() {
var b = window.site_settings && window.site_settings.previewBaseURL;
if (typeof b !== "string") return "";
b = b.trim().replace(/\/+$/, "");
if (!b) return "";
// as typed: a host name alone takes the scheme and the port of the page (preview.localhost on http://localhost:8080 is http://preview.localhost:8080)
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(b)) b = location.protocol + "//" + b + (location.port && !/(:\d+|\])$/.test(b) ? ":" + location.port : "");
return b;
}
function pub(p) { var b = previewBase(); return b ? b + p.replace(/^\/preview\//, "/") : p; }
function popUrl(p) { var b = previewBase(); return b ? pub(p) : location.origin + p; }
function pathOf(href) {
try {
var u = new URL(href, location.href), b = previewBase(), path = u.pathname;
if (b && u.hostname === new URL(b).hostname && !/^\/preview\//.test(path)) path = "/preview" + path;
return path + u.search + u.hash;
} catch (e) { return href; }
}
function renew(p) { return token ? p.replace(/^\/preview\/[^/]+\//, "/preview/" + token.value + "/") : p; }

// ---- tabs, history, the status line ---------------------------------------------------------------------------------
Expand Down Expand Up @@ -302,7 +322,7 @@ function selectTab(k) {
var frame = frameFor(target);
frame.setAttribute("data-url", "");
if (target.kind === "n") { load(); hideError(); render(); focusAddress(); return; }
if (tb.hist.length) { navTo = renew(tb.hist[tb.idx]); frame.setAttribute("data-url", navTo); setStatus("loading"); frame.src = navTo; } else load();
if (tb.hist.length) { navTo = renew(tb.hist[tb.idx]); frame.setAttribute("data-url", navTo); setStatus("loading"); frame.src = pub(navTo); } else load();
hideError(); render();
}

Expand All @@ -312,7 +332,7 @@ function closeTab(k) {
var was = k === cur;
cur = Math.min(cur > k ? cur - 1 : cur, tabs.length - 1);
target = tabs[cur].t;
if (was) { var tb = tabs[cur]; if (tb.hist.length) { navTo = renew(tb.hist[tb.idx]); var f = frameFor(target); f.setAttribute("data-url", navTo); f.src = navTo; } else load(); }
if (was) { var tb = tabs[cur]; if (tb.hist.length) { navTo = renew(tb.hist[tb.idx]); var f = frameFor(target); f.setAttribute("data-url", navTo); f.src = pub(navTo); } else load(); }
render();
}

Expand Down Expand Up @@ -648,8 +668,8 @@ function navigateTo(t) {
tb.hist = tb.hist.slice(0, tb.idx + 1); tb.hist.push(url); tb.idx = tb.hist.length - 1;
navTo = url;
frame.setAttribute("data-url", url);
frame.src = url;
if (popout && !popout.closed) { try { popout.location.href = location.origin + url; } catch (e) {} }
frame.src = pub(url);
if (popout && !popout.closed) { try { popout.location.href = popUrl(url); } catch (e) {} }
render();
}, function (e) {
message("<strong>The preview is not available.</strong><br>" + esc(e && e.message ? e.message : e), null);
Expand Down Expand Up @@ -739,7 +759,7 @@ function goHist(tb) {
navTo = renew(tb.hist[tb.idx]);
frame.setAttribute("data-url", navTo);
setStatus("loading"); hideError(); clearLogs();
frame.src = navTo;
frame.src = pub(navTo);
setAddress(describe(navTo)); render();
}

Expand All @@ -759,7 +779,7 @@ function toggleMenu(force) {

function copyAddress() {
var tb = tab();
var url = tb && tb.hist.length ? location.origin + renew(tb.hist[tb.idx]) : "";
var url = tb && tb.hist.length ? popUrl(renew(tb.hist[tb.idx])) : "";
var done = function () { if (window.notify) window.notify("Address copied.", { type: "success" }); };
if (!url) return;
if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(url).then(done, function () {});
Expand All @@ -769,7 +789,7 @@ function popOut() {
if (!target || target.kind === "n") return;
getToken().then(function (tok) {
var tb = tab();
var url = location.origin + (tb && tb.hist.length ? renew(tb.hist[tb.idx]) : urlFor(target, tok));
var url = popUrl(tb && tb.hist.length ? renew(tb.hist[tb.idx]) : urlFor(target, tok));
popout = window.open(url, "openrepl-preview", "popup=yes,width=1000,height=720");
if (!popout) { message("<strong>The window was blocked.</strong><br>Allow pop-ups for this site, then try again.", null); return; }
var frame = frameFor(target); frame.removeAttribute("src");
Expand Down Expand Up @@ -821,8 +841,8 @@ function load() {
var url = urlFor(target, tok);
navTo = "";
frame.setAttribute("data-url", url);
frame.src = url;
if (popout && !popout.closed) { try { popout.location.href = location.origin + url; } catch (e) {} }
frame.src = pub(url);
if (popout && !popout.closed) { try { popout.location.href = popUrl(url); } catch (e) {} }
}, function (e) {
message("<strong>The preview is not available.</strong><br>" + esc(e && e.message ? e.message : e), null);
});
Expand Down Expand Up @@ -855,8 +875,8 @@ function reload() {
var tb = tab();
if (tb && tb.hist.length) { url = renew(tb.hist[tb.idx]); navTo = url; frame.setAttribute("data-url", url); } // the page now shown, not the first one
setStatus("loading"); hideError(); clearLogs();
if (popout && !popout.closed) { try { popout.location.href = location.origin + url; } catch (e) {} }
frame.src = url; // the same address again reloads the page
if (popout && !popout.closed) { try { popout.location.href = popUrl(url); } catch (e) {} }
frame.src = pub(url); // the same address again reloads the page
}

function syncButton() {
Expand Down Expand Up @@ -925,7 +945,7 @@ function show(t) {
placePane();
setAddress();
applySize();
if (target) { var tb = tab(); if (tb && tb.hist.length && !t.sub) { var f = frameFor(target); navTo = renew(tb.hist[tb.idx]); f.setAttribute("data-url", navTo); setStatus("loading"); f.src = navTo; setAddress(describe(navTo)); } else load(); }
if (target) { var tb = tab(); if (tb && tb.hist.length && !t.sub) { var f = frameFor(target); navTo = renew(tb.hist[tb.idx]); f.setAttribute("data-url", navTo); setStatus("loading"); f.src = pub(navTo); setAddress(describe(navTo)); } else load(); }
else { message("<strong>Nothing to show yet.</strong><br>Run a program that listens on a port, or open an .html or Markdown file, a picture or a PDF.", null); setStatus("message"); }
render();
mobileTab(true);
Expand Down Expand Up @@ -993,7 +1013,7 @@ function init() {
el("preview-close").addEventListener("click", closePane);
el("preview-newtab").addEventListener("click", function () {
if (!target || target.kind === "n") return;
getToken().then(function (tok) { window.open(urlFor(target, tok), "_blank", "noopener"); });
getToken().then(function (tok) { window.open(popUrl(urlFor(target, tok)), "_blank", "noopener"); });
});
window.addEventListener("resize", function () { if (open) applySize(); });
var mt = el("mobile-view-terminal");
Expand Down
68 changes: 68 additions & 0 deletions src/js/test/preview-host.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// The addresses of the Preview with a preview host (js/src/page/27-preview.js, docs/lld/17-preview-pane.md "The preview host"): the history of a tab keeps
// the site's form (/preview/<token>/...), pub() makes the address a frame or a tab opens, and pathOf() brings an address the frame reports back.
// The four small functions are taken out of the page script and run with a pretend page.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import vm from "node:vm";
import path from "node:path";
import { fileURLToPath } from "node:url";

const here = path.dirname(fileURLToPath(import.meta.url));
const source = fs.readFileSync(path.join(here, "..", "src", "page", "27-preview.js"), "utf8");

function fn(name) {
const start = source.indexOf("function " + name + "(");
assert.ok(start >= 0, name + " is not in the page script");
let depth = 0, i = source.indexOf("{", start);
for (let j = i; j < source.length; j++) {
if (source[j] === "{") depth++;
if (source[j] === "}" && --depth === 0) return source.slice(start, j + 1);
}
throw new Error("no end of " + name);
}

function page(base, loc = { protocol: "https:", host: "openrepl.test", port: "" }) {
const ctx = { window: { site_settings: base === undefined ? {} : { previewBaseURL: base } }, location: { origin: loc.protocol + "//" + loc.host, href: loc.protocol + "//" + loc.host + "/", protocol: loc.protocol, port: loc.port }, URL };
vm.createContext(ctx);
vm.runInContext(["previewBase", "pub", "popUrl", "pathOf"].map(fn).join("\n"), ctx);
return ctx;
}

test("without a preview host the addresses are the site's own, as before", () => {
for (const base of [undefined, "", null]) {
const p = page(base);
assert.equal(p.pub("/preview/T/f/index.html"), "/preview/T/f/index.html");
assert.equal(p.popUrl("/preview/T/p/8000/"), "https://openrepl.test/preview/T/p/8000/");
assert.equal(p.pathOf("https://openrepl.test/preview/T/f/a.html?x=1#h"), "/preview/T/f/a.html?x=1#h");
}
});

test("with a preview host a frame opens <base>/<token>/..., without /preview", () => {
const p = page("https://preview.example.test");
assert.equal(p.pub("/preview/T/f/index.html"), "https://preview.example.test/T/f/index.html");
assert.equal(p.pub("/preview/T/p/8000/x?y=1"), "https://preview.example.test/T/p/8000/x?y=1");
assert.equal(p.popUrl("/preview/T/f/index.html"), "https://preview.example.test/T/f/index.html");
// a trailing slash of the setting is no double slash
assert.equal(page("https://preview.example.test/").pub("/preview/T/f/a.html"), "https://preview.example.test/T/f/a.html");
});

test("an address the frame reports on the preview host is brought back to the site's form, the history keeps one form", () => {
const p = page("https://preview.example.test");
assert.equal(p.pathOf("https://preview.example.test/T/f/a.html?render=md#top"), "/preview/T/f/a.html?render=md#top");
assert.equal(p.pathOf("https://preview.example.test/T/p/8000/"), "/preview/T/p/8000/");
// already in the site's form (the host accepts it too), or from the site itself
assert.equal(p.pathOf("https://preview.example.test/preview/T/f/a.html"), "/preview/T/f/a.html");
assert.equal(p.pathOf("https://openrepl.test/preview/T/f/a.html"), "/preview/T/f/a.html");
assert.equal(p.pathOf("/preview/T/f/b.html"), "/preview/T/f/b.html");
// the host name is compared, not the scheme or the port
assert.equal(p.pathOf("http://preview.example.test:8080/T/f/a.html"), "/preview/T/f/a.html");
});

test("a host name alone takes the scheme and the port of the page; one with a scheme is used as typed", () => {
const local = { protocol: "http:", host: "localhost:8080", port: "8080" };
assert.equal(page("preview.localhost", local).pub("/preview/T/f/index.html"), "http://preview.localhost:8080/T/f/index.html");
assert.equal(page("preview.localhost:9000", local).pub("/preview/T/f/index.html"), "http://preview.localhost:9000/T/f/index.html");
assert.equal(page("https://preview.example.test", local).pub("/preview/T/f/a.html"), "https://preview.example.test/T/f/a.html");
assert.equal(page("preview.example.test").pub("/preview/T/f/a.html"), "https://preview.example.test/T/f/a.html");
});
Loading
Loading