From 88eb5256c711c5a4b573d67da2bce89cbd103ce8 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:36:55 -0500 Subject: [PATCH] fix(server): a browser paired through the relay can lift a moved thread's fence A thread that moved here stays fenced from Threadlines tools until a person here sends it a message, proven by the message's server-stamped sentFrom. A browser paired through the relay never got one: RelayHost records its "browser" pairing kind as deviceType "unknown", and messageSentFromClient returned nothing for an unknown device. Its user stayed fenced for good. sessionDeviceKind now decides a session's device kind in one place, from the session's role, subject and client record: a relay-paired browser is a computer (as sessionIsComputer already said), while a linked computer (peer), a CLI-issued or script-like sign-in (bot) and one that said nothing about itself (unknown, not relay) get no sentFrom. messageSentFromSession replaces messageSentFromClient, and sessionIsComputer reuses the same rule. --- .../orchestration/decider.threadMoves.test.ts | 40 ++++++++ apps/server/src/orchestration/http.ts | 4 +- .../src/orchestration/messageSentFrom.ts | 76 +++++++++------ apps/server/src/server.test.ts | 96 ++++++++++++++++++- apps/server/src/ws.ts | 30 ++++-- docs/design/fleet.md | 2 +- 6 files changed, 207 insertions(+), 41 deletions(-) diff --git a/apps/server/src/orchestration/decider.threadMoves.test.ts b/apps/server/src/orchestration/decider.threadMoves.test.ts index 4afea7cb4..be181a760 100644 --- a/apps/server/src/orchestration/decider.threadMoves.test.ts +++ b/apps/server/src/orchestration/decider.threadMoves.test.ts @@ -8,6 +8,7 @@ import { MessageId, ProjectId, ProviderInstanceId, + RELAY_DEVICE_SESSION_SUBJECT, SideTurnId, ThreadId, ThreadMoveBatchId, @@ -17,6 +18,7 @@ import { ThreadParticipantId, TurnId, RoomAgentRequestId, + type AuthClientMetadata, type ModelSelection, type OrchestrationCommand, type OrchestrationEvent, @@ -35,6 +37,7 @@ import { describe, expect, it } from "vite-plus/test"; import { decideOrchestrationCommand } from "./decider.ts"; import { createEmptyReadModel, projectEvent } from "./projector.ts"; import { isLinkFenced } from "./linkFence.ts"; +import { messageSentFromSession } from "./messageSentFrom.ts"; import { threadMoveGuardRefusal, threadMoveRefusals } from "./threadMoveDecisions.ts"; const now = "2026-10-22T10:00:00.000Z"; @@ -1636,6 +1639,43 @@ describe("what a moved thread is trusted with (Part 3e, security changes)", () = expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBeUndefined(); }); + it("a browser paired through the relay lifts the fence; a linked computer, a CLI token or a script can't", async () => { + const signedIn = ( + subject: string, + role: "owner" | "client" | "peer", + client: AuthClientMetadata, + ) => messageSentFromSession({ subject, role, client }, "elsewhere"); + const relayBrowser = signedIn(RELAY_DEVICE_SESSION_SUBJECT, "client", { + label: "Chrome on macOS", + deviceType: "unknown", + os: "macOS", + }); + expect(relayBrowser).toEqual({ + kind: "computer", + name: "Chrome on macOS", + os: "macOS", + place: "elsewhere", + }); + const notAPerson = [ + // A computer link through the relay: its pairing said "computer". + signedIn(RELAY_DEVICE_SESSION_SUBJECT, "peer", { deviceType: "desktop" }), + // `threadlines auth session issue`, an owner token for a script or an agent. + signedIn("cli-issued-session", "owner", { label: "deploy bot", deviceType: "bot" }), + // A paired sign-in from curl, and one that sent no user agent at all. + signedIn("one-time-token", "client", { deviceType: "bot", userAgent: "curl/8.7.1" }), + signedIn("one-time-token", "owner", { deviceType: "unknown" }), + ]; + expect(notAPerson).toEqual([undefined, undefined, undefined, undefined]); + + const fenced = await withSession(await importedEmpty(), "ready"); + for (const sentFrom of notAPerson) { + const { model } = await apply(fenced, userTurn(sentFrom ? { sentFrom } : {})); + expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBe(true); + } + const { model } = await apply(fenced, userTurn({ sentFrom: relayBrowser })); + expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBeUndefined(); + }); + it("command output sent once the agent is idle leaves the fence up", async () => { let model = await withSession(await importedEmpty(), "ready"); model = await project(model, "thread.command-run-started", { diff --git a/apps/server/src/orchestration/http.ts b/apps/server/src/orchestration/http.ts index fcf08dadc..ac044cd5d 100644 --- a/apps/server/src/orchestration/http.ts +++ b/apps/server/src/orchestration/http.ts @@ -10,7 +10,7 @@ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"; import { ServerAuth } from "../auth/Services/ServerAuth.ts"; import { normalizeDispatchCommand, toDispatchCommandError } from "./Normalizer.ts"; import { - messageSentFromClient, + messageSentFromSession, sessionDevicePlace, withMessageSentFrom, writesUserMessage, @@ -88,7 +88,7 @@ export const orchestrationDispatchRouteLayer = HttpRouter.add( const normalizedCommand = writesUserMessage(normalized) ? withMessageSentFrom( normalized, - messageSentFromClient(session.client, sessionDevicePlace(session)), + messageSentFromSession(session, sessionDevicePlace(session)), ) : normalized; // No ThreadBootstrap here: the app's first sends go over the WebSocket, and diff --git a/apps/server/src/orchestration/messageSentFrom.ts b/apps/server/src/orchestration/messageSentFrom.ts index e95c89b34..6018eca43 100644 --- a/apps/server/src/orchestration/messageSentFrom.ts +++ b/apps/server/src/orchestration/messageSentFrom.ts @@ -1,5 +1,7 @@ import { type AuthClientMetadata, + type AuthSessionRole, + type MessageDeviceKind, type MessageId, type MessageSentFrom, type OrchestrationCommand, @@ -41,27 +43,56 @@ export function sessionDevicePlace( return "elsewhere"; } +/** A signed-in session, as far as the device it was issued to goes. */ +export interface DeviceSession { + readonly subject: string; + readonly role: AuthSessionRole; + readonly client: AuthClientMetadata; +} + +/** + * The kind of device a session was issued to, as MessageSentFrom.kind says + * it: a person's computer, phone or tablet. Undefined for a session that is + * no person's device the server can name: a linked computer's server + * (`peer`), a token the CLI issued or a sign-in that looked like a script + * (`bot`), and one that said nothing about itself (`unknown`). A browser + * paired through the relay is the one `unknown` that is a computer: its own + * pairing request called it a browser rather than a phone or a tablet, which + * RelayHost records as an unknown device type, and only a relay pairing the + * user approved gets that subject. + */ +export function sessionDeviceKind(session: DeviceSession): MessageDeviceKind | undefined { + if (session.role === "peer") return undefined; + switch (session.client.deviceType) { + case "desktop": + return "computer"; + case "mobile": + return "phone"; + case "tablet": + return "tablet"; + case "unknown": + return session.subject === RELAY_DEVICE_SESSION_SUBJECT ? "computer" : undefined; + case "bot": + return undefined; + } +} + /** - * The device a client session was issued to, as a user message records it - * (see MessageSentFrom): by the name its user gave it, else what it called - * itself, and where it is (sessionDevicePlace). Undefined for a device of - * unknown kind. + * The device a session was issued to, as a user message records it (see + * MessageSentFrom): its kind (sessionDeviceKind), the name its user gave it, + * else what it called itself, and where it is (sessionDevicePlace). Undefined + * for a session that is no person's device: its messages can't lift a moved + * thread's fence (turnLiftsMoveFence). */ -export function messageSentFromClient( - client: AuthClientMetadata, +export function messageSentFromSession( + session: DeviceSession, place: MessageSentFrom["place"], ): MessageSentFrom | undefined { - const kind = - client.deviceType === "desktop" - ? "computer" - : client.deviceType === "mobile" - ? "phone" - : client.deviceType === "tablet" - ? "tablet" - : undefined; + const kind = sessionDeviceKind(session); if (kind === undefined) { return undefined; } + const { client } = session; const name = client.name ?? client.label; return { kind, @@ -73,20 +104,9 @@ export function messageSentFromClient( }; } -/** - * Whether a session's device is a computer, for anything that asks if the user - * is at one. Beyond what messageSentFromClient says, a browser paired through - * the relay counts: its own pairing request called it a browser rather than a - * phone or a tablet, which RelayHost records as an unknown device type. - */ -export function sessionIsComputer(session: { - readonly subject: string; - readonly client: AuthClientMetadata; -}): boolean { - if (session.client.deviceType === "desktop") return true; - return ( - session.client.deviceType === "unknown" && session.subject === RELAY_DEVICE_SESSION_SUBJECT - ); +/** Whether a session's device is a computer, for anything that asks if the user is at one. */ +export function sessionIsComputer(session: DeviceSession): boolean { + return sessionDeviceKind(session) === "computer"; } /** diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 4ea1e3c73..c45bdb5bc 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -37,6 +37,7 @@ import { EMPTY_CHILD_REQUEST_STATE, RelayHostId, RelayInviteId, + RELAY_DEVICE_SESSION_SUBJECT, } from "@threadlines/contracts"; import { assert, it } from "@effect/vitest"; import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils"; @@ -44,6 +45,7 @@ import * as Deferred from "effect/Deferred"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; @@ -192,6 +194,7 @@ import * as PullRequestObservations from "./pullRequest/PullRequestObservations. import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts"; import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts"; import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts"; +import { SessionCredentialService } from "./auth/Services/SessionCredentialService.ts"; import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts"; import * as StallMonitor from "./observability/StallMonitor.ts"; @@ -1165,8 +1168,10 @@ const buildAppUnderTest = (options?: { Layer.provide(layerConfig), ); - yield* Layer.build(appLayer); - return config; + const app = yield* Layer.build(appLayer); + // The app's own sign-ins, for a case that needs one no HTTP route makes + // (a relay device's). + return { ...config, sessions: Context.get(app, SessionCredentialService) }; }); const parseSessionCookieFromWsUrl = ( @@ -5676,6 +5681,93 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); + it.effect( + "stamps a browser paired through the relay as a computer, and no sign-in a script made", + () => + Effect.gen(function* () { + const dispatchedCommands: Array = []; + const { sessions } = yield* buildAppUnderTest({ + config: { host: "0.0.0.0" }, + layers: { + orchestrationEngine: { + dispatch: (command) => + Effect.sync(() => { + dispatchedCommands.push(command); + return { sequence: dispatchedCommands.length }; + }), + readEvents: () => Stream.empty, + }, + }, + }); + const baseUrl = yield* getWsServerUrl("/ws", { authenticated: false }); + const withToken = (client: Parameters[0]) => + sessions.issue(client).pipe( + Effect.flatMap((issued) => sessions.issueWebSocketToken(issued.sessionId)), + Effect.map(({ token }) => `${baseUrl}?wsToken=${encodeURIComponent(token)}`), + ); + // As RelayHost signs in a browser whose pairing the user approved. + const relayBrowserUrl = yield* withToken({ + subject: RELAY_DEVICE_SESSION_SUBJECT, + method: "bearer-session-token", + role: "client", + client: { label: "Chrome on macOS", deviceType: "unknown", os: "macOS" }, + }); + // As `threadlines auth session issue` makes a token for a script or an agent. + const cliTokenUrl = yield* withToken({ + subject: "cli-issued-session", + method: "bearer-session-token", + role: "owner", + client: { label: "deploy", deviceType: "bot" }, + }); + // A pairing link spent from curl. + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { cookie: ownerCookie, "content-type": "application/json" }, + body: HttpBody.text("{}", "application/json"), + }); + const pairing = (yield* pairingResponse.json) as { readonly credential: string }; + const curlBootstrap = yield* bootstrapBrowserSession(pairing.credential, { + headers: { "user-agent": "curl/8.7.1" }, + }); + const curlUrl = appendSessionCookieToWsUrl( + baseUrl, + curlBootstrap.cookie?.split(";")[0] ?? "", + ); + + for (const [index, url] of [relayBrowserUrl, cliTokenUrl, curlUrl].entries()) { + yield* Effect.scoped( + withWsRpcClient(url, (client) => + client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ + type: "thread.turn.start", + commandId: CommandId.make(`cmd-signed-in-${index}`), + threadId: ThreadId.make("thread-signed-in"), + message: { + messageId: MessageId.make(`message-signed-in-${index}`), + role: "user", + text: "Carry on", + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: "default", + createdAt: "2026-01-01T00:00:00.000Z", + }), + ), + ); + } + + assert.deepEqual( + dispatchedCommands.map((command) => + "sentFrom" in command ? command.sentFrom : undefined, + ), + [ + { kind: "computer", name: "Chrome on macOS", os: "macOS", place: "elsewhere" }, + undefined, + undefined, + ], + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + it.effect("stamps a phone's messages with the name it was just given, without reconnecting", () => Effect.gen(function* () { const dispatchedCommands: Array = []; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 4f8e2ab23..75887fd24 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -90,7 +90,8 @@ import { Keybindings } from "./keybindings.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; import { normalizeDispatchCommand, toDispatchCommandError } from "./orchestration/Normalizer.ts"; import { - messageSentFromClient, + type DeviceSession, + messageSentFromSession, sessionIsComputer, sessionDevicePlace, withMessageSentFrom, @@ -423,22 +424,29 @@ function toAuthAccessStreamEvent( */ const followDeviceName = ( sessions: SessionCredentialServiceShape, - sessionId: AuthSessionId, + session: DeviceSession & { readonly sessionId: AuthSessionId }, sentFromRef: Ref.Ref, /** Where the device is (sessionDevicePlace): fixed for the session. */ place: MessageSentFrom["place"], ) => Effect.scoped( Effect.gen(function* () { + const { sessionId } = session; const changes = yield* sessions.subscribeChanges; const current = yield* sessions.clientOf(sessionId); if (Option.isSome(current)) { - yield* Ref.set(sentFromRef, messageSentFromClient(current.value, place)); + yield* Ref.set( + sentFromRef, + messageSentFromSession({ ...session, client: current.value }, place), + ); } yield* changes.pipe( Stream.runForEach((change) => change.type === "clientUpserted" && change.clientSession.sessionId === sessionId - ? Ref.set(sentFromRef, messageSentFromClient(change.clientSession.client, place)) + ? Ref.set( + sentFromRef, + messageSentFromSession({ ...session, client: change.clientSession.client }, place), + ) : Effect.void, ), ); @@ -447,7 +455,10 @@ const followDeviceName = ( Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) - : Effect.logWarning("ws.device-name.follow-failed", { sessionId, cause }), + : Effect.logWarning("ws.device-name.follow-failed", { + sessionId: session.sessionId, + cause, + }), ), Effect.andThen(Effect.never), ); @@ -915,7 +926,10 @@ const makeCoreRpcLayer = ( const currentSentFrom = sessions.clientOf(currentSessionId).pipe( Effect.flatMap((client) => Option.isSome(client) - ? Ref.setAndGet(sentFromRef, messageSentFromClient(client.value, devicePlace)) + ? Ref.setAndGet( + sentFromRef, + messageSentFromSession({ ...currentSession, client: client.value }, devicePlace), + ) : Ref.get(sentFromRef), ), Effect.catch(() => Ref.get(sentFromRef)), @@ -3618,7 +3632,7 @@ export const websocketRpcRouteLayer = Layer.unwrap( const session = yield* serverAuth.authenticateWebSocketUpgrade(request); const viewerId = randomUUIDv4Sync(); const devicePlace = sessionDevicePlace(session); - const sentFromRef = yield* Ref.make(messageSentFromClient(session.client, devicePlace)); + const sentFromRef = yield* Ref.make(messageSentFromSession(session, devicePlace)); const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, { disableTracing: true, }).pipe( @@ -3694,7 +3708,7 @@ export const websocketRpcRouteLayer = Layer.unwrap( rpcWebSocketHttpEffect, Effect.raceFirst( closeWhenRevoked, - followDeviceName(sessions, session.sessionId, sentFromRef, devicePlace), + followDeviceName(sessions, session, sentFromRef, devicePlace), ), ), () => diff --git a/docs/design/fleet.md b/docs/design/fleet.md index 3b2c7440b..2283a22ee 100644 --- a/docs/design/fleet.md +++ b/docs/design/fleet.md @@ -1289,7 +1289,7 @@ These win over everything above in Part 3e. What a move carries came from anothe - continuing it on a schedule. - Work still picks up on arrival as the link's permission allows, fenced. Its mode stays capped by the link's access ceiling, as before. - **The fence lifts** when a message a person sent from the app starts a turn in the thread, directly or from the queue ("send when done"): `liftsMoveFence` on that `thread.turn-start-requested`, which clears `fenced` in every projection. A restart keeps whatever the projection holds. The rule is an allow-list (`turnLiftsMoveFence` in `linkFence.ts`): the message must carry `sentFrom`, which only this server stamps from the connection's sign-in, so nothing Threadlines writes can lift it by forgetting a marker. - - **What doesn't lift it:** the arrival message (`afterMove`), queued messages the move carried (`imported` on the queued entry; the other computer's `sentFrom` on them is dropped at import), and anything Threadlines or an agent sends: command output, another thread, an outside assistant, a scheduled task, a restart or usage-limit resume, a retry, pull request auto-fix. A device the server can't name (no `sentFrom`) can't lift it either. + - **What doesn't lift it:** the arrival message (`afterMove`), queued messages the move carried (`imported` on the queued entry; the other computer's `sentFrom` on them is dropped at import), and anything Threadlines or an agent sends: command output, another thread, an outside assistant, a scheduled task, a restart or usage-limit resume, a retry, pull request auto-fix. A session that is no person's device gets no `sentFrom` and can't lift it either: a linked computer (`peer`), a CLI-issued token or a sign-in that looked like a script (`bot`), or one that said nothing about itself. A browser paired through the relay counts as a computer (`sessionDeviceKind` in `messageSentFrom.ts`). - A session started fenced is restarted with resume at the next start after the lift, so the agent gets its tools. - The "Moved here" line says it: "Its agent can't use other threads, rooms or schedules here until you send it a message."