Open History to see the last commit
1import {
2 CLIENT_GUARDED_RPC_SCOPES,
3 type DeviceListInput,
4 clientRpcRequiredScopes,
5 containsSecretReference,
6 authScopeRequiredResponse,
7 AssetCreateUrlInput,
8 AuthAccessReadScope,
9 ServerSettingsPatch,
10 ProviderInstanceMutation,
11 requiredScopesForServerSettingsPatch,
12 requiredScopesForProjectMutation,
13 ProjectMutation,
14 AuthSettingsWriteScope,
15 AuthProvidersManageScope,
16 AuthEnvironmentMaintainScope,
17 AuthFilesystemReadScope,
18 AuthFilesystemWriteScope,
19 AuthDiagnosticsReadScope,
20 AuthOrchestrationOperateScope,
21 AuthOrchestrationReadScope,
22 AuthPreviewOperateScope,
23 AuthRelayReadScope,
24 AuthRelayWriteScope,
25 AuthTerminalOperateScope,
26 ORCHESTRATION_V2_WS_METHODS,
27 AuthTerminalReadScope,
28 type AuthEnvironmentScope,
29 EnvironmentAuthorizationError,
30 RpcScopeAuthorization,
31 WS_METHODS,
32 WsRpcGroup,
33} from "@t3tools/contracts";
34import * as Effect from "effect/Effect";
35import * as Schema from "effect/Schema";
36import * as Layer from "effect/Layer";
37import type * as RpcGroup from "effect/rpc/RpcGroup";
38
39type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];
40
41export const RPC_REQUIRED_SCOPES = {
42 ...CLIENT_GUARDED_RPC_SCOPES,
43 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
44 [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,
45 [ORCHESTRATION_V2_WS_METHODS.getNativeChildWork]: AuthOrchestrationReadScope,
46 [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope,
47 [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: AuthOrchestrationOperateScope,
48 [ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,
49 [ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope,
50 [ORCHESTRATION_V2_WS_METHODS.searchThreads]: AuthOrchestrationReadScope,
51 [ORCHESTRATION_V2_WS_METHODS.searchThread]: AuthOrchestrationReadScope,
52 [ORCHESTRATION_V2_WS_METHODS.searchThreadStream]: AuthOrchestrationReadScope,
53 [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: AuthOrchestrationReadScope,
54 [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: AuthOrchestrationReadScope,
55 [ORCHESTRATION_V2_WS_METHODS.getThreadTitles]: AuthOrchestrationReadScope,
56 [ORCHESTRATION_V2_WS_METHODS.getThreadLinkMetadata]: AuthOrchestrationReadScope,
57 [ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds]: AuthOrchestrationReadScope,
58 [ORCHESTRATION_V2_WS_METHODS.getOlderSettledThreads]: AuthOrchestrationReadScope,
59 [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: AuthOrchestrationReadScope,
60 [ORCHESTRATION_V2_WS_METHODS.getTurnItem]: AuthOrchestrationReadScope,
61 [ORCHESTRATION_V2_WS_METHODS.launchThread]: AuthOrchestrationOperateScope,
62 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: AuthOrchestrationReadScope,
63 [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: AuthOrchestrationReadScope,
64 [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: AuthOrchestrationReadScope,
65 [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: AuthOrchestrationReadScope,
66 [WS_METHODS.projectsMutate]: AuthOrchestrationOperateScope,
67 [WS_METHODS.serverProbe]: AuthOrchestrationReadScope,
68 [WS_METHODS.serverGetConfig]: AuthOrchestrationReadScope,
69 [WS_METHODS.serverGetNpmRelease]: AuthOrchestrationReadScope,
70 [WS_METHODS.serverRefreshProviders]: AuthOrchestrationReadScope,
71 [WS_METHODS.serverUpdateProvider]: AuthProvidersManageScope,
72 [WS_METHODS.providerAuthStart]: AuthProvidersManageScope,
73 [WS_METHODS.providerConsumeResetCredit]: AuthProvidersManageScope,
74 [WS_METHODS.providerAuthComplete]: AuthProvidersManageScope,
75 [WS_METHODS.chatGptReconnectProfile]: AuthProvidersManageScope,
76 [WS_METHODS.chatGptImportProfile]: AuthProvidersManageScope,
77 [WS_METHODS.chatGptHandoffSubscribe]: AuthProvidersManageScope,
78 [WS_METHODS.providerAuthRespond]: AuthProvidersManageScope,
79 [WS_METHODS.providerAuthCancel]: AuthProvidersManageScope,
80 [WS_METHODS.providerAuthRemoveMethod]: AuthProvidersManageScope,
81 [WS_METHODS.providerAuthLogout]: AuthProvidersManageScope,
82 [WS_METHODS.providerAuthSubscribe]: AuthProvidersManageScope,
83 [WS_METHODS.providerInstallStart]: AuthProvidersManageScope,
84 [WS_METHODS.providerInstallCancel]: AuthProvidersManageScope,
85 [WS_METHODS.providerInstallSubscribe]: AuthOrchestrationReadScope,
86 [WS_METHODS.providerInstallRemove]: AuthProvidersManageScope,
87 [WS_METHODS.serverUpdateServer]: AuthEnvironmentMaintainScope,
88 [WS_METHODS.serverUpdateServerWithProgress]: AuthEnvironmentMaintainScope,
89 [WS_METHODS.serverCommitDesktopUpdate]: AuthEnvironmentMaintainScope,
90 [WS_METHODS.serverUpsertKeybinding]: AuthSettingsWriteScope,
91 [WS_METHODS.serverRemoveKeybinding]: AuthSettingsWriteScope,
92 [WS_METHODS.serverGetStorageCleanupReport]: AuthOrchestrationReadScope,
93 [WS_METHODS.serverGetDatabaseStorage]: AuthOrchestrationReadScope,
94 [WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope,
95 [WS_METHODS.peerLinksList]: AuthAccessReadScope,
96 [WS_METHODS.serverUpdateSettings]: AuthSettingsWriteScope,
97 [WS_METHODS.serverSearchAcpRegistry]: AuthOrchestrationReadScope,
98 [WS_METHODS.serverPrepareAcpRegistryAgent]: AuthProvidersManageScope,
99 [WS_METHODS.serverUninstallAcpRegistryManagedBinary]: AuthProvidersManageScope,
100 [WS_METHODS.serverAcceptAcpRegistryUrlAuth]: AuthProvidersManageScope,
101 [WS_METHODS.serverListAcpRegistrySessions]: AuthOrchestrationReadScope,
102 [WS_METHODS.serverImportAcpRegistrySession]: AuthOrchestrationOperateScope,
103 [WS_METHODS.serverDeleteAcpRegistrySession]: AuthOrchestrationOperateScope,
104 [WS_METHODS.serverListAcpRegistryProviders]: AuthOrchestrationReadScope,
105 [WS_METHODS.serverSetAcpRegistryProvider]: AuthProvidersManageScope,
106 [WS_METHODS.serverDisableAcpRegistryProvider]: AuthProvidersManageScope,
107 [WS_METHODS.serverLogoutAcpRegistry]: AuthProvidersManageScope,
108 [WS_METHODS.serverDiscoverSourceControl]: AuthOrchestrationReadScope,
109 [WS_METHODS.serverGetTraceDiagnostics]: AuthDiagnosticsReadScope,
110 [WS_METHODS.serverGetProcessDiagnostics]: AuthDiagnosticsReadScope,
111 // Thread load balancing reads host load, so it needs thread scope rather than diagnostics scope.
112 [WS_METHODS.serverGetHostResources]: AuthOrchestrationReadScope,
113 [WS_METHODS.serverGetProcessResourceHistory]: AuthDiagnosticsReadScope,
114 [WS_METHODS.serverGetResourceTelemetryHistory]: AuthDiagnosticsReadScope,
115 [WS_METHODS.serverRetryResourceTelemetry]: AuthDiagnosticsReadScope,
116 [WS_METHODS.serverGetUsageSummary]: AuthDiagnosticsReadScope,
117 [WS_METHODS.serverRefreshUsageRates]: AuthDiagnosticsReadScope,
118 [WS_METHODS.serverSignalProcess]: AuthEnvironmentMaintainScope,
119 [WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope,
120 [WS_METHODS.scheduledTasksSubscribe]: AuthOrchestrationReadScope,
121 [WS_METHODS.secretsAnswerRequest]: AuthOrchestrationOperateScope,
122 // Delivery logs hold request bodies, so they need the same scope as the URL.
123 [WS_METHODS.scheduledTasksListWebhookDeliveries]: AuthOrchestrationOperateScope,
124 [WS_METHODS.scheduledTasksGetWebhookDelivery]: AuthOrchestrationOperateScope,
125 [WS_METHODS.cloudGetRelayClientStatus]: AuthRelayReadScope,
126 [WS_METHODS.cloudInstallRelayClient]: AuthRelayWriteScope,
127 [WS_METHODS.pullRequestsList]: AuthOrchestrationReadScope,
128 [WS_METHODS.pullRequestsListStats]: AuthOrchestrationReadScope,
129 [WS_METHODS.pullRequestsFilterOptions]: AuthOrchestrationReadScope,
130 [WS_METHODS.pullRequestsSummary]: AuthOrchestrationReadScope,
131 [WS_METHODS.pullRequestsRouting]: AuthOrchestrationReadScope,
132 [WS_METHODS.pullRequestsRoutingIdentity]: AuthOrchestrationReadScope,
133 [WS_METHODS.pullRequestsStack]: AuthOrchestrationReadScope,
134 [WS_METHODS.pullRequestsLinkedThreads]: AuthOrchestrationReadScope,
135 [WS_METHODS.pullRequestsDetail]: AuthOrchestrationReadScope,
136 [WS_METHODS.issuesList]: AuthOrchestrationReadScope,
137 [WS_METHODS.issuesDetail]: AuthOrchestrationReadScope,
138 [WS_METHODS.issuesComments]: AuthOrchestrationReadScope,
139 [WS_METHODS.issuesTemplates]: AuthOrchestrationReadScope,
140 [WS_METHODS.issuesCandidates]: AuthOrchestrationReadScope,
141 [WS_METHODS.issuesLinkedThreads]: AuthOrchestrationReadScope,
142 [WS_METHODS.issueTrackersList]: AuthOrchestrationReadScope,
143 [WS_METHODS.issueTrackersConnect]: AuthSettingsWriteScope,
144 [WS_METHODS.issueTrackersBindProject]: AuthSettingsWriteScope,
145 [WS_METHODS.pullRequestsPreview]: AuthOrchestrationReadScope,
146 [WS_METHODS.pullRequestsChecks]: AuthOrchestrationReadScope,
147 [WS_METHODS.pullRequestsActivity]: AuthOrchestrationReadScope,
148 [WS_METHODS.pullRequestsReviewGuide]: AuthOrchestrationReadScope,
149 [WS_METHODS.pullRequestsThreadComments]: AuthOrchestrationReadScope,
150 [WS_METHODS.pullRequestsDiffFileContents]: AuthOrchestrationReadScope,
151 [WS_METHODS.pullRequestsFilesViewed]: AuthOrchestrationReadScope,
152 [WS_METHODS.pullRequestsChangeBreakdown]: AuthOrchestrationReadScope,
153 [WS_METHODS.pullRequestsInvalidate]: AuthOrchestrationReadScope,
154 [WS_METHODS.pullRequestsReportState]: AuthOrchestrationReadScope,
155 [WS_METHODS.pullRequestsSubscribeRefreshes]: AuthOrchestrationReadScope,
156 [WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes]: AuthOrchestrationReadScope,
157 [WS_METHODS.pullRequestsReviewerCandidates]: AuthOrchestrationReadScope,
158 [WS_METHODS.pullRequestsLabelCandidates]: AuthOrchestrationReadScope,
159 [WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,
160 [WS_METHODS.sourceControlAppAccess]: AuthOrchestrationReadScope,
161 [WS_METHODS.sourceControlStarred]: AuthOrchestrationReadScope,
162 [WS_METHODS.subscribeProjectClones]: AuthOrchestrationReadScope,
163 [WS_METHODS.projectsListEntries]: AuthFilesystemReadScope,
164 [WS_METHODS.projectsListIgnoredFiles]: AuthFilesystemReadScope,
165 [WS_METHODS.projectsReadFile]: AuthFilesystemReadScope,
166 [WS_METHODS.projectsSearchContents]: AuthFilesystemReadScope,
167 [WS_METHODS.projectsSearchEntries]: AuthFilesystemReadScope,
168 [WS_METHODS.projectsWriteFile]: AuthFilesystemWriteScope,
169 [WS_METHODS.projectsEnsureScratch]: AuthOrchestrationOperateScope,
170 [WS_METHODS.projectsCreateNew]: AuthOrchestrationOperateScope,
171 [WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,
172 [WS_METHODS.filesystemBrowse]: AuthFilesystemReadScope,
173 [WS_METHODS.filesystemGetMetadata]: AuthFilesystemReadScope,
174 [WS_METHODS.agentSessionsScan]: AuthOrchestrationReadScope,
175 [WS_METHODS.agentSessionsImport]: AuthOrchestrationOperateScope,
176 [WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,
177 [WS_METHODS.assetsPersistChatAttachments]: AuthOrchestrationOperateScope,
178 [WS_METHODS.attachmentsCreateUploadUrl]: AuthOrchestrationOperateScope,
179 [WS_METHODS.attachmentsDelete]: AuthOrchestrationOperateScope,
180 [WS_METHODS.providerUploadFeedback]: AuthOrchestrationOperateScope,
181 [WS_METHODS.mcpAppsCallTool]: AuthOrchestrationOperateScope,
182 [WS_METHODS.mcpAppsToolInfo]: AuthOrchestrationReadScope,
183 [WS_METHODS.mcpAppsReadResource]: AuthOrchestrationReadScope,
184 [WS_METHODS.mcpAppsUpdateModelContext]: AuthOrchestrationOperateScope,
185 [WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
186 [WS_METHODS.subscribeVcsBranch]: AuthOrchestrationReadScope,
187 [WS_METHODS.vcsRefreshBranch]: AuthOrchestrationReadScope,
188 [WS_METHODS.subscribeWorktreeSetup]: AuthOrchestrationReadScope,
189 [WS_METHODS.worktreeSetupCancel]: AuthOrchestrationOperateScope,
190 [WS_METHODS.subscribeResourceTelemetry]: AuthDiagnosticsReadScope,
191 [WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
192 [WS_METHODS.gitResolvePullRequest]: AuthOrchestrationReadScope,
193 [WS_METHODS.vcsListRefs]: AuthOrchestrationReadScope,
194 [WS_METHODS.reviewGetBranchCommits]: AuthFilesystemReadScope,
195 [WS_METHODS.reviewGetDiffPreview]: AuthFilesystemReadScope,
196 [WS_METHODS.reviewGetDiffFileContents]: AuthFilesystemReadScope,
197 [WS_METHODS.terminalOpen]: AuthTerminalOperateScope,
198 [WS_METHODS.terminalAttach]: AuthTerminalOperateScope,
199 [WS_METHODS.terminalObserve]: AuthTerminalReadScope,
200 [WS_METHODS.terminalWrite]: AuthTerminalOperateScope,
201 [WS_METHODS.terminalResize]: AuthTerminalOperateScope,
202 [WS_METHODS.terminalClear]: AuthTerminalOperateScope,
203 [WS_METHODS.terminalClose]: AuthTerminalOperateScope,
204 [WS_METHODS.subscribeTerminalMetadata]: AuthTerminalReadScope,
205 [WS_METHODS.previewOpen]: AuthPreviewOperateScope,
206 [WS_METHODS.previewResize]: AuthPreviewOperateScope,
207 [WS_METHODS.previewAdjust]: AuthPreviewOperateScope,
208 [WS_METHODS.previewClose]: AuthPreviewOperateScope,
209 [WS_METHODS.previewList]: AuthOrchestrationReadScope,
210 [WS_METHODS.previewClearProfile]: AuthPreviewOperateScope,
211 [WS_METHODS.previewReportProfiles]: AuthPreviewOperateScope,
212 [WS_METHODS.previewReportStatus]: AuthPreviewOperateScope,
213 [WS_METHODS.previewStopLocalServer]: AuthTerminalOperateScope,
214 [WS_METHODS.subscribePreviewEvents]: AuthOrchestrationReadScope,
215 [WS_METHODS.subscribeDiscoveredLocalServers]: AuthOrchestrationReadScope,
216 [WS_METHODS.deviceConfigure]: AuthSettingsWriteScope,
217 [WS_METHODS.deviceTestHost]: AuthSettingsWriteScope,
218 [WS_METHODS.deviceEasAccount]: AuthSettingsWriteScope,
219 [WS_METHODS.deviceSimlockIdentity]: AuthSettingsWriteScope,
220 [WS_METHODS.deviceList]: AuthOrchestrationReadScope,
221 [WS_METHODS.deviceOpen]: AuthOrchestrationOperateScope,
222 [WS_METHODS.deviceClose]: AuthOrchestrationOperateScope,
223 [WS_METHODS.deviceShutdown]: AuthOrchestrationOperateScope,
224 [WS_METHODS.deviceDetail]: AuthOrchestrationReadScope,
225 [WS_METHODS.deviceAction]: AuthOrchestrationOperateScope,
226 [WS_METHODS.subscribeDeviceState]: AuthOrchestrationReadScope,
227 [WS_METHODS.subscribeServerConfig]: AuthOrchestrationReadScope,
228 [WS_METHODS.subscribeServerLifecycle]: AuthOrchestrationReadScope,
229 [WS_METHODS.subscribeAuthAccess]: AuthAccessReadScope,
230} as const satisfies Readonly<Record<WsRpcMethod, AuthEnvironmentScope>>;
231
232export function requiredScopeForRpcMethod(method: string): AuthEnvironmentScope {
233 if (!Object.hasOwn(RPC_REQUIRED_SCOPES, method)) {
234 throw new Error(`RPC method ${method} has no declared authorization scope.`);
235 }
236 const requiredScope = RPC_REQUIRED_SCOPES[method as WsRpcMethod];
237 if (requiredScope === undefined) {
238 throw new Error(`RPC method ${method} has no declared authorization scope.`);
239 }
240 return requiredScope;
241}
242
243export const rpcAuthorizationError = (requiredScope: AuthEnvironmentScope) =>
244 new EnvironmentAuthorizationError({
245 message: `The authenticated token is missing required scope: ${requiredScope}.`,
246 ...authScopeRequiredResponse(requiredScope),
247 });
248
249const SettingsUpdate = Schema.Struct({
250 patch: ServerSettingsPatch,
251 providerInstanceMutation: Schema.optionalKey(ProviderInstanceMutation),
252});
253// Middleware receives the payload already decoded, so it is checked against the decoded shape.
254const decodeSettingsUpdate = Schema.decodeUnknownSync(Schema.toType(SettingsUpdate));
255
256const requiredScopesForSettingsUpdate = (payload: unknown) => {
257 const input = decodeSettingsUpdate(payload);
258 const scopes = requiredScopesForServerSettingsPatch(input.patch);
259 if (input.providerInstanceMutation === undefined) return scopes;
260 return Object.values(input.patch).every((value) => value === undefined)
261 ? [AuthProvidersManageScope]
262 : [...new Set([...scopes, AuthProvidersManageScope])];
263};
264
265const decodeProjectMutation = Schema.decodeUnknownSync(ProjectMutation);
266const decodeAssetCreateUrlInput = Schema.decodeUnknownSync(AssetCreateUrlInput);
267
268const requiredScopesForRpcCall = (
269 method: string,
270 payload: unknown,
271): ReadonlyArray<AuthEnvironmentScope> => {
272 if (method === WS_METHODS.serverRetryResourceTelemetry) {
273 return [AuthEnvironmentMaintainScope, AuthDiagnosticsReadScope];
274 }
275 if (method === WS_METHODS.assetsCreateUrl) {
276 const { resource } = decodeAssetCreateUrlInput(payload);
277 return [
278 resource._tag === "workspace-file" ||
279 resource._tag === "media-file" ||
280 resource._tag === "draft-workspace-file" ||
281 (resource._tag === "native-app-icon" && resource.app._tag === "app-path")
282 ? AuthFilesystemReadScope
283 : AuthOrchestrationReadScope,
284 ];
285 }
286 if (method === WS_METHODS.serverUpdateSettings) return requiredScopesForSettingsUpdate(payload);
287 // These send the credential they are given to a URL the caller names, as a saved setting would.
288 if (
289 (method === WS_METHODS.deviceSimlockIdentity ||
290 method === WS_METHODS.deviceEasAccount ||
291 method === WS_METHODS.serverListTextGeneratorModels) &&
292 containsSecretReference(payload)
293 ) {
294 return [AuthSettingsWriteScope, AuthProvidersManageScope];
295 }
296 if (method === WS_METHODS.projectsMutate) {
297 return requiredScopesForProjectMutation(decodeProjectMutation(payload));
298 }
299 const guarded = clientRpcRequiredScopes(method, payload);
300 if (guarded.length > 0) return guarded;
301 return [requiredScopeForRpcMethod(method)];
302};
303
304/**
305 * `onAuthorized` runs once after an authorized request succeeds; for a stream
306 * RPC, that is when the stream completes. Every RPC passes through here, so it
307 * is the one place to observe requests without wrapping each handler.
308 */
309export const layer = (
310 scopes: ReadonlyArray<AuthEnvironmentScope>,
311 onAuthorized?: (method: string, payload: unknown) => Effect.Effect<void>,
312) =>
313 Layer.succeed(RpcScopeAuthorization)((effect, { rpc, payload }) => {
314 const requiredScopes = requiredScopesForRpcCall(rpc._tag, payload);
315 const requiredScope = requiredScopes.find((scope) => !scopes.includes(scope));
316 if (requiredScope !== undefined) return Effect.fail(rpcAuthorizationError(requiredScope));
317 return onAuthorized === undefined
318 ? effect
319 : Effect.tap(effect, () => onAuthorized(rpc._tag, payload));
320 });
321
322/** Retrying can install or restart tools even though ordinary listing is readable. */
323export const requiredScopeForDeviceList = (input: DeviceListInput): AuthEnvironmentScope =>
324 input.retryHostId || input.updateTool
325 ? AuthOrchestrationOperateScope
326 : AuthOrchestrationReadScope;