Repository navigation
Deploy STomp
This page is the checklist for putting STomp on the public internet. It assumes you already have a host page that works locally (see Bootstrapper quickstart and Install into an existing app). Every config on this page was run: the nginx and Caddy files below served the host page and the proxy to a headless Chrome 157, which loaded a site through them.
In the examples, app.example.com and proxy.example.com stand for your own two hostnames. Replace them everywhere, including inside the Content-Security-Policy strings.
- Serve everything over HTTPS, and the wisp relay over
wss://. (HTTPS) - Put the host application and the proxy on two origins of one site, use
RemoteController, and lock the controller frame to your host. (Two origins on one site) - If proxied pages need
SharedArrayBuffer, send COOP and COEP on the host page, and COEP plus CORP on the proxy's files. (Cross-origin isolation headers) - Let
?<hash>asset URLs beimmutable, revalidate everything else, and never cacheserviceWorker.jsat a CDN. (Caching) - If you rename the files of
dist/, put the names in oneassetsobject and pass it toregister()and the controller. (Serve dist/ under your own names) - Handle
staleandrebindin the host page, and keepdirectoryandcodecthe same from one deploy to the next. (Rolling out an update) - Give the host page a Content-Security-Policy that allows the proxy origin as a script and frame source, and send no policy on the proxy's own files. (The host page's CSP)
- Forward the WebSocket upgrade on
/wisp/and raise the proxy's idle timeout. (Reverse proxy configs)
A service worker registers only in a secure context. On plain http: (other than localhost, 127.0.0.1 and *.localhost) the browser has no navigator.serviceWorker: StompController.register() rejects and the constructor throws, both with Your browser does not support service workers. Nothing of STomp runs.
The wisp URL must be wss:// too. A page on https: may not open a ws:// WebSocket (mixed content), and the transport worker is held to the same rule. If you derive the URL from the page, as the examples in this wiki do, location.protocol gives you the right scheme.
The site pool and Wisp over WebTransport also need a secure context. Without one they turn themselves off.
StompController runs the proxy on the host page's own origin, so a proxied page is same-origin with your page. The rewriter hides the host from the page's scripts, but that is not a security boundary: a script the rewriter cannot parse runs as it was, and can reach the real top. Same-origin mode is for development. See Origin isolation for the model.
For production, serve the host application from one origin and the proxy from another:
| Origin | Serves |
|---|---|
app.example.com |
your host page and its scripts |
proxy.example.com |
dist/ of @sysce/stomp at /stomp/ (the path stompPath names), the transport at /epoxy/, the wisp relay at /wisp/
|
The host page creates a RemoteController with proxyOrigin: 'https://proxy.example.com'. It embeds /stomp/controllerFrame.html from the proxy origin, and that frame registers the service worker, loads the transport and runs the real controller. The transport module must be on the proxy origin: a descriptor whose module resolves anywhere else is refused with Transport modules must live on the proxy origin.
The two hostnames must share a registrable domain. app.example.com and proxy.example.com are one site. These pairs are two sites:
-
localhostand127.0.0.1 -
example.comandexample-proxy.net - two subdomains of a public suffix, such as
you.github.ioandproxy.github.io(github.iois on the public suffix list)
The reason is third-party storage blocking. Brave and incognito windows block third-party cookies by default, and Chrome has a setting for it. A browser that does gives a frame of another site no service worker and no storage, so the controller frame cannot register. RemoteController.wait() then rejects with an error named StorageBlockedError. On one site, the proxy's frame is not third-party and this does not happen.
Your certificate has to cover both names: a wildcard for *.example.com, or one certificate with both names in it.
dist/controllerFrame.html trusts whichever page embeds it. Its <meta name="stomp-allowed-origins" content=""> is empty in the package, and an empty list means "the origin in document.referrer". Left like that, any site can embed your proxy origin's controller frame and browse through your relay.
Do one of these:
- Send
Content-Security-Policy: frame-ancestors https://app.example.comon/stomp/controllerFrame.html. The browser then refuses to show the frame anywhere else. The nginx and Caddy configs below do this, and you do not have to edit the package. - Edit the meta in your copy of
controllerFrame.htmlto list the host origins, separated by spaces. Redo it after every upgrade.
The proxied documents are covered already: the service worker sends frame-ancestors with your host's origin on each of them.
The controller frame learns its host from document.referrer, even when the meta lists origins. If the host page sends Referrer-Policy: no-referrer, the frame gets an empty referrer, never starts, and RemoteController.wait() never settles. same-origin sends no referrer to another origin and fails the same way. The browser default (strict-origin-when-cross-origin) works, as do origin and strict-origin, which all send the host's origin.
A relay that accepts every page is an open proxy for anyone who finds the URL. If you run holyWisp, list your proxy origin in allowedOrigins (the binary's allow-origin flag): the transport runs in a worker on the proxy origin, so that is the Origin its WebSocket sends. The wisp server example does this, and an upgrade with another Origin gets 403 Forbidden.
This part is optional. A proxied page can be cross-origin isolated (crossOriginIsolated, SharedArrayBuffer, the precise clock) only when your host page is. Without the headers below STomp runs the same way, and no proxied page is isolated. With them, STomp reads crossOriginIsolated of your page at run time and isolates exactly the proxied pages whose own headers would isolate them natively. There is no option to set.
| Response | Headers | Why |
|---|---|---|
| the host page |
Cross-Origin-Opener-Policy: same-origin, Cross-Origin-Embedder-Policy: require-corp
|
makes the page isolated |
every file of dist/ and of the transport |
Cross-Origin-Embedder-Policy: require-corp |
the controller starts its transport and rewrite workers from these files, and a worker of an isolated page starts only when its script has an embedder policy |
the same files, with RemoteController
|
Cross-Origin-Resource-Policy: cross-origin |
an isolated page loads a frame or script of another origin only with this header: without it controllerFrame.html and Controller.js are blocked and nothing runs |
Use require-corp, not credentialless. WebKit (Safari, and every browser on iOS) has no credentialless, and a page that sends it is not isolated there, so no proxied page would be either.
What it costs:
- Everything your host page loads from another origin must send
Cross-Origin-Resource-Policy(or be loaded with CORS). An image from a CDN that does not send it stops loading. - With
RemoteControllerand an isolated host, Chrome gives a proxied frame no window for a popup it opens:window.openreturnsnulland the popup has no opener. PassonOpento the controller and open popups as tabs of your own. See Embed STomp in your site.
To check, open the host page and run crossOriginIsolated in the console. If it is false in production but true locally, something in front of your server drops the headers. With nginx, the usual cause is a location that has an add_header of its own: nginx then drops every add_header of the enclosing server block for that location. The config below repeats the headers in each location for that reason.
docs/same-origin-policy.md has the measurements behind this section.
STomp asks for most of its own files by the hash of their bytes: rewriterLib.js?e6a00ad7272175f0, controllerFrame.html?<hash>&script=controllerFrame.js%3F<hash>. The hash is the first 16 hex digits of the file's SHA-256 (you can check one with sha256sum dist/rewriterLib.js | cut -c1-16), baked into the bundles at build time. One such URL names one file, so it can be kept for good.
| What | Cache-Control |
|---|---|
a URL whose query starts with 16 hex digits: rewriterLib.js, core.wasm, injectDocument.js, injectDocumentFull.js, transportWorker.js, rewriteWorker.js, blocker.wasm, controllerFrame.html and its script, siteFrame.js
|
public, max-age=31536000, immutable |
serviceWorker.js |
no-cache |
every other file of dist/, the transport, the host page |
no-cache |
The service worker script is the one file that must never be served stale. A browser checks it on every registration and every navigation in its scope, and STomp registers it with updateViaCache: 'none' (the default of StompController.register(), and what the controller frame uses), so the browser's HTTP cache is bypassed for it. A CDN in between is not bypassed. If your CDN keeps serviceWorker.js for an hour, your users keep the old proxy for an hour. Behind Cloudflare, check the zone's Browser Cache TTL: it overrides your origin's headers unless a cache rule for the host says to respect them.
no-cache does not mean "not cached": the browser keeps the file and revalidates it with its ETag, which costs one round trip and usually a 304.
The configs below mark any ?<16 hex> URL immutable without checking that the hash is the file's own. That has one edge: during a rollout, a tab still on the old build asks for the old hash and gets the new file, which its browser then keeps under the old URL for a year. This hurts only if you later roll back to that exact build. If you want to rule it out, answer immutable only when the hash matches the file, as askedByHash in demo/server.js does. Either way, replace dist/ in one step (copy the new build next to the old one and rename, or switch a symlink), so no request is answered from a half-copied directory.
Two MIME types need care:
-
.mjsmust be served as JavaScript. nginx's stockmime.typeshas no entry for it and sendsapplication/octet-stream, which the browser refuses for a module script. The nginx config below adds the type. Caddy gets it right. -
.wasmshould beapplication/wasm. STomp falls back to a slower compile when it is not, and epoxy logs a warning.
You can serve the files of dist/ under names of your own: a build stamp in each name, so every file can be cached for good, or neutral names, so no URL your users' browsers request carries STomp's file names. Tell STomp the names with one object, keyed like init.assets, and pass that object everywhere a name is read:
const directory = '/static/';
const assets = {
serviceWorker: 'sw.js',
rewriterLib: 'rl.7f3a.js',
core: 'c.7f3a.wasm',
transportWorker: 'tw.7f3a.js',
omnibox: 'ob.7f3a.js',
};
const name = (key) => assets[key] || StompController.DEFAULT_ASSETS[key];
const registration = await StompController.register(directory, { assets });
const controller = new StompController({ serviceworker: registration, transport, directory, assets });-
register()readsassets.serviceWorker.RemoteControllertakesassetstoo and hands it to its controller frame, which registers the worker under that name. - A key you leave out keeps its dist name.
StompController.DEFAULT_ASSETSis the table of those names, and the one way to read them from the classicController.js. - Your page loads some files itself: the controller bundle (
controller.mjsorController.js),SearchBuilder.jsand the omnibox module. STomp never requests them, so name them in your page. The omnibox has the keyomniboxso that its name can live in the same object:
const script = document.createElement('script');
script.src = directory + name('omnibox');
document.head.append(script); // defines the Omnibox globalSTomp still asks for the files in the immutable row of Caching as <your name>?<hash>, so the same rule works under your names. With a build stamp in every other name, those files can be immutable too, except the service worker.
Keep serviceWorker one name from build to build, and serve it no-cache. The browser keeps the worker's script URL in the registration, and a register() call with another name starts an update to the script under that name. With a new name per build, a page that registers the old name after the deploy (an old copy of your host page cached somewhere) puts the old worker back.
The demo's UI, demo/public/pm/main.js, takes its names from globalThis.STOMP_ASSETS. A host that vendors the demo sets it in a script that runs before main.js:
<script>
globalThis.STOMP_ASSETS = { serviceWorker: 'sw.js', rewriterLib: 'rl.7f3a.js', omnibox: 'ob.7f3a.js' };
</script>
<script src="/pm/main.js"></script>main.js passes the object as assets to both controllers, registers the service worker in same-origin mode as /stomp/ plus its serviceWorker name, and uses StompController.DEFAULT_ASSETS for every key the object lacks. The <script> tags in demo/public/index.html that load Controller.js, SearchBuilder.js and omnibox.js name their files themselves, so rename them there. The omnibox's tag is <script src="/stomp/omnibox.js" defer data-omnibox>. main.js waits for it, and when the page has no such tag or the tag fails to load, it loads the omnibox by its STOMP_ASSETS name instead.
Pin the exact version of @sysce/stomp you tested (for example npm install --save-exact @sysce/stomp@4.2.0-nightly.202611192242.ge5f74c5, never a range or the bare nightly tag), and deploy dist/ and the transport together. dist/build.json and controller.build tell you which build is live.
The service worker calls skipWaiting() on install and clients.claim() on activate, so a new worker takes over as soon as it is installed. Every bundle carries its build, and the controller compares its own with the worker's on each handshake. This is what a deploy looks like, measured with an old nightly swapped for a newer one under an open tab:
- A tab opened after the deploy loads the new
Controller.js. If the browser still runs the old worker, the controller logsStomp: the controller is build <new>, the service worker is build <old>; updating the service worker, updates the registration, waits up to 5 seconds for the new worker to activate and binds to it.wait()resolves on the new worker, andstalestaysnull. - A tab that was open during the deploy keeps working on the build it has. Its next proxied navigation makes the browser find the new worker, which takes over. The old controller now talks to a newer worker: it logs
... the new worker has not activated yet, continuing with the old one and switching when it does, setscontroller.staleto{ controller: <old>, worker: <new> }and firesstale. Pages still load. The tab stays stale until it is reloaded, because no worker of the old build is coming back. - When the builds agree again (a worker of the controller's build activates), the controller rebinds on its own and fires
rebindwith{ build }.
Chrome stops the old worker at the moment it activates the new one, and a frame navigation the old worker was handling in that moment is never answered. Before 4.2.0-nightly.202611200512.g041dc67, the frame kept its old document, go() waited out its 30 s, and the first site opened after a deploy stayed on "Loading" until a full reload. From that build on, the controller watches its registration for a newer worker that starts activating, and a go() navigation (on a Frame or a RemoteFrame) that has not reported, fired load or changed document 1 s later is sent again, once, by way of about:blank. The new worker also holds a page's first requests until the controller has shaken hands with it, where before they reached your server, and the old worker keeps a navigation's fetch event open until it has written the document's body, so Chrome does not stop it in the middle of a page. Your page has nothing to do for this.
The proxied pages notice too: an inject bundle of another build than the worker logs Stomp: this inject bundle is build <x> but the service worker is build <y>; hard-reload the page in the page's console.
Listen for stale and rebind, and offer a reload while stale is set:
const showBuild = () => {
$('status').textContent = controller.stale
? `Ready (stale: page ${controller.stale.controller}, worker ${controller.stale.worker}); reload to update`
: 'Ready';
};
controller.addEventListener('stale', showBuild);
controller.addEventListener('rebind', showBuild);This is part of the host page below. Embed STomp in your site covers the events from the host's side.
A routed URL looks like /stomp/<id>/<kind>/<encoded>. Three things in it have to survive a deploy:
- The controller id. Without
init.id, the controller keeps its id in the host origin'slocalStorageand reuses it on the next visit, so a reload, a history entry or a copied link resolves after a deploy as before. The deploy test above kept the same id across the swap and the reload.cookies.clear()without an origin forgets the kept ids. - The codec. A URL encoded with
xordoes not decode with another codec. Changingcodecbreaks every routed URL in your users' history. - The directory. It is the service worker's scope. The cookie jar, the HTTP cache and the storage partitions belong to it, so moving
dist/from/stomp/to another path starts your users over.
When a routed URL names a controller that is gone, the service worker sends a 307 to the same route under the newest live controller with the same codec. If no live controller can take it, the document gets your error page with kind controller (status 410, or 404 when the worker never served that address). If the worker has no live controller at all (no tab of your host is open, and someone opens a copied proxied URL), the request goes past the worker to your server, which answers 404.
With RemoteController, the host page itself does little: it loads Controller.js, runs your script and embeds frames from the proxy origin. The transport, the workers and the wasm all run in the controller frame on the proxy origin, under that origin's headers. This policy was tested with the host page below:
default-src 'self'; script-src 'self' https://proxy.example.com; frame-src https://proxy.example.com; object-src 'none'; base-uri 'none'; frame-ancestors 'none'
-
script-srcincludes the proxy origin because the page loadshttps://proxy.example.com/stomp/Controller.js. If you serve a copy ofController.jsfrom the host origin instead,'self'is enough. -
frame-srcmust allow the proxy origin: the controller frame and every proxied frame come from there. Without it the controller frame is blocked (Framing 'https://proxy.example.com/' violates the following Content Security Policy directive) andwait()never settles. - Keep your scripts in files. The policy has no
'unsafe-inline'. - Add whatever your own page needs:
img-srcfor site icons fromNavigateInfo.icon(those are the sites' real URLs),style-src,connect-srcfor your own APIs.
Do not send a policy on the proxy origin's /stomp/ files, other than frame-ancestors on controllerFrame.html. That file runs an inline script, the service worker compiles WebAssembly, and a script-src there stops both.
If you run StompController on one origin (development, an in-house tool), the host page runs the controller, and its policy needs more. This one was tested with the transport in its worker, with both rewriter: 'js' and rewriter: 'wasm':
default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; frame-src 'self'; worker-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'
'wasm-unsafe-eval' is required whichever rewriter you pick: the controller compiles core.wasm in the page. Without it, wait() rejects with Stomp: the host does not serve the asset 'core', although the file is there; the console line before it names the CSP. worker-src 'self' covers the transport worker and the rewrite workers. If the transport has to run in the page (host: 'page', or after a transporthost event), connect-src must also allow the wisp URL when the relay is on another host, for example wss://holywisp.fracit.al.
Send this policy on the host page only. A server-wide CSP would also land on the files of /stomp/, and a worker takes its policy from its own script's response.
Both configs implement everything above: two origins, isolation headers, caching, the controller frame's frame-ancestors, and the WebSocket upgrade for wisp. They expect:
- your host page in
/var/www/app(the host page below), -
dist/of@sysce/stompin/var/www/stomp(copy the directorystompPathnames,node_modules/@sysce/stomp/dist), -
dist/of the pinned epoxy build in/var/www/epoxy(see Transports and Wisp), - a wisp server on
127.0.0.1:6001(the example below).
If you use the public relay, wss://holywisp.fracit.al/, as your wisp URL, leave out the /wisp/ block and run no wisp server.
Tested with nginx 1.30.7. http2 on needs nginx 1.25.1 or newer. Put the file in the http {} context (for example /etc/nginx/conf.d/stomp.conf); it relies on the stock include mime.types there.
# STomp behind nginx: the host application on app.example.com, the proxy
# (dist/, the transport, wisp) on proxy.example.com. Goes in the http {} block.
# nginx's mime.types has no .mjs: a module script served as
# application/octet-stream does not run
types {
text/javascript mjs;
}
# What STomp asks for by the hash of its bytes (`rewriterLib.js?<hash>`,
# `controllerFrame.html?<hash>&script=...`) may be kept for good; every
# other file is revalidated.
map $args $stomp_cache {
"~^[0-9a-f]{16}(&|$)" "public, max-age=31536000, immutable";
default "no-cache";
}
map $http_upgrade $connection_upgrade {
default upgrade;
"" close;
}
server {
listen 443 ssl;
http2 on;
server_name app.example.com;
ssl_certificate /etc/ssl/example.com/fullchain.pem;
ssl_certificate_key /etc/ssl/example.com/privkey.pem;
root /var/www/app;
add_header Cross-Origin-Opener-Policy "same-origin" always;
add_header Cross-Origin-Embedder-Policy "require-corp" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://proxy.example.com; frame-src https://proxy.example.com; object-src 'none'; base-uri 'none'; frame-ancestors 'none'" always;
add_header Cache-Control "no-cache" always;
}
server {
listen 443 ssl;
http2 on;
server_name proxy.example.com;
ssl_certificate /etc/ssl/example.com/fullchain.pem;
ssl_certificate_key /etc/ssl/example.com/privkey.pem;
# nginx drops every add_header of an outer block in a location that has
# one of its own, so each location below repeats these two
add_header Cross-Origin-Embedder-Policy "require-corp" always;
add_header Cross-Origin-Resource-Policy "cross-origin" always;
# dist/ of @sysce/stomp (stompPath), copied or linked here
location /stomp/ {
alias /var/www/stomp/;
add_header Cross-Origin-Embedder-Policy "require-corp" always;
add_header Cross-Origin-Resource-Policy "cross-origin" always;
add_header Cache-Control $stomp_cache always;
}
# the service worker script is never asked for by a hash: always revalidated
location = /stomp/serviceWorker.js {
alias /var/www/stomp/serviceWorker.js;
add_header Cross-Origin-Embedder-Policy "require-corp" always;
add_header Cross-Origin-Resource-Policy "cross-origin" always;
add_header Cache-Control "no-cache" always;
}
# only the host application may embed the controller frame
location = /stomp/controllerFrame.html {
alias /var/www/stomp/controllerFrame.html;
add_header Cross-Origin-Embedder-Policy "require-corp" always;
add_header Cross-Origin-Resource-Policy "cross-origin" always;
add_header Cache-Control $stomp_cache always;
add_header Content-Security-Policy "frame-ancestors https://app.example.com" always;
}
# a routed script from a document the service worker does not control
# (an about:blank frame a page built): an empty script, not a 404 page
# Chrome refuses for its MIME type
location ~ "^/stomp/[^/]+/js:[^/]+/" {
add_header Cross-Origin-Embedder-Policy "require-corp" always;
add_header Cross-Origin-Resource-Policy "cross-origin" always;
add_header Cache-Control "no-store" always;
default_type "text/javascript";
return 200 "";
}
# the transport (the pinned epoxy build's dist/)
location /epoxy/ {
alias /var/www/epoxy/;
add_header Cross-Origin-Embedder-Policy "require-corp" always;
add_header Cross-Origin-Resource-Policy "cross-origin" always;
add_header Cache-Control "no-cache" always;
}
# the wisp server, a WebSocket
location /wisp/ {
proxy_pass http://127.0.0.1:6001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 1h;
proxy_send_timeout 1h;
proxy_buffering off;
}
location / {
return 404;
}
}Notes on the /wisp/ block:
-
UpgradeandConnectionare hop-by-hop headers, so nginx does not pass them on unless told to. Without these two lines the relay never sees a WebSocket, and every page fails withthe wisp WebSocket closed before the relay spoke(see Troubleshooting). - nginx closes a proxied connection that has carried nothing for
proxy_read_timeout, 60 seconds by default. All proxied traffic rides one wisp WebSocket, so a short timeout cuts it whenever the user stops clicking for a minute. -
X-Forwarded-Fortells the relay who the client is, for its per-client limits. holyWisp believes it only from a proxy listed intrustedProxies.
The js: location is optional. When a page builds an about:blank frame and loads a script into it, Chrome gives that document no service worker, so the script's routed URL reaches nginx. An empty script fails without a console line, where nginx's HTML 404 page would make Chrome log Refused to execute script ... because its MIME type ('text/html') is not executable. demo/server.js does the same.
Tested with Caddy 2.11.4, with tls <cert> <key> added to each site block for the test certificate. With real DNS names, Caddy gets the certificates itself and the file stays as it is.
# STomp behind Caddy: the host application on app.example.com, the proxy
# (dist/, the transport, wisp) on proxy.example.com. Caddy gets the
# certificates itself.
app.example.com {
root * /var/www/app
file_server
header {
Cross-Origin-Opener-Policy "same-origin"
Cross-Origin-Embedder-Policy "require-corp"
Content-Security-Policy "default-src 'self'; script-src 'self' https://proxy.example.com; frame-src https://proxy.example.com; object-src 'none'; base-uri 'none'; frame-ancestors 'none'"
Cache-Control "no-cache"
}
}
proxy.example.com {
header {
Cross-Origin-Embedder-Policy "require-corp"
Cross-Origin-Resource-Policy "cross-origin"
}
# what STomp asks for by the hash of its bytes may be kept for good
@hashed expression {query}.matches("^[0-9a-f]{16}(&|$)")
@fresh not expression {query}.matches("^[0-9a-f]{16}(&|$)")
header @hashed Cache-Control "public, max-age=31536000, immutable"
header @fresh Cache-Control "no-cache"
# only the host application may embed the controller frame
header /stomp/controllerFrame.html Content-Security-Policy "frame-ancestors https://app.example.com"
# a routed script from a document the service worker does not control:
# an empty script, not a 404 page Chrome refuses for its MIME type
@strayScript path_regexp ^/stomp/[^/]+/js:[^/]+/
handle @strayScript {
header Content-Type "text/javascript"
header Cache-Control "no-store"
respond "" 200
}
# dist/ of @sysce/stomp (stompPath)
handle_path /stomp/* {
root * /var/www/stomp
file_server
}
# the transport (the pinned epoxy build's dist/)
handle_path /epoxy/* {
root * /var/www/epoxy
file_server
}
# the wisp server; Caddy passes the WebSocket upgrade on by itself
handle /wisp/* {
reverse_proxy 127.0.0.1:6001
}
handle {
respond 404
}
}Caddy's reverse_proxy forwards WebSocket upgrades and sets X-Forwarded-For without extra lines, and has no idle timeout on an upgraded connection. serviceWorker.js has no query, so the @fresh rule gives it no-cache.
Both configs forward /wisp/ to 127.0.0.1:6001. This is the server that test ran, holyWisp in a small Node process (npm install holywisp):
// A wisp endpoint for nginx or Caddy to forward /wisp/ to: holyWisp behind
// a node:http server on loopback. The reverse proxy terminates TLS and
// passes the WebSocket upgrade on.
import { createServer } from 'node:http';
import { holyWisp } from 'holywisp';
const port = Number(process.env.WISP_PORT) || 6001;
const proxyOrigin = process.env.PROXY_ORIGIN || 'https://proxy.example.com';
const wisp = new holyWisp({
port: 0,
// the reverse proxy on this machine sets X-Forwarded-For
trustedProxies: ['127.0.0.1', '::1'],
// only the proxy origin's transport may connect
allowedOrigins: [proxyOrigin],
});
await wisp.start(1);
const server = createServer((req, res) => res.writeHead(404).end());
server.on('upgrade', (req, socket, head) => {
if (req.url.startsWith('/wisp/')) wisp.route(req, socket, head);
else socket.destroy();
});
server.listen(port, '127.0.0.1', () =>
console.log(`wisp on ws://127.0.0.1:${port}/wisp/`),
);Run it with node wisp.mjs under your process manager. The holyWisp child listens on a free loopback port of its own, and route() hands it each upgrade together with the client's address. Leave allowLoopbackIPs and allowPrivateIPs off in production: they let every visitor reach your machine's own services and your private network through the relay. Transports and Wisp covers holyWisp's other options, running the binary on its own, and wisp-js.
/var/www/app/index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Host</title>
<script src="https://proxy.example.com/stomp/Controller.js"></script>
<script src="/app.js" defer></script>
</head>
<body>
<form id="bar"><input id="address" /><button>Go</button></form>
<div id="status">Starting</div>
<div id="view"></div>
</body>
</html>/var/www/app/app.js:
// The host application's script, on app.example.com. The proxy runs on
// proxy.example.com, which serves dist/ at /stomp/ and epoxy at /epoxy/.
const proxyOrigin = 'https://proxy.example.com';
const $ = (id) => document.getElementById(id);
const controller = new StompRemoteController({
proxyOrigin,
directory: '/stomp/',
// loaded by the controller frame, so the module is on the proxy origin
transport: {
module: '/epoxy/index.mjs',
options: [{ wisp: 'wss://proxy.example.com/wisp/' }],
},
codec: 'xor',
onNavigate(info) {
$('address').value = info.url;
document.title = info.title || 'Host';
},
onOpen(url) {
frame.go(url);
},
});
let frame;
// After a deploy the page's build and the service worker's can differ for a
// while: `stale` says so, `rebind` says they agree again.
const showBuild = () => {
$('status').textContent = controller.stale
? `Ready (stale: page ${controller.stale.controller}, worker ${controller.stale.worker}); reload to update`
: 'Ready';
};
controller.addEventListener('stale', showBuild);
controller.addEventListener('rebind', showBuild);
controller
.wait()
.then(() => {
showBuild();
frame = controller.createFrame();
$('view').replaceWith(frame.element);
$('bar').onsubmit = (event) => {
event.preventDefault();
frame.go($('address').value);
};
window.host = { controller, frame };
})
.catch((error) => {
$('status').textContent = `${error.name}: ${error.message}`;
});Controller.js is the classic-script build; it defines StompRemoteController (and StompController) as globals. Type a full URL (https://example.com/, a real site) and press Enter. Embed STomp in your site turns this into a browser UI with tabs, history buttons and a search box.
The two configs above were run as written, with the hostnames changed to test names and the listen ports changed: nginx 1.30.7 and Caddy 2.11.4 in containers, the wisp server above, @sysce/stomp@4.2.0-nightly.202611192242.ge5f74c5 and the pinned epoxy build, and headless Chrome 157. In both, the host page was cross-origin isolated, wait() resolved, https://example.com/ loaded in the proxied frame, and the console showed no CSP violation. Each was then broken on purpose to confirm the failure modes on this page: no frame-src in the host policy, no CORP on the proxy's files, no CORP on controllerFrame.html alone, Referrer-Policy: no-referrer on the host, and no Upgrade/Connection lines for /wisp/. A deploy from 4.2.0-nightly.202611191632.g15aaeb2 to the newer nightly under an open tab produced the sequence in What happens in the browser.
https://stomp.fracit.al is the repository's demo, demo/server.js, deployed from master by .github/workflows/deploy.yml. It is one Express server under a process manager, behind a reverse proxy that terminates TLS. It is not the layout this page recommends: it runs on one hostname in same-origin mode on purpose (set STOMP_PROXY_ORIGIN to give it a second origin), and it uses the public relay through STOMP_WISP_URL instead of its built-in holyWisp.
On every push to master the workflow:
- Skips if the commit is no longer the head of
master(a newer push supersedes it). - Builds on a GitHub-hosted runner (
npm ci --ignore-scripts,npm run build) and checks thatdist/serviceWorker.jsexists. - On a self-hosted runner that can reach the server, writes the deploy SSH key into the job's temporary directory and connects. The key is pinned on the server to one forced command, a gate script kept in deploy/, which accepts only
deploy <40-hex commit>. The key file is removed when the job ends, however it ends. - The gate, under a lock so deploys run one at a time, refuses the commit if the live checkout has edits or commits that are not on GitHub. Otherwise it fetches the commit into a staging checkout, runs
npm ci --ignore-scriptsandnpm run buildthere, moves the live checkout to the commit, syncsnode_modules/anddist/over, and restarts the app. - It polls the app's
/api/statusfor 30 seconds. If the app does not come up, it rebuilds the previous commit the same way and restarts that. - A last job fetches the public site and
/api/statusfrom outside.
The gate runs as an unprivileged user. The few steps that need root (re-owning the trees, restarting the app, printing its logs) go through a second, root-owned script from the same directory, which sudo allows with exactly those three arguments. The server's .env (the port and the wisp URL) stays root-owned, and the deploy never touches it.
What the demo server sends, which the configs on this page follow: Cross-Origin-Opener-Policy: same-origin, Cross-Origin-Embedder-Policy: require-corp and Cross-Origin-Resource-Policy: cross-origin on every response (STOMP_ISOLATION=off leaves them out), no-cache on the page and on /stomp/, and public, max-age=31536000, immutable on a file asked for by its own hash. It also names its own scripts by hash in the page it serves, and serves each transport under a hash of its package's files (/epoxy/<hash>/index.mjs), so a reload revalidates little more than the page and the service worker. demo/README.md, "Deploying somewhere real", has the details.
The two subdirectories of deploy/ are build kits, not part of the server's deploy. deploy/epoxy builds the patched epoxy transport the demo and this page use. deploy/rust builds STomp's wasm modules, which are committed under assets/, so nothing is compiled from Rust during a deploy.
Troubleshooting lists the symptoms these settings produce when one is missing, and what each console message means.
STomp is licensed under the GPL-3.0. Found a mistake in these pages? Open an issue.