Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

RpcAuthorization.ts

394 lines21.0 KB

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