A local-first multi-agent app development platform, built on PenguinHarness
fix(server,web): a revoked session lands on the sign-in page at once (#819)
Yaowei Zhengbb9f744c5cd7
diff --git a/changelog/unreleased/2026-09-21-revoked-session-lands-on-login.md b/changelog/unreleased/2026-09-21-revoked-session-lands-on-login.mdnew file mode 100644index 00000000..92884e4d--- /dev/null+++ b/changelog/unreleased/2026-09-21-revoked-session-lands-on-login.md@@ -0,0 +1,19 @@+# A window whose session was revoked lands on the sign-in page by itself++- **Date:** 2026-09-21+- **Type:** fix+- **Scope:** `server`, `web`, `docs`+- **PR:** [#819](https://github.com/Prism-Shadow/penguin-harness/pull/819)++[中文版](2026-09-21-revoked-session-lands-on-login.zh.md)++Resetting a user's password dropped every session row they held, as the Admin page promises — but a window that already had the app open stayed on it. An SSE stream was authorised once, when it connected, and nothing ever checked it again; the Web App kept a single user stream for the whole login session and reported nothing when it died. The window went on streaming until its reader happened to make a request. The server now ends a revoked user's open streams, and a window that loses its stream — or simply comes back to the foreground — asks whether it is still signed in.++## Details++- The server tracks every open SSE stream by the user it was authenticated as (`LiveStreamRegistry`, registered and released by the stream itself). `AdminService` ends that user's streams in the same step as it drops their session rows, on both password reset and account deletion.+- Each stream re-checks its own session on its 20s heartbeat and ends when the row is gone or has expired — the catch-all for session rows dropped without going through the registry. The check reads the row by its token hash and never renews it, so a window left connected cannot keep itself signed in by doing nothing.+- A stream authenticated by the boot's local API token (the CLI, an Agent's own tools) carries no session row and is left alone.+- The Web App's app-wide user stream probes `GET /api/me` when the browser closes the connection for good, the way the chat page's Session stream already did; both now call one helper, and a 401 goes through the api client's global handler that clears the user and routes to the sign-in page.+- The same probe runs when a window regains focus or becomes visible, so a tab left open overnight does not linger on a dead page, and the terminal list's poll hands a 401 to it instead of quietly keeping its last known list. Concurrent probes share one request.+- The server API reference's SSE delivery guarantees record the heartbeat's session re-check and what ends a stream.diff --git a/changelog/unreleased/2026-09-21-revoked-session-lands-on-login.zh.md b/changelog/unreleased/2026-09-21-revoked-session-lands-on-login.zh.mdnew file mode 100644index 00000000..16d41845--- /dev/null+++ b/changelog/unreleased/2026-09-21-revoked-session-lands-on-login.zh.md@@ -0,0 +1,19 @@+# 会话被吊销的窗口会自己回到登录页++- **Date:** 2026-09-21+- **Type:** fix+- **Scope:** `server`, `web`, `docs`+- **PR:** [#819](https://github.com/Prism-Shadow/penguin-harness/pull/819)++[English](2026-09-21-revoked-session-lands-on-login.md)++管理员重置密码时,该用户的登录会话记录确实会被全部删除,与管理页的说明一致;但已经打开着应用的窗口仍停留在原处。SSE 流只在连接建立时鉴权一次,此后再无人复查;Web App 在整个登录期内只保持一条用户事件流,流断了也不向应用报告。于是窗口会一直推送下去,直到读者恰好发起某个请求。现在服务端会结束被吊销用户已打开的流,而失去流的窗口——或者只是重新回到前台的窗口——会主动确认自己是否还处于登录状态。++## 细节++- 服务端按连接建立时鉴权到的用户记录每一条打开中的 SSE 流(`LiveStreamRegistry`,由流自身登记与释放)。`AdminService` 在删除该用户会话记录的同一步里结束其全部流,重置密码与删除账号两条路径都是如此。+- 每条流在 20 秒心跳上复查自己的会话,记录已删除或已过期即结束连接——这是对那些未经注册表就删除会话记录的调用方的兜底。该复查按 token hash 读取记录,且绝不续期,因此一个连着不动的窗口无法靠什么都不做把自己续在登录状态里。+- 以本次启动的本地 API token 鉴权的流(CLI、Agent 自己的工具)没有对应的会话记录,不受影响。+- Web App 的应用级用户事件流在浏览器判定连接彻底断开时探测 `GET /api/me`,与聊天页的 Session 流此前的做法一致;两处现在调用同一个辅助函数,401 会走 api client 的全局处理器,清空当前用户并跳转到登录页。+- 窗口重新获得焦点或变为可见时也会做同一次探测,因此整夜开着的标签页不会滞留在失效页面上;终端列表的轮询也把 401 交给它,而不再默默沿用上一次的列表。并发的探测共用一次请求。+- 服务端 API 参考的 SSE 投递保证一节记下了心跳的会话复查,以及什么会结束一条流。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 079fbc0f..7144357e 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -1122,7 +1122,7 @@ export type ServerEvent =- Event ids increase monotonically per channel and have the form `<epoch>-<seq>`.- Each channel keeps a bounded replay buffer: the most recent 10,000 events or 8MB.- On reconnect with `Last-Event-ID`, the server replays the gap if the id is still in the buffer. Otherwise it first sends `resync_required`, and the client refetches `/messages` before continuing.-- A heartbeat comment line is written every 20 seconds.+- A heartbeat comment line is written every 20 seconds. The same beat re-checks the session behind the connection and ends the stream when that session is gone or has expired, so a client whose sign-in was revoked stops streaming instead of waiting for its next request to fail. Revoking sessions directly — an admin resetting a password or deleting an account — ends that user's open streams at once; the heartbeat is the catch-all. A stream authenticated by the local API token has no session row and is left alone.- Event order: on a reconnect that carries `Last-Event-ID`, the replayed gap (or `resync_required`) arrives first, then the initial events (the authoritative `task_state` snapshot and any still-pending `approval_request`s), then the live stream. A fresh connection without `Last-Event-ID` skips the replay, so its first event is the `task_state` snapshot.### Recommended Client Patterndiff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex d92b8d46..67b61a1d 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -1122,7 +1122,7 @@ export type ServerEvent =- 事件 id 在每个通道内单调递增,格式为 `<epoch>-<seq>`。- 每个通道保留一个有界的重放缓冲区:最近 10,000 个事件或 8MB。- 携带 `Last-Event-ID` 重连时,如果 id 仍在缓冲区内,服务器会重放缺失的事件;否则先发送 `resync_required`,客户端重新拉取 `/messages` 后再继续。-- 每 20 秒写入一行心跳注释。+- 每 20 秒写入一行心跳注释。同一次心跳会复查连接背后的会话,会话已删除或已过期时结束该流,因此登录被吊销的客户端会立即停止接收,而不必等到下一次请求失败才发现。直接吊销会话的操作——管理员重置密码或删除账号——会当场结束该用户所有打开中的流,心跳是兜底。以本地 API token 鉴权的流没有对应的会话记录,不受影响。- 事件顺序:携带 `Last-Event-ID` 重连时,先到达重放的缺失部分(或 `resync_required`),然后是初始事件(权威的 `task_state` 快照和所有仍待处理的 `approval_request`),最后是实时流。不带 `Last-Event-ID` 的新连接跳过重放,第一个事件就是 `task_state` 快照。### 推荐的客户端模式diff --git a/packages/server/src/auth/live-streams.ts b/packages/server/src/auth/live-streams.tsnew file mode 100644index 00000000..10235d67--- /dev/null+++ b/packages/server/src/auth/live-streams.ts@@ -0,0 +1,79 @@+/**+ * The live connections a user's sessions are holding open, so revoking a session can end+ * them.+ *+ * An SSE stream is authorised once, when it connects, and nothing on the request path ever+ * looks at it again — so deleting a user's `auth_sessions` rows leaves every stream they+ * opened still writing, and the window on the other end keeps rendering a conversation it+ * is no longer signed in for. This registry is the missing handle: a stream adds itself for+ * exactly as long as it is open, and whatever drops the rows ends the streams in the same+ * step (AdminService.signOutEverywhere).+ *+ * It is a best-effort index, not the source of truth. The streams themselves re-check their+ * own session on the heartbeat (http/sse.ts), which is what covers a caller that drops rows+ * without telling this registry.+ *+ * Nothing is persisted: a connection belongs to the process holding it, and a restart ends+ * every one of them anyway. A hot push builds a new registry along with the App, so streams+ * opened by the previous generation are no longer listed here — their own heartbeat is what+ * ends them, on the same schedule as any other.+ */+import { Component, Interface } from "@prismshadow/penguin-core/kernel";++/** LiveStreams: the mechanism LiveStreamRegistry implements. */+export abstract class LiveStreams extends Interface<{+ /**+ * Track a live stream for `userId`. The returned call removes it again and must run on+ * every exit path of the connection — an entry left behind names a stream nobody can+ * close, and its `end` would be called on a connection that is already gone.+ */+ add(userId: string, end: () => void): () => void;+ /** End every stream this user is holding open; returns how many were ended. */+ endForUser(userId: string): number;+ /** How many streams this user is holding open. */+ countFor(userId: string): number;+}>() {}++/** One tracked stream. An object rather than the bare callback, so two streams sharing a callback identity stay two entries. */+interface TrackedStream {+ end: () => void;+}++@Component()+export class LiveStreamRegistry implements LiveStreams {+ private readonly byUser = new Map<string, Set<TrackedStream>>();++ add(userId: string, end: () => void): () => void {+ const tracked: TrackedStream = { end };+ let streams = this.byUser.get(userId);+ if (streams === undefined) {+ streams = new Set<TrackedStream>();+ this.byUser.set(userId, streams);+ }+ const held = streams;+ held.add(tracked);+ let released = false;+ return () => {+ // Idempotent: a stream that ends itself while the registry is ending it would+ // otherwise release twice, and the second release could drop a set a later+ // connection is already using.+ if (released) return;+ released = true;+ held.delete(tracked);+ if (held.size === 0 && this.byUser.get(userId) === held) this.byUser.delete(userId);+ };+ }++ endForUser(userId: string): number {+ const streams = this.byUser.get(userId);+ if (streams === undefined) return 0;+ // Over a snapshot: ending a stream runs its own release, which mutates this very set.+ const ending = [...streams];+ for (const stream of ending) stream.end();+ return ending.length;+ }++ countFor(userId: string): number {+ return this.byUser.get(userId)?.size ?? 0;+ }+}diff --git a/packages/server/src/auth/service.ts b/packages/server/src/auth/service.tsindex 671e74fd..e6997dce 100644--- a/packages/server/src/auth/service.ts+++ b/packages/server/src/auth/service.ts@@ -354,6 +354,20 @@ export class AuthService implements Auth {return { user, via, renewed };}+ /**+ * Whether the session behind a cookie token still exists and has not expired — the same+ * two facts {@link authenticateWithMeta} establishes, without its sliding renewal or its+ * user lookup. A connection that outlives the request that opened it has to re-ask+ * periodically (the SSE heartbeat does, once per beat), and asking through the renewing+ * path would top the expiry up every time: a window nobody has touched since last week+ * would stay signed in purely because it is still connected.+ */+ sessionIsLive(token: string): boolean {+ const session = this.authSessions.findByTokenHash(sessionTokenHash(token));+ if (!session) return false;+ return Date.parse(session.expiresAt) > this.clock.now().getTime();+ }+private issueSession(userId: string, via: SessionViaValue): string {return this.authSessions.issue({userId,diff --git a/packages/server/src/http/routes/events.ts b/packages/server/src/http/routes/events.tsindex f07297bb..b9659e94 100644--- a/packages/server/src/http/routes/events.ts+++ b/packages/server/src/http/routes/events.ts@@ -4,15 +4,21 @@*/import { Hono } from "hono";import type { AppEnv } from "../../auth/middleware.js";-import { sseEndpoint } from "../sse.js";+import { sseEndpoint, streamRevocation } from "../sse.js";import type { ChannelHub } from "../../runtime/channel.js";import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";import type { ClassCtx } from "@prismshadow/penguin-core/kernel";import { Channels } from "../../hmr/capabilities.js";+import { LiveStreams } from "../../auth/live-streams.js";+import { Auth } from "../../mechanisms/identity.js";/** What this route group reaches — bound by its module (src/modules). */export interface EventsRouteDeps {channels: ChannelHub;+ /** The registry that ends this stream when the session behind it is revoked. */+ liveStreams: LiveStreams;+ /** Re-validates the session behind an open stream, once per heartbeat. */+ auth: Auth;}/** The user channel's key in ChannelHub. */@@ -25,7 +31,10 @@ export function eventsRoutes(deps: EventsRouteDeps): Hono<AppEnv> {app.get("/", (c) => {const channel = deps.channels.get(userChannelKey(c.var.user.userId));- return sseEndpoint(c, channel, { initialEvents: [{ type: "hello" }] });+ return sseEndpoint(c, channel, {+ initialEvents: [{ type: "hello" }],+ revocation: streamRevocation(c, c.var.user, deps),+ });});return app;@@ -45,8 +54,14 @@ export function eventsRoutes(deps: EventsRouteDeps): Hono<AppEnv> {})export class EventsRoutes {@Use() private readonly channels!: Channels;+ @Use() private readonly liveStreams!: LiveStreams;+ @Use() private readonly auth!: Auth;@Bind("EventsRoutes.routes") routes!: Hono<AppEnv>;setup() {- this.routes = eventsRoutes({ channels: this.channels as ChannelHub });+ this.routes = eventsRoutes({+ channels: this.channels as ChannelHub,+ liveStreams: this.liveStreams,+ auth: this.auth,+ });}}diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex ad1013c9..abdf8692 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -50,7 +50,7 @@ import type { SessionRow } from "../../db/repos/sessions.js";import { assertWorkspaceAllowed } from "../../services/workspace-guard.js";import { isGoalOutcome } from "../../runtime/goal-events.js";import { HttpError } from "../errors.js";-import { sseEndpoint } from "../sse.js";+import { sseEndpoint, streamRevocation } from "../sse.js";import {badRequest,optionalEnum,@@ -93,6 +93,10 @@ export interface SessionsRouteDeps {desktopMode: boolean;/** Opens a Workspace file's directory in the machine's file manager (the reveal route). */fileReveal: FileReveal;+ /** The registry that ends a Session stream when the session behind it is revoked. */+ liveStreams: LiveStreams;+ /** Re-validates the session behind an open stream, once per heartbeat. */+ auth: Auth;}import { MAX_UPLOAD_BYTES } from "../../services/workspace-files-service.js";import {@@ -141,6 +145,8 @@ import type { FileReveal, WorkspaceFiles } from "../../mechanisms/workspace.js";import type { Machines } from "../../machines/service.js";import type { AgentConfig, AgentLifecycle } from "../../mechanisms/agents.js";import type { Settings } from "../../mechanisms/settings.js";+import type { LiveStreams } from "../../auth/live-streams.js";+import type { Auth } from "../../mechanisms/identity.js";/** Max title length for manual renames: looser than the auto-generated 30-char limit, to accommodate users' own organizing conventions. */const SESSION_TITLE_MAX = 120;@@ -999,7 +1005,10 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {...(p.origin !== undefined ? { origin: p.origin } : {}),})),];- return sseEndpoint(c, channel, { initialEvents });+ return sseEndpoint(c, channel, {+ initialEvents,+ revocation: streamRevocation(c, c.var.user, deps),+ });});app.post("/:sessionId/tasks", async (c) => {@@ -1745,6 +1754,8 @@ export class SessionApiRoutes {@Use() private readonly sources!: SessionOrigins;@Use() private readonly errorsRepo!: ErrorLog;@Use() private readonly usage!: UsageQueries;+ @Use() private readonly liveStreams!: LiveStreams;+ @Use() private readonly auth!: Auth;@Bind("session-api.model-oauth-callback") modelOauthCallbackRoutes!: Hono<AppEnv>;@Bind("session-api.models") modelsRoutes!: Hono<AppEnv>;@Bind("session-api.model-oauth") modelOauthRoutes!: Hono<AppEnv>;@@ -1786,6 +1797,8 @@ export class SessionApiRoutes {// this process or it did not, and that cannot change under a running server.desktopMode: this.desktop.current() !== null,fileReveal: this.fileReveal,+ liveStreams: this.liveStreams,+ auth: this.auth,};const modelOAuthDeps = {config: this.config,diff --git a/packages/server/src/http/sse.ts b/packages/server/src/http/sse.tsindex 99f3baa7..5d17fc29 100644--- a/packages/server/src/http/sse.ts+++ b/packages/server/src/http/sse.ts@@ -11,23 +11,69 @@* caller supplied (pending approvals / hello). With a Last-Event-ID that hits the buffer,* replay resumes from there; on a miss, `resync_required` is sent first, then the* connection continues.+ * - Revocation: a stream is authorised at connect and never again by the request path, so+ * an authenticated route hands over {@link SseRevocation} — the registry that can end+ * this stream from outside, and the check the heartbeat runs on it.* Docs: /docs/server-api § "Delivery Guarantees".*/import type { Context } from "hono";+import { getCookie } from "hono/cookie";import { streamSSE } from "hono/streaming";import type { ServerEvent } from "../api/types.js";import type { Channel, ChannelEvent, ChannelListener } from "../runtime/channel.js";+import type { LiveStreams } from "../auth/live-streams.js";+import type { Auth } from "../mechanisms/identity.js";+import { SESSION_COOKIE, bearerToken } from "../auth/middleware.js";const HEARTBEAT_MS = 20_000;+/** How the session behind one connection reaches the stream it authorised. */+export interface SseRevocation {+ /** The user this connection was authenticated as. */+ userId: string;+ /** Holds the stream for as long as it is open (auth/live-streams.ts). */+ streams: LiveStreams;+ /** Whether the session behind this connection still exists and has not expired. Never renews it. */+ sessionIsLive(): boolean;+}+export interface SseEndpointOptions {/** Initial server events to send privately after the subscription is established (in order): pending-approval replay / user channel hello. */initialEvents?: ServerEvent[];+ /** Omitted only where there is no authenticated session to revoke. */+ revocation?: SseRevocation;+}++/**+ * The revocation wiring an authenticated SSE route hands {@link sseEndpoint}. One+ * definition, so a new streaming route cannot be wired half-way — with a registry entry+ * but no re-check, or the other way round.+ */+export function streamRevocation(+ c: Context,+ user: { userId: string },+ deps: { liveStreams: LiveStreams; auth: Auth },+): SseRevocation {+ // Bearer first, cookie otherwise — the precedence authMiddleware authenticated this+ // request with. A Bearer-authenticated stream (the CLI, an Agent's own tools) carries no+ // session row at all: its credential is the boot's local API token, which lives as long+ // as the process does. There is nothing for the heartbeat to re-check there, so it+ // leaves that connection alone instead of ending it on a lookup that can only miss.+ const token =+ bearerToken(c.req.header("authorization")) !== null+ ? null+ : (getCookie(c, SESSION_COOKIE) ?? null);+ return {+ userId: user.userId,+ streams: deps.liveStreams,+ sessionIsLive: () => token === null || deps.auth.sessionIsLive(token),+ };}/** Stream out a Channel as an SSE response. */export function sseEndpoint(c: Context, channel: Channel, opts: SseEndpointOptions = {}): Response {const lastEventIdHeader = c.req.header("Last-Event-ID");+ const revocation = opts.revocation;c.header("X-Accel-Buffering", "no");c.header("Cache-Control", "no-cache");@@ -42,53 +88,70 @@ export function sseEndpoint(c: Context, channel: Channel, opts: SseEndpointOptio};});- // Write serialization: SSE events must be written fully and in order; any write failure tears down the connection.- let chain: Promise<void> = Promise.resolve();- const enqueue = (write: () => Promise<unknown>): void => {- chain = chain- .then(async () => {- if (!closed) await write();- })- .catch(() => finish());- };- const listener: ChannelListener = (evt: ChannelEvent) => {- enqueue(() =>- stream.writeSSE({- data: evt.data,- // Event id is an opaque string generated by the channel (`<epoch>-<seq>`), passed through as-is.- id: evt.id,- ...(evt.event !== undefined ? { event: evt.event } : {}),- }),- );- };+ // Claimed before anything that can throw and released in the finally below, so the+ // registry holds an entry for exactly as long as the connection lives: one left+ // behind would name a stream nobody can close again.+ const release = revocation?.streams.add(revocation.userId, finish) ?? (() => {});+ let unsubscribe: (() => void) | null = null;+ let heartbeat: ReturnType<typeof setInterval> | null = null;+ try {+ // Write serialization: SSE events must be written fully and in order; any write failure tears down the connection.+ let chain: Promise<void> = Promise.resolve();+ const enqueue = (write: () => Promise<unknown>): void => {+ chain = chain+ .then(async () => {+ if (!closed) await write();+ })+ .catch(() => finish());+ };+ const listener: ChannelListener = (evt: ChannelEvent) => {+ enqueue(() =>+ stream.writeSSE({+ data: evt.data,+ // Event id is an opaque string generated by the channel (`<epoch>-<seq>`), passed through as-is.+ id: evt.id,+ ...(evt.event !== undefined ? { event: evt.event } : {}),+ }),+ );+ };- const unsubscribe = channel.subscribe(listener);- // Subscribe first (to avoid dropping events in a race with broadcasts), then replay- // synchronously — event order: buffered replay (or resync_required) -> initial events- // (task_state snapshot / pending approvals / hello) -> live stream.- if (lastEventIdHeader !== undefined) {- const replay = channel.replayAfter(lastEventIdHeader);- if (!replay.hit) {- const resync: ServerEvent = { type: "resync_required" };- channel.sendTo(listener, resync, "server_event");- } else {- for (const evt of replay.events) listener(evt);+ unsubscribe = channel.subscribe(listener);+ // Subscribe first (to avoid dropping events in a race with broadcasts), then replay+ // synchronously — event order: buffered replay (or resync_required) -> initial events+ // (task_state snapshot / pending approvals / hello) -> live stream.+ if (lastEventIdHeader !== undefined) {+ const replay = channel.replayAfter(lastEventIdHeader);+ if (!replay.hit) {+ const resync: ServerEvent = { type: "resync_required" };+ channel.sendTo(listener, resync, "server_event");+ } else {+ for (const evt of replay.events) listener(evt);+ }+ }+ for (const event of opts.initialEvents ?? []) {+ channel.sendTo(listener, event, "server_event");}- }- for (const event of opts.initialEvents ?? []) {- channel.sendTo(listener, event, "server_event");- }- const heartbeat = setInterval(() => {- enqueue(() => stream.write(": ping\n\n"));- }, HEARTBEAT_MS);+ heartbeat = setInterval(() => {+ // The heartbeat is the one beat an open stream already has, so re-asking whether+ // the session behind it still exists costs nothing extra — and it bounds how long+ // a window whose session was revoked keeps streaming to a single interval, no+ // matter which caller dropped the rows or whether it remembered the registry. The+ // check must not renew the session: sliding the expiry from here would keep a+ // window nobody has touched signed in for as long as it stays open.+ if (revocation !== undefined && !revocation.sessionIsLive()) {+ finish();+ return;+ }+ enqueue(() => stream.write(": ping\n\n"));+ }, HEARTBEAT_MS);- stream.onAbort(() => finish());- try {+ stream.onAbort(() => finish());await done;} finally {- clearInterval(heartbeat);- unsubscribe();+ if (heartbeat !== null) clearInterval(heartbeat);+ unsubscribe?.();+ release();}});}diff --git a/packages/server/src/mechanisms/identity.ts b/packages/server/src/mechanisms/identity.tsindex e36043e5..c076b367 100644--- a/packages/server/src/mechanisms/identity.ts+++ b/packages/server/src/mechanisms/identity.ts@@ -55,6 +55,7 @@ export abstract class Auth extends Interface<{localApiToken(): string | null;authenticateApiToken(token: string): { user: UserRow; via: SessionVia } | null;authenticateWithMeta(token: string): { user: UserRow; via: SessionVia; renewed: boolean } | null;+ sessionIsLive(token: string): boolean;isAdmin(userId: string): boolean;}>() {}diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex d23a8d60..8fae12bd 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -33,6 +33,7 @@ import {ResourceGroups,} from "./hmr/capabilities.js";import { ScryptHasher, PasswordHasher } from "./auth/password.js";+import { LiveStreamRegistry, LiveStreams } from "./auth/live-streams.js";import {DefaultMessagingTuning,Messaging,@@ -258,13 +259,14 @@ export class RuntimeModule {}UsersRepo,AuthSessionsRepo,ScryptHasher,+ LiveStreamRegistry,AuthService,AdminService,AdminRoutes,MeRoutes,AuthRoutes,],- exports: [Users, AuthSessions, Auth, Admin, PasswordHasher],+ exports: [Users, AuthSessions, Auth, Admin, PasswordHasher, LiveStreams],})export class IdentityModule {}diff --git a/packages/server/src/services/admin-service.ts b/packages/server/src/services/admin-service.tsindex 3c76251e..17453918 100644--- a/packages/server/src/services/admin-service.ts+++ b/packages/server/src/services/admin-service.ts@@ -9,6 +9,9 @@* - Delete: the built-in admin cannot be deleted; Projects owned by the user are* deleted along with it (including data directories), with sessions/memberships/UI* preferences cascade-deleted via foreign keys.+ *+ * Both of those end sessions, so both go through `signOutEverywhere`: dropping the rows+ * alone leaves the connections those rows authorised still open.*/import type { UserInfo } from "../api/types.js";import { HttpError } from "../http/errors.js";@@ -18,6 +21,7 @@ import type { UserRow } from "../db/repos/users.js";import { SEMANTIC_ID_RULE, USERNAME_PATTERN } from "./ids.js";import { Component, Use } from "@prismshadow/penguin-core/kernel";import type { Clock } from "../hmr/capabilities.js";+import type { LiveStreams } from "../auth/live-streams.js";import type { Admin, AuthSessions, Users } from "../mechanisms/identity.js";import type { ProjectLifecycle, Projects } from "../mechanisms/projects.js";@@ -25,6 +29,7 @@ import type { ProjectLifecycle, Projects } from "../mechanisms/projects.js";export class AdminService implements Admin {@Use() private readonly users!: Users;@Use() private readonly authSessions!: AuthSessions;+ @Use() private readonly liveStreams!: LiveStreams;@Use() private readonly projects!: Projects;@Use() private readonly projectService!: ProjectLifecycle;@Use() private readonly clock!: Clock;@@ -92,8 +97,21 @@ export class AdminService implements Admin {}const isSelfAdminReset = userId === ADMIN_USER_ID;this.users.updatePassword(userId, await this.hasher.hash(password), !isSelfAdminReset);- // Force re-login: delete every session row for this user.+ this.signOutEverywhere(userId);+ }++ /**+ * Sign a user out of every window: the session rows go, and so does every SSE stream+ * those sessions authorised. The two belong together — a stream is authorised once, when+ * it connects, so dropping the rows on their own leaves the window streaming happily+ * until its reader happens to make a request. Anything that revokes a user's sessions+ * calls this rather than the repo directly. Forgetting it is not fatal: each stream+ * re-checks its own session on the next heartbeat (http/sse.ts), which costs the window+ * one beat instead of ending it at once.+ */+ private signOutEverywhere(userId: string): void {this.authSessions.deleteByUser(userId);+ this.liveStreams.endForUser(userId);}/** Delete user: the built-in admin cannot be deleted; owned Projects (including data directories) are deleted along with it. */@@ -109,5 +127,9 @@ export class AdminService implements Admin {await this.projectService.destroyProject(project.projectId);}this.users.delete(userId); // project_members / ui_prefs cascade-deleted+ // The session rows went with the user row (ON DELETE CASCADE), so this is about the+ // connections they authorised: a window left open on a deleted account would go on+ // streaming until it tried to fetch something.+ this.signOutEverywhere(userId);}}diff --git a/packages/server/test/live-streams.test.ts b/packages/server/test/live-streams.test.tsnew file mode 100644index 00000000..bed7547a--- /dev/null+++ b/packages/server/test/live-streams.test.ts@@ -0,0 +1,191 @@+/**+ * Ending the streams a revoked session left open.+ *+ * Three layers, in the order the fix works: the registry that knows which streams belong+ * to which user, the non-renewing session check a long-lived connection re-asks with, and+ * the SSE heartbeat that puts the two together — the catch-all for anything that drops+ * session rows without telling the registry.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import { Hono } from "hono";+import { LiveStreamRegistry } from "../src/auth/live-streams.js";+import { SESSION_COOKIE } from "../src/auth/middleware.js";+import { sessionTokenHash } from "../src/db/repos/auth-sessions.js";+import { Channel } from "../src/runtime/channel.js";+import { sseEndpoint } from "../src/http/sse.js";+import { createTestApp, loginAdmin } from "./helpers.js";++const DAY_MS = 24 * 60 * 60 * 1000;+/** The heartbeat period the SSE endpoint runs on (http/sse.ts). */+const HEARTBEAT_MS = 20_000;++describe("live stream registry", () => {+ it("holds a user's streams and ends them all at once", () => {+ const registry = new LiveStreamRegistry();+ const ended: string[] = [];+ registry.add("alice", () => ended.push("alice-1"));+ registry.add("alice", () => ended.push("alice-2"));++ expect(registry.countFor("alice")).toBe(2);+ expect(registry.endForUser("alice")).toBe(2);+ expect(ended).toEqual(["alice-1", "alice-2"]);+ });++ it("leaves another user's streams alone", () => {+ const registry = new LiveStreamRegistry();+ let bobEnded = false;+ registry.add("alice", () => undefined);+ registry.add("bob", () => {+ bobEnded = true;+ });++ registry.endForUser("alice");+ expect(bobEnded).toBe(false);+ expect(registry.countFor("bob")).toBe(1);+ });++ it("a released stream is no longer ended, and releasing twice is harmless", () => {+ const registry = new LiveStreamRegistry();+ let ended = 0;+ const release = registry.add("alice", () => {+ ended += 1;+ });++ release();+ release();+ expect(registry.countFor("alice")).toBe(0);+ expect(registry.endForUser("alice")).toBe(0);+ expect(ended).toBe(0);+ });++ it("a stream that releases itself while the registry is ending it is still counted once", () => {+ const registry = new LiveStreamRegistry();+ let ended = 0;+ // What the SSE endpoint does: the call that ends the connection leads to the release.+ const release: () => void = registry.add("alice", () => {+ ended += 1;+ release();+ });++ expect(registry.endForUser("alice")).toBe(1);+ expect(ended).toBe(1);+ expect(registry.countFor("alice")).toBe(0);+ });++ it("a user nobody is streaming for is a no-op", () => {+ const registry = new LiveStreamRegistry();+ expect(registry.endForUser("nobody")).toBe(0);+ expect(registry.countFor("nobody")).toBe(0);+ });+});++describe("sessionIsLive", () => {+ it("answers for the row behind the token without sliding its expiry", async () => {+ let now = new Date("2026-09-21T00:00:00.000Z");+ // A session minted 30 days long renews once less than 29 days of it are left, so two+ // days on the clock is enough for the renewing path to be visibly different.+ const t = await createTestApp({+ now: () => now,+ config: { authSessionTtlMs: 30 * DAY_MS, authSessionRenewMs: 29 * DAY_MS },+ });+ try {+ const { cookie } = await loginAdmin(t.app);+ const token = cookie.slice(`${SESSION_COOKIE}=`.length);+ const hash = sessionTokenHash(token);+ const expiresAt = (): unknown => {+ const sql = "SELECT expires_at FROM auth_sessions WHERE token_hash = ?";+ const row = t.deps.db.prepare(sql).get(hash) as { expires_at: unknown };+ return row.expires_at;+ };++ now = new Date(now.getTime() + 2 * DAY_MS);+ const before = expiresAt();+ expect(t.deps.authService.sessionIsLive(token)).toBe(true);+ expect(expiresAt()).toBe(before);++ // The contrast: the path the request gate uses tops the expiry up in place, which is+ // exactly what a connection re-checking itself every 20s must not do.+ expect(t.deps.authService.authenticateWithMeta(token)).not.toBeNull();+ expect(expiresAt()).not.toBe(before);+ } finally {+ await t.cleanup();+ }+ });++ it("is false once the row is gone, and false while it is only expired", async () => {+ let now = new Date("2026-09-21T00:00:00.000Z");+ const t = await createTestApp({ now: () => now });+ try {+ const { cookie } = await loginAdmin(t.app);+ const token = cookie.slice(`${SESSION_COOKIE}=`.length);+ expect(t.deps.authService.sessionIsLive(token)).toBe(true);++ // Expired but still on disk: the sweep has not run, and the check must not be fooled+ // by the row merely existing.+ now = new Date(now.getTime() + 31 * DAY_MS);+ expect(t.deps.authService.sessionIsLive(token)).toBe(false);++ t.deps.db.prepare("DELETE FROM auth_sessions").run();+ expect(t.deps.authService.sessionIsLive(token)).toBe(false);+ expect(t.deps.authService.sessionIsLive("never-issued")).toBe(false);+ } finally {+ await t.cleanup();+ }+ });+});++describe("the SSE heartbeat re-checks its own session", () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ /** An SSE route over a bare channel; `live` stands in for the session row behind the connection. */+ function streamingApp(session: { live: boolean }, registry: LiveStreamRegistry) {+ const app = new Hono();+ app.get("/stream", (c) =>+ sseEndpoint(c, new Channel(), {+ initialEvents: [{ type: "hello" }],+ revocation: {+ userId: "alice",+ streams: registry,+ sessionIsLive: () => session.live,+ },+ }),+ );+ return app;+ }++ it("a session that is still there gets a ping and keeps the stream", async () => {+ // Only the interval: the stream's own plumbing runs on promises, and faking those+ // would stall the reads below.+ vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });+ const registry = new LiveStreamRegistry();+ const session = { live: true };+ const res = await streamingApp(session, registry).request("/stream");+ const reader = res.body!.getReader();+ await reader.read(); // hello: the connection is established and registered++ vi.advanceTimersByTime(HEARTBEAT_MS);+ const beat = await reader.read();+ expect(beat.done).toBe(false);+ expect(new TextDecoder().decode(beat.value)).toContain(": ping");+ expect(registry.countFor("alice")).toBe(1);+ await reader.cancel();+ });++ it("a session that was revoked ends the stream on the next beat, and releases it", async () => {+ vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });+ const registry = new LiveStreamRegistry();+ const session = { live: true };+ const res = await streamingApp(session, registry).request("/stream");+ const reader = res.body!.getReader();+ await reader.read();+ expect(registry.countFor("alice")).toBe(1);++ // Whatever dropped the rows did not tell the registry — the beat is what notices.+ session.live = false;+ vi.advanceTimersByTime(HEARTBEAT_MS);+ expect((await reader.read()).done).toBe(true);+ expect(registry.countFor("alice")).toBe(0);+ });+});diff --git a/packages/server/test/sse-stream.test.ts b/packages/server/test/sse-stream.test.tsindex 82a41dac..1aae372c 100644--- a/packages/server/test/sse-stream.test.ts+++ b/packages/server/test/sse-stream.test.ts@@ -10,7 +10,7 @@ import { approvalDecision, assistantText, toolCall, userText } from "@prismshadoimport type { ApproveFn, OmniMessage } from "@prismshadow/penguin-core";import type { SessionRow } from "../src/db/repos/sessions.js";import type { RuntimeSession } from "../src/runtime/session-manager.js";-import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";+import { apiClient, createTestApp, loginAdmin, provisionUser, waitFor } from "./helpers.js";import type { TestApp } from "./helpers.js";const SID = "session-2026-07-06-10-00-00-aabb0001";@@ -146,6 +146,26 @@ describe("sse-stream", () => {expect(JSON.parse(frames[1]!.data)).toEqual({ type: "task_state", state: "idle", queued: 0 });});+ it("an admin resetting the password ends the streams that user had open", async () => {+ const res = await t.app.request("/api/events", { headers: { cookie } });+ expect(res.status).toBe(200);+ const reader = res.body!.getReader();+ // The hello frame proves the subscription is live — and therefore registered — before+ // the reset lands.+ expect(new TextDecoder().decode((await reader.read()).value)).toContain("hello");++ const admin = await loginAdmin(t.app);+ const reset = await apiClient(t.app, admin.cookie).post("/api/admin/users/streamer/password", {+ password: "password-456",+ });+ expect(reset.status).toBe(204);++ // Ended by the reset itself, within the same request: no heartbeat has passed, and the+ // reader has made no request of its own that could have noticed.+ expect((await reader.read()).done).toBe(true);+ expect((await t.app.request("/api/events", { headers: { cookie } })).status).toBe(401);+ });+it("FD-2: same-epoch Last-Event-ID hitting the buffer → replays later events, then the task_state snapshot", async () => {const channel = t.deps.channels.get(SID);const first = channel.publish(userText("m1"));diff --git a/packages/web/src/api/session-probe.ts b/packages/web/src/api/session-probe.tsnew file mode 100644index 00000000..901e5759--- /dev/null+++ b/packages/web/src/api/session-probe.ts@@ -0,0 +1,32 @@+/**+ * "Am I still signed in?" — one request, shared by everything that has reason to doubt it.+ *+ * A revoked session is invisible to a page that is only listening. An SSE stream the server+ * ends looks exactly like a network blip from the browser's side (EventSource cannot read+ * the status code), and a window nobody touches makes no requests at all — so without a+ * deliberate ask, the window keeps showing a signed-in app until its reader tries to do+ * something. GET /api/me is the cheapest way to ask: a 401 goes through the api client's+ * global unauthorized handler, which clears the current user and lets the route guard take+ * the window to the sign-in page.+ *+ * Every other failure is left alone. An offline laptop and a server being restarted are not+ * revoked sessions, and signing someone out over one would be the worse mistake.+ */+import { getMe } from "./endpoints";++/** The probe in flight, so a burst of focus and stream-error events costs one request rather than one each. */+let inFlight: Promise<void> | null = null;++/** Asks once whether this browser's session is still good. Never rejects. */+export function probeSession(): Promise<void> {+ inFlight ??= getMe().then(+ () => {+ inFlight = null;+ },+ () => {+ // The 401 case has already been handled by the api client, on its way out.+ inFlight = null;+ },+ );+ return inFlight;+}diff --git a/packages/web/src/features/chat/use-session-stream.ts b/packages/web/src/features/chat/use-session-stream.tsindex 9f0838ff..d2e4c61d 100644--- a/packages/web/src/features/chat/use-session-stream.ts+++ b/packages/web/src/features/chat/use-session-stream.ts@@ -23,7 +23,8 @@ import type {SessionStatus,SubagentRuntimeInfo,} from "@prismshadow/penguin-server/api";-import { getGoal, getMe, getMessages } from "../../api/endpoints";+import { getGoal, getMessages } from "../../api/endpoints";+import { probeSession } from "../../api/session-probe";import { openSessionStream } from "../../api/sse";import { createStreamController } from "../../lib/omni/stream-controller";import type {@@ -261,11 +262,10 @@ export function useSessionStream(// Hydrate the goal banner only once the subscription is live (fires on first connect and// every reconnect); the prev/active guards keep it from clobbering a live banner.onOpen: hydrateGoal,- // EventSource can't read the status code: when the connection is judged a fatal error and- // closes, probe once with GET /api/me; if the session has expired (401), the client's- // global handler clears the user and redirects to the login page.+ // EventSource can't read the status code: when the connection is judged a fatal error+ // and closes, ask whether this browser is still signed in (api/session-probe.ts).onError: (closed) => {- if (closed) void getMe().catch(() => undefined);+ if (closed) void probeSession();},});void controller.load();diff --git a/packages/web/src/features/terminal/terminal-list.ts b/packages/web/src/features/terminal/terminal-list.tsindex d308a6c9..a65ba04b 100644--- a/packages/web/src/features/terminal/terminal-list.ts+++ b/packages/web/src/features/terminal/terminal-list.ts@@ -12,6 +12,7 @@* tab cannot see (a shell exiting on its own, terminals opened from another window).*/import type { TerminalInfo } from "./terminal-view";+import { probeSession } from "../../api/session-probe";import { pruneTerminalTabs } from "../dock/dock-state";import { apiUrl } from "../../lib/server-context";import {@@ -121,7 +122,15 @@ export function refreshTerminals(): Promise<void> {for (const listener of [...listeners]) listener();return;}- if (here === null || !here.ok) return; // signed out or unreachable: keep the last list+ // This poll is often the only request an idle window still makes, so it is the+ // first thing to see a session that was revoked meanwhile. It goes through the raw+ // fetch rather than the api client, so nothing has told the app yet — the probe+ // does, and the window lands on the sign-in page (api/session-probe.ts).+ if (here?.status === 401) {+ void probeSession();+ return;+ }+ if (here === null || !here.ok) return; // server unreachable or refusing: keep the last listunsupported = false;const terminals: TerminalInfo[] = [];for (const { source, res } of answers) {diff --git a/packages/web/src/state/auth.tsx b/packages/web/src/state/auth.tsxindex 9994be56..41ce92fb 100644--- a/packages/web/src/state/auth.tsx+++ b/packages/web/src/state/auth.tsx@@ -9,6 +9,7 @@ import type { ReactNode } from "react";import type { MeResponse, UploadLimits, UserInfo } from "@prismshadow/penguin-server/api";import * as api from "../api/endpoints";import { ApiError, setUnauthorizedHandler } from "../api/client";+import { probeSession } from "../api/session-probe";/*** Stand-in until GET /api/me answers, matching the server's shipped defaults. The window is the@@ -120,6 +121,26 @@ export function AuthProvider({ children }: { children: ReactNode }) {};}, []);+ // A window that only reads — a tab left open overnight, a page with no live stream —+ // learns nothing about a session revoked meanwhile until its reader acts, and then finds+ // out through a failed action. Re-asking when the window comes back to the foreground is+ // one request at the moment someone is about to use it, and probeSession collapses a+ // burst of focus events into that one request.+ const signedIn = user !== null && user !== undefined;+ useEffect(() => {+ if (!signedIn) return;+ const recheck = () => {+ if (document.visibilityState === "hidden") return;+ void probeSession();+ };+ window.addEventListener("focus", recheck);+ document.addEventListener("visibilitychange", recheck);+ return () => {+ window.removeEventListener("focus", recheck);+ document.removeEventListener("visibilitychange", recheck);+ };+ }, [signedIn]);+const login = useCallback(async (userId: string, password: string) => {const res = await api.login({ userId, password });setUser(res.user);diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsxindex 6b63089f..d18c9597 100644--- a/packages/web/src/state/sessions.tsx+++ b/packages/web/src/state/sessions.tsx@@ -54,6 +54,7 @@ import { useStore } from "zustand/react";import { createStore } from "zustand/vanilla";import * as api from "../api/endpoints";import { ApiError } from "../api/client";+import { probeSession } from "../api/session-probe";import { openUserEvents } from "../api/sse";import { isCompanyEvent, publishCompanyEvent, publishCompanyResync } from "./company";import {@@ -1304,6 +1305,14 @@ export function SessionsProvider({ children }: { children: ReactNode }) {const conn = openUserEvents({onOmniMessage: () => undefined,onServerEvent: (ev) => applyUserEvent(store, ev, () => window.location.reload()),+ // This stream is the only thing an idle window has open, and the server ends it when+ // the session behind it is revoked — which EventSource reports as an ordinary fatal+ // error, indistinguishable from a dead network. Asking settles it: a session that is+ // really gone takes the window to the sign-in page instead of leaving it here+ // listening to nothing (api/session-probe.ts).+ onError: (closed) => {+ if (closed) void probeSession();+ },});return () => conn.close();}, [store]);diff --git a/packages/web/test/session-probe.test.ts b/packages/web/test/session-probe.test.tsnew file mode 100644index 00000000..42557b13--- /dev/null+++ b/packages/web/test/session-probe.test.ts@@ -0,0 +1,90 @@+/**+ * The session probe (`probeSession`): the one question a window asks when it suspects it is+ * no longer signed in — after its stream dies, or when it comes back to the foreground.+ *+ * What it must get right is the asymmetry: a 401 signs the window out through the api+ * client's global handler, and every other failure leaves the user exactly where they are,+ * because an offline laptop is not a revoked session. Plus the cheapness the callers rely+ * on — a burst of focus and stream-error events costs one request.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import { setUnauthorizedHandler } from "../src/api/client";+import { probeSession } from "../src/api/session-probe";++/** Counts the global sign-out the api client fires on a 401. */+function countSignOuts(): { readonly count: number } {+ const seen = { count: 0 };+ setUnauthorizedHandler(() => {+ seen.count += 1;+ });+ return seen;+}++const json = (body: unknown, status: number): Response =>+ new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json" },+ });++describe("probeSession", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ setUnauthorizedHandler(null);+ });++ it("signs the window out when the server answers 401", async () => {+ vi.stubGlobal("fetch", async () => json({ error: { code: "unauthorized" } }, 401));+ const signOuts = countSignOuts();++ await probeSession();++ expect(signOuts.count).toBe(1);+ });++ it("says nothing when the session is still good", async () => {+ vi.stubGlobal("fetch", async () => json({ user: { userId: "admin" } }, 200));+ const signOuts = countSignOuts();++ await probeSession();++ expect(signOuts.count).toBe(0);+ });++ it("never signs the window out over an unreachable or broken server", async () => {+ const signOuts = countSignOuts();++ vi.stubGlobal("fetch", async () => {+ throw new Error("connection refused");+ });+ await expect(probeSession()).resolves.toBeUndefined();++ vi.stubGlobal("fetch", async () => json({ error: { code: "internal" } }, 500));+ await expect(probeSession()).resolves.toBeUndefined();++ expect(signOuts.count).toBe(0);+ });++ it("collapses a burst into a single request, and asks again once it has settled", async () => {+ let calls = 0;+ let answer: () => void = () => {};+ const pending = new Promise<void>((resolve) => {+ answer = resolve;+ });+ vi.stubGlobal("fetch", async () => {+ calls += 1;+ await pending;+ return json({ user: { userId: "admin" } }, 200);+ });++ const first = probeSession();+ const second = probeSession();+ expect(calls).toBe(1);++ answer();+ await Promise.all([first, second]);+ expect(calls).toBe(1);++ await probeSession();+ expect(calls).toBe(2);+ });+});