@chroxy/server 0.11.10 → 0.11.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +4 -2
- package/package.json +3 -3
- package/src/acp-session.js +5 -1
- package/src/agent-connections.js +12 -1
- package/src/agent-control/client.js +29 -0
- package/src/agent-control/events.js +8 -4
- package/src/agent-control/local-connection.js +34 -16
- package/src/agent-control/mcp-server.js +2 -0
- package/src/anthropic-compatible-config.js +1 -0
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- package/src/base-session.js +319 -2
- package/src/bound-client-policy.js +12 -0
- package/src/byok-mcp-config.js +9 -5
- package/src/byok-mcp-trust.js +34 -20
- package/src/byok-session.js +62 -9
- package/src/byok-tool-executor.js +81 -1
- package/src/claude-setting-sources.js +74 -0
- package/src/claude-tui/pty-driver.js +5 -1
- package/src/claude-tui/usage-limit.js +2 -2
- package/src/claude-tui-session.js +57 -4
- package/src/cli/agent-cmd.js +236 -0
- package/src/cli/connection-state.js +54 -0
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/pages-cmd.js +6 -4
- package/src/cli/pair-code-cmd.js +7 -6
- package/src/cli/pair-discord-cmd.js +7 -6
- package/src/cli/schedule-cmd.js +25 -3
- package/src/cli/server-cmd.js +6 -0
- package/src/cli/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- package/src/cli-session.js +190 -11
- package/src/cli.js +4 -0
- package/src/codex-app-server-session.js +78 -17
- package/src/codex-error-text.js +114 -0
- package/src/config-dir-migration.js +11 -6
- package/src/config.js +23 -3
- package/src/connection-info.js +73 -14
- package/src/continuations.js +153 -40
- package/src/conversation-scanner.js +2 -21
- package/src/conversation-search.js +4 -17
- package/src/dev-preview.js +2 -1
- package/src/docker-session.js +10 -1
- package/src/doctor.js +14 -3
- package/src/durable-write.js +35 -0
- package/src/environments/authority.js +7 -1
- package/src/event-normalizer.js +35 -2
- package/src/folder-trust-wire.js +137 -0
- package/src/folder-trust-worker.js +17 -0
- package/src/folder-trust.js +1572 -0
- package/src/freshness/activity-meter.js +101 -0
- package/src/freshness/adapter.js +199 -0
- package/src/freshness/checks.js +239 -0
- package/src/freshness/config.js +98 -0
- package/src/freshness/core.js +185 -0
- package/src/freshness/derive.js +680 -0
- package/src/freshness/exchange.js +305 -0
- package/src/freshness/file-ledger.js +400 -0
- package/src/freshness/grade.js +81 -0
- package/src/freshness/hash.js +45 -0
- package/src/freshness/inbox.js +163 -0
- package/src/freshness/index.js +20 -0
- package/src/freshness/investigation.js +474 -0
- package/src/freshness/keys.js +177 -0
- package/src/freshness/ledger.js +122 -0
- package/src/freshness/outbox.js +131 -0
- package/src/freshness/policy.js +599 -0
- package/src/freshness/queue.js +843 -0
- package/src/freshness/read-errors.js +23 -0
- package/src/freshness/render.js +153 -0
- package/src/freshness/runtime.js +113 -0
- package/src/freshness/session-registry-adapter.js +161 -0
- package/src/freshness/state-file-adapter.js +167 -0
- package/src/freshness-runner/build-info.js +139 -0
- package/src/freshness-runner/cli.js +105 -0
- package/src/freshness-runner/run-tick.js +109 -0
- package/src/freshness-runner/stamp.js +57 -0
- package/src/freshness-sources/claude-transcript-adapter.js +211 -0
- package/src/freshness-sources/codex-transcript-adapter.js +33 -0
- package/src/freshness-sources/index.js +8 -0
- package/src/gemini-byok-session.js +292 -0
- package/src/gemini-credentials.js +67 -0
- package/src/gemini-key-safety.js +246 -0
- package/src/gemini-models.js +386 -0
- package/src/handler-utils.js +6 -13
- package/src/handlers/checkpoint-handlers.js +8 -0
- package/src/handlers/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +40 -11
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +4 -4
- package/src/handlers/session-handlers.js +10 -1
- package/src/handlers/settings-handlers.js +42 -8
- package/src/handlers/skills-handlers.js +7 -0
- package/src/history-page.js +8 -0
- package/src/jsonl-reader.js +90 -10
- package/src/jsonl-subprocess-session.js +4 -1
- package/src/logger.js +105 -15
- package/src/mailbox-route.js +102 -0
- package/src/notification-prefs.js +15 -0
- package/src/orchestration/orchestration-manager.js +38 -9
- package/src/orchestration/permission-gate.js +4 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +151 -33
- package/src/orphan-reaper.js +77 -20
- package/src/outgoing-policy.js +10 -4
- package/src/permission-floor.js +54 -2
- package/src/permission-manager.js +32 -13
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +7 -3
- package/src/platform.js +156 -4
- package/src/principal-audit.js +189 -0
- package/src/principal-binding.js +25 -0
- package/src/principal-brakes.js +21 -0
- package/src/principal-effect.js +101 -0
- package/src/principal-journal.js +905 -0
- package/src/principal-kill-switch.js +183 -0
- package/src/principal-label.js +5 -0
- package/src/principal-pending-permissions.js +177 -0
- package/src/principal-policy.js +1094 -0
- package/src/principal-sessions-snapshot.js +208 -0
- package/src/principal-store.js +488 -0
- package/src/principal-subscriptions.js +283 -0
- package/src/providers.js +2 -0
- package/src/redaction.js +181 -22
- package/src/scheduled-task-store.js +12 -0
- package/src/scheduler.js +304 -17
- package/src/sdk-session.js +60 -7
- package/src/server-cli/push-notification-handler.js +6 -1
- package/src/server-cli.js +30 -1
- package/src/session-ci-watcher.js +210 -37
- package/src/session-manager.js +590 -19
- package/src/session-message-history.js +121 -2
- package/src/session-name-allocator.js +685 -0
- package/src/statusline.js +78 -19
- package/src/summarize-session.js +2 -0
- package/src/turn-outcome.js +5 -2
- package/src/utils/argv-safety.js +29 -0
- package/src/utils/binary-package-manifest.js +57 -15
- package/src/utils/bounded-regex-worker.js +4 -0
- package/src/utils/bounded-regex.js +16 -7
- package/src/utils/pid-liveness.js +47 -0
- package/src/web-task-manager.js +45 -4
- package/src/worktree-gc.js +195 -4
- package/src/ws-auth.js +103 -19
- package/src/ws-broadcaster.js +39 -7
- package/src/ws-client-manager.js +8 -0
- package/src/ws-file-ops/browser.js +35 -3
- package/src/ws-forwarding.js +23 -3
- package/src/ws-handler-context.js +18 -0
- package/src/ws-history.js +79 -12
- package/src/ws-message-handlers.js +10 -2
- package/src/ws-server.js +253 -13
|
@@ -0,0 +1,1094 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What an agent principal may send, see and be sent.
|
|
3
|
+
*
|
|
4
|
+
* An agent principal (docs/security/agent-principals.md) is a scoped, revocable,
|
|
5
|
+
* labelled credential for a supervisor agent. A principal connection is stamped
|
|
6
|
+
* `client.principal = { principalId, label, tier, scope, constraints }`, has
|
|
7
|
+
* `isPrimaryToken === false`, and carries a fixed non-empty sentinel in
|
|
8
|
+
* `client.boundSessionId` so every host gate that branches on the binding still
|
|
9
|
+
* refuses it. This module is the deny-by-default policy for that class:
|
|
10
|
+
*
|
|
11
|
+
* - INBOUND `refusePrincipalMessage`: a message type is dispatched for a
|
|
12
|
+
* principal only when it is in `PRINCIPAL_ALLOWED_MESSAGE_TYPES`, the
|
|
13
|
+
* principal's tier is high enough, and the message carries no field outside
|
|
14
|
+
* the per-operation envelope (`PRINCIPAL_ENVELOPES`). Everything else is
|
|
15
|
+
* refused `scope_denied`.
|
|
16
|
+
* - ACCESS `principalMaySee`: the one per-session access helper (grant
|
|
17
|
+
* constraint, tier and, for a mutation, lease).
|
|
18
|
+
* - OUTBOUND `frameForPrincipal`: deny by default. A frame tagged with a
|
|
19
|
+
* session is delivered only when the grant covers that session; a frame with
|
|
20
|
+
* no session is delivered only when its type is in
|
|
21
|
+
* `PRINCIPAL_OUTGOING_ALLOWED`, reduced to that type's field whitelist.
|
|
22
|
+
* Ordinary session broadcasts are never delivered (contract §3.1 item 7).
|
|
23
|
+
*
|
|
24
|
+
* `dispatchPolicyFor` is the ONE selector both inbound sites use (the pre-schema
|
|
25
|
+
* gate in ws-server.js and `handleSessionMessage`). A principal gets
|
|
26
|
+
* `refusePrincipalMessage` INSTEAD of `refuseBoundMessage`, never in addition,
|
|
27
|
+
* and the bound allowlist is neither consulted for a principal nor loosened.
|
|
28
|
+
*
|
|
29
|
+
* Every function here is INERT for a client with no `principal` stamp: no
|
|
30
|
+
* existing client can carry one until the credential class lands (S1, #9116),
|
|
31
|
+
* so non-principal behaviour is byte-identical.
|
|
32
|
+
*
|
|
33
|
+
* tests/principal-policy.test.js asserts the classification is total in both
|
|
34
|
+
* directions against the client-schema registry and `registeredMessageTypes`,
|
|
35
|
+
* and the outgoing roster against the server schema registry.
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
import { realpathSync } from 'node:fs'
|
|
39
|
+
import { sep } from 'node:path'
|
|
40
|
+
import { createLogger, loggableValue } from './logger.js'
|
|
41
|
+
import { refuseBoundMessage } from './bound-client-policy.js'
|
|
42
|
+
import { redactBounded } from './redaction.js'
|
|
43
|
+
|
|
44
|
+
const log = createLogger('principal-policy')
|
|
45
|
+
|
|
46
|
+
// -- Tiers ------------------------------------------------------------------
|
|
47
|
+
|
|
48
|
+
/** observe < steer < drive < answer; a higher tier includes everything below it. */
|
|
49
|
+
export const PRINCIPAL_TIER_ORDER = Object.freeze(['observe', 'steer', 'drive', 'answer'])
|
|
50
|
+
|
|
51
|
+
const TIER_RANK = new Map(PRINCIPAL_TIER_ORDER.map((t, i) => [t, i]))
|
|
52
|
+
|
|
53
|
+
/** Needs that mutate a session and therefore require a lease (steer and above). */
|
|
54
|
+
const MUTATION_NEEDS = new Set(['steer', 'drive', 'answer'])
|
|
55
|
+
|
|
56
|
+
// -- Inbound: transport exempt set ------------------------------------------
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Types handled in ws-auth.js and ws-server.js OUTSIDE `handlerRegistry`. They
|
|
60
|
+
* are asserted as a separate, literal set (not a hole in the roster): `auth` and
|
|
61
|
+
* `key_exchange` run before dispatch, and `ping` is answered before the gate.
|
|
62
|
+
* @type {readonly string[]}
|
|
63
|
+
*/
|
|
64
|
+
export const PRINCIPAL_TRANSPORT_EXEMPT = Object.freeze(['auth', 'key_exchange', 'ping'])
|
|
65
|
+
|
|
66
|
+
// -- Inbound: allowlist ------------------------------------------------------
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* v1 allowlist: the five existing types, plus the `principal_*` types of the children that
|
|
70
|
+
* have landed their handlers (S3: the journal read path). A new `principal_*` type is
|
|
71
|
+
* listed here only together with its handler. `tier` is the lowest tier that may send the
|
|
72
|
+
* type.
|
|
73
|
+
* @type {Readonly<Record<string, { tier: string, reason: string }>>}
|
|
74
|
+
*/
|
|
75
|
+
export const PRINCIPAL_ALLOWED_MESSAGE_TYPES = Object.freeze({
|
|
76
|
+
principal_subscribe: Object.freeze({
|
|
77
|
+
tier: 'observe',
|
|
78
|
+
reason: 'observe: a correlated subscribe to the normalized event journal; the handler resolves EVERY explicit session id through principalMaySee and refuses the whole request scope_denied when any one is not granted',
|
|
79
|
+
}),
|
|
80
|
+
principal_unsubscribe: Object.freeze({
|
|
81
|
+
tier: 'observe',
|
|
82
|
+
reason: 'observe: stops the caller\'s own journal subscriptions; it can name only its own, so it grants nothing and leaks nothing',
|
|
83
|
+
}),
|
|
84
|
+
principal_events_read: Object.freeze({
|
|
85
|
+
tier: 'observe',
|
|
86
|
+
reason: 'observe: a paged read of the normalized event journal (limit 200); the handler resolves the explicit session id through principalMaySee',
|
|
87
|
+
}),
|
|
88
|
+
principal_pending_permissions: Object.freeze({
|
|
89
|
+
tier: 'observe',
|
|
90
|
+
reason: 'observe: a read-only snapshot of the pending permission requests of the granted sessions (#9119); it grants no decision authority; the handler resolves EVERY explicit session id through principalMaySee and refuses the whole request scope_denied when any one is not granted',
|
|
91
|
+
}),
|
|
92
|
+
principal_sessions_snapshot: Object.freeze({
|
|
93
|
+
tier: 'observe',
|
|
94
|
+
reason: 'observe: a read-only roster of the granted sessions (observed and declared status, handoff blockers, model requested and observed) (#9120); the handler resolves EVERY explicit session id through principalMaySee and refuses the whole request scope_denied when any one is not granted',
|
|
95
|
+
}),
|
|
96
|
+
input: Object.freeze({
|
|
97
|
+
tier: 'steer',
|
|
98
|
+
reason: 'steer: one fenced, provenance-labelled input into a leased session; the handler resolves an explicit sessionId through principalMaySee with no activeSessionId fallback',
|
|
99
|
+
}),
|
|
100
|
+
interrupt: Object.freeze({
|
|
101
|
+
tier: 'drive',
|
|
102
|
+
reason: 'drive: stops a turn on a leased session; the handler resolves an explicit sessionId through principalMaySee',
|
|
103
|
+
}),
|
|
104
|
+
create_session: Object.freeze({
|
|
105
|
+
tier: 'drive',
|
|
106
|
+
reason: 'drive: creates a session inside the grant; the handler carries its own principal branch placed before the bound refusal (constrained create is S12)',
|
|
107
|
+
}),
|
|
108
|
+
destroy_session: Object.freeze({
|
|
109
|
+
tier: 'drive',
|
|
110
|
+
reason: 'drive: closes a session the principal created; the handler resolves the target through principalMaySee',
|
|
111
|
+
}),
|
|
112
|
+
permission_response: Object.freeze({
|
|
113
|
+
tier: 'answer',
|
|
114
|
+
reason: 'answer: denies a pending prompt on a leased session; deny only, field-limited, resolved through principalMaySee',
|
|
115
|
+
}),
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
// -- Inbound: denied roster --------------------------------------------------
|
|
119
|
+
|
|
120
|
+
const SESSION_READ = 'a raw session read: a principal reads through the daemon-normalized principal_* family, never the raw output a dashboard gets'
|
|
121
|
+
const SESSION_SETTING = 'changes a session setting a principal does not hold; a principal steers by input only'
|
|
122
|
+
const HOST_WIDE = 'host-wide surface a principal never sees'
|
|
123
|
+
const HOST_ACTION = 'host-wide action a principal never takes'
|
|
124
|
+
const CREDENTIAL = 'credential or trust management a principal never touches'
|
|
125
|
+
const WORKSPACE_WRITE = 'writes the workspace, which a principal never does'
|
|
126
|
+
const WORKSPACE_READ = 'reads the workspace directly; a principal reads through the normalized principal_* family'
|
|
127
|
+
const HUMAN_SURFACE = 'a human-client surface (focus, presence, subscription, visibility) with no meaning for a principal'
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Every other registered client type. Anything not listed here or in the allowlist
|
|
131
|
+
* is refused anyway, so a handler added without a decision is unavailable to a
|
|
132
|
+
* principal rather than silently open to it.
|
|
133
|
+
* @type {Readonly<Record<string, string>>}
|
|
134
|
+
*/
|
|
135
|
+
export const PRINCIPAL_DENIED_MESSAGE_TYPES = Object.freeze({
|
|
136
|
+
// -- sessions: roster, navigation, lifecycle other than create/destroy --
|
|
137
|
+
list_sessions: 'a raw roster; a principal reads its granted sessions through principal_sessions_snapshot',
|
|
138
|
+
switch_session: 'moves a human client\'s focus; a principal has no active session',
|
|
139
|
+
subscribe_sessions: HUMAN_SURFACE,
|
|
140
|
+
unsubscribe_sessions: HUMAN_SURFACE,
|
|
141
|
+
rename_session: 'renames a session; not in the v1 authority tiers',
|
|
142
|
+
claim_primary: 'takes the primary-driver slot, which belongs to a human client',
|
|
143
|
+
client_visible: HUMAN_SURFACE,
|
|
144
|
+
resume_conversation: 'creates a session outside the constrained create envelope',
|
|
145
|
+
restore_archived_session: 'creates a session outside the constrained create envelope',
|
|
146
|
+
list_archived_sessions: HOST_WIDE,
|
|
147
|
+
get_archived_session_history: HOST_WIDE,
|
|
148
|
+
delete_archived_session: 'archive purge is never delegated',
|
|
149
|
+
set_session_archive_policy: 'archive policy is never delegated',
|
|
150
|
+
list_failed_restores: HOST_WIDE,
|
|
151
|
+
retry_failed_restore: HOST_ACTION,
|
|
152
|
+
get_failed_restore_history: HOST_WIDE,
|
|
153
|
+
|
|
154
|
+
// -- turn control other than input/interrupt --
|
|
155
|
+
cancel_queued: 'edits a human queue; not in the v1 authority tiers',
|
|
156
|
+
cancel_activity: 'cancels background work; not in the v1 authority tiers',
|
|
157
|
+
resume_budget: 'lifts a budget pause, which a human decides',
|
|
158
|
+
user_question_response: 'answers a question; a principal answers prompts only through permission_response deny',
|
|
159
|
+
get_permission_input: 'the raw pending tool input; a principal reads the normalized pending-permission snapshot',
|
|
160
|
+
query_permission_audit: 'the permission audit is a host record',
|
|
161
|
+
register_push_token: 'registers a device for notifications; a principal is not a device',
|
|
162
|
+
notification_prefs_get: HOST_WIDE,
|
|
163
|
+
notification_prefs_set: 'host-wide notification settings are never delegated',
|
|
164
|
+
|
|
165
|
+
// -- terminals: a principal never types into a PTY --
|
|
166
|
+
terminal_input: 'raw keystrokes into a PTY; a principal reaches a PTY only through the fenced sendMessage path',
|
|
167
|
+
terminal_subscribe: 'raw terminal output; a principal reads normalized events',
|
|
168
|
+
terminal_unsubscribe: HUMAN_SURFACE,
|
|
169
|
+
terminal_resize: HUMAN_SURFACE,
|
|
170
|
+
terminal_resync: SESSION_READ,
|
|
171
|
+
|
|
172
|
+
// -- per-session settings --
|
|
173
|
+
set_model: SESSION_SETTING,
|
|
174
|
+
set_thinking_level: SESSION_SETTING,
|
|
175
|
+
set_permission_mode: 'permission mode is never delegated: auto and more-permissive modes are outside every tier',
|
|
176
|
+
set_prompt_evaluator: SESSION_SETTING,
|
|
177
|
+
set_chroxy_context_hint: SESSION_SETTING,
|
|
178
|
+
set_session_preamble: SESSION_SETTING,
|
|
179
|
+
set_mcp_server_enabled: SESSION_SETTING,
|
|
180
|
+
evaluate_draft: SESSION_SETTING,
|
|
181
|
+
extension_message: 'delivers an arbitrary extension payload to a session',
|
|
182
|
+
skill_activate: SESSION_SETTING,
|
|
183
|
+
skill_deactivate: SESSION_SETTING,
|
|
184
|
+
list_skills: SESSION_READ,
|
|
185
|
+
list_slash_commands: SESSION_READ,
|
|
186
|
+
list_agents: SESSION_READ,
|
|
187
|
+
|
|
188
|
+
// -- history, conversations and raw reads --
|
|
189
|
+
request_full_history: SESSION_READ,
|
|
190
|
+
request_session_context: SESSION_READ,
|
|
191
|
+
request_conversation_transcript: SESSION_READ,
|
|
192
|
+
list_conversations: SESSION_READ,
|
|
193
|
+
search_conversations: SESSION_READ,
|
|
194
|
+
summarize_session: SESSION_READ,
|
|
195
|
+
session_pr_status_request: SESSION_READ,
|
|
196
|
+
session_pr_threads_request: SESSION_READ,
|
|
197
|
+
|
|
198
|
+
// -- workspace reads, writes, git and IDE --
|
|
199
|
+
browse_files: WORKSPACE_READ,
|
|
200
|
+
list_files: WORKSPACE_READ,
|
|
201
|
+
read_file: WORKSPACE_READ,
|
|
202
|
+
memory_read: WORKSPACE_READ,
|
|
203
|
+
get_diff: WORKSPACE_READ,
|
|
204
|
+
git_status: WORKSPACE_READ,
|
|
205
|
+
git_branches: WORKSPACE_READ,
|
|
206
|
+
list_symbols: WORKSPACE_READ,
|
|
207
|
+
resolve_symbol: WORKSPACE_READ,
|
|
208
|
+
search_content: WORKSPACE_READ,
|
|
209
|
+
find_references: WORKSPACE_READ,
|
|
210
|
+
list_directory: 'enumerates host directories',
|
|
211
|
+
check_git_repo: 'probes arbitrary host directories',
|
|
212
|
+
write_file: WORKSPACE_WRITE,
|
|
213
|
+
append_memory: WORKSPACE_WRITE,
|
|
214
|
+
git_stage: WORKSPACE_WRITE,
|
|
215
|
+
git_unstage: WORKSPACE_WRITE,
|
|
216
|
+
git_commit: WORKSPACE_WRITE,
|
|
217
|
+
git_create_pr: 'writes the workspace and the remote',
|
|
218
|
+
restore_checkpoint: 'rewrites the workspace',
|
|
219
|
+
create_checkpoint: 'writes workspace state; not in the v1 authority tiers',
|
|
220
|
+
list_checkpoints: SESSION_READ,
|
|
221
|
+
delete_checkpoint: 'deletes workspace state',
|
|
222
|
+
|
|
223
|
+
// -- permission rules, credentials and trust --
|
|
224
|
+
set_permission_rules: 'permission rules and allowAlways are never delegated',
|
|
225
|
+
set_prompt_evaluator_skip_pattern: 'a pattern the daemon runs on its own event loop for every input',
|
|
226
|
+
add_mcp_server: 'MCP configuration is a command the machine runs',
|
|
227
|
+
remove_mcp_server: 'MCP configuration is never delegated',
|
|
228
|
+
trust_folder: 'folder trust lets project settings run on the machine and is never delegated',
|
|
229
|
+
untrust_folder: 'folder trust is never delegated',
|
|
230
|
+
submit_mcp_auth_code: CREDENTIAL,
|
|
231
|
+
list_providers: HOST_WIDE,
|
|
232
|
+
byok_get_credentials_status: HOST_WIDE,
|
|
233
|
+
get_credentials_status: HOST_WIDE,
|
|
234
|
+
byok_set_credentials: CREDENTIAL,
|
|
235
|
+
byok_clear_credentials: CREDENTIAL,
|
|
236
|
+
set_credential: CREDENTIAL,
|
|
237
|
+
delete_credential: CREDENTIAL,
|
|
238
|
+
test_credential: 'uses a host-wide credential',
|
|
239
|
+
skill_trust_accept: 'skill trust is host-executable code and never delegated',
|
|
240
|
+
skill_trust_grant: 'skill trust is host-executable code and never delegated',
|
|
241
|
+
github_webhook_config_request: HOST_WIDE,
|
|
242
|
+
github_webhook_set_secret: CREDENTIAL,
|
|
243
|
+
github_webhook_clear_secret: CREDENTIAL,
|
|
244
|
+
session_preset_get: HOST_WIDE,
|
|
245
|
+
session_preset_set: 'host-wide presets are never delegated',
|
|
246
|
+
session_preset_approve: 'host-wide presets are never delegated',
|
|
247
|
+
session_preset_revoke: 'host-wide presets are never delegated',
|
|
248
|
+
daemon_update_action: 'daemon update and restart are never delegated',
|
|
249
|
+
revoke_token: CREDENTIAL,
|
|
250
|
+
principal_admin_grant: CREDENTIAL,
|
|
251
|
+
principal_admin_list: CREDENTIAL,
|
|
252
|
+
principal_admin_revoke: CREDENTIAL,
|
|
253
|
+
principal_admin_disable: CREDENTIAL,
|
|
254
|
+
principal_admin_enable: CREDENTIAL,
|
|
255
|
+
pair_approve: 'pairing is never delegated',
|
|
256
|
+
pair_deny: 'pairing is never delegated',
|
|
257
|
+
|
|
258
|
+
// -- repositories, web tasks, previews, environments --
|
|
259
|
+
list_repos: HOST_WIDE,
|
|
260
|
+
add_repo: HOST_ACTION,
|
|
261
|
+
remove_repo: HOST_ACTION,
|
|
262
|
+
launch_web_task: 'starts independent execution',
|
|
263
|
+
teleport_web_task: 'starts independent execution',
|
|
264
|
+
list_web_tasks: HOST_WIDE,
|
|
265
|
+
open_dev_preview: 'preview publication is never delegated',
|
|
266
|
+
close_dev_preview: 'preview lifecycle is never delegated',
|
|
267
|
+
create_environment: 'environments are never delegated',
|
|
268
|
+
list_environments: HOST_WIDE,
|
|
269
|
+
destroy_environment: 'environments are never delegated',
|
|
270
|
+
get_environment: HOST_WIDE,
|
|
271
|
+
|
|
272
|
+
// -- control room, orchestration, scheduling --
|
|
273
|
+
request_cost_summary: HOST_WIDE,
|
|
274
|
+
host_status_request: HOST_WIDE,
|
|
275
|
+
runner_status_request: HOST_WIDE,
|
|
276
|
+
containers_status_request: HOST_WIDE,
|
|
277
|
+
repo_runtime_config_request: HOST_WIDE,
|
|
278
|
+
byok_pool_status_request: HOST_WIDE,
|
|
279
|
+
host_prune_status_request: HOST_WIDE,
|
|
280
|
+
simulator_status_request: HOST_WIDE,
|
|
281
|
+
emulator_status_request: HOST_WIDE,
|
|
282
|
+
wsl_status_request: HOST_WIDE,
|
|
283
|
+
integration_status_request: HOST_WIDE,
|
|
284
|
+
skills_inventory_request: HOST_WIDE,
|
|
285
|
+
mailbox_status_request: HOST_WIDE,
|
|
286
|
+
external_sessions_request: HOST_WIDE,
|
|
287
|
+
repo_events_request: HOST_WIDE,
|
|
288
|
+
containers_action: HOST_ACTION,
|
|
289
|
+
byok_pool_action: HOST_ACTION,
|
|
290
|
+
host_prune_action: HOST_ACTION,
|
|
291
|
+
simulator_action: HOST_ACTION,
|
|
292
|
+
emulator_action: HOST_ACTION,
|
|
293
|
+
wsl_action: HOST_ACTION,
|
|
294
|
+
integration_action: HOST_ACTION,
|
|
295
|
+
orchestration_runs_request: HOST_WIDE,
|
|
296
|
+
orchestration_run_detail_request: HOST_WIDE,
|
|
297
|
+
orchestration_run_start: 'orchestration start is never delegated',
|
|
298
|
+
orchestration_gate_response: HOST_ACTION,
|
|
299
|
+
orchestration_run_action: HOST_ACTION,
|
|
300
|
+
orchestration_run_annotate: HOST_ACTION,
|
|
301
|
+
scheduled_tasks_request: HOST_WIDE,
|
|
302
|
+
scheduled_task_action: 'scheduled tasks are never delegated',
|
|
303
|
+
set_scheduler_enabled: 'scheduled tasks are never delegated',
|
|
304
|
+
})
|
|
305
|
+
|
|
306
|
+
// -- Inbound: wire envelopes (contract §4.1.1) -------------------------------
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* One CLOSED field set per allowed operation. A field outside the set, including
|
|
310
|
+
* a `.passthrough()` extra, is refused `scope_denied` at dispatch. `leaseId` and
|
|
311
|
+
* `gen` are the lease the mutation is made under. `values` pins a field to the
|
|
312
|
+
* listed values (a principal answers a prompt with `deny` only in v1).
|
|
313
|
+
* @type {Readonly<Record<string, { fields: readonly string[], values?: Readonly<Record<string, readonly unknown[]>> }>>}
|
|
314
|
+
*/
|
|
315
|
+
export const PRINCIPAL_ENVELOPES = Object.freeze({
|
|
316
|
+
principal_subscribe: Object.freeze({
|
|
317
|
+
fields: Object.freeze(['type', 'requestId', 'sessionIds', 'cursors']),
|
|
318
|
+
}),
|
|
319
|
+
principal_unsubscribe: Object.freeze({
|
|
320
|
+
fields: Object.freeze(['type', 'requestId', 'sessionIds']),
|
|
321
|
+
}),
|
|
322
|
+
principal_events_read: Object.freeze({
|
|
323
|
+
fields: Object.freeze(['type', 'requestId', 'sessionId', 'cursor', 'limit']),
|
|
324
|
+
}),
|
|
325
|
+
principal_pending_permissions: Object.freeze({
|
|
326
|
+
fields: Object.freeze(['type', 'requestId', 'sessionIds']),
|
|
327
|
+
}),
|
|
328
|
+
principal_sessions_snapshot: Object.freeze({
|
|
329
|
+
fields: Object.freeze(['type', 'requestId', 'sessionIds']),
|
|
330
|
+
}),
|
|
331
|
+
input: Object.freeze({
|
|
332
|
+
fields: Object.freeze(['type', 'sessionId', 'clientMessageId', 'data', 'leaseId', 'gen']),
|
|
333
|
+
}),
|
|
334
|
+
interrupt: Object.freeze({
|
|
335
|
+
fields: Object.freeze(['type', 'sessionId', 'requestId', 'leaseId', 'gen']),
|
|
336
|
+
}),
|
|
337
|
+
permission_response: Object.freeze({
|
|
338
|
+
fields: Object.freeze(['type', 'sessionId', 'requestId', 'decision', 'leaseId', 'gen']),
|
|
339
|
+
values: Object.freeze({ decision: Object.freeze(['deny']) }),
|
|
340
|
+
}),
|
|
341
|
+
destroy_session: Object.freeze({
|
|
342
|
+
fields: Object.freeze(['type', 'sessionId', 'requestId', 'leaseId', 'gen']),
|
|
343
|
+
}),
|
|
344
|
+
// create_session is exempt from a session lease (no session exists yet).
|
|
345
|
+
create_session: Object.freeze({
|
|
346
|
+
fields: Object.freeze(['type', 'requestId', 'cwd', 'name', 'provider', 'model', 'permissionMode', 'worktree']),
|
|
347
|
+
}),
|
|
348
|
+
})
|
|
349
|
+
|
|
350
|
+
// -- Predicates --------------------------------------------------------------
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Is this connection an agent principal? Fail-safe, the same shape as the
|
|
354
|
+
* `== null` bound rule: anything that is not provably "no stamp" is a principal,
|
|
355
|
+
* so a malformed stamp (`{}`, `false`, `0`) is a principal that is granted nothing.
|
|
356
|
+
* @param {object|null|undefined} client
|
|
357
|
+
* @returns {boolean}
|
|
358
|
+
*/
|
|
359
|
+
export function isPrincipalClient(client) {
|
|
360
|
+
return client != null && client.principal != null
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* The ONE selector both inbound sites call. A principal gets the principal
|
|
365
|
+
* allowlist; every other client keeps the bound allowlist, unchanged. Never both.
|
|
366
|
+
* @param {object|null|undefined} client
|
|
367
|
+
* @returns {(ws: object, client: object, msg: object, ctx: object) => boolean}
|
|
368
|
+
*/
|
|
369
|
+
export function dispatchPolicyFor(client) {
|
|
370
|
+
return isPrincipalClient(client) ? refusePrincipalMessage : refuseBoundMessage
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// -- Inbound: refusal ---------------------------------------------------------
|
|
374
|
+
|
|
375
|
+
/** The one refusal text. It carries no detail beyond the code. */
|
|
376
|
+
export const PRINCIPAL_REFUSAL_MESSAGE = 'Not permitted for this credential'
|
|
377
|
+
|
|
378
|
+
/** The one refusal code. */
|
|
379
|
+
export const PRINCIPAL_REFUSAL_CODE = 'scope_denied'
|
|
380
|
+
|
|
381
|
+
const MAX_ECHOED_LENGTH = 128
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Send the one refusal reply. The reply names no session (the sentinel binding
|
|
385
|
+
* and every other session id stay out of it) and echoes `requestType` and
|
|
386
|
+
* `requestId` only when they are strings of at most MAX_ECHOED_LENGTH characters;
|
|
387
|
+
* anything else is dropped, not truncated. Nothing from the payload is logged:
|
|
388
|
+
* `reason` is one of this module's own fixed words and the type is rendered
|
|
389
|
+
* through `loggableValue`.
|
|
390
|
+
*
|
|
391
|
+
* @param {object} ws
|
|
392
|
+
* @param {object} client
|
|
393
|
+
* @param {object} msg
|
|
394
|
+
* @param {object} ctx
|
|
395
|
+
* @param {string} reason an internal reason word, logged but never sent
|
|
396
|
+
*/
|
|
397
|
+
export function sendPrincipalRefusal(ws, client, msg, ctx, reason) {
|
|
398
|
+
const type = msg?.type
|
|
399
|
+
log.info(`Principal client ${client?.id} refused message type ${loggableValue(type)} (${reason})`)
|
|
400
|
+
ctx.transport.send(ws, {
|
|
401
|
+
type: 'session_error',
|
|
402
|
+
code: PRINCIPAL_REFUSAL_CODE,
|
|
403
|
+
message: PRINCIPAL_REFUSAL_MESSAGE,
|
|
404
|
+
...(typeof type === 'string' && type.length <= MAX_ECHOED_LENGTH ? { requestType: type } : {}),
|
|
405
|
+
...(typeof msg?.requestId === 'string' && msg.requestId.length <= MAX_ECHOED_LENGTH ? { requestId: msg.requestId } : {}),
|
|
406
|
+
})
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Why a principal may not send `msg`, or null when dispatch may proceed. Checked
|
|
411
|
+
* in the order: transport exempt, allowlist, tier, envelope.
|
|
412
|
+
* @param {object} client
|
|
413
|
+
* @param {object} msg
|
|
414
|
+
* @returns {string|null}
|
|
415
|
+
*/
|
|
416
|
+
export function principalDispatchRefusal(client, msg) {
|
|
417
|
+
const type = msg?.type
|
|
418
|
+
if (typeof type !== 'string') return 'type_not_allowed'
|
|
419
|
+
if (PRINCIPAL_TRANSPORT_EXEMPT.includes(type)) return null
|
|
420
|
+
if (!Object.hasOwn(PRINCIPAL_ALLOWED_MESSAGE_TYPES, type)) return 'type_not_allowed'
|
|
421
|
+
const rank = TIER_RANK.get(client?.principal?.tier)
|
|
422
|
+
const needed = TIER_RANK.get(PRINCIPAL_ALLOWED_MESSAGE_TYPES[type].tier)
|
|
423
|
+
if (rank === undefined || needed === undefined || rank < needed) return 'tier'
|
|
424
|
+
const envelope = PRINCIPAL_ENVELOPES[type]
|
|
425
|
+
if (!envelope || msg === null || typeof msg !== 'object' || Array.isArray(msg)) return 'envelope'
|
|
426
|
+
for (const key of Object.keys(msg)) {
|
|
427
|
+
if (!envelope.fields.includes(key)) return 'envelope'
|
|
428
|
+
}
|
|
429
|
+
if (envelope.values) {
|
|
430
|
+
for (const [field, allowed] of Object.entries(envelope.values)) {
|
|
431
|
+
if (Object.hasOwn(msg, field) && !allowed.includes(msg[field])) return 'envelope'
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
return null
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* The single place the principal allowlist is applied to a principal's request.
|
|
439
|
+
* Returns true when `msg` was refused (and replied to), false when the
|
|
440
|
+
* connection may use it, and false for a client that is not a principal. A
|
|
441
|
+
* missing or non-string `type` is refused.
|
|
442
|
+
*
|
|
443
|
+
* ws-server calls this before schema validation and `handleSessionMessage` calls
|
|
444
|
+
* it again as the dispatch gate, both through `dispatchPolicyFor`.
|
|
445
|
+
*
|
|
446
|
+
* @param {object} ws
|
|
447
|
+
* @param {object} client
|
|
448
|
+
* @param {object} msg
|
|
449
|
+
* @param {object} ctx
|
|
450
|
+
* @returns {boolean}
|
|
451
|
+
*/
|
|
452
|
+
export function refusePrincipalMessage(ws, client, msg, ctx) {
|
|
453
|
+
if (!isPrincipalClient(client)) return false
|
|
454
|
+
const reason = principalDispatchRefusal(client, msg)
|
|
455
|
+
if (reason === null) return false
|
|
456
|
+
sendPrincipalRefusal(ws, client, msg, ctx, reason)
|
|
457
|
+
return true
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// -- Access: one helper for per-session authority ----------------------------
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* @typedef {object} PrincipalPolicyOpts
|
|
464
|
+
* @property {(sessionId: string) => string|null|undefined} [sessionCwd]
|
|
465
|
+
* resolves a session's cwd (the grant may be a cwd root)
|
|
466
|
+
* @property {(sessionId: string) => boolean} [sessionExists]
|
|
467
|
+
* when given, a session that does not exist is never granted
|
|
468
|
+
* @property {(client: object, sessionId: string) => ({ kind: string }|null|undefined)} [leaseFor]
|
|
469
|
+
* the lease this principal holds on a session; defaults to none (S8 supplies it)
|
|
470
|
+
* @property {(path: string) => string} [realpath] defaults to fs.realpathSync
|
|
471
|
+
*/
|
|
472
|
+
|
|
473
|
+
function underRoot(root, dir) {
|
|
474
|
+
return dir === root || dir.startsWith(root.endsWith(sep) ? root : root + sep)
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function grantCovers(constraints, sessionId, opts) {
|
|
478
|
+
if (constraints == null || typeof constraints !== 'object') return false
|
|
479
|
+
const ids = constraints.sessionIds
|
|
480
|
+
if (Array.isArray(ids) && ids.includes(sessionId)) return true
|
|
481
|
+
const roots = constraints.cwdRoots
|
|
482
|
+
if (!Array.isArray(roots) || roots.length === 0) return false
|
|
483
|
+
const cwd = typeof opts.sessionCwd === 'function' ? opts.sessionCwd(sessionId) : null
|
|
484
|
+
if (typeof cwd !== 'string' || cwd.length === 0) return false
|
|
485
|
+
const realpath = opts.realpath ?? realpathSync
|
|
486
|
+
let realCwd
|
|
487
|
+
try {
|
|
488
|
+
realCwd = realpath(cwd)
|
|
489
|
+
} catch {
|
|
490
|
+
return false
|
|
491
|
+
}
|
|
492
|
+
return roots.some((root) => {
|
|
493
|
+
if (typeof root !== 'string' || root.length === 0) return false
|
|
494
|
+
try {
|
|
495
|
+
return underRoot(realpath(root), realCwd)
|
|
496
|
+
} catch {
|
|
497
|
+
return false
|
|
498
|
+
}
|
|
499
|
+
})
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* May this principal act on `sessionId` with authority `need`?
|
|
504
|
+
*
|
|
505
|
+
* 1. grant: the session id is in `constraints.sessionIds`, or the session's cwd
|
|
506
|
+
* is under one of `constraints.cwdRoots` (either grants it). Nothing granted
|
|
507
|
+
* is nothing allowed.
|
|
508
|
+
* 2. tier: observe < steer < drive < answer.
|
|
509
|
+
* 3. lease: a mutation (steer and above) needs a lease from `opts.leaseFor`,
|
|
510
|
+
* which defaults to none, so no lease is `lease_required`. A steer need is
|
|
511
|
+
* met by a steer or drive lease; drive and answer need a drive lease.
|
|
512
|
+
*
|
|
513
|
+
* A session that is not granted and a session that does not exist return the SAME
|
|
514
|
+
* `scope` reason, so a principal cannot probe which ids exist. It never reads the
|
|
515
|
+
* sentinel binding.
|
|
516
|
+
*
|
|
517
|
+
* @param {object} client
|
|
518
|
+
* @param {unknown} sessionId
|
|
519
|
+
* @param {'observe'|'steer'|'drive'|'answer'} need
|
|
520
|
+
* @param {PrincipalPolicyOpts} [opts]
|
|
521
|
+
* @returns {{ ok: true } | { ok: false, reason: 'not_principal'|'scope'|'tier'|'lease_required' }}
|
|
522
|
+
*/
|
|
523
|
+
export function principalMaySee(client, sessionId, need, opts = {}) {
|
|
524
|
+
if (!isPrincipalClient(client)) return { ok: false, reason: 'not_principal' }
|
|
525
|
+
const needRank = TIER_RANK.get(need)
|
|
526
|
+
if (needRank === undefined) return { ok: false, reason: 'tier' }
|
|
527
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) return { ok: false, reason: 'scope' }
|
|
528
|
+
if (!grantCovers(client.principal.constraints, sessionId, opts)) return { ok: false, reason: 'scope' }
|
|
529
|
+
if (typeof opts.sessionExists === 'function' && opts.sessionExists(sessionId) !== true) {
|
|
530
|
+
return { ok: false, reason: 'scope' }
|
|
531
|
+
}
|
|
532
|
+
const rank = TIER_RANK.get(client.principal.tier)
|
|
533
|
+
if (rank === undefined || rank < needRank) return { ok: false, reason: 'tier' }
|
|
534
|
+
if (MUTATION_NEEDS.has(need)) {
|
|
535
|
+
const lease = typeof opts.leaseFor === 'function' ? opts.leaseFor(client, sessionId) : null
|
|
536
|
+
const kind = lease?.kind
|
|
537
|
+
const held = need === 'steer' ? (kind === 'steer' || kind === 'drive') : kind === 'drive'
|
|
538
|
+
if (!held) return { ok: false, reason: 'lease_required' }
|
|
539
|
+
}
|
|
540
|
+
return { ok: true }
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* The policy inputs a handler can derive from its context. Session lookups go
|
|
545
|
+
* through the session manager; the lease lookup is read from `ctx.services` when
|
|
546
|
+
* the lease store exists (S8) and is otherwise none.
|
|
547
|
+
* @param {object} ctx
|
|
548
|
+
* @returns {PrincipalPolicyOpts}
|
|
549
|
+
*/
|
|
550
|
+
export function principalPolicyOptsFromCtx(ctx) {
|
|
551
|
+
const manager = ctx?.sessions?.sessionManager
|
|
552
|
+
const entryFor = (id) => (typeof manager?.getSession === 'function' ? manager.getSession(id) : null)
|
|
553
|
+
const leases = ctx?.services?.principalLeases
|
|
554
|
+
return {
|
|
555
|
+
sessionCwd: (id) => {
|
|
556
|
+
const entry = entryFor(id)
|
|
557
|
+
return entry?.cwd ?? entry?.session?.cwd ?? null
|
|
558
|
+
},
|
|
559
|
+
sessionExists: (id) => entryFor(id) != null,
|
|
560
|
+
leaseFor: typeof leases?.leaseFor === 'function' ? (c, id) => leases.leaseFor(c, id) : undefined,
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* The principal branch of a session-mutating handler. It resolves the target
|
|
566
|
+
* through `principalMaySee` from an EXPLICIT `msg.sessionId` (no fallback to the
|
|
567
|
+
* active session) and always replies `scope_denied`: until the child that owns the
|
|
568
|
+
* operation lands (S8 lease, S9 delivery, S12 create, S13 interrupt, S15 answer)
|
|
569
|
+
* there is nothing a principal may do here, so a granted, leased principal is
|
|
570
|
+
* refused as well. A handler that calls this MUST return right after, so a
|
|
571
|
+
* principal can never fall into the host path.
|
|
572
|
+
*
|
|
573
|
+
* @param {object} ws
|
|
574
|
+
* @param {object} client
|
|
575
|
+
* @param {object} msg
|
|
576
|
+
* @param {object} ctx
|
|
577
|
+
* @param {'steer'|'drive'|'answer'|null} need null for create (no session yet)
|
|
578
|
+
*/
|
|
579
|
+
export function refusePrincipalHandler(ws, client, msg, ctx, need) {
|
|
580
|
+
let reason = 'not_available'
|
|
581
|
+
if (need !== null) {
|
|
582
|
+
const verdict = principalMaySee(client, msg?.sessionId, need, principalPolicyOptsFromCtx(ctx))
|
|
583
|
+
if (!verdict.ok) reason = verdict.reason
|
|
584
|
+
}
|
|
585
|
+
sendPrincipalRefusal(ws, client, msg, ctx, reason)
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// -- Outbound ----------------------------------------------------------------
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* Frames a principal may receive that carry no session, and the ONLY fields each
|
|
592
|
+
* is delivered with. Everything else is dropped. Each entry is one a principal
|
|
593
|
+
* plausibly needs today:
|
|
594
|
+
*
|
|
595
|
+
* - pong: the keepalive answer to its own `ping`.
|
|
596
|
+
* - auth_ok: the handshake answer. Reduced to the protocol negotiation and
|
|
597
|
+
* the public key-exchange material (the client derives its key from it): no
|
|
598
|
+
* session list, no replay, no host fields (cwd, version, features, exposure,
|
|
599
|
+
* connected clients, billing).
|
|
600
|
+
* - session_error: the refusal reply (`scope_denied`) and any error about its
|
|
601
|
+
* own request. Free text is kept; binding fields (`boundSessionId`,
|
|
602
|
+
* `boundSessionName`) and `primaryClientId` are not in the whitelist.
|
|
603
|
+
* - server_error: a daemon fault notice. The free-text message can carry host
|
|
604
|
+
* detail, so only `category` and `recoverable` are kept.
|
|
605
|
+
* - rate_limited: the throttle notice, so a principal backs off.
|
|
606
|
+
* - input_ack: the acceptance acknowledgement for its own input (session
|
|
607
|
+
* tagged, so it also needs the session grant).
|
|
608
|
+
* - credential_invalidated: the revoke/expiry notice that tells it to stop.
|
|
609
|
+
*
|
|
610
|
+
* @type {Readonly<Record<string, readonly string[]>>}
|
|
611
|
+
*/
|
|
612
|
+
export const PRINCIPAL_OUTGOING_ALLOWED = Object.freeze({
|
|
613
|
+
pong: Object.freeze(['type', 'serverTs']),
|
|
614
|
+
// The public handshake material of the eager key exchange stays: the client derives
|
|
615
|
+
// the shared key FROM serverPublicKey, so stripping it leaves a principal that can
|
|
616
|
+
// never decrypt the encrypted burst that follows auth_ok.
|
|
617
|
+
auth_ok: Object.freeze([
|
|
618
|
+
'type', 'clientId', 'encryption', 'protocolVersion', 'minProtocolVersion', 'maxProtocolVersion',
|
|
619
|
+
'serverPublicKey', 'serverKeySig', 'newIdentityKey', 'rotationCert',
|
|
620
|
+
]),
|
|
621
|
+
session_error: Object.freeze(['type', 'message', 'code', 'recoverable', 'reason', 'requestId', 'requestType', 'sessionId']),
|
|
622
|
+
server_error: Object.freeze(['type', 'category', 'recoverable', 'sessionId']),
|
|
623
|
+
rate_limited: Object.freeze(['type', 'retryAfterMs', 'message']),
|
|
624
|
+
input_ack: Object.freeze([
|
|
625
|
+
'type', 'sessionId', 'clientMessageId', 'status', 'delivery', 'retrySafe', 'acceptedAt',
|
|
626
|
+
'retentionExpiresAt', 'dedupScope', 'reason', 'message', 'context',
|
|
627
|
+
]),
|
|
628
|
+
credential_invalidated: Object.freeze(['type', 'reason']),
|
|
629
|
+
// The journal read path (S3). Delivered by a dedicated per-subscription direct send
|
|
630
|
+
// (principal-subscriptions.js), never by a broadcast, and each is re-checked against the
|
|
631
|
+
// grant at send time. `principal_subscribed` has no top-level session: every session it
|
|
632
|
+
// lists is checked (see `frameForPrincipal`).
|
|
633
|
+
principal_subscribed: Object.freeze(['type', 'requestId', 'sessions']),
|
|
634
|
+
principal_event: Object.freeze([
|
|
635
|
+
'type', 'requestId', 'sessionId', 'journalId', 'journalSeq', 'ts', 'eventType', 'data', 'truncated', 'replay',
|
|
636
|
+
]),
|
|
637
|
+
principal_live_fence: Object.freeze(['type', 'requestId', 'sessionId', 'journalId', 'journalSeq']),
|
|
638
|
+
principal_gap: Object.freeze(['type', 'requestId', 'sessionId', 'journalId', 'reason', 'fromSeq', 'toSeq', 'ended']),
|
|
639
|
+
principal_events_page: Object.freeze(['type', 'requestId', 'sessionId', 'journalId', 'events', 'headSeq', 'cursor', 'more', 'gap']),
|
|
640
|
+
// The pending-permission snapshot (S4). A direct reply to `principal_pending_permissions`;
|
|
641
|
+
// like `principal_subscribed` it has no top-level session: every request it lists is
|
|
642
|
+
// checked against the grant and rebuilt from `PRINCIPAL_PENDING_PERMISSION_FIELDS`.
|
|
643
|
+
principal_pending_permissions_result: Object.freeze(['type', 'requestId', 'generatedAt', 'permissions', 'truncated']),
|
|
644
|
+
// The session roster snapshot (S5). Like the two above it has no top-level session: every
|
|
645
|
+
// row it lists is checked against the grant and rebuilt from the whitelists below.
|
|
646
|
+
principal_sessions_snapshot_result: Object.freeze(['type', 'requestId', 'generatedAt', 'sessions', 'truncated']),
|
|
647
|
+
})
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* The only fields of one request in a `principal_pending_permissions_result`. There is no
|
|
651
|
+
* `input` and no `toolInput`: a tool input never reaches a principal (contract sections 7.3
|
|
652
|
+
* and 8). `description` is further limited to requests that are not floored.
|
|
653
|
+
* @type {readonly string[]}
|
|
654
|
+
*/
|
|
655
|
+
export const PRINCIPAL_PENDING_PERMISSION_FIELDS = Object.freeze([
|
|
656
|
+
'requestId', 'sessionId', 'tool', 'floored', 'explicitConsent', 'nonDelegable', 'origin', 'createdAt', 'expiresAt', 'description',
|
|
657
|
+
])
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* The only fields of one row in a `principal_sessions_snapshot_result` (#9120, S5), and of
|
|
661
|
+
* the objects nested in it. There is no cwd, history, cost, billing or capability field.
|
|
662
|
+
* `leaseHolder` is a label, `null` until S8 (leases) fills it.
|
|
663
|
+
* @type {readonly string[]}
|
|
664
|
+
*/
|
|
665
|
+
export const PRINCIPAL_SESSION_ROW_FIELDS = Object.freeze([
|
|
666
|
+
'sessionId', 'name', 'provider', 'status', 'declaredStatus', 'model', 'blockers', 'leaseHolder', 'lastActivityAt',
|
|
667
|
+
])
|
|
668
|
+
/** @type {readonly string[]} */
|
|
669
|
+
export const PRINCIPAL_SESSION_STATUS_FIELDS = Object.freeze(['isBusy', 'busyReason', 'starting'])
|
|
670
|
+
/** @type {readonly string[]} */
|
|
671
|
+
export const PRINCIPAL_SESSION_MODEL_FIELDS = Object.freeze(['requested', 'observed'])
|
|
672
|
+
/** The fields of a row's `declaredStatus` (the daemon's own `DeclaredStatusSchema`, field for field). */
|
|
673
|
+
export const PRINCIPAL_DECLARED_STATUS_FIELDS = Object.freeze({
|
|
674
|
+
state: 'string', summary: 'string', next: 'string', blockedOn: 'string', etaMinutes: 'number', decision: 'string', updatedAt: 'number', source: 'string',
|
|
675
|
+
})
|
|
676
|
+
/**
|
|
677
|
+
* The detail a blocker carries, per code, and the kind of value each field must hold. A code
|
|
678
|
+
* that is not listed (a future one, or one with no detail) is delivered as `{ code }` alone:
|
|
679
|
+
* it is still a blocker. A field whose value has the wrong kind is dropped.
|
|
680
|
+
* @type {Readonly<Record<string, Readonly<Record<string, 'count'|'bool'|'string'|'strings'>>>>}
|
|
681
|
+
*/
|
|
682
|
+
export const PRINCIPAL_BLOCKER_DETAIL_FIELDS = Object.freeze({
|
|
683
|
+
queued_prompts: Object.freeze({ count: 'count' }),
|
|
684
|
+
pending_permission: Object.freeze({ requestIds: 'strings' }),
|
|
685
|
+
pending_question: Object.freeze({ count: 'count' }),
|
|
686
|
+
active_agents: Object.freeze({ count: 'count' }),
|
|
687
|
+
background_shells: Object.freeze({ count: 'count', soft: 'bool' }),
|
|
688
|
+
automation_owned: Object.freeze({ scheduledTaskId: 'string', orchestrationRunId: 'string' }),
|
|
689
|
+
})
|
|
690
|
+
/** The longest list, string and code the roster frame carries. */
|
|
691
|
+
export const PRINCIPAL_SESSION_ROWS_MAX = 100
|
|
692
|
+
const BLOCKER_IDS_MAX = 100
|
|
693
|
+
const ROW_STRING_MAX = 300
|
|
694
|
+
|
|
695
|
+
/**
|
|
696
|
+
* One value of the given kind, or `undefined` when it is not of that kind.
|
|
697
|
+
* @param {unknown} value
|
|
698
|
+
* @param {'count'|'bool'|'string'|'number'|'strings'} kind
|
|
699
|
+
*/
|
|
700
|
+
function valueOfKind(value, kind) {
|
|
701
|
+
switch (kind) {
|
|
702
|
+
case 'count': return Number.isSafeInteger(value) && value >= 0 ? value : undefined
|
|
703
|
+
case 'number': return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined
|
|
704
|
+
case 'bool': return typeof value === 'boolean' ? value : undefined
|
|
705
|
+
case 'string': return typeof value === 'string' ? value.slice(0, ROW_STRING_MAX) : undefined
|
|
706
|
+
case 'strings':
|
|
707
|
+
return Array.isArray(value) && value.every((v) => typeof v === 'string')
|
|
708
|
+
? value.slice(0, BLOCKER_IDS_MAX).map((v) => v.slice(0, ROW_STRING_MAX))
|
|
709
|
+
: undefined
|
|
710
|
+
default: return undefined
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
const nullableString = (v) => (typeof v === 'string' ? v.slice(0, ROW_STRING_MAX) : null)
|
|
715
|
+
|
|
716
|
+
/** Free text a row carries (a model id): redacted BEFORE it is clipped, so a cut cannot keep a credential's prefix. */
|
|
717
|
+
const nullableRedactedString = (v) => (typeof v === 'string' ? redactBounded(v, ROW_STRING_MAX) : null)
|
|
718
|
+
|
|
719
|
+
/** One blocker rebuilt from its whitelists. A value that is not a blocker reads as `unavailable`, never as nothing. */
|
|
720
|
+
function rebuildBlocker(b) {
|
|
721
|
+
if (b === null || typeof b !== 'object' || typeof b.code !== 'string' || b.code.length === 0) return { code: 'unavailable' }
|
|
722
|
+
const out = { code: b.code.slice(0, 64) }
|
|
723
|
+
const spec = Object.hasOwn(PRINCIPAL_BLOCKER_DETAIL_FIELDS, b.code) ? PRINCIPAL_BLOCKER_DETAIL_FIELDS[b.code] : null
|
|
724
|
+
if (spec && b.detail !== null && typeof b.detail === 'object') {
|
|
725
|
+
const detail = {}
|
|
726
|
+
for (const [field, kind] of Object.entries(spec)) {
|
|
727
|
+
if (!Object.hasOwn(b.detail, field)) continue
|
|
728
|
+
const v = valueOfKind(b.detail[field], kind)
|
|
729
|
+
if (v !== undefined) detail[field] = v
|
|
730
|
+
}
|
|
731
|
+
if (Object.keys(detail).length > 0) out.detail = detail
|
|
732
|
+
}
|
|
733
|
+
return out
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/** One roster row rebuilt from `PRINCIPAL_SESSION_ROW_FIELDS` and the nested whitelists. */
|
|
737
|
+
function rebuildSessionRow(row) {
|
|
738
|
+
const out = {}
|
|
739
|
+
for (const field of PRINCIPAL_SESSION_ROW_FIELDS) {
|
|
740
|
+
const v = row[field]
|
|
741
|
+
switch (field) {
|
|
742
|
+
case 'sessionId': out.sessionId = row.sessionId; break
|
|
743
|
+
case 'name': case 'provider': case 'leaseHolder': out[field] = nullableString(v); break
|
|
744
|
+
case 'lastActivityAt': out.lastActivityAt = valueOfKind(v, 'number') ?? null; break
|
|
745
|
+
case 'status': {
|
|
746
|
+
const s = v !== null && typeof v === 'object' ? v : null
|
|
747
|
+
out.status = s === null ? null : {
|
|
748
|
+
isBusy: s.isBusy === true,
|
|
749
|
+
busyReason: s.busyReason === 'turn' || s.busyReason === 'background-shells' ? s.busyReason : null,
|
|
750
|
+
starting: s.starting === true,
|
|
751
|
+
}
|
|
752
|
+
break
|
|
753
|
+
}
|
|
754
|
+
case 'model': {
|
|
755
|
+
const m = v !== null && typeof v === 'object' ? v : null
|
|
756
|
+
out.model = m === null ? null : { requested: nullableRedactedString(m.requested), observed: nullableRedactedString(m.observed) }
|
|
757
|
+
break
|
|
758
|
+
}
|
|
759
|
+
case 'declaredStatus': {
|
|
760
|
+
if (v === null || typeof v !== 'object') { out.declaredStatus = null; break }
|
|
761
|
+
const d = {}
|
|
762
|
+
for (const [key, kind] of Object.entries(PRINCIPAL_DECLARED_STATUS_FIELDS)) {
|
|
763
|
+
if (!Object.hasOwn(v, key)) continue
|
|
764
|
+
const value = valueOfKind(v[key], kind)
|
|
765
|
+
if (value !== undefined) d[key] = value
|
|
766
|
+
}
|
|
767
|
+
out.declaredStatus = d
|
|
768
|
+
break
|
|
769
|
+
}
|
|
770
|
+
case 'blockers':
|
|
771
|
+
// A blocker list that is not a list is NOT an empty one: an empty list reads as
|
|
772
|
+
// "safe to hand off".
|
|
773
|
+
out.blockers = Array.isArray(v) ? v.slice(0, 32).map(rebuildBlocker) : [{ code: 'unavailable' }]
|
|
774
|
+
break
|
|
775
|
+
default: break
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
return out
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
/**
|
|
782
|
+
* Every other real server frame: a principal is never sent one on the direct-reply
|
|
783
|
+
* path. Together with `PRINCIPAL_OUTGOING_ALLOWED` and `PRINCIPAL_TRANSPORT_FRAMES`
|
|
784
|
+
* this classifies EVERY frame the daemon can emit (schema-backed and schema-less), so a
|
|
785
|
+
* new frame cannot reach a principal without a decision. Delivery stays deny by default
|
|
786
|
+
* either way; this roster exists so tests/principal-policy.test.js can be red when a
|
|
787
|
+
* frame is added and nobody decided about it.
|
|
788
|
+
* @type {readonly string[]}
|
|
789
|
+
*/
|
|
790
|
+
export const PRINCIPAL_OUTGOING_DENIED = Object.freeze([
|
|
791
|
+
'activity_delta', 'activity_snapshot', 'agent_busy', 'agent_completed', 'agent_event', 'agent_idle',
|
|
792
|
+
'agent_list', 'agent_spawned', 'append_memory_result', 'archived_session_history',
|
|
793
|
+
'archived_sessions_list', 'auth_bootstrap', 'auth_fail', 'available_models',
|
|
794
|
+
'available_permission_modes', 'background_work_changed', 'billing_canary', 'budget_exceeded',
|
|
795
|
+
'budget_resume_ack', 'budget_resumed', 'budget_warning', 'byok_credentials_status',
|
|
796
|
+
'byok_pool_action_ack', 'byok_pool_status_snapshot', 'cancel_activity_ack', 'checkpoint_created',
|
|
797
|
+
'checkpoint_list', 'checkpoint_restored', 'chroxy_context_hint_changed', 'claude_ready',
|
|
798
|
+
'client_focus_changed', 'client_joined', 'client_left', 'code_search_results', 'confirm_permission_mode',
|
|
799
|
+
'containers_action_ack', 'containers_status_snapshot', 'conversation_id', 'conversations_list',
|
|
800
|
+
'cost_summary', 'cost_update', 'credential_test_result', 'credentials_status',
|
|
801
|
+
'daemon_update_action_result', 'daemon_update_confirm_required', 'daemon_update_status',
|
|
802
|
+
'delete_archived_session_result', 'dev_preview', 'dev_preview_status', 'dev_preview_stopped',
|
|
803
|
+
'diff_result', 'directory_listing', 'emulator_action_ack', 'emulator_status_snapshot',
|
|
804
|
+
'environment_created', 'environment_destroyed', 'environment_error', 'environment_info',
|
|
805
|
+
'environment_list', 'evaluate_draft_result', 'evaluator_clarify', 'evaluator_rewrite',
|
|
806
|
+
'extension_message', 'external_sessions_snapshot', 'failed_restore_history', 'failed_restores_list',
|
|
807
|
+
'file_content', 'file_list', 'file_listing', 'folder_trust_result', 'folder_trust_state', 'git_branches_result', 'git_commit_result', 'git_create_pr_result',
|
|
808
|
+
'git_repo_check_result', 'git_stage_result', 'git_status_result', 'git_unstage_result',
|
|
809
|
+
'github_webhook_config', 'history_replay_end', 'history_replay_start', 'host_prune_action_ack',
|
|
810
|
+
'host_prune_status_snapshot', 'host_status_snapshot', 'inactivity_warning', 'integration_action_ack',
|
|
811
|
+
'integration_status_snapshot', 'log_entry', 'mailbox_status_snapshot', 'mcp_servers',
|
|
812
|
+
'memory_stack_result', 'message', 'message_dequeued', 'message_queued', 'model_changed',
|
|
813
|
+
'monthly_budget', 'multi_question_intervention', 'notification_prefs', 'orchestration_action_ack',
|
|
814
|
+
'orchestration_run_delta', 'orchestration_run_snapshot', 'orchestration_runs_snapshot', 'pair_fail',
|
|
815
|
+
'pair_pending', 'pair_request_pending', 'pair_resolved', 'pair_result', 'pairing_refreshed',
|
|
816
|
+
'permission_audit_result', 'permission_expired', 'permission_input', 'permission_mode_changed',
|
|
817
|
+
'permission_outcome', 'permission_request', 'permission_resolved', 'permission_rules_updated',
|
|
818
|
+
'plan_ready', 'plan_started', 'primary_changed', 'principal_admin_result', 'prompt_evaluator_changed',
|
|
819
|
+
'prompt_evaluator_skip_pattern_changed', 'provider_list', 'provider_runtime_info', 'push_token_error',
|
|
820
|
+
'references_result', 'repo_events_delta', 'repo_events_snapshot', 'repo_list',
|
|
821
|
+
'repo_runtime_config_snapshot', 'restore_archived_session_result', 'result',
|
|
822
|
+
'retry_failed_restore_result', 'runner_status_snapshot', 'scheduled_tasks', 'search_results',
|
|
823
|
+
'server_mode', 'server_shutdown', 'server_status', 'session_activity', 'session_archive_policy_result',
|
|
824
|
+
'session_context', 'session_cost_threshold_crossed', 'session_destroyed', 'session_list',
|
|
825
|
+
'session_persist_failed', 'session_pr_status', 'session_pr_threads', 'session_preamble_changed',
|
|
826
|
+
'session_preset_snapshot', 'session_restore_failed', 'session_role', 'session_status', 'session_stopped',
|
|
827
|
+
'session_switched', 'session_timeout', 'session_updated', 'session_usage', 'session_warning',
|
|
828
|
+
'shell_pending_approval', 'simulator_action_ack', 'simulator_status_snapshot', 'skill_activated',
|
|
829
|
+
'skill_changed', 'skill_deactivated', 'skill_trust_accepted', 'skill_trust_grant_ok',
|
|
830
|
+
'skill_trust_granted', 'skill_trust_request', 'skills_inventory_snapshot', 'skills_list',
|
|
831
|
+
'slash_commands', 'status', 'statusline_output', 'stdin_dropped_totals', 'stream_delta', 'stream_end',
|
|
832
|
+
'stream_start', 'subscriptions_updated', 'summarize_session_result', 'symbol_location',
|
|
833
|
+
'symbols_snapshot', 'terminal_output', 'terminal_size', 'thinking_level_changed', 'token_rotated',
|
|
834
|
+
'tool_input_backfill', 'tool_input_delta', 'tool_result', 'tool_start', 'tunnel_url_changed', 'user_input', 'user_question',
|
|
835
|
+
'web_feature_status', 'web_task_created', 'web_task_error', 'web_task_list', 'web_task_updated',
|
|
836
|
+
'write_file_result', 'wsl_action_ack', 'wsl_status_snapshot',
|
|
837
|
+
])
|
|
838
|
+
|
|
839
|
+
/**
|
|
840
|
+
* Frames sent to a principal by RAW socket writes that bypass `_send` on purpose (the
|
|
841
|
+
* key exchange is plaintext and must keep its ordering, so it cannot use the queued or
|
|
842
|
+
* encrypted sender). Each type lists the only fields it is sent with. `error` is limited
|
|
843
|
+
* to the key-exchange codes, and `server_error` (whose whitelist lives in
|
|
844
|
+
* `PRINCIPAL_OUTGOING_ALLOWED`) to the two fixed encryption messages.
|
|
845
|
+
* @type {Readonly<Record<string, { fields: readonly string[], codes?: readonly string[] }>>}
|
|
846
|
+
*/
|
|
847
|
+
export const PRINCIPAL_TRANSPORT_FRAMES = Object.freeze({
|
|
848
|
+
key_exchange_ok: Object.freeze({ fields: Object.freeze(['type', 'publicKey', 'serverKeySig', 'newIdentityKey', 'rotationCert']) }),
|
|
849
|
+
error: Object.freeze({
|
|
850
|
+
fields: Object.freeze(['type', 'code', 'message']),
|
|
851
|
+
codes: Object.freeze(['KEY_EXCHANGE_SALT_REQUIRED', 'INVALID_MESSAGE']),
|
|
852
|
+
}),
|
|
853
|
+
})
|
|
854
|
+
|
|
855
|
+
/** The fixed `server_error` texts the raw key-exchange sinks send. */
|
|
856
|
+
export const PRINCIPAL_TRANSPORT_SERVER_ERROR_MESSAGES = Object.freeze([
|
|
857
|
+
'Encryption required but key exchange timed out. Please reconnect.',
|
|
858
|
+
'Encryption required but client did not initiate key exchange.',
|
|
859
|
+
])
|
|
860
|
+
|
|
861
|
+
/**
|
|
862
|
+
* The payload a RAW transport send should write for `client`: the frame unchanged for a
|
|
863
|
+
* client that is not a principal (byte-identical), the whitelisted reduction for a
|
|
864
|
+
* principal, and null when a principal may not be sent it (the caller writes nothing).
|
|
865
|
+
* @param {object} client
|
|
866
|
+
* @param {object} frame
|
|
867
|
+
* @returns {object|null}
|
|
868
|
+
*/
|
|
869
|
+
export function principalTransportFrame(client, frame) {
|
|
870
|
+
if (!isPrincipalClient(client)) return frame
|
|
871
|
+
const type = frame?.type
|
|
872
|
+
if (type === 'server_error') {
|
|
873
|
+
if (!PRINCIPAL_TRANSPORT_SERVER_ERROR_MESSAGES.includes(frame.message)) return null
|
|
874
|
+
return { type, message: frame.message, recoverable: frame.recoverable }
|
|
875
|
+
}
|
|
876
|
+
if (typeof type !== 'string' || !Object.hasOwn(PRINCIPAL_TRANSPORT_FRAMES, type)) return null
|
|
877
|
+
const spec = PRINCIPAL_TRANSPORT_FRAMES[type]
|
|
878
|
+
if (spec.codes && !spec.codes.includes(frame.code)) return null
|
|
879
|
+
const out = {}
|
|
880
|
+
for (const field of spec.fields) {
|
|
881
|
+
if (Object.hasOwn(frame, field)) out[field] = frame[field]
|
|
882
|
+
}
|
|
883
|
+
return out
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/**
|
|
887
|
+
* Write a transport frame straight to a socket (plaintext, in order, no queue and no
|
|
888
|
+
* encryption: the key exchange needs exactly that) through `principalTransportFrame`.
|
|
889
|
+
* A client that is not a principal gets the frame unchanged. Throws what `ws.send` throws.
|
|
890
|
+
*/
|
|
891
|
+
export function sendRawTransport(ws, client, frame) {
|
|
892
|
+
const out = principalTransportFrame(client, frame)
|
|
893
|
+
if (out !== null) ws.send(JSON.stringify(out))
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
/**
|
|
897
|
+
* Frames a principal may receive on the BROADCAST path (the broadcaster and the
|
|
898
|
+
* session-broadcast paths), with the fields each is delivered with. EMPTY, and it stays
|
|
899
|
+
* empty in S3: a principal receives no ordinary session broadcast of any type (contract
|
|
900
|
+
* section 3.1 item 7). S3 chose the other of the two options its predecessor left open: the
|
|
901
|
+
* `principal_event` family is delivered by a dedicated per-subscription DIRECT send
|
|
902
|
+
* (principal-subscriptions.js) through `PRINCIPAL_OUTGOING_ALLOWED`, because the fence, the
|
|
903
|
+
* held buffer and the release order are per-subscription state and because the broadcast
|
|
904
|
+
* path would need the principal on the ClientManager session index, which S2 pinned shut.
|
|
905
|
+
* The extension point and `frameForPrincipalBroadcast` remain, deny by default, for a
|
|
906
|
+
* later child that needs a true broadcast; the grant check applies to every entry.
|
|
907
|
+
* @type {Readonly<Record<string, readonly string[]>>}
|
|
908
|
+
*/
|
|
909
|
+
export const PRINCIPAL_BROADCAST_ALLOWED = Object.freeze({})
|
|
910
|
+
|
|
911
|
+
// Frames `frameForPrincipalBroadcast` already vetted, mapped to the ONE client each was vetted
|
|
912
|
+
// for. The broadcaster hands them to `_send`, whose direct-reply allowlist would otherwise drop
|
|
913
|
+
// them. A vetted frame is frozen, is honoured only for its own recipient, and has its session
|
|
914
|
+
// re-checked against that recipient's grant at send time (a grant revoked in between wins).
|
|
915
|
+
const VETTED_BROADCAST = new WeakMap()
|
|
916
|
+
|
|
917
|
+
/**
|
|
918
|
+
* The frame a principal should receive from a BROADCAST, or null. Separate from
|
|
919
|
+
* `frameForPrincipal` (direct replies to the principal's own requests): the two
|
|
920
|
+
* allowlists are distinct, so a direct-reply type such as `session_error` reaches a
|
|
921
|
+
* principal only as a reply and never as a broadcast. A broadcast frame must be in
|
|
922
|
+
* `opts.broadcastAllowed` (default `PRINCIPAL_BROADCAST_ALLOWED`), carry a string
|
|
923
|
+
* `sessionId`, and pass `principalMaySee(..., 'observe')`.
|
|
924
|
+
* @param {object} client
|
|
925
|
+
* @param {object} message
|
|
926
|
+
* @param {PrincipalPolicyOpts & { broadcastAllowed?: Readonly<Record<string, readonly string[]>> }} [opts]
|
|
927
|
+
* @returns {object|null}
|
|
928
|
+
*/
|
|
929
|
+
export function frameForPrincipalBroadcast(client, message, opts = {}) {
|
|
930
|
+
if (!isPrincipalClient(client)) return null
|
|
931
|
+
const allowed = opts.broadcastAllowed ?? PRINCIPAL_BROADCAST_ALLOWED
|
|
932
|
+
const type = message?.type
|
|
933
|
+
if (typeof type !== 'string' || !Object.hasOwn(allowed, type)) return null
|
|
934
|
+
if (typeof message.sessionId !== 'string' || !principalMaySee(client, message.sessionId, 'observe', opts).ok) return null
|
|
935
|
+
const frame = {}
|
|
936
|
+
for (const field of allowed[type]) {
|
|
937
|
+
if (Object.hasOwn(message, field)) frame[field] = cloneField(message[field])
|
|
938
|
+
}
|
|
939
|
+
const binding = client.boundSessionId
|
|
940
|
+
if (typeof binding === 'string' && binding.length > 0 && JSON.stringify(frame).includes(binding)) return null
|
|
941
|
+
VETTED_BROADCAST.set(frame, client)
|
|
942
|
+
return deepFreezeFrame(frame)
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
/** Freeze a vetted frame and every nested object in it: `Object.freeze` alone is shallow. */
|
|
946
|
+
function deepFreezeFrame(value) {
|
|
947
|
+
if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
948
|
+
Object.freeze(value)
|
|
949
|
+
for (const key of Object.keys(value)) deepFreezeFrame(value[key])
|
|
950
|
+
}
|
|
951
|
+
return value
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
/** A frame field's value, deep-copied when it is an object or array. */
|
|
955
|
+
function cloneField(value) {
|
|
956
|
+
return value !== null && typeof value === 'object' ? structuredClone(value) : value
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
/**
|
|
960
|
+
* The frame a principal should receive for `message`, or null when it must
|
|
961
|
+
* receive nothing. DENY BY DEFAULT: a type that is not in
|
|
962
|
+
* `PRINCIPAL_OUTGOING_ALLOWED` is never delivered, and a frame tagged with a
|
|
963
|
+
* string `sessionId` is delivered only when `principalMaySee(..., 'observe')`
|
|
964
|
+
* passes for it. The delivered frame is rebuilt from the type's field whitelist.
|
|
965
|
+
* As a last line of defence a frame that contains the client's own binding value
|
|
966
|
+
* is dropped, so the sentinel cannot reach the wire through a future field.
|
|
967
|
+
*
|
|
968
|
+
* @param {object} client
|
|
969
|
+
* @param {object} message
|
|
970
|
+
* @param {PrincipalPolicyOpts} [opts]
|
|
971
|
+
* @returns {object|null}
|
|
972
|
+
*/
|
|
973
|
+
export function frameForPrincipal(client, message, opts = {}) {
|
|
974
|
+
if (!isPrincipalClient(client)) return null
|
|
975
|
+
if (message !== null && typeof message === 'object' && VETTED_BROADCAST.has(message)) {
|
|
976
|
+
const ok = VETTED_BROADCAST.get(message) === client && Object.isFrozen(message) &&
|
|
977
|
+
typeof message.sessionId === 'string' && principalMaySee(client, message.sessionId, 'observe', opts).ok
|
|
978
|
+
return ok ? message : null
|
|
979
|
+
}
|
|
980
|
+
const type = message?.type
|
|
981
|
+
if (typeof type !== 'string' || !Object.hasOwn(PRINCIPAL_OUTGOING_ALLOWED, type)) return null
|
|
982
|
+
// The ONE frame that is delivered for a session the principal can no longer see: the notice
|
|
983
|
+
// that its own subscription ended because the grant was narrowed or the session was removed.
|
|
984
|
+
// It names only the session id the principal itself subscribed to, and nothing else.
|
|
985
|
+
const endNotice = type === 'principal_gap' && message.ended === true && (message.reason === 'scope' || message.reason === 'removed')
|
|
986
|
+
if (!endNotice && typeof message.sessionId === 'string' && !principalMaySee(client, message.sessionId, 'observe', opts).ok) {
|
|
987
|
+
return null
|
|
988
|
+
}
|
|
989
|
+
// `principal_subscribed` lists its sessions instead of carrying one: each must be granted.
|
|
990
|
+
if (type === 'principal_subscribed') {
|
|
991
|
+
const sessions = message.sessions
|
|
992
|
+
if (sessions !== undefined && (!Array.isArray(sessions) || !sessions.every((s) => typeof s?.sessionId === 'string' && principalMaySee(client, s.sessionId, 'observe', opts).ok))) {
|
|
993
|
+
return null
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
// The roster lists sessions instead of carrying one: each must be granted, and each row is
|
|
997
|
+
// rebuilt from its own whitelists. A frame that holds more rows than the cap is refused.
|
|
998
|
+
if (type === 'principal_sessions_snapshot_result') {
|
|
999
|
+
const rows = message.sessions
|
|
1000
|
+
if (rows !== undefined && (!Array.isArray(rows) || rows.length > PRINCIPAL_SESSION_ROWS_MAX ||
|
|
1001
|
+
!rows.every((r) => r !== null && typeof r === 'object' && typeof r.sessionId === 'string' && principalMaySee(client, r.sessionId, 'observe', opts).ok))) {
|
|
1002
|
+
return null
|
|
1003
|
+
}
|
|
1004
|
+
const rebuilt = {}
|
|
1005
|
+
for (const field of PRINCIPAL_OUTGOING_ALLOWED[type]) {
|
|
1006
|
+
if (field === 'sessions') { if (rows !== undefined) rebuilt.sessions = rows.map(rebuildSessionRow) }
|
|
1007
|
+
else if (Object.hasOwn(message, field)) rebuilt[field] = cloneField(message[field])
|
|
1008
|
+
}
|
|
1009
|
+
return withoutBindingValue(client, rebuilt)
|
|
1010
|
+
}
|
|
1011
|
+
// The snapshot lists requests instead of carrying one session: each must be granted, and
|
|
1012
|
+
// each is rebuilt from its own whitelist (no input, a description only when not floored).
|
|
1013
|
+
if (type === 'principal_pending_permissions_result') {
|
|
1014
|
+
const requests = message.permissions
|
|
1015
|
+
if (requests !== undefined && (!Array.isArray(requests) || !requests.every((r) => typeof r?.sessionId === 'string' && principalMaySee(client, r.sessionId, 'observe', opts).ok))) {
|
|
1016
|
+
return null
|
|
1017
|
+
}
|
|
1018
|
+
const rebuilt = {}
|
|
1019
|
+
for (const field of PRINCIPAL_OUTGOING_ALLOWED[type]) {
|
|
1020
|
+
if (field === 'permissions') {
|
|
1021
|
+
if (requests !== undefined) rebuilt.permissions = requests.map((r) => {
|
|
1022
|
+
const entry = {}
|
|
1023
|
+
for (const key of PRINCIPAL_PENDING_PERMISSION_FIELDS) {
|
|
1024
|
+
if (key === 'description' && r.floored !== false) continue
|
|
1025
|
+
if (Object.hasOwn(r, key)) entry[key] = cloneField(r[key])
|
|
1026
|
+
}
|
|
1027
|
+
return entry
|
|
1028
|
+
})
|
|
1029
|
+
} else if (Object.hasOwn(message, field)) {
|
|
1030
|
+
rebuilt[field] = cloneField(message[field])
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
return withoutBindingValue(client, rebuilt)
|
|
1034
|
+
}
|
|
1035
|
+
const frame = {}
|
|
1036
|
+
for (const field of PRINCIPAL_OUTGOING_ALLOWED[type]) {
|
|
1037
|
+
// A nested value is copied, never shared: the delivered frame holds nothing the
|
|
1038
|
+
// journal (or any other owner) can still change or that could be changed through it.
|
|
1039
|
+
if (Object.hasOwn(message, field)) frame[field] = cloneField(message[field])
|
|
1040
|
+
}
|
|
1041
|
+
return withoutBindingValue(client, frame)
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
/** The frame, or null when it contains the client's own binding value (the sentinel must not reach the wire). */
|
|
1045
|
+
function withoutBindingValue(client, frame) {
|
|
1046
|
+
const binding = client.boundSessionId
|
|
1047
|
+
if (typeof binding === 'string' && binding.length > 0 && JSON.stringify(frame).includes(binding)) return null
|
|
1048
|
+
return frame
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
// -- Never table (contract §4.3) ----------------------------------------------
|
|
1052
|
+
|
|
1053
|
+
/**
|
|
1054
|
+
* Each capability a principal never holds, as a machine-read table. Column (a) is
|
|
1055
|
+
* the dispatch allowlist (the type is absent from `PRINCIPAL_ALLOWED_MESSAGE_TYPES`).
|
|
1056
|
+
* Column (b) is `handlerPredicate`: the handler-level check that refuses a
|
|
1057
|
+
* principal on its own. The guard in tests/principal-policy.test.js reads THIS
|
|
1058
|
+
* constant, not the contract prose.
|
|
1059
|
+
*
|
|
1060
|
+
* - `types`: the client message types the row covers (empty when no WebSocket
|
|
1061
|
+
* type exists).
|
|
1062
|
+
* - `sentinelDependent`: the predicate tests a truthy `boundSessionId` (not
|
|
1063
|
+
* `isBoundClient`, which has refused a principal through its own `principal != null`
|
|
1064
|
+
* clause since S1), so it refuses a principal ONLY because the sentinel is set.
|
|
1065
|
+
* Removing the sentinel must turn it red.
|
|
1066
|
+
* - `s2AddsRefusal`: the handler had no principal-relevant check; S2 adds an
|
|
1067
|
+
* explicit `isPrincipalClient` refusal.
|
|
1068
|
+
*
|
|
1069
|
+
* @type {readonly Readonly<{ id: string, capability: string, types: readonly string[], handlerPredicate: string, sentinelDependent: boolean, s2AddsRefusal: boolean }>[]}
|
|
1070
|
+
*/
|
|
1071
|
+
export const PRINCIPAL_NEVER_CAPABILITIES = Object.freeze([
|
|
1072
|
+
{ id: 'permission-mode', capability: 'auto / more-permissive mode, acceptEdits, skipPermissions', types: ['set_permission_mode'], handlerPredicate: 'handleSetPermissionMode resolves the session through resolveSession, which refuses isBoundClient(client) bound to another id; isBoundClient is true for a principal through the principal clause (S1), with or without the sentinel', sentinelDependent: false, s2AddsRefusal: false },
|
|
1073
|
+
{ id: 'permission-rules', capability: 'permission rules and allowAlways', types: ['set_permission_rules'], handlerPredicate: 'handleSetPermissionRules refuses isPrincipalClient(client) first (independent gate); isBoundClient(client) follows', sentinelDependent: false, s2AddsRefusal: true },
|
|
1074
|
+
{ id: 'revoke-token', capability: 'revoke_token', types: ['revoke_token'], handlerPredicate: 'handleRevokeToken refuses client.isPrimaryToken !== true', sentinelDependent: false, s2AddsRefusal: false },
|
|
1075
|
+
{ id: 'pairing', capability: 'pairing (pair_approve, pair_deny), QR, /connect', types: ['pair_approve', 'pair_deny'], handlerPredicate: 'rejectIfBound refuses a truthy boundSessionId', sentinelDependent: true, s2AddsRefusal: false },
|
|
1076
|
+
{ id: 'identity-rotation', capability: 'identity rotation', types: [], handlerPredicate: 'no WebSocket type exists; the CLI needs local primary authority', sentinelDependent: false, s2AddsRefusal: false },
|
|
1077
|
+
{ id: 'mcp-config', capability: 'MCP config', types: ['add_mcp_server', 'remove_mcp_server'], handlerPredicate: 'rejectMcpConfigWriteUnlessPrimary refuses client.isPrimaryToken !== true', sentinelDependent: false, s2AddsRefusal: false },
|
|
1078
|
+
{ id: 'folder-trust', capability: 'folder trust', types: ['trust_folder', 'untrust_folder'], handlerPredicate: 'rejectFolderTrustUnlessPrimary refuses client.isPrimaryToken !== true or isBoundClient(client), true for a principal through the principal clause (S1), with or without the sentinel', sentinelDependent: false, s2AddsRefusal: false },
|
|
1079
|
+
{ id: 'skill-trust', capability: 'skill trust', types: ['skill_trust_accept', 'skill_trust_grant'], handlerPredicate: 'rejectSkillTrustIfBound refuses isPrincipalClient(client) first (independent gate); a truthy boundSessionId follows', sentinelDependent: false, s2AddsRefusal: true },
|
|
1080
|
+
{ id: 'file-git-writes', capability: 'file and git writes', types: ['write_file', 'append_memory', 'git_stage', 'git_unstage', 'git_commit', 'git_create_pr'], handlerPredicate: 'rejectMutationIfBound refuses a truthy boundSessionId', sentinelDependent: true, s2AddsRefusal: false },
|
|
1081
|
+
{ id: 'environment-create', capability: 'environments (create)', types: ['create_environment'], handlerPredicate: 'handleCreateEnvironment refuses client.isPrimaryToken !== true', sentinelDependent: false, s2AddsRefusal: false },
|
|
1082
|
+
{ id: 'environment-destroy', capability: 'environments (destroy)', types: ['destroy_environment'], handlerPredicate: 'handleDestroyEnvironment refuses isBoundClient(client), true for a principal through the principal clause (S1), with or without the sentinel', sentinelDependent: false, s2AddsRefusal: false },
|
|
1083
|
+
{ id: 'config-settings', capability: 'host-wide config and settings', types: ['session_preset_set'], handlerPredicate: 'handleSessionPresetSet opens with rejectIfNotHost, which refuses a truthy boundSessionId', sentinelDependent: true, s2AddsRefusal: false },
|
|
1084
|
+
{ id: 'notification-prefs', capability: 'notification preferences', types: ['notification_prefs_set'], handlerPredicate: 'handleNotificationPrefsSet refuses isPrincipalClient(client) (it had no authority check)', sentinelDependent: false, s2AddsRefusal: true },
|
|
1085
|
+
{ id: 'terminal-input', capability: 'user-shell, terminal_input, shell terminal_subscribe', types: ['terminal_input'], handlerPredicate: 'handleTerminalInput refuses isPrincipalClient(client) unconditionally (the user-shell check applies to user-shell sessions only)', sentinelDependent: false, s2AddsRefusal: true },
|
|
1086
|
+
{ id: 'terminal-subscribe', capability: 'shell terminal_subscribe (and raw terminal output)', types: ['terminal_subscribe'], handlerPredicate: 'handleTerminalSubscribe returns when a bound client names another session (the sentinel); a user-shell session additionally needs client.isPrimaryToken === true', sentinelDependent: true, s2AddsRefusal: false },
|
|
1087
|
+
{ id: 'dev-preview', capability: 'dev-preview publication', types: ['open_dev_preview'], handlerPredicate: 'DevPreviewManager._assertAuthority requires the primary-token client with no boundSessionId', sentinelDependent: false, s2AddsRefusal: false },
|
|
1088
|
+
{ id: 'archive', capability: 'archive purge and policy', types: ['delete_archived_session', 'set_session_archive_policy'], handlerPredicate: 'both handlers refuse isBoundClient(client), true for a principal through the principal clause (S1), with or without the sentinel', sentinelDependent: false, s2AddsRefusal: false },
|
|
1089
|
+
{ id: 'daemon-update', capability: 'daemon update and restart', types: ['daemon_update_action'], handlerPredicate: 'handleDaemonUpdateAction refuses isPrimaryToken !== true or a truthy boundSessionId', sentinelDependent: false, s2AddsRefusal: false },
|
|
1090
|
+
{ id: 'scheduled-tasks', capability: 'scheduled tasks', types: ['scheduled_task_action', 'set_scheduler_enabled'], handlerPredicate: 'rejectSchedulerWriteUnlessPrimary refuses a non-primary client or a truthy boundSessionId', sentinelDependent: false, s2AddsRefusal: false },
|
|
1091
|
+
{ id: 'orchestration-start', capability: 'orchestration start', types: ['orchestration_run_start'], handlerPredicate: 'guardAction refuses a truthy boundSessionId and, with requirePrimary, a non-primary client', sentinelDependent: false, s2AddsRefusal: false },
|
|
1092
|
+
{ id: 'checkpoint-restore', capability: 'checkpoint file restore', types: ['restore_checkpoint'], handlerPredicate: 'handleRestoreCheckpoint refuses isBoundClient(client), true for a principal through the principal clause (S1), with or without the sentinel', sentinelDependent: false, s2AddsRefusal: false },
|
|
1093
|
+
{ id: 'set-model', capability: 'set_model (v1)', types: ['set_model'], handlerPredicate: 'handleSetModel resolves the session through resolveSession, which refuses isBoundClient(client) bound to another id; isBoundClient is true for a principal through the principal clause (S1), with or without the sentinel', sentinelDependent: false, s2AddsRefusal: false },
|
|
1094
|
+
].map((row) => Object.freeze({ ...row, types: Object.freeze([...row.types]) })))
|