From f16a7bc26a4b46cccf98110382dc271855fbdd31 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Sat, 24 Oct 2026 23:50:59 -0400 Subject: [PATCH 1/4] fix(j5): lowering an Owner ends the MCP clients they approved J5's MCP approval gate now reads who approves an MCP client (the person a pairing code was made for, or the person whose browser approves) and the access gate records the issued session as theirs in a J5 table keyed by session id. Lowering or removing that Owner revokes those sessions in the same transaction as the change of level. Clients approved before this, or with a code that names no one, have no recorded approver and keep working until an Owner ends them. An approval still waiting when the Owners change stays refused. Closes #639 Co-Authored-By: Claude Opus 5.5 --- FORK.md | 2 +- apps/server/src/j5/a2a/Migrations.test.ts | 4 +- apps/server/src/j5/a2a/Migrations.ts | 2 + .../a2a/migrations/044_McpClientApprovers.ts | 23 ++ apps/server/src/j5/sharing/Access.test.ts | 60 ++++- apps/server/src/j5/sharing/Access.ts | 83 +++++- apps/server/src/j5/sharing/AccessGate.ts | 13 +- .../server/src/j5/sharing/McpApproval.test.ts | 245 ++++++++++++------ apps/server/src/j5/sharing/McpApproval.ts | 65 +++-- docs/j5/product/upstream.md | 5 +- 10 files changed, 372 insertions(+), 130 deletions(-) create mode 100644 apps/server/src/j5/a2a/migrations/044_McpClientApprovers.ts diff --git a/FORK.md b/FORK.md index 43f73b45d39cc..a1c98e86c6f9a 100644 --- a/FORK.md +++ b/FORK.md @@ -430,7 +430,7 @@ migrations after upstream migrations. 68. The web testing skill matches what works on a headless host ([#546](https://github.com/Jacksondr5/j5code/issues/546), Jackson's 2026-10-11 decision: follow upstream's Browser panel, and edit its skill in place). `.agents/skills/test-t3-app/SKILL.md` keeps upstream's structure and voice. J5's edits: the state paths are `.j5code` and `~/.j5code/userdata`; the start command unsets the inherited port, host and home variables (see `AGENTS.md`); "Start the app" points at J5's `j5-live-test` skill; and "Use the Browser panel" is rewritten as the steps that worked when the panel was driven end to end on 2026-10-11 (open before judging availability, wait after pairing and after each move, read with `preview_evaluate`, retry once after a timeout, save screenshots at 1280x800, and which callers may act). Each step answers a failure seen in a test run; steps agents already get right are left out. J5's own testing practice is not in this file: it lives in J5-owned `.agents/skills/j5-live-test/`. On a pin advance, read upstream's changes to this skill and port them; if upstream documents the same panel steps, take upstream's wording and keep only the J5 paths and the `j5-live-test` pointer. 69. A connection whose person's scope is narrower than the server is narrowed to it ([#532](https://github.com/Jacksondr5/j5code/issues/532), [#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, Jackson's 2026-10-09, 2026-10-11 and 2026-10-17 decisions). Upstream's permissions are per connection and cover the whole server. J5 reads, for each session, whose device it is (J5-owned `apps/server/src/j5/sharing/PersonAccess.ts`, `sessionReach`): a person's, by the binding case 70 records as the session is issued; the first owner's, by the subjects of the startup link, the desktop app, T3 Connect (`cloud-connect`, which upstream mints only for the cloud account the server is linked to) and the development credential; a service's (`peer:*`, `machine:*`, `mcp-client`, `cli-issued-session`); or a device no one has claimed. A service session and a person who holds Collaborator or Owner at server scope are wide and get upstream's own answers, the same objects. Everyone else is narrowed: a person at a project or a thread at either level, a Viewer at server scope, and an unclaimed device. A narrowed session is refused everything but an allow-list, every listed request is checked against the level the person holds at the scope it names, and the answers that name the host are reduced. All of it is J5-owned code under `apps/server/src/j5/sharing/`, reached from two upstream server files. In `apps/server/src/server.ts`, `layerAuth` is upstream's `EnvironmentAuth.layer` wrapped in `gateEnvironmentAuth` (`AccessGate.ts`): a narrowed session keeps its permissions only on the routes `accessHttpRule` allows (`/ws`, a reachable thread's loads, and J5's artifact read for a reachable project), so every other route's own permission check refuses it. In `apps/server/src/ws.ts`, the per-connection `RpcAuthorization.layer` is wrapped in `layerRpcAuthorization`, which refuses a narrowed session every request not in `ACCESS_RPC_RULES` and checks each listed one: at a thread or project the payload names, at the level given (`thread`, `project`); for a person who holds Collaborator anywhere, whatever folder it names (`collaborator`: files, terminals' folders, git, previews' profiles, the host's devices; a terminal or an agent reaches every folder anyway, Jackson 2026-10-17), and the server's Playbook library, read only (AC20); for anyone (`anyone`: what a client reports of itself); for a person with a level at server scope (`server`: the Fleet page, Personas, the providers' skills, every Playbook run, read only); or answered narrowly by its handler (`narrowed`). Upstream's own permission check runs after J5's on every request, so what a level's permissions lack (settings, providers, access, relay management, environment maintenance) is refused by upstream. A request still running is ended when the person's reach changes so that it no longer meets its rule (`PersonAccess.subscribeChanges`). Whether a session is wide is read once, when the socket opens; a change that would alter it renews the session (case 70). `layerWsRpc` reads `connectionView(currentSession)` (`GuestView.ts`) once, and six handlers pass their answer through it: `server.getConfig` (`Effect.map(j5View.config)`), `subscribeServerConfig` (`.pipe(j5View.configStream)`), `subscribeServerLifecycle` (`.pipe(j5View.lifecycleStream)`), `orchestration.subscribeShell` (`j5View.shellStream` around upstream's `subscribeOrchestrationV2Shell`), and `scheduledTasks.list` and `scheduledTasks.subscribe` (`j5View.scheduledTasks`, `j5View.scheduledTasksStream`), which list a narrowed person only the tasks bound to a thread they reach or, for a task bound to no thread, its project's, and give a Viewer no webhook address. The configuration is reduced for a Viewer and an unclaimed device (AC24) and given whole to a narrowed Collaborator, who can open a terminal on the host; the lifecycle welcome is reduced and the sidebar filtered for every narrowed session, and a Viewer's projects and threads carry placeholder folders where a Collaborator's carry the real ones. `apps/server/src/orchestration-v2/http.ts` is upstream's file: the HTTP sidebar snapshot (`GET /api/orchestration/shell`) is refused to a narrowed session, and upstream's client then reads the sidebar from the socket's feed (`packages/client-runtime/src/state/shell.ts` falls back when the HTTP load fails), so the feed is the one filtered path. A Viewer may ask `assets.createUrl` for an attachment or a tool's image only when `PersonAccess.messageAssetLevel` finds it in a thread they reach: in a message's attachments, or in a turn item's output, where a page a tool published is named; a Collaborator may ask for any asset. A favicon reaches a narrowed person through J5 and never by a host path (Jackson's 2026-10-12 decision; `GuestProjectIcons.ts`, no upstream edit): a reduced project carries `guestIconPath(projectId)` as its `faviconPath`, `ACCESS_RPC_RULES` reads the project id from a `project-favicon` request's `path`, checks `PersonAccess.projectInFeed`, and answers in place of upstream's handler with a link to `GET /api/j5/sharing/project-icon//`, signed with J5's own key, which serves the file through upstream's exported `issueAssetUrl`, `resolveAsset` and `assetFileResponse`. Both allow-lists refuse by default, so a route or request upstream adds is closed to a narrowed session until J5 lists it; `ACCESS_RPC_RULES` is keyed by the RPC group's method names, so a method upstream renames or removes fails to compile. The reduced configuration is built field by field (`reduceServerConfig`, `reduceProvider`), so a field upstream adds is left out for a Viewer until J5 lists it. The client half adds three J5 RPC groups and one call in each chat view: `J5AccessRpcGroup`, `J5PeopleRpcGroup` and `J5SharedConversationRpcGroup` (J5-owned `packages/contracts/src/j5/access.ts`, `people.ts` and `sharedConversation.ts`) are merged in `packages/contracts/src/rpc.ts`, and their streams (`j5.access.subscribeThreadLevel`, `j5.people.subscribeScopeChanges`, `j5.sharedConversation.subscribeThreadAuthorsChanges`) join `EnvironmentSubscriptionRpcTag` in `packages/client-runtime/src/rpc/client.ts` (one line each, the shape of cases 45 and 64); `packages/client-runtime/package.json` exports `./j5/sharing`. In `apps/server/src/ws.ts`, case 58's `layerJ5WsRpc(...)` call passes the connection's `session`, so the handlers answer for the session the socket was opened with. Upstream's web chat view (`apps/web/src/components/ChatView.tsx`) and mobile thread screen (`apps/mobile/src/features/threads/ThreadRouteScreen.tsx`) each call J5-owned `useCanOperateThread(environmentId, threadId)` from their app's `j5/sharing/access.ts` (web) or `j5/sharing/guestAccess.ts` (mobile) where they computed `canOperateThread` (one import and one call), and upstream's thread action menu (`apps/web/src/hooks/useThreadActionMenu.ts`) calls `readCanOperateThread(threadRef)` from `apps/web/src/j5/sharing/threadOperability.ts`. On a pin advance: keep the wrapping calls where the answers are produced; if upstream adds another place that sends a `ServerConfig`, a lifecycle event, a shell item or a list of scheduled tasks, a narrowed session cannot reach it until it is listed, and it must pass through `GuestView` when it is; if upstream changes how the shell feed resumes or what its items are, reread `GuestView.ts`; if upstream's client stops falling back to the feed when the HTTP sidebar snapshot is refused, a narrowed person's sidebar stays empty; if upstream adds an asset kind or changes where attachments are named (`orchestration_v2_projection_messages` `$.attachments[].id`, or a turn item's payload), reread `messageAssetLevel`; if upstream reshapes its permissions, reread case 70's level mapping; if upstream changes how its client keys a favicon request or the three asset functions, reread `GuestProjectIcons.ts`, whose test runs upstream's real resolution. -70. Every device belongs to a person, holds its level's permissions, and renews when the level changes ([#535](https://github.com/Jacksondr5/j5code/issues/535), [#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, Jackson's 2026-10-11 approval on [#531](https://github.com/Jacksondr5/j5code/issues/531) of one small edit inside upstream's pairing code, and his 2026-10-17 rulings). A level's permissions are listed in one place, J5-owned `packages/contracts/src/j5/levels.ts` (`LEVEL_PERMISSIONS`), and a device holds its person's highest level's set cut to the ceiling it was paired with (`devicePermissions`). Whose device a session is, and that ceiling, are recorded in J5's own table `j5_a2a_person_session` (J5 migrations 34 and 39) as upstream issues the session, without changing upstream's tables. The person a pairing credential is for is recorded in `j5_a2a_pairing_intent` (migration 39), found again by a hash of the credential because upstream's pairing code holds the credential when it issues a session. `apps/server/src/auth/EnvironmentAuth.ts` carries the edit, at seven sites: one import; two lines in `make` (`const j5TiedToPerson = yield* makePairingSessionIssuer` and `const j5ApprovesMcpClient = yield* makeMcpApprovalCheck`, each read with `Effect.serviceOption`, so upstream's own tests build the layer without them); one pipe step, `j5TiedToPerson(grant, credential)`, on each of the two `sessions.issue` calls that issue a session from a pairing grant (`createBrowserSession` and `exchangeBootstrapCredentialForAccessToken`); and one check in `consumeMcpApprovalCode`, so only a code an Owner's level backs approves an MCP client (`PairingIntents.approvesMcpClient`: not a J5 link's credential, subject `j5:link`, and not one whose intent names someone who is not an Owner); and the message a browser session from another origin is refused with is a named export, `FOREIGN_ORIGIN_DIAGNOSTIC`, so J5's renewal refuses what upstream refuses. Lowering or removing an Owner voids every MCP approval checked before it, however soon after the check it lands, and leaves MCP client sessions already issued alone: J5-owned `McpApproval.layerGatedMcpOAuth` decorates upstream's `McpOAuth` (`apps/server/src/auth/McpOAuth.ts` is not edited), reads which change of Owners it is (`Access.ownersGeneration`, under the same lock as a change of level) before upstream's `approve` checks the approval, ties that to the code in the redirect `approve` returns, and gives it to the exchange of that code; `layerGatedEnvironmentAuth` wraps `issueMcpClientSession` in `Access.issueMcpClient`, which refuses under that lock if the Owners changed since, or if no approval was given to it. In `server.ts`, `McpOAuth.layer` is wrapped in `gateMcpOAuth` where `McpOAuthHttp.layer` is given it (one import and one line). For a credential with no intent the pipe step costs one read by primary key and returns upstream's own effect, and binds the session to the first owner when the credential is the startup link's, the desktop app's or T3 Connect's (`FIRST_OWNER_SUBJECTS`; if upstream mints another credential for the server's own account, add its subject there, or its device is one no one has claimed). For one with an intent it runs upstream's `sessions.issue` and the binding in one transaction (`PairingIntents.issueSession`), so the session and the record of whose it is commit together, and it issues nothing when the credential carries more than its person may hold now, when its person was removed, or when it carries the retired guest subject `j5:guest`. In `apps/server/src/server.ts`, `layerAuth` (case 69) gains one line, `Layer.provideMerge(J5PeopleLive)`, above `layerPersistence`: it gives `PersonAccess` and `PairingIntents` to upstream's `EnvironmentAuth.layer` and to J5's own services. `apps/server/src/auth/http.ts`'s `pairingCredential` handler, which Connections' "Create link" calls, records after `issuePairingCredential` that the link pairs a device for the person whose device made it, under the permissions chosen there (`recordConnectionsLinkCreator`; one import and one call); a link whose maker cannot be recorded is revoked before the request fails. A change of level ends each of the person's sessions for renewal (`Access.ts`): the binding is marked and upstream's `SessionStore.revoke` ends the session, which closes its open sockets at once, in the transaction that changes the level. The device then renews on J5's route `POST /api/j5/session/renew` (`SessionRenewal.ts`, no upstream edit) with its old token: upstream's `SessionStore.verify` checks a token's signature before whether it was revoked and names a revoked token's session, so the route issues a session that holds the new permissions, with the old session's method, subject, client and expiry, only for a session J5 marked, once. `apps/web/src/environments/primary/auth.ts` calls `renewPrimarySession` before its sign-in gate sends a browser to pair (one import and one line), and J5-owned `SessionRenewalWatcher` reloads the page once when the primary connection drops and renewal succeeds. `apps/web/src/connection/runtime.ts` adds J5-owned `@t3tools/client-runtime/j5/session-renewal` to the connection runtime (one import and one line), which renews a saved server's bearer token when its connection is refused for authentication; `packages/client-runtime/package.json` exports it. DPoP sessions, mobile and a device offline past its session's life are paired again by hand; an MCP client holds no person's level, so a change of level does not touch it. The refusal of a browser paired as one person opening a link made for another reaches the pairing page with its reason through three upstream files, each a line or a literal: `packages/contracts/src/environmentHttp.ts` (`EnvironmentAuthInvalidError`'s optional `pairingRefusal: "paired_as_someone_else"`), `apps/server/src/auth/http.ts` (`failEnvironmentAuthInvalid`'s third argument, passed by the `browserSession` handler), and `apps/web/src/environments/primary/auth.ts` (the rejected-credential error's flag). `layerGatedEnvironmentAuth` (case 69's J5-owned decorator) wraps `createBrowserSession` to refuse that before upstream is called, so the link is not used up, and wraps `revokeSession`, `revokeClientSession`, `revokeOtherSessionsExcept` and `revokeOtherClientSessions` so that ending a device cuts it loose from its person first, and with that from any renewal. On a pin advance: if upstream adds another place that turns a pairing grant into a session, it must go through `j5TiedToPerson`, or the device is one no one has claimed; if upstream reshapes its permissions, update `LEVEL_PERMISSIONS` and the definition (`levelPermissions.test.ts` pins each level's set by upstream's names); if upstream adds a method that ends a session, wrap it in the decorator; if upstream changes `SessionStore.verify`'s order of checks or stops naming a revoked token's session, renewal stops working and must be rethought; if upstream adds a pairing path that issues a session from something other than a pairing grant, record whose its sessions are or narrow them; if upstream changes how it refuses a browser session from another origin, keep `FOREIGN_ORIGIN_DIAGNOSTIC` the message it refuses with; if upstream stops returning the code in `approve`'s redirect, or issues an MCP client's session other than from `exchangeCode` through `EnvironmentAuth.issueMcpClientSession`, every MCP sign-in is refused (`McpApproval.test.ts` runs upstream's own sign-in through the gate) and the tie must be rethought; if upstream provides `McpOAuth.layer` somewhere else, wrap it there too. +70. Every device belongs to a person, holds its level's permissions, and renews when the level changes ([#535](https://github.com/Jacksondr5/j5code/issues/535), [#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, Jackson's 2026-10-11 approval on [#531](https://github.com/Jacksondr5/j5code/issues/531) of one small edit inside upstream's pairing code, and his 2026-10-17 rulings). A level's permissions are listed in one place, J5-owned `packages/contracts/src/j5/levels.ts` (`LEVEL_PERMISSIONS`), and a device holds its person's highest level's set cut to the ceiling it was paired with (`devicePermissions`). Whose device a session is, and that ceiling, are recorded in J5's own table `j5_a2a_person_session` (J5 migrations 34 and 39) as upstream issues the session, without changing upstream's tables. The person a pairing credential is for is recorded in `j5_a2a_pairing_intent` (migration 39), found again by a hash of the credential because upstream's pairing code holds the credential when it issues a session. `apps/server/src/auth/EnvironmentAuth.ts` carries the edit, at seven sites: one import; two lines in `make` (`const j5TiedToPerson = yield* makePairingSessionIssuer` and `const j5ApprovesMcpClient = yield* makeMcpApprovalCheck`, each read with `Effect.serviceOption`, so upstream's own tests build the layer without them); one pipe step, `j5TiedToPerson(grant, credential)`, on each of the two `sessions.issue` calls that issue a session from a pairing grant (`createBrowserSession` and `exchangeBootstrapCredentialForAccessToken`); and one check in `consumeMcpApprovalCode`, so only a code an Owner's level backs approves an MCP client (`PairingIntents.approvesMcpClient`: not a J5 link's credential, subject `j5:link`, and not one whose intent names someone who is not an Owner); and the message a browser session from another origin is refused with is a named export, `FOREIGN_ORIGIN_DIAGNOSTIC`, so J5's renewal refuses what upstream refuses. Lowering or removing an Owner voids every MCP approval checked before it, however soon after the check it lands, and ends the MCP clients that Owner approved: J5-owned `McpApproval.layerGatedMcpOAuth` decorates upstream's `McpOAuth` (`apps/server/src/auth/McpOAuth.ts` is not edited), reads which change of Owners it is (`Access.ownersGeneration`, under the same lock as a change of level) and who approves (the person the pairing code's intent names, read before upstream spends it, or the person whose browser session approves) before upstream's `approve` checks the approval, ties both to the code in the redirect `approve` returns, and gives them to the exchange of that code; `layerGatedEnvironmentAuth` wraps `issueMcpClientSession` in `Access.issueMcpClient`, which refuses under that lock if the Owners changed since, or if no approval was given to it, and otherwise records the issued session as its approver's in J5's own table `j5_a2a_mcp_client_approver` (J5 migration 44), keyed by the session id upstream's `SessionStore.verify` reads from the token it issued. Lowering or removing that person as an Owner revokes those sessions upstream in the same transaction. Upstream's MCP sign-in issues no refresh token, so a client's session is never replaced under a new id; an MCP client approved before migration 44, or with a code that names no one (the first owner's), has no approver and is ended by hand. In `server.ts`, `McpOAuth.layer` is wrapped in `gateMcpOAuth` where `McpOAuthHttp.layer` is given it (one import and one line). For a credential with no intent the pipe step costs one read by primary key and returns upstream's own effect, and binds the session to the first owner when the credential is the startup link's, the desktop app's or T3 Connect's (`FIRST_OWNER_SUBJECTS`; if upstream mints another credential for the server's own account, add its subject there, or its device is one no one has claimed). For one with an intent it runs upstream's `sessions.issue` and the binding in one transaction (`PairingIntents.issueSession`), so the session and the record of whose it is commit together, and it issues nothing when the credential carries more than its person may hold now, when its person was removed, or when it carries the retired guest subject `j5:guest`. In `apps/server/src/server.ts`, `layerAuth` (case 69) gains one line, `Layer.provideMerge(J5PeopleLive)`, above `layerPersistence`: it gives `PersonAccess` and `PairingIntents` to upstream's `EnvironmentAuth.layer` and to J5's own services. `apps/server/src/auth/http.ts`'s `pairingCredential` handler, which Connections' "Create link" calls, records after `issuePairingCredential` that the link pairs a device for the person whose device made it, under the permissions chosen there (`recordConnectionsLinkCreator`; one import and one call); a link whose maker cannot be recorded is revoked before the request fails. A change of level ends each of the person's sessions for renewal (`Access.ts`): the binding is marked and upstream's `SessionStore.revoke` ends the session, which closes its open sockets at once, in the transaction that changes the level. The device then renews on J5's route `POST /api/j5/session/renew` (`SessionRenewal.ts`, no upstream edit) with its old token: upstream's `SessionStore.verify` checks a token's signature before whether it was revoked and names a revoked token's session, so the route issues a session that holds the new permissions, with the old session's method, subject, client and expiry, only for a session J5 marked, once. `apps/web/src/environments/primary/auth.ts` calls `renewPrimarySession` before its sign-in gate sends a browser to pair (one import and one line), and J5-owned `SessionRenewalWatcher` reloads the page once when the primary connection drops and renewal succeeds. `apps/web/src/connection/runtime.ts` adds J5-owned `@t3tools/client-runtime/j5/session-renewal` to the connection runtime (one import and one line), which renews a saved server's bearer token when its connection is refused for authentication; `packages/client-runtime/package.json` exports it. DPoP sessions, mobile and a device offline past its session's life are paired again by hand; an MCP client holds no person's level, so a change of level does not touch it, except that lowering or removing an Owner ends the ones they approved. The refusal of a browser paired as one person opening a link made for another reaches the pairing page with its reason through three upstream files, each a line or a literal: `packages/contracts/src/environmentHttp.ts` (`EnvironmentAuthInvalidError`'s optional `pairingRefusal: "paired_as_someone_else"`), `apps/server/src/auth/http.ts` (`failEnvironmentAuthInvalid`'s third argument, passed by the `browserSession` handler), and `apps/web/src/environments/primary/auth.ts` (the rejected-credential error's flag). `layerGatedEnvironmentAuth` (case 69's J5-owned decorator) wraps `createBrowserSession` to refuse that before upstream is called, so the link is not used up, and wraps `revokeSession`, `revokeClientSession`, `revokeOtherSessionsExcept` and `revokeOtherClientSessions` so that ending a device cuts it loose from its person first, and with that from any renewal. On a pin advance: if upstream adds another place that turns a pairing grant into a session, it must go through `j5TiedToPerson`, or the device is one no one has claimed; if upstream reshapes its permissions, update `LEVEL_PERMISSIONS` and the definition (`levelPermissions.test.ts` pins each level's set by upstream's names); if upstream adds a method that ends a session, wrap it in the decorator; if upstream changes `SessionStore.verify`'s order of checks or stops naming a revoked token's session, renewal stops working and must be rethought; if upstream adds a pairing path that issues a session from something other than a pairing grant, record whose its sessions are or narrow them; if upstream changes how it refuses a browser session from another origin, keep `FOREIGN_ORIGIN_DIAGNOSTIC` the message it refuses with; if upstream adds a refresh grant or any other way to renew an MCP client's session under a new id, record the new session as the old one's approver's, or lowering that Owner leaves it live; if upstream stops returning the code in `approve`'s redirect, or issues an MCP client's session other than from `exchangeCode` through `EnvironmentAuth.issueMcpClientSession`, every MCP sign-in is refused (`McpApproval.test.ts` runs upstream's own sign-in through the gate) and the tie must be rethought; if upstream provides `McpOAuth.layer` somewhere else, wrap it there too. 71. An Owner shares from the app ([#535](https://github.com/Jacksondr5/j5code/issues/535), [#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, Jackson's 2026-10-12 design and approval of an appended item in the thread menu, and the 2026-10-17 design review of the one Share dialog). The Share dialog (one for a thread, a project and the server), the link step and their state are J5-owned files under `apps/web/src/j5/sharing/`. Upstream's thread action menu (`apps/web/src/hooks/useThreadActionMenu.ts`, already carrying case 69's one call) gains one import and two calls: the list upstream's `buildThreadActionMenuItems` returns is passed through `withSharingMenuItems(items, threadRef)`, and after the menu closes `if (runSharingMenuAction(clicked.value, threadRef)) return;` opens the dialog J5 asked for and keeps J5's ids away from upstream's switch. `withSharingMenuItems` inserts "Share thread…" after "Copy" (disabled on a device without `access:write`, People and access AC34). For someone who is not an Owner of the thread's server it also leaves out Archive, Delete and "Project settings" (AC14, AC27), leaves out "Mark unread" for a Viewer of the thread (the read marker is everyone's, Shared conversations AC19), and puts "Leave thread" where Archive was when they hold a level on the thread itself (AC48). The ids (`j5:share-thread`, `j5:leave-thread`) are outside upstream's `ThreadActionMenuId` union, and `runSharingMenuAction` is the type guard that takes them back out, so upstream's `components/threadActionMenu.logic.ts` is untouched. `apps/web/src/hooks/useThreadActionMenu.test.ts` carries two J5 cases at its end (the item's place, and that picking it reaches none of upstream's actions). Upstream's sidebar builds and handles the same menu itself (`apps/web/src/components/Sidebar.tsx`, the thread row's right-click): one import, the builder wrapped where the list is built, `buildWithSharingMenuItems(buildThreadActionMenuItems, threadRef)({…})`, which leaves upstream's arguments where they are, and the same `if (runSharingMenuAction(clicked.value, threadRef)) return;` after the menu closes. The dialogs are opened from places that render nothing, so `apps/web/src/routes/__root.tsx` mounts J5's `` beside upstream's `` (one import, one line), the way upstream draws its own confirm and custom-snooze dialogs; the host also draws the name question a server asks before a device uses it (AC5, AC6), renews a session ended for a change of level (case 70), tells an Owner once that links made before the move to levels stopped working, and takes someone off a thread no longer theirs. `apps/web/src/components/CommandPalette.tsx` gains one import, one hook call (`useSharingPaletteItems({ activeThread, projectRef: contextualProjectRef })`, beside where `actionItems` is declared) and `actionItems.push(...sharingPaletteItems)` before the "Project settings" entry, for "Share thread", "Share project", "Share server", "Open People" and "Change your name"; the palette searches an entry's `searchTerms` only, so each entry's title is among its terms (Jackson's 2026-10-12 approval). The web menu draws an item's icon from the table in `apps/web/src/contextMenuFallback.ts`, which gains one entry, `users` (lucide's four shapes, six lines and a comment), so that J5's item lines up with its neighbours. `j5/sharing/sharingMenu.ts` and `sharingDialogs.ts` import nothing of React or the connection runtime, because that test mocks `react`. A link always opens on the server itself; the link step's route choice mirrors helpers that are private to upstream's `apps/web/src/components/settings/ConnectionsSettings.tsx` (`selectPairingEndpoint`'s default, `endpointDefaultPreferenceKey`, `endpointShareHint`), copied into J5-owned `j5/sharing/shareLink.logic.ts` with no upstream edit; what upstream already exports (`isQrShareableEndpoint`, `selectQrEndpointOption`, `pairingUrls.ts`, `QRCodeSvg`, the saved default route in `uiStateStore`) is imported. On a pin advance: compare those helpers with upstream's and carry over any change to how a route is picked or described; if upstream moves `api.contextMenu.show(items, position)` in the hook, re-apply the two calls around it, and the same in the sidebar's thread-row menu; if the palette's `actionItems` list or the root's dialog hosts move, re-apply the append and the mount where they went; if upstream renames the "copy", "archive", "delete", "project-settings" or "mark-unread" items, "Share thread…" falls to the end of the menu or an Owner's item shows to someone who is not one, and `sharingMenu.test.ts` still passes, so check both menus in a browser. 72. Settings › People, and Settings for someone who is not an Owner ([#535](https://github.com/Jacksondr5/j5code/issues/535), [#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, Jackson's 2026-10-12 design and approval of the Settings navigation and route registration, and his 2026-10-17 ruling that Settings is an Owner's). The page (`apps/web/src/j5/sharing/PeoplePage.tsx`) and everything it draws are J5-owned; `apps/web/src/routes/settings.people.tsx` is a J5-owned route file in upstream's routes folder, the shape of `settings.skills.tsx` (case 42), and `routeTree.gen.ts` regenerates with it. Registering a settings section takes upstream's own tables, each one entry: in `apps/web/src/components/settings/settingsSearch.ts` the `SettingsPath` union, `SETTINGS_SECTION_LABELS` (after Connections, which sets the sidebar order), `SETTINGS_CATEGORY_SCOPES` (`"connections"`) and one search item, `people`; in `SettingsSidebarNav.tsx` the icon map (`UsersIcon`); in `SettingsScopeSentence.tsx` one line adding the path to `SETTINGS_DEVICE_ONLY_PATHS`, since the page has its own server picker. Settings is an Owner's (AC27 to AC29), by four calls into J5-owned `j5/sharing/settingsAccess.tsx`, each one import and one or two lines. `SettingsSidebarNav.tsx` builds its list through `useSettingsNavItems(…)` around upstream's own filter: for someone who owns no connected server it keeps only the pages in `PAGES_FOR_EVERYONE` (Appearance, SnapShots, People) and adds Open-source licenses, which upstream reaches only from General, as a page of its own. `useAvailableSettingsSearchItems.ts` returns `useShownSettingsSearchItems(items)`, so search finds the same pages, in the sidebar and the command palette alike. `apps/web/src/routes/settings.tsx` wraps upstream's `SettingsScopeBoundary` and the `` in ``, which shows that person a "Coming soon" notice in place of any other page, one upstream adds later among them, so a link to one (a thread's "Manage scheduled tasks") still lands; the gate is outside the boundary because a server the person does not own leaves the boundary's scope unavailable. `SettingsScopeContext.tsx` and `SettingsScopeSentence.tsx` read their servers through `useOwnedEnvironments(useEnvironments().environments)`, and `useSettingsProjectGroups.ts` its projects through `useOwnedEnvironments(useProjects())`, so Settings lists and changes only the servers and projects the person owns, in the scope picker and the project panel alike; upstream applies a change to every listed server and greys a row unless all of them allow it. `ProjectSettingsPanel.test.tsx` mocks `j5/sharing/settingsAccess` (one comment and four lines), because the test replaces the connection runtime with `undefined` and J5's access atoms are made from it when their module loads. J5's Fleet page and inbox, which name a project from any server, group every server's projects themselves (`j5/logicalProjects.ts`). A server that has not answered yet counts as owned, so an Owner's Settings does not flicker. J5's own Settings pages (Personas, Playbooks, Skills) list only owned servers the same way. The project page carries no Sharing section (AC34). On a pin advance: if upstream reshapes how a settings section is declared, re-register People after Connections; if upstream resolves Settings' servers anywhere besides those two files, filter it there too, or a server the person does not own greys out their Settings; if upstream renames the Appearance or SnapShots path, update `PAGES_FOR_EVERYONE` (its test pins the list); if upstream adds a settings page of its own for people or access, read D33 before keeping J5's. 73. A thread says who reaches it, and the client fits what a person's level lets them do ([#535](https://github.com/Jacksondr5/j5code/issues/535), [#541](https://github.com/Jacksondr5/j5code/issues/541), [#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, Jackson's 2026-10-12 design and approval of one mount or item in each of these files, and his 2026-10-13 approvals of the route files and of the two edits that quiet what could only fail). All of it is J5-owned code under `apps/web/src/j5/sharing/`, mounted once in each upstream file, and it reads what the server says the connection is (`j5.access.getConnectionAccess`, read again when people or levels change) and the level it holds over each thread (`j5.access.subscribeThreadLevel`). `apps/web/src/components/chat/ChatHeader.tsx`: one import and `` after the breadcrumb, for a server thread; it draws nothing unless more than one person reaches the thread. `apps/web/src/components/chat/ThreadDetailsPanel.tsx`: one import and `` after `ThreadRelationshipsPanel`, under the same `density === "full" && !props.draftId` condition as its neighbours; and `const readOnly = !useCanOperateThread(…)` with `&& !readOnly` on the condition that mounts upstream's `ThreadAutomationsPanel`, so a Viewer of the thread sees no Automations. `apps/web/src/components/chat/ChatComposer.tsx`: one import, one hook call after the props are read (`useViewOnlyComposerProps(environmentId, canOperateThread)`), and one spread, `{...viewOnlyComposerProps}`, after upstream's `placeholder={…}` prop, so that someone who is not an Owner and cannot write to the thread reads "You can read this thread, but not send anything to it."; the collapsed composer's fallback literal becomes `(viewOnlyComposerProps.placeholder ?? "Ask anything...")`. The chip and the section ask the server who reaches the thread (`j5.people.listScope`) and ask again when its counter moves (`j5.people.subscribeScopeChanges`). Two route files carry a person's way in. `apps/web/src/routes/pair.tsx`: the import of upstream's `PairingRouteSurface` becomes J5's `JoinLinkPairingSurface`, and the JSX tag changes with it (three lines; upstream's `components/auth/PairingRouteSurface.tsx` is not edited). J5's surface asks `POST /api/j5/links/describe` what a link opens, without spending it, only for a link that carries J5's mark, and waits up to five seconds; everything else gets upstream's surface with the props it was given, and an ordinary pairing token is sent nowhere but upstream's own exchange. The person confirms or types their name and joins on `POST /api/j5/links/join`, which answers with an upstream pairing credential the page exchanges at once. The Share dialog puts the mark, `j5share=1`, in the fragment beside upstream's `token`; upstream reads the fragment as parameters and takes only `token`. `apps/web/src/routes/_chat.index.tsx`: one import, and `` is wrapped in ``, which renders its child at once for anyone at server scope and before the server answers, and for someone who reaches less shows their one thread, a list, or that nothing is shared with them (AC30). `apps/web/src/routes/__root.tsx`: one import, one hook call beside `primaryEnvironmentAuthenticated`, `useFirstRunSetupOffered(primaryEnvironmentAuthenticated)`, and `FirstRunGate`'s `enabled` reads its answer: the wizard is offered only to an Owner of the primary server the server has a name for, by that server's answer, so the name is asked first (AC6), and upstream's gate decides again when the answer arrives; a failed or missing answer offers nothing. `apps/web/src/routes/welcome.tsx`, the wizard's own address, gains one import and two lines before its return, `const setupRefusal = useSetupWizardRefusal(localAvailable); if (setupRefusal !== null) return setupRefusal;`, which draws nothing until the primary server answers and then sends anyone the wizard is not offered to to the first screen, where the name is asked; the hosted app, with no server of its own, is left to upstream. `apps/web/src/components/Sidebar.tsx`: one import, `const isNarrowEverywhere = useIsNarrowEverywhere()` beside the primary environment's id, and `&& !isNarrowEverywhere` on the empty list's `projects.length === 0` condition, so someone who reaches no whole server reads upstream's "No threads yet" in place of an "Add project" button that could only fail. Two more quiet upstream notices a person sees fail (J5-owned `apps/web/src/j5/sharing/upstreamNotices.ts`; Jackson's standing permission on this workstream for one import and one or two lines, used 2026-10-18): `apps/web/src/components/PermissionUpdateNotice.tsx` (one import, one changed line) lists its servers through `useEnvironmentsForPermissionNotice(useEnvironments().environments)`, which leaves out a server that places the connection as a person or a device it will ask about, and one that has not answered yet, as J5 sets and renews those permissions from the person's level, so "Pair again" never applies; its test (`PermissionUpdateNotice.test.tsx`, three added lines as formatted) mocks that hook as passing every server through. `apps/web/src/routes/__root.tsx` (one import, one added and one changed line) mounts `ProviderUpdateLaunchNotification` on `const providerUpdatesShown = useProviderUpdateNoticeShown(primaryEnvironmentAuthenticated)` in place of `primaryEnvironmentAuthenticated`, so the provider updates notice shows only to a connection holding Manage providers. On a pin advance: if upstream moves the composer's `placeholder` prop, keep the spread after it; if upstream renames `PermissionUpdateNotice`'s server list or moves the provider updates mount, filter or gate it where it moved; if upstream reorders the details panel, keep People after Lineage and the condition on the Automations mount; if upstream changes how a pairing address carries its token, or starts to refuse a fragment it does not know, reread `SHARE_LINK_MARK` in J5-owned `packages/contracts/src/j5/sharing.ts`; if upstream renames `PairingRouteSurface` or changes its props, J5's surface fails to compile; if upstream's index route stops rendering `IndexDraftLanding`, re-wrap whatever it renders; if upstream renames `FirstRunGate`'s `enabled`, or decides first run before `enabled` can change, someone who is not an Owner may be offered the wizard. diff --git a/apps/server/src/j5/a2a/Migrations.test.ts b/apps/server/src/j5/a2a/Migrations.test.ts index ca08eb2c40dc1..b4c5e947fd6ae 100644 --- a/apps/server/src/j5/a2a/Migrations.test.ts +++ b/apps/server/src/j5/a2a/Migrations.test.ts @@ -97,6 +97,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () { migration_id: 41, name: "SharedConversation" }, { migration_id: 42, name: "EveryoneHereAsks" }, { migration_id: 43, name: "TaskSchedulers" }, + { migration_id: 44, name: "McpClientApprovers" }, ]); assert.deepStrictEqual( migrationEntries.map(([id, name]) => [id, name]), @@ -144,6 +145,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () [41, "SharedConversation"], [42, "EveryoneHereAsks"], [43, "TaskSchedulers"], + [44, "McpClientApprovers"], ], ); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), @@ -1392,7 +1394,7 @@ it.effect("recreates earlier-shaped crews tables when 14 runs over them", () => applied.map((row) => row.migration_id), [ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 36, 37, 38, 39, 40, 41, 42, 43, + 36, 37, 38, 39, 40, 41, 42, 43, 44, ], ); const memberColumns = yield* sql<{ readonly name: string }>` diff --git a/apps/server/src/j5/a2a/Migrations.ts b/apps/server/src/j5/a2a/Migrations.ts index bd79a2a8609a3..40b8f427319db 100644 --- a/apps/server/src/j5/a2a/Migrations.ts +++ b/apps/server/src/j5/a2a/Migrations.ts @@ -44,6 +44,7 @@ import Migration0040 from "./migrations/040_Links.ts"; import Migration0041 from "./migrations/041_SharedConversation.ts"; import Migration0042 from "./migrations/042_EveryoneHereAsks.ts"; import Migration0043 from "./migrations/043_TaskSchedulers.ts"; +import Migration0044 from "./migrations/044_McpClientApprovers.ts"; export const J5_A2A_MIGRATIONS_TABLE = "j5_a2a_migrations"; @@ -98,6 +99,7 @@ export const migrationEntries = [ [41, "SharedConversation", Migration0041], [42, "EveryoneHereAsks", Migration0042], [43, "TaskSchedulers", Migration0043], + [44, "McpClientApprovers", Migration0044], ] as const; const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/j5/a2a/migrations/044_McpClientApprovers.ts b/apps/server/src/j5/a2a/migrations/044_McpClientApprovers.ts new file mode 100644 index 0000000000000..de3daacb27fb2 --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/044_McpClientApprovers.ts @@ -0,0 +1,23 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +// Who approved an MCP client (People and access, D33): the person whose device or pairing code +// approved it, against the session upstream issued it. Lowering or removing that person as an +// Owner ends the sessions recorded for them. Keyed by upstream's session id, as +// `j5_a2a_person_session` is, rather than a column on upstream's `auth_sessions`. A client +// approved before this, or by a code that names no one, has no row and is ended by hand. +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE TABLE j5_a2a_mcp_client_approver ( + session_id TEXT PRIMARY KEY, + person_id TEXT NOT NULL, + expires_at TEXT NOT NULL + ) + `; + yield* sql` + CREATE INDEX j5_a2a_mcp_client_approver_person + ON j5_a2a_mcp_client_approver (person_id) + `; +}); diff --git a/apps/server/src/j5/sharing/Access.test.ts b/apps/server/src/j5/sharing/Access.test.ts index 888df720303a2..62ba0b6159464 100644 --- a/apps/server/src/j5/sharing/Access.test.ts +++ b/apps/server/src/j5/sharing/Access.test.ts @@ -260,10 +260,14 @@ it.layer(accessLayer)("Access", (it) => { subject: "mcp-client", scopes: [AuthOrchestrationReadScope], }); - yield* access.issueMcpClient(yield* access.ownersGeneration, issueAgent); + const approvedNow = Effect.map(access.ownersGeneration, (generation) => ({ + generation, + approver: owner.personId, + })); + yield* access.issueMcpClient(yield* approvedNow, issueAgent); // Approved, then the Owner is lowered, then the approval is exchanged: refused. - const approved = yield* access.ownersGeneration; + const approved = yield* approvedNow; yield* access.setLevel({ personId: owner.personId, scope: { kind: "server" }, @@ -272,18 +276,66 @@ it.layer(accessLayer)("Access", (it) => { const stale = yield* access.issueMcpClient(approved, issueAgent).pipe(Effect.flip); assert.strictEqual(stale._tag, "StaleMcpApprovalError"); // One approved after the change issues, however soon. - yield* access.issueMcpClient(yield* access.ownersGeneration, issueAgent); + yield* access.issueMcpClient(yield* approvedNow, issueAgent); const other = yield* person("Owner who leaves", [ { scope: { kind: "server" }, level: "owner" }, ]); - const beforeRemoval = yield* access.ownersGeneration; + const beforeRemoval = { generation: yield* access.ownersGeneration, approver: null }; yield* access.removePerson(other.personId); const removed = yield* access.issueMcpClient(beforeRemoval, issueAgent).pipe(Effect.flip); assert.strictEqual(removed._tag, "StaleMcpApprovalError"); }), ); + it.effect("ends the MCP clients a lowered or removed Owner approved, and no one else's", () => + Effect.gen(function* () { + const access = yield* Access; + const sessions = yield* SessionStore.SessionStore; + const owner = (name: string) => person(name, [{ scope: { kind: "server" }, level: "owner" }]); + const approve = (approver: PersonAccess.Person | null) => + Effect.gen(function* () { + const issued = yield* access.issueMcpClient( + { generation: yield* access.ownersGeneration, approver: approver?.personId ?? null }, + sessions.issue({ subject: "mcp-client", scopes: [AuthOrchestrationReadScope] }), + ); + return issued.sessionId; + }); + const lowered = yield* owner("Owner who is lowered"); + const staying = yield* owner("Owner who stays"); + const removed = yield* owner("Owner who is removed"); + const loweredClient = yield* approve(lowered); + const stayingClient = yield* approve(staying); + const removedClient = yield* approve(removed); + // Approved before approvers were recorded, or by a code that names no one. + const unrecordedClient = yield* approve(null); + const waiting = { generation: yield* access.ownersGeneration, approver: staying.personId }; + + yield* access.setLevel({ + personId: lowered.personId, + scope: { kind: "server" }, + level: "collaborator", + }); + assert.isFalse(yield* isLive(loweredClient)); + assert.isTrue(yield* isLive(stayingClient)); + assert.isTrue(yield* isLive(removedClient)); + assert.isTrue(yield* isLive(unrecordedClient)); + // Still waiting when the Owners changed: refused, whoever approved it. + const stale = yield* access + .issueMcpClient( + waiting, + sessions.issue({ subject: "mcp-client", scopes: [AuthOrchestrationReadScope] }), + ) + .pipe(Effect.flip); + assert.strictEqual(stale._tag, "StaleMcpApprovalError"); + + yield* access.removePerson(removed.personId); + assert.isFalse(yield* isLive(removedClient)); + assert.isTrue(yield* isLive(stayingClient)); + assert.isTrue(yield* isLive(unrecordedClient)); + }), + ); + it.effect("renews at startup every device whose permissions its level does not give", () => Effect.gen(function* () { const access = yield* Access; diff --git a/apps/server/src/j5/sharing/Access.ts b/apps/server/src/j5/sharing/Access.ts index 960a48b4ad099..fef0ebe0b3088 100644 --- a/apps/server/src/j5/sharing/Access.ts +++ b/apps/server/src/j5/sharing/Access.ts @@ -86,6 +86,16 @@ export class StaleMcpApprovalError extends Schema.TaggedError; /** - * Issues an MCP client's session approved at `generation`, unless an Owner was lowered or - * removed since: the approval may have been an Owner's who is not one now, and is refused to be - * approved again. Held under the same lock as a change of level, so the two never cross. + * Issues an MCP client's session, unless an Owner was lowered or removed since its approval was + * checked: the approval may have been an Owner's who is not one now, and is refused to be + * approved again. The session is recorded as its approver's, so lowering or removing them as an + * Owner ends it. Held under the same lock as a change of level, so the two never cross. */ - readonly issueMcpClient: ( - generation: number, + readonly issueMcpClient: < + A extends { readonly token: string; readonly expiresAt: DateTime.DateTime }, + E, + R, + >( + approval: McpClientApproval, issue: Effect.Effect, ) => Effect.Effect; } @@ -289,12 +304,50 @@ const make = Effect.gen(function* () { const ownersGeneration = yield* Ref.make(0); /** - * Every MCP approval not yet issued, voided: it may have been an Owner's who is not one now. - * MCP clients already issued keep their sessions; ending only those the lowered Owner approved - * is Later. + * Every MCP approval not yet issued, voided, whoever gave it: it may have been an Owner's who + * is not one now, and the Owners who remain approve it again. */ const voidWaitingMcpApprovals = Ref.update(ownersGeneration, (generation) => generation + 1); + const mcpStorage = (operation: string) => (cause: unknown) => + new PersonAccessStorageError({ operation, cause }); + + /** Records an issued MCP client's session as `personId`'s, and forgets those since expired. */ + const recordMcpApprover = Effect.fn("j5.sharing.access.recordMcpApprover")(function* ( + personId: ParticipantId, + issued: { readonly token: string; readonly expiresAt: DateTime.DateTime }, + ) { + const { sessionId } = yield* sessions + .verify(issued.token) + .pipe(Effect.mapError(mcpStorage("read the MCP client's session"))); + const now = DateTime.formatIso(yield* DateTime.now); + yield* sql` + DELETE FROM j5_a2a_mcp_client_approver WHERE expires_at <= ${now} + `.pipe(Effect.mapError(mcpStorage("forget expired MCP clients"))); + yield* sql` + INSERT INTO j5_a2a_mcp_client_approver (session_id, person_id, expires_at) + VALUES (${sessionId}, ${personId}, ${DateTime.formatIso(issued.expiresAt)}) + `.pipe(Effect.mapError(mcpStorage("record who approved an MCP client"))); + }); + + /** + * Ends the MCP clients `personId` approved, in the transaction that lowers or removes them. A + * session already ended or expired is passed over. + */ + const endApprovedMcpClients = Effect.fn("j5.sharing.access.endApprovedMcpClients")(function* ( + personId: ParticipantId, + ) { + const approved = yield* sql<{ readonly session_id: AuthSessionId }>` + DELETE FROM j5_a2a_mcp_client_approver WHERE person_id = ${personId} + RETURNING session_id + `.pipe(Effect.mapError(mcpStorage("read the MCP clients a person approved"))); + for (const { session_id: sessionId } of approved) { + yield* sessions + .revoke(sessionId) + .pipe(Effect.mapError(mcpStorage("end an MCP client a person approved"))); + } + }); + /** * Runs a change to one person and renews whichever of their devices it requires, all in one * transaction; then tells subscribers. @@ -315,7 +368,10 @@ const make = Effect.gen(function* () { yield* revokeForRenewal(device.sessionId); } } - if (before.owner && !after.owner) yield* voidWaitingMcpApprovals; + if (before.owner && !after.owner) { + yield* voidWaitingMcpApprovals; + yield* endApprovedMcpClients(personId); + } return result; }), ).pipe(Effect.tap(() => tell({ personId, kind: "reach" }))); @@ -381,6 +437,7 @@ const make = Effect.gen(function* () { } yield* afterChange(personId); if (owner) yield* voidWaitingMcpApprovals; + yield* endApprovedMcpClients(personId); }), ); yield* tell({ personId, kind: "removed" }); @@ -446,13 +503,15 @@ const make = Effect.gen(function* () { ownersGeneration: committed(Ref.get(ownersGeneration)), - issueMcpClient: (generation, issue) => + issueMcpClient: (approval, issue) => committed( Effect.gen(function* () { - if ((yield* Ref.get(ownersGeneration)) !== generation) { + if ((yield* Ref.get(ownersGeneration)) !== approval.generation) { return yield* new StaleMcpApprovalError({}); } - return yield* issue; + const issued = yield* issue; + if (approval.approver !== null) yield* recordMcpApprover(approval.approver, issued); + return issued; }), ), }); diff --git a/apps/server/src/j5/sharing/AccessGate.ts b/apps/server/src/j5/sharing/AccessGate.ts index 386116cdf3ef2..405dc704954d1 100644 --- a/apps/server/src/j5/sharing/AccessGate.ts +++ b/apps/server/src/j5/sharing/AccessGate.ts @@ -51,7 +51,7 @@ import { peopleLayer as peopleRecordsLayer, } from "./PairingIntents.ts"; import { layer as linksLayer } from "./Links.ts"; -import { McpApprovalGeneration } from "./McpApproval.ts"; +import { McpExchangeApproval } from "./McpApproval.ts"; import { layer as peopleLayer } from "./People.ts"; import { type MessageAsset, @@ -605,15 +605,16 @@ export const layerGatedEnvironmentAuth = Layer.effect( inner.revokeOtherClientSessions(currentSessionId), ), // An MCP client is approved by an Owner; one approved before an Owner was lowered or - // removed is refused its session, and approved again (`Access.issueMcpClient`). Upstream - // issues one only from an exchange `McpApproval` gave the approval's generation to. + // removed is refused its session, and approved again, and one issued is recorded as its + // approver's (`Access.issueMcpClient`). Upstream issues one only from an exchange + // `McpApproval` gave the approval to. issueMcpClientSession: (input) => - Effect.serviceOption(McpApprovalGeneration).pipe( + Effect.serviceOption(McpExchangeApproval).pipe( Effect.flatMap( Option.match({ onNone: () => Effect.fail(new StaleMcpApprovalError({})), - onSome: (generation) => - changes.issueMcpClient(generation, inner.issueMcpClientSession(input)), + onSome: (approval) => + changes.issueMcpClient(approval, inner.issueMcpClientSession(input)), }), ), Effect.mapError((cause) => diff --git a/apps/server/src/j5/sharing/McpApproval.test.ts b/apps/server/src/j5/sharing/McpApproval.test.ts index 572056c204c87..a78d3289928b1 100644 --- a/apps/server/src/j5/sharing/McpApproval.test.ts +++ b/apps/server/src/j5/sharing/McpApproval.test.ts @@ -14,7 +14,8 @@ import { Access } from "./Access.ts"; import * as AccessGate from "./AccessGate.ts"; import { gateMcpOAuth } from "./McpApproval.ts"; import { PairingIntents } from "./PairingIntents.ts"; -import { accessLayer, person } from "./test-support/accessHarness.ts"; +import type { Person } from "./PersonAccess.ts"; +import { accessLayer, device, person } from "./test-support/accessHarness.ts"; const urls = { issuer: "https://j5.test", resource: "https://j5.test/mcp" }; const redirectUri = "http://localhost/callback"; @@ -22,105 +23,179 @@ const verifier = `${"a".repeat(43)}-verifier-for-tests`; const challenge = "DeB41nTVkPwpbbYecrnqtVq7VXLezustdHAK4SWt13c"; const request = HttpServerRequest.fromWeb(new Request("https://j5.test/oauth/mcp/token")); +/** + * Upstream's own MCP sign-in behind J5's gate, over the real stores, with upstream's + * `EnvironmentAuth` checks as the two approval paths run them. `beforeCodeSpent` runs once the + * pairing-code path has passed its checks. + */ +const signIn = Effect.gen(function* () { + const sessions = yield* SessionStore.SessionStore; + const grants = yield* PairingGrantStore.PairingGrantStore; + const intents = yield* PairingIntents; + const hooks = { + beforeCodeSpent: Effect.void as Effect.Effect, + browser: undefined as EnvironmentAuth.AuthenticatedSession | undefined, + }; + const upstreamAuth = Layer.mock(EnvironmentAuth.EnvironmentAuth)({ + consumeMcpApprovalCode: (code) => + Effect.gen(function* () { + const grant = yield* grants.consume(code).pipe(Effect.orDie); + assert.isTrue(yield* intents.approvesMcpClient(grant, code).pipe(Effect.orDie)); + yield* hooks.beforeCodeSpent; + }), + authenticateBrowserSession: () => + hooks.browser === undefined + ? Effect.fail(new EnvironmentAuth.ServerAuthMissingCredentialError({})) + : Effect.succeed(hooks.browser), + issueMcpClientSession: (input) => + sessions + .issue({ + subject: "mcp-client", + method: "bearer-access-token", + scopes: EnvironmentAuth.mcpClientScopes(input.access), + }) + .pipe(Effect.orDie), + }); + const oauth = yield* McpOAuth.McpOAuth.pipe( + Effect.provide( + gateMcpOAuth(McpOAuth.layer).pipe( + Layer.provide(AccessGate.layerGatedEnvironmentAuth.pipe(Layer.provide(upstreamAuth))), + Layer.provide( + Layer.mock(ServerSecretStore.ServerSecretStore)({ + getOrCreateRandom: () => Effect.succeed(new Uint8Array(32).fill(1)), + }), + ), + ), + ), + ); + const client = yield* oauth.register({ client_name: "Agent", redirect_uris: [redirectUri] }); + const authorization = yield* oauth.validateAuthorization({ + urls, + request: { + response_type: "code", + client_id: client.clientId, + redirect_uri: redirectUri, + code_challenge: challenge, + code_challenge_method: "S256", + resource: urls.resource, + }, + }); + const codeOf = (redirect: string) => new URL(redirect).searchParams.get("code")!; + const approveWithCode = Effect.fn(function* (approver: Person) { + const link = yield* grants.issueOneTimeToken({ + subject: "one-time-token", + scopes: LEVEL_PERMISSIONS.owner, + }); + yield* intents.record({ + pairingLinkId: link.id, + credential: link.credential, + personId: approver.personId, + linkId: null, + ceiling: null, + }); + return codeOf( + yield* oauth.approve({ + request, + authorization, + decision: { _tag: "pairing-code", access: "full-access", code: link.credential }, + }), + ); + }); + const approveWithBrowser = Effect.fn(function* (approver: Person) { + const laptop = yield* device(approver.personId, LEVEL_PERMISSIONS.owner); + hooks.browser = { + sessionId: laptop.sessionId, + subject: "one-time-token", + method: "browser-session-cookie", + scopes: LEVEL_PERMISSIONS.owner, + }; + const session = yield* oauth.approvingBrowserSession(request, authorization); + assert.isDefined(session); + return codeOf( + yield* oauth.approve({ + request, + authorization, + decision: { + _tag: "browser-session", + access: "full-access", + csrfToken: session?.csrfToken ?? "", + }, + }), + ); + }); + const exchange = (code: string) => + oauth.exchangeCode({ + request, + urls, + token: { + grant_type: "authorization_code", + code, + redirect_uri: redirectUri, + client_id: client.clientId, + code_verifier: verifier, + resource: urls.resource, + }, + }); + return { hooks, approveWithCode, approveWithBrowser, exchange }; +}); + +const isRevoked = (token: string) => + SessionStore.SessionStore.use((sessions) => + sessions + .verify(token) + .pipe( + Effect.as(false), + Effect.catchTags({ SessionTokenRevokedError: () => Effect.succeed(true) }), + ), + ); + it.layer(accessLayer)("MCP approval", (it) => { it.effect("refuses a code an Owner approved just before they were lowered", () => Effect.gen(function* () { const access = yield* Access; const sessions = yield* SessionStore.SessionStore; - const grants = yield* PairingGrantStore.PairingGrantStore; - const intents = yield* PairingIntents; + const { hooks, approveWithCode, exchange } = yield* signIn; const owner = yield* person("Owner approving an agent", [ { scope: { kind: "server" }, level: "owner" }, ]); - let lowerOnceChecked = false; - // Upstream's checks, as the pairing-code path runs them, over the real stores. - const upstreamAuth = Layer.mock(EnvironmentAuth.EnvironmentAuth)({ - consumeMcpApprovalCode: (code) => - Effect.gen(function* () { - const grant = yield* grants.consume(code).pipe(Effect.orDie); - assert.isTrue(yield* intents.approvesMcpClient(grant, code).pipe(Effect.orDie)); - if (lowerOnceChecked) { - yield* access - .setLevel({ personId: owner.personId, scope: { kind: "server" }, level: "viewer" }) - .pipe(Effect.orDie); - yield* TestClock.adjust("10 millis"); - } - }), - issueMcpClientSession: (input) => - sessions - .issue({ - subject: "mcp-client", - method: "bearer-access-token", - scopes: EnvironmentAuth.mcpClientScopes(input.access), - }) - .pipe(Effect.orDie), - }); - const oauth = yield* McpOAuth.McpOAuth.pipe( - Effect.provide( - gateMcpOAuth(McpOAuth.layer).pipe( - Layer.provide(AccessGate.layerGatedEnvironmentAuth.pipe(Layer.provide(upstreamAuth))), - Layer.provide( - Layer.mock(ServerSecretStore.ServerSecretStore)({ - getOrCreateRandom: () => Effect.succeed(new Uint8Array(32).fill(1)), - }), - ), - ), - ), - ); - const client = yield* oauth.register({ client_name: "Agent", redirect_uris: [redirectUri] }); - const authorization = yield* oauth.validateAuthorization({ - urls, - request: { - response_type: "code", - client_id: client.clientId, - redirect_uri: redirectUri, - code_challenge: challenge, - code_challenge_method: "S256", - resource: urls.resource, - }, - }); - const approve = Effect.gen(function* () { - const link = yield* grants.issueOneTimeToken({ - subject: "one-time-token", - scopes: LEVEL_PERMISSIONS.owner, - }); - yield* intents.record({ - pairingLinkId: link.id, - credential: link.credential, - personId: owner.personId, - linkId: null, - ceiling: null, - }); - const redirect = yield* oauth.approve({ - request, - authorization, - decision: { _tag: "pairing-code", access: "full-access", code: link.credential }, - }); - return new URL(redirect).searchParams.get("code")!; - }); - const exchange = (code: string) => - oauth.exchangeCode({ - request, - urls, - token: { - grant_type: "authorization_code", - code, - redirect_uri: redirectUri, - client_id: client.clientId, - code_verifier: verifier, - resource: urls.resource, - }, - }); - const issued = yield* exchange(yield* approve); + const issued = yield* exchange(yield* approveWithCode(owner)); assert.strictEqual((yield* sessions.verify(issued.access_token)).subject, "mcp-client"); // The approval passes its checks, the Owner is lowered, the code is minted 10ms later and // exchanged just inside its life. - lowerOnceChecked = true; - const raced = yield* approve; + hooks.beforeCodeSpent = Effect.gen(function* () { + yield* access + .setLevel({ personId: owner.personId, scope: { kind: "server" }, level: "viewer" }) + .pipe(Effect.orDie); + yield* TestClock.adjust("10 millis"); + }); + const raced = yield* approveWithCode(owner); yield* TestClock.adjust("59995 millis"); assert.strictEqual((yield* exchange(raced).pipe(Effect.flip)).error, "invalid_grant"); }), ); + + it.effect("ends the clients an Owner approved, by code or browser, when they are lowered", () => + Effect.gen(function* () { + const access = yield* Access; + const { approveWithCode, approveWithBrowser, exchange } = yield* signIn; + const owner = (name: string) => person(name, [{ scope: { kind: "server" }, level: "owner" }]); + const lowered = yield* owner("Owner who is lowered"); + const staying = yield* owner("Owner who stays"); + + const byCode = yield* exchange(yield* approveWithCode(lowered)); + const byBrowser = yield* exchange(yield* approveWithBrowser(lowered)); + const others = yield* exchange(yield* approveWithBrowser(staying)); + yield* access.setLevel({ + personId: lowered.personId, + scope: { kind: "server" }, + level: "collaborator", + }); + + assert.isTrue(yield* isRevoked(byCode.access_token)); + assert.isTrue(yield* isRevoked(byBrowser.access_token)); + assert.isFalse(yield* isRevoked(others.access_token)); + }), + ); }); diff --git a/apps/server/src/j5/sharing/McpApproval.ts b/apps/server/src/j5/sharing/McpApproval.ts index 4dcd680ca5527..21ad5df1243ca 100644 --- a/apps/server/src/j5/sharing/McpApproval.ts +++ b/apps/server/src/j5/sharing/McpApproval.ts @@ -4,17 +4,20 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; +import * as EnvironmentAuth from "../../auth/EnvironmentAuth.ts"; import * as McpOAuth from "../../auth/McpOAuth.ts"; -import { Access } from "./Access.ts"; +import { Access, type McpClientApproval } from "./Access.ts"; +import { PairingIntents } from "./PairingIntents.ts"; +import { PersonAccess } from "./PersonAccess.ts"; /** - * The change of the server's Owners an MCP client's approval was checked against, given to the - * exchange of its code. Upstream's exchange then issues the session through the access gate, - * which refuses it if the Owners changed since (`Access.issueMcpClient`). An issue with none is - * refused. + * What an MCP client's approval was checked against, and who gave it, given to the exchange of + * its code. Upstream's exchange then issues the session through the access gate, which refuses + * it if the Owners changed since and records it as the approver's (`Access.issueMcpClient`). An + * issue with none is refused. */ -export class McpApprovalGeneration extends Context.Service()( - "t3/j5/sharing/McpApproval/McpApprovalGeneration", +export class McpExchangeApproval extends Context.Service()( + "t3/j5/sharing/McpApproval/McpExchangeApproval", ) {} /** @@ -26,27 +29,43 @@ const KEPT_MS = 10 * 60_000; /** * Upstream's MCP sign-in with each approval tied to its code. The generation is read before * upstream checks the approval, so a change of Owners after the read, however soon, voids it. + * The approver is read before upstream spends a pairing code: the person the code was made for, + * or the person whose browser approves. */ export const layerGatedMcpOAuth = Layer.effect( McpOAuth.McpOAuth, Effect.gen(function* () { const inner = yield* McpOAuth.McpOAuth; const access = yield* Access; + const auth = yield* EnvironmentAuth.EnvironmentAuth; + const people = yield* PersonAccess; + const intents = yield* PairingIntents; const approved = yield* Ref.make( - new Map(), + new Map(), ); + const approverOf = Effect.fn("j5.sharing.mcpApproval.approverOf")(function* ( + input: Parameters[0], + ) { + if (input.decision._tag === "pairing-code") { + return (yield* intents.intentOf(input.decision.code))?.personId ?? null; + } + return yield* auth.authenticateBrowserSession(input.request).pipe( + Effect.flatMap((session) => people.sessionReach(session)), + Effect.map((reach) => (reach.kind === "person" ? reach.person.personId : null)), + // Upstream's approve refuses a browser that is not signed in. + Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, () => Effect.succeed(null)), + ); + }); return McpOAuth.McpOAuth.of({ ...inner, approve: (input) => Effect.gen(function* () { - const generation = yield* access.ownersGeneration.pipe( - Effect.mapError( - () => - new McpOAuth.McpOAuthPageError({ - description: "The approval could not be checked. Try again.", - }), - ), - ); + const unchecked = () => + new McpOAuth.McpOAuthPageError({ + description: "The approval could not be checked. Try again.", + }); + const generation = yield* access.ownersGeneration.pipe(Effect.mapError(unchecked)); + const approver = yield* approverOf(input).pipe(Effect.mapError(unchecked)); const redirect = yield* inner.approve(input); const code = new URL(redirect).searchParams.get("code"); const now = yield* Clock.currentTimeMillis; @@ -55,7 +74,7 @@ export const layerGatedMcpOAuth = Layer.effect( const next = new Map( Array.from(current).filter(([, entry]) => now - entry.atMs < KEPT_MS), ); - next.set(code, { generation, atMs: now }); + next.set(code, { generation, approver, atMs: now }); return next; }); } @@ -77,12 +96,20 @@ export const layerGatedMcpOAuth = Layer.effect( const exchange = inner.exchangeCode(input); return yield* entry === undefined ? exchange - : exchange.pipe(Effect.provideService(McpApprovalGeneration, entry.generation)); + : exchange.pipe( + Effect.provideService(McpExchangeApproval, { + generation: entry.generation, + approver: entry.approver, + }), + ); }), }); }), ); -/** Upstream's MCP sign-in, `upstream`, behind J5's approval check. Needs `Access`. */ +/** + * Upstream's MCP sign-in, `upstream`, behind J5's approval check. Needs `Access`, `PersonAccess` + * and `PairingIntents`. + */ export const gateMcpOAuth = (upstream: Layer.Layer) => layerGatedMcpOAuth.pipe(Layer.provide(upstream)); diff --git a/docs/j5/product/upstream.md b/docs/j5/product/upstream.md index 8e852562a978b..12fead210d11c 100644 --- a/docs/j5/product/upstream.md +++ b/docs/j5/product/upstream.md @@ -377,7 +377,7 @@ Each advance checks for new upstream reads of `T3CODE_HOME` or `.t3` paths and n **J5:** each device belongs to a person, and the person's scope and level decide what it reaches ([People and access](features/people-and-access.md)). -- **Who a device is** is recorded by J5 against upstream's session as it is issued, without changing upstream's tables. Sessions that are no person's device are left as upstream issues them and are not narrowed: those of peer servers, of `j5 a2a` machine senders, of MCP clients and of the CLI's `auth session issue`. MCP clients are approved only by an Owner, and lowering or removing an Owner refuses an approval still waiting to be exchanged, for the remaining Owners to approve again. Ending the MCP clients a lowered or removed Owner approved is Later ([#639](https://github.com/Jacksondr5/j5code/issues/639)). +- **Who a device is** is recorded by J5 against upstream's session as it is issued, without changing upstream's tables. Sessions that are no person's device are left as upstream issues them and are not narrowed: those of peer servers, of `j5 a2a` machine senders, of MCP clients and of the CLI's `auth session issue`. MCP clients are approved only by an Owner. Lowering or removing an Owner ends the MCP clients that Owner approved, and refuses any approval still waiting to be exchanged, for the remaining Owners to approve again. An MCP client approved before J5 recorded who approved it keeps working until an Owner ends it. - **A device holds exactly its person's level's permissions**, mapped onto upstream's in one place. When the level changes, J5 revokes the device's session. The device then renews it on J5's own route, proving itself with the old token, and gets a session holding the new permissions. J5 never hands upstream more permissions for a request than the device holds. - **A person whose scope is narrower than the server** has a connection narrowed to it: - every HTTP route and WebSocket request is refused unless J5 has listed it; @@ -411,7 +411,7 @@ Each advance checks for new upstream reads of `T3CODE_HOME` or `.t3` paths and n - **A lowered level reaches an open socket at once,** because upstream closes a session's sockets when it is revoked, replaced or expires. - **A change of level makes the person's devices reconnect once.** -- **A device offline past its session's lifetime is paired again by hand** after a change of level. An MCP client holds no person's level, so a change of level does not touch it. +- **A device offline past its session's lifetime is paired again by hand** after a change of level. An MCP client holds no person's level, so a change of level does not touch it, except that lowering or removing an Owner ends the MCP clients they approved. - **Each advance checks four things:** - whether upstream added a place that sends configuration, lifecycle events or sidebar items; - whether every route still signs in through the functions J5 wraps; @@ -603,3 +603,4 @@ J5 kept a run from resuming after a usage-limit reset when the person had presse - 2026-10-19 — D37 added: a connection that keeps failing can be retried at once on web and desktop (Jackson). - 2026-10-24 — D38 added: a completion sound can be a local MP3 on web and desktop (proposed by Abraham, accepted by Jackson). - 2026-10-20 — D2 clarifies that native-question answers retain upstream access and attribution behavior, and placed-agent notices replace raw thread waiting ([#674](https://github.com/Jacksondr5/j5code/pull/674), [#281](https://github.com/Jacksondr5/j5code/issues/281), [existing access decision](https://github.com/Jacksondr5/j5code/issues/345#issuecomment-6092125478)). +- 2026-10-24 — D33: lowering or removing an Owner ends the MCP clients that Owner approved, and only those (Jackson; [#639](https://github.com/Jacksondr5/j5code/issues/639)). From 32bf7558351a082446e46c4f9fabba5639cc3c55 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Sun, 25 Oct 2026 00:07:51 -0400 Subject: [PATCH 2/4] fix(j5): a link made as its maker is removed approves no MCP client A Connections link minted by an Owner who was removed before J5 recorded whose it was read as made by no one, so its code could approve an MCP client with no approver. `recordForCreator` now refuses a maker that is no one's and no longer live; upstream's handler then revokes the link. Co-Authored-By: Claude Opus 5.5 --- FORK.md | 2 +- .../src/j5/sharing/PairingIntents.test.ts | 36 +++++++++++++- apps/server/src/j5/sharing/PairingIntents.ts | 48 ++++++++++++------- 3 files changed, 68 insertions(+), 18 deletions(-) diff --git a/FORK.md b/FORK.md index a1c98e86c6f9a..551de3143436a 100644 --- a/FORK.md +++ b/FORK.md @@ -430,7 +430,7 @@ migrations after upstream migrations. 68. The web testing skill matches what works on a headless host ([#546](https://github.com/Jacksondr5/j5code/issues/546), Jackson's 2026-10-11 decision: follow upstream's Browser panel, and edit its skill in place). `.agents/skills/test-t3-app/SKILL.md` keeps upstream's structure and voice. J5's edits: the state paths are `.j5code` and `~/.j5code/userdata`; the start command unsets the inherited port, host and home variables (see `AGENTS.md`); "Start the app" points at J5's `j5-live-test` skill; and "Use the Browser panel" is rewritten as the steps that worked when the panel was driven end to end on 2026-10-11 (open before judging availability, wait after pairing and after each move, read with `preview_evaluate`, retry once after a timeout, save screenshots at 1280x800, and which callers may act). Each step answers a failure seen in a test run; steps agents already get right are left out. J5's own testing practice is not in this file: it lives in J5-owned `.agents/skills/j5-live-test/`. On a pin advance, read upstream's changes to this skill and port them; if upstream documents the same panel steps, take upstream's wording and keep only the J5 paths and the `j5-live-test` pointer. 69. A connection whose person's scope is narrower than the server is narrowed to it ([#532](https://github.com/Jacksondr5/j5code/issues/532), [#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, Jackson's 2026-10-09, 2026-10-11 and 2026-10-17 decisions). Upstream's permissions are per connection and cover the whole server. J5 reads, for each session, whose device it is (J5-owned `apps/server/src/j5/sharing/PersonAccess.ts`, `sessionReach`): a person's, by the binding case 70 records as the session is issued; the first owner's, by the subjects of the startup link, the desktop app, T3 Connect (`cloud-connect`, which upstream mints only for the cloud account the server is linked to) and the development credential; a service's (`peer:*`, `machine:*`, `mcp-client`, `cli-issued-session`); or a device no one has claimed. A service session and a person who holds Collaborator or Owner at server scope are wide and get upstream's own answers, the same objects. Everyone else is narrowed: a person at a project or a thread at either level, a Viewer at server scope, and an unclaimed device. A narrowed session is refused everything but an allow-list, every listed request is checked against the level the person holds at the scope it names, and the answers that name the host are reduced. All of it is J5-owned code under `apps/server/src/j5/sharing/`, reached from two upstream server files. In `apps/server/src/server.ts`, `layerAuth` is upstream's `EnvironmentAuth.layer` wrapped in `gateEnvironmentAuth` (`AccessGate.ts`): a narrowed session keeps its permissions only on the routes `accessHttpRule` allows (`/ws`, a reachable thread's loads, and J5's artifact read for a reachable project), so every other route's own permission check refuses it. In `apps/server/src/ws.ts`, the per-connection `RpcAuthorization.layer` is wrapped in `layerRpcAuthorization`, which refuses a narrowed session every request not in `ACCESS_RPC_RULES` and checks each listed one: at a thread or project the payload names, at the level given (`thread`, `project`); for a person who holds Collaborator anywhere, whatever folder it names (`collaborator`: files, terminals' folders, git, previews' profiles, the host's devices; a terminal or an agent reaches every folder anyway, Jackson 2026-10-17), and the server's Playbook library, read only (AC20); for anyone (`anyone`: what a client reports of itself); for a person with a level at server scope (`server`: the Fleet page, Personas, the providers' skills, every Playbook run, read only); or answered narrowly by its handler (`narrowed`). Upstream's own permission check runs after J5's on every request, so what a level's permissions lack (settings, providers, access, relay management, environment maintenance) is refused by upstream. A request still running is ended when the person's reach changes so that it no longer meets its rule (`PersonAccess.subscribeChanges`). Whether a session is wide is read once, when the socket opens; a change that would alter it renews the session (case 70). `layerWsRpc` reads `connectionView(currentSession)` (`GuestView.ts`) once, and six handlers pass their answer through it: `server.getConfig` (`Effect.map(j5View.config)`), `subscribeServerConfig` (`.pipe(j5View.configStream)`), `subscribeServerLifecycle` (`.pipe(j5View.lifecycleStream)`), `orchestration.subscribeShell` (`j5View.shellStream` around upstream's `subscribeOrchestrationV2Shell`), and `scheduledTasks.list` and `scheduledTasks.subscribe` (`j5View.scheduledTasks`, `j5View.scheduledTasksStream`), which list a narrowed person only the tasks bound to a thread they reach or, for a task bound to no thread, its project's, and give a Viewer no webhook address. The configuration is reduced for a Viewer and an unclaimed device (AC24) and given whole to a narrowed Collaborator, who can open a terminal on the host; the lifecycle welcome is reduced and the sidebar filtered for every narrowed session, and a Viewer's projects and threads carry placeholder folders where a Collaborator's carry the real ones. `apps/server/src/orchestration-v2/http.ts` is upstream's file: the HTTP sidebar snapshot (`GET /api/orchestration/shell`) is refused to a narrowed session, and upstream's client then reads the sidebar from the socket's feed (`packages/client-runtime/src/state/shell.ts` falls back when the HTTP load fails), so the feed is the one filtered path. A Viewer may ask `assets.createUrl` for an attachment or a tool's image only when `PersonAccess.messageAssetLevel` finds it in a thread they reach: in a message's attachments, or in a turn item's output, where a page a tool published is named; a Collaborator may ask for any asset. A favicon reaches a narrowed person through J5 and never by a host path (Jackson's 2026-10-12 decision; `GuestProjectIcons.ts`, no upstream edit): a reduced project carries `guestIconPath(projectId)` as its `faviconPath`, `ACCESS_RPC_RULES` reads the project id from a `project-favicon` request's `path`, checks `PersonAccess.projectInFeed`, and answers in place of upstream's handler with a link to `GET /api/j5/sharing/project-icon//`, signed with J5's own key, which serves the file through upstream's exported `issueAssetUrl`, `resolveAsset` and `assetFileResponse`. Both allow-lists refuse by default, so a route or request upstream adds is closed to a narrowed session until J5 lists it; `ACCESS_RPC_RULES` is keyed by the RPC group's method names, so a method upstream renames or removes fails to compile. The reduced configuration is built field by field (`reduceServerConfig`, `reduceProvider`), so a field upstream adds is left out for a Viewer until J5 lists it. The client half adds three J5 RPC groups and one call in each chat view: `J5AccessRpcGroup`, `J5PeopleRpcGroup` and `J5SharedConversationRpcGroup` (J5-owned `packages/contracts/src/j5/access.ts`, `people.ts` and `sharedConversation.ts`) are merged in `packages/contracts/src/rpc.ts`, and their streams (`j5.access.subscribeThreadLevel`, `j5.people.subscribeScopeChanges`, `j5.sharedConversation.subscribeThreadAuthorsChanges`) join `EnvironmentSubscriptionRpcTag` in `packages/client-runtime/src/rpc/client.ts` (one line each, the shape of cases 45 and 64); `packages/client-runtime/package.json` exports `./j5/sharing`. In `apps/server/src/ws.ts`, case 58's `layerJ5WsRpc(...)` call passes the connection's `session`, so the handlers answer for the session the socket was opened with. Upstream's web chat view (`apps/web/src/components/ChatView.tsx`) and mobile thread screen (`apps/mobile/src/features/threads/ThreadRouteScreen.tsx`) each call J5-owned `useCanOperateThread(environmentId, threadId)` from their app's `j5/sharing/access.ts` (web) or `j5/sharing/guestAccess.ts` (mobile) where they computed `canOperateThread` (one import and one call), and upstream's thread action menu (`apps/web/src/hooks/useThreadActionMenu.ts`) calls `readCanOperateThread(threadRef)` from `apps/web/src/j5/sharing/threadOperability.ts`. On a pin advance: keep the wrapping calls where the answers are produced; if upstream adds another place that sends a `ServerConfig`, a lifecycle event, a shell item or a list of scheduled tasks, a narrowed session cannot reach it until it is listed, and it must pass through `GuestView` when it is; if upstream changes how the shell feed resumes or what its items are, reread `GuestView.ts`; if upstream's client stops falling back to the feed when the HTTP sidebar snapshot is refused, a narrowed person's sidebar stays empty; if upstream adds an asset kind or changes where attachments are named (`orchestration_v2_projection_messages` `$.attachments[].id`, or a turn item's payload), reread `messageAssetLevel`; if upstream reshapes its permissions, reread case 70's level mapping; if upstream changes how its client keys a favicon request or the three asset functions, reread `GuestProjectIcons.ts`, whose test runs upstream's real resolution. -70. Every device belongs to a person, holds its level's permissions, and renews when the level changes ([#535](https://github.com/Jacksondr5/j5code/issues/535), [#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, Jackson's 2026-10-11 approval on [#531](https://github.com/Jacksondr5/j5code/issues/531) of one small edit inside upstream's pairing code, and his 2026-10-17 rulings). A level's permissions are listed in one place, J5-owned `packages/contracts/src/j5/levels.ts` (`LEVEL_PERMISSIONS`), and a device holds its person's highest level's set cut to the ceiling it was paired with (`devicePermissions`). Whose device a session is, and that ceiling, are recorded in J5's own table `j5_a2a_person_session` (J5 migrations 34 and 39) as upstream issues the session, without changing upstream's tables. The person a pairing credential is for is recorded in `j5_a2a_pairing_intent` (migration 39), found again by a hash of the credential because upstream's pairing code holds the credential when it issues a session. `apps/server/src/auth/EnvironmentAuth.ts` carries the edit, at seven sites: one import; two lines in `make` (`const j5TiedToPerson = yield* makePairingSessionIssuer` and `const j5ApprovesMcpClient = yield* makeMcpApprovalCheck`, each read with `Effect.serviceOption`, so upstream's own tests build the layer without them); one pipe step, `j5TiedToPerson(grant, credential)`, on each of the two `sessions.issue` calls that issue a session from a pairing grant (`createBrowserSession` and `exchangeBootstrapCredentialForAccessToken`); and one check in `consumeMcpApprovalCode`, so only a code an Owner's level backs approves an MCP client (`PairingIntents.approvesMcpClient`: not a J5 link's credential, subject `j5:link`, and not one whose intent names someone who is not an Owner); and the message a browser session from another origin is refused with is a named export, `FOREIGN_ORIGIN_DIAGNOSTIC`, so J5's renewal refuses what upstream refuses. Lowering or removing an Owner voids every MCP approval checked before it, however soon after the check it lands, and ends the MCP clients that Owner approved: J5-owned `McpApproval.layerGatedMcpOAuth` decorates upstream's `McpOAuth` (`apps/server/src/auth/McpOAuth.ts` is not edited), reads which change of Owners it is (`Access.ownersGeneration`, under the same lock as a change of level) and who approves (the person the pairing code's intent names, read before upstream spends it, or the person whose browser session approves) before upstream's `approve` checks the approval, ties both to the code in the redirect `approve` returns, and gives them to the exchange of that code; `layerGatedEnvironmentAuth` wraps `issueMcpClientSession` in `Access.issueMcpClient`, which refuses under that lock if the Owners changed since, or if no approval was given to it, and otherwise records the issued session as its approver's in J5's own table `j5_a2a_mcp_client_approver` (J5 migration 44), keyed by the session id upstream's `SessionStore.verify` reads from the token it issued. Lowering or removing that person as an Owner revokes those sessions upstream in the same transaction. Upstream's MCP sign-in issues no refresh token, so a client's session is never replaced under a new id; an MCP client approved before migration 44, or with a code that names no one (the first owner's), has no approver and is ended by hand. In `server.ts`, `McpOAuth.layer` is wrapped in `gateMcpOAuth` where `McpOAuthHttp.layer` is given it (one import and one line). For a credential with no intent the pipe step costs one read by primary key and returns upstream's own effect, and binds the session to the first owner when the credential is the startup link's, the desktop app's or T3 Connect's (`FIRST_OWNER_SUBJECTS`; if upstream mints another credential for the server's own account, add its subject there, or its device is one no one has claimed). For one with an intent it runs upstream's `sessions.issue` and the binding in one transaction (`PairingIntents.issueSession`), so the session and the record of whose it is commit together, and it issues nothing when the credential carries more than its person may hold now, when its person was removed, or when it carries the retired guest subject `j5:guest`. In `apps/server/src/server.ts`, `layerAuth` (case 69) gains one line, `Layer.provideMerge(J5PeopleLive)`, above `layerPersistence`: it gives `PersonAccess` and `PairingIntents` to upstream's `EnvironmentAuth.layer` and to J5's own services. `apps/server/src/auth/http.ts`'s `pairingCredential` handler, which Connections' "Create link" calls, records after `issuePairingCredential` that the link pairs a device for the person whose device made it, under the permissions chosen there (`recordConnectionsLinkCreator`; one import and one call); a link whose maker cannot be recorded is revoked before the request fails. A change of level ends each of the person's sessions for renewal (`Access.ts`): the binding is marked and upstream's `SessionStore.revoke` ends the session, which closes its open sockets at once, in the transaction that changes the level. The device then renews on J5's route `POST /api/j5/session/renew` (`SessionRenewal.ts`, no upstream edit) with its old token: upstream's `SessionStore.verify` checks a token's signature before whether it was revoked and names a revoked token's session, so the route issues a session that holds the new permissions, with the old session's method, subject, client and expiry, only for a session J5 marked, once. `apps/web/src/environments/primary/auth.ts` calls `renewPrimarySession` before its sign-in gate sends a browser to pair (one import and one line), and J5-owned `SessionRenewalWatcher` reloads the page once when the primary connection drops and renewal succeeds. `apps/web/src/connection/runtime.ts` adds J5-owned `@t3tools/client-runtime/j5/session-renewal` to the connection runtime (one import and one line), which renews a saved server's bearer token when its connection is refused for authentication; `packages/client-runtime/package.json` exports it. DPoP sessions, mobile and a device offline past its session's life are paired again by hand; an MCP client holds no person's level, so a change of level does not touch it, except that lowering or removing an Owner ends the ones they approved. The refusal of a browser paired as one person opening a link made for another reaches the pairing page with its reason through three upstream files, each a line or a literal: `packages/contracts/src/environmentHttp.ts` (`EnvironmentAuthInvalidError`'s optional `pairingRefusal: "paired_as_someone_else"`), `apps/server/src/auth/http.ts` (`failEnvironmentAuthInvalid`'s third argument, passed by the `browserSession` handler), and `apps/web/src/environments/primary/auth.ts` (the rejected-credential error's flag). `layerGatedEnvironmentAuth` (case 69's J5-owned decorator) wraps `createBrowserSession` to refuse that before upstream is called, so the link is not used up, and wraps `revokeSession`, `revokeClientSession`, `revokeOtherSessionsExcept` and `revokeOtherClientSessions` so that ending a device cuts it loose from its person first, and with that from any renewal. On a pin advance: if upstream adds another place that turns a pairing grant into a session, it must go through `j5TiedToPerson`, or the device is one no one has claimed; if upstream reshapes its permissions, update `LEVEL_PERMISSIONS` and the definition (`levelPermissions.test.ts` pins each level's set by upstream's names); if upstream adds a method that ends a session, wrap it in the decorator; if upstream changes `SessionStore.verify`'s order of checks or stops naming a revoked token's session, renewal stops working and must be rethought; if upstream adds a pairing path that issues a session from something other than a pairing grant, record whose its sessions are or narrow them; if upstream changes how it refuses a browser session from another origin, keep `FOREIGN_ORIGIN_DIAGNOSTIC` the message it refuses with; if upstream adds a refresh grant or any other way to renew an MCP client's session under a new id, record the new session as the old one's approver's, or lowering that Owner leaves it live; if upstream stops returning the code in `approve`'s redirect, or issues an MCP client's session other than from `exchangeCode` through `EnvironmentAuth.issueMcpClientSession`, every MCP sign-in is refused (`McpApproval.test.ts` runs upstream's own sign-in through the gate) and the tie must be rethought; if upstream provides `McpOAuth.layer` somewhere else, wrap it there too. +70. Every device belongs to a person, holds its level's permissions, and renews when the level changes ([#535](https://github.com/Jacksondr5/j5code/issues/535), [#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, Jackson's 2026-10-11 approval on [#531](https://github.com/Jacksondr5/j5code/issues/531) of one small edit inside upstream's pairing code, and his 2026-10-17 rulings). A level's permissions are listed in one place, J5-owned `packages/contracts/src/j5/levels.ts` (`LEVEL_PERMISSIONS`), and a device holds its person's highest level's set cut to the ceiling it was paired with (`devicePermissions`). Whose device a session is, and that ceiling, are recorded in J5's own table `j5_a2a_person_session` (J5 migrations 34 and 39) as upstream issues the session, without changing upstream's tables. The person a pairing credential is for is recorded in `j5_a2a_pairing_intent` (migration 39), found again by a hash of the credential because upstream's pairing code holds the credential when it issues a session. `apps/server/src/auth/EnvironmentAuth.ts` carries the edit, at seven sites: one import; two lines in `make` (`const j5TiedToPerson = yield* makePairingSessionIssuer` and `const j5ApprovesMcpClient = yield* makeMcpApprovalCheck`, each read with `Effect.serviceOption`, so upstream's own tests build the layer without them); one pipe step, `j5TiedToPerson(grant, credential)`, on each of the two `sessions.issue` calls that issue a session from a pairing grant (`createBrowserSession` and `exchangeBootstrapCredentialForAccessToken`); and one check in `consumeMcpApprovalCode`, so only a code an Owner's level backs approves an MCP client (`PairingIntents.approvesMcpClient`: not a J5 link's credential, subject `j5:link`, and not one whose intent names someone who is not an Owner); and the message a browser session from another origin is refused with is a named export, `FOREIGN_ORIGIN_DIAGNOSTIC`, so J5's renewal refuses what upstream refuses. Lowering or removing an Owner voids every MCP approval checked before it, however soon after the check it lands, and ends the MCP clients that Owner approved: J5-owned `McpApproval.layerGatedMcpOAuth` decorates upstream's `McpOAuth` (`apps/server/src/auth/McpOAuth.ts` is not edited), reads which change of Owners it is (`Access.ownersGeneration`, under the same lock as a change of level) and who approves (the person the pairing code's intent names, read before upstream spends it, or the person whose browser session approves) before upstream's `approve` checks the approval, ties both to the code in the redirect `approve` returns, and gives them to the exchange of that code; `layerGatedEnvironmentAuth` wraps `issueMcpClientSession` in `Access.issueMcpClient`, which refuses under that lock if the Owners changed since, or if no approval was given to it, and otherwise records the issued session as its approver's in J5's own table `j5_a2a_mcp_client_approver` (J5 migration 44), keyed by the session id upstream's `SessionStore.verify` reads from the token it issued. Lowering or removing that person as an Owner revokes those sessions upstream in the same transaction. Upstream's MCP sign-in issues no refresh token, so a client's session is never replaced under a new id; an MCP client approved before migration 44, or with a code that names no one (the first owner's), has no approver and is ended by hand. In `server.ts`, `McpOAuth.layer` is wrapped in `gateMcpOAuth` where `McpOAuthHttp.layer` is given it (one import and one line). For a credential with no intent the pipe step costs one read by primary key and returns upstream's own effect, and binds the session to the first owner when the credential is the startup link's, the desktop app's or T3 Connect's (`FIRST_OWNER_SUBJECTS`; if upstream mints another credential for the server's own account, add its subject there, or its device is one no one has claimed). For one with an intent it runs upstream's `sessions.issue` and the binding in one transaction (`PairingIntents.issueSession`), so the session and the record of whose it is commit together, and it issues nothing when the credential carries more than its person may hold now, when its person was removed, or when it carries the retired guest subject `j5:guest`. In `apps/server/src/server.ts`, `layerAuth` (case 69) gains one line, `Layer.provideMerge(J5PeopleLive)`, above `layerPersistence`: it gives `PersonAccess` and `PairingIntents` to upstream's `EnvironmentAuth.layer` and to J5's own services. `apps/server/src/auth/http.ts`'s `pairingCredential` handler, which Connections' "Create link" calls, records after `issuePairingCredential` that the link pairs a device for the person whose device made it, under the permissions chosen there (`recordConnectionsLinkCreator`; one import and one call); a link whose maker cannot be recorded is revoked before the request fails, and that includes one whose maker's session is no one's and no longer live (its person was removed while the link was made), so no such link approves an MCP client as no one. A change of level ends each of the person's sessions for renewal (`Access.ts`): the binding is marked and upstream's `SessionStore.revoke` ends the session, which closes its open sockets at once, in the transaction that changes the level. The device then renews on J5's route `POST /api/j5/session/renew` (`SessionRenewal.ts`, no upstream edit) with its old token: upstream's `SessionStore.verify` checks a token's signature before whether it was revoked and names a revoked token's session, so the route issues a session that holds the new permissions, with the old session's method, subject, client and expiry, only for a session J5 marked, once. `apps/web/src/environments/primary/auth.ts` calls `renewPrimarySession` before its sign-in gate sends a browser to pair (one import and one line), and J5-owned `SessionRenewalWatcher` reloads the page once when the primary connection drops and renewal succeeds. `apps/web/src/connection/runtime.ts` adds J5-owned `@t3tools/client-runtime/j5/session-renewal` to the connection runtime (one import and one line), which renews a saved server's bearer token when its connection is refused for authentication; `packages/client-runtime/package.json` exports it. DPoP sessions, mobile and a device offline past its session's life are paired again by hand; an MCP client holds no person's level, so a change of level does not touch it, except that lowering or removing an Owner ends the ones they approved. The refusal of a browser paired as one person opening a link made for another reaches the pairing page with its reason through three upstream files, each a line or a literal: `packages/contracts/src/environmentHttp.ts` (`EnvironmentAuthInvalidError`'s optional `pairingRefusal: "paired_as_someone_else"`), `apps/server/src/auth/http.ts` (`failEnvironmentAuthInvalid`'s third argument, passed by the `browserSession` handler), and `apps/web/src/environments/primary/auth.ts` (the rejected-credential error's flag). `layerGatedEnvironmentAuth` (case 69's J5-owned decorator) wraps `createBrowserSession` to refuse that before upstream is called, so the link is not used up, and wraps `revokeSession`, `revokeClientSession`, `revokeOtherSessionsExcept` and `revokeOtherClientSessions` so that ending a device cuts it loose from its person first, and with that from any renewal. On a pin advance: if upstream adds another place that turns a pairing grant into a session, it must go through `j5TiedToPerson`, or the device is one no one has claimed; if upstream reshapes its permissions, update `LEVEL_PERMISSIONS` and the definition (`levelPermissions.test.ts` pins each level's set by upstream's names); if upstream adds a method that ends a session, wrap it in the decorator; if upstream changes `SessionStore.verify`'s order of checks or stops naming a revoked token's session, renewal stops working and must be rethought; if upstream adds a pairing path that issues a session from something other than a pairing grant, record whose its sessions are or narrow them; if upstream changes how it refuses a browser session from another origin, keep `FOREIGN_ORIGIN_DIAGNOSTIC` the message it refuses with; if upstream adds a refresh grant or any other way to renew an MCP client's session under a new id, record the new session as the old one's approver's, or lowering that Owner leaves it live; if upstream stops returning the code in `approve`'s redirect, or issues an MCP client's session other than from `exchangeCode` through `EnvironmentAuth.issueMcpClientSession`, every MCP sign-in is refused (`McpApproval.test.ts` runs upstream's own sign-in through the gate) and the tie must be rethought; if upstream provides `McpOAuth.layer` somewhere else, wrap it there too. 71. An Owner shares from the app ([#535](https://github.com/Jacksondr5/j5code/issues/535), [#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, Jackson's 2026-10-12 design and approval of an appended item in the thread menu, and the 2026-10-17 design review of the one Share dialog). The Share dialog (one for a thread, a project and the server), the link step and their state are J5-owned files under `apps/web/src/j5/sharing/`. Upstream's thread action menu (`apps/web/src/hooks/useThreadActionMenu.ts`, already carrying case 69's one call) gains one import and two calls: the list upstream's `buildThreadActionMenuItems` returns is passed through `withSharingMenuItems(items, threadRef)`, and after the menu closes `if (runSharingMenuAction(clicked.value, threadRef)) return;` opens the dialog J5 asked for and keeps J5's ids away from upstream's switch. `withSharingMenuItems` inserts "Share thread…" after "Copy" (disabled on a device without `access:write`, People and access AC34). For someone who is not an Owner of the thread's server it also leaves out Archive, Delete and "Project settings" (AC14, AC27), leaves out "Mark unread" for a Viewer of the thread (the read marker is everyone's, Shared conversations AC19), and puts "Leave thread" where Archive was when they hold a level on the thread itself (AC48). The ids (`j5:share-thread`, `j5:leave-thread`) are outside upstream's `ThreadActionMenuId` union, and `runSharingMenuAction` is the type guard that takes them back out, so upstream's `components/threadActionMenu.logic.ts` is untouched. `apps/web/src/hooks/useThreadActionMenu.test.ts` carries two J5 cases at its end (the item's place, and that picking it reaches none of upstream's actions). Upstream's sidebar builds and handles the same menu itself (`apps/web/src/components/Sidebar.tsx`, the thread row's right-click): one import, the builder wrapped where the list is built, `buildWithSharingMenuItems(buildThreadActionMenuItems, threadRef)({…})`, which leaves upstream's arguments where they are, and the same `if (runSharingMenuAction(clicked.value, threadRef)) return;` after the menu closes. The dialogs are opened from places that render nothing, so `apps/web/src/routes/__root.tsx` mounts J5's `` beside upstream's `` (one import, one line), the way upstream draws its own confirm and custom-snooze dialogs; the host also draws the name question a server asks before a device uses it (AC5, AC6), renews a session ended for a change of level (case 70), tells an Owner once that links made before the move to levels stopped working, and takes someone off a thread no longer theirs. `apps/web/src/components/CommandPalette.tsx` gains one import, one hook call (`useSharingPaletteItems({ activeThread, projectRef: contextualProjectRef })`, beside where `actionItems` is declared) and `actionItems.push(...sharingPaletteItems)` before the "Project settings" entry, for "Share thread", "Share project", "Share server", "Open People" and "Change your name"; the palette searches an entry's `searchTerms` only, so each entry's title is among its terms (Jackson's 2026-10-12 approval). The web menu draws an item's icon from the table in `apps/web/src/contextMenuFallback.ts`, which gains one entry, `users` (lucide's four shapes, six lines and a comment), so that J5's item lines up with its neighbours. `j5/sharing/sharingMenu.ts` and `sharingDialogs.ts` import nothing of React or the connection runtime, because that test mocks `react`. A link always opens on the server itself; the link step's route choice mirrors helpers that are private to upstream's `apps/web/src/components/settings/ConnectionsSettings.tsx` (`selectPairingEndpoint`'s default, `endpointDefaultPreferenceKey`, `endpointShareHint`), copied into J5-owned `j5/sharing/shareLink.logic.ts` with no upstream edit; what upstream already exports (`isQrShareableEndpoint`, `selectQrEndpointOption`, `pairingUrls.ts`, `QRCodeSvg`, the saved default route in `uiStateStore`) is imported. On a pin advance: compare those helpers with upstream's and carry over any change to how a route is picked or described; if upstream moves `api.contextMenu.show(items, position)` in the hook, re-apply the two calls around it, and the same in the sidebar's thread-row menu; if the palette's `actionItems` list or the root's dialog hosts move, re-apply the append and the mount where they went; if upstream renames the "copy", "archive", "delete", "project-settings" or "mark-unread" items, "Share thread…" falls to the end of the menu or an Owner's item shows to someone who is not one, and `sharingMenu.test.ts` still passes, so check both menus in a browser. 72. Settings › People, and Settings for someone who is not an Owner ([#535](https://github.com/Jacksondr5/j5code/issues/535), [#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, Jackson's 2026-10-12 design and approval of the Settings navigation and route registration, and his 2026-10-17 ruling that Settings is an Owner's). The page (`apps/web/src/j5/sharing/PeoplePage.tsx`) and everything it draws are J5-owned; `apps/web/src/routes/settings.people.tsx` is a J5-owned route file in upstream's routes folder, the shape of `settings.skills.tsx` (case 42), and `routeTree.gen.ts` regenerates with it. Registering a settings section takes upstream's own tables, each one entry: in `apps/web/src/components/settings/settingsSearch.ts` the `SettingsPath` union, `SETTINGS_SECTION_LABELS` (after Connections, which sets the sidebar order), `SETTINGS_CATEGORY_SCOPES` (`"connections"`) and one search item, `people`; in `SettingsSidebarNav.tsx` the icon map (`UsersIcon`); in `SettingsScopeSentence.tsx` one line adding the path to `SETTINGS_DEVICE_ONLY_PATHS`, since the page has its own server picker. Settings is an Owner's (AC27 to AC29), by four calls into J5-owned `j5/sharing/settingsAccess.tsx`, each one import and one or two lines. `SettingsSidebarNav.tsx` builds its list through `useSettingsNavItems(…)` around upstream's own filter: for someone who owns no connected server it keeps only the pages in `PAGES_FOR_EVERYONE` (Appearance, SnapShots, People) and adds Open-source licenses, which upstream reaches only from General, as a page of its own. `useAvailableSettingsSearchItems.ts` returns `useShownSettingsSearchItems(items)`, so search finds the same pages, in the sidebar and the command palette alike. `apps/web/src/routes/settings.tsx` wraps upstream's `SettingsScopeBoundary` and the `` in ``, which shows that person a "Coming soon" notice in place of any other page, one upstream adds later among them, so a link to one (a thread's "Manage scheduled tasks") still lands; the gate is outside the boundary because a server the person does not own leaves the boundary's scope unavailable. `SettingsScopeContext.tsx` and `SettingsScopeSentence.tsx` read their servers through `useOwnedEnvironments(useEnvironments().environments)`, and `useSettingsProjectGroups.ts` its projects through `useOwnedEnvironments(useProjects())`, so Settings lists and changes only the servers and projects the person owns, in the scope picker and the project panel alike; upstream applies a change to every listed server and greys a row unless all of them allow it. `ProjectSettingsPanel.test.tsx` mocks `j5/sharing/settingsAccess` (one comment and four lines), because the test replaces the connection runtime with `undefined` and J5's access atoms are made from it when their module loads. J5's Fleet page and inbox, which name a project from any server, group every server's projects themselves (`j5/logicalProjects.ts`). A server that has not answered yet counts as owned, so an Owner's Settings does not flicker. J5's own Settings pages (Personas, Playbooks, Skills) list only owned servers the same way. The project page carries no Sharing section (AC34). On a pin advance: if upstream reshapes how a settings section is declared, re-register People after Connections; if upstream resolves Settings' servers anywhere besides those two files, filter it there too, or a server the person does not own greys out their Settings; if upstream renames the Appearance or SnapShots path, update `PAGES_FOR_EVERYONE` (its test pins the list); if upstream adds a settings page of its own for people or access, read D33 before keeping J5's. 73. A thread says who reaches it, and the client fits what a person's level lets them do ([#535](https://github.com/Jacksondr5/j5code/issues/535), [#541](https://github.com/Jacksondr5/j5code/issues/541), [#636](https://github.com/Jacksondr5/j5code/issues/636), register D33, Jackson's 2026-10-12 design and approval of one mount or item in each of these files, and his 2026-10-13 approvals of the route files and of the two edits that quiet what could only fail). All of it is J5-owned code under `apps/web/src/j5/sharing/`, mounted once in each upstream file, and it reads what the server says the connection is (`j5.access.getConnectionAccess`, read again when people or levels change) and the level it holds over each thread (`j5.access.subscribeThreadLevel`). `apps/web/src/components/chat/ChatHeader.tsx`: one import and `` after the breadcrumb, for a server thread; it draws nothing unless more than one person reaches the thread. `apps/web/src/components/chat/ThreadDetailsPanel.tsx`: one import and `` after `ThreadRelationshipsPanel`, under the same `density === "full" && !props.draftId` condition as its neighbours; and `const readOnly = !useCanOperateThread(…)` with `&& !readOnly` on the condition that mounts upstream's `ThreadAutomationsPanel`, so a Viewer of the thread sees no Automations. `apps/web/src/components/chat/ChatComposer.tsx`: one import, one hook call after the props are read (`useViewOnlyComposerProps(environmentId, canOperateThread)`), and one spread, `{...viewOnlyComposerProps}`, after upstream's `placeholder={…}` prop, so that someone who is not an Owner and cannot write to the thread reads "You can read this thread, but not send anything to it."; the collapsed composer's fallback literal becomes `(viewOnlyComposerProps.placeholder ?? "Ask anything...")`. The chip and the section ask the server who reaches the thread (`j5.people.listScope`) and ask again when its counter moves (`j5.people.subscribeScopeChanges`). Two route files carry a person's way in. `apps/web/src/routes/pair.tsx`: the import of upstream's `PairingRouteSurface` becomes J5's `JoinLinkPairingSurface`, and the JSX tag changes with it (three lines; upstream's `components/auth/PairingRouteSurface.tsx` is not edited). J5's surface asks `POST /api/j5/links/describe` what a link opens, without spending it, only for a link that carries J5's mark, and waits up to five seconds; everything else gets upstream's surface with the props it was given, and an ordinary pairing token is sent nowhere but upstream's own exchange. The person confirms or types their name and joins on `POST /api/j5/links/join`, which answers with an upstream pairing credential the page exchanges at once. The Share dialog puts the mark, `j5share=1`, in the fragment beside upstream's `token`; upstream reads the fragment as parameters and takes only `token`. `apps/web/src/routes/_chat.index.tsx`: one import, and `` is wrapped in ``, which renders its child at once for anyone at server scope and before the server answers, and for someone who reaches less shows their one thread, a list, or that nothing is shared with them (AC30). `apps/web/src/routes/__root.tsx`: one import, one hook call beside `primaryEnvironmentAuthenticated`, `useFirstRunSetupOffered(primaryEnvironmentAuthenticated)`, and `FirstRunGate`'s `enabled` reads its answer: the wizard is offered only to an Owner of the primary server the server has a name for, by that server's answer, so the name is asked first (AC6), and upstream's gate decides again when the answer arrives; a failed or missing answer offers nothing. `apps/web/src/routes/welcome.tsx`, the wizard's own address, gains one import and two lines before its return, `const setupRefusal = useSetupWizardRefusal(localAvailable); if (setupRefusal !== null) return setupRefusal;`, which draws nothing until the primary server answers and then sends anyone the wizard is not offered to to the first screen, where the name is asked; the hosted app, with no server of its own, is left to upstream. `apps/web/src/components/Sidebar.tsx`: one import, `const isNarrowEverywhere = useIsNarrowEverywhere()` beside the primary environment's id, and `&& !isNarrowEverywhere` on the empty list's `projects.length === 0` condition, so someone who reaches no whole server reads upstream's "No threads yet" in place of an "Add project" button that could only fail. Two more quiet upstream notices a person sees fail (J5-owned `apps/web/src/j5/sharing/upstreamNotices.ts`; Jackson's standing permission on this workstream for one import and one or two lines, used 2026-10-18): `apps/web/src/components/PermissionUpdateNotice.tsx` (one import, one changed line) lists its servers through `useEnvironmentsForPermissionNotice(useEnvironments().environments)`, which leaves out a server that places the connection as a person or a device it will ask about, and one that has not answered yet, as J5 sets and renews those permissions from the person's level, so "Pair again" never applies; its test (`PermissionUpdateNotice.test.tsx`, three added lines as formatted) mocks that hook as passing every server through. `apps/web/src/routes/__root.tsx` (one import, one added and one changed line) mounts `ProviderUpdateLaunchNotification` on `const providerUpdatesShown = useProviderUpdateNoticeShown(primaryEnvironmentAuthenticated)` in place of `primaryEnvironmentAuthenticated`, so the provider updates notice shows only to a connection holding Manage providers. On a pin advance: if upstream moves the composer's `placeholder` prop, keep the spread after it; if upstream renames `PermissionUpdateNotice`'s server list or moves the provider updates mount, filter or gate it where it moved; if upstream reorders the details panel, keep People after Lineage and the condition on the Automations mount; if upstream changes how a pairing address carries its token, or starts to refuse a fragment it does not know, reread `SHARE_LINK_MARK` in J5-owned `packages/contracts/src/j5/sharing.ts`; if upstream renames `PairingRouteSurface` or changes its props, J5's surface fails to compile; if upstream's index route stops rendering `IndexDraftLanding`, re-wrap whatever it renders; if upstream renames `FirstRunGate`'s `enabled`, or decides first run before `enabled` can change, someone who is not an Owner may be offered the wizard. diff --git a/apps/server/src/j5/sharing/PairingIntents.test.ts b/apps/server/src/j5/sharing/PairingIntents.test.ts index 075109973714e..dbe511b3ffe72 100644 --- a/apps/server/src/j5/sharing/PairingIntents.test.ts +++ b/apps/server/src/j5/sharing/PairingIntents.test.ts @@ -8,7 +8,11 @@ import * as Result from "effect/Result"; import * as SessionStore from "../../auth/SessionStore.ts"; import { Access } from "./Access.ts"; -import { J5_LINK_PAIRING_SUBJECT, PairingIntents } from "./PairingIntents.ts"; +import { + J5_LINK_PAIRING_SUBJECT, + PairingIntents, + recordConnectionsLinkCreator, +} from "./PairingIntents.ts"; import * as PersonAccess from "./PersonAccess.ts"; import { accessLayer, device, isLive, person } from "./test-support/accessHarness.ts"; @@ -244,6 +248,7 @@ it.layer(accessLayer)("PairingIntents", (it) => { pairingLinkId: "pairing:connections", credential: "credential-connections", scopes: [AuthOrchestrationReadScope], + creatorLive: Effect.succeed(true), }); const intent = yield* intents.intentOf("credential-connections"); assert.strictEqual(intent?.personId, maker.personId); @@ -255,8 +260,37 @@ it.layer(accessLayer)("PairingIntents", (it) => { pairingLinkId: "pairing:peer", credential: "credential-peer", scopes: [AuthOrchestrationReadScope], + creatorLive: Effect.succeed(true), }); assert.isNull(yield* intents.intentOf("credential-peer")); }), ); + + it.effect("refuses a Connections link whose maker was removed while it was made", () => + Effect.gen(function* () { + const intents = yield* PairingIntents; + const access = yield* Access; + const maker = yield* person("Leaving", [{ scope: { kind: "server" }, level: "owner" }]); + const laptop = yield* device(maker.personId, LEVEL_PERMISSIONS.owner); + // Upstream has minted the link; the maker is removed before J5 records whose it is. + yield* access.removePerson(maker.personId); + const refused = yield* recordConnectionsLinkCreator({ + creator: laptop.identity, + link: { id: "pairing:late", credential: "credential-late" }, + scopes: LEVEL_PERMISSIONS.owner, + }).pipe(Effect.flip); + // Upstream's handler revokes a link whose maker is not recorded. + assert.strictEqual(refused.reason, "no_person"); + assert.isNull(yield* intents.intentOf("credential-late")); + + // A device no one has claimed still makes links, recorded as no one's. + const unclaimed = yield* device(null, LEVEL_PERMISSIONS.owner); + yield* recordConnectionsLinkCreator({ + creator: unclaimed.identity, + link: { id: "pairing:unclaimed", credential: "credential-unclaimed" }, + scopes: LEVEL_PERMISSIONS.owner, + }); + assert.isNull(yield* intents.intentOf("credential-unclaimed")); + }), + ); }); diff --git a/apps/server/src/j5/sharing/PairingIntents.ts b/apps/server/src/j5/sharing/PairingIntents.ts index 2ee3237014d8d..fd0e209839573 100644 --- a/apps/server/src/j5/sharing/PairingIntents.ts +++ b/apps/server/src/j5/sharing/PairingIntents.ts @@ -16,6 +16,7 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; +import * as SessionStore from "../../auth/SessionStore.ts"; import { ParticipantId } from "../a2a/contracts.ts"; import { ReadChanges, layer as readChangesLayer } from "../a2a/ReadChanges.ts"; import { @@ -133,13 +134,17 @@ export interface PairingIntentsShape { /** * Records, for a link made in upstream's Connections settings, that it pairs a device for the * person whose device made it, under the permissions chosen there (AC3, AC18). A link made by a - * session that is no person's records nothing. + * session that is no person's records nothing, and the link then approves an MCP client as no + * one; so one made by a session that is no longer live is refused, since that is a device whose + * person was removed while the link was made. */ readonly recordForCreator: (input: { readonly creator: SessionIdentity; readonly pairingLinkId: string; readonly credential: string; readonly scopes: ReadonlyArray; + /** Whether the maker's session is still live, read only when it is no person's. */ + readonly creatorLive: Effect.Effect; }) => Effect.Effect; /** The intent a credential carries, read without using it; `null` for none. */ readonly intentOf: ( @@ -241,7 +246,14 @@ const make: Layer.Layer; }) => - Effect.serviceOption(PairingIntents).pipe( - Effect.flatMap((intents) => - Option.match(intents, { - onNone: () => Effect.void, - onSome: (service) => - service.recordForCreator({ - creator: input.creator, - pairingLinkId: input.link.id, - credential: input.link.credential, - scopes: input.scopes, - }), - }), - ), - ); + Effect.gen(function* () { + const intents = yield* Effect.serviceOption(PairingIntents); + if (Option.isNone(intents)) return; + const sessions = yield* SessionStore.SessionStore; + yield* intents.value.recordForCreator({ + creator: input.creator, + pairingLinkId: input.link.id, + credential: input.link.credential, + scopes: input.scopes, + creatorLive: sessions + .listActive() + .pipe( + Effect.map((active) => + active.some((session) => session.sessionId === input.creator.sessionId), + ), + ), + }); + }); From 08eb921401a12d333b2c23b745d45ab58e07e228 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Sun, 25 Oct 2026 00:23:19 -0400 Subject: [PATCH 3/4] fix(j5): ending a device cuts it loose and revokes it in one transaction A link made on an Owner's device while another device ended it could see the device unbound but still live, record it as no one's, and keep approving MCP clients after the Owner was removed. The gate's four revoke paths now unbind and revoke in one transaction, as People.revokeDevice and Access.removePerson already do. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/j5/sharing/AccessGate.ts | 35 +++++++++---- .../src/j5/sharing/PairingIntents.test.ts | 50 +++++++++++++++++++ apps/server/src/j5/sharing/PairingIntents.ts | 6 ++- 3 files changed, 79 insertions(+), 12 deletions(-) diff --git a/apps/server/src/j5/sharing/AccessGate.ts b/apps/server/src/j5/sharing/AccessGate.ts index 405dc704954d1..8309317a778cf 100644 --- a/apps/server/src/j5/sharing/AccessGate.ts +++ b/apps/server/src/j5/sharing/AccessGate.ts @@ -30,7 +30,8 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; -import type * as SqlClient from "effect/sql/SqlClient"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as SqlError from "effect/sql/SqlError"; import type * as RpcGroup from "effect/rpc/RpcGroup"; import type * as HttpServerRequest from "effect/http/HttpServerRequest"; @@ -137,6 +138,8 @@ type AccessRpcRule = ( } ) & { readonly unknownToo?: true }; +const isSqlError = Schema.is(SqlError.SqlError); + const field = (value: unknown, name: string): unknown => typeof value === "object" && value !== null && name in value ? (value as Record)[name] @@ -456,6 +459,7 @@ export const layerGatedEnvironmentAuth = Layer.effect( const access = yield* PersonAccess; const intents = yield* PairingIntents; const changes = yield* Access; + const sql = yield* SqlClient.SqlClient; // Upstream's own session store, to read whose browser is asking. A test that stands in for // upstream's auth has none, and then no browser is taken for anyone's. const sessions = yield* Effect.serviceOption(SessionStore.SessionStore); @@ -501,20 +505,31 @@ export const layerGatedEnvironmentAuth = Layer.effect( /** * Before upstream ends a session, by any of its four ways, the session is cut loose from its * person, and with that from any mark that would let it renew: an ended device stays ended - * (AC49, AC50). If it cannot be done, nothing is revoked, so the Owner sees the failure and - * the device is not left half ended. + * (AC49, AC50). The two commit together or not at all, so no one sees a session that is no + * one's and still live, which would make links as no one's (`PairingIntents.recordForCreator`), + * and a failure leaves the device as it was for the Owner to try again. */ const unbound = ( unbind: Effect.Effect, revoke: Effect.Effect, ) => - unbind.pipe( - Effect.mapError( - (cause): EnvironmentAuth.ServerAuthInternalError => - new EnvironmentAuth.ServerAuthSessionRevocationError({ cause }), - ), - Effect.andThen(revoke), - ); + sql + .withTransaction( + unbind.pipe( + Effect.mapError( + (cause): EnvironmentAuth.ServerAuthInternalError => + new EnvironmentAuth.ServerAuthSessionRevocationError({ cause }), + ), + Effect.andThen(revoke), + ), + ) + .pipe( + Effect.mapError((cause) => + isSqlError(cause) + ? new EnvironmentAuth.ServerAuthSessionRevocationError({ cause }) + : (cause as Exclude), + ), + ); /** * What to do about the session a browser already holds when it pairs again. Upstream replaces diff --git a/apps/server/src/j5/sharing/PairingIntents.test.ts b/apps/server/src/j5/sharing/PairingIntents.test.ts index dbe511b3ffe72..524315188d109 100644 --- a/apps/server/src/j5/sharing/PairingIntents.test.ts +++ b/apps/server/src/j5/sharing/PairingIntents.test.ts @@ -4,10 +4,13 @@ import { LEVEL_PERMISSIONS } from "@t3tools/contracts/j5"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; import * as Result from "effect/Result"; +import * as EnvironmentAuth from "../../auth/EnvironmentAuth.ts"; import * as SessionStore from "../../auth/SessionStore.ts"; import { Access } from "./Access.ts"; +import * as AccessGate from "./AccessGate.ts"; import { J5_LINK_PAIRING_SUBJECT, PairingIntents, @@ -293,4 +296,51 @@ it.layer(accessLayer)("PairingIntents", (it) => { assert.isNull(yield* intents.intentOf("credential-unclaimed")); }), ); + + it.effect("refuses a Connections link whose maker's device is ended while it is made", () => + Effect.gen(function* () { + const intents = yield* PairingIntents; + const sessions = yield* SessionStore.SessionStore; + const maker = yield* person("Ending", [{ scope: { kind: "server" }, level: "owner" }]); + const laptop = yield* device(maker.personId, LEVEL_PERMISSIONS.owner); + // Upstream's revoke waits here, once the gate has cut the laptop loose from its person. + const revoking = yield* Deferred.make(); + const resume = yield* Deferred.make(); + const auth = yield* EnvironmentAuth.EnvironmentAuth.pipe( + Effect.provide( + AccessGate.layerGatedEnvironmentAuth.pipe( + Layer.provide( + Layer.mock(EnvironmentAuth.EnvironmentAuth)({ + revokeSession: (sessionId) => + Deferred.succeed(revoking, undefined).pipe( + Effect.andThen(Deferred.await(resume)), + Effect.andThen(sessions.revoke(sessionId)), + Effect.orDie, + ), + }), + ), + ), + ), + ); + + // Another device ends the laptop just as upstream has minted a link on it. + const ending = yield* auth.revokeSession(laptop.sessionId).pipe(Effect.forkChild); + yield* Deferred.await(revoking); + // The record runs as far as it can while the revoke is paused: before the cut and the + // revoke were one transaction, to its end, finding the laptop no one's and still live. + const recording = yield* recordConnectionsLinkCreator({ + creator: laptop.identity, + link: { id: "pairing:ending", credential: "credential-ending" }, + scopes: LEVEL_PERMISSIONS.owner, + }).pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.succeed(resume, undefined); + yield* Fiber.join(ending); + + // Refused, so upstream's handler revokes the link rather than leave it approving as no one. + const recorded = yield* Fiber.join(recording).pipe(Effect.result); + assert.isTrue(Result.isFailure(recorded), "the link was recorded as no one's"); + if (Result.isFailure(recorded)) assert.strictEqual(recorded.failure.reason, "no_person"); + assert.isNull(yield* intents.intentOf("credential-ending")); + }), + ); }); diff --git a/apps/server/src/j5/sharing/PairingIntents.ts b/apps/server/src/j5/sharing/PairingIntents.ts index fd0e209839573..0724ba7f0a9c1 100644 --- a/apps/server/src/j5/sharing/PairingIntents.ts +++ b/apps/server/src/j5/sharing/PairingIntents.ts @@ -248,8 +248,10 @@ const make: Layer.Layer Date: Sun, 25 Oct 2026 00:47:51 -0400 Subject: [PATCH 4/4] test(j5): the crews migration test expects migration 45 Co-Authored-By: Claude Opus 5.5 --- apps/server/src/j5/a2a/Migrations.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/j5/a2a/Migrations.test.ts b/apps/server/src/j5/a2a/Migrations.test.ts index d6b098ecf7aa5..9fa19c4be06f6 100644 --- a/apps/server/src/j5/a2a/Migrations.test.ts +++ b/apps/server/src/j5/a2a/Migrations.test.ts @@ -1396,7 +1396,7 @@ it.effect("recreates earlier-shaped crews tables when 14 runs over them", () => applied.map((row) => row.migration_id), [ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 36, 37, 38, 39, 40, 41, 42, 43, 44, + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, ], ); const memberColumns = yield* sql<{ readonly name: string }>`