Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

Persist web access token and add in-page token modal

anirudhkumar-nanonets7c09906b3b40
diff --git a/README.md b/README.md
index 0dc896ac..ee473574 100644
--- a/README.md
+++ b/README.md
@@ -174,10 +174,10 @@ This is how nearly every self-hosted team tool works (Vaultwarden, Outline, Book
```bash
docker compose up -d
-docker compose logs | grep token # the share link, with access token
+cat ./data/share-link.txt # the share link, with access token
```
-The graph persists to `./data/graph.db`; drop documents into `./docs` and ingest them from the UI as `/docs`. When exposed beyond localhost the API requires the access token from the logs (pin it with `CONTEXT_GRAPH_WEB_TOKEN`).
+The graph persists to `./data/graph.db`; drop documents into `./docs` and ingest them from the UI as `/docs`. When exposed beyond localhost the API requires an access token. It's generated once, saved to `./data/share-link.txt` (and printed to `docker compose logs`), and **stays stable across restarts** so shared links keep working. Pin your own with `CONTEXT_GRAPH_WEB_TOKEN`.
No server to put it on? Run it on any machine and share it over [Tailscale](https://tailscale.com) without opening a port to the internet:
diff --git a/docker-compose.yml b/docker-compose.yml
index 10e185fa..604786a3 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,7 +1,7 @@
# Context Graph — one shared team-brain server.
#
# docker compose up -d
-# docker compose logs | grep token # grab the access/share link
+# cat ./data/share-link.txt # grab the access/share link
#
# The graph lives in ./data as a single SQLite file. Put documents you want to
# ingest into ./docs and type /docs in the UI's "Ingest a folder" box.
@@ -17,7 +17,7 @@ services:
# Optional: cloud extraction + written answers. Without it the graph and
# retrieval still work; extraction needs this key or a reachable Ollama.
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
- # Optional: pin the access token; otherwise one is generated per start
- # and printed in the logs.
+ # Optional: pin the access token. Otherwise one is generated once and
+ # saved to ./data/share-link.txt (stable across restarts).
CONTEXT_GRAPH_WEB_TOKEN: ${CONTEXT_GRAPH_WEB_TOKEN:-}
restart: unless-stopped
diff --git a/docs/index.html b/docs/index.html
index ae809def..dfca8c72 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -659,7 +659,7 @@
<h3>One shared server</h3>
<p>Run a single container; teammates open a link with an access token. Put it on your tailnet and it's reachable from anywhere, exposed to no one.</p>
<pre>$ docker compose up -d
-$ docker compose logs | grep token
+$ cat ./data/share-link.txt
<span class="c"># optional: private access from anywhere</span>
$ tailscale serve localhost:4680</pre>
</div>
diff --git a/src/web.ts b/src/web.ts
index 773d43e4..2a30356b 100644
--- a/src/web.ts
+++ b/src/web.ts
@@ -17,9 +17,9 @@
import "dotenv/config";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
-import { readFileSync, existsSync, statSync } from "node:fs";
+import { readFileSync, writeFileSync, existsSync, statSync, mkdirSync } from "node:fs";
import { networkInterfaces } from "node:os";
-import { resolve } from "node:path";
+import { resolve, dirname, join } from "node:path";
import OpenAI from "openai";
import { ContextGraphEngine } from "./engine.js";
import { resolveConfig } from "./ai/providers.js";
@@ -96,16 +96,78 @@ function json(res: ServerResponse, status: number, body: unknown): void {
const LOCAL_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
+/**
+ * Directory that holds durable server state (the graph db, and the persisted
+ * access token). Defaults next to the SQLite file so it rides the same mounted
+ * volume in Docker. Undefined for an in-memory db — nothing to persist.
+ */
+function dataDir(): string | undefined {
+ if (cfg.dbPath === ":memory:") return undefined;
+ return dirname(resolve(cfg.dbPath));
+}
+
+/**
+ * Resolve the access token, persisting a generated one so it survives restarts.
+ *
+ * Precedence: an explicit CONTEXT_GRAPH_WEB_TOKEN always wins (and is never
+ * written to disk). Otherwise, when exposed, reuse a previously persisted token
+ * or mint one and save it (owner-only) beside the db — so a `docker compose
+ * restart` no longer invalidates every teammate's saved link. Also drops a
+ * human-readable share-link.txt so the deployer never has to grep the logs.
+ */
+function resolveWebToken(): { token?: string; sharePath?: string } {
+ const explicit = process.env.CONTEXT_GRAPH_WEB_TOKEN?.trim();
+ if (explicit) return { token: explicit };
+ if (!EXPOSED) return {};
+
+ const dir = dataDir();
+ if (!dir) return { token: randomBytes(18).toString("base64url") };
+
+ const tokenPath = join(dir, ".web-token");
+ let token: string;
+ try {
+ token = existsSync(tokenPath) ? readFileSync(tokenPath, "utf8").trim() : "";
+ if (!token) {
+ token = randomBytes(18).toString("base64url");
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(tokenPath, token + "\n", { mode: 0o600 });
+ }
+ } catch {
+ // Read-only volume or similar — fall back to an in-memory token so the
+ // server still starts (it'll just change on restart, as before).
+ return { token: randomBytes(18).toString("base64url") };
+ }
+
+ // Best-effort human-readable share file; failure here must not block startup.
+ let sharePath: string | undefined;
+ try {
+ const lan = lanAddress();
+ const base = lan ? `http://${lan}:${PORT}` : `http://<this-machine>:${PORT}`;
+ const share = join(dir, "share-link.txt");
+ writeFileSync(
+ share,
+ `Context Graph — team access\n\n` +
+ `Access token:\n ${token}\n\n` +
+ `Share this link with your team (opens the UI already signed in):\n ${base}/#token=${token}\n\n` +
+ `On this machine, use:\n http://localhost:${PORT}/#token=${token}\n`,
+ { mode: 0o600 },
+ );
+ sharePath = share;
+ } catch {
+ /* ignore */
+ }
+ return { token, sharePath };
+}
+
/**
* Access token for the API. On the loopback default no token is needed — the
* OS already gates who can reach the port. The moment the server is exposed
* beyond loopback (HOST=0.0.0.0, Docker, a VPS) a token is required: taken
- * from CONTEXT_GRAPH_WEB_TOKEN, or generated fresh and printed at startup.
+ * from CONTEXT_GRAPH_WEB_TOKEN, or persisted next to the db and printed at
+ * startup (see resolveWebToken).
*/
const EXPOSED = !LOCAL_HOSTNAMES.has(HOST);
-const WEB_TOKEN =
- process.env.CONTEXT_GRAPH_WEB_TOKEN?.trim() ||
- (EXPOSED ? randomBytes(18).toString("base64url") : undefined);
+const { token: WEB_TOKEN, sharePath: SHARE_PATH } = resolveWebToken();
function isAuthorized(req: IncomingMessage): boolean {
if (!WEB_TOKEN) return true;
@@ -272,6 +334,9 @@ server.listen(PORT, HOST, () => {
// the network, so it can't leak into proxy or access logs.
if (lan) console.log(` share with your team: http://${lan}:${PORT}/#token=${WEB_TOKEN}`);
else console.log(` share: http://<this-machine>:${PORT}/#token=${WEB_TOKEN}`);
+ // The same link is written to a file on the mounted volume, so the deployer
+ // (who ran `docker compose up -d` and sees no logs) can just open it.
+ if (SHARE_PATH) console.log(` share link also saved to: ${SHARE_PATH}`);
}
console.log(` graph db: ${p.db}`);
console.log(` extraction: ${p.extraction} (${p.model})`);
diff --git a/src/web/ui.html b/src/web/ui.html
index c1583807..53cada93 100644
--- a/src/web/ui.html
+++ b/src/web/ui.html
@@ -249,10 +249,59 @@
@media (prefers-reduced-motion: reduce) {
* { transition: none !important; animation: none !important; }
}
+
+ /* ---------- access-token gate ---------- */
+ .token-overlay {
+ position: fixed; inset: 0; z-index: 1000;
+ display: none; align-items: center; justify-content: center;
+ background: rgba(28, 36, 34, .55); padding: 20px;
+ }
+ .token-overlay.open { display: flex; }
+ .token-card {
+ width: 100%; max-width: 440px;
+ background: var(--panel); border: 1px solid var(--line); border-radius: 10px;
+ padding: 24px 24px 20px; box-shadow: 0 12px 40px rgba(28, 36, 34, .25);
+ }
+ .token-card h2 {
+ font-family: var(--serif); font-size: 20px; font-weight: 600; margin-bottom: 8px;
+ }
+ .token-card p { font-size: 14px; color: var(--ink-soft); margin-bottom: 14px; }
+ .token-card p code {
+ font-family: var(--mono); font-size: 12px;
+ background: var(--paper); border: 1px solid var(--line);
+ border-radius: 4px; padding: 1px 5px; color: var(--ink);
+ }
+ .token-input {
+ width: 100%; padding: 11px 13px; font-family: var(--mono); font-size: 13px;
+ border: 1px solid var(--line); border-radius: 6px; background: var(--panel);
+ }
+ .token-input:focus { border-color: var(--verdant); }
+ .token-hint { font-size: 12.5px; color: var(--ink-faint); margin: 10px 0 0; }
+ .token-hint code { font-family: var(--mono); font-size: 11.5px; }
+ .token-err { color: var(--amber); font-size: 13px; margin-top: 10px; min-height: 0; }
+ .token-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 18px; }
</style>
</head>
<body>
+<div class="token-overlay" id="token-overlay" role="dialog" aria-modal="true" aria-labelledby="token-title">
+ <div class="token-card">
+ <h2 id="token-title">This graph is protected</h2>
+ <p>Paste the <b>access token</b> or the full <b>share link</b> your team was given.</p>
+ <input class="token-input" id="token-input" type="text"
+ placeholder="token, or http://…/#token=…" autocomplete="off" spellcheck="false" />
+ <div class="token-err" id="token-err"></div>
+ <p class="token-hint">
+ Where to find it: open <code>./data/share-link.txt</code> next to the server,
+ or run <code>docker compose logs | grep token</code>.
+ </p>
+ <div class="token-actions">
+ <button class="btn quiet" id="token-cancel" type="button">Cancel</button>
+ <button class="btn" id="token-submit" type="button">Unlock</button>
+ </div>
+ </div>
+</div>
+
<header class="masthead">
<span class="wordmark">Context<span class="dot">·</span>Graph</span>
<span class="tagline">a living ledger of what your team knows</span>
@@ -346,8 +395,17 @@ const $ = (id) => document.getElementById(id);
/* ---------- access token (shared/team deployments) ---------- */
// A share link carries #token=… in the URL fragment — fragments are never
-// sent to the server, so the token stays out of proxy/access logs. Stash it
-// and strip it from the address bar.
+// sent to the server, so the token stays out of proxy/access logs. Accept
+// either a bare token or a whole pasted link and pull the token out of it.
+function extractToken(raw) {
+ const s = (raw || "").trim();
+ if (!s) return "";
+ // Full share link: token lives in the #token=… fragment.
+ const hash = s.includes("#") ? s.slice(s.indexOf("#") + 1) : "";
+ const fromHash = new URLSearchParams(hash).get("token");
+ return (fromHash || s).trim();
+}
+
(function pickUpToken() {
const frag = new URLSearchParams(location.hash.replace(/^#/, ""));
const t = frag.get("token");
@@ -357,17 +415,51 @@ const $ = (id) => document.getElementById(id);
}
})();
+// In-page token modal — a Promise that resolves with the entered token (already
+// normalized) or null if the user cancels. Replaces the browser's window.prompt.
+function askForToken(message) {
+ const overlay = $("token-overlay");
+ const input = $("token-input");
+ const err = $("token-err");
+ err.textContent = message || "";
+ input.value = "";
+ overlay.classList.add("open");
+ input.focus();
+ return new Promise((resolve) => {
+ const close = (value) => {
+ overlay.classList.remove("open");
+ $("token-submit").onclick = null;
+ $("token-cancel").onclick = null;
+ input.onkeydown = null;
+ overlay.onmousedown = null;
+ resolve(value);
+ };
+ const submit = () => {
+ const token = extractToken(input.value);
+ if (!token) { err.textContent = "Enter a token or share link."; return; }
+ close(token);
+ };
+ $("token-submit").onclick = submit;
+ $("token-cancel").onclick = () => close(null);
+ input.onkeydown = (e) => {
+ if (e.key === "Enter") submit();
+ else if (e.key === "Escape") close(null);
+ };
+ // Click on the backdrop (not the card) cancels.
+ overlay.onmousedown = (e) => { if (e.target === overlay) close(null); };
+ });
+}
+
async function api(path, opts = {}) {
const headers = { ...(opts.headers || {}) };
const token = localStorage.getItem("cg-token");
if (token) headers["authorization"] = "Bearer " + token;
const r = await fetch(path, { ...opts, headers });
if (r.status === 401) {
- const t = window.prompt(
- "This graph is protected. Paste the access token (shown where the server was started, or in your share link):",
- );
- if (t && t.trim()) {
- localStorage.setItem("cg-token", t.trim());
+ const wrong = Boolean(token); // had a token that the server rejected
+ const t = await askForToken(wrong ? "That token was rejected. Try again." : "");
+ if (t) {
+ localStorage.setItem("cg-token", t);
return api(path, opts);
}
throw new Error("access token required");