Skip to content

Commit 0d5472b

Browse files
committed
refactor: share session mutation scope policy
1 parent 74f3ec1 commit 0d5472b

10 files changed

Lines changed: 378 additions & 89 deletions

‎src/gateway/method-scopes.ts‎

Lines changed: 4 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ import {
99
getActivePluginHttpRouteRegistry,
1010
getActivePluginSessionExtensionRegistry,
1111
} from "../plugins/runtime.js";
12-
import { isIncognitoSessionKey } from "../routing/session-key.js";
1312
import { resolveReservedGatewayMethodScope } from "../shared/gateway-method-policy.js";
13+
import { resolveDynamicSessionMutationRequiredScope } from "../shared/session-method-scopes.js";
1414
import { isAgentSessionResetCommand } from "./agent-command-policy.js";
1515
import {
1616
isCoreGatewayMethodClassified,
@@ -87,53 +87,6 @@ function resolveRequiredOperatorScopeForMethod(method: string): OperatorScope |
8787
return resolveScopedMethod(method);
8888
}
8989

90-
/**
91-
* sessions.patch fields a write-scoped operator may mutate: user-level chat
92-
* organization only. Any other field (model, sendPolicy, tool inheritance,
93-
* exec routing, ...) keeps requiring operator.admin — fail closed on unknowns.
94-
*/
95-
const SESSIONS_PATCH_WRITE_SCOPE_FIELDS: ReadonlySet<string> = new Set([
96-
"key",
97-
"agentId",
98-
"label",
99-
"category",
100-
"boardFace",
101-
"icon",
102-
"pinned",
103-
"archived",
104-
"unread",
105-
]);
106-
107-
function resolveSessionsPatchRequiredScopes(params: unknown): OperatorScope[] {
108-
if (!params || typeof params !== "object" || Array.isArray(params)) {
109-
// Malformed params cannot mutate anything; let the handler return the
110-
// precise validation error instead of a misleading missing-scope error.
111-
return [WRITE_SCOPE];
112-
}
113-
const safeOnly = Object.keys(params).every((key) => SESSIONS_PATCH_WRITE_SCOPE_FIELDS.has(key));
114-
return safeOnly ? [WRITE_SCOPE] : [ADMIN_SCOPE];
115-
}
116-
117-
function resolveSessionsCreateRequiredScopes(params: unknown): OperatorScope[] {
118-
if (!params || typeof params !== "object" || Array.isArray(params)) {
119-
return [WRITE_SCOPE];
120-
}
121-
const record = params as { incognito?: unknown; key?: unknown; parentSessionKey?: unknown };
122-
// Incognito creation and inheritance expose process-only session state; cwd and
123-
// execNode target privileged host resources. All require operator.admin.
124-
if (
125-
record.incognito === true ||
126-
(typeof record.key === "string" && isIncognitoSessionKey(record.key)) ||
127-
(typeof record.parentSessionKey === "string" &&
128-
isIncognitoSessionKey(record.parentSessionKey)) ||
129-
Object.hasOwn(params, "cwd") ||
130-
Object.hasOwn(params, "execNode")
131-
) {
132-
return [ADMIN_SCOPE];
133-
}
134-
return [WRITE_SCOPE];
135-
}
136-
13790
function resolveSessionActionRegisteredScopes(params: unknown): OperatorScope[] | undefined {
13891
if (!params || typeof params !== "object" || Array.isArray(params)) {
13992
return undefined;
@@ -221,46 +174,17 @@ function resolveDynamicLeastPrivilegeOperatorScopesForMethod(
221174
return bootstrapCommandOwner === true ? [PAIRING_SCOPE, ADMIN_SCOPE] : [PAIRING_SCOPE];
222175
}
223176
if (method === "sessions.patch") {
224-
return resolveSessionsPatchRequiredScopes(params);
177+
return [resolveDynamicSessionMutationRequiredScope(method, params) ?? WRITE_SCOPE];
225178
}
226179
if (method === "sessions.create") {
227-
return resolveSessionsCreateRequiredScopes(params);
180+
return [resolveDynamicSessionMutationRequiredScope(method, params) ?? WRITE_SCOPE];
228181
}
229182
if (method === "sessions.delete") {
230-
return resolveSessionsDeleteRequiredScopes(params);
183+
return [resolveDynamicSessionMutationRequiredScope(method, params) ?? ADMIN_SCOPE];
231184
}
232185
return [WRITE_SCOPE];
233186
}
234187

235-
/**
236-
* sessions.delete params a write-scoped archive-then-delete request may carry.
237-
* Internal controls (emitLifecycleHooks, expected* CAS guards) stay admin-only
238-
* — fail closed on anything outside this set.
239-
*/
240-
const SESSIONS_DELETE_WRITE_SCOPE_FIELDS: ReadonlySet<string> = new Set([
241-
"key",
242-
"agentId",
243-
"deleteTranscript",
244-
"archivedOnly",
245-
]);
246-
247-
function resolveSessionsDeleteRequiredScopes(params: unknown): OperatorScope[] {
248-
// archivedOnly is the explicit archive-then-delete opt-in: write scope may
249-
// delete only already-archived sessions (the handler enforces the state,
250-
// both pre-lock and under the lifecycle lock). Everything else — including
251-
// internal fallback/synthetic dispatch, which never sets the flag, and any
252-
// request carrying internal-only params — keeps requiring admin.
253-
if (!params || typeof params !== "object" || Array.isArray(params)) {
254-
return [ADMIN_SCOPE];
255-
}
256-
const record = params as { archivedOnly?: unknown };
257-
if (record.archivedOnly !== true) {
258-
return [ADMIN_SCOPE];
259-
}
260-
const safeOnly = Object.keys(params).every((key) => SESSIONS_DELETE_WRITE_SCOPE_FIELDS.has(key));
261-
return safeOnly ? [WRITE_SCOPE] : [ADMIN_SCOPE];
262-
}
263-
264188
function findMissingOperatorScope(
265189
requiredScopes: readonly OperatorScope[],
266190
scopes: readonly string[],

‎src/gateway/methods/core-descriptors.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -236,14 +236,14 @@ const CORE_GATEWAY_METHOD_SPECS: readonly CoreGatewayMethodSpec[] = [
236236
{ name: "sessions.abort", scope: "operator.write", since: "<=2026.7", startup: true },
237237
// Params-aware: write scope may mutate chat-organization fields
238238
// (label/category/icon/pinned/archived/unread); every other patch field stays
239-
// admin-only. Policy lives in method-scopes.ts.
239+
// admin-only. Policy lives in shared/session-method-scopes.ts.
240240
{ name: "sessions.patch", scope: "dynamic", since: "<=2026.7" },
241241
{ name: "sessions.pluginPatch", scope: "operator.admin", since: "<=2026.7" },
242242
{ name: "sessions.cleanup", scope: "operator.admin", since: "<=2026.7" },
243243
{ name: "sessions.reset", scope: "operator.admin", since: "<=2026.7" },
244244
// State-aware: write scope may delete already-archived sessions
245245
// (archive-then-delete); the handler enforces the archived requirement and
246-
// admin keeps unrestricted delete. Policy in method-scopes.ts + handler.
246+
// admin keeps unrestricted delete. Shared policy plus the handler own both checks.
247247
{ name: "sessions.delete", scope: "dynamic", since: "<=2026.7" },
248248
{ name: "sessions.compact", scope: "operator.admin", since: "<=2026.7" },
249249
{ name: "sessions.groups.list", scope: "operator.read", since: "<=2026.7" },

‎src/routing/session-key.ts‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
normalizeSessionKeyPreservingOpaquePeerIds,
1212
parseAgentSessionKey,
1313
} from "../sessions/session-key-utils.js";
14+
import { isIncognitoSessionKey } from "../shared/incognito-session-key.js";
1415
import { normalizeAccountId } from "./account-id.js";
1516

1617
export {
@@ -22,6 +23,7 @@ export {
2223
parseThreadSessionSuffix,
2324
type ParsedAgentSessionKey,
2425
} from "../sessions/session-key-utils.js";
26+
export { isIncognitoSessionKey };
2527
export {
2628
DEFAULT_ACCOUNT_ID,
2729
normalizeAccountId,
@@ -34,7 +36,6 @@ export const LEGACY_IMPLICIT_AGENT_ID = "main";
3436
/** @deprecated legacy implicit agent id; use roster default resolution. Removal: next major SDK cut. */
3537
export const DEFAULT_AGENT_ID = LEGACY_IMPLICIT_AGENT_ID;
3638
export const DEFAULT_MAIN_KEY = "main";
37-
const INCOGNITO_SESSION_RE = /^(?:dashboard|subagent|internal-session-effects):incognito-[^:]+$/u;
3839
type SessionKeyShape = "missing" | "agent" | "legacy_or_alias" | "malformed_agent";
3940

4041
function normalizeToken(value: string | undefined | null): string {
@@ -169,12 +170,6 @@ export function isUnscopedSessionKeySentinel(sessionKey: string | undefined | nu
169170
return lowered === "global" || lowered === "unknown";
170171
}
171172

172-
/** Classifies process-only session keys without consulting runtime registry state. */
173-
export function isIncognitoSessionKey(sessionKey: string | undefined | null): boolean {
174-
const rest = parseAgentSessionKey(sessionKey)?.rest;
175-
return typeof rest === "string" && INCOGNITO_SESSION_RE.test(rest);
176-
}
177-
178173
export function scopeLegacySessionKeyToAgent(params: {
179174
agentId?: string | undefined;
180175
sessionKey?: string | undefined;
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { describe, expect, it } from "vitest";
2+
import { isIncognitoSessionKey } from "./incognito-session-key.js";
3+
4+
describe("isIncognitoSessionKey", () => {
5+
it.each([
6+
"agent:main:dashboard:incognito-123",
7+
"AGENT:MAIN:SUBAGENT:INCOGNITO-123",
8+
"agent:main:internal-session-effects:incognito-123",
9+
])("recognizes %s", (sessionKey) => {
10+
expect(isIncognitoSessionKey(sessionKey)).toBe(true);
11+
});
12+
13+
it.each([
14+
undefined,
15+
"",
16+
"dashboard:incognito-123",
17+
"agent:main:dashboard:regular-123",
18+
"agent::dashboard:incognito-123",
19+
])("rejects %s", (sessionKey) => {
20+
expect(isIncognitoSessionKey(sessionKey)).toBe(false);
21+
});
22+
});
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
const INCOGNITO_SESSION_RE = /^(?:dashboard|subagent|internal-session-effects):incognito-[^:]+$/u;
2+
3+
/** Classifies process-only agent session keys without consulting runtime registry state. */
4+
export function isIncognitoSessionKey(sessionKey: string | undefined | null): boolean {
5+
const raw = sessionKey?.trim().toLowerCase();
6+
if (!raw) {
7+
return false;
8+
}
9+
const parts = raw.split(":");
10+
if (parts.length < 3 || parts[0] !== "agent" || !parts[1]) {
11+
return false;
12+
}
13+
return INCOGNITO_SESSION_RE.test(parts.slice(2).join(":"));
14+
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import { describe, expect, it } from "vitest";
2+
import { resolveDynamicSessionMutationRequiredScope } from "./session-method-scopes.js";
3+
4+
describe("resolveDynamicSessionMutationRequiredScope", () => {
5+
it("keeps ordinary session creation write-scoped", () => {
6+
expect(
7+
resolveDynamicSessionMutationRequiredScope("sessions.create", {
8+
agentId: "main",
9+
message: "hello",
10+
worktree: true,
11+
}),
12+
).toBe("operator.write");
13+
});
14+
15+
it.each([
16+
{ incognito: true },
17+
{ key: "agent:main:dashboard:incognito-123" },
18+
{ parentSessionKey: "agent:main:subagent:incognito-123" },
19+
{ cwd: "/tmp/workspace" },
20+
{ execNode: "node-1" },
21+
])("requires admin for privileged session creation params %#", (params) => {
22+
expect(resolveDynamicSessionMutationRequiredScope("sessions.create", params)).toBe(
23+
"operator.admin",
24+
);
25+
});
26+
27+
it("allows only organizational session patches with write scope", () => {
28+
expect(
29+
resolveDynamicSessionMutationRequiredScope("sessions.patch", {
30+
key: "agent:main:thread",
31+
label: "Renamed",
32+
archived: true,
33+
}),
34+
).toBe("operator.write");
35+
expect(
36+
resolveDynamicSessionMutationRequiredScope("sessions.patch", {
37+
key: "agent:main:thread",
38+
thinkingLevel: "high",
39+
}),
40+
).toBe("operator.admin");
41+
});
42+
43+
it("allows write-scoped deletion only for safe archived-only requests", () => {
44+
expect(
45+
resolveDynamicSessionMutationRequiredScope("sessions.delete", {
46+
key: "agent:main:archived",
47+
deleteTranscript: true,
48+
archivedOnly: true,
49+
}),
50+
).toBe("operator.write");
51+
expect(
52+
resolveDynamicSessionMutationRequiredScope("sessions.delete", {
53+
key: "agent:main:active",
54+
deleteTranscript: true,
55+
}),
56+
).toBe("operator.admin");
57+
expect(
58+
resolveDynamicSessionMutationRequiredScope("sessions.delete", {
59+
key: "agent:main:archived",
60+
archivedOnly: true,
61+
emitLifecycleHooks: false,
62+
}),
63+
).toBe("operator.admin");
64+
});
65+
66+
it("does not duplicate static method policy from the core descriptor table", () => {
67+
expect(resolveDynamicSessionMutationRequiredScope("sessions.groups.put")).toBeUndefined();
68+
expect(resolveDynamicSessionMutationRequiredScope("sessions.list")).toBeUndefined();
69+
});
70+
});
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import { isIncognitoSessionKey } from "./incognito-session-key.js";
2+
3+
export type SessionMutationOperatorScope = "operator.write" | "operator.admin";
4+
5+
const SESSIONS_PATCH_WRITE_SCOPE_FIELDS: ReadonlySet<string> = new Set([
6+
"key",
7+
"agentId",
8+
"label",
9+
"category",
10+
"boardFace",
11+
"icon",
12+
"pinned",
13+
"archived",
14+
"unread",
15+
]);
16+
17+
const SESSIONS_DELETE_WRITE_SCOPE_FIELDS: ReadonlySet<string> = new Set([
18+
"key",
19+
"agentId",
20+
"deleteTranscript",
21+
"archivedOnly",
22+
]);
23+
24+
function isRecord(value: unknown): value is Record<string, unknown> {
25+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
26+
}
27+
28+
function resolveSessionsPatchRequiredScope(params: unknown): SessionMutationOperatorScope {
29+
if (!isRecord(params)) {
30+
// Malformed params cannot mutate anything; let the handler return the
31+
// precise validation error instead of a misleading missing-scope error.
32+
return "operator.write";
33+
}
34+
return Object.keys(params).every((key) => SESSIONS_PATCH_WRITE_SCOPE_FIELDS.has(key))
35+
? "operator.write"
36+
: "operator.admin";
37+
}
38+
39+
function resolveSessionsCreateRequiredScope(params: unknown): SessionMutationOperatorScope {
40+
if (!isRecord(params)) {
41+
return "operator.write";
42+
}
43+
// Incognito creation and inheritance expose process-only session state; cwd and
44+
// execNode target privileged host resources. All require operator.admin.
45+
if (
46+
params.incognito === true ||
47+
(typeof params.key === "string" && isIncognitoSessionKey(params.key)) ||
48+
(typeof params.parentSessionKey === "string" &&
49+
isIncognitoSessionKey(params.parentSessionKey)) ||
50+
Object.hasOwn(params, "cwd") ||
51+
Object.hasOwn(params, "execNode")
52+
) {
53+
return "operator.admin";
54+
}
55+
return "operator.write";
56+
}
57+
58+
function resolveSessionsDeleteRequiredScope(params: unknown): SessionMutationOperatorScope {
59+
// archivedOnly is the explicit archive-then-delete opt-in: write scope may
60+
// delete only already-archived sessions. Internal controls stay admin-only.
61+
if (!isRecord(params) || params.archivedOnly !== true) {
62+
return "operator.admin";
63+
}
64+
return Object.keys(params).every((key) => SESSIONS_DELETE_WRITE_SCOPE_FIELDS.has(key))
65+
? "operator.write"
66+
: "operator.admin";
67+
}
68+
69+
/** Returns the exact scope for the Gateway's params-aware session mutations. */
70+
export function resolveDynamicSessionMutationRequiredScope(
71+
method: string,
72+
params?: unknown,
73+
): SessionMutationOperatorScope | undefined {
74+
if (method === "sessions.create") {
75+
return resolveSessionsCreateRequiredScope(params);
76+
}
77+
if (method === "sessions.patch") {
78+
return resolveSessionsPatchRequiredScope(params);
79+
}
80+
if (method === "sessions.delete") {
81+
return resolveSessionsDeleteRequiredScope(params);
82+
}
83+
return undefined;
84+
}

‎ui/src/i18n/locales/en.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -665,6 +665,10 @@ export const en: TranslationMap = {
665665
sessionsView: {
666666
subagentPrefix: "Subagent:",
667667
automationPrefix: "Automation:",
668+
actionRequiresConnection: "Connect to the Gateway to change threads.",
669+
actionUnavailable: "This Gateway does not support this thread action.",
670+
actionRequiresWrite: "This action requires operator.write access.",
671+
actionRequiresAdmin: "This action requires operator.admin access.",
668672
deletePreservedWorktrees:
669673
"{count} thread worktree(s) with uncommitted or unpushed work were kept ({branches}). Manage them under Settings -> Worktrees.",
670674
deletePreservedWorktreeConfirm:

0 commit comments

Comments
 (0)