feat(auth): separate environment administration permissions #9786
Mergedjuliusmarmingemerged 76 commits into
t3code/auth-pairing-scopes fromrefs/pull/9786/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/web/src/components/settings/ProviderInstanceCard.tsx line 1133Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -855,9 +855,4 @@855855 </SettingsSection>856856857857 {driverOption !== undefined ? (858- <SettingsSection859- title="Models"860- inert={readOnly}861- aria-disabled={readOnly || undefined}862- className={readOnly ? "opacity-50 select-none" : undefined}863- >858+ <SettingsSection title="Models">apps/web/src/components/settings/ConnectionsSettings.tsx line 2266Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1890,7 +1955,13 @@18901955 const setDefaultAdvertisedEndpointKey = useUiStateStore(18911956 (state) => state.setDefaultAdvertisedEndpointKey,18921957 );1893- const canManageLocalBackend = currentSessionScopes?.includes(AuthAccessWriteScope) ?? false;1894- const canManageRelay = currentSessionScopes?.includes(AuthRelayWriteScope) ?? false;1958+ const canReadAccess = useEnvironmentScope(primaryEnvironmentId, AuthAccessReadScope);1959+ const canWriteAccess = useEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope);1960+ const canReadRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope);1961+ const canManageLocalBackend = useEnvironmentScope(1962+ primaryEnvironmentId,1963+ AuthEnvironmentMaintainScope,1964+ );1965+ const canManageRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope);18951966 const authAccessChanges = useEnvironmentQuery(1896- canManageLocalBackend && primaryEnvironmentId !== null1967+ canReadAccess && primaryEnvironmentId !== nullapps/web/src/hooks/useSettings.ts line 483Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -399,4 +415,6 @@399415 (patch: UnifiedSettingsPatch) => {400416 const { serverPatch, clientPatch } = splitPatch(patch);401417402- if (Object.keys(serverPatch).length > 0) {418+ const canWriteServerPatch =419+ environmentId === null ||420+ requiredScopesForServerSettingsPatch(serverPatch).every((scope) =>
juliusmarminge changed the title
- @@ -569,0 +573,21 @@573+ (get) =>574+ new Set(575+ environments.filter(supportsSharedSettingsSync).flatMap((environment) => {576+ const result = get(environmentSession.sessionStateAtom(environment.environmentId));577+ const session = result._tag === "Success" ? result.value : null;578+ return session?.authenticated === true &&579+ session.scopes?.includes(AuthSettingsWriteScope)580+ ? [environment.environmentId]581+ : [];582+ }),583+ ),584+ ),585+ [environments],586+ );587+ const writableEnvironmentIds = useAtomValue(writableEnvironmentIdsAtom);588+ const availableTargets = environments.filter(supportsSharedSettingsSync);589+ const syncTargets = availableTargets.filter((environment) =>590+ writableEnvironmentIds.has(environment.environmentId),591+ );592+ const canWriteSettings = syncTargets.length > 0;593+ const reference = syncTargets[0] ?? availableTargets[0] ?? null;
- @@ -31,13 +34,4 @@3134 [ORCHESTRATION_WS_METHODS.subscribeThread]: AuthOrchestrationReadScope,3235 [WS_METHODS.serverProbe]: AuthOrchestrationReadScope,3336 [WS_METHODS.serverGetConfig]: AuthOrchestrationReadScope,34- [WS_METHODS.serverRefreshProviders]: AuthOrchestrationOperateScope,35- [WS_METHODS.serverUpdateProvider]: AuthOrchestrationOperateScope,36- [WS_METHODS.providerAuthStart]: AuthOrchestrationOperateScope,37- [WS_METHODS.providerConsumeResetCredit]: AuthOrchestrationOperateScope,38- [WS_METHODS.providerAuthComplete]: AuthOrchestrationOperateScope,39- [WS_METHODS.providerAuthCancel]: AuthOrchestrationOperateScope,40- [WS_METHODS.providerAuthLogout]: AuthOrchestrationOperateScope,41- [WS_METHODS.providerAuthSubscribe]: AuthOrchestrationOperateScope,42- [WS_METHODS.providerInstallStart]: AuthOrchestrationOperateScope,43- [WS_METHODS.providerInstallCancel]: AuthOrchestrationOperateScope,37+ [WS_METHODS.serverRefreshProviders]: AuthOrchestrationReadScope,apps/web/src/components/settings/EnvironmentIconPicker.tsx line 58Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -85,4 +54,4 @@8554 readonly size?: "xs" | "sm";8655 }) {8756 const updateSettings = useUpdateEnvironmentSettings(environmentId);88- const operateAccess = useEnvironmentOperateAccess(environmentId);57+ const operateAccess = useEnvironmentScope(environmentId, AuthSettingsWriteScope)@@ -3190,4 +3324,4 @@31903324 }31913325 />31923326 ) : null}3193- {desktopBridge ? (3327+ {desktopBridge && canManageLocalBackend ? (
- @@ -424,21 +424,2 @@424- // checks the scopes its cookie session was granted.425- if (isElectron) {426- return (427- <AccessGatedProviderSettings428- environment={environment}429- operateAccess="granted"430- deviceTabs={deviceTabs}431- targetInstanceId={targetInstanceId}432- />433- );434- }435- return (436- <PrimarySessionGatedProviderSettings437- environment={environment}438- deviceTabs={deviceTabs}439- targetInstanceId={targetInstanceId}440- />441- );442- }443424 return (444425 <RemoteSessionGatedProviderSettingsapps/web/src/components/settings/DiagnosticsSettings.tsx line 334OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -329,2 +333,2 @@329333 render={330334 <button
- apps/web/src/components/ChatView.tsx line 3599OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3546,8 +3580,20 @@3580+ : AsyncResult.failure(3581+ Cause.fail(3582+ new Error(3583+ "The script was saved, but this connection can no longer change keyboard shortcuts.",3584+ ),3585+ ),3586+ );3587+ }3588+ if (keybindingRule) {35463589 return mapAtomCommandResult(35473590 await upsertKeybinding({35483591 environmentId,3549- input: keybindingRule,3592+ input: previousTarget ? { ...keybindingRule, replace: previousTarget } : keybindingRule,35503593 }),35513594 () => undefined,35523595 );35533596 }3597+ if (previousTarget) {3598+ return mapAtomCommandResult(3599+ await removeKeybinding({ environmentId, input: previousTarget }),apps/web/src/components/ChatView.tsx lines 5030 to 5032Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3523,3 +3530,15 @@35233530 keybinding?: string | null;35243531 keybindingCommand: KeybindingCommand;35253532 }): Promise<AtomCommandResult<void, unknown>> => {3533+ const previousKeybinding = keybindingValueForCommand(3534+ appAtomRegistry.get(serverEnvironment.configValueAtom(environmentId))?.keybindings ?? [],3535+ input.keybindingCommand,3536+ );3537+ const isDeletingScript = !input.nextScripts.some(3538+ (script) => commandForProjectScript(script.id) === input.keybindingCommand,3539+ );3540+ const changesKeybinding =3541+ isElectron &&3542+ input.keybinding !== undefined &&3543+ (input.keybinding?.trim() || null) !== previousKeybinding &&3544+ (!isDeletingScript || readEnvironmentScope(environmentId, AuthSettingsWriteScope));
- apps/web/src/cloud/useCloudLinkController.ts line 105OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -84,3 +86,20 @@8486 reportUpdateFailure(new Error("Local environment is not ready yet."));8587 return false;8688 }89+ const readManageableLinkState = () => {90+ if (91+ !readEnvironmentScope(target.environmentId, AuthRelayReadScope) ||92+ !readEnvironmentScope(target.environmentId, AuthRelayWriteScope)93+ ) {94+ reportUpdateFailure(95+ new Error("This connection needs permission to view and manage T3 Connect settings."),96+ );97+ return null;98+ }99+ const state = readCachedPrimaryCloudLinkState(target);100+ if (state === null) {101+ reportUpdateFailure(new Error("Wait until the current T3 Connect settings can be read."));102+ }103+ return state;104+ };105+ if (readManageableLinkState() === null) return false;
- apps/web/src/hooks/useSettings.ts line 452Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -371,8 +376,15 @@371376 /** Environments that can receive a shared settings write right now. */372377 function useSharedSettingsSyncTargetIds(): ReadonlyArray<EnvironmentId> {373378 const { environments } = useEnvironments();374- return useMemo(379+ const writableTargetsAtom = useMemo(375380 () =>376- environments377- .filter(supportsSharedSettingsSync)378- .map((environment) => environment.environmentId),381+ Atom.make((get) =>382+ environments.filter(supportsSharedSettingsSync).flatMap((environment) => {383+ // Subscribe before offering sync so the first action sees each target's grant.384+ const result = get(environmentSession.sessionStateAtom(environment.environmentId));385+ const session =386+ result._tag === "Failure" ? null : Option.getOrNull(AsyncResult.value(result));387+ return session?.authenticated && session.scopes?.includes(AuthSettingsWriteScope)388+ ? [environment.environmentId]389+ : [];390+ }),
- apps/web/src/components/chat/ChatHeader.tsx line 424OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -421,3 +421,4 @@421421 >422422 {activeProjectScripts && (423423 <ProjectScriptsControl424+ environmentId={activeThreadEnvironmentId}
- @@ -558,3 +560,11 @@558560 // Captured before the write so a cleared or deleted binding can be559561 // removed from the keybindings config afterwards.560562 const previousKeybinding = keybindingValueForCommand(keybindings, keybindingCommand);563+ const isDeletingScript = !nextScripts.some(564+ (script) => commandForProjectScript(script.id) === keybindingCommand,565+ );566+ const changesKeybinding =567+ isElectron &&568+ keybinding !== undefined &&569+ (keybinding?.trim() || null) !== previousKeybinding &&570+ (!isDeletingScript ||apps/web/src/components/settings/ProviderSettingsPanel.tsx lines 1085 to 1088Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -927,4 +885,7 @@927885 onUpdate={(next) => {928886 const wasEnabled = resolveProviderInstanceEnabled(row.instance);929887 const isDisabling = next.enabled === false && wasEnabled;930- const shouldClearTextGen = isDisabling && textGenInstanceId === row.instanceId;888+ const shouldClearTextGen =889+ isDisabling &&890+ textGenInstanceId === row.instanceId &&891+ readEnvironmentScope(environmentId, AuthSettingsWriteScope);apps/web/src/keybindings.ts line 180Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -222,3 +223,11 @@222223 return null;223224 }224225226+/** App shortcuts use the primary environment; script shortcuts belong to the active project. */227+export function resolveChatShortcutCommand(228+ event: ShortcutEventLike,229+ primaryKeybindings: ResolvedKeybindingsConfig,230+ activeKeybindings: ResolvedKeybindingsConfig,231+ options?: ShortcutMatchOptions,232+): KeybindingCommand | null {233+ const primaryCommand = resolveShortcutCommand(event, primaryKeybindings, options);
- apps/web/src/editorPreferences.ts lines 99 to 101OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -89,3 +96,6 @@8996 ),9097 );9198 }99+ if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {100+ return AsyncResult.failure(101+ Cause.fail(new Error("This connection cannot open an editor on this environment.")),apps/web/src/state/use-orchestration-command.ts lines 22 to 24OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +4,21 @@4+ AtomCommandResult,5+} from "@t3tools/client-runtime/state/runtime";6+import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts";7+import * as Cause from "effect/Cause";8+import { AsyncResult } from "effect/unstable/reactivity";9+import { useCallback } from "react";10+11+import { readEnvironmentScope } from "./session";12+import { useAtomCommand } from "./use-atom-command";13+14+/** Recheck the target grant for every step of a thread or project mutation. */15+export function useOrchestrationCommand<W extends { readonly environmentId: EnvironmentId }, A, E>(16+ command: AtomCommand<W, A, E>,17+ options?: string | AtomCommandOptions,18+): (value: W) => Promise<AtomCommandResult<A, E | Error>> {19+ const run = useAtomCommand(command, options);20+ return useCallback(21+ async (value: W): Promise<AtomCommandResult<A, E | Error>> => {22+ if (!readEnvironmentScope(value.environmentId, AuthOrchestrationOperateScope)) {23+ return AsyncResult.failure(24+ Cause.fail(new Error("This connection cannot change threads or projects.")),
- apps/mobile/src/state/attachments.ts lines 12 to 18OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1,5 +1,18 @@11 import { createAttachmentEnvironmentAtoms } from "@t3tools/client-runtime/state/attachments";2+import type { AtomCommand } from "@t3tools/client-runtime/state/runtime";3+import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts";4+import * as Cause from "effect/Cause";5+import { AsyncResult } from "effect/unstable/reactivity";2637 import { connectionAtomRuntime } from "../connection/runtime";8+import { readEnvironmentScope } from "./session";495-export const attachmentEnvironment = createAttachmentEnvironmentAtoms(connectionAtomRuntime);10+function requireAttachmentWriteAccess<W extends { readonly environmentId: EnvironmentId }, A, E>(11+ command: AtomCommand<W, A, E>,12+): AtomCommand<W, A, E | Error> {13+ return {14+ ...command,15+ run: async (registry, input) => {16+ if (!readEnvironmentScope(input.environmentId, AuthOrchestrationOperateScope)) {17+ return AsyncResult.failure(18+ Cause.fail(new Error("This connection cannot change attachments.")),
- apps/web/src/cloud/useCloudLinkController.ts lines 91 to 92OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -84,4 +86,7 @@8486 reportUpdateFailure(new Error("Local environment is not ready yet."));8587 return false;8688 }87- const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));89+ const canManageLink = () => {90+ if (91+ !readEnvironmentScope(target.environmentId, AuthRelayReadScope) ||92+ !readEnvironmentScope(target.environmentId, AuthRelayWriteScope)apps/web/src/components/ChatView.tsx lines 5028 to 5042Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -3734,0 +3760,21 @@3760+ appAtomRegistry.get(serverEnvironment.configValueAtom(environmentId))?.keybindings ?? [],3761+ input.keybindingCommand,3762+ );3763+ const isDeletingScript = !input.nextScripts.some(3764+ (script) => commandForProjectScript(script.id) === input.keybindingCommand,3765+ );3766+ const changesKeybinding =3767+ isElectron &&3768+ input.keybinding !== undefined &&3769+ (input.keybinding?.trim() || null) !== previousKeybinding &&3770+ (!isDeletingScript || readEnvironmentScope(environmentId, AuthSettingsWriteScope));3771+ if (changesKeybinding && !readEnvironmentScope(environmentId, AuthSettingsWriteScope)) {3772+ return AsyncResult.failure(3773+ Cause.fail(3774+ new EnvironmentAuthorizationError({3775+ requiredScope: AuthSettingsWriteScope,3776+ message: "This connection cannot change keyboard shortcuts.",3777+ }),3778+ ),3779+ );3780+ }apps/web/src/components/projectScriptEditor.tsx lines 282 to 284Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -219,4 +242,6 @@219242 command: trimmedCommand,220243 icon,221244 runOnWorktreeCreate,222- keybinding: keybindingRule?.key ?? null,245+ ...((request.scriptId === null && canChangeKeybinding) || changesKeybinding246+ ? { keybinding: keybindingRule?.key ?? null }247+ : {}),apps/web/src/components/settings/ProviderInstanceCard.tsx lines 1133 to 1140Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -889,11 +889,7 @@889889 </SettingsSection>890890891891 {driverOption !== undefined ? (892- <SettingsSection893- title="Models"894- inert={readOnly}895- aria-disabled={readOnly || undefined}896- className={readOnly ? "opacity-50 select-none" : undefined}897- >892+ <SettingsSection title="Models">898893 <div className="px-3 py-3 sm:px-4">899894 <ProviderModelsSection895+ canManageCustomModels={!readOnly}
- @@ -804,3 +808,5 @@804808 </ComposerDictationToolbar>805809 </Animated.View>806810 </ComposerSurface>811+812+ {!props.canOperateThread ? (apps/web/src/components/chat/ChatComposer.tsx line 1504OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1495,4 +1501,4 @@14951501 const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);1496150214971503 useEffect(() => {1498- if (!attachmentUploadsCapabilityKnown) {1504+ if (!attachmentUploadsCapabilityKnown || !canOperateThread) {apps/web/src/components/ChatView.tsx line 7898Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -5905,3 +5992,4 @@59055992 }5906599359075994 if (command === "thread.settle") {5995+ if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;apps/web/src/components/projectScriptEditor.tsx lines 95 to 96Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -78,4 +83,5 @@7883 command: string;7984 icon: ProjectScriptIcon;8085 runOnWorktreeCreate: boolean;81- keybinding: string | null;86+ /** Omit to preserve the current shortcut when the form did not edit it. */87+ keybinding?: string | null;
- apps/web/src/components/settings/ProjectSettingsPanel.tsx line 1276OutdatedResolvedby juliusmarminge@@ -1168,4 +1273,4 @@11681273 <SettingResetButton11691274 label="automatic pull"11701275 tooltip="Reset to inherited automatic pull setting"1171- disabled={savingBrowserAccess}1276+ disabled={savingBrowserAccess || !canEditGroup}
- apps/server/src/auth/RpcAuthorization.ts line 68Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -34,11 +37,11 @@34- [WS_METHODS.serverRefreshProviders]: AuthOrchestrationOperateScope,35- [WS_METHODS.serverUpdateProvider]: AuthOrchestrationOperateScope,36- [WS_METHODS.providerAuthStart]: AuthOrchestrationOperateScope,37- [WS_METHODS.providerConsumeResetCredit]: AuthOrchestrationOperateScope,38- [WS_METHODS.providerAuthComplete]: AuthOrchestrationOperateScope,39- [WS_METHODS.providerAuthCancel]: AuthOrchestrationOperateScope,40- [WS_METHODS.providerAuthLogout]: AuthOrchestrationOperateScope,41- [WS_METHODS.providerAuthSubscribe]: AuthOrchestrationOperateScope,42- [WS_METHODS.providerInstallStart]: AuthOrchestrationOperateScope,43- [WS_METHODS.providerInstallCancel]: AuthOrchestrationOperateScope,37+ [WS_METHODS.serverRefreshProviders]: AuthOrchestrationReadScope,38+ [WS_METHODS.serverUpdateProvider]: AuthProvidersManageScope,39+ [WS_METHODS.providerAuthStart]: AuthProvidersManageScope,40+ [WS_METHODS.providerConsumeResetCredit]: AuthProvidersManageScope,41+ [WS_METHODS.providerAuthComplete]: AuthProvidersManageScope,42+ [WS_METHODS.providerAuthCancel]: AuthProvidersManageScope,43+ [WS_METHODS.providerAuthLogout]: AuthProvidersManageScope,44+ [WS_METHODS.providerAuthSubscribe]: AuthProvidersManageScope,45+ [WS_METHODS.providerInstallStart]: AuthProvidersManageScope,46+ [WS_METHODS.providerInstallCancel]: AuthProvidersManageScope,4447 [WS_METHODS.providerInstallSubscribe]: AuthOrchestrationReadScope,apps/web/src/components/ChatView.tsx lines 1575 to 1576Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1419,9 +1432,11 @@14191432 const upsertKeybinding = useAtomCommand(serverEnvironment.upsertKeybinding, {14201433 reportFailure: false,14211434 });1435+ const removeKeybinding = useAtomCommand(serverEnvironment.removeKeybinding, {1436+ reportFailure: false,1437+ });14221438 const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");14231439 const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");14241440 const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close");1425- const createThread = useAtomCommand(threadEnvironment.create, { reportFailure: false });1426- const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });1427- const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {1441+ const createThread = useOrchestrationCommand(threadEnvironment.create, { reportFailure: false });1442+ const deleteThread = useOrchestrationCommand(threadEnvironment.delete, { reportFailure: false });apps/web/src/components/ChatView.tsx lines 3998 to 4000OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -3931,9 +3994,7 @@39313994 return updateResult;39323995 }393339963934- const keybindingRule = decodeProjectScriptKeybindingRule({3935- keybinding: input.keybinding,3936- command: input.keybindingCommand,3937- });3938-3939- if (isElectron && keybindingRule) {3997+ if (!changesKeybinding) return updateResult;3998+ if (!readEnvironmentScope(environmentId, AuthSettingsWriteScope)) {3999+ return isDeletingScript4000+ ? updateResult
juliusmarminge added labelsmacroscope-review
Sign in to join this conversation.












Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline: unavailable · PR result:
bd3387e· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.