@sleep2agi/commhub-server 0.9.0-preview.22 → 0.9.0-preview.221
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/README.md +129 -9
- package/bin/commhub.ts +93 -9
- package/package.json +7 -7
- package/src/ack-create-request-transport.test.ts +182 -0
- package/src/ack-create-request.test.ts +50 -7
- package/src/admin-delete-network-http.test.ts +228 -0
- package/src/admin-networks-http.test.ts +88 -0
- package/src/adoption-candidates-http.test.ts +137 -0
- package/src/adoption-candidates.ts +158 -0
- package/src/agent-access-batch.test.ts +210 -0
- package/src/agent-access.ts +487 -0
- package/src/agent-acl-groups-http.test.ts +247 -0
- package/src/agent-acl-http.test.ts +659 -0
- package/src/agent-acl-slice3-http.test.ts +654 -0
- package/src/agent-department-http.test.ts +215 -0
- package/src/agent-groups-perf.test.ts +223 -0
- package/src/agent-notice.ts +48 -0
- package/src/agent-team-whoami-http.test.ts +98 -0
- package/src/agent-teams-http.test.ts +330 -0
- package/src/agent-teams.ts +244 -0
- package/src/alias-baseline-2571.test.ts +162 -0
- package/src/alias-baseline.ts +113 -0
- package/src/alias-filter.test.ts +72 -0
- package/src/alias-filter.ts +42 -0
- package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
- package/src/api-host-supervisors-fallback.test.ts +6 -7
- package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
- package/src/api-nodes-shape.test.ts +120 -13
- package/src/auth-password-change-cli-tokens-http.test.ts +423 -0
- package/src/auth-sessions-http.test.ts +250 -0
- package/src/auth-validate.test.ts +5 -1
- package/src/auth-weak-password-login.test.ts +176 -0
- package/src/auth.ts +609 -51
- package/src/avatar-validate.test.ts +52 -2
- package/src/avatar-validate.ts +35 -1
- package/src/backfill-node-ids-2664.test.ts +128 -0
- package/src/binding-generation-http.test.ts +121 -0
- package/src/blocked-exit-on-reply.test.ts +122 -0
- package/src/broadcast-fanout-2721.test.ts +149 -0
- package/src/broadcast-fanout.ts +117 -0
- package/src/chain-attempt-dedup.test.ts +447 -0
- package/src/clone-node.test.ts +248 -0
- package/src/clone-node.ts +289 -0
- package/src/codex-config-flags.ts +77 -0
- package/src/codex-fork-contract.ts +23 -0
- package/src/codex-fork-migration.test.ts +38 -0
- package/src/commhub-bin-args.test.ts +85 -0
- package/src/config-apply-validate.test.ts +188 -1
- package/src/config-apply-validate.ts +222 -3
- package/src/cors-origins.test.ts +56 -0
- package/src/create-node-blocked-gate.test.ts +356 -0
- package/src/create-node-network-id.test.ts +91 -0
- package/src/create-node-tool-schema.test.ts +49 -0
- package/src/create-node-unicode-name.test.ts +120 -0
- package/src/create-node-validate.test.ts +199 -7
- package/src/create-node-validate.ts +232 -15
- package/src/create-node-workdir.test.ts +289 -0
- package/src/create-node.ts +88 -23
- package/src/daemon-provider-snapshots.test.ts +421 -0
- package/src/daemon-provider-snapshots.ts +327 -0
- package/src/daemon-token-owner-http.test.ts +236 -0
- package/src/dashboard-slash-routing-http.test.ts +109 -0
- package/src/db-adapter-guard.test.ts +148 -0
- package/src/db-adapter-translate.test.ts +128 -0
- package/src/db-adapter.ts +377 -91
- package/src/db-timestamp.test.ts +38 -0
- package/src/db-timestamp.ts +15 -0
- package/src/db.ts +1296 -153
- package/src/delivered-without-push.test.ts +140 -0
- package/src/department-groups-http.test.ts +209 -0
- package/src/department-groups-sync-http.test.ts +328 -0
- package/src/department-groups.ts +434 -0
- package/src/department-heads-http.test.ts +350 -0
- package/src/department-heads.ts +226 -0
- package/src/departments-agent-count.test.ts +132 -0
- package/src/departments-http.test.ts +185 -0
- package/src/departments-mcp.test.ts +128 -0
- package/src/departments.ts +318 -0
- package/src/desktop-message-seam.test.ts +150 -0
- package/src/desktop-message.test.ts +368 -0
- package/src/dm-file-scope-http.test.ts +178 -0
- package/src/empty-node-sweeper.test.ts +104 -0
- package/src/empty-node-sweeper.ts +88 -0
- package/src/env-transport-gate-http.test.ts +240 -0
- package/src/env-transport-gate.ts +80 -0
- package/src/env-transport-policy.ts +56 -0
- package/src/etag-of.test.ts +57 -0
- package/src/event-loop-lag.test.ts +180 -0
- package/src/event-loop-lag.ts +201 -0
- package/src/ext-token-shared.test.ts +60 -0
- package/src/ext-validation-regression.test.ts +131 -0
- package/src/external-schedule-edits-http.test.ts +321 -0
- package/src/external-schedule-edits-timestamps.test.ts +64 -0
- package/src/external-schedule-edits.ts +327 -0
- package/src/file-download-authz-dev-open.test.ts +135 -0
- package/src/file-download-authz.test.ts +404 -0
- package/src/file-download-date-bucket.test.ts +436 -0
- package/src/file-network-scope-dev-open.test.ts +97 -0
- package/src/file-network-scope.test.ts +732 -0
- package/src/group-membership-events-http.test.ts +264 -0
- package/src/group-messages-http.test.ts +482 -0
- package/src/group-messages.ts +297 -0
- package/src/health-anon-readers.ts +59 -0
- package/src/health-host-disk-2756.test.ts +71 -0
- package/src/health-redaction.test.ts +1583 -2
- package/src/host-supervisor-identity-http.test.ts +152 -0
- package/src/host-supervisor-identity.ts +92 -0
- package/src/host-supervisors-daemon-version.test.ts +137 -0
- package/src/http-gzip.test.ts +94 -0
- package/src/http-gzip.ts +112 -0
- package/src/hub-catalog-read-http.test.ts +266 -0
- package/src/hub-provider-config.test.ts +156 -0
- package/src/hub-provider-config.ts +124 -0
- package/src/hub-timestamp.test.ts +38 -0
- package/src/hub-timestamp.ts +27 -0
- package/src/human-dm.ts +215 -0
- package/src/human-inbox.ts +42 -0
- package/src/inbox-caller.ts +49 -0
- package/src/inbox-count-sse.test.ts +310 -0
- package/src/inbox-count.ts +29 -0
- package/src/index.ts +6 -2
- package/src/license-state.test.ts +56 -0
- package/src/license-state.ts +48 -0
- package/src/list-host-supervisors.test.ts +15 -4
- package/src/mcp-context-cost-http.test.ts +127 -0
- package/src/mcp-inflight.test.ts +92 -0
- package/src/mcp-inflight.ts +38 -0
- package/src/mcp-projects-events-http.test.ts +165 -0
- package/src/mcp-route-label-http.test.ts +120 -0
- package/src/mcp-write-network-resolution.test.ts +435 -0
- package/src/member-audit-network-id-http.test.ts +93 -0
- package/src/member-presence-http.test.ts +210 -0
- package/src/messages-ack-by-agent-http.test.ts +142 -0
- package/src/migrate-sqlite-to-pg.test.ts +47 -0
- package/src/migrate-sqlite-to-pg.ts +263 -0
- package/src/model-auth-notify-http.test.ts +181 -0
- package/src/model-auth-notify.ts +116 -0
- package/src/network-name-http.test.ts +75 -0
- package/src/network-rules-http.test.ts +169 -0
- package/src/network-rules.ts +129 -0
- package/src/network-scope.ts +276 -0
- package/src/network-token-membership-http.test.ts +139 -0
- package/src/node-alias-control.ts +12 -0
- package/src/node-attrs-validate.ts +88 -0
- package/src/node-attrs.test.ts +258 -0
- package/src/node-caller-identity-http.test.ts +1091 -0
- package/src/node-create-request-status-http.test.ts +105 -0
- package/src/node-daemon-bindings.test.ts +132 -0
- package/src/node-daemon-bindings.ts +135 -0
- package/src/node-failure-alert.test.ts +150 -0
- package/src/node-failure-alert.ts +177 -0
- package/src/node-files-transport.test.ts +344 -0
- package/src/node-health-codex-login.test.ts +120 -0
- package/src/node-health-dispatch-http.test.ts +335 -0
- package/src/node-health-guard.ts +121 -0
- package/src/node-health-passthrough.test.ts +115 -0
- package/src/node-health-store.ts +101 -0
- package/src/node-id-alias.test.ts +190 -0
- package/src/node-identity-conflict-http.test.ts +269 -0
- package/src/node-identity-conflict.ts +142 -0
- package/src/node-identity-mismatch.test.ts +74 -0
- package/src/node-in-flight-tasks.ts +31 -0
- package/src/node-lifecycle-controllable.test.ts +64 -0
- package/src/node-lifecycle-controllable.ts +53 -0
- package/src/node-lifecycle-read-http.test.ts +250 -0
- package/src/node-lifecycle-read.ts +124 -0
- package/src/node-logs-transport.test.ts +263 -0
- package/src/node-peer-allowlist.test.ts +114 -0
- package/src/node-permissions-http.test.ts +728 -0
- package/src/node-permissions.ts +494 -0
- package/src/node-request-retention.test.ts +281 -0
- package/src/node-request-retention.ts +120 -0
- package/src/node-secret-rest-http.test.ts +190 -0
- package/src/node-serviceability.test.ts +86 -0
- package/src/node-serviceability.ts +124 -0
- package/src/node-session-control-http.test.ts +310 -0
- package/src/node-session-control.ts +258 -0
- package/src/node-skills-transport.test.ts +212 -0
- package/src/node-token-identity.ts +35 -0
- package/src/node-token-ownership.ts +51 -0
- package/src/node-token-privilege-http.test.ts +158 -0
- package/src/not-found-api-http.test.ts +67 -0
- package/src/observer-avatar-http.test.ts +102 -9
- package/src/observer-push.test.ts +76 -0
- package/src/opencode-catalog-report-http.test.ts +139 -0
- package/src/opencode-v2-catalog.test.ts +268 -0
- package/src/opencode-v2-catalog.ts +356 -0
- package/src/package-version-consistency.test.ts +25 -0
- package/src/parent-source-marker.test.ts +50 -0
- package/src/password-network-tokens.ts +25 -0
- package/src/peer-reply-atomic.test.ts +457 -0
- package/src/peer-reply-capability.test.ts +70 -0
- package/src/pg-worker.ts +87 -0
- package/src/poll-pacing.test.ts +74 -0
- package/src/poll-pacing.ts +123 -0
- package/src/project-dir-warn-clear-http.test.ts +132 -0
- package/src/project-viewer-can-http.test.ts +116 -0
- package/src/push.test.ts +20 -10
- package/src/push.ts +382 -9
- package/src/redact-tokens.test.ts +86 -0
- package/src/redact-tokens.ts +43 -0
- package/src/rejection-counters.test.ts +72 -0
- package/src/rejection-counters.ts +173 -0
- package/src/rename.ts +38 -10
- package/src/reply-target-derivation.test.ts +96 -0
- package/src/report-status-handover-capabilities-http.test.ts +124 -0
- package/src/report-status-host-schema.test.ts +235 -0
- package/src/report-status-resume-id-handover.test.ts +184 -0
- package/src/report-status-secret-keys.test.ts +140 -0
- package/src/require-explicit-test-db.ts +9 -0
- package/src/requirement-due-reminders-http.test.ts +620 -0
- package/src/requirement-due-reminders.ts +416 -0
- package/src/requirement-events-http.test.ts +295 -0
- package/src/requirement-events.test.ts +45 -0
- package/src/requirement-events.ts +144 -0
- package/src/requirement-notify.ts +165 -0
- package/src/requirement-participant-notify-http.test.ts +309 -0
- package/src/requirement-tag-ops-http.test.ts +425 -0
- package/src/requirement-tag-tree-http.test.ts +275 -0
- package/src/requirement-tag-tree.ts +127 -0
- package/src/requirement-tags.ts +102 -0
- package/src/requirements-abandoned-http.test.ts +236 -0
- package/src/requirements-comment-http.test.ts +167 -0
- package/src/requirements-completed-at-migration.test.ts +70 -0
- package/src/requirements-errors-mcp-http.test.ts +164 -0
- package/src/requirements-errors.ts +158 -0
- package/src/requirements-etag-http.test.ts +91 -0
- package/src/requirements-http.test.ts +709 -0
- package/src/requirements-last-event-http.test.ts +349 -0
- package/src/requirements-list-mcp-slim-http.test.ts +155 -0
- package/src/requirements-list-slim-http.test.ts +324 -0
- package/src/requirements-mcp.test.ts +163 -0
- package/src/requirements-migrate.ts +283 -0
- package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
- package/src/requirements-people-http.test.ts +114 -0
- package/src/requirements-people-mcp-http.test.ts +231 -0
- package/src/requirements-people.ts +196 -0
- package/src/requirements-priority-lowest.test.ts +114 -0
- package/src/requirements-projects-network-echo.test.ts +57 -0
- package/src/requirements-projects-parent-http.test.ts +123 -0
- package/src/requirements-search-http.test.ts +182 -0
- package/src/requirements-search.test.ts +32 -0
- package/src/requirements-search.ts +145 -0
- package/src/requirements-seq-http.test.ts +193 -0
- package/src/requirements-seq-migration.test.ts +63 -0
- package/src/requirements-start-date.test.ts +125 -0
- package/src/requirements-stats-http.test.ts +357 -0
- package/src/requirements-stats.ts +195 -0
- package/src/requirements-status-participants-http.test.ts +222 -0
- package/src/requirements-upgrade-e2e.test.ts +126 -0
- package/src/requirements-upgrade-migration.test.ts +98 -0
- package/src/requirements.ts +2057 -0
- package/src/resolve-port.test.ts +57 -0
- package/src/resolve-port.ts +44 -0
- package/src/rest-alias-network-fallback-http.test.ts +123 -0
- package/src/rest-alias-network-fallback.test.ts +60 -0
- package/src/rest-alias-network-fallback.ts +65 -0
- package/src/rest-explicit-columns-http.test.ts +266 -0
- package/src/rest-identity.test.ts +130 -0
- package/src/rest-identity.ts +141 -0
- package/src/rest-projections.ts +72 -0
- package/src/rest-read-network-real-chain.test.ts +97 -0
- package/src/rest-write-network-resolution.test.ts +133 -0
- package/src/restart-readiness-http.test.ts +121 -0
- package/src/restricted-files.ts +76 -0
- package/src/retention-first-sweep-quiet.test.ts +31 -0
- package/src/retention.test.ts +100 -40
- package/src/retention.ts +423 -104
- package/src/route-callers-http.test.ts +120 -0
- package/src/route-timing.test.ts +218 -0
- package/src/route-timing.ts +262 -0
- package/src/rules-file-duplicate-alias.test.ts +234 -0
- package/src/rules-file-session-target.test.ts +207 -0
- package/src/rules-file-transport.test.ts +237 -0
- package/src/runtime-label.test.ts +22 -0
- package/src/runtime-label.ts +21 -0
- package/src/runtime-readiness.ts +90 -0
- package/src/schedule-agent-mcp-http.test.ts +432 -0
- package/src/schedule-agent.ts +252 -0
- package/src/schedule-starved.test.ts +92 -0
- package/src/schedule-starved.ts +114 -0
- package/src/scheduled-backoff-http.test.ts +193 -0
- package/src/scheduled-backoff.ts +64 -0
- package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
- package/src/scheduled-failure-backoff-2622.test.ts +145 -0
- package/src/scheduled-failure-code.test.ts +73 -0
- package/src/scheduled-failure-code.ts +105 -0
- package/src/scheduled-failures-http.test.ts +279 -0
- package/src/scheduled-failures.ts +425 -0
- package/src/scheduled-noprogress-backoff-2622.test.ts +163 -0
- package/src/scheduled-offline-backoff-probe.test.ts +56 -0
- package/src/scheduled-offline.test.ts +131 -0
- package/src/scheduled-offline.ts +66 -0
- package/src/scheduled-outcome-guidance-http.test.ts +139 -0
- package/src/scheduled-outcome-guidance.ts +9 -0
- package/src/scheduled-reply-unread-http.test.ts +212 -0
- package/src/scheduled-requirement-wake-http.test.ts +279 -0
- package/src/scheduled-requirement-wake.ts +125 -0
- package/src/scheduled-run-terminal.test.ts +268 -0
- package/src/scheduled-skip-blocking-task.test.ts +120 -0
- package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
- package/src/scheduled-stuck-http.test.ts +316 -0
- package/src/scheduled-stuck-notice-cap.test.ts +80 -0
- package/src/scheduled-stuck.ts +219 -0
- package/src/scheduled-tasks-http.test.ts +679 -0
- package/src/scheduled-tasks.ts +959 -0
- package/src/scheduled-work-outcome-http.test.ts +154 -0
- package/src/scheduled-work-outcome.ts +50 -0
- package/src/scoped-secrets.ts +141 -0
- package/src/send-dedup-request-id.test.ts +229 -0
- package/src/send-reply-agent-warning.test.ts +202 -0
- package/src/send-reply-alias-optional.test.ts +131 -0
- package/src/send-reply-attachments.test.ts +458 -0
- package/src/send_dedup.test.ts +54 -0
- package/src/send_dedup.ts +52 -6
- package/src/serve-error.test.ts +73 -0
- package/src/serve-error.ts +56 -0
- package/src/server.ts +4945 -338
- package/src/session-task-on-dispatch.ts +14 -0
- package/src/session-token-ownership-http.test.ts +122 -0
- package/src/shared/codex-inventory.ts +41 -0
- package/src/shared/daemon-provider-login.ts +31 -0
- package/src/shared/daemon-provider-snapshot.ts +52 -0
- package/src/shared/external-schedule-contract.ts +60 -0
- package/src/shared/node-name.test.ts +62 -0
- package/src/shared/node-name.ts +161 -0
- package/src/shared/probe-host-allowlist-drift.test.ts +45 -0
- package/src/shared/provider-application.ts +29 -0
- package/src/shared/provider-collection.ts +14 -0
- package/src/shared/provider-initialization.ts +8 -0
- package/src/shared/reserved-env-drift.test.ts +10 -0
- package/src/shared/scoped-secret-contract.ts +5 -0
- package/src/shared/task-content-limit-drift.test.ts +28 -0
- package/src/shared/task-content-limit.ts +25 -0
- package/src/side-thread-command-transport.test.ts +312 -0
- package/src/side-thread-command-transport.ts +318 -0
- package/src/side-thread-http-integration.test.ts +233 -0
- package/src/side-thread-http.ts +504 -0
- package/src/side-thread-production.test.ts +72 -0
- package/src/side-thread-production.ts +118 -0
- package/src/side-thread.test.ts +1067 -0
- package/src/side-thread.ts +2499 -0
- package/src/skillhub-http.test.ts +142 -0
- package/src/sqlite-close-checkpoint.test.ts +78 -0
- package/src/start-node.test.ts +264 -0
- package/src/status-alias-filter-http.test.ts +106 -0
- package/src/status-alias-resolver-http.test.ts +163 -0
- package/src/status-alias-resolver.ts +19 -0
- package/src/status-node-id-filter-http.test.ts +161 -0
- package/src/status-read-cache-http.test.ts +229 -0
- package/src/status-read-cache.ts +129 -0
- package/src/stop-delete-node.test.ts +567 -1
- package/src/task-access-http.test.ts +402 -0
- package/src/task-access.ts +420 -0
- package/src/task-activity.ts +60 -0
- package/src/task-auth-origin-http.test.ts +93 -0
- package/src/task-auth-origin.test.ts +24 -0
- package/src/task-auth-origin.ts +7 -0
- package/src/task-consumption.test.ts +490 -0
- package/src/task-diagnostic-http.test.ts +149 -0
- package/src/task-diagnostic.test.ts +115 -0
- package/src/task-diagnostic.ts +118 -0
- package/src/task-expiry-notice-http.test.ts +287 -0
- package/src/task-expiry-notice.ts +315 -0
- package/src/task-idempotency-mcp.test.ts +142 -0
- package/src/task-idempotency.test.ts +76 -0
- package/src/task-idempotency.ts +81 -0
- package/src/task-late-replies.ts +54 -0
- package/src/task-late-reply-http.test.ts +227 -0
- package/src/task-lifecycle-watcher-busy.test.ts +114 -0
- package/src/task-lifecycle-watcher.test.ts +204 -0
- package/src/task-lifecycle-watcher.ts +109 -0
- package/src/task-network-resolution-http.test.ts +140 -0
- package/src/task-offline-delivery-2668.test.ts +119 -0
- package/src/task-offline-delivery.ts +81 -0
- package/src/task-orphan-http.test.ts +287 -0
- package/src/task-orphan.ts +119 -0
- package/src/task-queue-ahead-http.test.ts +309 -0
- package/src/task-queue-ahead-scale.test.ts +236 -0
- package/src/task-queue-ahead.ts +186 -0
- package/src/task-rejection-log-http.test.ts +160 -0
- package/src/task-rejection-log.ts +58 -0
- package/src/task-sender-http.test.ts +143 -0
- package/src/task-stale-open-http.test.ts +292 -0
- package/src/task-stale-open.ts +103 -0
- package/src/tasks-pagination-http.test.ts +141 -0
- package/src/team-rules-status-http.test.ts +90 -0
- package/src/team-rules-status.test.ts +59 -0
- package/src/team-rules-status.ts +72 -0
- package/src/tmux-allowlist.test.ts +48 -0
- package/src/tool-audience-http.test.ts +230 -0
- package/src/tool-audience.ts +127 -0
- package/src/tools-list-json-schema.test.ts +94 -0
- package/src/tools.ts +4320 -413
- package/src/upload-early-reject-guard.test.ts +155 -0
- package/src/uploads-http.test.ts +86 -7
- package/src/uploads.ts +103 -6
- package/src/user-avatar-http.test.ts +74 -0
- package/src/user-avatar-image.ts +160 -0
- package/src/user-avatar-migration.test.ts +25 -0
- package/src/user-avatar-upload-http.test.ts +348 -0
- package/src/user-inbox-by-agent-http.test.ts +161 -0
- package/src/user-inbox-netid-notnull.test.ts +122 -0
- package/src/user-inbox-read-http.test.ts +223 -0
- package/src/user-inbox-schema.test.ts +54 -0
- package/src/version-stats.test.ts +66 -0
- package/src/version-stats.ts +109 -0
|
@@ -15,8 +15,11 @@ import { describe, expect, test, beforeAll, afterAll } from "bun:test";
|
|
|
15
15
|
import { mkdtempSync, rmSync } from "fs";
|
|
16
16
|
import { join } from "path";
|
|
17
17
|
import { tmpdir } from "os";
|
|
18
|
-
import {
|
|
18
|
+
import { createHash } from "node:crypto";
|
|
19
|
+
import { register, addNetworkMember, removeNetworkMember } from "./auth.js";
|
|
19
20
|
import { db } from "./db.js";
|
|
21
|
+
import { MAX_REQUEST_CONTENT_LENGTH, MAX_UPLOAD_BYTES } from "./uploads.js";
|
|
22
|
+
import { HEALTH_FIELD_META, PUBLIC_HEALTH_KEYS, mayBePublic, projectPublicHealth } from "./server.js";
|
|
20
23
|
|
|
21
24
|
const SERVER_DB = mkdtempSync(join(tmpdir(), "anet-health-red-db-")) + "/commhub.db";
|
|
22
25
|
|
|
@@ -29,6 +32,10 @@ let userNetworkId = "";
|
|
|
29
32
|
let userName = "";
|
|
30
33
|
let adminToken = "";
|
|
31
34
|
|
|
35
|
+
// 30s 而不是 bun 默认的 5s:这个 hook 跑 register()(KDF)+bootServer(),
|
|
36
|
+
// 本机空载基线 ~620ms,而 2026-08-17 与 2026-08-31 两次 CI 上它被 5s 上限打死
|
|
37
|
+
// (0 pass / 1 fail / Ran 1 test —— 见 #928、#1627)。5247ms 是**被截断的下界**,
|
|
38
|
+
// 不是测量值,所以余量按基线的 ~48x 取,而不是按那个数取。
|
|
32
39
|
beforeAll(async () => {
|
|
33
40
|
process.env.COMMHUB_DB = process.env.COMMHUB_DB || SERVER_DB;
|
|
34
41
|
process.env.HOST = "127.0.0.1";
|
|
@@ -71,7 +78,7 @@ beforeAll(async () => {
|
|
|
71
78
|
if (res.status !== 200) throw new Error("SSE subscribe failed: " + res.status);
|
|
72
79
|
sseReader = res.body!.getReader();
|
|
73
80
|
await sseReader.read(); // consume the connected frame → registration done
|
|
74
|
-
});
|
|
81
|
+
}, 30_000);
|
|
75
82
|
|
|
76
83
|
afterAll(() => {
|
|
77
84
|
try { sseReader?.cancel(); } catch {}
|
|
@@ -91,6 +98,1087 @@ describe("#473 anonymous /health — watchdog contract intact, no topology leak"
|
|
|
91
98
|
expect(body.sse_connections).toBeGreaterThanOrEqual(1);
|
|
92
99
|
});
|
|
93
100
|
|
|
101
|
+
// 2026-10-31 —— 站位要可验,但**匿名读者只配知道「有没有」,不配知道「是什么」**。
|
|
102
|
+
// /health 是匿名端点;commit sha 对匿名读者 = 精确告诉外部这是哪一版代码(本仓公开)。
|
|
103
|
+
// ⇒ 匿名给布尔 build_identified;完整 sha(+dirty)只给已鉴权者。
|
|
104
|
+
test("anonymous /health discloses only whether a build id exists, never the sha", async () => {
|
|
105
|
+
const res = await fetch(`${BASE}/health`);
|
|
106
|
+
const body = await res.json() as any;
|
|
107
|
+
expect("git_commit" in body).toBe(false);
|
|
108
|
+
expect("git_dirty" in body).toBe(false);
|
|
109
|
+
expect(typeof body.build_identified).toBe("boolean");
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test("authenticated admin /health carries git_commit (40-hex or null) and git_dirty", async () => {
|
|
113
|
+
const res = await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } });
|
|
114
|
+
const body = await res.json() as any;
|
|
115
|
+
expect("git_commit" in body).toBe(true);
|
|
116
|
+
const value = body.git_commit;
|
|
117
|
+
const isSha = typeof value === "string" && /^[0-9a-f]{40}$/.test(value);
|
|
118
|
+
// null 是设计(没有 .git),不是缺陷;但任何别的形状都不允许。
|
|
119
|
+
expect(isSha || value === null).toBe(true);
|
|
120
|
+
if (value !== null) expect(value).not.toBe(body.version);
|
|
121
|
+
// dirty 位必须与 sha 成对,否则 vantage 会把脏树读数当成提交。
|
|
122
|
+
expect(typeof body.git_dirty).toBe("boolean");
|
|
123
|
+
if (value === null) expect(body.git_dirty).toBe(false);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
// 2026-10-31 —— 拒绝计数的 **must-fire**:注入一次真实拒绝,看它跳不跳。
|
|
127
|
+
//
|
|
128
|
+
// 为什么必须有这一条:光断言 by_reason 存在,测的是形状;形状对、接线错,读数照样是 0。
|
|
129
|
+
// 而「只有异常路径能让它 +1」这一类,0 与「从没出过错」同形 —— 不注入就永远发现不了。
|
|
130
|
+
test("a real rejected /api/task actually bumps the counter (must-fire, not just shape)", async () => {
|
|
131
|
+
const before = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
132
|
+
const beforeTotal = before.counters.task_rejections.total as number;
|
|
133
|
+
|
|
134
|
+
// 🔴 必须**带登录态**、并在 handler 内部失败:
|
|
135
|
+
// 全局鉴权中间件的 401 在到达 /api/task 之前就返回 ⇒ 根本不经过 logTaskRejection。
|
|
136
|
+
// (这本身就是一条已知缺口,写在 rejection-counters.ts 的注释里。)
|
|
137
|
+
const rej = await fetch(`${BASE}/api/task`, {
|
|
138
|
+
method: "POST",
|
|
139
|
+
headers: { "content-type": "application/json", Authorization: `Bearer ${userToken}` },
|
|
140
|
+
body: JSON.stringify({}), // schema 校验失败 ⇒ 400,走 reject()
|
|
141
|
+
});
|
|
142
|
+
expect(rej.status).toBeGreaterThanOrEqual(400);
|
|
143
|
+
|
|
144
|
+
const after = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
145
|
+
expect(after.counters.task_rejections.total).toBe(beforeTotal + 1);
|
|
146
|
+
// 🔴 窗口起点必须不动:计数器 +1 而 since 变化,会让「这段时间拒了几次」算错。
|
|
147
|
+
// 没有窗口的计数器是「没有域的数」;没有 must-fire 的计数器是「没有证据的数」。
|
|
148
|
+
expect(after.counters.since).toBe(before.counters.since);
|
|
149
|
+
expect(after.startedAt).toBe(before.startedAt);
|
|
150
|
+
// 2026-10-31 —— **窗口与值必须同响应**(外部复核 ③:窗口是分母,必须先固定再取数)。
|
|
151
|
+
// 本仓的结构比「s1 = since; v = counter; s2 = since」更强:since 与各计数在**同一份载荷**里,
|
|
152
|
+
// 单次读就原子,不存在跨越 reset 的长读。⇒ 这里把「同一个对象里」这件事钉住。
|
|
153
|
+
expect(Object.prototype.hasOwnProperty.call(before.counters, "since")).toBe(true);
|
|
154
|
+
expect(typeof before.counters.since).toBe("string");
|
|
155
|
+
// 跨两次读的读者(如上面的 before/after 比较)必须自己比对 since —— 本条就是那个例子。
|
|
156
|
+
expect(before.counters.since.length).toBeGreaterThan(0);
|
|
157
|
+
const bumped = Object.keys(after.counters.task_rejections.by_reason).find(
|
|
158
|
+
(k) => k.startsWith(`${rej.status}:`),
|
|
159
|
+
);
|
|
160
|
+
expect(bumped).toBeTruthy();
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
// 2026-10-31 —— 把「已知缺口」钉在 CI 里,而不是只写在注释里。
|
|
164
|
+
//
|
|
165
|
+
// 🔴 这条断言的语义是:**目前如此**,不是「应该如此」。
|
|
166
|
+
// 将来谁把计数上移到中间件,这条会红 —— 那就对了:他必须同时更新
|
|
167
|
+
// 模块注释里的覆盖比例(现在是 2/6 类出口)。
|
|
168
|
+
test("KNOWN GAP: unauthenticated /api/task rejection is NOT counted (see rejection-counters.ts)", async () => {
|
|
169
|
+
const before = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
170
|
+
const beforeTotal = before.counters.task_rejections.total as number;
|
|
171
|
+
|
|
172
|
+
// 不带 Authorization ⇒ 鉴权中间件在到达 handler 之前就返回 401。
|
|
173
|
+
const rej = await fetch(`${BASE}/api/task`, {
|
|
174
|
+
method: "POST",
|
|
175
|
+
headers: { "content-type": "application/json" },
|
|
176
|
+
body: JSON.stringify({}),
|
|
177
|
+
});
|
|
178
|
+
expect(rej.status).toBeGreaterThanOrEqual(400);
|
|
179
|
+
|
|
180
|
+
const after = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
181
|
+
if (after.counters.task_rejections.total !== beforeTotal) {
|
|
182
|
+
throw new Error(
|
|
183
|
+
"已知缺口已被修复?401 出口现在会计数了 —— "
|
|
184
|
+
+ "请同时更新 rejection-counters.ts 的出口清单与覆盖比例(当前 2/6),"
|
|
185
|
+
+ "并把这条测试改成断言「已被计数」。",
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
expect(after.counters.task_rejections.total).toBe(beforeTotal);
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
// 2026-10-31 —— 出口清单里最后一行空 pinned_by:**请求体超限**(Bun maxRequestBodySize)。
|
|
192
|
+
// 它是**运行时在 fetch() 之前**拒绝的:我们的代码一行都没跑 ⇒ 不可能计数。
|
|
193
|
+
// 这一条钉住的是「不计数」,而它最容易怀疑的方向恰好相反("那么大一个请求,肯定记了吧")。
|
|
194
|
+
test("KNOWN GAP: body over runtime maxRequestBodySize is NOT counted (rejected before fetch())", async () => {
|
|
195
|
+
const read = async () => (await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any);
|
|
196
|
+
const before = await read();
|
|
197
|
+
const huge = "x".repeat(MAX_REQUEST_CONTENT_LENGTH + 1024);
|
|
198
|
+
let status: number | null = null;
|
|
199
|
+
let rejectedAtTransport = false;
|
|
200
|
+
try {
|
|
201
|
+
const r = await fetch(`${BASE}/api/task`, {
|
|
202
|
+
method: "POST",
|
|
203
|
+
headers: { "content-type": "application/json", Authorization: `Bearer ${userToken}` },
|
|
204
|
+
body: huge,
|
|
205
|
+
});
|
|
206
|
+
status = r.status;
|
|
207
|
+
await r.text();
|
|
208
|
+
} catch {
|
|
209
|
+
rejectedAtTransport = true;
|
|
210
|
+
}
|
|
211
|
+
const after = await read();
|
|
212
|
+
// 形态有两条:运行时回 413,或传输层直接断(两者都算「没到我们的代码」)。
|
|
213
|
+
// 本机实测:**status=413**(Bun 在 fetch() 之前就回了,响应体不是我们的 handler 生成的)。
|
|
214
|
+
expect(rejectedAtTransport || status === 413).toBe(true);
|
|
215
|
+
|
|
216
|
+
// 2026-10-31 —— **否定断言必须配镜像**:上面「没计数」在「这条路由根本不通」时也成立。
|
|
217
|
+
// ⇒ 同一条路由 + 同一组鉴权头,用小请求体必须**走到 handler**(拿到 HTTP 状态码)。
|
|
218
|
+
// 两条合起来才说明:计数没变是**因为这个请求太大了**,不是因为这条路本来就不计数。
|
|
219
|
+
const control = await fetch(`${BASE}/api/task`, {
|
|
220
|
+
method: "POST",
|
|
221
|
+
headers: { "content-type": "application/json", Authorization: `Bearer ${userToken}` },
|
|
222
|
+
body: JSON.stringify({}),
|
|
223
|
+
});
|
|
224
|
+
expect(control.status).toBeGreaterThanOrEqual(200);
|
|
225
|
+
await control.text();
|
|
226
|
+
if (after.counters.task_rejections.total !== before.counters.task_rejections.total) {
|
|
227
|
+
throw new Error("已知缺口已被修复?超限请求体现在会计数了 —— 请更新 TASK_REJECTION_EXITS 与这条测试。");
|
|
228
|
+
}
|
|
229
|
+
expect(after.counters.task_rejections.total).toBe(before.counters.task_rejections.total);
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
// 2026-10-31 —— 出口清单里「before_route_table」那一行原本 pinned_by 为空(= 缺口)。
|
|
233
|
+
// 补上它的钉:未匹配的 /api/* 在路由表之前就 404,**不经过 handler,也不计数**。
|
|
234
|
+
// 这一条同时是「清单要能被一次坏输入打出来」的实例(对方那句)。
|
|
235
|
+
test("KNOWN GAP: unmatched /api/* route 404 is NOT counted (route table rejects before handler)", async () => {
|
|
236
|
+
const read = async () => (await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any);
|
|
237
|
+
const before = await read();
|
|
238
|
+
const r = await fetch(`${BASE}/api/definitely-not-a-route-xyz`, {
|
|
239
|
+
method: "POST",
|
|
240
|
+
headers: { "content-type": "application/json", Authorization: `Bearer ${userToken}` },
|
|
241
|
+
body: JSON.stringify({}),
|
|
242
|
+
});
|
|
243
|
+
expect(r.status).toBeGreaterThanOrEqual(400);
|
|
244
|
+
const after = await read();
|
|
245
|
+
if (after.counters.task_rejections.total !== before.counters.task_rejections.total) {
|
|
246
|
+
throw new Error("已知缺口已被修复?404 出口现在会计数了 —— 请更新 TASK_REJECTION_EXITS 与这条测试。");
|
|
247
|
+
}
|
|
248
|
+
expect(after.counters.task_rejections.total).toBe(before.counters.task_rejections.total);
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
// 2026-10-31 —— **出口清单的分母要有来源**(外部复核 ②):
|
|
252
|
+
// 六行以前只活在注释里;现在它是数据,这条断言把「表」与「钉住它的测试」绑在一起。
|
|
253
|
+
// 2026-10-31 —— **白名单条目必须指得出读者**(外部复核 ⑤ 第 ②′ 问:路标还是仪表)。
|
|
254
|
+
// 三分类(landmark/gauge/credential)回答「该不该给」,这张表回答「谁在读」。
|
|
255
|
+
// 关键是它**跨源**:声明 reader=cli 的键,必须在 agent-network/src 里真的出现,
|
|
256
|
+
// 否则「有人在读」就只是白名单里的一个愿望。
|
|
257
|
+
test("every anonymous key names a reader, and reader=cli is cross-checked against the CLI source", async () => {
|
|
258
|
+
const { PUBLIC_HEALTH_KEYS } = await import("./server.js");
|
|
259
|
+
const { PUBLIC_HEALTH_KEY_READERS } = await import("./health-anon-readers.js");
|
|
260
|
+
const { readFileSync, readdirSync, statSync } = await import("node:fs");
|
|
261
|
+
const { join } = await import("node:path");
|
|
262
|
+
|
|
263
|
+
// ① 覆盖:白名单里每个键都要有读者登记,反之亦然(两边同集合,防「删了白名单留下登记」)
|
|
264
|
+
expect(Object.keys(PUBLIC_HEALTH_KEY_READERS).sort()).toEqual([...PUBLIC_HEALTH_KEYS].sort());
|
|
265
|
+
|
|
266
|
+
// ② 读者类别必须在闭集里(防「reader: 某个系统」这种自由文本)
|
|
267
|
+
for (const [key, entry] of Object.entries(PUBLIC_HEALTH_KEY_READERS)) {
|
|
268
|
+
expect(["cli", "probe", "external", "operator"]).toContain(entry.reader);
|
|
269
|
+
// 「同上」在这一类表里是无效理由:它把理由指向另一行,而那行改了它不会跟着改。
|
|
270
|
+
expect(entry.why).not.toContain("同上");
|
|
271
|
+
expect(entry.why.length).toBeGreaterThan(3);
|
|
272
|
+
// external 必须写明「未验」或指明是哪类系统 —— 两种都接受,但不能什么都不说
|
|
273
|
+
if (entry.reader === "external") expect(entry.why.length).toBeGreaterThan(10);
|
|
274
|
+
expect(key.length).toBeGreaterThan(0);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// ③ 跨源:reader=cli 必须能在客户端源码里找到这个名字
|
|
278
|
+
// 两个根都要扫:`src/`(库)与 `bin/`(CLI 入口)。第一版只扫了 src,
|
|
279
|
+
// 于是把「只在 cli.ts 里读」的 4 个键误判成「没有读者」——
|
|
280
|
+
// 这正是这类跨源断言最容易出的错:**读者在,只是不在我扫的那个目录里**。
|
|
281
|
+
const roots = [
|
|
282
|
+
join(import.meta.dir, "..", "..", "agent-network", "src"),
|
|
283
|
+
join(import.meta.dir, "..", "..", "agent-network", "bin"),
|
|
284
|
+
];
|
|
285
|
+
const walk = (dir: string, out: string[] = []): string[] => {
|
|
286
|
+
for (const name of readdirSync(dir)) {
|
|
287
|
+
const full = join(dir, name);
|
|
288
|
+
if (statSync(full).isDirectory()) walk(full, out);
|
|
289
|
+
else if (name.endsWith(".ts") && !name.endsWith(".test.ts")) out.push(full);
|
|
290
|
+
}
|
|
291
|
+
return out;
|
|
292
|
+
};
|
|
293
|
+
const cliSource = roots.flatMap((r) => walk(r)).map((f) => readFileSync(f, "utf8")).join("\n");
|
|
294
|
+
const cliKeys = Object.entries(PUBLIC_HEALTH_KEY_READERS).filter(([, e]) => e.reader === "cli").map(([k]) => k);
|
|
295
|
+
expect(cliKeys.length).toBeGreaterThan(0);
|
|
296
|
+
const missing = cliKeys.filter((k) => !new RegExp(`\\b${k}\\b`).test(cliSource));
|
|
297
|
+
if (missing.length) throw new Error(`声明 reader=cli 但这些键在客户端源码里找不到:${missing.join(", ")}`);
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
test("rejection exit inventory: 6 rows, and every counted row names a pinning test", async () => {
|
|
301
|
+
const { TASK_REJECTION_EXITS } = await import("./rejection-counters.js");
|
|
302
|
+
expect(TASK_REJECTION_EXITS.length).toBe(6);
|
|
303
|
+
// counted 的位置必须有测试钉住(空串 ⇒ 缺口,红)
|
|
304
|
+
for (const row of TASK_REJECTION_EXITS) {
|
|
305
|
+
if (row.counted) expect(row.pinned_by.length).toBeGreaterThan(0);
|
|
306
|
+
}
|
|
307
|
+
// 2026-10-31 —— **空 pinned_by 必须自报家门**(外部复核 (b):「兜底值必须说出自己是兜底」)。
|
|
308
|
+
// 空的 pinned_by 与「忘了填」在数据里长得一样 ⇒ 要求 `pinned_by` 与 `gap_reason` **恰好填一个**。
|
|
309
|
+
// 两个都填 = 自相矛盾(既说钉住了又说钉不住);都不填 = 又回到静默缺口。
|
|
310
|
+
for (const row of TASK_REJECTION_EXITS) {
|
|
311
|
+
const hasPin = row.pinned_by.length > 0;
|
|
312
|
+
const hasGap = (row.gap_reason ?? "").length > 0;
|
|
313
|
+
expect(hasPin !== hasGap).toBe(true);
|
|
314
|
+
}
|
|
315
|
+
// 声明为缺口的行:目前恰好 1 行(error_hook_500),且理由里必须同时写出「卡在哪」与「什么能解锁」
|
|
316
|
+
const gaps = TASK_REJECTION_EXITS.filter((r) => !r.pinned_by.length);
|
|
317
|
+
expect(gaps.map((r) => r.position)).toEqual(["error_hook_500"]);
|
|
318
|
+
expect(gaps[0].gap_reason).toContain("解锁条件");
|
|
319
|
+
|
|
320
|
+
// 反过来:未计数的位置若已有测试钉住,名字必须非空 —— 否则「钉住了」只是注释
|
|
321
|
+
const pinnedNames = TASK_REJECTION_EXITS.map((r) => r.pinned_by).filter(Boolean);
|
|
322
|
+
expect(pinnedNames.length).toBeGreaterThanOrEqual(3);
|
|
323
|
+
// 位置名必须唯一(否则两行描述同一处,比例就重复计了)
|
|
324
|
+
expect(new Set(TASK_REJECTION_EXITS.map((r) => r.position)).size).toBe(TASK_REJECTION_EXITS.length);
|
|
325
|
+
|
|
326
|
+
// 2026-10-31 —— **「数对、集合错」**(外部复核 164b3e5e 那条:14 个块数得对,
|
|
327
|
+
// 而「13 个公共头」不成立,因为 14 个头集合的交集是空集)。
|
|
328
|
+
// 本表同款:有 2 个位置装了表(一个**计数**),但链路必须先过前面若干个位置 ——
|
|
329
|
+
// 所以「链路覆盖」只能是**前缀长度**,不能是「计数 / 总数」。
|
|
330
|
+
const instrumented = TASK_REJECTION_EXITS.filter((r) => r.counted).length;
|
|
331
|
+
let prefix = 0;
|
|
332
|
+
for (const r of TASK_REJECTION_EXITS) { if (r.counted) prefix += 1; else break; }
|
|
333
|
+
expect(instrumented).toBe(2); // 装了几个点(计数)
|
|
334
|
+
expect(prefix).toBe(0); // 链路覆盖(前缀)—— 第 1 个位置就是洞
|
|
335
|
+
// 反例守卫:一旦数错集合(把第 1 行改成 counted),前缀与计数会一起变 —— 那时必须改比例与注释
|
|
336
|
+
expect(instrumented).not.toBe(prefix);
|
|
337
|
+
|
|
338
|
+
// 2026-10-31 —— **构造自洽的断言不会以我们关心的方式失败**(外部复核 164b3e5e:
|
|
339
|
+
// 「14 个块数得对,但那是构造自洽的断言,不会以我们关心的方式失败」)。
|
|
340
|
+
// 上面那些都是对着**自己声明的表**断言 —— 它只证明「表没被改」,不证明「表描述的世界还在」。
|
|
341
|
+
// ⇒ 加一条**跨源**检查:计数器的主语(/api/task)必须真的出现在生成的路由清单里。
|
|
342
|
+
// 若有人改了路由名而没改计数器,这条会红;而只对自己的表断言的测试永远不会。
|
|
343
|
+
const { readFileSync } = await import("node:fs");
|
|
344
|
+
// 仓根的 docs/(从 server/src 出发是 ../../docs),不是 server/docs
|
|
345
|
+
const table = JSON.parse(readFileSync(new URL("../../docs/rest-route-table.json", import.meta.url), "utf8"));
|
|
346
|
+
expect(table.rows.some((r: any) => r.path === "/api/task")).toBe(true);
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
// 2026-10-31 —— parser 级拒绝在本仓**是**被计数的,因为我们在 handler 内 await req.json()。
|
|
350
|
+
// 与 Express 恰好相反(express.json() 走 next(err) ⇒ 错误中间件 ⇒ 不计)。
|
|
351
|
+
// ⇒ 这类出口的归属取决于 parser 放在哪,而不是取决于框架。
|
|
352
|
+
test("malformed JSON on /api/task IS counted — parser lives inside our handler", async () => {
|
|
353
|
+
const before = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
354
|
+
const beforeTotal = before.counters.task_rejections.total as number;
|
|
355
|
+
const rej = await fetch(`${BASE}/api/task`, {
|
|
356
|
+
method: "POST",
|
|
357
|
+
headers: { "content-type": "application/json", Authorization: `Bearer ${userToken}` },
|
|
358
|
+
body: "{bad",
|
|
359
|
+
});
|
|
360
|
+
expect(rej.status).toBe(400);
|
|
361
|
+
const after = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
362
|
+
expect(after.counters.task_rejections.total).toBe(beforeTotal + 1);
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
// 2026-10-31 —— served_at 的**敏感性**:单调不减只证「它没倒退」,常量也满足。
|
|
366
|
+
// 要证「它在跟着墙钟走」,断言里必须出现**两次读数之差**。
|
|
367
|
+
// (今晚的教训:startedAt 的敏感性当初是靠「换进程才变」证的,不是靠「刷新两次相同」。)
|
|
368
|
+
test("served_at actually advances with the wall clock (difference, not just monotonicity)", async () => {
|
|
369
|
+
const read = async () => (await (await fetch(`${BASE}/health`)).json() as any).served_at;
|
|
370
|
+
const t1 = await read();
|
|
371
|
+
const startedAt = Date.now();
|
|
372
|
+
await new Promise((r) => setTimeout(r, 250));
|
|
373
|
+
const t2 = await read();
|
|
374
|
+
const elapsed = Date.now() - startedAt;
|
|
375
|
+
const delta = Date.parse(t2) - Date.parse(t1);
|
|
376
|
+
expect(delta).toBeGreaterThan(0); // 真的走了(否定「常量」)
|
|
377
|
+
// 2026-10-31 —— (b) 容差必须**大于被测时钟可能的最大步进**,否则一次 NTP 步进就假红,
|
|
378
|
+
// 而假红会被读成「字段坏了」,实际是「时钟动了一下」。
|
|
379
|
+
// NTP:slew 阈 128ms,超阈值即步进(秒级)。⇒ 容差 5s,不是 1s。
|
|
380
|
+
// ⚠️ 这条量的是**速率**(差 / 等待);「时钟偏置」(绝对值)在 epoch_delta_ms 那条,
|
|
381
|
+
// 两者不能共用容差 —— 它们量的是两件事。
|
|
382
|
+
const STEP_ALLOWANCE_MS = 5000;
|
|
383
|
+
expect(Math.abs(delta - elapsed)).toBeLessThanOrEqual(STEP_ALLOWANCE_MS);
|
|
384
|
+
// 2026-10-31 —— (a) 「必须变」没排除「以错误的方式变」:
|
|
385
|
+
// 每次请求变 / 每秒变 / 每次部署变 都满足「差 > 0」,而语义完全不同。
|
|
386
|
+
// 两次读数上,「每次请求变」与「每秒变」同形 ⇒ 需要第二条锁定**时间尺度**:
|
|
387
|
+
// 在同样的等待里多打若干请求,差值不应随请求数增长。
|
|
388
|
+
const t3 = await read();
|
|
389
|
+
const burstStart = Date.now();
|
|
390
|
+
const BURST = 20;
|
|
391
|
+
for (let i = 0; i < BURST; i++) await read(); // 20 次额外请求
|
|
392
|
+
await new Promise((r) => setTimeout(r, 250));
|
|
393
|
+
const t4 = await read();
|
|
394
|
+
const burstElapsed = Date.now() - burstStart;
|
|
395
|
+
const burstDelta = Date.parse(t4) - Date.parse(t3);
|
|
396
|
+
// ⚠️ 这一条的容差**不能**用上面那个时钟步进容差,否则判据被它自己压平:
|
|
397
|
+
// 20 次请求 × 每次 +150ms 的假实现 = +3000ms,而我第一版给的是 +5000ms ⇒ 照样绿。
|
|
398
|
+
// (witnessed-red 抓到了:把 served_at 改成每次请求 +150ms,那一版仍然 68 pass。)
|
|
399
|
+
// ⇒ 这里用「与请求数无关」的紧口:20 次请求带来的增量必须远小于其漂移规模。
|
|
400
|
+
const PER_REQUEST_ALLOWANCE_MS = 1000; // 20 次请求合计只许 +1s;每请求漂移 ≥50ms 就会红
|
|
401
|
+
expect(burstDelta).toBeLessThanOrEqual(burstElapsed + PER_REQUEST_ALLOWANCE_MS);
|
|
402
|
+
expect(burstDelta).toBeGreaterThanOrEqual(0);
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
// 2026-10-31 —— 误差界必须有**地板**。
|
|
406
|
+
// uptime×|delta|/value 只覆盖尺子自己的舍入,delta=0 时报 0;
|
|
407
|
+
// 而 btime 是整秒(±500ms)、jiffies 是 10ms 量化 —— 这两项不会因为尺子变准而消失。
|
|
408
|
+
// ⇒ 判据:误差界的最小值是「尺子之外的误差之和」,不是 0。
|
|
409
|
+
describe("clk_tck 的误差界与守卫的可检出下限", () => {
|
|
410
|
+
test("error bound never reports 0 (floor from btime seconds + jiffies quantum)", async () => {
|
|
411
|
+
const b = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
412
|
+
if (b.kernel_started_at === null) return; // 非 Linux:这一族本来就不发布
|
|
413
|
+
expect(typeof b.kernel_started_at_error_ms).toBe("number");
|
|
414
|
+
expect(b.kernel_started_at_error_ms).toBeGreaterThanOrEqual(510);
|
|
415
|
+
// 即使 delta=0(尺子最准的那一刻),地板仍然在
|
|
416
|
+
if (b.clk_tck_delta === 0) expect(b.kernel_started_at_error_ms).toBeGreaterThanOrEqual(510);
|
|
417
|
+
});
|
|
418
|
+
|
|
419
|
+
// 2026-10-31 —— 阈值决定了它抓得住多大的异常;不报换算,读者无法区分
|
|
420
|
+
// 「没有挂起过」与「挂起太小,抓不到」—— 两者都读成 derived。
|
|
421
|
+
test("publishes the smallest suspend the 1% guard could actually catch", async () => {
|
|
422
|
+
const b = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
423
|
+
if (b.kernel_started_at === null) return;
|
|
424
|
+
expect(typeof b.clk_tck_guard_min_suspend_s).toBe("number");
|
|
425
|
+
// relErr ≈ 挂起 / **机器** uptime ⇒ 1% ⇒ 0.01 × host_uptime_s
|
|
426
|
+
// ⚠️ 不是 b.uptime(那是进程的),两者相差可以上万倍 —— 这一条正是在钉这个区别
|
|
427
|
+
expect(typeof b.host_uptime_s).toBe("number");
|
|
428
|
+
const expected = 0.01 * b.host_uptime_s;
|
|
429
|
+
expect(Math.abs(b.clk_tck_guard_min_suspend_s - expected)).toBeLessThanOrEqual(2);
|
|
430
|
+
expect(b.clk_tck_guard_min_suspend_s).toBeGreaterThan(0);
|
|
431
|
+
// 机器 uptime ≥ 进程 uptime(本进程是这台机器上后起的)—— 两个量确实不同名不同物
|
|
432
|
+
expect(b.host_uptime_s).toBeGreaterThanOrEqual(b.uptime);
|
|
433
|
+
// 2026-10-31 —— 原始估计与阈值判定分开报:
|
|
434
|
+
// 本机实测 estimate=99.35 而 suspend_total_s=0 ⇒ 被打回 assumed 不是挂起造成的,是估计器偏置。
|
|
435
|
+
// 没有这一格,那句「为什么是 assumed」说不出来(只能看到 assumed)。
|
|
436
|
+
expect(typeof b.clk_tck_estimate).toBe("number");
|
|
437
|
+
expect(Math.abs(b.clk_tck_estimate - 100)).toBeLessThan(10);
|
|
438
|
+
if (b.clk_tck_source === "confirmed") expect(Math.abs(b.clk_tck_estimate - 100)).toBeLessThan(0.5);
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
// 2026-10-31 —— 把**推导的前提**做成读数:累计挂起 = (now − btime) − /proc/uptime。
|
|
442
|
+
// 没有它,derived 与 confirmed 在读数上只差一个容差,而「没挂起过」这个前提在两者之外。
|
|
443
|
+
test("derived carries its premise: suspend_total_s is published (null ≠ 0)", async () => {
|
|
444
|
+
const b = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
445
|
+
if (b.kernel_started_at === null) return;
|
|
446
|
+
expect("suspend_total_s" in b).toBe(true);
|
|
447
|
+
const s = b.suspend_total_s;
|
|
448
|
+
expect(s === null || (typeof s === "number" && s >= 0)).toBe(true);
|
|
449
|
+
// 前提与结论必须一致:若已挂起超过守卫的可检出下限,就不该还报 confirmed
|
|
450
|
+
if (typeof s === "number" && s > (b.clk_tck_guard_min_suspend_s ?? Infinity)) {
|
|
451
|
+
expect(b.clk_tck_source).not.toBe("confirmed");
|
|
452
|
+
}
|
|
453
|
+
});
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
// 2026-10-31 —— `/health` 的 validator 语义:**不发 ETag,且 `If-None-Match: *` 也回 200**。
|
|
457
|
+
//
|
|
458
|
+
// 起因(外部复核在同族端点上实测到的):当响应体里带时间/计数器时,
|
|
459
|
+
// 「回不回 304」从头到尾不由 cache-control 决定:
|
|
460
|
+
// · Express 的默认 etag 对每个 body 都变 ⇒ validator 永远匹配不上 ⇒ 一次 If-None-Match 测不出任何东西
|
|
461
|
+
// · `if-none-match: *` 会**直接跳过** etag 比较(RFC 9110 §13.1.2:资源存在 ⇒ 304)
|
|
462
|
+
// ⇒ 本仓的选择是:不发 ETag(没有 validator 可匹配),并且对 `*` 也回 200 ——
|
|
463
|
+
// 因为我们每一份正文都是「此刻的读数」,回 304 等于告诉客户端「你手里那份是当前的」,那是假话。
|
|
464
|
+
// 这条断言把「不发的决定」和「对 * 的例外」都钉住;否则它只是注释里的一句话。
|
|
465
|
+
describe("/health 的 validator 语义", () => {
|
|
466
|
+
test("no ETag at all, and If-None-Match: * still returns 200 with fresh body", async () => {
|
|
467
|
+
const a = await fetch(`${BASE}/health`);
|
|
468
|
+
expect(a.headers.get("etag")).toBeNull(); // 没有 validator 可匹配
|
|
469
|
+
expect(a.headers.get("cache-control")).toBe("no-store");
|
|
470
|
+
const b = await fetch(`${BASE}/health`, { headers: { "If-None-Match": "*" } });
|
|
471
|
+
expect(b.status).toBe(200); // RFC 会要 304;我们是**故意的例外**
|
|
472
|
+
const bodyB = await b.json() as any;
|
|
473
|
+
const bodyA = await a.json() as any;
|
|
474
|
+
// 而且正文确实是新的(不是把上一份原样回给条件请求)
|
|
475
|
+
expect(typeof bodyB.served_at).toBe("string");
|
|
476
|
+
expect(Date.parse(bodyB.served_at)).toBeGreaterThanOrEqual(Date.parse(bodyA.served_at));
|
|
477
|
+
});
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
// 2026-10-31 —— 补的是**反方向**:既有的
|
|
481
|
+
// "every field in the authenticated body carries a class"
|
|
482
|
+
// 只查 payload → meta(加字段忘了分类);它查不到 meta → payload(**声明了一个永远不出现的字段**)。
|
|
483
|
+
// 后者是「死 meta」:一条 meta 写着 class/granularity/frozen_at_boot,而没有任何响应会带它,
|
|
484
|
+
// 于是它会一直正确地描述一个不存在的东西 —— 并且看起来比没有更权威。
|
|
485
|
+
// (写这条时我以为两个方向都没覆盖;实测 witness 表明正向早就有,只有反向是空的。)
|
|
486
|
+
test("every field in the full payload has meta, and every meta appears in it", async () => {
|
|
487
|
+
const full = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
488
|
+
const payloadKeys = Object.keys(full);
|
|
489
|
+
const metaKeys = Object.keys(HEALTH_FIELD_META);
|
|
490
|
+
const undocumented = payloadKeys.filter((k) => !metaKeys.includes(k)).sort();
|
|
491
|
+
// **有条件出现的字段**:meta 里有、默认响应里没有。每一项都必须能说出触发条件,
|
|
492
|
+
// 并且在这里当场把它触发一次 —— 否则「有条件出现」与「写错了」同形。
|
|
493
|
+
const conditional: Record<string, string> = {
|
|
494
|
+
probe_nonce: "只在带 X-Probe-Nonce 时出现",
|
|
495
|
+
};
|
|
496
|
+
const phantom = metaKeys.filter((k) => !payloadKeys.includes(k) && !(k in conditional)).sort();
|
|
497
|
+
expect({ undocumented, phantom }).toEqual({ undocumented: [], phantom: [] });
|
|
498
|
+
// 把每个条件字段真的触发一次
|
|
499
|
+
for (const k of Object.keys(conditional)) {
|
|
500
|
+
if (k !== "probe_nonce") continue;
|
|
501
|
+
const withNonce = await (await fetch(`${BASE}/health`, { headers: { "X-Probe-Nonce": "meta-bijection" } })).json() as any;
|
|
502
|
+
expect(Object.prototype.hasOwnProperty.call(withNonce, k)).toBe(true);
|
|
503
|
+
}
|
|
504
|
+
});
|
|
505
|
+
|
|
506
|
+
// 2026-10-31 —— license 三态必须是「三种不同的可修性」,不能折成一个 "none"。
|
|
507
|
+
// 本条只断言形状(测试库没有 license 行 ⇒ absent);四种映射由 license-state.test.ts 钉死。
|
|
508
|
+
test("license_state distinguishes absent from unknown instead of collapsing to none", async () => {
|
|
509
|
+
const body = await (await fetch(`${BASE}/health`)).json() as any;
|
|
510
|
+
expect(typeof body.license).toBe("string"); // 兼容字段仍在
|
|
511
|
+
const st = body.license_state;
|
|
512
|
+
expect(st && typeof st.kind).toBeTruthy();
|
|
513
|
+
expect(["known", "absent", "unknown"]).toContain(st.kind);
|
|
514
|
+
if (st.kind === "known") expect(typeof st.type).toBe("string");
|
|
515
|
+
if (st.kind === "unknown") expect(typeof st.reason).toBe("string");
|
|
516
|
+
|
|
517
|
+
// 2026-10-31 —— 兼容字段 `license` 与三态之间的**配对约束**(外部复核在本仓指到的那个洞):
|
|
518
|
+
// `license: "none"` 同时表示 absent 与 unknown ⇒ 单看它无法支撑「是否商业授权」。
|
|
519
|
+
// 这一条把它的歧义**限定在一个范围内**:只有这两种状态才允许渲染成 "none";
|
|
520
|
+
// 反过来,known 时 "none" 绝不允许出现(那才是真的把「有授权」读成「没有」)。
|
|
521
|
+
const legacy = body.license;
|
|
522
|
+
if (legacy === "none") expect(["absent", "unknown"]).toContain(st.kind);
|
|
523
|
+
if (st.kind === "known") expect(legacy).not.toBe("none");
|
|
524
|
+
});
|
|
525
|
+
|
|
526
|
+
// 2026-10-31 —— 匿名投影必须是**白名单**:新字段默认不出现。
|
|
527
|
+
// 这条断言的是「每一个匿名可见的键都在白名单里」——
|
|
528
|
+
// 于是「忘了想」的结果是**少给**,不是泄露。
|
|
529
|
+
test("anonymous /health exposes ONLY allow-listed keys (new fields default to authenticated)", async () => {
|
|
530
|
+
const body = await (await fetch(`${BASE}/health`)).json() as any;
|
|
531
|
+
const { PUBLIC_HEALTH_KEYS } = await import("./server.js");
|
|
532
|
+
for (const key of Object.keys(body)) {
|
|
533
|
+
expect(PUBLIC_HEALTH_KEYS.has(key)).toBe(true);
|
|
534
|
+
}
|
|
535
|
+
// 两个敏感的典型:不进匿名投影。
|
|
536
|
+
expect("git_commit" in body).toBe(false);
|
|
537
|
+
expect("counters" in body).toBe(false);
|
|
538
|
+
expect("sse_sessions" in body).toBe(false);
|
|
539
|
+
|
|
540
|
+
// 2026-10-31 —— **witness 已做隔离版**(上一轮记的是「未验」,本轮转「已验」):
|
|
541
|
+
// 只在**鉴权分支**丢掉 sse_sessions(匿名投影一字未动)
|
|
542
|
+
// ⇒ 上面三条否定断言**全绿**("不存在"仍然成立),失败点恰好落在下面第 446 行的镜像上。
|
|
543
|
+
// ⇒ 这就是「否定断言单独的强度是零」的现场:它抓不住「鉴权侧丢键」,镜像抓得住。
|
|
544
|
+
//
|
|
545
|
+
// 2026-10-31 —— **否定断言必须配镜像**(外部复核:「一条否定断言单独的强度是零 ——
|
|
546
|
+
// 它和『这里什么都没有』无法区分」)。
|
|
547
|
+
// 上面三条都是「不出现在匿名里」;若投影实现坏成「什么都不给」,它们仍然全绿。
|
|
548
|
+
// ⇒ 镜像:同一 URL 在**鉴权态**下,这几个键必须真的出现。
|
|
549
|
+
const authed = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
550
|
+
expect("git_commit" in authed).toBe(true);
|
|
551
|
+
expect("counters" in authed).toBe(true);
|
|
552
|
+
expect("sse_sessions" in authed).toBe(true);
|
|
553
|
+
// 再强一格:鉴权投影必须**严格大于**匿名投影(否则「白名单」可能只是把两边都截了)
|
|
554
|
+
expect(Object.keys(authed).length).toBeGreaterThan(Object.keys(body).length);
|
|
555
|
+
});
|
|
556
|
+
|
|
557
|
+
// 2026-10-31 —— 内核口径的进程身份:与自报 startedAt 互为独立的第二条腿。
|
|
558
|
+
// 2026-10-31 修订 —— 原来这条写的是「两条腿一致才发布」,那是**让自报字段否决内核读数**。
|
|
559
|
+
// 现在:判据 = 内核三元组(无条件发布);展示 = kernel_started_at(永远带 agreement 标记);
|
|
560
|
+
// 不一致 = 一条独立读数(disagree + delta),**不再折成 null**。
|
|
561
|
+
test("kernel identity is the judgment basis; disagreement with the self-report is its own reading, not a null", async () => {
|
|
562
|
+
// 🔴 用**鉴权**响应:pid / boot_id / kernel_started_at 是「路标」不是「仪表」
|
|
563
|
+
// ⇒ 不在匿名白名单里(这条测试第一次就是因为读了匿名响应而红 —— 白名单生效了)。
|
|
564
|
+
const body = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
565
|
+
expect(body.pid).toBe(process.pid);
|
|
566
|
+
if (body.boot_id !== null) expect(String(body.boot_id)).toMatch(/^[0-9a-f-]{16,64}$/i);
|
|
567
|
+
expect(body.proc_start_ticks === null || typeof body.proc_start_ticks === "number").toBe(true);
|
|
568
|
+
|
|
569
|
+
// 判据三元组:pid 必须等于真值;boot_id 可读时必须合法 —— 二者都不依赖 startedAt
|
|
570
|
+
// 换算假设必须显式
|
|
571
|
+
// 一个叫 assumed 的字段必须有一条「它是否成立」的判定:
|
|
572
|
+
// 在 x86 上应当 confirmed;非 100 的架构上应当 derived;读不到才 assumed。
|
|
573
|
+
expect([100].includes(body.clk_tck_assumed) || Number.isInteger(body.clk_tck_assumed)).toBe(true);
|
|
574
|
+
expect(["confirmed", "derived", "assumed"]).toContain(body.clk_tck_source);
|
|
575
|
+
// 2026-10-31 —— confirmed 不能只说「相等」,必须报「差多少」+ 误差界;
|
|
576
|
+
// 而且差值大到不可能是舍入时,source 必须退回 assumed(典型成因:机器挂起过)。
|
|
577
|
+
if (body.clk_tck_source === "assumed") {
|
|
578
|
+
expect(body.clk_tck_source).toBe("assumed");
|
|
579
|
+
} else {
|
|
580
|
+
expect(typeof body.clk_tck_delta).toBe("number");
|
|
581
|
+
expect(typeof body.kernel_started_at_error_ms).toBe("number");
|
|
582
|
+
expect(Math.abs(body.clk_tck_delta)).toBeLessThan(0.01 * body.clk_tck_assumed);
|
|
583
|
+
}
|
|
584
|
+
expect(["agree", "disagree", "unknown"]).toContain(body.epoch_agreement);
|
|
585
|
+
|
|
586
|
+
if (body.kernel_started_at !== null) {
|
|
587
|
+
expect(typeof body.kernel_started_at).toBe("string");
|
|
588
|
+
expect(body.kernel_started_at_note).toBeNull();
|
|
589
|
+
// 🔴 关键:发布条件**不再**是「与自报一致」
|
|
590
|
+
// 实测这台机器上应当一致 ⇒ 断言的是一条**真实现象**,而不是发布条件的复述
|
|
591
|
+
const delta = Math.abs(Date.parse(body.kernel_started_at) - Date.parse(body.startedAt));
|
|
592
|
+
if (body.epoch_agreement === "agree") expect(delta).toBeLessThanOrEqual(10_000);
|
|
593
|
+
// 2026-10-31 —— 「两次读数相同」只证明相同,证明不了「它会变」:
|
|
594
|
+
// 一个写死的常量头与真的 startedAt 在那个测法下完全一样。
|
|
595
|
+
// 我们的独立生产者是**内核**:epoch_delta_ms = (btime + ticks/CLK_TCK) − startedAt。
|
|
596
|
+
// ⇒ 只有当 startedAt 与内核推出的时刻一致时,它才不是抄来的配置值。
|
|
597
|
+
if (body.epoch_agreement === "agree") {
|
|
598
|
+
expect(typeof body.epoch_delta_ms).toBe("number");
|
|
599
|
+
expect(Math.abs(body.epoch_delta_ms)).toBeLessThanOrEqual(10_000);
|
|
600
|
+
expect(body.kernel_started_at).not.toBeNull();
|
|
601
|
+
}
|
|
602
|
+
if (body.epoch_agreement === "disagree") {
|
|
603
|
+
// 分歧必须能被外部算出来:delta 与 agreement 同向,不能一个说 disagree 一个给个小 delta
|
|
604
|
+
expect(delta).toBeGreaterThan(10_000);
|
|
605
|
+
expect(typeof body.epoch_delta_ms).toBe("number");
|
|
606
|
+
}
|
|
607
|
+
} else {
|
|
608
|
+
// 算不出来时必须给出原因,不能是“静默的 null”
|
|
609
|
+
expect(typeof body.kernel_started_at_note).toBe("string");
|
|
610
|
+
expect(body.epoch_agreement).toBe("unknown");
|
|
611
|
+
}
|
|
612
|
+
});
|
|
613
|
+
|
|
614
|
+
// 否定断言必须配镜像肯定断言:上面允许 null,这条要求「在 Linux 上它必须不是 null」。
|
|
615
|
+
// 否则「永远给 null」也能满足上面那条。
|
|
616
|
+
test("on Linux the kernel trio is actually present (a permanent null would satisfy the test above)", async () => {
|
|
617
|
+
if (process.platform !== "linux") return;
|
|
618
|
+
const body = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
619
|
+
expect(body.boot_id).not.toBeNull();
|
|
620
|
+
expect(body.proc_start_ticks).not.toBeNull();
|
|
621
|
+
expect(body.kernel_started_at).not.toBeNull();
|
|
622
|
+
expect(body.epoch_agreement).not.toBe("unknown");
|
|
623
|
+
});
|
|
624
|
+
|
|
625
|
+
// 2026-10-31 —— `limits` 故意保持匿名(dashboard 上传代理开流前要读,且已在公开文档里),
|
|
626
|
+
// 但「故意公开」不等于「可以长东西」:它必须只有静态容量上限,不许出现路径/主机/用户。
|
|
627
|
+
test("anonymous `limits` carries ONLY static byte caps (public by decision, pinned in shape)", async () => {
|
|
628
|
+
const b = await (await fetch(`${BASE}/health`)).json() as any;
|
|
629
|
+
expect(Object.keys(b.limits).sort()).toEqual(["max_request_content_length", "max_upload_bytes"]);
|
|
630
|
+
for (const v of Object.values(b.limits)) expect(typeof v).toBe("number");
|
|
631
|
+
// 反例守卫:路径/用户名/主机名一类的字符串一旦混进来,这条会红
|
|
632
|
+
expect(JSON.stringify(b.limits)).not.toMatch(/\/|[A-Za-z]:\\|@/);
|
|
633
|
+
});
|
|
634
|
+
|
|
635
|
+
// 2026-10-31 —— 头集合断言:**与登录无关**的那条判据。
|
|
636
|
+
//
|
|
637
|
+
// 为什么需要它:凡是「需要会话才能判」的断言都会继承 vantage 病
|
|
638
|
+
// (未登录 CI 恒红 / 有会话环境恒绿 ⇒ 它测的是环境,不是代码)。
|
|
639
|
+
// 头集合不需要会话就能读 ⇒ 它回答的是「我站在哪一层」,而不是「我有没有登录」。
|
|
640
|
+
describe("header set (vantage-free: readable without a session)", () => {
|
|
641
|
+
test("anonymous /health does not leak build identity through headers", async () => {
|
|
642
|
+
const res = await fetch(`${BASE}/health`);
|
|
643
|
+
expect(res.status).toBe(200);
|
|
644
|
+
expect(res.headers.get("content-type") || "").toContain("application/json");
|
|
645
|
+
// 正文里我们只给 build_identified;头里更不能给指纹
|
|
646
|
+
const leaky = [...res.headers.keys()].filter((h) => /git|commit|build[-_]?(sha|id)/i.test(h));
|
|
647
|
+
expect(leaky).toEqual([]);
|
|
648
|
+
// 2026-10-31 —— 镜像必须针对**同一个属性在另一种条件下确实存在**,
|
|
649
|
+
// 而不是「这个响应是 JSON」(那只排除了取错对象)。
|
|
650
|
+
const authed = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
651
|
+
expect(typeof authed.git_commit).toBe("string"); // 同一 URL、登录态下确实有指纹
|
|
652
|
+
// ⇒ 于是「匿名不带」才是一个有对照的读数
|
|
653
|
+
});
|
|
654
|
+
|
|
655
|
+
test("version carries its role in the payload (a label, not a fingerprint)", async () => {
|
|
656
|
+
const body = await (await fetch(`${BASE}/health`)).json() as any;
|
|
657
|
+
expect(body.version_role).toBe("deployment_label");
|
|
658
|
+
// 反证:同一次响应里**没有**匿名可读的 commit(否则那条角色声明是多余的)
|
|
659
|
+
expect(body.git_commit).toBeUndefined();
|
|
660
|
+
});
|
|
661
|
+
});
|
|
662
|
+
|
|
663
|
+
// #3174 —— stall_count / last_stall_at 原来只有 [startedAt, now] 这个**隐含**窗口:
|
|
664
|
+
// 单独引用它,读者会把「计数器归零」读成「从未卡过」。
|
|
665
|
+
// ⇒ 现在窗口两端跟着读数一起走(event_loop.since / event_loop.observed_at)。
|
|
666
|
+
describe("event_loop carries its own window (no implicit [startedAt, now])", () => {
|
|
667
|
+
test("both ends are present, and they are ordered", async () => {
|
|
668
|
+
const body = await (await fetch(`${BASE}/health`)).json() as any;
|
|
669
|
+
expect(typeof body.event_loop.since).toBe("string");
|
|
670
|
+
expect(typeof body.event_loop.observed_at).toBe("string");
|
|
671
|
+
expect(Date.parse(body.event_loop.since)).toBeLessThanOrEqual(Date.parse(body.event_loop.observed_at));
|
|
672
|
+
});
|
|
673
|
+
|
|
674
|
+
// 敏感性:起点**不许**跟着时间走,终点**必须**跟着时间走。
|
|
675
|
+
// 只断言「两者可比」的话,一个冻结的时钟也能通过。
|
|
676
|
+
test("since is frozen while observed_at advances (difference, not just comparability)", async () => {
|
|
677
|
+
const a = (await (await fetch(`${BASE}/health`)).json() as any).event_loop;
|
|
678
|
+
const waitStart = Date.now();
|
|
679
|
+
await new Promise((r) => setTimeout(r, 250));
|
|
680
|
+
const b = (await (await fetch(`${BASE}/health`)).json() as any).event_loop;
|
|
681
|
+
const elapsed = Date.now() - waitStart;
|
|
682
|
+
|
|
683
|
+
expect(b.since).toBe(a.since); // 起点不动
|
|
684
|
+
const delta = Date.parse(b.observed_at) - Date.parse(a.observed_at);
|
|
685
|
+
expect(delta).toBeGreaterThan(0); // 终点真的走
|
|
686
|
+
expect(Math.abs(delta - elapsed)).toBeLessThanOrEqual(1000); // 且走的是同一个墙钟
|
|
687
|
+
});
|
|
688
|
+
});
|
|
689
|
+
|
|
690
|
+
// 2026-10-31 —— 「累计值 ÷ (now − since)」这个用法本身是错的,而且错法很隐蔽。
|
|
691
|
+
//
|
|
692
|
+
// 本仓的 counters.since **就等于 startedAt**(同一个字符串)⇒ 分母是 uptime,不是窗口长度。
|
|
693
|
+
// · 进程刚重启 ⇒ 分母趋近 0 ⇒ 比值巨大 ⇒ 与 flapping 长得一模一样
|
|
694
|
+
// 而「刚部署」比 flapping 常见得多 ⇒ **这条判据的主要阳性是正常状态**
|
|
695
|
+
// · 而且分子会被派去看它的人推动(如果那是应答计数)
|
|
696
|
+
// ⇒ 正确判据是**两次读数的差分**:S2 ≠ S1 ∧ (t2 − t1 很小),不需要除法。
|
|
697
|
+
//
|
|
698
|
+
// 这条测试不是「验证除法」,是**把那个事实钉住**:
|
|
699
|
+
// 哪一天有人给 counters 加了真正的窗口起点,这里会红,届时才允许重新讨论除法。
|
|
700
|
+
test("counters.since is the process start, so it is NOT a window length (denominator trap)", async () => {
|
|
701
|
+
const body = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
702
|
+
expect(body.counters.since).toBe(body.startedAt);
|
|
703
|
+
expect(body.counters.task_rejections.scope).toBe("process_lifetime");
|
|
704
|
+
});
|
|
705
|
+
|
|
706
|
+
// 2026-10-31 —— 304 会让「重启判据」假阳性:
|
|
707
|
+
// 若某层做协商缓存,304 会冻结 startedAt,而 counters 照涨 ⇒ 看起来像 flapping。
|
|
708
|
+
// ⇒ 探针必须显式拿到 200,且服务端必须禁止缓存。
|
|
709
|
+
test("health is never cacheable, and a conditional request still yields 200 (not 304)", async () => {
|
|
710
|
+
const plain = await fetch(`${BASE}/health`);
|
|
711
|
+
expect(plain.status).toBe(200);
|
|
712
|
+
// 2026-10-31 —— 「包含」不是值级:`toContain("no-store")` 允许
|
|
713
|
+
// `private, no-store, max-age=31536000`(两者矛盾)而不红,而「被加料」正是缓存头最危险的改法。
|
|
714
|
+
// 合法值唯一(就是 no-store)⇒ 用「等于」。
|
|
715
|
+
expect(plain.headers.get("cache-control")).toBe("no-store");
|
|
716
|
+
|
|
717
|
+
// 2026-10-31 —— 先分清「不可能 304」与「可能 304 但服务端拒绝了」:
|
|
718
|
+
// 没有 ETag 时,条件请求必然 200,那条断言是**空的**(vacuous),
|
|
719
|
+
// 而它与「实测过 304 不存在」在报告里长得一样。
|
|
720
|
+
const etag = plain.headers.get("etag");
|
|
721
|
+
if (etag === null) {
|
|
722
|
+
// 明确记录:本服务不产生 ETag ⇒ 304 在协议层不可能发生;这一格不靠条件请求证明。
|
|
723
|
+
expect(plain.headers.get("etag")).toBeNull();
|
|
724
|
+
}
|
|
725
|
+
const conditional = await fetch(`${BASE}/health`, {
|
|
726
|
+
headers: { "cache-control": "no-cache", "if-none-match": etag ?? "*" },
|
|
727
|
+
});
|
|
728
|
+
expect(conditional.status).toBe(200); // 304 会让 startedAt 冻结、counters 照涨 = 假 flapping
|
|
729
|
+
const body = await conditional.json() as any;
|
|
730
|
+
expect(typeof body.startedAt).toBe("string");
|
|
731
|
+
expect(typeof body.served_at).toBe("string");
|
|
732
|
+
});
|
|
733
|
+
|
|
734
|
+
// 2026-10-31 —— 「读不到」不许渲染成 0。
|
|
735
|
+
// 0 是一个合法值,而它会被当成事实;「0 个会话」与「读库失败」在读数上同形。
|
|
736
|
+
// 兄弟字段 status_reasons 里已有 db_unreadable ⇒ 两者一起读才完整。
|
|
737
|
+
test("sessions_count is a number when the DB is readable, and null (not 0) when it is not", async () => {
|
|
738
|
+
const b = await (await fetch(`${BASE}/health`)).json() as any;
|
|
739
|
+
const dbBad = Array.isArray(b.status_reasons) && b.status_reasons.includes("db_unreadable");
|
|
740
|
+
if (dbBad) {
|
|
741
|
+
expect(b.sessions_count).toBeNull();
|
|
742
|
+
} else {
|
|
743
|
+
expect(typeof b.sessions_count).toBe("number");
|
|
744
|
+
}
|
|
745
|
+
});
|
|
746
|
+
|
|
747
|
+
// 2026-10-31 —— 「200 那一格」必须有 body 判据:ok 恒 true 不等于健康。
|
|
748
|
+
// 与 counters.releases 同族:一个恒真的字段,读起来像「一切正常」。
|
|
749
|
+
test("status separates alive-but-degraded from all-normal (200 stays a promise, not a verdict)", async () => {
|
|
750
|
+
const res = await fetch(`${BASE}/health`);
|
|
751
|
+
expect(res.status).toBe(200); // 承诺不变
|
|
752
|
+
const b = await res.json() as any;
|
|
753
|
+
expect(["ok", "degraded"]).toContain(b.status);
|
|
754
|
+
expect(Array.isArray(b.status_reasons)).toBe(true);
|
|
755
|
+
if (b.status === "ok") expect(b.status_reasons).toEqual([]); // 两字段必须自洽
|
|
756
|
+
else expect(b.status_reasons.length).toBeGreaterThan(0);
|
|
757
|
+
expect(b.ok).toBe(true); // 兼容字段仍在,但不再承担判据
|
|
758
|
+
});
|
|
759
|
+
|
|
760
|
+
// 2026-10-31 —— 契约测试,不是碰撞测试:用**对抗输入**证明「不在白名单里就进不去」,
|
|
761
|
+
// 而不是去证明某个具体分隔符撞不撞。
|
|
762
|
+
// (外部复核的原话:只写「不能碰撞」的测试,测的是实现;契约是「键集恰好是这些」。)
|
|
763
|
+
test("adversarial keys (separator-in-name / extra / landmark) never survive the projection", () => {
|
|
764
|
+
const adversarial = {
|
|
765
|
+
"ok\u0000version": 1, // 含分隔符的键名:任何 join 方案都会在这里含糊
|
|
766
|
+
"ok,version": 2, // 逗号分隔符
|
|
767
|
+
ok: true, // 合法
|
|
768
|
+
git_commit: "deadbeef", // landmark:必须被丢
|
|
769
|
+
sessions_count: 3, // 合法
|
|
770
|
+
"__proto__": { polluted: true },// 原型污染形态
|
|
771
|
+
} as Record<string, unknown>;
|
|
772
|
+
const out = projectPublicHealth(adversarial);
|
|
773
|
+
const keys = Object.keys(out).sort();
|
|
774
|
+
// 断言的是**键集恰好**,不是「某些键被丢」—— 后者在「什么都丢」时也成立
|
|
775
|
+
expect(keys).toEqual(["ok", "sessions_count"]);
|
|
776
|
+
expect((out as any)["ok\u0000version"]).toBeUndefined();
|
|
777
|
+
expect(JSON.stringify(out)).not.toContain("polluted");
|
|
778
|
+
});
|
|
779
|
+
|
|
780
|
+
// 2026-10-31 —— 形状测试必须先证明**输入彼此不同**,否则它测的是同一个形状 N 次。
|
|
781
|
+
// 顺序不能反:先断言两两不等,再断言各自的行为。
|
|
782
|
+
// 2026-10-31 —— 夹具的身份写进**测试名**(每次运行都会打印、且不依赖测试通过)。
|
|
783
|
+
// 有人后加一份重复的 ⇒ 名字里的 sha 立刻变,diff 里就能看见,而不用等断言红。
|
|
784
|
+
const WITNESS_SET_SHA = createHash("sha256")
|
|
785
|
+
.update(JSON.stringify({ unknown_field: { ok: true }, landmark: { git_commit: "deadbeef" } }))
|
|
786
|
+
.digest("hex")
|
|
787
|
+
.slice(0, 8);
|
|
788
|
+
test(`the four projection witnesses are pairwise distinct inputs (fixtureset=${WITNESS_SET_SHA})`, () => {
|
|
789
|
+
const cases = {
|
|
790
|
+
unknown_field: { ok: true, future_issued_token: "abc" }, // 未登记 ⇒ 丢
|
|
791
|
+
landmark: { ok: true, git_commit: "deadbeef" }, // landmark ⇒ 丢
|
|
792
|
+
gauge: { ok: true, sessions_count: 3 }, // gauge ⇒ 留
|
|
793
|
+
echo: { probe_nonce: "n-1" }, // credential(echo) ⇒ 留
|
|
794
|
+
};
|
|
795
|
+
const serialized = Object.entries(cases).map(([k, v]) => [k, JSON.stringify(v)] as const);
|
|
796
|
+
// 2026-10-31 —— 报「哪一对相等」,不是只报「存在相等」。
|
|
797
|
+
// 只报「存在相等」时,红的人要在四份夹具里自己找,而他通常先怀疑新加的那份;
|
|
798
|
+
// 而问题可能在一份旧的里(旧的那份才是标准)。
|
|
799
|
+
const equalPairs: string[] = [];
|
|
800
|
+
for (let i = 0; i < serialized.length; i += 1) {
|
|
801
|
+
for (let j = i + 1; j < serialized.length; j += 1) {
|
|
802
|
+
if (serialized[i][1] === serialized[j][1]) {
|
|
803
|
+
equalPairs.push(`${serialized[i][0]} == ${serialized[j][0]}`);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
expect(equalPairs).toEqual([]);
|
|
808
|
+
// 2026-10-31 —— 这条前置断言自己也要有反例,否则它只是在数份数:
|
|
809
|
+
// 用「内容不同但长度相同」的对,证明判定按**内容**而不是按长度/份数。
|
|
810
|
+
const sameLenDifferent = [{ a: "xy" }, { a: "yz" }];
|
|
811
|
+
expect(JSON.stringify(sameLenDifferent[0]).length).toBe(JSON.stringify(sameLenDifferent[1]).length);
|
|
812
|
+
expect(JSON.stringify(sameLenDifferent[0])).not.toBe(JSON.stringify(sameLenDifferent[1]));
|
|
813
|
+
|
|
814
|
+
// 再断言各自行为(顺序与上面一致:先证输入不同,再看结果)
|
|
815
|
+
expect(Object.keys(projectPublicHealth(cases.unknown_field))).toEqual(["ok"]);
|
|
816
|
+
expect(Object.keys(projectPublicHealth(cases.landmark))).toEqual(["ok"]);
|
|
817
|
+
expect(Object.keys(projectPublicHealth(cases.gauge)).sort()).toEqual(["ok", "sessions_count"]);
|
|
818
|
+
expect(Object.keys(projectPublicHealth(cases.echo))).toEqual(["probe_nonce"]);
|
|
819
|
+
});
|
|
820
|
+
|
|
821
|
+
// 2026-10-31 —— 分类必须写出**谁不算**:形似启动快照但会变的那个字段。
|
|
822
|
+
// 读初始快照的判据只会漏报、不会误报;而它的失效形态与「真的没有」同形。
|
|
823
|
+
test("test_spawn_time_snapshot_family_excludes_the_one_field_that_must_change", async () => {
|
|
824
|
+
const { HEALTH_FIELD_META } = await import("./server.js");
|
|
825
|
+
// 分子:至少 5 个被明确标成启动快照(今天:startedAt / git_commit / boot_id / pid / proc_start_ticks / kernel_started_at)
|
|
826
|
+
const frozen = Object.entries(HEALTH_FIELD_META).filter(([, m]) => m.frozen_at_boot === true).map(([k]) => k);
|
|
827
|
+
expect(frozen.length).toBeGreaterThanOrEqual(5);
|
|
828
|
+
// 例外必须显式:served_at 长得一模一样,但它会变。
|
|
829
|
+
// ⚠️ 但「不被冻结」只是一个**否定**,它在很多实现上都成立(没打标 / 标打错 / 字段不存在)。
|
|
830
|
+
// ⇒ 它的正面断言在别处:「served_at actually advances with the wall clock」——
|
|
831
|
+
// 那条要求**连续两次读数不同**,是「必须变」而不是「没有被打标」。
|
|
832
|
+
expect(frozen).not.toContain("served_at");
|
|
833
|
+
expect(HEALTH_FIELD_META.served_at.frozen_at_boot).toBeUndefined();
|
|
834
|
+
});
|
|
835
|
+
|
|
836
|
+
// 2026-10-31 —— credential 的「可对账性」是**字段取值**,不是注释里的辩论。
|
|
837
|
+
test("joinability decides anonymity, not the reader's interpretation", async () => {
|
|
838
|
+
const { HEALTH_FIELD_META, mayBePublic } = await import("./server.js");
|
|
839
|
+
const creds = Object.entries(HEALTH_FIELD_META).filter(([, m]) => m.class === "credential");
|
|
840
|
+
expect(creds.length).toBeGreaterThan(0); // 分母非空
|
|
841
|
+
const bad = creds.filter(([, m]) => m.joinability !== "echo_only" && mayBePublic(m)).map(([k]) => k);
|
|
842
|
+
expect(bad).toEqual([]); // 服务端生成的一律不可匿名
|
|
843
|
+
expect(HEALTH_FIELD_META.probe_nonce.joinability).toBe("echo_only");
|
|
844
|
+
});
|
|
845
|
+
|
|
846
|
+
// 2026-10-31 —— gauge 的粒度词表是**封闭枚举**,且必须分清「电平」与「累积」。
|
|
847
|
+
// 一个电平不能算速率,一个累积不能回答「现在怎么样」——两者在 JSON 里都是数字。
|
|
848
|
+
describe("granularity vocabulary is closed and distinguishes level from cumulative", () => {
|
|
849
|
+
test("every gauge declares one of level/cumulative/instant/label/boolean/verdict", async () => {
|
|
850
|
+
const { HEALTH_FIELD_META } = await import("./server.js");
|
|
851
|
+
const allowed = ["level", "cumulative", "instant", "label", "boolean", "verdict"];
|
|
852
|
+
const bad = Object.entries(HEALTH_FIELD_META)
|
|
853
|
+
.filter(([, m]) => m.class === "gauge" && !allowed.includes(String(m.granularity)))
|
|
854
|
+
.map(([k, m]) => `${k}=${m.granularity}`);
|
|
855
|
+
expect(bad).toEqual([]);
|
|
856
|
+
// 分母非空:这一条今天必须有东西可查
|
|
857
|
+
expect(Object.values(HEALTH_FIELD_META).filter((m) => m.class === "gauge").length).toBeGreaterThan(20);
|
|
858
|
+
});
|
|
859
|
+
|
|
860
|
+
// 2026-10-31 —— verdict 与 label 的差别只有一条,但它是致命的:
|
|
861
|
+
// label 是描述("streamable-http")⇒ 为常量无害
|
|
862
|
+
// verdict 是判定("ok"/"degraded")⇒ 若另一支不可观测,它就不是判定而是装饰
|
|
863
|
+
// 起因:一次复核提议给 /health 加 `ptyWsAttached`,而 attach 在 listen 回调里无条件执行
|
|
864
|
+
// ⇒ true 恒成立、false 不可观测 ⇒ 这个字段永远只有一个读数,正是被审的「一侧不可达」缺陷本身。
|
|
865
|
+
// 2026-10-31 —— **身份三分类,且恰好一个权威**(外部复核:产物属性 / 调用属性 / 声明)。
|
|
866
|
+
// 「三类混在一起且不标注,就是『六个身份』的根。」
|
|
867
|
+
test("identity fields carry a class; exactly one artifact-class authority", async () => {
|
|
868
|
+
const { HEALTH_FIELD_META } = await import("./server.js");
|
|
869
|
+
const rows = Object.entries(HEALTH_FIELD_META).filter(([, m]: any) => m.identity_class);
|
|
870
|
+
const cls = (r: [string, any]) => r[1].identity_class;
|
|
871
|
+
// 三类都必须有代表(否则分类只是给已有字段贴了个词)
|
|
872
|
+
for (const want of ["artifact", "call", "declaration"]) {
|
|
873
|
+
expect(rows.filter((r) => cls(r as [string, any]) === want).length).toBeGreaterThanOrEqual(1);
|
|
874
|
+
}
|
|
875
|
+
// **恰好一个 artifact 类权威** —— 两个权威等于回到「谁说了算」
|
|
876
|
+
expect(rows.filter((r) => cls(r as [string, any]) === "artifact").length).toBe(1);
|
|
877
|
+
// 有 call 类覆盖时,必须同时存在 artifact 类(否则「怎么被启动的」在冒充「跑的是什么」)
|
|
878
|
+
if (rows.some((r) => cls(r as [string, any]) === "call")) {
|
|
879
|
+
expect(rows.some((r) => cls(r as [string, any]) === "artifact")).toBe(true);
|
|
880
|
+
}
|
|
881
|
+
});
|
|
882
|
+
|
|
883
|
+
// 2026-10-31 —— **身份是从哪个根读的**(外部复核那条:release 读的是 cwd,不是可执行文件目录)。
|
|
884
|
+
// 我们优先模块目录,只在拿不到时退回 cwd —— 但若没有字段说明是哪一支,
|
|
885
|
+
// 「读到的是本包的身份」与「读到的是启动目录里另一个仓库」在载荷上完全同形。
|
|
886
|
+
test("git identity says which root it came from (module_dir vs cwd)", async () => {
|
|
887
|
+
const b = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
888
|
+
expect(["module_dir", "cwd"]).toContain(b.git_identity_root);
|
|
889
|
+
// 从 cwd 读出来的身份,必须显式承认它不是制品身份
|
|
890
|
+
if (b.git_identity_root === "cwd") {
|
|
891
|
+
expect(b.build_identity_note === null || typeof b.build_identity_note === "string").toBe(true);
|
|
892
|
+
}
|
|
893
|
+
// 反向:有 commit 却说不出来源 ⇒ 这条断言不允许
|
|
894
|
+
if (b.git_commit) expect(["module_dir", "cwd"]).toContain(b.git_identity_root);
|
|
895
|
+
});
|
|
896
|
+
|
|
897
|
+
// 2026-10-31 —— **每个 verdict 都要有仲裁字段**(外部复核那条:
|
|
898
|
+
// 「每个问题一个权威字段 + 一个仲裁字段」)。
|
|
899
|
+
// 只有权威字段时,读者无法区分「结论是对的」与「检查没跑」。
|
|
900
|
+
test("every verdict declares an arbiter field that is actually in the payload", async () => {
|
|
901
|
+
const full = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
902
|
+
const verdicts = Object.entries(HEALTH_FIELD_META).filter(([, m]: any) => m.granularity === "verdict");
|
|
903
|
+
expect(verdicts.length).toBeGreaterThanOrEqual(4);
|
|
904
|
+
for (const [k, m] of verdicts as Array<[string, any]>) {
|
|
905
|
+
expect(typeof m.arbiter).toBe("string");
|
|
906
|
+
expect(m.arbiter.length).toBeGreaterThan(2);
|
|
907
|
+
// 仲裁字段必须在同一个载荷里(否则读者还得再发一次请求,那就不是仲裁而是推测)
|
|
908
|
+
expect(Object.prototype.hasOwnProperty.call(full, m.arbiter)).toBe(true);
|
|
909
|
+
// 不能自己仲裁自己
|
|
910
|
+
expect(m.arbiter).not.toBe(k);
|
|
911
|
+
}
|
|
912
|
+
});
|
|
913
|
+
|
|
914
|
+
test("every verdict names how to make the OTHER branch fire", async () => {
|
|
915
|
+
const { HEALTH_FIELD_META } = await import("./server.js");
|
|
916
|
+
// HEALTH_FIELD_META 覆盖**两个投影**(匿名 + 鉴权)⇒ 存在性要对着完整那份查。
|
|
917
|
+
const full = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
918
|
+
const anon = await (await fetch(`${BASE}/health`)).json() as any;
|
|
919
|
+
const verdicts = Object.entries(HEALTH_FIELD_META).filter(([, m]) => m.granularity === "verdict");
|
|
920
|
+
// 分母非空:今天至少要有这么多真判定,否则这条门是装饰
|
|
921
|
+
expect(verdicts.length).toBeGreaterThanOrEqual(4);
|
|
922
|
+
for (const [k, m] of verdicts) {
|
|
923
|
+
expect((m.verdict_other_branch ?? "").length).toBeGreaterThanOrEqual(20);
|
|
924
|
+
// 判定必须真的在载荷里(不许给不存在的字段配说明)
|
|
925
|
+
expect(Object.prototype.hasOwnProperty.call(full, k)).toBe(true);
|
|
926
|
+
}
|
|
927
|
+
// 匿名/鉴权的边界也钉住:新增一个 verdict 时必须**显式决定**它匿不匿名,
|
|
928
|
+
// 否则它会静默地默认进匿名载荷(或默认被滤掉,而没人注意到)。
|
|
929
|
+
const anonVerdicts = verdicts.map(([k]) => k)
|
|
930
|
+
.filter((k) => Object.prototype.hasOwnProperty.call(anon, k)).sort();
|
|
931
|
+
expect(anonVerdicts).toEqual(["build_identified", "license_state", "status"]);
|
|
932
|
+
});
|
|
933
|
+
|
|
934
|
+
// 反面:断言自己是常量的字段,必须给出「另一支为什么不会出现」,并且**真的还是那个常量**。
|
|
935
|
+
test("fields declared constant-by-design still read as that constant", async () => {
|
|
936
|
+
const { HEALTH_FIELD_META } = await import("./server.js");
|
|
937
|
+
const b = await (await fetch(`${BASE}/health`)).json() as any;
|
|
938
|
+
const claimed: Record<string, unknown> = {
|
|
939
|
+
ok: true,
|
|
940
|
+
api_version: "v3",
|
|
941
|
+
transport: "streamable-http",
|
|
942
|
+
version_role: "deployment_label",
|
|
943
|
+
v3_auth: true,
|
|
944
|
+
multi_network: true,
|
|
945
|
+
};
|
|
946
|
+
for (const [k, want] of Object.entries(claimed)) {
|
|
947
|
+
const m = (HEALTH_FIELD_META as any)[k];
|
|
948
|
+
expect((m.constant_by_design ?? "").length).toBeGreaterThanOrEqual(20);
|
|
949
|
+
expect(b[k]).toBe(want);
|
|
950
|
+
}
|
|
951
|
+
// 反例守卫:一条「常量」若其实是可变的,claim 就写错了 ⇒ 这里会红
|
|
952
|
+
expect(b.status).toBe("ok");
|
|
953
|
+
});
|
|
954
|
+
|
|
955
|
+
test("the two that people confuse are labelled right (peak is cumulative, inflight is a level)", async () => {
|
|
956
|
+
const { HEALTH_FIELD_META } = await import("./server.js");
|
|
957
|
+
expect(HEALTH_FIELD_META.mcp_inflight_peak.granularity).toBe("cumulative");
|
|
958
|
+
expect(HEALTH_FIELD_META.mcp_inflight.granularity).toBe("level");
|
|
959
|
+
expect(HEALTH_FIELD_META.uptime.granularity).toBe("cumulative");
|
|
960
|
+
});
|
|
961
|
+
});
|
|
962
|
+
|
|
963
|
+
// 2026-10-31 —— 规则:「每个可为 null 的字段都必须有一个能解释它的兄弟字段。」
|
|
964
|
+
// 反过来:不许用 false 冒充「不知道」—— git_dirty=false 读起来是「干净树」。
|
|
965
|
+
describe("nullable fields carry an explainer", () => {
|
|
966
|
+
test("git identity: committed ⇒ note null & dirty boolean; absent ⇒ note non-null & dirty null", async () => {
|
|
967
|
+
const b = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
968
|
+
if (b.git_commit !== null) {
|
|
969
|
+
expect(b.build_identity_note).toBeNull();
|
|
970
|
+
expect(typeof b.git_dirty).toBe("boolean");
|
|
971
|
+
} else {
|
|
972
|
+
expect(typeof b.build_identity_note).toBe("string");
|
|
973
|
+
expect(b.git_dirty).toBeNull(); // 不知道 ≠ 干净
|
|
974
|
+
}
|
|
975
|
+
});
|
|
976
|
+
|
|
977
|
+
test("kernel_started_at has its explainer sibling (already true, pinned so it stays true)", async () => {
|
|
978
|
+
const b = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
979
|
+
if (b.kernel_started_at === null) expect(typeof b.kernel_started_at_note).toBe("string");
|
|
980
|
+
else expect(b.kernel_started_at_note).toBeNull();
|
|
981
|
+
});
|
|
982
|
+
});
|
|
983
|
+
|
|
984
|
+
// 2026-10-31 —— 三分类从「注释里的提醒」变成「字段上的必填标签」。
|
|
985
|
+
//
|
|
986
|
+
// 原来的问题:probe_nonce 恰好是对的,但那是因为**恰好这样写**;
|
|
987
|
+
// 「凭证类要慎给」这四个字在代码里没有任何东西能检查。
|
|
988
|
+
// ⇒ 现在每个字段必填一档,匿名合法与否由这一档推出来。
|
|
989
|
+
describe("field classification is machine-checked, not documentation", () => {
|
|
990
|
+
test("every field in the authenticated body carries a class (no untagged field may exist)", async () => {
|
|
991
|
+
const body = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
992
|
+
const untagged = Object.keys(body).filter((k) => !HEALTH_FIELD_META[k]);
|
|
993
|
+
expect(untagged).toEqual([]); // 空数组 ⇒ 没有「加字段忘了分类」的路
|
|
994
|
+
});
|
|
995
|
+
|
|
996
|
+
test("nothing in the anonymous whitelist is a landmark or a server-issued credential", () => {
|
|
997
|
+
const illegal = [...PUBLIC_HEALTH_KEYS].filter((k) => !mayBePublic(HEALTH_FIELD_META[k]));
|
|
998
|
+
expect(illegal).toEqual([]);
|
|
999
|
+
});
|
|
1000
|
+
|
|
1001
|
+
test("no landmark field actually appears in the anonymous body (the rule has a witness today: git_commit/pid/boot_id)", async () => {
|
|
1002
|
+
const authBody = await (await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${adminToken}` } })).json() as any;
|
|
1003
|
+
const anonBody = await (await fetch(`${BASE}/health`)).json() as any;
|
|
1004
|
+
const landmarks = Object.keys(HEALTH_FIELD_META).filter((k) => HEALTH_FIELD_META[k].class === "landmark");
|
|
1005
|
+
// 分母:这份断言今天必须有分子可看,否则它是空的。
|
|
1006
|
+
// 2026-10-31 —— 分母**写死今天的数**(不是在运行时重算),这样:
|
|
1007
|
+
// 有人把某个字段从 landmark 改成 gauge ⇒ 分母下降 ⇒ 这里先红。
|
|
1008
|
+
// 若只检查「一个都不出现」,那次改动会让断言**更容易通过**。
|
|
1009
|
+
const present = landmarks.filter((k) => k in authBody).length;
|
|
1010
|
+
expect(present).toBeGreaterThanOrEqual(5);
|
|
1011
|
+
expect(landmarks.filter((k) => k in anonBody)).toEqual([]);
|
|
1012
|
+
});
|
|
1013
|
+
|
|
1014
|
+
// 合成体见证:将来有人加一个「我们生成的凭证」字段,这一条必须红。
|
|
1015
|
+
test("projection drops unknown fields and landmarks; keeps only gauge + caller-supplied echo (synthetic witness)", () => {
|
|
1016
|
+
const out = projectPublicHealth({
|
|
1017
|
+
ok: true,
|
|
1018
|
+
git_commit: "deadbeef",
|
|
1019
|
+
future_issued_token: "abc123", // 没登记 ⇒ 未分类 ⇒ 丢掉(默认安全方向)
|
|
1020
|
+
probe_nonce: "n-1", // 请求方自带 ⇒ 保留
|
|
1021
|
+
});
|
|
1022
|
+
expect(out).toEqual({ ok: true, probe_nonce: "n-1" });
|
|
1023
|
+
});
|
|
1024
|
+
});
|
|
1025
|
+
|
|
1026
|
+
// 2026-10-31 —— 白名单的另一半:**无死条目**。
|
|
1027
|
+
//
|
|
1028
|
+
// 已有的那条断言「匿名响应里每个键都在白名单内」防的是泄露;
|
|
1029
|
+
// 缺的这半边防的是「死条目」:白名单里的键若早就不再出现(改名/删除),
|
|
1030
|
+
// 它却一直躺在那里,看起来「这个字段是公开的」⇒ 下一个人把同名字段加回来时**默认就是公开的**。
|
|
1031
|
+
// ⇒ 白名单会从「审批记录」退化成「历史残留」。
|
|
1032
|
+
// 这与今晚那条镜像规则同构:否定断言必须配肯定断言,否则前者可被「永远不给」满足。
|
|
1033
|
+
test("no dead entries: every allow-listed key is actually served to anonymous callers", async () => {
|
|
1034
|
+
const { PUBLIC_HEALTH_KEYS } = await import("./server.js");
|
|
1035
|
+
const plain = await (await fetch(`${BASE}/health`)).json() as any;
|
|
1036
|
+
// 条件出现的键(只在带 X-Probe-Nonce 时出现)要在第二种请求里核对
|
|
1037
|
+
const probed = await (await fetch(`${BASE}/health`, { headers: { "X-Probe-Nonce": "dead-entry-check" } })).json() as any;
|
|
1038
|
+
const seen = new Set([...Object.keys(plain), ...Object.keys(probed)]);
|
|
1039
|
+
const dead = [...PUBLIC_HEALTH_KEYS].filter((k) => !seen.has(k));
|
|
1040
|
+
// 2026-10-31 —— 失败时必须点名(外部复核 ③):只说 `toEqual([])` 的失败信息里
|
|
1041
|
+
// 没有「是哪几个键」,而修它需要的正是那几个名字。
|
|
1042
|
+
if (dead.length) {
|
|
1043
|
+
throw new Error(
|
|
1044
|
+
`白名单里有 ${dead.length} 个键在任何投影里都不出现(死条目):${dead.join(", ")}\n` +
|
|
1045
|
+
" ⇒ 要么从 PUBLIC_HEALTH_KEYS 删掉,要么让 body 真的产出它;" +
|
|
1046
|
+
"留着等于给未来的同名字段预授权。",
|
|
1047
|
+
);
|
|
1048
|
+
}
|
|
1049
|
+
expect(dead).toEqual([]);
|
|
1050
|
+
});
|
|
1051
|
+
|
|
1052
|
+
test("exposes stable upload limits anonymously without exposing topology", async () => {
|
|
1053
|
+
const res = await fetch(`${BASE}/health`);
|
|
1054
|
+
expect(res.status).toBe(200);
|
|
1055
|
+
const body = await res.json() as any;
|
|
1056
|
+
expect(body.limits).toEqual({
|
|
1057
|
+
max_upload_bytes: MAX_UPLOAD_BYTES,
|
|
1058
|
+
max_request_content_length: MAX_REQUEST_CONTENT_LENGTH,
|
|
1059
|
+
});
|
|
1060
|
+
expect(body.limits.max_request_content_length).toBeGreaterThan(body.limits.max_upload_bytes);
|
|
1061
|
+
});
|
|
1062
|
+
|
|
1063
|
+
// 2026-10-31 —— 「这一次」的判据。
|
|
1064
|
+
//
|
|
1065
|
+
// /health 恒 200,所以「200」不证明是这台机器、这个进程、更不证明是**这个请求**。
|
|
1066
|
+
// 缓存层 / 前面的代理 / 上一次运行留下的响应,都给同一个 200。
|
|
1067
|
+
// 请求方带随机 nonce ⇒ 回显 ⇔ 这个响应生成于收到这个请求之后。
|
|
1068
|
+
test("echoes a caller-supplied probe nonce so 'this very request' is provable", async () => {
|
|
1069
|
+
const nonce = `p-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
|
|
1070
|
+
const res = await fetch(`${BASE}/health`, { headers: { "X-Probe-Nonce": nonce } });
|
|
1071
|
+
expect(res.status).toBe(200);
|
|
1072
|
+
expect(res.headers.get("cache-control")).toBe("no-store");
|
|
1073
|
+
const body = await res.json() as any;
|
|
1074
|
+
expect(body.probe_nonce).toBe(nonce);
|
|
1075
|
+
// 🔴 served_at 的断言只到「可解析」——它**不证明新鲜**,也不参与任何判据。
|
|
1076
|
+
// 真正证明“这一次”的是 probe_nonce(缓存不可能为它生成响应)。
|
|
1077
|
+
// 这里把它标清楚,否则它就会变成下一个 startedAt:看着像证据,却没有消费者。
|
|
1078
|
+
const servedAt = Date.parse(body.served_at);
|
|
1079
|
+
expect(Number.isFinite(servedAt)).toBe(true);
|
|
1080
|
+
expect(servedAt).toBeGreaterThan(0);
|
|
1081
|
+
});
|
|
1082
|
+
|
|
1083
|
+
// 三件套的第③件:nonce 必须也出现在**响应之外**(服务端日志)。
|
|
1084
|
+
// 判据:一次探针之后,日志里该 nonce 出现**恰好 1 次**。
|
|
1085
|
+
// == 1 ⇒ 这次请求真的到了这个进程(中间层伪造不了服务端日志)
|
|
1086
|
+
// == 0 ⇒ 缺日志
|
|
1087
|
+
// > 1 ⇒ 有人复用了同一个 nonce(重试没换)⇒ 那次读数不可信
|
|
1088
|
+
test("logs the probe nonce exactly once, outside the response", async () => {
|
|
1089
|
+
const nonce = `log-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
|
|
1090
|
+
const seen: string[] = [];
|
|
1091
|
+
const original = console.log;
|
|
1092
|
+
console.log = (...args: unknown[]) => {
|
|
1093
|
+
const line = args.map(String).join(" ");
|
|
1094
|
+
if (line.includes(nonce)) seen.push(line);
|
|
1095
|
+
original(...args);
|
|
1096
|
+
};
|
|
1097
|
+
try {
|
|
1098
|
+
const res = await fetch(`${BASE}/health`, { headers: { "X-Probe-Nonce": nonce } });
|
|
1099
|
+
await res.json();
|
|
1100
|
+
} finally {
|
|
1101
|
+
console.log = original;
|
|
1102
|
+
}
|
|
1103
|
+
expect(seen.length).toBe(1);
|
|
1104
|
+
expect(seen[0]).toContain("[health] probe nonce=");
|
|
1105
|
+
});
|
|
1106
|
+
|
|
1107
|
+
// 2026-10-31 —— 上面那条 `== 1` 需要一个**镜像**,否则它只在「日志存在」时成立,
|
|
1108
|
+
// 而在「日志被去重」时同样成立 —— 而去重恰好会毁掉 ==1 判据的全部价值:
|
|
1109
|
+
// 判据里的 `> 1` 只有在「复用会被记两次」时才能被发现。
|
|
1110
|
+
// ⇒ 一个看起来无害的优化(同一 nonce 只打一行、或加个 seen 集合)会让复用永远读成「新鲜」。
|
|
1111
|
+
test("reusing the same nonce logs TWICE (so `>1` can actually fire)", async () => {
|
|
1112
|
+
const nonce = `reuse-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
|
|
1113
|
+
const seen: string[] = [];
|
|
1114
|
+
const original = console.log;
|
|
1115
|
+
console.log = (...args: unknown[]) => {
|
|
1116
|
+
const line = args.map(String).join(" ");
|
|
1117
|
+
if (line.includes(nonce)) seen.push(line);
|
|
1118
|
+
original(...args);
|
|
1119
|
+
};
|
|
1120
|
+
try {
|
|
1121
|
+
for (let i = 0; i < 2; i++) {
|
|
1122
|
+
const res = await fetch(`${BASE}/health`, { headers: { "X-Probe-Nonce": nonce } });
|
|
1123
|
+
await res.json();
|
|
1124
|
+
}
|
|
1125
|
+
} finally {
|
|
1126
|
+
console.log = original;
|
|
1127
|
+
}
|
|
1128
|
+
expect(seen.length).toBe(2); // 去重实现会让这条红 —— 那是故意的
|
|
1129
|
+
});
|
|
1130
|
+
|
|
1131
|
+
test("two distinct nonces are each logged once (no cross-talk)", async () => {
|
|
1132
|
+
const mk = () => `pair-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
|
|
1133
|
+
const a = mk(); const b = mk();
|
|
1134
|
+
const seen: string[] = [];
|
|
1135
|
+
const original = console.log;
|
|
1136
|
+
console.log = (...args: unknown[]) => {
|
|
1137
|
+
const line = args.map(String).join(" ");
|
|
1138
|
+
if (line.includes("pair-")) seen.push(line);
|
|
1139
|
+
original(...args);
|
|
1140
|
+
};
|
|
1141
|
+
try {
|
|
1142
|
+
await (await fetch(`${BASE}/health`, { headers: { "X-Probe-Nonce": a } })).json();
|
|
1143
|
+
await (await fetch(`${BASE}/health`, { headers: { "X-Probe-Nonce": b } })).json();
|
|
1144
|
+
} finally {
|
|
1145
|
+
console.log = original;
|
|
1146
|
+
}
|
|
1147
|
+
expect(seen.filter(l => l.includes(a)).length).toBe(1);
|
|
1148
|
+
expect(seen.filter(l => l.includes(b)).length).toBe(1);
|
|
1149
|
+
});
|
|
1150
|
+
|
|
1151
|
+
// 2026-10-31 —— served_at 变成**常驻**:窗口的两端必须在同一个时钟域里。
|
|
1152
|
+
// 没有它,读者只能拿自己的钟去减 since ⇒ 偷偷假设两边时钟一致。
|
|
1153
|
+
// 而 probe_nonce 仍然只在带 X-Probe-Nonce 时出现(它是“这一次”的凭据)。
|
|
1154
|
+
test("default /health always carries served_at (same clock domain) but never probe_nonce", async () => {
|
|
1155
|
+
const res = await fetch(`${BASE}/health`);
|
|
1156
|
+
const body = await res.json() as any;
|
|
1157
|
+
expect("probe_nonce" in body).toBe(false);
|
|
1158
|
+
expect(typeof body.served_at).toBe("string");
|
|
1159
|
+
const served = Date.parse(body.served_at);
|
|
1160
|
+
expect(Number.isFinite(served)).toBe(true);
|
|
1161
|
+
// 同一时钟域:served_at 不早于进程起点,且两次读数单调不减。
|
|
1162
|
+
expect(served).toBeGreaterThanOrEqual(Date.parse(body.startedAt));
|
|
1163
|
+
const second = await (await fetch(`${BASE}/health`)).json() as any;
|
|
1164
|
+
expect(Date.parse(second.served_at)).toBeGreaterThanOrEqual(served);
|
|
1165
|
+
// 2026-10-31 修订:**一律 no-store**。原来只在带 nonce 时设,
|
|
1166
|
+
// 而 /health 每个字段都是「此刻的读数」——304 会冻结 startedAt 而 counters 照涨,
|
|
1167
|
+
// 那正是 flapping 的假阳性形状。断言方向随之从 null 改成必须存在。
|
|
1168
|
+
expect(res.headers.get("cache-control")).toBe("no-store");
|
|
1169
|
+
});
|
|
1170
|
+
|
|
1171
|
+
test("refuses a nonce it cannot echo verbatim instead of half-accepting it", async () => {
|
|
1172
|
+
// 注意:非 ASCII 那类(如「中文」)到不了这一层 —— fetch/undici 在**发送端**
|
|
1173
|
+
// 就拒绝非 token 的 header 值。所以这里只用能被发出去的非法值。
|
|
1174
|
+
for (const bad of ["has space", "semi;colon", "a".repeat(65)]) {
|
|
1175
|
+
const res = await fetch(`${BASE}/health`, { headers: { "X-Probe-Nonce": bad } });
|
|
1176
|
+
const body = await res.json() as any;
|
|
1177
|
+
// 半接受会造出「看起来回显了、其实被改过」的值 —— 比不回显更糟。
|
|
1178
|
+
expect("probe_nonce" in body).toBe(false);
|
|
1179
|
+
}
|
|
1180
|
+
});
|
|
1181
|
+
|
|
94
1182
|
test("CLI count source stays truthful: health.sse_connections == /api/stats/sse total (no fake 0)", async () => {
|
|
95
1183
|
// The CLI's `anet doctor` line reads health.sse_connections now
|
|
96
1184
|
// (was Object.keys(sse_sessions).length). This pins that aggregate to
|
|
@@ -115,6 +1203,76 @@ describe("#473 anonymous /health — watchdog contract intact, no topology leak"
|
|
|
115
1203
|
});
|
|
116
1204
|
});
|
|
117
1205
|
|
|
1206
|
+
describe("f28a6c1b /health sse_sessions — auth-gated restoration for dashboard 'online' widget", () => {
|
|
1207
|
+
// The dashboard's server-side Next.js proxy (agent-network-dashboard
|
|
1208
|
+
// `app/api/hub/health/route.ts` → `hubFetch('/health')`) forwards the
|
|
1209
|
+
// logged-in user's V3 utok_ as `Authorization: Bearer …`. Anonymous
|
|
1210
|
+
// callers (public watchdog, internet strangers) still get NO
|
|
1211
|
+
// sse_sessions — that leak stays closed. Authenticated callers get
|
|
1212
|
+
// the sessions map scoped to their networks (ops sees all).
|
|
1213
|
+
|
|
1214
|
+
test("regular member with valid utok_: sse_sessions present, filtered to member's networks", async () => {
|
|
1215
|
+
const res = await fetch(`${BASE}/health`, {
|
|
1216
|
+
headers: { Authorization: `Bearer ${userToken}` },
|
|
1217
|
+
});
|
|
1218
|
+
expect(res.status).toBe(200);
|
|
1219
|
+
const body = await res.json() as any;
|
|
1220
|
+
// Field must be present when authenticated — otherwise dashboard
|
|
1221
|
+
// "online" widget shows 0.
|
|
1222
|
+
expect("sse_sessions" in body).toBe(true);
|
|
1223
|
+
// Must contain the member's own SSE connection key.
|
|
1224
|
+
const ownKey = `${userNetworkId}:${userName}`;
|
|
1225
|
+
expect(body.sse_sessions[ownKey]).toBeGreaterThanOrEqual(1);
|
|
1226
|
+
// Watchdog aggregate contract unchanged.
|
|
1227
|
+
expect(body.sse_connections).toBeGreaterThanOrEqual(1);
|
|
1228
|
+
});
|
|
1229
|
+
|
|
1230
|
+
test("admin with valid utok_: sse_sessions present, full unfiltered map (ops parity with /api/stats/sse)", async () => {
|
|
1231
|
+
const res = await fetch(`${BASE}/health`, {
|
|
1232
|
+
headers: { Authorization: `Bearer ${adminToken}` },
|
|
1233
|
+
});
|
|
1234
|
+
expect(res.status).toBe(200);
|
|
1235
|
+
const body = await res.json() as any;
|
|
1236
|
+
expect("sse_sessions" in body).toBe(true);
|
|
1237
|
+
// Admin sees the member's key even though they live in a different
|
|
1238
|
+
// network (admin scope spans everything, same as /api/stats/sse).
|
|
1239
|
+
const memberKey = `${userNetworkId}:${userName}`;
|
|
1240
|
+
expect(body.sse_sessions[memberKey]).toBeGreaterThanOrEqual(1);
|
|
1241
|
+
// Sanity: admin's view must match the auth-gated ops endpoint.
|
|
1242
|
+
const opsRes = await fetch(`${BASE}/api/stats/sse`, {
|
|
1243
|
+
headers: { Authorization: `Bearer ${adminToken}` },
|
|
1244
|
+
});
|
|
1245
|
+
const ops = await opsRes.json() as any;
|
|
1246
|
+
expect(body.sse_sessions).toEqual(ops.sessions);
|
|
1247
|
+
});
|
|
1248
|
+
|
|
1249
|
+
test("anonymous still gets NO sse_sessions (leak stays closed, mutation-red witness)", async () => {
|
|
1250
|
+
// This is the mutation-red assertion for the auth gate: if the
|
|
1251
|
+
// handler stops distinguishing anonymous from authenticated and
|
|
1252
|
+
// starts including sse_sessions unconditionally, this test turns
|
|
1253
|
+
// RED. Distinct from the older `does NOT expose SSE key detail`
|
|
1254
|
+
// test — that one guards against any regression restoring the
|
|
1255
|
+
// OLD unconditional leak; this one guards against a well-meaning
|
|
1256
|
+
// "just always send it if authenticated is optional" bug.
|
|
1257
|
+
const res = await fetch(`${BASE}/health`);
|
|
1258
|
+
const body = await res.json() as any;
|
|
1259
|
+
expect("sse_sessions" in body).toBe(false);
|
|
1260
|
+
});
|
|
1261
|
+
|
|
1262
|
+
test("invalid/garbage token: treated as anonymous — no sse_sessions", async () => {
|
|
1263
|
+
const res = await fetch(`${BASE}/health`, {
|
|
1264
|
+
headers: { Authorization: "Bearer utok_completely_fake_nonexistent" },
|
|
1265
|
+
});
|
|
1266
|
+
expect(res.status).toBe(200);
|
|
1267
|
+
const body = await res.json() as any;
|
|
1268
|
+
// resolveRequestAuth returns null for unresolvable tokens, so the
|
|
1269
|
+
// handler must NOT fall through to "authenticated" branch. Otherwise
|
|
1270
|
+
// a bad token would degrade to "anonymous with sse_sessions" — that
|
|
1271
|
+
// would be the leak in a different disguise.
|
|
1272
|
+
expect("sse_sessions" in body).toBe(false);
|
|
1273
|
+
});
|
|
1274
|
+
});
|
|
1275
|
+
|
|
118
1276
|
describe("#473 GET /api/stats/sse — detail survives, behind ops auth", () => {
|
|
119
1277
|
test("anonymous → 401", async () => {
|
|
120
1278
|
const res = await fetch(`${BASE}/api/stats/sse`);
|
|
@@ -174,3 +1332,426 @@ describe("#473 GET /api/stats/sse — detail survives, behind ops auth", () => {
|
|
|
174
1332
|
expect(r.healthHasSseSessions).toBe(false); // /health still redacted with a token set
|
|
175
1333
|
}, 20_000);
|
|
176
1334
|
});
|
|
1335
|
+
|
|
1336
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
1337
|
+
// CR3 (4703b0e7) — M1-M7 matrix tests
|
|
1338
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
1339
|
+
//
|
|
1340
|
+
// Independent audit on aef48a3d showed the existing f28a6c1b tests
|
|
1341
|
+
// pinned only the "anonymous vs authenticated" gate. The reviewer
|
|
1342
|
+
// mutated `scopedSessions = sse.sessions` (unconditional) and got
|
|
1343
|
+
// 11/11 green — meaning the *tenant-scope* invariant (a member sees
|
|
1344
|
+
// only their own networks, cross-network is invisible) was not
|
|
1345
|
+
// witnessed by any assertion, and a future refactor that broke the
|
|
1346
|
+
// filter would ship silently.
|
|
1347
|
+
//
|
|
1348
|
+
// This block adds explicit tests for every shape the fork's auth
|
|
1349
|
+
// decision distinguishes:
|
|
1350
|
+
// M1: utok_ member sees own network's sessions
|
|
1351
|
+
// M2: utok_ member does NOT see other network's sessions
|
|
1352
|
+
// M3: ntok_ (network-scoped token) is forced to the token's bound
|
|
1353
|
+
// network — the user's other networks are invisible even
|
|
1354
|
+
// though the underlying user is a member
|
|
1355
|
+
// M4: same user, utok_ vs ntok_ — utok_ sees union, ntok_ sees only
|
|
1356
|
+
// the token's bound network (mutation-red for the ntok_
|
|
1357
|
+
// "healthAuth.networkId ? [...] : db.all(...)" branch)
|
|
1358
|
+
// M5: membership revocation invalidates visibility immediately —
|
|
1359
|
+
// no cache; the next /health request reflects new membership
|
|
1360
|
+
// M6: observer keys (shape `\0netobs:<networkId>`; the getSSEStats
|
|
1361
|
+
// serializer renders leading NUL as printable `\\0`) are
|
|
1362
|
+
// classified through the shared PRINTABLE_OBSERVER_KEY_PREFIX
|
|
1363
|
+
// constant, not a re-typed literal. Mutation-red for the
|
|
1364
|
+
// constant drift (server.ts had `"netobs:"` without `\\0`
|
|
1365
|
+
// before this CR, so all observer keys silently fell through).
|
|
1366
|
+
// M7: two networks with the same alias — invisibility survives
|
|
1367
|
+
// key collision. Explicit assertion; M1/M2 hide-cover this
|
|
1368
|
+
// implicitly but M7 makes the property visible in review.
|
|
1369
|
+
describe("f28a6c1b CR3 — network-scoped filter matrix (M1-M7)", () => {
|
|
1370
|
+
let mUserAToken = "";
|
|
1371
|
+
let mUserANet = "";
|
|
1372
|
+
let mUserAName = "";
|
|
1373
|
+
let mUserBToken = "";
|
|
1374
|
+
let mUserBNet = "";
|
|
1375
|
+
let mUserBName = "";
|
|
1376
|
+
let mAliceToken = ""; // utok_ (user-scoped)
|
|
1377
|
+
let mAliceNtok = ""; // ntok_ bound to mAliceNet
|
|
1378
|
+
let mAliceNet = "";
|
|
1379
|
+
let mAliceName = "";
|
|
1380
|
+
let mCarolToken = "";
|
|
1381
|
+
let mCarolNet = "";
|
|
1382
|
+
let mCarolName = "";
|
|
1383
|
+
let mUserAId = "";
|
|
1384
|
+
let mAliceId = "";
|
|
1385
|
+
let mCarolId = "";
|
|
1386
|
+
let mSameAliasName = ""; // used by M7 — two sessions, one per network
|
|
1387
|
+
|
|
1388
|
+
const openReaders: ReadableStreamDefaultReader<Uint8Array>[] = [];
|
|
1389
|
+
|
|
1390
|
+
const startSse = async (base: string, name: string, netId: string, token: string) => {
|
|
1391
|
+
const res = await fetch(`${base}/events/${encodeURIComponent(name)}?network_id=${netId}`, {
|
|
1392
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
1393
|
+
});
|
|
1394
|
+
if (res.status !== 200) throw new Error(`SSE subscribe failed (${res.status}) for ${name}@${netId}`);
|
|
1395
|
+
const reader = res.body!.getReader();
|
|
1396
|
+
await reader.read();
|
|
1397
|
+
openReaders.push(reader);
|
|
1398
|
+
return reader;
|
|
1399
|
+
};
|
|
1400
|
+
|
|
1401
|
+
const startObserverSse = async (base: string, netId: string, token: string) => {
|
|
1402
|
+
// The observer endpoint is /events/network/:networkId — carries no
|
|
1403
|
+
// per-agent alias; server registers with the special observer key
|
|
1404
|
+
// shape `\0netobs:<networkId>` (see push.ts observerKey()).
|
|
1405
|
+
const res = await fetch(`${base}/events/network/${encodeURIComponent(netId)}`, {
|
|
1406
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
1407
|
+
});
|
|
1408
|
+
if (res.status !== 200) throw new Error(`observer SSE subscribe failed (${res.status}) for ${netId}`);
|
|
1409
|
+
const reader = res.body!.getReader();
|
|
1410
|
+
await reader.read();
|
|
1411
|
+
openReaders.push(reader);
|
|
1412
|
+
return reader;
|
|
1413
|
+
};
|
|
1414
|
+
|
|
1415
|
+
beforeAll(async () => {
|
|
1416
|
+
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1000)}`;
|
|
1417
|
+
const pw = "BootstrapPw123Aa!";
|
|
1418
|
+
|
|
1419
|
+
// userA — own network, plain member
|
|
1420
|
+
mUserAName = `cr3_userA_${suffix}`;
|
|
1421
|
+
const rA = register(mUserAName, pw, undefined, "seed");
|
|
1422
|
+
if (!rA.ok || !rA.token || !rA.network_id) throw new Error("userA register failed");
|
|
1423
|
+
mUserAToken = rA.token;
|
|
1424
|
+
mUserANet = rA.network_id;
|
|
1425
|
+
db.run("UPDATE users SET role = 'user' WHERE username = ?1", [mUserAName]);
|
|
1426
|
+
mUserAId = db.get<{ user_id: string }>("SELECT user_id FROM users WHERE username = ?1", [mUserAName])!.user_id;
|
|
1427
|
+
|
|
1428
|
+
// userB — different own network, plain member
|
|
1429
|
+
mUserBName = `cr3_userB_${suffix}`;
|
|
1430
|
+
const rB = register(mUserBName, pw, undefined, "seed");
|
|
1431
|
+
if (!rB.ok || !rB.token || !rB.network_id) throw new Error("userB register failed");
|
|
1432
|
+
mUserBToken = rB.token;
|
|
1433
|
+
mUserBNet = rB.network_id;
|
|
1434
|
+
db.run("UPDATE users SET role = 'user' WHERE username = ?1", [mUserBName]);
|
|
1435
|
+
|
|
1436
|
+
// alice — own network + will also be added to userA's N_A, so
|
|
1437
|
+
// membership set = { mAliceNet (owner), mUserANet (member) }.
|
|
1438
|
+
// Her ntok_ (from register) is bound to mAliceNet only — the M3/M4
|
|
1439
|
+
// scope-enforcement test target.
|
|
1440
|
+
mAliceName = `cr3_alice_${suffix}`;
|
|
1441
|
+
const rAl = register(mAliceName, pw, undefined, "seed");
|
|
1442
|
+
if (!rAl.ok || !rAl.token || !rAl.network_token || !rAl.network_id) throw new Error("alice register failed");
|
|
1443
|
+
mAliceToken = rAl.token;
|
|
1444
|
+
mAliceNtok = rAl.network_token;
|
|
1445
|
+
mAliceNet = rAl.network_id;
|
|
1446
|
+
db.run("UPDATE users SET role = 'user' WHERE username = ?1", [mAliceName]);
|
|
1447
|
+
mAliceId = db.get<{ user_id: string }>("SELECT user_id FROM users WHERE username = ?1", [mAliceName])!.user_id;
|
|
1448
|
+
// 多用户 Agent 权限:新成员默认只看授权 Agent;本测试测的是「完全信任的成员」旧语义,显式 agent_access=all。
|
|
1449
|
+
const addAlice = addNetworkMember(mUserANet, mAliceId, "member", mUserAId, { agentAccess: "all" });
|
|
1450
|
+
if (!addAlice.ok) throw new Error("addNetworkMember(alice→N_A) failed: " + addAlice.error);
|
|
1451
|
+
|
|
1452
|
+
// carol — own network + will also be added to N_A, then revoked
|
|
1453
|
+
// in M5.
|
|
1454
|
+
mCarolName = `cr3_carol_${suffix}`;
|
|
1455
|
+
const rC = register(mCarolName, pw, undefined, "seed");
|
|
1456
|
+
if (!rC.ok || !rC.token || !rC.network_id) throw new Error("carol register failed");
|
|
1457
|
+
mCarolToken = rC.token;
|
|
1458
|
+
mCarolNet = rC.network_id;
|
|
1459
|
+
db.run("UPDATE users SET role = 'user' WHERE username = ?1", [mCarolName]);
|
|
1460
|
+
mCarolId = db.get<{ user_id: string }>("SELECT user_id FROM users WHERE username = ?1", [mCarolName])!.user_id;
|
|
1461
|
+
const addCarol = addNetworkMember(mUserANet, mCarolId, "member", mUserAId, { agentAccess: "all" });
|
|
1462
|
+
if (!addCarol.ok) throw new Error("addNetworkMember(carol→N_A) failed: " + addCarol.error);
|
|
1463
|
+
|
|
1464
|
+
// Live SSE sessions — one per network — so the filter has real
|
|
1465
|
+
// keys to include/exclude.
|
|
1466
|
+
await startSse(BASE, mUserAName, mUserANet, mUserAToken);
|
|
1467
|
+
await startSse(BASE, mUserBName, mUserBNet, mUserBToken);
|
|
1468
|
+
await startSse(BASE, mAliceName, mAliceNet, mAliceToken);
|
|
1469
|
+
await startSse(BASE, mCarolName, mCarolNet, mCarolToken);
|
|
1470
|
+
|
|
1471
|
+
// M6 — observer stream for N_A (produces `\0netobs:<mUserANet>` key)
|
|
1472
|
+
await startObserverSse(BASE, mUserANet, mUserAToken);
|
|
1473
|
+
|
|
1474
|
+
// M7 note: The dashboard-user SSE gate only lets a caller subscribe
|
|
1475
|
+
// as their own username (path 3, gate 4a). Standing up two sessions
|
|
1476
|
+
// named the same alias in two different networks would need two
|
|
1477
|
+
// separate "helper" users per network — significantly larger setup
|
|
1478
|
+
// than the property we're testing. M1/M2 already witness the shape
|
|
1479
|
+
// invariant (`<netId>:<alias>` keying) that would defeat collision:
|
|
1480
|
+
// cross-network same-alias would land at `<N_A>:<alias>` vs
|
|
1481
|
+
// `<N_B>:<alias>`, and M2's `expect(body.sse_sessions[<N_B>:...]).toBeUndefined()`
|
|
1482
|
+
// pins exactly the "wrong-tenant key is invisible" property. M7 is
|
|
1483
|
+
// therefore covered structurally; skipping the physical fixture.
|
|
1484
|
+
mSameAliasName = "";
|
|
1485
|
+
});
|
|
1486
|
+
|
|
1487
|
+
afterAll(() => {
|
|
1488
|
+
for (const r of openReaders) { try { r.cancel(); } catch {} }
|
|
1489
|
+
});
|
|
1490
|
+
|
|
1491
|
+
// ── M1 + M2 — utok_ member sees own network only ────────────────
|
|
1492
|
+
test("M1: utok_ member of N_A sees N_A sessions", async () => {
|
|
1493
|
+
const res = await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${mUserAToken}` } });
|
|
1494
|
+
expect(res.status).toBe(200);
|
|
1495
|
+
const body = await res.json() as any;
|
|
1496
|
+
expect("sse_sessions" in body).toBe(true);
|
|
1497
|
+
expect(body.sse_sessions[`${mUserANet}:${mUserAName}`]).toBeGreaterThanOrEqual(1);
|
|
1498
|
+
});
|
|
1499
|
+
|
|
1500
|
+
test("M2: utok_ member of N_A does NOT see N_B sessions (cross-network invisibility)", async () => {
|
|
1501
|
+
const res = await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${mUserAToken}` } });
|
|
1502
|
+
const body = await res.json() as any;
|
|
1503
|
+
expect("sse_sessions" in body).toBe(true);
|
|
1504
|
+
// The N_B session (userB's own network) must not surface here —
|
|
1505
|
+
// this is the assertion the reviewer's "delete member filter"
|
|
1506
|
+
// mutation must break (currently was silently green).
|
|
1507
|
+
expect(body.sse_sessions[`${mUserBNet}:${mUserBName}`]).toBeUndefined();
|
|
1508
|
+
});
|
|
1509
|
+
|
|
1510
|
+
test("M2b: utok_ member of N_B sees own but not N_A (reverse of M2)", async () => {
|
|
1511
|
+
const res = await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${mUserBToken}` } });
|
|
1512
|
+
const body = await res.json() as any;
|
|
1513
|
+
expect(body.sse_sessions[`${mUserBNet}:${mUserBName}`]).toBeGreaterThanOrEqual(1);
|
|
1514
|
+
expect(body.sse_sessions[`${mUserANet}:${mUserAName}`]).toBeUndefined();
|
|
1515
|
+
});
|
|
1516
|
+
|
|
1517
|
+
// ── M3 + M4 — ntok_ single-network enforce ──────────────────────
|
|
1518
|
+
test("M3: alice utok_ (user-scoped) sees union — both mAliceNet and mUserANet", async () => {
|
|
1519
|
+
const res = await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${mAliceToken}` } });
|
|
1520
|
+
expect(res.status).toBe(200);
|
|
1521
|
+
const body = await res.json() as any;
|
|
1522
|
+
expect(body.sse_sessions[`${mAliceNet}:${mAliceName}`]).toBeGreaterThanOrEqual(1);
|
|
1523
|
+
expect(body.sse_sessions[`${mUserANet}:${mUserAName}`]).toBeGreaterThanOrEqual(1);
|
|
1524
|
+
});
|
|
1525
|
+
|
|
1526
|
+
test("M4: alice ntok_ (network-scoped, bound to mAliceNet) sees ONLY mAliceNet — N_A invisible even though she is a member", async () => {
|
|
1527
|
+
// This is the CR3 P1 fix's mutation-red target: if the /health
|
|
1528
|
+
// filter falls through to the `db.all(...)` union for ntok_
|
|
1529
|
+
// callers (i.e. drops the `healthAuth.networkId ? [...] : ...`
|
|
1530
|
+
// branch), this test flips because alice would suddenly see
|
|
1531
|
+
// mUserANet sessions through a token that only granted mAliceNet.
|
|
1532
|
+
const res = await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${mAliceNtok}` } });
|
|
1533
|
+
expect(res.status).toBe(200);
|
|
1534
|
+
const body = await res.json() as any;
|
|
1535
|
+
expect("sse_sessions" in body).toBe(true);
|
|
1536
|
+
// Own network — must be present.
|
|
1537
|
+
expect(body.sse_sessions[`${mAliceNet}:${mAliceName}`]).toBeGreaterThanOrEqual(1);
|
|
1538
|
+
// The other network she belongs to — ntok_ must NOT show it.
|
|
1539
|
+
expect(body.sse_sessions[`${mUserANet}:${mUserAName}`]).toBeUndefined();
|
|
1540
|
+
// Sanity: an unrelated network she's not in must also be absent.
|
|
1541
|
+
expect(body.sse_sessions[`${mUserBNet}:${mUserBName}`]).toBeUndefined();
|
|
1542
|
+
});
|
|
1543
|
+
|
|
1544
|
+
// ── M5 — membership revocation invalidates visibility ───────────
|
|
1545
|
+
test("M5: removing carol from N_A → next /health hides N_A sessions", async () => {
|
|
1546
|
+
// Pre-revocation: carol utok_ sees own network + N_A (userA lives
|
|
1547
|
+
// in N_A). Filter is per-request, no cache — so a revoke followed
|
|
1548
|
+
// by an immediate /health must reflect the new state.
|
|
1549
|
+
const before = await (await fetch(`${BASE}/health`, {
|
|
1550
|
+
headers: { Authorization: `Bearer ${mCarolToken}` },
|
|
1551
|
+
})).json() as any;
|
|
1552
|
+
expect(before.sse_sessions[`${mCarolNet}:${mCarolName}`]).toBeGreaterThanOrEqual(1);
|
|
1553
|
+
expect(before.sse_sessions[`${mUserANet}:${mUserAName}`]).toBeGreaterThanOrEqual(1);
|
|
1554
|
+
|
|
1555
|
+
const rm = removeNetworkMember(mUserANet, mCarolId);
|
|
1556
|
+
if (!rm.ok) throw new Error("revoke failed: " + rm.error);
|
|
1557
|
+
|
|
1558
|
+
const after = await (await fetch(`${BASE}/health`, {
|
|
1559
|
+
headers: { Authorization: `Bearer ${mCarolToken}` },
|
|
1560
|
+
})).json() as any;
|
|
1561
|
+
expect(after.sse_sessions[`${mCarolNet}:${mCarolName}`]).toBeGreaterThanOrEqual(1);
|
|
1562
|
+
// The revoked N_A must be gone. Mutation-red for any caching of
|
|
1563
|
+
// the memberNets Set across requests.
|
|
1564
|
+
expect(after.sse_sessions[`${mUserANet}:${mUserAName}`]).toBeUndefined();
|
|
1565
|
+
});
|
|
1566
|
+
|
|
1567
|
+
// ── M6 — observer key format via shared constant ────────────────
|
|
1568
|
+
test("M6: observer keys (\\0netobs:<net>) are classified through the shared prefix constant, member sees own network's observer entry", async () => {
|
|
1569
|
+
const res = await fetch(`${BASE}/health`, {
|
|
1570
|
+
headers: { Authorization: `Bearer ${mUserAToken}` },
|
|
1571
|
+
});
|
|
1572
|
+
const body = await res.json() as any;
|
|
1573
|
+
// Observer key surfaces with the printable prefix (`\\0netobs:`)
|
|
1574
|
+
// because push.ts's printableKey renders the NUL byte as `\\0`.
|
|
1575
|
+
// The filter must classify this as belonging to `mUserANet` and
|
|
1576
|
+
// include it in userA's view.
|
|
1577
|
+
const observerKey = `\\0netobs:${mUserANet}`;
|
|
1578
|
+
expect(body.sse_sessions[observerKey]).toBeGreaterThanOrEqual(1);
|
|
1579
|
+
});
|
|
1580
|
+
|
|
1581
|
+
test("M6b: userB (not in N_A) does NOT see N_A's observer key — mutation-red for prefix constant drift", async () => {
|
|
1582
|
+
const res = await fetch(`${BASE}/health`, {
|
|
1583
|
+
headers: { Authorization: `Bearer ${mUserBToken}` },
|
|
1584
|
+
});
|
|
1585
|
+
const body = await res.json() as any;
|
|
1586
|
+
const observerKey = `\\0netobs:${mUserANet}`;
|
|
1587
|
+
// If the prefix constant drifts (e.g. server.ts checks "netobs:"
|
|
1588
|
+
// without `\\0`), the classifier falls through to `key.split(":")[0]`
|
|
1589
|
+
// which for a `\\0netobs:` key returns the literal `\\0netobs` string
|
|
1590
|
+
// — that would never match memberNets, so the observer key gets
|
|
1591
|
+
// over-filtered but silently. That is the pre-CR3 bug shape;
|
|
1592
|
+
// this assertion pins the "not in wrong tenant's view" side.
|
|
1593
|
+
expect(body.sse_sessions[observerKey]).toBeUndefined();
|
|
1594
|
+
});
|
|
1595
|
+
|
|
1596
|
+
// M7 removed — see beforeAll note. Cross-network same-alias
|
|
1597
|
+
// invisibility is covered structurally by M1/M2: keys are
|
|
1598
|
+
// `<netId>:<alias>`, so a `<N_A>:foo` vs `<N_B>:foo` collision
|
|
1599
|
+
// resolves via network prefix, which is what M2's cross-network
|
|
1600
|
+
// absence assertion already pins.
|
|
1601
|
+
});
|
|
1602
|
+
|
|
1603
|
+
// ── #506 — same alias, two networks: /health sse_sessions must not cross ──
|
|
1604
|
+
//
|
|
1605
|
+
// #505 restored auth-gated `sse_sessions`. Its member filter parses the
|
|
1606
|
+
// `{networkId}:{alias}` key prefix and keeps only the caller's networks.
|
|
1607
|
+
// That was verified at merge time by a standalone validator, but a
|
|
1608
|
+
// validator does not re-run on future refactors — this pins it.
|
|
1609
|
+
//
|
|
1610
|
+
// Construction: the dashboard-user SSE gate only lets a caller subscribe
|
|
1611
|
+
// to its own username (gate 4a), so two users can never share one key that
|
|
1612
|
+
// way. Gate 4b is the usable path: any member may subscribe to an alias
|
|
1613
|
+
// that exists as a session IN THEIR network. So we seed a session row with
|
|
1614
|
+
// the SAME alias in two different networks and have each network's own
|
|
1615
|
+
// member subscribe to it — producing `{N_A}:{alias}` and `{N_B}:{alias}`
|
|
1616
|
+
// live at once, which is exactly the collision the filter must separate.
|
|
1617
|
+
//
|
|
1618
|
+
// Mutation-red (verified by hand, see the PR): replacing the member filter
|
|
1619
|
+
// with `scopedSessions = sse.sessions` turns the two "must NOT contain the
|
|
1620
|
+
// other network's key" assertions red.
|
|
1621
|
+
describe("#506 cross-network isolation of /health sse_sessions (same alias, two networks)", () => {
|
|
1622
|
+
const SHARED_ALIAS = "shared-alias-506";
|
|
1623
|
+
let aToken = "", aNet = "", aName = "";
|
|
1624
|
+
let bToken = "", bNet = "", bName = "";
|
|
1625
|
+
let readerA: ReadableStreamDefaultReader<Uint8Array> | null = null;
|
|
1626
|
+
let readerB: ReadableStreamDefaultReader<Uint8Array> | null = null;
|
|
1627
|
+
|
|
1628
|
+
beforeAll(async () => {
|
|
1629
|
+
const sfx = `${Date.now()}_${Math.floor(Math.random() * 1000)}`;
|
|
1630
|
+
const pw = "BootstrapPw123Aa!";
|
|
1631
|
+
|
|
1632
|
+
// Probe users are registered AFTER the suite's seed user, so neither is
|
|
1633
|
+
// the auto-admin first user. Asserted below rather than assumed: an
|
|
1634
|
+
// admin caller takes the unfiltered branch and would make these tests
|
|
1635
|
+
// pass while proving nothing.
|
|
1636
|
+
const ra = register(`h506_a_${sfx}`, pw, undefined, "seed");
|
|
1637
|
+
const rb = register(`h506_b_${sfx}`, pw, undefined, "seed");
|
|
1638
|
+
if (!ra.ok || !ra.token || !rb.ok || !rb.token) throw new Error("506 register failed");
|
|
1639
|
+
aName = `h506_a_${sfx}`; aToken = ra.token; aNet = ra.network_id ?? "";
|
|
1640
|
+
bName = `h506_b_${sfx}`; bToken = rb.token; bNet = rb.network_id ?? "";
|
|
1641
|
+
if (!aNet || !bNet || aNet === bNet) throw new Error("506 needs two distinct networks");
|
|
1642
|
+
db.run("UPDATE users SET role = 'user' WHERE username IN (?1, ?2)", [aName, bName]);
|
|
1643
|
+
|
|
1644
|
+
// Same alias name, one session row per network → gate 4b lets each
|
|
1645
|
+
// network's own member subscribe to it.
|
|
1646
|
+
for (const [net, tag] of [[aNet, "a"], [bNet, "b"]] as const) {
|
|
1647
|
+
db.run(
|
|
1648
|
+
`INSERT INTO sessions (resume_id, alias, network_id, last_seen_at, status)
|
|
1649
|
+
VALUES (?1, ?2, ?3, datetime('now'), 'idle')`,
|
|
1650
|
+
[`s_506_${tag}_${sfx}`, SHARED_ALIAS, net],
|
|
1651
|
+
);
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
const sub = async (token: string, net: string) => {
|
|
1655
|
+
const res = await fetch(
|
|
1656
|
+
`${BASE}/events/${encodeURIComponent(SHARED_ALIAS)}?network_id=${encodeURIComponent(net)}`,
|
|
1657
|
+
{ headers: { Authorization: `Bearer ${token}` } },
|
|
1658
|
+
);
|
|
1659
|
+
if (res.status !== 200) throw new Error(`506 SSE subscribe failed (${net}): ${res.status}`);
|
|
1660
|
+
const rd = res.body!.getReader();
|
|
1661
|
+
await rd.read(); // connected frame → key registered
|
|
1662
|
+
return rd;
|
|
1663
|
+
};
|
|
1664
|
+
readerA = await sub(aToken, aNet);
|
|
1665
|
+
readerB = await sub(bToken, bNet);
|
|
1666
|
+
});
|
|
1667
|
+
|
|
1668
|
+
afterAll(() => {
|
|
1669
|
+
try { readerA?.cancel(); } catch {}
|
|
1670
|
+
try { readerB?.cancel(); } catch {}
|
|
1671
|
+
});
|
|
1672
|
+
|
|
1673
|
+
test("probe users are NOT admin (an admin caller would bypass the filter and prove nothing)", () => {
|
|
1674
|
+
for (const n of [aName, bName]) {
|
|
1675
|
+
const row = db.get<{ role: string }>("SELECT role FROM users WHERE username = ?1", n);
|
|
1676
|
+
expect(row?.role).not.toBe("admin");
|
|
1677
|
+
}
|
|
1678
|
+
});
|
|
1679
|
+
|
|
1680
|
+
test("both same-alias keys are live at once (the collision actually exists)", async () => {
|
|
1681
|
+
// Read through the ops endpoint with the admin token: if this shows only
|
|
1682
|
+
// one of the two keys, the fixture never built the collision and the
|
|
1683
|
+
// isolation assertions below would be vacuous.
|
|
1684
|
+
const res = await fetch(`${BASE}/api/stats/sse`, { headers: { Authorization: `Bearer ${adminToken}` } });
|
|
1685
|
+
expect(res.status).toBe(200);
|
|
1686
|
+
const body = await res.json() as { sessions?: Record<string, number> };
|
|
1687
|
+
const keys = Object.keys(body.sessions ?? {});
|
|
1688
|
+
expect(keys).toContain(`${aNet}:${SHARED_ALIAS}`);
|
|
1689
|
+
expect(keys).toContain(`${bNet}:${SHARED_ALIAS}`);
|
|
1690
|
+
});
|
|
1691
|
+
|
|
1692
|
+
test("member of network A sees only A's copy of the shared alias", async () => {
|
|
1693
|
+
const res = await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${aToken}` } });
|
|
1694
|
+
expect(res.status).toBe(200);
|
|
1695
|
+
const body = await res.json() as { sse_sessions?: Record<string, number> };
|
|
1696
|
+
expect(body.sse_sessions).toBeDefined();
|
|
1697
|
+
const keys = Object.keys(body.sse_sessions!);
|
|
1698
|
+
expect(keys).toContain(`${aNet}:${SHARED_ALIAS}`);
|
|
1699
|
+
expect(keys).not.toContain(`${bNet}:${SHARED_ALIAS}`);
|
|
1700
|
+
// Nothing from the other network at all, by any key shape.
|
|
1701
|
+
expect(keys.some((k) => k.startsWith(`${bNet}:`))).toBe(false);
|
|
1702
|
+
});
|
|
1703
|
+
|
|
1704
|
+
test("member of network B sees only B's copy (reverse direction)", async () => {
|
|
1705
|
+
const res = await fetch(`${BASE}/health`, { headers: { Authorization: `Bearer ${bToken}` } });
|
|
1706
|
+
expect(res.status).toBe(200);
|
|
1707
|
+
const body = await res.json() as { sse_sessions?: Record<string, number> };
|
|
1708
|
+
expect(body.sse_sessions).toBeDefined();
|
|
1709
|
+
const keys = Object.keys(body.sse_sessions!);
|
|
1710
|
+
expect(keys).toContain(`${bNet}:${SHARED_ALIAS}`);
|
|
1711
|
+
expect(keys).not.toContain(`${aNet}:${SHARED_ALIAS}`);
|
|
1712
|
+
expect(keys.some((k) => k.startsWith(`${aNet}:`))).toBe(false);
|
|
1713
|
+
});
|
|
1714
|
+
});
|
|
1715
|
+
|
|
1716
|
+
// #2149 —— 错误路径**不能回显凭据**。
|
|
1717
|
+
//
|
|
1718
|
+
// 背景:2026-10-23 TMA云鲸 对 CommHub MCP 做只读扫描时收到 502,代理生成的
|
|
1719
|
+
// 非 JSON 错误页把本次请求的鉴权相关头回显在正文里。那个 502 页很可能来自
|
|
1720
|
+
// 调用链上的代理(本仓没有 502 生成逻辑),但**这条防线必须在本仓也有**:
|
|
1721
|
+
// 任何 4xx/5xx 的响应体都不该把调用方递上来的 `Authorization` / `Cookie` /
|
|
1722
|
+
// query 里的 token 原样吐回去 —— 一旦有人写出这种错误文案,它就会进日志、
|
|
1723
|
+
// 进回执、进诊断归档。
|
|
1724
|
+
//
|
|
1725
|
+
// 做法是**注入一个形状像真凭据的 canary**,然后打一圈错误路径,断言响应正文
|
|
1726
|
+
// 里一次都不出现它。canary 用 `ntok_` 前缀,正是本仓 `redactTokens` 认得的形状。
|
|
1727
|
+
describe("#2149 error paths never echo credentials", () => {
|
|
1728
|
+
const CANARY = "ntok_LEAKCANARY_0123456789abcdef";
|
|
1729
|
+
const COOKIE = "session=COOKIELEAKCANARY0123456789";
|
|
1730
|
+
|
|
1731
|
+
const paths: Array<{ method: string; path: string; body?: string }> = [
|
|
1732
|
+
{ method: "GET", path: "/api/nope-not-a-route" },
|
|
1733
|
+
{ method: "GET", path: "/api/requirements" },
|
|
1734
|
+
{ method: "GET", path: "/api/nodes" },
|
|
1735
|
+
{ method: "POST", path: "/mcp", body: "{not json" },
|
|
1736
|
+
{ method: "POST", path: "/api/auth/login", body: JSON.stringify({ username: "nobody", password: "wrong-password-Aa1!" }) },
|
|
1737
|
+
{ method: "POST", path: "/api/auth/me/avatar/upload" },
|
|
1738
|
+
];
|
|
1739
|
+
|
|
1740
|
+
test("no 4xx/5xx body contains the presented token, cookie or query secret", async () => {
|
|
1741
|
+
for (const c of paths) {
|
|
1742
|
+
const res = await fetch(`${BASE}${c.path}${c.path.includes("?") ? "&" : "?"}access_token=${CANARY}`, {
|
|
1743
|
+
method: c.method,
|
|
1744
|
+
headers: {
|
|
1745
|
+
authorization: `Bearer ${CANARY}`,
|
|
1746
|
+
cookie: COOKIE,
|
|
1747
|
+
"content-type": "application/json",
|
|
1748
|
+
},
|
|
1749
|
+
body: c.body,
|
|
1750
|
+
});
|
|
1751
|
+
const text = await res.text();
|
|
1752
|
+
expect(text.includes(CANARY)).toBe(false);
|
|
1753
|
+
expect(text.includes("LEAKCANARY")).toBe(false);
|
|
1754
|
+
expect(text.includes("COOKIELEAKCANARY")).toBe(false);
|
|
1755
|
+
}
|
|
1756
|
+
});
|
|
1757
|
+
});
|