@chroxy/server 0.11.0 → 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 +206 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +958 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +304 -0
- package/src/agent-control/client.js +1645 -0
- package/src/agent-control/events.js +551 -0
- package/src/agent-control/local-connection.js +293 -0
- package/src/agent-control/mcp-server.js +547 -0
- package/src/anthropic-compatible-config.js +30 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1520 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +291 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +92 -7
- package/src/byok-mcp-config.js +633 -122
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +37 -23
- package/src/byok-session.js +707 -179
- package/src/byok-tool-executor.js +2742 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-setting-sources.js +74 -0
- package/src/claude-stream-parser.js +53 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +215 -88
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3563 -284
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-cmd.js +236 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/connection-state.js +54 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/init-cmd.js +15 -16
- 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/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +91 -40
- package/src/cli/server-cmd.js +54 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1250 -126
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1517 -81
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-error-text.js +114 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +450 -27
- package/src/config-dir-migration.js +449 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +306 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +78 -23
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +227 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +42 -39
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +28 -39
- package/src/credential-store.js +23 -19
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +170 -182
- package/src/device-preferences.js +2 -2
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +172 -3
- package/src/docker-session.js +294 -11
- package/src/doctor.js +781 -64
- package/src/durable-write.js +35 -0
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +101 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +186 -235
- 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/gemini-session.js +81 -5
- package/src/handler-utils.js +540 -80
- package/src/handlers/checkpoint-handlers.js +47 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +57 -13
- package/src/handlers/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +714 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +92 -18
- package/src/handlers/session-handlers.js +551 -20
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +372 -50
- package/src/handlers/skills-handlers.js +20 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +112 -0
- package/src/http-routes.js +127 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +378 -91
- package/src/jsonl-subprocess-session.js +96 -9
- package/src/keychain.js +1 -1
- package/src/logger.js +166 -30
- package/src/mailbox-route.js +113 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +27 -4
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +64 -23
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +112 -36
- package/src/orchestration/permission-gate.js +17 -2
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +185 -43
- package/src/orphan-reaper.js +470 -0
- package/src/outgoing-policy.js +189 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1410 -43
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +737 -89
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +126 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +315 -47
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- 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/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +209 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +531 -20
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +330 -26
- package/src/scheduler.js +368 -11
- package/src/sdk-session.js +2114 -188
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +17 -3
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +553 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +1099 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +4062 -312
- package/src/session-message-history.js +841 -16
- package/src/session-name-allocator.js +685 -0
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-token-store.js +17 -8
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +100 -29
- package/src/summarize-session.js +53 -4
- package/src/supervisor.js +22 -11
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +140 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +770 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +639 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +29 -0
- package/src/utils/bounded-regex.js +162 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +133 -37
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/pid-liveness.js +47 -0
- package/src/utils/preflight.js +360 -16
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +297 -16
- package/src/worktree-gc.js +202 -6
- package/src/ws-auth.js +163 -31
- package/src/ws-broadcaster.js +49 -5
- package/src/ws-client-manager.js +24 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +363 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +349 -39
- package/src/ws-handler-context.js +88 -2
- package/src/ws-history.js +1010 -175
- package/src/ws-message-handlers.js +25 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +885 -98
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
|
@@ -209,9 +209,9 @@ function orchestration_run_action(ws, client, msg, ctx) {
|
|
|
209
209
|
.then(() => manager(ctx).runAction(msg.runId, msg.action))
|
|
210
210
|
.then(() => sendAck(ws, ctx, msg, msg.action, msg.runId))
|
|
211
211
|
// 'unsupported' is a PERMANENT no — this engine will never serve the action
|
|
212
|
-
//
|
|
213
|
-
//
|
|
214
|
-
//
|
|
212
|
+
// — as distinct from 'action-failed', which is "not this time". The wire
|
|
213
|
+
// schema admits `cancel` only (pause/resume were removed, #7140), so this is
|
|
214
|
+
// the backstop for a caller that skipped the validator.
|
|
215
215
|
.catch((err) => orchestrationActionError(ws, ctx, msg,
|
|
216
216
|
err?.code === 'ACTION_UNSUPPORTED' ? 'unsupported' : 'action-failed',
|
|
217
217
|
getErrorMessage(err, `failed to ${msg.action} run`)))
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent-principal management over WebSocket (agent-principals.md §3.1 "Management
|
|
3
|
+
* surface"): `principal_admin_grant`, `principal_admin_list`, `principal_admin_revoke`.
|
|
4
|
+
*
|
|
5
|
+
* Each is STRICT-PRIMARY and LOOPBACK-ONLY, and the gate is the FIRST statement of the
|
|
6
|
+
* handler: `isPrimaryToken === true`, no session binding, no principal stamp, and an
|
|
7
|
+
* upgrade request that still passes `isLoopbackPeer`. A pairing token, a bound token and
|
|
8
|
+
* a principal are all refused, and every other gate in this module sits behind that one.
|
|
9
|
+
* The daemon is the only writer of the principal store; the CLI asks the daemon.
|
|
10
|
+
*
|
|
11
|
+
* `grant` REFUSES ("agent principals not yet enabled") until the audit writer and kill
|
|
12
|
+
* switch land (§12 landing order). There is no mint path behind the refusal.
|
|
13
|
+
*
|
|
14
|
+
* `revoke` and `disable` follow the §10.2 order: flip in memory, persist durably (file
|
|
15
|
+
* fsync, rename, directory fsync), acknowledge, then end the affected principals'
|
|
16
|
+
* connections with `credential_invalidated` and close code 4401, then drain their queued
|
|
17
|
+
* work with one `dropped:<reason>` audit line per entry.
|
|
18
|
+
*
|
|
19
|
+
* `disable` is a safety brake: it proceeds even when the audit write fails (its line is
|
|
20
|
+
* best effort). `enable` is the permissive direction: it REFUSES when the audit line
|
|
21
|
+
* cannot be written, and is never automatic.
|
|
22
|
+
*/
|
|
23
|
+
import { createLogger } from '../logger.js'
|
|
24
|
+
import { isLoopbackPeer } from '../connection-locality.js'
|
|
25
|
+
import { PRINCIPALS_NOT_ENABLED_MESSAGE, PRINCIPAL_LABEL_PATTERN } from '../principal-store.js'
|
|
26
|
+
import { principalAuditor } from '../principal-audit.js'
|
|
27
|
+
|
|
28
|
+
const log = createLogger('principal-admin')
|
|
29
|
+
|
|
30
|
+
function reply(ws, ctx, msg, op, fields) {
|
|
31
|
+
ctx.transport.send(ws, {
|
|
32
|
+
type: 'principal_admin_result',
|
|
33
|
+
requestId: typeof msg?.requestId === 'string' ? msg.requestId : null,
|
|
34
|
+
op,
|
|
35
|
+
...fields,
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The strict-primary, unbound, non-principal, loopback gate. True when the caller may proceed. */
|
|
40
|
+
function mayAdminister(client) {
|
|
41
|
+
return client?.isPrimaryToken === true && !client.boundSessionId && !client.principal &&
|
|
42
|
+
isLoopbackPeer(client._upgradeReq)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function refuseUnauthorized(ws, client, msg, ctx, op) {
|
|
46
|
+
log.warn(`Denied ${op} from ${client?.id ?? 'a client'} (NOT_AUTHORIZED)`)
|
|
47
|
+
reply(ws, ctx, msg, op, { ok: false, code: 'NOT_AUTHORIZED', message: 'Managing agent principals requires the primary token from this machine.' })
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function handlePrincipalAdminGrant(ws, client, msg, ctx) {
|
|
51
|
+
if (!mayAdminister(client)) return refuseUnauthorized(ws, client, msg, ctx, 'grant')
|
|
52
|
+
reply(ws, ctx, msg, 'grant', { ok: false, code: 'PRINCIPALS_NOT_ENABLED', message: PRINCIPALS_NOT_ENABLED_MESSAGE })
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function handlePrincipalAdminList(ws, client, msg, ctx) {
|
|
56
|
+
if (!mayAdminister(client)) return refuseUnauthorized(ws, client, msg, ctx, 'list')
|
|
57
|
+
const store = ctx.services?.principalStore
|
|
58
|
+
if (!store) {
|
|
59
|
+
reply(ws, ctx, msg, 'list', { ok: false, code: 'UNAVAILABLE', message: 'The principal store is not available on this server.' })
|
|
60
|
+
return
|
|
61
|
+
}
|
|
62
|
+
const { health, principals } = store.list()
|
|
63
|
+
reply(ws, ctx, msg, 'list', {
|
|
64
|
+
ok: true,
|
|
65
|
+
health: { ok: health.ok, status: health.status, reason: health.reason },
|
|
66
|
+
principals,
|
|
67
|
+
})
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function handlePrincipalAdminRevoke(ws, client, msg, ctx) {
|
|
71
|
+
if (!mayAdminister(client)) return refuseUnauthorized(ws, client, msg, ctx, 'revoke')
|
|
72
|
+
const store = ctx.services?.principalStore
|
|
73
|
+
if (!store) {
|
|
74
|
+
reply(ws, ctx, msg, 'revoke', { ok: false, code: 'UNAVAILABLE', message: 'The principal store is not available on this server.' })
|
|
75
|
+
return
|
|
76
|
+
}
|
|
77
|
+
const selector = typeof msg.principalId === 'string' && msg.principalId.length > 0
|
|
78
|
+
? { principalId: msg.principalId }
|
|
79
|
+
: (typeof msg.label === 'string' && msg.label.length > 0 ? { label: msg.label } : null)
|
|
80
|
+
if (selector === null) {
|
|
81
|
+
reply(ws, ctx, msg, 'revoke', { ok: false, code: 'BAD_REQUEST', message: 'Name a principal by principalId or label.' })
|
|
82
|
+
return
|
|
83
|
+
}
|
|
84
|
+
// Memory first, then the durable write (inside store.revoke), then the verdict.
|
|
85
|
+
const out = store.revoke(selector)
|
|
86
|
+
if (!out.found) {
|
|
87
|
+
reply(ws, ctx, msg, 'revoke', { ok: false, code: 'NOT_FOUND', message: 'No such live principal.' })
|
|
88
|
+
return
|
|
89
|
+
}
|
|
90
|
+
log.warn(`Principal ${out.principalId} revoked by client ${client.id} (durable=${out.durable})`)
|
|
91
|
+
// A revoke is a brake too: its outcome line is best effort and never blocks it.
|
|
92
|
+
auditorOf(ctx).outcome({ principalId: out.principalId, label: out.label }, { action: 'revoke', requestId: msg.requestId }, 'revoked', out.durable ? 'durable' : 'not_durable')
|
|
93
|
+
reply(ws, ctx, msg, 'revoke', {
|
|
94
|
+
ok: true,
|
|
95
|
+
principalId: out.principalId,
|
|
96
|
+
alreadyRevoked: out.alreadyRevoked,
|
|
97
|
+
durable: out.durable,
|
|
98
|
+
...(out.durable ? {} : { message: 'Revoked in this process but NOT durable: a restart before a successful write can revive it. Revoke again once the store is writable.' }),
|
|
99
|
+
})
|
|
100
|
+
// The revoke is acknowledged; now cut the principal's connections.
|
|
101
|
+
ctx.services?.endPrincipalConnections?.(out.principalId, 'revoked')
|
|
102
|
+
dropQueuedWork(ctx, { principalId: out.principalId }, 'revoked')
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** `{ all: true }` or `{ label }`, never both, never neither; a label must be well formed. */
|
|
106
|
+
function parseSwitchSelector(msg) {
|
|
107
|
+
const hasAll = msg?.all === true
|
|
108
|
+
const hasLabel = typeof msg?.label === 'string' && msg.label.length > 0
|
|
109
|
+
if (hasAll === hasLabel) return null
|
|
110
|
+
if (hasAll) return { all: true }
|
|
111
|
+
return PRINCIPAL_LABEL_PATTERN.test(msg.label) ? { label: msg.label } : null
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function auditorOf(ctx) {
|
|
115
|
+
return ctx.services?.principalAuditor ?? principalAuditor
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Drain principal-tagged queued work (the S9 queue, absent on this build: the hook
|
|
120
|
+
* returns nothing) and write one `dropped:<reason>` outcome line per dropped entry. A
|
|
121
|
+
* failing drain is logged and never blocks the brake: the credential is already dead
|
|
122
|
+
* and a queue's delivery path must re-check it (contract 6.5).
|
|
123
|
+
*/
|
|
124
|
+
function dropQueuedWork(ctx, selector, reason) {
|
|
125
|
+
let dropped = []
|
|
126
|
+
try {
|
|
127
|
+
const out = ctx.services?.drainPrincipalQueues?.(selector)
|
|
128
|
+
dropped = Array.isArray(out) ? out : []
|
|
129
|
+
} catch (err) {
|
|
130
|
+
log.error(`Draining principal queues failed: ${err?.message || err}`)
|
|
131
|
+
}
|
|
132
|
+
const auditor = auditorOf(ctx)
|
|
133
|
+
for (const entry of dropped) {
|
|
134
|
+
auditor.outcome({ principalId: entry?.principalId, label: entry?.label }, { action: 'enqueue', ...entry, text: undefined }, `dropped:${reason}`, reason)
|
|
135
|
+
}
|
|
136
|
+
return dropped.length
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function describeSelector(selector) {
|
|
140
|
+
return selector.all === true ? 'all agent principals' : `label ${selector.label}`
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function handlePrincipalAdminDisable(ws, client, msg, ctx) {
|
|
144
|
+
if (!mayAdminister(client)) return refuseUnauthorized(ws, client, msg, ctx, 'disable')
|
|
145
|
+
const sw = ctx.services?.principalStore?.brakes?.killSwitch
|
|
146
|
+
if (!sw) {
|
|
147
|
+
reply(ws, ctx, msg, 'disable', { ok: false, code: 'UNAVAILABLE', message: 'The agent kill switch is not available on this server.' })
|
|
148
|
+
return
|
|
149
|
+
}
|
|
150
|
+
const selector = parseSwitchSelector(msg)
|
|
151
|
+
if (selector === null) {
|
|
152
|
+
reply(ws, ctx, msg, 'disable', { ok: false, code: 'BAD_REQUEST', message: 'Name exactly one of all: true or a label.' })
|
|
153
|
+
return
|
|
154
|
+
}
|
|
155
|
+
// 1. Memory first (inside disable): from here principal auth and every principal frame
|
|
156
|
+
// are refused. 2. Then the durable write (file fsync, rename, directory fsync).
|
|
157
|
+
const out = sw.disable(selector)
|
|
158
|
+
if (!out.ok) {
|
|
159
|
+
reply(ws, ctx, msg, 'disable', { ok: false, code: out.code, message: out.code === 'TOO_MANY_LABELS' ? 'Too many disabled labels: nothing was changed. Use --all to disable every agent.' : 'Could not apply the request.' })
|
|
160
|
+
return
|
|
161
|
+
}
|
|
162
|
+
// The kill is a SAFETY BRAKE: it proceeds whether or not this line can be written
|
|
163
|
+
// (the writer's verdict is deliberately ignored here), unlike `enable`.
|
|
164
|
+
auditorOf(ctx).outcome(null, { action: 'disable', requestId: msg.requestId, ...(selector.label ? { label: selector.label } : {}) }, 'killed', selector.all === true ? 'all' : 'label')
|
|
165
|
+
log.warn(`Agent principals disabled (${describeSelector(selector)}) by client ${client.id} (durable=${out.durable})`)
|
|
166
|
+
// 3. Ack, carrying the durability verdict. Memory stays disabled when it is false.
|
|
167
|
+
reply(ws, ctx, msg, 'disable', {
|
|
168
|
+
ok: true,
|
|
169
|
+
durable: out.durable,
|
|
170
|
+
disabled: out.state,
|
|
171
|
+
...(out.durable ? {} : { message: 'Disabled in this process but NOT durable: a restart before a successful write can revive the principals. Disable again once the config directory is writable.' }),
|
|
172
|
+
})
|
|
173
|
+
// 4. Cut the affected connections (4401). 5. Drain their queued work. 6. Leases: none exist
|
|
174
|
+
// yet (S8), which releases them when it lands.
|
|
175
|
+
ctx.services?.endPrincipalConnections?.(selector, 'disabled')
|
|
176
|
+
dropQueuedWork(ctx, selector, 'killed')
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const ENABLE_REFUSAL_MESSAGES = {
|
|
180
|
+
ALL_DISABLED: 'Every agent is disabled: re-enable with --all.',
|
|
181
|
+
PERSIST_UNCONFIRMED: 'The enable was not confirmed on disk, so the daemon stays disabled. The file may already read "enabled", so a restart could apply it: run enable again once the disk is healthy, or run disable to make the disabled state durable.',
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function handlePrincipalAdminEnable(ws, client, msg, ctx) {
|
|
185
|
+
if (!mayAdminister(client)) return refuseUnauthorized(ws, client, msg, ctx, 'enable')
|
|
186
|
+
const sw = ctx.services?.principalStore?.brakes?.killSwitch
|
|
187
|
+
if (!sw) {
|
|
188
|
+
reply(ws, ctx, msg, 'enable', { ok: false, code: 'UNAVAILABLE', message: 'The agent kill switch is not available on this server.' })
|
|
189
|
+
return
|
|
190
|
+
}
|
|
191
|
+
const selector = parseSwitchSelector(msg)
|
|
192
|
+
if (selector === null) {
|
|
193
|
+
reply(ws, ctx, msg, 'enable', { ok: false, code: 'BAD_REQUEST', message: 'Name exactly one of all: true or a label.' })
|
|
194
|
+
return
|
|
195
|
+
}
|
|
196
|
+
// Permissive direction: the audit attempt line must be written BEFORE anything changes.
|
|
197
|
+
const descriptor = { action: 'enable', requestId: msg.requestId, ...(selector.label ? { label: selector.label } : {}) }
|
|
198
|
+
const auditor = auditorOf(ctx)
|
|
199
|
+
if (auditor.attempt(null, descriptor).ok !== true) {
|
|
200
|
+
log.warn(`Refused enable (${describeSelector(selector)}): the audit log is unavailable`)
|
|
201
|
+
reply(ws, ctx, msg, 'enable', { ok: false, code: 'AUDIT_UNAVAILABLE', message: 'Re-enabling agents requires a writable audit log, and it is not available.' })
|
|
202
|
+
return
|
|
203
|
+
}
|
|
204
|
+
const out = sw.enable(selector)
|
|
205
|
+
if (!out.ok) {
|
|
206
|
+
reply(ws, ctx, msg, 'enable', {
|
|
207
|
+
ok: false,
|
|
208
|
+
code: out.code,
|
|
209
|
+
message: ENABLE_REFUSAL_MESSAGES[out.code] ?? 'Could not re-enable: the switch file could not be written, so agents stay disabled.',
|
|
210
|
+
})
|
|
211
|
+
return
|
|
212
|
+
}
|
|
213
|
+
auditor.outcome(null, descriptor, 'enabled', out.durable ? 'durable' : 'not_durable')
|
|
214
|
+
log.warn(`Agent principals enabled (${describeSelector(selector)}) by client ${client.id} (durable=${out.durable})`)
|
|
215
|
+
reply(ws, ctx, msg, 'enable', {
|
|
216
|
+
ok: true,
|
|
217
|
+
durable: out.durable,
|
|
218
|
+
disabled: out.state,
|
|
219
|
+
...(out.durable ? {} : { message: 'Enabled in this process but NOT durable: a restart before a successful write brings the previous state back.' }),
|
|
220
|
+
})
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export const principalAdminHandlers = {
|
|
224
|
+
principal_admin_grant: handlePrincipalAdminGrant,
|
|
225
|
+
principal_admin_list: handlePrincipalAdminList,
|
|
226
|
+
principal_admin_revoke: handlePrincipalAdminRevoke,
|
|
227
|
+
principal_admin_disable: handlePrincipalAdminDisable,
|
|
228
|
+
principal_admin_enable: handlePrincipalAdminEnable,
|
|
229
|
+
}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The agent principal's read path over WebSocket (docs/security/agent-principals.md
|
|
3
|
+
* sections 7.1 and 7.2; #9118, S3 of #9112): `principal_subscribe`,
|
|
4
|
+
* `principal_unsubscribe` and `principal_events_read`, and (#9119, S4) the pending-permission
|
|
5
|
+
* snapshot `principal_pending_permissions` (section 7.3) and (#9120, S5) the session roster
|
|
6
|
+
* snapshot `principal_sessions_snapshot`.
|
|
7
|
+
*
|
|
8
|
+
* All three are OBSERVE tier. Dispatch has already checked the type, the tier and the
|
|
9
|
+
* closed envelope (principal-policy.js); each handler then resolves EVERY session id
|
|
10
|
+
* through `principalMaySee(..., 'observe')` from the explicit ids in the message (never
|
|
11
|
+
* the active session) and refuses the whole request `scope_denied` when any one is not
|
|
12
|
+
* granted. A session that does not exist and a session that is not granted fail the same
|
|
13
|
+
* check with the same reply, so a principal cannot probe which ids exist, and a multi-id
|
|
14
|
+
* subscribe is all-or-nothing: nothing is subscribed unless every id is granted.
|
|
15
|
+
*
|
|
16
|
+
* A client that is not a principal has no use for these types (they exist for the
|
|
17
|
+
* `principal_*` family) and is refused without touching the journal.
|
|
18
|
+
*/
|
|
19
|
+
import { PRINCIPAL_ENVELOPES, isPrincipalClient, principalMaySee, principalPolicyOptsFromCtx, sendPrincipalRefusal } from '../principal-policy.js'
|
|
20
|
+
import { collectPendingPermissions } from '../principal-pending-permissions.js'
|
|
21
|
+
import { collectSessionsSnapshot } from '../principal-sessions-snapshot.js'
|
|
22
|
+
|
|
23
|
+
export const PRINCIPAL_READ_DEFAULT_LIMIT = 50
|
|
24
|
+
export const PRINCIPAL_READ_MAX_LIMIT = 200
|
|
25
|
+
|
|
26
|
+
// The protocol schemas' caps for a snapshot request (PrincipalPendingPermissionsSchema and
|
|
27
|
+
// PrincipalSessionsSnapshotSchema in @chroxy/protocol). The handler checks them itself because
|
|
28
|
+
// the Zod layer is not the only way in; tests/principal-handlers.test.js pins these equal to
|
|
29
|
+
// the schemas' own boundaries.
|
|
30
|
+
export const PRINCIPAL_SNAPSHOT_REQUEST_ID_MAX = 128
|
|
31
|
+
export const PRINCIPAL_SNAPSHOT_SESSION_IDS_MAX = 32
|
|
32
|
+
export const PRINCIPAL_SNAPSHOT_SESSION_ID_MAX = 128
|
|
33
|
+
|
|
34
|
+
/** Not a principal: the journal is for principals only. Reveals nothing about any session. */
|
|
35
|
+
function refuseNonPrincipal(ws, msg, ctx) {
|
|
36
|
+
ctx.transport.send(ws, {
|
|
37
|
+
type: 'session_error',
|
|
38
|
+
code: 'scope_denied',
|
|
39
|
+
message: 'Not permitted for this credential',
|
|
40
|
+
...(typeof msg?.type === 'string' && msg.type.length <= 128 ? { requestType: msg.type } : {}),
|
|
41
|
+
...(typeof msg?.requestId === 'string' && msg.requestId.length <= 128 ? { requestId: msg.requestId } : {}),
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Every id granted at observe tier, or false. Evaluated for ALL ids, in order. */
|
|
46
|
+
function allGranted(client, ids, ctx) {
|
|
47
|
+
if (!Array.isArray(ids) || ids.length === 0) return false
|
|
48
|
+
const opts = principalPolicyOptsFromCtx(ctx)
|
|
49
|
+
let ok = true
|
|
50
|
+
for (const id of ids) {
|
|
51
|
+
if (!principalMaySee(client, id, 'observe', opts).ok) ok = false
|
|
52
|
+
}
|
|
53
|
+
return ok
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function sessionIdList(value) {
|
|
57
|
+
if (!Array.isArray(value) || value.length === 0) return null
|
|
58
|
+
const out = []
|
|
59
|
+
for (const id of value) {
|
|
60
|
+
if (typeof id !== 'string' || id.length === 0 || out.includes(id)) return null
|
|
61
|
+
out.push(id)
|
|
62
|
+
}
|
|
63
|
+
return out
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function handlePrincipalSubscribe(ws, client, msg, ctx) {
|
|
67
|
+
if (!isPrincipalClient(client)) return refuseNonPrincipal(ws, msg, ctx)
|
|
68
|
+
const ids = sessionIdList(msg?.sessionIds)
|
|
69
|
+
if (ids === null || typeof msg.requestId !== 'string' || msg.requestId.length === 0) {
|
|
70
|
+
return sendPrincipalRefusal(ws, client, msg, ctx, 'envelope')
|
|
71
|
+
}
|
|
72
|
+
// ALL-OR-NOTHING: one id that is not granted (or not there) refuses the whole request.
|
|
73
|
+
if (!allGranted(client, ids, ctx)) return sendPrincipalRefusal(ws, client, msg, ctx, 'scope')
|
|
74
|
+
const cursors = new Map()
|
|
75
|
+
for (const c of Array.isArray(msg.cursors) ? msg.cursors : []) {
|
|
76
|
+
// A cursor names a session the request names; a second one for it, or one for another
|
|
77
|
+
// session, is a malformed request.
|
|
78
|
+
if (c === null || typeof c !== 'object' || !ids.includes(c.sessionId) || cursors.has(c.sessionId)) {
|
|
79
|
+
return sendPrincipalRefusal(ws, client, msg, ctx, 'envelope')
|
|
80
|
+
}
|
|
81
|
+
cursors.set(c.sessionId, c)
|
|
82
|
+
}
|
|
83
|
+
const subs = ctx.services?.principalSubscriptions
|
|
84
|
+
if (!subs) return sendPrincipalRefusal(ws, client, msg, ctx, 'not_available')
|
|
85
|
+
subs.subscribe({
|
|
86
|
+
ws, client, requestId: msg.requestId,
|
|
87
|
+
sessions: ids.map((sessionId) => ({ sessionId, cursor: cursors.get(sessionId) ?? null })),
|
|
88
|
+
})
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function handlePrincipalUnsubscribe(ws, client, msg, ctx) {
|
|
92
|
+
if (!isPrincipalClient(client)) return refuseNonPrincipal(ws, msg, ctx)
|
|
93
|
+
const subs = ctx.services?.principalSubscriptions
|
|
94
|
+
if (!subs) return
|
|
95
|
+
// Only the caller's own subscriptions can be named, so no grant check is needed and none
|
|
96
|
+
// can leak: an id that is not subscribed is simply a no-op.
|
|
97
|
+
let ids = null
|
|
98
|
+
if (msg?.sessionIds !== undefined) {
|
|
99
|
+
ids = Array.isArray(msg.sessionIds) ? msg.sessionIds.filter((id) => typeof id === 'string') : null
|
|
100
|
+
if (ids === null) return sendPrincipalRefusal(ws, client, msg, ctx, 'envelope')
|
|
101
|
+
}
|
|
102
|
+
subs.unsubscribe(client, ids)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function handlePrincipalEventsRead(ws, client, msg, ctx) {
|
|
106
|
+
if (!isPrincipalClient(client)) return refuseNonPrincipal(ws, msg, ctx)
|
|
107
|
+
if (typeof msg?.sessionId !== 'string' || typeof msg.requestId !== 'string' || msg.requestId.length === 0) {
|
|
108
|
+
return sendPrincipalRefusal(ws, client, msg, ctx, 'envelope')
|
|
109
|
+
}
|
|
110
|
+
if (!allGranted(client, [msg.sessionId], ctx)) return sendPrincipalRefusal(ws, client, msg, ctx, 'scope')
|
|
111
|
+
const journal = ctx.services?.principalJournal
|
|
112
|
+
if (!journal) return sendPrincipalRefusal(ws, client, msg, ctx, 'not_available')
|
|
113
|
+
const requested = Number.isSafeInteger(msg.limit) ? msg.limit : PRINCIPAL_READ_DEFAULT_LIMIT
|
|
114
|
+
const limit = Math.min(Math.max(1, requested), PRINCIPAL_READ_MAX_LIMIT)
|
|
115
|
+
const resolved = journal.resolveCursor(msg.sessionId, msg.cursor ?? null)
|
|
116
|
+
const read = journal.readFrom(msg.sessionId, resolved.afterSeq, limit)
|
|
117
|
+
// The first unavailable range after the cursor is the gap the cursor itself ran into; a
|
|
118
|
+
// range met while reading on from there is the read's own.
|
|
119
|
+
const gap = resolved.gap && read.gap
|
|
120
|
+
? { reason: resolved.gap.reason, fromSeq: resolved.gap.fromSeq, toSeq: read.gap.toSeq }
|
|
121
|
+
: (resolved.gap ?? read.gap)
|
|
122
|
+
ctx.transport.send(ws, {
|
|
123
|
+
type: 'principal_events_page',
|
|
124
|
+
requestId: msg.requestId,
|
|
125
|
+
sessionId: msg.sessionId,
|
|
126
|
+
journalId: resolved.journalId,
|
|
127
|
+
events: read.events.map((e) => ({
|
|
128
|
+
seq: e.seq, ts: e.ts, eventType: e.type, data: e.data, ...(e.truncated === true ? { truncated: true } : {}),
|
|
129
|
+
})),
|
|
130
|
+
headSeq: read.headSeq,
|
|
131
|
+
cursor: { sessionId: msg.sessionId, journalId: resolved.journalId, seq: read.lastSeq },
|
|
132
|
+
more: read.lastSeq < read.headSeq,
|
|
133
|
+
...(gap ? { gap } : {}),
|
|
134
|
+
})
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* `principal_pending_permissions`: a snapshot of what is waiting for a decision on the
|
|
139
|
+
* principal's granted sessions, read from the canonical state of both permission pipelines
|
|
140
|
+
* (principal-pending-permissions.js). OBSERVE tier and READ ONLY: seeing a request is not
|
|
141
|
+
* being able to answer it, and nothing here touches a pending request.
|
|
142
|
+
*
|
|
143
|
+
* With `sessionIds`, EVERY id goes through `principalMaySee(..., 'observe')` and one that is
|
|
144
|
+
* not granted (or not there) refuses the whole request `scope_denied`, replying exactly as
|
|
145
|
+
* for a session that does not exist. Without it, the reply covers the sessions the principal
|
|
146
|
+
* may see, which is a filter, not a refusal: an empty grant gets an empty snapshot.
|
|
147
|
+
*/
|
|
148
|
+
function handlePrincipalPendingPermissions(ws, client, msg, ctx) {
|
|
149
|
+
if (!isPrincipalClient(client)) return refuseNonPrincipal(ws, msg, ctx)
|
|
150
|
+
const ids = resolveSnapshotSessionIds(ws, client, msg, ctx)
|
|
151
|
+
if (ids === null) return
|
|
152
|
+
const snapshot = collectPendingPermissions({
|
|
153
|
+
sessionIds: ids,
|
|
154
|
+
sessionManager: ctx.sessions?.sessionManager ?? null,
|
|
155
|
+
pendingPermissions: ctx.permissions?.pendingPermissions,
|
|
156
|
+
permissionSessionMap: ctx.permissions?.permissionSessionMap,
|
|
157
|
+
})
|
|
158
|
+
ctx.transport.send(ws, {
|
|
159
|
+
type: 'principal_pending_permissions_result',
|
|
160
|
+
requestId: msg.requestId,
|
|
161
|
+
generatedAt: snapshot.generatedAt,
|
|
162
|
+
permissions: snapshot.permissions,
|
|
163
|
+
truncated: snapshot.truncated,
|
|
164
|
+
})
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Is this request inside its type's closed envelope (principal-policy.js's table) with a
|
|
169
|
+
* well-formed `requestId` and `sessionIds`? Independent of dispatch and of the Zod layer.
|
|
170
|
+
*/
|
|
171
|
+
function snapshotEnvelopeOk(msg) {
|
|
172
|
+
const envelope = typeof msg?.type === 'string' && Object.hasOwn(PRINCIPAL_ENVELOPES, msg.type) ? PRINCIPAL_ENVELOPES[msg.type] : null
|
|
173
|
+
if (envelope === null || msg === null || typeof msg !== 'object' || Array.isArray(msg)) return false
|
|
174
|
+
for (const key of Object.keys(msg)) {
|
|
175
|
+
if (!envelope.fields.includes(key)) return false
|
|
176
|
+
}
|
|
177
|
+
if (typeof msg.requestId !== 'string' || msg.requestId.length === 0 || msg.requestId.length > PRINCIPAL_SNAPSHOT_REQUEST_ID_MAX) return false
|
|
178
|
+
if (msg.sessionIds !== undefined) {
|
|
179
|
+
const ids = msg.sessionIds
|
|
180
|
+
if (!Array.isArray(ids) || ids.length === 0 || ids.length > PRINCIPAL_SNAPSHOT_SESSION_IDS_MAX) return false
|
|
181
|
+
if (!ids.every((id) => typeof id === 'string' && id.length > 0 && id.length <= PRINCIPAL_SNAPSHOT_SESSION_ID_MAX)) return false
|
|
182
|
+
}
|
|
183
|
+
return true
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* The session ids a snapshot request covers, or null after the request was refused. With
|
|
188
|
+
* `sessionIds`, EVERY id goes through `principalMaySee(..., 'observe')` and one that is not
|
|
189
|
+
* granted (or not there) refuses the whole request `scope_denied`, replying exactly as for a
|
|
190
|
+
* session that does not exist. Without it, the ids are the sessions the principal may see,
|
|
191
|
+
* which is a filter, not a refusal: an empty grant gets an empty snapshot.
|
|
192
|
+
*/
|
|
193
|
+
function resolveSnapshotSessionIds(ws, client, msg, ctx) {
|
|
194
|
+
// Contract 4.1.1: the closed envelope holds at the handler as well as at dispatch, so a
|
|
195
|
+
// handler reached any other way refuses the same way (the same refusal, byte for byte).
|
|
196
|
+
if (!snapshotEnvelopeOk(msg)) {
|
|
197
|
+
sendPrincipalRefusal(ws, client, msg, ctx, 'envelope')
|
|
198
|
+
return null
|
|
199
|
+
}
|
|
200
|
+
if (msg.sessionIds !== undefined) {
|
|
201
|
+
const ids = sessionIdList(msg.sessionIds)
|
|
202
|
+
// The envelope check passed, so only a DUPLICATE id can still make the list null.
|
|
203
|
+
if (ids === null) { sendPrincipalRefusal(ws, client, msg, ctx, 'envelope'); return null }
|
|
204
|
+
// ALL-OR-NOTHING, evaluated for every id (no early exit that would time differently).
|
|
205
|
+
if (!allGranted(client, ids, ctx)) { sendPrincipalRefusal(ws, client, msg, ctx, 'scope'); return null }
|
|
206
|
+
return ids
|
|
207
|
+
}
|
|
208
|
+
const opts = principalPolicyOptsFromCtx(ctx)
|
|
209
|
+
// Ids only: the full listing runs provider getters for EVERY session, so one the principal
|
|
210
|
+
// is not granted could change this reply.
|
|
211
|
+
const listed = ctx.sessions?.sessionManager?.listSessionIds?.() ?? []
|
|
212
|
+
const ids = []
|
|
213
|
+
for (const id of Array.isArray(listed) ? listed : []) {
|
|
214
|
+
if (typeof id === 'string' && !ids.includes(id) && principalMaySee(client, id, 'observe', opts).ok) ids.push(id)
|
|
215
|
+
}
|
|
216
|
+
return ids
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Does the prompt evaluator hold a draft for this session? The WS layer's answer, which
|
|
221
|
+
* `SessionManager.getHandoffBlockers` cannot see and asks its caller for: input-handlers
|
|
222
|
+
* takes the per-session lock `runtime.pendingEvaluatorAwaits` before it awaits the skip
|
|
223
|
+
* decision and holds it until the evaluator settles (released in a `finally`). When the map
|
|
224
|
+
* is not there the answer is UNKNOWN, and unknown reads as pending: a blocker that is not
|
|
225
|
+
* real is safe, a missing one is not.
|
|
226
|
+
*/
|
|
227
|
+
function evaluatorPendingFor(ctx) {
|
|
228
|
+
const awaits = ctx.runtime?.pendingEvaluatorAwaits
|
|
229
|
+
return awaits instanceof Map ? (id) => awaits.has(id) : () => true
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* `principal_sessions_snapshot`: a roster of the principal's granted sessions with observed
|
|
234
|
+
* and declared status, handoff blockers and the model requested and observed
|
|
235
|
+
* (principal-sessions-snapshot.js; section 7.3). OBSERVE tier and READ ONLY. Same id rules as
|
|
236
|
+
* `principal_pending_permissions`.
|
|
237
|
+
*/
|
|
238
|
+
function handlePrincipalSessionsSnapshot(ws, client, msg, ctx) {
|
|
239
|
+
if (!isPrincipalClient(client)) return refuseNonPrincipal(ws, msg, ctx)
|
|
240
|
+
const ids = resolveSnapshotSessionIds(ws, client, msg, ctx)
|
|
241
|
+
if (ids === null) return
|
|
242
|
+
const snapshot = collectSessionsSnapshot({
|
|
243
|
+
sessionIds: ids,
|
|
244
|
+
sessionManager: ctx.sessions?.sessionManager ?? null,
|
|
245
|
+
evaluatorPending: evaluatorPendingFor(ctx),
|
|
246
|
+
})
|
|
247
|
+
ctx.transport.send(ws, {
|
|
248
|
+
type: 'principal_sessions_snapshot_result',
|
|
249
|
+
requestId: msg.requestId,
|
|
250
|
+
generatedAt: snapshot.generatedAt,
|
|
251
|
+
sessions: snapshot.sessions,
|
|
252
|
+
truncated: snapshot.truncated,
|
|
253
|
+
})
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export const principalHandlers = {
|
|
257
|
+
principal_pending_permissions: handlePrincipalPendingPermissions,
|
|
258
|
+
principal_sessions_snapshot: handlePrincipalSessionsSnapshot,
|
|
259
|
+
principal_subscribe: handlePrincipalSubscribe,
|
|
260
|
+
principal_unsubscribe: handlePrincipalUnsubscribe,
|
|
261
|
+
principal_events_read: handlePrincipalEventsRead,
|
|
262
|
+
}
|
|
@@ -60,6 +60,17 @@ const log = createLogger('ws')
|
|
|
60
60
|
/** Actions that only need a taskId (no `task` payload). */
|
|
61
61
|
const ID_ONLY_ACTIONS = new Set(['pause', 'resume', 'delete'])
|
|
62
62
|
|
|
63
|
+
// Wire caps for the snapshot's #7079 unreadable surface and the adjacent fields
|
|
64
|
+
// the snapshot audit bounded. Mirror SCHEDULED_TASK_UNREADABLE_* / SCHEDULABLE_PROVIDERS_MAX
|
|
65
|
+
// in @chroxy/protocol (schemas/server/scheduler.ts); the handler tests safeParse
|
|
66
|
+
// the REAL schema at each boundary, so a drift fails a test instead of bricking
|
|
67
|
+
// the dashboard's whole-snapshot parse.
|
|
68
|
+
const UNREADABLE_MAX_ENTRIES = 100
|
|
69
|
+
const UNREADABLE_REASON_MAX = 512
|
|
70
|
+
const SCHEDULABLE_PROVIDERS_MAX = 256
|
|
71
|
+
const SNAPSHOT_ERROR_CODE_MAX = 128
|
|
72
|
+
const SNAPSHOT_ERROR_MESSAGE_MAX = 2048
|
|
73
|
+
|
|
63
74
|
/**
|
|
64
75
|
* Send a scheduled-task failure envelope.
|
|
65
76
|
*
|
|
@@ -238,7 +249,7 @@ function projectLastRun(lastRun) {
|
|
|
238
249
|
* registry, and the panel now surfaces that as a readable snapshot error rather
|
|
239
250
|
* than hanging.
|
|
240
251
|
*/
|
|
241
|
-
function projectTask(task, ctx, quarantinedIds) {
|
|
252
|
+
function projectTask(task, ctx, quarantinedIds, daemonDefault) {
|
|
242
253
|
const provider = effectiveProvider(task, ctx)
|
|
243
254
|
const requestedMode = task?.target?.permissionMode
|
|
244
255
|
const effectiveMode = resolveScheduledPermissionMode(requestedMode)
|
|
@@ -253,7 +264,7 @@ function projectTask(task, ctx, quarantinedIds) {
|
|
|
253
264
|
lastRun: projectLastRun(task.lastRun),
|
|
254
265
|
createdAt: Number.isFinite(task.createdAt) ? task.createdAt : 0,
|
|
255
266
|
updatedAt: Number.isFinite(task.updatedAt) ? task.updatedAt : 0,
|
|
256
|
-
providerRefusal: clampWire(scheduledProviderRefusalReason(provider), 2048),
|
|
267
|
+
providerRefusal: clampWire(scheduledProviderRefusalReason(provider, undefined, daemonDefault), 2048),
|
|
257
268
|
effectiveProvider: clampWire(provider, 128),
|
|
258
269
|
effectivePermissionMode: clampWire(effectiveMode, 64),
|
|
259
270
|
// True only when the task ASKED for something and got clamped — an absent
|
|
@@ -292,7 +303,7 @@ function buildSnapshot(ctx, requestId, { error = null } = {}) {
|
|
|
292
303
|
let tasks = []
|
|
293
304
|
if (store && !error) {
|
|
294
305
|
try {
|
|
295
|
-
tasks = store.list().map((t) => projectTask(t, ctx, quarantinedIds))
|
|
306
|
+
tasks = store.list().map((t) => projectTask(t, ctx, quarantinedIds, effectiveProvider(null, ctx)))
|
|
296
307
|
} catch (err) {
|
|
297
308
|
// Degrade to a structurally valid empty snapshot + error, the same posture
|
|
298
309
|
// the Control Room surveys use — never a dead/unparseable reply.
|
|
@@ -302,6 +313,22 @@ function buildSnapshot(ctx, requestId, { error = null } = {}) {
|
|
|
302
313
|
})
|
|
303
314
|
}
|
|
304
315
|
}
|
|
316
|
+
// #7079: the load-refused stored entries. Only `{ handle, reason }` travel —
|
|
317
|
+
// never the raw entry (any shape, may be huge) and never its id (may be absent
|
|
318
|
+
// or over the id cap, which is why the handle exists). The list is bounded;
|
|
319
|
+
// `unreadableCount` is the true total so the panel can say "and N more".
|
|
320
|
+
let unreadableCount = 0
|
|
321
|
+
let unreadable = []
|
|
322
|
+
if (store && !error) {
|
|
323
|
+
try {
|
|
324
|
+
unreadableCount = store.unreadableCount()
|
|
325
|
+
unreadable = store.listUnreadable()
|
|
326
|
+
.slice(0, UNREADABLE_MAX_ENTRIES)
|
|
327
|
+
.map(({ handle, reason }) => ({ handle, reason: clampWire(reason, UNREADABLE_REASON_MAX) }))
|
|
328
|
+
} catch (err) {
|
|
329
|
+
log.warn(`Failed to list unreadable scheduled tasks: ${getErrorMessage(err)}`)
|
|
330
|
+
}
|
|
331
|
+
}
|
|
305
332
|
const defaultProvider = effectiveProvider(null, ctx)
|
|
306
333
|
return {
|
|
307
334
|
type: 'scheduled_tasks',
|
|
@@ -313,11 +340,20 @@ function buildSnapshot(ctx, requestId, { error = null } = {}) {
|
|
|
313
340
|
restartRequired: enabled !== engineArmed,
|
|
314
341
|
source: gateSource(ctx),
|
|
315
342
|
},
|
|
316
|
-
schedulableProviders: listSchedulableProviders(),
|
|
343
|
+
schedulableProviders: listSchedulableProviders().slice(0, SCHEDULABLE_PROVIDERS_MAX),
|
|
317
344
|
defaultProvider,
|
|
318
|
-
defaultProviderRefusal: scheduledProviderRefusalReason(defaultProvider),
|
|
345
|
+
defaultProviderRefusal: scheduledProviderRefusalReason(defaultProvider, undefined, defaultProvider),
|
|
319
346
|
tasks,
|
|
320
|
-
|
|
347
|
+
unreadableCount,
|
|
348
|
+
unreadable,
|
|
349
|
+
...(error
|
|
350
|
+
? {
|
|
351
|
+
error: {
|
|
352
|
+
code: clampWire(String(error.code), SNAPSHOT_ERROR_CODE_MAX),
|
|
353
|
+
message: clampWire(String(error.message), SNAPSHOT_ERROR_MESSAGE_MAX),
|
|
354
|
+
},
|
|
355
|
+
}
|
|
356
|
+
: {}),
|
|
321
357
|
}
|
|
322
358
|
}
|
|
323
359
|
|
|
@@ -346,7 +382,8 @@ function handleScheduledTasksRequest(ws, client, msg, ctx) {
|
|
|
346
382
|
}
|
|
347
383
|
|
|
348
384
|
/**
|
|
349
|
-
* Create / update / pause / resume / delete a scheduled task
|
|
385
|
+
* Create / update / pause / resume / delete a scheduled task, or discard a
|
|
386
|
+
* load-refused stored entry (`discard_unreadable`, #7079).
|
|
350
387
|
*
|
|
351
388
|
* STRICT-PRIMARY gated (first statement, before any validation or store touch).
|
|
352
389
|
* On success the reply is the re-emitted snapshot echoing `requestId` — that IS
|
|
@@ -373,6 +410,53 @@ function handleScheduledTaskAction(ws, client, msg, ctx) {
|
|
|
373
410
|
return
|
|
374
411
|
}
|
|
375
412
|
|
|
413
|
+
// The registry changed — let a running engine re-evaluate immediately instead
|
|
414
|
+
// of waiting out its max-sleep tick. Best-effort: a refresh failure must not
|
|
415
|
+
// turn an applied mutation into a reported failure.
|
|
416
|
+
const refreshEngineAndReply = () => {
|
|
417
|
+
const engine = ctx?.services?.schedulerEngine ?? null
|
|
418
|
+
try {
|
|
419
|
+
engine?.refresh?.()
|
|
420
|
+
} catch (err) {
|
|
421
|
+
log.warn(`Scheduler refresh after ${action} failed: ${getErrorMessage(err)}`)
|
|
422
|
+
}
|
|
423
|
+
replySnapshot(ws, ctx, requestId)
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// #7079: `discard_unreadable` is addressed by an opaque handle the SERVER derived,
|
|
427
|
+
// never by a task id — a stored entry's own id may be absent or over the wire
|
|
428
|
+
// cap, and a taskId here must never be able to name a live task.
|
|
429
|
+
if (action === 'discard_unreadable') {
|
|
430
|
+
const handle = typeof msg?.handle === 'string' ? msg.handle : ''
|
|
431
|
+
if (!handle) {
|
|
432
|
+
fail("scheduled_task_action 'discard_unreadable' requires a handle")
|
|
433
|
+
return
|
|
434
|
+
}
|
|
435
|
+
try {
|
|
436
|
+
// Authorisation is the same strict-primary gate as `delete` (checked above).
|
|
437
|
+
if (!store.discardUnreadable(handle)) {
|
|
438
|
+
fail(
|
|
439
|
+
'No unreadable scheduled-task entry matches that handle — it may already have been discarded, or the registry file was edited. Refresh to see the current list.',
|
|
440
|
+
'SCHEDULED_TASK_NOT_FOUND',
|
|
441
|
+
)
|
|
442
|
+
// The row that sent this handle is stale, and a refusal alone leaves it on
|
|
443
|
+
// screen as a dead end. Follow with the current snapshot (the store has
|
|
444
|
+
// already refreshed itself). `requestId: null` on purpose: a snapshot that
|
|
445
|
+
// echoed it would be read as the ACK and mask the refusal.
|
|
446
|
+
replySnapshot(ws, ctx, null)
|
|
447
|
+
return
|
|
448
|
+
}
|
|
449
|
+
// The handle is a hash, safe to log; the entry's contents never are.
|
|
450
|
+
log.info(`Unreadable scheduled-task entry discarded: ${handle}`)
|
|
451
|
+
} catch (err) {
|
|
452
|
+
log.error(`scheduled_task_action 'discard_unreadable' failed: ${getErrorMessage(err)}`)
|
|
453
|
+
fail(getErrorMessage(err))
|
|
454
|
+
return
|
|
455
|
+
}
|
|
456
|
+
refreshEngineAndReply()
|
|
457
|
+
return
|
|
458
|
+
}
|
|
459
|
+
|
|
376
460
|
const taskId = typeof msg?.taskId === 'string' ? msg.taskId.trim() : ''
|
|
377
461
|
if ((ID_ONLY_ACTIONS.has(action) || action === 'update') && !taskId) {
|
|
378
462
|
fail(`scheduled_task_action '${action}' requires a taskId`)
|
|
@@ -436,17 +520,7 @@ function handleScheduledTaskAction(ws, client, msg, ctx) {
|
|
|
436
520
|
return
|
|
437
521
|
}
|
|
438
522
|
|
|
439
|
-
|
|
440
|
-
// of waiting out its max-sleep tick. Best-effort: a refresh failure must not
|
|
441
|
-
// turn an applied mutation into a reported failure.
|
|
442
|
-
const engine = ctx?.services?.schedulerEngine ?? null
|
|
443
|
-
try {
|
|
444
|
-
engine?.refresh?.()
|
|
445
|
-
} catch (err) {
|
|
446
|
-
log.warn(`Scheduler refresh after ${action} failed: ${getErrorMessage(err)}`)
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
replySnapshot(ws, ctx, requestId)
|
|
523
|
+
refreshEngineAndReply()
|
|
450
524
|
}
|
|
451
525
|
|
|
452
526
|
/**
|