TypeScript
fix(auth): show connection permissions and enforce session lifetime (#17370)
Julius Marminge456930a09db2
diff --git a/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx b/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsxindex 7e5021153a6..69cc5b35df4 100644--- a/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx+++ b/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx@@ -9,7 +9,9 @@ import {connectionRoutes,isLearned,} from "@t3tools/client-runtime/connection";-import type { EnvironmentId } from "@t3tools/contracts";+import { type EnvironmentId, sessionGrantsScope } from "@t3tools/contracts";+import { AUTH_SCOPE_OPTIONS } from "@t3tools/shared/authScopeOptions";+import { AsyncResult } from "effect/reactivity";import * as Option from "effect/Option";import { useEffect, useMemo, useRef, useState } from "react";import { Alert, Platform, Pressable, View } from "react-native";@@ -56,6 +58,9 @@ export function EnvironmentRoutesSection({}) {const entry = useAtomValue(environmentCatalog.catalogValueAtom).entries.get(environmentId);const prepared = useAtomValue(environmentSession.preparedConnectionValueAtom(environmentId));+ const sessionResult = useAtomValue(environmentSession.sessionStateAtom(environmentId));+ const session = Option.getOrNull(AsyncResult.value(sessionResult));+ const [permissionsOpen, setPermissionsOpen] = useState(false);const reorder = useAtomCommand(environmentCatalog.reorderRoutes, "route reorder");const removeRoute = useAtomCommand(environmentCatalog.removeRoute, "route removal");const [editing, setEditing] = useState(false);@@ -146,6 +151,36 @@ export function EnvironmentRoutesSection({) : undefined}>+ <SettingsActionRow+ icon="checkmark.circle"+ label="Your permissions"+ onPress={() => setPermissionsOpen((open) => !open)}+ />+ {permissionsOpen ? (+ <View className="gap-2 px-4 py-3">+ {activeRouteId !== null &&+ sessionResult._tag !== "Failure" &&+ !sessionResult.waiting &&+ session?.authenticated ? (+ <>+ <Text className="text-sm text-foreground-muted">+ Applies to the route marked In use. Other routes may have different permissions and+ have not been checked.+ </Text>+ {AUTH_SCOPE_OPTIONS.map(({ scope, title }) => (+ <Text key={scope} className="text-sm text-foreground">+ {title}: {sessionGrantsScope(session, scope) ? "Allowed" : "Not granted"}+ </Text>+ ))}+ </>+ ) : (+ <Text className="text-sm text-foreground-muted">+ Permissions not checked. Connect to this environment to view this session’s+ permissions.+ </Text>+ )}+ </View>+ ) : null}{routes.map((route, index) => {const id = connectionRouteId(route.target);// Rows between the lifted row and its drop slot shift to make room.diff --git a/apps/server/src/auth/SessionStore.test.ts b/apps/server/src/auth/SessionStore.test.tsindex 374a51be687..05da2ac755d 100644--- a/apps/server/src/auth/SessionStore.test.ts+++ b/apps/server/src/auth/SessionStore.test.ts@@ -3,6 +3,8 @@ import { AuthStandardClientScopes, EnvironmentId } from "@t3tools/contracts";import { expect, it } from "@effect/vitest";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";+import * as Fiber from "effect/Fiber";+import * as Deferred from "effect/Deferred";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Option from "effect/Option";@@ -113,6 +115,57 @@ const layerFailingSessionLookupCredential = Layer.effect();it.layer(NodeServices.layer)("SessionStore.layer", (it) => {+ it.effect.each(["revoke", "revokeAllExcept", "replace"] as const)(+ "invalidates every connection for a session on %s and leaves other sessions active",+ (operation) =>+ Effect.gen(function* () {+ const sessions = yield* SessionStore.SessionStore;+ const owner = yield* sessions.issue({ subject: "owner" });+ const client = yield* sessions.issue(relaySessionInput);+ const ownerInvalidated = yield* Deferred.make<void>();+ yield* sessions+ .awaitInvalidation(owner.sessionId)+ .pipe(+ Effect.andThen(Deferred.succeed(ownerInvalidated, undefined)),+ Effect.forkScoped({ startImmediately: true }),+ );+ const first = yield* sessions+ .awaitInvalidation(client.sessionId)+ .pipe(Effect.forkScoped({ startImmediately: true }));+ const second = yield* sessions+ .awaitInvalidation(client.sessionId)+ .pipe(Effect.forkScoped({ startImmediately: true }));+ if (operation === "revoke") yield* sessions.revoke(client.sessionId);+ else if (operation === "revokeAllExcept") yield* sessions.revokeAllExcept(owner.sessionId);+ else yield* sessions.issue({ ...relaySessionInput, replaceSessionId: client.sessionId });+ yield* Fiber.join(first);+ yield* Fiber.join(second);+ expect(yield* Deferred.isDone(ownerInvalidated)).toBe(false);+ // A connection whose upgrade authenticated just before revocation must also stop.+ yield* sessions.awaitInvalidation(client.sessionId);+ }).pipe(Effect.scoped, Effect.provide(Layer.merge(layerSessionStore(), TestClock.layer()))),+ );++ it.effect("expires a connected session at its credential deadline", () =>+ Effect.gen(function* () {+ const sessions = yield* SessionStore.SessionStore;+ const client = yield* sessions.issue(relaySessionInput);+ yield* sessions.markConnected(client.sessionId);+ const invalidated = yield* Deferred.make<void>();+ const watcher = yield* sessions+ .awaitInvalidation(client.sessionId)+ .pipe(+ Effect.andThen(Deferred.succeed(invalidated, undefined)),+ Effect.forkScoped({ startImmediately: true }),+ );+ yield* TestClock.adjust(Duration.minutes(59));+ expect(yield* Deferred.isDone(invalidated)).toBe(false);+ yield* TestClock.adjust(Duration.minutes(1));+ yield* Fiber.join(watcher);+ yield* sessions.awaitInvalidation(client.sessionId);+ }).pipe(Effect.scoped, Effect.provide(Layer.merge(layerSessionStore(), TestClock.layer()))),+ );+it.effect("keys remote cookies by environment identity instead of state directory", () =>Effect.gen(function* () {const cookieName = (stateDir: string, environmentId: EnvironmentId) =>diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.tsindex 4db7e95e306..9570785d9f9 100644--- a/apps/server/src/auth/SessionStore.ts+++ b/apps/server/src/auth/SessionStore.ts@@ -407,6 +407,9 @@ export class SessionStore extends Context.Service<SessionCredentialInternalError>;readonly streamChanges: Stream.Stream<SessionCredentialChange>;+ readonly awaitInvalidation: (+ sessionId: AuthSessionId,+ ) => Effect.Effect<void, SessionCredentialVerificationError>;readonly revoke: (sessionId: AuthSessionId,) => Effect.Effect<boolean, SessionCredentialInternalError>;@@ -1047,6 +1050,35 @@ export const make = Effect.gen(function* () {return revokedSessionIds.length;});+ const awaitInvalidation = Effect.fn(function* (sessionId: AuthSessionId) {+ return yield* Effect.scoped(+ Effect.gen(function* () {+ // Subscribe before reading: revocation can race with the WebSocket upgrade.+ const subscription = yield* PubSub.subscribe(changesPubSub);+ const row = yield* authSessions+ .getById({ sessionId })+ .pipe(+ Effect.mapError(+ (cause) => new SessionCredentialVerificationError({ sessionId, cause }),+ ),+ );+ if (Option.isNone(row) || row.value.revokedAt !== null) return;+ const now = yield* DateTime.now;+ const remaining = row.value.expiresAt.epochMilliseconds - now.epochMilliseconds;+ if (remaining <= 0) return;+ yield* Effect.raceFirst(+ Stream.fromSubscription(subscription).pipe(+ Stream.filter(+ (change) => change.type === "clientRemoved" && change.sessionId === sessionId,+ ),+ Stream.runHead,+ ),+ Effect.sleep(Duration.millis(remaining)),+ );+ }),+ );+ });+return SessionStore.of({cookieName,legacyCookieName,@@ -1055,6 +1087,7 @@ export const make = Effect.gen(function* () {issueWebSocketToken,verifyWebSocketToken,listActive,+ awaitInvalidation,get streamChanges() {return Stream.fromPubSub(changesPubSub);},diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex eee2755fcf0..31b07cea2ba 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -3224,7 +3224,17 @@ export const layer = Layer.unwrap();return yield* Effect.acquireUseRelease(sessions.markConnected(session.sessionId),- () => rpcWebSocketHttpEffect,+ () =>+ Effect.raceFirst(+ rpcWebSocketHttpEffect,+ sessions.awaitInvalidation(session.sessionId).pipe(+ Effect.as(HttpServerResponse.empty()),+ Effect.catchTags({+ SessionCredentialVerificationError: (error) =>+ failEnvironmentInternal("internal_error", error),+ }),+ ),+ ),() => sessions.markDisconnected(session.sessionId),);}).pipe(diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsxindex 625efb562f9..a8d9d961a6c 100644--- a/apps/web/src/components/settings/ConnectionsSettings.tsx+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx@@ -1,3 +1,5 @@+import { SessionPermissions } from "./SessionPermissions";+import { AUTH_SCOPE_OPTIONS as PAIRING_SCOPE_OPTIONS } from "@t3tools/shared/authScopeOptions";import {ChevronRightIcon,ChevronsLeftRightEllipsisIcon,@@ -23,20 +25,13 @@ import {import {AuthAccessReadScope,AuthAccessWriteScope,- AuthSettingsWriteScope,- AuthProvidersManageScope,AuthEnvironmentMaintainScope,AuthDiagnosticsReadScope,- AuthOrchestrationOperateScope,AuthOrchestrationReadScope,- AuthPreviewOperateScope,AuthRelayReadScope,AuthRelayWriteScope,- AuthSourceControlWriteScope,AuthFilesystemReadScope,- AuthFilesystemWriteScope,AuthStandardClientScopes,- AuthTerminalOperateScope,AuthTerminalReadScope,type AuthClientSession,type AuthEnvironmentScope,@@ -231,93 +226,6 @@ function formatAccessTimestamp(value: string): string {return accessTimestampFormatter.format(parsed);}-const PAIRING_SCOPE_OPTIONS: ReadonlyArray<{- readonly scope: AuthGrantScope;- readonly title: string;- readonly description: string;-}> = [- {- scope: AuthOrchestrationReadScope,- title: "View environment",- description: "Read threads, status, checkpoints, and configuration.",- },- {- scope: AuthOrchestrationOperateScope,- title: "Operate tasks",- description: "Start, update, and stop tasks.",- },- {- scope: AuthSettingsWriteScope,- title: "Change environment settings",- description: "Edit environment preferences and keybindings.",- },- {- scope: AuthProvidersManageScope,- title: "Manage providers",- description: "Configure, install, sign in to, and update providers and usage sources.",- },- {- scope: AuthEnvironmentMaintainScope,- title: "Maintain environment",- description: "Update the server and control environment processes.",- },- {- scope: AuthPreviewOperateScope,- title: "Control previews",- description: "Open browser previews and host browser automation.",- },- {- scope: AuthDiagnosticsReadScope,- title: "View diagnostics and usage",- description: "Read process diagnostics, resource history, and usage totals.",- },- {- scope: AuthTerminalReadScope,- title: "View terminals",- description: "Read existing terminal output and status.",- },- {- scope: AuthTerminalOperateScope,- title: "Use terminals",- description: "Create terminals and send input to running shells.",- },- {- scope: AuthSourceControlWriteScope,- title: "Change source control",- description: "Commit, push, manage branches and repositories, and change pull requests.",- },- {- scope: AuthFilesystemReadScope,- title: "Read files",- description: "Browse host files, search workspaces, and inspect local changes.",- },- {- scope: AuthFilesystemWriteScope,- title: "Write files",- description: "Edit workspace files and save plans to disk.",- },- {- scope: AuthAccessReadScope,- title: "View access",- description: "Inspect pairing links and authorized clients.",- },- {- scope: AuthAccessWriteScope,- title: "Manage access",- description: "Issue and revoke credentials for other clients.",- },- {- scope: AuthRelayReadScope,- title: "View relay",- description: "Inspect managed relay connectivity.",- },- {- scope: AuthRelayWriteScope,- title: "Manage relay",- description: "Change managed tunnel connectivity.",- },-];-function AccessScopeSummary({scopes,label,@@ -1586,6 +1494,7 @@ function SavedBackendListRow({onAddRoute,}: SavedBackendListRowProps) {const [routesOpen, setRoutesOpen] = useState(false);+ const [permissionsOpen, setPermissionsOpen] = useState(false);const environmentId = environment.environmentId;const unsupported = environment.connection.phase === "unsupported";const enabled = environment.entry.enabled && !unsupported;@@ -1753,6 +1662,25 @@ function SavedBackendListRow({)}/></button>+ <span aria-hidden className="shrink-0">+ ·+ </span>+ <button+ type="button"+ aria-expanded={permissionsOpen}+ aria-controls={`remote-permissions-${environmentId}`}+ onClick={() => setPermissionsOpen((open) => !open)}+ className="inline-flex shrink-0 items-center gap-0.5 rounded-sm text-muted-foreground outline-none hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring"+ >+ Permissions+ <ChevronRightIcon+ aria-hidden+ className={cn(+ "size-3 shrink-0 transition-transform duration-150 motion-reduce:transition-none",+ permissionsOpen && "rotate-90",+ )}+ />+ </button></span>}below={@@ -1763,12 +1691,26 @@ function SavedBackendListRow({) : null}detail={- routesOpen ? (- <EnvironmentRoutesList- environment={environment}- onAddRoute={() => onAddRoute(environment)}- />- ) : null+ <>+ {routesOpen && (+ <EnvironmentRoutesList+ environment={environment}+ onAddRoute={() => onAddRoute(environment)}+ />+ )}+ {permissionsOpen && (+ <div+ id={`remote-permissions-${environmentId}`}+ className="mt-2 border-t border-border/50"+ >+ <SessionPermissions+ environmentId={environmentId}+ connected={isConnected}+ routeContext+ />+ </div>+ )}+ </>}>{unsupported &&@@ -3774,6 +3716,21 @@ export function ConnectionsSettings() {) : null}</>) : null}+ {primaryEnvironment ? (+ <details className="group px-3 sm:px-4">+ <summary className="flex min-h-11 cursor-pointer list-none items-center gap-2 rounded-md text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-ring [&::-webkit-details-marker]:hidden">+ Permissions+ <ChevronRightIcon+ aria-hidden+ className="size-3 text-muted-foreground group-open:rotate-90"+ />+ </summary>+ <SessionPermissions+ environmentId={primaryEnvironment.environmentId}+ connected={primaryEnvironment.connection.phase === "connected"}+ />+ </details>+ ) : null}</SettingsSection>{canReadAccess || canWriteAccess ? (diff --git a/apps/web/src/components/settings/EnvironmentRoutesList.tsx b/apps/web/src/components/settings/EnvironmentRoutesList.tsxindex 9bf09668800..d2cb166f9e4 100644--- a/apps/web/src/components/settings/EnvironmentRoutesList.tsx+++ b/apps/web/src/components/settings/EnvironmentRoutesList.tsx@@ -103,7 +103,7 @@ export function EnvironmentRoutesList({};return (- <div className="mt-2 rounded-md border border-border/70">+ <div className="mt-2 border-t border-border/50 py-2"><DndContextsensors={sensors}collisionDetection={closestCenter}@@ -128,7 +128,7 @@ export function EnvironmentRoutesList({</ol></SortableContext></DndContext>- <div className="border-t border-border/70 px-1 py-1">+ <div className="-ml-1.5 pt-1"><Button size="xs" variant="ghost-muted" onClick={onAddRoute}><PlusIcon className="size-3" />Add route@@ -169,20 +169,10 @@ function SortableRouteRow({ref={setNodeRef}style={{ transform: CSS.Translate.toString(transform), transition }}className={cn(- "flex items-center gap-2 border-b border-border/70 px-1 py-1.5 last:border-b-0",+ "flex items-center gap-2 py-2",isDragging && "relative z-10 rounded-md bg-background shadow-md",)}>- <button- type="button"- ref={setActivatorNodeRef}- {...attributes}- {...listeners}- aria-label={`Reorder ${label}, position ${position}`}- className="flex size-6 shrink-0 cursor-grab touch-none items-center justify-center rounded text-muted-foreground/70 outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"- >- <GripVerticalIcon className="size-3.5" />- </button><div className="min-w-0 flex-1"><p className="flex items-center gap-1.5 text-xs font-medium text-foreground">{label}@@ -199,6 +189,16 @@ function SortableRouteRow({</p>) : null}</div>+ <button+ type="button"+ ref={setActivatorNodeRef}+ {...attributes}+ {...listeners}+ aria-label={`Reorder ${label}, position ${position}`}+ className="flex size-6 shrink-0 cursor-grab touch-none items-center justify-center rounded text-muted-foreground/70 outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"+ >+ <GripVerticalIcon className="size-3.5" />+ </button>{removable ? (<Tooltip><TooltipTriggerdiff --git a/apps/web/src/components/settings/SessionPermissions.tsx b/apps/web/src/components/settings/SessionPermissions.tsxnew file mode 100644index 00000000000..1cbff3d750c--- /dev/null+++ b/apps/web/src/components/settings/SessionPermissions.tsx@@ -0,0 +1,38 @@+import { type EnvironmentId, sessionGrantsScope } from "@t3tools/contracts";+import { AUTH_SCOPE_OPTIONS } from "@t3tools/shared/authScopeOptions";+import { useEnvironmentSessionState } from "~/state/session";++export function SessionPermissions({+ environmentId,+ connected,+ routeContext = false,+}: {+ readonly environmentId: EnvironmentId;+ readonly connected: boolean;+ readonly routeContext?: boolean;+}) {+ const session = useEnvironmentSessionState(environmentId);+ return connected && !session.hasError && !session.isPending && session.data?.authenticated ? (+ <div className="space-y-3 py-3 text-xs">+ <p className="text-muted-foreground">+ {routeContext+ ? "These permissions apply to your active route. Other routes may have different permissions."+ : "These permissions apply to this client’s current connection."}+ </p>+ <ul className="grid gap-x-6 gap-y-2 sm:grid-cols-2">+ {AUTH_SCOPE_OPTIONS.map(({ scope, title }) => (+ <li key={scope} className="flex items-start justify-between gap-3">+ <span>{title}</span>+ <span className="shrink-0 text-muted-foreground">+ {sessionGrantsScope(session.data!, scope) ? "Allowed" : "Not granted"}+ </span>+ </li>+ ))}+ </ul>+ </div>+ ) : (+ <p className="py-3 text-xs text-muted-foreground">+ Permissions not checked. Connect to this environment to view this session’s permissions.+ </p>+ );+}diff --git a/apps/web/src/components/settings/scopedSettings.test.ts b/apps/web/src/components/settings/scopedSettings.test.tsindex 7e15b4e5a26..800ff48360a 100644--- a/apps/web/src/components/settings/scopedSettings.test.ts+++ b/apps/web/src/components/settings/scopedSettings.test.ts@@ -1,11 +1,13 @@import {DEFAULT_SERVER_SETTINGS,+ EnvironmentAuthorizationError,EnvironmentId,ProjectId,type ServerSettings,} from "@t3tools/contracts";import { describe, expect, it, vi } from "vite-plus/test";import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";+import * as Cause from "effect/Cause";import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping";@@ -410,7 +412,15 @@ describe("scoped settings writes", () => {const persistServer = vi.fn().mockResolvedValueOnce({ _tag: "Success" })- .mockResolvedValueOnce({ _tag: "Failure" })+ .mockResolvedValueOnce({+ _tag: "Failure",+ cause: Cause.fail(+ new EnvironmentAuthorizationError({+ requiredScope: "settings:write",+ message: "This connection lacks permission to change settings.",+ }),+ ),+ }).mockRejectedValueOnce(new Error("Disconnected during save")).mockResolvedValueOnce({ _tag: "Success" });const result = await persistScopedSettingsPatch(@@ -419,6 +429,14 @@ describe("scoped settings writes", () => {vi.fn(),);expect(result.savedEnvironmentCount).toBe(2);+ expect(result.savedEnvironments.map(({ label }) => label)).toEqual([+ laptop.label,+ fourth.label,+ ]);+ expect(result.failedEnvironments.map(({ message }) => message)).toEqual([+ "This connection lacks permission to change settings.",+ "Disconnected during save",+ ]);expect(result.failedEnvironments.map(({ label }) => label)).toEqual([server.label,third.label,diff --git a/apps/web/src/components/settings/scopedSettings.ts b/apps/web/src/components/settings/scopedSettings.tsindex e1e88463235..537c3bb381b 100644--- a/apps/web/src/components/settings/scopedSettings.ts+++ b/apps/web/src/components/settings/scopedSettings.ts@@ -19,6 +19,7 @@ import {type ProjectSettingSource,} from "@t3tools/shared/projectSettings";import * as Equal from "effect/Equal";+import * as Cause from "effect/Cause";import type { ResolvedSettingsScope } from "./settingsScope";@@ -394,7 +395,7 @@ export async function persistScopedSettingsPatch(persistServer: (input: {environmentId: EnvironmentId;input: { patch: ServerSettingsPatch };- }) => Promise<{ readonly _tag: "Success" | "Failure" }>,+ }) => Promise<{ readonly _tag: "Success" | "Failure"; readonly cause?: Cause.Cause<unknown> }>,persistClient: (patch: ClientSettingsPatch) => void,) {if (plan.hasClientWrite) persistClient(plan.clientPatch);@@ -403,12 +404,32 @@ export async function persistScopedSettingsPatch(persistServer({ environmentId, input: { patch } }),),);- const failedEnvironments = plan.serverWrites.filter((_, index) => {+ const failedEnvironments = plan.serverWrites.flatMap((environment, index) => {const result = results[index];- return result?.status !== "fulfilled" || result.value._tag === "Failure";+ if (result?.status === "fulfilled" && result.value._tag === "Success") return [];+ const error: unknown =+ result?.status === "rejected"+ ? result.reason+ : result?.status === "fulfilled" && result.value.cause+ ? Cause.squash(result.value.cause)+ : undefined;+ return [+ {+ ...environment,+ message:+ error instanceof Error+ ? error.message+ : "The save failed. Try reconnecting and saving again.",+ },+ ];+ });+ const savedEnvironments = plan.serverWrites.filter((_, index) => {+ const result = results[index];+ return result?.status === "fulfilled" && result.value._tag === "Success";});return {failedEnvironments,- savedEnvironmentCount: plan.serverWrites.length - failedEnvironments.length,+ savedEnvironments,+ savedEnvironmentCount: savedEnvironments.length,};}diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsxindex 99a47cb5aa6..381ba5c54f7 100644--- a/apps/web/src/components/settings/settingsLayout.tsx+++ b/apps/web/src/components/settings/settingsLayout.tsx@@ -1,6 +1,6 @@import { SettingsGroup } from "./SettingsGroup";import { AuthSettingsWriteScope } from "@t3tools/contracts";-import { usePrimaryEnvironmentId } from "../../state/environments";+import { usePrimaryEnvironmentId, usePrimaryEnvironment } from "../../state/environments";import { useEnvironmentScope, useEnvironmentsWithScope } from "../../state/session";import { InfoIcon, Undo2Icon } from "lucide-react";import { DEFAULT_SERVER_SETTINGS, type ServerSettings } from "@t3tools/contracts";@@ -290,6 +290,7 @@ export function SettingsRow({const primarySettingsAvailable = usePrimarySettingsAvailable();const context = useOptionalSettingsScope();const primaryEnvironmentId = usePrimaryEnvironmentId();+ const primaryEnvironment = usePrimaryEnvironment();const primaryCanWrite = useEnvironmentScope(primaryEnvironmentId, AuthSettingsWriteScope);const writableIds = useEnvironmentsWithScope(context?.connectedEnvironments ?? [],@@ -395,7 +396,14 @@ export function SettingsRow({unavailable && control? inertControl(!canWriteSettings- ? "This connection does not have permission to change environment settings."+ ? `This connection lacks permission to change settings on ${+ context+ ? context.connectedEnvironments+ .filter((target) => !writableIds.has(target.environmentId))+ .map((target) => target.label)+ .join(", ") || "the selected environment"+ : (primaryEnvironment?.label ?? "the primary environment")+ }.`: context? "Reconnect the selected environment to change this setting.": PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,diff --git a/apps/web/src/components/settings/useScopedSettings.ts b/apps/web/src/components/settings/useScopedSettings.tsindex 743eb4ec439..4bed07267b1 100644--- a/apps/web/src/components/settings/useScopedSettings.ts+++ b/apps/web/src/components/settings/useScopedSettings.ts@@ -83,20 +83,27 @@ function useRunScopedPlan() {Cause.fail(new EnvironmentAuthorizationError({requiredScope: missing,- message: "This connection cannot change these settings.",+ message: "This connection lacks permission to change these settings.",}),),);return persistServer(request);},persistClientSettingsPatch,- ).then(({ failedEnvironments, savedEnvironmentCount }) => {+ ).then(({ failedEnvironments, savedEnvironments, savedEnvironmentCount }) => {if (failedEnvironments.length === 0) return;toastManager.add({type: "error",title:savedEnvironmentCount > 0 ? "Setting saved on some environments" : "Setting not saved",- description: `Could not update ${failedEnvironments.map((environment) => environment.label).join(", ")}.${savedEnvironmentCount > 0 ? " The other selected environments saved the change." : ""}`,+ description: [+ ...failedEnvironments.map(+ ({ label, message }) => `Could not save on ${label}: ${message}`,+ ),+ ...(savedEnvironmentCount > 0+ ? [`Saved on ${savedEnvironments.map(({ label }) => label).join(", ")}.`]+ : []),+ ].join("\n"),});});},diff --git a/apps/web/src/hooks/useSettings.sync.test.tsx b/apps/web/src/hooks/useSettings.sync.test.tsxindex fd46cd8962d..129c5f5469b 100644--- a/apps/web/src/hooks/useSettings.sync.test.tsx+++ b/apps/web/src/hooks/useSettings.sync.test.tsx@@ -122,6 +122,54 @@ afterEach(async () => {});describe("shared settings writes", () => {+ it("waits for the remaining target before reporting a partial save", async () => {+ let finishRemote = () => {};+ const remote = new Promise((resolve) => {+ finishRemote = () => resolve(AsyncResult.success(DEFAULT_SERVER_SETTINGS));+ });+ state.persist.mockResolvedValueOnce(+ AsyncResult.failure(Cause.fail(new Error("Permission denied"))),+ );+ state.persist.mockReturnValueOnce(remote);+ await mountEditor();+ await act(async () => saveSharedSettings());+ expect(state.toast).not.toHaveBeenCalled();+ await act(async () => finishRemote());+ expect(state.toast).toHaveBeenCalledExactlyOnceWith({+ type: "error",+ title: "Setting saved on some environments",+ description: "Could not save on primary: Permission denied\nSaved on remote.",+ });+ });++ it("keeps a single-target failure specific to that environment", async () => {+ state.registry!.set(state.sessions.get(remoteId)!, AsyncResult.success(session([])));+ state.persist.mockResolvedValueOnce(+ AsyncResult.failure(Cause.fail(new Error("Permission denied"))),+ );+ await mountEditor();+ await act(async () => saveSharedSettings());+ expect(state.toast).toHaveBeenCalledExactlyOnceWith({+ type: "error",+ title: "Setting not saved",+ description: "Could not save on primary: Permission denied",+ });+ });++ it("names the failed environment when a server rejects a save after the grant check", async () => {+ state.persist.mockResolvedValueOnce(AsyncResult.success(DEFAULT_SERVER_SETTINGS));+ state.persist.mockResolvedValueOnce(+ AsyncResult.failure(Cause.fail(new Error("Permission denied"))),+ );+ await mountEditor();+ await act(async () => saveSharedSettings());+ expect(state.toast).toHaveBeenCalledExactlyOnceWith({+ type: "error",+ title: "Setting saved on some environments",+ description: "Could not save on remote: Permission denied\nSaved on primary.",+ });+ });+it("dispatches to the primary and connected remote before the remote grant finishes loading", async () => {await mountEditor();saveSharedSettings();@@ -193,7 +241,7 @@ describe("shared settings writes", () => {expect(state.toast).toHaveBeenCalledExactlyOnceWith({type: "warning",title: "Setting not saved",- description: "This connection does not have permission to change these settings.",+ description: "This connection lacks permission to change settings on remote.",});}},diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.tsindex 04fab1c1d1c..d61abb34f55 100644--- a/apps/web/src/hooks/useSettings.ts+++ b/apps/web/src/hooks/useSettings.ts@@ -29,6 +29,10 @@ import {type UnifiedSettings,} from "@t3tools/contracts/settings";import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";+import {+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";import {filterSharedServerPatch,splitSharedServerPatch,@@ -469,11 +473,29 @@ function useSharedSettingsSyncTargetIds(includePending = false): ReadonlyArray<Efunction useUpdateSettingsTarget(environmentId: EnvironmentId | null) {// Mount this session even on pages without a visible permission-gated control.useEnvironmentScope(environmentId, AuthSettingsWriteScope);- const persistServerSettings = useAtomCommand(- serverEnvironment.updateSettings,- "server settings update",- );+ const persist = useAtomCommand(serverEnvironment.updateSettings, {+ label: "server settings update",+ reportFailure: false,+ });const { environments } = useEnvironments();+ const persistServerSettings = useCallback(+ async (request: Parameters<typeof persist>[0]) => {+ const result = await persist(request);+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {+ const label =+ environments.find((environment) => environment.environmentId === request.environmentId)+ ?.label ?? request.environmentId;+ const error = squashAtomCommandFailure(result);+ toastManager.add({+ type: "error",+ title: "Setting not saved",+ description: `Could not save on ${label}: ${error instanceof Error ? error.message : "The save failed. Try reconnecting and saving again."}`,+ });+ }+ return result;+ },+ [environments, persist],+ );const sharedSettingsSyncTargetIds = useSharedSettingsSyncTargetIds(true);const updateSettings = useCallback((patch: UnifiedSettingsPatch) => {@@ -488,7 +510,7 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {toastManager.add({type: "warning",title: "Setting not saved",- description: "This connection does not have permission to change these settings.",+ description: `This connection lacks permission to change settings on ${environments.find((target) => target.environmentId === environmentId)?.label ?? "the selected environment"}.`,});}if (Object.keys(serverPatch).length > 0 && canWriteServerPatch) {@@ -518,8 +540,8 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {if (environmentId) {targets.add(environmentId);}- let wroteToTarget = false;- let permissionDenied = false;+ const writes: Array<Parameters<typeof persist>[0]> = [];+ const deniedLabels: string[] = [];for (const targetId of targets) {const target = environments.find((candidate) => candidate.environmentId === targetId);const targetPatch = filterSharedServerPatch(@@ -537,23 +559,52 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {readEnvironmentScope(targetId, scope),)) {- permissionDenied = true;+ deniedLabels.push(target?.label ?? targetId);continue;}- wroteToTarget = true;- void persistServerSettings({+ writes.push({environmentId: targetId,input: { patch: targetPatch },});}- if (!wroteToTarget) {+ if (writes.length === 0) {warnUnsaved(- permissionDenied- ? "This connection does not have permission to change these settings."+ deniedLabels.length > 0+ ? `This connection lacks permission to change settings on ${deniedLabels.join(", ")}.`: targets.size > 0? "Update older servers to save this setting.": undefined,);+ } else {+ void Promise.all(+ writes.map(async (request) => ({+ label:+ environments.find((target) => target.environmentId === request.environmentId)+ ?.label ?? request.environmentId,+ result: await persist(request),+ })),+ ).then((outcomes) => {+ const failures = outcomes.flatMap(({ label, result }) => {+ if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return [];+ const error = squashAtomCommandFailure(result);+ return [+ `Could not save on ${label}: ${error instanceof Error ? error.message : "The save failed. Try reconnecting and saving again."}`,+ ];+ });+ if (failures.length === 0) return;+ const saved = outcomes+ .filter(({ result }) => result._tag === "Success")+ .map(({ label }) => label);+ toastManager.add({+ type: "error",+ title:+ saved.length > 0 ? "Setting saved on some environments" : "Setting not saved",+ description: [+ ...failures,+ ...(saved.length > 0 ? [`Saved on ${saved.join(", ")}.`] : []),+ ].join("\n"),+ });+ });}}}@@ -561,7 +612,7 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {void persistClientSettingsPatch(clientPatch);}},- [environmentId, environments, persistServerSettings, sharedSettingsSyncTargetIds],+ [environmentId, environments, persist, persistServerSettings, sharedSettingsSyncTargetIds],);return updateSettings;diff --git a/docs/user/remote-access.md b/docs/user/remote-access.mdindex 87c8ee9bea6..73062245c9b 100644--- a/docs/user/remote-access.md+++ b/docs/user/remote-access.md@@ -91,6 +91,13 @@ or remove it. On mobile, open the machine under **Settings → Environments** anchoose **Edit**. Signing out of T3 Connect removes only that route; a machineyou can still reach another way stays saved.+Open **Permissions** next to **Routes** in web or desktop, or **Your permissions**+in the mobile route details, to see what your current connection can do on that+environment. For a remote environment, this is in its route details. Permissions+shown there apply only to the route marked **In use**; other routes are not+checked. Direct pairing and T3 Connect have separate sessions and may grant+different permissions.+### Balance new threads across machinesAuto balance is off by default. On web and desktop, enable it indiff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 697dbeb81e3..ec9277fc0cd 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -3,6 +3,10 @@"private": true,"type": "module","exports": {+ "./authScopeOptions": {+ "types": "./src/authScopeOptions.ts",+ "import": "./src/authScopeOptions.ts"+ },"./orchestrationV2ThreadError": {"types": "./src/orchestrationV2ThreadError.ts","import": "./src/orchestrationV2ThreadError.ts"diff --git a/packages/shared/src/authScopeOptions.ts b/packages/shared/src/authScopeOptions.tsnew file mode 100644index 00000000000..d443e50326d--- /dev/null+++ b/packages/shared/src/authScopeOptions.ts@@ -0,0 +1,106 @@+import {+ AuthAccessReadScope,+ AuthAccessWriteScope,+ AuthDiagnosticsReadScope,+ AuthEnvironmentMaintainScope,+ AuthFilesystemReadScope,+ AuthFilesystemWriteScope,+ type AuthGrantScope,+ AuthOrchestrationOperateScope,+ AuthOrchestrationReadScope,+ AuthPreviewOperateScope,+ AuthProvidersManageScope,+ AuthRelayReadScope,+ AuthRelayWriteScope,+ AuthSettingsWriteScope,+ AuthSourceControlWriteScope,+ AuthTerminalOperateScope,+ AuthTerminalReadScope,+} from "@t3tools/contracts";++export const AUTH_SCOPE_OPTIONS: ReadonlyArray<{+ readonly scope: AuthGrantScope;+ readonly title: string;+ readonly description: string;+}> = [+ {+ scope: AuthOrchestrationReadScope,+ title: "View environment",+ description: "Read threads, status, checkpoints, and configuration.",+ },+ {+ scope: AuthOrchestrationOperateScope,+ title: "Operate tasks",+ description: "Start, update, and stop tasks.",+ },+ {+ scope: AuthSettingsWriteScope,+ title: "Change environment settings",+ description: "Edit environment preferences and keybindings.",+ },+ {+ scope: AuthProvidersManageScope,+ title: "Manage providers",+ description: "Configure, install, sign in to, and update providers and usage sources.",+ },+ {+ scope: AuthEnvironmentMaintainScope,+ title: "Maintain environment",+ description: "Update the server and control environment processes.",+ },+ {+ scope: AuthPreviewOperateScope,+ title: "Control previews",+ description: "Open browser previews and host browser automation.",+ },+ {+ scope: AuthDiagnosticsReadScope,+ title: "View diagnostics and usage",+ description: "Read process diagnostics, resource history, and usage totals.",+ },+ {+ scope: AuthTerminalReadScope,+ title: "View terminals",+ description: "Read existing terminal output and status.",+ },+ {+ scope: AuthTerminalOperateScope,+ title: "Use terminals",+ description: "Create terminals and send input to running shells.",+ },+ {+ scope: AuthSourceControlWriteScope,+ title: "Change source control",+ description: "Commit, push, manage branches and repositories, and change pull requests.",+ },+ {+ scope: AuthFilesystemReadScope,+ title: "Read files",+ description: "Browse host files, search workspaces, and inspect local changes.",+ },+ {+ scope: AuthFilesystemWriteScope,+ title: "Write files",+ description: "Edit workspace files and save plans to disk.",+ },+ {+ scope: AuthAccessReadScope,+ title: "View access",+ description: "Inspect pairing links and authorized clients.",+ },+ {+ scope: AuthAccessWriteScope,+ title: "Manage access",+ description: "Issue and revoke credentials for other clients.",+ },+ {+ scope: AuthRelayReadScope,+ title: "View relay",+ description: "Inspect managed relay connectivity.",+ },+ {+ scope: AuthRelayWriteScope,+ title: "Manage relay",+ description: "Change managed tunnel connectivity.",+ },+];