Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

feat(share): share links — CLI, guest reading room, tunnel (#947)

xerj-org01d0044dd9b2
diff --git a/.github/scripts/share-links-smoke.sh b/.github/scripts/share-links-smoke.sh
new file mode 100755
index 000000000..1724f9c32
--- /dev/null
+++ b/.github/scripts/share-links-smoke.sh
@@ -0,0 +1,271 @@
+#!/usr/bin/env bash
+# CI gate for share links (`xerj share`, `/_share`, the guest page).
+#
+# Boots THROWAWAY nodes on private ports and drives, in order:
+# A. engine/crates/xerj-api/tests/live/share_security_live.py against a node
+# with authentication on AND `logging.access_log = true` — what a guest
+# key can and cannot reach, and that no share id reaches the node's log;
+# B. the `xerj share` CLI against that node: create / --list / --revoke /
+# --json, the folder-not-indexed error, the wrong-key error (index AND
+# folder argument), a --url with no scheme, and --tunnel with a stub
+# `cloudflared` — the Cloudflare notice, and its last lines when it dies;
+# C. xerj-ux/test/share-guest-flow.e2e.mjs — the guest page in a real
+# headless Chrome (claim, search, read, XSS probe, sign-out), on a fresh
+# node with the access log on;
+# D. the same security test against a node that declares loopback a trusted
+# proxy (the `--tunnel` + trusted_proxies configuration);
+# E. the refusal: `xerj share` against an --insecure node exits 1 and says why;
+# F. the headline path: `xerj brain <folder>` boots a node and indexes notes
+# and email, its output carries a pasteable `xerj share` hint, and
+# `xerj share <folder>` resolves the folder to that brain and its indices.
+#
+# Not covered here, because it needs the public internet and a third party:
+# `xerj share --tunnel` actually opening a cloudflared quick tunnel. The
+# hostname parser and the fallbacks are unit-tested in xerj-server.
+#
+# Env overrides:
+# XERJ_BIN xerj binary (default <repo>/engine/target/release/xerj)
+# XERJ_SHARE_ROOT scratch root (default a fresh mktemp -d)
+# XERJ_SHARE_PORT first of THREE consecutive ports (default 9510); the
+# nodes run one after another on the same three
+# XERJ_SHARE_REQUIRE_BROWSER 1 = a missing Chrome is a failure (CI), else phase C is skipped
+# CHROME_BIN Chrome/Chromium binary for phase C
+set -uo pipefail
+
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+REPO="$(cd "$HERE/../.." && pwd)"
+XERJ_BIN="${XERJ_BIN:-$REPO/engine/target/release/xerj}"
+ROOT="${XERJ_SHARE_ROOT:-$(mktemp -d)}"
+PORT="${XERJ_SHARE_PORT:-9510}"
+LIVE="$REPO/engine/crates/xerj-api/tests/live/share_security_live.py"
+E2E="$REPO/xerj-ux/test/share-guest-flow.e2e.mjs"
+
+FAILED=0
+PIDS=()
+phase() { echo; echo "════ $* ════"; }
+bad() { echo "::error::$*"; FAILED=$((FAILED + 1)); }
+ok() { echo " PASS: $*"; }
+cleanup() { for pid in "${PIDS[@]:-}"; do [ -n "$pid" ] && kill "$pid" 2>/dev/null; done; return 0; }
+trap cleanup EXIT
+
+# stop <name> — by the PID we recorded, never by pattern; then wait for the port.
+stop() {
+ local pid; pid="$(cat "$ROOT/$1/server.pid" 2>/dev/null)"
+ [ -n "$pid" ] && kill "$pid" 2>/dev/null
+ for _ in $(seq 1 60); do
+ curl -s -o /dev/null "http://127.0.0.1:$PORT/" 2>/dev/null || return 0
+ sleep 0.5
+ done
+ echo "node $1 did not stop"; return 1
+}
+
+[ -x "$XERJ_BIN" ] || { echo "xerj binary not found at $XERJ_BIN"; exit 1; }
+command -v python3 >/dev/null || { echo "python3 is required"; exit 1; }
+
+# boot <name> <es_port> <extra [server] toml> <extra cli args…>
+# ports: es = $2, rest = $2+1, grpc = $2+2. Auth is ON unless --insecure is passed.
+# BOOT_ACCESS_LOG=true turns on `logging.access_log` for that node.
+boot() {
+ local name="$1" es="$2" extra="$3"; shift 3
+ local dir="$ROOT/$name"
+ # Something already answering here is NOT our node: the phases below create
+ # and delete indices, so never adopt a listener we did not start.
+ if curl -s -o /dev/null "http://127.0.0.1:$es/" 2>/dev/null; then
+ echo "port $es is already in use — refusing to test against a node this script did not start"
+ return 1
+ fi
+ mkdir -p "$dir/data"
+ cat >"$dir/xerj.toml" <<EOF
+[server]
+es_compat_port = $es
+rest_port = $((es + 1))
+grpc_port = $((es + 2))
+bind_address = "127.0.0.1"
+data_dir = "$dir/data"
+$extra
+
+[tls]
+enabled = false
+
+[logging]
+access_log = ${BOOT_ACCESS_LOG:-false}
+EOF
+ nohup "$XERJ_BIN" --config "$dir/xerj.toml" --data-dir "$dir/data" "$@" >"$dir/server.log" 2>&1 &
+ PIDS+=("$!")
+ echo "$!" >"$dir/server.pid"
+ for _ in $(seq 1 120); do
+ # 200 on an open node, 401 on an authenticated one — either means "up".
+ code="$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:$es/" 2>/dev/null)"
+ { [ "$code" = 200 ] || [ "$code" = 401 ]; } && return 0
+ sleep 0.5
+ done
+ echo "node $name failed to boot on :$es"; tail -20 "$dir/server.log"; return 1
+}
+
+# ── A. what a guest key can and cannot reach ───────────────────────────────
+phase "A. live security test (auth on, no trusted proxies, access log ON)"
+# With the access log OFF (the default) the "no share id in the log" check
+# below passes whatever the claim route looks like — which is how the first cut
+# shipped a claim path that carried the id. This node logs every request.
+BOOT_ACCESS_LOG=true boot a "$PORT" "" || exit 1
+A_URL="http://127.0.0.1:$PORT"; A_DATA="$ROOT/a/data"
+[ -s "$A_DATA/admin.key" ] || { echo "no admin.key — is auth on?"; exit 1; }
+if XERJ_URL="$A_URL" XERJ_NATIVE_URL="http://127.0.0.1:$((PORT + 1))" XERJ_DATA_DIR="$A_DATA" XERJ_SERVER_LOG="$ROOT/a/server.log" python3 "$LIVE"; then ok "share_security_live.py"; else bad "share_security_live.py failed"; fi
+# The live test checks the log for the exact ids it created. This is the same
+# thing by *shape*, for anything else that ran: a 32-hex id in a logged path.
+# (`f`×32 is the live test's probe of the retired id-in-path claim shape.)
+grep -q '/_share/claim' "$ROOT/a/server.log" && ok "the node logged its requests (access log on)" || bad "access log is not on — the next check would test nothing"
+if grep -E '/_share/[0-9a-f]{32}' "$ROOT/a/server.log" | grep -vq "/_share/$(printf 'f%.0s' $(seq 1 32))"; then bad "a share id was written to the server log"; else ok "no share id in the server log"; fi
+
+# ── B. the CLI ─────────────────────────────────────────────────────────────
+phase "B. xerj share CLI"
+share() { "$XERJ_BIN" share "$@" --url "$A_URL" --data-dir "$A_DATA" --disable-feedback; }
+OUT="$(share casefile --label "for the CI" --expires 30m --max-claims 2 --json 2>"$ROOT/cli.err")"; RC=$?
+HANDLE="$(printf '%s' "$OUT" | python3 -c 'import json,sys; print(json.load(sys.stdin)["handle"])' 2>/dev/null)"
+LINK="$(printf '%s' "$OUT" | python3 -c 'import json,sys; print(json.load(sys.stdin)["link"])' 2>/dev/null)"
+if [ $RC -eq 0 ] && [ -n "$HANDLE" ] && [[ "$LINK" == "$A_URL/_xerj-console/share#"* ]]; then ok "create --json → $HANDLE"; else bad "create --json (rc=$RC): $OUT $(cat "$ROOT/cli.err")"; fi
+HUMAN="$(share casefile --label "readable" 2>&1)"
+for want in "link:" "passcode:" "expires:" "xerj share --revoke" "read-only" "only this machine can reach"; do
+ printf '%s' "$HUMAN" | grep -qF -- "$want" || bad "create output lacks \"$want\": $HUMAN"
+done
+ok "create prints link, passcode, expiry, how to revoke, and that the link is local-only"
+# Capture, then grep: `xerj share … | grep -q` is a trap under pipefail —
+# grep -q exits on its first match, the CLI's next write gets SIGPIPE (exit
+# 141, nothing on stderr), and the pipeline fails with the handle right there
+# in the output. Seen once in CI-shaped runs under load.
+LISTED="$(share --list 2>&1)"
+printf '%s' "$LISTED" | grep -q "$HANDLE" && ok "--list shows the share" || bad "--list does not show $HANDLE: $LISTED"
+REVOKED="$(share --revoke "$HANDLE" 2>&1)"
+printf '%s' "$REVOKED" | grep -q "revoked" && ok "--revoke" || bad "--revoke $HANDLE: $REVOKED"
+share --list --json | python3 -c "import json,sys; s=[x for x in json.load(sys.stdin)['shares'] if x['handle']=='$HANDLE']; sys.exit(0 if s and s[0]['status']=='revoked' else 1)" \
+ && ok "--list --json reports it revoked" || bad "revoked share not reported as revoked"
+mkdir -p "$ROOT/never-indexed"
+ERR="$(share "$ROOT/never-indexed" 2>&1)"; RC=$?
+{ [ $RC -eq 1 ] && printf '%s' "$ERR" | grep -q "has not been indexed"; } && ok "a folder nobody indexed is an error that says so" || bad "folder error (rc=$RC): $ERR"
+ERR="$("$XERJ_BIN" share casefile --url "$A_URL" --api-key not-the-admin-key --disable-feedback 2>&1)"; RC=$?
+{ [ $RC -eq 1 ] && printf '%s' "$ERR" | grep -qi "admin key"; } && ok "a wrong key is refused with the reason" || bad "wrong-key error (rc=$RC): $ERR"
+# The same wrong key with a FOLDER argument used to be reported as "has not
+# been indexed — run xerj brain first": the brain lookup read its 401 as "no
+# such brain".
+ERR="$("$XERJ_BIN" share "$ROOT/never-indexed" --url "$A_URL" --api-key not-the-admin-key --disable-feedback 2>&1)"; RC=$?
+{ [ $RC -eq 1 ] && printf '%s' "$ERR" | grep -qi "admin key" && ! printf '%s' "$ERR" | grep -q "has not been indexed"; } \
+ && ok "a wrong key with a folder argument is a key error, not \"not indexed\"" || bad "wrong-key + folder (rc=$RC): $ERR"
+ERR="$("$XERJ_BIN" share casefile --url "127.0.0.1:$PORT" --data-dir "$A_DATA" --disable-feedback 2>&1)"; RC=$?
+{ [ $RC -eq 2 ] && printf '%s' "$ERR" | grep -qF "http://127.0.0.1:$PORT"; } && ok "--url without a scheme is a usage error that says what to type" || bad "--url without scheme (rc=$RC): $ERR"
+ERR="$(share autoindex-catalog 2>&1)"; RC=$?
+{ [ $RC -eq 1 ] && printf '%s' "$ERR" | grep -q "every corpus"; } && ok "the autoindex catalog cannot be shared" || bad "autoindex-catalog (rc=$RC): $ERR"
+OUT="$(share casefile --public-url http://plain.example 2>&1)"
+printf '%s' "$OUT" | grep -q "plain http" && ok "--public-url http:// warns that the passcode and key travel unencrypted" || bad "--public-url http:// printed no warning: $OUT"
+
+# `--tunnel` without cloudflared: install steps and the local link, not a failure.
+OUT="$(XERJ_CLOUDFLARED=/nonexistent/cloudflared share casefile --tunnel 2>&1)"; RC=$?
+{ [ $RC -eq 0 ] && printf '%s' "$OUT" | grep -q "install it" && printf '%s' "$OUT" | grep -qF "$A_URL/_xerj-console/share#"; } \
+ && ok "--tunnel without cloudflared prints install steps and the local link (exit 0)" || bad "--tunnel fallback (rc=$RC): $OUT"
+
+# `--tunnel` with a STUB cloudflared: prints a quick-tunnel banner, registers,
+# then dies on its own. No network. What the owner must see: that the link goes
+# through Cloudflare and what Cloudflare can read — at the moment the link is
+# printed, not only in the docs — and, when the tunnel drops, its last lines.
+STUB="$ROOT/cloudflared-stub.sh"
+cat >"$STUB" <<'STUBEOF'
+#!/usr/bin/env bash
+echo "2026-01-01T00:00:00Z INF | https://smoke-stub-tunnel.trycloudflare.com |" >&2
+echo "2026-01-01T00:00:01Z INF Registered tunnel connection connIndex=0" >&2
+sleep 2
+echo "2026-01-01T00:00:03Z ERR failed to serve tunnel connection error=\"stub: edge went away\"" >&2
+exit 1
+STUBEOF
+chmod +x "$STUB"
+OUT="$(XERJ_CLOUDFLARED="$STUB" share casefile --tunnel 2>&1)"; RC=$?
+FLAT="$(printf '%s' "$OUT" | tr -s '[:space:]' ' ')"
+{ [ $RC -eq 0 ] && printf '%s' "$FLAT" | grep -qF "https://smoke-stub-tunnel.trycloudflare.com/_xerj-console/share#" \
+ && printf '%s' "$FLAT" | grep -q "goes through Cloudflare" && printf '%s' "$FLAT" | grep -q "the passcode, the guest's key" \
+ && ! printf '%s' "$FLAT" | grep -q "browser reads from this node"; } \
+ && ok "--tunnel says the link goes through Cloudflare, and what Cloudflare can read" || bad "--tunnel banner (rc=$RC): $OUT"
+{ printf '%s' "$OUT" | grep -q "cloudflared stopped" && printf '%s' "$OUT" | grep -q "stub: edge went away" && printf '%s' "$OUT" | grep -q "revoked"; } \
+ && ok "when cloudflared dies on its own: its last lines are shown and the share is revoked" || bad "tunnel death: $OUT"
+
+# ── C. the guest page in a real browser ────────────────────────────────────
+phase "C. guest page, headless Chrome (a fresh node, access log ON)"
+# Its own node: phase A spent 127.0.0.1's junk-id claim budget on purpose, and
+# the page's "this link is not recognised" view needs one unknown-id claim to
+# get a 404 rather than a 429. The access log is on so the shape check below
+# covers what the page itself requests.
+stop a || exit 1
+if command -v node >/dev/null; then
+ BOOT_ACCESS_LOG=true boot c "$PORT" "" || exit 1
+ XERJ_URL="http://127.0.0.1:$PORT" XERJ_DATA_DIR="$ROOT/c/data" node "$E2E"; RC=$?
+ case $RC in
+ 0) ok "share-guest-flow.e2e.mjs" ;;
+ 77) echo " SKIP: no Chrome/Chromium on this machine (set CHROME_BIN)" ;;
+ *) bad "share-guest-flow.e2e.mjs failed (rc=$RC)" ;;
+ esac
+ if grep -E '/_share/[0-9a-f]{32}' "$ROOT/c/server.log" >/dev/null; then bad "the guest page put a share id in a logged path"; else ok "no share id in the server log after the browser flow"; fi
+ stop c || exit 1
+else
+ [ "${XERJ_SHARE_REQUIRE_BROWSER:-0}" = 1 ] && bad "node is required for the browser test" || echo " SKIP: node not installed"
+fi
+
+# ── D. the tunnel configuration: loopback declared a trusted proxy ─────────
+phase "D. live security test (server.trusted_proxies = [\"127.0.0.1\", \"::1\"])"
+boot d "$PORT" 'trusted_proxies = ["127.0.0.1", "::1"]' || exit 1
+if XERJ_URL="http://127.0.0.1:$PORT" XERJ_DATA_DIR="$ROOT/d/data" XERJ_TRUSTS_LOOPBACK=1 python3 "$LIVE" >"$ROOT/d/live.out" 2>&1; then
+ ok "share_security_live.py ($(tail -1 "$ROOT/d/live.out"))"
+else
+ grep -E "FAIL|passed=" "$ROOT/d/live.out"; bad "share_security_live.py failed behind a trusted proxy"
+fi
+
+# ── E. the refusal ─────────────────────────────────────────────────────────
+phase "E. an open node cannot share"
+stop d || exit 1
+boot e "$PORT" "" --insecure || exit 1
+E_URL="http://127.0.0.1:$PORT"
+curl -s -o /dev/null -XPUT "$E_URL/open-index"
+ERR="$("$XERJ_BIN" share open-index --url "$E_URL" --disable-feedback 2>&1)"; RC=$?
+{ [ $RC -eq 1 ] && printf '%s' "$ERR" | grep -q "authentication OFF" && printf '%s' "$ERR" | grep -q "restrict nothing"; } \
+ && ok "xerj share refuses, exit 1, and says why" || bad "refusal (rc=$RC): $ERR"
+CODE="$(curl -s -o "$ROOT/e/create.json" -w '%{http_code}' -XPOST "$E_URL/_share" -H 'content-type: application/json' -d '{"index":"open-index"}')"
+[ "$CODE" = 409 ] && ok "POST /_share on an open node → 409" || bad "POST /_share on an open node → $CODE $(cat "$ROOT/e/create.json")"
+
+# ── F. the headline path: xerj brain <folder> → xerj share <folder> ─────────
+phase "F. share the folder you gave xerj brain"
+stop e || exit 1
+F="$ROOT/f"; mkdir -p "$F/casefiles/notes" "$F/casefiles/mail"
+printf '# Lease dispute\n\nThe landlord refused to return the deposit. See [[inspection]].\n' >"$F/casefiles/notes/lease.md"
+printf '# Inspection\n\nMould in the bathroom, photographed in March. Related: [[lease]].\n' >"$F/casefiles/notes/inspection.md"
+printf 'From: Dana <[email protected]>\nTo: Owner <[email protected]>\nSubject: Deposit not returned\nDate: Tue, 03 Mar 2026 10:00:00 +0000\nMessage-ID: <[email protected]>\nContent-Type: text/plain; charset=utf-8\n\nThe deposit of 1200 has still not been returned.\n' >"$F/casefiles/mail/0001.eml"
+F_URL="http://localhost:$PORT"
+"$XERJ_BIN" brain "$F/casefiles" --url "$F_URL" --data-dir "$F/data" --no-open --disable-feedback >"$F/brain.out" 2>&1; RC=$?
+[ -s "$F/data/server.pid" ] && PIDS+=("$(cat "$F/data/server.pid")")
+{ [ $RC -eq 0 ] || [ $RC -eq 3 ]; } && ok "xerj brain indexed the folder (exit $RC)" || { bad "xerj brain failed (rc=$RC)"; tail -20 "$F/brain.out"; }
+HINT="$(grep -F 'share it: xerj share' "$F/brain.out" | head -1)"
+{ printf '%s' "$HINT" | grep -qF -- "--url $F_URL" && printf '%s' "$HINT" | grep -qF -- "--data-dir $F/data"; } \
+ && ok "xerj brain prints a pasteable share hint (with --url and --data-dir)" || bad "share hint: $HINT"
+OUT="$("$XERJ_BIN" share "$F/casefiles" --url "$F_URL" --data-dir "$F/data" --json --disable-feedback 2>"$F/share.err")"; RC=$?
+python3 - "$F_URL" "$OUT" <<'PYEOF' && ok "folder → brain → indices; the guest can search it and walk its links, and nothing else" || bad "folder share (rc=$RC): $(cat "$F/share.err")"
+import json, sys, urllib.request, urllib.error
+url, created = sys.argv[1], json.loads(sys.argv[2])
+assert created["brain"] == "casefiles" and created["indices"], created
+def call(method, path, body=None, key=None):
+ h = {"content-type": "application/json"}
+ if key: h["authorization"] = "ApiKey " + key
+ req = urllib.request.Request(url + path, data=None if body is None else json.dumps(body).encode(), method=method, headers=h)
+ try:
+ r = urllib.request.urlopen(req, timeout=30); return r.status, json.loads(r.read() or b"{}")
+ except urllib.error.HTTPError as e:
+ return e.code, {}
+s, claim = call("POST", "/_share/claim", {"id": created["share_id"], "passcode": created["passcode"]})
+assert s == 200 and claim["brain"] == "casefiles", (s, claim)
+key, index = claim["api_key"], claim["index"]
+s, r = call("POST", f"/{index}/_search", {"query": {"simple_query_string": {"query": "deposit"}}}, key)
+assert s == 200 and r["hits"]["total"]["value"] >= 2, (s, r)
+s, r = call("GET", "/_graph/casefiles/overview", None, key)
+assert s == 200 and r["edges"]["live"] >= 2 and r["nodes"]["total"] >= 3, (s, r)
+for path in ("/autoindex-catalog/_search", "/_cat/indices", "/_share"):
+ s, _ = call("GET", path, None, key)
+ assert s == 403, (path, s)
+PYEOF
+
+echo
+if [ "$FAILED" -eq 0 ]; then echo "share-links smoke: all phases passed"; else echo "share-links smoke: $FAILED failure(s)"; fi
+exit "$FAILED"
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 91114d6b6..7d7379d67 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -723,6 +723,21 @@ jobs:
XERJ_MCP_BIN: ${{ github.workspace }}/engine/target/ci-test/xerj-mcp
run: bash .github/scripts/usecase-smoke.sh
+ # Share links end to end, against throwaway nodes this script boots on
+ # 127.0.0.1:9510-9512: what a guest key can and cannot reach (the live
+ # security test, with and without a trusted proxy), the `xerj share` CLI,
+ # the guest page in the runner's headless Chrome (claim, search, read, an
+ # XSS probe document, sign-out), the open-node refusal, and the
+ # `xerj brain` -> `xerj share <folder>` path. No npm install: Chrome is
+ # driven over the DevTools pipe. NOT covered, because it needs the public
+ # internet and a third party: `--tunnel` opening a real cloudflared quick
+ # tunnel (its hostname parser and fallbacks are unit tests).
+ - name: Share links (guest reach, CLI, headless-Chrome guest flow)
+ env:
+ XERJ_BIN: ${{ github.workspace }}/engine/target/ci-test/xerj
+ XERJ_SHARE_REQUIRE_BROWSER: '1'
+ run: bash .github/scripts/share-links-smoke.sh
+
# The published agent-facing schema vs what the server actually serves.
# It drifted once already — six tools published against ten served, every
# xerj_brain_* tool missing — and nothing failed, because nothing
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8c84db4ba..78c29c899 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **`xerj share <index|folder>` — give one person read-only search over one
+ indexed folder: a link, a passcode, an expiry.** The guest opens the link,
+ types the passcode and gets a reading room (search, highlighted snippets, a
+ document view) served by the owner's node; the folder is not uploaded and
+ the guest installs nothing. `POST /_share` (admin key only) stores only a
+ SHA-256 digest of the share id and an Argon2id hash of the passcode; the
+ unauthenticated, rate-limited, audited `POST /_share/claim` takes
+ `{id, passcode}` in its body, so the share id is not in the request line an
+ access log records, and mints a scoped read-only key that expires with the
+ share; a guest-only route allow-list closes `_cat`, `_cluster`, every other
+ index, all writes, and scroll / PIT / async contexts. Every response under
+ `/_share` and every response to a guest key is `no-store`; a guest's refused
+ attempts to manage shares or mint a key are audited; the `autoindex-catalog`
+ index cannot be shared. `--tunnel` supervises your own `cloudflared` quick
+ tunnel and revokes the share on Ctrl-C. That traffic passes through
+ Cloudflare, which terminates TLS and can read the passcode, the guest key and
+ the documents; the command and the guest page both say so. `--list` /
+ `--revoke <handle>` manage shares; the command refuses a node running with
+ authentication off, where a read-only key would restrict nothing.
+ `xerj brain` now prints the share command for the folder it indexed. Found
+ and fixed on the way: the graph API
+ authorized a multi-dataset brain's comma-joined `nodes_index` as one literal
+ index name, so every scoped key got `403` on `overview` for any folder with
+ more than one dataset (and `overview` reported 0 notes for it); and the
+ Console asset bundle was not rebuilt when a new file appeared under
+ `xerj-ux/` on a warm target directory. Threat model, guest reach table and
+ the quick-tunnel trade-offs: [docs/SHARING.md](docs/SHARING.md).
- **`xerj autoindex` reads mbox mailboxes and Google Takeout exports** — an mbox
(Takeout, Thunderbird, Apple Mail, mutt) is detected by content, split in a
bounded-memory stream with `>From ` unquoting, CRLF/LF and a missing final
diff --git a/README.md b/README.md
index ec43c6deb..99505f6ba 100644
--- a/README.md
+++ b/README.md
@@ -408,6 +408,9 @@ limits each one does not lift:
resource limits that bound them.
- [Snapshot and restore](./docs/SNAPSHOT_AND_RESTORE.md) for the supported subset of the
snapshot API, and what restore replaces.
+- [Sharing](./docs/SHARING.md) for `xerj share`: read-only guest access to one indexed
+ folder through a link and a passcode, what a guest can and cannot reach, and the threat
+ model.
- [Security model](./docs/SECURITY_MODEL.md) for authentication, the reserved
`.xerj-memory-*` namespace, API keys and what is not enforced.
- [Reranking](./docs/RERANK.md) for the optional `rerank` search stage: an external judge
diff --git a/content/answers/share-folder-read-only-search-without-uploading.md b/content/answers/share-folder-read-only-search-without-uploading.md
new file mode 100644
index 000000000..1a2911e6f
--- /dev/null
+++ b/content/answers/share-folder-read-only-search-without-uploading.md
@@ -0,0 +1,116 @@
+---
+title: "Read-only search over a folder, without uploading it"
+h1: "How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?"
+description: "Index the folder on your own machine, then run xerj share: the other person gets a link, a passcode and a read-only search page. The folder is not uploaded."
+slug: "share-folder-read-only-search-without-uploading"
+cluster: "Sharing: read-only guest access"
+question: "I need my accountant to search a folder of emails and PDFs. How do I do that without uploading everything somewhere?"
+intent: "how-to"
+published: "2026-09-18"
+author: "XERJ documentation team"
+reviewer: "XERJ engineering team"
+schema_type: "TechArticle"
+agent_prompt: "Act as a coding agent. Read https://xerj.org/llms.txt, run xerj brain on the folder the user names, then run xerj share on the same folder with a label and an expiry, and give the user the link and the passcode separately. Tell them the link only works on this machine unless they add --tunnel, and show them the xerj share --revoke command that was printed."
+commands:
+ - cmd: "xerj brain ./casefiles"
+ note: "Index the folder. This boots a local node with authentication on and prints the share command for this folder when it finishes."
+ - cmd: "xerj share ./casefiles --label 'for Dana' --expires 7d"
+ note: "Create the share. Prints the link, the passcode, the expiry and the revoke command, once."
+ - cmd: "xerj share ./casefiles --label 'for Dana' --tunnel"
+ note: "Same, with a temporary public address from cloudflared for someone who is not on this machine. Ctrl-C closes the tunnel and revokes the share."
+ - cmd: "xerj share --list"
+ note: "Every share on this node: handle, status, claims used, expiry, index, label."
+links_out:
+ - "what-a-share-link-guest-can-reach"
+ - "share-local-search-index-through-a-tunnel"
+ - "search-all-pdfs-in-a-folder"
+ - "/docs/security"
+evidence:
+ - claim: "A share defaults to 24h and 1 claim; the longest lifetime is 30 days and the most claims is 50."
+ source: "engine/crates/xerj-api/src/share.rs"
+ - claim: "A generated passcode is 8 symbols from a 31-symbol alphabet; a share id is 128 bits."
+ source: "engine/crates/xerj-api/src/share.rs"
+ - claim: "Claims against one share are limited to 10 a minute and 30 an hour."
+ source: "engine/crates/xerj-api/src/share.rs"
+ - claim: "xerj share refuses a node running with authentication off and exits 1."
+ source: "engine/crates/xerj-server/src/share.rs"
+ - claim: "The folder path was run end to end on 2026-09-18: 3 files indexed, shared by folder, claimed, searched."
+ source: "docs/usecases/share-links/VERIFICATION.md"
+faq:
+ - q: "I need my accountant to search a folder of emails and PDFs. How do I do that without uploading everything somewhere?"
+ a: "Run `xerj brain` on the folder, then `xerj share` on the same folder. Your accountant gets a link and a passcode and searches from a browser. The documents and the index stay on your machine."
+ - q: "Does the other person have to install anything?"
+ a: "No. They open the link in a browser and type the passcode. The page is served by your node and loads nothing from anywhere else."
+ - q: "Can they change or delete my files?"
+ a: "No. The guest key is read-only and reaches only the shared index. Writes, deletes and every other index on the node are refused by the server, not by the page."
+ - q: "How do I stop the access?"
+ a: "Run the `xerj share --revoke` command that was printed when you created the share. The guest's next request is refused. A share also ends on its own: the default lifetime is 24h."
+ - q: "What if they are not on my network?"
+ a: "Add `--tunnel`. XERJ starts your own `cloudflared`, prints a public link, and closes the tunnel and revokes the share when you press Ctrl-C. That traffic passes through Cloudflare, which can read it: the passcode, the guest key, the searches and the documents. The command prints this with the link."
+ - q: "Can they come back to the link later?"
+ a: "Only while the browser tab stays open, unless you allow more than one open. One open is one browser tab. Opening the same link again in that tab keeps the session. A closed tab is a spent open, so give `--max-claims 5` to someone who will read over several days."
+ - q: "Is the search AI? Does it write answers?"
+ a: "No. It is search and reading only: no text is generated and no model is called. The default embedder is lexical feature hashing, so ranking is by word and sub-word overlap plus BM25."
+---
+
+**TL;DR** — Index the folder with `xerj brain`, then run `xerj share` on the same folder. The other person gets a link and a passcode. They open a read-only search page in a browser and read what they find. The documents and the index stay on your machine. You can revoke it at any time.
+
+## The two commands
+
+`xerj brain ./casefiles` indexes the folder and starts a local node with authentication on. When it finishes it prints the exact share command for that folder.
+
+`xerj share ./casefiles --label 'for Dana' --expires 7d` creates the share. The folder argument resolves to the indices that `xerj brain` built for it. The output is shown once:
+
+```text
+✓ share created — "for Dana"
+ shares: index ax-docs · brain casefiles (its links) — read-only
+ link: http://localhost:9200/_xerj-console/share#…
+ passcode: ….-…. (send it separately from the link)
+ expires: 2026-09-25T08:41:09Z · can be opened 1 time — one browser tab; --max-claims <N> for a guest who will come back
+ revoke: xerj share --revoke 8a1e546d4ee8
+```
+
+Send the link and the passcode through different channels. Either one alone opens nothing.
+
+One open is one browser tab. The guest's key lives in that tab. Opening the same link again in the same tab keeps the session and spends nothing. A closed tab is a spent open. With the default of 1 open, a guest who closes the tab cannot come back, even if the share has 7 days left. For someone who will read over several days, add `--max-claims 5`.
+
+## What the other person sees
+
+A page that asks for the passcode, then a reading room over that one index: a search field, highlighted passages, and a document view. The page states that access is read-only, shows when it ends, and has a sign-out button.
+
+Email is shown as text. HTML in a message body is displayed as its source and never rendered, and addresses inside documents are not turned into links, because document text is other people's content.
+
+Search here means search. No text is generated and no model is called. Where the index has a `semantic_text` field the page uses the `hybrid` query, which fuses BM25 with the node's embedder. The default embedder is lexical feature hashing, so that ranking is word and sub-word overlap, not meaning. The page says which mode it is using.
+
+## What stays on your machine
+
+The documents and the index are not uploaded, synced or copied to a hosting service. The guest installs nothing. What does leave your machine is what the guest asks to see: search results and the documents they open, sent to their browser.
+
+With `--tunnel` that traffic passes through Cloudflare, which terminates the HTTPS connection. The folder is not uploaded there, but the operator of a TLS endpoint can read what passes through it: the passcode, the guest key, every search and every document the guest opens. The command prints this with the link, and the guest page shows it before the passcode is typed. The second article linked below covers that trade.
+
+## The limits on a share
+
+| Setting | Default | Bound |
+| --- | --- | --- |
+| lifetime (`--expires`) | 24h | up to 30 days |
+| times the link can be opened (`--max-claims`) | 1 | up to 50 |
+| passcode | generated, 8 symbols | or your own, 6 characters or more |
+| passcode attempts per share | 10 a minute | 30 an hour |
+
+A revoke invalidates every key the share produced. The guest's next request is refused.
+
+## What a share does not do
+
+It does not restrict what the guest reads inside the index. A share grants the whole index: there is no per-document or per-field restriction. If the folder holds things this person must not see, index a folder that does not.
+
+It does not stop the guest copying what they read. Read access is read access.
+
+It does not work on a node started with `--insecure`. With authentication off every request is already the superuser, so a read-only key would restrict nothing. `xerj share` refuses, says why, and exits 1.
+
+XERJ makes no legal claim about this arrangement. Whether sharing documents this way meets a professional or regulatory duty is a question for the people involved.
+
+## What was verified
+
+The folder path was run end to end on 2026-09-18 on a Linux host. The run: `xerj brain` on a folder of 3 files (two notes and one email), then `xerj share` on the same folder. Then a claim with the printed passcode, a guest search, and a walk of the folder's links. The same run confirmed that the guest key was refused the catalog index, `_cat/indices` and `/_share`. macOS and Windows were not run.
+
+XERJ is single-node: one process, one data directory, no replication. The share lives and dies with that host.
diff --git a/content/answers/share-local-search-index-through-a-tunnel.md b/content/answers/share-local-search-index-through-a-tunnel.md
new file mode 100644
index 000000000..2fc94ced7
--- /dev/null
+++ b/content/answers/share-local-search-index-through-a-tunnel.md
@@ -0,0 +1,110 @@
+---
+title: "Share a local search index through a tunnel"
+h1: "How do I let someone outside my network search an index on my laptop without opening a port?"
+description: "xerj share --tunnel starts your own cloudflared, prints a public guest link, and closes the tunnel and revokes the share on Ctrl-C. What the trade is."
+slug: "share-local-search-index-through-a-tunnel"
+cluster: "Sharing: read-only guest access"
+question: "How can I give a remote person temporary search access to files on my laptop without port forwarding or a VPN?"
+intent: "how-to"
+published: "2026-09-18"
+author: "XERJ documentation team"
+reviewer: "XERJ engineering team"
+schema_type: "TechArticle"
+agent_prompt: "Act as a coding agent. Read https://xerj.org/llms.txt. Confirm cloudflared is installed, then run xerj share on the user's indexed folder with --tunnel in the background, wait for the line that says the tunnel is up, and give the user the https link and the passcode separately. Tell them the link stops working when the command stops, and that stopping it revokes the share."
+commands:
+ - cmd: "xerj share ./casefiles --label 'for Dana' --tunnel"
+ note: "Open a temporary public address and print the full guest link. Runs until Ctrl-C, then closes the tunnel and revokes the share."
+ - cmd: "xerj share ./casefiles --tunnel --keep"
+ note: "Same, but leave the share active after Ctrl-C. The link stops working anyway, because the hostname is gone."
+ - cmd: "xerj share ./casefiles --public-url https://search.example.org"
+ note: "For a node you already publish at your own hostname: print the link for that address and open no tunnel."
+links_out:
+ - "share-folder-read-only-search-without-uploading"
+ - "what-a-share-link-guest-can-reach"
+ - "search-engine-without-docker"
+ - "/docs/security"
+evidence:
+ - claim: "xerj share --tunnel runs cloudflared tunnel --url against 127.0.0.1 and reads the trycloudflare.com hostname from its output."
+ source: "engine/crates/xerj-server/src/share.rs"
+ - claim: "A real quick tunnel was exercised on 2026-09-18: page 200, wrong passcode 401, claim 200, guest _cat 403, and after SIGINT the guest key answered 401 with 1 key invalidated."
+ source: "docs/usecases/share-links/VERIFICATION.md"
+ - claim: "A known share is limited to 30 passcode attempts an hour from anywhere, so the lockout does not depend on the source address."
+ source: "engine/crates/xerj-api/src/share.rs"
+ - claim: "Forwarded headers are read only when the peer is listed in server.trusted_proxies."
+ source: "engine/crates/xerj-console-api/src/client_ip.rs"
+faq:
+ - q: "How can I give a remote person temporary search access to files on my laptop without port forwarding or a VPN?"
+ a: "Run `xerj share` on the indexed folder with `--tunnel`. XERJ starts your own `cloudflared`, prints a public HTTPS link, and revokes the share when you stop the command."
+ - q: "What happens when I press Ctrl-C?"
+ a: "The tunnel is closed and the share is revoked, which invalidates every guest key it minted. Add `--keep` to leave the share active. The link still stops working, because the hostname is gone."
+ - q: "Do I need a Cloudflare account?"
+ a: "Not for a quick tunnel. You do need the `cloudflared` binary. If it is missing, `xerj share` prints the install steps for your platform and the local link, and does not fail."
+ - q: "Can Cloudflare read what my guest searches for?"
+ a: "It terminates the HTTPS connection, so in principle yes. The folder is not uploaded there, but everything between the guest's browser and your node crosses its network: the passcode, the guest key, the searches and the documents the guest opens. The command prints this with the link, and the guest page shows it. Use your own hostname and certificate with `--public-url` when that matters."
+ - q: "Why does the guest get a passcode and not a passkey?"
+ a: "A passkey is bound to a hostname, and a quick tunnel gets a new random hostname on every start. A passkey made through one tunnel would not work through the next."
+ - q: "Every guest arrives from 127.0.0.1 through a tunnel. Does that break the passcode lockout?"
+ a: "No. The lockout is charged to the share, not to the address: 30 attempts an hour from anywhere. Junk ids are charged to the source address, where one shared bucket only makes the bound tighter."
+---
+
+**TL;DR** — `xerj share` with `--tunnel` starts your own `cloudflared`, prints a public HTTPS guest link, and runs until you press Ctrl-C. Stopping it closes the tunnel and revokes the share. No port is opened on your router. The trade: the guest's traffic passes through Cloudflare, which terminates the TLS connection.
+
+## What the command does
+
+It checks that the node is enforcing authentication, then starts `cloudflared tunnel --url http://127.0.0.1:<port>` as a child process and reads the `trycloudflare.com` hostname from its output. The tunnel comes up before the share is created, so a link is never printed for an address that is not there.
+
+Then it creates the share and prints the full link, the passcode, the expiry and the revoke command. It keeps running while your guest reads.
+
+On Ctrl-C, on SIGTERM, or when the terminal closes, it terminates the tunnel and revokes the share. With `--keep` the share stays active on the node until it expires.
+
+If `cloudflared` is not installed, the command prints the install steps for your platform and the local link. It does not fail.
+
+## What was verified, and what was not
+
+On 2026-09-18 the command was run against a real quick tunnel from a Linux host and the public hostname was exercised over IPv4:
+
+| Request through the tunnel | Result |
+| --- | --- |
+| guest page | 200, with the full security header set |
+| claim with a wrong passcode | 401 |
+| claim with the right passcode | 200 |
+| guest search on the shared index | 200 |
+| guest `_cat/indices` | 403 |
+
+After SIGINT the `cloudflared` process was gone, the share listed as `revoked` with 1 key invalidated, and the guest key answered 401.
+
+That run cannot be repeated in CI, because it needs the public internet and a third party. It also predates the review fixes: the claim then carried the share id in its path, and the command did not yet print the Cloudflare notice. CI covers the hostname parser, the missing-`cloudflared` fallback, and a stub `cloudflared` that checks the notice and what happens when the tunnel dies. A browser was not driven through a real tunnel. The browser test serves the page under a `trycloudflare.com` name that points at the local node, and checks the page's notice there.
+
+## Three properties of a quick tunnel
+
+**The hostname is random and new on every start.** A link stops working when the command stops. That is the intended lifetime.
+
+**Cloudflare terminates TLS.** The corpus is not uploaded there. Everything between the guest's browser and your node does cross Cloudflare's network, and the operator of a TLS endpoint can read what passes through it. That includes the passcode, the guest's API key, every search and every document the guest opens. `xerj share --tunnel` prints this with the link. The guest page shows it on a `trycloudflare.com` address before the passcode is typed. When that is not acceptable, publish the node at your own hostname behind your own certificate and pass it as `--public-url`.
+
+**The share id is never in a URL the page requests.** The id is in the link's fragment, which a browser does not send. The page then sends it in the body of `POST /_share/claim`. So the id is not in the request line that a proxy or a tunnel logs. Cloudflare still carries that body and can read it, together with the passcode.
+
+**When the tunnel drops on its own, the command says why.** It prints the last lines `cloudflared` wrote, closes the tunnel and revokes the share.
+
+**It is temporary by design.** Cloudflare offers quick tunnels without an account and makes no promise about how long one stays up. For a standing arrangement use a named tunnel on your own domain, or your own reverse proxy.
+
+## Why guests do not get passkeys
+
+The XERJ Console signs its owner in with a passkey. A passkey is bound to the hostname it was created on, which is what makes it resistant to phishing. A quick tunnel gets a new random hostname each time it starts, so a passkey enrolled through one tunnel is unusable through the next.
+
+That is why a share is a link plus a passcode. The route to guest passkeys is a stable hostname: a named Cloudflare Tunnel on your own domain, optionally with Cloudflare Access in front, or any reverse proxy with your own certificate. Guest passkeys are not built.
+
+## The rate limiter behind a tunnel
+
+Through a tunnel every request reaches the node from `127.0.0.1`. A limiter keyed on the source address first would put every guest in one bucket, and a few junk requests would lock the real guest out.
+
+XERJ does not fix that by trusting `X-Forwarded-For`, because a direct client can write that header itself. A claim against a real share is charged to the share: 30 attempts an hour, from anywhere. Junk ids are charged to the source address. The two are not stacked.
+
+To log each guest's real address in the audit log, list loopback under `trusted_proxies` in the `[server]` section of the node's config and restart it. Only then is the forwarded header read. The command tells you which mode your node is in.
+
+## What this does not do
+
+`--tunnel` fronts a plain-http node on this machine only. For a node with TLS on, run your own tunnel or proxy and use `--public-url`.
+
+It does not work on a node started with `--insecure`. The command refuses before it opens a tunnel.
+
+XERJ is single-node. The share is reachable only while that one host and that one command are running.
diff --git a/content/answers/what-a-share-link-guest-can-reach.md b/content/answers/what-a-share-link-guest-can-reach.md
new file mode 100644
index 000000000..53bd50071
--- /dev/null
+++ b/content/answers/what-a-share-link-guest-can-reach.md
@@ -0,0 +1,114 @@
+---
+title: "What a XERJ share-link guest can and cannot reach"
+h1: "If I share one index with a link and a passcode, what can that person actually reach on my node?"
+description: "A share-link guest key reads the shared index and nothing else: no other index, no _cat or _cluster, no writes, no scroll or PIT. Each refusal is a live test."
+slug: "what-a-share-link-guest-can-reach"
+cluster: "Sharing: read-only guest access"
+question: "If I give someone a read-only share link to one search index, can they see my other indices or anything else on the server?"
+intent: "informational"
+published: "2026-09-18"
+author: "XERJ documentation team"
+reviewer: "XERJ engineering team"
+schema_type: "TechArticle"
+agent_prompt: "Act as a coding agent. Read https://xerj.org/llms.txt. On a throwaway XERJ node with authentication on, create a share with POST /_share, claim it with POST /_share/claim and a JSON body of {id, passcode}, then use the returned api_key to call /_cat/indices, /_cluster/health, a search on another index, a write to the shared index and a search with ?scroll=1m, and report the status code of each call."
+commands:
+ - cmd: "xerj share casefile --label 'for the auditor' --max-claims 1"
+ note: "Create a share over one index. Needs the node's admin key, read from the data directory."
+ - cmd: "curl -s -XPOST 'http://127.0.0.1:9200/_share/claim' -H 'content-type: application/json' -d '{\"id\":\"0123456789abcdef0123456789abcdef\",\"passcode\":\"abcd-2345\"}'"
+ note: "What the guest page does: exchange the share id and the passcode for a read-only key. Both travel in the body, so the id is not in the request line an access log records. This id and passcode are placeholders and return 404."
+ - cmd: "xerj share --revoke 8a1e546d4ee8"
+ note: "End a share by the handle that the list prints. Every key it minted is invalidated."
+links_out:
+ - "share-folder-read-only-search-without-uploading"
+ - "share-local-search-index-through-a-tunnel"
+ - "private-agent-memory-namespaces"
+ - "/docs/security"
+evidence:
+ - claim: "The guest route allow-list: _search, _count, _msearch, _mget, _mapping, _field_caps, GET _doc, and the graph ego and overview routes."
+ source: "engine/crates/xerj-api/src/authz.rs"
+ - claim: "The live test makes 237 checks against a node with authentication on and the access log on (225 without the native-listener section); all passed on 2026-09-19."
+ source: "docs/usecases/share-links/VERIFICATION.md"
+ - claim: "A share id is 128 bits and is stored as a SHA-256 digest; the passcode is stored as an Argon2id hash in a file with mode 0600."
+ source: "engine/crates/xerj-api/src/share.rs"
+ - claim: "Unknown share ids are limited to 10 a minute and 100 an hour per source address; a known share to 10 a minute and 30 an hour."
+ source: "engine/crates/xerj-api/src/share.rs"
+ - claim: "The guest page is served with default-src 'none' and frame-ancestors 'none'."
+ source: "engine/crates/xerj-console-api/src/spa.rs"
+faq:
+ - q: "If I give someone a read-only share link to one search index, can they see my other indices or anything else on the server?"
+ a: "No. The guest key is granted `read` on the shared index only, and a route allow-list closes everything that describes the node. Another index is a 403 by name, by alias and from inside a request body."
+ - q: "Can a guest list my indices with _cat/indices?"
+ a: "No. `_cat`, `_cluster`, `_nodes`, `_snapshot`, `_tasks` and `_stats` all return 403 to a guest key. An ordinary scoped key sees a filtered view of those; a guest sees none of it."
+ - q: "Can a guest write, delete or reindex?"
+ a: "No. Index, update, delete, bulk, delete-by-query, reindex, refresh, mapping and settings changes all return 403. The live test also confirms that no guest write landed."
+ - q: "Can a guest keep a scroll or a point-in-time open on my machine?"
+ a: "No. `scroll`, `_search/scroll`, `_pit` and `_async_search` are refused, and so is a `pit` clause in a search body, so a guest cannot ride a point-in-time that someone else opened."
+ - q: "What is stored on disk about a share?"
+ a: "A SHA-256 digest of the share id and an Argon2id hash of the passcode, in `shares.json` with mode 0600. No share id, passcode or guest key is written to that file, to the API-key file or to the audit log. The guest page sends the share id in a request body and never in a URL, so the node's access log does not hold it either."
+ - q: "What can a guest still do that I should think about?"
+ a: "Read every document in the shared index and copy what they read. A share grants whole indices. There is no per-document or per-field restriction to apply."
+---
+
+**TL;DR** — A share-link guest gets a key with `read` on the shared index and nothing else. A route allow-list, used for guests only, closes `_cat`, `_cluster`, every other index, all writes, and scroll and point-in-time contexts. Each refusal is a check in a live test that ran 237 checks on 2026-09-19, with 0 failures.
+
+## The key a guest is given
+
+Claiming a share mints an ordinary scoped API key with one role, named `share:` plus the share's handle. It carries `read` on the indices the share names and, when a brain is named, on that brain's edges index. It expires when the share does.
+
+Two things confine that key, and both are enforced by the server. The first is the index grants every scoped key gets. The second is a route allow-list that applies only to keys whose roles are all named `share:`. Being recognised as a guest only ever removes reach.
+
+## What is on the allow-list
+
+| A guest can call | On |
+| --- | --- |
+| `_search`, `_count`, `_msearch`, `_mget` | the shared indices |
+| `GET _doc/{id}` | the shared indices |
+| `_mapping`, `_field_caps` | the shared indices |
+| `GET /_graph/{brain}/ego` and `/overview` | the shared brain |
+| `GET /`, `_security/_authenticate`, health probes | the node |
+
+Nothing else. The allow-list can only refuse: a route it permits still goes through the index decision, so an index the guest was not granted is a 403 on a permitted route.
+
+## What was refused in the live test
+
+The test runs against a real node with authentication on. It seeds one shared index and one private index that holds a marker sentence, then looks for that sentence in every response.
+
+| Attempt | Result |
+| --- | --- |
+| `_cat/*`, `_cluster/*`, `_nodes`, `_snapshot`, `_tasks`, `_stats`, `_aliases`, the audit log, `/v1/metrics`, the native `/v1/*` router | 403 |
+| the private index by name, in a comma list, by `_search` with no index | 403, or an answer that holds shared documents only |
+| an alias that points at the private index | 403 |
+| `_msearch` and `_mget` bodies that name the private index | refused, no private text returned |
+| a `terms` lookup, a `more_like_this` like-document, a stored `percolate` document and a `lookup` runtime field that name the private index | no private text returned |
+| `?scroll=1m`, also as `SCROLL` and percent-encoded; `_search/scroll`; `_pit`; `_async_search` | 403 |
+| the owner's own point-in-time id and scroll id, presented by the guest | 403 |
+| index, update, delete, bulk, delete-by-query, reindex, refresh, close, mapping and settings changes | 403 |
+| another brain, writes to the shared brain, `/_memory/*` | 403 |
+| `GET /_share`, `POST /_share`, `DELETE /_share/{handle}`, `POST /_security/api_key` | 403 |
+| the Console API under `/_xerj-console/api/v1/` | 401: it takes a session cookie, not an API key |
+
+A pattern such as `_all` is not refused. It is expanded over what the key holds, so for a guest it means the shared indices and no more.
+
+## An alias is fixed when the share is made
+
+Sharing an alias pins the concrete indices it points at now. The test shares an alias, re-points it at another index, and confirms the guest still reads the first index and gets a 403 on the second.
+
+## The claim route
+
+`POST /_share/claim` is the one route on the node that hands out a credential without authentication, so it is narrow. It is `POST` only, its body is `{id, passcode}` and at most 4 KiB, it is never cached, and every outcome goes to the audit log with the source address.
+
+The share id is in the body and not in the path. A request path is what an access log, a reverse proxy and a tunnel write down by default; a body is not, unless a proxy is set up to log bodies. The test runs against a node with `logging.access_log = true` and looks in that log for every share id it made. It finds none.
+
+A claim against a known share is charged to that share: 10 a minute and 30 an hour, from anywhere. A claim against an unknown id is charged to the source address: 10 a minute and 100 an hour. The two are not stacked, so a flood of made-up ids cannot lock a real guest out, even when a tunnel makes every client arrive from the same address. The test floods the source bucket with a rotating `X-Forwarded-For` and then claims successfully from the same address.
+
+## What this does not cover
+
+A guest can read every document in the shared index, and its mapping. XERJ has no per-document or per-field restriction. That is also why the `autoindex-catalog` index is never granted: it lists every corpus on the node and could not be filtered. `POST /_share` refuses it by name, in a list and through an alias.
+
+Successful reads are only partly audited. The audit log holds a line for every claim outcome and every `_search`. It also holds a line for every request refused to an authenticated key, such as a guest's attempt to list, create or revoke a share or to mint a key. It holds no line for a successful `_msearch`, `_mget`, `_count`, `_mapping`, `_field_caps` or `GET _doc`. So a guest can read the whole shared index through those without a trace. It holds no line for an unauthenticated request other than a claim.
+
+Through `xerj share --tunnel`, Cloudflare ends TLS and can read the passcode, the guest key, the searches and the documents.
+
+Guest searches are not rate-limited. Authorization in XERJ comes from scoped API keys; roles are stored but not enforced. XERJ is single-node, so the share is only as available as that one host.
+
+The test ran on Linux. macOS and Windows were not run.
diff --git a/docs/SECOND_BRAIN.md b/docs/SECOND_BRAIN.md
index 23e58c0f3..a905dfcc6 100644
--- a/docs/SECOND_BRAIN.md
+++ b/docs/SECOND_BRAIN.md
@@ -516,6 +516,7 @@ The resource a brain authorizes against is its edges index,
| the configured admin key | every brain |
| a key minted with `role_descriptors` naming the edges index | that brain, at the granted privilege |
| a key minted without `role_descriptors` | no brain |
+| a share-link guest (`xerj share … --brain`, see [Sharing a brain](#sharing-a-brain)) | that brain, `read` only: `ego` and `overview`, never `link` or `unlink` |
| no or invalid credential | nothing |
`ego` and `overview` need `read`; `link` and `unlink` need `write`. Creating the
@@ -560,6 +561,15 @@ Two properties are worth calling out because they are deliberate:
with `write` on the brain) can point it anywhere, so hydration is authorized
against the resolved index in its own right. Without that, `write` on one
brain would be a read primitive for every index on the node.
+- **A multi-dataset `nodes_index` is authorized name by name.** `xerj brain`
+ records every dataset index a folder produced as one comma-joined string
+ (`"ax-mail,ax-pdfs"`). Each name in it is authorized on its own
+ (`graph_api.rs`, `authorize_nodes_index`), and one ungranted name refuses the
+ request. Before 2026-09-18 the whole string was compared to the key's grants
+ as a single index name, so every scoped key was refused `overview` and node
+ hydration on any brain over more than one dataset, and `overview` reported 0
+ notes for such a brain because it looked for an index called
+ `"ax-mail,ax-pdfs"`.
Enforcement is not limited to these four routes. A brain's edges live in an
ordinary index whose name merely starts with a dot, so it is nameable through
@@ -590,6 +600,44 @@ handlers do call `authz::authorize_memory_namespace` (for example
`memory_api.rs:318` and `memory_api.rs:490`); the comment is stale, the code is
not.
+## Sharing a brain
+
+`xerj share <folder>` gives one other person read-only search over the folder
+`xerj brain` indexed, through a link and a passcode. `xerj brain` prints the
+exact command in its closing summary, with each argument quoted when it needs to
+be (a folder called `case files` pastes as one argument):
+
+```
+ share it: xerj share /home/you/casefiles (read-only link + passcode for one person; the documents stay on this machine)
+```
+
+A folder argument resolves the way `xerj brain` named things: the brain is
+`derive_brain_name(<folder>)` (or `--brain`), and the indices are the
+`nodes_index` list in that brain's meta document
+(`engine/crates/xerj-server/src/share.rs`, `resolve_target`). A folder that was
+never indexed on this node is an error that says so, never a guess — and a wrong
+or non-admin key is reported as a key problem, not as a folder that was never
+indexed.
+
+The guest's key gets `read` on those indices and on the brain's edges index,
+and nothing else in the reserved namespace — not the `.xerj-memory-{brain}`
+memory namespace, not any other brain, and not `/_memory/*`. One consequence: a
+brain built through the HTTP API alone keeps its notes in
+`.xerj-memory-{brain}`, which a share never grants, so a guest of such a brain
+can walk its links with `ego` but is refused `overview` and node hydration
+(`403`). A brain built by `xerj brain` keeps its notes in the dataset indices
+the share names, and both work. On the graph API that means
+`GET /_graph/{brain}/ego` and `GET /_graph/{brain}/overview`; `link` and
+`unlink` are refused by the guest route allow-list before the privilege check is
+reached. `ego?nodes_index=` cannot be used to redirect hydration at an index the
+share does not name, alone or as one name in a list.
+
+The command refuses a node running in open mode, for the reason given above:
+brain isolation only exists on a server with authentication on.
+
+The whole feature — the command, what a guest can and cannot reach, the threat
+model, `--tunnel` — is in [SHARING.md](./SHARING.md).
+
## What is not covered here
- Console and MCP surfaces for the second brain exist but are not documented in
diff --git a/docs/SECURITY_MODEL.md b/docs/SECURITY_MODEL.md
index 992e44e58..02cb9e76b 100644
--- a/docs/SECURITY_MODEL.md
+++ b/docs/SECURITY_MODEL.md
@@ -18,6 +18,8 @@ Primary sources:
| Engine-side visibility funnel | `engine/crates/xerj-engine/src/index_guard.rs` |
| Privileges, roles, `role_descriptors` parsing | `engine/crates/xerj-engine/src/rbac.rs` |
| Console client identity and rate limiting | `engine/crates/xerj-console-api/src/client_ip.rs`, `.../auth/rate_limit.rs` |
+| Share links: records, claim route, claim limiter | `engine/crates/xerj-api/src/share.rs` |
+| Share-link guest route allow-list | `engine/crates/xerj-api/src/authz.rs` (`guest_route_allowed`, `guest_body_denied`) |
| Cluster control-frame authentication | `engine/crates/xerj-cluster/src/auth.rs` |
## The two layers
@@ -370,6 +372,109 @@ Broad RBAC over the general ES-compatible surface is not implemented. What is
enforced is the reserved namespace and the confinement of a `Scoped` key to its
named indices (`authz.rs:94-101`).
+## Share-link guests
+
+`xerj share` (`POST /_share`) lets the owner hand one person read-only access
+to named indices through a link and a passcode. The full description, including
+the threat model, is [SHARING.md](./SHARING.md); this section records where it
+sits in the model above.
+
+**A guest is a `Scoped` principal with one extra rule.** A successful claim
+mints an ordinary API key whose single role is named `share:<handle>`, with
+`read` on the share's indices and, when a brain is named, on that brain's edges
+index. It expires when the share does. Everything in
+[What a scoped key can and cannot do](#what-a-scoped-key-can-and-cannot-do)
+applies to it. On top of that, a key whose roles are *all* named `share:…`
+(`Principal::is_share_guest`, `auth.rs`) is subject to a **route allow-list**
+(`authz.rs`, `guest_route_allowed`) checked before the index decision:
+
+- index-scoped `_search`, `_count`, `_msearch`, `_mget`, `_mapping`,
+ `_field_caps`; `GET _doc/{id}`; `GET /_graph/{brain}/ego|overview`; the
+ exempt probes. Nothing else. (`GET _source/{id}` is not a route on this node,
+ and is not on the list.)
+- The cluster surface an ordinary scoped key sees *filtered* (`_cat`,
+ `_cluster/*`, `_nodes`, `_snapshot`, the global `_search`) is closed to a
+ guest outright, as are the native `/v1/*` router and `/v1/metrics`.
+- No server-side context: `scroll` as a query parameter (percent-decoded and
+ case-folded before it is compared), `_search/scroll`, `_pit` and
+ `_async_search` are refused. A `pit` clause in a `_search` or `_msearch` body
+ is refused too (`guest_body_denied`): a PIT, not the path, decides which index
+ a search runs against, and a guest can never have opened one. Before that
+ rule existed the engine funnel already refused the owner's PIT presented by a
+ guest — with a `404` that echoed the other index's name.
+
+Recognition is by role name and nothing else, which is safe in the only
+direction that matters: being recognised as a guest only ever *removes* reach.
+An operator who mints an ordinary key with a role descriptor called `share:x`
+gets a key that is more confined than they asked for, never less.
+
+**The allow-list can only refuse.** A route it permits still goes through the
+index decision and the engine funnel, so an index the guest was not granted is a
+`403` on a permitted route exactly as it is for any scoped key.
+
+**The claim route is the node's one unauthenticated credential-issuing route.**
+`POST /_share/claim` is exempted from authentication by exact path and method
+(`auth::is_share_claim_path`), never by prefix. Its body is `{id, passcode}`,
+capped at 4 KiB. The share id is in the body and never in a path, because a
+path is what an access log records: the first cut claimed at
+`POST /_share/{id}/claim`, and with `logging.access_log = true` the node wrote
+the id to its own log, as would any reverse proxy or tunnel in front of it. It
+is rate-limited (next section), answers `Cache-Control: no-store` on every
+outcome, and audits every outcome with the source address — only the first
+refusal per throttle window, so a flood cannot evict the ring. It refuses with
+`409` on a node running with authentication off, where a scoped key would
+restrict nothing.
+
+**Management is superuser-only.** `POST /_share`, `GET /_share` and
+`DELETE /_share/{handle}` return `403` to every principal except the admin key
+(`share.rs`, `require_superuser`). A scoped key must not widen its own reach by
+minting a share, and an unscoped key must not hand a guest a brain it cannot
+reach itself. A refusal is audited whichever layer produced it: the handler
+records the ones it sees, and the request-level audit layer records the ones
+the authorization middleware stopped before any handler ran
+(`authz::RefusedBeforeHandler`, `audit_mw.rs`) — which is every management call
+a guest key makes, and a guest's `POST /_security/api_key` as well.
+
+**Nothing a guest receives may be cached.** Every response to a guest key, and
+every response under `/_share` including the `401` and `403` the middleware
+produces, carries `Cache-Control: no-store`.
+
+**At rest.** `<data_dir>/shares.json`, mode `0600`, written by the same atomic
+secret-file writer as `api_keys.json`. It holds a SHA-256 digest of the share id
+and an Argon2id hash of the passcode — a slow hash here, unlike minted API-key
+secrets, because a passcode is short and may have been chosen by a person. The
+guest's key is minted at claim time; the record keeps only key *ids*, so a
+revoke can invalidate every key the share produced.
+
+All of the above is exercised against a running node by
+`engine/crates/xerj-api/tests/live/share_security_live.py`.
+
+## The share-claim limiter, and why it does not key on the source first
+
+`share.rs` carries its own sliding-window limiter (same shape as the Console's,
+re-implemented because this crate must not depend on the Console):
+
+- a claim against a **known** share id charges that share's window — 10 a
+ minute, 30 an hour, from anywhere. This is the passcode lockout;
+- a claim against an **unknown** id charges the source address's window — 10 a
+ minute, 100 an hour. IPv6 sources are keyed by their /64. State is bounded at
+ 50,000 windows; past that, unseen sources share one overflow bucket.
+
+The source address is resolved exactly as the Console resolves it (`share.rs`
+`ClaimSource`; the rules are in
+[The Console rate limiter keys on the socket peer](#the-console-rate-limiter-keys-on-the-socket-peer)):
+the TCP peer, with `X-Forwarded-For` believed only when the peer is in
+`server.trusted_proxies`.
+
+The two are not stacked, because of tunnels. Behind `xerj share --tunnel`, or
+any reverse proxy on the same host, every request arrives from `127.0.0.1`. A
+limiter that charged the source first would put every guest in one bucket, and
+ten junk requests a minute would answer every real guest with `429`. Rather
+than believe a header a direct client can write, the collapsed bucket is made
+not to matter: a real share id is governed by its own window, which junk cannot
+touch. An operator who wants real guest addresses in the audit log declares
+loopback in `server.trusted_proxies`; the lockout holds either way.
+
## Snapshot and restore
Snapshot and restore are the one place where a wildcard is decided by the
@@ -723,9 +828,12 @@ it is on a schedule this document can promise.
`AuditRead`. Every mutating request that passes authentication leaves one
entry naming the caller — a bulk is one entry with its item counts, not one
per document — and a refused request is recorded as `denied`, reads included:
- a `403` on `_search`, on `GET _doc`, or on `/_audit/*` itself leaves an entry
+ a `403` on `_search`, on `GET _doc`, on `/_audit/*` itself, or on the
+ self-auditing `/_share` and `/_security/api_key` routes leaves an entry
naming the credential that reached for it. What is **not** in it: reads that
- *succeeded*, other than `_search` (`_mget`, `_count`, `GET _doc`, `_cat`),
+ *succeeded*, other than `_search` (`_msearch`, `_mget`, `_count`, `_mapping`,
+ `_field_caps`, `GET _doc`, `_cat`) — a share-link guest can read a whole
+ shared index through those without a line —
unauthenticated attempts (recorded nowhere but the access log — auditing them
would let anyone who can reach the port evict the ring), and anything older
than the last 4096 entries. Long-term retention means shipping entries off
@@ -762,6 +870,22 @@ it is on a schedule this document can promise.
[Transport encryption](#transport-encryption-listener-by-listener).
- **No encryption at rest at the engine level.** The startup banner says to use
OS full-disk encryption or bucket-side encryption instead (`main.rs:318`).
-- **Rate limiting covers three Console auth endpoints only.** There is no
- general per-IP request throttle on the data plane (`rate_limit.rs`, and the
- three call sites listed above).
+- **Rate limiting covers three Console auth endpoints and the share-claim
+ route only.** There is no general per-IP request throttle on the data plane
+ (`rate_limit.rs` and the three call sites listed above; `share.rs` for the
+ claim route). A share-link guest's searches are not rate-limited.
+- **A share grants whole indices.** There is no document-level or field-level
+ restriction to apply to a guest, so a share exposes every document in the
+ indices it names, and their mappings. The `autoindex-catalog` index is never
+ granted for the same reason — it could not be filtered — and `POST /_share`
+ refuses it by name, in a list and through an alias.
+- **`xerj share --tunnel` puts a third party on the path.** A Cloudflare quick
+ tunnel terminates TLS at Cloudflare, so everything between the guest's browser
+ and the node crosses Cloudflare's network in a form its operator could read:
+ the passcode, the minted guest key, every search and every document opened.
+ The corpus is not uploaded there. The CLI prints this with the link
+ and the guest page shows it on a `trycloudflare.com` hostname. Use your own
+ hostname and certificate (`--public-url`) when that matters.
+- **No guest passkeys.** A passkey binds to a hostname and a quick tunnel gets
+ a new one on every start, so guests authenticate with link + passcode
+ ([SHARING.md](./SHARING.md#passkeys-and-why-guests-use-a-link-and-a-passcode)).
diff --git a/docs/SHARING.md b/docs/SHARING.md
new file mode 100644
index 000000000..d9899614e
--- /dev/null
+++ b/docs/SHARING.md
@@ -0,0 +1,404 @@
+# Sharing an indexed folder
+
+`xerj share` gives one person read-only search over one indexed folder: a link,
+a passcode and an expiry. The guest opens the link in a browser, types the
+passcode, and gets a reading room — a search box, highlighted snippets and a
+document view — over that one index and nothing else on the node.
+
+The documents and the index stay on your machine. Nothing is uploaded, synced
+or copied to a hosting service, and the guest installs nothing. What does leave
+the machine is what the guest asks to see: search results and the documents
+they open, sent to their browser. Who else can read that traffic depends on how
+the link reaches your node: nobody on a loopback link, whoever is on the network
+path for a plain-`http` address, and **Cloudflare** for a `--tunnel` link — see
+[`--tunnel`](#--tunnel). The command says which of these applies when it prints
+the link.
+
+"Zero-token" in this document means search and reading. The reading room
+generates no text, summarises nothing and calls no model.
+
+Every statement below points at the code or the test that makes it true.
+Primary sources:
+
+| Area | File |
+|---|---|
+| `/_share` API, records, passcode, claim limiter | `engine/crates/xerj-api/src/share.rs` |
+| Guest route allow-list, PIT refusal | `engine/crates/xerj-api/src/authz.rs` (`guest_route_allowed`, `guest_body_denied`) |
+| `xerj share` CLI and the tunnel supervisor | `engine/crates/xerj-server/src/share.rs` |
+| Guest page | `xerj-ux/share/` |
+| Guest page serving and its header set | `engine/crates/xerj-console-api/src/spa.rs` |
+| Live security test | `engine/crates/xerj-api/tests/live/share_security_live.py` |
+| Headless-browser test of the guest flow | `xerj-ux/test/share-guest-flow.e2e.mjs` |
+| One script that runs all of it | `.github/scripts/share-links-smoke.sh` |
+
+## Quick start
+
+```sh
+# 1. index the folder (boots a local node with authentication ON)
+xerj brain ~/casefiles
+
+# 2. share it — prints a link, a passcode, the expiry and how to revoke
+xerj share ~/casefiles --label "for Dana" --expires 7d
+
+# 3. for someone who is not on this machine: a temporary public address
+xerj share ~/casefiles --label "for Dana" --tunnel
+```
+
+`xerj brain` prints, in its closing summary, the exact `xerj share` command for
+the folder it just indexed, including `--url` and `--data-dir` when they are not
+the defaults. Each argument is quoted when it needs to be, so a folder called
+`case files` pastes as one argument.
+
+**One open is one browser tab.** The guest's key lives in that tab's
+`sessionStorage`. Opening the same link again in the same tab keeps the session
+and spends nothing; a closed tab is a spent open. With the default
+`--max-claims 1`, a guest who closes the tab cannot come back, however long the
+share has left to run. For someone who will read over several days, give a few:
+`--max-claims 5`.
+
+Send the link and the passcode **through different channels** — the link by
+email, the passcode by phone or a messenger. Either one alone opens nothing.
+
+## The command
+
+```text
+xerj share <index|folder> [OPTIONS] create a share
+xerj share --list every share on this node
+xerj share --revoke <handle> end one (invalidates its guest keys)
+```
+
+| Option | Meaning |
+|---|---|
+| `<index\|folder>` | An index name (`ax-notes`, or `a,b`), or the folder you gave `xerj brain`. A folder resolves to the brain `xerj brain` built for it and to the indices that brain's meta document lists. |
+| `--expires <D>` | Lifetime: `30m`, `24h`, `7d`. Default `24h`, longest `30d`. |
+| `--max-claims <N>` | How many times the link can be opened. Default `1`, most `50`. Each claim mints its own guest key. One open is one browser tab (see above). |
+| `--passcode <CODE>` | Choose the passcode (6–128 characters). Default: a generated `xxxx-xxxx`. A passcode typed on the command line lands in your shell history; the generated one does not. |
+| `--label <TEXT>` | What the guest sees as the title. |
+| `--brain <NAME>` | Also share this brain's links. A folder argument sets it for you. |
+| `--index` | Treat the argument as an index name even when a folder of that name exists. |
+| `--tunnel` | Open a temporary public address with `cloudflared`, print the full guest link, run until Ctrl-C, then close the tunnel **and revoke the share**. The traffic passes through Cloudflare, which can read it; the command says so when it prints the link. |
+| `--keep` | With `--tunnel`: leave the share active after Ctrl-C. |
+| `--public-url <U>` | The `https://` address this node is already reachable at; the printed link uses it. `http://` is accepted with a printed warning: the passcode and the guest key would cross the network unencrypted. |
+| `--url`, `--data-dir`, `--api-key` | The node (scheme included: `http://localhost:9200`), where its `admin.key` is, or the admin key itself (also `XERJ_API_KEY`). Same resolution order as `xerj brain`. |
+| `--json` | Machine-readable output. |
+
+Exit codes: `0` ok, `1` refused or failed, `2` usage, `130` interrupted before
+the tunnel was up (nothing was shared).
+
+Shares are managed with the node's **admin key** and nothing less. A scoped or
+minted key gets `403` on `POST /_share`, `GET /_share` and
+`DELETE /_share/{handle}` — otherwise a key could widen its own reach by minting
+a share (`share.rs`, `require_superuser`). A wrong or non-admin key is reported
+as a key problem whether the argument is an index or a folder.
+
+### It refuses an open node
+
+A node started with `--insecure` (or `auth.enabled = false`) treats every
+request as the superuser. A "read-only guest key" on such a node restricts
+nothing: the guest, and anyone else who can reach the port, can already read,
+change and delete every index without it. `xerj share` therefore refuses, says
+why, and exits `1`; the node answers `POST /_share` and the claim route with
+`409` (`share.rs`, `open_node_refusal`). Restart the node without `--insecure` —
+authentication is on by default and the admin key is written to
+`<data_dir>/admin.key`.
+
+### `--tunnel`
+
+`--tunnel` runs your own `cloudflared` as a child process
+(`cloudflared tunnel --url http://127.0.0.1:<es port>`), reads the
+`https://….trycloudflare.com` hostname from its output, and prints the full
+guest link. The tunnel comes up **before** the share is created, so a link is
+never printed for an address that is not there. On Ctrl-C (and SIGTERM, and a
+closed terminal) the tunnel is terminated and the share is revoked, which
+invalidates every guest key it minted.
+
+If `cloudflared` is not installed the command does not fail: it prints the exact
+install steps for your platform and the local link. It looks at
+`XERJ_CLOUDFLARED`, then `PATH`, then `~/.local/bin`.
+
+Verified on 2026-09-18 against a real quick tunnel: the guest page, a wrong and
+a right passcode, a guest search and a refused `_cat` call all went through the
+public hostname; after SIGINT the `cloudflared` process was gone, the share
+listed as `revoked`, and the guest key answered `401`. That run cannot be
+repeated in CI — it needs the public internet and a third party — so CI covers
+the hostname parser, the fallbacks and everything that does not need the tunnel
+itself.
+
+When `cloudflared` stops on its own, the command revokes the share and prints
+`cloudflared`'s last lines, which are the only explanation there is.
+
+Three things to know about quick tunnels:
+
+- **The hostname is random and new on every start.** A link stops working when
+ the command stops. That is the intended lifetime, not a fault.
+- **Traffic passes through Cloudflare, which terminates TLS.** The corpus is not
+ uploaded there. Everything the guest's browser and your node say to
+ each other does travel through Cloudflare's network, and the operator of a TLS
+ endpoint can read what passes through it: **the passcode, the guest's API key,
+ every search and every document the guest opens.** `xerj share --tunnel`
+ prints this with the link, `--help` says it under `--tunnel`, and the guest
+ page shows a notice on a `trycloudflare.com` hostname before the passcode is
+ typed. If that is not acceptable, publish the node at your own hostname behind
+ your own TLS and use `--public-url`.
+- **Cloudflare offers quick tunnels without an account and without an uptime
+ guarantee.** For a standing arrangement use a named tunnel or your own
+ reverse proxy with a stable hostname.
+
+`--tunnel` fronts a plain-http node on this machine only. For a node with TLS
+on, run your own tunnel or proxy and pass its address as `--public-url`.
+
+## What the guest can and cannot do
+
+The guest's key carries one role, `share:<handle>`: `read` on the indices the
+share names, plus `read` on the shared brain's edges index when a brain is
+named. Two things confine it, both enforced server-side:
+
+1. **The index grants** — the per-index authorization every scoped key gets, in
+ the middleware and again at the engine's index funnel
+ (see [SECURITY_MODEL.md](./SECURITY_MODEL.md#the-two-layers)).
+2. **A route allow-list that applies to share guests only**
+ (`authz.rs`, `guest_route_allowed`). An ordinary scoped key is given a
+ *filtered* view of `_cat`, `_cluster/*` and `_nodes` because Kibana needs
+ one. A guest was handed one corpus by someone who did not agree to describe
+ their node, so for a guest that surface is closed outright.
+
+| A guest can | A guest cannot |
+|---|---|
+| `_search`, `_count`, `_msearch`, `_mget` on the shared indices | search, count, fetch or map any other index — by name, by pattern, by alias, or by naming it inside a request body |
+| `GET _doc/{id}` (and `HEAD`) on the shared indices | write, update, delete, bulk, reindex, refresh, flush, close, or change a mapping or a setting |
+| `_mapping` and `_field_caps` on the shared indices | read `_cat/*`, `_cluster/*`, `_nodes`, `_snapshot`, `_tasks`, `_stats`, `_aliases`, index templates, ingest pipelines, `/v1/metrics`, the native `/v1/*` router |
+| `GET /_graph/{brain}/ego` and `/overview` for the shared brain | read or write another brain, write to the shared brain, use `/_memory/*` |
+| read `GET /`, `_security/_authenticate`, the health probes | list, create or revoke shares; mint an API key; read the audit log |
+| | open a scroll, a point-in-time or an async search — nothing that parks state on your machine — or ride one that someone else opened |
+| | use the Console API (`/_xerj-console/api/v1/*`), which takes a session cookie and not an API key |
+
+A pattern such as `_all` or `*` is not refused: it is expanded over what the
+key **holds**, so for a guest `_all` means "all of yours". It never means more.
+
+The allow-list covers both HTTP listeners (the ES-compatible port and the
+native REST port). The **gRPC listener** is outside it: it applies the same
+per-index grants. An in-process test drives the real gRPC interceptor and
+handlers with a claimed guest key: it reads the shared index, and gets
+`PermissionDenied` on every other index, on patterns, on system indices and on
+`index` and `delete` (`bulk_index` needs a transport to call; it runs the same
+per-item check as `index`), and `Unauthenticated` after a revoke
+(`xerj-server/src/grpc.rs`, `a_share_guest_key_reads_its_index_over_grpc_and_nothing_else`).
+No test opens a gRPC socket with a guest key. The listener binds to loopback by
+default and is not reachable through `--tunnel`, which fronts the ES-compatible
+port only.
+
+The `autoindex-catalog` index, which lists every corpus on the node, is **never**
+granted. A folder share does not include it, and it cannot be shared by name, in
+a list or through an alias: `POST /_share` answers `400` (`share.rs`,
+`validate_share_index`). The engine has no document-level security to filter it
+with, and the guest page is handed the index name directly.
+
+There is no `GET /{index}/_source/{id}` route on this node (`404` for the admin
+key), so it is not on the guest allow-list either; `GET _doc/{id}` returns the
+source.
+
+Every row of that table is a check in
+`engine/crates/xerj-api/tests/live/share_security_live.py`, which runs against a
+real node with authentication on. It includes the indirect routes: a `terms`
+lookup, a `more_like_this` like-document, a `percolate` stored document, an
+`indexed_shape` and a `lookup` runtime field that each name a private index from
+inside an otherwise permitted search; an `_msearch` header and an `_mget` body
+that name another index; aliases that point elsewhere; and the owner's own
+point-in-time and scroll ids presented by the guest.
+
+### An alias is resolved when the share is made
+
+Naming an alias in `xerj share` (or `POST /_share`) records the **concrete
+indices it points at now**. Re-pointing the alias later does not move, or widen,
+what a guest already holds. The backing names go through the same validation as
+any other, so an alias is not a way to share a system index.
+
+### What can never be shared
+
+A share names concrete indices of yours. Patterns and lists-as-patterns
+(`logs-*`), `_all`, every dot-index (`.xerj_sessions`, `.xerj_api_tokens`,
+`.xerj_passkeys`, `.xerj_audit`, …), the reserved `.xerj-memory-*` namespace and
+the `autoindex-catalog` index are refused with `400`. A brain's links are shared by naming the brain, which
+grants its edges index and nothing else in the namespace.
+
+## Threat model
+
+### What a share protects against
+
+| Threat | What stands in the way |
+|---|---|
+| Someone finds or guesses the link | The share id is 128 bits from the OS CSPRNG. The link alone opens nothing: the passcode is a second factor sent separately. |
+| Someone has the link and guesses passcodes | A lockout per share, from anywhere: 10 attempts a minute and 30 an hour (`SHARE_PER_MINUTE`, `SHARE_PER_HOUR`). A generated passcode is 8 symbols from a 31-symbol alphabet — 852,891,037,441 codes, about 39.6 bits. Thirty guesses an hour for the 30-day maximum lifetime is 21,600 guesses. |
+| The node's disk is read | `shares.json` (mode `0600`) holds a SHA-256 digest of the share id and an Argon2id hash of the passcode (`m=19456,t=2,p=1` in the records this build writes). No share id, passcode or guest key is written to `shares.json`, to `api_keys.json` or to the audit log. The CLI and the guest page never put a share id in a URL, so the node's own log does not hold one either, also with `logging.access_log = true` (the smoke script turns it on to check exactly that). |
+| The link leaks into a log | The share id is never part of a URL the guest page requests. It rides in the URL **fragment**, which a browser does not send to a server, so the page request and every `Referer` are free of it. The page then sends it in the **body** of `POST /_share/claim` — not in the path, which is what an access log, a reverse proxy and a tunnel's edge record — and removes it from the address bar. The browser test asserts the id is in no requested URL and only in the claim body. A proxy configured to log request *bodies* would still record it, together with the passcode. The HTTP API's `DELETE /_share/{handle}` also accepts the full id; a caller who uses it that way puts the id in a request path, and revokes it. `xerj share --revoke` takes only the handle. |
+| A proxy or browser caches the credential | Every `/_share` response — success or error, including the `401` and `403` the authentication and authorization layers produce — is `Cache-Control: no-store`. So is every response to a guest key (search results, documents, refusals), and so are the guest page and its assets. |
+| A document tries to attack the guest | Document text is other people's email and is treated as hostile. The page places it with `textContent` only — there is no `innerHTML`, `eval` or HTML parsing in `share.js`, HTML email bodies are shown as source text, and URLs in documents are not made into links. Independently of that, the page is served with `Content-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`, so injected markup could neither run nor fetch. `Referrer-Policy: no-referrer`, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`. |
+| The guest wanders | The route allow-list and the index grants above. |
+| A link that outlives its purpose | Expiry (default 24 hours, at most 30 days), a claim limit (default 1), `xerj share --revoke`, and `--tunnel` revoking on exit. A revoke invalidates every key the share minted; the guest's next request is refused. |
+| Junk traffic locks the real guest out | See the next section. |
+
+### The claim route and its limiter
+
+`POST /_share/claim` is the only unauthenticated route on the node that hands
+out a credential, so it is narrow on purpose: one exact path, `POST` only, a
+body of at most 4 KiB, rate-limited, never cached, and every outcome — success,
+wrong passcode, exhausted, expired, revoked, unknown, throttled — goes to the
+audit log with the source address. Only the *first* refusal in a throttle window is audited, so a
+flood cannot turn the audit log into its own denial of service.
+
+There are two throttles, and they are deliberately **not** stacked:
+
+- A claim against a **known** share is charged to that share's window, from
+ anywhere. This is the passcode lockout, and it does not depend on knowing who
+ is asking.
+- A claim against an **unknown** id is charged to the source address's window
+ (10 a minute, 100 an hour; IPv6 sources are keyed by their /64).
+
+Behind `--tunnel` — or any reverse proxy on the same host — every request
+arrives from `127.0.0.1`. A limiter that charged the source address first would
+collapse every guest into one bucket, and ten junk requests a minute from
+anyone who had found the hostname would answer every real guest with `429`.
+The fix is not to believe `X-Forwarded-For`: a direct client writes that header
+itself. It is to stop the collapsed bucket from mattering — a real share id is
+governed by its own window, which junk cannot touch, and junk is governed by the
+source window, where collapsing every tunnel client into one bucket only makes
+the bound tighter. The live test floods the source bucket from the same address
+as the guest, with a rotating spoofed `X-Forwarded-For`, and then claims
+successfully.
+
+To record each guest's real address in the audit log, declare the proxy the way
+the Console already requires:
+
+```toml
+[server]
+trusted_proxies = ["127.0.0.1", "::1"]
+```
+
+Then, and only then, `X-Forwarded-For` is read, right to left, skipping declared
+proxies — the same reading as the Console's `client_ip.rs` (#76 S5-4). An
+unconfigured node believes nobody. `xerj share --tunnel` tells you which of the
+two your node is doing.
+
+One consequence to accept: someone who **has the link** can spend that share's
+30 guesses an hour and lock the real guest out for the rest of the hour. They
+cannot get in, and they need the 128-bit link to do it. The alternative — no
+lockout for holders of the link — is a passcode that can be brute-forced.
+
+### What a share does not protect against
+
+- **The guest.** Read access is read access. A guest can copy, screenshot or
+ retype anything they can open, and there is no watermarking or download
+ control. Share an index you are content for that person to read in full.
+- **No per-document or per-field restriction.** A share grants whole indices.
+ The engine has no document-level or field-level security
+ ([SECURITY_MODEL.md](./SECURITY_MODEL.md#known-limits)). If a folder holds
+ things the guest must not see, index a folder that does not.
+- **Link and passcode sent together.** Whoever holds both is the guest, until
+ the share expires, is used up, or is revoked.
+- **An observer on the path.** A local link is plain `http` on loopback. A link
+ to a LAN or public `http://` address is readable by anyone on the path, and
+ the command says so. A `--tunnel` link is HTTPS to Cloudflare, which
+ terminates it and can read the passcode, the guest key and the documents (see
+ above). For end-to-end TLS you control, publish the node behind your own
+ certificate.
+- **A compromised guest browser.** The guest key lives in that tab's
+ `sessionStorage` until the tab closes or the guest signs out.
+- **Successful reads are only partly audited.** The audit log records every
+ claim outcome, every `_search`, and every request an authenticated key was
+ **refused** (`403`) — including a guest's attempt to list, create or revoke a
+ share or to mint an API key. It does **not** record a successful `_msearch`,
+ `_mget`, `_count`, `_mapping`, `_field_caps` or `GET _doc`: a guest can read
+ the whole shared index through those without leaving a line. It records
+ nothing for an unauthenticated request (`401`) other than a claim
+ ([SECURITY_MODEL.md](./SECURITY_MODEL.md#known-limits)).
+
+XERJ makes no legal claim about any of this. Whether sharing documents this way
+satisfies a professional, contractual or regulatory duty is a question for the
+people involved and their advisers, not for this document.
+
+## Passkeys, and why guests use a link and a passcode
+
+The Console's own sign-in is a passkey. A passkey is bound to the **hostname**
+it was created on — that binding is what makes it phishing-resistant — and a
+quick tunnel gets a new random hostname every time it starts. A passkey
+enrolled through one tunnel would be unusable through the next, so a guest
+cannot be given one over a quick tunnel.
+
+That is why a share is a link plus a passcode. The path to guest passkeys is a
+**stable hostname**: a named Cloudflare Tunnel on your own domain (optionally
+with Cloudflare Access in front of it), or any reverse proxy with your own
+certificate, passed to `xerj share` as `--public-url`. Guest passkeys are not
+built; the stable hostname is the prerequisite for building them.
+
+## The guest page
+
+The page is `xerj-ux/share/`, bundled into the binary and served at
+`/_xerj-console/share` without a session — the guest has no credential until the
+page has exchanged the passcode for one. It is buildless and self-contained: no
+third-party script, font, stylesheet or image, and the browser test asserts that
+every request it makes goes to the node itself.
+
+1. It reads the share id from `location.hash`.
+2. It asks for the passcode and posts `{id, passcode}` to `POST /_share/claim`.
+ The id is in the body, never in a URL.
+3. On success it stores the session record, in `sessionStorage` (scoped to the
+ tab, gone when it closes):
+
+ ```js
+ sessionStorage['xerj.share'] = JSON.stringify({api_key, index, brain, expires_at, label})
+ ```
+
+ The Console's guest mode reads the same record, which is why its shape is
+ fixed. Beside it the page keeps `xerj.share.link`: the share's public
+ **handle** (the 12 characters `xerj share --list` shows), which cannot be
+ turned back into the link. That is how the page recognises the same link
+ opened again in the same tab and keeps the session instead of asking for —
+ and spending — another claim. A different link asks for its own passcode, and
+ the session the tab holds is replaced only when that claim succeeds. A link
+ pasted over another one changes only the fragment; the page listens for that.
+4. It learns the mapping and searches: the `hybrid` query (BM25 fused with the
+ node's embedder) where the index has a `semantic_text` field, `multi_match`
+ over the text fields otherwise. It says which on the page. The default
+ embedder is lexical feature hashing, so hybrid here is not "semantic AI": it
+ ranks by word and sub-word overlap. A hybrid hit that contains none of the
+ query's words is labelled as ranked by vector similarity, and when no listed
+ hit contains them the page says "No document contains …" before the list.
+5. It shows the expiry, a read-only notice, and a sign-out that clears
+ `sessionStorage`. On a `trycloudflare.com` hostname it also shows that
+ Cloudflare carries the connection and can read it.
+
+## The HTTP API
+
+| Route | Who | Body / result |
+|---|---|---|
+| `POST /_share` | admin key | `{index: "a" \| ["a","b"], brain?, expires_in?: "24h", max_claims?: 1, passcode?, label?}` → the record plus `share_id`, `url_path`, `passcode` — the only time either plaintext is shown |
+| `GET /_share` | admin key | `{shares: [{handle, label, indices, brain, created_at, expires_at, max_claims, claims, claims_left, status}]}` — no ids, no hashes |
+| `DELETE /_share/{handle}` | admin key | `{handle, revoked: true, keys_invalidated}`. The full share id is accepted in place of the handle, but then it is in the request path; the CLI sends only the handle. |
+| `POST /_share/claim` | anyone, rate-limited | `{id, passcode}` → `{api_key, index, indices, brain, expires_at, label, claims_left}`; `401` wrong passcode, `404` unknown link, `410` expired / used up / revoked, `429` with `Retry-After`, `409` on an open node. The share id is in the body so that it is not in the request line an access log records. |
+
+`api_key` is ready for `Authorization: ApiKey <api_key>`. `index` is the
+comma-joined list, which is a valid multi-index expression for
+`/{index}/_search`.
+
+## Verifying it yourself
+
+```sh
+(cd engine && cargo build --release -p xerj-server)
+bash .github/scripts/share-links-smoke.sh
+```
+
+The script boots throwaway nodes on `127.0.0.1:9510–9512` (override with
+`XERJ_SHARE_PORT`), and refuses to run against a port that already answers. It
+runs the live security test with and without a trusted proxy (the first node
+with `logging.access_log = true`, so that "no share id in the node's log" is
+checked against a node that logs), the CLI — including `--tunnel` against a stub
+`cloudflared` — the headless-browser guest flow (Chrome or Chromium;
+`CHROME_BIN` to point at one), the open-node refusal, and the `xerj brain` →
+`xerj share <folder>` path. Do not start it on port `10080` or any other port
+browsers refuse (`ERR_UNSAFE_PORT`): the browser phase cannot reach the node
+there. CI
+runs the same script in the `usecase-smoke` job.
+
+The record of what was run on this branch, on which build, with which result —
+including the by-hand quick-tunnel run that CI cannot repeat — is
+[docs/usecases/share-links/VERIFICATION.md](./usecases/share-links/VERIFICATION.md).
diff --git a/docs/usecases/share-links/VERIFICATION.md b/docs/usecases/share-links/VERIFICATION.md
new file mode 100644
index 000000000..1c7d123f6
--- /dev/null
+++ b/docs/usecases/share-links/VERIFICATION.md
@@ -0,0 +1,239 @@
+# Share links — verification record
+
+What was run to verify `xerj share`, the `/_share` API and the guest page, on
+which build, with which result. Every number cited by the share-link docs and
+answers traces to a line on this page. Runs 1 and 2 and the tunnel run are
+from 2026-09-18; run 3, after the review of PR #947, is from 2026-09-19.
+
+Environment: Linux x86_64, release build of `xerj-server` from branch
+`feat/share-links` — runs 1 and 2 rebased on `main` at `4d8dadbf`, run 3 on the
+branch head named in its section — `cloudflared` 2026.7.3 from the operator's
+`~/.local/bin`, Google Chrome (headless) for the browser flow, Python 3 for the
+live test. macOS and Windows: **not verified**.
+
+## What the smoke script covers, and what it does not
+
+`.github/scripts/share-links-smoke.sh` boots throwaway nodes on
+`127.0.0.1:9510–9512` (`XERJ_SHARE_PORT` moves them) and runs, in order:
+
+| Phase | What | Where |
+|---|---|---|
+| A | live security test, authentication on, no trusted proxy, `logging.access_log = true` so the "no share id in the node's log" checks test a node that logs | `engine/crates/xerj-api/tests/live/share_security_live.py` |
+| B | the CLI: create, `--list`, `--revoke`, `--json`, the error paths (folder + wrong key, `--url` without a scheme, the catalog refusal, `--public-url http://`), `--tunnel` without `cloudflared`, and `--tunnel` against a stub `cloudflared` (the Cloudflare notice; its last lines when it dies) | same script |
+| C | the guest page in headless Chrome, on a fresh node with the access log on: claim, search, read, an XSS probe document, the same link re-opened, a link pasted over another, the quick-tunnel notice, sign-out | `xerj-ux/test/share-guest-flow.e2e.mjs` |
+| D | the live security test again with `server.trusted_proxies = ["127.0.0.1", "::1"]` | — |
+| E | the refusal: `xerj share` against an `--insecure` node | — |
+| F | `xerj brain <folder>` → `xerj share <folder>`: the folder resolves to the brain and its indices | — |
+
+CI runs the same script in the `usecase-smoke` job with
+`XERJ_SHARE_REQUIRE_BROWSER=1`, so a missing Chrome fails the job rather than
+skipping phase C.
+
+**Not covered by the script, and why:** `--tunnel` opening a real
+`cloudflared` quick tunnel needs the public internet and a third party. It was
+run by hand (below). The hostname parser, the connection-banner detection and
+the no-`cloudflared` fallback are unit tests in
+`engine/crates/xerj-server/src/share.rs`. The gRPC listener is exercised with a
+claimed guest key in process (`xerj-server/src/grpc.rs`), not over a socket.
+
+## Run 1 — first full smoke of this branch on the rebased build
+
+```
+A live 201/202 · B CLI 7/8 · C browser 30/31 · D 192/192 · E 2/2 · F 3/3
+```
+
+Three failures, each with a distinct cause, all fixed in commit `8f5d1a5e`:
+
+- **A.** The owner-side check that the native listener answers asked
+ `GET /v1/indices`, which is POST-only (create) → 405. The native describe
+ route is `GET /v1/indices/{name}`. The eight guest refusals on that port
+ passed as they were.
+- **B.** `share --list | grep -q "$HANDLE"` under `set -o pipefail`. `grep -q`
+ exits on its first match; the CLI's next write gets SIGPIPE and the process
+ ends with 141 and nothing on stderr (forced deterministically with
+ `xerj share --list | true`: exit 141, empty stderr). 0 failures in 40 runs on
+ a quiet machine, 1 in 1 in the loaded smoke run. The script now captures
+ the output and greps the string. Same change for `--revoke`.
+- **C.** The e2e waited for "two result rows" after searching `landlord`, but
+ the previous query (`deposit`) had also produced exactly two rows, and those
+ stay on screen until the new response lands. The check ran against the stale
+ list — its snippet was windowed around "deposit", the previous word. The page
+ now stamps `#results` with `data-query` once a list is rendered, and the
+ test's `search()` waits for that stamp. The similarity-label logic itself was
+ right.
+
+## Run 2 — full smoke on the final build (after the fixes)
+
+Release binary rebuilt after the fixes (`cargo build --release -p xerj-server`,
+`Finished release … in 9m 28s`), then `.github/scripts/share-links-smoke.sh`
+with `XERJ_SHARE_REQUIRE_BROWSER=1` and Chrome at `/usr/bin/google-chrome`:
+
+```
+A. live security test (auth on, no trusted proxies) passed=202 failed=0
+ no share id in the server log PASS
+B. xerj share CLI 8/8
+ create --json · create prints link/passcode/expiry/revoke/local-only ·
+ --list · --revoke · --list --json reports revoked · folder-not-indexed
+ error · wrong-key error · --tunnel without cloudflared (exit 0)
+C. guest page, headless Chrome passed=31 failed=0
+D. live security test (trusted_proxies = loopback) passed=192 failed=0
+E. an open node cannot share 2/2
+F. xerj brain <folder> → xerj share <folder> 3/3
+share-links smoke: all phases passed
+```
+
+Between run 1 and this run one more test-only change was needed: the first
+`waitFor` in the e2e evaluated `document.getElementById('view-claim').hidden`
+before the guest page had finished loading (load average 54 at the time) and
+the harness treated the resulting exception as fatal. A predicate that throws
+now counts as "not yet", and `visible()` is null-safe. No page or server code
+changed for that.
+
+The 202 live checks are the 192 of run D plus the native-listener section,
+which only runs when `XERJ_NATIVE_URL` is set (phase A sets it; phase D does
+not). The counts are fixed by the test files, not by the run.
+
+## Run 3 — after the review of PR #947 (2026-09-19)
+
+Three review lenses (security, correctness and UX, docs and honest claims)
+found two blockers, six majors and a set of minors; the PR description maps
+each one to its fix and its proof. The fixes are commits `7bfa24ec` (server),
+`a47df92a` (guest page), `df11e5ff` (CLI) and `f152538f` (CI and wording).
+
+CI on `df11e5ff` failed in two jobs, and each failure was a test or lint
+defect, not a server defect: two clippy 1.97 lints in test code; the live test
+revoking a share by its full id — putting that id in a request path — on the
+node that phase A now runs with the access log on; the live test expecting
+`401`/`403` where the full server answers an unrouted path with a bare `404`
+before authentication; and the browser test running on phase A's node after
+phase A had drained `127.0.0.1`'s junk-id budget on purpose. `f152538f` has
+the detail.
+
+Release binary of `f152538f` (`cargo build --release -j 6 -p xerj-server`,
+`Finished release … in 8m 32s`), then
+
+```
+XERJ_SHARE_PORT=12003 XERJ_SHARE_REQUIRE_BROWSER=1 CHROME_BIN=/usr/bin/google-chrome \
+ bash .github/scripts/share-links-smoke.sh
+```
+
+```
+A. live security test (auth on, no trusted proxies, access log ON)
+ passed=237 failed=0
+ the node logged its requests (access log on) PASS
+ no share id in the server log PASS
+B. xerj share CLI 14/14
+C. guest page, headless Chrome (a fresh node, access log ON)
+ passed=48 failed=0
+ no share id in the server log after the browser flow PASS
+D. live security test (trusted_proxies = loopback) passed=225 failed=0
+E. an open node cannot share 2/2
+F. xerj brain <folder> → xerj share <folder> 3/3
+share-links smoke: all phases passed
+```
+
+The 237 live checks are the 225 of run D plus the native-listener section,
+which only runs when `XERJ_NATIVE_URL` is set. The counts grew from runs 1–2
+because the review added checks: the retired claim shape, the body cap, the
+positive rows of the "a guest can" table, the catalog refusal, the audit and
+`no-store` checks, and the server-log check.
+
+"No share id in the server log" means: with `logging.access_log = true`, the
+node's `server.log` holds none of the share ids, passcodes or guest keys the
+live test created (phase A), and no `/_share/<32 hex>` path other than the live
+test's own made-up `f…f` probe of the retired claim shape (phases A and C). It does not cover a reverse proxy that logs request bodies; see
+docs/SHARING.md.
+
+## ES-compatibility conformance suite
+
+Against an `--insecure` throwaway node on `127.0.0.1:9518`, the release binary
+of this branch:
+
+```
+es-yaml-runner --url http://127.0.0.1:9518 --dir tests/es-compat-yaml/yaml
+1371 passed · 0 failed · 3 skipped · 1374 total
+```
+
+Identical to the `main` baseline (1371 / 0 / 3). The share routes are new
+paths; nothing on the existing wire surface changed.
+
+Run 3, the release binary of `f152538f`, against an `--insecure` throwaway
+node on `127.0.0.1:12000`:
+
+```
+cargo run --release -p es-yaml-runner -- --url http://localhost:12000 --dir tests/es-compat-yaml/yaml
+1371 passed · 0 failed · 3 skipped · 1374 total
+```
+
+## The real quick tunnel, by hand
+
+This run is from 2026-09-18 and predates the review: the claim was still
+`POST /_share/{id}/claim`, and the CLI did not yet print the Cloudflare notice.
+It has not been repeated through a real tunnel since. What changed is covered
+without one: smoke phase B runs `--tunnel` against a stub `cloudflared` and
+checks the notice, and the browser test serves the page under a
+`*.trycloudflare.com` name mapped to the local node and checks the page's
+notice.
+
+Node with authentication on at `127.0.0.1:9513`, one index of one document,
+one private index. `xerj share tun-notes --expires 30m --max-claims 3 --tunnel
+--json`, then every request below through the public hostname with `curl -4`
+(this machine resolves `trycloudflare.com` over IPv6 only and cannot route it;
+a plain `curl` fails here for that reason alone).
+
+| Step | Result |
+|---|---|
+| link printed | `https://<random>.trycloudflare.com/_xerj-console/share#<share id>` |
+| `GET /_xerj-console/share` through the tunnel | `HTTP/2 200`, `cache-control: no-store, max-age=0`, `content-security-policy: default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`, `referrer-policy: no-referrer`, `x-content-type-options: nosniff`, `x-frame-options: DENY` |
+| claim, wrong passcode | `401` |
+| claim, right passcode | `200`, `cache-control: no-store, max-age=0`, a key in the body |
+| guest `POST /tun-notes/_search` | `200` |
+| guest `GET /_cat/indices` | `403` |
+| guest `POST /tun-private/_search` | `403` |
+| audit log | `share.claim … [email protected] … denied … wrong passcode`, then `… ok … claims_left=2` — the TCP peer, because no trusted proxy was declared |
+| SIGINT to `xerj share` | exit 0; "Ctrl-C — closing the tunnel." then "share <handle> revoked — 1 guest key(s) invalidated." |
+| `cloudflared` processes | one fewer than before the run (the child was terminated; other tunnels on the machine untouched) |
+| guest key after the revoke, on the node directly | `401` |
+| `xerj share --list` | the share listed as `revoked`, claims `1/3` |
+
+The tunnel binary was found at `~/.local/bin/cloudflared` (the CLI looks at
+`XERJ_CLOUDFLARED`, then `PATH`, then `~/.local/bin`). The run was done once,
+by hand; it is not part of CI.
+
+## Unit tests, lint, format
+
+Run 3, on the tree of `f152538f`, toolchain 1.97.1 (the version CI pins), from
+`engine/`:
+
+```
+cargo fmt --check -p xerj-api -p xerj-server -p xerj-console-api
+ -> clean
+
+cargo clippy -j 6 -p xerj-api -p xerj-server -p xerj-console-api --all-targets -- -D warnings
+ -> exit 0
+
+cargo test --profile ci-test -j 6 -p xerj-api -p xerj-server -p xerj-console-api -- --test-threads=4
+ -> 86 test binaries, 778 passed, 0 failed, 3 ignored
+ xerj-api lib 261 passed · xerj-console-api lib 49 passed · xerj (xerj-server) 58 passed
+ tests/share_links_review_findings.rs 5 passed · tests/audit_records_writes_and_who.rs 6 passed
+ tests/brain_is_a_security_boundary.rs 5 passed
+```
+
+The review's regression tests are among those: in xerj-server,
+`share::tests::a_tunnel_link_says_cloudflare_can_read_the_traffic`,
+`the_banner_is_about_the_address_the_link_really_has`,
+`a_url_without_a_scheme_is_a_usage_error_that_says_what_to_type`,
+`cloudflareds_last_lines_are_kept_for_when_it_dies`,
+`pasted_follow_up_commands_survive_spaces_and_quotes`,
+`list_revoke_and_create_are_mutually_exclusive`,
+`brain::tests::share_hint_quotes_a_folder_with_a_space` and
+`grpc::tests::a_share_guest_key_reads_its_index_over_grpc_and_nothing_else`;
+in xerj-api, the five tests of `tests/share_links_review_findings.rs`, which
+commit `7bfa24ec` records as run against the pre-fix sources first (0 passed,
+5 failed).
+
+## Wording checks that also gate this page
+
+`python3 scripts/seo/factcheck.py --fail-on error` resolves every
+`evidence: source:` in the three share answers; this page is one of those
+sources, which is why it carries the numbers rather than the answers.
diff --git a/engine/Cargo.lock b/engine/Cargo.lock
index 1b9e4f8c7..53d93604d 100644
--- a/engine/Cargo.lock
+++ b/engine/Cargo.lock
@@ -170,6 +170,18 @@ dependencies = [
"rustversion",
]
+[[package]]
+name = "argon2"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
+dependencies = [
+ "base64ct",
+ "blake2",
+ "cpufeatures 0.2.17",
+ "password-hash",
+]
+
[[package]]
name = "arrayvec"
version = "0.7.8"
@@ -771,6 +783,12 @@ dependencies = [
"vsimd",
]
+[[package]]
+name = "base64ct"
+version = "1.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
+
[[package]]
name = "base64urlsafedata"
version = "0.5.5"
@@ -824,6 +842,15 @@ dependencies = [
"crunchy",
]
+[[package]]
+name = "blake2"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
+dependencies = [
+ "digest 0.10.7",
+]
+
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -3803,6 +3830,17 @@ dependencies = [
"regex",
]
+[[package]]
+name = "password-hash"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
+dependencies = [
+ "base64ct",
+ "rand_core 0.6.4",
+ "subtle",
+]
+
[[package]]
name = "paste"
version = "1.0.15"
@@ -7222,6 +7260,7 @@ name = "xerj-api"
version = "1.0.0-rc.74"
dependencies = [
"anyhow",
+ "argon2",
"async-trait",
"axum",
"bytes",
@@ -7230,6 +7269,7 @@ dependencies = [
"http-body-util",
"libc",
"prometheus",
+ "rand 0.8.7",
"serde",
"serde_json",
"sha2 0.10.9",
diff --git a/engine/crates/xerj-api/Cargo.toml b/engine/crates/xerj-api/Cargo.toml
index dd7a4a660..d10784b1d 100644
--- a/engine/crates/xerj-api/Cargo.toml
+++ b/engine/crates/xerj-api/Cargo.toml
@@ -44,9 +44,15 @@ xxhash-rust = { workspace = true }
async-trait = "0.1"
libc = "0.2"
+# Share links (`/_share`): the passcode a guest types is short and human-typed,
+# so unlike a minted API-key secret it needs a real password hash.
+argon2 = "0.5"
+# Share ids / passcodes are minted from the OS CSPRNG.
+rand = { workspace = true }
+# Share ids are stored as a SHA-256 digest, never in the clear.
+sha2 = "0.10"
[dev-dependencies]
tempfile = { workspace = true }
tower = { workspace = true, features = ["util"] }
http-body-util = "0.1"
-sha2 = "0.10"
diff --git a/engine/crates/xerj-api/src/audit_mw.rs b/engine/crates/xerj-api/src/audit_mw.rs
index 278358c82..d6c3a7887 100644
--- a/engine/crates/xerj-api/src/audit_mw.rs
+++ b/engine/crates/xerj-api/src/audit_mw.rs
@@ -92,6 +92,17 @@ struct Audited {
/// It is also the only way a *denied* search gets recorded at all, since
/// the handler that would have appended never runs.
only_if_denied: bool,
+ /// The handler writes its own entries (`_security/api_key`, `_share`), so
+ /// record this one **only** when the request never reached it — i.e. the
+ /// response carries [`crate::authz::RefusedBeforeHandler`].
+ ///
+ /// These paths used to be skipped outright, on the reasoning that the
+ /// handler audits them. It does — when it runs. A share-link guest's
+ /// `POST /_share`, `DELETE /_share/{handle}` and `POST /_security/api_key`
+ /// are refused by the authorization middleware, so neither layer wrote a
+ /// line for the very requests that are attempts to widen a credential
+ /// (review of PR #947: four such calls, zero entries).
+ handler_audits: bool,
}
/// Path segments, empty ones dropped.
@@ -157,9 +168,27 @@ fn classify(method: &Method, path: &str) -> Option<Audited> {
}
// The three `_security/api_key` operations append their own entries (with
// a `sync_to_disk` barrier a generic layer should not impose on every
- // write); auditing them here as well would double every one.
+ // write); auditing them here as well would double every one. What the
+ // handler cannot record is a request that never reached it.
if segs.first() == Some(&"_security") && segs.get(1) == Some(&"api_key") {
- return None;
+ let op = match *method {
+ Method::GET | Method::HEAD => "security.api_key.get",
+ Method::DELETE => "security.api_key.invalidate",
+ _ => "security.api_key.create",
+ };
+ return Some(Audited {
+ op: op.to_string(),
+ resource: "_security/api_key".to_string(),
+ only_if_denied: true,
+ handler_audits: true,
+ });
+ }
+ // Share links audit themselves with the outcome detail that matters
+ // (which share, wrong passcode vs exhausted vs throttled, the source
+ // address of an unauthenticated claim) — see `crate::share`. Same rule:
+ // only the requests the handler never saw are recorded here.
+ if segs.first() == Some(&"_share") {
+ return Some(classify_share(method, &segs));
}
// `/_xerj-console/*` is a separate application mounted at the server level
// with its own `.xerj_audit` trail; the SPA's own traffic is not node data.
@@ -192,6 +221,7 @@ fn classify(method: &Method, path: &str) -> Option<Audited> {
op: op.to_string(),
resource: index.to_string(),
only_if_denied: false,
+ handler_audits: false,
});
}
// The endpoint keyword is the first `_`-prefixed segment.
@@ -218,9 +248,37 @@ fn classify(method: &Method, path: &str) -> Option<Audited> {
op,
resource: index.to_string(),
only_if_denied: false,
+ handler_audits: false,
})
}
+/// `/_share/…`, with the op tags `crate::share` uses for the same routes.
+///
+/// The resource is `_share`, or the share's public **handle** when the path
+/// names one. Never any other path segment: `DELETE /_share/{id}` also accepts
+/// the full share id, and the audit log must not be the place a share id is
+/// written down.
+fn classify_share(method: &Method, segs: &[&str]) -> Audited {
+ let op = match (method, segs.get(1).copied()) {
+ (&Method::POST, None) => "share.create",
+ (&Method::GET, None) | (&Method::HEAD, None) => "share.list",
+ (&Method::POST, Some("claim")) => "share.claim",
+ (&Method::DELETE, Some(_)) => "share.revoke",
+ _ => "share.other",
+ };
+ let is_handle = |s: &str| s.len() == 12 && s.bytes().all(|b| b.is_ascii_hexdigit());
+ let resource = match segs.get(1).copied() {
+ Some(handle) if segs.len() == 2 && is_handle(handle) => handle.to_string(),
+ _ => "_share".to_string(),
+ };
+ Audited {
+ op: op.to_string(),
+ resource,
+ only_if_denied: true,
+ handler_audits: true,
+ }
+}
+
/// A read, described well enough to be worth an entry **if it was refused**.
///
/// The op tag matches what the successful path would have written — a denied
@@ -239,6 +297,7 @@ fn classify_read(segs: &[&str]) -> Option<Audited> {
),
resource: "_audit".to_string(),
only_if_denied: true,
+ handler_audits: false,
});
}
let (op, resource) = match segs {
@@ -265,6 +324,7 @@ fn classify_read(segs: &[&str]) -> Option<Audited> {
op: op.to_string(),
resource,
only_if_denied: true,
+ handler_audits: false,
})
}
@@ -276,6 +336,7 @@ fn classify_native(method: &Method, segs: &[&str]) -> Option<Audited> {
op: "index.create".to_string(),
resource: "_indices".to_string(),
only_if_denied: false,
+ handler_audits: false,
}),
["v1", "indices", name] => Some(Audited {
op: if *method == Method::DELETE {
@@ -285,6 +346,7 @@ fn classify_native(method: &Method, segs: &[&str]) -> Option<Audited> {
},
resource: (*name).to_string(),
only_if_denied: false,
+ handler_audits: false,
}),
["v1", "indices", name, tail @ ..] => {
let op = match tail {
@@ -308,6 +370,7 @@ fn classify_native(method: &Method, segs: &[&str]) -> Option<Audited> {
op,
resource: (*name).to_string(),
only_if_denied: false,
+ handler_audits: false,
})
}
["v1", rest @ ..] => Some(Audited {
@@ -318,6 +381,7 @@ fn classify_native(method: &Method, segs: &[&str]) -> Option<Audited> {
),
resource: format!("/v1/{}", rest.join("/")),
only_if_denied: false,
+ handler_audits: false,
}),
_ => None,
}
@@ -381,6 +445,15 @@ pub async fn audit_middleware(State(state): State<AppState>, req: Request, next:
let response = next.run(req).await;
+ // A self-auditing route is recorded here only when its handler never ran.
+ if audited.handler_audits
+ && response
+ .extensions()
+ .get::<crate::authz::RefusedBeforeHandler>()
+ .is_none()
+ {
+ return response;
+ }
// A read that succeeded is not recorded: the ring is small, shared, and
// better spent on changes and refusals.
if audited.only_if_denied && response.status() != StatusCode::FORBIDDEN {
@@ -527,6 +600,72 @@ mod tests {
);
}
+ /// A self-auditing route: `(op, resource)` when the layer would record a
+ /// request the handler never saw, `None` when it would not look at all.
+ fn upstream_refusal(method: Method, path: &str) -> Option<(String, String)> {
+ classify(&method, path)
+ .filter(|a| a.handler_audits && a.only_if_denied)
+ .map(|a| (a.op, a.resource))
+ }
+
+ /// Review of PR #947: a share-link guest's `POST /_share`, `GET /_share`,
+ /// `DELETE /_share/{handle}` and `POST /_security/api_key` were refused in
+ /// the authorization middleware and recorded by nobody, because this layer
+ /// skipped both prefixes outright. They are classified now — as entries
+ /// that are written only for a request the handler never saw.
+ #[test]
+ fn self_auditing_routes_are_recorded_when_the_handler_never_ran() {
+ assert_eq!(
+ upstream_refusal(Method::POST, "/_share"),
+ Some(("share.create".into(), "_share".into()))
+ );
+ assert_eq!(
+ upstream_refusal(Method::GET, "/_share"),
+ Some(("share.list".into(), "_share".into()))
+ );
+ assert_eq!(
+ upstream_refusal(Method::DELETE, "/_share/1a2b3c4d5e6f"),
+ Some(("share.revoke".into(), "1a2b3c4d5e6f".into()))
+ );
+ assert_eq!(
+ upstream_refusal(Method::POST, "/_share/claim"),
+ Some(("share.claim".into(), "_share".into()))
+ );
+ assert_eq!(
+ upstream_refusal(Method::POST, "/_security/api_key"),
+ Some(("security.api_key.create".into(), "_security/api_key".into()))
+ );
+ assert_eq!(
+ upstream_refusal(Method::GET, "/_security/api_key"),
+ Some(("security.api_key.get".into(), "_security/api_key".into()))
+ );
+ assert_eq!(
+ upstream_refusal(Method::DELETE, "/_security/api_key"),
+ Some((
+ "security.api_key.invalidate".into(),
+ "_security/api_key".into()
+ ))
+ );
+ }
+
+ /// `DELETE /_share/{id}` accepts the full share id as well as the handle.
+ /// Only the handle — 12 hex characters, public, opens nothing — may become
+ /// the entry's resource; a share id must never be written to the log.
+ #[test]
+ fn a_share_id_in_a_path_never_becomes_an_audit_resource() {
+ let id = "0123456789abcdef0123456789abcdef";
+ for path in [
+ format!("/_share/{id}"),
+ format!("/_share/{id}/claim"),
+ format!("/_share/{}", &id[..13]),
+ "/_share/not-a-handle".to_string(),
+ ] {
+ let a = classify(&Method::DELETE, &path).expect("classified");
+ assert_eq!(a.resource, "_share", "{path}");
+ assert!(!a.op.contains(id), "{path}");
+ }
+ }
+
/// Every native write path is covered without being enumerated by hand —
/// including the ingest shapes (`logs`, `otlp`, `syslog`) that no
/// per-handler `append` list would have remembered.
diff --git a/engine/crates/xerj-api/src/auth.rs b/engine/crates/xerj-api/src/auth.rs
index 1a8b1fd1e..0bad8f9b5 100644
--- a/engine/crates/xerj-api/src/auth.rs
+++ b/engine/crates/xerj-api/src/auth.rs
@@ -40,6 +40,28 @@ use crate::state::AppState;
/// `"live"`/`"ready"` string), so leaving them open is safe.
pub const AUTH_EXEMPT_PATHS: [&str; 2] = ["/health/live", "/health/ready"];
+/// Is `path` the share-claim route, `/_share/claim`?
+///
+/// The one unauthenticated route that hands out a credential: a guest who
+/// opens a share link has, by definition, no key yet. It is exempted the way
+/// `/v1/metrics` is for the scrape token — by exact path, `POST` only (the
+/// method check is the caller's), never by prefix — and the handler
+/// (`crate::share::claim_share`) rate-limits per source address and per share
+/// and audits every outcome. Everything else under `/_share` stays behind
+/// authentication and is superuser-only in its handler.
+///
+/// The share id is in the request **body**. The first cut matched
+/// `/_share/{id}/claim`, which put the id into every access log between the
+/// guest and the node; that shape is deliberately not exempt any more, so a
+/// stale client gets a plain `401` instead of a second, id-leaking way in.
+pub fn is_share_claim_path(path: &str) -> bool {
+ let mut segs = path.split('/').filter(|s| !s.is_empty());
+ matches!(
+ (segs.next(), segs.next(), segs.next()),
+ (Some("_share"), Some("claim"), None)
+ )
+}
+
// ─────────────────────────────────────────────────────────────────────────────
// Principal
// ─────────────────────────────────────────────────────────────────────────────
@@ -105,6 +127,27 @@ impl Principal {
}
}
+ /// Is this the key a share-link claim minted (`crate::share::claim_share`)?
+ ///
+ /// Such a key carries exactly one role, named `share:<handle>`. It is
+ /// recognised by that name and nothing else, which is safe in the only
+ /// direction that matters: being recognised as a guest only ever *removes*
+ /// reach ([`crate::authz`] intersects the guest route allow-list with the
+ /// key's index grants — it never adds to them). An operator who mints an
+ /// ordinary key with a role descriptor called `share:x` gets a key that is
+ /// more confined than they asked for, never less.
+ pub fn is_share_guest(&self) -> bool {
+ match self {
+ Principal::Scoped { roles, .. } => {
+ !roles.is_empty()
+ && roles
+ .iter()
+ .all(|r| r.name.starts_with(crate::share::GUEST_ROLE_PREFIX))
+ }
+ _ => false,
+ }
+ }
+
/// True for the one principal that is allowed to see and do everything —
/// used to skip the authorization work entirely on the local-dev path.
pub fn is_superuser(&self) -> bool {
@@ -165,6 +208,12 @@ pub async fn auth_middleware(State(state): State<AppState>, req: Request, next:
return next.run(req).await;
}
+ // A guest claiming a share link has no credential yet — that is the
+ // whole point of the route. See `is_share_claim_path`.
+ if req.method() == axum::http::Method::POST && is_share_claim_path(req.uri().path()) {
+ return next.run(req).await;
+ }
+
// Xerj Console lives in a peer router (mounted by `xerj-server` via
// `Router::merge`) and runs its own session-cookie auth, so this
// middleware never sees `/_xerj-console/*` requests — no path-prefix
diff --git a/engine/crates/xerj-api/src/authz.rs b/engine/crates/xerj-api/src/authz.rs
index d57060ff9..0bb364292 100644
--- a/engine/crates/xerj-api/src/authz.rs
+++ b/engine/crates/xerj-api/src/authz.rs
@@ -501,6 +501,9 @@ fn classify(path: &str) -> Target {
if AUTH_EXEMPT_PATHS.contains(&path)
|| path == "/v1/metrics"
|| path == "/_security/_authenticate"
+ // `POST /_share/claim` is unauthenticated by design (the guest
+ // has no key yet) and names no index; the handler decides everything.
+ || crate::auth::is_share_claim_path(path)
{
return Target::Exempt;
}
@@ -1264,6 +1267,26 @@ fn authorize_expression(
/// so a pathological response cannot be turned into an OOM.
const MAX_PRUNABLE_RESPONSE_BYTES: usize = 64 * 1024 * 1024;
+/// Set on every response this middleware produced itself — a refusal, so the
+/// handler never ran.
+///
+/// [`crate::audit_mw`] needs the distinction. The `_share` and
+/// `_security/api_key` handlers write their own audit entries, so the
+/// request-level layer used to skip those paths entirely — and a request that
+/// was stopped *here* reached neither: a share-link guest's `POST /_share`,
+/// `DELETE /_share/{handle}` and `POST /_security/api_key` all answered `403`
+/// and left no trace (review of PR #947, reproduced 2026-09-19: four refused
+/// calls, zero audit lines). Those are the escalation probes an owner most
+/// wants recorded. The marker lets the audit layer record exactly the requests
+/// the handler could not, without doubling the ones it could.
+#[derive(Clone, Copy, Debug)]
+pub struct RefusedBeforeHandler;
+
+fn refused(mut resp: Response) -> Response {
+ resp.extensions_mut().insert(RefusedBeforeHandler);
+ resp
+}
+
/// Authorization middleware for both routers.
///
/// Layered *inside* [`crate::auth::auth_middleware`] (added to the router
@@ -1278,6 +1301,23 @@ pub async fn authz_middleware(State(state): State<AppState>, req: Request, next:
let path = req.uri().path().to_string();
let target = classify(&path);
if matches!(target, Target::Exempt) {
+ // `/v1/metrics` is exempt because it names no index — but it does
+ // describe the node (index counts, document counts, request rates),
+ // which is more than a share-link guest was handed. Every other exempt
+ // path is a probe, the version banner, "who am I" or the claim route
+ // itself. Authenticating here costs one header lookup on the scrape
+ // path only.
+ if path == "/v1/metrics" {
+ let principal = authenticate(
+ &state,
+ req.headers()
+ .get(header::AUTHORIZATION)
+ .and_then(|v| v.to_str().ok()),
+ );
+ if principal.is_share_guest() {
+ return refused(guest_forbidden(&principal, &path));
+ }
+ }
return next.run(req).await;
}
@@ -1293,6 +1333,15 @@ pub async fn authz_middleware(State(state): State<AppState>, req: Request, next:
let segs = segments(&path);
let method = req.method().clone();
+
+ // A share-link guest gets a route allow-list on top of its index grants.
+ // Checked first and separately so that everything below still runs for a
+ // guest: this can only refuse, never permit.
+ if principal.is_share_guest()
+ && !guest_route_allowed(&method, &segs, &target, req.uri().query())
+ {
+ return refused(guest_forbidden(&principal, &path));
+ }
let shape = body_shape(&method, &segs);
// Buffer the body only for the routes that can name an index inside it.
@@ -1315,8 +1364,17 @@ pub async fn authz_middleware(State(state): State<AppState>, req: Request, next:
}
};
+ if principal.is_share_guest() && guest_body_denied(shape, &body) {
+ return refused(guest_forbidden(&principal, &path));
+ }
+
if let Err(denied) = decide(&principal, &method, &segs, &target, shape, &body, &state) {
- return denied;
+ let denied = refused(denied);
+ return if principal.is_share_guest() {
+ crate::share::no_store(denied)
+ } else {
+ denied
+ };
}
// Layer 2: whatever the handler resolves from here on — including names
@@ -1324,7 +1382,159 @@ pub async fn authz_middleware(State(state): State<AppState>, req: Request, next:
// engine's index funnel.
let response =
xerj_engine::index_guard::scoped(visibility_for(&principal), next.run(req)).await;
- prune_response(response, &segs, &principal, &state).await
+ let response = prune_response(response, &segs, &principal, &state).await;
+ // What a guest reads is somebody's documents, and the road to the guest
+ // may run through a tunnel or a proxy the owner does not operate. Nothing
+ // on that road may keep a copy.
+ if principal.is_share_guest() {
+ crate::share::no_store(response)
+ } else {
+ response
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Share-link guests
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Index-scoped operations a share-link guest may call: what a reading room
+/// needs, and nothing that opens a server-side context or describes the node.
+///
+/// Not on the list, on purpose: `_pit` and `_async_search` (server-side state
+/// a guest could pile up), `_sql`/`_esql`/`_eql` (the table name is resolved
+/// deep in a statement), `_stats`/`_settings`/`_segments`/`_disk_usage`
+/// (storage layout), `_alias`, `_analyze`, `_explain`, `_termvectors`,
+/// `_validate`, `_rank_eval`, `_knn_search`, `_terms_enum`, `_graph`.
+const GUEST_INDEX_OPS: &[&str] = &[
+ "_search",
+ "_count",
+ "_msearch",
+ "_mget",
+ "_mapping",
+ "_field_caps",
+];
+/// The same, for the ops that take a document id as one further segment.
+///
+/// `_source` was on this list and in the docs' "a guest can" table, but the
+/// router has no `/{index}/_source/{id}` route — `404` for the admin key too
+/// (review of PR #947). An allow-list entry for a route that does not exist
+/// is a permission nobody tested; whoever adds the route decides then.
+const GUEST_DOC_OPS: &[&str] = &["_doc"];
+/// The read half of the graph API.
+const GUEST_GRAPH_OPS: &[&str] = &["ego", "overview"];
+/// Query-string parameters that turn a permitted search into something else.
+/// `scroll` opens a server-side cursor that outlives the request.
+const GUEST_DENIED_PARAMS: &[&str] = &["scroll"];
+
+/// May a share-link guest call this route at all?
+///
+/// A route allow-list, deliberately separate from — and applied before — the
+/// index decision in [`decide`]. A scoped key is normally given a *filtered*
+/// view of the cluster surface (`_cat`, `_cluster/*`, `_nodes`, `_snapshot`
+/// listings, the global `_search`), because Kibana cannot function without
+/// one. A guest is not Kibana: it was handed one corpus by someone who did not
+/// agree to describe their node. So for a guest the cluster surface is simply
+/// closed, and the index surface is closed except for reading.
+///
+/// Returning `true` permits nothing on its own; [`decide`] still checks every
+/// named index against the key's grants.
+fn guest_route_allowed(
+ method: &Method,
+ segs: &[String],
+ target: &Target,
+ query: Option<&str>,
+) -> bool {
+ let is_get = method == Method::GET || method == Method::HEAD;
+ let is_read_verb = is_get || method == Method::POST;
+ match target {
+ Target::Exempt => true,
+ Target::Cluster | Target::Memory(_) => false,
+ Target::Brain(_) => {
+ is_get
+ && segs.len() == 3
+ && segs
+ .get(2)
+ .is_some_and(|op| GUEST_GRAPH_OPS.contains(&op.as_str()))
+ }
+ Target::Indices(_, op_start) => {
+ // The native router spells the same index `/v1/indices/{name}/…`;
+ // the guest page speaks ES-compat only, so that door stays shut.
+ if segs.first().map(String::as_str) == Some("v1") {
+ return false;
+ }
+ let Some(op) = segs.get(*op_start).map(String::as_str) else {
+ // `GET /{index}` — settings, aliases and mappings in one.
+ return false;
+ };
+ let extra = segs.len() - op_start - 1;
+ let shape_ok = if GUEST_INDEX_OPS.contains(&op) {
+ is_read_verb && extra == 0
+ } else if GUEST_DOC_OPS.contains(&op) {
+ is_get && extra == 1
+ } else {
+ false
+ };
+ shape_ok && !query_names_any(query, GUEST_DENIED_PARAMS)
+ }
+ }
+}
+
+/// Does a guest's request body ask for something the route allow-list exists
+/// to keep shut?
+///
+/// One thing today: a point-in-time id. A guest cannot open a PIT (`_pit` is
+/// not on the allow-list), so any id it presents was opened by someone else —
+/// and a PIT, not the path, decides which index a search runs against:
+/// `POST /casefile/_search {"pit": {"id": <a PIT on private-diary>}}` searches
+/// `private-diary`. The engine's index funnel already refuses that for a
+/// guest (live-verified 2026-09-18: `404 no such index [private-diary]`), but
+/// that answer echoes the other index's name back, and the path-level decision
+/// above it authorized `casefile` for a request that was never going to read
+/// `casefile`. Refused here, by shape, for both spellings that carry a search
+/// body: `_search`-like bodies and `_msearch` body lines.
+fn guest_body_denied(shape: BodyShape, body: &[u8]) -> bool {
+ let has_pit = |v: &Value| v.as_object().is_some_and(|o| o.contains_key("pit"));
+ match shape {
+ BodyShape::Query => serde_json::from_slice::<Value>(body)
+ .map(|v| has_pit(&v))
+ .unwrap_or(false),
+ BodyShape::MsearchHeaders => body
+ .split(|b| *b == b'\n')
+ .filter_map(|line| serde_json::from_slice::<Value>(line).ok())
+ .any(|v| has_pit(&v)),
+ _ => false,
+ }
+}
+
+/// Does the raw query string carry any of `names` as a parameter name?
+/// Names are percent-decoded and compared case-insensitively, so `%73croll`
+/// and `SCROLL` are the parameter they decode to.
+fn query_names_any(query: Option<&str>, names: &[&str]) -> bool {
+ let Some(query) = query else {
+ return false;
+ };
+ query.split('&').any(|pair| {
+ let key = pair.split('=').next().unwrap_or("");
+ let key = percent_decode(&key.replace('+', " ")).to_ascii_lowercase();
+ names.contains(&key.trim())
+ })
+}
+
+/// The guest's 403. Says what the key is for, so a guest who wandered gets an
+/// explanation rather than the operator-facing "mint a key whose
+/// role_descriptors grant…" remedy, which they can do nothing with.
+fn guest_forbidden(principal: &Principal, path: &str) -> Response {
+ tracing::debug!(
+ principal = principal.label(),
+ path,
+ "share-link guest denied a route outside the reading-room allow-list"
+ );
+ crate::share::no_store(es_error(
+ StatusCode::FORBIDDEN,
+ "this credential is a share-link guest key: it can search and read the shared \
+ index (and walk the shared brain's links), and nothing else on this node"
+ .to_string(),
+ ))
}
/// The whole decision, split out so it can be unit-tested without a router.
@@ -1858,6 +2068,256 @@ mod tests {
}
}
+ /// The principal a share-link claim mints: one `share:<handle>` role,
+ /// `read` on the shared index and on the brain's edges index.
+ fn guest() -> Principal {
+ Principal::Scoped {
+ key_id: "g1".into(),
+ roles: vec![Role::new(
+ format!("{}1a2b3c4d5e6f", crate::share::GUEST_ROLE_PREFIX),
+ HashSet::from([Privilege::ReadIndex]),
+ vec!["casefile".to_string(), brain_edges_index("case")],
+ )],
+ }
+ }
+
+ /// The guest route allow-list AND the index decision, the way the
+ /// middleware stacks them. `path` may carry a query string.
+ fn guest_check(method: Method, path_and_query: &str, body: &str) -> bool {
+ let p = guest();
+ let (path, query) = match path_and_query.split_once('?') {
+ Some((p, q)) => (p, Some(q)),
+ None => (path_and_query, None),
+ };
+ let segs = segments(path);
+ let target = classify(path);
+ guest_route_allowed(&method, &segs, &target, query) && check(&p, method, path, body)
+ }
+
+ #[test]
+ fn a_share_guest_is_recognised_by_its_role_name_and_only_loses_reach() {
+ assert!(guest().is_share_guest());
+ assert!(!scoped(&["casefile"], &[Privilege::ReadIndex]).is_share_guest());
+ assert!(!unscoped().is_share_guest());
+ assert!(!Principal::Superuser.is_share_guest());
+ assert!(!Principal::Denied.is_share_guest());
+ // A key holding a share role AND an ordinary one is not a guest: the
+ // allow-list is for keys a claim minted, which carry exactly one role.
+ let mixed = Principal::Scoped {
+ key_id: "m".into(),
+ roles: vec![
+ Role::new(
+ "share:x",
+ HashSet::from([Privilege::ReadIndex]),
+ vec!["a".into()],
+ ),
+ Role::new(
+ "ops",
+ HashSet::from([Privilege::ReadIndex]),
+ vec!["b".into()],
+ ),
+ ],
+ };
+ assert!(!mixed.is_share_guest());
+ }
+
+ #[test]
+ fn a_share_guest_can_read_the_shared_index_and_walk_the_shared_brain() {
+ for (method, path) in [
+ (Method::POST, "/casefile/_search"),
+ (Method::GET, "/casefile/_search"),
+ (Method::POST, "/casefile/_search?size=10&from=20"),
+ (Method::POST, "/casefile/_count"),
+ (Method::GET, "/casefile/_doc/1"),
+ (Method::HEAD, "/casefile/_doc/1"),
+ (Method::GET, "/casefile/_mapping"),
+ (Method::POST, "/casefile/_field_caps"),
+ (Method::GET, "/_graph/case/ego"),
+ (Method::GET, "/_graph/case/overview"),
+ (Method::GET, "/"),
+ (Method::GET, "/_security/_authenticate"),
+ (Method::GET, "/health/ready"),
+ ] {
+ assert!(
+ guest_check(method.clone(), path, ""),
+ "{method} {path} must be allowed"
+ );
+ }
+ assert!(guest_check(
+ Method::POST,
+ "/casefile/_mget",
+ r#"{"docs":[{"_id":"1"}]}"#
+ ));
+ }
+
+ #[test]
+ fn a_share_guest_is_shut_out_of_everything_that_describes_or_changes_the_node() {
+ for (method, path) in [
+ // the cluster surface an ordinary scoped key sees filtered
+ (Method::GET, "/_cat/indices"),
+ (Method::GET, "/_cat/aliases"),
+ (Method::GET, "/_cluster/health"),
+ (Method::GET, "/_cluster/state"),
+ (Method::GET, "/_cluster/settings"),
+ (Method::GET, "/_nodes"),
+ (Method::GET, "/_nodes/stats"),
+ (Method::GET, "/_snapshot"),
+ (Method::GET, "/_snapshot/_all"),
+ (Method::GET, "/_mapping"),
+ (Method::GET, "/_aliases"),
+ (Method::GET, "/_alias"),
+ (Method::GET, "/_tasks"),
+ (Method::GET, "/_stats"),
+ (Method::GET, "/_resolve/index/*"),
+ (Method::GET, "/_security/api_key"),
+ (Method::POST, "/_security/api_key"),
+ (Method::GET, "/_xerj/wal_tap"),
+ // share management
+ (Method::GET, "/_share"),
+ (Method::POST, "/_share"),
+ (Method::DELETE, "/_share/1a2b3c4d5e6f"),
+ // global verbs: a reading room names its index
+ (Method::POST, "/_search"),
+ (Method::POST, "/_msearch"),
+ (Method::POST, "/_mget"),
+ (Method::POST, "/_count"),
+ (Method::POST, "/_sql"),
+ // server-side contexts
+ (Method::POST, "/casefile/_search?scroll=1m"),
+ (Method::POST, "/casefile/_search?size=1&SCROLL=1m"),
+ (Method::POST, "/casefile/_search?%73croll=1m"),
+ (Method::POST, "/_search/scroll"),
+ (Method::DELETE, "/_search/scroll"),
+ (Method::POST, "/casefile/_pit"),
+ (Method::DELETE, "/_pit"),
+ (Method::POST, "/casefile/_async_search"),
+ // the shared index's own non-reading surface
+ (Method::GET, "/casefile"),
+ (Method::HEAD, "/casefile"),
+ (Method::GET, "/casefile/_settings"),
+ (Method::GET, "/casefile/_stats"),
+ (Method::GET, "/casefile/_alias"),
+ (Method::GET, "/casefile/_segments"),
+ (Method::POST, "/casefile/_search/template"),
+ (Method::POST, "/casefile/_sql"),
+ (Method::POST, "/casefile/_analyze"),
+ // no such route on this node; not pre-approved for a guest either
+ (Method::GET, "/casefile/_source/1"),
+ (Method::HEAD, "/casefile/_source/1"),
+ // the retired claim shape is not a door of any kind
+ (
+ Method::POST,
+ "/_share/0123456789abcdef0123456789abcdef/claim",
+ ),
+ (Method::POST, "/casefile/_doc/1"),
+ (Method::PUT, "/casefile/_doc/1"),
+ (Method::DELETE, "/casefile/_doc/1"),
+ (Method::POST, "/casefile/_doc"),
+ (Method::POST, "/casefile/_update/1"),
+ (Method::POST, "/casefile/_bulk"),
+ (Method::POST, "/casefile/_delete_by_query"),
+ (Method::POST, "/casefile/_refresh"),
+ (Method::DELETE, "/casefile"),
+ (Method::PUT, "/casefile"),
+ // another index, another brain, the brain's write half, memory
+ (Method::POST, "/private-diary/_search"),
+ (Method::GET, "/private-diary/_doc/1"),
+ (Method::POST, "/casefile,private-diary/_search"),
+ (Method::GET, "/_graph/other/ego"),
+ (Method::GET, "/_graph/other/overview"),
+ (Method::POST, "/_graph/case/link"),
+ (Method::DELETE, "/_graph/case/link/e1"),
+ (Method::GET, "/_memory/case"),
+ (Method::POST, "/_memory/case/_recall"),
+ // the native router's spelling of the same index
+ (Method::POST, "/v1/indices/casefile/search"),
+ (Method::GET, "/v1/indices/casefile"),
+ (Method::GET, "/v1/indices"),
+ ] {
+ assert!(
+ !guest_check(method.clone(), path, ""),
+ "{method} {path} must be refused"
+ );
+ }
+ // A body that reaches past the path index is refused by the index
+ // decision, exactly as for any other scoped key.
+ assert!(!guest_check(
+ Method::POST,
+ "/casefile/_mget",
+ r#"{"docs":[{"_index":"private-diary","_id":"1"}]}"#
+ ));
+ assert!(!guest_check(
+ Method::POST,
+ "/casefile/_msearch",
+ "{\"index\":\"private-diary\"}\n{\"query\":{\"match_all\":{}}}\n"
+ ));
+ }
+
+ #[test]
+ fn the_guest_allow_list_never_grants_what_the_key_does_not_hold() {
+ // An ordinary scoped key is not subject to the allow-list at all…
+ let ordinary = scoped(&["casefile"], &[Privilege::ReadIndex]);
+ assert!(check(&ordinary, Method::GET, "/_cat/indices", ""));
+ // …and the allow-list saying yes is not a grant: the index decision
+ // still refuses an index the guest was never given.
+ let segs = segments("/private-diary/_search");
+ let target = classify("/private-diary/_search");
+ assert!(guest_route_allowed(&Method::POST, &segs, &target, None));
+ assert!(!check(&guest(), Method::POST, "/private-diary/_search", ""));
+ }
+
+ #[test]
+ fn a_share_guest_cannot_ride_someone_elses_point_in_time() {
+ // A PIT decides the searched index in place of the path, and a guest
+ // can never have opened one.
+ assert!(guest_body_denied(
+ BodyShape::Query,
+ br#"{"query":{"match_all":{}},"pit":{"id":"abc","keep_alive":"1m"}}"#
+ ));
+ assert!(guest_body_denied(BodyShape::Query, br#"{"pit":null}"#));
+ assert!(guest_body_denied(
+ BodyShape::MsearchHeaders,
+ b"{}\n{\"query\":{\"match_all\":{}},\"pit\":{\"id\":\"abc\"}}\n"
+ ));
+ // An ordinary search is untouched — including one that merely
+ // mentions the word, or nests it where it is not the PIT clause.
+ assert!(!guest_body_denied(
+ BodyShape::Query,
+ br#"{"query":{"match":{"body":"pit"}}}"#
+ ));
+ assert!(!guest_body_denied(
+ BodyShape::Query,
+ br#"{"query":{"term":{"pit":"x"}}}"#
+ ));
+ assert!(!guest_body_denied(
+ BodyShape::MsearchHeaders,
+ b"{\"index\":\"casefile\"}\n{\"query\":{\"match_all\":{}}}\n"
+ ));
+ assert!(!guest_body_denied(BodyShape::Query, b"not json"));
+ assert!(!guest_body_denied(
+ BodyShape::None,
+ br#"{"pit":{"id":"x"}}"#
+ ));
+ assert!(!guest_body_denied(
+ BodyShape::MgetDocs,
+ br#"{"pit":{"id":"x"}}"#
+ ));
+ }
+
+ #[test]
+ fn query_parameter_names_are_decoded_before_they_are_compared() {
+ assert!(query_names_any(Some("scroll=1m"), GUEST_DENIED_PARAMS));
+ assert!(query_names_any(Some("a=b&Scroll=1m"), GUEST_DENIED_PARAMS));
+ assert!(query_names_any(Some("%73%63roll=1m"), GUEST_DENIED_PARAMS));
+ assert!(query_names_any(Some("scroll"), GUEST_DENIED_PARAMS));
+ assert!(!query_names_any(
+ Some("q=scroll&size=1"),
+ GUEST_DENIED_PARAMS
+ ));
+ assert!(!query_names_any(Some("scroll_size=1"), GUEST_DENIED_PARAMS));
+ assert!(!query_names_any(None, GUEST_DENIED_PARAMS));
+ }
+
/// Run the whole decision the way the middleware does.
fn check(p: &Principal, method: Method, path: &str, body: &str) -> bool {
check_with(p, method, path, body, &NoAliases)
diff --git a/engine/crates/xerj-api/src/graph_api.rs b/engine/crates/xerj-api/src/graph_api.rs
index 9d287e538..10bf1819d 100644
--- a/engine/crates/xerj-api/src/graph_api.rs
+++ b/engine/crates/xerj-api/src/graph_api.rs
@@ -264,6 +264,42 @@ fn index_exists(state: &AppState, index: &str) -> bool {
state.engine.get_index(index).is_ok()
}
+/// The concrete names in a `nodes_index` value.
+///
+/// `xerj brain <folder>` records every dataset index the folder produced as
+/// one comma-joined string (`"ax-mail,ax-pdfs"`), which is also a valid
+/// multi-index search expression — so that is what the meta doc holds.
+fn nodes_index_names(nodes_index: &str) -> impl Iterator<Item = &str> {
+ nodes_index
+ .split(',')
+ .map(str::trim)
+ .filter(|n| !n.is_empty())
+}
+
+/// Authorize `read` on a brain's nodes index — every name in it.
+///
+/// This used to hand the whole string to [`authz::authorize_index`], which
+/// compares it to the principal's grants as ONE name. A key granted `ax-mail`
+/// and `ax-pdfs` does not hold an index called `"ax-mail,ax-pdfs"`, so for any
+/// brain over more than one dataset — the ordinary result of pointing
+/// `xerj brain` at a real folder — every scoped key, and therefore every
+/// share-link guest, was refused `overview` and node hydration with a 403
+/// naming an index that does not exist (live-verified 2026-09-18). Each name is
+/// authorized in its own right; one ungranted name still refuses the request.
+fn authorize_nodes_index(principal: &Principal, nodes_index: &str) -> Result<(), Response> {
+ let mut any = false;
+ for name in nodes_index_names(nodes_index) {
+ authz::authorize_index(principal, name, Privilege::ReadIndex)?;
+ any = true;
+ }
+ if any {
+ Ok(())
+ } else {
+ // Nothing but separators: decide it as the literal it is.
+ authz::authorize_index(principal, nodes_index, Privilege::ReadIndex)
+ }
+}
+
/// Parse a timestamp that may be an epoch-ms JSON number or an RFC3339 string
/// (inputs accept both; outputs are always numbers).
fn parse_ms_value(v: &Value) -> Option<i64> {
@@ -726,7 +762,7 @@ pub async fn ego(
// so it is authorized separately — otherwise a grant on one brain would be
// a read primitive for any index on the node.
if let Some(nodes_index) = params.nodes_index.as_deref() {
- if let Err(denied) = authz::authorize_index(&principal, nodes_index, Privilege::ReadIndex) {
+ if let Err(denied) = authorize_nodes_index(&principal, nodes_index) {
return denied;
}
}
@@ -904,8 +940,7 @@ pub async fn ego(
// authorized against the RESOLVED index, not just the brain. Without
// this, write on one brain would be a read primitive for every index
// on the node.
- if let Err(denied) = authz::authorize_index(&principal, &nodes_index, Privilege::ReadIndex)
- {
+ if let Err(denied) = authorize_nodes_index(&principal, &nodes_index) {
return denied;
}
let mut found: HashSet<String> = HashSet::new();
@@ -1309,17 +1344,22 @@ pub async fn overview(
// The nodes index comes from the brain's meta doc, which is writable by
// anyone with write on the brain — so it is authorized in its own right
// (see the matching check in `ego`).
- if let Err(denied) = authz::authorize_index(&principal, &nodes_index, Privilege::ReadIndex) {
+ if let Err(denied) = authorize_nodes_index(&principal, &nodes_index) {
return denied;
}
- let nodes_total = if index_exists(&state, &nodes_index) {
+ // Counted over the names that exist. `index_exists` on the joined string
+ // is false for any multi-dataset brain, which reported 0 notes for it.
+ let existing: Vec<&str> = nodes_index_names(&nodes_index)
+ .filter(|name| index_exists(&state, name))
+ .collect();
+ let nodes_total = if !existing.is_empty() {
let count_body = EsSearchBody {
query: Some(json!({ "match_all": {} })),
size: 0,
track_total_hits: Some(json!(true)),
..Default::default()
};
- match overview_search(&state, &nodes_index, &principal, count_body).await {
+ match overview_search(&state, &existing.join(","), &principal, count_body).await {
Ok(v) => v
.pointer("/hits/total/value")
.and_then(Value::as_u64)
@@ -1368,6 +1408,38 @@ mod tests {
use xerj_common::{config::Config, metrics::Metrics};
use xerj_engine::Engine;
+ /// `xerj brain <folder>` records a multi-dataset folder as a comma-joined
+ /// `nodes_index`. A key that holds every name in it must be let through;
+ /// a key missing any one of them must not.
+ #[test]
+ fn a_multi_dataset_nodes_index_is_authorized_name_by_name() {
+ let guest = Principal::Scoped {
+ key_id: "g".into(),
+ roles: vec![xerj_engine::rbac::Role::new(
+ "share:1a2b3c4d5e6f",
+ HashSet::from([Privilege::ReadIndex]),
+ vec!["ax-mail".to_string(), "ax-pdfs".to_string()],
+ )],
+ };
+ assert!(authorize_nodes_index(&guest, "ax-mail,ax-pdfs").is_ok());
+ assert!(authorize_nodes_index(&guest, "ax-mail, ax-pdfs").is_ok());
+ assert!(authorize_nodes_index(&guest, "ax-pdfs").is_ok());
+ // One ungranted name refuses the whole request — splitting the list
+ // must not become a way to smuggle a second index past the check.
+ assert!(authorize_nodes_index(&guest, "ax-mail,private-diary").is_err());
+ assert!(authorize_nodes_index(&guest, "private-diary").is_err());
+ assert!(authorize_nodes_index(&guest, "ax-mail,.xerj-memory-other").is_err());
+ // Patterns and empty lists are decided as the literals they are.
+ assert!(authorize_nodes_index(&guest, "*").is_err());
+ assert!(authorize_nodes_index(&guest, "ax-*").is_err());
+ assert!(authorize_nodes_index(&guest, ",").is_err());
+ assert!(authorize_nodes_index(&guest, "").is_err());
+ assert_eq!(
+ nodes_index_names(" a, ,b,").collect::<Vec<_>>(),
+ vec!["a", "b"]
+ );
+ }
+
const T0: i64 = 1_753_600_000_000; // fixture valid_at / created_at
const AS_OF: i64 = 1_753_700_000_000; // fixture as-of instant
const INVALID_AT: i64 = 1_753_650_000_000; // §8.6 invalidation instant
diff --git a/engine/crates/xerj-api/src/lib.rs b/engine/crates/xerj-api/src/lib.rs
index 03349cbdc..c55f4c49d 100644
--- a/engine/crates/xerj-api/src/lib.rs
+++ b/engine/crates/xerj-api/src/lib.rs
@@ -77,6 +77,7 @@ pub mod native;
pub mod rerank_stage;
pub mod responses;
pub mod router;
+pub mod share;
pub mod state;
pub mod stub;
pub mod wal_tap_api;
diff --git a/engine/crates/xerj-api/src/memory_api.rs b/engine/crates/xerj-api/src/memory_api.rs
index b5f81d11c..6dbc8e9e2 100644
--- a/engine/crates/xerj-api/src/memory_api.rs
+++ b/engine/crates/xerj-api/src/memory_api.rs
@@ -106,7 +106,7 @@ fn backing_index(namespace: &str) -> String {
/// name is always a legal, lowercase XERJ/ES index name and cannot be used to
/// smuggle characters (`/`, `,`, `*`, whitespace, uppercase, `..`) into the
/// backing-index routing layer.
-fn validate_namespace(ns: &str) -> Result<(), String> {
+pub(crate) fn validate_namespace(ns: &str) -> Result<(), String> {
if ns.is_empty() {
return Err("namespace must not be empty".into());
}
diff --git a/engine/crates/xerj-api/src/router.rs b/engine/crates/xerj-api/src/router.rs
index f7397741d..0a6e84842 100644
--- a/engine/crates/xerj-api/src/router.rs
+++ b/engine/crates/xerj-api/src/router.rs
@@ -29,7 +29,7 @@ use xerj_common::config::CorsConfig;
use crate::{
audit_mw, auth::auth_middleware, authz, es_compat, graph_api, ism_api, memory_api, native,
- state::AppState, wal_tap_api,
+ share, state::AppState, wal_tap_api,
};
// ─────────────────────────────────────────────────────────────────────────────
@@ -893,6 +893,24 @@ pub fn build_es_compat_router(state: AppState) -> Router {
)
.route("/_memory/:namespace/_recall", post(memory_api::recall))
.route("/_memory/:namespace/:id", delete(memory_api::forget_one))
+ // ── Share links ───────────────────────────────────────────────────────
+ // `xerj share`: hand one indexed corpus to a guest as a scoped,
+ // read-only, expiring key. Create/list/revoke are superuser-only in
+ // the handler; `claim` is the one unauthenticated route on this
+ // router (`auth::is_share_claim_path`) and is rate-limited instead.
+ // The share id is in the claim BODY, never in the path — a path is
+ // what an access log records. The static `/_share/claim` wins over
+ // `/_share/:id`, which only answers DELETE. See `share.rs`.
+ .route("/_share", post(share::create_share).get(share::list_shares))
+ .route("/_share/:id", delete(share::revoke_share))
+ .route(
+ "/_share/claim",
+ // An unauthenticated caller gets a few KiB, not the node-wide
+ // bulk-ingest limit. `DefaultBodyLimit` is what the `Json`
+ // extractor consults; it is disabled router-wide below and
+ // re-enabled for this one route.
+ post(share::claim_share).layer(DefaultBodyLimit::max(share::MAX_CLAIM_BODY_BYTES)),
+ )
// ── Second-Brain Graph API ─────────────────────────────────────────────
// Edges are ordinary documents in reserved `.xerj-memory-{brain}-edges`
// indices; traversal is a bounded columnar expansion
@@ -931,6 +949,10 @@ pub fn build_es_compat_router(state: AppState) -> Router {
state.clone(),
auth_middleware,
))
+ // OUTSIDE authentication, so the `401` and `403` the two layers above
+ // produce for `/_share…` are `no-store` too — the handlers only cover
+ // the responses they write themselves.
+ .layer(middleware::from_fn(share_no_store_middleware))
.layer(middleware::from_fn_with_state(state, es_headers_middleware))
.layer(middleware::from_fn(request_id_middleware))
.layer(trace_layer(access_log))
@@ -949,6 +971,21 @@ pub fn build_es_compat_router(state: AppState) -> Router {
.layer(RequestDecompressionLayer::new().gzip(true))
}
+/// Everything under `/_share` is `Cache-Control: no-store`, whoever produced
+/// the response. The handlers set it on what they return; a request refused by
+/// `auth_middleware` (401) or `authz_middleware` (403) never reaches one, and
+/// the docs say "every `/_share` response — success or error".
+async fn share_no_store_middleware(req: Request, next: Next) -> Response {
+ let path = req.uri().path();
+ let under_share = path == "/_share" || path.starts_with("/_share/");
+ let resp = next.run(req).await;
+ if under_share {
+ share::no_store(resp)
+ } else {
+ resp
+ }
+}
+
// ─────────────────────────────────────────────────────────────────────────────
// Middleware helpers
// ─────────────────────────────────────────────────────────────────────────────
diff --git a/engine/crates/xerj-api/src/share.rs b/engine/crates/xerj-api/src/share.rs
new file mode 100644
index 000000000..bb0642b69
--- /dev/null
+++ b/engine/crates/xerj-api/src/share.rs
@@ -0,0 +1,1726 @@
+//! Share links — hand one indexed corpus to someone who has nothing else.
+//!
+//! `xerj brain <folder>` leaves the owner with a node whose only credential is
+//! the admin key. Sending a friend that key hands them the whole node; minting
+//! them a scoped key by hand means explaining `role_descriptors`. A share is
+//! the one-command version of the second thing: the owner names an index (and
+//! optionally the brain whose links sit beside it), gets a link plus a
+//! passcode, and the guest who opens the link and types the passcode is
+//! handed a **scoped, read-only, expiring** API key that reaches exactly the
+//! indices the share names — and nothing else on the node.
+//!
+//! ## What is stored, and what is not
+//!
+//! Records live in `<data_dir>/shares.json` beside `api_keys.json` — same 0600
+//! atomic writer ([`xerj_engine::engine::write_secret_file_atomic`]). They are
+//! deliberately *not* documents in a reserved index: a file is reachable by no
+//! search, `_cat`, snapshot, alias or `_delete_by_query` route, so there is no
+//! second copy of the reserved-namespace exception list to keep in sync.
+//!
+//! Nothing in a record is a usable secret:
+//! - the share id (the token in the link) is stored as a **SHA-256 digest**;
+//! the plaintext exists only in the create response and in the link;
+//! - the passcode is stored as an **Argon2id** hash. Unlike a minted API-key
+//! secret (244 bits of CSPRNG, see `xerj_engine::secret_hash` for why that
+//! one is a fast hash) a passcode is short and may have been chosen by a
+//! human, so an offline guess is a real threat and a slow hash is the right
+//! tool. It is verified once per claim, on a rate-limited route, so the cost
+//! never lands on the request path;
+//! - the guest's API key is **minted at claim time**, one per claim, expiring
+//! when the share expires. The record keeps only the minted key *ids* so a
+//! revoke can invalidate every key the share ever produced. No credential
+//! is ever written to the share file.
+//!
+//! ## Who may do what
+//!
+//! | Route | Who |
+//! |---|---|
+//! | `POST /_share`, `GET /_share`, `DELETE /_share/{handle}` | superuser only (the admin key) — a scoped or unscoped key gets 403 |
+//! | `POST /_share/claim` | **nobody in particular** — it is exempt from authentication (`auth::is_share_claim_path`) the way `/v1/metrics` is for the scrape token, and rate-limited per source address and per share instead |
+//!
+//! The claim route is the only unauthenticated door that hands out a
+//! credential, so it is narrow on purpose: one exact path, `POST` only, a body
+//! capped at [`MAX_CLAIM_BODY_BYTES`], a sliding-window throttle,
+//! `Cache-Control: no-store` on every answer, and every outcome — success,
+//! wrong passcode, exhausted, expired, revoked, unknown, throttled — in the
+//! audit log with the source address.
+//!
+//! ## The share id is never part of a request path
+//!
+//! The claim body is `{id, passcode}`. The first cut put the id in the path
+//! (`POST /_share/{id}/claim`), and the guest page's care to keep the id in the
+//! URL *fragment* was undone one request later: a request path is exactly what
+//! an access log records. With `logging.access_log = true` this node wrote the
+//! id to `server.log` twice per claim, and any reverse proxy or tunnel in front
+//! of it logged the same line (review of PR #947, reproduced 2026-09-19). A
+//! body is in none of those logs. `DELETE /_share/{handle}` takes the public
+//! handle, which opens nothing. It also accepts the full id, for an API caller
+//! who kept only that — such a call puts the id in its own request path, which
+//! is why `xerj share --revoke` sends only the handle.
+//!
+//! ## The two throttles, and why a tunnel does not break them
+//!
+//! - A claim against a **known** share is charged to that share's window
+//! ([`SHARE_PER_MINUTE`] / [`SHARE_PER_HOUR`]), from anywhere. This is the
+//! passcode lockout, and it does not depend on knowing who is asking.
+//! - A claim against an **unknown** id is charged to the source address's
+//! window ([`IP_PER_MINUTE`] / [`IP_PER_HOUR`]). It bounds junk traffic and
+//! the audit lines it writes.
+//!
+//! They are deliberately *not* stacked. The first cut charged the source
+//! window before looking the share up, which is fine on a directly exposed
+//! node and wrong behind `xerj share --tunnel`: every request a tunnel (or any
+//! reverse proxy on the same host) delivers arrives from `127.0.0.1`, so all
+//! guests shared one source bucket, and ten junk requests a minute from anyone
+//! who had found the hostname answered every real guest with `429` — a
+//! one-line denial of service on the feature. The fix is not to believe
+//! `X-Forwarded-For`: a direct client writes that header itself (#76 S5-4),
+//! and an unconfigured node believes nobody. It is to stop the collapsed
+//! bucket from mattering: a real share id is governed by its own window, which
+//! no amount of junk can touch, and junk is governed by the source window,
+//! where collapsing every tunnel client into one bucket only makes the bound
+//! tighter.
+//!
+//! Operators who want each guest's real address — in the audit log and as the
+//! junk-traffic key — declare the proxy the usual way,
+//! `server.trusted_proxies = ["127.0.0.1", "::1"]`; then, and only then,
+//! `X-Forwarded-For` is read, right to left (see [`ClaimSource`]). IPv6
+//! sources are keyed by their /64, since one host is routinely handed a whole
+//! /64 to rotate through.
+//!
+//! ## An open node cannot share
+//!
+//! With authentication off (`--insecure`, `auth.enabled = false`, or no admin
+//! key) every request is [`Principal::Superuser`], so a "scoped, read-only"
+//! guest key would restrict nothing. `POST /_share` and the claim route answer
+//! `409` there rather than hand out a credential that promises a boundary the
+//! node is not enforcing.
+//!
+//! ## What a guest can reach
+//!
+//! The minted key carries one role, named `share:<handle>`: `read` on the
+//! share's `indices` plus, when a brain is named, `read` on that brain's edges
+//! index (`authz::brain_edges_index`). Two things then confine it:
+//!
+//! 1. the index grants — the same per-index authorization every scoped key
+//! gets, in the middleware and again in the engine's index funnel;
+//! 2. a **route allow-list** that applies to share guests only
+//! (`authz::guest_route_allowed`, keyed on [`GUEST_ROLE_PREFIX`]):
+//! `_search`, `_count`, `_msearch`, `_mget`, `_mapping`, `_field_caps` and
+//! `GET _doc/{id}` on the granted indices, and
+//! `GET /_graph/{brain}/ego|overview`. An ordinary scoped key is given a
+//! *filtered* view of `_cat`, `_cluster/*`, `_nodes` and friends because
+//! Kibana needs one; a guest is given none of it. No `scroll`, no `_pit`,
+//! no `_async_search` either — nothing that parks state on the owner's
+//! machine.
+//!
+//! The `autoindex-catalog` index is **never** granted, and cannot be named in a
+//! share ([`CATALOG_INDEX`], refused by `validate_share_index`): it lists every
+//! corpus on the node, the engine has no document-level security to filter it
+//! with, and the guest page already receives the index name directly.
+//!
+//! Every response to a guest key is `Cache-Control: no-store`
+//! (`authz::authz_middleware`): it is somebody's documents, on its way through
+//! whatever proxy or tunnel the owner put in front of the node.
+
+use std::collections::HashSet;
+use std::net::{IpAddr, SocketAddr};
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+
+use argon2::password_hash::{
+ rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString,
+};
+use argon2::Argon2;
+use axum::{
+ extract::{ConnectInfo, FromRequestParts, Path as AxumPath, State},
+ http::{header, request::Parts, StatusCode},
+ response::{IntoResponse, Response},
+ Json,
+};
+use dashmap::DashMap;
+use rand::RngCore;
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use sha2::{Digest, Sha256};
+use xerj_engine::rbac::{Privilege, Role};
+
+use crate::auth::Principal;
+use crate::error::{EsErrorBody, EsErrorResponse, EsRootCause};
+use crate::state::AppState;
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Limits
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Default lifetime when the request names none.
+pub const DEFAULT_EXPIRES_IN: &str = "24h";
+/// Longest lifetime a share may be given.
+pub const MAX_EXPIRES_MS: u64 = 30 * 86_400_000;
+/// Shortest lifetime. Seconds are accepted so a test can watch one expire.
+pub const MIN_EXPIRES_MS: u64 = 1_000;
+/// `max_claims` bounds.
+pub const DEFAULT_MAX_CLAIMS: u32 = 1;
+pub const MAX_MAX_CLAIMS: u32 = 50;
+/// A caller-supplied passcode must be at least this long.
+pub const MIN_PASSCODE_CHARS: usize = 6;
+pub const MAX_PASSCODE_CHARS: usize = 128;
+pub const MAX_LABEL_CHARS: usize = 120;
+/// How many indices one share may name.
+pub const MAX_INDICES: usize = 32;
+/// Largest body the unauthenticated claim route reads: a 32-hex id and a
+/// passcode of at most [`MAX_PASSCODE_CHARS`] characters (four bytes each at
+/// worst), with room for JSON around them. The router enforces it
+/// (`router.rs`, the `/_share/claim` route) — the node-wide
+/// `limits.max_body_bytes` is sized for bulk ingest, not for a caller who has
+/// not authenticated.
+pub const MAX_CLAIM_BODY_BYTES: usize = 4096;
+/// `xerj autoindex`'s catalog: one row per corpus on the node — index names,
+/// file counts, sample queries. Same value as
+/// `xerj_autoindex::catalog::CATALOG_INDEX` (this crate does not depend on
+/// that one; `xerj-server` has a test that the two agree).
+pub const CATALOG_INDEX: &str = "autoindex-catalog";
+
+/// Claim attempts per source address per minute / per hour.
+pub const IP_PER_MINUTE: u32 = 10;
+pub const IP_PER_HOUR: u32 = 100;
+/// Claim attempts against one share per minute / per hour, from anywhere.
+/// This is the lockout: a passcode has ~40 bits, and thirty guesses an hour
+/// against it is a search that does not finish.
+pub const SHARE_PER_MINUTE: u32 = 10;
+pub const SHARE_PER_HOUR: u32 = 30;
+
+/// Every guest key's single role is named `share:<handle>`. `authz` keys its
+/// guest route allow-list on this prefix (`Principal::is_share_guest`).
+pub const GUEST_ROLE_PREFIX: &str = "share:";
+
+/// Hard ceiling on live rate windows. Past it, new source addresses share one
+/// overflow bucket — throttled together rather than tracked without bound.
+const MAX_WINDOWS: usize = 50_000;
+/// Stale windows are swept every this-many charges, not on every call.
+const PRUNE_EVERY: u64 = 64;
+
+const WINDOW_MIN_MS: u64 = 60_000;
+const WINDOW_HOUR_MS: u64 = 3_600_000;
+
+/// The file name under the data directory.
+const SHARES_FILE: &str = "shares.json";
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Records
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// One share, as persisted. The two secret-derived fields are private and
+/// only ever hold digests — see the module docs.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ShareRecord {
+ /// Public handle: the first 12 hex chars of `id_hash`. Safe to list and
+ /// to print in a revoke command; it cannot be turned back into the link.
+ pub handle: String,
+ /// SHA-256 of the share id (the token carried in the link), lowercase hex.
+ id_hash: String,
+ /// Argon2id PHC string of the passcode.
+ passcode_hash: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub label: Option<String>,
+ /// Concrete index names the guest may read. Never patterns.
+ pub indices: Vec<String>,
+ /// The brain whose edges index is also granted, if any.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub brain: Option<String>,
+ pub created_ms: u64,
+ pub expires_ms: u64,
+ pub max_claims: u32,
+ #[serde(default)]
+ pub claims: u32,
+ #[serde(default)]
+ pub revoked: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub revoked_ms: Option<u64>,
+ /// Ids of every API key a claim minted, so a revoke can invalidate them.
+ #[serde(default)]
+ pub key_ids: Vec<String>,
+}
+
+impl ShareRecord {
+ /// Every index the guest key is granted `read` on.
+ pub fn granted_indices(&self) -> Vec<String> {
+ let mut out = self.indices.clone();
+ if let Some(brain) = &self.brain {
+ out.push(crate::authz::brain_edges_index(brain));
+ }
+ out
+ }
+
+ /// Why this share cannot be claimed right now, if it cannot.
+ fn unavailable(&self, now_ms: u64) -> Option<&'static str> {
+ if self.revoked {
+ Some("this share link has been revoked")
+ } else if now_ms >= self.expires_ms {
+ Some("this share link has expired")
+ } else if self.claims >= self.max_claims {
+ Some("this share link has been used up (max_claims reached)")
+ } else {
+ None
+ }
+ }
+
+ /// The listing / response shape. Carries no hash.
+ fn public_json(&self, now_ms: u64) -> Value {
+ let status = if self.revoked {
+ "revoked"
+ } else if now_ms >= self.expires_ms {
+ "expired"
+ } else if self.claims >= self.max_claims {
+ "exhausted"
+ } else {
+ "active"
+ };
+ json!({
+ "handle": self.handle,
+ "label": self.label,
+ "index": self.indices.join(","),
+ "indices": self.indices,
+ "brain": self.brain,
+ "created_at": rfc3339(self.created_ms),
+ "expires_at": rfc3339(self.expires_ms),
+ "max_claims": self.max_claims,
+ "claims": self.claims,
+ "claims_left": self.max_claims.saturating_sub(self.claims),
+ "revoked": self.revoked,
+ "status": status,
+ })
+ }
+}
+
+#[derive(Clone, Copy)]
+struct RateWindow {
+ count: u32,
+ start_ms: u64,
+}
+
+/// The share store: records keyed by handle, plus the claim rate limiter.
+pub struct ShareStore {
+ path: PathBuf,
+ records: DashMap<String, ShareRecord>,
+ windows: DashMap<String, RateWindow>,
+ charges: std::sync::atomic::AtomicU64,
+}
+
+/// A refused charge.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Throttled {
+ /// Seconds until the window that refused rolls over.
+ pub retry_after_secs: u64,
+ /// True for the first refusal in that window only. The caller audits that
+ /// one and stays quiet for the rest, so an unauthenticated flood cannot
+ /// turn the audit log into its own denial of service.
+ pub first_in_window: bool,
+}
+
+impl ShareStore {
+ /// Load `<data_dir>/shares.json`, or start empty. A file that does not
+ /// parse is logged and left alone rather than overwritten — the operator
+ /// can inspect it; nothing in it could authenticate anyway.
+ pub fn open(data_dir: &str) -> Arc<Self> {
+ let path = Path::new(data_dir).join(SHARES_FILE);
+ let records = DashMap::new();
+ match std::fs::read(&path) {
+ Ok(bytes) => match serde_json::from_slice::<Vec<ShareRecord>>(&bytes) {
+ Ok(list) => {
+ for r in list {
+ records.insert(r.handle.clone(), r);
+ }
+ }
+ Err(e) => {
+ tracing::error!(path = %path.display(), error = %e, "shares.json does not parse; starting with no shares")
+ }
+ },
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
+ Err(e) => {
+ tracing::error!(path = %path.display(), error = %e, "shares.json unreadable; starting with no shares")
+ }
+ }
+ Arc::new(Self {
+ path,
+ records,
+ windows: DashMap::new(),
+ charges: std::sync::atomic::AtomicU64::new(0),
+ })
+ }
+
+ fn persist(&self) -> std::io::Result<()> {
+ let mut list: Vec<ShareRecord> = self.records.iter().map(|r| r.value().clone()).collect();
+ list.sort_by_key(|r| r.created_ms);
+ let bytes = serde_json::to_vec_pretty(&list)?;
+ xerj_engine::engine::write_secret_file_atomic(&self.path, &bytes)
+ }
+
+ fn find_by_id(&self, share_id: &str) -> Option<ShareRecord> {
+ let (hash, handle) = hash_share_id(share_id);
+ let rec = self.records.get(&handle)?;
+ // Full-digest compare, in constant time, so a handle prefix collision
+ // (or a caller who only knows the handle) never resolves to a record.
+ if constant_time_eq(rec.id_hash.as_bytes(), hash.as_bytes()) {
+ Some(rec.clone())
+ } else {
+ None
+ }
+ }
+
+ /// Resolve `DELETE /_share/{id}` — accepts the full share id (what the
+ /// create response returned) or the public handle (what the listing
+ /// shows). Either is enough to revoke: revoking is superuser-only.
+ fn find_for_revoke(&self, id_or_handle: &str) -> Option<String> {
+ if let Some(rec) = self.find_by_id(id_or_handle) {
+ return Some(rec.handle);
+ }
+ self.records.get(id_or_handle).map(|r| r.handle.clone())
+ }
+
+ /// Snapshot of every record, oldest first.
+ pub fn list(&self) -> Vec<ShareRecord> {
+ let mut list: Vec<ShareRecord> = self.records.iter().map(|r| r.value().clone()).collect();
+ list.sort_by_key(|r| r.created_ms);
+ list
+ }
+
+ /// Test seam: rewrite one record's expiry. Not reachable over HTTP.
+ #[doc(hidden)]
+ pub fn set_expiry_for_test(&self, handle: &str, expires_ms: u64) {
+ if let Some(mut r) = self.records.get_mut(handle) {
+ r.expires_ms = expires_ms;
+ }
+ }
+
+ /// Charge one claim attempt against `key`. `Err` when over either window.
+ /// Same sliding-window shape as the console's auth limiter
+ /// (`xerj-console-api::auth::rate_limit`), re-implemented here because
+ /// that one is bound to `ConsoleState` and this crate must not depend on
+ /// the console.
+ fn charge(
+ &self,
+ key: &str,
+ per_minute: u32,
+ per_hour: u32,
+ now_ms: u64,
+ ) -> Result<(), Throttled> {
+ use std::sync::atomic::Ordering;
+ if self
+ .charges
+ .fetch_add(1, Ordering::Relaxed)
+ .is_multiple_of(PRUNE_EVERY)
+ {
+ self.windows
+ .retain(|_, w| now_ms.saturating_sub(w.start_ms) < WINDOW_HOUR_MS);
+ }
+ // Bounded state for an unauthenticated route: once the table is full,
+ // addresses it has not seen yet are throttled as one.
+ // Only source keys collapse: share keys are bounded by the number of
+ // shares, which only the superuser can create.
+ let key = if key.starts_with("ip:")
+ && self.windows.len() >= MAX_WINDOWS
+ && !self.windows.contains_key(&format!("{key}:m"))
+ {
+ "ip:overflow"
+ } else {
+ key
+ };
+ for (suffix, window_ms, limit) in [
+ ("m", WINDOW_MIN_MS, per_minute),
+ ("h", WINDOW_HOUR_MS, per_hour),
+ ] {
+ let k = format!("{key}:{suffix}");
+ let mut w = self.windows.entry(k).or_insert(RateWindow {
+ count: 0,
+ start_ms: now_ms,
+ });
+ if now_ms.saturating_sub(w.start_ms) > window_ms {
+ *w = RateWindow {
+ count: 0,
+ start_ms: now_ms,
+ };
+ }
+ w.count = w.count.saturating_add(1);
+ if w.count > limit {
+ return Err(Throttled {
+ retry_after_secs: (w.start_ms + window_ms).saturating_sub(now_ms) / 1000 + 1,
+ first_in_window: w.count == limit + 1,
+ });
+ }
+ }
+ Ok(())
+ }
+}
+
+/// The rate-limit key for a claim source: the address itself for IPv4, the
+/// enclosing /64 for IPv6. A single IPv6 host is routinely delegated a whole
+/// /64 and can take a fresh address per request, so per-address buckets there
+/// are no throttle at all. Anything that is not an address (`unknown`) is its
+/// own bucket.
+fn source_bucket(source: &str) -> String {
+ match source.parse::<IpAddr>() {
+ Ok(IpAddr::V6(v6)) => {
+ let mut seg = v6.segments();
+ seg[4..].fill(0);
+ format!("{}/64", std::net::Ipv6Addr::from(seg))
+ }
+ _ => source.to_string(),
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Secrets
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// A fresh share id: 128 bits from the OS CSPRNG, lowercase hex.
+fn mint_share_id() -> String {
+ let mut bytes = [0u8; 16];
+ rand::rngs::OsRng.fill_bytes(&mut bytes);
+ hex(&bytes)
+}
+
+/// `(full sha256 hex, 12-char handle)` for a share id.
+fn hash_share_id(share_id: &str) -> (String, String) {
+ let digest = Sha256::digest(share_id.as_bytes());
+ let full = hex(&digest);
+ let handle = full[..12].to_string();
+ (full, handle)
+}
+
+/// Alphabet for generated passcodes: lowercase + digits with the four
+/// look-alikes (`0/o`, `1/l`, plus `i`) removed, 31 symbols. Eight of them is
+/// ~39.6 bits, which with [`SHARE_PER_HOUR`] guesses an hour is out of reach
+/// online, and which is what the human on the other end has to type.
+const PASSCODE_ALPHABET: &[u8] = b"abcdefghjkmnpqrstuvwxyz23456789";
+
+/// `xxxx-xxxx` from the alphabet above.
+pub fn generate_passcode() -> String {
+ let mut out = String::with_capacity(9);
+ let mut rng = rand::rngs::OsRng;
+ for i in 0..8 {
+ if i == 4 {
+ out.push('-');
+ }
+ // Rejection-free: 31 does not divide 256, so draw a u32 and take the
+ // modulo of a much larger range; the bias is < 2^-24 per symbol.
+ let n = rng.next_u32() as usize % PASSCODE_ALPHABET.len();
+ out.push(PASSCODE_ALPHABET[n] as char);
+ }
+ out
+}
+
+fn hash_passcode(passcode: &str) -> Result<String, String> {
+ let salt = SaltString::generate(&mut OsRng);
+ Argon2::default()
+ .hash_password(passcode.as_bytes(), &salt)
+ .map(|h| h.to_string())
+ .map_err(|e| e.to_string())
+}
+
+/// Constant-time-by-construction: argon2's verifier compares the derived
+/// key with `subtle`. Anything unparsable is a `false`, never a panic.
+pub fn verify_passcode(presented: &str, stored: &str) -> bool {
+ let Ok(parsed) = PasswordHash::new(stored) else {
+ return false;
+ };
+ Argon2::default()
+ .verify_password(presented.as_bytes(), &parsed)
+ .is_ok()
+}
+
+fn hex(bytes: &[u8]) -> String {
+ const T: &[u8; 16] = b"0123456789abcdef";
+ let mut s = String::with_capacity(bytes.len() * 2);
+ for b in bytes {
+ s.push(T[(b >> 4) as usize] as char);
+ s.push(T[(b & 15) as usize] as char);
+ }
+ s
+}
+
+fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
+ if a.len() != b.len() {
+ return false;
+ }
+ let mut diff = 0u8;
+ for (x, y) in a.iter().zip(b) {
+ diff |= x ^ y;
+ }
+ diff == 0
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Small helpers
+// ─────────────────────────────────────────────────────────────────────────────
+
+fn now_ms() -> u64 {
+ chrono::Utc::now().timestamp_millis().max(0) as u64
+}
+
+fn rfc3339(ms: u64) -> String {
+ chrono::DateTime::<chrono::Utc>::from_timestamp_millis(ms as i64)
+ .map(|t| t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
+ .unwrap_or_default()
+}
+
+/// `"30m"`, `"24h"`, `"7d"` (and `"90s"`) → milliseconds. `None` on anything
+/// else, including a bare number: the unit is the whole point.
+pub fn parse_expires_in(spec: &str) -> Option<u64> {
+ let s = spec.trim();
+ let split = s.find(|c: char| c.is_ascii_alphabetic())?;
+ let (num, unit) = s.split_at(split);
+ let n: u64 = num.trim().parse().ok()?;
+ let per_ms: u64 = match unit.trim() {
+ "d" => 86_400_000,
+ "h" => 3_600_000,
+ "m" => 60_000,
+ "s" => 1_000,
+ _ => return None,
+ };
+ n.checked_mul(per_ms)
+}
+
+/// Is `name` a concrete index a share may grant? Same alphabet the engine
+/// accepts, minus anything that is a pattern or a list — a grant must name
+/// exactly what it grants — and minus the reserved namespace, which is only
+/// reachable through `brain`.
+fn validate_share_index(name: &str) -> Result<(), String> {
+ if name.is_empty() || name.len() > 255 {
+ return Err("index name must be 1–255 characters".into());
+ }
+ if name.starts_with(crate::authz::RESERVED_INDEX_PREFIX) {
+ return Err(format!(
+ "index `{name}` is in the reserved .xerj-memory-* namespace; share a brain with `brain` instead"
+ ));
+ }
+ // Every dot-index is the node's own: `.xerj_sessions`, `.xerj_api_tokens`,
+ // `.xerj_passkeys` and `.xerj_magic_links` are credential stores, and
+ // `.xerj_audit` records who connected from where. The check above named only
+ // the memory namespace, so a share on any of these was accepted — found by
+ // the first live run (2026-09-18), which minted a guest link onto the audit
+ // log. A share grants a *user's* corpus, and no user index starts with a dot,
+ // so the rule is the whole prefix rather than a list that has to be kept in
+ // step with every system index added later.
+ if name.starts_with('.') {
+ return Err(format!(
+ "index `{name}` is a system index and cannot be shared; a share names one of your own indices"
+ ));
+ }
+ if name.starts_with('_') {
+ return Err(format!("index `{name}` is not an index name"));
+ }
+ // The catalog describes EVERY corpus on the node. The docs said it was
+ // "never granted" while `xerj share autoindex-catalog` minted a guest key
+ // that read all of it (review of PR #947). A guest is handed one corpus;
+ // the list of the others is not part of it, and there is no
+ // document-level security to filter the list down.
+ if name == CATALOG_INDEX {
+ return Err(format!(
+ "index `{name}` is the autoindex catalog: it describes every corpus on this \
+ node, not one of them, so it cannot be shared. Share the corpus index itself \
+ (`xerj autoindex map` lists them)"
+ ));
+ }
+ for c in name.chars() {
+ if c.is_whitespace()
+ || matches!(
+ c,
+ '*' | ',' | '/' | '\\' | '?' | '"' | '<' | '>' | '|' | '#'
+ )
+ {
+ return Err(format!(
+ "index `{name}` contains `{c}`; a share names concrete indices, not patterns"
+ ));
+ }
+ if c.is_ascii_uppercase() {
+ return Err(format!("index `{name}` must be lowercase"));
+ }
+ }
+ Ok(())
+}
+
+fn es_error(status: StatusCode, error_type: &str, reason: String) -> Response {
+ let body = EsErrorResponse {
+ error: EsErrorBody {
+ root_cause: vec![EsRootCause {
+ error_type: error_type.to_string(),
+ reason: reason.clone(),
+ resource_type: None,
+ resource_id: None,
+ index_uuid: None,
+ index: None,
+ }],
+ error_type: error_type.to_string(),
+ reason,
+ resource_type: None,
+ resource_id: None,
+ index_uuid: None,
+ index: None,
+ request_id: None,
+ },
+ status: status.as_u16(),
+ xerj_hint: None,
+ };
+ (status, Json(body)).into_response()
+}
+
+fn bad_request(reason: String) -> Response {
+ es_error(
+ StatusCode::BAD_REQUEST,
+ "illegal_argument_exception",
+ reason,
+ )
+}
+
+/// Is this node enforcing authentication at all? Mirrors the open-mode test in
+/// [`crate::auth::authenticate`] exactly: those are the conditions under which
+/// every request is the superuser.
+fn auth_is_enforced(state: &AppState) -> bool {
+ let cfg = &state.config.auth;
+ cfg.enabled && !cfg.admin_api_key.is_empty()
+}
+
+/// The `409` an open node gives instead of a share. See the module docs.
+fn open_node_refusal() -> Response {
+ es_error(
+ StatusCode::CONFLICT,
+ "illegal_state_exception",
+ "this node runs with authentication off (--insecure, or auth.enabled = false), so \
+ every request is already the superuser and a read-only guest key would restrict \
+ nothing. Restart the node with authentication on (the default) to share an index"
+ .into(),
+ )
+}
+
+/// Nothing under `/_share` may be stored by a browser, a proxy or a CDN: the
+/// create response carries the link and passcode, the claim response carries
+/// a live credential, and an error body says whether a share exists.
+/// `no-store` for HTTP/1.1 caches, `Pragma` for the HTTP/1.0 ones still found
+/// in front of things.
+pub(crate) fn no_store(mut resp: Response) -> Response {
+ let headers = resp.headers_mut();
+ headers.insert(
+ header::CACHE_CONTROL,
+ header::HeaderValue::from_static("no-store, max-age=0"),
+ );
+ headers.insert(header::PRAGMA, header::HeaderValue::from_static("no-cache"));
+ resp
+}
+
+/// Does the node believe forwarding headers from a proxy on this machine —
+/// i.e. is loopback a declared `server.trusted_proxies` entry? Reported in the
+/// create response so `xerj share --tunnel` can tell the owner whose address
+/// the audit log will record.
+fn loopback_is_trusted_proxy(state: &AppState) -> bool {
+ xerj_common::net::TrustedProxies::parse(&state.config.server.trusted_proxies)
+ .map(|t| t.contains(&IpAddr::from([127, 0, 0, 1])))
+ .unwrap_or(false)
+}
+
+/// The management routes are superuser-only. The admin key is what
+/// `xerj share` reads from `<data-dir>/admin.key`; a scoped key must not be
+/// able to widen its own reach by minting a share, and an unscoped key must
+/// not be able to hand the reserved namespace to a guest it cannot reach
+/// itself.
+fn require_superuser(principal: &Principal) -> Result<(), Response> {
+ if principal.is_superuser() {
+ Ok(())
+ } else {
+ Err(crate::authz::forbidden(
+ principal,
+ "_share",
+ Privilege::SecurityAdmin,
+ ))
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Claim source address
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// The address a claim came from, for the rate limiter and the audit line.
+///
+/// The TCP peer, from `ConnectInfo` — the caller cannot forge it. Forwarding
+/// headers are believed only when the peer is one of the operator's declared
+/// `server.trusted_proxies`, walking `X-Forwarded-For` right-to-left past
+/// other declared proxies (the same reading as the console's `client_ip`,
+/// #76 S5-4). With no `ConnectInfo` at all — a router driven by `oneshot` in
+/// a test — every caller shares one `unknown` bucket, which throttles rather
+/// than exempts.
+pub struct ClaimSource(pub String);
+
+#[axum::async_trait]
+impl FromRequestParts<AppState> for ClaimSource {
+ type Rejection = std::convert::Infallible;
+
+ async fn from_request_parts(
+ parts: &mut Parts,
+ state: &AppState,
+ ) -> Result<Self, Self::Rejection> {
+ let peer = parts
+ .extensions
+ .get::<ConnectInfo<SocketAddr>>()
+ .map(|c| xerj_common::net::canonical_ip(c.0.ip()));
+ let Some(peer) = peer else {
+ return Ok(ClaimSource("unknown".to_string()));
+ };
+ let trusted = xerj_common::net::TrustedProxies::parse(&state.config.server.trusted_proxies)
+ .unwrap_or_else(|_| xerj_common::net::TrustedProxies::none());
+ if !trusted.contains(&peer) {
+ return Ok(ClaimSource(peer.to_string()));
+ }
+ let elements: Vec<&str> = parts
+ .headers
+ .get_all("x-forwarded-for")
+ .iter()
+ .filter_map(|v| v.to_str().ok())
+ .flat_map(|v| v.split(','))
+ .collect();
+ for element in elements.iter().rev() {
+ match xerj_common::net::parse_forwarded_element(element) {
+ Some(ip) => {
+ let ip: IpAddr = xerj_common::net::canonical_ip(ip);
+ if !trusted.contains(&ip) {
+ return Ok(ClaimSource(ip.to_string()));
+ }
+ }
+ None => break,
+ }
+ }
+ Ok(ClaimSource(peer.to_string()))
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Handlers
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// `POST /_share` — create a share. Superuser only.
+///
+/// Body: `{index: "name" | ["a","b"], brain?, expires_in?: "24h", max_claims?: 1,
+/// passcode?, label?}`. Returns the share id, the console path to send, and
+/// the passcode — the only time either plaintext is ever shown.
+pub async fn create_share(
+ State(state): State<AppState>,
+ principal: Principal,
+ body: Option<Json<Value>>,
+) -> Response {
+ no_store(create_share_inner(state, principal, body).await)
+}
+
+async fn create_share_inner(
+ state: AppState,
+ principal: Principal,
+ body: Option<Json<Value>>,
+) -> Response {
+ if !auth_is_enforced(&state) {
+ state.engine.audit.append(
+ "share.create",
+ principal.label(),
+ "_share",
+ "denied",
+ "node has authentication off",
+ );
+ return open_node_refusal();
+ }
+ if let Err(resp) = require_superuser(&principal) {
+ state
+ .engine
+ .audit
+ .append("share.create", principal.label(), "_share", "denied", "");
+ return resp;
+ }
+ let Some(Json(body)) = body else {
+ return bad_request("a JSON body naming `index` is required".into());
+ };
+
+ // `index`: a string, a comma list, or an array. Deduplicated, order kept.
+ let mut indices: Vec<String> = Vec::new();
+ let raw = body.get("index").or_else(|| body.get("indices"));
+ match raw {
+ Some(Value::String(s)) => indices.extend(
+ s.split(',')
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(String::from),
+ ),
+ Some(Value::Array(a)) => indices.extend(
+ a.iter()
+ .filter_map(Value::as_str)
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(String::from),
+ ),
+ Some(_) => return bad_request("`index` must be a string or an array of strings".into()),
+ None => {}
+ }
+ let mut seen = HashSet::new();
+ indices.retain(|i| seen.insert(i.clone()));
+ let brain = match body.get("brain") {
+ None | Some(Value::Null) => None,
+ Some(Value::String(b)) if !b.trim().is_empty() => {
+ let b = b.trim().to_string();
+ if let Err(why) = crate::memory_api::validate_namespace(&b) {
+ return bad_request(format!("`brain`: {why}"));
+ }
+ Some(b)
+ }
+ Some(_) => return bad_request("`brain` must be a string".into()),
+ };
+ if indices.is_empty() && brain.is_none() {
+ return bad_request(
+ "`index` (or `brain`) is required — a share must name what it grants".into(),
+ );
+ }
+ if indices.len() > MAX_INDICES {
+ return bad_request(format!("a share may name at most {MAX_INDICES} indices"));
+ }
+ // An alias is resolved NOW, to the indices it points at as the owner runs
+ // the command, and the share records those. Two reasons. Authorization
+ // resolves an alias to its backing indices and checks each of *those*
+ // against the key's grants (`authz::authorize_expression`), so a grant on
+ // the alias name alone mints a key that can read nothing — the first cut
+ // accepted an alias here and produced exactly that. And a frozen list means
+ // re-pointing the alias later cannot move, or widen, what a guest already
+ // holds: the owner shared these indices, not whatever the name means next
+ // week. The backing names go through the same validation, so an alias is
+ // not a way to share a system index.
+ let mut concrete: Vec<String> = Vec::with_capacity(indices.len());
+ for name in &indices {
+ if let Err(why) = validate_share_index(name) {
+ return bad_request(why);
+ }
+ let backing = state
+ .engine
+ .aliases
+ .get(name)
+ .map(|e| e.value().clone())
+ .filter(|b| !b.is_empty());
+ let resolved = backing.unwrap_or_else(|| vec![name.clone()]);
+ for index in resolved {
+ if let Err(why) = validate_share_index(&index) {
+ return bad_request(if index == *name {
+ why
+ } else {
+ format!("alias `{name}` resolves to `{index}`: {why}")
+ });
+ }
+ if state.engine.get_index(&index).is_err() {
+ return es_error(
+ StatusCode::NOT_FOUND,
+ "index_not_found_exception",
+ format!("no such index [{index}]"),
+ );
+ }
+ concrete.push(index);
+ }
+ }
+ let mut seen = HashSet::new();
+ concrete.retain(|i| seen.insert(i.clone()));
+ if concrete.len() > MAX_INDICES {
+ return bad_request(format!("a share may name at most {MAX_INDICES} indices"));
+ }
+ let indices = concrete;
+ if let Some(b) = &brain {
+ let edges = crate::authz::brain_edges_index(b);
+ if state.engine.get_index(&edges).is_err() {
+ return es_error(
+ StatusCode::NOT_FOUND,
+ "resource_not_found_exception",
+ format!(
+ "no brain named [{b}] on this node (its edges index [{edges}] does not exist)"
+ ),
+ );
+ }
+ }
+
+ let expires_spec = match body.get("expires_in") {
+ None | Some(Value::Null) => DEFAULT_EXPIRES_IN.to_string(),
+ Some(Value::String(s)) => s.clone(),
+ Some(_) => {
+ return bad_request("`expires_in` must be a duration string like \"24h\"".into())
+ }
+ };
+ let Some(expires_in_ms) = parse_expires_in(&expires_spec) else {
+ return bad_request(format!(
+ "`expires_in`: cannot parse {expires_spec:?} — use e.g. \"30m\", \"24h\", \"7d\""
+ ));
+ };
+ if !(MIN_EXPIRES_MS..=MAX_EXPIRES_MS).contains(&expires_in_ms) {
+ return bad_request(format!(
+ "`expires_in` must be between 1s and 30d (got {expires_spec})"
+ ));
+ }
+ let max_claims = match body.get("max_claims") {
+ None | Some(Value::Null) => DEFAULT_MAX_CLAIMS,
+ Some(v) => match v.as_u64() {
+ Some(n) if (1..=MAX_MAX_CLAIMS as u64).contains(&n) => n as u32,
+ _ => {
+ return bad_request(format!(
+ "`max_claims` must be an integer from 1 to {MAX_MAX_CLAIMS}"
+ ))
+ }
+ },
+ };
+ let (passcode, passcode_supplied) = match body.get("passcode") {
+ None | Some(Value::Null) => (generate_passcode(), false),
+ Some(Value::String(p)) => {
+ let p = p.trim().to_string();
+ let n = p.chars().count();
+ if !(MIN_PASSCODE_CHARS..=MAX_PASSCODE_CHARS).contains(&n) {
+ return bad_request(format!(
+ "`passcode` must be {MIN_PASSCODE_CHARS}–{MAX_PASSCODE_CHARS} characters"
+ ));
+ }
+ (p, true)
+ }
+ Some(_) => return bad_request("`passcode` must be a string".into()),
+ };
+ let label = match body.get("label") {
+ None | Some(Value::Null) => None,
+ Some(Value::String(l)) => {
+ let l = l.trim().to_string();
+ if l.chars().count() > MAX_LABEL_CHARS {
+ return bad_request(format!(
+ "`label` must be at most {MAX_LABEL_CHARS} characters"
+ ));
+ }
+ if l.is_empty() {
+ None
+ } else {
+ Some(l)
+ }
+ }
+ Some(_) => return bad_request("`label` must be a string".into()),
+ };
+
+ // Argon2 is deliberately slow; keep it off the async worker.
+ let pc = passcode.clone();
+ let passcode_hash = match tokio::task::spawn_blocking(move || hash_passcode(&pc)).await {
+ Ok(Ok(h)) => h,
+ Ok(Err(e)) => {
+ tracing::error!(error = %e, "argon2 could not hash the share passcode");
+ return es_error(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "share_exception",
+ "could not hash the passcode".into(),
+ );
+ }
+ Err(e) => {
+ tracing::error!(error = %e, "passcode hashing task panicked");
+ return es_error(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "share_exception",
+ "could not hash the passcode".into(),
+ );
+ }
+ };
+
+ let share_id = mint_share_id();
+ let (id_hash, handle) = hash_share_id(&share_id);
+ let now = now_ms();
+ let record = ShareRecord {
+ handle: handle.clone(),
+ id_hash,
+ passcode_hash,
+ label: label.clone(),
+ indices: indices.clone(),
+ brain: brain.clone(),
+ created_ms: now,
+ expires_ms: now + expires_in_ms,
+ max_claims,
+ claims: 0,
+ revoked: false,
+ revoked_ms: None,
+ key_ids: Vec::new(),
+ };
+ state.shares.records.insert(handle.clone(), record.clone());
+ if let Err(e) = state.shares.persist() {
+ state.shares.records.remove(&handle);
+ tracing::error!(error = %e, "could not persist shares.json");
+ return es_error(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "share_exception",
+ format!("could not persist the share: {e}"),
+ );
+ }
+ state.engine.audit.append(
+ "share.create",
+ principal.label(),
+ &handle,
+ "ok",
+ &format!(
+ "indices={} brain={} max_claims={max_claims} expires_at={} passcode={}",
+ indices.join(","),
+ brain.as_deref().unwrap_or("-"),
+ rfc3339(record.expires_ms),
+ if passcode_supplied {
+ "supplied"
+ } else {
+ "generated"
+ }
+ ),
+ );
+ state.engine.audit.sync_to_disk();
+
+ let mut out = record.public_json(now);
+ out["share_id"] = json!(share_id);
+ out["url_path"] = json!(format!("/_xerj-console/share#{share_id}"));
+ out["passcode"] = json!(passcode);
+ out["claim_limiter"] = json!({
+ "per_share_per_minute": SHARE_PER_MINUTE,
+ "per_share_per_hour": SHARE_PER_HOUR,
+ // Whose address a claim is attributed to: the TCP peer, or — when
+ // loopback is a declared trusted proxy — the address a local reverse
+ // proxy or tunnel forwarded.
+ "source_address": if loopback_is_trusted_proxy(&state) { "forwarded" } else { "peer" },
+ });
+ Json(out).into_response()
+}
+
+/// `GET /_share` — list every share. Superuser only. No hashes, no ids.
+pub async fn list_shares(State(state): State<AppState>, principal: Principal) -> Response {
+ no_store(list_shares_inner(state, principal).await)
+}
+
+async fn list_shares_inner(state: AppState, principal: Principal) -> Response {
+ if let Err(resp) = require_superuser(&principal) {
+ state
+ .engine
+ .audit
+ .append("share.list", principal.label(), "_share", "denied", "");
+ return resp;
+ }
+ let now = now_ms();
+ let shares: Vec<Value> = state
+ .shares
+ .list()
+ .iter()
+ .map(|r| r.public_json(now))
+ .collect();
+ state.engine.audit.append(
+ "share.list",
+ principal.label(),
+ "_share",
+ "ok",
+ &format!("count={}", shares.len()),
+ );
+ Json(json!({ "shares": shares })).into_response()
+}
+
+/// `DELETE /_share/{id}` — revoke. Accepts the share id or its handle.
+/// Invalidates every key a claim of this share minted, so a guest who has
+/// already claimed loses access on their next request.
+pub async fn revoke_share(
+ State(state): State<AppState>,
+ principal: Principal,
+ AxumPath(id): AxumPath<String>,
+) -> Response {
+ no_store(revoke_share_inner(state, principal, id).await)
+}
+
+async fn revoke_share_inner(state: AppState, principal: Principal, id: String) -> Response {
+ if let Err(resp) = require_superuser(&principal) {
+ state
+ .engine
+ .audit
+ .append("share.revoke", principal.label(), "_share", "denied", "");
+ return resp;
+ }
+ let Some(handle) = state.shares.find_for_revoke(id.trim()) else {
+ state.engine.audit.append(
+ "share.revoke",
+ principal.label(),
+ "_share",
+ "error",
+ "unknown share",
+ );
+ return es_error(
+ StatusCode::NOT_FOUND,
+ "resource_not_found_exception",
+ "unknown share".into(),
+ );
+ };
+ let now = now_ms();
+ let key_ids = {
+ let Some(mut rec) = state.shares.records.get_mut(&handle) else {
+ return es_error(
+ StatusCode::NOT_FOUND,
+ "resource_not_found_exception",
+ "unknown share".into(),
+ );
+ };
+ let already = rec.revoked;
+ rec.revoked = true;
+ if !already {
+ rec.revoked_ms = Some(now);
+ }
+ rec.key_ids.clone()
+ };
+ let invalidated = match state.engine.invalidate_api_keys(&key_ids, now) {
+ Ok((fresh, _previously)) => fresh.len(),
+ Err(e) => {
+ return crate::error::ApiError::new(xerj_common::XerjError::from(e)).into_response();
+ }
+ };
+ if let Err(e) = state.shares.persist() {
+ tracing::error!(error = %e, "could not persist shares.json after revoke");
+ }
+ state.engine.audit.append(
+ "share.revoke",
+ principal.label(),
+ &handle,
+ "ok",
+ &format!("keys_invalidated={invalidated}"),
+ );
+ state.engine.audit.sync_to_disk();
+ Json(json!({
+ "handle": handle,
+ "revoked": true,
+ "keys_invalidated": invalidated,
+ }))
+ .into_response()
+}
+
+/// `POST /_share/claim` — the guest's one call. **Unauthenticated** (see the
+/// module docs for why that is safe), rate-limited, audited.
+///
+/// Body: `{id, passcode}` — the share id travels in the body, never in the
+/// path (module docs, "The share id is never part of a request path"). On
+/// success: `{api_key, index, indices, brain, expires_at, label, claims_left}`
+/// — `api_key` is ready for `Authorization: ApiKey <api_key>`. `index` is the
+/// comma-joined list, which is a valid ES multi-index expression for
+/// `/{index}/_search`.
+pub async fn claim_share(
+ State(state): State<AppState>,
+ ClaimSource(source): ClaimSource,
+ body: Option<Json<Value>>,
+) -> Response {
+ no_store(claim_share_inner(state, source, body).await)
+}
+
+/// The share id a claim body names. Anything that is not a string is the
+/// empty id, which no share has: a body without one is answered like any other
+/// unknown link — charged to the source window, audited, `404`.
+fn claim_id(body: Option<&Value>) -> String {
+ body.and_then(|b| b.get("id"))
+ .and_then(Value::as_str)
+ .map(|s| s.trim().to_string())
+ .unwrap_or_default()
+}
+
+async fn claim_share_inner(state: AppState, source: String, body: Option<Json<Value>>) -> Response {
+ let subject = format!("guest@{source}");
+ let now = now_ms();
+ let id = claim_id(body.as_ref().map(|Json(b)| b));
+ if !auth_is_enforced(&state) {
+ return open_node_refusal();
+ }
+ // The lookup comes FIRST, and which window is charged depends on its
+ // answer — see "The two throttles" in the module docs. It is a SHA-256 and
+ // a map probe, so an unauthenticated caller buys nothing by forcing it.
+ let Some(record) = state.shares.find_by_id(&id) else {
+ // Junk: the source window is the only throttle there is. Behind a
+ // tunnel every client shares the loopback bucket, which makes this
+ // bound tighter, never looser — and it cannot lock a real guest out,
+ // because a real share id never reaches this branch.
+ let bucket = format!("ip:{}", source_bucket(&source));
+ if let Err(t) = state
+ .shares
+ .charge(&bucket, IP_PER_MINUTE, IP_PER_HOUR, now)
+ {
+ if t.first_in_window {
+ state.engine.audit.append(
+ "share.claim",
+ &subject,
+ "_share",
+ "denied",
+ "rate-limited (source); further refusals in this window are not logged",
+ );
+ }
+ return too_many(t.retry_after_secs);
+ }
+ state
+ .engine
+ .audit
+ .append("share.claim", &subject, "_share", "error", "unknown share");
+ return es_error(
+ StatusCode::NOT_FOUND,
+ "resource_not_found_exception",
+ "unknown share link".into(),
+ );
+ };
+ let handle = record.handle.clone();
+ // A real share: its own window, from anywhere. This is the passcode
+ // lockout and it holds whoever is asking and however they got here.
+ if let Err(t) = state.shares.charge(
+ &format!("share:{handle}"),
+ SHARE_PER_MINUTE,
+ SHARE_PER_HOUR,
+ now,
+ ) {
+ if t.first_in_window {
+ state.engine.audit.append(
+ "share.claim",
+ &subject,
+ &handle,
+ "denied",
+ "rate-limited (share); further refusals in this window are not logged",
+ );
+ }
+ return too_many(t.retry_after_secs);
+ }
+ if let Some(why) = record.unavailable(now) {
+ state
+ .engine
+ .audit
+ .append("share.claim", &subject, &handle, "denied", why);
+ return es_error(StatusCode::GONE, "share_unavailable", why.into());
+ }
+ let presented = body
+ .as_ref()
+ .and_then(|Json(b)| b.get("passcode"))
+ .and_then(Value::as_str)
+ .map(|s| s.trim().to_string())
+ .unwrap_or_default();
+ let stored = record.passcode_hash.clone();
+ let ok = if presented.is_empty() {
+ false
+ } else {
+ tokio::task::spawn_blocking(move || verify_passcode(&presented, &stored))
+ .await
+ .unwrap_or(false)
+ };
+ if !ok {
+ state
+ .engine
+ .audit
+ .append("share.claim", &subject, &handle, "denied", "wrong passcode");
+ state.engine.audit.sync_to_disk();
+ return es_error(
+ StatusCode::UNAUTHORIZED,
+ "security_exception",
+ "wrong passcode".into(),
+ );
+ }
+
+ // Mint the guest's key: read-only over exactly the granted indices,
+ // expiring with the share. Same key material shape as
+ // `POST /_security/api_key` so the same auth path re-authenticates it.
+ let granted = record.granted_indices();
+ let roles = vec![Role::new(
+ format!("{GUEST_ROLE_PREFIX}{handle}"),
+ HashSet::from([Privilege::ReadIndex]),
+ granted,
+ )];
+ let key_id = uuid::Uuid::new_v4().to_string();
+ let raw_secret = format!(
+ "{}{}",
+ uuid::Uuid::new_v4().simple(),
+ uuid::Uuid::new_v4().simple()
+ );
+ let api_key = crate::es_compat::base64_encode(&raw_secret);
+ let encoded = crate::es_compat::base64_encode(&format!("{key_id}:{api_key}"));
+ let key_record = xerj_engine::engine::ApiKeyRecord::new(
+ format!("share:{handle}"),
+ &api_key,
+ now,
+ Some(record.expires_ms),
+ roles,
+ );
+
+ // Consume the claim first, under the record lock, so two racing claims of
+ // a one-claim share cannot both succeed.
+ let claims_left = {
+ let Some(mut rec) = state.shares.records.get_mut(&handle) else {
+ return es_error(
+ StatusCode::NOT_FOUND,
+ "resource_not_found_exception",
+ "unknown share link".into(),
+ );
+ };
+ if let Some(why) = rec.unavailable(now) {
+ state
+ .engine
+ .audit
+ .append("share.claim", &subject, &handle, "denied", why);
+ return es_error(StatusCode::GONE, "share_unavailable", why.into());
+ }
+ rec.claims += 1;
+ rec.key_ids.push(key_id.clone());
+ rec.max_claims.saturating_sub(rec.claims)
+ };
+ if let Err(e) = state.engine.persist_api_key(key_id.clone(), key_record) {
+ if let Some(mut rec) = state.shares.records.get_mut(&handle) {
+ rec.claims = rec.claims.saturating_sub(1);
+ rec.key_ids.retain(|k| k != &key_id);
+ }
+ return crate::error::ApiError::new(xerj_common::XerjError::from(e)).into_response();
+ }
+ if let Err(e) = state.shares.persist() {
+ tracing::error!(error = %e, "could not persist shares.json after claim");
+ }
+ state.engine.audit.append(
+ "share.claim",
+ &subject,
+ &handle,
+ "ok",
+ &format!("key_id={key_id} claims_left={claims_left}"),
+ );
+ state.engine.audit.sync_to_disk();
+
+ Json(json!({
+ "api_key": encoded,
+ "index": record.indices.join(","),
+ "indices": record.indices,
+ "brain": record.brain,
+ "expires_at": rfc3339(record.expires_ms),
+ "label": record.label,
+ "claims_left": claims_left,
+ }))
+ .into_response()
+}
+
+fn too_many(retry_after_secs: u64) -> Response {
+ let mut resp = es_error(
+ StatusCode::TOO_MANY_REQUESTS,
+ "too_many_requests",
+ format!("too many claim attempts; retry in {retry_after_secs}s"),
+ );
+ if let Ok(v) = header::HeaderValue::from_str(&retry_after_secs.to_string()) {
+ resp.headers_mut().insert(header::RETRY_AFTER, v);
+ }
+ resp
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn expires_in_parses_units_and_rejects_bare_numbers() {
+ assert_eq!(parse_expires_in("24h"), Some(24 * 3_600_000));
+ assert_eq!(parse_expires_in("30m"), Some(30 * 60_000));
+ assert_eq!(parse_expires_in("7d"), Some(7 * 86_400_000));
+ assert_eq!(parse_expires_in("90s"), Some(90_000));
+ assert_eq!(parse_expires_in(" 2 d "), Some(2 * 86_400_000));
+ assert_eq!(parse_expires_in("24"), None);
+ assert_eq!(parse_expires_in("h"), None);
+ assert_eq!(parse_expires_in("1w"), None);
+ assert_eq!(parse_expires_in(""), None);
+ }
+
+ #[test]
+ fn generated_passcodes_are_typeable_and_distinct() {
+ let a = generate_passcode();
+ let b = generate_passcode();
+ assert_eq!(a.len(), 9);
+ assert_eq!(&a[4..5], "-");
+ for c in a.chars().filter(|c| *c != '-') {
+ assert!(PASSCODE_ALPHABET.contains(&(c as u8)), "{a}");
+ }
+ assert_ne!(a, b);
+ }
+
+ #[test]
+ fn passcode_hash_verifies_only_the_right_code_and_never_stores_plaintext() {
+ let h = hash_passcode("k7mq-2xhd").unwrap();
+ assert!(h.starts_with("$argon2id$"), "{h}");
+ assert!(!h.contains("k7mq-2xhd"));
+ assert!(verify_passcode("k7mq-2xhd", &h));
+ assert!(!verify_passcode("k7mq-2xhe", &h));
+ assert!(!verify_passcode("", &h));
+ assert!(!verify_passcode("k7mq-2xhd", "not-a-phc-string"));
+ }
+
+ #[test]
+ fn share_id_hashes_to_a_handle_that_cannot_reopen_the_share() {
+ let id = mint_share_id();
+ assert_eq!(id.len(), 32);
+ let (full, handle) = hash_share_id(&id);
+ assert_eq!(full.len(), 64);
+ assert_eq!(handle.len(), 12);
+ assert!(full.starts_with(&handle));
+ assert!(!full.contains(&id));
+ }
+
+ #[test]
+ fn index_validation_refuses_patterns_lists_and_the_reserved_namespace() {
+ assert!(validate_share_index("ax-notes").is_ok());
+ assert!(validate_share_index("logs-*").is_err());
+ assert!(validate_share_index("a,b").is_err());
+ assert!(validate_share_index(".xerj-memory-kb-edges").is_err());
+ // The node's own indices, credential stores first. Each of these was
+ // shareable before the dot-prefix rule.
+ for system in [
+ ".xerj_sessions",
+ ".xerj_api_tokens",
+ ".xerj_passkeys",
+ ".xerj_magic_links",
+ ".xerj_users",
+ ".xerj_audit",
+ ".anything-else",
+ ] {
+ assert!(
+ validate_share_index(system).is_err(),
+ "{system} must not be shareable"
+ );
+ }
+ assert!(validate_share_index("_all").is_err());
+ assert!(validate_share_index("Upper").is_err());
+ assert!(validate_share_index("").is_err());
+ }
+
+ /// Review of PR #947: three public docs said the catalog is "never
+ /// granted" while `validate_share_index` accepted it and a guest read
+ /// every corpus's row.
+ #[test]
+ fn the_autoindex_catalog_cannot_be_shared() {
+ let why = validate_share_index(CATALOG_INDEX).unwrap_err();
+ assert!(why.contains("every corpus"), "{why}");
+ assert!(why.contains("autoindex map"), "{why}");
+ // A user's own index that merely resembles it is theirs to share.
+ assert!(validate_share_index("autoindex-catalog-2").is_ok());
+ assert!(validate_share_index("my-autoindex-catalog").is_ok());
+ }
+
+ /// The id comes out of the claim BODY. A body without a usable one is the
+ /// empty id — never a panic, and never a record.
+ #[test]
+ fn the_claim_id_is_read_from_the_body() {
+ let id = "0123456789abcdef0123456789abcdef";
+ assert_eq!(claim_id(Some(&json!({"id": id, "passcode": "x"}))), id);
+ assert_eq!(claim_id(Some(&json!({"id": format!(" {id}\n")}))), id);
+ for junk in [
+ json!({}),
+ json!({"passcode": "x"}),
+ json!({"id": 7}),
+ json!({"id": [id]}),
+ json!({"id": {"$ne": ""}}),
+ json!([id]),
+ json!(id),
+ ] {
+ assert_eq!(claim_id(Some(&junk)), "", "{junk}");
+ }
+ assert_eq!(claim_id(None), "");
+ // And the empty id is nobody's share.
+ let dir = tempfile::tempdir().unwrap();
+ let store = ShareStore::open(dir.path().to_str().unwrap());
+ assert!(store.find_by_id("").is_none());
+ const { assert!((MAX_PASSCODE_CHARS * 4 + 32 + 64) < MAX_CLAIM_BODY_BYTES) };
+ }
+
+ #[test]
+ fn rate_windows_lock_out_after_the_limit() {
+ let dir = tempfile::tempdir().unwrap();
+ let store = ShareStore::open(dir.path().to_str().unwrap());
+ let now = 1_000_000;
+ for _ in 0..SHARE_PER_MINUTE {
+ store
+ .charge("share:x", SHARE_PER_MINUTE, SHARE_PER_HOUR, now)
+ .unwrap();
+ }
+ let refused = store
+ .charge("share:x", SHARE_PER_MINUTE, SHARE_PER_HOUR, now)
+ .unwrap_err();
+ let retry = refused.retry_after_secs;
+ assert!((1..=61).contains(&retry), "{retry}");
+ // The first refusal in a window is the one that gets audited; the
+ // flood behind it is not, or the audit log becomes the attack.
+ assert!(refused.first_in_window);
+ let again = store
+ .charge("share:x", SHARE_PER_MINUTE, SHARE_PER_HOUR, now)
+ .unwrap_err();
+ assert!(!again.first_in_window);
+ // A different share is untouched.
+ store
+ .charge("share:y", SHARE_PER_MINUTE, SHARE_PER_HOUR, now)
+ .unwrap();
+ // The minute window rolls over; the hour window still counts.
+ //
+ // A minute-throttled attempt returns before the hour window is
+ // charged — it never reaches passcode verification, so it is not a
+ // guess and does not spend the hourly guess budget. Filling the hour
+ // therefore takes *accepted* charges, spread over fresh minute windows.
+ let mut t = now;
+ let mut accepted = SHARE_PER_MINUTE;
+ while accepted < SHARE_PER_HOUR {
+ t += WINDOW_MIN_MS + 1;
+ for _ in 0..SHARE_PER_MINUTE {
+ if accepted == SHARE_PER_HOUR {
+ break;
+ }
+ store
+ .charge("share:x", SHARE_PER_MINUTE, SHARE_PER_HOUR, t)
+ .unwrap();
+ accepted += 1;
+ }
+ }
+ // The hourly budget is spent. A brand-new minute window does not help.
+ t += WINDOW_MIN_MS + 1;
+ assert!(t - now < WINDOW_HOUR_MS, "still inside the same hour");
+ let retry = store
+ .charge("share:x", SHARE_PER_MINUTE, SHARE_PER_HOUR, t)
+ .unwrap_err()
+ .retry_after_secs;
+ assert!(
+ retry > 60,
+ "locked out by the hour window, not the minute one: {retry}s"
+ );
+ // And the throttled attempts above never counted as guesses.
+ assert_eq!(accepted, SHARE_PER_HOUR);
+ }
+
+ #[test]
+ fn ipv6_sources_are_bucketed_by_their_64() {
+ // One host, two addresses out of the /64 it was delegated: one bucket.
+ assert_eq!(
+ source_bucket("2001:db8:1:2:aaaa:bbbb:cccc:dddd"),
+ source_bucket("2001:db8:1:2::1")
+ );
+ assert_eq!(source_bucket("2001:db8:1:2::1"), "2001:db8:1:2::/64");
+ // A different /64 is a different bucket.
+ assert_ne!(
+ source_bucket("2001:db8:1:3::1"),
+ source_bucket("2001:db8:1:2::1")
+ );
+ // IPv4 and the no-transport bucket are left alone.
+ assert_eq!(source_bucket("203.0.113.9"), "203.0.113.9");
+ assert_eq!(source_bucket("unknown"), "unknown");
+ }
+
+ #[test]
+ fn junk_traffic_cannot_spend_a_real_shares_budget() {
+ // The tunnel case: every client arrives as 127.0.0.1. Exhaust that
+ // source bucket the way a flood of made-up ids would…
+ let dir = tempfile::tempdir().unwrap();
+ let store = ShareStore::open(dir.path().to_str().unwrap());
+ let now = 5_000_000;
+ let junk = format!("ip:{}", source_bucket("127.0.0.1"));
+ for _ in 0..IP_PER_MINUTE {
+ store
+ .charge(&junk, IP_PER_MINUTE, IP_PER_HOUR, now)
+ .unwrap();
+ }
+ assert!(store
+ .charge(&junk, IP_PER_MINUTE, IP_PER_HOUR, now)
+ .is_err());
+ // …and a real share's window is untouched: `claim_share` charges a
+ // known id to `share:<handle>` only, never to the source bucket.
+ for _ in 0..SHARE_PER_MINUTE {
+ store
+ .charge("share:abc123", SHARE_PER_MINUTE, SHARE_PER_HOUR, now)
+ .unwrap();
+ }
+ }
+
+ #[test]
+ fn the_window_table_is_bounded_and_overflow_throttles_rather_than_exempts() {
+ let dir = tempfile::tempdir().unwrap();
+ let store = ShareStore::open(dir.path().to_str().unwrap());
+ let now = 9_000_000;
+ for i in 0..MAX_WINDOWS {
+ store.windows.insert(
+ format!("ip:filler-{i}:m"),
+ RateWindow {
+ count: 1,
+ start_ms: now,
+ },
+ );
+ }
+ // New sources now share one bucket: ten of them, from ten "addresses",
+ // and the eleventh is refused.
+ for i in 0..IP_PER_MINUTE {
+ store
+ .charge(&format!("ip:new-{i}"), IP_PER_MINUTE, IP_PER_HOUR, now)
+ .unwrap();
+ }
+ assert!(store
+ .charge("ip:new-last", IP_PER_MINUTE, IP_PER_HOUR, now)
+ .is_err());
+ assert!(!store.windows.contains_key("ip:new-0:m"));
+ // A share's own window is never collapsed into the overflow bucket.
+ store
+ .charge("share:real", SHARE_PER_MINUTE, SHARE_PER_HOUR, now)
+ .unwrap();
+ assert!(store.windows.contains_key("share:real:m"));
+ }
+
+ #[test]
+ fn nothing_under_share_is_cacheable() {
+ let resp = no_store(Json(json!({"api_key": "x"})).into_response());
+ assert_eq!(
+ resp.headers().get(header::CACHE_CONTROL).unwrap(),
+ "no-store, max-age=0"
+ );
+ assert_eq!(resp.headers().get(header::PRAGMA).unwrap(), "no-cache");
+ // Errors too: a cached 404/410 says whether a share exists.
+ let resp = no_store(too_many(5));
+ assert_eq!(
+ resp.headers().get(header::CACHE_CONTROL).unwrap(),
+ "no-store, max-age=0"
+ );
+ assert_eq!(resp.headers().get(header::RETRY_AFTER).unwrap(), "5");
+ }
+
+ #[test]
+ fn store_round_trips_through_disk_without_plaintext() {
+ let dir = tempfile::tempdir().unwrap();
+ let data_dir = dir.path().to_str().unwrap();
+ let store = ShareStore::open(data_dir);
+ let share_id = mint_share_id();
+ let (id_hash, handle) = hash_share_id(&share_id);
+ store.records.insert(
+ handle.clone(),
+ ShareRecord {
+ handle: handle.clone(),
+ id_hash,
+ passcode_hash: hash_passcode("secret-code").unwrap(),
+ label: Some("friend".into()),
+ indices: vec!["ax-notes".into()],
+ brain: Some("notes".into()),
+ created_ms: 1,
+ expires_ms: 2,
+ max_claims: 1,
+ claims: 0,
+ revoked: false,
+ revoked_ms: None,
+ key_ids: vec![],
+ },
+ );
+ store.persist().unwrap();
+ let raw = std::fs::read_to_string(dir.path().join(SHARES_FILE)).unwrap();
+ assert!(!raw.contains(&share_id), "share id must not be on disk");
+ assert!(!raw.contains("secret-code"), "passcode must not be on disk");
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mode = std::fs::metadata(dir.path().join(SHARES_FILE))
+ .unwrap()
+ .permissions()
+ .mode()
+ & 0o777;
+ assert_eq!(mode, 0o600);
+ }
+ let reloaded = ShareStore::open(data_dir);
+ let rec = reloaded
+ .find_by_id(&share_id)
+ .expect("id resolves after reload");
+ assert_eq!(rec.handle, handle);
+ assert_eq!(
+ rec.granted_indices(),
+ vec![
+ "ax-notes".to_string(),
+ ".xerj-memory-notes-edges".to_string()
+ ]
+ );
+ assert!(reloaded.find_by_id("0000").is_none());
+ // The handle alone resolves for revoke, but never as a claim id.
+ assert_eq!(
+ reloaded.find_for_revoke(&handle).as_deref(),
+ Some(handle.as_str())
+ );
+ assert!(reloaded.find_by_id(&handle).is_none());
+ }
+}
diff --git a/engine/crates/xerj-api/src/state.rs b/engine/crates/xerj-api/src/state.rs
index 174b89215..2473ce0f4 100644
--- a/engine/crates/xerj-api/src/state.rs
+++ b/engine/crates/xerj-api/src/state.rs
@@ -533,6 +533,9 @@ pub struct AppState {
/// Live background scoring tasks, keyed by datafeed id. Aborted on `_stop`
/// (and replaced on a re-`_start`). In-memory only.
pub ml_datafeed_tasks: Arc<DashMap<String, tokio::task::JoinHandle<()>>>,
+ /// Share links (`/_share`): records loaded from `<data_dir>/shares.json`
+ /// plus the claim rate limiter. See `crate::share`.
+ pub shares: Arc<crate::share::ShareStore>,
/// Resolved rerank-provider settings (key, endpoint, kill switch, shared
/// HTTP client) — the injection seam for [`crate::rerank_stage`].
///
@@ -573,6 +576,7 @@ impl AppState {
} else {
(Arc::new(DashMap::new()), Arc::new(DashMap::new()))
};
+ let shares = crate::share::ShareStore::open(&config.server.data_dir);
let rerank = Arc::new(xerj_rerank::ProviderSettings::from_config_and_env(
config.rerank.enabled,
&config.rerank.api_key,
@@ -590,6 +594,7 @@ impl AppState {
ml_datafeeds,
ml_results: Arc::new(DashMap::new()),
ml_datafeed_tasks: Arc::new(DashMap::new()),
+ shares,
}
}
diff --git a/engine/crates/xerj-api/tests/live/share_security_live.py b/engine/crates/xerj-api/tests/live/share_security_live.py
new file mode 100644
index 000000000..c9fbe2dc7
--- /dev/null
+++ b/engine/crates/xerj-api/tests/live/share_security_live.py
@@ -0,0 +1,593 @@
+#!/usr/bin/env python3
+"""Live security check of share links, against a real node with auth ON.
+
+ XERJ_URL=http://127.0.0.1:9510 XERJ_DATA_DIR=/path/to/data \
+ python3 share_security_live.py
+
+The node must be a THROWAWAY: this test creates indices, aliases and a brain,
+and burns the claim rate-limit windows. Never point it at a node you use.
+`run_share_live.sh` beside this file boots one and runs this against it.
+
+What it proves, in order:
+ 1. management is superuser-only; secrets are shown once and never stored;
+ 2. a guest key reads the shared index — and nothing else on the node, by any
+ route: cluster surface, other indices, aliases, body-named indices,
+ cross-index lookups inside a query, server-side contexts, the console
+ API, the native router, another brain, writes of any kind;
+ 3. an alias is resolved when the share is made, not when it is used;
+ 4. nothing under /_share — and nothing a guest reads — is cacheable; the
+ guest page ships a strict CSP;
+ 5. the claim limiter: per-share lockout, junk traffic cannot lock a real
+ guest out (the tunnel case), and a spoofed X-Forwarded-For buys nothing;
+ 6. the share id is never part of a request path: a claim is
+ `POST /_share/claim` with `{id, passcode}`, and with XERJ_SERVER_LOG set
+ (a node started with `logging.access_log = true`) no share id this test
+ created is anywhere in the node's log;
+ 7. a guest's refused attempts to list, create or revoke a share, or to mint
+ a key, are in the audit log.
+
+Exit status is the number of failed checks (0 = all passed).
+"""
+import json
+import os
+import sys
+import urllib.error
+import urllib.request
+
+URL = os.environ.get("XERJ_URL", "http://127.0.0.1:9510").rstrip("/")
+DATA = os.environ.get("XERJ_DATA_DIR") or os.path.join(
+ os.environ.get("XERJ_DATA_PARENT", os.path.dirname(os.path.abspath(__file__))), "data"
+)
+ADMIN = open(os.path.join(DATA, "admin.key")).read().strip()
+# The node's native REST listener (`server.rest_port`), when the caller knows it.
+NATIVE = os.environ.get("XERJ_NATIVE_URL", "").rstrip("/")
+# Set when the node was started with server.trusted_proxies = ["127.0.0.1"].
+TRUSTS_LOOPBACK = os.environ.get("XERJ_TRUSTS_LOOPBACK", "") == "1"
+# The node's own log, when the caller started it with logging.access_log = true.
+SERVER_LOG = os.environ.get("XERJ_SERVER_LOG", "")
+
+PASSED = FAILED = 0
+
+
+def call(method, path, body=None, key=None, headers=None, base=None):
+ """-> (status, parsed-json-or-{'raw':…}, response headers)"""
+ h = {"content-type": "application/json"}
+ if key:
+ h["authorization"] = "ApiKey " + key
+ data = None
+ if isinstance(body, bytes):
+ data, h["content-type"] = body, "application/x-ndjson"
+ elif body is not None:
+ data = json.dumps(body).encode()
+ h.update(headers or {})
+ req = urllib.request.Request((base or URL) + path, data=data, method=method, headers=h)
+ try:
+ resp = urllib.request.urlopen(req, timeout=30)
+ status, raw, rh = resp.status, resp.read(), resp.headers
+ except urllib.error.HTTPError as e:
+ status, raw, rh = e.code, e.read(), e.headers
+ try:
+ parsed = json.loads(raw or b"{}")
+ except Exception:
+ parsed = {"raw": raw[:300].decode(errors="replace")}
+ return status, parsed, rh
+
+
+def ok(name, cond, detail=""):
+ global PASSED, FAILED
+ if cond:
+ PASSED += 1
+ print(" ok ", name)
+ else:
+ FAILED += 1
+ print(" FAIL", name, "->", str(detail)[:400])
+
+
+def section(title):
+ print(f"\n── {title}")
+
+
+def claim(share_id, passcode, **kw):
+ """The guest's one call. The id is in the BODY — never in the path."""
+ return call("POST", "/_share/claim", {"id": share_id, "passcode": passcode}, **kw)
+
+
+def audit_lines():
+ return [json.loads(l) for l in open(os.path.join(DATA, "audit.jsonl")) if l.strip()]
+
+
+def hits_outside(resp, allowed):
+ """Index names in a search response that are not in `allowed`."""
+ out = []
+ for h in (resp.get("hits") or {}).get("hits") or []:
+ if h.get("_index") not in allowed:
+ out.append(h.get("_index"))
+ return out
+
+
+SECRET = "nobody else should ever read this"
+
+
+def nd(*lines):
+ """NDJSON body."""
+ return ("\n".join(json.dumps(l) for l in lines) + "\n").encode()
+
+
+def leaks(resp):
+ """Does any part of a response carry the private document's text?"""
+ return SECRET in json.dumps(resp)
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+section("seed: one shared index, one private index, one brain, aliases")
+bulk = (
+ b'{"index":{"_index":"casefile","_id":"1"}}\n'
+ b'{"subject":"Lease dispute","body":"the landlord refused to return the deposit"}\n'
+ b'{"index":{"_index":"casefile","_id":"2"}}\n'
+ b'{"subject":"Inspection report","body":"mould in the bathroom, photographed in March"}\n'
+ b'{"index":{"_index":"private-diary","_id":"1"}}\n'
+ b'{"subject":"diary","body":"' + SECRET.encode() + b'","tag":"deposit"}\n'
+)
+s, r, _ = call("POST", "/_bulk", bulk, ADMIN)
+ok("seed documents indexed", s == 200 and not r.get("errors"), (s, r))
+call("POST", "/casefile,private-diary/_refresh", None, ADMIN)
+s, r, _ = call("PUT", "/casefile-pdfs/_doc/1?refresh=true", {"subject": "Scanned lease", "body": "twelve month tenancy"}, ADMIN)
+ok("second shared index seeded", s in (200, 201), (s, r))
+s, r, _ = call("POST", "/_graph/case/link", {"src": "casefile/1", "dst": "casefile-pdfs/1", "type": "mentions"}, ADMIN)
+ok("brain 'case' has an edge", s in (200, 201), (s, r))
+# What `xerj brain <folder>` records for a folder with more than one dataset:
+# every index it built, comma-joined, in the brain's meta document.
+s, r, _ = call("PUT", "/.xerj-memory-case-edges/_doc/__xerj-brain-meta?refresh=true",
+ {"meta_version": 1, "brain": "case", "nodes_index": "casefile,casefile-pdfs", "created_at": 1}, ADMIN)
+ok("brain 'case' spans two indices", s in (200, 201), (s, r))
+s, r, _ = call("POST", "/_graph/other/link", {"src": "private-diary/1", "dst": "x/9", "type": "mentions"}, ADMIN)
+ok("brain 'other' has an edge", s in (200, 201), (s, r))
+s, r, _ = call("POST", "/_aliases", {"actions": [
+ {"add": {"index": "private-diary", "alias": "looks-harmless"}},
+ {"add": {"index": "casefile", "alias": "both"}},
+ {"add": {"index": "private-diary", "alias": "both"}},
+ {"add": {"index": "casefile", "alias": "case-alias"}},
+]}, ADMIN)
+ok("aliases created", s == 200, (s, r))
+
+# ─────────────────────────────────────────────────────────────────────────────
+section("management is superuser-only")
+want = {"index": ["casefile", "casefile-pdfs"], "brain": "case", "expires_in": "1h", "max_claims": 1, "label": "my lawyer"}
+SHARED = {"casefile", "casefile-pdfs", ".xerj-memory-case-edges"} # everything the guest holds
+s, r, _ = call("POST", "/_share", want)
+ok("create without a key is refused", s in (401, 403), (s, r))
+s, r, h = call("POST", "/_share", want, ADMIN)
+ok("owner creates a share", s == 200 and r.get("share_id") and r.get("passcode"), (s, r))
+ok("create response is never cached", "no-store" in (h.get("cache-control") or ""), h.get("cache-control"))
+SID, PW, HANDLE = r.get("share_id"), r.get("passcode"), r.get("handle")
+ok("link carries the id in the URL fragment, which browsers never send",
+ r.get("url_path") == f"/_xerj-console/share#{SID}", r.get("url_path"))
+for bad, why in [("case*", "wildcard"), ("casefile,private-*", "pattern in a list"),
+ (".xerj_audit", "audit log"), (".xerj_sessions", "console sessions"),
+ (".xerj-memory-other-edges", "another brain's edges"), ("_all", "_all")]:
+ s, r, _ = call("POST", "/_share", {"index": bad}, ADMIN)
+ ok(f"cannot share {why} ({bad})", s == 400, (s, r))
+s, r, _ = call("POST", "/_share", {"index": "no-such-index"}, ADMIN)
+ok("cannot share an index that does not exist", s == 404, (s, r))
+# The catalog lists every corpus on the node. The docs say it is never granted;
+# it has to exist here for the refusal to be about WHAT it is.
+s, r, _ = call("PUT", "/autoindex-catalog/_doc/x?refresh=true", {"index_name": "private-diary", "file_count": 1}, ADMIN)
+ok("autoindex-catalog seeded", s in (200, 201), (s, r))
+call("POST", "/_aliases", {"actions": [{"add": {"index": "autoindex-catalog", "alias": "whats-here"}}]}, ADMIN)
+for bad, why in [("autoindex-catalog", "by name"), (["casefile", "autoindex-catalog"], "in a list"),
+ ("whats-here", "through an alias")]:
+ s, r, _ = call("POST", "/_share", {"index": bad}, ADMIN)
+ ok(f"cannot share the autoindex catalog {why}", s == 400 and "every corpus" in json.dumps(r), (s, r))
+
+# ─────────────────────────────────────────────────────────────────────────────
+section("claiming")
+s, r, h = claim(SID, "wrong-code")
+ok("wrong passcode refused", s == 401, (s, r))
+ok("a refusal is never cached either", "no-store" in (h.get("cache-control") or ""), h.get("cache-control"))
+s, r, _ = claim("0" * 32, PW)
+ok("unknown share id refused without detail", s == 404 and PW not in json.dumps(r), (s, r))
+s, r, _ = claim(HANDLE, PW)
+ok("the public handle is not a claim id", s == 404, (s, r))
+s, r, _ = call("POST", "/_share/claim", {"passcode": PW})
+ok("a claim that names no id is an unknown link", s == 404, (s, r))
+s, r, _ = call("GET", "/_share/claim")
+ok("claim is POST-only (GET is not the open door)", s in (401, 403, 405), (s, r))
+# The retired shape put the share id in the request path — and so in every
+# access log on the way. It must not be a second way in. (A made-up id: the
+# smoke script greps the node's log for real ones.)
+s, r, _ = call("POST", f"/_share/{'f' * 32}/claim", {"passcode": PW})
+# On the full server an unrouted path is a bare 404 from the router's fallback
+# (before authentication); the ES router on its own answers 401. Either way no
+# handler ran and no key was minted.
+ok("POST /_share/{id}/claim — the id-in-path shape — is not an open door", s in (401, 404) and "api_key" not in r, (s, r))
+s, r, _ = call("POST", "/_share/claim", {"id": SID, "passcode": PW, "pad": "x" * 16384})
+ok("a claim body past the route's few-KiB cap is not read", s != 200 and "api_key" not in r, (s, r))
+s, g, h = claim(SID, PW)
+ok("right passcode yields a key", s == 200 and g.get("api_key"), (s, g))
+ok("claim response is never cached",
+ "no-store" in (h.get("cache-control") or "") and (h.get("pragma") or "") == "no-cache",
+ dict(h))
+ok("claim response is the guest-page contract",
+ all(k in g for k in ("api_key", "index", "brain", "expires_at", "label"))
+ and g["index"] == "casefile,casefile-pdfs" and g["brain"] == "case" and g["label"] == "my lawyer", g)
+GK = g.get("api_key")
+s, r, _ = claim(SID, PW)
+ok("max_claims=1: second claim refused", s == 410, (s, r))
+
+# ─────────────────────────────────────────────────────────────────────────────
+section("what the guest CAN do")
+s, r, _ = call("POST", "/casefile/_search", {"query": {"match": {"body": "deposit"}}}, GK)
+ok("search the shared index", s == 200 and r["hits"]["total"]["value"] == 1, (s, r))
+s, r, _ = call("POST", "/casefile/_search",
+ {"query": {"multi_match": {"query": "deposit", "fields": ["subject^2", "body"]}},
+ "highlight": {"pre_tags": ["\uE000"], "post_tags": ["\uE001"], "fields": {"subject": {}, "body": {}}}}, GK)
+ok("highlighted snippets with the page's private-use delimiters",
+ s == 200 and "\uE000" in json.dumps(r, ensure_ascii=False), (s, r))
+s, r, h = call("GET", "/casefile/_doc/1", None, GK)
+ok("read one document", s == 200 and r.get("found"), (s, r))
+ok("…and what a guest reads is never cached", "no-store" in (h.get("cache-control") or ""), h.get("cache-control"))
+s, r, _ = call("HEAD", "/casefile/_doc/1", None, GK)
+ok("HEAD one document", s == 200, (s, r))
+s, r, _ = call("POST", "/casefile/_field_caps?fields=*", None, GK)
+ok("_field_caps on the shared index", s == 200, (s, r))
+# `GET _source/{id}` used to be in the docs' "a guest can" table. The node has
+# no such route — 404 for the owner — and a guest is not pre-approved for it.
+s, r, _ = call("GET", "/casefile/_source/1", None, ADMIN)
+ok("there is no /{index}/_source/{id} route (owner: 404)", s == 404, (s, r))
+s, r, _ = call("GET", "/casefile/_source/1", None, GK)
+# 404 from the full server's fallback, 403 where authz sees it first; the
+# allow-list itself is pinned by the authz unit tests (`GUEST_DOC_OPS`).
+ok("…and a guest gets nothing from it either", s in (403, 404) and not r.get("_source"), (s, r))
+# The last "a guest can" row: who-am-I, the banner, the probes. None names an index.
+for path in ("/", "/_security/_authenticate", "/health/ready", "/health/live"):
+ s, r, _ = call("GET", path, None, GK)
+ ok(f"GET {path} answers a guest", s == 200 and not leaks(r), (s, r))
+s, r, _ = call("GET", "/_security/_authenticate", None, GK)
+ok("…and who-am-I shows the guest role and nothing wider",
+ s == 200 and r.get("roles") == [f"share:{HANDLE}"], (s, r))
+s, r, _ = call("GET", "/casefile/_mapping", None, GK)
+ok("read the shared index's mapping", s == 200 and "casefile" in r, (s, r))
+s, r, _ = call("POST", "/casefile/_count", {"query": {"match_all": {}}}, GK)
+ok("count", s == 200 and r.get("count") == 2, (s, r))
+s, r, _ = call("POST", "/casefile/_mget", {"ids": ["1", "2"]}, GK)
+ok("_mget inside the shared index", s == 200 and len(r.get("docs", [])) == 2, (s, r))
+s, r, _ = call("GET", "/_graph/case/overview", None, GK)
+ok("walk the shared brain (overview)", s == 200, (s, r))
+ok("…and the overview counts notes across both shared indices", r.get("nodes", {}).get("total") == 3, r)
+s, r, _ = call("GET", "/_graph/case/ego?node=casefile/1", None, GK)
+ok("walk the shared brain (ego)", s == 200 and len(r.get("edges", [])) == 1, (s, r))
+s, r, _ = call("GET", "/_graph/case/ego?node=casefile/1&include_nodes=true", None, GK)
+ok("…with the linked notes hydrated from both shared indices", s == 200 and not leaks(r), (s, r))
+s, r, _ = call("GET", "/_graph/case/ego?node=casefile/1&include_nodes=true&nodes_index=private-diary", None, GK)
+ok("…but nodes_index cannot redirect hydration at a private index", s == 403 and not leaks(r), (s, r))
+s, r, _ = call("GET", "/_graph/case/ego?node=casefile/1&include_nodes=true&nodes_index=casefile,private-diary", None, GK)
+ok("…not even as one name in a list", s == 403 and not leaks(r), (s, r))
+
+# ─────────────────────────────────────────────────────────────────────────────
+section("what the guest CANNOT reach: the cluster surface")
+for method, path in [
+ ("GET", "/_cat/indices?format=json"), ("GET", "/_cat/aliases?format=json"),
+ ("GET", "/_cat/shards"), ("GET", "/_cat/count"), ("GET", "/_cat/nodes"),
+ ("GET", "/_cluster/health"), ("GET", "/_cluster/state"), ("GET", "/_cluster/stats"),
+ ("GET", "/_cluster/settings"), ("GET", "/_nodes"), ("GET", "/_nodes/stats"),
+ ("GET", "/_snapshot"), ("GET", "/_snapshot/_all"), ("GET", "/_tasks"),
+ ("GET", "/_stats"), ("GET", "/_mapping"), ("GET", "/_aliases"), ("GET", "/_alias"),
+ ("GET", "/_resolve/index/*"),
+ ("GET", "/_index_template"), ("GET", "/_ingest/pipeline"),
+ ("GET", "/_security/api_key"), ("GET", "/_audit/_search"), ("GET", "/_audit/_verify"),
+ ("GET", "/v1/metrics"), ("GET", "/v1/indices"), ("GET", "/v1/indices/casefile"),
+ ("GET", "/_xerj/wal_tap"),
+]:
+ s, r, _ = call(method, path, None, GK)
+ ok(f"{method} {path} → refused", s in (403, 404, 405) and "private-diary" not in json.dumps(r), (s, r))
+# A pattern is not refused: it is expanded over what the key HOLDS, so `_all`
+# means "all of yours". What matters is that it never means more than that.
+for path in ("/_all/_mapping", "/*/_mapping", "/case*,private*/_mapping"):
+ s, r, _ = call("GET", path, None, GK)
+ ok(f"GET {path} shows only what the guest holds", s == 200 and set(r) <= SHARED and "private-diary" not in r, (s, sorted(r)))
+s, r, _ = call("PUT", "/_snapshot/exfil", {"type": "fs", "settings": {"location": "/tmp/exfil"}}, GK)
+ok("cannot register a snapshot repository", s == 403, (s, r))
+s, r, _ = call("POST", "/_security/api_key", {"name": "upgrade-myself"}, GK)
+ok("cannot mint itself a wider key", s == 403 and "api_key" not in r, (s, r))
+
+section("what the guest CANNOT reach: share management")
+for method, path, body in [("GET", "/_share", None), ("POST", "/_share", {"index": "casefile"}),
+ ("DELETE", f"/_share/{HANDLE}", None)]:
+ s, r, _ = call(method, path, body, GK)
+ ok(f"{method} {path.split('/')[1]} → 403", s == 403, (s, r))
+
+section("what the guest CANNOT reach: other indices")
+for method, path, body in [
+ ("POST", "/private-diary/_search", {"query": {"match_all": {}}}),
+ ("GET", "/private-diary/_doc/1", None), ("GET", "/private-diary/_source/1", None),
+ ("POST", "/private-diary/_count", None), ("GET", "/private-diary/_mapping", None),
+ ("POST", "/private-diary/_field_caps?fields=*", None),
+ ("POST", "/casefile,private-diary/_search", {"query": {"match_all": {}}}),
+ ("POST", "/_search", {"query": {"match_all": {}}}),
+ ("POST", "/_all/_search", {"query": {"match_all": {}}}),
+ ("POST", "/*/_search", {"query": {"match_all": {}}}),
+ ("POST", "/private-*/_search", {"query": {"match_all": {}}}),
+ ("POST", "/.xerj-memory-other-edges/_search", {"query": {"match_all": {}}}),
+ ("POST", "/.xerj_audit/_search", {"query": {"match_all": {}}}),
+ ("POST", "/autoindex-catalog/_search", {"query": {"match_all": {}}}),
+]:
+ s, r, _ = call(method, path, body, GK)
+ ok(f"{method} {path} leaks nothing", not leaks(r) and not hits_outside(r, SHARED), (s, r))
+s, r, _ = call("POST", "/private-diary/_search", {"query": {"match_all": {}}}, GK)
+ok("a named private index is a plain 403", s == 403, (s, r))
+
+section("what the guest CANNOT reach: aliases pointing elsewhere")
+for alias in ("looks-harmless", "both"):
+ s, r, _ = call("POST", f"/{alias}/_search", {"query": {"match_all": {}}}, GK)
+ ok(f"alias `{alias}` (→ private-diary) is refused", s == 403 and not leaks(r), (s, r))
+ s, r, _ = call("GET", f"/{alias}/_doc/1", None, GK)
+ ok(f"alias `{alias}` cannot fetch a document", s in (403, 404) and not leaks(r), (s, r))
+s, r, _ = call("POST", "/case-alias/_search", {"query": {"match_all": {}}}, GK)
+ok("an alias onto the shared index itself still works", s == 200 and not hits_outside(r, SHARED), (s, r))
+s, r, _ = call("POST", "/_aliases", {"actions": [{"add": {"index": "private-diary", "alias": "casefile-2"}}]}, GK)
+ok("cannot create an alias", s == 403, (s, r))
+s, r, _ = call("PUT", "/private-diary/_alias/mine", None, GK)
+ok("cannot create an alias (index route)", s == 403, (s, r))
+
+section("what the guest CANNOT reach: indices named in a body")
+s, r, _ = call("POST", "/casefile/_msearch", nd({"index": "private-diary"}, {"query": {"match_all": {}}}), GK)
+ok("_msearch header naming another index", not leaks(r) and s in (200, 403), (s, r))
+s, r, _ = call("POST", "/casefile/_msearch", nd({"index": ["casefile", "private-diary"]}, {"query": {"match_all": {}}}), GK)
+ok("_msearch header naming a list", not leaks(r), (s, r))
+s, r, _ = call("POST", "/casefile/_msearch", nd({"index": "looks-harmless"}, {"query": {"match_all": {}}}), GK)
+ok("_msearch header naming an alias elsewhere", not leaks(r), (s, r))
+s, r, _ = call("POST", "/_msearch", nd({"index": "private-diary"}, {"query": {"match_all": {}}}), GK)
+ok("global _msearch", s == 403 and not leaks(r), (s, r))
+s, r, _ = call("POST", "/casefile/_mget", {"docs": [{"_index": "private-diary", "_id": "1"}]}, GK)
+ok("_mget naming another index", not leaks(r) and s in (200, 403), (s, r))
+s, r, _ = call("POST", "/_mget", {"docs": [{"_index": "private-diary", "_id": "1"}]}, GK)
+ok("global _mget", s == 403 and not leaks(r), (s, r))
+s, r, _ = call("POST", "/casefile/_msearch", nd({}, {"query": {"match_all": {}}}), GK)
+ok("_msearch inside the shared index still works", s == 200 and not leaks(r), (s, r))
+
+section("what the guest CANNOT reach: another index from INSIDE a permitted query")
+for name, query in [
+ ("terms lookup", {"terms": {"body": {"index": "private-diary", "id": "1", "path": "tag"}}}),
+ ("more_like_this like-doc", {"more_like_this": {"fields": ["body"], "like": [{"_index": "private-diary", "_id": "1"}],
+ "min_term_freq": 1, "min_doc_freq": 1}}),
+ ("percolate stored doc", {"percolate": {"field": "q", "index": "private-diary", "id": "1"}}),
+ ("geo_shape indexed_shape", {"geo_shape": {"loc": {"indexed_shape": {"index": "private-diary", "id": "1", "path": "body"}}}}),
+ ("bool-wrapped terms lookup", {"bool": {"filter": [{"terms": {"body": {"index": "private-diary", "id": "1", "path": "body"}}}]}}),
+]:
+ s, r, _ = call("POST", "/casefile/_search", {"query": query}, GK)
+ ok(f"{name} cannot read private-diary", not leaks(r) and not hits_outside(r, SHARED), (s, r))
+ # The probe that matters: a terms lookup on `tag` = "deposit" would match
+ # casefile/1 if — and only if — the node fetched the private document.
+ if name == "terms lookup":
+ ok("terms lookup did not silently resolve the private document",
+ s == 403 or r.get("hits", {}).get("total", {}).get("value", 0) == 0, (s, r))
+s, r, _ = call("POST", "/casefile/_search",
+ {"query": {"match_all": {}}, "runtime_mappings": {"x": {"type": "lookup", "target_index": "private-diary",
+ "input_field": "subject", "target_field": "subject", "fetch_fields": ["body"]}}, "fields": ["x"]}, GK)
+ok("lookup runtime field cannot join private-diary", not leaks(r), (s, r))
+
+section("what the guest CANNOT reach: server-side contexts")
+for method, path, body in [
+ ("POST", "/casefile/_search?scroll=1m", {"query": {"match_all": {}}}),
+ ("POST", "/casefile/_search?%73croll=1m", {"query": {"match_all": {}}}),
+ ("POST", "/casefile/_search?size=1&SCROLL=1m", {"query": {"match_all": {}}}),
+ ("POST", "/_search/scroll", {"scroll": "1m", "scroll_id": "x"}),
+ ("DELETE", "/_search/scroll", {"scroll_id": "x"}),
+ ("POST", "/casefile/_pit?keep_alive=1m", None),
+ ("DELETE", "/_pit", {"id": "x"}),
+ ("POST", "/casefile/_async_search", {"query": {"match_all": {}}}),
+ ("POST", "/casefile/_search/template", {"source": {"query": {"match_all": {}}}}),
+ ("POST", "/_sql", {"query": "SELECT * FROM \"private-diary\""}),
+ ("POST", "/casefile/_sql", {"query": "SELECT * FROM \"private-diary\""}),
+ ("POST", "/_esql/query", {"query": "FROM private-diary"}),
+]:
+ s, r, _ = call(method, path, body, GK)
+ # 404 = this build has no such route at all (`_esql`, index-scoped `_sql`).
+ ok(f"{method} {path} → refused", s in (403, 404) and not leaks(r) and "_scroll_id" not in r and "id" not in r, (s, r))
+# Someone else's server-side context. A PIT — not the path — decides which index
+# a search runs against, so the owner's PIT on private-diary is the real probe.
+s, r, _ = call("POST", "/private-diary/_pit?keep_alive=5m", None, ADMIN)
+PIT = r.get("id")
+ok("(owner opens a PIT on the private index)", s == 200 and PIT, (s, r))
+s, r, _ = call("POST", "/casefile/_search", {"query": {"match_all": {}}, "pit": {"id": PIT}}, ADMIN)
+ok("(and for the owner that PIT really does override the path index)", s == 200 and leaks(r), (s, r))
+s, r, _ = call("POST", "/casefile/_search", {"query": {"match_all": {}}, "pit": {"id": PIT, "keep_alive": "1m"}}, GK)
+ok("a guest cannot ride it via _search", s == 403 and not leaks(r) and "private-diary" not in json.dumps(r), (s, r))
+s, r, _ = call("POST", "/casefile/_msearch", nd({}, {"query": {"match_all": {}}, "pit": {"id": PIT}}), GK)
+ok("…nor via an _msearch body line", s == 403 and not leaks(r) and "private-diary" not in json.dumps(r), (s, r))
+s, r, _ = call("POST", "/private-diary/_search?scroll=5m", {"size": 1, "query": {"match_all": {}}}, ADMIN)
+SCROLL = r.get("_scroll_id")
+s, r, _ = call("POST", "/_search/scroll", {"scroll": "1m", "scroll_id": SCROLL}, GK)
+ok("a guest cannot continue the owner's scroll", s == 403 and not leaks(r), (s, r))
+
+section("what the guest CANNOT reach: writes and index administration")
+for method, path, body in [
+ ("PUT", "/casefile/_doc/99", {"body": "tampered"}), ("POST", "/casefile/_doc", {"body": "tampered"}),
+ ("POST", "/casefile/_update/1", {"doc": {"body": "tampered"}}), ("DELETE", "/casefile/_doc/1", None),
+ ("POST", "/casefile/_bulk", nd({"index": {"_id": "77"}}, {"body": "tampered"})),
+ ("POST", "/_bulk", nd({"index": {"_index": "casefile", "_id": "77"}}, {"body": "tampered"})),
+ ("POST", "/casefile/_delete_by_query", {"query": {"match_all": {}}}),
+ ("POST", "/casefile/_update_by_query", {"query": {"match_all": {}}}),
+ ("POST", "/_reindex", {"source": {"index": "private-diary"}, "dest": {"index": "casefile"}}),
+ ("POST", "/_reindex", {"source": {"index": "casefile"}, "dest": {"index": "mine"}}),
+ ("PUT", "/casefile/_mapping", {"properties": {"x": {"type": "keyword"}}}),
+ ("PUT", "/casefile/_settings", {"index": {"number_of_replicas": 0}}),
+ ("POST", "/casefile/_refresh", None), ("POST", "/casefile/_flush", None),
+ ("POST", "/casefile/_forcemerge", None), ("POST", "/casefile/_close", None),
+ ("GET", "/casefile", None), ("GET", "/casefile/_settings", None), ("GET", "/casefile/_stats", None),
+ ("GET", "/casefile/_segments", None), ("POST", "/casefile/_analyze", {"text": "x"}),
+ ("PUT", "/brand-new", None), ("DELETE", "/casefile", None),
+]:
+ s, r, _ = call(method, path, body, GK)
+ ok(f"{method} {path} → 403", s == 403, (s, r))
+s, r, _ = call("GET", "/casefile/_doc/1", None, GK)
+ok("the shared document is untouched", s == 200 and "tampered" not in json.dumps(r), (s, r))
+s, r, _ = call("GET", "/casefile/_doc/99", None, ADMIN)
+ok("no guest write landed", s == 404, (s, r))
+
+section("what the guest CANNOT reach: another brain, memory, the console API")
+for method, path, body in [
+ ("GET", "/_graph/other/overview", None), ("GET", "/_graph/other/ego?node=private-diary/1", None),
+ ("POST", "/_graph/case/link", {"src": "a", "dst": "b", "type": "t"}),
+ ("POST", "/_graph/other/link", {"src": "a", "dst": "b", "type": "t"}),
+ ("DELETE", "/_graph/case/link/e1", None),
+ ("GET", "/_memory/case", None), ("POST", "/_memory/case/_recall", {"query": "x"}),
+ ("POST", "/_memory/other/_recall", {"query": "x"}),
+]:
+ s, r, _ = call(method, path, body, GK)
+ ok(f"{method} {path} → 403", s == 403 and not leaks(r), (s, r))
+for method, path, body in [
+ ("GET", "/_xerj-console/api/v1/me", None), ("GET", "/_xerj-console/api/v1/prefs", None),
+ ("GET", "/_xerj-console/api/v1/dashboards", None), ("GET", "/_xerj-console/api/v1/auth/api-tokens", None),
+ ("GET", "/_xerj-console/api/v1/data-sources/connections", None),
+ ("POST", "/_xerj-console/api/v1/data-sources/connections/built-in/indices/private-diary/search",
+ {"query": {"match_all": {}}}),
+ ("POST", "/_xerj-console/api/v1/auth/magic/issue", {}),
+]:
+ s, r, _ = call(method, path, body, GK)
+ ok(f"console API {path.rsplit('/v1/', 1)[1]} does not accept a guest key", s in (401, 403) and not leaks(r), (s, r))
+
+if NATIVE:
+ section("what the guest CANNOT reach: the native REST listener")
+ # (`/v1/indices` is POST-only — create; the native listing is `GET /v1/indices/{name}`.)
+ s, r, _ = call("GET", "/v1/indices/casefile", None, ADMIN, base=NATIVE)
+ ok("(the owner can describe the shared index on the native port)", s == 200, (s, r))
+ for method, path, body in [
+ ("GET", "/v1/indices", None), ("GET", "/v1/indices/casefile", None),
+ ("POST", "/v1/indices/casefile/search", {"query": {"match_all": {}}}),
+ ("POST", "/v1/indices/private-diary/search", {"query": {"match_all": {}}}),
+ ("POST", "/v1/indices/casefile/docs", {"body": "tampered"}),
+ ("GET", "/v1/metrics", None), ("GET", "/_cat/indices", None),
+ ("POST", "/private-diary/_search", {"query": {"match_all": {}}}),
+ ]:
+ s, r, _ = call(method, path, body, GK, base=NATIVE)
+ ok(f"native port: {method} {path} → refused", s in (401, 403, 404, 405) and not leaks(r), (s, r))
+
+# ─────────────────────────────────────────────────────────────────────────────
+section("an alias is resolved when the share is made")
+s, r, _ = call("POST", "/_share", {"index": "looks-harmless", "max_claims": 1}, ADMIN)
+ok("sharing an alias records the concrete index it points at",
+ s == 200 and r.get("indices") == ["private-diary"], (s, r))
+asid, apw, ahandle = r.get("share_id"), r.get("passcode"), r.get("handle")
+s, ag, _ = claim(asid, apw)
+AK = ag.get("api_key")
+s, r, _ = call("POST", "/private-diary/_search", {"query": {"match_all": {}}}, AK)
+ok("that guest reads what the owner chose to share", s == 200 and r["hits"]["total"]["value"] == 1, (s, r))
+call("POST", "/_aliases", {"actions": [{"remove": {"index": "private-diary", "alias": "looks-harmless"}},
+ {"add": {"index": "casefile", "alias": "looks-harmless"}}]}, ADMIN)
+s, r, _ = call("POST", "/casefile/_search", {"query": {"match_all": {}}}, AK)
+ok("re-pointing the alias afterwards does not move the guest", s == 403, (s, r))
+# By the handle, as the CLI does: a DELETE naming the full id would put that
+# id in the request line, which the log check at the end would (rightly) find.
+call("DELETE", f"/_share/{ahandle}", None, ADMIN)
+
+# ─────────────────────────────────────────────────────────────────────────────
+section("at rest, listing, revoke")
+disk = open(os.path.join(DATA, "shares.json")).read()
+ok("shares.json holds no passcode, share id or key", PW not in disk and SID not in disk and GK not in disk)
+mode = oct(os.stat(os.path.join(DATA, "shares.json")).st_mode & 0o777)
+ok("shares.json is 0600", mode == "0o600", mode)
+s, l, h = call("GET", "/_share", None, ADMIN)
+ok("owner lists shares, no secrets in the listing",
+ s == 200 and PW not in json.dumps(l) and SID not in json.dumps(l) and "hash" not in json.dumps(l), (s, l))
+ok("listing is never cached", "no-store" in (h.get("cache-control") or ""))
+# "Every /_share response — success or error": the 401 and 403 come from the
+# middleware, not from a share handler, and used to carry no Cache-Control.
+for method, path, key, want in [("GET", "/_share", None, 401), ("POST", "/_share", None, 401),
+ ("DELETE", f"/_share/{HANDLE}", None, 401), ("GET", "/_share/claim", None, 401),
+ ("GET", "/_share", GK, 403), ("POST", "/_share", GK, 403)]:
+ s, r, h = call(method, path, {} if method == "POST" else None, key)
+ ok(f"{method} {path} as {'a guest' if key else 'nobody'} → {want}, no-store",
+ s == want and "no-store" in (h.get("cache-control") or ""), (s, h.get("cache-control")))
+
+# A guest reaching for the share and key management surface is the escalation
+# attempt an owner most wants on record. These are refused in the
+# authorization middleware, so no handler ever audited them.
+before = len(audit_lines())
+for method, path in [("POST", "/_share"), ("GET", "/_share"), ("DELETE", f"/_share/{HANDLE}"),
+ ("POST", "/_security/api_key"), ("GET", "/_security/api_key")]:
+ s, r, _ = call(method, path, {} if method == "POST" else None, GK)
+ ok(f"guest {method} {path} → 403", s == 403, (s, r))
+new = audit_lines()[before:]
+for op, resource in [("share.create", "_share"), ("share.list", "_share"), ("share.revoke", HANDLE),
+ ("security.api_key.create", "_security/api_key"), ("security.api_key.get", "_security/api_key")]:
+ found = [e for e in new if e.get("op") == op and e.get("outcome") == "denied"]
+ ok(f"…and the refused {op} is in the audit log, once, against {resource}",
+ len(found) == 1 and found[0].get("resource") == resource
+ and found[0].get("subject") not in (None, "", "superuser", "unauthenticated"), new)
+s, r, _ = call("DELETE", f"/_share/{HANDLE}", None, ADMIN)
+ok("owner revokes by handle", s == 200 and r.get("keys_invalidated") == 1, (s, r))
+s, r, _ = call("POST", "/casefile/_search", {"query": {"match_all": {}}}, GK)
+ok("revoke kills the guest's key", s in (401, 403), (s, r))
+s, r, _ = call("GET", "/_graph/case/overview", None, GK)
+ok("…on the graph API too", s in (401, 403), (s, r))
+
+# ─────────────────────────────────────────────────────────────────────────────
+section("the guest page is served without a session, with a strict policy")
+for path in ("/_xerj-console/share", "/_xerj-console/share/", "/_xerj-console/share/share.js",
+ "/_xerj-console/share/share.css"):
+ s, r, h = call("GET", path)
+ csp = h.get("content-security-policy") or ""
+ ok(f"GET {path} → 200 + CSP + no-referrer + nosniff + no-store + unframeable",
+ s == 200 and "default-src 'none'" in csp and "frame-ancestors 'none'" in csp
+ and "script-src 'self'" in csp and "unsafe" not in csp
+ and h.get("referrer-policy") == "no-referrer" and h.get("x-content-type-options") == "nosniff"
+ and "no-store" in (h.get("cache-control") or "") and h.get("x-frame-options") == "DENY",
+ (s, dict(h)))
+for path in ("/_xerj-console/share/../api/v1/me", "/_xerj-console/share/%2e%2e/index.html",
+ "/_xerj-console/share/nope.js"):
+ s, r, _ = call("GET", path)
+ ok(f"GET {path} opens nothing", s in (400, 401, 404), (s, r))
+s, r, _ = call("GET", "/_xerj-console/api/v1/me")
+ok("the console API still needs a session", s == 401, (s, r))
+
+# ─────────────────────────────────────────────────────────────────────────────
+section("the claim limiter")
+s, r, _ = call("POST", "/_share", {"index": "casefile", "max_claims": 5}, ADMIN)
+sid2, pw2 = r["share_id"], r["passcode"]
+codes = [claim(sid2, "guess")[0] for _ in range(14)]
+ok("wrong-passcode hammering is locked out with 429", codes[:10] == [401] * 10 and set(codes[10:]) == {429}, codes)
+s, r, h = claim(sid2, pw2)
+ok("…and while locked, even the right passcode waits (with Retry-After)",
+ s == 429 and int(h.get("retry-after") or 0) >= 1, (s, dict(h)))
+
+# The tunnel case. Behind `xerj share --tunnel` every client arrives from
+# 127.0.0.1 — which is also where this test runs from. Flood the junk bucket…
+s, r, _ = call("POST", "/_share", {"index": "casefile", "max_claims": 2}, ADMIN)
+sid3, pw3 = r["share_id"], r["passcode"]
+junk = [claim(f"{i:032x}", "x", headers={"x-forwarded-for": f"198.51.100.{i % 250}"})[0] for i in range(1, 16)]
+if TRUSTS_LOOPBACK:
+ ok("trusted loopback proxy: each forwarded address gets its own junk bucket", 429 not in junk, junk)
+else:
+ first_429 = junk.index(429) if 429 in junk else len(junk)
+ ok("junk ids are throttled per source (404s, then nothing but 429)",
+ 0 < first_429 < len(junk) and set(junk[:first_429]) == {404} and set(junk[first_429:]) == {429}, junk)
+ ok("a rotating X-Forwarded-For from a direct client buys no fresh bucket", junk[-1] == 429, junk)
+# …and a real guest, from the same address, is not locked out by it.
+s, r, _ = claim(sid3, pw3)
+ok("a junk flood from the same address does NOT lock a real guest out", s == 200 and r.get("api_key"), (s, r))
+
+audit = open(os.path.join(DATA, "audit.jsonl")).read()
+ok("every claim outcome is in the audit log",
+ all(w in audit for w in ("share.claim", "wrong passcode", "unknown share", "rate-limited", "share.revoke")))
+if TRUSTS_LOOPBACK:
+ ok("audit records the forwarded address when loopback is a declared proxy", "[email protected]." in audit)
+else:
+ ok("audit records the TCP peer, never a header the client wrote",
+ "[email protected]" in audit and "198.51.100." not in audit)
+ok("no passcode, share id or guest key is written to the audit log",
+ all(x not in audit for x in (PW, SID, GK, pw2, sid2, pw3, sid3, asid, apw)))
+
+# The node's own log. The guest page keeps the id in the URL fragment so that
+# no server sees it; the first cut then posted it as part of a request PATH,
+# and with `logging.access_log = true` every claim wrote the id to server.log
+# (twice). Only meaningful against a node that logs requests — so insist on it.
+if SERVER_LOG:
+ log = open(SERVER_LOG, errors="replace").read()
+ ok("the node is logging requests (logging.access_log = true), so the next check tests something",
+ "/_share/claim" in log, log[-300:])
+ ok("no share id, passcode or guest key is anywhere in the node's log",
+ all(x not in log for x in (SID, sid2, sid3, asid, PW, pw2, pw3, apw, GK)))
+
+print(f"\npassed={PASSED} failed={FAILED}")
+sys.exit(min(FAILED, 255))
diff --git a/engine/crates/xerj-api/tests/share_links_review_findings.rs b/engine/crates/xerj-api/tests/share_links_review_findings.rs
new file mode 100644
index 000000000..2092bcded
--- /dev/null
+++ b/engine/crates/xerj-api/tests/share_links_review_findings.rs
@@ -0,0 +1,462 @@
+//! Executable statement of the review findings on share links (PR #947) that
+//! live in this crate. Each test was written against the pre-fix tree, failed
+//! there, and names the finding it pins down.
+//!
+//! * **The share id reached every access log.** The guest page keeps the id in
+//! the URL fragment so that no server ever sees it — and then posted it as
+//! part of a request *path* (`POST /_share/{id}/claim`). With
+//! `logging.access_log = true` the node wrote the id to `server.log` twice
+//! per claim, and any reverse proxy or tunnel in front logged the same line.
+//! The claim is `POST /_share/claim` with `{id, passcode}` now, and the old
+//! shape is not a door of any kind.
+//! * **A guest's escalation attempts left no audit line.** `POST /_share`,
+//! `GET /_share`, `DELETE /_share/{handle}` and `POST /_security/api_key`
+//! with a guest key: four `403`s, zero entries — the audit layer skipped
+//! both prefixes because "the handler audits them", and the handler never
+//! ran.
+//! * **`autoindex-catalog` was shareable** while three public documents said
+//! it is never granted.
+//! * **`GET _source/{id}` was documented as something a guest can call.** The
+//! router has no such route.
+//! * **"Every `/_share` response is no-store"** was not true of the `401` and
+//! `403` the middleware produces, and nothing a guest *read* was marked
+//! uncacheable at all.
+
+use axum::body::Body;
+use axum::http::{HeaderMap, Request, StatusCode};
+use http_body_util::BodyExt;
+use serde_json::{json, Value};
+use tower::ServiceExt;
+use xerj_api::{
+ router::{build_es_compat_router, build_native_router},
+ state::AppState,
+};
+use xerj_common::{config::Config, metrics::Metrics};
+use xerj_engine::Engine;
+
+const ADMIN_KEY: &str = "admin-key-for-the-share-review-findings-test";
+
+fn state_over(data_dir: &str) -> AppState {
+ let mut config = Config::default();
+ config.server.data_dir = data_dir.to_string();
+ config.auth.enabled = true;
+ config.auth.admin_api_key = ADMIN_KEY.to_string();
+ let metrics = Metrics::new().expect("metrics");
+ let engine = Engine::new(config.clone()).expect("engine");
+ AppState::new(config, engine, metrics)
+}
+
+async fn send(
+ app: &axum::Router,
+ method: &str,
+ uri: &str,
+ auth: &str,
+ body: &str,
+) -> (StatusCode, Value, HeaderMap) {
+ let mut builder = Request::builder()
+ .method(method)
+ .uri(uri)
+ .header("content-type", "application/json");
+ if !auth.is_empty() {
+ builder = builder.header("authorization", auth);
+ }
+ let req = builder.body(Body::from(body.to_string())).expect("request");
+ let resp = app.clone().oneshot(req).await.expect("response");
+ let status = resp.status();
+ let headers = resp.headers().clone();
+ let bytes = resp.into_body().collect().await.expect("body").to_bytes();
+ let json: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
+ (status, json, headers)
+}
+
+fn admin() -> String {
+ format!("ApiKey {ADMIN_KEY}")
+}
+
+fn no_store(headers: &HeaderMap) -> bool {
+ headers
+ .get("cache-control")
+ .and_then(|v| v.to_str().ok())
+ .is_some_and(|v| v.contains("no-store"))
+}
+
+/// An index with one document, a share on it, and the share's
+/// `(id, passcode, handle)`.
+async fn casefile_share(es: &axum::Router, max_claims: u32) -> (String, String, String) {
+ let (status, _, _) = send(es, "PUT", "/casefile", &admin(), "").await;
+ assert_eq!(status, StatusCode::OK);
+ let (status, _, _) = send(
+ es,
+ "PUT",
+ "/casefile/_doc/1?refresh=true",
+ &admin(),
+ r#"{"title":"Lease","body":"the deposit was not returned"}"#,
+ )
+ .await;
+ assert_eq!(status, StatusCode::CREATED);
+ let (status, share, _) = send(
+ es,
+ "POST",
+ "/_share",
+ &admin(),
+ &json!({"index": "casefile", "max_claims": max_claims}).to_string(),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{share}");
+ (
+ share["share_id"].as_str().expect("share_id").to_string(),
+ share["passcode"].as_str().expect("passcode").to_string(),
+ share["handle"].as_str().expect("handle").to_string(),
+ )
+}
+
+/// Claim and return the guest's `Authorization` header value.
+async fn claim(es: &axum::Router, id: &str, passcode: &str) -> String {
+ let (status, got, _) = send(
+ es,
+ "POST",
+ "/_share/claim",
+ "",
+ &json!({"id": id, "passcode": passcode}).to_string(),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "claim should succeed: {got}");
+ format!("ApiKey {}", got["api_key"].as_str().expect("api_key"))
+}
+
+async fn audit_entries(native: &axum::Router) -> Vec<Value> {
+ let (status, body, _) = send(native, "GET", "/_audit/_search?size=1000", &admin(), "").await;
+ assert_eq!(status, StatusCode::OK, "audit read should succeed: {body}");
+ body["entries"].as_array().cloned().unwrap_or_default()
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// The share id is never part of a request path
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test]
+async fn the_share_id_travels_in_the_claim_body_never_in_a_path() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let state = state_over(dir.path().to_str().expect("utf8 path"));
+ let es = build_es_compat_router(state);
+ let (id, passcode, handle) = casefile_share(&es, 2).await;
+
+ // The retired shape. Pre-fix this was the open door (200 + a key) and the
+ // id was in the request line. It must not be a second way in: without a
+ // credential it is an ordinary unauthenticated request.
+ let (status, body, _) = send(
+ &es,
+ "POST",
+ &format!("/_share/{id}/claim"),
+ "",
+ &json!({"passcode": passcode}).to_string(),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::UNAUTHORIZED,
+ "the id-in-path claim shape must be gone: {body}"
+ );
+ assert!(body.get("api_key").is_none(), "{body}");
+
+ // The body shape: wrong passcode, no id, the handle in place of the id.
+ let (status, _, headers) = send(
+ &es,
+ "POST",
+ "/_share/claim",
+ "",
+ &json!({"id": id, "passcode": "not-the-code"}).to_string(),
+ )
+ .await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert!(no_store(&headers));
+ let (status, _, _) = send(
+ &es,
+ "POST",
+ "/_share/claim",
+ "",
+ &json!({"passcode": passcode}).to_string(),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::NOT_FOUND,
+ "a claim with no id is an unknown link"
+ );
+ let (status, _, _) = send(
+ &es,
+ "POST",
+ "/_share/claim",
+ "",
+ &json!({"id": handle, "passcode": passcode}).to_string(),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::NOT_FOUND,
+ "the public handle is not a claim id"
+ );
+
+ // The claim route reads a few KiB and no more: a padded body is not
+ // parsed, so it names no share.
+ let padded = json!({"id": id, "passcode": passcode, "pad": "x".repeat(16 * 1024)}).to_string();
+ let (status, body, _) = send(&es, "POST", "/_share/claim", "", &padded).await;
+ assert_ne!(status, StatusCode::OK, "an oversized claim body: {body}");
+ assert!(body.get("api_key").is_none(), "{body}");
+
+ // And the real thing.
+ let (status, got, headers) = send(
+ &es,
+ "POST",
+ "/_share/claim",
+ "",
+ &json!({"id": id, "passcode": passcode}).to_string(),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{got}");
+ assert!(got["api_key"].as_str().is_some_and(|k| k.len() > 20));
+ assert_eq!(got["index"].as_str(), Some("casefile"));
+ assert!(no_store(&headers));
+
+ // `claim` is a route, not a handle: it cannot be revoked into.
+ let (status, _, _) = send(&es, "DELETE", "/_share/claim", &admin(), "").await;
+ assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
+ // GET is not the open door either.
+ let (status, _, _) = send(&es, "GET", "/_share/claim", "", "").await;
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// A guest's escalation attempts are audited
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test]
+async fn a_guests_refused_escalation_attempts_are_audited() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let state = state_over(dir.path().to_str().expect("utf8 path"));
+ let es = build_es_compat_router(state.clone());
+ let native = build_native_router(state);
+ let (id, passcode, handle) = casefile_share(&es, 1).await;
+ let guest = claim(&es, &id, &passcode).await;
+
+ for (method, uri) in [
+ ("POST", "/_share".to_string()),
+ ("GET", "/_share".to_string()),
+ ("DELETE", format!("/_share/{handle}")),
+ ("POST", "/_security/api_key".to_string()),
+ ("GET", "/_security/api_key".to_string()),
+ ] {
+ let (status, body, _) = send(&es, method, &uri, &guest, "{}").await;
+ assert_eq!(status, StatusCode::FORBIDDEN, "{method} {uri}: {body}");
+ }
+
+ let entries = audit_entries(&native).await;
+ let denied = |op: &str| -> Vec<&Value> {
+ entries
+ .iter()
+ .filter(|e| e["op"].as_str() == Some(op) && e["outcome"].as_str() == Some("denied"))
+ .collect()
+ };
+ for (op, resource) in [
+ ("share.create", "_share"),
+ ("share.list", "_share"),
+ ("share.revoke", handle.as_str()),
+ ("security.api_key.create", "_security/api_key"),
+ ("security.api_key.get", "_security/api_key"),
+ ] {
+ let found = denied(op);
+ assert_eq!(
+ found.len(),
+ 1,
+ "a guest's refused {op} must leave exactly one `denied` entry; log: {:?}",
+ entries
+ .iter()
+ .map(|e| format!("{} {}", e["op"], e["outcome"]))
+ .collect::<Vec<_>>()
+ );
+ assert_eq!(found[0]["resource"].as_str(), Some(resource), "{op}");
+ let subject = found[0]["subject"].as_str().unwrap_or("");
+ assert!(
+ !subject.is_empty() && subject != "superuser" && subject != "unauthenticated",
+ "{op} must name the guest key, got {subject:?}"
+ );
+ }
+
+ // An ordinary scoped key reaches the listing handler, which writes its own
+ // entry — the request-level layer must not write a second one.
+ let (status, minted, _) = send(
+ &es,
+ "POST",
+ "/_security/api_key",
+ &admin(),
+ r#"{"name":"reader","role_descriptors":{"r":{"indices":[{"names":["casefile"],"privileges":["read"]}]}}}"#,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{minted}");
+ let reader = format!("ApiKey {}", minted["encoded"].as_str().expect("encoded"));
+ let before = audit_entries(&native).await.len();
+ let (status, _, _) = send(&es, "GET", "/_share", &reader, "").await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ let after = audit_entries(&native).await;
+ let new: Vec<&Value> = after[before.min(after.len())..]
+ .iter()
+ .filter(|e| e["op"].as_str() == Some("share.list"))
+ .collect();
+ assert_eq!(new.len(), 1, "one refusal, one entry: {new:?}");
+
+ // Nothing above wrote the share id, the passcode or the guest key down.
+ let log = serde_json::to_string(&after).expect("json");
+ assert!(!log.contains(&id), "the share id is in the audit log");
+ assert!(!log.contains(&passcode), "the passcode is in the audit log");
+ assert!(
+ !log.contains(guest.trim_start_matches("ApiKey ")),
+ "the guest key is in the audit log"
+ );
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Nothing under /_share, and nothing a guest reads, may be cached
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test]
+async fn share_responses_and_guest_reads_are_never_cacheable() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let state = state_over(dir.path().to_str().expect("utf8 path"));
+ let es = build_es_compat_router(state);
+ let (id, passcode, handle) = casefile_share(&es, 1).await;
+ let guest = claim(&es, &id, &passcode).await;
+
+ // Refusals the handlers never see.
+ for (method, uri, auth, want) in [
+ ("GET", "/_share".to_string(), "", StatusCode::UNAUTHORIZED),
+ ("POST", "/_share".to_string(), "", StatusCode::UNAUTHORIZED),
+ (
+ "DELETE",
+ format!("/_share/{handle}"),
+ "",
+ StatusCode::UNAUTHORIZED,
+ ),
+ (
+ "GET",
+ "/_share/claim".to_string(),
+ "",
+ StatusCode::UNAUTHORIZED,
+ ),
+ (
+ "GET",
+ "/_share".to_string(),
+ guest.as_str(),
+ StatusCode::FORBIDDEN,
+ ),
+ (
+ "POST",
+ "/_share".to_string(),
+ guest.as_str(),
+ StatusCode::FORBIDDEN,
+ ),
+ ] {
+ let (status, _, headers) = send(&es, method, &uri, auth, "{}").await;
+ assert_eq!(status, want, "{method} {uri}");
+ assert!(
+ no_store(&headers),
+ "{method} {uri} → {status} must be no-store, got {:?}",
+ headers.get("cache-control")
+ );
+ }
+
+ // What the guest reads: the documents themselves.
+ for (method, uri, body) in [
+ ("POST", "/casefile/_search", r#"{"query":{"match_all":{}}}"#),
+ ("GET", "/casefile/_doc/1", ""),
+ ("GET", "/casefile/_mapping", ""),
+ ("POST", "/casefile/_count", ""),
+ ] {
+ let (status, _, headers) = send(&es, method, uri, &guest, body).await;
+ assert_eq!(status, StatusCode::OK, "{method} {uri}");
+ assert!(
+ no_store(&headers),
+ "a guest's {method} {uri} must be no-store, got {:?}",
+ headers.get("cache-control")
+ );
+ }
+ // …and what it is refused.
+ let (status, _, headers) = send(&es, "GET", "/_cat/indices", &guest, "").await;
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert!(no_store(&headers));
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// The catalog is never granted; `_source/{id}` is not a guest route
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test]
+async fn the_autoindex_catalog_cannot_be_shared_by_name_list_or_alias() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let state = state_over(dir.path().to_str().expect("utf8 path"));
+ let es = build_es_compat_router(state);
+ let _ = casefile_share(&es, 1).await;
+ let (status, _, _) = send(&es, "PUT", "/autoindex-catalog", &admin(), "").await;
+ assert_eq!(status, StatusCode::OK);
+ let (status, body, _) = send(
+ &es,
+ "POST",
+ "/_aliases",
+ &admin(),
+ r#"{"actions":[{"add":{"index":"autoindex-catalog","alias":"what-is-here"}}]}"#,
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+
+ for index in [
+ json!("autoindex-catalog"),
+ json!(["casefile", "autoindex-catalog"]),
+ json!("casefile,autoindex-catalog"),
+ json!("what-is-here"),
+ ] {
+ let (status, body, _) = send(
+ &es,
+ "POST",
+ "/_share",
+ &admin(),
+ &json!({ "index": index }).to_string(),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::BAD_REQUEST,
+ "sharing {index} must be refused: {body}"
+ );
+ assert!(
+ body["error"]["reason"]
+ .as_str()
+ .is_some_and(|r| r.contains("every corpus")),
+ "{body}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn source_by_id_is_not_a_route_and_not_a_guest_permission() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let state = state_over(dir.path().to_str().expect("utf8 path"));
+ let es = build_es_compat_router(state);
+ let (id, passcode, _) = casefile_share(&es, 1).await;
+ let guest = claim(&es, &id, &passcode).await;
+
+ // If this ever answers 200 for the admin key, the route has been added:
+ // decide then whether a guest gets it, and only then document it.
+ let (status, _, _) = send(&es, "GET", "/casefile/_source/1", &admin(), "").await;
+ assert_eq!(
+ status,
+ StatusCode::NOT_FOUND,
+ "there is no /{{index}}/_source/{{id}} route on this node"
+ );
+ let (status, _, _) = send(&es, "GET", "/casefile/_source/1", &guest, "").await;
+ assert_eq!(
+ status,
+ StatusCode::FORBIDDEN,
+ "a route that does not exist is not pre-approved for a guest"
+ );
+ let (status, _, _) = send(&es, "GET", "/casefile/_doc/1", &guest, "").await;
+ assert_eq!(status, StatusCode::OK);
+}
diff --git a/engine/crates/xerj-autoindex/src/esclient.rs b/engine/crates/xerj-autoindex/src/esclient.rs
index 117e59e2e..d2d81da19 100644
--- a/engine/crates/xerj-autoindex/src/esclient.rs
+++ b/engine/crates/xerj-autoindex/src/esclient.rs
@@ -743,6 +743,38 @@ impl Es {
Ok(body)
}
+ /// One JSON request, one attempt, status handed back to the caller.
+ ///
+ /// For interactive commands whose statuses *are* the answer — `xerj share`
+ /// reads a 403 as "that key is not the admin key", a 404 as "no such
+ /// index" and a 409 as "this node has authentication off". `get_json`
+ /// folds every non-2xx into one opaque error, and the retry wrapper would
+ /// spend ~16s re-asking a question whose answer will not change. A body
+ /// that is not JSON comes back as `Value::Null` rather than an error: the
+ /// status is still the caller's to interpret.
+ ///
+ /// `method` is the verb as text (`"GET"`, `"POST"`, `"DELETE"`) so that a
+ /// caller in another crate does not need `reqwest` as a dependency of its
+ /// own just to name one.
+ pub fn request_json(
+ &self,
+ method: &str,
+ path: &str,
+ body: Option<&Value>,
+ ) -> Result<(u16, Value)> {
+ let method = reqwest::Method::from_bytes(method.as_bytes())
+ .with_context(|| format!("not an HTTP method: {method}"))?;
+ let mut r = self.req(method, path);
+ if let Some(b) = body {
+ r = r.json(b);
+ }
+ let resp = r
+ .send()
+ .with_context(|| format!("no response from {}{}", self.base, path))?;
+ let status = resp.status().as_u16();
+ Ok((status, resp.json().unwrap_or(Value::Null)))
+ }
+
/// One attempt of a retried request, classified.
fn attempt_from<T>(
what: &str,
diff --git a/engine/crates/xerj-console-api/build.rs b/engine/crates/xerj-console-api/build.rs
index bf0e7a7be..5ca69d959 100644
--- a/engine/crates/xerj-console-api/build.rs
+++ b/engine/crates/xerj-console-api/build.rs
@@ -12,8 +12,9 @@
// PDF in the UX tree doesn't bloat the binary.
//
// Re-run logic: cargo invokes this script when build.rs itself
-// changes OR when any file under the xerj-ux source tree is
-// modified (we emit `cargo:rerun-if-changed` for each one).
+// changes OR when anything under the xerj-ux source tree is modified,
+// added or removed (we emit `cargo:rerun-if-changed` for the tree root
+// as well as for each bundled file).
use std::env;
use std::fs;
@@ -61,6 +62,14 @@ fn main() {
}
};
+ // The per-file lines emitted by `walk` only cover files that existed the
+ // last time this script ran, so a NEW file — or a whole new directory, as
+ // `share/` was — never re-triggered the script on a warm target dir: the
+ // binary built, and served 404 for assets that were sitting in the tree.
+ // A directory path makes cargo scan the tree, which catches additions and
+ // removals as well as edits.
+ println!("cargo:rerun-if-changed={}", ux_root.display());
+
let mut entries: Vec<(String, PathBuf)> = Vec::new();
walk(&ux_root, &ux_root, &mut entries);
entries.sort();
diff --git a/engine/crates/xerj-console-api/src/spa.rs b/engine/crates/xerj-console-api/src/spa.rs
index 7a0a5667b..dd218579f 100644
--- a/engine/crates/xerj-console-api/src/spa.rs
+++ b/engine/crates/xerj-console-api/src/spa.rs
@@ -12,12 +12,27 @@
//! GET /_xerj-console → Console index.html (302 to /_xerj-console/)
//! GET /_xerj-console/ → Console index.html (200, text/html)
//! GET /_xerj-console/{path*} → static asset by path, 404 if missing
+//! GET /_xerj-console/share → the share-link guest page (share/index.html)
//! ```
//!
//! Cache-Control is set to `public, max-age=300` for static assets;
//! the index.html gets `no-cache` so a deploy of a new binary surfaces
//! the new UI on next page load without ctrl-F5.
//!
+//! ## The share-link guest page
+//!
+//! `share/` is the one part of the bundle meant for someone who is **not** the
+//! operator: the page a guest opens from a `xerj share` link, possibly through
+//! a public tunnel. Like every other asset it is served without a session —
+//! the guest has no credential until the page has exchanged a passcode for
+//! one — so serving it makes nothing new reachable: it is three static files
+//! that were already in the asset table. What it adds is a directory index
+//! (`share` and `share/` both answer with `share/index.html`; the link the CLI
+//! prints has no trailing slash) and a header set no other asset gets, see
+//! [`GUEST_CSP`]. The page renders text from other people's documents, so the
+//! policy is written to make a markup-injection bug inert rather than to rely
+//! on there being none.
+//!
//! ## Why not include_dir / rust-embed
//!
//! Both pull in proc-macro deps. The build.rs approach is ~80 LOC,
@@ -38,6 +53,40 @@ fn find_asset(path: &str) -> Option<&'static (&'static str, &'static [u8], &'sta
XERJ_CONSOLE_ASSETS.iter().find(|(p, _, _)| *p == path)
}
+/// Everything under this asset directory is the share-link guest page.
+const GUEST_DIR: &str = "share";
+
+/// The guest page's Content-Security-Policy.
+///
+/// `default-src 'none'` and then only what the page uses, all same-origin: its
+/// one script, one stylesheet, one icon, and `fetch` back to this node. No
+/// inline script or style is permitted — so text that somehow became markup
+/// could not run — and no third-party origin is reachable, so nothing a guest
+/// reads can be beaconed elsewhere. `form-action 'none'` matters for a
+/// specific failure: the passcode form has no `action`, and if the script
+/// failed to load a native submit would put the passcode in the query string
+/// of a GET, i.e. in the address bar and the access log. `frame-ancestors
+/// 'none'` (with `X-Frame-Options` for browsers that predate it) keeps the
+/// passcode prompt out of anyone else's frame.
+pub const GUEST_CSP: &str = "default-src 'none'; script-src 'self'; style-src 'self'; \
+ img-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; \
+ frame-ancestors 'none'";
+
+/// Is `path` (an asset-table path) part of the guest page?
+fn is_guest_asset(path: &str) -> bool {
+ path.strip_prefix(GUEST_DIR)
+ .is_some_and(|rest| rest.starts_with('/'))
+}
+
+/// Map a request path onto the asset table: the guest page's directory index,
+/// with or without the trailing slash. Everything else is served as asked.
+fn resolve_request_path(rest: &str) -> &str {
+ match rest {
+ "share" | "share/" => "share/index.html",
+ other => other,
+ }
+}
+
/// Serve the Console's index.html for `/_xerj-console/`.
pub async fn xerj_console_index() -> impl IntoResponse {
serve("index.html", true)
@@ -47,11 +96,11 @@ pub async fn xerj_console_index() -> impl IntoResponse {
pub async fn xerj_console_asset(Path(rest): Path<String>) -> impl IntoResponse {
// Empty rest path = same as `/_xerj-console/` — serve index.
let path = if rest.is_empty() {
- "index.html".to_string()
+ "index.html"
} else {
- rest
+ resolve_request_path(&rest)
};
- serve(&path, false)
+ serve(path, false)
}
/// Bare `/_xerj-console` (no trailing slash) — relative `<script src="src/app.js">`
@@ -93,6 +142,9 @@ fn serve(path: &str, no_cache: bool) -> Response {
}
fn serve_asset(asset: &(&'static str, &'static [u8], &'static str), no_cache: bool) -> Response {
+ if is_guest_asset(asset.0) {
+ return serve_guest_asset(asset);
+ }
let cache = if no_cache {
"no-cache"
} else {
@@ -108,8 +160,327 @@ fn serve_asset(asset: &(&'static str, &'static [u8], &'static str), no_cache: bo
.into_response()
}
+/// The guest page and its assets: never stored, never framed, never sniffed,
+/// never a `Referer` source, and confined by [`GUEST_CSP`].
+///
+/// `no-store` rather than the console's five-minute cache: a guest may be on
+/// a borrowed or shared browser, and a page fetched through a quick tunnel
+/// must not be replayed from a cache after the tunnel — and its hostname — is
+/// gone. The files are a few kilobytes; the cost is nothing.
+fn serve_guest_asset(asset: &(&'static str, &'static [u8], &'static str)) -> Response {
+ (
+ [
+ (header::CONTENT_TYPE, asset.2),
+ (header::CACHE_CONTROL, "no-store, max-age=0"),
+ (header::PRAGMA, "no-cache"),
+ (header::CONTENT_SECURITY_POLICY, GUEST_CSP),
+ (header::REFERRER_POLICY, "no-referrer"),
+ (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
+ (header::X_FRAME_OPTIONS, "DENY"),
+ (
+ header::HeaderName::from_static("cross-origin-opener-policy"),
+ "same-origin",
+ ),
+ (
+ header::HeaderName::from_static("cross-origin-resource-policy"),
+ "same-origin",
+ ),
+ (
+ header::HeaderName::from_static("permissions-policy"),
+ "camera=(), microphone=(), geolocation=(), payment=(), usb=()",
+ ),
+ (
+ header::HeaderName::from_static("x-robots-tag"),
+ "noindex, nofollow, noarchive",
+ ),
+ ],
+ asset.1,
+ )
+ .into_response()
+}
+
/// Number of bundled assets — exposed for the startup banner so
/// operators see at-a-glance whether the Console UX was bundled.
pub fn asset_count() -> usize {
XERJ_CONSOLE_ASSETS.len()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A release tarball may omit `xerj-ux/` (build.rs then emits an empty
+ /// table). With nothing bundled there is nothing to assert about.
+ fn bundled() -> bool {
+ asset_count() > 0
+ }
+
+ fn asset_text(path: &str) -> String {
+ let asset = find_asset(path).unwrap_or_else(|| panic!("{path} is not bundled"));
+ String::from_utf8(asset.1.to_vec()).expect("utf-8 asset")
+ }
+
+ fn header<'a>(resp: &'a Response, name: &str) -> &'a str {
+ resp.headers()
+ .get(name)
+ .unwrap_or_else(|| panic!("missing header {name}"))
+ .to_str()
+ .unwrap()
+ }
+
+ /// Drop `/* … */` blocks and whole-line `//` comments, so a scan for a
+ /// forbidden API does not trip over the comment that forbids it.
+ fn strip_js_comments(src: &str) -> String {
+ let mut out = String::with_capacity(src.len());
+ let mut rest = src;
+ while let Some(start) = rest.find("/*") {
+ out.push_str(&rest[..start]);
+ match rest[start..].find("*/") {
+ Some(end) => rest = &rest[start + end + 2..],
+ None => {
+ rest = "";
+ break;
+ }
+ }
+ }
+ out.push_str(rest);
+ out.lines()
+ .filter(|l| !l.trim_start().starts_with("//"))
+ .collect::<Vec<_>>()
+ .join("\n")
+ }
+
+ #[test]
+ fn the_guest_page_answers_with_and_without_the_trailing_slash() {
+ if !bundled() {
+ return;
+ }
+ // The CLI prints `/_xerj-console/share#<id>`; a mail client or a
+ // person may add the slash. Both are the page, not a 404 or a 400.
+ for rest in ["share", "share/", "share/index.html"] {
+ let resp = serve(resolve_request_path(rest), false);
+ assert_eq!(resp.status(), StatusCode::OK, "{rest}");
+ assert_eq!(header(&resp, "content-type"), "text/html; charset=utf-8");
+ assert_eq!(header(&resp, "content-security-policy"), GUEST_CSP);
+ }
+ }
+
+ #[test]
+ fn guest_assets_carry_the_strict_header_set() {
+ if !bundled() {
+ return;
+ }
+ for path in ["share/index.html", "share/share.js", "share/share.css"] {
+ let resp = serve(path, false);
+ assert_eq!(resp.status(), StatusCode::OK, "{path}");
+ assert_eq!(header(&resp, "cache-control"), "no-store, max-age=0");
+ assert_eq!(header(&resp, "referrer-policy"), "no-referrer");
+ assert_eq!(header(&resp, "x-content-type-options"), "nosniff");
+ assert_eq!(header(&resp, "x-frame-options"), "DENY");
+ assert_eq!(header(&resp, "cross-origin-opener-policy"), "same-origin");
+ let csp = header(&resp, "content-security-policy");
+ for directive in [
+ "default-src 'none'",
+ "script-src 'self'",
+ "style-src 'self'",
+ "connect-src 'self'",
+ "base-uri 'none'",
+ "form-action 'none'",
+ "frame-ancestors 'none'",
+ ] {
+ assert!(csp.contains(directive), "{path}: CSP lacks {directive}");
+ }
+ // Nothing that would let injected markup run or phone home.
+ for forbidden in [
+ "unsafe-inline",
+ "unsafe-eval",
+ "data:",
+ "blob:",
+ "*",
+ "http",
+ ] {
+ assert!(!csp.contains(forbidden), "{path}: CSP contains {forbidden}");
+ }
+ }
+ }
+
+ #[test]
+ fn the_console_itself_is_served_exactly_as_before() {
+ if !bundled() {
+ return;
+ }
+ let resp = serve("index.html", true);
+ assert_eq!(resp.status(), StatusCode::OK);
+ assert_eq!(header(&resp, "cache-control"), "no-cache");
+ assert!(resp.headers().get("content-security-policy").is_none());
+ assert!(!is_guest_asset("index.html"));
+ assert!(!is_guest_asset("shared.js"));
+ assert!(!is_guest_asset("share"));
+ assert!(is_guest_asset("share/share.js"));
+ }
+
+ #[test]
+ fn the_directory_index_opens_nothing_else() {
+ // Only the two spellings of the directory map anywhere.
+ assert_eq!(resolve_request_path("share"), "share/index.html");
+ assert_eq!(resolve_request_path("share/"), "share/index.html");
+ for other in [
+ "shared",
+ "share/x",
+ "share//",
+ "api/v1/me",
+ "src/",
+ "share/..",
+ ] {
+ assert_eq!(resolve_request_path(other), other);
+ }
+ for bad in [
+ "share/..",
+ "share/../index.html",
+ "share//share.js",
+ "../share",
+ ] {
+ assert_eq!(serve(bad, false).status(), StatusCode::BAD_REQUEST, "{bad}");
+ }
+ for missing in ["share/nope.js", "shared", "share/share", "share/index.htm"] {
+ assert_eq!(
+ serve(missing, false).status(),
+ StatusCode::NOT_FOUND,
+ "{missing}"
+ );
+ }
+ // The console's extensionless fallback (`setup` → `setup.html`) also
+ // makes `share/index` the page. It is the same file, and it gets the
+ // same policy — the guest header set is keyed on the asset served,
+ // not on the spelling of the request.
+ if bundled() {
+ let resp = serve("share/index", false);
+ assert_eq!(resp.status(), StatusCode::OK);
+ assert_eq!(header(&resp, "content-security-policy"), GUEST_CSP);
+ }
+ }
+
+ #[test]
+ fn the_guest_page_has_no_inline_code_and_loads_nothing_from_elsewhere() {
+ if !bundled() {
+ return;
+ }
+ let html = asset_text("share/index.html");
+ let lower = html.to_ascii_lowercase();
+ // Every <script> is external; the CSP would refuse an inline one, and
+ // this fails the build before a browser has to.
+ for (at, _) in lower.match_indices("<script") {
+ let tag_end = lower[at..].find('>').map(|e| at + e).unwrap_or(lower.len());
+ assert!(
+ lower[at..tag_end].contains("src="),
+ "inline <script> at byte {at}"
+ );
+ }
+ // (`javascript:` is matched as an attribute value: the <noscript> text
+ // legitimately says "This page needs JavaScript: …".)
+ for forbidden in [
+ "<style",
+ " style=",
+ "=\"javascript:",
+ "='javascript:",
+ "=javascript:",
+ "http://",
+ "https://",
+ "src=\"//",
+ "href=\"//",
+ "<iframe",
+ "<object",
+ "<embed",
+ "<base",
+ ] {
+ assert!(
+ !lower.contains(forbidden),
+ "guest page contains {forbidden}"
+ );
+ }
+ // No inline event handlers (` onclick=`, ` onerror=`, …).
+ for (at, _) in lower.match_indices(" on") {
+ let word: String = lower[at + 1..]
+ .chars()
+ .take_while(|c| c.is_ascii_alphabetic())
+ .collect();
+ let after = lower[at + 1 + word.len()..].chars().next();
+ assert!(
+ after != Some('='),
+ "inline event handler `{word}=` in the guest page"
+ );
+ }
+ // What the page tells a guest has to be true through a tunnel too
+ // (review of PR #947): it used to say the browser "talks to their
+ // machine" and that nothing goes "to a third party", on a page served
+ // through Cloudflare. The Cloudflare notice ships hidden; share.js
+ // shows it on a quick-tunnel hostname.
+ for untrue in ["third party", "talks to their machine"] {
+ assert!(!lower.contains(untrue), "guest page still says `{untrue}`");
+ }
+ for id in ["id=\"via-tunnel\" hidden", "id=\"room-via-tunnel\" hidden"] {
+ assert!(html.contains(id), "guest page lacks {id}");
+ }
+ assert!(lower.contains("cloudflare carries the connection and can read"));
+ // Every asset it names is one the bundle actually carries.
+ for asset in ["share/share.js", "share/share.css", "share/icon.svg"] {
+ assert!(find_asset(asset).is_some(), "{asset} is not bundled");
+ assert!(
+ html.contains(&format!("/_xerj-console/{asset}")),
+ "page does not reference {asset}"
+ );
+ }
+ }
+
+ #[test]
+ fn the_guest_script_never_parses_document_text_as_markup() {
+ if !bundled() {
+ return;
+ }
+ // Text from the shared index is attacker-controlled (it is other
+ // people's email). The page may only ever place it as text.
+ let code = strip_js_comments(&asset_text("share/share.js"));
+ for sink in [
+ "innerHTML",
+ "outerHTML",
+ "insertAdjacentHTML",
+ "document.write",
+ "DOMParser",
+ "createContextualFragment",
+ "srcdoc",
+ "eval(",
+ "new Function",
+ "setTimeout('",
+ "setTimeout(\"",
+ "localStorage",
+ "document.cookie",
+ ] {
+ assert!(!code.contains(sink), "share.js uses `{sink}`");
+ }
+ // The one storage contract the console's guest mode depends on.
+ assert!(code.contains("'xerj.share'"));
+ assert!(code.contains("sessionStorage.setItem(SHARE_KEY"));
+ // The share id goes to the node in the claim BODY. A path built from
+ // it is what put the id into access logs (review of PR #947).
+ assert!(code.contains("'/_share/claim'"), "claim route");
+ assert!(
+ !code.contains("/_share/${"),
+ "share.js builds a /_share path from a variable — the id must stay out of URLs"
+ );
+ assert!(code.contains("{ id: state.shareId, passcode }"));
+ // A link pasted over another differs only in its fragment.
+ assert!(code.contains("'hashchange'"));
+ // The highlight delimiters are private-use code points, which are
+ // invisible in an editor and in review: they must be written as
+ // escapes, never as the characters themselves.
+ assert!(
+ !asset_text("share/share.js")
+ .chars()
+ .any(|c| ('\u{E000}'..='\u{F8FF}').contains(&c)),
+ "share.js contains a raw private-use character; write it as \\uE000"
+ );
+ assert!(code.contains("'\\uE000'") && code.contains("'\\uE001'"));
+ // No request leaves the origin: every fetch target is a path.
+ assert!(!code.contains("http://") && !code.contains("https://"));
+ }
+}
diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rs
index 15a4cf11f..0029ea588 100644
--- a/engine/crates/xerj-engine/src/engine.rs
+++ b/engine/crates/xerj-engine/src/engine.rs
@@ -412,10 +412,7 @@ impl ApiKeyRecord {
/// the secret is never briefly world-readable, then renamed over the target
/// (the rename carries the 0600 inode). On non-unix, perms are left to the OS
/// default. Mirrors `index::write_file_atomic` but hardens the mode.
-pub(crate) fn write_secret_file_atomic(
- path: &std::path::Path,
- bytes: &[u8],
-) -> std::io::Result<()> {
+pub fn write_secret_file_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
use std::io::Write as _;
// Unique staging name, for the same reason as `index::write_file_atomic`:
// two concurrent key mints sharing one `api_keys.tmp` can interleave into a
diff --git a/engine/crates/xerj-server/src/brain.rs b/engine/crates/xerj-server/src/brain.rs
index ff6127551..532e648ff 100644
--- a/engine/crates/xerj-server/src/brain.rs
+++ b/engine/crates/xerj-server/src/brain.rs
@@ -379,6 +379,10 @@ fn run(cfg: BrainCfg) -> Result<i32> {
\x20 documents and will pick up links on the next run:"
);
println!(" → {console_url}");
+ println!(
+ "{}",
+ share_hint(&cfg.root, &cfg.url, cfg.data_dir.as_deref())
+ );
if let Some(link) = &setup_link {
println!(" one-time passkey setup (open once, valid 30 min):");
println!(" → {link}");
@@ -407,6 +411,12 @@ fn run(cfg: BrainCfg) -> Result<i32> {
// to say the same thing. Plain ASCII, one line, matching the surrounding
// human-facing summary; nothing here asks anyone (or any agent) to write
// praise into a commit message, comment, or PR.
+ // One line, so the feature is discoverable at the moment it is useful:
+ // the folder has just been indexed and the owner is looking at the result.
+ println!(
+ "{}",
+ share_hint(&cfg.root, &cfg.url, cfg.data_dir.as_deref())
+ );
println!(" if this saved you time, tell a teammate — that is how it spreads.");
if let Some(link) = &setup_link {
println!(" one-time passkey setup (open once, valid 30 min):");
@@ -548,6 +558,36 @@ fn mcp_env_with(url: &str, api_key: Option<&str>, env_key: Option<&str>) -> Stri
}
}
+/// The one-line pointer at `xerj share`. Carries `--url` and `--data-dir`
+/// only when the run used non-default ones, so the printed command works as
+/// pasted: `xerj share` finds the admin key in the data dir, and without the
+/// flag it would look in `~/.xerj/brain` — another node's key, or none.
+///
+/// Every argument is one shell word (`share::sh_quote`): a folder called
+/// `case files` used to come out as two arguments, and the "exact command"
+/// failed with `unknown argument: files`. The parenthesis says what is true in
+/// every mode — the documents stay here. It used to say "nothing is uploaded",
+/// which reads as "nobody else sees the traffic"; with `--tunnel` Cloudflare
+/// does, and `xerj share` says so when it prints the link.
+fn share_hint(root: &Path, url: &str, data_dir: Option<&Path>) -> String {
+ use crate::share::sh_quote;
+ let mut args = String::new();
+ if url != "http://localhost:9200" {
+ args.push_str(&format!(" --url {}", sh_quote(url)));
+ }
+ if let Some(dir) = data_dir {
+ args.push_str(&format!(
+ " --data-dir {}",
+ sh_quote(&dir.display().to_string())
+ ));
+ }
+ format!(
+ " share it: xerj share {}{args} (read-only link + passcode for one person; \
+ the documents stay on this machine)",
+ sh_quote(&root.display().to_string())
+ )
+}
+
fn index_cfg(cfg: &BrainCfg, brain: &str, api_key: Option<String>) -> IndexCfg {
// Same resource policy as `xerj autoindex` itself — `xerj brain` composes
// autoindex, so it must not invent its own worker counts (#240).
@@ -793,6 +833,59 @@ fn open_browser(url: &str) -> Result<()> {
mod tests {
use super::*;
+ #[test]
+ fn share_hint_is_one_pasteable_line() {
+ let hint = share_hint(Path::new("/home/u/notes"), "http://localhost:9200", None);
+ assert_eq!(hint.lines().count(), 1, "{hint}");
+ assert!(hint.contains("xerj share /home/u/notes "), "{hint}");
+ assert!(
+ !hint.contains("--url"),
+ "default url is not repeated: {hint}"
+ );
+ assert!(
+ !hint.contains("--data-dir"),
+ "default data dir is not repeated: {hint}"
+ );
+ let hint = share_hint(Path::new("notes"), "http://localhost:9510", None);
+ assert!(
+ hint.contains("xerj share notes --url http://localhost:9510 "),
+ "{hint}"
+ );
+ // A non-default data dir is where the admin key is; without it the
+ // pasted command looks in ~/.xerj/brain and fails (or finds another
+ // node's key).
+ let hint = share_hint(
+ Path::new("notes"),
+ "http://localhost:9510",
+ Some(Path::new("/srv/xerj")),
+ );
+ assert!(
+ hint.contains("xerj share notes --url http://localhost:9510 --data-dir /srv/xerj "),
+ "{hint}"
+ );
+ assert_eq!(hint.lines().count(), 1, "{hint}");
+ }
+
+ /// Review of PR #947: `xerj brain "case files"` printed a share command
+ /// that failed when pasted (`unknown argument: files`).
+ #[test]
+ #[cfg(not(windows))]
+ fn share_hint_quotes_a_folder_with_a_space() {
+ let hint = share_hint(
+ Path::new("/home/u/case files"),
+ "http://localhost:9510",
+ Some(Path::new("/srv/my data")),
+ );
+ assert!(
+ hint.contains(
+ "xerj share '/home/u/case files' --url http://localhost:9510 --data-dir '/srv/my data' "
+ ),
+ "{hint}"
+ );
+ assert!(hint.contains("stay on this machine"), "{hint}");
+ assert!(!hint.contains("nothing is uploaded"), "{hint}");
+ }
+
/// ONBOARDING-401-REPRO.md §3: `brain` resolves a credential itself (from
/// `<data-dir>/admin.key` when nothing else supplies one) and then printed
/// an `XERJ_URL=… xerj-mcp` hint with no credential in it — a command that
diff --git a/engine/crates/xerj-server/src/grpc.rs b/engine/crates/xerj-server/src/grpc.rs
index 4f087a2f0..c4e5bf015 100644
--- a/engine/crates/xerj-server/src/grpc.rs
+++ b/engine/crates/xerj-server/src/grpc.rs
@@ -1164,4 +1164,233 @@ mod tests {
let _ = tx.send(());
let _ = server.await;
}
+
+ /// A share-link guest key on the gRPC listener.
+ ///
+ /// The guest route allow-list (`authz::guest_route_allowed`) lives in the
+ /// HTTP middleware; this listener has no route list, only the per-index
+ /// decision every RPC makes. Reading the code says that is a strict subset
+ /// of what a guest gets over HTTP — read on the shared index, nothing on
+ /// any other, no write anywhere — and until the review of PR #947 nothing
+ /// exercised it. This drives the real interceptor and the real RPC
+ /// handlers, in process: no socket, so no port.
+ ///
+ /// `bulk_index` is not called here — its argument is a tonic `Streaming`,
+ /// which only a transport can build. It authorizes each item with the same
+ /// `authorize(…, WriteIndex)` call that `index` makes.
+ #[tokio::test]
+ // `as_caller` returns the interceptor's `tonic::Status`; same rationale as
+ // the allow on `authorize`.
+ #[allow(clippy::result_large_err)]
+ async fn a_share_guest_key_reads_its_index_over_grpc_and_nothing_else() {
+ use axum::extract::State;
+ use axum::Json;
+ use tonic::service::Interceptor;
+ use tonic::Code;
+
+ let dir = TempDir::new().unwrap();
+ let admin = "grpc-share-guest-admin";
+ let state = app_state_with_auth(&dir, admin);
+ let svc = GrpcService::new(state.clone());
+
+ // Authenticate the way the listener does, then hand the principal to
+ // the typed request the way tonic hands over its extensions.
+ let as_caller = |authorization: &str| -> Result<Principal, Status> {
+ let mut bare = tonic::Request::new(());
+ bare.metadata_mut()
+ .insert("authorization", authorization.parse().unwrap());
+ let passed = GrpcAuth {
+ state: state.clone(),
+ }
+ .call(bare)?;
+ Ok(passed
+ .extensions()
+ .get::<Principal>()
+ .cloned()
+ .expect("the interceptor plants the principal"))
+ };
+ fn with<T>(message: T, principal: &Principal) -> tonic::Request<T> {
+ let mut request = tonic::Request::new(message);
+ request.extensions_mut().insert(principal.clone());
+ request
+ }
+ async fn body_of(resp: axum::response::Response) -> serde_json::Value {
+ let bytes = axum::body::to_bytes(resp.into_body(), 1 << 20)
+ .await
+ .expect("body");
+ serde_json::from_slice(&bytes).expect("json")
+ }
+
+ let owner = as_caller(&format!("ApiKey {admin}")).expect("admin key");
+ for (index, id, source) in [
+ (
+ "casefile",
+ "1",
+ r#"{"body":"the deposit was not returned"}"#,
+ ),
+ (
+ "private-diary",
+ "1",
+ r#"{"body":"nobody else should read this"}"#,
+ ),
+ ] {
+ let done = svc
+ .index(with(
+ pb::IndexRequest {
+ index: index.into(),
+ id: id.into(),
+ source_json: source.into(),
+ },
+ &owner,
+ ))
+ .await
+ .expect("owner indexes")
+ .into_inner();
+ assert_eq!(done.result, "created");
+ }
+
+ // A real share, claimed the way the guest page claims it.
+ let created = body_of(
+ xerj_api::share::create_share(
+ State(state.clone()),
+ Principal::Superuser,
+ Some(Json(serde_json::json!({"index": "casefile"}))),
+ )
+ .await,
+ )
+ .await;
+ let claimed = body_of(
+ xerj_api::share::claim_share(
+ State(state.clone()),
+ xerj_api::share::ClaimSource("grpc-test".into()),
+ Some(Json(serde_json::json!({
+ "id": created["share_id"], "passcode": created["passcode"],
+ }))),
+ )
+ .await,
+ )
+ .await;
+ let guest_key = claimed["api_key"].as_str().expect("a guest key");
+ let guest = as_caller(&format!("ApiKey {guest_key}")).expect("guest key authenticates");
+ assert!(guest.is_share_guest(), "{guest:?}");
+
+ // ── what the guest holds ────────────────────────────────────────────
+ let found = svc
+ .search(with(
+ pb::SearchRequest {
+ index: "casefile".into(),
+ query_json: String::new(),
+ size: 10,
+ from: 0,
+ },
+ &guest,
+ ))
+ .await
+ .expect("a guest searches the shared index")
+ .into_inner();
+ assert_eq!(found.total_hits, 1, "{found:?}");
+ let got = svc
+ .get_document(with(
+ pb::GetRequest {
+ index: "casefile".into(),
+ id: "1".into(),
+ },
+ &guest,
+ ))
+ .await
+ .expect("a guest reads a shared document")
+ .into_inner();
+ assert!(got.found);
+
+ // ── every other index, by name and by pattern ───────────────────────
+ for index in [
+ "private-diary",
+ "*",
+ "_all",
+ "case*",
+ ".xerj_audit",
+ ".xerj-memory-case-edges",
+ "autoindex-catalog",
+ ] {
+ let e = svc
+ .search(with(
+ pb::SearchRequest {
+ index: index.into(),
+ query_json: String::new(),
+ size: 10,
+ from: 0,
+ },
+ &guest,
+ ))
+ .await
+ .expect_err("a guest must not search another index");
+ assert_eq!(e.code(), Code::PermissionDenied, "search [{index}]: {e:?}");
+ assert!(!e.message().contains("nobody else"), "{e:?}");
+ let e = svc
+ .get_document(with(
+ pb::GetRequest {
+ index: index.into(),
+ id: "1".into(),
+ },
+ &guest,
+ ))
+ .await
+ .expect_err("a guest must not read another index");
+ assert_eq!(e.code(), Code::PermissionDenied, "get [{index}]: {e:?}");
+ }
+
+ // ── no write, not even to the shared index ──────────────────────────
+ for index in ["casefile", "private-diary", "brand-new"] {
+ let e = svc
+ .index(with(
+ pb::IndexRequest {
+ index: index.into(),
+ id: "9".into(),
+ source_json: r#"{"body":"tampered"}"#.into(),
+ },
+ &guest,
+ ))
+ .await
+ .expect_err("a guest must not write");
+ assert_eq!(e.code(), Code::PermissionDenied, "index [{index}]: {e:?}");
+ let e = svc
+ .delete_document(with(
+ pb::DeleteRequest {
+ index: index.into(),
+ id: "1".into(),
+ },
+ &guest,
+ ))
+ .await
+ .expect_err("a guest must not delete");
+ assert_eq!(e.code(), Code::PermissionDenied, "delete [{index}]: {e:?}");
+ }
+ let still = svc
+ .get_document(with(
+ pb::GetRequest {
+ index: "casefile".into(),
+ id: "1".into(),
+ },
+ &owner,
+ ))
+ .await
+ .expect("owner reads")
+ .into_inner();
+ assert!(still.found && still.source_json.contains("deposit"));
+
+ // ── a revoke ends it here too ───────────────────────────────────────
+ let handle = created["handle"].as_str().expect("handle").to_string();
+ let revoked = body_of(
+ xerj_api::share::revoke_share(
+ State(state.clone()),
+ Principal::Superuser,
+ axum::extract::Path(handle),
+ )
+ .await,
+ )
+ .await;
+ assert_eq!(revoked["keys_invalidated"], 1, "{revoked}");
+ let e = as_caller(&format!("ApiKey {guest_key}")).expect_err("a revoked guest key");
+ assert_eq!(e.code(), Code::Unauthenticated, "{e:?}");
+ }
}
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rs
index 17107c539..cd7812c42 100644
--- a/engine/crates/xerj-server/src/main.rs
+++ b/engine/crates/xerj-server/src/main.rs
@@ -97,6 +97,7 @@ mod brain;
mod debug_profiling;
mod grpc;
mod ingest_memory_trace;
+mod share;
// ─────────────────────────────────────────────────────────────────────────────
// CLI
@@ -208,6 +209,9 @@ fn help_text(feedback: bool) -> String {
index --help)\n\
xerj brain <folder> index + browse in one command (see xerj\n\
brain --help)\n\
+ xerj share <index|folder> give someone read-only search over one\n\
+ index: link + passcode + expiry (see xerj\n\
+ share --help)\n\
xerj feedback [OPTIONS] draft the agent field report (and open its\n\
PR) — see xerj feedback --help\n\
\n\
@@ -1980,6 +1984,17 @@ async fn async_main() -> Result<()> {
.unwrap_or(1);
std::process::exit(code);
}
+ if matches!(argv1.as_deref(), Some("share")) {
+ // Share one indexed corpus as a link + passcode. A thin client of the
+ // node's own `/_share` API; with `--tunnel` it also supervises a
+ // `cloudflared` child until Ctrl-C. Synchronous internally — it runs on
+ // a blocking thread like `brain`, and borrows this runtime only for
+ // the portable Ctrl-C future.
+ let code = tokio::task::spawn_blocking(share::run_cli)
+ .await
+ .unwrap_or(1);
+ std::process::exit(code);
+ }
if matches!(argv1.as_deref(), Some("feedback")) {
// Draft the agent field report XERJ asks every agent to file, and
// optionally open its pull request. Pure ES-compat client + local
diff --git a/engine/crates/xerj-server/src/share.rs b/engine/crates/xerj-server/src/share.rs
new file mode 100644
index 000000000..829f5ee21
--- /dev/null
+++ b/engine/crates/xerj-server/src/share.rs
@@ -0,0 +1,2278 @@
+//! `xerj share <index|folder>` — hand one indexed corpus to someone who has
+//! nothing else: a link, a passcode, an expiry.
+//!
+//! This is the command-line face of `xerj-api::share` (`/_share`). It mints
+//! nothing itself: the node creates the share, stores only digests, and hands
+//! back the share id and passcode exactly once; this command formats them into
+//! something a person can send.
+//!
+//! Composition, not reimplementation — the same rule `xerj brain` follows:
+//! - **credentials** are resolved the way `xerj brain` resolves them:
+//! `--api-key`, then `XERJ_API_KEY`, then `<data-dir>/admin.key`. `/_share`
+//! is superuser-only, so the key has to be the node's admin key;
+//! - a **folder** argument resolves to what `xerj brain <folder>` built for it:
+//! the brain named by `xerj_autoindex::derive_brain_name`, and the dataset
+//! indices that brain's meta document lists (`nodes_index`);
+//! - `--tunnel` runs the operator's own `cloudflared` as a child process and
+//! reads the public hostname off its log. No tunnel code lives here.
+//!
+//! ## What the owner is told about the road to the guest
+//!
+//! The documents never leave this machine as a copy — that sentence is true in
+//! every mode. *Who can read the traffic* is not the same in every mode, and
+//! the first cut said "the guest's browser reads from this node" under
+//! `--tunnel` too, where the browser talks to Cloudflare, which ends TLS and
+//! can read the passcode, the guest key and every document opened (review of
+//! PR #947). [`Reach`] is how the link gets to this node, and
+//! [`render_created`] says what that means at the moment the owner is about to
+//! send it — not only in the docs.
+//!
+//! ## The one refusal
+//!
+//! A node running with authentication off (`--insecure`, `auth.enabled =
+//! false`) treats every request as the superuser. A "scoped, read-only" guest
+//! key on such a node restricts nothing — the guest, and anyone else who can
+//! reach the port, can already read and delete everything without it. So this
+//! command refuses, in words, rather than print a link that promises a
+//! boundary the node is not enforcing. The server refuses the same request
+//! with `409`; the client-side probe exists so the refusal happens *before* a
+//! tunnel is opened.
+
+use anyhow::{anyhow, bail, Context, Result};
+use serde_json::{json, Value};
+use std::io::{BufRead, BufReader};
+use std::path::{Path, PathBuf};
+use std::process::{Child, Command, Stdio};
+use std::sync::mpsc;
+use std::time::Duration;
+
+use xerj_autoindex::detect;
+use xerj_autoindex::esclient::Es;
+
+/// Where the guest page lives on the node. Must match the `url_path` the
+/// server returns (`xerj-api::share::create_share`); the server's value wins
+/// when it sends one.
+const GUEST_PAGE_PATH: &str = "/_xerj-console/share";
+/// Where a node listens unless told otherwise — the same default `xerj brain`
+/// uses.
+const DEFAULT_URL: &str = "http://localhost:9200";
+/// How long `cloudflared` gets to print its hostname.
+const TUNNEL_URL_TIMEOUT: Duration = Duration::from_secs(45);
+/// After the hostname is known, how long to wait for the first edge
+/// connection before printing the link anyway.
+const TUNNEL_CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
+
+pub fn run_cli() -> i32 {
+ let args: Vec<String> = std::env::args().skip(2).collect();
+ let cfg = match parse(args, std::env::var("XERJ_API_KEY").ok()) {
+ Ok(Some(cfg)) => cfg,
+ Ok(None) => {
+ print_help();
+ return 0;
+ }
+ Err(e) => {
+ eprintln!("error: {e}\n");
+ print_help();
+ return 2;
+ }
+ };
+ match run(cfg) {
+ Ok(code) => code,
+ Err(e) => {
+ eprintln!("error: {e:#}");
+ 1
+ }
+ }
+}
+
+pub fn print_help() {
+ println!("{}", help_text(xerj_common::feedback::enabled()));
+}
+
+pub fn help_text(feedback: bool) -> String {
+ format!(
+ "xerj share — give someone read-only search over one indexed folder: a link, a\n\
+ passcode, an expiry\n\
+ \n\
+ The guest opens the link, types the passcode, and gets a reading room over\n\
+ that one index: search, highlighted snippets, a document view. Read-only.\n\
+ The documents stay on this machine: XERJ copies them nowhere, and this node\n\
+ answers the guest's browser. With --tunnel that traffic passes through\n\
+ Cloudflare, which can read it, and what Cloudflare keeps of what it carries\n\
+ is between you and Cloudflare (see --tunnel). Revoke any time.\n\
+ \n\
+ {}\
+ USAGE:\n\
+ xerj share <index|folder> [OPTIONS] create a share\n\
+ xerj share --list every share on this node\n\
+ xerj share --revoke <handle> end one (kills its guest keys)\n\
+ \n\
+ <index|folder>: an index name (`ax-notes`, or `a,b`), or the folder you gave\n\
+ `xerj brain` — that resolves to the brain and indices it built.\n\
+ \n\
+ OPTIONS:\n\
+ --expires <D> lifetime: 30m, 24h, 7d … (default {}; longest 30d)\n\
+ --max-claims <N> how many times the link can be opened (default {},\n\
+ most {}). Each open mints its own guest key. One\n\
+ open is one browser tab: a guest who closes the tab\n\
+ needs another open to come back — give a few to\n\
+ someone who will read over several days\n\
+ --passcode <CODE> choose the passcode ({}–{} chars). Default: a generated\n\
+ xxxx-xxxx. A passcode typed here lands in your shell\n\
+ history; the generated one does not\n\
+ --label <TEXT> what the guest sees as the title (e.g. \"for Dana\")\n\
+ --brain <NAME> also share this brain's links (a folder argument sets\n\
+ this for you)\n\
+ --index treat the argument as an index name even when a folder\n\
+ of that name exists here\n\
+ --tunnel open a temporary public address with `cloudflared`, print\n\
+ the full guest link, run until Ctrl-C, then close the\n\
+ tunnel and revoke the share. Without `cloudflared`\n\
+ installed you get install steps and the local link.\n\
+ The tunnel is Cloudflare's: it ends TLS there, so\n\
+ Cloudflare can read what passes through — the\n\
+ passcode, the guest's key, the searches and every\n\
+ document the guest opens.\n\
+ If that is not acceptable, use --public-url with\n\
+ your own certificate\n\
+ --keep with --tunnel: leave the share active after Ctrl-C\n\
+ --public-url <U> the https:// address this node is reachable at (your own\n\
+ hostname or reverse proxy); the printed link uses it.\n\
+ http:// is accepted with a warning: the passcode and\n\
+ the guest's key would cross the network unencrypted\n\
+ --url <U> the node, scheme included (default http://localhost:9200)\n\
+ --data-dir <PATH> where the node's admin.key is (default ~/.xerj/brain)\n\
+ --api-key <K> the node's ADMIN key (or env XERJ_API_KEY). Shares can\n\
+ only be managed with the admin key\n\
+ --json machine-readable output\n\
+ --disable-feedback do not print the feedback invitation above (env\n\
+ XERJ_DISABLE_FEEDBACK=true)\n\
+ --help, -h this help\n\
+ \n\
+ REFUSES against a node running with --insecure / auth off: every request is\n\
+ already the superuser there, so a read-only guest key would restrict nothing.\n\
+ \n\
+ EXIT CODES: 0 ok; 1 refused or failed; 2 usage; 130 interrupted before the tunnel\n\
+ was up (nothing was shared)\n",
+ xerj_common::feedback::block(feedback),
+ xerj_api::share::DEFAULT_EXPIRES_IN,
+ xerj_api::share::DEFAULT_MAX_CLAIMS,
+ xerj_api::share::MAX_MAX_CLAIMS,
+ xerj_api::share::MIN_PASSCODE_CHARS,
+ xerj_api::share::MAX_PASSCODE_CHARS,
+ )
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Arguments
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Common {
+ pub url: String,
+ pub data_dir: Option<PathBuf>,
+ pub api_key: Option<String>,
+ pub json: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct CreateCfg {
+ pub target: String,
+ pub force_index: bool,
+ pub brain: Option<String>,
+ pub expires: Option<String>,
+ pub max_claims: Option<u32>,
+ pub passcode: Option<String>,
+ pub label: Option<String>,
+ pub tunnel: bool,
+ pub keep: bool,
+ pub public_url: Option<String>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Action {
+ Create(CreateCfg),
+ List,
+ Revoke(String),
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ShareCfg {
+ pub common: Common,
+ pub action: Action,
+}
+
+/// `env_key` is the ambient `XERJ_API_KEY`, passed in so tests do not depend
+/// on (or race over) the process environment.
+fn parse(args: Vec<String>, env_key: Option<String>) -> Result<Option<ShareCfg>, String> {
+ let mut it = args.into_iter();
+ let mut target: Option<String> = None;
+ let mut list = false;
+ let mut revoke: Option<String> = None;
+ let mut url = DEFAULT_URL.to_string();
+ let mut data_dir: Option<PathBuf> = None;
+ let mut api_key = env_key.filter(|s| !s.is_empty());
+ let mut json = false;
+ let mut create = CreateCfg {
+ target: String::new(),
+ force_index: false,
+ brain: None,
+ expires: None,
+ max_claims: None,
+ passcode: None,
+ label: None,
+ tunnel: false,
+ keep: false,
+ public_url: None,
+ };
+ // Which create-only flags were seen, so `--list --expires 1h` is an error
+ // rather than a silently ignored flag.
+ let mut create_flags: Vec<&'static str> = Vec::new();
+
+ while let Some(arg) = it.next() {
+ match arg.as_str() {
+ "--list" => list = true,
+ "--revoke" => revoke = Some(it.next().ok_or("--revoke needs a share handle")?),
+ "--expires" => {
+ let spec = it.next().ok_or("--expires needs a value like 24h")?;
+ let ms = xerj_api::share::parse_expires_in(&spec).ok_or_else(|| {
+ format!("--expires {spec}: use a number and a unit — 30m, 24h, 7d")
+ })?;
+ if !(xerj_api::share::MIN_EXPIRES_MS..=xerj_api::share::MAX_EXPIRES_MS)
+ .contains(&ms)
+ {
+ return Err(format!("--expires {spec}: must be between 1s and 30d"));
+ }
+ create.expires = Some(spec);
+ create_flags.push("--expires");
+ }
+ "--max-claims" => {
+ let raw = it.next().ok_or("--max-claims needs a number")?;
+ let n: u32 = raw
+ .parse()
+ .map_err(|_| format!("--max-claims {raw}: not a number"))?;
+ if !(1..=xerj_api::share::MAX_MAX_CLAIMS).contains(&n) {
+ return Err(format!(
+ "--max-claims {n}: must be from 1 to {}",
+ xerj_api::share::MAX_MAX_CLAIMS
+ ));
+ }
+ create.max_claims = Some(n);
+ create_flags.push("--max-claims");
+ }
+ "--passcode" => {
+ let code = it.next().ok_or("--passcode needs a value")?;
+ let n = code.trim().chars().count();
+ if !(xerj_api::share::MIN_PASSCODE_CHARS..=xerj_api::share::MAX_PASSCODE_CHARS)
+ .contains(&n)
+ {
+ return Err(format!(
+ "--passcode must be {}–{} characters",
+ xerj_api::share::MIN_PASSCODE_CHARS,
+ xerj_api::share::MAX_PASSCODE_CHARS
+ ));
+ }
+ create.passcode = Some(code.trim().to_string());
+ create_flags.push("--passcode");
+ }
+ "--label" => {
+ let label = it.next().ok_or("--label needs a value")?;
+ if label.chars().count() > xerj_api::share::MAX_LABEL_CHARS {
+ return Err(format!(
+ "--label must be at most {} characters",
+ xerj_api::share::MAX_LABEL_CHARS
+ ));
+ }
+ create.label = Some(label);
+ create_flags.push("--label");
+ }
+ "--brain" => {
+ let name = it.next().ok_or("--brain needs a value")?;
+ detect::validate_brain(&name)
+ .map_err(|reason| format!("--brain {name}: {reason}"))?;
+ create.brain = Some(name);
+ create_flags.push("--brain");
+ }
+ "--index" => {
+ create.force_index = true;
+ create_flags.push("--index");
+ }
+ "--tunnel" => {
+ create.tunnel = true;
+ create_flags.push("--tunnel");
+ }
+ "--keep" => {
+ create.keep = true;
+ create_flags.push("--keep");
+ }
+ "--public-url" => {
+ let u = it.next().ok_or("--public-url needs a value")?;
+ if !(u.starts_with("https://") || u.starts_with("http://")) {
+ return Err(format!(
+ "--public-url {u}: must start with https:// (or http://)"
+ ));
+ }
+ create.public_url = Some(u.trim_end_matches('/').to_string());
+ create_flags.push("--public-url");
+ }
+ "--url" => {
+ // Without a scheme the HTTP client fails before it connects,
+ // and that used to be reported as "no xerj node answers" while
+ // the node was up (review of PR #947).
+ let u = it.next().ok_or("--url needs a value")?;
+ if !(u.starts_with("http://") || u.starts_with("https://")) {
+ return Err(format!(
+ "--url {u}: include the scheme — for example http://{u}"
+ ));
+ }
+ url = u;
+ }
+ "--data-dir" => {
+ data_dir = Some(PathBuf::from(it.next().ok_or("--data-dir needs a value")?))
+ }
+ "--api-key" => api_key = Some(it.next().ok_or("--api-key needs a value")?),
+ "--json" => json = true,
+ // Read out of band by `xerj_common::feedback`; accepted here so it
+ // is not "unknown".
+ xerj_common::feedback::DISABLE_FLAG => {}
+ "--help" | "-h" => return Ok(None),
+ other if !other.starts_with('-') && target.is_none() => {
+ target = Some(other.to_string())
+ }
+ other => return Err(format!("unknown argument: {other}")),
+ }
+ }
+
+ let common = Common {
+ url: url.trim_end_matches('/').to_string(),
+ data_dir,
+ api_key,
+ json,
+ };
+
+ let picked = [list, revoke.is_some(), target.is_some()]
+ .iter()
+ .filter(|b| **b)
+ .count();
+ if picked == 0 {
+ return Ok(None); // nothing asked for → help, like `xerj brain`
+ }
+ if picked > 1 {
+ return Err("choose one: a target to share, --list, or --revoke <handle>".into());
+ }
+ if (list || revoke.is_some()) && !create_flags.is_empty() {
+ return Err(format!(
+ "{} only applies when creating a share",
+ create_flags.join(", ")
+ ));
+ }
+ if create.keep && !create.tunnel {
+ return Err("--keep only applies with --tunnel".into());
+ }
+ if create.tunnel && create.public_url.is_some() {
+ return Err(
+ "--tunnel and --public-url are two answers to the same question; pick one".into(),
+ );
+ }
+
+ let action = if list {
+ Action::List
+ } else if let Some(handle) = revoke {
+ let handle = handle.trim().to_string();
+ // Exactly the 12-hex handle. The 32-hex share id from a link would
+ // work on the server, but it would travel in the DELETE's request
+ // path, and the docs say the CLI never puts a share id in a URL.
+ let hex = handle.chars().all(|c| c.is_ascii_hexdigit());
+ if handle.len() == 32 && hex {
+ // Not echoed: the error line may end up in a terminal log.
+ return Err(
+ "--revoke <share id>: that is the share id from the link, which is \
+ never sent in a URL — revoke by the handle `xerj share --list` prints"
+ .into(),
+ );
+ }
+ if handle.len() != 12 || !hex {
+ return Err(format!(
+ "--revoke {handle}: a share handle is the 12 hex characters `xerj share \
+ --list` prints"
+ ));
+ }
+ Action::Revoke(handle)
+ } else {
+ create.target = target.unwrap_or_default();
+ Action::Create(create)
+ };
+ Ok(Some(ShareCfg { common, action }))
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Pure helpers (unit-tested)
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// What the positional argument names.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Target {
+ /// One or more concrete index names.
+ Indices(Vec<String>),
+ /// A folder `xerj brain` indexed.
+ Folder(PathBuf),
+}
+
+/// Decide what `arg` names. `is_dir` is injected so the rule is testable
+/// without a filesystem.
+///
+/// An existing directory wins unless `--index` was passed: the command is
+/// documented as "share the folder you gave `xerj brain`", and printing what
+/// the folder resolved to (see [`run`]) makes a wrong guess visible before
+/// anything is sent to anyone. Something that *looks* like a path but is not a
+/// directory is an error, never an index name — `xerj share ./nots` must not
+/// turn into a request for an index called `./nots`.
+fn classify_target(
+ arg: &str,
+ force_index: bool,
+ is_dir: impl Fn(&Path) -> bool,
+) -> Result<Target, String> {
+ let arg = arg.trim();
+ if arg.is_empty() {
+ return Err("name an index or a folder to share".into());
+ }
+ let pathish =
+ arg.contains('/') || arg.contains('\\') || arg.starts_with('.') || arg.starts_with('~');
+ if force_index {
+ if pathish {
+ return Err(format!("--index {arg}: that is a path, not an index name"));
+ }
+ } else {
+ if is_dir(Path::new(arg)) {
+ return Ok(Target::Folder(PathBuf::from(arg)));
+ }
+ if pathish {
+ return Err(format!(
+ "{arg} is not a folder here. Pass the folder you gave `xerj brain`, or an \
+ index name (see `xerj autoindex map`)"
+ ));
+ }
+ }
+ let indices: Vec<String> = arg
+ .split(',')
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(String::from)
+ .collect();
+ if indices.is_empty() {
+ return Err("name an index or a folder to share".into());
+ }
+ Ok(Target::Indices(indices))
+}
+
+/// How the printed link reaches this node. It decides what the owner is told
+/// about who else can read the traffic — see the module docs.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Reach {
+ /// The node's own URL, and the host is loopback: only this machine.
+ Loopback,
+ /// The node's own URL, and the host is NOT loopback — a LAN or public
+ /// address. The first cut called this "only this machine can reach" too,
+ /// because it looked at the flags and not at the URL.
+ Direct,
+ /// `--public-url`: the owner's hostname or reverse proxy.
+ PublicUrl,
+ /// `--tunnel`: a Cloudflare quick tunnel, which terminates TLS.
+ CloudflareTunnel,
+}
+
+impl Reach {
+ /// The `via` field of `--json` output.
+ fn as_str(self) -> &'static str {
+ match self {
+ Reach::Loopback => "loopback",
+ Reach::Direct => "direct",
+ Reach::PublicUrl => "public_url",
+ Reach::CloudflareTunnel => "cloudflare_tunnel",
+ }
+ }
+}
+
+/// What a quick tunnel means for the traffic, in the words the owner reads
+/// before sending the link. One constant: the human banner, `--json`
+/// (`transit_notice`) and the tests all use it.
+pub const CLOUDFLARE_TRANSIT_NOTICE: &str =
+ "this link goes through Cloudflare. A quick tunnel ends TLS at Cloudflare, so Cloudflare \
+ can read everything that passes through it: the passcode, the guest's key, the searches \
+ and every document the guest opens. If that is not acceptable, \
+ publish the node under your own certificate and use --public-url instead";
+
+/// The host part of an `http(s)://host[:port]/…` URL, brackets kept.
+fn url_host(url: &str) -> Option<&str> {
+ let rest = url
+ .strip_prefix("http://")
+ .or_else(|| url.strip_prefix("https://"))?;
+ let hostport = rest.split(['/', '?', '#']).next().unwrap_or(rest);
+ let host = match hostport.strip_prefix('[') {
+ // [::1]:9200
+ Some(v6) => v6.split(']').next().unwrap_or(v6),
+ None => hostport.rsplit_once(':').map_or(hostport, |(h, _)| h),
+ };
+ (!host.is_empty()).then_some(host)
+}
+
+/// Does `url` name this machine and nothing else?
+fn is_loopback_url(url: &str) -> bool {
+ match url_host(url) {
+ Some("localhost") => true,
+ Some(host) => host
+ .parse::<std::net::IpAddr>()
+ .is_ok_and(|ip| ip.is_loopback()),
+ None => false,
+ }
+}
+
+/// How the link for this create reaches the node.
+fn reach_of(tunnel_up: bool, public_url: Option<&str>, node_url: &str) -> Reach {
+ if tunnel_up {
+ Reach::CloudflareTunnel
+ } else if public_url.is_some() {
+ Reach::PublicUrl
+ } else if is_loopback_url(node_url) {
+ Reach::Loopback
+ } else {
+ Reach::Direct
+ }
+}
+
+/// The link a guest opens. The share id rides in the **fragment**: a browser
+/// never sends a fragment to the server, so the page request carries no id and
+/// neither does any `Referer`. The page's own script then sends the id in the
+/// **body** of the claim `POST` (`/_share/claim`) — never in a path, which is
+/// what an access log, a reverse proxy and a tunnel's edge would record.
+pub fn guest_link(base_url: &str, url_path: Option<&str>, share_id: &str) -> String {
+ let base = base_url.trim_end_matches('/');
+ match url_path {
+ // The node's own path wins — but only a console path whose fragment is
+ // exactly this share id and that carries no query string. Anything
+ // else falls back to the path this build knows.
+ Some(p)
+ if p.starts_with("/_xerj-console/")
+ && !p.contains('?')
+ && p.split_once('#').map(|(_, frag)| frag) == Some(share_id) =>
+ {
+ format!("{base}{p}")
+ }
+ _ => format!("{base}{GUEST_PAGE_PATH}#{share_id}"),
+ }
+}
+
+/// Pull the public hostname out of one line of `cloudflared` output. The
+/// banner wraps it in a box (`| https://x-y-z.trycloudflare.com |`); the
+/// URL itself has no whitespace. Only a `trycloudflare.com` host counts —
+/// the log also mentions `https://www.cloudflare.com/website-terms/` and
+/// `https://developers.cloudflare.com/…`, which are not tunnels.
+fn parse_tunnel_url(line: &str) -> Option<String> {
+ let mut rest = line;
+ while let Some(at) = rest.find("https://") {
+ let tail = &rest[at..];
+ let end = tail
+ .find(|c: char| c.is_whitespace() || c == '|' || c == '"' || c == '\'')
+ .unwrap_or(tail.len());
+ let url = tail[..end].trim_end_matches(['/', '.', ',']);
+ let host = url.trim_start_matches("https://");
+ let host = host.split('/').next().unwrap_or(host);
+ if host.ends_with(".trycloudflare.com")
+ && host.len() > ".trycloudflare.com".len()
+ && host
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.')
+ {
+ return Some(format!("https://{host}"));
+ }
+ rest = &tail[8..];
+ }
+ None
+}
+
+/// Has `cloudflared` told us an edge connection is up?
+fn tunnel_line_means_connected(line: &str) -> bool {
+ line.contains("Registered tunnel connection") || line.contains("Connection registered")
+}
+
+/// (host, port) of a plain-http node URL — the only kind `--tunnel` fronts.
+fn local_http_origin(url: &str) -> Result<(String, u16), String> {
+ let Some(rest) = url.strip_prefix("http://") else {
+ return Err(format!(
+ "--tunnel fronts a plain-http node on this machine (the default); {url} is not \
+ one. For a TLS node, run your own `cloudflared tunnel --url {url} \
+ --no-tls-verify` and pass its address as --public-url"
+ ));
+ };
+ let hostport = rest.split('/').next().unwrap_or(rest);
+ let (host, port) = match hostport.rsplit_once(':') {
+ Some((h, p)) => (
+ h.to_string(),
+ p.parse::<u16>()
+ .map_err(|_| format!("invalid port in --url {url}"))?,
+ ),
+ None => (hostport.to_string(), 9200),
+ };
+ if !matches!(host.as_str(), "localhost" | "127.0.0.1" | "[::1]" | "::1") {
+ return Err(format!(
+ "--tunnel exposes a node on THIS machine; {url} is somewhere else. Run \
+ `xerj share --tunnel` on the machine that holds the data"
+ ));
+ }
+ Ok((host, port))
+}
+
+/// Exact install steps, per platform. Printed instead of failing when
+/// `cloudflared` is absent.
+fn cloudflared_install_help() -> &'static str {
+ if cfg!(target_os = "macos") {
+ " install it: brew install cloudflared"
+ } else if cfg!(target_os = "windows") {
+ " install it: winget install --id Cloudflare.cloudflared"
+ } else {
+ " install it (no root needed):\n\
+ \x20 mkdir -p ~/.local/bin && curl -fsSL -o ~/.local/bin/cloudflared \\\n\
+ \x20 https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64 \\\n\
+ \x20 && chmod +x ~/.local/bin/cloudflared\n\
+ \x20 (arm64: replace amd64 with arm64; Debian/Ubuntu/RHEL packages:\n\
+ \x20 https://pkg.cloudflare.com)"
+ }
+}
+
+/// Find `cloudflared`: `XERJ_CLOUDFLARED`, then `PATH`, then `~/.local/bin`
+/// (where the install steps above put it, and which a non-login shell often
+/// does not have on `PATH`).
+fn find_cloudflared() -> Option<PathBuf> {
+ if let Some(p) = std::env::var_os("XERJ_CLOUDFLARED").filter(|s| !s.is_empty()) {
+ let p = PathBuf::from(p);
+ return p.is_file().then_some(p);
+ }
+ let exe = if cfg!(windows) {
+ "cloudflared.exe"
+ } else {
+ "cloudflared"
+ };
+ let mut dirs: Vec<PathBuf> = std::env::var_os("PATH")
+ .map(|p| std::env::split_paths(&p).collect())
+ .unwrap_or_default();
+ if let Some(home) = std::env::var_os("HOME") {
+ dirs.push(Path::new(&home).join(".local").join("bin"));
+ }
+ dirs.into_iter().map(|d| d.join(exe)).find(|p| p.is_file())
+}
+
+fn default_data_dir() -> PathBuf {
+ let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
+ Path::new(&home).join(".xerj").join("brain")
+}
+
+/// `--api-key` / `XERJ_API_KEY` first, then `<data-dir>/admin.key` — the same
+/// order `xerj brain` uses.
+fn resolve_api_key(common: &Common) -> (Option<String>, PathBuf) {
+ let key_path = common
+ .data_dir
+ .clone()
+ .unwrap_or_else(default_data_dir)
+ .join("admin.key");
+ let key = common.api_key.clone().or_else(|| {
+ std::fs::read_to_string(&key_path)
+ .ok()
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+ });
+ (key, key_path)
+}
+
+/// The words for the refusal. One place, so the CLI probe and the server's
+/// `409` say the same thing.
+fn open_mode_refusal(url: &str) -> String {
+ format!(
+ "the node at {url} is running with authentication OFF (--insecure, or \
+ auth.enabled = false).\n\
+ \x20 A share is a read-only guest key. On a node with auth off every request is \
+ already\n\
+ \x20 the superuser, so that key would restrict nothing: the guest — and anyone \
+ else who\n\
+ \x20 can reach the port — could read, change and delete every index without it.\n\
+ \x20 Restart the node without --insecure (auth is on by default; the admin key is \
+ written\n\
+ \x20 to <data_dir>/admin.key), then run this again."
+ )
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Running
+// ─────────────────────────────────────────────────────────────────────────────
+
+fn run(cfg: ShareCfg) -> Result<i32> {
+ let common = &cfg.common;
+
+ // 1. Is anything there, and is it enforcing anything? An unauthenticated
+ // `GET /` answers 200 only on an open node.
+ let anon = Es::new(&common.url, None)?;
+ match anon.get_status("/") {
+ Ok(200) => bail!("{}", open_mode_refusal(&common.url)),
+ Ok(401) | Ok(403) => {}
+ Ok(status) => bail!(
+ "something answers at {} but it does not look like a xerj node (GET / → HTTP \
+ {status}). Point --url at your node",
+ common.url
+ ),
+ Err(_) => bail!(
+ "no xerj node answers at {}. Start one first — `xerj brain <folder>` boots a \
+ node and indexes the folder — or pass --url",
+ common.url
+ ),
+ }
+
+ // 2. The admin key.
+ let (api_key, key_path) = resolve_api_key(common);
+ let Some(api_key) = api_key else {
+ bail!(
+ "no admin key. Shares are managed with the node's admin key: pass --api-key, set \
+ XERJ_API_KEY, or point --data-dir at the node's data directory (looked for {})",
+ key_path.display()
+ );
+ };
+ let es = Es::new(&common.url, Some(api_key))?;
+
+ match &cfg.action {
+ Action::List => list(&es, common),
+ Action::Revoke(handle) => revoke(&es, common, handle),
+ Action::Create(create) => create_share(&es, common, create),
+ }
+}
+
+/// Turn a non-2xx from `/_share` into words.
+fn explain(status: u16, body: &Value, common: &Common) -> anyhow::Error {
+ let reason = body
+ .pointer("/error/reason")
+ .and_then(Value::as_str)
+ .unwrap_or("");
+ match status {
+ 401 => anyhow!(
+ "the node at {} rejected the key. Shares need the node's ADMIN key — the one in \
+ <data_dir>/admin.key",
+ common.url
+ ),
+ 403 => anyhow!(
+ "that key is not the admin key. A scoped or minted key cannot create, list or \
+ revoke shares — otherwise it could widen its own reach. Use the key in \
+ <data_dir>/admin.key"
+ ),
+ 409 => anyhow!("{}", open_mode_refusal(&common.url)),
+ 404 if !reason.is_empty() => anyhow!("{reason}"),
+ 404 | 405 => anyhow!(
+ "the node at {} has no share links (`/_share` is not there) — it is an older \
+ xerj. Upgrade the node, then run this again",
+ common.url
+ ),
+ _ if !reason.is_empty() => anyhow!("{reason} (HTTP {status})"),
+ _ => anyhow!(
+ "unexpected HTTP {status} from {}/_share: {body}",
+ common.url
+ ),
+ }
+}
+
+fn list(es: &Es, common: &Common) -> Result<i32> {
+ let (status, body) = es.request_json("GET", "/_share", None)?;
+ if status != 200 {
+ return Err(explain(status, &body, common));
+ }
+ if common.json {
+ println!("{}", serde_json::to_string_pretty(&body)?);
+ return Ok(0);
+ }
+ let shares = body
+ .get("shares")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+ if shares.is_empty() {
+ println!("no shares on this node. Create one: xerj share <index|folder>");
+ return Ok(0);
+ }
+ println!(
+ "{:<14} {:<10} {:<8} {:<22} {:<28} LABEL",
+ "HANDLE", "STATUS", "CLAIMS", "EXPIRES", "INDEX"
+ );
+ for s in &shares {
+ let g = |k: &str| s.get(k).and_then(Value::as_str).unwrap_or("-").to_string();
+ let claims = format!(
+ "{}/{}",
+ s.get("claims").and_then(Value::as_u64).unwrap_or(0),
+ s.get("max_claims").and_then(Value::as_u64).unwrap_or(0)
+ );
+ println!(
+ "{:<14} {:<10} {:<8} {:<22} {:<28} {}",
+ g("handle"),
+ g("status"),
+ claims,
+ g("expires_at"),
+ g("index"),
+ g("label")
+ );
+ }
+ println!(
+ "\nrevoke one: xerj share --revoke <HANDLE>{}",
+ connection_args(common)
+ );
+ Ok(0)
+}
+
+fn revoke(es: &Es, common: &Common, handle: &str) -> Result<i32> {
+ let (status, body) = es.request_json("DELETE", &format!("/_share/{handle}"), None)?;
+ if status == 404 {
+ bail!("no share with handle {handle} on this node (see `xerj share --list`)");
+ }
+ if status != 200 {
+ return Err(explain(status, &body, common));
+ }
+ if common.json {
+ println!("{}", serde_json::to_string_pretty(&body)?);
+ return Ok(0);
+ }
+ let n = body
+ .get("keys_invalidated")
+ .and_then(Value::as_u64)
+ .unwrap_or(0);
+ println!(
+ "✓ share {handle} revoked — {n} guest key{} invalidated. Anyone who had opened it \
+ loses access on their next request.",
+ if n == 1 { "" } else { "s" }
+ );
+ Ok(0)
+}
+
+/// What a folder argument resolved to.
+struct Resolved {
+ indices: Vec<String>,
+ brain: Option<String>,
+ /// A line for the owner: how the argument became these indices.
+ how: Option<String>,
+}
+
+/// What the brain-meta lookup for a folder argument came back with.
+#[derive(Debug, PartialEq)]
+enum BrainMeta {
+ Found(Value),
+ /// The node answered and there is no such brain.
+ NotIndexed,
+ /// The node did not answer the question — most often `401`/`403`, a wrong
+ /// or non-admin key.
+ Refused,
+}
+
+/// Read a `GET /{edges}/_doc/__brain_meta__` answer.
+///
+/// This went through `Es::get_doc`, which turns *every* body without
+/// `found: true` into "no document" — including a `401`. So a wrong key with a
+/// folder argument was reported as "<folder> has not been indexed … run `xerj
+/// brain` first", sending the owner to re-index a folder that was indexed all
+/// along, while the same key with an index argument got the right sentence
+/// (review of PR #947). Only a `404`, or a `200` that says `found: false`,
+/// means the brain is not there.
+fn brain_meta(status: u16, body: &Value) -> BrainMeta {
+ match status {
+ 200 if body.get("found").and_then(Value::as_bool) == Some(true) => body
+ .get("_source")
+ .cloned()
+ .map_or(BrainMeta::NotIndexed, BrainMeta::Found),
+ 200 | 404 => BrainMeta::NotIndexed,
+ _ => BrainMeta::Refused,
+ }
+}
+
+fn resolve_target(es: &Es, common: &Common, create: &CreateCfg) -> Result<Resolved> {
+ let target = classify_target(&create.target, create.force_index, |p| p.is_dir())
+ .map_err(|e| anyhow!(e))?;
+ match target {
+ Target::Indices(indices) => Ok(Resolved {
+ indices,
+ brain: create.brain.clone(),
+ how: None,
+ }),
+ Target::Folder(folder) => {
+ let brain = match &create.brain {
+ Some(b) => b.clone(),
+ None => {
+ let derived = xerj_autoindex::derive_brain_name(&folder);
+ detect::validate_brain(&derived).map_err(|reason| {
+ anyhow!(
+ "folder name '{derived}' is not usable as a brain name ({reason}) — \
+ pass the one you used with --brain <name>"
+ )
+ })?;
+ derived
+ }
+ };
+ let edges_index = detect::edges_index_name(&brain);
+ let (status, body) = es
+ .request_json(
+ "GET",
+ &format!("/{edges_index}/_doc/{}", detect::BRAIN_META_ID),
+ None,
+ )
+ .with_context(|| format!("look up brain '{brain}'"))?;
+ let meta = match brain_meta(status, &body) {
+ BrainMeta::Found(meta) => meta,
+ BrainMeta::NotIndexed => bail!(
+ "{} has not been indexed on this node: there is no brain named '{brain}'. \
+ Run `xerj brain {}` first, or pass an index name",
+ folder.display(),
+ folder.display()
+ ),
+ BrainMeta::Refused => return Err(explain(status, &body, common)),
+ };
+ let indices: Vec<String> = meta
+ .get("nodes_index")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .split(',')
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(String::from)
+ .collect();
+ if indices.is_empty() {
+ bail!(
+ "brain '{brain}' does not record which indices hold its documents (it \
+ predates that field). Share by index name instead — `xerj autoindex \
+ map` lists them"
+ );
+ }
+ let how = format!(
+ "{} → brain '{brain}' → {}",
+ folder.display(),
+ indices.join(", ")
+ );
+ Ok(Resolved {
+ indices,
+ brain: Some(brain),
+ how: Some(how),
+ })
+ }
+ }
+}
+
+fn create_share(es: &Es, common: &Common, create: &CreateCfg) -> Result<i32> {
+ let resolved = resolve_target(es, common, create)?;
+ if let Some(how) = &resolved.how {
+ eprintln!("sharing {how}");
+ }
+
+ // The tunnel comes up BEFORE the share exists, so a link is never printed
+ // for an address that is not there, and a tunnel that cannot start costs
+ // nothing but a message.
+ let mut tunnel: Option<Tunnel> = None;
+ let mut tunnel_note: Option<String> = None;
+ // Listening before the tunnel exists — see `Interrupts`.
+ let interrupts = create.tunnel.then(Interrupts::listen);
+ if create.tunnel {
+ let (_, port) = local_http_origin(&common.url).map_err(|e| anyhow!(e))?;
+ match find_cloudflared() {
+ None => {
+ tunnel_note = Some(format!(
+ "--tunnel needs `cloudflared`, which is not installed (looked on PATH and \
+ in ~/.local/bin).\n{}\n then run this command again. Until then the \
+ link above only works on this machine.",
+ cloudflared_install_help()
+ ));
+ }
+ Some(bin) => {
+ eprintln!("opening a tunnel with {} …", bin.display());
+ let opened = Tunnel::open(
+ &bin,
+ port,
+ interrupts.as_ref().expect("listening when --tunnel is set"),
+ );
+ match opened {
+ Ok(t) => tunnel = Some(t),
+ Err(OpenError::Interrupted(why)) => {
+ eprintln!("{why} before the tunnel was up — nothing was shared.");
+ return Ok(130);
+ }
+ Err(OpenError::Failed(e)) => {
+ tunnel_note = Some(format!(
+ "the tunnel did not come up: {e:#}\n the link above only works on \
+ this machine."
+ ))
+ }
+ }
+ }
+ }
+ }
+
+ let mut body = json!({ "index": resolved.indices });
+ if let Some(b) = &resolved.brain {
+ body["brain"] = json!(b);
+ }
+ if let Some(e) = &create.expires {
+ body["expires_in"] = json!(e);
+ }
+ if let Some(n) = create.max_claims {
+ body["max_claims"] = json!(n);
+ }
+ if let Some(p) = &create.passcode {
+ body["passcode"] = json!(p);
+ }
+ if let Some(l) = &create.label {
+ body["label"] = json!(l);
+ }
+ let (status, resp) = es.request_json("POST", "/_share", Some(&body))?;
+ if status != 200 {
+ return Err(explain(status, &resp, common));
+ }
+ let share_id = resp
+ .get("share_id")
+ .and_then(Value::as_str)
+ .context("the node's response carries no share_id")?;
+ let handle = resp.get("handle").and_then(Value::as_str).unwrap_or("");
+ let url_path = resp.get("url_path").and_then(Value::as_str);
+
+ let base = tunnel
+ .as_ref()
+ .map(|t| t.public_url.clone())
+ .or_else(|| create.public_url.clone())
+ .unwrap_or_else(|| common.url.clone());
+ let link = guest_link(&base, url_path, share_id);
+ let reach = reach_of(tunnel.is_some(), create.public_url.as_deref(), &common.url);
+
+ if common.json {
+ let mut out = resp.clone();
+ out["link"] = json!(link);
+ out["local_only"] = json!(reach == Reach::Loopback);
+ out["via"] = json!(reach.as_str());
+ if reach == Reach::CloudflareTunnel {
+ out["transit_notice"] = json!(CLOUDFLARE_TRANSIT_NOTICE);
+ }
+ out["revoke"] = json!(format!(
+ "xerj share --revoke {handle}{}",
+ connection_args(common)
+ ));
+ println!("{}", serde_json::to_string_pretty(&out)?);
+ } else {
+ print!("{}", render_created(&resp, &link, reach, common));
+ }
+ if let Some(note) = &tunnel_note {
+ eprintln!("\n{note}");
+ }
+
+ let Some(tunnel) = tunnel else {
+ return Ok(0);
+ };
+ if resp
+ .pointer("/claim_limiter/source_address")
+ .and_then(Value::as_str)
+ == Some("peer")
+ {
+ eprintln!(
+ "\nnote: through a tunnel every guest reaches this node from 127.0.0.1, so the \
+ audit log\n records that address for them. To record each guest's real \
+ address, add\n trusted_proxies = [\"127.0.0.1\", \"::1\"]\n under \
+ [server] in the node's config and restart it. The passcode lockout\n \
+ ({} guesses per share per hour) holds either way.",
+ xerj_api::share::SHARE_PER_HOUR
+ );
+ }
+ eprintln!(
+ "\ntunnel is up — keep this running while your guest reads. Ctrl-C closes the tunnel{}.",
+ if create.keep {
+ " (the share stays active: --keep)"
+ } else {
+ " and revokes the share"
+ }
+ );
+ let why = tunnel.wait(interrupts.as_ref().expect("listening when --tunnel is set"));
+ eprintln!("\n{why} — closing the tunnel.");
+ if why == CLOUDFLARED_STOPPED {
+ // Nobody asked it to stop: its own last words are the only reason.
+ let tail = tunnel_log_tail(&tunnel.log);
+ if !tail.is_empty() {
+ eprintln!("{}", tail.trim_start_matches('\n'));
+ }
+ }
+ drop(tunnel);
+ if create.keep {
+ eprintln!(
+ "the share is still active on this node until it expires. End it: xerj share \
+ --revoke {handle}{}",
+ connection_args(common)
+ );
+ return Ok(0);
+ }
+ match es.request_json("DELETE", &format!("/_share/{handle}"), None) {
+ Ok((200, body)) => eprintln!(
+ "share {handle} revoked — {} guest key(s) invalidated.",
+ body.get("keys_invalidated")
+ .and_then(Value::as_u64)
+ .unwrap_or(0)
+ ),
+ Ok((status, _)) => eprintln!(
+ "could not revoke share {handle} (HTTP {status}). Do it by hand: xerj share \
+ --revoke {handle}{}",
+ connection_args(common)
+ ),
+ Err(e) => eprintln!(
+ "could not revoke share {handle} ({e:#}). Do it by hand: xerj share --revoke \
+ {handle}{}",
+ connection_args(common)
+ ),
+ }
+ Ok(0)
+}
+
+/// The connection flags a follow-up command has to repeat to reach the same
+/// node: `--url` and `--data-dir`, each only when it is not the default. Never
+/// `--api-key` — a key is not something to echo back into a terminal
+/// scrollback, and `--data-dir` (or `XERJ_API_KEY`) already supplies it.
+fn connection_args(common: &Common) -> String {
+ let mut out = String::new();
+ if common.url != DEFAULT_URL {
+ out.push_str(&format!(" --url {}", sh_quote(&common.url)));
+ }
+ if let Some(dir) = &common.data_dir {
+ out.push_str(&format!(
+ " --data-dir {}",
+ sh_quote(&dir.display().to_string())
+ ));
+ }
+ out
+}
+
+/// `arg` as one shell word, for a command the owner is meant to paste.
+///
+/// `xerj brain "case files"` printed `xerj share /…/case files --url …`, and
+/// pasting it failed with `unknown argument: files` (review of PR #947). An
+/// argument made only of characters no shell treats specially is left alone,
+/// so the common case still reads cleanly; anything else is quoted — single
+/// quotes on unix (`'` itself as `'\''`), double quotes on Windows, where
+/// `cmd.exe` and PowerShell both accept them around a path.
+pub(crate) fn sh_quote(arg: &str) -> String {
+ let plain = !arg.is_empty()
+ && arg.chars().all(|c| {
+ c.is_ascii_alphanumeric()
+ || matches!(c, '_' | '-' | '.' | '/' | ':' | ',' | '+' | '=' | '@' | '%')
+ });
+ if plain {
+ return arg.to_string();
+ }
+ if cfg!(windows) {
+ // A Windows path legitimately holds `\` and `:`; neither needs more
+ // than the surrounding quotes.
+ let bare_ok = !arg.is_empty()
+ && arg.chars().all(|c| {
+ c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | '\\' | ':')
+ });
+ return if bare_ok {
+ arg.to_string()
+ } else {
+ format!("\"{}\"", arg.replace('"', "\\\""))
+ };
+ }
+ format!("'{}'", arg.replace('\'', "'\\''"))
+}
+
+/// The human-readable result of a create. A value, so tests can read it.
+fn render_created(resp: &Value, link: &str, reach: Reach, common: &Common) -> String {
+ let node_url = common.url.as_str();
+ let g = |k: &str| resp.get(k).and_then(Value::as_str).unwrap_or("");
+ let mut what = format!("index {}", g("index"));
+ if !g("brain").is_empty() {
+ what.push_str(&format!(" · brain {} (its links)", g("brain")));
+ }
+ let claims = resp.get("max_claims").and_then(Value::as_u64).unwrap_or(1);
+ let mut out = String::new();
+ out.push_str(&format!(
+ "\n✓ share created{}\n",
+ if g("label").is_empty() {
+ String::new()
+ } else {
+ format!(" — \"{}\"", g("label"))
+ }
+ ));
+ out.push_str(&format!(" shares: {what} — read-only\n"));
+ out.push_str(&format!(" link: {link}\n"));
+ out.push_str(&format!(
+ " passcode: {} (send it separately from the link)\n",
+ g("passcode")
+ ));
+ out.push_str(&format!(
+ " expires: {} · can be opened {claims} time{}{}\n",
+ g("expires_at"),
+ if claims == 1 { "" } else { "s" },
+ // sessionStorage is per tab: a closed tab is a spent open. Say so
+ // where the number is, not only in the docs.
+ if claims == 1 {
+ " — one browser tab; --max-claims <N> for a guest who will come back"
+ } else {
+ ""
+ }
+ ));
+ out.push_str(&format!(
+ " revoke: xerj share --revoke {}{}\n",
+ g("handle"),
+ connection_args(common)
+ ));
+ out.push_str(" the link and passcode are shown once — the node keeps only their hashes.\n");
+ let plain_http = link.starts_with("http://");
+ match reach {
+ Reach::CloudflareTunnel => {
+ // NOT "the guest's browser reads from this node": it reads from
+ // Cloudflare, which reads from this node.
+ out.push_str(" your documents stay on this machine — XERJ copies them nowhere.\n");
+ out.push_str(&format!(
+ "\n {}.\n",
+ wrap(CLOUDFLARE_TRANSIT_NOTICE, 76, " ")
+ ));
+ }
+ Reach::Loopback => {
+ out.push_str(
+ " your documents stay on this machine; the guest's browser reads from this \
+ node.\n",
+ );
+ out.push_str(&format!(
+ "\n this link points at {node_url}, which only this machine can reach.\n\
+ \x20 for someone elsewhere: `xerj share … --tunnel` (temporary public address \
+ through\n\
+ \x20 Cloudflare), or --public-url https://<your-hostname> if the node is \
+ already published.\n"
+ ));
+ }
+ Reach::Direct | Reach::PublicUrl => {
+ if reach == Reach::PublicUrl {
+ // The browser talks to whatever serves that address — the
+ // owner's reverse proxy, or a CDN in front of it — not
+ // necessarily to this node directly.
+ out.push_str(
+ " your documents stay on this machine; the guest's browser reaches this \
+ node through the\n\
+ \x20 address above, and whoever ends TLS for that address can read what \
+ passes through it.\n",
+ );
+ } else {
+ out.push_str(
+ " your documents stay on this machine; the guest's browser reads from \
+ this node.\n",
+ );
+ }
+ if plain_http {
+ out.push_str(
+ "\n this link is plain http: the passcode, the guest's key and every \
+ document the guest\n\
+ \x20 opens cross the network unencrypted, readable by anyone on the path. \
+ Use it on a\n\
+ \x20 network you trust, or put the node behind https and pass that address \
+ as --public-url.\n",
+ );
+ }
+ }
+ }
+ out
+}
+
+/// Greedy word wrap at `width`, continuation lines prefixed with `indent`.
+fn wrap(text: &str, width: usize, indent: &str) -> String {
+ let mut out = String::new();
+ let mut line = 0usize;
+ for word in text.split_whitespace() {
+ let n = word.chars().count();
+ if line > 0 && line + 1 + n > width {
+ out.push('\n');
+ out.push_str(indent);
+ line = 0;
+ } else if line > 0 {
+ out.push(' ');
+ line += 1;
+ }
+ out.push_str(word);
+ line += n;
+ }
+ out
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// The tunnel
+// ─────────────────────────────────────────────────────────────────────────────
+
+enum TunnelEvent {
+ Url(String),
+ Connected,
+ Exited,
+}
+
+/// Ctrl-C (and, on unix, SIGTERM / SIGHUP) as a channel.
+///
+/// Installed BEFORE `cloudflared` is spawned. The tunnel runs in its own
+/// process group so that it is closed by us, in order; the price is that a
+/// signal which kills this command by default action would orphan it. With the
+/// listener in place first, there is no window in which that can happen.
+///
+/// `xerj share` runs inside the binary's tokio runtime (on a blocking thread),
+/// so the portable signal futures are available — no handler of our own, and
+/// Ctrl-C works on Windows.
+struct Interrupts(mpsc::Receiver<&'static str>);
+
+impl Interrupts {
+ fn listen() -> Self {
+ let (tx, rx) = mpsc::channel::<&'static str>();
+ if let Ok(handle) = tokio::runtime::Handle::try_current() {
+ let tx_c = tx.clone();
+ handle.spawn(async move {
+ if tokio::signal::ctrl_c().await.is_ok() {
+ let _ = tx_c.send("Ctrl-C");
+ }
+ });
+ #[cfg(unix)]
+ for (kind, name) in [
+ (tokio::signal::unix::SignalKind::terminate(), "SIGTERM"),
+ (tokio::signal::unix::SignalKind::hangup(), "terminal closed"),
+ ] {
+ let tx_s = tx.clone();
+ handle.spawn(async move {
+ if let Ok(mut sig) = tokio::signal::unix::signal(kind) {
+ if sig.recv().await.is_some() {
+ let _ = tx_s.send(name);
+ }
+ }
+ });
+ }
+ }
+ Interrupts(rx)
+ }
+
+ fn fired(&self) -> Option<&'static str> {
+ self.0.try_recv().ok()
+ }
+}
+
+struct Tunnel {
+ child: Child,
+ public_url: String,
+ events: mpsc::Receiver<TunnelEvent>,
+ log: TunnelLog,
+}
+
+/// The last lines `cloudflared` wrote. Its output is not shown while it works
+/// — it is a wall of connection chatter — but when it dies on its own those
+/// lines are the only explanation there is, and the first cut threw them away:
+/// the owner saw "cloudflared stopped" and a revoked share, and nothing else
+/// (review of PR #947, a real quick tunnel that dropped after two minutes).
+type TunnelLog = std::sync::Arc<std::sync::Mutex<std::collections::VecDeque<String>>>;
+/// How many of them are kept.
+const TUNNEL_LOG_LINES: usize = 20;
+
+/// `\n cloudflared's last lines:\n …` — or nothing, if it never wrote any.
+fn tunnel_log_tail(log: &TunnelLog) -> String {
+ let lines = match log.lock() {
+ Ok(l) => l,
+ Err(poisoned) => poisoned.into_inner(),
+ };
+ if lines.is_empty() {
+ return String::new();
+ }
+ let mut out = String::from("\n cloudflared's last lines:");
+ for line in lines.iter() {
+ out.push_str("\n ");
+ out.push_str(line);
+ }
+ out
+}
+
+/// Why a tunnel did not open. The two cases end differently: an interrupt
+/// stops the command with nothing shared; a failure falls back to the local
+/// link.
+enum OpenError {
+ Interrupted(&'static str),
+ Failed(anyhow::Error),
+}
+
+/// How often the wait loops look up from the tunnel's log to check for a
+/// signal.
+const TICK: Duration = Duration::from_millis(200);
+/// What [`Tunnel::wait`] returns when the tunnel went away by itself.
+const CLOUDFLARED_STOPPED: &str = "cloudflared stopped";
+
+impl Tunnel {
+ /// Spawn `cloudflared tunnel --url http://127.0.0.1:<port>` and wait for
+ /// its hostname. `127.0.0.1`, not `localhost`: the node binds IPv4
+ /// loopback by default and `localhost` may resolve to `::1` first.
+ fn open(bin: &Path, port: u16, interrupts: &Interrupts) -> Result<Self, OpenError> {
+ let failed = |msg: String| OpenError::Failed(anyhow!(msg));
+ let mut command = Command::new(bin);
+ command
+ .args(["tunnel", "--no-autoupdate", "--url"])
+ .arg(format!("http://127.0.0.1:{port}"))
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ // Its own process group: a terminal Ctrl-C goes to the foreground
+ // group, and the tunnel must be closed by us, in order — after the
+ // wait loop has noticed — not race us to the exit.
+ #[cfg(unix)]
+ {
+ use std::os::unix::process::CommandExt;
+ command.process_group(0);
+ }
+ // Belt and braces on Linux: if this command dies in a way no handler
+ // sees (SIGKILL, a panic=abort), the kernel terminates the tunnel.
+ // The "parent" here is the spawning *thread*, which is the thread that
+ // runs this whole command, so it lives exactly as long as we do.
+ #[cfg(target_os = "linux")]
+ {
+ use std::os::unix::process::CommandExt;
+ // SAFETY: `prctl` is async-signal-safe and touches no memory the
+ // parent shares; nothing else runs between fork and exec.
+ unsafe {
+ command.pre_exec(|| {
+ libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM);
+ Ok(())
+ });
+ }
+ }
+ let mut child = command
+ .spawn()
+ .map_err(|e| failed(format!("start {}: {e}", bin.display())))?;
+
+ let (tx, rx) = mpsc::channel::<TunnelEvent>();
+ let log = TunnelLog::default();
+ let mut readers = Vec::new();
+ // cloudflared logs to stderr; read stdout too so neither pipe can fill
+ // and stall it.
+ if let Some(err) = child.stderr.take() {
+ readers.push(spawn_reader(err, tx.clone(), log.clone()));
+ }
+ if let Some(out) = child.stdout.take() {
+ readers.push(spawn_reader(out, tx.clone(), log.clone()));
+ }
+ // When both pipes close, the process is gone.
+ std::thread::spawn(move || {
+ for r in readers {
+ let _ = r.join();
+ }
+ let _ = tx.send(TunnelEvent::Exited);
+ });
+
+ // From here on `tunnel` owns the child: every early return below drops
+ // it, and `Drop` closes the tunnel.
+ let mut tunnel = Tunnel {
+ child,
+ public_url: String::new(),
+ events: rx,
+ log,
+ };
+ let deadline = std::time::Instant::now() + TUNNEL_URL_TIMEOUT;
+ loop {
+ if let Some(why) = interrupts.fired() {
+ return Err(OpenError::Interrupted(why));
+ }
+ match tunnel.events.recv_timeout(TICK) {
+ Ok(TunnelEvent::Url(u)) => {
+ tunnel.public_url = u;
+ break;
+ }
+ Ok(TunnelEvent::Connected) => {}
+ Ok(TunnelEvent::Exited) | Err(mpsc::RecvTimeoutError::Disconnected) => {
+ return Err(failed(format!(
+ "cloudflared exited before printing an address{}",
+ tunnel_log_tail(&tunnel.log)
+ )));
+ }
+ Err(mpsc::RecvTimeoutError::Timeout) => {
+ if std::time::Instant::now() > deadline {
+ return Err(failed(format!(
+ "cloudflared printed no address within {}s (is this machine online?)",
+ TUNNEL_URL_TIMEOUT.as_secs()
+ )));
+ }
+ }
+ }
+ }
+ // The hostname is printed before the first edge connection registers;
+ // a link opened in that gap gets Cloudflare's 530. Wait for the
+ // connection, but not forever — the link is still the right link.
+ let deadline = std::time::Instant::now() + TUNNEL_CONNECT_TIMEOUT;
+ loop {
+ if let Some(why) = interrupts.fired() {
+ return Err(OpenError::Interrupted(why));
+ }
+ match tunnel.events.recv_timeout(TICK) {
+ Ok(TunnelEvent::Connected) => break,
+ Ok(TunnelEvent::Url(_)) => {}
+ Ok(TunnelEvent::Exited) | Err(mpsc::RecvTimeoutError::Disconnected) => {
+ return Err(failed(format!(
+ "cloudflared exited while connecting{}",
+ tunnel_log_tail(&tunnel.log)
+ )));
+ }
+ Err(mpsc::RecvTimeoutError::Timeout) => {
+ if std::time::Instant::now() > deadline {
+ eprintln!(
+ "cloudflared has an address but has not confirmed a connection \
+ yet; the link may take a few seconds to start answering."
+ );
+ break;
+ }
+ }
+ }
+ }
+ Ok(tunnel)
+ }
+
+ /// Block until a signal arrives or `cloudflared` goes away. Returns why.
+ fn wait(&self, interrupts: &Interrupts) -> &'static str {
+ loop {
+ if let Some(why) = interrupts.fired() {
+ return why;
+ }
+ match self.events.recv_timeout(TICK) {
+ Ok(TunnelEvent::Exited) | Err(mpsc::RecvTimeoutError::Disconnected) => {
+ return CLOUDFLARED_STOPPED
+ }
+ _ => {}
+ }
+ }
+ }
+}
+
+impl Drop for Tunnel {
+ /// The tunnel never outlives this command: terminate, give it a moment to
+ /// deregister from the edge, then kill.
+ fn drop(&mut self) {
+ #[cfg(unix)]
+ {
+ // SAFETY: plain `kill(2)` on a pid we spawned and still own.
+ unsafe {
+ libc::kill(self.child.id() as libc::pid_t, libc::SIGTERM);
+ }
+ for _ in 0..30 {
+ if matches!(self.child.try_wait(), Ok(Some(_))) {
+ return;
+ }
+ std::thread::sleep(Duration::from_millis(100));
+ }
+ }
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+}
+
+fn spawn_reader<R: std::io::Read + Send + 'static>(
+ pipe: R,
+ tx: mpsc::Sender<TunnelEvent>,
+ log: TunnelLog,
+) -> std::thread::JoinHandle<()> {
+ std::thread::spawn(move || {
+ let mut sent_url = false;
+ for line in BufReader::new(pipe).lines() {
+ let Ok(line) = line else { break };
+ remember_tunnel_line(&log, &line);
+ if !sent_url {
+ if let Some(u) = parse_tunnel_url(&line) {
+ sent_url = true;
+ let _ = tx.send(TunnelEvent::Url(u));
+ continue;
+ }
+ }
+ if tunnel_line_means_connected(&line) {
+ let _ = tx.send(TunnelEvent::Connected);
+ }
+ }
+ })
+}
+
+/// Keep `line` as one of the last [`TUNNEL_LOG_LINES`]; long lines are cut.
+fn remember_tunnel_line(log: &TunnelLog, line: &str) {
+ let line = line.trim_end();
+ if line.is_empty() {
+ return;
+ }
+ let kept: String = line.chars().take(300).collect();
+ let mut lines = match log.lock() {
+ Ok(l) => l,
+ Err(poisoned) => poisoned.into_inner(),
+ };
+ if lines.len() == TUNNEL_LOG_LINES {
+ lines.pop_front();
+ }
+ lines.push_back(kept);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn args(list: &[&str]) -> Vec<String> {
+ list.iter().map(|s| s.to_string()).collect()
+ }
+
+ fn create_of(cfg: ShareCfg) -> CreateCfg {
+ match cfg.action {
+ Action::Create(c) => c,
+ other => panic!("expected a create, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn no_arguments_is_help_not_an_error() {
+ assert_eq!(parse(args(&[]), None), Ok(None));
+ assert_eq!(parse(args(&["--help"]), None), Ok(None));
+ assert_eq!(parse(args(&["notes", "-h"]), None), Ok(None));
+ }
+
+ #[test]
+ fn a_bare_target_takes_every_default_from_the_server() {
+ let cfg = parse(args(&["ax-notes"]), None).unwrap().unwrap();
+ assert_eq!(cfg.common.url, "http://localhost:9200");
+ assert_eq!(cfg.common.api_key, None);
+ assert!(!cfg.common.json);
+ let c = create_of(cfg);
+ assert_eq!(c.target, "ax-notes");
+ // Unset, not defaulted here: the server owns the defaults (24h, one
+ // claim, a generated passcode), so the two cannot drift apart.
+ assert_eq!(c.expires, None);
+ assert_eq!(c.max_claims, None);
+ assert_eq!(c.passcode, None);
+ assert!(!c.tunnel && !c.keep && !c.force_index);
+ }
+
+ #[test]
+ fn every_create_flag_lands_where_it_should() {
+ let cfg = parse(
+ args(&[
+ "~/mail",
+ "--expires",
+ "7d",
+ "--max-claims",
+ "3",
+ "--passcode",
+ "correct horse",
+ "--label",
+ "for Dana",
+ "--brain",
+ "mail",
+ "--tunnel",
+ "--keep",
+ "--url",
+ "http://localhost:9510/",
+ "--api-key",
+ "k",
+ "--data-dir",
+ "/d",
+ "--json",
+ ]),
+ Some("from-env".into()),
+ )
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ cfg.common.url, "http://localhost:9510",
+ "trailing slash trimmed"
+ );
+ assert_eq!(
+ cfg.common.api_key.as_deref(),
+ Some("k"),
+ "--api-key beats XERJ_API_KEY"
+ );
+ assert_eq!(cfg.common.data_dir, Some(PathBuf::from("/d")));
+ assert!(cfg.common.json);
+ let c = create_of(cfg);
+ assert_eq!(c.expires.as_deref(), Some("7d"));
+ assert_eq!(c.max_claims, Some(3));
+ assert_eq!(c.passcode.as_deref(), Some("correct horse"));
+ assert_eq!(c.label.as_deref(), Some("for Dana"));
+ assert_eq!(c.brain.as_deref(), Some("mail"));
+ assert!(c.tunnel && c.keep);
+ }
+
+ #[test]
+ fn the_environment_key_is_used_when_no_flag_names_one() {
+ let cfg = parse(args(&["--list"]), Some("env-key".into()))
+ .unwrap()
+ .unwrap();
+ assert_eq!(cfg.common.api_key.as_deref(), Some("env-key"));
+ let cfg = parse(args(&["--list"]), Some(String::new()))
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ cfg.common.api_key, None,
+ "an empty XERJ_API_KEY is no key, not an empty key"
+ );
+ }
+
+ #[test]
+ fn values_are_validated_before_anything_is_sent() {
+ for bad in [
+ vec!["i", "--expires", "24"], // no unit
+ vec!["i", "--expires", "1w"], // unknown unit
+ vec!["i", "--expires", "31d"], // past the ceiling
+ vec!["i", "--expires", "0s"], // below the floor
+ vec!["i", "--max-claims", "0"], // at least one
+ vec!["i", "--max-claims", "51"], // at most 50
+ vec!["i", "--max-claims", "many"], // a number
+ vec!["i", "--passcode", "short"], // 5 chars
+ vec!["i", "--brain", "Bad Name"], // not a brain slug
+ vec!["i", "--public-url", "example.com"],
+ vec!["i", "--expires"], // missing value
+ vec!["i", "--wat"], // unknown flag
+ vec!["i", "j"], // two targets
+ ] {
+ assert!(parse(args(&bad), None).is_err(), "{bad:?} must be refused");
+ }
+ let long_label = "x".repeat(xerj_api::share::MAX_LABEL_CHARS + 1);
+ assert!(parse(args(&["i", "--label", &long_label]), None).is_err());
+ }
+
+ #[test]
+ fn list_revoke_and_create_are_mutually_exclusive() {
+ assert_eq!(
+ parse(args(&["--list"]), None).unwrap().unwrap().action,
+ Action::List
+ );
+ assert_eq!(
+ parse(args(&["--revoke", "1a2b3c4d5e6f"]), None)
+ .unwrap()
+ .unwrap()
+ .action,
+ Action::Revoke("1a2b3c4d5e6f".into())
+ );
+ assert!(parse(args(&["--list", "notes"]), None).is_err());
+ assert!(parse(args(&["--list", "--revoke", "abc"]), None).is_err());
+ // A create-only flag beside --list would be silently ignored; refuse.
+ assert!(parse(args(&["--list", "--expires", "1h"]), None).is_err());
+ assert!(parse(args(&["--revoke", "abc", "--tunnel"]), None).is_err());
+ // A handle is hex. A pasted link or a path is a mistake worth naming.
+ assert!(parse(args(&["--revoke", "not-hex!"]), None).is_err());
+ // The share id is refused, and the error does not echo it back.
+ let id = "0123456789abcdef0123456789abcdef";
+ let err = parse(args(&["--revoke", id]), None).unwrap_err();
+ assert!(err.contains("never sent in a URL"), "{err}");
+ assert!(!err.contains(id), "{err}");
+ assert!(parse(args(&["--revoke", "1a2b3c"]), None).is_err());
+ assert!(parse(args(&["--revoke"]), None).is_err());
+ }
+
+ #[test]
+ fn keep_and_public_url_only_make_sense_in_their_own_mode() {
+ assert!(parse(args(&["i", "--keep"]), None).is_err());
+ assert!(parse(
+ args(&["i", "--tunnel", "--public-url", "https://x.example"]),
+ None
+ )
+ .is_err());
+ let c = create_of(
+ parse(args(&["i", "--public-url", "https://x.example/"]), None)
+ .unwrap()
+ .unwrap(),
+ );
+ assert_eq!(c.public_url.as_deref(), Some("https://x.example"));
+ }
+
+ #[test]
+ fn an_existing_folder_is_a_folder_and_everything_else_is_an_index() {
+ let dirs = |p: &Path| p == Path::new("notes") || p == Path::new("./mail");
+ assert_eq!(
+ classify_target("notes", false, dirs),
+ Ok(Target::Folder(PathBuf::from("notes")))
+ );
+ assert_eq!(
+ classify_target("./mail", false, dirs),
+ Ok(Target::Folder(PathBuf::from("./mail")))
+ );
+ // --index forces the other reading of an ambiguous name.
+ assert_eq!(
+ classify_target("notes", true, dirs),
+ Ok(Target::Indices(vec!["notes".into()]))
+ );
+ assert_eq!(
+ classify_target("ax-mail, ax-pdf", false, dirs),
+ Ok(Target::Indices(vec!["ax-mail".into(), "ax-pdf".into()]))
+ );
+ // A path that is not a folder is never quietly treated as an index.
+ assert!(classify_target("./nots", false, dirs).is_err());
+ assert!(classify_target("~/gone", false, dirs).is_err());
+ assert!(classify_target("/abs/gone", false, dirs).is_err());
+ assert!(classify_target("./mail", true, dirs).is_err());
+ assert!(classify_target(" ", false, dirs).is_err());
+ assert!(classify_target(",", false, dirs).is_err());
+ }
+
+ #[test]
+ fn the_share_id_rides_in_the_fragment() {
+ let id = "0123456789abcdef0123456789abcdef";
+ assert_eq!(
+ guest_link("http://localhost:9200/", None, id),
+ format!("http://localhost:9200/_xerj-console/share#{id}")
+ );
+ // The server's own path wins when it sends one…
+ assert_eq!(
+ guest_link(
+ "https://a-b.trycloudflare.com",
+ Some(&format!("/_xerj-console/share#{id}")),
+ id
+ ),
+ format!("https://a-b.trycloudflare.com/_xerj-console/share#{id}")
+ );
+ // …but only a path with a fragment: an id in the path or the query
+ // would be sent to the server and written to every log on the way.
+ for hostile in ["/_xerj-console/share?id=x", "https://evil.example/#x", ""] {
+ let link = guest_link("http://h", Some(hostile), id);
+ assert_eq!(link, format!("http://h/_xerj-console/share#{id}"));
+ }
+ let link = guest_link("http://h", None, id);
+ let (before, after) = link.split_once('#').unwrap();
+ assert!(!before.contains(id), "{link}");
+ assert_eq!(after, id);
+ }
+
+ #[test]
+ fn the_tunnel_hostname_is_read_out_of_cloudflareds_banner() {
+ let banner = "2026-09-18T07:41:02Z INF | https://shiny-rain-forest-42.trycloudflare.com |";
+ assert_eq!(
+ parse_tunnel_url(banner).as_deref(),
+ Some("https://shiny-rain-forest-42.trycloudflare.com")
+ );
+ // The other https:// lines in the same log are not tunnels.
+ for other in [
+ "INF Thank you for trying Cloudflare Tunnel. Doing so, without a Cloudflare account, is a quick way to experiment and try it out. However, be aware that these account-less Tunnels have no uptime guarantee, are subject to the Cloudflare Online Services Terms of Use (https://www.cloudflare.com/website-terms/)",
+ "INF Requesting new quick Tunnel on trycloudflare.com...",
+ "see https://developers.cloudflare.com/cloudflare-one/connections/connect-apps",
+ "https://trycloudflare.com",
+ "https://.trycloudflare.com",
+ "https://evil.example/?x=.trycloudflare.com",
+ ] {
+ assert_eq!(parse_tunnel_url(other), None, "{other}");
+ }
+ // Two URLs on one line: the tunnel is found past the first.
+ assert_eq!(
+ parse_tunnel_url(
+ "terms https://www.cloudflare.com/x then https://a-b.trycloudflare.com/ ok"
+ )
+ .as_deref(),
+ Some("https://a-b.trycloudflare.com")
+ );
+ assert!(tunnel_line_means_connected(
+ "INF Registered tunnel connection connIndex=0 connection=… location=ams01 protocol=quic"
+ ));
+ assert!(!tunnel_line_means_connected("INF Starting metrics server"));
+ }
+
+ #[test]
+ fn a_tunnel_only_fronts_a_plain_http_node_on_this_machine() {
+ assert_eq!(
+ local_http_origin("http://localhost:9510"),
+ Ok(("localhost".into(), 9510))
+ );
+ assert_eq!(
+ local_http_origin("http://127.0.0.1"),
+ Ok(("127.0.0.1".into(), 9200))
+ );
+ assert!(local_http_origin("https://localhost:9200").is_err());
+ assert!(local_http_origin("http://search.internal:9200").is_err());
+ assert!(local_http_origin("http://localhost:notaport").is_err());
+ }
+
+ #[test]
+ fn the_created_banner_says_what_is_shared_and_how_to_end_it() {
+ let resp = json!({
+ "handle": "1a2b3c4d5e6f", "label": "for Dana", "index": "ax-mail,ax-pdf",
+ "brain": "mail", "expires_at": "2026-09-19T08:00:00Z", "max_claims": 1,
+ "passcode": "k7mq-2xhd",
+ });
+ let default_node = Common {
+ url: DEFAULT_URL.to_string(),
+ data_dir: None,
+ api_key: Some("never-printed".into()),
+ json: false,
+ };
+ let local = render_created(
+ &resp,
+ "http://localhost:9200/_xerj-console/share#id",
+ Reach::Loopback,
+ &default_node,
+ );
+ assert!(local.contains("for Dana"));
+ assert!(local.contains("ax-mail,ax-pdf"));
+ assert!(local.contains("brain mail"));
+ assert!(local.contains("read-only"));
+ assert!(local.contains("k7mq-2xhd"));
+ assert!(local.contains("2026-09-19T08:00:00Z"));
+ assert!(local.contains("xerj share --revoke 1a2b3c4d5e6f"));
+ assert!(local.contains("stay on this machine"));
+ assert!(
+ local.contains("--tunnel"),
+ "a localhost link must say it is local-only"
+ );
+ assert!(
+ local.contains("xerj share --revoke 1a2b3c4d5e6f\n"),
+ "{local}"
+ );
+ let public = render_created(
+ &resp,
+ "https://a.trycloudflare.com/_xerj-console/share#id",
+ Reach::CloudflareTunnel,
+ &default_node,
+ );
+ assert!(!public.contains("only this machine can reach"));
+ // One open is one browser tab; the banner says so next to the number.
+ assert!(local.contains("one browser tab"), "{local}");
+ assert!(local.contains("--max-claims"), "{local}");
+ // On a non-default node the revoke line has to be pasteable: the same
+ // --url and --data-dir, and never the key.
+ let custom = Common {
+ url: "http://localhost:9510".into(),
+ data_dir: Some(PathBuf::from("/srv/xerj")),
+ api_key: Some("never-printed".into()),
+ json: false,
+ };
+ let out = render_created(
+ &resp,
+ "http://localhost:9510/_xerj-console/share#id",
+ Reach::Loopback,
+ &custom,
+ );
+ assert!(
+ out.contains(
+ "xerj share --revoke 1a2b3c4d5e6f --url http://localhost:9510 --data-dir /srv/xerj\n"
+ ),
+ "{out}"
+ );
+ assert!(!out.contains("never-printed"));
+ }
+
+ fn banner(link: &str, reach: Reach, node_url: &str) -> String {
+ let resp = json!({
+ "handle": "1a2b3c4d5e6f", "index": "ax-mail",
+ "expires_at": "2026-09-19T08:00:00Z", "max_claims": 3, "passcode": "k7mq-2xhd",
+ });
+ let common = Common {
+ url: node_url.to_string(),
+ data_dir: None,
+ api_key: None,
+ json: false,
+ };
+ render_created(&resp, link, reach, &common)
+ }
+
+ /// Review of PR #947 (blocker): under `--tunnel` the banner said "the
+ /// guest's browser reads from this node" and never said "Cloudflare",
+ /// while every byte — passcode and guest key included — went through
+ /// Cloudflare's TLS termination. The owner reads this banner, not the docs,
+ /// in the second before sending the link.
+ #[test]
+ fn a_tunnel_link_says_cloudflare_can_read_the_traffic() {
+ let out = banner(
+ "https://a-b-c.trycloudflare.com/_xerj-console/share#id",
+ Reach::CloudflareTunnel,
+ DEFAULT_URL,
+ );
+ let flat = out.split_whitespace().collect::<Vec<_>>().join(" ");
+ assert!(flat.contains("goes through Cloudflare"), "{out}");
+ assert!(flat.contains("ends TLS at Cloudflare"), "{out}");
+ for crosses in [
+ "the passcode",
+ "the guest's key",
+ "every document the guest opens",
+ ] {
+ assert!(flat.contains(crosses), "must name {crosses:?}: {out}");
+ }
+ assert!(
+ flat.contains("--public-url"),
+ "must name the alternative: {out}"
+ );
+ // What Cloudflare keeps is Cloudflare's business; the notice does not
+ // promise anything about it. "nothing is uploaded or stored elsewhere"
+ // sat one line above the notice and promised exactly that, which is the
+ // retention claim f152538f removed from the notice itself.
+ assert!(!flat.contains("stored there"), "{out}");
+ for retention in ["or stored", "stored anywhere", "stored elsewhere"] {
+ assert!(
+ !flat.contains(retention),
+ "the banner promises what a third party retains ({retention:?}): {out}"
+ );
+ }
+ assert!(
+ !flat.contains("browser reads from this node"),
+ "in tunnel mode the browser reads from Cloudflare: {out}"
+ );
+ assert!(flat.contains("stay on this machine"), "{out}");
+ assert!(out.lines().all(|l| l.chars().count() <= 100), "{out}");
+ // No other mode mentions a third party that is not there.
+ let local = banner(
+ "http://localhost:9200/_xerj-console/share#id",
+ Reach::Loopback,
+ DEFAULT_URL,
+ );
+ assert!(!local.contains("ends TLS at Cloudflare"), "{local}");
+ assert!(local.contains("browser reads from this node"), "{local}");
+ // Behind --public-url the browser talks to whatever serves that
+ // address (a reverse proxy, maybe a CDN), so the banner does not say
+ // it reads from this node — it says who can read the traffic.
+ let public = banner(
+ "https://files.example.org/_xerj-console/share#id",
+ Reach::PublicUrl,
+ DEFAULT_URL,
+ );
+ let flat_public = public.split_whitespace().collect::<Vec<_>>().join(" ");
+ assert!(!public.contains("ends TLS at Cloudflare"), "{public}");
+ assert!(
+ !flat_public.contains("browser reads from this node"),
+ "{public}"
+ );
+ assert!(
+ flat_public.contains("whoever ends TLS for that address can read"),
+ "{public}"
+ );
+ assert!(public.lines().all(|l| l.chars().count() <= 100), "{public}");
+ // `--help` says it where `--tunnel` is described, and no longer says
+ // the guest's browser "talks to this node" without qualification.
+ let help = help_text(false);
+ let flat = help.split_whitespace().collect::<Vec<_>>().join(" ");
+ assert!(
+ flat.contains("Cloudflare can read what passes through"),
+ "{help}"
+ );
+ assert!(!flat.contains("browser talks to this node"), "{help}");
+ }
+
+ /// Review of PR #947 (minor): "only this machine can reach" was printed for
+ /// any `--url`, and `--public-url http://…` printed a cleartext link with
+ /// no warning although the docs call it the https:// address.
+ #[test]
+ fn the_banner_is_about_the_address_the_link_really_has() {
+ assert_eq!(
+ reach_of(false, None, "http://localhost:9200"),
+ Reach::Loopback
+ );
+ assert_eq!(
+ reach_of(false, None, "http://127.0.0.1:9510"),
+ Reach::Loopback
+ );
+ assert_eq!(
+ reach_of(false, None, "http://127.8.9.1:9510"),
+ Reach::Loopback
+ );
+ assert_eq!(reach_of(false, None, "http://[::1]:9200"), Reach::Loopback);
+ assert_eq!(
+ reach_of(false, None, "http://192.168.1.20:9200"),
+ Reach::Direct
+ );
+ assert_eq!(
+ reach_of(false, None, "https://search.example.org"),
+ Reach::Direct
+ );
+ assert_eq!(
+ reach_of(false, None, "http://localhost.evil.example:9200"),
+ Reach::Direct
+ );
+ assert_eq!(
+ reach_of(false, Some("https://x.example"), "http://localhost:9200"),
+ Reach::PublicUrl
+ );
+ assert_eq!(
+ reach_of(true, None, "http://localhost:9200"),
+ Reach::CloudflareTunnel
+ );
+
+ let lan = banner(
+ "http://192.168.1.20:9200/_xerj-console/share#id",
+ Reach::Direct,
+ "http://192.168.1.20:9200",
+ );
+ assert!(!lan.contains("only this machine can reach"), "{lan}");
+ assert!(lan.contains("plain http"), "{lan}");
+ assert!(lan.contains("unencrypted"), "{lan}");
+
+ let cleartext = banner(
+ "http://plain.example/_xerj-console/share#id",
+ Reach::PublicUrl,
+ DEFAULT_URL,
+ );
+ assert!(cleartext.contains("plain http"), "{cleartext}");
+ assert!(cleartext.contains("the passcode"), "{cleartext}");
+ let tls = banner(
+ "https://files.example.org/_xerj-console/share#id",
+ Reach::PublicUrl,
+ DEFAULT_URL,
+ );
+ assert!(!tls.contains("plain http"), "{tls}");
+ // More than one open: no one-tab hint to read past.
+ assert!(!tls.contains("one browser tab"), "{tls}");
+ }
+
+ /// Review of PR #947 (major): with a folder argument a wrong or non-admin
+ /// key was reported as "<folder> has not been indexed … run `xerj brain`
+ /// first" — `Es::get_doc` reads a `401` as "no document".
+ #[test]
+ fn a_refused_brain_lookup_is_a_key_problem_not_a_missing_brain() {
+ let unauthorized =
+ json!({"error": {"type": "security_exception", "reason": "x"}, "status": 401});
+ assert_eq!(brain_meta(401, &unauthorized), BrainMeta::Refused);
+ assert_eq!(brain_meta(403, &json!({})), BrainMeta::Refused);
+ assert_eq!(brain_meta(500, &Value::Null), BrainMeta::Refused);
+ assert_eq!(
+ brain_meta(404, &json!({"found": false})),
+ BrainMeta::NotIndexed
+ );
+ assert_eq!(brain_meta(404, &Value::Null), BrainMeta::NotIndexed);
+ assert_eq!(
+ brain_meta(200, &json!({"found": false})),
+ BrainMeta::NotIndexed
+ );
+ assert_eq!(
+ brain_meta(
+ 200,
+ &json!({"found": true, "_source": {"nodes_index": "ax-docs"}})
+ ),
+ BrainMeta::Found(json!({"nodes_index": "ax-docs"}))
+ );
+ // …and a refusal becomes the sentence about the key, never about
+ // indexing.
+ let common = Common {
+ url: "http://localhost:9200".into(),
+ data_dir: None,
+ api_key: None,
+ json: false,
+ };
+ for status in [401, 403] {
+ let text = format!("{:#}", explain(status, &unauthorized, &common));
+ assert!(text.to_lowercase().contains("admin key"), "{text}");
+ assert!(!text.contains("has not been indexed"), "{text}");
+ }
+ }
+
+ /// Review of PR #947 (minor): `--url localhost:9613` was reported as "no
+ /// xerj node answers" while the node was up.
+ #[test]
+ fn a_url_without_a_scheme_is_a_usage_error_that_says_what_to_type() {
+ let err = parse(args(&["notes", "--url", "localhost:9613"]), None).unwrap_err();
+ assert!(err.contains("http://localhost:9613"), "{err}");
+ assert!(parse(args(&["notes", "--url", "https://node.example"]), None).is_ok());
+ assert_eq!(url_host("http://localhost:9200/x"), Some("localhost"));
+ assert_eq!(url_host("https://[::1]:9200"), Some("::1"));
+ assert_eq!(url_host("http://10.0.0.7"), Some("10.0.0.7"));
+ assert_eq!(url_host("localhost:9200"), None);
+ }
+
+ #[test]
+ #[cfg(not(windows))]
+ fn pasted_follow_up_commands_survive_spaces_and_quotes() {
+ assert_eq!(sh_quote("/home/u/notes"), "/home/u/notes");
+ assert_eq!(sh_quote("http://localhost:9510"), "http://localhost:9510");
+ assert_eq!(sh_quote("/tmp/case files"), "'/tmp/case files'");
+ assert_eq!(sh_quote("it's here"), "'it'\\''s here'");
+ assert_eq!(sh_quote("$(rm -rf ~)"), "'$(rm -rf ~)'");
+ assert_eq!(sh_quote(""), "''");
+ let common = Common {
+ url: "http://localhost:9510".into(),
+ data_dir: Some(PathBuf::from("/srv/my data")),
+ api_key: None,
+ json: false,
+ };
+ assert_eq!(
+ connection_args(&common),
+ " --url http://localhost:9510 --data-dir '/srv/my data'"
+ );
+ }
+
+ /// Review of PR #947 (minor): when `cloudflared` died on its own the owner
+ /// was told "cloudflared stopped" and nothing else.
+ #[test]
+ fn cloudflareds_last_lines_are_kept_for_when_it_dies() {
+ let log = TunnelLog::default();
+ assert_eq!(tunnel_log_tail(&log), "");
+ for i in 0..(TUNNEL_LOG_LINES + 5) {
+ remember_tunnel_line(&log, &format!("INF line {i} "));
+ }
+ remember_tunnel_line(&log, "");
+ remember_tunnel_line(&log, &format!("ERR {}", "x".repeat(1000)));
+ let tail = tunnel_log_tail(&log);
+ assert!(tail.contains("cloudflared's last lines"), "{tail}");
+ assert!(
+ !tail.contains("INF line 0\n"),
+ "oldest lines are dropped: {tail}"
+ );
+ assert!(!tail.contains("INF line 5\n"), "{tail}");
+ assert!(
+ tail.contains(&format!("INF line {}", TUNNEL_LOG_LINES + 4)),
+ "{tail}"
+ );
+ assert!(tail.contains("ERR xxx"), "{tail}");
+ assert_eq!(
+ tail.lines().filter(|l| l.starts_with(" ")).count(),
+ TUNNEL_LOG_LINES
+ );
+ assert!(
+ tail.lines().all(|l| l.chars().count() <= 304),
+ "long lines are cut"
+ );
+ }
+
+ /// `xerj-api` cannot depend on `xerj-autoindex`, so it carries its own copy
+ /// of the catalog's name for the "cannot be shared" rule. They must agree.
+ #[test]
+ fn the_unshareable_catalog_is_the_catalog_autoindex_writes() {
+ assert_eq!(
+ xerj_api::share::CATALOG_INDEX,
+ xerj_autoindex::catalog::CATALOG_INDEX
+ );
+ }
+
+ #[test]
+ fn the_refusal_names_the_reason_not_just_the_rule() {
+ let text = open_mode_refusal("http://localhost:9200");
+ assert!(text.contains("authentication OFF"));
+ assert!(text.contains("--insecure"));
+ assert!(text.contains("restrict nothing"));
+ assert!(text.contains("admin.key"));
+ }
+
+ #[test]
+ fn help_documents_every_flag_and_the_refusal() {
+ let help = help_text(false);
+ for flag in [
+ "--expires",
+ "--max-claims",
+ "--passcode",
+ "--label",
+ "--brain",
+ "--index",
+ "--tunnel",
+ "--keep",
+ "--public-url",
+ "--url",
+ "--data-dir",
+ "--api-key",
+ "--json",
+ "--list",
+ "--revoke",
+ ] {
+ assert!(help.contains(flag), "help must document {flag}");
+ }
+ assert!(help.contains("REFUSES"));
+ assert!(help.contains("Read-only"));
+ assert!(help.contains("stay on this machine"));
+ assert!(help.contains("one browser tab"), "{help}");
+ }
+
+ #[test]
+ fn status_codes_become_sentences() {
+ let common = Common {
+ url: "http://localhost:9200".into(),
+ data_dir: None,
+ api_key: None,
+ json: false,
+ };
+ let text = |status, body: Value| format!("{:#}", explain(status, &body, &common));
+ assert!(text(403, json!({})).contains("not the admin key"));
+ assert!(text(401, json!({})).contains("ADMIN key"));
+ assert!(text(409, json!({})).contains("authentication OFF"));
+ assert!(text(404, json!({})).contains("older"));
+ assert!(text(405, json!({})).contains("older"));
+ assert_eq!(
+ text(404, json!({"error": {"reason": "no such index [nope]"}})),
+ "no such index [nope]"
+ );
+ assert!(text(400, json!({"error": {"reason": "bad thing"}})).contains("bad thing"));
+ }
+}
diff --git a/landing/answers/agent-memory-without-postgres-qdrant.html b/landing/answers/agent-memory-without-postgres-qdrant.html
index c510f57e1..caa596e43 100644
--- a/landing/answers/agent-memory-without-postgres-qdrant.html
+++ b/landing/answers/agent-memory-without-postgres-qdrant.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/audit-php-codebase-with-an-index.html b/landing/answers/audit-php-codebase-with-an-index.html
index 639dadfa9..f64807524 100644
--- a/landing/answers/audit-php-codebase-with-an-index.html
+++ b/landing/answers/audit-php-codebase-with-an-index.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/autoindex-exit-codes.html b/landing/answers/autoindex-exit-codes.html
index 3a9544922..272fc4991 100644
--- a/landing/answers/autoindex-exit-codes.html
+++ b/landing/answers/autoindex-exit-codes.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/autoindex-says-extract-the-archive-first.html b/landing/answers/autoindex-says-extract-the-archive-first.html
index 03a046387..83bd4af27 100644
--- a/landing/answers/autoindex-says-extract-the-archive-first.html
+++ b/landing/answers/autoindex-says-extract-the-archive-first.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/catalog-files-with-autoindex-map.html b/landing/answers/catalog-files-with-autoindex-map.html
index f51520663..d3f8893bc 100644
--- a/landing/answers/catalog-files-with-autoindex-map.html
+++ b/landing/answers/catalog-files-with-autoindex-map.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/cheap-low-volume-log-search.html b/landing/answers/cheap-low-volume-log-search.html
index 20883343c..d6e410f7a 100644
--- a/landing/answers/cheap-low-volume-log-search.html
+++ b/landing/answers/cheap-low-volume-log-search.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/check-codebase-index-is-complete.html b/landing/answers/check-codebase-index-is-complete.html
index e17e0339d..4056af317 100644
--- a/landing/answers/check-codebase-index-is-complete.html
+++ b/landing/answers/check-codebase-index-is-complete.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/classify-text-from-labelled-history-without-llm.html b/landing/answers/classify-text-from-labelled-history-without-llm.html
index 064c66d35..ad948efa6 100644
--- a/landing/answers/classify-text-from-labelled-history-without-llm.html
+++ b/landing/answers/classify-text-from-labelled-history-without-llm.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/code-search-mcp-for-claude-code.html b/landing/answers/code-search-mcp-for-claude-code.html
index 69f6ec975..4533ac74c 100644
--- a/landing/answers/code-search-mcp-for-claude-code.html
+++ b/landing/answers/code-search-mcp-for-claude-code.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/coding-agent-memory-across-sessions.html b/landing/answers/coding-agent-memory-across-sessions.html
index cbf3e5ed0..fb584366d 100644
--- a/landing/answers/coding-agent-memory-across-sessions.html
+++ b/landing/answers/coding-agent-memory-across-sessions.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/do-search-embeddings-help.html b/landing/answers/do-search-embeddings-help.html
index f63c0421c..ab1cfada1 100644
--- a/landing/answers/do-search-embeddings-help.html
+++ b/landing/answers/do-search-embeddings-help.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/does-xerj-support-s3-alerting-plugins.html b/landing/answers/does-xerj-support-s3-alerting-plugins.html
index 5641472e3..9256b92a3 100644
--- a/landing/answers/does-xerj-support-s3-alerting-plugins.html
+++ b/landing/answers/does-xerj-support-s3-alerting-plugins.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/estimate-autoindex-time-before-running.html b/landing/answers/estimate-autoindex-time-before-running.html
index cb12bb853..7c258f06c 100644
--- a/landing/answers/estimate-autoindex-time-before-running.html
+++ b/landing/answers/estimate-autoindex-time-before-running.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/evidence-for-agent-memory-links.html b/landing/answers/evidence-for-agent-memory-links.html
index 374130ecf..f49994e7d 100644
--- a/landing/answers/evidence-for-agent-memory-links.html
+++ b/landing/answers/evidence-for-agent-memory-links.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/filter-knn-exact-scan-caveat.html b/landing/answers/filter-knn-exact-scan-caveat.html
index 4f6fac9a2..50271fe04 100644
--- a/landing/answers/filter-knn-exact-scan-caveat.html
+++ b/landing/answers/filter-knn-exact-scan-caveat.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class="active"><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/full-text-search-browser-history.html b/landing/answers/full-text-search-browser-history.html
index 6b1bf036d..1bc29b122 100644
--- a/landing/answers/full-text-search-browser-history.html
+++ b/landing/answers/full-text-search-browser-history.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/full-text-search-sqlite-database.html b/landing/answers/full-text-search-sqlite-database.html
index 41b066fdc..9d48e6ac2 100644
--- a/landing/answers/full-text-search-sqlite-database.html
+++ b/landing/answers/full-text-search-sqlite-database.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/give-chatgpt-claude-local-file-access.html b/landing/answers/give-chatgpt-claude-local-file-access.html
index a9d120f5e..f21a4eb74 100644
--- a/landing/answers/give-chatgpt-claude-local-file-access.html
+++ b/landing/answers/give-chatgpt-claude-local-file-access.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/how-xerj-autoindexes-a-folder.html b/landing/answers/how-xerj-autoindexes-a-folder.html
index 75ff2a2d8..60e047403 100644
--- a/landing/answers/how-xerj-autoindexes-a-folder.html
+++ b/landing/answers/how-xerj-autoindexes-a-folder.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/how-xerj-combines-search.html b/landing/answers/how-xerj-combines-search.html
index db89e4e63..7d3f10d4f 100644
--- a/landing/answers/how-xerj-combines-search.html
+++ b/landing/answers/how-xerj-combines-search.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/hybrid-search-quality-measured-ndcg.html b/landing/answers/hybrid-search-quality-measured-ndcg.html
index 2b974f642..596530869 100644
--- a/landing/answers/hybrid-search-quality-measured-ndcg.html
+++ b/landing/answers/hybrid-search-quality-measured-ndcg.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/improve-basic-faiss-rag-pipeline.html b/landing/answers/improve-basic-faiss-rag-pipeline.html
index 476f64997..f5c2cd803 100644
--- a/landing/answers/improve-basic-faiss-rag-pipeline.html
+++ b/landing/answers/improve-basic-faiss-rag-pipeline.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class="active"><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/index-csv-with-many-columns.html b/landing/answers/index-csv-with-many-columns.html
index 56c49c565..2f557e2d8 100644
--- a/landing/answers/index-csv-with-many-columns.html
+++ b/landing/answers/index-csv-with-many-columns.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/index-markdown-into-elasticsearch-api.html b/landing/answers/index-markdown-into-elasticsearch-api.html
index ae4259dec..4d198efe5 100644
--- a/landing/answers/index-markdown-into-elasticsearch-api.html
+++ b/landing/answers/index-markdown-into-elasticsearch-api.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/index-monorepo-for-agent.html b/landing/answers/index-monorepo-for-agent.html
index 473d2e6ca..68dfdf405 100644
--- a/landing/answers/index-monorepo-for-agent.html
+++ b/landing/answers/index-monorepo-for-agent.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/index-multiple-csv-files.html b/landing/answers/index-multiple-csv-files.html
index 2a0a4cfc5..ee1a29767 100644
--- a/landing/answers/index-multiple-csv-files.html
+++ b/landing/answers/index-multiple-csv-files.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/index-reference-library-for-coding-agent.html b/landing/answers/index-reference-library-for-coding-agent.html
index 765570ba0..8618dc9e8 100644
--- a/landing/answers/index-reference-library-for-coding-agent.html
+++ b/landing/answers/index-reference-library-for-coding-agent.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/index.html b/landing/answers/index.html
index f60362590..c8f946b3e 100644
--- a/landing/answers/index.html
+++ b/landing/answers/index.html
@@ -190,6 +190,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
@@ -396,6 +399,12 @@
<ul>
<li><a href="/answers/vector-database-vs-full-text-search">What's the actual difference between a vector database and full-text search when I have a folder?</a> — Full-text search matches tokens, kNN matches vectors, hybrid fuses both. XERJ serves all three from one index over an indexed folder, so the choice is a clause.</li>
</ul>
+ <h2>Sharing: read-only guest access</h2>
+ <ul>
+ <li><a href="/answers/share-folder-read-only-search-without-uploading">How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a> — Index the folder on your own machine, then run xerj share: the other person gets a link, a passcode and a read-only search page. The folder is not uploaded.</li>
+ <li><a href="/answers/share-local-search-index-through-a-tunnel">How do I let someone outside my network search an index on my laptop without opening a port?</a> — xerj share --tunnel starts your own cloudflared, prints a public guest link, and closes the tunnel and revokes the share on Ctrl-C. What the trade is.</li>
+ <li><a href="/answers/what-a-share-link-guest-can-reach">If I share one index with a link and a passcode, what can that person actually reach on my node?</a> — A share-link guest key reads the shared index and nothing else: no other index, no _cat or _cluster, no writes, no scroll or PIT. Each refusal is a live test.</li>
+ </ul>
</main>
</div>
<!-- seo:footer-begin — generated by scripts/seo/fix_links.py · do not hand-edit -->
diff --git a/landing/answers/index.json b/landing/answers/index.json
index 739519263..248d7da68 100644
--- a/landing/answers/index.json
+++ b/landing/answers/index.json
@@ -613,6 +613,33 @@
"cluster": "Retrieval: selection",
"updated": "2026-08-23",
"summary": "Full-text search matches tokens, kNN matches vectors, hybrid fuses both. XERJ serves all three from one index over an indexed folder, so the choice is a clause."
+ },
+ {
+ "title": "Read-only search over a folder, without uploading it",
+ "question": "I need my accountant to search a folder of emails and PDFs. How do I do that without uploading everything somewhere?",
+ "canonical_url": "https://xerj.org/answers/share-folder-read-only-search-without-uploading",
+ "markdown_url": "https://xerj.org/answers/share-folder-read-only-search-without-uploading.md",
+ "cluster": "Sharing: read-only guest access",
+ "updated": "2026-09-19",
+ "summary": "Index the folder on your own machine, then run xerj share: the other person gets a link, a passcode and a read-only search page. The folder is not uploaded."
+ },
+ {
+ "title": "Share a local search index through a tunnel",
+ "question": "How can I give a remote person temporary search access to files on my laptop without port forwarding or a VPN?",
+ "canonical_url": "https://xerj.org/answers/share-local-search-index-through-a-tunnel",
+ "markdown_url": "https://xerj.org/answers/share-local-search-index-through-a-tunnel.md",
+ "cluster": "Sharing: read-only guest access",
+ "updated": "2026-09-19",
+ "summary": "xerj share --tunnel starts your own cloudflared, prints a public guest link, and closes the tunnel and revokes the share on Ctrl-C. What the trade is."
+ },
+ {
+ "title": "What a XERJ share-link guest can and cannot reach",
+ "question": "If I give someone a read-only share link to one search index, can they see my other indices or anything else on the server?",
+ "canonical_url": "https://xerj.org/answers/what-a-share-link-guest-can-reach",
+ "markdown_url": "https://xerj.org/answers/what-a-share-link-guest-can-reach.md",
+ "cluster": "Sharing: read-only guest access",
+ "updated": "2026-09-19",
+ "summary": "A share-link guest key reads the shared index and nothing else: no other index, no _cat or _cluster, no writes, no scroll or PIT. Each refusal is a live test."
}
]
}
diff --git a/landing/answers/is-pdf-indexing-efficient.html b/landing/answers/is-pdf-indexing-efficient.html
index 666612151..4469a018a 100644
--- a/landing/answers/is-pdf-indexing-efficient.html
+++ b/landing/answers/is-pdf-indexing-efficient.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/keep-index-current-as-files-change.html b/landing/answers/keep-index-current-as-files-change.html
index f00c6dc4f..e045bcf25 100644
--- a/landing/answers/keep-index-current-as-files-change.html
+++ b/landing/answers/keep-index-current-as-files-change.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/knowledge-graphs-for-agent-memory.html b/landing/answers/knowledge-graphs-for-agent-memory.html
index a87e1b27c..9aa3dcdb8 100644
--- a/landing/answers/knowledge-graphs-for-agent-memory.html
+++ b/landing/answers/knowledge-graphs-for-agent-memory.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/local-embeddings-without-openai-api.html b/landing/answers/local-embeddings-without-openai-api.html
index 8dd0f7a0e..75315cb29 100644
--- a/landing/answers/local-embeddings-without-openai-api.html
+++ b/landing/answers/local-embeddings-without-openai-api.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/mcp-api-search-or-vector-search.html b/landing/answers/mcp-api-search-or-vector-search.html
index a8f8a643d..4c3461ff3 100644
--- a/landing/answers/mcp-api-search-or-vector-search.html
+++ b/landing/answers/mcp-api-search-or-vector-search.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/notion-export-duplicate-search-results.html b/landing/answers/notion-export-duplicate-search-results.html
index c5bfad099..5d0c1f528 100644
--- a/landing/answers/notion-export-duplicate-search-results.html
+++ b/landing/answers/notion-export-duplicate-search-results.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/private-agent-memory-namespaces.html b/landing/answers/private-agent-memory-namespaces.html
index 5d0db9e1c..3befbe327 100644
--- a/landing/answers/private-agent-memory-namespaces.html
+++ b/landing/answers/private-agent-memory-namespaces.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/rag-without-vector-database.html b/landing/answers/rag-without-vector-database.html
index b78502ef0..4ab2ed985 100644
--- a/landing/answers/rag-without-vector-database.html
+++ b/landing/answers/rag-without-vector-database.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/read-autoindex-progress.html b/landing/answers/read-autoindex-progress.html
index 8ce98e06d..d3f6c0886 100644
--- a/landing/answers/read-autoindex-progress.html
+++ b/landing/answers/read-autoindex-progress.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/reciprocal-rank-fusion-when-to-use.html b/landing/answers/reciprocal-rank-fusion-when-to-use.html
index b068366be..8fdb4d3fa 100644
--- a/landing/answers/reciprocal-rank-fusion-when-to-use.html
+++ b/landing/answers/reciprocal-rank-fusion-when-to-use.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/reduce-embedding-api-cost.html b/landing/answers/reduce-embedding-api-cost.html
index e82ca68bd..c67ce9b35 100644
--- a/landing/answers/reduce-embedding-api-cost.html
+++ b/landing/answers/reduce-embedding-api-cost.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/reindex-taking-forever.html b/landing/answers/reindex-taking-forever.html
index dd3fb01e9..30ba58db0 100644
--- a/landing/answers/reindex-taking-forever.html
+++ b/landing/answers/reindex-taking-forever.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/rerank-search-results-calibrated-judge.html b/landing/answers/rerank-search-results-calibrated-judge.html
index c0aafa2fb..a7e1c50eb 100644
--- a/landing/answers/rerank-search-results-calibrated-judge.html
+++ b/landing/answers/rerank-search-results-calibrated-judge.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/resume-interrupted-autoindex-run.html b/landing/answers/resume-interrupted-autoindex-run.html
index 214b0076c..1f28d8688 100644
--- a/landing/answers/resume-interrupted-autoindex-run.html
+++ b/landing/answers/resume-interrupted-autoindex-run.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-all-pdfs-in-a-folder.html b/landing/answers/search-all-pdfs-in-a-folder.html
index 9a15da0c2..5d701b418 100644
--- a/landing/answers/search-all-pdfs-in-a-folder.html
+++ b/landing/answers/search-all-pdfs-in-a-folder.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-bvh-motion-capture-files.html b/landing/answers/search-bvh-motion-capture-files.html
index 0527819d6..6338738a6 100644
--- a/landing/answers/search-bvh-motion-capture-files.html
+++ b/landing/answers/search-bvh-motion-capture-files.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-confluence-html-export.html b/landing/answers/search-confluence-html-export.html
index f2305745a..0683fb535 100644
--- a/landing/answers/search-confluence-html-export.html
+++ b/landing/answers/search-confluence-html-export.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-engine-without-docker.html b/landing/answers/search-engine-without-docker.html
index 0dd8ce0c6..9eafdf21a 100644
--- a/landing/answers/search-engine-without-docker.html
+++ b/landing/answers/search-engine-without-docker.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-file-contents-in-a-folder.html b/landing/answers/search-file-contents-in-a-folder.html
index 077c7b180..a8926b0ed 100644
--- a/landing/answers/search-file-contents-in-a-folder.html
+++ b/landing/answers/search-file-contents-in-a-folder.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-files-in-an-s3-bucket.html b/landing/answers/search-files-in-an-s3-bucket.html
index 49e5441cd..87a9ca92f 100644
--- a/landing/answers/search-files-in-an-s3-bucket.html
+++ b/landing/answers/search-files-in-an-s3-bucket.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-gmail-takeout-mbox-locally.html b/landing/answers/search-gmail-takeout-mbox-locally.html
index 724b633a3..8c6a855c0 100644
--- a/landing/answers/search-gmail-takeout-mbox-locally.html
+++ b/landing/answers/search-gmail-takeout-mbox-locally.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-gzip-logs-without-zgrep.html b/landing/answers/search-gzip-logs-without-zgrep.html
index a8f1a0b3a..b267be7c2 100644
--- a/landing/answers/search-gzip-logs-without-zgrep.html
+++ b/landing/answers/search-gzip-logs-without-zgrep.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-gzipped-csv-or-json.html b/landing/answers/search-gzipped-csv-or-json.html
index b7a465190..98cd375d6 100644
--- a/landing/answers/search-gzipped-csv-or-json.html
+++ b/landing/answers/search-gzipped-csv-or-json.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-html-export.html b/landing/answers/search-html-export.html
index 829c25cd1..010bc21c0 100644
--- a/landing/answers/search-html-export.html
+++ b/landing/answers/search-html-export.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-json-and-jsonl-logs.html b/landing/answers/search-json-and-jsonl-logs.html
index ae1aa6245..c01ccba85 100644
--- a/landing/answers/search-json-and-jsonl-logs.html
+++ b/landing/answers/search-json-and-jsonl-logs.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-jupyter-notebook-cells.html b/landing/answers/search-jupyter-notebook-cells.html
index b604d121b..885764c74 100644
--- a/landing/answers/search-jupyter-notebook-cells.html
+++ b/landing/answers/search-jupyter-notebook-cells.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-kubernetes-pod-logs-on-disk.html b/landing/answers/search-kubernetes-pod-logs-on-disk.html
index 6102c5723..e9268f2a8 100644
--- a/landing/answers/search-kubernetes-pod-logs-on-disk.html
+++ b/landing/answers/search-kubernetes-pod-logs-on-disk.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-obsidian-pdf-docx-attachments.html b/landing/answers/search-obsidian-pdf-docx-attachments.html
index 2b4e4a677..e742f5eaf 100644
--- a/landing/answers/search-obsidian-pdf-docx-attachments.html
+++ b/landing/answers/search-obsidian-pdf-docx-attachments.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-openapi-spec-for-agent.html b/landing/answers/search-openapi-spec-for-agent.html
index 7ab0fcfc9..dd2a054d8 100644
--- a/landing/answers/search-openapi-spec-for-agent.html
+++ b/landing/answers/search-openapi-spec-for-agent.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-slack-json-export.html b/landing/answers/search-slack-json-export.html
index 79ae5eebf..9cfe00735 100644
--- a/landing/answers/search-slack-json-export.html
+++ b/landing/answers/search-slack-json-export.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-sql-dump-file.html b/landing/answers/search-sql-dump-file.html
index c8677acce..4817f94a7 100644
--- a/landing/answers/search-sql-dump-file.html
+++ b/landing/answers/search-sql-dump-file.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-unity-project-assets.html b/landing/answers/search-unity-project-assets.html
index e566aa329..887ad69be 100644
--- a/landing/answers/search-unity-project-assets.html
+++ b/landing/answers/search-unity-project-assets.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-word-documents-in-a-folder.html b/landing/answers/search-word-documents-in-a-folder.html
index 82180688e..7e87b71fe 100644
--- a/landing/answers/search-word-documents-in-a-folder.html
+++ b/landing/answers/search-word-documents-in-a-folder.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-yaml-xml-config-repository.html b/landing/answers/search-yaml-xml-config-repository.html
index df100e844..327674564 100644
--- a/landing/answers/search-yaml-xml-config-repository.html
+++ b/landing/answers/search-yaml-xml-config-repository.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/search-zendesk-ticket-json-export.html b/landing/answers/search-zendesk-ticket-json-export.html
index 9b7d874de..62248ec3c 100644
--- a/landing/answers/search-zendesk-ticket-json-export.html
+++ b/landing/answers/search-zendesk-ticket-json-export.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/set-mcp-memory-storage-path.html b/landing/answers/set-mcp-memory-storage-path.html
index 5c3ea91e1..92711e3d6 100644
--- a/landing/answers/set-mcp-memory-storage-path.html
+++ b/landing/answers/set-mcp-memory-storage-path.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/share-folder-read-only-search-without-uploading.html b/landing/answers/share-folder-read-only-search-without-uploading.html
new file mode 100644
index 000000000..06b03e6fe
--- /dev/null
+++ b/landing/answers/share-folder-read-only-search-without-uploading.html
@@ -0,0 +1,398 @@
+<!-- generated by build_articles.py — edit content/answers/share-folder-read-only-search-without-uploading.md instead -->
+<!DOCTYPE html>
+<html lang="en" data-theme="day">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>Read-only search over a folder, without uploading it</title>
+<meta name="description" content="Index the folder on your own machine, then run xerj share: the other person gets a link, a passcode and a read-only search page. The folder is not uploaded.">
+<link rel="preconnect" href="https://fonts.googleapis.com">
+<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+<link href="https://fonts.googleapis.com/css2?family=Big+Shoulders+Display:wght@400;700;800;900&family=Inter:wght@400;500;600;700&family=IBM+Plex+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">
+<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><rect width='100' height='100' fill='%230b0b0d'/><text x='50' y='68' font-size='60' font-family='Big Shoulders Display,sans-serif' font-weight='900' fill='%23ffc400' text-anchor='middle'>X</text></svg>">
+<link rel="stylesheet" href="/style.css?v=90f643e">
+<link rel="alternate" type="text/markdown" href="/answers/share-folder-read-only-search-without-uploading.md">
+<!-- seo:begin — generated by scripts/seo/fix_heads.py · do not hand-edit -->
+<link rel="canonical" href="https://xerj.org/answers/share-folder-read-only-search-without-uploading">
+<meta property="og:site_name" content="XERJ.ai">
+<meta property="og:type" content="article">
+<meta property="og:title" content="Read-only search over a folder, without uploading it">
+<meta property="og:description" content="Index the folder on your own machine, then run xerj share: the other person gets a link, a passcode and a read-only search page. The folder is not uploaded.">
+<meta property="og:url" content="https://xerj.org/answers/share-folder-read-only-search-without-uploading">
+<meta property="og:image" content="https://xerj.org/og/xerj-card.png">
+<meta property="og:image:width" content="1200">
+<meta property="og:image:height" content="630">
+<meta property="og:image:alt" content="XERJ.ai — the search engine built for AI agents">
+<meta property="og:locale" content="en_US">
+<meta name="twitter:card" content="summary_large_image">
+<meta name="twitter:title" content="Read-only search over a folder, without uploading it">
+<meta name="twitter:description" content="Index the folder on your own machine, then run xerj share: the other person gets a link, a passcode and a read-only search page. The folder is not uploaded.">
+<meta name="twitter:image" content="https://xerj.org/og/xerj-card.png">
+<script type="application/ld+json">
+{
+ "@context": "https://schema.org",
+ "@type": "Organization",
+ "@id": "https://xerj.org/#organization",
+ "name": "XERJ",
+ "alternateName": "XERJ.ai",
+ "url": "https://xerj.org/",
+ "logo": "https://xerj.org/brandbook/xerj-mark.svg",
+ "sameAs": [
+ "https://github.com/xerj-org/xerj"
+ ]
+}
+</script>
+<script type="application/ld+json">
+{
+ "@context": "https://schema.org",
+ "@type": "WebSite",
+ "@id": "https://xerj.org/#website",
+ "name": "XERJ.ai",
+ "url": "https://xerj.org/",
+ "inLanguage": "en",
+ "publisher": {
+ "@id": "https://xerj.org/#organization"
+ }
+}
+</script>
+<script type="application/ld+json">
+{
+ "@context": "https://schema.org",
+ "@type": "TechArticle",
+ "headline": "Read-only search over a folder, without uploading it",
+ "description": "Index the folder on your own machine, then run xerj share: the other person gets a link, a passcode and a read-only search page. The folder is not uploaded.",
+ "url": "https://xerj.org/answers/share-folder-read-only-search-without-uploading",
+ "image": "https://xerj.org/og/xerj-card.png",
+ "inLanguage": "en",
+ "datePublished": "2026-09-18",
+ "dateModified": "2026-09-19",
+ "author": {
+ "@type": "Person",
+ "name": "XERJ documentation team"
+ },
+ "publisher": {
+ "@id": "https://xerj.org/#organization"
+ },
+ "isPartOf": {
+ "@id": "https://xerj.org/#website"
+ },
+ "mainEntityOfPage": {
+ "@type": "WebPage",
+ "@id": "https://xerj.org/answers/share-folder-read-only-search-without-uploading"
+ },
+ "reviewedBy": {
+ "@type": "Person",
+ "name": "XERJ engineering team"
+ }
+}
+</script>
+<script type="application/ld+json">
+{
+ "@context": "https://schema.org",
+ "@type": "BreadcrumbList",
+ "itemListElement": [
+ {
+ "@type": "ListItem",
+ "position": 1,
+ "name": "Home",
+ "item": "https://xerj.org/"
+ },
+ {
+ "@type": "ListItem",
+ "position": 2,
+ "name": "Answers",
+ "item": "https://xerj.org/answers/"
+ },
+ {
+ "@type": "ListItem",
+ "position": 3,
+ "name": "How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?"
+ }
+ ]
+}
+</script>
+<!-- seo:end -->
+</head>
+<body>
+<nav class="nav" aria-label="Primary">
+ <a href="/" class="brand">XERJ.AI</a>
+ <a href="/">HOME</a>
+ <a href="/product">PRODUCT</a>
+ <span class="nav-drop">
+ <a href="/use-cases">USE CASES</a>
+ </span>
+ <a href="/case-studies">CASE STUDIES</a>
+ <a href="/benchmarks/">BENCHMARKS</a>
+ <span class="spacer"></span>
+ <a href="/for-agents">FOR AGENTS</a>
+ <a href="/docs/" class="active">DOCS</a>
+ <a href="/docs/recipes/">RECIPES</a>
+ <a href="/playground">DASHBOARDS</a>
+ <a href="https://github.com/xerj-org/xerj" rel="external">GITHUB</a>
+ <span class="spacer"></span>
+ <span class="theme">
+ <button type="button" data-theme="day" class="active">DAY</button>
+ <span class="dash">·</span>
+ <button type="button" data-theme="night">NIGHT</button>
+ </span>
+</nav>
+<div class="docs-shell">
+<nav class="docs-nav" aria-label="Article sections">
+ <div class="group">
+ <span class="label">ANSWERS</span>
+ <a href="/answers/"><span class="eyebrow">00</span>All Answers</a>
+ <a href="/answers/give-chatgpt-claude-local-file-access" class=""><span class="eyebrow">01</span>Can ChatGPT search a folder on my laptop, or do I need something else?</a>
+ <a href="/answers/code-search-mcp-for-claude-code" class=""><span class="eyebrow">02</span>I need my agent to find a passage and cite the file, not dump the whole tree. How?</a>
+ <a href="/answers/mcp-api-search-or-vector-search" class=""><span class="eyebrow">03</span>Should an agent use API search or vector search?</a>
+ <a href="/answers/knowledge-graphs-for-agent-memory" class=""><span class="eyebrow">04</span>Should agent memory use a knowledge graph?</a>
+ <a href="/answers/store-agent-memory-without-llm-call" class=""><span class="eyebrow">05</span>How do I stop an agent memory store from filling with near-duplicate notes?</a>
+ <a href="/answers/evidence-for-agent-memory-links" class=""><span class="eyebrow">06</span>How can agent-memory links retain evidence?</a>
+ <a href="/answers/private-agent-memory-namespaces" class=""><span class="eyebrow">07</span>How do I give two agents private memory on one laptop?</a>
+ <a href="/answers/coding-agent-memory-across-sessions" class=""><span class="eyebrow">08</span>How do people store user preferences so an agent can recall them next week?</a>
+ <a href="/answers/set-mcp-memory-storage-path" class=""><span class="eyebrow">09</span>How do I set the MCP memory storage path?</a>
+ <a href="/answers/agent-memory-without-postgres-qdrant" class=""><span class="eyebrow">10</span>What's a simple way to give an agent long-term memory on my laptop without Qdrant?</a>
+ <a href="/answers/does-xerj-support-s3-alerting-plugins" class=""><span class="eyebrow">11</span>Does XERJ support S3 storage, alerting or custom plugins yet?</a>
+ <a href="/answers/audit-php-codebase-with-an-index" class=""><span class="eyebrow">12</span>How do I audit a PHP codebase with an index instead of grepping 1,400 files?</a>
+ <a href="/answers/index-reference-library-for-coding-agent" class=""><span class="eyebrow">13</span>How do I set up reference coding so the agent retrieves a mechanism before writing code?</a>
+ <a href="/answers/classify-text-from-labelled-history-without-llm" class=""><span class="eyebrow">14</span>Can I route tickets or filter spam from labelled history, without an LLM call?</a>
+ <a href="/answers/reduce-embedding-api-cost" class=""><span class="eyebrow">15</span>How do I reduce embedding API cost?</a>
+ <a href="/answers/local-embeddings-without-openai-api" class=""><span class="eyebrow">16</span>I want local search that works offline, no cloud embeddings. What are my options?</a>
+ <a href="/answers/do-search-embeddings-help" class=""><span class="eyebrow">17</span>When should I turn on neural embeddings, and when is the lexical default enough?</a>
+ <a href="/answers/search-yaml-xml-config-repository" class=""><span class="eyebrow">18</span>How do I find every place a config key is set across YAML and XML in a repo?</a>
+ <a href="/answers/full-text-search-sqlite-database" class=""><span class="eyebrow">19</span>How do I full-text search a SQLite database I just copied onto disk?</a>
+ <a href="/answers/index-csv-with-many-columns" class=""><span class="eyebrow">20</span>How do I index a CSV with many columns?</a>
+ <a href="/answers/index-markdown-into-elasticsearch-api" class=""><span class="eyebrow">21</span>How do I index Markdown into the Elasticsearch API?</a>
+ <a href="/answers/syntax-aware-code-search-refactoring" class=""><span class="eyebrow">22</span>How do I run syntax-aware code search?</a>
+ <a href="/answers/search-gzipped-csv-or-json" class=""><span class="eyebrow">23</span>How do I search a .csv.gz or .json.gz without unzipping it first?</a>
+ <a href="/answers/search-confluence-html-export" class=""><span class="eyebrow">24</span>How do I search a Confluence export?</a>
+ <a href="/answers/search-slack-json-export" class=""><span class="eyebrow">25</span>How do I search a Slack JSON export?</a>
+ <a href="/answers/search-bvh-motion-capture-files" class=""><span class="eyebrow">26</span>How do I search BVH motion-capture files?</a>
+ <a href="/answers/search-gzip-logs-without-zgrep" class=""><span class="eyebrow">27</span>How do I search gzipped logs without decompressing the whole file — including when JSONL sits next to them?</a>
+ <a href="/answers/search-kubernetes-pod-logs-on-disk" class=""><span class="eyebrow">28</span>How do I search Kubernetes pod logs?</a>
+ <a href="/answers/search-word-documents-in-a-folder" class=""><span class="eyebrow">29</span>How do I search through a folder of contracts in .docx?</a>
+ <a href="/answers/search-unity-project-assets" class=""><span class="eyebrow">30</span>How do I search Unity YAML scenes and the C# that references them as one project?</a>
+ <a href="/answers/index-monorepo-for-agent" class=""><span class="eyebrow">31</span>How do I stop my agent from reading the whole repo into context?</a>
+ <a href="/answers/catalog-files-with-autoindex-map" class=""><span class="eyebrow">32</span>How should an agent figure out what's in a messy data folder before searching?</a>
+ <a href="/answers/search-all-pdfs-in-a-folder" class=""><span class="eyebrow">33</span>I downloaded a bunch of papers as PDFs. How do I search across them?</a>
+ <a href="/answers/search-sql-dump-file" class=""><span class="eyebrow">34</span>I have a 2GB SQL dump. How do I find rows mentioning a customer without loading it into Postgres?</a>
+ <a href="/answers/index-multiple-csv-files" class=""><span class="eyebrow">35</span>I have a directory of CSV exports. How do I query them without opening each one in Excel?</a>
+ <a href="/answers/search-file-contents-in-a-folder" class=""><span class="eyebrow">36</span>I have a folder of PDFs, Word docs, and markdown. How do I search all of them at once?</a>
+ <a href="/answers/search-zendesk-ticket-json-export" class=""><span class="eyebrow">37</span>I have a JSON export of Jira issues (or Zendesk tickets). How do I search it like a help-center search?</a>
+ <a href="/answers/search-jupyter-notebook-cells" class=""><span class="eyebrow">38</span>I need to find a function I wrote in a notebook months ago. How do I search all .ipynb files and the .py next to them?</a>
+ <a href="/answers/search-html-export" class=""><span class="eyebrow">39</span>I saved a help-center as HTML. How do I search it like the real help-center search?</a>
+ <a href="/answers/is-pdf-indexing-efficient" class=""><span class="eyebrow">40</span>Is it efficient to index PDF files?</a>
+ <a href="/answers/full-text-search-browser-history" class=""><span class="eyebrow">41</span>Is there a way to full-text search my browser history file itself?</a>
+ <a href="/answers/search-openapi-spec-for-agent" class=""><span class="eyebrow">42</span>My agent needs to look up endpoints in a big OpenAPI spec and the SDK markdown. What's the right way?</a>
+ <a href="/answers/search-obsidian-pdf-docx-attachments" class=""><span class="eyebrow">43</span>What's the best way to search markdown notes and PDFs in the same vault?</a>
+ <a href="/answers/search-json-and-jsonl-logs" class=""><span class="eyebrow">44</span>What's the easiest way to search JSON logs plus some old gzip text logs in the same folder?</a>
+ <a href="/answers/notion-export-duplicate-search-results" class=""><span class="eyebrow">45</span>Why does my Notion export duplicate titles?</a>
+ <a href="/answers/search-gmail-takeout-mbox-locally" class=""><span class="eyebrow">46</span>I exported my Gmail with Google Takeout. How do I search that mbox file locally?</a>
+ <a href="/answers/how-xerj-autoindexes-a-folder" class=""><span class="eyebrow">47</span>I want to point something at a folder and then ask questions about what's in it. What should I use?</a>
+ <a href="/answers/rag-without-vector-database" class=""><span class="eyebrow">48</span>How do I build RAG without a vector database?</a>
+ <a href="/answers/hybrid-search-quality-measured-ndcg" class=""><span class="eyebrow">49</span>How much better is hybrid search than BM25? Measured nDCG numbers</a>
+ <a href="/answers/rerank-search-results-calibrated-judge" class=""><span class="eyebrow">50</span>How do I rerank search results with a calibrated relevance judge?</a>
+ <a href="/answers/reciprocal-rank-fusion-when-to-use" class=""><span class="eyebrow">51</span>What is Reciprocal Rank Fusion?</a>
+ <a href="/answers/how-xerj-combines-search" class=""><span class="eyebrow">52</span>How does XERJ combine BM25 and kNN?</a>
+ <a href="/answers/search-files-in-an-s3-bucket" class=""><span class="eyebrow">53</span>How do I search files that live in an S3 bucket?</a>
+ <a href="/answers/check-codebase-index-is-complete" class=""><span class="eyebrow">54</span>My codebase indexer says indexed but I don't see my code. How do I check it actually finished?</a>
+ <a href="/answers/estimate-autoindex-time-before-running" class=""><span class="eyebrow">55</span>How do I estimate folder-indexing time?</a>
+ <a href="/answers/why-autoindex-skipped-files" class=""><span class="eyebrow">56</span>Why would a folder search miss files that I can see on disk?</a>
+ <a href="/answers/autoindex-exit-codes" class=""><span class="eyebrow">57</span>The indexer exited 3 (or 4). Did it fail?</a>
+ <a href="/answers/autoindex-says-extract-the-archive-first" class=""><span class="eyebrow">58</span>xerj autoindex recorded my Takeout .zip as junk and said to extract it first. Why?</a>
+ <a href="/answers/keep-index-current-as-files-change" class=""><span class="eyebrow">59</span>How do I keep a search index up to date as files change, without re-indexing everything?</a>
+ <a href="/answers/search-engine-without-docker" class=""><span class="eyebrow">60</span>Is there a single-binary local search engine I can just run?</a>
+ <a href="/answers/cheap-low-volume-log-search" class=""><span class="eyebrow">61</span>What can I use for low-volume log search?</a>
+ <a href="/answers/read-autoindex-progress" class=""><span class="eyebrow">62</span>How do I read autoindex progress?</a>
+ <a href="/answers/resume-interrupted-autoindex-run" class=""><span class="eyebrow">63</span>The indexer died overnight. Do I have to start over?</a>
+ <a href="/answers/reindex-taking-forever" class=""><span class="eyebrow">64</span>Reindexing my files is taking forever. What usually causes that?</a>
+ <a href="/answers/what-is-xerj" class=""><span class="eyebrow">65</span>What is XERJ?</a>
+ <a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
+ <a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
+ <a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class="active"><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
+ </div>
+ <div class="group">
+ <span class="label">COMPARISONS</span>
+ <a href="/compare/"><span class="eyebrow">00</span>All Comparisons</a>
+ <a href="/compare/xerj-vs-web-agent-search" class=""><span class="eyebrow">01</span>How do I let an agent search a folder on my laptop instead of crawling the web?</a>
+ <a href="/compare/xerj-vs-ast-grep" class=""><span class="eyebrow">02</span>ast-grep vs a code index for an agent?</a>
+ <a href="/compare/xerj-vs-ripgrep-for-code-agents" class=""><span class="eyebrow">03</span>Is ripgrep enough for a coding agent, or do I need a code index?</a>
+ <a href="/compare/xerj-vs-ripgrep-all" class=""><span class="eyebrow">04</span>How do I grep PDFs and Word docs from the command line?</a>
+ <a href="/compare/xerj-vs-docfetcher" class=""><span class="eyebrow">05</span>What's a free DocFetcher alternative that an agent can call?</a>
+ <a href="/compare/xerj-vs-recoll" class=""><span class="eyebrow">06</span>What's the best local desktop search for a folder of PDFs and docs?</a>
+ <a href="/compare/xerj-vs-houdahspot" class=""><span class="eyebrow">07</span>XERJ vs HoudahSpot — Spotlight GUI vs an agent index</a>
+ <a href="/compare/xerj-vs-spotlight" class=""><span class="eyebrow">08</span>XERJ vs macOS Spotlight for folder content an agent can query</a>
+ <a href="/compare/xerj-vs-localsynapse" class=""><span class="eyebrow">09</span>What's a local MCP search engine for Claude?</a>
+ <a href="/compare/xerj-vs-elasticsearch-local" class=""><span class="eyebrow">10</span>Is there an Elasticsearch-compatible engine that isn't Elasticsearch?</a>
+ <a href="/compare/xerj-vs-obsidian-omnisearch" class=""><span class="eyebrow">11</span>How do I search an Obsidian vault from outside Obsidian?</a>
+ <a href="/compare/xerj-vs-khoj" class=""><span class="eyebrow">12</span>What's a simpler alternative to Khoj if I only need search and memory?</a>
+ <a href="/compare/xerj-vs-typesense" class=""><span class="eyebrow">13</span>Do I need Typesense for an agent to search my docs?</a>
+ <a href="/compare/xerj-vs-meilisearch" class=""><span class="eyebrow">14</span>What's a local alternative to Meilisearch that indexes a folder by itself?</a>
+ <a href="/compare/xerj-vs-pagefind" class=""><span class="eyebrow">15</span>Pagefind vs indexing a local HTML dump for an agent?</a>
+ <a href="/compare/xerj-vs-vector-database" class=""><span class="eyebrow">16</span>Should my agent call a search API or stand up Qdrant for persistent memory?</a>
+ </div>
+</nav>
+<main class="docs-content">
+ <div class="breadcrumb"><a href="/">HOME</a><span class="sep">·</span><a href="/answers/">ANSWERS</a><span class="sep">·</span>HOW DO I GIVE MY LAWYER OR ACCOUNTANT READ-ONLY SEARCH OVER A FOLDER OF EMAIL AND PDFS WITHOUT UPLOADING IT?</div>
+ <div class="kicker"><span>ANSWERS · SHARING: READ-ONLY GUEST ACCESS</span></div>
+ <h1>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</h1>
+ <div class="source-note">AUTHOR · XERJ documentation team · REVIEWED BY · XERJ engineering team · PUBLISHED · 2026-09-18 · UPDATED · 2026-09-19</div>
+ <p><strong>TL;DR</strong> — Index the folder with <code class="inline">xerj brain</code>, then run <code class="inline">xerj share</code> on the same folder. The other person gets a link and a passcode. They open a read-only search page in a browser and read what they find. The documents and the index stay on your machine. You can revoke it at any time.</p>
+ <div class="prompt-card">
+ <span class="prompt-label">PASTE THIS TO YOUR AI AGENT — IT DOES THE REST</span>
+ <code>Act as a coding agent. Read https://xerj.org/llms.txt, run xerj brain on the folder the user names, then run xerj share on the same folder with a label and an expiry, and give the user the link and the passcode separately. Tell them the link only works on this machine unless they add --tunnel, and show them the xerj share --revoke command that was printed.</code>
+ <button type="button" class="prompt-copy" data-copy="Act as a coding agent. Read https://xerj.org/llms.txt, run xerj brain on the folder the user names, then run xerj share on the same folder with a label and an expiry, and give the user the link and the passcode separately. Tell them the link only works on this machine unless they add --tunnel, and show them the xerj share --revoke command that was printed.">COPY THE PROMPT</button>
+ </div>
+ <div class="prompt-card">
+ <span class="prompt-label">RUN THIS XERJ COMMAND</span>
+ <code>xerj brain ./casefiles</code>
+ <button type="button" class="prompt-copy" data-copy="xerj brain ./casefiles">COPY COMMAND</button>
+ <span class="hero-proof">Index the folder. This boots a local node with authentication on and prints the share command for this folder when it finishes.</span>
+ </div>
+ <div class="prompt-card">
+ <span class="prompt-label">RUN THIS XERJ COMMAND</span>
+ <code>xerj share ./casefiles --label 'for Dana' --expires 7d</code>
+ <button type="button" class="prompt-copy" data-copy="xerj share ./casefiles --label &#x27;for Dana&#x27; --expires 7d">COPY COMMAND</button>
+ <span class="hero-proof">Create the share. Prints the link, the passcode, the expiry and the revoke command, once.</span>
+ </div>
+ <div class="prompt-card">
+ <span class="prompt-label">RUN THIS XERJ COMMAND</span>
+ <code>xerj share ./casefiles --label 'for Dana' --tunnel</code>
+ <button type="button" class="prompt-copy" data-copy="xerj share ./casefiles --label &#x27;for Dana&#x27; --tunnel">COPY COMMAND</button>
+ <span class="hero-proof">Same, with a temporary public address from cloudflared for someone who is not on this machine. Ctrl-C closes the tunnel and revokes the share.</span>
+ </div>
+ <div class="prompt-card">
+ <span class="prompt-label">RUN THIS XERJ COMMAND</span>
+ <code>xerj share --list</code>
+ <button type="button" class="prompt-copy" data-copy="xerj share --list">COPY COMMAND</button>
+ <span class="hero-proof">Every share on this node: handle, status, claims used, expiry, index, label.</span>
+ </div>
+ <h2>The two commands</h2>
+ <p><code class="inline">xerj brain ./casefiles</code> indexes the folder and starts a local node with authentication on. When it finishes it prints the exact share command for that folder.</p>
+ <p><code class="inline">xerj share ./casefiles --label 'for Dana' --expires 7d</code> creates the share. The folder argument resolves to the indices that <code class="inline">xerj brain</code> built for it. The output is shown once:</p>
+ <pre class="code"><code class="language-text">✓ share created — "for Dana"
+ shares: index ax-docs · brain casefiles (its links) — read-only
+ link: http://localhost:9200/_xerj-console/share#…
+ passcode: ….-…. (send it separately from the link)
+ expires: 2026-09-25T08:41:09Z · can be opened 1 time — one browser tab; --max-claims &lt;N&gt; for a guest who will come back
+ revoke: xerj share --revoke 8a1e546d4ee8
+</code></pre>
+ <p>Send the link and the passcode through different channels. Either one alone opens nothing.</p>
+ <p>One open is one browser tab. The guest's key lives in that tab. Opening the same link again in the same tab keeps the session and spends nothing. A closed tab is a spent open. With the default of 1 open, a guest who closes the tab cannot come back, even if the share has 7 days left. For someone who will read over several days, add <code class="inline">--max-claims 5</code>.</p>
+ <h2>What the other person sees</h2>
+ <p>A page that asks for the passcode, then a reading room over that one index: a search field, highlighted passages, and a document view. The page states that access is read-only, shows when it ends, and has a sign-out button.</p>
+ <p>Email is shown as text. HTML in a message body is displayed as its source and never rendered, and addresses inside documents are not turned into links, because document text is other people's content.</p>
+ <p>Search here means search. No text is generated and no model is called. Where the index has a <code class="inline">semantic_text</code> field the page uses the <code class="inline">hybrid</code> query, which fuses BM25 with the node's embedder. The default embedder is lexical feature hashing, so that ranking is word and sub-word overlap, not meaning. The page says which mode it is using.</p>
+ <h2>What stays on your machine</h2>
+ <p>The documents and the index are not uploaded, synced or copied to a hosting service. The guest installs nothing. What does leave your machine is what the guest asks to see: search results and the documents they open, sent to their browser.</p>
+ <p>With <code class="inline">--tunnel</code> that traffic passes through Cloudflare, which terminates the HTTPS connection. The folder is not uploaded there, but the operator of a TLS endpoint can read what passes through it: the passcode, the guest key, every search and every document the guest opens. The command prints this with the link, and the guest page shows it before the passcode is typed. The second article linked below covers that trade.</p>
+ <h2>The limits on a share</h2>
+ <table>
+ <thead><tr><th>Setting</th><th>Default</th><th>Bound</th></tr></thead>
+ <tbody>
+ <tr><td>lifetime (<code class="inline">--expires</code>)</td><td>24h</td><td>up to 30 days</td></tr>
+ <tr><td>times the link can be opened (<code class="inline">--max-claims</code>)</td><td>1</td><td>up to 50</td></tr>
+ <tr><td>passcode</td><td>generated, 8 symbols</td><td>or your own, 6 characters or more</td></tr>
+ <tr><td>passcode attempts per share</td><td>10 a minute</td><td>30 an hour</td></tr>
+ </tbody>
+ </table>
+ <p>A revoke invalidates every key the share produced. The guest's next request is refused.</p>
+ <h2>What a share does not do</h2>
+ <p>It does not restrict what the guest reads inside the index. A share grants the whole index: there is no per-document or per-field restriction. If the folder holds things this person must not see, index a folder that does not.</p>
+ <p>It does not stop the guest copying what they read. Read access is read access.</p>
+ <p>It does not work on a node started with <code class="inline">--insecure</code>. With authentication off every request is already the superuser, so a read-only key would restrict nothing. <code class="inline">xerj share</code> refuses, says why, and exits 1.</p>
+ <p>XERJ makes no legal claim about this arrangement. Whether sharing documents this way meets a professional or regulatory duty is a question for the people involved.</p>
+ <h2>What was verified</h2>
+ <p>The folder path was run end to end on 2026-09-18 on a Linux host. The run: <code class="inline">xerj brain</code> on a folder of 3 files (two notes and one email), then <code class="inline">xerj share</code> on the same folder. Then a claim with the printed passcode, a guest search, and a walk of the folder's links. The same run confirmed that the guest key was refused the catalog index, <code class="inline">_cat/indices</code> and <code class="inline">/_share</code>. macOS and Windows were not run.</p>
+ <p>XERJ is single-node: one process, one data directory, no replication. The share lives and dies with that host.</p>
+ <h2>FAQ</h2>
+ <h3>I need my accountant to search a folder of emails and PDFs. How do I do that without uploading everything somewhere?</h3>
+ <p>Run <code class="inline">xerj brain</code> on the folder, then <code class="inline">xerj share</code> on the same folder. Your accountant gets a link and a passcode and searches from a browser. The documents and the index stay on your machine.</p>
+ <h3>Does the other person have to install anything?</h3>
+ <p>No. They open the link in a browser and type the passcode. The page is served by your node and loads nothing from anywhere else.</p>
+ <h3>Can they change or delete my files?</h3>
+ <p>No. The guest key is read-only and reaches only the shared index. Writes, deletes and every other index on the node are refused by the server, not by the page.</p>
+ <h3>How do I stop the access?</h3>
+ <p>Run the <code class="inline">xerj share --revoke</code> command that was printed when you created the share. The guest's next request is refused. A share also ends on its own: the default lifetime is 24h.</p>
+ <h3>What if they are not on my network?</h3>
+ <p>Add <code class="inline">--tunnel</code>. XERJ starts your own <code class="inline">cloudflared</code>, prints a public link, and closes the tunnel and revokes the share when you press Ctrl-C. That traffic passes through Cloudflare, which can read it: the passcode, the guest key, the searches and the documents. The command prints this with the link.</p>
+ <h3>Can they come back to the link later?</h3>
+ <p>Only while the browser tab stays open, unless you allow more than one open. One open is one browser tab. Opening the same link again in that tab keeps the session. A closed tab is a spent open, so give <code class="inline">--max-claims 5</code> to someone who will read over several days.</p>
+ <h3>Is the search AI? Does it write answers?</h3>
+ <p>No. It is search and reading only: no text is generated and no model is called. The default embedder is lexical feature hashing, so ranking is by word and sub-word overlap plus BM25.</p>
+ <h2>Evidence</h2>
+ <ul>
+ <li>A share defaults to 24h and 1 claim; the longest lifetime is 30 days and the most claims is 50. — <code>engine/crates/xerj-api/src/share.rs</code></li>
+ <li>A generated passcode is 8 symbols from a 31-symbol alphabet; a share id is 128 bits. — <code>engine/crates/xerj-api/src/share.rs</code></li>
+ <li>Claims against one share are limited to 10 a minute and 30 an hour. — <code>engine/crates/xerj-api/src/share.rs</code></li>
+ <li>xerj share refuses a node running with authentication off and exits 1. — <code>engine/crates/xerj-server/src/share.rs</code></li>
+ <li>The folder path was run end to end on 2026-09-18: 3 files indexed, shared by folder, claimed, searched. — <code>docs/usecases/share-links/VERIFICATION.md</code></li>
+ </ul>
+ <h2>Related</h2>
+ <ul>
+ <li><a href="/answers/what-a-share-link-guest-can-reach">If I share one index with a link and a passcode, what can that person actually reach on my node?</a></li>
+ <li><a href="/answers/share-local-search-index-through-a-tunnel">How do I let someone outside my network search an index on my laptop without opening a port?</a></li>
+ <li><a href="/answers/search-all-pdfs-in-a-folder">I downloaded a bunch of papers as PDFs. How do I search across them?</a></li>
+ <li><a href="/docs/security">Auth &amp; TLS</a></li>
+ </ul>
+</main>
+</div>
+<!-- seo:footer-begin — generated by scripts/seo/fix_links.py · do not hand-edit -->
+<nav class="footer-map" aria-label="Site map">
+ <div class="fm-col">
+ <span class="fm-h">PRODUCT</span>
+ <a href="/product">PRODUCT</a>
+ <a href="/architecture/">ARCHITECTURE</a>
+ <a href="/benchmarks/">BENCHMARKS</a>
+ <a href="/pricing/">PRICING</a>
+ <a href="/security/">SECURITY</a>
+ <a href="/playground">DASHBOARDS</a>
+ <a href="/demo/">REAL-DATA DEMO</a>
+ <a href="/aise-demo">PRODUCT TOUR</a>
+ </div>
+ <div class="fm-col">
+ <span class="fm-h">SOLUTIONS</span>
+ <a href="/solutions/">SOLUTIONS</a>
+ <a href="/use-cases">USE CASES</a>
+ <a href="/case-studies">CASE STUDIES</a>
+ <a href="/industries/">INDUSTRIES</a>
+ <a href="/industries/finserv">FINANCIAL SERVICES</a>
+ <a href="/industries/public-sector">PUBLIC SECTOR</a>
+ <a href="/industries/healthcare">HEALTHCARE</a>
+ <a href="/industries/retail">RETAIL</a>
+ <a href="/use-cases/code-security-audit">AI CODE-SECURITY AUDIT</a>
+ <a href="/use-cases/semantic-analytics">SEMANTIC ANALYTICS</a>
+ </div>
+ <div class="fm-col">
+ <span class="fm-h">DOCS</span>
+ <a href="/docs/">DOCUMENTATION</a>
+ <a href="/docs/quickstart">QUICKSTART</a>
+ <a href="/docs/install">INSTALL</a>
+ <a href="/docs/migration-from-es">MIGRATE FROM ELASTICSEARCH</a>
+ <a href="/docs/recipes/">RECIPES</a>
+ <a href="/docs/agents/">DOCS FOR AI</a>
+ <a href="/for-agents">FOR AI AGENTS</a>
+ <a href="/agent-search/">AGENTIC SEARCH DEMO</a>
+ <a href="/answers/">ANSWERS</a>
+ <a href="/compare/">COMPARISONS</a>
+ </div>
+ <div class="fm-col">
+ <span class="fm-h">RESOURCES</span>
+ <a href="/resources/">SALES KIT</a>
+ <a href="/brand">BRAND</a>
+ <a href="/brandbook/">BRAND BOOK</a>
+ <a href="/llms.txt">LLMS.TXT</a>
+ <a href="https://github.com/xerj-org/xerj" rel="external">GITHUB</a>
+ </div>
+</nav>
+<!-- seo:footer-end -->
+<footer class="footer">
+ <span>XERJ.AI · ANSWERS</span>
+ <span>READ THE SOURCE</span>
+ <span><a href="/">HOME</a> · <a href="/product">PRODUCT</a> · <a href="/brand">BRAND</a> · <a href="/playground">DASHBOARDS</a> &middot; <a href="/llms.txt">LLMS.TXT</a></span>
+</footer>
+<script src="/interact.js"></script>
+</body>
+</html>
diff --git a/landing/answers/share-folder-read-only-search-without-uploading.md b/landing/answers/share-folder-read-only-search-without-uploading.md
new file mode 100644
index 000000000..708449627
--- /dev/null
+++ b/landing/answers/share-folder-read-only-search-without-uploading.md
@@ -0,0 +1,156 @@
+<!-- generated by build_articles.py — edit content/answers/share-folder-read-only-search-without-uploading.md instead -->
+---
+title: "Read-only search over a folder, without uploading it"
+canonical: "https://xerj.org/answers/share-folder-read-only-search-without-uploading"
+updated: "2026-09-19"
+source: "content/answers/share-folder-read-only-search-without-uploading.md"
+---
+
+# How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?
+
+**TL;DR** — Index the folder with `xerj brain`, then run `xerj share` on the same folder. The other person gets a link and a passcode. They open a read-only search page in a browser and read what they find. The documents and the index stay on your machine. You can revoke it at any time.
+
+## Agent prompt
+
+```text
+Act as a coding agent. Read https://xerj.org/llms.txt, run xerj brain on the folder the user names, then run xerj share on the same folder with a label and an expiry, and give the user the link and the passcode separately. Tell them the link only works on this machine unless they add --tunnel, and show them the xerj share --revoke command that was printed.
+```
+
+## Commands
+
+### Command 1
+
+Note: Index the folder. This boots a local node with authentication on and prints the share command for this folder when it finishes.
+
+```sh
+xerj brain ./casefiles
+```
+
+### Command 2
+
+Note: Create the share. Prints the link, the passcode, the expiry and the revoke command, once.
+
+```sh
+xerj share ./casefiles --label 'for Dana' --expires 7d
+```
+
+### Command 3
+
+Note: Same, with a temporary public address from cloudflared for someone who is not on this machine. Ctrl-C closes the tunnel and revokes the share.
+
+```sh
+xerj share ./casefiles --label 'for Dana' --tunnel
+```
+
+### Command 4
+
+Note: Every share on this node: handle, status, claims used, expiry, index, label.
+
+```sh
+xerj share --list
+```
+
+## The two commands
+
+`xerj brain ./casefiles` indexes the folder and starts a local node with authentication on. When it finishes it prints the exact share command for that folder.
+
+`xerj share ./casefiles --label 'for Dana' --expires 7d` creates the share. The folder argument resolves to the indices that `xerj brain` built for it. The output is shown once:
+
+```text
+✓ share created — "for Dana"
+ shares: index ax-docs · brain casefiles (its links) — read-only
+ link: http://localhost:9200/_xerj-console/share#…
+ passcode: ….-…. (send it separately from the link)
+ expires: 2026-09-25T08:41:09Z · can be opened 1 time — one browser tab; --max-claims <N> for a guest who will come back
+ revoke: xerj share --revoke 8a1e546d4ee8
+```
+
+Send the link and the passcode through different channels. Either one alone opens nothing.
+
+One open is one browser tab. The guest's key lives in that tab. Opening the same link again in the same tab keeps the session and spends nothing. A closed tab is a spent open. With the default of 1 open, a guest who closes the tab cannot come back, even if the share has 7 days left. For someone who will read over several days, add `--max-claims 5`.
+
+## What the other person sees
+
+A page that asks for the passcode, then a reading room over that one index: a search field, highlighted passages, and a document view. The page states that access is read-only, shows when it ends, and has a sign-out button.
+
+Email is shown as text. HTML in a message body is displayed as its source and never rendered, and addresses inside documents are not turned into links, because document text is other people's content.
+
+Search here means search. No text is generated and no model is called. Where the index has a `semantic_text` field the page uses the `hybrid` query, which fuses BM25 with the node's embedder. The default embedder is lexical feature hashing, so that ranking is word and sub-word overlap, not meaning. The page says which mode it is using.
+
+## What stays on your machine
+
+The documents and the index are not uploaded, synced or copied to a hosting service. The guest installs nothing. What does leave your machine is what the guest asks to see: search results and the documents they open, sent to their browser.
+
+With `--tunnel` that traffic passes through Cloudflare, which terminates the HTTPS connection. The folder is not uploaded there, but the operator of a TLS endpoint can read what passes through it: the passcode, the guest key, every search and every document the guest opens. The command prints this with the link, and the guest page shows it before the passcode is typed. The second article linked below covers that trade.
+
+## The limits on a share
+
+| Setting | Default | Bound |
+| --- | --- | --- |
+| lifetime (`--expires`) | 24h | up to 30 days |
+| times the link can be opened (`--max-claims`) | 1 | up to 50 |
+| passcode | generated, 8 symbols | or your own, 6 characters or more |
+| passcode attempts per share | 10 a minute | 30 an hour |
+
+A revoke invalidates every key the share produced. The guest's next request is refused.
+
+## What a share does not do
+
+It does not restrict what the guest reads inside the index. A share grants the whole index: there is no per-document or per-field restriction. If the folder holds things this person must not see, index a folder that does not.
+
+It does not stop the guest copying what they read. Read access is read access.
+
+It does not work on a node started with `--insecure`. With authentication off every request is already the superuser, so a read-only key would restrict nothing. `xerj share` refuses, says why, and exits 1.
+
+XERJ makes no legal claim about this arrangement. Whether sharing documents this way meets a professional or regulatory duty is a question for the people involved.
+
+## What was verified
+
+The folder path was run end to end on 2026-09-18 on a Linux host. The run: `xerj brain` on a folder of 3 files (two notes and one email), then `xerj share` on the same folder. Then a claim with the printed passcode, a guest search, and a walk of the folder's links. The same run confirmed that the guest key was refused the catalog index, `_cat/indices` and `/_share`. macOS and Windows were not run.
+
+XERJ is single-node: one process, one data directory, no replication. The share lives and dies with that host.
+
+## FAQ
+
+### I need my accountant to search a folder of emails and PDFs. How do I do that without uploading everything somewhere?
+
+Run `xerj brain` on the folder, then `xerj share` on the same folder. Your accountant gets a link and a passcode and searches from a browser. The documents and the index stay on your machine.
+
+### Does the other person have to install anything?
+
+No. They open the link in a browser and type the passcode. The page is served by your node and loads nothing from anywhere else.
+
+### Can they change or delete my files?
+
+No. The guest key is read-only and reaches only the shared index. Writes, deletes and every other index on the node are refused by the server, not by the page.
+
+### How do I stop the access?
+
+Run the `xerj share --revoke` command that was printed when you created the share. The guest's next request is refused. A share also ends on its own: the default lifetime is 24h.
+
+### What if they are not on my network?
+
+Add `--tunnel`. XERJ starts your own `cloudflared`, prints a public link, and closes the tunnel and revokes the share when you press Ctrl-C. That traffic passes through Cloudflare, which can read it: the passcode, the guest key, the searches and the documents. The command prints this with the link.
+
+### Can they come back to the link later?
+
+Only while the browser tab stays open, unless you allow more than one open. One open is one browser tab. Opening the same link again in that tab keeps the session. A closed tab is a spent open, so give `--max-claims 5` to someone who will read over several days.
+
+### Is the search AI? Does it write answers?
+
+No. It is search and reading only: no text is generated and no model is called. The default embedder is lexical feature hashing, so ranking is by word and sub-word overlap plus BM25.
+
+## Evidence
+
+- A share defaults to 24h and 1 claim; the longest lifetime is 30 days and the most claims is 50. — `engine/crates/xerj-api/src/share.rs`
+- A generated passcode is 8 symbols from a 31-symbol alphabet; a share id is 128 bits. — `engine/crates/xerj-api/src/share.rs`
+- Claims against one share are limited to 10 a minute and 30 an hour. — `engine/crates/xerj-api/src/share.rs`
+- xerj share refuses a node running with authentication off and exits 1. — `engine/crates/xerj-server/src/share.rs`
+- The folder path was run end to end on 2026-09-18: 3 files indexed, shared by folder, claimed, searched. — `docs/usecases/share-links/VERIFICATION.md`
+
+## Related
+
+- [If I share one index with a link and a passcode, what can that person actually reach on my node?](/answers/what-a-share-link-guest-can-reach)
+- [How do I let someone outside my network search an index on my laptop without opening a port?](/answers/share-local-search-index-through-a-tunnel)
+- [I downloaded a bunch of papers as PDFs. How do I search across them?](/answers/search-all-pdfs-in-a-folder)
+- [Auth & TLS](/docs/security)
diff --git a/landing/answers/share-local-search-index-through-a-tunnel.html b/landing/answers/share-local-search-index-through-a-tunnel.html
new file mode 100644
index 000000000..d6f4a07c5
--- /dev/null
+++ b/landing/answers/share-local-search-index-through-a-tunnel.html
@@ -0,0 +1,387 @@
+<!-- generated by build_articles.py — edit content/answers/share-local-search-index-through-a-tunnel.md instead -->
+<!DOCTYPE html>
+<html lang="en" data-theme="day">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>Share a local search index through a tunnel</title>
+<meta name="description" content="xerj share --tunnel starts your own cloudflared, prints a public guest link, and closes the tunnel and revokes the share on Ctrl-C. What the trade is.">
+<link rel="preconnect" href="https://fonts.googleapis.com">
+<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+<link href="https://fonts.googleapis.com/css2?family=Big+Shoulders+Display:wght@400;700;800;900&family=Inter:wght@400;500;600;700&family=IBM+Plex+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">
+<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><rect width='100' height='100' fill='%230b0b0d'/><text x='50' y='68' font-size='60' font-family='Big Shoulders Display,sans-serif' font-weight='900' fill='%23ffc400' text-anchor='middle'>X</text></svg>">
+<link rel="stylesheet" href="/style.css?v=90f643e">
+<link rel="alternate" type="text/markdown" href="/answers/share-local-search-index-through-a-tunnel.md">
+<!-- seo:begin — generated by scripts/seo/fix_heads.py · do not hand-edit -->
+<link rel="canonical" href="https://xerj.org/answers/share-local-search-index-through-a-tunnel">
+<meta property="og:site_name" content="XERJ.ai">
+<meta property="og:type" content="article">
+<meta property="og:title" content="Share a local search index through a tunnel">
+<meta property="og:description" content="xerj share --tunnel starts your own cloudflared, prints a public guest link, and closes the tunnel and revokes the share on Ctrl-C. What the trade is.">
+<meta property="og:url" content="https://xerj.org/answers/share-local-search-index-through-a-tunnel">
+<meta property="og:image" content="https://xerj.org/og/xerj-card.png">
+<meta property="og:image:width" content="1200">
+<meta property="og:image:height" content="630">
+<meta property="og:image:alt" content="XERJ.ai — the search engine built for AI agents">
+<meta property="og:locale" content="en_US">
+<meta name="twitter:card" content="summary_large_image">
+<meta name="twitter:title" content="Share a local search index through a tunnel">
+<meta name="twitter:description" content="xerj share --tunnel starts your own cloudflared, prints a public guest link, and closes the tunnel and revokes the share on Ctrl-C. What the trade is.">
+<meta name="twitter:image" content="https://xerj.org/og/xerj-card.png">
+<script type="application/ld+json">
+{
+ "@context": "https://schema.org",
+ "@type": "Organization",
+ "@id": "https://xerj.org/#organization",
+ "name": "XERJ",
+ "alternateName": "XERJ.ai",
+ "url": "https://xerj.org/",
+ "logo": "https://xerj.org/brandbook/xerj-mark.svg",
+ "sameAs": [
+ "https://github.com/xerj-org/xerj"
+ ]
+}
+</script>
+<script type="application/ld+json">
+{
+ "@context": "https://schema.org",
+ "@type": "WebSite",
+ "@id": "https://xerj.org/#website",
+ "name": "XERJ.ai",
+ "url": "https://xerj.org/",
+ "inLanguage": "en",
+ "publisher": {
+ "@id": "https://xerj.org/#organization"
+ }
+}
+</script>
+<script type="application/ld+json">
+{
+ "@context": "https://schema.org",
+ "@type": "TechArticle",
+ "headline": "Share a local search index through a tunnel",
+ "description": "xerj share --tunnel starts your own cloudflared, prints a public guest link, and closes the tunnel and revokes the share on Ctrl-C. What the trade is.",
+ "url": "https://xerj.org/answers/share-local-search-index-through-a-tunnel",
+ "image": "https://xerj.org/og/xerj-card.png",
+ "inLanguage": "en",
+ "datePublished": "2026-09-18",
+ "dateModified": "2026-09-19",
+ "author": {
+ "@type": "Person",
+ "name": "XERJ documentation team"
+ },
+ "publisher": {
+ "@id": "https://xerj.org/#organization"
+ },
+ "isPartOf": {
+ "@id": "https://xerj.org/#website"
+ },
+ "mainEntityOfPage": {
+ "@type": "WebPage",
+ "@id": "https://xerj.org/answers/share-local-search-index-through-a-tunnel"
+ },
+ "reviewedBy": {
+ "@type": "Person",
+ "name": "XERJ engineering team"
+ }
+}
+</script>
+<script type="application/ld+json">
+{
+ "@context": "https://schema.org",
+ "@type": "BreadcrumbList",
+ "itemListElement": [
+ {
+ "@type": "ListItem",
+ "position": 1,
+ "name": "Home",
+ "item": "https://xerj.org/"
+ },
+ {
+ "@type": "ListItem",
+ "position": 2,
+ "name": "Answers",
+ "item": "https://xerj.org/answers/"
+ },
+ {
+ "@type": "ListItem",
+ "position": 3,
+ "name": "How do I let someone outside my network search an index on my laptop without opening a port?"
+ }
+ ]
+}
+</script>
+<!-- seo:end -->
+</head>
+<body>
+<nav class="nav" aria-label="Primary">
+ <a href="/" class="brand">XERJ.AI</a>
+ <a href="/">HOME</a>
+ <a href="/product">PRODUCT</a>
+ <span class="nav-drop">
+ <a href="/use-cases">USE CASES</a>
+ </span>
+ <a href="/case-studies">CASE STUDIES</a>
+ <a href="/benchmarks/">BENCHMARKS</a>
+ <span class="spacer"></span>
+ <a href="/for-agents">FOR AGENTS</a>
+ <a href="/docs/" class="active">DOCS</a>
+ <a href="/docs/recipes/">RECIPES</a>
+ <a href="/playground">DASHBOARDS</a>
+ <a href="https://github.com/xerj-org/xerj" rel="external">GITHUB</a>
+ <span class="spacer"></span>
+ <span class="theme">
+ <button type="button" data-theme="day" class="active">DAY</button>
+ <span class="dash">·</span>
+ <button type="button" data-theme="night">NIGHT</button>
+ </span>
+</nav>
+<div class="docs-shell">
+<nav class="docs-nav" aria-label="Article sections">
+ <div class="group">
+ <span class="label">ANSWERS</span>
+ <a href="/answers/"><span class="eyebrow">00</span>All Answers</a>
+ <a href="/answers/give-chatgpt-claude-local-file-access" class=""><span class="eyebrow">01</span>Can ChatGPT search a folder on my laptop, or do I need something else?</a>
+ <a href="/answers/code-search-mcp-for-claude-code" class=""><span class="eyebrow">02</span>I need my agent to find a passage and cite the file, not dump the whole tree. How?</a>
+ <a href="/answers/mcp-api-search-or-vector-search" class=""><span class="eyebrow">03</span>Should an agent use API search or vector search?</a>
+ <a href="/answers/knowledge-graphs-for-agent-memory" class=""><span class="eyebrow">04</span>Should agent memory use a knowledge graph?</a>
+ <a href="/answers/store-agent-memory-without-llm-call" class=""><span class="eyebrow">05</span>How do I stop an agent memory store from filling with near-duplicate notes?</a>
+ <a href="/answers/evidence-for-agent-memory-links" class=""><span class="eyebrow">06</span>How can agent-memory links retain evidence?</a>
+ <a href="/answers/private-agent-memory-namespaces" class=""><span class="eyebrow">07</span>How do I give two agents private memory on one laptop?</a>
+ <a href="/answers/coding-agent-memory-across-sessions" class=""><span class="eyebrow">08</span>How do people store user preferences so an agent can recall them next week?</a>
+ <a href="/answers/set-mcp-memory-storage-path" class=""><span class="eyebrow">09</span>How do I set the MCP memory storage path?</a>
+ <a href="/answers/agent-memory-without-postgres-qdrant" class=""><span class="eyebrow">10</span>What's a simple way to give an agent long-term memory on my laptop without Qdrant?</a>
+ <a href="/answers/does-xerj-support-s3-alerting-plugins" class=""><span class="eyebrow">11</span>Does XERJ support S3 storage, alerting or custom plugins yet?</a>
+ <a href="/answers/audit-php-codebase-with-an-index" class=""><span class="eyebrow">12</span>How do I audit a PHP codebase with an index instead of grepping 1,400 files?</a>
+ <a href="/answers/index-reference-library-for-coding-agent" class=""><span class="eyebrow">13</span>How do I set up reference coding so the agent retrieves a mechanism before writing code?</a>
+ <a href="/answers/classify-text-from-labelled-history-without-llm" class=""><span class="eyebrow">14</span>Can I route tickets or filter spam from labelled history, without an LLM call?</a>
+ <a href="/answers/reduce-embedding-api-cost" class=""><span class="eyebrow">15</span>How do I reduce embedding API cost?</a>
+ <a href="/answers/local-embeddings-without-openai-api" class=""><span class="eyebrow">16</span>I want local search that works offline, no cloud embeddings. What are my options?</a>
+ <a href="/answers/do-search-embeddings-help" class=""><span class="eyebrow">17</span>When should I turn on neural embeddings, and when is the lexical default enough?</a>
+ <a href="/answers/search-yaml-xml-config-repository" class=""><span class="eyebrow">18</span>How do I find every place a config key is set across YAML and XML in a repo?</a>
+ <a href="/answers/full-text-search-sqlite-database" class=""><span class="eyebrow">19</span>How do I full-text search a SQLite database I just copied onto disk?</a>
+ <a href="/answers/index-csv-with-many-columns" class=""><span class="eyebrow">20</span>How do I index a CSV with many columns?</a>
+ <a href="/answers/index-markdown-into-elasticsearch-api" class=""><span class="eyebrow">21</span>How do I index Markdown into the Elasticsearch API?</a>
+ <a href="/answers/syntax-aware-code-search-refactoring" class=""><span class="eyebrow">22</span>How do I run syntax-aware code search?</a>
+ <a href="/answers/search-gzipped-csv-or-json" class=""><span class="eyebrow">23</span>How do I search a .csv.gz or .json.gz without unzipping it first?</a>
+ <a href="/answers/search-confluence-html-export" class=""><span class="eyebrow">24</span>How do I search a Confluence export?</a>
+ <a href="/answers/search-slack-json-export" class=""><span class="eyebrow">25</span>How do I search a Slack JSON export?</a>
+ <a href="/answers/search-bvh-motion-capture-files" class=""><span class="eyebrow">26</span>How do I search BVH motion-capture files?</a>
+ <a href="/answers/search-gzip-logs-without-zgrep" class=""><span class="eyebrow">27</span>How do I search gzipped logs without decompressing the whole file — including when JSONL sits next to them?</a>
+ <a href="/answers/search-kubernetes-pod-logs-on-disk" class=""><span class="eyebrow">28</span>How do I search Kubernetes pod logs?</a>
+ <a href="/answers/search-word-documents-in-a-folder" class=""><span class="eyebrow">29</span>How do I search through a folder of contracts in .docx?</a>
+ <a href="/answers/search-unity-project-assets" class=""><span class="eyebrow">30</span>How do I search Unity YAML scenes and the C# that references them as one project?</a>
+ <a href="/answers/index-monorepo-for-agent" class=""><span class="eyebrow">31</span>How do I stop my agent from reading the whole repo into context?</a>
+ <a href="/answers/catalog-files-with-autoindex-map" class=""><span class="eyebrow">32</span>How should an agent figure out what's in a messy data folder before searching?</a>
+ <a href="/answers/search-all-pdfs-in-a-folder" class=""><span class="eyebrow">33</span>I downloaded a bunch of papers as PDFs. How do I search across them?</a>
+ <a href="/answers/search-sql-dump-file" class=""><span class="eyebrow">34</span>I have a 2GB SQL dump. How do I find rows mentioning a customer without loading it into Postgres?</a>
+ <a href="/answers/index-multiple-csv-files" class=""><span class="eyebrow">35</span>I have a directory of CSV exports. How do I query them without opening each one in Excel?</a>
+ <a href="/answers/search-file-contents-in-a-folder" class=""><span class="eyebrow">36</span>I have a folder of PDFs, Word docs, and markdown. How do I search all of them at once?</a>
+ <a href="/answers/search-zendesk-ticket-json-export" class=""><span class="eyebrow">37</span>I have a JSON export of Jira issues (or Zendesk tickets). How do I search it like a help-center search?</a>
+ <a href="/answers/search-jupyter-notebook-cells" class=""><span class="eyebrow">38</span>I need to find a function I wrote in a notebook months ago. How do I search all .ipynb files and the .py next to them?</a>
+ <a href="/answers/search-html-export" class=""><span class="eyebrow">39</span>I saved a help-center as HTML. How do I search it like the real help-center search?</a>
+ <a href="/answers/is-pdf-indexing-efficient" class=""><span class="eyebrow">40</span>Is it efficient to index PDF files?</a>
+ <a href="/answers/full-text-search-browser-history" class=""><span class="eyebrow">41</span>Is there a way to full-text search my browser history file itself?</a>
+ <a href="/answers/search-openapi-spec-for-agent" class=""><span class="eyebrow">42</span>My agent needs to look up endpoints in a big OpenAPI spec and the SDK markdown. What's the right way?</a>
+ <a href="/answers/search-obsidian-pdf-docx-attachments" class=""><span class="eyebrow">43</span>What's the best way to search markdown notes and PDFs in the same vault?</a>
+ <a href="/answers/search-json-and-jsonl-logs" class=""><span class="eyebrow">44</span>What's the easiest way to search JSON logs plus some old gzip text logs in the same folder?</a>
+ <a href="/answers/notion-export-duplicate-search-results" class=""><span class="eyebrow">45</span>Why does my Notion export duplicate titles?</a>
+ <a href="/answers/search-gmail-takeout-mbox-locally" class=""><span class="eyebrow">46</span>I exported my Gmail with Google Takeout. How do I search that mbox file locally?</a>
+ <a href="/answers/how-xerj-autoindexes-a-folder" class=""><span class="eyebrow">47</span>I want to point something at a folder and then ask questions about what's in it. What should I use?</a>
+ <a href="/answers/rag-without-vector-database" class=""><span class="eyebrow">48</span>How do I build RAG without a vector database?</a>
+ <a href="/answers/hybrid-search-quality-measured-ndcg" class=""><span class="eyebrow">49</span>How much better is hybrid search than BM25? Measured nDCG numbers</a>
+ <a href="/answers/rerank-search-results-calibrated-judge" class=""><span class="eyebrow">50</span>How do I rerank search results with a calibrated relevance judge?</a>
+ <a href="/answers/reciprocal-rank-fusion-when-to-use" class=""><span class="eyebrow">51</span>What is Reciprocal Rank Fusion?</a>
+ <a href="/answers/how-xerj-combines-search" class=""><span class="eyebrow">52</span>How does XERJ combine BM25 and kNN?</a>
+ <a href="/answers/search-files-in-an-s3-bucket" class=""><span class="eyebrow">53</span>How do I search files that live in an S3 bucket?</a>
+ <a href="/answers/check-codebase-index-is-complete" class=""><span class="eyebrow">54</span>My codebase indexer says indexed but I don't see my code. How do I check it actually finished?</a>
+ <a href="/answers/estimate-autoindex-time-before-running" class=""><span class="eyebrow">55</span>How do I estimate folder-indexing time?</a>
+ <a href="/answers/why-autoindex-skipped-files" class=""><span class="eyebrow">56</span>Why would a folder search miss files that I can see on disk?</a>
+ <a href="/answers/autoindex-exit-codes" class=""><span class="eyebrow">57</span>The indexer exited 3 (or 4). Did it fail?</a>
+ <a href="/answers/autoindex-says-extract-the-archive-first" class=""><span class="eyebrow">58</span>xerj autoindex recorded my Takeout .zip as junk and said to extract it first. Why?</a>
+ <a href="/answers/keep-index-current-as-files-change" class=""><span class="eyebrow">59</span>How do I keep a search index up to date as files change, without re-indexing everything?</a>
+ <a href="/answers/search-engine-without-docker" class=""><span class="eyebrow">60</span>Is there a single-binary local search engine I can just run?</a>
+ <a href="/answers/cheap-low-volume-log-search" class=""><span class="eyebrow">61</span>What can I use for low-volume log search?</a>
+ <a href="/answers/read-autoindex-progress" class=""><span class="eyebrow">62</span>How do I read autoindex progress?</a>
+ <a href="/answers/resume-interrupted-autoindex-run" class=""><span class="eyebrow">63</span>The indexer died overnight. Do I have to start over?</a>
+ <a href="/answers/reindex-taking-forever" class=""><span class="eyebrow">64</span>Reindexing my files is taking forever. What usually causes that?</a>
+ <a href="/answers/what-is-xerj" class=""><span class="eyebrow">65</span>What is XERJ?</a>
+ <a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
+ <a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
+ <a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class="active"><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
+ </div>
+ <div class="group">
+ <span class="label">COMPARISONS</span>
+ <a href="/compare/"><span class="eyebrow">00</span>All Comparisons</a>
+ <a href="/compare/xerj-vs-web-agent-search" class=""><span class="eyebrow">01</span>How do I let an agent search a folder on my laptop instead of crawling the web?</a>
+ <a href="/compare/xerj-vs-ast-grep" class=""><span class="eyebrow">02</span>ast-grep vs a code index for an agent?</a>
+ <a href="/compare/xerj-vs-ripgrep-for-code-agents" class=""><span class="eyebrow">03</span>Is ripgrep enough for a coding agent, or do I need a code index?</a>
+ <a href="/compare/xerj-vs-ripgrep-all" class=""><span class="eyebrow">04</span>How do I grep PDFs and Word docs from the command line?</a>
+ <a href="/compare/xerj-vs-docfetcher" class=""><span class="eyebrow">05</span>What's a free DocFetcher alternative that an agent can call?</a>
+ <a href="/compare/xerj-vs-recoll" class=""><span class="eyebrow">06</span>What's the best local desktop search for a folder of PDFs and docs?</a>
+ <a href="/compare/xerj-vs-houdahspot" class=""><span class="eyebrow">07</span>XERJ vs HoudahSpot — Spotlight GUI vs an agent index</a>
+ <a href="/compare/xerj-vs-spotlight" class=""><span class="eyebrow">08</span>XERJ vs macOS Spotlight for folder content an agent can query</a>
+ <a href="/compare/xerj-vs-localsynapse" class=""><span class="eyebrow">09</span>What's a local MCP search engine for Claude?</a>
+ <a href="/compare/xerj-vs-elasticsearch-local" class=""><span class="eyebrow">10</span>Is there an Elasticsearch-compatible engine that isn't Elasticsearch?</a>
+ <a href="/compare/xerj-vs-obsidian-omnisearch" class=""><span class="eyebrow">11</span>How do I search an Obsidian vault from outside Obsidian?</a>
+ <a href="/compare/xerj-vs-khoj" class=""><span class="eyebrow">12</span>What's a simpler alternative to Khoj if I only need search and memory?</a>
+ <a href="/compare/xerj-vs-typesense" class=""><span class="eyebrow">13</span>Do I need Typesense for an agent to search my docs?</a>
+ <a href="/compare/xerj-vs-meilisearch" class=""><span class="eyebrow">14</span>What's a local alternative to Meilisearch that indexes a folder by itself?</a>
+ <a href="/compare/xerj-vs-pagefind" class=""><span class="eyebrow">15</span>Pagefind vs indexing a local HTML dump for an agent?</a>
+ <a href="/compare/xerj-vs-vector-database" class=""><span class="eyebrow">16</span>Should my agent call a search API or stand up Qdrant for persistent memory?</a>
+ </div>
+</nav>
+<main class="docs-content">
+ <div class="breadcrumb"><a href="/">HOME</a><span class="sep">·</span><a href="/answers/">ANSWERS</a><span class="sep">·</span>HOW DO I LET SOMEONE OUTSIDE MY NETWORK SEARCH AN INDEX ON MY LAPTOP WITHOUT OPENING A PORT?</div>
+ <div class="kicker"><span>ANSWERS · SHARING: READ-ONLY GUEST ACCESS</span></div>
+ <h1>How do I let someone outside my network search an index on my laptop without opening a port?</h1>
+ <div class="source-note">AUTHOR · XERJ documentation team · REVIEWED BY · XERJ engineering team · PUBLISHED · 2026-09-18 · UPDATED · 2026-09-19</div>
+ <p><strong>TL;DR</strong> — <code class="inline">xerj share</code> with <code class="inline">--tunnel</code> starts your own <code class="inline">cloudflared</code>, prints a public HTTPS guest link, and runs until you press Ctrl-C. Stopping it closes the tunnel and revokes the share. No port is opened on your router. The trade: the guest's traffic passes through Cloudflare, which terminates the TLS connection.</p>
+ <div class="prompt-card">
+ <span class="prompt-label">PASTE THIS TO YOUR AI AGENT — IT DOES THE REST</span>
+ <code>Act as a coding agent. Read https://xerj.org/llms.txt. Confirm cloudflared is installed, then run xerj share on the user's indexed folder with --tunnel in the background, wait for the line that says the tunnel is up, and give the user the https link and the passcode separately. Tell them the link stops working when the command stops, and that stopping it revokes the share.</code>
+ <button type="button" class="prompt-copy" data-copy="Act as a coding agent. Read https://xerj.org/llms.txt. Confirm cloudflared is installed, then run xerj share on the user&#x27;s indexed folder with --tunnel in the background, wait for the line that says the tunnel is up, and give the user the https link and the passcode separately. Tell them the link stops working when the command stops, and that stopping it revokes the share.">COPY THE PROMPT</button>
+ </div>
+ <div class="prompt-card">
+ <span class="prompt-label">RUN THIS XERJ COMMAND</span>
+ <code>xerj share ./casefiles --label 'for Dana' --tunnel</code>
+ <button type="button" class="prompt-copy" data-copy="xerj share ./casefiles --label &#x27;for Dana&#x27; --tunnel">COPY COMMAND</button>
+ <span class="hero-proof">Open a temporary public address and print the full guest link. Runs until Ctrl-C, then closes the tunnel and revokes the share.</span>
+ </div>
+ <div class="prompt-card">
+ <span class="prompt-label">RUN THIS XERJ COMMAND</span>
+ <code>xerj share ./casefiles --tunnel --keep</code>
+ <button type="button" class="prompt-copy" data-copy="xerj share ./casefiles --tunnel --keep">COPY COMMAND</button>
+ <span class="hero-proof">Same, but leave the share active after Ctrl-C. The link stops working anyway, because the hostname is gone.</span>
+ </div>
+ <div class="prompt-card">
+ <span class="prompt-label">RUN THIS XERJ COMMAND</span>
+ <code>xerj share ./casefiles --public-url https://search.example.org</code>
+ <button type="button" class="prompt-copy" data-copy="xerj share ./casefiles --public-url https://search.example.org">COPY COMMAND</button>
+ <span class="hero-proof">For a node you already publish at your own hostname: print the link for that address and open no tunnel.</span>
+ </div>
+ <h2>What the command does</h2>
+ <p>It checks that the node is enforcing authentication, then starts <code class="inline">cloudflared tunnel --url http://127.0.0.1:&lt;port&gt;</code> as a child process and reads the <code class="inline">trycloudflare.com</code> hostname from its output. The tunnel comes up before the share is created, so a link is never printed for an address that is not there.</p>
+ <p>Then it creates the share and prints the full link, the passcode, the expiry and the revoke command. It keeps running while your guest reads.</p>
+ <p>On Ctrl-C, on SIGTERM, or when the terminal closes, it terminates the tunnel and revokes the share. With <code class="inline">--keep</code> the share stays active on the node until it expires.</p>
+ <p>If <code class="inline">cloudflared</code> is not installed, the command prints the install steps for your platform and the local link. It does not fail.</p>
+ <h2>What was verified, and what was not</h2>
+ <p>On 2026-09-18 the command was run against a real quick tunnel from a Linux host and the public hostname was exercised over IPv4:</p>
+ <table>
+ <thead><tr><th>Request through the tunnel</th><th>Result</th></tr></thead>
+ <tbody>
+ <tr><td>guest page</td><td>200, with the full security header set</td></tr>
+ <tr><td>claim with a wrong passcode</td><td>401</td></tr>
+ <tr><td>claim with the right passcode</td><td>200</td></tr>
+ <tr><td>guest search on the shared index</td><td>200</td></tr>
+ <tr><td>guest <code class="inline">_cat/indices</code></td><td>403</td></tr>
+ </tbody>
+ </table>
+ <p>After SIGINT the <code class="inline">cloudflared</code> process was gone, the share listed as <code class="inline">revoked</code> with 1 key invalidated, and the guest key answered 401.</p>
+ <p>That run cannot be repeated in CI, because it needs the public internet and a third party. It also predates the review fixes: the claim then carried the share id in its path, and the command did not yet print the Cloudflare notice. CI covers the hostname parser, the missing-<code class="inline">cloudflared</code> fallback, and a stub <code class="inline">cloudflared</code> that checks the notice and what happens when the tunnel dies. A browser was not driven through a real tunnel. The browser test serves the page under a <code class="inline">trycloudflare.com</code> name that points at the local node, and checks the page's notice there.</p>
+ <h2>Three properties of a quick tunnel</h2>
+ <p><strong>The hostname is random and new on every start.</strong> A link stops working when the command stops. That is the intended lifetime.</p>
+ <p><strong>Cloudflare terminates TLS.</strong> The corpus is not uploaded there. Everything between the guest's browser and your node does cross Cloudflare's network, and the operator of a TLS endpoint can read what passes through it. That includes the passcode, the guest's API key, every search and every document the guest opens. <code class="inline">xerj share --tunnel</code> prints this with the link. The guest page shows it on a <code class="inline">trycloudflare.com</code> address before the passcode is typed. When that is not acceptable, publish the node at your own hostname behind your own certificate and pass it as <code class="inline">--public-url</code>.</p>
+ <p><strong>The share id is never in a URL the page requests.</strong> The id is in the link's fragment, which a browser does not send. The page then sends it in the body of <code class="inline">POST /_share/claim</code>. So the id is not in the request line that a proxy or a tunnel logs. Cloudflare still carries that body and can read it, together with the passcode.</p>
+ <p><strong>When the tunnel drops on its own, the command says why.</strong> It prints the last lines <code class="inline">cloudflared</code> wrote, closes the tunnel and revokes the share.</p>
+ <p><strong>It is temporary by design.</strong> Cloudflare offers quick tunnels without an account and makes no promise about how long one stays up. For a standing arrangement use a named tunnel on your own domain, or your own reverse proxy.</p>
+ <h2>Why guests do not get passkeys</h2>
+ <p>The XERJ Console signs its owner in with a passkey. A passkey is bound to the hostname it was created on, which is what makes it resistant to phishing. A quick tunnel gets a new random hostname each time it starts, so a passkey enrolled through one tunnel is unusable through the next.</p>
+ <p>That is why a share is a link plus a passcode. The route to guest passkeys is a stable hostname: a named Cloudflare Tunnel on your own domain, optionally with Cloudflare Access in front, or any reverse proxy with your own certificate. Guest passkeys are not built.</p>
+ <h2>The rate limiter behind a tunnel</h2>
+ <p>Through a tunnel every request reaches the node from <code class="inline">127.0.0.1</code>. A limiter keyed on the source address first would put every guest in one bucket, and a few junk requests would lock the real guest out.</p>
+ <p>XERJ does not fix that by trusting <code class="inline">X-Forwarded-For</code>, because a direct client can write that header itself. A claim against a real share is charged to the share: 30 attempts an hour, from anywhere. Junk ids are charged to the source address. The two are not stacked.</p>
+ <p>To log each guest's real address in the audit log, list loopback under <code class="inline">trusted_proxies</code> in the <code class="inline">[server]</code> section of the node's config and restart it. Only then is the forwarded header read. The command tells you which mode your node is in.</p>
+ <h2>What this does not do</h2>
+ <p><code class="inline">--tunnel</code> fronts a plain-http node on this machine only. For a node with TLS on, run your own tunnel or proxy and use <code class="inline">--public-url</code>.</p>
+ <p>It does not work on a node started with <code class="inline">--insecure</code>. The command refuses before it opens a tunnel.</p>
+ <p>XERJ is single-node. The share is reachable only while that one host and that one command are running.</p>
+ <h2>FAQ</h2>
+ <h3>How can I give a remote person temporary search access to files on my laptop without port forwarding or a VPN?</h3>
+ <p>Run <code class="inline">xerj share</code> on the indexed folder with <code class="inline">--tunnel</code>. XERJ starts your own <code class="inline">cloudflared</code>, prints a public HTTPS link, and revokes the share when you stop the command.</p>
+ <h3>What happens when I press Ctrl-C?</h3>
+ <p>The tunnel is closed and the share is revoked, which invalidates every guest key it minted. Add <code class="inline">--keep</code> to leave the share active. The link still stops working, because the hostname is gone.</p>
+ <h3>Do I need a Cloudflare account?</h3>
+ <p>Not for a quick tunnel. You do need the <code class="inline">cloudflared</code> binary. If it is missing, <code class="inline">xerj share</code> prints the install steps for your platform and the local link, and does not fail.</p>
+ <h3>Can Cloudflare read what my guest searches for?</h3>
+ <p>It terminates the HTTPS connection, so in principle yes. The folder is not uploaded there, but everything between the guest's browser and your node crosses its network: the passcode, the guest key, the searches and the documents the guest opens. The command prints this with the link, and the guest page shows it. Use your own hostname and certificate with <code class="inline">--public-url</code> when that matters.</p>
+ <h3>Why does the guest get a passcode and not a passkey?</h3>
+ <p>A passkey is bound to a hostname, and a quick tunnel gets a new random hostname on every start. A passkey made through one tunnel would not work through the next.</p>
+ <h3>Every guest arrives from 127.0.0.1 through a tunnel. Does that break the passcode lockout?</h3>
+ <p>No. The lockout is charged to the share, not to the address: 30 attempts an hour from anywhere. Junk ids are charged to the source address, where one shared bucket only makes the bound tighter.</p>
+ <h2>Evidence</h2>
+ <ul>
+ <li>xerj share --tunnel runs cloudflared tunnel --url against 127.0.0.1 and reads the trycloudflare.com hostname from its output. — <code>engine/crates/xerj-server/src/share.rs</code></li>
+ <li>A real quick tunnel was exercised on 2026-09-18: page 200, wrong passcode 401, claim 200, guest _cat 403, and after SIGINT the guest key answered 401 with 1 key invalidated. — <code>docs/usecases/share-links/VERIFICATION.md</code></li>
+ <li>A known share is limited to 30 passcode attempts an hour from anywhere, so the lockout does not depend on the source address. — <code>engine/crates/xerj-api/src/share.rs</code></li>
+ <li>Forwarded headers are read only when the peer is listed in server.trusted_proxies. — <code>engine/crates/xerj-console-api/src/client_ip.rs</code></li>
+ </ul>
+ <h2>Related</h2>
+ <ul>
+ <li><a href="/answers/share-folder-read-only-search-without-uploading">How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a></li>
+ <li><a href="/answers/what-a-share-link-guest-can-reach">If I share one index with a link and a passcode, what can that person actually reach on my node?</a></li>
+ <li><a href="/answers/search-engine-without-docker">Is there a single-binary local search engine I can just run?</a></li>
+ <li><a href="/docs/security">Auth &amp; TLS</a></li>
+ </ul>
+</main>
+</div>
+<!-- seo:footer-begin — generated by scripts/seo/fix_links.py · do not hand-edit -->
+<nav class="footer-map" aria-label="Site map">
+ <div class="fm-col">
+ <span class="fm-h">PRODUCT</span>
+ <a href="/product">PRODUCT</a>
+ <a href="/architecture/">ARCHITECTURE</a>
+ <a href="/benchmarks/">BENCHMARKS</a>
+ <a href="/pricing/">PRICING</a>
+ <a href="/security/">SECURITY</a>
+ <a href="/playground">DASHBOARDS</a>
+ <a href="/demo/">REAL-DATA DEMO</a>
+ <a href="/aise-demo">PRODUCT TOUR</a>
+ </div>
+ <div class="fm-col">
+ <span class="fm-h">SOLUTIONS</span>
+ <a href="/solutions/">SOLUTIONS</a>
+ <a href="/use-cases">USE CASES</a>
+ <a href="/case-studies">CASE STUDIES</a>
+ <a href="/industries/">INDUSTRIES</a>
+ <a href="/industries/finserv">FINANCIAL SERVICES</a>
+ <a href="/industries/public-sector">PUBLIC SECTOR</a>
+ <a href="/industries/healthcare">HEALTHCARE</a>
+ <a href="/industries/retail">RETAIL</a>
+ <a href="/use-cases/code-security-audit">AI CODE-SECURITY AUDIT</a>
+ <a href="/use-cases/semantic-analytics">SEMANTIC ANALYTICS</a>
+ </div>
+ <div class="fm-col">
+ <span class="fm-h">DOCS</span>
+ <a href="/docs/">DOCUMENTATION</a>
+ <a href="/docs/quickstart">QUICKSTART</a>
+ <a href="/docs/install">INSTALL</a>
+ <a href="/docs/migration-from-es">MIGRATE FROM ELASTICSEARCH</a>
+ <a href="/docs/recipes/">RECIPES</a>
+ <a href="/docs/agents/">DOCS FOR AI</a>
+ <a href="/for-agents">FOR AI AGENTS</a>
+ <a href="/agent-search/">AGENTIC SEARCH DEMO</a>
+ <a href="/answers/">ANSWERS</a>
+ <a href="/compare/">COMPARISONS</a>
+ </div>
+ <div class="fm-col">
+ <span class="fm-h">RESOURCES</span>
+ <a href="/resources/">SALES KIT</a>
+ <a href="/brand">BRAND</a>
+ <a href="/brandbook/">BRAND BOOK</a>
+ <a href="/llms.txt">LLMS.TXT</a>
+ <a href="https://github.com/xerj-org/xerj" rel="external">GITHUB</a>
+ </div>
+</nav>
+<!-- seo:footer-end -->
+<footer class="footer">
+ <span>XERJ.AI · ANSWERS</span>
+ <span>READ THE SOURCE</span>
+ <span><a href="/">HOME</a> · <a href="/product">PRODUCT</a> · <a href="/brand">BRAND</a> · <a href="/playground">DASHBOARDS</a> &middot; <a href="/llms.txt">LLMS.TXT</a></span>
+</footer>
+<script src="/interact.js"></script>
+</body>
+</html>
diff --git a/landing/answers/share-local-search-index-through-a-tunnel.md b/landing/answers/share-local-search-index-through-a-tunnel.md
new file mode 100644
index 000000000..dc1e0ebf3
--- /dev/null
+++ b/landing/answers/share-local-search-index-through-a-tunnel.md
@@ -0,0 +1,143 @@
+<!-- generated by build_articles.py — edit content/answers/share-local-search-index-through-a-tunnel.md instead -->
+---
+title: "Share a local search index through a tunnel"
+canonical: "https://xerj.org/answers/share-local-search-index-through-a-tunnel"
+updated: "2026-09-19"
+source: "content/answers/share-local-search-index-through-a-tunnel.md"
+---
+
+# How do I let someone outside my network search an index on my laptop without opening a port?
+
+**TL;DR** — `xerj share` with `--tunnel` starts your own `cloudflared`, prints a public HTTPS guest link, and runs until you press Ctrl-C. Stopping it closes the tunnel and revokes the share. No port is opened on your router. The trade: the guest's traffic passes through Cloudflare, which terminates the TLS connection.
+
+## Agent prompt
+
+```text
+Act as a coding agent. Read https://xerj.org/llms.txt. Confirm cloudflared is installed, then run xerj share on the user's indexed folder with --tunnel in the background, wait for the line that says the tunnel is up, and give the user the https link and the passcode separately. Tell them the link stops working when the command stops, and that stopping it revokes the share.
+```
+
+## Commands
+
+### Command 1
+
+Note: Open a temporary public address and print the full guest link. Runs until Ctrl-C, then closes the tunnel and revokes the share.
+
+```sh
+xerj share ./casefiles --label 'for Dana' --tunnel
+```
+
+### Command 2
+
+Note: Same, but leave the share active after Ctrl-C. The link stops working anyway, because the hostname is gone.
+
+```sh
+xerj share ./casefiles --tunnel --keep
+```
+
+### Command 3
+
+Note: For a node you already publish at your own hostname: print the link for that address and open no tunnel.
+
+```sh
+xerj share ./casefiles --public-url https://search.example.org
+```
+
+## What the command does
+
+It checks that the node is enforcing authentication, then starts `cloudflared tunnel --url http://127.0.0.1:<port>` as a child process and reads the `trycloudflare.com` hostname from its output. The tunnel comes up before the share is created, so a link is never printed for an address that is not there.
+
+Then it creates the share and prints the full link, the passcode, the expiry and the revoke command. It keeps running while your guest reads.
+
+On Ctrl-C, on SIGTERM, or when the terminal closes, it terminates the tunnel and revokes the share. With `--keep` the share stays active on the node until it expires.
+
+If `cloudflared` is not installed, the command prints the install steps for your platform and the local link. It does not fail.
+
+## What was verified, and what was not
+
+On 2026-09-18 the command was run against a real quick tunnel from a Linux host and the public hostname was exercised over IPv4:
+
+| Request through the tunnel | Result |
+| --- | --- |
+| guest page | 200, with the full security header set |
+| claim with a wrong passcode | 401 |
+| claim with the right passcode | 200 |
+| guest search on the shared index | 200 |
+| guest `_cat/indices` | 403 |
+
+After SIGINT the `cloudflared` process was gone, the share listed as `revoked` with 1 key invalidated, and the guest key answered 401.
+
+That run cannot be repeated in CI, because it needs the public internet and a third party. It also predates the review fixes: the claim then carried the share id in its path, and the command did not yet print the Cloudflare notice. CI covers the hostname parser, the missing-`cloudflared` fallback, and a stub `cloudflared` that checks the notice and what happens when the tunnel dies. A browser was not driven through a real tunnel. The browser test serves the page under a `trycloudflare.com` name that points at the local node, and checks the page's notice there.
+
+## Three properties of a quick tunnel
+
+**The hostname is random and new on every start.** A link stops working when the command stops. That is the intended lifetime.
+
+**Cloudflare terminates TLS.** The corpus is not uploaded there. Everything between the guest's browser and your node does cross Cloudflare's network, and the operator of a TLS endpoint can read what passes through it. That includes the passcode, the guest's API key, every search and every document the guest opens. `xerj share --tunnel` prints this with the link. The guest page shows it on a `trycloudflare.com` address before the passcode is typed. When that is not acceptable, publish the node at your own hostname behind your own certificate and pass it as `--public-url`.
+
+**The share id is never in a URL the page requests.** The id is in the link's fragment, which a browser does not send. The page then sends it in the body of `POST /_share/claim`. So the id is not in the request line that a proxy or a tunnel logs. Cloudflare still carries that body and can read it, together with the passcode.
+
+**When the tunnel drops on its own, the command says why.** It prints the last lines `cloudflared` wrote, closes the tunnel and revokes the share.
+
+**It is temporary by design.** Cloudflare offers quick tunnels without an account and makes no promise about how long one stays up. For a standing arrangement use a named tunnel on your own domain, or your own reverse proxy.
+
+## Why guests do not get passkeys
+
+The XERJ Console signs its owner in with a passkey. A passkey is bound to the hostname it was created on, which is what makes it resistant to phishing. A quick tunnel gets a new random hostname each time it starts, so a passkey enrolled through one tunnel is unusable through the next.
+
+That is why a share is a link plus a passcode. The route to guest passkeys is a stable hostname: a named Cloudflare Tunnel on your own domain, optionally with Cloudflare Access in front, or any reverse proxy with your own certificate. Guest passkeys are not built.
+
+## The rate limiter behind a tunnel
+
+Through a tunnel every request reaches the node from `127.0.0.1`. A limiter keyed on the source address first would put every guest in one bucket, and a few junk requests would lock the real guest out.
+
+XERJ does not fix that by trusting `X-Forwarded-For`, because a direct client can write that header itself. A claim against a real share is charged to the share: 30 attempts an hour, from anywhere. Junk ids are charged to the source address. The two are not stacked.
+
+To log each guest's real address in the audit log, list loopback under `trusted_proxies` in the `[server]` section of the node's config and restart it. Only then is the forwarded header read. The command tells you which mode your node is in.
+
+## What this does not do
+
+`--tunnel` fronts a plain-http node on this machine only. For a node with TLS on, run your own tunnel or proxy and use `--public-url`.
+
+It does not work on a node started with `--insecure`. The command refuses before it opens a tunnel.
+
+XERJ is single-node. The share is reachable only while that one host and that one command are running.
+
+## FAQ
+
+### How can I give a remote person temporary search access to files on my laptop without port forwarding or a VPN?
+
+Run `xerj share` on the indexed folder with `--tunnel`. XERJ starts your own `cloudflared`, prints a public HTTPS link, and revokes the share when you stop the command.
+
+### What happens when I press Ctrl-C?
+
+The tunnel is closed and the share is revoked, which invalidates every guest key it minted. Add `--keep` to leave the share active. The link still stops working, because the hostname is gone.
+
+### Do I need a Cloudflare account?
+
+Not for a quick tunnel. You do need the `cloudflared` binary. If it is missing, `xerj share` prints the install steps for your platform and the local link, and does not fail.
+
+### Can Cloudflare read what my guest searches for?
+
+It terminates the HTTPS connection, so in principle yes. The folder is not uploaded there, but everything between the guest's browser and your node crosses its network: the passcode, the guest key, the searches and the documents the guest opens. The command prints this with the link, and the guest page shows it. Use your own hostname and certificate with `--public-url` when that matters.
+
+### Why does the guest get a passcode and not a passkey?
+
+A passkey is bound to a hostname, and a quick tunnel gets a new random hostname on every start. A passkey made through one tunnel would not work through the next.
+
+### Every guest arrives from 127.0.0.1 through a tunnel. Does that break the passcode lockout?
+
+No. The lockout is charged to the share, not to the address: 30 attempts an hour from anywhere. Junk ids are charged to the source address, where one shared bucket only makes the bound tighter.
+
+## Evidence
+
+- xerj share --tunnel runs cloudflared tunnel --url against 127.0.0.1 and reads the trycloudflare.com hostname from its output. — `engine/crates/xerj-server/src/share.rs`
+- A real quick tunnel was exercised on 2026-09-18: page 200, wrong passcode 401, claim 200, guest _cat 403, and after SIGINT the guest key answered 401 with 1 key invalidated. — `docs/usecases/share-links/VERIFICATION.md`
+- A known share is limited to 30 passcode attempts an hour from anywhere, so the lockout does not depend on the source address. — `engine/crates/xerj-api/src/share.rs`
+- Forwarded headers are read only when the peer is listed in server.trusted_proxies. — `engine/crates/xerj-console-api/src/client_ip.rs`
+
+## Related
+
+- [How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?](/answers/share-folder-read-only-search-without-uploading)
+- [If I share one index with a link and a passcode, what can that person actually reach on my node?](/answers/what-a-share-link-guest-can-reach)
+- [Is there a single-binary local search engine I can just run?](/answers/search-engine-without-docker)
+- [Auth & TLS](/docs/security)
diff --git a/landing/answers/store-agent-memory-without-llm-call.html b/landing/answers/store-agent-memory-without-llm-call.html
index 9039ee77d..d4a09d328 100644
--- a/landing/answers/store-agent-memory-without-llm-call.html
+++ b/landing/answers/store-agent-memory-without-llm-call.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/syntax-aware-code-search-refactoring.html b/landing/answers/syntax-aware-code-search-refactoring.html
index f7ca03b45..3896262fb 100644
--- a/landing/answers/syntax-aware-code-search-refactoring.html
+++ b/landing/answers/syntax-aware-code-search-refactoring.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/vector-database-vs-full-text-search.html b/landing/answers/vector-database-vs-full-text-search.html
index 04259b2a8..29e0f815b 100644
--- a/landing/answers/vector-database-vs-full-text-search.html
+++ b/landing/answers/vector-database-vs-full-text-search.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class="active"><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/what-a-share-link-guest-can-reach.html b/landing/answers/what-a-share-link-guest-can-reach.html
new file mode 100644
index 000000000..12b97e244
--- /dev/null
+++ b/landing/answers/what-a-share-link-guest-can-reach.html
@@ -0,0 +1,398 @@
+<!-- generated by build_articles.py — edit content/answers/what-a-share-link-guest-can-reach.md instead -->
+<!DOCTYPE html>
+<html lang="en" data-theme="day">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>What a XERJ share-link guest can and cannot reach</title>
+<meta name="description" content="A share-link guest key reads the shared index and nothing else: no other index, no _cat or _cluster, no writes, no scroll or PIT. Each refusal is a live test.">
+<link rel="preconnect" href="https://fonts.googleapis.com">
+<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+<link href="https://fonts.googleapis.com/css2?family=Big+Shoulders+Display:wght@400;700;800;900&family=Inter:wght@400;500;600;700&family=IBM+Plex+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">
+<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><rect width='100' height='100' fill='%230b0b0d'/><text x='50' y='68' font-size='60' font-family='Big Shoulders Display,sans-serif' font-weight='900' fill='%23ffc400' text-anchor='middle'>X</text></svg>">
+<link rel="stylesheet" href="/style.css?v=90f643e">
+<link rel="alternate" type="text/markdown" href="/answers/what-a-share-link-guest-can-reach.md">
+<!-- seo:begin — generated by scripts/seo/fix_heads.py · do not hand-edit -->
+<link rel="canonical" href="https://xerj.org/answers/what-a-share-link-guest-can-reach">
+<meta property="og:site_name" content="XERJ.ai">
+<meta property="og:type" content="article">
+<meta property="og:title" content="What a XERJ share-link guest can and cannot reach">
+<meta property="og:description" content="A share-link guest key reads the shared index and nothing else: no other index, no _cat or _cluster, no writes, no scroll or PIT. Each refusal is a live test.">
+<meta property="og:url" content="https://xerj.org/answers/what-a-share-link-guest-can-reach">
+<meta property="og:image" content="https://xerj.org/og/xerj-card.png">
+<meta property="og:image:width" content="1200">
+<meta property="og:image:height" content="630">
+<meta property="og:image:alt" content="XERJ.ai — the search engine built for AI agents">
+<meta property="og:locale" content="en_US">
+<meta name="twitter:card" content="summary_large_image">
+<meta name="twitter:title" content="What a XERJ share-link guest can and cannot reach">
+<meta name="twitter:description" content="A share-link guest key reads the shared index and nothing else: no other index, no _cat or _cluster, no writes, no scroll or PIT. Each refusal is a live test.">
+<meta name="twitter:image" content="https://xerj.org/og/xerj-card.png">
+<script type="application/ld+json">
+{
+ "@context": "https://schema.org",
+ "@type": "Organization",
+ "@id": "https://xerj.org/#organization",
+ "name": "XERJ",
+ "alternateName": "XERJ.ai",
+ "url": "https://xerj.org/",
+ "logo": "https://xerj.org/brandbook/xerj-mark.svg",
+ "sameAs": [
+ "https://github.com/xerj-org/xerj"
+ ]
+}
+</script>
+<script type="application/ld+json">
+{
+ "@context": "https://schema.org",
+ "@type": "WebSite",
+ "@id": "https://xerj.org/#website",
+ "name": "XERJ.ai",
+ "url": "https://xerj.org/",
+ "inLanguage": "en",
+ "publisher": {
+ "@id": "https://xerj.org/#organization"
+ }
+}
+</script>
+<script type="application/ld+json">
+{
+ "@context": "https://schema.org",
+ "@type": "TechArticle",
+ "headline": "What a XERJ share-link guest can and cannot reach",
+ "description": "A share-link guest key reads the shared index and nothing else: no other index, no _cat or _cluster, no writes, no scroll or PIT. Each refusal is a live test.",
+ "url": "https://xerj.org/answers/what-a-share-link-guest-can-reach",
+ "image": "https://xerj.org/og/xerj-card.png",
+ "inLanguage": "en",
+ "datePublished": "2026-09-18",
+ "dateModified": "2026-09-19",
+ "author": {
+ "@type": "Person",
+ "name": "XERJ documentation team"
+ },
+ "publisher": {
+ "@id": "https://xerj.org/#organization"
+ },
+ "isPartOf": {
+ "@id": "https://xerj.org/#website"
+ },
+ "mainEntityOfPage": {
+ "@type": "WebPage",
+ "@id": "https://xerj.org/answers/what-a-share-link-guest-can-reach"
+ },
+ "reviewedBy": {
+ "@type": "Person",
+ "name": "XERJ engineering team"
+ }
+}
+</script>
+<script type="application/ld+json">
+{
+ "@context": "https://schema.org",
+ "@type": "BreadcrumbList",
+ "itemListElement": [
+ {
+ "@type": "ListItem",
+ "position": 1,
+ "name": "Home",
+ "item": "https://xerj.org/"
+ },
+ {
+ "@type": "ListItem",
+ "position": 2,
+ "name": "Answers",
+ "item": "https://xerj.org/answers/"
+ },
+ {
+ "@type": "ListItem",
+ "position": 3,
+ "name": "If I share one index with a link and a passcode, what can that person actually reach on my node?"
+ }
+ ]
+}
+</script>
+<!-- seo:end -->
+</head>
+<body>
+<nav class="nav" aria-label="Primary">
+ <a href="/" class="brand">XERJ.AI</a>
+ <a href="/">HOME</a>
+ <a href="/product">PRODUCT</a>
+ <span class="nav-drop">
+ <a href="/use-cases">USE CASES</a>
+ </span>
+ <a href="/case-studies">CASE STUDIES</a>
+ <a href="/benchmarks/">BENCHMARKS</a>
+ <span class="spacer"></span>
+ <a href="/for-agents">FOR AGENTS</a>
+ <a href="/docs/" class="active">DOCS</a>
+ <a href="/docs/recipes/">RECIPES</a>
+ <a href="/playground">DASHBOARDS</a>
+ <a href="https://github.com/xerj-org/xerj" rel="external">GITHUB</a>
+ <span class="spacer"></span>
+ <span class="theme">
+ <button type="button" data-theme="day" class="active">DAY</button>
+ <span class="dash">·</span>
+ <button type="button" data-theme="night">NIGHT</button>
+ </span>
+</nav>
+<div class="docs-shell">
+<nav class="docs-nav" aria-label="Article sections">
+ <div class="group">
+ <span class="label">ANSWERS</span>
+ <a href="/answers/"><span class="eyebrow">00</span>All Answers</a>
+ <a href="/answers/give-chatgpt-claude-local-file-access" class=""><span class="eyebrow">01</span>Can ChatGPT search a folder on my laptop, or do I need something else?</a>
+ <a href="/answers/code-search-mcp-for-claude-code" class=""><span class="eyebrow">02</span>I need my agent to find a passage and cite the file, not dump the whole tree. How?</a>
+ <a href="/answers/mcp-api-search-or-vector-search" class=""><span class="eyebrow">03</span>Should an agent use API search or vector search?</a>
+ <a href="/answers/knowledge-graphs-for-agent-memory" class=""><span class="eyebrow">04</span>Should agent memory use a knowledge graph?</a>
+ <a href="/answers/store-agent-memory-without-llm-call" class=""><span class="eyebrow">05</span>How do I stop an agent memory store from filling with near-duplicate notes?</a>
+ <a href="/answers/evidence-for-agent-memory-links" class=""><span class="eyebrow">06</span>How can agent-memory links retain evidence?</a>
+ <a href="/answers/private-agent-memory-namespaces" class=""><span class="eyebrow">07</span>How do I give two agents private memory on one laptop?</a>
+ <a href="/answers/coding-agent-memory-across-sessions" class=""><span class="eyebrow">08</span>How do people store user preferences so an agent can recall them next week?</a>
+ <a href="/answers/set-mcp-memory-storage-path" class=""><span class="eyebrow">09</span>How do I set the MCP memory storage path?</a>
+ <a href="/answers/agent-memory-without-postgres-qdrant" class=""><span class="eyebrow">10</span>What's a simple way to give an agent long-term memory on my laptop without Qdrant?</a>
+ <a href="/answers/does-xerj-support-s3-alerting-plugins" class=""><span class="eyebrow">11</span>Does XERJ support S3 storage, alerting or custom plugins yet?</a>
+ <a href="/answers/audit-php-codebase-with-an-index" class=""><span class="eyebrow">12</span>How do I audit a PHP codebase with an index instead of grepping 1,400 files?</a>
+ <a href="/answers/index-reference-library-for-coding-agent" class=""><span class="eyebrow">13</span>How do I set up reference coding so the agent retrieves a mechanism before writing code?</a>
+ <a href="/answers/classify-text-from-labelled-history-without-llm" class=""><span class="eyebrow">14</span>Can I route tickets or filter spam from labelled history, without an LLM call?</a>
+ <a href="/answers/reduce-embedding-api-cost" class=""><span class="eyebrow">15</span>How do I reduce embedding API cost?</a>
+ <a href="/answers/local-embeddings-without-openai-api" class=""><span class="eyebrow">16</span>I want local search that works offline, no cloud embeddings. What are my options?</a>
+ <a href="/answers/do-search-embeddings-help" class=""><span class="eyebrow">17</span>When should I turn on neural embeddings, and when is the lexical default enough?</a>
+ <a href="/answers/search-yaml-xml-config-repository" class=""><span class="eyebrow">18</span>How do I find every place a config key is set across YAML and XML in a repo?</a>
+ <a href="/answers/full-text-search-sqlite-database" class=""><span class="eyebrow">19</span>How do I full-text search a SQLite database I just copied onto disk?</a>
+ <a href="/answers/index-csv-with-many-columns" class=""><span class="eyebrow">20</span>How do I index a CSV with many columns?</a>
+ <a href="/answers/index-markdown-into-elasticsearch-api" class=""><span class="eyebrow">21</span>How do I index Markdown into the Elasticsearch API?</a>
+ <a href="/answers/syntax-aware-code-search-refactoring" class=""><span class="eyebrow">22</span>How do I run syntax-aware code search?</a>
+ <a href="/answers/search-gzipped-csv-or-json" class=""><span class="eyebrow">23</span>How do I search a .csv.gz or .json.gz without unzipping it first?</a>
+ <a href="/answers/search-confluence-html-export" class=""><span class="eyebrow">24</span>How do I search a Confluence export?</a>
+ <a href="/answers/search-slack-json-export" class=""><span class="eyebrow">25</span>How do I search a Slack JSON export?</a>
+ <a href="/answers/search-bvh-motion-capture-files" class=""><span class="eyebrow">26</span>How do I search BVH motion-capture files?</a>
+ <a href="/answers/search-gzip-logs-without-zgrep" class=""><span class="eyebrow">27</span>How do I search gzipped logs without decompressing the whole file — including when JSONL sits next to them?</a>
+ <a href="/answers/search-kubernetes-pod-logs-on-disk" class=""><span class="eyebrow">28</span>How do I search Kubernetes pod logs?</a>
+ <a href="/answers/search-word-documents-in-a-folder" class=""><span class="eyebrow">29</span>How do I search through a folder of contracts in .docx?</a>
+ <a href="/answers/search-unity-project-assets" class=""><span class="eyebrow">30</span>How do I search Unity YAML scenes and the C# that references them as one project?</a>
+ <a href="/answers/index-monorepo-for-agent" class=""><span class="eyebrow">31</span>How do I stop my agent from reading the whole repo into context?</a>
+ <a href="/answers/catalog-files-with-autoindex-map" class=""><span class="eyebrow">32</span>How should an agent figure out what's in a messy data folder before searching?</a>
+ <a href="/answers/search-all-pdfs-in-a-folder" class=""><span class="eyebrow">33</span>I downloaded a bunch of papers as PDFs. How do I search across them?</a>
+ <a href="/answers/search-sql-dump-file" class=""><span class="eyebrow">34</span>I have a 2GB SQL dump. How do I find rows mentioning a customer without loading it into Postgres?</a>
+ <a href="/answers/index-multiple-csv-files" class=""><span class="eyebrow">35</span>I have a directory of CSV exports. How do I query them without opening each one in Excel?</a>
+ <a href="/answers/search-file-contents-in-a-folder" class=""><span class="eyebrow">36</span>I have a folder of PDFs, Word docs, and markdown. How do I search all of them at once?</a>
+ <a href="/answers/search-zendesk-ticket-json-export" class=""><span class="eyebrow">37</span>I have a JSON export of Jira issues (or Zendesk tickets). How do I search it like a help-center search?</a>
+ <a href="/answers/search-jupyter-notebook-cells" class=""><span class="eyebrow">38</span>I need to find a function I wrote in a notebook months ago. How do I search all .ipynb files and the .py next to them?</a>
+ <a href="/answers/search-html-export" class=""><span class="eyebrow">39</span>I saved a help-center as HTML. How do I search it like the real help-center search?</a>
+ <a href="/answers/is-pdf-indexing-efficient" class=""><span class="eyebrow">40</span>Is it efficient to index PDF files?</a>
+ <a href="/answers/full-text-search-browser-history" class=""><span class="eyebrow">41</span>Is there a way to full-text search my browser history file itself?</a>
+ <a href="/answers/search-openapi-spec-for-agent" class=""><span class="eyebrow">42</span>My agent needs to look up endpoints in a big OpenAPI spec and the SDK markdown. What's the right way?</a>
+ <a href="/answers/search-obsidian-pdf-docx-attachments" class=""><span class="eyebrow">43</span>What's the best way to search markdown notes and PDFs in the same vault?</a>
+ <a href="/answers/search-json-and-jsonl-logs" class=""><span class="eyebrow">44</span>What's the easiest way to search JSON logs plus some old gzip text logs in the same folder?</a>
+ <a href="/answers/notion-export-duplicate-search-results" class=""><span class="eyebrow">45</span>Why does my Notion export duplicate titles?</a>
+ <a href="/answers/search-gmail-takeout-mbox-locally" class=""><span class="eyebrow">46</span>I exported my Gmail with Google Takeout. How do I search that mbox file locally?</a>
+ <a href="/answers/how-xerj-autoindexes-a-folder" class=""><span class="eyebrow">47</span>I want to point something at a folder and then ask questions about what's in it. What should I use?</a>
+ <a href="/answers/rag-without-vector-database" class=""><span class="eyebrow">48</span>How do I build RAG without a vector database?</a>
+ <a href="/answers/hybrid-search-quality-measured-ndcg" class=""><span class="eyebrow">49</span>How much better is hybrid search than BM25? Measured nDCG numbers</a>
+ <a href="/answers/rerank-search-results-calibrated-judge" class=""><span class="eyebrow">50</span>How do I rerank search results with a calibrated relevance judge?</a>
+ <a href="/answers/reciprocal-rank-fusion-when-to-use" class=""><span class="eyebrow">51</span>What is Reciprocal Rank Fusion?</a>
+ <a href="/answers/how-xerj-combines-search" class=""><span class="eyebrow">52</span>How does XERJ combine BM25 and kNN?</a>
+ <a href="/answers/search-files-in-an-s3-bucket" class=""><span class="eyebrow">53</span>How do I search files that live in an S3 bucket?</a>
+ <a href="/answers/check-codebase-index-is-complete" class=""><span class="eyebrow">54</span>My codebase indexer says indexed but I don't see my code. How do I check it actually finished?</a>
+ <a href="/answers/estimate-autoindex-time-before-running" class=""><span class="eyebrow">55</span>How do I estimate folder-indexing time?</a>
+ <a href="/answers/why-autoindex-skipped-files" class=""><span class="eyebrow">56</span>Why would a folder search miss files that I can see on disk?</a>
+ <a href="/answers/autoindex-exit-codes" class=""><span class="eyebrow">57</span>The indexer exited 3 (or 4). Did it fail?</a>
+ <a href="/answers/autoindex-says-extract-the-archive-first" class=""><span class="eyebrow">58</span>xerj autoindex recorded my Takeout .zip as junk and said to extract it first. Why?</a>
+ <a href="/answers/keep-index-current-as-files-change" class=""><span class="eyebrow">59</span>How do I keep a search index up to date as files change, without re-indexing everything?</a>
+ <a href="/answers/search-engine-without-docker" class=""><span class="eyebrow">60</span>Is there a single-binary local search engine I can just run?</a>
+ <a href="/answers/cheap-low-volume-log-search" class=""><span class="eyebrow">61</span>What can I use for low-volume log search?</a>
+ <a href="/answers/read-autoindex-progress" class=""><span class="eyebrow">62</span>How do I read autoindex progress?</a>
+ <a href="/answers/resume-interrupted-autoindex-run" class=""><span class="eyebrow">63</span>The indexer died overnight. Do I have to start over?</a>
+ <a href="/answers/reindex-taking-forever" class=""><span class="eyebrow">64</span>Reindexing my files is taking forever. What usually causes that?</a>
+ <a href="/answers/what-is-xerj" class=""><span class="eyebrow">65</span>What is XERJ?</a>
+ <a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
+ <a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
+ <a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class="active"><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
+ </div>
+ <div class="group">
+ <span class="label">COMPARISONS</span>
+ <a href="/compare/"><span class="eyebrow">00</span>All Comparisons</a>
+ <a href="/compare/xerj-vs-web-agent-search" class=""><span class="eyebrow">01</span>How do I let an agent search a folder on my laptop instead of crawling the web?</a>
+ <a href="/compare/xerj-vs-ast-grep" class=""><span class="eyebrow">02</span>ast-grep vs a code index for an agent?</a>
+ <a href="/compare/xerj-vs-ripgrep-for-code-agents" class=""><span class="eyebrow">03</span>Is ripgrep enough for a coding agent, or do I need a code index?</a>
+ <a href="/compare/xerj-vs-ripgrep-all" class=""><span class="eyebrow">04</span>How do I grep PDFs and Word docs from the command line?</a>
+ <a href="/compare/xerj-vs-docfetcher" class=""><span class="eyebrow">05</span>What's a free DocFetcher alternative that an agent can call?</a>
+ <a href="/compare/xerj-vs-recoll" class=""><span class="eyebrow">06</span>What's the best local desktop search for a folder of PDFs and docs?</a>
+ <a href="/compare/xerj-vs-houdahspot" class=""><span class="eyebrow">07</span>XERJ vs HoudahSpot — Spotlight GUI vs an agent index</a>
+ <a href="/compare/xerj-vs-spotlight" class=""><span class="eyebrow">08</span>XERJ vs macOS Spotlight for folder content an agent can query</a>
+ <a href="/compare/xerj-vs-localsynapse" class=""><span class="eyebrow">09</span>What's a local MCP search engine for Claude?</a>
+ <a href="/compare/xerj-vs-elasticsearch-local" class=""><span class="eyebrow">10</span>Is there an Elasticsearch-compatible engine that isn't Elasticsearch?</a>
+ <a href="/compare/xerj-vs-obsidian-omnisearch" class=""><span class="eyebrow">11</span>How do I search an Obsidian vault from outside Obsidian?</a>
+ <a href="/compare/xerj-vs-khoj" class=""><span class="eyebrow">12</span>What's a simpler alternative to Khoj if I only need search and memory?</a>
+ <a href="/compare/xerj-vs-typesense" class=""><span class="eyebrow">13</span>Do I need Typesense for an agent to search my docs?</a>
+ <a href="/compare/xerj-vs-meilisearch" class=""><span class="eyebrow">14</span>What's a local alternative to Meilisearch that indexes a folder by itself?</a>
+ <a href="/compare/xerj-vs-pagefind" class=""><span class="eyebrow">15</span>Pagefind vs indexing a local HTML dump for an agent?</a>
+ <a href="/compare/xerj-vs-vector-database" class=""><span class="eyebrow">16</span>Should my agent call a search API or stand up Qdrant for persistent memory?</a>
+ </div>
+</nav>
+<main class="docs-content">
+ <div class="breadcrumb"><a href="/">HOME</a><span class="sep">·</span><a href="/answers/">ANSWERS</a><span class="sep">·</span>IF I SHARE ONE INDEX WITH A LINK AND A PASSCODE, WHAT CAN THAT PERSON ACTUALLY REACH ON MY NODE?</div>
+ <div class="kicker"><span>ANSWERS · SHARING: READ-ONLY GUEST ACCESS</span></div>
+ <h1>If I share one index with a link and a passcode, what can that person actually reach on my node?</h1>
+ <div class="source-note">AUTHOR · XERJ documentation team · REVIEWED BY · XERJ engineering team · PUBLISHED · 2026-09-18 · UPDATED · 2026-09-19</div>
+ <p><strong>TL;DR</strong> — A share-link guest gets a key with <code class="inline">read</code> on the shared index and nothing else. A route allow-list, used for guests only, closes <code class="inline">_cat</code>, <code class="inline">_cluster</code>, every other index, all writes, and scroll and point-in-time contexts. Each refusal is a check in a live test that ran 237 checks on 2026-09-19, with 0 failures.</p>
+ <div class="prompt-card">
+ <span class="prompt-label">PASTE THIS TO YOUR AI AGENT — IT DOES THE REST</span>
+ <code>Act as a coding agent. Read https://xerj.org/llms.txt. On a throwaway XERJ node with authentication on, create a share with POST /_share, claim it with POST /_share/claim and a JSON body of {id, passcode}, then use the returned api_key to call /_cat/indices, /_cluster/health, a search on another index, a write to the shared index and a search with ?scroll=1m, and report the status code of each call.</code>
+ <button type="button" class="prompt-copy" data-copy="Act as a coding agent. Read https://xerj.org/llms.txt. On a throwaway XERJ node with authentication on, create a share with POST /_share, claim it with POST /_share/claim and a JSON body of {id, passcode}, then use the returned api_key to call /_cat/indices, /_cluster/health, a search on another index, a write to the shared index and a search with ?scroll=1m, and report the status code of each call.">COPY THE PROMPT</button>
+ </div>
+ <div class="prompt-card">
+ <span class="prompt-label">RUN THIS XERJ COMMAND</span>
+ <code>xerj share casefile --label 'for the auditor' --max-claims 1</code>
+ <button type="button" class="prompt-copy" data-copy="xerj share casefile --label &#x27;for the auditor&#x27; --max-claims 1">COPY COMMAND</button>
+ <span class="hero-proof">Create a share over one index. Needs the node's admin key, read from the data directory.</span>
+ </div>
+ <div class="prompt-card">
+ <span class="prompt-label">RUN THIS XERJ COMMAND</span>
+ <code>curl -s -XPOST 'http://127.0.0.1:9200/_share/claim' -H 'content-type: application/json' -d '{"id":"0123456789abcdef0123456789abcdef","passcode":"abcd-2345"}'</code>
+ <button type="button" class="prompt-copy" data-copy="curl -s -XPOST &#x27;http://127.0.0.1:9200/_share/claim&#x27; -H &#x27;content-type: application/json&#x27; -d &#x27;{&quot;id&quot;:&quot;0123456789abcdef0123456789abcdef&quot;,&quot;passcode&quot;:&quot;abcd-2345&quot;}&#x27;">COPY COMMAND</button>
+ <span class="hero-proof">What the guest page does: exchange the share id and the passcode for a read-only key. Both travel in the body, so the id is not in the request line an access log records. This id and passcode are placeholders and return 404.</span>
+ </div>
+ <div class="prompt-card">
+ <span class="prompt-label">RUN THIS XERJ COMMAND</span>
+ <code>xerj share --revoke 8a1e546d4ee8</code>
+ <button type="button" class="prompt-copy" data-copy="xerj share --revoke 8a1e546d4ee8">COPY COMMAND</button>
+ <span class="hero-proof">End a share by the handle that the list prints. Every key it minted is invalidated.</span>
+ </div>
+ <h2>The key a guest is given</h2>
+ <p>Claiming a share mints an ordinary scoped API key with one role, named <code class="inline">share:</code> plus the share's handle. It carries <code class="inline">read</code> on the indices the share names and, when a brain is named, on that brain's edges index. It expires when the share does.</p>
+ <p>Two things confine that key, and both are enforced by the server. The first is the index grants every scoped key gets. The second is a route allow-list that applies only to keys whose roles are all named <code class="inline">share:</code>. Being recognised as a guest only ever removes reach.</p>
+ <h2>What is on the allow-list</h2>
+ <table>
+ <thead><tr><th>A guest can call</th><th>On</th></tr></thead>
+ <tbody>
+ <tr><td><code class="inline">_search</code>, <code class="inline">_count</code>, <code class="inline">_msearch</code>, <code class="inline">_mget</code></td><td>the shared indices</td></tr>
+ <tr><td><code class="inline">GET _doc/{id}</code></td><td>the shared indices</td></tr>
+ <tr><td><code class="inline">_mapping</code>, <code class="inline">_field_caps</code></td><td>the shared indices</td></tr>
+ <tr><td><code class="inline">GET /_graph/{brain}/ego</code> and <code class="inline">/overview</code></td><td>the shared brain</td></tr>
+ <tr><td><code class="inline">GET /</code>, <code class="inline">_security/_authenticate</code>, health probes</td><td>the node</td></tr>
+ </tbody>
+ </table>
+ <p>Nothing else. The allow-list can only refuse: a route it permits still goes through the index decision, so an index the guest was not granted is a 403 on a permitted route.</p>
+ <h2>What was refused in the live test</h2>
+ <p>The test runs against a real node with authentication on. It seeds one shared index and one private index that holds a marker sentence, then looks for that sentence in every response.</p>
+ <table>
+ <thead><tr><th>Attempt</th><th>Result</th></tr></thead>
+ <tbody>
+ <tr><td><code class="inline">_cat/*</code>, <code class="inline">_cluster/*</code>, <code class="inline">_nodes</code>, <code class="inline">_snapshot</code>, <code class="inline">_tasks</code>, <code class="inline">_stats</code>, <code class="inline">_aliases</code>, the audit log, <code class="inline">/v1/metrics</code>, the native <code class="inline">/v1/*</code> router</td><td>403</td></tr>
+ <tr><td>the private index by name, in a comma list, by <code class="inline">_search</code> with no index</td><td>403, or an answer that holds shared documents only</td></tr>
+ <tr><td>an alias that points at the private index</td><td>403</td></tr>
+ <tr><td><code class="inline">_msearch</code> and <code class="inline">_mget</code> bodies that name the private index</td><td>refused, no private text returned</td></tr>
+ <tr><td>a <code class="inline">terms</code> lookup, a <code class="inline">more_like_this</code> like-document, a stored <code class="inline">percolate</code> document and a <code class="inline">lookup</code> runtime field that name the private index</td><td>no private text returned</td></tr>
+ <tr><td><code class="inline">?scroll=1m</code>, also as <code class="inline">SCROLL</code> and percent-encoded; <code class="inline">_search/scroll</code>; <code class="inline">_pit</code>; <code class="inline">_async_search</code></td><td>403</td></tr>
+ <tr><td>the owner's own point-in-time id and scroll id, presented by the guest</td><td>403</td></tr>
+ <tr><td>index, update, delete, bulk, delete-by-query, reindex, refresh, close, mapping and settings changes</td><td>403</td></tr>
+ <tr><td>another brain, writes to the shared brain, <code class="inline">/_memory/*</code></td><td>403</td></tr>
+ <tr><td><code class="inline">GET /_share</code>, <code class="inline">POST /_share</code>, <code class="inline">DELETE /_share/{handle}</code>, <code class="inline">POST /_security/api_key</code></td><td>403</td></tr>
+ <tr><td>the Console API under <code class="inline">/_xerj-console/api/v1/</code></td><td>401: it takes a session cookie, not an API key</td></tr>
+ </tbody>
+ </table>
+ <p>A pattern such as <code class="inline">_all</code> is not refused. It is expanded over what the key holds, so for a guest it means the shared indices and no more.</p>
+ <h2>An alias is fixed when the share is made</h2>
+ <p>Sharing an alias pins the concrete indices it points at now. The test shares an alias, re-points it at another index, and confirms the guest still reads the first index and gets a 403 on the second.</p>
+ <h2>The claim route</h2>
+ <p><code class="inline">POST /_share/claim</code> is the one route on the node that hands out a credential without authentication, so it is narrow. It is <code class="inline">POST</code> only, its body is <code class="inline">{id, passcode}</code> and at most 4 KiB, it is never cached, and every outcome goes to the audit log with the source address.</p>
+ <p>The share id is in the body and not in the path. A request path is what an access log, a reverse proxy and a tunnel write down by default; a body is not, unless a proxy is set up to log bodies. The test runs against a node with <code class="inline">logging.access_log = true</code> and looks in that log for every share id it made. It finds none.</p>
+ <p>A claim against a known share is charged to that share: 10 a minute and 30 an hour, from anywhere. A claim against an unknown id is charged to the source address: 10 a minute and 100 an hour. The two are not stacked, so a flood of made-up ids cannot lock a real guest out, even when a tunnel makes every client arrive from the same address. The test floods the source bucket with a rotating <code class="inline">X-Forwarded-For</code> and then claims successfully from the same address.</p>
+ <h2>What this does not cover</h2>
+ <p>A guest can read every document in the shared index, and its mapping. XERJ has no per-document or per-field restriction. That is also why the <code class="inline">autoindex-catalog</code> index is never granted: it lists every corpus on the node and could not be filtered. <code class="inline">POST /_share</code> refuses it by name, in a list and through an alias.</p>
+ <p>Successful reads are only partly audited. The audit log holds a line for every claim outcome and every <code class="inline">_search</code>. It also holds a line for every request refused to an authenticated key, such as a guest's attempt to list, create or revoke a share or to mint a key. It holds no line for a successful <code class="inline">_msearch</code>, <code class="inline">_mget</code>, <code class="inline">_count</code>, <code class="inline">_mapping</code>, <code class="inline">_field_caps</code> or <code class="inline">GET _doc</code>. So a guest can read the whole shared index through those without a trace. It holds no line for an unauthenticated request other than a claim.</p>
+ <p>Through <code class="inline">xerj share --tunnel</code>, Cloudflare ends TLS and can read the passcode, the guest key, the searches and the documents.</p>
+ <p>Guest searches are not rate-limited. Authorization in XERJ comes from scoped API keys; roles are stored but not enforced. XERJ is single-node, so the share is only as available as that one host.</p>
+ <p>The test ran on Linux. macOS and Windows were not run.</p>
+ <h2>FAQ</h2>
+ <h3>If I give someone a read-only share link to one search index, can they see my other indices or anything else on the server?</h3>
+ <p>No. The guest key is granted <code class="inline">read</code> on the shared index only, and a route allow-list closes everything that describes the node. Another index is a 403 by name, by alias and from inside a request body.</p>
+ <h3>Can a guest list my indices with _cat/indices?</h3>
+ <p>No. <code class="inline">_cat</code>, <code class="inline">_cluster</code>, <code class="inline">_nodes</code>, <code class="inline">_snapshot</code>, <code class="inline">_tasks</code> and <code class="inline">_stats</code> all return 403 to a guest key. An ordinary scoped key sees a filtered view of those; a guest sees none of it.</p>
+ <h3>Can a guest write, delete or reindex?</h3>
+ <p>No. Index, update, delete, bulk, delete-by-query, reindex, refresh, mapping and settings changes all return 403. The live test also confirms that no guest write landed.</p>
+ <h3>Can a guest keep a scroll or a point-in-time open on my machine?</h3>
+ <p>No. <code class="inline">scroll</code>, <code class="inline">_search/scroll</code>, <code class="inline">_pit</code> and <code class="inline">_async_search</code> are refused, and so is a <code class="inline">pit</code> clause in a search body, so a guest cannot ride a point-in-time that someone else opened.</p>
+ <h3>What is stored on disk about a share?</h3>
+ <p>A SHA-256 digest of the share id and an Argon2id hash of the passcode, in <code class="inline">shares.json</code> with mode 0600. No share id, passcode or guest key is written to that file, to the API-key file or to the audit log. The guest page sends the share id in a request body and never in a URL, so the node's access log does not hold it either.</p>
+ <h3>What can a guest still do that I should think about?</h3>
+ <p>Read every document in the shared index and copy what they read. A share grants whole indices. There is no per-document or per-field restriction to apply.</p>
+ <h2>Evidence</h2>
+ <ul>
+ <li>The guest route allow-list: _search, _count, _msearch, _mget, _mapping, _field_caps, GET _doc, and the graph ego and overview routes. — <code>engine/crates/xerj-api/src/authz.rs</code></li>
+ <li>The live test makes 237 checks against a node with authentication on and the access log on (225 without the native-listener section); all passed on 2026-09-19. — <code>docs/usecases/share-links/VERIFICATION.md</code></li>
+ <li>A share id is 128 bits and is stored as a SHA-256 digest; the passcode is stored as an Argon2id hash in a file with mode 0600. — <code>engine/crates/xerj-api/src/share.rs</code></li>
+ <li>Unknown share ids are limited to 10 a minute and 100 an hour per source address; a known share to 10 a minute and 30 an hour. — <code>engine/crates/xerj-api/src/share.rs</code></li>
+ <li>The guest page is served with default-src 'none' and frame-ancestors 'none'. — <code>engine/crates/xerj-console-api/src/spa.rs</code></li>
+ </ul>
+ <h2>Related</h2>
+ <ul>
+ <li><a href="/answers/share-folder-read-only-search-without-uploading">How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a></li>
+ <li><a href="/answers/share-local-search-index-through-a-tunnel">How do I let someone outside my network search an index on my laptop without opening a port?</a></li>
+ <li><a href="/answers/private-agent-memory-namespaces">How do I give two agents private memory on one laptop?</a></li>
+ <li><a href="/docs/security">Auth &amp; TLS</a></li>
+ </ul>
+</main>
+</div>
+<!-- seo:footer-begin — generated by scripts/seo/fix_links.py · do not hand-edit -->
+<nav class="footer-map" aria-label="Site map">
+ <div class="fm-col">
+ <span class="fm-h">PRODUCT</span>
+ <a href="/product">PRODUCT</a>
+ <a href="/architecture/">ARCHITECTURE</a>
+ <a href="/benchmarks/">BENCHMARKS</a>
+ <a href="/pricing/">PRICING</a>
+ <a href="/security/">SECURITY</a>
+ <a href="/playground">DASHBOARDS</a>
+ <a href="/demo/">REAL-DATA DEMO</a>
+ <a href="/aise-demo">PRODUCT TOUR</a>
+ </div>
+ <div class="fm-col">
+ <span class="fm-h">SOLUTIONS</span>
+ <a href="/solutions/">SOLUTIONS</a>
+ <a href="/use-cases">USE CASES</a>
+ <a href="/case-studies">CASE STUDIES</a>
+ <a href="/industries/">INDUSTRIES</a>
+ <a href="/industries/finserv">FINANCIAL SERVICES</a>
+ <a href="/industries/public-sector">PUBLIC SECTOR</a>
+ <a href="/industries/healthcare">HEALTHCARE</a>
+ <a href="/industries/retail">RETAIL</a>
+ <a href="/use-cases/code-security-audit">AI CODE-SECURITY AUDIT</a>
+ <a href="/use-cases/semantic-analytics">SEMANTIC ANALYTICS</a>
+ </div>
+ <div class="fm-col">
+ <span class="fm-h">DOCS</span>
+ <a href="/docs/">DOCUMENTATION</a>
+ <a href="/docs/quickstart">QUICKSTART</a>
+ <a href="/docs/install">INSTALL</a>
+ <a href="/docs/migration-from-es">MIGRATE FROM ELASTICSEARCH</a>
+ <a href="/docs/recipes/">RECIPES</a>
+ <a href="/docs/agents/">DOCS FOR AI</a>
+ <a href="/for-agents">FOR AI AGENTS</a>
+ <a href="/agent-search/">AGENTIC SEARCH DEMO</a>
+ <a href="/answers/">ANSWERS</a>
+ <a href="/compare/">COMPARISONS</a>
+ </div>
+ <div class="fm-col">
+ <span class="fm-h">RESOURCES</span>
+ <a href="/resources/">SALES KIT</a>
+ <a href="/brand">BRAND</a>
+ <a href="/brandbook/">BRAND BOOK</a>
+ <a href="/llms.txt">LLMS.TXT</a>
+ <a href="https://github.com/xerj-org/xerj" rel="external">GITHUB</a>
+ </div>
+</nav>
+<!-- seo:footer-end -->
+<footer class="footer">
+ <span>XERJ.AI · ANSWERS</span>
+ <span>READ THE SOURCE</span>
+ <span><a href="/">HOME</a> · <a href="/product">PRODUCT</a> · <a href="/brand">BRAND</a> · <a href="/playground">DASHBOARDS</a> &middot; <a href="/llms.txt">LLMS.TXT</a></span>
+</footer>
+<script src="/interact.js"></script>
+</body>
+</html>
diff --git a/landing/answers/what-a-share-link-guest-can-reach.md b/landing/answers/what-a-share-link-guest-can-reach.md
new file mode 100644
index 000000000..42c566e17
--- /dev/null
+++ b/landing/answers/what-a-share-link-guest-can-reach.md
@@ -0,0 +1,146 @@
+<!-- generated by build_articles.py — edit content/answers/what-a-share-link-guest-can-reach.md instead -->
+---
+title: "What a XERJ share-link guest can and cannot reach"
+canonical: "https://xerj.org/answers/what-a-share-link-guest-can-reach"
+updated: "2026-09-19"
+source: "content/answers/what-a-share-link-guest-can-reach.md"
+---
+
+# If I share one index with a link and a passcode, what can that person actually reach on my node?
+
+**TL;DR** — A share-link guest gets a key with `read` on the shared index and nothing else. A route allow-list, used for guests only, closes `_cat`, `_cluster`, every other index, all writes, and scroll and point-in-time contexts. Each refusal is a check in a live test that ran 237 checks on 2026-09-19, with 0 failures.
+
+## Agent prompt
+
+```text
+Act as a coding agent. Read https://xerj.org/llms.txt. On a throwaway XERJ node with authentication on, create a share with POST /_share, claim it with POST /_share/claim and a JSON body of {id, passcode}, then use the returned api_key to call /_cat/indices, /_cluster/health, a search on another index, a write to the shared index and a search with ?scroll=1m, and report the status code of each call.
+```
+
+## Commands
+
+### Command 1
+
+Note: Create a share over one index. Needs the node's admin key, read from the data directory.
+
+```sh
+xerj share casefile --label 'for the auditor' --max-claims 1
+```
+
+### Command 2
+
+Note: What the guest page does: exchange the share id and the passcode for a read-only key. Both travel in the body, so the id is not in the request line an access log records. This id and passcode are placeholders and return 404.
+
+```sh
+curl -s -XPOST 'http://127.0.0.1:9200/_share/claim' -H 'content-type: application/json' -d '{"id":"0123456789abcdef0123456789abcdef","passcode":"abcd-2345"}'
+```
+
+### Command 3
+
+Note: End a share by the handle that the list prints. Every key it minted is invalidated.
+
+```sh
+xerj share --revoke 8a1e546d4ee8
+```
+
+## The key a guest is given
+
+Claiming a share mints an ordinary scoped API key with one role, named `share:` plus the share's handle. It carries `read` on the indices the share names and, when a brain is named, on that brain's edges index. It expires when the share does.
+
+Two things confine that key, and both are enforced by the server. The first is the index grants every scoped key gets. The second is a route allow-list that applies only to keys whose roles are all named `share:`. Being recognised as a guest only ever removes reach.
+
+## What is on the allow-list
+
+| A guest can call | On |
+| --- | --- |
+| `_search`, `_count`, `_msearch`, `_mget` | the shared indices |
+| `GET _doc/{id}` | the shared indices |
+| `_mapping`, `_field_caps` | the shared indices |
+| `GET /_graph/{brain}/ego` and `/overview` | the shared brain |
+| `GET /`, `_security/_authenticate`, health probes | the node |
+
+Nothing else. The allow-list can only refuse: a route it permits still goes through the index decision, so an index the guest was not granted is a 403 on a permitted route.
+
+## What was refused in the live test
+
+The test runs against a real node with authentication on. It seeds one shared index and one private index that holds a marker sentence, then looks for that sentence in every response.
+
+| Attempt | Result |
+| --- | --- |
+| `_cat/*`, `_cluster/*`, `_nodes`, `_snapshot`, `_tasks`, `_stats`, `_aliases`, the audit log, `/v1/metrics`, the native `/v1/*` router | 403 |
+| the private index by name, in a comma list, by `_search` with no index | 403, or an answer that holds shared documents only |
+| an alias that points at the private index | 403 |
+| `_msearch` and `_mget` bodies that name the private index | refused, no private text returned |
+| a `terms` lookup, a `more_like_this` like-document, a stored `percolate` document and a `lookup` runtime field that name the private index | no private text returned |
+| `?scroll=1m`, also as `SCROLL` and percent-encoded; `_search/scroll`; `_pit`; `_async_search` | 403 |
+| the owner's own point-in-time id and scroll id, presented by the guest | 403 |
+| index, update, delete, bulk, delete-by-query, reindex, refresh, close, mapping and settings changes | 403 |
+| another brain, writes to the shared brain, `/_memory/*` | 403 |
+| `GET /_share`, `POST /_share`, `DELETE /_share/{handle}`, `POST /_security/api_key` | 403 |
+| the Console API under `/_xerj-console/api/v1/` | 401: it takes a session cookie, not an API key |
+
+A pattern such as `_all` is not refused. It is expanded over what the key holds, so for a guest it means the shared indices and no more.
+
+## An alias is fixed when the share is made
+
+Sharing an alias pins the concrete indices it points at now. The test shares an alias, re-points it at another index, and confirms the guest still reads the first index and gets a 403 on the second.
+
+## The claim route
+
+`POST /_share/claim` is the one route on the node that hands out a credential without authentication, so it is narrow. It is `POST` only, its body is `{id, passcode}` and at most 4 KiB, it is never cached, and every outcome goes to the audit log with the source address.
+
+The share id is in the body and not in the path. A request path is what an access log, a reverse proxy and a tunnel write down by default; a body is not, unless a proxy is set up to log bodies. The test runs against a node with `logging.access_log = true` and looks in that log for every share id it made. It finds none.
+
+A claim against a known share is charged to that share: 10 a minute and 30 an hour, from anywhere. A claim against an unknown id is charged to the source address: 10 a minute and 100 an hour. The two are not stacked, so a flood of made-up ids cannot lock a real guest out, even when a tunnel makes every client arrive from the same address. The test floods the source bucket with a rotating `X-Forwarded-For` and then claims successfully from the same address.
+
+## What this does not cover
+
+A guest can read every document in the shared index, and its mapping. XERJ has no per-document or per-field restriction. That is also why the `autoindex-catalog` index is never granted: it lists every corpus on the node and could not be filtered. `POST /_share` refuses it by name, in a list and through an alias.
+
+Successful reads are only partly audited. The audit log holds a line for every claim outcome and every `_search`. It also holds a line for every request refused to an authenticated key, such as a guest's attempt to list, create or revoke a share or to mint a key. It holds no line for a successful `_msearch`, `_mget`, `_count`, `_mapping`, `_field_caps` or `GET _doc`. So a guest can read the whole shared index through those without a trace. It holds no line for an unauthenticated request other than a claim.
+
+Through `xerj share --tunnel`, Cloudflare ends TLS and can read the passcode, the guest key, the searches and the documents.
+
+Guest searches are not rate-limited. Authorization in XERJ comes from scoped API keys; roles are stored but not enforced. XERJ is single-node, so the share is only as available as that one host.
+
+The test ran on Linux. macOS and Windows were not run.
+
+## FAQ
+
+### If I give someone a read-only share link to one search index, can they see my other indices or anything else on the server?
+
+No. The guest key is granted `read` on the shared index only, and a route allow-list closes everything that describes the node. Another index is a 403 by name, by alias and from inside a request body.
+
+### Can a guest list my indices with _cat/indices?
+
+No. `_cat`, `_cluster`, `_nodes`, `_snapshot`, `_tasks` and `_stats` all return 403 to a guest key. An ordinary scoped key sees a filtered view of those; a guest sees none of it.
+
+### Can a guest write, delete or reindex?
+
+No. Index, update, delete, bulk, delete-by-query, reindex, refresh, mapping and settings changes all return 403. The live test also confirms that no guest write landed.
+
+### Can a guest keep a scroll or a point-in-time open on my machine?
+
+No. `scroll`, `_search/scroll`, `_pit` and `_async_search` are refused, and so is a `pit` clause in a search body, so a guest cannot ride a point-in-time that someone else opened.
+
+### What is stored on disk about a share?
+
+A SHA-256 digest of the share id and an Argon2id hash of the passcode, in `shares.json` with mode 0600. No share id, passcode or guest key is written to that file, to the API-key file or to the audit log. The guest page sends the share id in a request body and never in a URL, so the node's access log does not hold it either.
+
+### What can a guest still do that I should think about?
+
+Read every document in the shared index and copy what they read. A share grants whole indices. There is no per-document or per-field restriction to apply.
+
+## Evidence
+
+- The guest route allow-list: _search, _count, _msearch, _mget, _mapping, _field_caps, GET _doc, and the graph ego and overview routes. — `engine/crates/xerj-api/src/authz.rs`
+- The live test makes 237 checks against a node with authentication on and the access log on (225 without the native-listener section); all passed on 2026-09-19. — `docs/usecases/share-links/VERIFICATION.md`
+- A share id is 128 bits and is stored as a SHA-256 digest; the passcode is stored as an Argon2id hash in a file with mode 0600. — `engine/crates/xerj-api/src/share.rs`
+- Unknown share ids are limited to 10 a minute and 100 an hour per source address; a known share to 10 a minute and 30 an hour. — `engine/crates/xerj-api/src/share.rs`
+- The guest page is served with default-src 'none' and frame-ancestors 'none'. — `engine/crates/xerj-console-api/src/spa.rs`
+
+## Related
+
+- [How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?](/answers/share-folder-read-only-search-without-uploading)
+- [How do I let someone outside my network search an index on my laptop without opening a port?](/answers/share-local-search-index-through-a-tunnel)
+- [How do I give two agents private memory on one laptop?](/answers/private-agent-memory-namespaces)
+- [Auth & TLS](/docs/security)
diff --git a/landing/answers/what-is-xerj.html b/landing/answers/what-is-xerj.html
index da61e073b..e8605a61a 100644
--- a/landing/answers/what-is-xerj.html
+++ b/landing/answers/what-is-xerj.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/answers/why-autoindex-skipped-files.html b/landing/answers/why-autoindex-skipped-files.html
index 2ca70dbed..800e3da9a 100644
--- a/landing/answers/why-autoindex-skipped-files.html
+++ b/landing/answers/why-autoindex-skipped-files.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/index.html b/landing/compare/index.html
index 8dff45edf..954f4363a 100644
--- a/landing/compare/index.html
+++ b/landing/compare/index.html
@@ -190,6 +190,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/xerj-vs-ast-grep.html b/landing/compare/xerj-vs-ast-grep.html
index 68bea507f..22d50a39c 100644
--- a/landing/compare/xerj-vs-ast-grep.html
+++ b/landing/compare/xerj-vs-ast-grep.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/xerj-vs-docfetcher.html b/landing/compare/xerj-vs-docfetcher.html
index 312dd08b2..ea13578ab 100644
--- a/landing/compare/xerj-vs-docfetcher.html
+++ b/landing/compare/xerj-vs-docfetcher.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/xerj-vs-elasticsearch-local.html b/landing/compare/xerj-vs-elasticsearch-local.html
index 50b505b08..228e44b62 100644
--- a/landing/compare/xerj-vs-elasticsearch-local.html
+++ b/landing/compare/xerj-vs-elasticsearch-local.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/xerj-vs-houdahspot.html b/landing/compare/xerj-vs-houdahspot.html
index 6907cb41c..653a79d6f 100644
--- a/landing/compare/xerj-vs-houdahspot.html
+++ b/landing/compare/xerj-vs-houdahspot.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/xerj-vs-khoj.html b/landing/compare/xerj-vs-khoj.html
index 8f54dfef7..e69ddd2c8 100644
--- a/landing/compare/xerj-vs-khoj.html
+++ b/landing/compare/xerj-vs-khoj.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/xerj-vs-localsynapse.html b/landing/compare/xerj-vs-localsynapse.html
index 3d7d99d8b..49a98dd9d 100644
--- a/landing/compare/xerj-vs-localsynapse.html
+++ b/landing/compare/xerj-vs-localsynapse.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/xerj-vs-meilisearch.html b/landing/compare/xerj-vs-meilisearch.html
index be9b0ab3a..42aa860f1 100644
--- a/landing/compare/xerj-vs-meilisearch.html
+++ b/landing/compare/xerj-vs-meilisearch.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/xerj-vs-obsidian-omnisearch.html b/landing/compare/xerj-vs-obsidian-omnisearch.html
index 298102ec0..9eb63a54e 100644
--- a/landing/compare/xerj-vs-obsidian-omnisearch.html
+++ b/landing/compare/xerj-vs-obsidian-omnisearch.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/xerj-vs-pagefind.html b/landing/compare/xerj-vs-pagefind.html
index 5d8e848e1..294f6dc69 100644
--- a/landing/compare/xerj-vs-pagefind.html
+++ b/landing/compare/xerj-vs-pagefind.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/xerj-vs-recoll.html b/landing/compare/xerj-vs-recoll.html
index 70605694c..4657c86c0 100644
--- a/landing/compare/xerj-vs-recoll.html
+++ b/landing/compare/xerj-vs-recoll.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/xerj-vs-ripgrep-all.html b/landing/compare/xerj-vs-ripgrep-all.html
index 04f396b71..6cce4bef9 100644
--- a/landing/compare/xerj-vs-ripgrep-all.html
+++ b/landing/compare/xerj-vs-ripgrep-all.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/xerj-vs-ripgrep-for-code-agents.html b/landing/compare/xerj-vs-ripgrep-for-code-agents.html
index 37280f5be..0b75c4c78 100644
--- a/landing/compare/xerj-vs-ripgrep-for-code-agents.html
+++ b/landing/compare/xerj-vs-ripgrep-for-code-agents.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/xerj-vs-spotlight.html b/landing/compare/xerj-vs-spotlight.html
index 33554ef43..bf0092b08 100644
--- a/landing/compare/xerj-vs-spotlight.html
+++ b/landing/compare/xerj-vs-spotlight.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/xerj-vs-typesense.html b/landing/compare/xerj-vs-typesense.html
index 26f71291d..c5dd905eb 100644
--- a/landing/compare/xerj-vs-typesense.html
+++ b/landing/compare/xerj-vs-typesense.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/xerj-vs-vector-database.html b/landing/compare/xerj-vs-vector-database.html
index 332980bcc..d70c43dc2 100644
--- a/landing/compare/xerj-vs-vector-database.html
+++ b/landing/compare/xerj-vs-vector-database.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/compare/xerj-vs-web-agent-search.html b/landing/compare/xerj-vs-web-agent-search.html
index 5378bdb4e..52b8c7e9d 100644
--- a/landing/compare/xerj-vs-web-agent-search.html
+++ b/landing/compare/xerj-vs-web-agent-search.html
@@ -209,6 +209,9 @@
<a href="/answers/improve-basic-faiss-rag-pipeline" class=""><span class="eyebrow">66</span>How do I improve a basic FAISS RAG pipeline?</a>
<a href="/answers/filter-knn-exact-scan-caveat" class=""><span class="eyebrow">67</span>Why did my filtered vector search get slower when I added a filter?</a>
<a href="/answers/vector-database-vs-full-text-search" class=""><span class="eyebrow">68</span>What's the actual difference between a vector database and full-text search when I have a folder?</a>
+ <a href="/answers/share-folder-read-only-search-without-uploading" class=""><span class="eyebrow">69</span>How do I give my lawyer or accountant read-only search over a folder of email and PDFs without uploading it?</a>
+ <a href="/answers/share-local-search-index-through-a-tunnel" class=""><span class="eyebrow">70</span>How do I let someone outside my network search an index on my laptop without opening a port?</a>
+ <a href="/answers/what-a-share-link-guest-can-reach" class=""><span class="eyebrow">71</span>If I share one index with a link and a passcode, what can that person actually reach on my node?</a>
</div>
<div class="group">
<span class="label">COMPARISONS</span>
diff --git a/landing/llms-full.txt b/landing/llms-full.txt
index 57ae4159e..ab8ad01f6 100644
--- a/landing/llms-full.txt
+++ b/landing/llms-full.txt
@@ -876,6 +876,53 @@ All three case studies are collected at https://xerj.org/case-studies —
one measured on real code (WordPress), two functional proofs on synthetic
corpora (semantic analytics, Postgres CDC); the named parties are not customers.
+Share an indexed folder with one person, read-only — `xerj share`:
+ https://xerj.org/answers/share-folder-read-only-search-without-uploading
+ https://github.com/xerj-org/xerj/blob/main/docs/SHARING.md (threat model)
+ xerj share <index|folder> [--expires 24h] [--max-claims 1] [--passcode <code>]
+ [--label <text>] [--brain <name>] [--tunnel [--keep]] [--public-url <https://…>]
+ [--url <node>] [--data-dir <dir>] [--api-key <admin key>] [--json]
+ xerj share --list xerj share --revoke <handle>
+ Prints, ONCE: the guest link (the share id rides in the URL fragment, which a
+ browser never sends to a server), the passcode, the expiry, and the revoke
+ command. Give the human the link and the passcode through DIFFERENT channels.
+ A folder argument resolves to the brain and indices `xerj brain <folder>` built;
+ `xerj brain` prints the exact share command when it finishes.
+ - The guest opens the link, types the passcode, and gets a reading room over that
+ one index: search, highlighted snippets, a document view. Served by the owner's
+ node; the folder is not uploaded, the guest installs nothing. Search and reading ONLY —
+ no text is generated, no model is called. Where the index has a `semantic_text`
+ field the page uses `hybrid`; with the DEFAULT embedder that is lexical (word /
+ sub-word overlap + BM25), not meaning. Do not describe it to a user as AI search.
+ - Needs authentication ON (the default) and the node's ADMIN key. It REFUSES a node
+ started with `--insecure` (exit 1; `POST /_share` → 409): there every request is
+ already the superuser, so a read-only key would restrict nothing.
+ - Defaults: expires 24h (max 30d), max-claims 1 (max 50), generated passcode
+ xxxx-xxxx (8 symbols, 31-symbol alphabet). Passcode attempts: 10/min and 30/hour
+ PER SHARE, from anywhere; junk ids: 10/min and 100/hour per source address.
+ - The printed link points at the node's own URL; on a loopback URL only that machine
+ can reach it. One open (max-claims) is one browser tab. For a remote guest: `--tunnel` (runs the operator's own `cloudflared` quick
+ tunnel, prints the https link, runs until Ctrl-C, then closes the tunnel AND
+ revokes the share; if `cloudflared` is missing it prints install steps and the
+ local link instead of failing) or `--public-url` for a node already published.
+ A quick tunnel's hostname is new on every start, and Cloudflare terminates TLS:
+ the corpus is not uploaded there, but the passcode, the guest key, the
+ searches and the documents the guest opens cross Cloudflare's network in a form
+ Cloudflare can read. The command prints this with the link; relay it to the human.
+ Running it for a human: start it in the background, wait for "tunnel is up",
+ relay the link + passcode, and tell them the link dies when the command stops.
+ - A guest key reaches the shared indices (and the shared brain's `ego`/`overview`)
+ and NOTHING else: other indices (by name, pattern, alias or request body), `_cat`,
+ `_cluster`, `_nodes`, `_snapshot`, `/_share`, `/_memory`, writes of any kind,
+ `scroll` / `_pit` / `_async_search`, and the Console API are refused. A share
+ grants WHOLE indices — there is no per-document or per-field restriction, and a
+ guest can copy what they read.
+ - Verified 2026-09-19 on Linux: a live test of 237 reach/limiter/header/audit checks
+ against a node with authentication on and the access log on, and a headless-Chrome
+ run of the guest page (claim, search, read, an XSS probe document that stayed inert,
+ re-opening the link, sign-out). One manual run through a real quick tunnel on
+ 2026-09-18, before the review fixes. macOS / Windows: not verified.
+
Also validated end-to-end: semantic search & RAG, passage retrieval, vector search
(kNN), vector quantization (SQ8), hybrid search, log analytics, anomaly detection,
continuous anomaly datafeeds, migrate-from-Elasticsearch — all linked from the
@@ -1064,6 +1111,22 @@ Agent memory (see §3.5–3.6):
POST /_memory/{namespace}/_recall
DELETE /_memory/{namespace}/{id}
+Share links (`xerj share`, §4 — read-only guest access to named indices):
+ POST /_share admin key only. {index: "a"|["a","b"], brain?,
+ expires_in?: "24h", max_claims?: 1, passcode?,
+ label?} → record + share_id, url_path, passcode
+ (plaintext shown this once; only digests stored)
+ GET /_share admin key only. No ids, no hashes.
+ DELETE /_share/{id|handle} admin key only. Invalidates every key it minted.
+ POST /_share/claim UNAUTHENTICATED, rate-limited, audited, never
+ cached. {id, passcode} → {api_key, index, indices,
+ brain, expires_at, label, claims_left}. The share
+ id goes in the BODY, never in a URL (a path is
+ what access logs record);
+ 401 wrong passcode · 404 unknown · 410 expired/
+ used up/revoked · 429 + Retry-After · 409 open node
+ GET /_xerj-console/share the guest page (no session; strict CSP)
+
Autoindex artifacts (written by the `xerj autoindex` CLI, §3.0 — ordinary indices,
query them like any other):
POST /autoindex-catalog/_search the self-describing catalog: datasets,
diff --git a/landing/llms.txt b/landing/llms.txt
index 0980f1e3f..cc693a8f7 100644
--- a/landing/llms.txt
+++ b/landing/llms.txt
@@ -73,6 +73,7 @@ Then, from an unknown folder to an answered question: `xerj autoindex <folder>`
- `POST|GET /{index}/_count` · `POST /{index}/_delete_by_query` · `POST /{index}/_update_by_query` · `POST /_mget` · `POST /{index}/_mget`.
- `POST /_memory/{namespace}` (also `GET` list, `DELETE` namespace) · `POST /_memory/{namespace}/_recall` · `DELETE /_memory/{namespace}/{id}`.
- `POST /autoindex-catalog/_search` — the self-describing catalog written by `xerj autoindex`. CLI equivalents: `xerj autoindex map [--json]`, `xerj autoindex status`.
+- `POST /_share` · `GET /_share` · `DELETE /_share/{handle}` (admin key only) · `POST /_share/claim` with `{id, passcode}` (unauthenticated, rate-limited) — share links; CLI: `xerj share`. See Use cases below.
- [llms-full.txt §3](https://xerj.org/llms-full.txt): the full contract for all seven operations — every parameter, response shape, error and field type
- [Endpoint contract](https://xerj.org/docs/agents/endpoints): the same surface as an agent reference page · [ES-compatible API](https://xerj.org/docs/api-es-compat) · [Native API](https://xerj.org/docs/api-native) on `http://localhost:8080`
@@ -189,6 +190,10 @@ Direct answers for you, the AI agent: the link, then the question that page answ
- [When does XERJ kNN use an exact scan instead of HNSW?](https://xerj.org/answers/filter-knn-exact-scan-caveat.md): Why is filtered kNN slower than unfiltered?
- **Retrieval: selection**
- [Vector database or full-text search for a folder?](https://xerj.org/answers/vector-database-vs-full-text-search.md): What's the actual difference between a vector database and full-text search?
+- **Sharing: read-only guest access**
+ - [Read-only search over a folder, without uploading it](https://xerj.org/answers/share-folder-read-only-search-without-uploading.md): I need my accountant to search a folder of emails and PDFs. How do I do that without uploading everything somewhere?
+ - [Share a local search index through a tunnel](https://xerj.org/answers/share-local-search-index-through-a-tunnel.md): How can I give a remote person temporary search access to files on my laptop without port forwarding or a VPN?
+ - [What a XERJ share-link guest can and cannot reach](https://xerj.org/answers/what-a-share-link-guest-can-reach.md): If I give someone a read-only share link to one search index, can they see my other indices or anything else on the server?
## Comparisons
@@ -226,6 +231,7 @@ Direct answers for you, the AI agent: the link, then the question that page answ
- [Use cases](https://xerj.org/use-cases): what people point XERJ at, by industry and workload
- [Recipes index](https://xerj.org/docs/recipes/): the full catalog, every recipe validated end-to-end and carrying its own honest findings including the ties and the losses
- [Zero-config folder indexing](https://xerj.org/docs/recipes/zero-config-autoindex): the flagship — one command, no per-corpus flags, a self-describing catalog and data map
+- **Share an indexed folder with one person, read-only** — `xerj share <index|folder> [--expires 24h] [--max-claims 1] [--label <text>] [--tunnel]` prints a link, a passcode, the expiry and the revoke command; the guest opens the link in a browser and gets a search-and-read page over that one index, served by the owner's node. **The folder is not uploaded and the guest installs nothing; it is search and reading only — no text is generated.** Needs a node with authentication ON (the default; it REFUSES an `--insecure` node, where a read-only key would restrict nothing) and the node's admin key (`--data-dir` / `XERJ_API_KEY`). With the default local URL the link only works on this machine unless you add `--tunnel` (your own `cloudflared` quick tunnel; Cloudflare terminates TLS and can read the passcode, the guest key and what the guest opens — the command says so; Ctrl-C closes the tunnel and revokes the share) or `--public-url`. Give the human the link and the passcode **separately**, and show them the printed `xerj share --revoke <handle>`. A guest key reaches the shared index only: no other index, no `_cat`/`_cluster`, no writes, no scroll/PIT. [How-to](https://xerj.org/answers/share-folder-read-only-search-without-uploading.md) · [what a guest can reach](https://xerj.org/answers/what-a-share-link-guest-can-reach.md) · [through a tunnel](https://xerj.org/answers/share-local-search-index-through-a-tunnel.md) · [threat model](https://github.com/xerj-org/xerj/blob/main/docs/SHARING.md)
- [Agent long-term memory](https://xerj.org/docs/recipes/agentic-memory): `/_memory` store and recall, namespaced, with dedup, metadata filters and recency blending
- [Index a folder of documents](https://xerj.org/docs/recipes/document-folder-index): recursive PDF/DOCX/HTML/MD/TXT → extract, chunk, auto-embed → ranked, cited passages
- [Semantic search & RAG](https://xerj.org/docs/recipes/semantic-search-rag) · [passage retrieval](https://xerj.org/docs/recipes/passage-retrieval) · [vector search (kNN)](https://xerj.org/docs/recipes/vector-search-knn) · [vector quantization](https://xerj.org/docs/recipes/vector-quantization) · [hybrid search](https://xerj.org/docs/recipes/hybrid-search): one retrieval mode per recipe, each with a runnable request
diff --git a/landing/sitemap.xml b/landing/sitemap.xml
index 172ae2fdd..684df499d 100644
--- a/landing/sitemap.xml
+++ b/landing/sitemap.xml
@@ -268,6 +268,14 @@
<loc>https://xerj.org/answers/set-mcp-memory-storage-path</loc>
<lastmod>2026-09-20</lastmod>
</url>
+ <url>
+ <loc>https://xerj.org/answers/share-folder-read-only-search-without-uploading</loc>
+ <lastmod>2026-09-20</lastmod>
+ </url>
+ <url>
+ <loc>https://xerj.org/answers/share-local-search-index-through-a-tunnel</loc>
+ <lastmod>2026-09-20</lastmod>
+ </url>
<url>
<loc>https://xerj.org/answers/store-agent-memory-without-llm-call</loc>
<lastmod>2026-09-20</lastmod>
@@ -280,6 +288,10 @@
<loc>https://xerj.org/answers/vector-database-vs-full-text-search</loc>
<lastmod>2026-09-20</lastmod>
</url>
+ <url>
+ <loc>https://xerj.org/answers/what-a-share-link-guest-can-reach</loc>
+ <lastmod>2026-09-20</lastmod>
+ </url>
<url>
<loc>https://xerj.org/answers/what-is-xerj</loc>
<lastmod>2026-09-20</lastmod>
diff --git a/scripts/seo/article_data.py b/scripts/seo/article_data.py
index 031ad2fea..f36074e63 100644
--- a/scripts/seo/article_data.py
+++ b/scripts/seo/article_data.py
@@ -58,7 +58,9 @@ COMMAND_TOKEN_RE = re.compile(r"^-{1,2}[A-Za-z][A-Za-z0-9-]*(?:=.*)?$")
# (the binary answers `unknown argument`), while omitting `index` and `brain`,
# which are — so it rejected a page documenting `xerj brain ./notes` and waved
# through a command nobody can run. Check the binary before editing this.
-XERJ_COMMANDS = frozenset({"index", "autoindex", "brain", "mcp", "help", "version"})
+# `share` added 2026-09-18 with the subcommand itself (`xerj share --help`,
+# engine/crates/xerj-server/src/share.rs).
+XERJ_COMMANDS = frozenset({"index", "autoindex", "brain", "mcp", "share", "help", "version"})
SHELL_PRIMITIVES = frozenset({
"bash", "cd", "command", "curl", "env", "export", "git", "sh", "until", "wget",
})
diff --git a/scripts/seo/claims_rules.py b/scripts/seo/claims_rules.py
index dc3bbb4ee..f3bae2b1d 100644
--- a/scripts/seo/claims_rules.py
+++ b/scripts/seo/claims_rules.py
@@ -927,11 +927,11 @@ RULES = [
"kind": "pattern",
"code": True,
"pattern": r"\bxerj\s+(?:query|snapshot|cluster|migrate|restore|backup|admin|search)\b",
- "reason": "The only subcommands are `index`, `autoindex`, `brain` and `mcp`. There is no "
+ "reason": "The subcommands are `index`, `autoindex`, `brain`, `mcp` and `share`. There is no "
"`xerj query`, `xerj snapshot`, `xerj cluster` or `xerj migrate`. (`xerj mcp` "
"itself landed in rc.17 - on rc.16 it returns `unknown argument: mcp`.)",
"evidence": [LC + ":56", LC + ":641"],
- "rewrite": "Use `xerj index`, `xerj autoindex`, `xerj brain` or `xerj mcp`. Everything else "
+ "rewrite": "Use `xerj index`, `xerj autoindex`, `xerj brain`, `xerj mcp` or `xerj share`. Everything else "
"is an HTTP call against the running node.",
},
{
diff --git a/xerj-ux/share/icon.svg b/xerj-ux/share/icon.svg
new file mode 100644
index 000000000..ae2ebae17
--- /dev/null
+++ b/xerj-ux/share/icon.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><rect width="16" height="16" rx="3" fill="#0D0D0D"/><path d="M4 4l8 8M12 4l-8 8" stroke="#EEBB00" stroke-width="2.2" stroke-linecap="round"/></svg>
diff --git a/xerj-ux/share/index.html b/xerj-ux/share/index.html
new file mode 100644
index 000000000..c7bd88661
--- /dev/null
+++ b/xerj-ux/share/index.html
@@ -0,0 +1,96 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<meta name="referrer" content="no-referrer">
+<meta name="robots" content="noindex, nofollow, noarchive">
+<meta name="color-scheme" content="dark light">
+<title>Shared with you · XERJ</title>
+<!--
+ The share-link guest page. Buildless and self-contained on purpose:
+ no third-party script, font, stylesheet or image — the server sends this
+ page with `default-src 'none'; script-src 'self'; style-src 'self'; …`, so
+ nothing here may be inline either. Absolute asset paths because the page is
+ served at both /_xerj-console/share and /_xerj-console/share/.
+-->
+<link rel="stylesheet" href="/_xerj-console/share/share.css">
+<link rel="icon" href="/_xerj-console/share/icon.svg" type="image/svg+xml">
+<script src="/_xerj-console/share/share.js" defer></script>
+</head>
+<body>
+<noscript>
+ <p class="noscript">This page needs JavaScript: it exchanges your passcode for read-only access and runs your searches. Nothing else is loaded — every script on this page comes from the computer that shared these documents with you.</p>
+</noscript>
+
+<main id="app">
+
+ <!-- ── 1. passcode ───────────────────────────────────────────────── -->
+ <section id="view-claim" class="card" hidden>
+ <p class="eyebrow">XERJ · shared with you</p>
+ <h1>Enter the passcode</h1>
+ <p class="lead">Someone gave you read-only access to a set of documents on their computer. They sent you a passcode separately from this link.</p>
+ <form id="claim-form" autocomplete="off" novalidate>
+ <label for="passcode">Passcode</label>
+ <input id="passcode" name="passcode" type="text" inputmode="text" autocomplete="off" autocapitalize="none" autocorrect="off" spellcheck="false" maxlength="128" required>
+ <p id="claim-error" class="error" role="alert" hidden></p>
+ <button id="claim-button" type="submit">Open</button>
+ </form>
+ <ul class="facts">
+ <li>Read-only. You can search and read; you cannot change or delete anything.</li>
+ <li>The documents stay on the owner's computer. What you search for and open is sent from their machine to your browser, over the connection the owner set up.</li>
+ <li id="via-tunnel" hidden>This link goes through a Cloudflare tunnel. Cloudflare carries the connection and can read what passes through it: your passcode, your searches and the documents you open.</li>
+ <li>Access ends on its own, and the owner can end it at any time.</li>
+ </ul>
+ </section>
+
+ <!-- ── 2. a link that cannot be used ─────────────────────────────── -->
+ <section id="view-ended" class="card" hidden>
+ <p class="eyebrow">XERJ · shared with you</p>
+ <h1 id="ended-title">This link cannot be opened</h1>
+ <p id="ended-text" class="lead"></p>
+ <p id="ended-hint" class="hint"></p>
+ </section>
+
+ <!-- ── 3. the reading room ───────────────────────────────────────── -->
+ <section id="view-room" hidden>
+ <header class="room-head">
+ <div class="room-title">
+ <p class="eyebrow">XERJ · shared with you · read-only</p>
+ <h1 id="room-label"></h1>
+ </div>
+ <div class="room-meta">
+ <p id="room-expiry" class="expiry"></p>
+ <button id="signout" type="button" class="quiet">Sign out</button>
+ </div>
+ </header>
+
+ <p class="notice" id="room-notice">Read-only. These documents stay on the owner's computer — your searches are answered by their machine, and nothing leaves it except the results you see.</p>
+ <p class="notice" id="room-via-tunnel" hidden>This link goes through a Cloudflare tunnel: Cloudflare carries the connection and can read your searches and the documents you open.</p>
+
+ <form id="search-form" role="search" autocomplete="off">
+ <label for="q" class="visually-hidden">Search these documents</label>
+ <input id="q" name="q" type="search" placeholder="Search these documents" autocomplete="off" spellcheck="false" maxlength="512">
+ <button type="submit">Search</button>
+ </form>
+ <p id="search-mode" class="hint"></p>
+ <p id="room-status" class="status" role="status" aria-live="polite"></p>
+
+ <div id="results-pane">
+ <ol id="results" class="results"></ol>
+ <button id="more" type="button" class="quiet" hidden>More results</button>
+ </div>
+
+ <article id="doc-pane" class="doc" hidden>
+ <button id="doc-back" type="button" class="quiet">← Back to results</button>
+ <h2 id="doc-title"></h2>
+ <dl id="doc-meta" class="doc-meta"></dl>
+ <div id="doc-body"></div>
+ </article>
+
+ <p id="console-link" class="hint" hidden><a id="console-href" href="/_xerj-console/">Open the full console view</a> — the same read-only access, with the corpus map.</p>
+ </section>
+
+</main>
+</body>
+</html>
diff --git a/xerj-ux/share/share.css b/xerj-ux/share/share.css
new file mode 100644
index 000000000..c59e26231
--- /dev/null
+++ b/xerj-ux/share/share.css
@@ -0,0 +1,186 @@
+/* ============================================================
+ XERJ — share-link guest page
+ Self-contained: same six colours as assets/tokens.css, system
+ font stacks only (the console pulls web fonts from a CDN; a page
+ handed to a stranger loads nothing from anyone but the owner).
+ ============================================================ */
+
+:root {
+ --paper: #0D0D0D;
+ --ink: #E0E0E0;
+ --mute: #8A8A8A;
+ --faint: #2A2A2A;
+ --raise: #161616;
+ --accent: #EEBB00;
+ --on-accent: #0D0D0D;
+ --danger: #FF8A8A;
+ --danger-bg: #2A1414;
+ --mark-bg: #4A3A00;
+ --mark-ink: #FFE9A0;
+ --font-display: 'Helvetica Neue Condensed', 'Arial Narrow', Impact, sans-serif;
+ --font-data: ui-monospace, 'SF Mono', Menlo, Consolas, monospace;
+ --font-prose: -apple-system, system-ui, 'Segoe UI', Roboto, sans-serif;
+}
+@media (prefers-color-scheme: light) {
+ :root {
+ --paper: #FBFAF6;
+ --ink: #141414;
+ --mute: #6A6661;
+ --faint: #E6E4DC;
+ --raise: #FFFFFF;
+ --accent: #A06800;
+ --on-accent: #FFFFFF;
+ --danger: #9A1B1B;
+ --danger-bg: #FBE9E9;
+ --mark-bg: #FFE9A0;
+ --mark-ink: #141414;
+ }
+}
+
+* { box-sizing: border-box; }
+html { -webkit-text-size-adjust: 100%; }
+body {
+ margin: 0;
+ background: var(--paper);
+ color: var(--ink);
+ font: 16px/1.55 var(--font-prose);
+}
+[hidden] { display: none !important; }
+.visually-hidden {
+ position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0;
+ overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0;
+}
+
+main { max-width: 880px; margin: 0 auto; padding: 48px 24px 96px; }
+.noscript { max-width: 560px; margin: 64px auto; padding: 0 24px; }
+
+.eyebrow {
+ margin: 0 0 8px;
+ font: 11px/1.4 var(--font-data);
+ letter-spacing: 0.18em; text-transform: uppercase;
+ color: var(--mute);
+}
+h1 {
+ margin: 0 0 8px;
+ font: 800 32px/1.1 var(--font-display);
+ letter-spacing: -0.01em;
+ overflow-wrap: anywhere;
+}
+h2 { margin: 16px 0 8px; font: 700 24px/1.2 var(--font-prose); overflow-wrap: anywhere; }
+.lead { margin: 0 0 24px; color: var(--mute); }
+.hint { margin: 8px 0 0; font-size: 13px; color: var(--mute); }
+.hint a { color: var(--accent); }
+
+/* ── cards (passcode, ended) ─────────────────────────────── */
+.card {
+ max-width: 480px; margin: 8vh auto 0;
+ padding: 32px;
+ background: var(--raise);
+ border: 1px solid var(--faint);
+ border-radius: 8px;
+}
+label { display: block; margin: 0 0 6px; font-size: 13px; font-weight: 600; }
+input[type="text"], input[type="search"] {
+ width: 100%; padding: 12px 14px;
+ background: var(--paper); color: var(--ink);
+ border: 1px solid var(--faint); border-radius: 4px;
+ font: 16px/1.3 var(--font-data);
+}
+input:focus-visible, button:focus-visible, a:focus-visible {
+ outline: 2px solid var(--accent); outline-offset: 2px;
+}
+button {
+ padding: 12px 20px;
+ background: var(--accent); color: var(--on-accent);
+ border: 1px solid var(--accent); border-radius: 4px;
+ font: 600 14px/1.2 var(--font-prose);
+ cursor: pointer;
+}
+button:disabled { opacity: 0.55; cursor: progress; }
+button.quiet {
+ padding: 8px 12px;
+ background: transparent; color: var(--ink);
+ border-color: var(--faint);
+ font-weight: 500;
+}
+button.quiet:hover { border-color: var(--mute); }
+#claim-form button { width: 100%; margin-top: 16px; }
+
+.error {
+ margin: 12px 0 0; padding: 10px 12px;
+ background: var(--danger-bg); color: var(--danger);
+ border-radius: 4px; font-size: 14px;
+}
+.facts {
+ margin: 28px 0 0; padding: 20px 0 0 18px;
+ border-top: 1px solid var(--faint);
+ color: var(--mute); font-size: 13px;
+}
+.facts li { margin: 0 0 8px; }
+
+/* ── reading room ────────────────────────────────────────── */
+.room-head {
+ display: flex; gap: 24px; align-items: flex-end; justify-content: space-between;
+ flex-wrap: wrap;
+ padding-bottom: 16px; border-bottom: 1px solid var(--faint);
+}
+.room-title { min-width: 0; flex: 1 1 320px; }
+.room-meta { display: flex; gap: 16px; align-items: center; }
+.expiry { margin: 0; font: 13px/1.4 var(--font-data); color: var(--mute); text-align: right; }
+.expiry.soon { color: var(--danger); }
+.notice {
+ margin: 16px 0 24px; padding: 12px 14px;
+ border-left: 3px solid var(--accent);
+ background: var(--raise);
+ font-size: 14px; color: var(--ink);
+}
+
+#search-form { display: flex; gap: 8px; }
+#search-form input { flex: 1 1 auto; min-width: 0; }
+.status { min-height: 24px; margin: 16px 0 8px; font: 13px/1.4 var(--font-data); color: var(--mute); }
+.status.bad { color: var(--danger); }
+
+.results { list-style: none; margin: 0; padding: 0; }
+.results li { border-bottom: 1px solid var(--faint); }
+.hit {
+ display: block; width: 100%;
+ padding: 16px 4px; text-align: left;
+ background: transparent; color: var(--ink);
+ border: 0; border-radius: 0;
+ font: inherit; cursor: pointer;
+}
+.hit:hover .hit-title, .hit:focus-visible .hit-title { color: var(--accent); }
+.hit-title { display: block; font-weight: 600; font-size: 16px; overflow-wrap: anywhere; }
+.hit-meta { display: block; margin: 2px 0 6px; font: 12px/1.4 var(--font-data); color: var(--mute); overflow-wrap: anywhere; }
+.hit-snippet { display: block; font-size: 14px; color: var(--ink); overflow-wrap: anywhere; white-space: pre-wrap; }
+.hit-note { display: block; margin-top: 6px; font: 12px/1.4 var(--font-data); color: var(--mute); font-style: italic; }
+mark { background: var(--mark-bg); color: var(--mark-ink); border-radius: 2px; padding: 0 1px; }
+#more { margin: 24px 0 0; }
+
+/* ── document view ───────────────────────────────────────── */
+.doc { margin-top: 8px; }
+.doc-meta {
+ display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px;
+ margin: 0 0 24px; padding: 12px 0;
+ border-top: 1px solid var(--faint); border-bottom: 1px solid var(--faint);
+ font: 13px/1.5 var(--font-data);
+}
+.doc-meta dt { color: var(--mute); }
+.doc-meta dd { margin: 0; overflow-wrap: anywhere; white-space: pre-wrap; }
+.doc-field-name {
+ margin: 24px 0 6px;
+ font: 11px/1.4 var(--font-data); letter-spacing: 0.18em; text-transform: uppercase;
+ color: var(--mute);
+}
+.doc-text {
+ margin: 0; white-space: pre-wrap; overflow-wrap: anywhere;
+ font: 16px/1.65 var(--font-prose);
+}
+#console-link { margin-top: 48px; padding-top: 16px; border-top: 1px solid var(--faint); }
+
+@media (max-width: 560px) {
+ main { padding: 24px 16px 64px; }
+ .card { margin-top: 0; padding: 24px; }
+ h1 { font-size: 26px; }
+ .expiry { text-align: left; }
+}
diff --git a/xerj-ux/share/share.js b/xerj-ux/share/share.js
new file mode 100644
index 000000000..c00c7b5bf
--- /dev/null
+++ b/xerj-ux/share/share.js
@@ -0,0 +1,820 @@
+// ============================================================
+// XERJ — share-link guest page
+//
+// The whole guest side of `xerj share`: read the share id from the URL
+// fragment, exchange it plus a passcode for a read-only key, then give the
+// guest a reading room over the one index that key can reach.
+//
+// THREE RULES THIS FILE KEEPS — the tests grep for the first and drive a real
+// browser at the other two:
+//
+// 1. Document text is attacker-controlled. It is other people's email. It is
+// only ever put on the page as TEXT — `textContent` / `createTextNode` —
+// and never parsed as markup. There is no `innerHTML`, `outerHTML`,
+// `insertAdjacentHTML`, `document.write`, `eval` or `new Function` in
+// this file, and an HTML email body is shown as the text it is. URLs in
+// documents are not turned into links.
+// 2. The share id is never part of a URL this page requests. It lives in
+// the URL *fragment*, which a browser does not send to a server, and it
+// goes to the node in the BODY of the claim POST (`/_share/claim`) —
+// never in a path. A path is what an access log, a reverse proxy and a
+// tunnel's edge write down; the first cut posted to `/_share/<id>/claim`
+// and undid the fragment one request later. After a claim the id is
+// removed from the address bar.
+// 3. The session is ONE sessionStorage record, written exactly as
+// sessionStorage['xerj.share'] =
+// JSON.stringify({api_key, index, brain, expires_at, label})
+// — the console's guest mode reads the same record. sessionStorage, not
+// localStorage: it is scoped to this tab and gone when the tab closes.
+// Beside it sits `xerj.share.link`: the share's public HANDLE (the first
+// 12 hex characters of SHA-256(id), what `xerj share --list` prints). It
+// cannot be turned back into the link. It is how the page knows that a
+// link opened again in this tab is the one it already holds a key for.
+//
+// "Zero-token": search and reading. Nothing here generates text, summarises,
+// or calls a model.
+// ============================================================
+'use strict';
+
+(() => {
+ const SHARE_KEY = 'xerj.share';
+ const LINK_KEY = 'xerj.share.link';
+ const PAGE_SIZE = 10;
+ // Highlight delimiters. Private-use code points: they cannot be typed into a
+ // search box by accident and mean nothing as markup, so a snippet is split on
+ // them and rebuilt from text nodes. The engine's default `<em>` tags would
+ // arrive glued to unescaped document text — unusable without parsing HTML.
+ const HL_PRE = '\uE000';
+ const HL_POST = '\uE001';
+ // Fields that usually hold the readable body, best first.
+ const BODY_FIELDS = ['body', 'text', 'content', 'message', 'description', 'summary'];
+ // Fields that usually name the document, best first.
+ const TITLE_FIELDS = ['title', 'subject', 'email_subject', 'name', 'attachment_name', 'filename', 'file_name', 'path'];
+ // Shown under a hit's title, in this order, when present.
+ const META_FIELDS = ['email_from', 'from', 'author', 'email_date', 'date', 'attachment_name', 'ax_path', 'path', '_source_path'];
+ const MAX_QUERY_FIELDS = 24;
+ const MAX_INLINE_VALUE = 280;
+
+ const $ = (id) => document.getElementById(id);
+ const views = { claim: $('view-claim'), ended: $('view-ended'), room: $('view-room') };
+
+ /** In-memory only. `session` mirrors the sessionStorage record. */
+ const state = {
+ shareId: null,
+ session: null,
+ plans: [], // [{index, semanticField, fields}]
+ query: '',
+ terms: [],
+ from: 0,
+ total: 0,
+ shown: 0,
+ noneContain: false,
+ expiryTimer: null,
+ };
+
+ // ── small DOM helpers (text only) ────────────────────────────────────────
+
+ function show(name) {
+ for (const [key, el] of Object.entries(views)) el.hidden = key !== name;
+ }
+
+ function el(tag, className, text) {
+ const node = document.createElement(tag);
+ if (className) node.className = className;
+ if (text != null) node.textContent = String(text);
+ return node;
+ }
+
+ function clear(node) {
+ while (node.firstChild) node.removeChild(node.firstChild);
+ }
+
+ function setStatus(text, bad) {
+ const node = $('room-status');
+ node.textContent = text || '';
+ node.classList.toggle('bad', !!bad);
+ }
+
+ // ── the session record ───────────────────────────────────────────────────
+
+ function expiryMs(v) {
+ if (v == null || v === '') return null;
+ if (typeof v === 'number') return Number.isFinite(v) ? v : null;
+ const t = Date.parse(String(v));
+ return Number.isFinite(t) ? t : null;
+ }
+
+ function loadSession() {
+ let raw = null;
+ try { raw = sessionStorage.getItem(SHARE_KEY); } catch { return null; }
+ if (!raw) return null;
+ let obj;
+ try { obj = JSON.parse(raw); } catch { return null; }
+ if (!obj || typeof obj.api_key !== 'string' || !obj.api_key ||
+ typeof obj.index !== 'string' || !obj.index) return null;
+ const exp = expiryMs(obj.expires_at);
+ if (exp != null && exp <= Date.now()) return null;
+ return obj;
+ }
+
+ /** The contract, exactly: five keys, nothing else. */
+ function saveSession(claim) {
+ const record = {
+ api_key: claim.api_key,
+ index: claim.index,
+ brain: claim.brain == null ? null : claim.brain,
+ expires_at: claim.expires_at == null ? null : claim.expires_at,
+ label: claim.label == null ? null : claim.label,
+ };
+ sessionStorage.setItem(SHARE_KEY, JSON.stringify(record));
+ return record;
+ }
+
+ /** Stop using the session in this page, without touching what is stored. */
+ function leaveRoom() {
+ state.session = null;
+ state.plans = [];
+ if (state.expiryTimer) clearInterval(state.expiryTimer);
+ state.expiryTimer = null;
+ }
+
+ function dropSession() {
+ try {
+ sessionStorage.removeItem(SHARE_KEY);
+ sessionStorage.removeItem(LINK_KEY);
+ } catch { /* storage disabled */ }
+ leaveRoom();
+ }
+
+ // ── which share is this? ─────────────────────────────────────────────────
+
+ // SHA-256 (FIPS 180-4) of an ASCII string, as hex. It is only ever fed the
+ // 32-character share id. `crypto.subtle` would do the same, but it does not
+ // exist on a plain-http page that is not localhost — which a share on a LAN
+ // address is — and the same-link check has to behave the same everywhere.
+ // The browser test checks the result against the node's own digest.
+ function sha256Hex(ascii) {
+ const K = [
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
+ ];
+ const H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
+ const rotr = (x, n) => (x >>> n) | (x << (32 - n));
+ const bytes = [];
+ for (let i = 0; i < ascii.length; i += 1) bytes.push(ascii.charCodeAt(i) & 0xff);
+ const bits = bytes.length * 8;
+ bytes.push(0x80);
+ while (bytes.length % 64 !== 56) bytes.push(0);
+ // 64-bit big-endian length. The input is a 32-character id, so the high
+ // word is always zero.
+ bytes.push(0, 0, 0, 0, (bits >>> 24) & 0xff, (bits >>> 16) & 0xff, (bits >>> 8) & 0xff, bits & 0xff);
+ const w = new Array(64);
+ for (let off = 0; off < bytes.length; off += 64) {
+ for (let i = 0; i < 16; i += 1) {
+ const at = off + 4 * i;
+ w[i] = (bytes[at] << 24) | (bytes[at + 1] << 16) | (bytes[at + 2] << 8) | bytes[at + 3];
+ }
+ for (let i = 16; i < 64; i += 1) {
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
+ }
+ let [a, b, c, d, e, f, g, h] = H;
+ for (let i = 0; i < 64; i += 1) {
+ const t1 = (h + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]) | 0;
+ const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
+ h = g; g = f; f = e; e = (d + t1) | 0;
+ d = c; c = b; b = a; a = (t1 + t2) | 0;
+ }
+ [a, b, c, d, e, f, g, h].forEach((v, i) => { H[i] = (H[i] + v) | 0; });
+ }
+ return H.map((x) => (x >>> 0).toString(16).padStart(8, '0')).join('');
+ }
+
+ /** The share's public handle — what the node derives from the same id. */
+ function handleOf(shareId) {
+ return sha256Hex(shareId).slice(0, 12);
+ }
+
+ function storedHandle() {
+ try { return sessionStorage.getItem(LINK_KEY); } catch { return null; }
+ }
+
+ function stripFragment() {
+ try { history.replaceState(null, '', location.pathname); } catch { /* ignore */ }
+ }
+
+ // ── talking to the node ──────────────────────────────────────────────────
+
+ /** Same-origin only, never cached, never with cookies, never with a Referer. */
+ async function call(method, path, body, withKey) {
+ const headers = { accept: 'application/json' };
+ if (body !== undefined) headers['content-type'] = 'application/json';
+ if (withKey && state.session) headers.authorization = `ApiKey ${state.session.api_key}`;
+ const resp = await fetch(path, {
+ method,
+ headers,
+ body: body === undefined ? undefined : JSON.stringify(body),
+ cache: 'no-store',
+ credentials: 'omit',
+ referrerPolicy: 'no-referrer',
+ redirect: 'error',
+ });
+ let json = null;
+ try { json = await resp.json(); } catch { /* not JSON */ }
+ return { status: resp.status, json, retryAfter: resp.headers.get('retry-after') };
+ }
+
+ function encIndex(index) {
+ return String(index).split(',').map((s) => encodeURIComponent(s.trim())).join(',');
+ }
+
+ // ── 1. claiming ──────────────────────────────────────────────────────────
+
+ function readShareId() {
+ const frag = (location.hash || '').replace(/^#/, '').trim();
+ return /^[0-9a-f]{32}$/.test(frag) ? frag : null;
+ }
+
+ function ended(title, text, hint) {
+ $('ended-title').textContent = title;
+ $('ended-text').textContent = text;
+ $('ended-hint').textContent = hint || '';
+ show('ended');
+ }
+
+ async function onClaim(event) {
+ event.preventDefault();
+ const input = $('passcode');
+ const button = $('claim-button');
+ const error = $('claim-error');
+ const passcode = input.value.trim();
+ error.hidden = true;
+ if (!passcode) {
+ error.textContent = 'Type the passcode you were sent.';
+ error.hidden = false;
+ input.focus();
+ return;
+ }
+ button.disabled = true;
+ let result;
+ try {
+ // The id goes in the body. Never in the path — see rule 2.
+ result = await call('POST', '/_share/claim', { id: state.shareId, passcode }, false);
+ } catch {
+ button.disabled = false;
+ error.textContent = 'Could not reach the computer that shared this. It may be offline — ask the owner to check, then try again.';
+ error.hidden = false;
+ return;
+ }
+ button.disabled = false;
+ const { status, json } = result;
+ if (status === 200 && json && typeof json.api_key === 'string') {
+ input.value = '';
+ // Only now does a session from another share stop being kept.
+ state.session = saveSession(json);
+ try { sessionStorage.setItem(LINK_KEY, handleOf(state.shareId)); } catch { /* storage disabled */ }
+ // The id has done its job; take it out of the address bar.
+ stripFragment();
+ state.shareId = null;
+ enterRoom();
+ return;
+ }
+ if (status === 401 || status === 403) {
+ error.textContent = 'That passcode is not right. Check it and try again — a few wrong tries lock the link for a while.';
+ } else if (status === 429) {
+ const secs = Number(result.retryAfter);
+ const wait = Number.isFinite(secs) && secs > 0
+ ? (secs >= 120 ? `about ${Math.ceil(secs / 60)} minutes` : `${secs} seconds`)
+ : 'a little while';
+ error.textContent = `Too many tries. This link is locked for ${wait}.`;
+ } else if (status === 410) {
+ const reason = json && json.error && typeof json.error.reason === 'string' ? json.error.reason : '';
+ ended(
+ 'This link is no longer active',
+ reason.includes('used up') ? 'It has already been opened as many times as its owner allowed.'
+ : reason.includes('revoked') ? 'Its owner has ended it.'
+ : 'It has expired.',
+ 'Ask the person who sent it for a new one.',
+ );
+ return;
+ } else if (status === 404) {
+ ended('This link is not recognised', 'The link may be incomplete, or it belongs to a different computer.', 'Check that you copied the whole link, including everything after the # sign.');
+ return;
+ } else if (status === 409) {
+ ended('Sharing is turned off on this computer', 'The owner is running it without authentication, so it will not hand out guest access.', 'Let the person who sent the link know.');
+ return;
+ } else {
+ error.textContent = `Something went wrong (HTTP ${status}). Try again in a moment.`;
+ }
+ error.hidden = false;
+ input.select();
+ }
+
+ // ── 2. the reading room ──────────────────────────────────────────────────
+
+ function fmtRemaining(ms) {
+ if (ms <= 0) return 'now';
+ const s = Math.floor(ms / 1000);
+ const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60);
+ if (d > 0) return `in ${d}d ${h}h`;
+ if (h > 0) return `in ${h}h ${m}m`;
+ if (m > 0) return `in ${m}m`;
+ return `in ${s}s`;
+ }
+
+ function tickExpiry() {
+ const exp = expiryMs(state.session && state.session.expires_at);
+ const node = $('room-expiry');
+ if (exp == null) { node.textContent = 'read-only access'; return; }
+ const left = exp - Date.now();
+ if (left <= 0) {
+ dropSession();
+ ended('Your access has ended', 'This share has expired.', 'Ask the person who sent it for a new link if you still need it.');
+ return;
+ }
+ const when = new Date(exp);
+ node.textContent = `access ends ${fmtRemaining(left)} · ${when.toLocaleString()}`;
+ node.classList.toggle('soon', left < 15 * 60 * 1000);
+ }
+
+ function accessEnded() {
+ dropSession();
+ ended('Your access has ended', 'The share expired, or its owner ended it.', 'Ask the person who sent it for a new link if you still need it.');
+ }
+
+ async function enterRoom() {
+ const s = state.session;
+ $('room-label').textContent = s.label || s.index;
+ document.title = `${s.label || 'Shared documents'} · XERJ`;
+ clear($('results'));
+ $('more').hidden = true;
+ $('doc-pane').hidden = true;
+ $('results-pane').hidden = false;
+ $('search-mode').textContent = '';
+ setStatus('');
+ show('room');
+ tickExpiry();
+ if (!state.session) return; // expired between claim and here
+ state.expiryTimer = setInterval(tickExpiry, 20000);
+ $('q').focus();
+ await learnMappings();
+ probeConsole();
+ }
+
+ /** Walk an ES mapping `properties` tree into [{name, type}]. */
+ function flattenProps(props, prefix, out) {
+ for (const [name, def] of Object.entries(props || {})) {
+ if (!def || typeof def !== 'object') continue;
+ const full = prefix ? `${prefix}.${name}` : name;
+ if (def.properties) flattenProps(def.properties, full, out);
+ else if (typeof def.type === 'string') out.push({ name: full, type: def.type });
+ }
+ return out;
+ }
+
+ /**
+ * One search plan per shared index: which field (if any) is `semantic_text`
+ * — that is what makes the `hybrid` query available — and which text fields
+ * a plain `multi_match` should cover.
+ */
+ async function learnMappings() {
+ const indices = String(state.session.index).split(',').map((x) => x.trim()).filter(Boolean);
+ let mapping = null;
+ try {
+ const r = await call('GET', `/${encIndex(state.session.index)}/_mapping`, undefined, true);
+ if (r.status === 401 || r.status === 403) return accessEnded();
+ if (r.status === 200) mapping = r.json;
+ } catch { /* fall through: search without a field list */ }
+ state.plans = indices.map((index) => {
+ const props = mapping && mapping[index] && mapping[index].mappings && mapping[index].mappings.properties;
+ const flat = flattenProps(props, '', []).filter((f) => !f.name.endsWith('_vector'));
+ const semantic = flat.find((f) => f.type === 'semantic_text');
+ const texts = flat.filter((f) => f.type === 'text' || f.type === 'semantic_text').map((f) => f.name);
+ const ordered = [
+ ...TITLE_FIELDS.filter((f) => texts.includes(f)).map((f) => `${f}^2`),
+ ...texts.filter((f) => !TITLE_FIELDS.includes(f)),
+ ].slice(0, MAX_QUERY_FIELDS);
+ return { index, semanticField: semantic ? semantic.name : null, fields: ordered };
+ });
+ const hybrid = state.plans.filter((p) => p.semanticField).length;
+ $('search-mode').textContent = hybrid === 0
+ ? 'Keyword search (BM25). Results are ranked by how well the words match.'
+ : hybrid === state.plans.length
+ ? 'Hybrid search: keyword matching (BM25) fused with vector similarity from the owner\'s embedder. No text is generated.'
+ : 'Hybrid search where the index supports it, keyword search elsewhere. No text is generated.';
+ return undefined;
+ }
+
+ /**
+ * The keyword leg. `multi_match` over the text fields the mapping listed,
+ * titles boosted. With no field list (the mapping could not be read) it is
+ * `simple_query_string`, which needs none — this engine refuses a
+ * `multi_match` without `fields`, and `simple_query_string` never throws on
+ * what a person types.
+ */
+ function lexicalQuery(plan, q) {
+ if (plan.fields.length) return { multi_match: { query: q, fields: plan.fields } };
+ return { simple_query_string: { query: q } };
+ }
+
+ function queryFor(plan, q) {
+ if (!plan.semanticField) return lexicalQuery(plan, q);
+ return { hybrid: { queries: [
+ { query: lexicalQuery(plan, q), weight: 1 },
+ { query: { semantic: { field: plan.semanticField, query: q } }, weight: 1 },
+ ] } };
+ }
+
+ /**
+ * Named fields, never `*`: this engine's highlighter does not expand a field
+ * pattern, so a wildcard comes back with no highlight at all. The names are
+ * the ones being searched (boosts stripped); with no mapping, the usual
+ * body and title names.
+ */
+ function highlightFields(plan) {
+ const names = plan.fields.length
+ ? plan.fields.map((f) => f.replace(/\^.*$/, ''))
+ : [...BODY_FIELDS, ...TITLE_FIELDS];
+ const fields = {};
+ for (const name of names) fields[name] = {};
+ return fields;
+ }
+
+ function searchBody(plan, q, from) {
+ return {
+ from,
+ size: PAGE_SIZE,
+ track_total_hits: true,
+ query: queryFor(plan, q),
+ _source: { excludes: ['*_vector'] },
+ highlight: {
+ pre_tags: [HL_PRE],
+ post_tags: [HL_POST],
+ fragment_size: 220,
+ number_of_fragments: 1,
+ fields: highlightFields(plan),
+ },
+ };
+ }
+
+ function termsOf(q) {
+ return Array.from(new Set(
+ q.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((t) => t.length >= 2),
+ )).slice(0, 12);
+ }
+
+ async function runSearch(q, from) {
+ if (!state.session) return;
+ if (!state.plans.length) await learnMappings();
+ if (!state.session) return;
+ setStatus('Searching…');
+ const perIndex = [];
+ try {
+ // One request per shared index, each with the query its mapping
+ // supports. Scores from different query types are not comparable, so
+ // pages are interleaved by rank rather than merged by score.
+ for (const plan of state.plans) {
+ const r = await call('POST', `/${encodeURIComponent(plan.index)}/_search`, searchBody(plan, q, from), true);
+ if (r.status === 401 || r.status === 403) return accessEnded();
+ if (r.status !== 200 || !r.json || !r.json.hits) {
+ const reason = r.json && r.json.error && r.json.error.reason;
+ setStatus(`The search could not be run${reason ? `: ${String(reason).slice(0, 200)}` : ` (HTTP ${r.status})`}.`, true);
+ return;
+ }
+ perIndex.push(r.json.hits);
+ }
+ } catch {
+ setStatus('Could not reach the computer that shared this. It may be offline.', true);
+ return;
+ }
+ const total = perIndex.reduce((n, h) => n + (h.total && typeof h.total.value === 'number' ? h.total.value : 0), 0);
+ const lists = perIndex.map((h) => Array.isArray(h.hits) ? h.hits : []);
+ const merged = [];
+ for (let rank = 0; rank < PAGE_SIZE; rank += 1) {
+ for (const list of lists) if (list[rank]) merged.push(list[rank]);
+ }
+ if (from === 0) { clear($('results')); state.shown = 0; }
+ state.query = q;
+ state.terms = termsOf(q);
+ state.from = from;
+ state.total = total;
+ for (const hit of merged) $('results').appendChild(renderHit(hit));
+ // Which query the list now shows. Until the answer is in, the previous
+ // list stays on screen, so a reader (or a test) cannot tell a new result
+ // from an old one by looking at the rows alone.
+ $('results').dataset.query = q;
+ state.shown += merged.length;
+ const anyFull = lists.some((l) => l.length === PAGE_SIZE);
+ $('more').hidden = !(anyFull && state.shown < total);
+ // The vector leg of a hybrid query ranks *something* for any string. When
+ // not one row on the first page contains a word of the query, say that
+ // first — a guest looking for a name that is not in the corpus should not
+ // have to read ten notes to find out.
+ const rows = Array.from($('results').children);
+ state.noneContain = rows.length > 0 && rows.every((li) => li.dataset.similarOnly === '1');
+ setStatus(total === 0 ? `No documents match “${q}”.` : countLine());
+ }
+
+ /**
+ * "N matching documents" is only true of a keyword search. The vector leg of
+ * a hybrid query scores every document it looks at, so there the count is
+ * how many were ranked, not how many contain the words.
+ */
+ function countLine() {
+ const n = state.total.toLocaleString();
+ const noun = state.total === 1 ? 'document' : 'documents';
+ if (state.noneContain) {
+ return `No document contains “${state.query}”. Showing ${state.shown.toLocaleString()} ranked by vector similarity instead.`;
+ }
+ const what = state.plans.some((p) => p.semanticField) ? `${n} ${noun} ranked, best first` : `${n} matching ${noun}`;
+ return `${what} · showing ${state.shown.toLocaleString()}`;
+ }
+
+ function firstString(source, names) {
+ for (const name of names) {
+ const v = source[name];
+ if (typeof v === 'string' && v.trim()) return v.trim();
+ }
+ return null;
+ }
+
+ function titleOf(hit) {
+ return firstString(hit._source || {}, TITLE_FIELDS) || String(hit._id);
+ }
+
+ /** Append `text` to `parent`, wrapping sentinel-delimited runs in <mark>. */
+ function appendHighlighted(parent, text) {
+ let rest = String(text);
+ for (;;) {
+ const a = rest.indexOf(HL_PRE);
+ if (a < 0) break;
+ const b = rest.indexOf(HL_POST, a + 1);
+ if (b < 0) break;
+ if (a > 0) parent.appendChild(document.createTextNode(rest.slice(0, a)));
+ parent.appendChild(el('mark', null, rest.slice(a + 1, b)));
+ rest = rest.slice(b + 1);
+ }
+ // Whatever is left — including a stray, unpaired delimiter — is text.
+ const tail = rest.split(HL_PRE).join('').split(HL_POST).join('');
+ if (tail) parent.appendChild(document.createTextNode(tail));
+ }
+
+ /** Append `text`, marking whole-word-prefix occurrences of the query terms. */
+ function appendWithTerms(parent, text, terms) {
+ const value = String(text);
+ if (!terms.length) { parent.appendChild(document.createTextNode(value)); return; }
+ const escaped = terms.map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
+ const re = new RegExp(`(${escaped.join('|')})`, 'giu');
+ let last = 0;
+ let marks = 0;
+ for (const m of value.matchAll(re)) {
+ if (marks >= 2000) break; // a pathological document must not freeze the tab
+ if (m.index > last) parent.appendChild(document.createTextNode(value.slice(last, m.index)));
+ parent.appendChild(el('mark', null, m[0]));
+ last = m.index + m[0].length;
+ marks += 1;
+ }
+ if (last < value.length) parent.appendChild(document.createTextNode(value.slice(last)));
+ }
+
+ /** `size` characters of `text` around the first occurrence of any term. */
+ function windowAround(text, terms, size) {
+ const value = String(text).replace(/\s+/g, ' ').trim();
+ if (value.length <= size) return value;
+ const lower = value.toLowerCase();
+ let at = -1;
+ for (const t of terms) {
+ const i = lower.indexOf(t);
+ if (i >= 0 && (at < 0 || i < at)) at = i;
+ }
+ const start = at < 0 ? 0 : Math.max(0, at - Math.floor(size / 3));
+ const end = Math.min(value.length, start + size);
+ return `${start > 0 ? '…' : ''}${value.slice(start, end)}${end < value.length ? '…' : ''}`;
+ }
+
+ function renderHit(hit) {
+ const source = hit._source || {};
+ const li = el('li');
+ const button = el('button', 'hit');
+ button.type = 'button';
+ button.appendChild(el('span', 'hit-title', titleOf(hit)));
+ const meta = META_FIELDS
+ .map((f) => (typeof source[f] === 'string' || typeof source[f] === 'number') ? String(source[f]) : null)
+ .filter(Boolean)
+ .slice(0, 3);
+ if (meta.length) button.appendChild(el('span', 'hit-meta', meta.join(' · ').slice(0, 300)));
+ const snippet = el('span', 'hit-snippet');
+ // A fragment of the body says more than a fragment of the title, which is
+ // already on the line above — so body-like fields first.
+ const hl = hit.highlight && typeof hit.highlight === 'object' ? hit.highlight : {};
+ const order = [...BODY_FIELDS.filter((f) => f in hl), ...Object.keys(hl).filter((f) => !BODY_FIELDS.includes(f) && !TITLE_FIELDS.includes(f)), ...TITLE_FIELDS.filter((f) => f in hl)];
+ const fragments = order.flatMap((f) => (Array.isArray(hl[f]) ? hl[f] : [])).filter((f) => typeof f === 'string');
+ if (fragments.length) {
+ appendHighlighted(snippet, fragments[0].slice(0, 600));
+ } else {
+ // No highlight came back (the hybrid query returns none): cut a window
+ // around the first query term instead of always showing the opening.
+ const body = firstString(source, BODY_FIELDS);
+ if (body) appendWithTerms(snippet, windowAround(body, state.terms, 280), state.terms);
+ }
+ if (snippet.firstChild) button.appendChild(snippet);
+ // The vector leg of a hybrid query ranks documents that share no word with
+ // the query. Say so on the hit, rather than let a reader hunt for a word
+ // that is not there.
+ const plan = state.plans.find((p) => p.index === hit._index);
+ if (plan && plan.semanticField && state.terms.length) {
+ const haystack = `${titleOf(hit)} ${firstString(source, BODY_FIELDS) || ''}`.toLowerCase();
+ if (!state.terms.some((t) => haystack.includes(t))) {
+ button.appendChild(el('span', 'hit-note', 'Does not contain your words — ranked here by vector similarity.'));
+ li.dataset.similarOnly = '1';
+ }
+ }
+ button.addEventListener('click', () => openDoc(hit._index, hit._id));
+ li.appendChild(button);
+ return li;
+ }
+
+ // ── the document view ────────────────────────────────────────────────────
+
+ function isVectorish(name, value) {
+ return name.endsWith('_vector') ||
+ (Array.isArray(value) && value.length > 16 && value.every((x) => typeof x === 'number'));
+ }
+
+ function asText(value) {
+ if (value == null) return '';
+ if (typeof value === 'string') return value;
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
+ if (Array.isArray(value) && value.every((x) => x == null || typeof x !== 'object')) return value.join(', ');
+ try { return JSON.stringify(value, null, 2); } catch { return ''; }
+ }
+
+ async function openDoc(index, id) {
+ setStatus('Opening…');
+ let r;
+ try {
+ r = await call('GET', `/${encodeURIComponent(index)}/_doc/${encodeURIComponent(id)}?_source_excludes=*_vector`, undefined, true);
+ } catch {
+ setStatus('Could not reach the computer that shared this. It may be offline.', true);
+ return;
+ }
+ if (r.status === 401 || r.status === 403) return accessEnded();
+ if (r.status !== 200 || !r.json || !r.json._source) {
+ setStatus(`That document could not be opened (HTTP ${r.status}).`, true);
+ return;
+ }
+ const source = r.json._source;
+ $('doc-title').textContent = firstString(source, TITLE_FIELDS) || String(id);
+
+ const meta = $('doc-meta');
+ const bodyPane = $('doc-body');
+ clear(meta);
+ clear(bodyPane);
+ const bodyName = BODY_FIELDS.find((f) => typeof source[f] === 'string' && source[f].trim());
+ const long = [];
+ for (const [name, value] of Object.entries(source)) {
+ if (name === bodyName || isVectorish(name, value)) continue;
+ const text = asText(value);
+ if (!text.trim()) continue;
+ if (text.length > MAX_INLINE_VALUE || text.includes('\n')) { long.push([name, text]); continue; }
+ meta.appendChild(el('dt', null, name));
+ meta.appendChild(el('dd', null, text));
+ }
+ meta.hidden = !meta.firstChild;
+ if (bodyName) {
+ const block = el('p', 'doc-text');
+ appendWithTerms(block, source[bodyName], state.terms);
+ bodyPane.appendChild(block);
+ }
+ for (const [name, text] of long) {
+ bodyPane.appendChild(el('p', 'doc-field-name', name));
+ const block = el('p', 'doc-text');
+ appendWithTerms(block, text, state.terms);
+ bodyPane.appendChild(block);
+ }
+ if (!bodyPane.firstChild && !meta.firstChild) bodyPane.appendChild(el('p', 'hint', 'This record has no readable fields.'));
+
+ $('results-pane').hidden = true;
+ $('doc-pane').hidden = false;
+ setStatus('');
+ $('doc-back').focus();
+ window.scrollTo(0, 0);
+ return undefined;
+ }
+
+ function closeDoc() {
+ $('doc-pane').hidden = true;
+ $('results-pane').hidden = false;
+ if (state.total) setStatus(countLine());
+ }
+
+ // ── sign-out, console hand-off ───────────────────────────────────────────
+
+ function signOut() {
+ dropSession();
+ clear($('results'));
+ clear($('doc-meta'));
+ clear($('doc-body'));
+ $('doc-title').textContent = '';
+ $('q').value = '';
+ ended(
+ 'Signed out',
+ 'This browser no longer holds your access.',
+ 'To read again, open the link you were sent. If it was set to open only once, ask its owner for a new one.',
+ );
+ }
+
+ /** The console's guest mode ships separately; only offer it where it exists. */
+ async function probeConsole() {
+ try {
+ const r = await fetch('/_xerj-console/src/data/guest.js', { method: 'HEAD', cache: 'no-store', credentials: 'omit', referrerPolicy: 'no-referrer' });
+ if (!r.ok || !state.session) return;
+ const s = state.session;
+ const first = String(s.index).split(',')[0];
+ $('console-href').href = `/_xerj-console/#/reader?index=${encodeURIComponent(first)}${s.brain ? `&brain=${encodeURIComponent(s.brain)}` : ''}`;
+ $('console-link').hidden = false;
+ } catch { /* no console guest mode on this node */ }
+ }
+
+ // ── boot ─────────────────────────────────────────────────────────────────
+
+ function boot() {
+ $('claim-form').addEventListener('submit', onClaim);
+ $('search-form').addEventListener('submit', (event) => {
+ event.preventDefault();
+ const q = $('q').value.trim();
+ if (!q) { setStatus('Type something to search for.'); return; }
+ closeDoc();
+ runSearch(q, 0);
+ });
+ $('more').addEventListener('click', () => runSearch(state.query, state.from + PAGE_SIZE));
+ $('doc-back').addEventListener('click', closeDoc);
+ $('signout').addEventListener('click', signOut);
+
+ // A quick tunnel is Cloudflare's: say so before a passcode is typed.
+ if (/\.trycloudflare\.com$/i.test(location.hostname)) {
+ for (const id of ['via-tunnel', 'room-via-tunnel']) $(id).hidden = false;
+ }
+ // A link pasted over the one in the address bar differs only in its
+ // fragment, which no browser treats as a new page: without this the old
+ // view — often "this link is no longer active", whose advice is to ask for
+ // a new link — stayed on screen until a manual reload.
+ window.addEventListener('hashchange', route);
+ route();
+ }
+
+ /**
+ * Decide what to show from the address bar and what this tab already holds.
+ * Runs at load and whenever only the fragment changes.
+ */
+ function route() {
+ state.shareId = readShareId();
+ const existing = loadSession();
+ if (existing && state.shareId && storedHandle() === handleOf(state.shareId)) {
+ // The link this tab has already opened. Its key is still here, so do
+ // NOT ask for the passcode again: on a one-open share that second claim
+ // is refused ("used up") and the guest — who only clicked the link in
+ // their email a second time — would be locked out of a share that still
+ // has days to run. If the key has since been revoked or has expired, the
+ // room's first request says so.
+ stripFragment();
+ state.shareId = null;
+ if (state.session && !views.room.hidden) return; // already reading
+ state.session = existing;
+ enterRoom();
+ return;
+ }
+ if (state.shareId) {
+ // A link to a different share (or a first visit). Ask for its passcode —
+ // but whatever this tab holds is kept until that claim SUCCEEDS, so a
+ // mistyped or dead link does not cost the guest the access they had.
+ leaveRoom();
+ $('claim-error').hidden = true;
+ show('claim');
+ $('passcode').focus();
+ return;
+ }
+ if (existing) {
+ if (state.session && !views.room.hidden) return;
+ state.session = existing;
+ enterRoom();
+ return;
+ }
+ // No session: a handle on its own means nothing.
+ try { sessionStorage.removeItem(LINK_KEY); } catch { /* storage disabled */ }
+ ended(
+ 'This link is incomplete',
+ 'A share link ends with a # sign followed by a long code. That part is missing here.',
+ 'Copy the whole link from the message you were sent and open it again.',
+ );
+ }
+
+ boot();
+})();
diff --git a/xerj-ux/test/share-guest-flow.e2e.mjs b/xerj-ux/test/share-guest-flow.e2e.mjs
new file mode 100644
index 000000000..4822f1d5f
--- /dev/null
+++ b/xerj-ux/test/share-guest-flow.e2e.mjs
@@ -0,0 +1,467 @@
+// ============================================================
+// Share-link guest page — the real flow, in a real browser.
+//
+// XERJ_URL=http://127.0.0.1:9510 XERJ_DATA_DIR=/path/to/data \
+// node xerj-ux/test/share-guest-flow.e2e.mjs
+//
+// Needs a THROWAWAY node with authentication on (it creates an index and
+// shares) and a Chrome/Chromium binary (CHROME_BIN, or one of the usual
+// places). `.github/scripts/share-links-smoke.sh` boots the node and runs this.
+//
+// No npm dependencies on purpose: Chrome is driven over the DevTools
+// protocol's *pipe* transport (`--remote-debugging-pipe`: NUL-delimited JSON
+// on fd 3/4), so there is no WebSocket client, no Playwright, no install step,
+// and the file is not named *.test.mjs because `node --test` in the ux-tests
+// job has no node to talk to.
+//
+// What it proves:
+// 1. wrong passcode → an error, and nothing in sessionStorage;
+// 2. right passcode → the reading room, the share id gone from the address
+// bar, and sessionStorage['xerj.share'] holding EXACTLY
+// {api_key, index, brain, expires_at, label} (the console guest-mode
+// contract);
+// 3. search returns highlighted snippets; a document opens;
+// 4. a document full of markup is shown as the text it is — no element is
+// created from it, no handler runs, nothing is fetched — in the result
+// list, in the snippet and in the document view;
+// 5. the page talks to its own origin and nowhere else, and the share id is
+// in NO URL the browser requests — it travels in the body of the claim
+// POST (`/_share/claim`), so no request line an access log records holds it;
+// 6. opening the same link again in the same tab keeps the session (and does
+// not spend a second claim — on a one-open share that would lock the
+// guest out), and a link pasted over another one, which changes only the
+// fragment, is noticed;
+// 7. a query no document contains says so before listing similarity ranks;
+// 8. on a quick-tunnel hostname the page says Cloudflare can read the
+// traffic, and says nothing of the kind anywhere else;
+// 9. sign-out empties sessionStorage and the page.
+// ============================================================
+import { spawn } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { homedir, tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const URL_BASE = (process.env.XERJ_URL || 'http://127.0.0.1:9510').replace(/\/$/, '');
+const DATA_DIR = process.env.XERJ_DATA_DIR;
+if (!DATA_DIR) { console.error('XERJ_DATA_DIR is required (the throwaway node\'s data dir)'); process.exit(2); }
+const ADMIN = readFileSync(join(DATA_DIR, 'admin.key'), 'utf8').trim();
+const INDEX = 'guestroom'; // dynamic mapping: keyword (BM25) search
+const SEM_INDEX = 'guestroom-sem'; // a semantic_text field: the hybrid query
+// A name shaped like a quick tunnel's. Chrome is told to resolve it to the
+// node (see Browser); `.test` hosts never resolve, this one must look real.
+const TUNNEL_HOST = 'xerj-e2e-not-a-real-tunnel.trycloudflare.com';
+
+let passed = 0, failed = 0;
+function ok(name, cond, detail) {
+ if (cond) { passed += 1; console.log(' ok ', name); }
+ else { failed += 1; console.log(' FAIL', name, '->', String(detail === undefined ? '' : JSON.stringify(detail)).slice(0, 500)); }
+}
+
+// ── the node, as its owner ─────────────────────────────────────────────────
+async function api(method, path, body, ndjson) {
+ const resp = await fetch(URL_BASE + path, {
+ method,
+ headers: { authorization: `ApiKey ${ADMIN}`, 'content-type': ndjson ? 'application/x-ndjson' : 'application/json' },
+ body: body === undefined ? undefined : (ndjson ? body : JSON.stringify(body)),
+ });
+ let json = null;
+ try { json = await resp.json(); } catch { /* not json */ }
+ return { status: resp.status, json };
+}
+
+// Text a hostile sender would put in an email. Every one of these runs, loads
+// or navigates if it is ever parsed as HTML.
+const XSS_SUBJECT = '<img src=x onerror="window.__xss=\'subject\'">Quarterly invoice';
+const XSS_BODY = [
+ 'Please review the invoice attached.',
+ '<script>window.__xss="script"</script>',
+ '<img src="/_xerj-console/share/icon.svg?beacon=1" onerror="window.__xss=\'img\'" onload="window.__xss=\'imgload\'">',
+ '<svg onload="window.__xss=\'svg\'"></svg>',
+ '<iframe src="javascript:parent.__xss=\'iframe\'"></iframe>',
+ '<a href="javascript:window.__xss=\'link\'" id="xss-link">click for the invoice</a>',
+ '<style>#view-room{display:none}</style>',
+ '</p></div></article><h1 id="xss-breakout">broke out</h1>',
+ 'invoice total due on receipt.',
+].join('\n');
+
+async function seed() {
+ await api('DELETE', `/${INDEX}`);
+ await api('DELETE', `/${SEM_INDEX}`);
+ const made = await api('PUT', `/${SEM_INDEX}`, { mappings: { properties: { subject: { type: 'text' }, body: { type: 'semantic_text' } } } });
+ if (made.status !== 200) throw new Error(`semantic_text index: ${JSON.stringify(made)}`);
+ const lines = [
+ { index: { _index: INDEX, _id: 'lease' } },
+ { subject: 'Lease dispute', body: 'The landlord refused to return the deposit after the inspection.', email_from: '[email protected]' },
+ { index: { _index: SEM_INDEX, _id: 'receipt' } },
+ { subject: 'Receipt', body: `${'Rent was paid on the first of every month without fail. '.repeat(8)}The deposit of 1200 was paid in January.` },
+ { index: { _index: INDEX, _id: 'xss' } },
+ { subject: XSS_SUBJECT, body: XSS_BODY, email_from: '"><script>window.__xss="from"</script>', body_html: '<html><body onload="window.__xss=\'html\'"><b>bold</b></body></html>' },
+ ].map((l) => JSON.stringify(l)).join('\n') + '\n';
+ const bulk = await api('POST', '/_bulk', lines, true);
+ if (bulk.status !== 200 || bulk.json.errors) throw new Error(`seed failed: ${JSON.stringify(bulk)}`);
+ await api('POST', `/${INDEX},${SEM_INDEX}/_refresh`);
+ const share = await api('POST', '/_share', { index: [INDEX, SEM_INDEX], expires_in: '1h', max_claims: 1, label: 'Files for Dana <b>(bold?)</b>' });
+ if (share.status !== 200) throw new Error(`share create failed: ${JSON.stringify(share)}`);
+ return share.json;
+}
+
+async function shareStatus(handle) {
+ const list = await api('GET', '/_share');
+ return (list.json.shares || []).find((s) => s.handle === handle) || null;
+}
+
+// ── Chrome over the DevTools pipe ──────────────────────────────────────────
+function findChrome() {
+ const candidates = [process.env.CHROME_BIN, '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable',
+ '/usr/bin/chromium', '/usr/bin/chromium-browser',
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'];
+ const pw = join(homedir(), '.cache', 'ms-playwright');
+ for (const c of candidates) if (c && existsSync(c)) return c;
+ if (existsSync(pw)) {
+ for (const dir of ['chromium_headless_shell-1243/chrome-linux/headless_shell', 'chromium-1243/chrome-linux/chrome']) {
+ if (existsSync(join(pw, dir))) return join(pw, dir);
+ }
+ }
+ return null;
+}
+
+class Browser {
+ constructor(bin) {
+ this.profile = mkdtempSync(join(tmpdir(), 'xerj-share-e2e-'));
+ this.proc = spawn(bin, [
+ '--headless=new', '--remote-debugging-pipe', '--no-first-run', '--no-default-browser-check',
+ '--disable-gpu', '--disable-extensions', '--disable-background-networking', '--disable-sync',
+ '--disable-dev-shm-usage', '--no-sandbox', `--user-data-dir=${this.profile}`,
+ // Phase 8 opens the page under a quick-tunnel HOSTNAME without a tunnel:
+ // that one name resolves to the node under test. Nothing leaves the box.
+ `--host-resolver-rules=MAP ${TUNNEL_HOST} ${new URL(URL_BASE).hostname}`,
+ 'about:blank',
+ ], { stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'] });
+ this.nextId = 1;
+ this.pending = new Map();
+ this.listeners = [];
+ let buffer = Buffer.alloc(0);
+ this.proc.stdio[4].on('data', (chunk) => {
+ buffer = Buffer.concat([buffer, chunk]);
+ let end;
+ while ((end = buffer.indexOf(0)) >= 0) {
+ const msg = JSON.parse(buffer.subarray(0, end).toString('utf8'));
+ buffer = buffer.subarray(end + 1);
+ if (msg.id && this.pending.has(msg.id)) {
+ const { resolve, reject } = this.pending.get(msg.id);
+ this.pending.delete(msg.id);
+ if (msg.error) reject(new Error(`${msg.error.message}`)); else resolve(msg.result);
+ } else if (msg.method) {
+ for (const l of this.listeners) l(msg);
+ }
+ }
+ });
+ }
+
+ send(method, params = {}, sessionId) {
+ const id = this.nextId++;
+ const msg = { id, method, params };
+ if (sessionId) msg.sessionId = sessionId;
+ return new Promise((resolve, reject) => {
+ this.pending.set(id, { resolve, reject });
+ this.proc.stdio[3].write(JSON.stringify(msg) + '\0');
+ });
+ }
+
+ async close() {
+ try { await this.send('Browser.close'); } catch { /* already gone */ }
+ this.proc.kill();
+ try { rmSync(this.profile, { recursive: true, force: true }); } catch { /* best effort */ }
+ }
+}
+
+async function main() {
+ const chrome = findChrome();
+ if (!chrome) {
+ console.error('no Chrome/Chromium found (set CHROME_BIN)');
+ process.exit(process.env.XERJ_SHARE_REQUIRE_BROWSER === '1' ? 1 : 77);
+ }
+ console.log(`node ${URL_BASE} · browser ${chrome}`);
+ const share = await seed();
+ const link = `${URL_BASE}${share.url_path}`;
+ ok('the link carries the share id only in its fragment',
+ link.endsWith(`/_xerj-console/share#${share.share_id}`) && !link.split('#')[0].includes(share.share_id), link);
+
+ const browser = new Browser(chrome);
+ const requests = [];
+ const wireHeaders = [];
+ const consoleErrors = [];
+ const dialogs = [];
+ let otherHandle = null;
+ try {
+ const { targetId } = await browser.send('Target.createTarget', { url: 'about:blank' });
+ const { sessionId } = await browser.send('Target.attachToTarget', { targetId, flatten: true });
+ const cdp = (method, params) => browser.send(method, params, sessionId);
+ browser.listeners.push((msg) => {
+ if (msg.sessionId !== sessionId) return;
+ if (msg.method === 'Network.requestWillBeSent') requests.push({ url: msg.params.request.url, method: msg.params.request.method, headers: msg.params.request.headers, postData: msg.params.request.postData || '' });
+ // The headers that actually went on the wire. `requestWillBeSent` lists a
+ // `Referer` key for every request, empty when policy suppressed it.
+ if (msg.method === 'Network.requestWillBeSentExtraInfo') wireHeaders.push(msg.params.headers);
+ if (msg.method === 'Runtime.exceptionThrown') consoleErrors.push(msg.params.exceptionDetails.text);
+ if (msg.method === 'Log.entryAdded' && msg.params.entry.level === 'error') consoleErrors.push(msg.params.entry.text);
+ if (msg.method === 'Page.javascriptDialogOpening') dialogs.push(msg.params.message);
+ });
+ await cdp('Page.enable'); await cdp('Runtime.enable'); await cdp('Network.enable'); await cdp('Log.enable');
+
+ const evaluate = async (expression) => {
+ const r = await cdp('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
+ if (r.exceptionDetails) throw new Error(`page threw: ${r.exceptionDetails.text} ${r.exceptionDetails.exception?.description || ''}`);
+ return r.result.value;
+ };
+ // A predicate that throws is "not yet", not a failure: right after a
+ // navigation the document may still be the previous page (or about:blank),
+ // and `document.getElementById(…)` is null until the new one is parsed.
+ // Seen once under a load average of 54, when the first wait ran before the
+ // guest page had loaded.
+ const waitFor = async (expression, what, ms = 15000) => {
+ const deadline = Date.now() + ms;
+ for (;;) {
+ let hit = false;
+ try { hit = await evaluate(`!!(${expression})`); } catch { hit = false; }
+ if (hit) return true;
+ if (Date.now() > deadline) { ok(`waited for: ${what}`, false, await evaluate('document.body.innerText.slice(0, 400)')); return false; }
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ };
+ const visible = (id) => `(!!document.getElementById('${id}') && !document.getElementById('${id}').hidden)`;
+ const submitPasscode = (code) => evaluate(`(() => {
+ const i = document.getElementById('passcode'); i.value = ${JSON.stringify(code)};
+ document.getElementById('claim-form').requestSubmit(); })()`);
+ // Submit a query and wait until the list shows THAT query's answer. The
+ // previous rows stay on screen until the response lands, so a row count
+ // alone cannot tell a fresh list from a stale one (two queries that both
+ // return two rows looked identical to an earlier version of this test).
+ const search = async (q) => {
+ await evaluate(`(() => {
+ const i = document.getElementById('q'); i.value = ${JSON.stringify(q)};
+ document.getElementById('search-form').requestSubmit(); })()`);
+ await waitFor(`document.getElementById('results').dataset.query === ${JSON.stringify(q)}`, `results for ${JSON.stringify(q)}`);
+ };
+ const injected = () => evaluate(`({
+ xss: window.__xss === undefined ? null : String(window.__xss),
+ foreign: document.querySelectorAll('#app script, #app img, #app svg, #app iframe, #app style, #app a[href^="javascript"], #xss-link, #xss-breakout, #app b').length,
+ roomHidden: document.getElementById('view-room').hidden,
+ })`);
+
+ // ── 1. open the link; the page is the passcode prompt ───────────────────
+ await cdp('Page.navigate', { url: link });
+ await waitFor(visible('view-claim'), 'the passcode prompt');
+ ok('nothing is stored before a passcode is given', await evaluate(`sessionStorage.length === 0 && localStorage.length === 0`));
+ const pageReq = requests.find((r) => r.url.includes('/_xerj-console/share'));
+ ok('the page request does not carry the share id', pageReq && !requests.some((r) => r.url.includes(share.share_id)), requests.map((r) => r.url));
+
+ // ── 2. wrong passcode ───────────────────────────────────────────────────
+ await submitPasscode('not-the-code');
+ await waitFor(`!document.getElementById('claim-error').hidden`, 'the wrong-passcode message');
+ ok('wrong passcode → a message, still on the prompt',
+ await evaluate(`${visible('view-claim')} && /passcode is not right/i.test(document.getElementById('claim-error').textContent)`));
+ ok('wrong passcode stores nothing', await evaluate(`sessionStorage.getItem('xerj.share') === null`));
+
+ // ── 3. right passcode ───────────────────────────────────────────────────
+ await submitPasscode(share.passcode);
+ await waitFor(visible('view-room'), 'the reading room');
+ const stored = JSON.parse(await evaluate(`sessionStorage.getItem('xerj.share')`));
+ ok('sessionStorage[xerj.share] is EXACTLY {api_key, index, brain, expires_at, label}',
+ JSON.stringify(Object.keys(stored)) === JSON.stringify(['api_key', 'index', 'brain', 'expires_at', 'label']), Object.keys(stored));
+ ok('…with a usable key, this index, no brain, the owner\'s expiry and label',
+ typeof stored.api_key === 'string' && stored.api_key.length > 20 && stored.index === `${INDEX},${SEM_INDEX}` && stored.brain === null
+ && Number.isFinite(Date.parse(stored.expires_at)) && stored.label === 'Files for Dana <b>(bold?)</b>', stored);
+ // Beside the session: the share's PUBLIC handle — sha256(id)[..12], what
+ // `xerj share --list` prints — so the page can tell that a link opened
+ // again in this tab is the one it already holds a key for. The page
+ // computes it itself; it has to match the node's.
+ const keptHandle = await evaluate(`sessionStorage.getItem('xerj.share.link')`);
+ ok('beside it, only the share\'s public handle — and it is the node\'s own sha256(id)[..12]',
+ keptHandle === share.handle && keptHandle === createHash('sha256').update(share.share_id).digest('hex').slice(0, 12)
+ && !share.share_id.includes(keptHandle), { keptHandle, handle: share.handle });
+ ok('nothing else is kept in the browser', await evaluate(`sessionStorage.length === 2 && localStorage.length === 0 && document.cookie === ''`));
+ ok('the share id itself is stored nowhere', await evaluate(`!JSON.stringify(Object.entries(sessionStorage)).includes(${JSON.stringify(share.share_id)})`));
+ ok('the share id is gone from the address bar', await evaluate(`location.hash === '' && !location.href.includes(${JSON.stringify(share.share_id)})`));
+ ok('the label is shown as text, not markup',
+ await evaluate(`document.getElementById('room-label').textContent === 'Files for Dana <b>(bold?)</b>' && document.querySelectorAll('#room-label b').length === 0`));
+ ok('the room says read-only, names the expiry, and says where the documents stay',
+ await evaluate(`/read-only/i.test(document.getElementById('view-room').innerText) && /access ends/i.test(document.getElementById('room-expiry').textContent) && /stay on the owner/i.test(document.getElementById('room-notice').textContent)`));
+ await waitFor(`document.getElementById('search-mode').textContent.length > 0`, 'the search-mode line');
+ ok('the page says how it searches — hybrid where a semantic_text field exists, keyword elsewhere — and claims no AI',
+ await evaluate(`/hybrid search where the index supports it, keyword search elsewhere/i.test(document.getElementById('search-mode').textContent) && /no text is generated/i.test(document.getElementById('search-mode').textContent) && !/\\b(AI|neural|semantic search|understands)\\b/i.test(document.getElementById('search-mode').textContent)`),
+ await evaluate(`document.getElementById('search-mode').textContent`));
+
+ // ── 4. search + highlighted snippet + document view ─────────────────────
+ await search('deposit');
+ await waitFor(`document.querySelectorAll('#results li').length > 0`, 'results for "deposit"');
+ await waitFor(`document.querySelectorAll('#results li').length === 2`, 'one hit from each shared index');
+ ok('search covers both shared indices, and every snippet shows the term highlighted',
+ await evaluate(`[...document.querySelectorAll('#results li')].every((li) => [...li.querySelectorAll('mark')].some((m) => /deposit/i.test(m.textContent)))`),
+ await evaluate(`document.getElementById('results').innerText`));
+ ok('a hybrid hit with no server-side highlight gets a snippet cut around the term, not the opening lines',
+ await evaluate(`[...document.querySelectorAll('#results .hit-snippet')].some((n) => n.textContent.startsWith('…') && /deposit of 1200/.test(n.textContent))`),
+ await evaluate(`[...document.querySelectorAll('#results .hit-snippet')].map((n) => n.textContent)`));
+ ok('the count line does not call vector-ranked results "matching"',
+ await evaluate(`/ranked, best first/.test(document.getElementById('room-status').textContent)`),
+ await evaluate(`document.getElementById('room-status').textContent`));
+ await evaluate(`[...document.querySelectorAll('#results button.hit')].find((b) => b.textContent.includes('Lease dispute')).click()`);
+ await waitFor(visible('doc-pane'), 'the document view');
+ ok('the document view shows the subject and the body',
+ await evaluate(`document.getElementById('doc-title').textContent === 'Lease dispute' && /landlord refused/.test(document.getElementById('doc-body').textContent)`));
+ await evaluate(`document.getElementById('doc-back').click()`);
+
+ // A query whose words are in NO document of the semantic_text index: the
+ // vector leg still ranks its one document, and the page has to say so.
+ await search('landlord');
+ await waitFor(`document.querySelectorAll('#results li').length === 2`, 'results for "landlord"');
+ ok('a hybrid hit that contains none of the words is labelled as similarity-ranked, and a real match is not',
+ await evaluate(`(() => {
+ const items = [...document.querySelectorAll('#results li')];
+ const receipt = items.find((li) => li.textContent.includes('Receipt'));
+ const lease = items.find((li) => li.textContent.includes('Lease dispute'));
+ return !!receipt && !!lease && !!receipt.querySelector('.hit-note') && !lease.querySelector('.hit-note');
+ })()`),
+ await evaluate(`document.getElementById('results').innerText`));
+
+ // ── 5. the hostile document ─────────────────────────────────────────────
+ await search('invoice');
+ await waitFor(`[...document.querySelectorAll('#results .hit-title')].some((t) => t.textContent.includes('Quarterly invoice'))`, 'the hostile document in the results');
+ ok('its subject is listed as literal text', await evaluate(`[...document.querySelectorAll('#results .hit-title')].some((t) => t.textContent === ${JSON.stringify(XSS_SUBJECT)})`));
+ let state = await injected();
+ ok('result list + snippet: no element was created from document text, no handler ran', state.xss === null && state.foreign === 0 && !state.roomHidden, state);
+ await evaluate(`[...document.querySelectorAll('#results button.hit')].find((b) => b.textContent.includes('Quarterly invoice')).click()`);
+ await waitFor(visible('doc-pane'), 'the hostile document\'s view');
+ ok('document view shows the markup as the text it is',
+ await evaluate(`document.getElementById('doc-body').textContent.includes('<script>window.__xss="script"</script>') && document.getElementById('doc-body').textContent.includes('<a href="javascript:')`));
+ ok('an HTML email body is shown as source text, never rendered',
+ await evaluate(`document.getElementById('view-room').textContent.includes('<html><body onload=')`));
+ await new Promise((r) => setTimeout(r, 500)); // give any handler that was going to run the time to run
+ state = await injected();
+ ok('document view: no element was created from document text, no handler ran', state.xss === null && state.foreign === 0 && !state.roomHidden, state);
+ ok('no dialog was opened by document content', dialogs.length === 0, dialogs);
+ ok('no request was made for a URL inside a document', !requests.some((r) => r.url.includes('beacon=1')), requests.map((r) => r.url));
+
+ // ── 6. the page only ever talks to its own origin ───────────────────────
+ const origin = new URL(URL_BASE).origin;
+ const foreign = requests.filter((r) => !r.url.startsWith(origin + '/') && !r.url.startsWith('about:') && !r.url.startsWith('data:'));
+ ok('every request went to the node itself — no third party', foreign.length === 0, foreign.map((r) => r.url));
+ // The id is kept out of the page URL (fragment) so that no server logs it.
+ // The claim must not undo that: a request PATH is what an access log, a
+ // reverse proxy and a tunnel's edge write down. The first cut posted to
+ // /_share/<id>/claim, and the node's own access log recorded the id.
+ const withId = requests.filter((r) => r.url.includes(share.share_id));
+ ok('the share id is in NO url the browser requested', withId.length === 0, withId.map((r) => r.url));
+ const claims = requests.filter((r) => r.method === 'POST' && r.url.startsWith(`${origin}/_share`));
+ ok('it travels in the BODY of the claim POST, to /_share/claim, and nowhere else',
+ claims.length === 2 && claims.every((r) => r.url === `${origin}/_share/claim` && JSON.parse(r.postData).id === share.share_id)
+ && requests.filter((r) => r.postData.includes(share.share_id)).length === 2,
+ claims.map((r) => [r.url, r.postData.replace(share.share_id, '<id>')]));
+ const referers = [...requests.map((r) => r.headers), ...wireHeaders]
+ .flatMap((h) => Object.entries(h).filter(([k, v]) => k.toLowerCase() === 'referer' && v).map(([, v]) => v));
+ ok('no request carried a Referer', wireHeaders.length > 0 && referers.length === 0, { seen: wireHeaders.length, referers });
+ ok('the page raised no script errors or CSP violations', consoleErrors.filter((e) => !/401|Failed to load resource/.test(e)).length === 0, consoleErrors);
+
+ // ── 7. the same link again, in the same tab ─────────────────────────────
+ // A guest reading in this tab clicks the link in their email a second
+ // time. The first cut dropped the session whenever a fragment was present
+ // and asked for the passcode again; on this one-open share the second
+ // claim is refused ("used up"), so the guest was locked out for good of a
+ // share that had an hour (in the docs' example: seven days) left to run.
+ // Via about:blank, so that this is a full page load with the fragment in
+ // the URL (from the page itself it would be a fragment-only change, which
+ // is the next check). sessionStorage belongs to the tab and survives it.
+ await cdp('Page.navigate', { url: 'about:blank' });
+ await waitFor(`location.href === 'about:blank'`, 'about:blank');
+ await cdp('Page.navigate', { url: link });
+ await waitFor(`${visible('view-room')} || ${visible('view-claim')} || ${visible('view-ended')}`, 'the page after re-opening the link');
+ ok('re-opening the SAME link in the same tab keeps the session: the room, not the passcode prompt',
+ await evaluate(`${visible('view-room')} && sessionStorage.getItem('xerj.share') !== null`),
+ await evaluate(`({ room: ${visible('view-room')}, claim: ${visible('view-claim')}, ended: ${visible('view-ended')}, stored: sessionStorage.getItem('xerj.share') !== null })`));
+ ok('…and the id is taken out of the address bar again', await evaluate(`location.hash === ''`), await evaluate('location.href'));
+ await search('deposit');
+ ok('…and the kept key still searches', await evaluate(`document.querySelectorAll('#results li').length === 2`));
+ // The same thing without a page load: only the fragment changes.
+ await evaluate(`location.hash = ${JSON.stringify('#' + share.share_id)}`);
+ await new Promise((r) => setTimeout(r, 300));
+ ok('the same link arriving as a fragment-only change leaves the reader where they were',
+ await evaluate(`${visible('view-room')} && location.hash === '' && document.querySelectorAll('#results li').length === 2`));
+ const spent = await shareStatus(share.handle);
+ ok('none of that spent a second claim', spent && spent.claims === 1, spent);
+
+ // ── 8. a query no document contains ─────────────────────────────────────
+ // The vector leg ranks something for any string. Say that nothing matched
+ // before listing what was ranked instead.
+ await search('zzzzqqqqxxxx');
+ ok('a query no document contains says so first, instead of "N documents ranked"',
+ await evaluate(`/^No document contains/.test(document.getElementById('room-status').textContent) && /vector similarity/.test(document.getElementById('room-status').textContent)`),
+ await evaluate(`document.getElementById('room-status').textContent`));
+ await search('deposit');
+ ok('…and a query that does match is counted as before',
+ await evaluate(`/ranked, best first/.test(document.getElementById('room-status').textContent)`),
+ await evaluate(`document.getElementById('room-status').textContent`));
+
+ // ── 9. a DIFFERENT link pasted over this one ────────────────────────────
+ // Pasting a link into the address bar of a tab already on the page changes
+ // only the fragment — no browser reloads for that. Without a `hashchange`
+ // listener the old view stayed: typically "this link is no longer active",
+ // whose own advice is to ask for a new link and open it.
+ const other = await api('POST', '/_share', { index: INDEX, expires_in: '1h', max_claims: 1, label: 'second share' });
+ const bogus = 'ab'.repeat(16);
+ await evaluate(`location.hash = ${JSON.stringify('#' + bogus)}`);
+ await waitFor(visible('view-claim'), 'the passcode prompt for a different link');
+ ok('a different link asks for ITS passcode — and the session this tab holds is not thrown away yet',
+ await evaluate(`sessionStorage.getItem('xerj.share') !== null && document.getElementById('view-room').hidden`));
+ await submitPasscode('whatever-code');
+ await waitFor(visible('view-ended'), 'the not-recognised view');
+ ok('an unknown link ends in "not recognised"', await evaluate(`/not recognised/i.test(document.getElementById('ended-title').textContent)`));
+ await evaluate(`location.hash = ${JSON.stringify('#' + other.json.share_id)}`);
+ await waitFor(visible('view-claim'), 'the passcode prompt after pasting a new link over a dead one');
+ ok('a new link pasted over a dead one (fragment-only navigation) shows the passcode prompt, without a reload',
+ await evaluate(`${visible('view-claim')} && document.getElementById('view-ended').hidden`));
+ await submitPasscode(other.json.passcode);
+ await waitFor(`${visible('view-room')} && document.getElementById('room-label').textContent === 'second share'`, 'the second share\'s room');
+ ok('claiming it replaces the session and the remembered handle',
+ await evaluate(`JSON.parse(sessionStorage.getItem('xerj.share')).label === 'second share' && sessionStorage.getItem('xerj.share.link') === ${JSON.stringify(other.json.handle)}`));
+ ok('no tunnel notice on an ordinary hostname', await evaluate(`document.getElementById('via-tunnel').hidden && document.getElementById('room-via-tunnel').hidden`));
+ otherHandle = other.json.handle; // revoked in `finally`: its key is still needed below
+
+ // ── 10. under a quick-tunnel hostname ───────────────────────────────────
+ // Through `xerj share --tunnel` the browser talks to Cloudflare, which
+ // ends TLS and can read the passcode, the key and every document. The page
+ // used to tell the guest "Nothing is uploaded to a third party — your
+ // browser talks to their machine", and it said so on the tunnel too.
+ const port = new URL(URL_BASE).port;
+ await cdp('Page.navigate', { url: `http://${TUNNEL_HOST}:${port}/_xerj-console/share#${bogus}` });
+ const loaded = await waitFor(`location.hostname === ${JSON.stringify(TUNNEL_HOST)} && ${visible('view-claim')}`, 'the guest page under a quick-tunnel hostname');
+ if (loaded) {
+ ok('on a quick-tunnel hostname the page says, before the passcode is typed, that Cloudflare can read the traffic',
+ await evaluate(`!document.getElementById('via-tunnel').hidden && /Cloudflare/.test(document.getElementById('via-tunnel').textContent) && /your passcode/.test(document.getElementById('via-tunnel').textContent)`),
+ await evaluate(`document.getElementById('view-claim').innerText`));
+ }
+ ok('the page never claims that no third party is involved',
+ await evaluate(`!/third party|talks to their machine/i.test(document.getElementById('app').textContent)`));
+ await cdp('Page.navigate', { url: `${URL_BASE}/_xerj-console/share` });
+ await waitFor(visible('view-room'), 'back in the room on the node\'s own address');
+
+ // ── 11. sign out ────────────────────────────────────────────────────────
+ await evaluate(`document.getElementById('signout').click()`);
+ await waitFor(visible('view-ended'), 'the signed-out view');
+ ok('sign-out empties sessionStorage', await evaluate(`sessionStorage.getItem('xerj.share') === null && sessionStorage.length === 0`));
+ ok('sign-out empties the page', await evaluate(`document.getElementById('results').children.length === 0 && document.getElementById('doc-body').children.length === 0 && document.getElementById('view-room').hidden`));
+ await cdp('Page.reload');
+ await waitFor(`${visible('view-ended')} || ${visible('view-claim')}`, 'the page after a reload');
+ ok('a reload after sign-out does not bring the room back', await evaluate(`document.getElementById('view-room').hidden && sessionStorage.length === 0`));
+ } finally {
+ await browser.close();
+ await api('DELETE', `/_share/${share.handle}`);
+ if (otherHandle) await api('DELETE', `/_share/${otherHandle}`);
+ await api('DELETE', `/${INDEX}`);
+ await api('DELETE', `/${SEM_INDEX}`);
+ }
+ console.log(`\npassed=${passed} failed=${failed}`);
+ process.exit(failed === 0 ? 0 : 1);
+}
+
+main().catch((e) => { console.error(e); process.exit(1); });