diff --git a/src/app/panel/page.tsx b/src/app/panel/page.tsx
index 9e4dae8..ebde6df 100644
--- a/src/app/panel/page.tsx
+++ b/src/app/panel/page.tsx
@@ -441,6 +441,11 @@ function ConnectBar({ daemon }: { daemon: UseDaemonResult }) {
const [urlInput, setUrlInput] = useState("")
const [tokenInput, setTokenInput] = useState("")
const [copied, setCopied] = useState(false)
+ const [shareOpen, setShareOpen] = useState(false)
+ // Opt-in — a copied link with the token embedded grants full access to
+ // whoever opens it (agentproto/ts#1398: a remote daemon in bearer mode
+ // requires this exact token on every route), so it defaults off.
+ const [includeToken, setIncludeToken] = useState(false)
const submit = () => {
if (!urlInput.trim()) return
@@ -450,12 +455,18 @@ function ConnectBar({ daemon }: { daemon: UseDaemonResult }) {
setTokenInput("")
}
- // Shareable deep-link: the tunnel wss origin, no token (auth rides the
- // trusted panel Origin). Opening it on another machine auto-connects.
+ // Shareable deep-link: the fragment form (`#daemon=&token=`) — fragments
+ // never reach a server (no Referer, no access/proxy log, no CDN cache
+ // key), unlike the legacy `?daemon=&token=` query-string form this panel
+ // still accepts for back-compat. The token is only embedded when
+ // `includeToken` is explicitly checked; without it, whoever opens the
+ // link still needs to paste the token in themselves via "connect ▾".
const shareLink = (): string => {
if (typeof window === "undefined" || !daemon.url) return ""
const wss = daemon.url.replace(/^http/, "ws")
- return `${window.location.origin}/panel?daemon=${encodeURIComponent(wss)}`
+ const params = new URLSearchParams({ daemon: wss })
+ if (includeToken && daemon.token) params.set("token", daemon.token)
+ return `${window.location.origin}/panel#${params.toString()}`
}
const copyLink = async () => {
@@ -464,6 +475,7 @@ function ConnectBar({ daemon }: { daemon: UseDaemonResult }) {
try {
await navigator.clipboard.writeText(link)
setCopied(true)
+ setShareOpen(false)
setTimeout(() => setCopied(false), 1500)
} catch {
/* clipboard blocked — ignore */
@@ -535,9 +547,67 @@ function ConnectBar({ daemon }: { daemon: UseDaemonResult }) {
)}
{daemon.remote && (
-
- {copied ? "copied ✓" : "copy link"}
-
+
+
setShareOpen(o => !o)}
+ title="Copy a shareable link to this daemon"
+ >
+ {copied ? "copied ✓" : shareOpen ? "close" : "copy link ▾"}
+
+ {shareOpen && (
+
+
+ setIncludeToken(e.target.checked)}
+ />
+ include access token
+
+
+ {daemon.token
+ ? includeToken
+ ? "Anyone with this link gets full access to this daemon — share it only with someone you trust."
+ : "Without the token, whoever opens this link must paste it in themselves via “connect”."
+ : "This connection has no token to embed."}
+
+
void copyLink()}
+ >
+ copy
+
+
+ )}
+
)}
{daemon.remote && (
@@ -863,6 +933,7 @@ export default function PanelPage() {
daemonUrl={daemon.url!}
sessionId={selected.id}
sessionStatus={selected.status}
+ token={daemon.token}
/>
) : (
)
@@ -880,6 +952,7 @@ export default function PanelPage() {
daemonUrl={daemon.url!}
sessionId={selected.id}
sessionStatus={selected.status}
+ token={daemon.token}
/>
)}
{tab === "tty" && (
diff --git a/src/components/SessionChatView.tsx b/src/components/SessionChatView.tsx
index c5816d6..a38dd73 100644
--- a/src/components/SessionChatView.tsx
+++ b/src/components/SessionChatView.tsx
@@ -2,6 +2,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { toDisplayText } from "@/components/ToolBlocks"
+import { daemonFetch } from "@/lib/use-daemon"
import ReactMarkdown from "react-markdown"
import remarkGfm from "remark-gfm"
@@ -727,10 +728,12 @@ function PromptInput({
daemonUrl,
sessionId,
disabled,
+ token,
}: {
daemonUrl: string
sessionId: string
disabled: boolean
+ token?: string | null
}) {
const [value, setValue] = useState("")
const [sending, setSending] = useState(false)
@@ -742,10 +745,8 @@ function PromptInput({
setSending(true)
setErr(null)
try {
- const res = await fetch(`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/prompt`, {
+ const res = await daemonFetch(`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/prompt`, token, {
method: "POST",
- mode: "cors",
- credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt: trimmed }),
})
@@ -759,7 +760,7 @@ function PromptInput({
} finally {
setSending(false)
}
- }, [value, sending, daemonUrl, sessionId])
+ }, [value, sending, daemonUrl, sessionId, token])
const onKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter" && !e.shiftKey) {
@@ -836,9 +837,11 @@ interface Props {
daemonUrl: string
sessionId: string
sessionStatus: string
+ /** Bearer token for a remote/tunnel daemon connection; omitted for local. */
+ token?: string | null
}
-export function SessionChatView({ daemonUrl, sessionId, sessionStatus }: Props) {
+export function SessionChatView({ daemonUrl, sessionId, sessionStatus, token }: Props) {
const [transcript, setTranscript] = useState(null)
const [rawExport, setRawExport] = useState(null)
const [noTranscript, setNoTranscript] = useState(false)
@@ -858,15 +861,15 @@ export function SessionChatView({ daemonUrl, sessionId, sessionStatus }: Props)
const fetchTranscript = useCallback(async () => {
try {
- let res = await fetch(
+ let res = await daemonFetch(
`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/export?format=json`,
- { mode: "cors", credentials: "include" }
+ token,
)
if (!res.ok && (res.status === 404 || res.status === 422)) {
// Retry with source=daemon
- res = await fetch(
+ res = await daemonFetch(
`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/export?format=json&source=daemon`,
- { mode: "cors", credentials: "include" }
+ token,
)
}
if (!res.ok) {
@@ -891,7 +894,7 @@ export function SessionChatView({ daemonUrl, sessionId, sessionStatus }: Props)
setFetchErr(e instanceof Error ? e.message : String(e))
}
}
- }, [daemonUrl, sessionId])
+ }, [daemonUrl, sessionId, token])
// Scroll to bottom when new messages arrive
useEffect(() => {
@@ -995,6 +998,7 @@ export function SessionChatView({ daemonUrl, sessionId, sessionStatus }: Props)
daemonUrl={daemonUrl}
sessionId={sessionId}
disabled={!isRunning}
+ token={token}
/>
)}
@@ -1212,9 +1216,11 @@ interface JsonViewProps {
daemonUrl: string
sessionId: string
sessionStatus: string
+ /** Bearer token for a remote/tunnel daemon connection; omitted for local. */
+ token?: string | null
}
-export function SessionJsonView({ daemonUrl, sessionId, sessionStatus }: JsonViewProps) {
+export function SessionJsonView({ daemonUrl, sessionId, sessionStatus, token }: JsonViewProps) {
const [data, setData] = useState(null)
const [noTranscript, setNoTranscript] = useState(false)
const [fetchErr, setFetchErr] = useState(null)
@@ -1223,14 +1229,14 @@ export function SessionJsonView({ daemonUrl, sessionId, sessionStatus }: JsonVie
const fetchData = useCallback(async () => {
try {
- let res = await fetch(
+ let res = await daemonFetch(
`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/export?format=json`,
- { mode: "cors", credentials: "include" }
+ token,
)
if (!res.ok && (res.status === 404 || res.status === 422)) {
- res = await fetch(
+ res = await daemonFetch(
`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/export?format=json&source=daemon`,
- { mode: "cors", credentials: "include" }
+ token,
)
}
if (!res.ok) {
@@ -1247,7 +1253,7 @@ export function SessionJsonView({ daemonUrl, sessionId, sessionStatus }: JsonVie
} catch (e) {
setFetchErr(e instanceof Error ? e.message : String(e))
}
- }, [daemonUrl, sessionId])
+ }, [daemonUrl, sessionId, token])
useEffect(() => {
setData(null)
diff --git a/src/components/SessionEventsView.tsx b/src/components/SessionEventsView.tsx
index 58a199c..c4179ab 100644
--- a/src/components/SessionEventsView.tsx
+++ b/src/components/SessionEventsView.tsx
@@ -12,6 +12,7 @@ import {
type ToolResultEvent,
type UsageCost,
} from "@/lib/use-session-events"
+import { daemonFetch } from "@/lib/use-daemon"
import { PlanList, ToolPairBlock, toDisplayText } from "@/components/ToolBlocks"
// ---------------------------------------------------------------------------
@@ -601,7 +602,17 @@ function RenderItemView({ item, groupExpanded, onGroupToggle }: RenderItemViewPr
// PromptInput (same as SessionChatView, duplicated to keep file self-contained)
// ---------------------------------------------------------------------------
-function PromptInput({ daemonUrl, sessionId, disabled }: { daemonUrl: string; sessionId: string; disabled: boolean }) {
+function PromptInput({
+ daemonUrl,
+ sessionId,
+ disabled,
+ token,
+}: {
+ daemonUrl: string
+ sessionId: string
+ disabled: boolean
+ token?: string | null
+}) {
const [value, setValue] = useState("")
const [sending, setSending] = useState(false)
const [err, setErr] = useState(null)
@@ -612,8 +623,8 @@ function PromptInput({ daemonUrl, sessionId, disabled }: { daemonUrl: string; se
setSending(true)
setErr(null)
try {
- const res = await fetch(`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/prompt`, {
- method: "POST", mode: "cors", credentials: "include",
+ const res = await daemonFetch(`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/prompt`, token, {
+ method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt: trimmed }),
})
@@ -627,7 +638,7 @@ function PromptInput({ daemonUrl, sessionId, disabled }: { daemonUrl: string; se
} finally {
setSending(false)
}
- }, [value, sending, daemonUrl, sessionId])
+ }, [value, sending, daemonUrl, sessionId, token])
const onKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); void send() }
@@ -688,12 +699,14 @@ interface Props {
daemonUrl: string
sessionId: string
sessionStatus: string
+ /** Bearer token for a remote/tunnel daemon connection; omitted for local. */
+ token?: string | null
/** Called when the events endpoint 404s so the parent can fall back to export polling. */
onNotSupported: () => void
}
-export function SessionEventsView({ daemonUrl, sessionId, sessionStatus, onNotSupported }: Props) {
- const { events, notSupported, loading, error } = useSessionEvents(daemonUrl, sessionId, sessionStatus)
+export function SessionEventsView({ daemonUrl, sessionId, sessionStatus, token, onNotSupported }: Props) {
+ const { events, notSupported, loading, error } = useSessionEvents(daemonUrl, sessionId, sessionStatus, token)
const scrollRef = useRef(null)
const isRunning = sessionStatus === "running"
@@ -757,7 +770,7 @@ export function SessionEventsView({ daemonUrl, sessionId, sessionStatus, onNotSu
{/* Prompt input */}
-
+
)
}
diff --git a/src/components/SessionTerminal.tsx b/src/components/SessionTerminal.tsx
index bcd49ca..39d198b 100644
--- a/src/components/SessionTerminal.tsx
+++ b/src/components/SessionTerminal.tsx
@@ -13,6 +13,7 @@ import type { Terminal as XTerminal } from "@xterm/xterm"
import type { FitAddon as FitAddonType } from "@xterm/addon-fit"
import "@xterm/xterm/css/xterm.css"
import { cn } from "@/lib/utils"
+import { withToken } from "@/lib/use-daemon"
interface Props {
daemonUrl: string
@@ -146,9 +147,8 @@ function attachPty({
const cols = term.cols || 80
const rows = term.rows || 24
const qs = new URLSearchParams({ cols: String(cols), rows: String(rows) })
- if (token) qs.set("token", token)
const sock = new WebSocket(
- `${wsBase}/sessions/${encodeURIComponent(sessionId)}/pty?${qs}`
+ withToken(`${wsBase}/sessions/${encodeURIComponent(sessionId)}/pty?${qs}`, token)
)
ws = sock
@@ -233,13 +233,12 @@ function attachSse({
}): () => void {
const dim = "\x1b[2m", reset = "\x1b[0m"
term.writeln(`${dim}── attached to ${sessionId} (${daemonUrl}) ──${reset}`)
- // The SSE stream is read-only and ungated, so a token isn't required — but
- // an EventSource can't set an Authorization header, so we thread it via the
- // query string (same `?token=` the WS path uses) to stay correct if a daemon
- // ever gates the stream.
- const streamQs = token ? `?token=${encodeURIComponent(token)}` : ""
+ // A remote daemon in bearer mode (agentproto/ts#1398) 401s this stream for
+ // any non-loopback request without the bearer — and an EventSource can't
+ // set an Authorization header, so it rides the query string instead (same
+ // `?token=` the WS path uses).
const src = new EventSource(
- `${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/stream${streamQs}`,
+ withToken(`${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/stream`, token),
{ withCredentials: true }
)
src.onmessage = ev => {
diff --git a/src/lib/use-daemon.ts b/src/lib/use-daemon.ts
index 817277f..fb33ccc 100644
--- a/src/lib/use-daemon.ts
+++ b/src/lib/use-daemon.ts
@@ -66,8 +66,11 @@ export interface UseDaemonResult {
/** True when connected to an explicit (remote/tunnel) daemon rather than a
* locally auto-probed one. */
remote: boolean
- /** Bearer token for the current connection, if any. Threaded into the PTY
- * WebSocket + mutating POSTs; read-only GETs/SSE ride CORS ungated. */
+ /** Bearer token for the current connection, if any. Threaded through
+ * `daemonFetch` on every fetch (as `Authorization: Bearer`) and via
+ * `withToken` on the PTY WebSocket + SSE stream (`?token=`) — a remote
+ * daemon in bearer mode (agentproto/ts#1398) requires it on every
+ * non-loopback route, not just mutating ones. */
token: string | null
probing: boolean
health: DaemonHealth | null
@@ -107,6 +110,41 @@ export function normalizeDaemonBase(input: string): string | null {
}
}
+/**
+ * Every daemon-facing `fetch` goes through this — after agentproto/ts#1398,
+ * a remote daemon in bearer mode 401s any non-loopback request that doesn't
+ * carry the real bearer; `Origin` (CORS) is no longer a substitute. `token`
+ * is threaded as `Authorization: Bearer `; omit it (null/undefined)
+ * for a local/loopback connection or one with no token, and the request
+ * goes out exactly as before.
+ */
+export function daemonFetch(
+ url: string,
+ token: string | null | undefined,
+ init: RequestInit = {},
+): Promise {
+ const headers = new Headers(init.headers)
+ if (token) headers.set("authorization", `Bearer ${token}`)
+ return fetch(url, {
+ mode: "cors",
+ credentials: "include",
+ ...init,
+ headers,
+ })
+}
+
+/**
+ * Append `?token=` (or `&token=` if `url` already has a query
+ * string) for the two transports that can't set a request header: an
+ * `EventSource` (SSE) and a `WebSocket` upgrade. No-ops when `token` is
+ * falsy. Mirrors the daemon's own `?token=` convenience
+ * (`checkSessionsToken` / the P0 tunnel-bearer gate, `packages/runtime/src/http-server.ts`).
+ */
+export function withToken(url: string, token: string | null | undefined): string {
+ if (!token) return url
+ return `${url}${url.includes("?") ? "&" : "?"}token=${encodeURIComponent(token)}`
+}
+
function readStoredConnection(): DaemonConnection | null {
if (typeof window === "undefined") return null
try {
@@ -126,10 +164,12 @@ function readStoredConnection(): DaemonConnection | null {
}
/**
- * Read a `?daemon=&token=` deep-link once on mount. The token is
- * stripped from the address bar immediately (history.replaceState) so it isn't
- * left in a shareable URL / browser history — the connection is held in state
- * + localStorage instead.
+ * Read a `?daemon=&token=` deep-link once on mount. Kept for
+ * back-compat — `readFragmentConnection` below is preferred (the fragment
+ * form never reaches a server, so it can't leak into access/proxy logs the
+ * way a query string can). The token is stripped from the address bar
+ * immediately (history.replaceState) so it isn't left in a shareable URL /
+ * browser history — the connection is held in state + localStorage instead.
*/
function readLinkConnection(): DaemonConnection | null {
if (typeof window === "undefined") return null
@@ -154,6 +194,33 @@ function readLinkConnection(): DaemonConnection | null {
return { url: base, ...(token ? { token } : {}) }
}
+/**
+ * Read a `#daemon=&token=` deep-link once on mount — the
+ * fragment form `remote_enable`'s `phoneUrl` uses (agentproto/ts, P1.2).
+ * Fragments are never sent to a server (no Referer, no server/proxy access
+ * log, no CDN cache key), which a `?token=` query string is exposed to — so
+ * this is the preferred link shape; `readLinkConnection`'s `?daemon=&token=`
+ * stays only for back-compat. Scrubbed from the address bar immediately via
+ * `history.replaceState`, same as the query-string form.
+ */
+function readFragmentConnection(): DaemonConnection | null {
+ if (typeof window === "undefined") return null
+ const raw = window.location.hash.replace(/^#/, "")
+ if (!raw) return null
+ const params = new URLSearchParams(raw)
+ const daemon = params.get("daemon")
+ if (!daemon) return null
+ const base = normalizeDaemonBase(daemon)
+ if (!base) return null
+ const token = params.get("token") ?? undefined
+ try {
+ window.history.replaceState(null, "", window.location.pathname + window.location.search)
+ } catch {
+ /* ignore */
+ }
+ return { url: base, ...(token ? { token } : {}) }
+}
+
export function useDaemon(port = DEFAULT_PORT): UseDaemonResult {
const [url, setUrl] = useState(null)
const [remote, setRemote] = useState(false)
@@ -171,15 +238,11 @@ export function useDaemon(port = DEFAULT_PORT): UseDaemonResult {
const tokenRef = useRef(null)
tokenRef.current = token
- const authHeaders = useCallback((): Record => {
- const t = tokenRef.current
- return t ? { authorization: `Bearer ${t}` } : {}
- }, [])
-
- // Resolve the initial connection once: deep-link wins over stored, both win
- // over localhost auto-probe.
+ // Resolve the initial connection once: the fragment deep-link (preferred —
+ // never reaches a server) wins over the legacy query-string deep-link,
+ // both win over stored, all three win over localhost auto-probe.
useEffect(() => {
- setConnection(readLinkConnection() ?? readStoredConnection() ?? null)
+ setConnection(readFragmentConnection() ?? readLinkConnection() ?? readStoredConnection() ?? null)
}, [])
const connect = useCallback((input: { url: string; token?: string }) => {
@@ -223,12 +286,7 @@ export function useDaemon(port = DEFAULT_PORT): UseDaemonResult {
try {
const ctrl = new AbortController()
const t = setTimeout(() => ctrl.abort(), PROBE_TIMEOUT_MS)
- const res = await fetch(`${base}/health`, {
- mode: "cors",
- credentials: "include",
- headers: tok ? { authorization: `Bearer ${tok}` } : {},
- signal: ctrl.signal,
- })
+ const res = await daemonFetch(`${base}/health`, tok, { signal: ctrl.signal })
clearTimeout(t)
if (!res.ok) return null
return (await res.json()) as DaemonHealth
@@ -305,11 +363,7 @@ export function useDaemon(port = DEFAULT_PORT): UseDaemonResult {
const target = urlRef.current
if (!target) return
try {
- const res = await fetch(`${target}/sessions`, {
- mode: "cors",
- credentials: "include",
- headers: authHeaders(),
- })
+ const res = await daemonFetch(`${target}/sessions`, tokenRef.current)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const body = (await res.json()) as { sessions?: DaemonSession[] }
setSessions(Array.isArray(body.sessions) ? body.sessions : [])
@@ -317,18 +371,15 @@ export function useDaemon(port = DEFAULT_PORT): UseDaemonResult {
} catch (err) {
setError(err instanceof Error ? err.message : String(err))
}
- }, [authHeaders])
+ }, [])
const killSession = useCallback(
async (id: string): Promise => {
const target = urlRef.current
if (!target) return false
try {
- const res = await fetch(`${target}/sessions/${id}/kill`, {
+ const res = await daemonFetch(`${target}/sessions/${id}/kill`, tokenRef.current, {
method: "POST",
- mode: "cors",
- credentials: "include",
- headers: authHeaders(),
})
const body = (await res.json().catch(() => ({}))) as { ok?: boolean }
if (body.ok) await refresh()
@@ -337,7 +388,7 @@ export function useDaemon(port = DEFAULT_PORT): UseDaemonResult {
return false
}
},
- [refresh, authHeaders]
+ [refresh]
)
useEffect(() => {
@@ -362,11 +413,9 @@ export function useDaemon(port = DEFAULT_PORT): UseDaemonResult {
const target = urlRef.current
if (!target) return { ok: false, error: "daemon not connected" }
try {
- const res = await fetch(`${target}/sessions/terminal`, {
+ const res = await daemonFetch(`${target}/sessions/terminal`, tokenRef.current, {
method: "POST",
- mode: "cors",
- credentials: "include",
- headers: { "Content-Type": "application/json", ...authHeaders() },
+ headers: { "Content-Type": "application/json" },
body: JSON.stringify(params),
})
if (res.status === 201) {
@@ -380,7 +429,7 @@ export function useDaemon(port = DEFAULT_PORT): UseDaemonResult {
return { ok: false, error: e instanceof Error ? e.message : String(e) }
}
},
- [refresh, authHeaders]
+ [refresh]
)
return {
diff --git a/src/lib/use-session-events.ts b/src/lib/use-session-events.ts
index 5c9016d..17d1700 100644
--- a/src/lib/use-session-events.ts
+++ b/src/lib/use-session-events.ts
@@ -1,6 +1,7 @@
"use client"
import { useCallback, useEffect, useRef, useState } from "react"
+import { daemonFetch } from "@/lib/use-daemon"
// ---------------------------------------------------------------------------
// Event type definitions
@@ -116,6 +117,7 @@ export function useSessionEvents(
daemonUrl: string,
sessionId: string,
sessionStatus: string,
+ token?: string | null,
): UseSessionEventsResult {
const [events, setEvents] = useState([])
const [notSupported, setNotSupported] = useState(false)
@@ -141,7 +143,7 @@ export function useSessionEvents(
if (notSupportedRef.current) return false
const url = `${daemonUrl}/sessions/${encodeURIComponent(sessionId)}/events?since=${nextSeqRef.current}`
try {
- const res = await fetch(url, { mode: "cors", credentials: "include" })
+ const res = await daemonFetch(url, token)
if (res.status === 404) {
// Endpoint doesn't exist on this daemon version — permanent fallback.
notSupportedRef.current = true
@@ -171,7 +173,7 @@ export function useSessionEvents(
setLoading(false)
return false
}
- }, [daemonUrl, sessionId])
+ }, [daemonUrl, sessionId, token])
useEffect(() => {
let cancelled = false