@sleep2agi/commhub-server 0.9.0-preview.28 → 0.9.0-preview.281
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 +120 -3
- package/bin/commhub.ts +93 -9
- package/build-info.json +7 -0
- package/package.json +10 -8
- package/src/ack-create-request-transport.test.ts +182 -0
- package/src/ack-create-request.test.ts +52 -8
- package/src/admin-delete-network-http.test.ts +229 -0
- package/src/admin-networks-http.test.ts +88 -0
- package/src/adoption-candidates-http.test.ts +140 -0
- package/src/adoption-candidates.ts +158 -0
- package/src/agent-access-batch.test.ts +215 -0
- package/src/agent-access.ts +585 -0
- package/src/agent-acl-groups-http.test.ts +247 -0
- package/src/agent-acl-http.test.ts +691 -0
- package/src/agent-acl-slice3-http.test.ts +888 -0
- package/src/agent-department-grants.test.ts +129 -0
- package/src/agent-department-http.test.ts +215 -0
- package/src/agent-groups-perf.test.ts +228 -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/all-status-cache.test.ts +31 -0
- package/src/all-status-cache.ts +37 -0
- package/src/anet-variant-real-daemon-http.test.ts +185 -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 +131 -4
- package/src/auth-abuse-counters.test.ts +144 -0
- package/src/auth-abuse-counters.ts +122 -0
- package/src/auth-layer-shape.test.ts +105 -0
- package/src/auth-password-change-cli-tokens-http.test.ts +423 -0
- package/src/auth-sessions-http.test.ts +260 -0
- package/src/auth-validate.test.ts +5 -1
- package/src/auth-weak-password-login.test.ts +176 -0
- package/src/auth.ts +641 -68
- package/src/backfill-node-ids-2664.test.ts +128 -0
- package/src/binding-generation-http.test.ts +141 -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/build-commit-report-http.test.ts +219 -0
- package/src/build-info.test.ts +60 -0
- package/src/build-info.ts +85 -0
- package/src/chain-attempt-dedup.test.ts +447 -0
- package/src/clip.test.ts +36 -0
- package/src/clip.ts +48 -0
- package/src/clone-node.test.ts +269 -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-sec1.test.ts +37 -0
- package/src/config-apply-validate.test.ts +188 -1
- package/src/config-apply-validate.ts +226 -3
- package/src/contracts/session-project-create.ts +14 -0
- package/src/contracts/session-source-delivery.ts +16 -0
- package/src/contracts/session-source-directory.ts +54 -0
- package/src/contracts/session-source-evidence.ts +72 -0
- package/src/contracts/session-source-execution.ts +24 -0
- package/src/contracts/session-source-transport.ts +18 -0
- package/src/cors-origins.test.ts +73 -0
- package/src/create-node-blocked-gate.test.ts +365 -0
- package/src/create-node-error-domain.test.ts +127 -0
- package/src/create-node-network-id.test.ts +91 -0
- package/src/create-node-tool-schema.test.ts +59 -0
- package/src/create-node-unicode-name.test.ts +126 -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 +298 -0
- package/src/create-node.ts +88 -23
- package/src/daemon-provider-snapshots.test.ts +453 -0
- package/src/daemon-provider-snapshots.ts +327 -0
- package/src/daemon-token-owner-http.test.ts +346 -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 +1334 -154
- 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 +139 -0
- package/src/departments-http.test.ts +185 -0
- package/src/departments-mcp-error-domain.test.ts +135 -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 +227 -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/expiry-counters.test.ts +187 -0
- package/src/expiry-counters.ts +227 -0
- package/src/expiry-evidence-db.test.ts +103 -0
- package/src/ext-token-shared.test.ts +60 -0
- package/src/ext-validation-regression.test.ts +10 -17
- 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 +1 -1
- package/src/file-download-authz.test.ts +25 -4
- package/src/file-download-date-bucket.test.ts +1 -1
- package/src/file-network-scope-dev-open.test.ts +1 -1
- package/src/file-network-scope.test.ts +7 -6
- package/src/group-membership-events-http.test.ts +264 -0
- package/src/group-messages-http.test.ts +483 -0
- package/src/group-messages.ts +297 -0
- package/src/health-anon-readers.ts +67 -0
- package/src/health-host-disk-2756.test.ts +71 -0
- package/src/health-identity-root.test.ts +98 -0
- package/src/health-redaction.test.ts +1603 -7
- package/src/health-status-reasons.test.ts +84 -0
- 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 +664 -0
- package/src/hub-provider-config.test.ts +166 -0
- package/src/hub-provider-config.ts +202 -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 +318 -0
- package/src/inbox-count.ts +29 -0
- package/src/index.ts +6 -2
- package/src/launched-by-cli-report-http.test.ts +155 -0
- package/src/license-state.test.ts +105 -0
- package/src/license-state.ts +48 -0
- package/src/lifecycle-error-domain.test.ts +149 -0
- package/src/list-ack-error-domain.test.ts +108 -0
- package/src/list-host-supervisors.test.ts +15 -4
- package/src/list-tasks-omit-default.test.ts +84 -0
- package/src/list-tasks-since-last.test.ts +100 -0
- package/src/list-tasks-since.test.ts +104 -0
- 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 +168 -0
- package/src/mcp-route-label-http.test.ts +120 -0
- package/src/mcp-write-network-resolution.test.ts +21 -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-quota-config.test.ts +100 -0
- package/src/network-rules-http.test.ts +169 -0
- package/src/network-rules.ts +129 -0
- package/src/network-scope.ts +222 -3
- package/src/network-token-membership-http.test.ts +186 -0
- package/src/node-alias-control.ts +12 -0
- package/src/node-attrs.test.ts +47 -2
- package/src/node-caller-identity-http.test.ts +1108 -0
- package/src/node-config-last-update.test.ts +126 -0
- package/src/node-config-last-update.ts +107 -0
- package/src/node-create-request-status-http.test.ts +105 -0
- package/src/node-daemon-bindings.test.ts +142 -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 +350 -0
- package/src/node-health-codex-login.test.ts +120 -0
- package/src/node-health-dispatch-http.test.ts +373 -0
- package/src/node-health-guard-origin.test.ts +98 -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-inbox-allowlist-http.test.ts +320 -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 +257 -0
- package/src/node-lifecycle-read.ts +126 -0
- package/src/node-logs-transport.test.ts +266 -0
- package/src/node-peer-allowlist.test.ts +114 -0
- package/src/node-permissions-http.test.ts +901 -0
- package/src/node-permissions.ts +627 -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-secret-vault-inject.test.ts +132 -0
- package/src/node-security-write-gate.test.ts +72 -0
- package/src/node-serviceability.test.ts +86 -0
- package/src/node-serviceability.ts +124 -0
- package/src/node-session-control-http.test.ts +398 -0
- package/src/node-session-control.ts +316 -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 +224 -0
- package/src/node-token-usage.test.ts +128 -0
- package/src/node-token-usage.ts +228 -0
- package/src/not-found-api-http.test.ts +67 -0
- package/src/observer-avatar-http.test.ts +103 -10
- 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 +282 -0
- package/src/opencode-v2-catalog.ts +357 -0
- package/src/package-self-contained.test.ts +32 -0
- package/src/package-version-consistency.test.ts +25 -0
- package/src/parent-infer.test.ts +82 -0
- package/src/parent-infer.ts +110 -0
- package/src/parent-source-marker.test.ts +70 -0
- package/src/parent-source-orphan.test.ts +121 -0
- package/src/password-network-tokens.ts +25 -0
- package/src/peer-reply-atomic.test.ts +462 -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/probe-provider-error-domain.test.ts +145 -0
- package/src/project-dir-warn-clear-http.test.ts +132 -0
- package/src/project-viewer-can-http.test.ts +116 -0
- package/src/provider-skill-error-domain.test.ts +130 -0
- package/src/provider-tools-shape.test.ts +165 -0
- package/src/push.test.ts +20 -10
- package/src/push.ts +373 -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 +272 -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 +318 -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 +313 -0
- package/src/requirement-tag-ops-http.test.ts +454 -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-assignee-drift.test.ts +154 -0
- package/src/requirements-comment-http.test.ts +174 -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 +180 -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 +2205 -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 +280 -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 +486 -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 +203 -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 +289 -0
- package/src/scheduled-requirement-wake.ts +125 -0
- package/src/scheduled-run-terminal.test.ts +290 -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 +980 -0
- package/src/scheduled-work-outcome-http.test.ts +154 -0
- package/src/scheduled-work-outcome.ts +50 -0
- package/src/scoped-secrets.ts +167 -0
- package/src/secret-echo-negative-control.test.ts +118 -0
- package/src/send-dedup-request-id.test.ts +229 -0
- package/src/send-reply-agent-warning.test.ts +38 -38
- package/src/send-reply-alias-optional.test.ts +131 -0
- package/src/send-reply-attachments.test.ts +28 -7
- 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 +5103 -377
- package/src/session-fork-store.test.ts +43 -0
- package/src/session-fork-store.ts +51 -0
- package/src/session-project-attach-migration.test.ts +23 -0
- package/src/session-project-attach-native.test.ts +123 -0
- package/src/session-project-create-http.test.ts +408 -0
- package/src/session-project-create-native.test.ts +292 -0
- package/src/session-project-create.ts +159 -0
- package/src/session-source-admission-store.ts +58 -0
- package/src/session-source-create.test.ts +155 -0
- package/src/session-source-create.ts +97 -0
- package/src/session-source-delivery.ts +114 -0
- package/src/session-source-directory-http.test.ts +196 -0
- package/src/session-source-evidence.test.ts +905 -0
- package/src/session-source-evidence.ts +191 -0
- package/src/session-source-execution.ts +87 -0
- package/src/session-source-grant.test.ts +117 -0
- package/src/session-source-grant.ts +78 -0
- package/src/session-source-issuer.test.ts +250 -0
- package/src/session-source-issuer.ts +164 -0
- package/src/session-source-transport.ts +381 -0
- 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 +144 -0
- package/src/sqlite-close-checkpoint.test.ts +78 -0
- package/src/start-node.test.ts +265 -0
- package/src/start-request-error-domain.test.ts +182 -0
- package/src/start-skill-error-domain.test.ts +122 -0
- package/src/stats-versions-http.test.ts +65 -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-node-secrets-capable-http.test.ts +44 -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 +407 -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 +512 -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 +298 -0
- package/src/task-expiry-notice.ts +318 -0
- package/src/task-idempotency-mcp.test.ts +148 -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 +209 -0
- package/src/task-lifecycle-watcher.ts +109 -0
- package/src/task-network-resolution-http.test.ts +140 -0
- package/src/task-not-found-error-domain.test.ts +117 -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 +61 -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/test-work-root.ts +18 -0
- package/src/tmux-allowlist.test.ts +48 -0
- package/src/token-usage-http.test.ts +156 -0
- package/src/tool-audience-http.test.ts +266 -0
- package/src/tool-audience.ts +130 -0
- package/src/tools-list-json-schema.test.ts +94 -0
- package/src/tools.ts +4557 -472
- package/src/update-node-config-error-domain.test.ts +107 -0
- package/src/uploads-http.test.ts +6 -4
- package/src/uploads.ts +23 -4
- 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 +353 -0
- package/src/user-inbox-by-agent-http.test.ts +189 -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
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { db } from "./db";
|
|
3
|
+
import { resolveToken, getUserNetworkRole } from "./auth";
|
|
4
|
+
import { isHumanCredential, readSessionControlCredential, resolveSessionControlNodeCaller, readSessionControlBody } from "./node-session-control";
|
|
5
|
+
import { createSessionSourceIssuer } from "./session-source-issuer";
|
|
6
|
+
import { createSessionSourceEvidenceQueue } from "./session-source-evidence";
|
|
7
|
+
import { createSessionSourceExecutionQueue } from "./session-source-execution";
|
|
8
|
+
import { createSessionSourceDeliveryQueue } from "./session-source-delivery";
|
|
9
|
+
import { checkNodeName } from "./shared/node-name";
|
|
10
|
+
import { SOURCE_DELIVERY_CAPABILITY } from "./contracts/session-source-delivery";
|
|
11
|
+
import { secretTransportVerdict } from "./env-transport-policy";
|
|
12
|
+
import { SOURCE_DIRECTORY_CAPABILITY as DIR_CAP, isDirectoryRequestId, isDirectoryServerId, isSourceDirectorySnapshot,
|
|
13
|
+
type SourceDirectoryTask, type SourceDirectorySnapshot } from "./contracts/session-source-directory";
|
|
14
|
+
import { PROJECT_CREATE_CAPABILITY, SESSION_ATTACH_CAPABILITY } from "./contracts/session-project-create";
|
|
15
|
+
import { createSessionProjectTransport } from "./session-project-create";
|
|
16
|
+
import { SOURCE_FORK_ROOT as ROOT, SOURCE_FORK_CAPABILITY as CAP, isSourceForkRequestId,
|
|
17
|
+
type SourceForkTask, type SourceForkStatus, type SourceForkReceipt } from "./contracts/session-source-transport";
|
|
18
|
+
|
|
19
|
+
type Row = { request_id: string; user_id: string; requester_token_id: string; network_id: string; intent_id: string;
|
|
20
|
+
source_node_id: string; daemon_node_id: string; daemon_token_id: string; daemon_instance_id: string; session_id: string;
|
|
21
|
+
child_name: string; state: SourceForkStatus; expires_at: number; evidence_id: string; execution_id: string | null;
|
|
22
|
+
delivery_id: string | null; child_node_id: string | null; child_session_id: string | null };
|
|
23
|
+
const keys = (o: Record<string, unknown>, allowed: string[]) => Object.keys(o).every(k => allowed.includes(k));
|
|
24
|
+
const id = (v: unknown): v is string => typeof v === "string" && /^[A-Za-z0-9_-]{1,200}$/.test(v);
|
|
25
|
+
const terminal = (r: Row) => ["registration_confirmed", "refused", "unknown_rotation_required"].includes(r.state);
|
|
26
|
+
const ok = (value: object) => Response.json({ ok: true, ...value }, { headers: { "cache-control": "no-store" } });
|
|
27
|
+
|
|
28
|
+
/** Why a fork create was refused after the caller's source permissions were verified. */
|
|
29
|
+
export type SourceForkFailureReason = "daemon_offline" | "daemon_not_capable" | "hub_busy" | "evidence_unavailable" | "intent_reused"
|
|
30
|
+
| "source_not_managed" | "source_management_ambiguous";
|
|
31
|
+
|
|
32
|
+
/** Separate REST semantics within the existing session-control HTTP surface.
|
|
33
|
+
* Secret bodies are never persisted. Original human Request lives ONLY in this
|
|
34
|
+
* bounded in-memory orchestration until terminal/expiry, like pendingEnvBlobs;
|
|
35
|
+
* no plaintext requester bearer is journaled or reconstructed after restart. */
|
|
36
|
+
|
|
37
|
+
export function createSessionSourceTransport(options: { enabled?: boolean; directoryEnabled?: boolean; projectEnabled?: boolean; attachEnabled?: boolean } = {}) {
|
|
38
|
+
const enabled = options.enabled === true;
|
|
39
|
+
const issuer = createSessionSourceIssuer(), evidence = createSessionSourceEvidenceQueue({ enabled });
|
|
40
|
+
const execution = createSessionSourceExecutionQueue(evidence, { enabled });
|
|
41
|
+
const delivery = createSessionSourceDeliveryQueue(execution, { enabled });
|
|
42
|
+
const daemons = new Map<string, { token: string; instance: string; expires: number; retired: Set<string>; projectCreate?: boolean; sessionAttach?: boolean }>();
|
|
43
|
+
type DirectoryRow = { task: SourceDirectoryTask; token: string; user: string; daemonToken: string; instance: string;
|
|
44
|
+
status: "pending" | "claimed" | "ready" | "failed"; snapshot?: SourceDirectorySnapshot; parent?: string };
|
|
45
|
+
const directories = new Map<string, DirectoryRow>();
|
|
46
|
+
const directoryPermissions = (r: DirectoryRow) => issuer.directoryPermissions(r.token, r.user, { network_id: r.task.network_id,
|
|
47
|
+
source_node_id: r.task.source_node_id, daemon_node_id: r.task.daemon_node_id, mode: "attach_existing" });
|
|
48
|
+
const directoryCapable = (nodeId: string, network: string) => {
|
|
49
|
+
try {
|
|
50
|
+
const n = db.get<{ config_snapshot: string }>("SELECT config_snapshot FROM nodes WHERE node_id=?1 AND network_id=?2", nodeId, network);
|
|
51
|
+
const s = JSON.parse(n?.config_snapshot ?? "{}");
|
|
52
|
+
const channel = db.get<{ env_transport: string }>("SELECT env_transport FROM sessions WHERE node_id=?1 AND network_id=?2 ORDER BY last_seen_at DESC LIMIT 1", nodeId, network);
|
|
53
|
+
return s.role === "host_supervisor" && s.daemon_capabilities?.source_directory_read === DIR_CAP
|
|
54
|
+
&& secretTransportVerdict(channel?.env_transport ?? null, { ANET_SECRET_TRANSPORT_GATE: "enforce", ANET_SECRET_TRANSPORT_GATE_STRICT: "1" }) === null;
|
|
55
|
+
} catch { return false; }
|
|
56
|
+
};
|
|
57
|
+
const directoryCurrent = (r: DirectoryRow, projectSelection = false): boolean => {
|
|
58
|
+
const t = r.task, d = daemons.get(`directory:${t.network_id}:${t.daemon_node_id}`), n = resolveSessionControlNodeCaller(r.daemonToken);
|
|
59
|
+
return Date.now() < (projectSelection ? r.snapshot?.selection_expires_at ?? t.expires_at : t.expires_at) && !!d && d.token === r.daemonToken && d.instance === r.instance && d.expires > Date.now()
|
|
60
|
+
&& n?.node_id === t.daemon_node_id && n.network_id === t.network_id && directoryCapable(t.daemon_node_id, t.network_id)
|
|
61
|
+
&& directoryPermissions(r) && (!r.parent || (!!directories.get(r.parent) && directoryCurrent(directories.get(r.parent)!, projectSelection)));
|
|
62
|
+
};
|
|
63
|
+
const directoryView = (r: DirectoryRow) => ({ ...r.task, status: r.status, ...(r.snapshot ? { snapshot: r.snapshot } : {}),
|
|
64
|
+
...(r.status === "failed" ? { error: "directory_read_failed" } : {}) });
|
|
65
|
+
const attachEnabled = options.directoryEnabled === true && process.env.COMMHUB_SESSION_ATTACH_PREVIEW === "1";
|
|
66
|
+
const projectTransport = createSessionProjectTransport({ enabled: options.projectEnabled === true && options.directoryEnabled === true,
|
|
67
|
+
attachEnabled,
|
|
68
|
+
select(s, token, user) {
|
|
69
|
+
const r = directories.get(s.selection_scope);
|
|
70
|
+
if (!r || r.status !== "ready" || r.token !== token || r.user !== user || !r.task.server_id || !directoryCurrent(r, true)
|
|
71
|
+
|| typeof r.snapshot?.selection_expires_at !== "number" || r.snapshot.snapshot_id !== s.snapshot_id) return null;
|
|
72
|
+
const attach = "session_id" in s;
|
|
73
|
+
const parent = attach ? r.snapshot.sessions.find(v => v.session_id === s.session_id)?.project_id : s.project_id;
|
|
74
|
+
if (!parent || !r.snapshot.projects.some(p => p.project_id === parent)) return null;
|
|
75
|
+
return { network_id: r.task.network_id, source_node_id: r.task.source_node_id, daemon_node_id: r.task.daemon_node_id,
|
|
76
|
+
daemon_token_id: r.daemonToken, daemon_instance_id: r.instance, selected_project_id: parent,
|
|
77
|
+
operation_kind: attach ? "attach_existing_session" : "project_new_session" };
|
|
78
|
+
},
|
|
79
|
+
permissions: r => issuer.directoryPermissions(r.requester_token_id, r.user_id, { network_id: r.network_id,
|
|
80
|
+
source_node_id: r.source_node_id, daemon_node_id: r.daemon_node_id, mode: "attach_existing" }),
|
|
81
|
+
current(r) {
|
|
82
|
+
const d = daemons.get(`directory:${r.network_id}:${r.daemon_node_id}`), n = resolveSessionControlNodeCaller(r.daemon_token_id);
|
|
83
|
+
try {
|
|
84
|
+
const s = JSON.parse(db.get<{ config_snapshot: string }>("SELECT config_snapshot FROM nodes WHERE node_id=?1 AND network_id=?2", r.daemon_node_id, r.network_id)?.config_snapshot ?? "{}");
|
|
85
|
+
const canNew = options.projectEnabled === true && d?.projectCreate === true && s.daemon_capabilities?.project_new_session === PROJECT_CREATE_CAPABILITY;
|
|
86
|
+
const canAttach = attachEnabled && d?.sessionAttach === true && s.daemon_capabilities?.session_attach === SESSION_ATTACH_CAPABILITY;
|
|
87
|
+
const operationAllowed = r.operation_kind === "attach_existing_session" ? canAttach : r.source_node_id ? canNew : canNew || canAttach;
|
|
88
|
+
return !!d && operationAllowed && d.token === r.daemon_token_id && d.instance === r.daemon_instance_id && d.expires > Date.now()
|
|
89
|
+
&& n?.node_id === r.daemon_node_id && n.network_id === r.network_id && directoryCapable(r.daemon_node_id, r.network_id)
|
|
90
|
+
;
|
|
91
|
+
} catch { return false; }
|
|
92
|
+
} });
|
|
93
|
+
const active = new Map<string, { human: Request; release?: () => void; timer: ReturnType<typeof setTimeout> }>();
|
|
94
|
+
const row = (requestId: string) => db.get<Row>("SELECT * FROM session_source_transports WHERE request_id=?1", requestId);
|
|
95
|
+
const selection = (r: Row) => ({ network_id: r.network_id, source_node_id: r.source_node_id,
|
|
96
|
+
daemon_node_id: r.daemon_node_id, mode: "fork_independent" as const });
|
|
97
|
+
const permissions = (r: Row) => "permissions_verified" in issuer.inspectStoredRequester(r.requester_token_id, r.user_id, selection(r));
|
|
98
|
+
const capable = (nodeId: string, network: string) => {
|
|
99
|
+
try {
|
|
100
|
+
const n = db.get<{ config_snapshot: string }>("SELECT config_snapshot FROM nodes WHERE node_id=?1 AND network_id=?2", nodeId, network);
|
|
101
|
+
const s = JSON.parse(n?.config_snapshot ?? "{}");
|
|
102
|
+
const channel = db.get<{ env_transport: string }>("SELECT env_transport FROM sessions WHERE node_id=?1 AND network_id=?2 ORDER BY last_seen_at DESC LIMIT 1", nodeId, network);
|
|
103
|
+
return s.role === "host_supervisor" && s.daemon_capabilities?.source_node_delivery === SOURCE_DELIVERY_CAPABILITY
|
|
104
|
+
&& s.daemon_capabilities?.source_fork_transport === CAP && secretTransportVerdict(channel?.env_transport ?? null,
|
|
105
|
+
{ ANET_SECRET_TRANSPORT_GATE: "enforce", ANET_SECRET_TRANSPORT_GATE_STRICT: "1" }) === null;
|
|
106
|
+
} catch { return false; }
|
|
107
|
+
};
|
|
108
|
+
const current = (r: Row) => {
|
|
109
|
+
const d = daemons.get(`${r.network_id}:${r.daemon_node_id}`), n = resolveSessionControlNodeCaller(r.daemon_token_id);
|
|
110
|
+
return Date.now() < r.expires_at && !!d && d.token === r.daemon_token_id && d.instance === r.daemon_instance_id && d.expires > Date.now()
|
|
111
|
+
&& n?.node_id === r.daemon_node_id && n.network_id === r.network_id && capable(r.daemon_node_id, r.network_id) && permissions(r);
|
|
112
|
+
};
|
|
113
|
+
const forget = (r: Row) => { const a = active.get(r.request_id); if (a) { clearTimeout(a.timer); active.delete(r.request_id); a.release?.(); } };
|
|
114
|
+
const settle = (r: Row, state: "refused" | "unknown_rotation_required" | "registration_confirmed") => {
|
|
115
|
+
const a = active.get(r.request_id);
|
|
116
|
+
if (state === "unknown_rotation_required" && r.delivery_id) delivery.abandon(r.delivery_id);
|
|
117
|
+
if (state === "unknown_rotation_required" && r.delivery_id && a) {
|
|
118
|
+
const d = delivery.recover(a.human, r.delivery_id);
|
|
119
|
+
if (d) db.run("UPDATE session_source_transports SET child_node_id=?1,child_session_id=?2 WHERE request_id=?3", [d.child_node_id, d.session_id, r.request_id]);
|
|
120
|
+
}
|
|
121
|
+
db.run("UPDATE session_source_transports SET state=?1 WHERE request_id=?2 AND state NOT IN ('registration_confirmed','refused','unknown_rotation_required')", [state, r.request_id]);
|
|
122
|
+
forget(r);
|
|
123
|
+
};
|
|
124
|
+
const refresh = (r: Row) => {
|
|
125
|
+
if (!terminal(r) && (!active.has(r.request_id) || Date.now() >= r.expires_at || !current(r))) settle(r, "unknown_rotation_required");
|
|
126
|
+
return row(r.request_id)!;
|
|
127
|
+
};
|
|
128
|
+
const view = (r: Row): Omit<SourceForkReceipt, "ok"> => ({ request_id: r.request_id, intent_id: r.intent_id, network_id: r.network_id,
|
|
129
|
+
source_node_id: r.source_node_id, daemon_node_id: r.daemon_node_id, session_id: r.session_id, mode: "fork_independent",
|
|
130
|
+
child_name: r.child_name, status: r.state, expires_at: r.expires_at,
|
|
131
|
+
...(r.child_node_id ? { child_node_id: r.child_node_id } : {}), ...(r.child_session_id ? { child_session_id: r.child_session_id } : {}),
|
|
132
|
+
native_acceptance: "not_verified", dispatch_scope: "gated_preview" });
|
|
133
|
+
const envelope = (r: Row) => ({ request_id: r.request_id, intent_id: r.intent_id, network_id: r.network_id,
|
|
134
|
+
source_node_id: r.source_node_id, daemon_node_id: r.daemon_node_id });
|
|
135
|
+
function startAdmission(r: Row) {
|
|
136
|
+
const a = active.get(r.request_id)!;
|
|
137
|
+
void evidence.admit(a.human, r.evidence_id, r.intent_id, r.child_name, async () => {
|
|
138
|
+
db.run("UPDATE session_source_transports SET state='recheck_pending' WHERE request_id=?1 AND state='evidence_claimed'", [r.request_id]);
|
|
139
|
+
await new Promise<void>(resolve => { a.release = resolve; });
|
|
140
|
+
if (active.get(r.request_id) !== a || !current(r)) throw Error("source_fork_changed");
|
|
141
|
+
}).then(receipt => {
|
|
142
|
+
const now = row(r.request_id)!;
|
|
143
|
+
if (terminal(now) || !current(now)) return;
|
|
144
|
+
const executionId = execution.queue(a.human, receipt.request_id);
|
|
145
|
+
if (!executionId) { settle(now, "refused"); return; }
|
|
146
|
+
db.run("UPDATE session_source_transports SET execution_id=?1,state='execute_pending' WHERE request_id=?2", [executionId, r.request_id]);
|
|
147
|
+
}).catch(() => { const now = row(r.request_id); if (now) settle(now, "refused"); });
|
|
148
|
+
}
|
|
149
|
+
return async function handle(req: Request, url: URL): Promise<Response | null> {
|
|
150
|
+
const projectResponse = await projectTransport(req, url); if (projectResponse) return projectResponse;
|
|
151
|
+
if (url.pathname !== ROOT && !url.pathname.startsWith(`${ROOT}/`)) return null;
|
|
152
|
+
const directoryPath = url.pathname === `${ROOT}/directory` || url.pathname.startsWith(`${ROOT}/directory/`);
|
|
153
|
+
// `reason` is additive diagnostics for the UI (it used to show a bare "conflict" for every 409).
|
|
154
|
+
// Only attached after the caller's permissions on the source are verified — see the fork create path.
|
|
155
|
+
const fail = (status = 409, reason?: SourceForkFailureReason) => Response.json({ ok: false, error: directoryPath ? "source_directory_unavailable" : "source_fork_unavailable",
|
|
156
|
+
...(reason ? { reason } : {}) }, { status, headers: { "cache-control": "no-store" } });
|
|
157
|
+
if (directoryPath ? options.directoryEnabled !== true : !enabled) return fail(404);
|
|
158
|
+
try {
|
|
159
|
+
const auth = resolveToken(req.headers.get("authorization")?.match(/^Bearer (\S+)$/)?.[1] ?? "");
|
|
160
|
+
if (!auth?.tokenId) return fail(401);
|
|
161
|
+
const credential = readSessionControlCredential(auth.tokenId);
|
|
162
|
+
const suffix = url.pathname.slice((directoryPath ? `${ROOT}/directory` : ROOT).length);
|
|
163
|
+
if (directoryPath) {
|
|
164
|
+
// Read-only, bounded process-memory queue using the same pin/instance
|
|
165
|
+
// transport as source execution. Restart/expiry discards read scopes;
|
|
166
|
+
// no mutation recovery journal or evidence/admission machine is involved.
|
|
167
|
+
for (const [key, r] of directories) if (Date.now() >= (r.snapshot?.selection_expires_at ?? r.task.expires_at)) directories.delete(key);
|
|
168
|
+
if (req.method === "GET") {
|
|
169
|
+
const r = directories.get(suffix.slice(1));
|
|
170
|
+
if (!isHumanCredential(credential) || !isDirectoryRequestId(suffix.slice(1)) || !r
|
|
171
|
+
|| [...url.searchParams.keys()].some(k => k !== "network_id") || url.searchParams.getAll("network_id").length !== 1
|
|
172
|
+
|| url.searchParams.get("network_id") !== r.task.network_id || auth.tokenId !== r.token || auth.user.user_id !== r.user
|
|
173
|
+
|| !directoryCurrent(r)) return fail(403);
|
|
174
|
+
return ok(directoryView(r));
|
|
175
|
+
}
|
|
176
|
+
if (req.method !== "POST" || url.search) return fail(400);
|
|
177
|
+
const b = await readSessionControlBody(req, 65536); if (!b) return fail(400);
|
|
178
|
+
if (!suffix) {
|
|
179
|
+
// 凭据类型与请求体是**两种不同性质**的问题,不能共用一个 400(#4467):
|
|
180
|
+
// · 凭据不是 human 凭据 → 权限问题,403
|
|
181
|
+
// · 请求体键/ID 不合法 → 请求问题,400
|
|
182
|
+
// 混在一起的实际代价:2026-11-10 我用节点 token 验这条链路,
|
|
183
|
+
// 拿到 400 后第一反应是「body 拼错了」,查了半小时才想到是凭据类型。
|
|
184
|
+
if (!isHumanCredential(credential)) return fail(403);
|
|
185
|
+
if (!keys(b, ["network_id", "source_node_id", "daemon_node_id", "server_id", "selection_scope"])
|
|
186
|
+
|| !id(b.network_id) || !id(b.source_node_id) || !id(b.daemon_node_id)
|
|
187
|
+
|| (b.server_id !== undefined && (!isDirectoryServerId(b.server_id) || !isDirectoryRequestId(b.selection_scope)))
|
|
188
|
+
|| (b.server_id === undefined && b.selection_scope !== undefined)) return fail(400);
|
|
189
|
+
const d = daemons.get(`directory:${b.network_id}:${b.daemon_node_id}`);
|
|
190
|
+
const task: SourceDirectoryTask = { request_id: `srcdir_${randomUUID()}`, network_id: b.network_id as string,
|
|
191
|
+
source_node_id: b.source_node_id as string, daemon_node_id: b.daemon_node_id as string,
|
|
192
|
+
expires_at: Date.now() + 30000, ...(b.server_id ? { server_id: b.server_id as string } : {}) };
|
|
193
|
+
const r: DirectoryRow = { task, token: auth.tokenId, user: auth.user.user_id, daemonToken: d?.token ?? "", instance: d?.instance ?? "", status: "pending" };
|
|
194
|
+
if (!directoryCurrent(r)) return fail(403);
|
|
195
|
+
if (b.server_id) {
|
|
196
|
+
const parent = directories.get(b.selection_scope as string);
|
|
197
|
+
if (!parent || parent.parent || parent.status !== "ready" || !directoryCurrent(parent) || parent.token !== r.token || parent.user !== r.user
|
|
198
|
+
|| parent.task.network_id !== task.network_id || parent.task.source_node_id !== task.source_node_id || parent.task.daemon_node_id !== task.daemon_node_id
|
|
199
|
+
|| parent.instance !== r.instance || !parent.snapshot?.servers.some(s => s.server_id === b.server_id)) return fail(403);
|
|
200
|
+
r.parent = parent.task.request_id; task.expires_at = Math.min(task.expires_at, parent.task.expires_at);
|
|
201
|
+
}
|
|
202
|
+
if (directories.size >= 100) return fail();
|
|
203
|
+
directories.set(task.request_id, r); return ok(directoryView(r));
|
|
204
|
+
}
|
|
205
|
+
const n = resolveSessionControlNodeCaller(auth.tokenId), expected: any = b.expected;
|
|
206
|
+
if (!n || !expected || Object.keys(expected).length !== 2 || expected.node_id !== n.node_id || expected.network_id !== n.network_id
|
|
207
|
+
|| b.capability !== DIR_CAP || !directoryCapable(n.node_id, n.network_id)) return fail(403);
|
|
208
|
+
const key = `directory:${n.network_id}:${n.node_id}`;
|
|
209
|
+
if (suffix === "/daemon") {
|
|
210
|
+
if (!keys(b, ["expected", "capability", "instance_id", "project_create_capability", "session_attach_capability"]) || typeof b.instance_id !== "string" || !/^[a-f0-9-]{36}$/.test(b.instance_id)
|
|
211
|
+
|| (b.project_create_capability !== undefined && b.project_create_capability !== PROJECT_CREATE_CAPABILITY)
|
|
212
|
+
|| (b.session_attach_capability !== undefined && b.session_attach_capability !== SESSION_ATTACH_CAPABILITY)) return fail(400);
|
|
213
|
+
const previous = daemons.get(key), retired = previous?.retired ?? new Set<string>();
|
|
214
|
+
if ((!previous && daemons.size >= 128) || retired.has(b.instance_id) || (previous?.instance === b.instance_id && previous.token !== auth.tokenId)) return fail();
|
|
215
|
+
if (previous && (previous.instance !== b.instance_id || previous.token !== auth.tokenId)) {
|
|
216
|
+
if (retired.size >= 64) return fail(); retired.add(previous.instance);
|
|
217
|
+
for (const [id, r] of directories) if (r.task.daemon_node_id === n.node_id && r.task.network_id === n.network_id) directories.delete(id);
|
|
218
|
+
}
|
|
219
|
+
daemons.set(key, { token: auth.tokenId, instance: b.instance_id, expires: Date.now() + 30000, retired,
|
|
220
|
+
projectCreate: options.projectEnabled === true && b.project_create_capability === PROJECT_CREATE_CAPABILITY,
|
|
221
|
+
sessionAttach: attachEnabled && b.session_attach_capability === SESSION_ATTACH_CAPABILITY }); return ok({ capability: DIR_CAP, expected });
|
|
222
|
+
}
|
|
223
|
+
const d = daemons.get(key);
|
|
224
|
+
if (!d || d.token !== auth.tokenId || d.instance !== b.instance_id || d.expires <= Date.now()) return fail(403);
|
|
225
|
+
if (suffix === "/pull") {
|
|
226
|
+
if (!keys(b, ["expected", "capability", "instance_id"])) return fail(400);
|
|
227
|
+
for (const r of directories.values()) if (r.status === "pending" && r.daemonToken === auth.tokenId && r.instance === d.instance && directoryCurrent(r)) {
|
|
228
|
+
r.status = "claimed"; return ok({ task: r.task });
|
|
229
|
+
}
|
|
230
|
+
return ok({ task: null });
|
|
231
|
+
}
|
|
232
|
+
if (suffix === "/ack") {
|
|
233
|
+
if (!keys(b, ["expected", "capability", "instance_id", "request_id", "result"]) || !isDirectoryRequestId(b.request_id)) return fail(400);
|
|
234
|
+
const r = directories.get(b.request_id as string);
|
|
235
|
+
if (!r || r.status !== "claimed" || r.daemonToken !== auth.tokenId || r.instance !== d.instance || !directoryCurrent(r)) return fail(403);
|
|
236
|
+
const result: any = b.result;
|
|
237
|
+
if (result && Object.keys(result).length === 1 && result.error === "directory_read_failed") r.status = "failed";
|
|
238
|
+
else if (isSourceDirectorySnapshot(result, r.task.expires_at)
|
|
239
|
+
&& (!r.task.server_id ? !result.projects.length && !result.sessions.length : result.servers.some(s => s.server_id === r.task.server_id)
|
|
240
|
+
&& result.projects.every(p => p.server_id === r.task.server_id))) { r.status = "ready"; r.snapshot = result; }
|
|
241
|
+
else return fail(400);
|
|
242
|
+
return ok({ acknowledged: true });
|
|
243
|
+
}
|
|
244
|
+
return fail(404);
|
|
245
|
+
}
|
|
246
|
+
if (req.method === "GET") {
|
|
247
|
+
if (!isHumanCredential(credential) || !/^\/srcf_[a-f0-9-]{36}$/.test(suffix)
|
|
248
|
+
|| [...url.searchParams.keys()].some(k => k !== "network_id")) return fail(403);
|
|
249
|
+
const r = row(suffix.slice(1));
|
|
250
|
+
if (!r || url.searchParams.get("network_id") !== r.network_id || auth.tokenId !== r.requester_token_id
|
|
251
|
+
|| auth.user.user_id !== r.user_id || !permissions(r)) return fail(403);
|
|
252
|
+
const now = refresh(r);
|
|
253
|
+
// Unknown recovery may record known IDs/revoke an unconfirmed credential,
|
|
254
|
+
// never dispatch, mint or repeat a session mutation.
|
|
255
|
+
if (now.state === "unknown_rotation_required") {
|
|
256
|
+
const e = now.execution_id && execution.recover(req, now.execution_id);
|
|
257
|
+
if (e && e.status === "session_ready") now.child_session_id = e.session_id!;
|
|
258
|
+
const d = now.delivery_id && delivery.recover(req, now.delivery_id);
|
|
259
|
+
if (d) { now.child_node_id = d.child_node_id; now.child_session_id = d.session_id; }
|
|
260
|
+
}
|
|
261
|
+
return ok(view(now));
|
|
262
|
+
}
|
|
263
|
+
if (req.method !== "POST" || url.search) return fail(400);
|
|
264
|
+
const b = await readSessionControlBody(req, 32768); if (!b) return fail(400);
|
|
265
|
+
if (suffix === "") {
|
|
266
|
+
if (db.dialect !== "sqlite" || db.atomicTransactions !== true || db.transactionalFeaturesRefusal !== null) return fail();
|
|
267
|
+
if (!isHumanCredential(credential) || !keys(b, ["network_id", "source_node_id", "session_id", "mode", "child_name", "intent_id"])
|
|
268
|
+
|| !id(b.network_id) || !id(b.source_node_id) || !id(b.intent_id) || typeof b.session_id !== "string"
|
|
269
|
+
|| !/^ses_[A-Za-z0-9]{1,190}$/.test(b.session_id) || b.mode !== "fork_independent") return fail(400);
|
|
270
|
+
const name = checkNodeName(b.child_name); if (!name.ok || name.name !== b.child_name) return fail(400);
|
|
271
|
+
// Infer management from existing authoritative create/adoption journals.
|
|
272
|
+
const owners = db.all<{ daemon_node_id: string }>(`SELECT daemon_node_id FROM node_create_requests WHERE child_node_id=?1
|
|
273
|
+
AND network_id=?2 AND status='succeeded' AND source_ref IS NULL UNION SELECT daemon_node_id FROM node_daemon_bindings
|
|
274
|
+
WHERE node_id=?1 AND network_id=?2 AND status='active'
|
|
275
|
+
UNION SELECT daemon_node_id FROM session_project_creates
|
|
276
|
+
WHERE child_node_id=?1 AND network_id=?2 AND state='registration_confirmed'`, b.source_node_id, b.network_id);
|
|
277
|
+
if (owners.length !== 1) {
|
|
278
|
+
// No daemon (hand-started node, never adopted) or more than one: the source cannot be
|
|
279
|
+
// forked. Network members already see `managed` in /api/nodes, so naming the cause
|
|
280
|
+
// to them discloses nothing new; anyone else still gets a bare refusal.
|
|
281
|
+
const member = !!getUserNetworkRole(auth.user.user_id, b.network_id);
|
|
282
|
+
return fail(409, member ? (owners.length === 0 ? "source_not_managed" : "source_management_ambiguous") : undefined);
|
|
283
|
+
}
|
|
284
|
+
const s = { network_id: b.network_id, source_node_id: b.source_node_id, daemon_node_id: owners[0].daemon_node_id, mode: "fork_independent" as const };
|
|
285
|
+
if (!("permissions_verified" in issuer.inspect(req, s))) return fail(403);
|
|
286
|
+
const existing = db.get<Row>("SELECT * FROM session_source_transports WHERE user_id=?1 AND network_id=?2 AND intent_id=?3", auth.user.user_id, b.network_id, b.intent_id);
|
|
287
|
+
if (existing) {
|
|
288
|
+
if (existing.requester_token_id !== auth.tokenId || existing.source_node_id !== b.source_node_id || existing.session_id !== b.session_id
|
|
289
|
+
|| existing.child_name !== b.child_name || existing.daemon_node_id !== s.daemon_node_id) return fail(409, "intent_reused");
|
|
290
|
+
return ok(view(refresh(existing))); // idempotent receipt, not a new workflow
|
|
291
|
+
}
|
|
292
|
+
const d = daemons.get(`${s.network_id}:${s.daemon_node_id}`);
|
|
293
|
+
if (!d || d.expires <= Date.now()) return fail(409, "daemon_offline");
|
|
294
|
+
if (!capable(s.daemon_node_id, s.network_id)) return fail(409, "daemon_not_capable");
|
|
295
|
+
if (active.size >= 128) return fail(409, "hub_busy");
|
|
296
|
+
const q = evidence.queue(req, s, b.session_id); if (!q) return fail(409, "evidence_unavailable");
|
|
297
|
+
const requestId = `srcf_${randomUUID()}`, expires = Date.now() + 75_000;
|
|
298
|
+
db.run(`INSERT INTO session_source_transports (request_id,user_id,requester_token_id,network_id,intent_id,source_node_id,
|
|
299
|
+
daemon_node_id,daemon_token_id,daemon_instance_id,session_id,child_name,state,expires_at,evidence_id)
|
|
300
|
+
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,'evidence_pending',?12,?13)`,
|
|
301
|
+
[requestId, auth.user.user_id, auth.tokenId, s.network_id, b.intent_id, s.source_node_id, s.daemon_node_id,
|
|
302
|
+
d.token, d.instance, b.session_id, name.name, expires, q.request_id]);
|
|
303
|
+
const timer = setTimeout(() => { const r = row(requestId); if (r && !terminal(r)) settle(r, "unknown_rotation_required"); }, 75_000);
|
|
304
|
+
timer.unref?.(); active.set(requestId, { human: req, timer }); return ok(view(row(requestId)!));
|
|
305
|
+
}
|
|
306
|
+
if (suffix === "/child-register") {
|
|
307
|
+
if (!keys(b, ["request_id", "intent_id", "network_id", "source_node_id", "daemon_node_id", "delivery_id"]) || !isSourceForkRequestId(b.request_id)) return fail(400);
|
|
308
|
+
const r = row(b.request_id);
|
|
309
|
+
if (!r || r.state !== "deliver_claimed" || !current(r) || !active.has(r.request_id)
|
|
310
|
+
|| !Object.entries(envelope(r)).every(([k, v]) => b[k] === v) || r.delivery_id !== b.delivery_id
|
|
311
|
+
|| !delivery.confirmRegistration(req, r.delivery_id!)) return fail(403);
|
|
312
|
+
const child = db.get<{ child_node_id: string }>("SELECT child_node_id FROM session_source_node_deliveries WHERE delivery_id=?1", r.delivery_id!);
|
|
313
|
+
db.run("UPDATE session_source_transports SET child_node_id=?1 WHERE request_id=?2", [child!.child_node_id, r.request_id]);
|
|
314
|
+
settle(r, "registration_confirmed"); return ok({ request_id: r.request_id, delivery_id: r.delivery_id, status: "registration_confirmed" });
|
|
315
|
+
}
|
|
316
|
+
const n = resolveSessionControlNodeCaller(auth.tokenId);
|
|
317
|
+
const expected: any = b.expected;
|
|
318
|
+
if (!n || !expected || Object.keys(expected).length !== 2 || expected.node_id !== n.node_id || expected.network_id !== n.network_id
|
|
319
|
+
|| b.capability !== CAP || !capable(n.node_id, n.network_id)) return fail(403);
|
|
320
|
+
const daemonKey = `${n.network_id}:${n.node_id}`;
|
|
321
|
+
if (suffix === "/daemon") {
|
|
322
|
+
if (!keys(b, ["expected", "capability", "instance_id"]) || typeof b.instance_id !== "string" || !/^[a-f0-9-]{36}$/.test(b.instance_id)) return fail(400);
|
|
323
|
+
if (!daemons.has(daemonKey) && daemons.size >= 128) return fail();
|
|
324
|
+
const previous = daemons.get(daemonKey), retired = previous?.retired ?? new Set<string>();
|
|
325
|
+
if (retired.has(b.instance_id)) return fail();
|
|
326
|
+
if (previous?.instance === b.instance_id && previous.token !== auth.tokenId) return fail();
|
|
327
|
+
if (previous && (previous.instance !== b.instance_id || previous.token !== auth.tokenId)) {
|
|
328
|
+
if (retired.size >= 64) return fail();
|
|
329
|
+
retired.add(previous.instance);
|
|
330
|
+
for (const r of db.all<Row>("SELECT * FROM session_source_transports WHERE daemon_node_id=?1 AND network_id=?2 AND state NOT IN ('registration_confirmed','refused','unknown_rotation_required')", n.node_id, n.network_id)) {
|
|
331
|
+
settle(r, "unknown_rotation_required");
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
daemons.set(daemonKey, { token: auth.tokenId, instance: b.instance_id, expires: Date.now() + 75_000, retired }); return ok({ capability: CAP, expected });
|
|
335
|
+
}
|
|
336
|
+
if (suffix === "/pull") {
|
|
337
|
+
if (!keys(b, ["expected", "capability", "instance_id"]) || daemons.get(daemonKey)?.instance !== b.instance_id) return fail(403);
|
|
338
|
+
const rows = db.all<Row>("SELECT * FROM session_source_transports WHERE daemon_node_id=?1 AND network_id=?2 AND daemon_token_id=?3 AND state NOT IN ('registration_confirmed','refused','unknown_rotation_required') ORDER BY rowid", n.node_id, n.network_id, auth.tokenId);
|
|
339
|
+
for (const original of rows) {
|
|
340
|
+
const r = refresh(original); if (terminal(r)) continue;
|
|
341
|
+
let task: SourceForkTask | null = null;
|
|
342
|
+
if (r.state === "evidence_pending") { const t = evidence.take(req, r.evidence_id); if (t) task = { ...envelope(r), phase: "evidence", task: t }; }
|
|
343
|
+
if (r.state === "recheck_pending") { const t = evidence.takeRecheck(req, r.evidence_id); if (t) task = { ...envelope(r), phase: "recheck", task: t }; }
|
|
344
|
+
if (r.state === "execute_pending") { const t = execution.take(req, r.execution_id!); if (t) task = { ...envelope(r), phase: "execute", task: t }; }
|
|
345
|
+
if (r.state === "deliver_pending") { const t = delivery.take(req, r.delivery_id!, SOURCE_DELIVERY_CAPABILITY); if (t) task = { ...envelope(r), phase: "deliver", task: t }; }
|
|
346
|
+
if (task) { db.run("UPDATE session_source_transports SET state=?1 WHERE request_id=?2", [`${task.phase}_claimed`, r.request_id]); return ok({ task }); }
|
|
347
|
+
if (r.state.endsWith("_pending")) settle(r, "unknown_rotation_required");
|
|
348
|
+
}
|
|
349
|
+
return ok({ task: null });
|
|
350
|
+
}
|
|
351
|
+
if (suffix === "/ack") {
|
|
352
|
+
if (!keys(b, ["expected", "capability", "instance_id", "request_id", "intent_id", "network_id", "source_node_id", "daemon_node_id", "phase", "result"])
|
|
353
|
+
|| !isSourceForkRequestId(b.request_id)) return fail(400);
|
|
354
|
+
const r = row(b.request_id);
|
|
355
|
+
if (!r || !Object.entries(envelope(r)).every(([k, v]) => b[k] === v) || r.daemon_token_id !== auth.tokenId
|
|
356
|
+
|| r.daemon_instance_id !== b.instance_id || !current(r)) return fail(403);
|
|
357
|
+
if (r.state === "registration_confirmed" && b.phase === "deliver") return ok({ acknowledged: true });
|
|
358
|
+
if (r.state !== `${b.phase}_claimed` || !active.has(r.request_id)) return fail();
|
|
359
|
+
const result: any = b.result;
|
|
360
|
+
if (result && Object.keys(result).length === 1 && result.transport_failure === "unknown_rotation_required") {
|
|
361
|
+
settle(r, "unknown_rotation_required"); return ok({ acknowledged: true });
|
|
362
|
+
}
|
|
363
|
+
if (b.phase === "evidence") { if (result?.request?.request_id !== r.evidence_id || !evidence.ack(req, result)) return fail(400); startAdmission(r); }
|
|
364
|
+
else if (b.phase === "recheck") { if (result?.request?.evidence?.request?.request_id !== r.evidence_id || !evidence.ackRecheck(req, result)) return fail(400); active.get(r.request_id)?.release?.(); }
|
|
365
|
+
else if (b.phase === "execute") {
|
|
366
|
+
if (result?.execution_id !== r.execution_id || !execution.ack(req, b.result)) return fail(400);
|
|
367
|
+
const a = active.get(r.request_id)!, recovered = execution.recover(a.human, r.execution_id!);
|
|
368
|
+
if (recovered?.status !== "session_ready") { settle(r, recovered?.status === "refused" ? "refused" : "unknown_rotation_required"); }
|
|
369
|
+
else {
|
|
370
|
+
const deliveryId = delivery.queue(a.human, r.execution_id!);
|
|
371
|
+
if (!deliveryId) settle(r, "unknown_rotation_required");
|
|
372
|
+
else db.run("UPDATE session_source_transports SET state='deliver_pending',delivery_id=?1,child_session_id=?2 WHERE request_id=?3", [deliveryId, recovered.session_id!, r.request_id]);
|
|
373
|
+
}
|
|
374
|
+
} else if (b.phase === "deliver") { settle(r, "unknown_rotation_required"); }
|
|
375
|
+
else return fail(400);
|
|
376
|
+
return ok({ acknowledged: true });
|
|
377
|
+
}
|
|
378
|
+
return fail(404);
|
|
379
|
+
} catch { return fail(); }
|
|
380
|
+
};
|
|
381
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Board #668. A dispatch preview is what the hub shows before the node
|
|
2
|
+
// reports. Once the session is already working, that text is the task in
|
|
3
|
+
// flight — a newer message waits in the inbox and must not replace it.
|
|
4
|
+
// Idle and every other status still take the preview.
|
|
5
|
+
|
|
6
|
+
const PLACEHOLDER = /^\?\d+$/;
|
|
7
|
+
|
|
8
|
+
/** SQL expression for `sessions.task` on dispatch. `placeholder` is a `?N` bind. */
|
|
9
|
+
export function sessionTaskOnDispatch(placeholder: string): string {
|
|
10
|
+
if (!PLACEHOLDER.test(placeholder)) {
|
|
11
|
+
throw new Error("sessionTaskOnDispatch placeholder must be a ?N bind");
|
|
12
|
+
}
|
|
13
|
+
return `CASE WHEN status = 'working' THEN task ELSE ${placeholder} END`;
|
|
14
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { beforeAll, afterAll, expect, test } from "bun:test";
|
|
2
|
+
import { mkdtempSync } from "node:fs";
|
|
3
|
+
|
|
4
|
+
process.env.COMMHUB_DB ||= `${mkdtempSync("/tmp/session689-")}/hub.db`;
|
|
5
|
+
let db: any, hub: ReturnType<typeof Bun.serve>, base: string;
|
|
6
|
+
let owner: any, holder: any, member: any, admin: any, outsider: any;
|
|
7
|
+
let generateNetworkToken: () => string, hashToken: (token: string) => string;
|
|
8
|
+
async function mint(actor: any, alias: string, nodeId?: string, network = owner.network_id) {
|
|
9
|
+
const response = await fetch(`${base}/api/auth/node-token`, {
|
|
10
|
+
method: "POST", headers: { Authorization: `Bearer ${actor.token}`, "Content-Type": "application/json" },
|
|
11
|
+
body: JSON.stringify({ network_id: network, node_name: alias, ...(nodeId ? { node_id: nodeId } : {}) }),
|
|
12
|
+
});
|
|
13
|
+
return { status: response.status, body: await response.json() as any };
|
|
14
|
+
}
|
|
15
|
+
function session(alias: string, network = owner.network_id, nodeId: string | null = null) {
|
|
16
|
+
db.run("INSERT INTO sessions(resume_id,alias,network_id,node_id,status) VALUES(?1,?2,?3,?4,'offline')",
|
|
17
|
+
[crypto.randomUUID(), alias, network, nodeId]);
|
|
18
|
+
}
|
|
19
|
+
function credential(alias: string, actor = holder, options: { epoch?: number; revoked?: boolean; expired?: boolean; network?: string; bound?: string; scope?: string } = {}) {
|
|
20
|
+
const id = crypto.randomUUID();
|
|
21
|
+
db.run(`INSERT INTO api_tokens(token_id,token_hash,user_id,network_id,name,scope,node_identity_epoch,bound_node_id,revoked_at,expires_at)
|
|
22
|
+
VALUES(?1,?2,?3,?4,?5,?6,?7,?8,?9,?10)`,
|
|
23
|
+
[id, hashToken(generateNetworkToken()), actor.user.user_id, options.network ?? owner.network_id,
|
|
24
|
+
`node:${alias}`, options.scope ?? "network", options.epoch ?? 0, options.bound ?? null,
|
|
25
|
+
options.revoked ? "2000-01-01 00:00:00" : null, options.expired ? "2000-01-01 00:00:00" : null]);
|
|
26
|
+
}
|
|
27
|
+
function snapshot() {
|
|
28
|
+
return {
|
|
29
|
+
tokens: db.all("SELECT token_id,user_id,name,bound_node_id FROM api_tokens ORDER BY token_id"),
|
|
30
|
+
sessions: db.all("SELECT resume_id,alias,network_id,node_id,status FROM sessions ORDER BY resume_id"),
|
|
31
|
+
nodes: db.all("SELECT node_id,alias,network_id,owner_user_id FROM nodes ORDER BY node_id"),
|
|
32
|
+
audits: db.all("SELECT id,action,target_id FROM audit_log ORDER BY id"),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
async function denied(actor: any, alias: string, nodeId?: string) {
|
|
36
|
+
const before = snapshot();
|
|
37
|
+
expect(await mint(actor, alias, nodeId)).toEqual({ status: 400, body: { ok: false, error: "node_owner_mismatch" } });
|
|
38
|
+
expect(snapshot()).toEqual(before);
|
|
39
|
+
}
|
|
40
|
+
beforeAll(async () => {
|
|
41
|
+
({ db, generateNetworkToken, hashToken } = await import("./db.js"));
|
|
42
|
+
const { register } = await import("./auth.js");
|
|
43
|
+
owner = register("owner689", "Fixture-Strong1!");
|
|
44
|
+
holder = register("holder689", "Fixture-Strong1!");
|
|
45
|
+
member = register("member689", "Fixture-Strong1!");
|
|
46
|
+
admin = register("admin689", "Fixture-Strong1!");
|
|
47
|
+
outsider = register("outside689", "Fixture-Strong1!");
|
|
48
|
+
for (const actor of [holder, member, admin]) {
|
|
49
|
+
db.run("INSERT INTO network_members(network_id,user_id,role,agent_access) VALUES(?1,?2,?3,'all')",
|
|
50
|
+
[owner.network_id, actor.user.user_id, actor === admin ? "admin" : "member"]);
|
|
51
|
+
}
|
|
52
|
+
const { bootServer } = await import("./server.js");
|
|
53
|
+
hub = bootServer({ port: 0, hostname: "127.0.0.1" }); base = `http://127.0.0.1:${hub.port}`;
|
|
54
|
+
}, 60000);
|
|
55
|
+
afterAll(() => hub?.stop(true));
|
|
56
|
+
|
|
57
|
+
test("existing session requires authority for both request shapes without writes", async () => {
|
|
58
|
+
session("existing689");
|
|
59
|
+
await denied(member, "existing689");
|
|
60
|
+
await denied(member, "existing689", "n_existing689");
|
|
61
|
+
});
|
|
62
|
+
test("network owner and administrator can restore a legacy identity", async () => {
|
|
63
|
+
for (const [actor, alias] of [[owner, "restore-owner689"], [admin, "restore-admin689"]]) {
|
|
64
|
+
session(alias);
|
|
65
|
+
expect((await mint(actor, alias)).status).toBe(200);
|
|
66
|
+
const withId = await mint(actor, alias, `n_${alias}`);
|
|
67
|
+
expect(withId.status).toBe(200);
|
|
68
|
+
expect(db.get("SELECT owner_user_id FROM nodes WHERE node_id=?1", `n_${alias}`).owner_user_id).toBe(actor.user.user_id);
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
test("unique legacy holder can refresh without rewriting the session", async () => {
|
|
72
|
+
session("holder-session689"); credential("holder-session689");
|
|
73
|
+
await denied(member, "holder-session689");
|
|
74
|
+
const before = db.get("SELECT * FROM sessions WHERE alias='holder-session689'");
|
|
75
|
+
expect((await mint(holder, "holder-session689")).status).toBe(200);
|
|
76
|
+
expect((await mint(holder, "holder-session689", "n_holder-session689")).status).toBe(200);
|
|
77
|
+
expect(db.get("SELECT * FROM sessions WHERE alias='holder-session689'")).toEqual(before);
|
|
78
|
+
});
|
|
79
|
+
test("current name-only holder can refresh while registration is pending", async () => {
|
|
80
|
+
expect((await mint(holder, "pending689")).status).toBe(200);
|
|
81
|
+
session("pending689");
|
|
82
|
+
await denied(member, "pending689", "n_pending689");
|
|
83
|
+
expect((await mint(holder, "pending689")).status).toBe(200);
|
|
84
|
+
});
|
|
85
|
+
for (const [label, options] of [
|
|
86
|
+
["revoked", { revoked: true }], ["expired", { expired: true }],
|
|
87
|
+
["renamed-general", { epoch: 1 }], ["wrong-scope", { scope: "full" }],
|
|
88
|
+
["missing-bound-row", { bound: "n_missing689" }],
|
|
89
|
+
] as const) {
|
|
90
|
+
test(`${label} credential is not session holder evidence`, async () => {
|
|
91
|
+
const alias = `${label}689`; session(alias); credential(alias, holder, options);
|
|
92
|
+
await denied(holder, alias);
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
test("conflicting legacy holders need administrator recovery", async () => {
|
|
96
|
+
session("ambiguous689"); credential("ambiguous689"); credential("ambiguous689", member);
|
|
97
|
+
await denied(holder, "ambiguous689"); await denied(member, "ambiguous689", "n_ambiguous689");
|
|
98
|
+
expect((await mint(admin, "ambiguous689")).status).toBe(200);
|
|
99
|
+
});
|
|
100
|
+
test("session and holder evidence stay in the requested network", async () => {
|
|
101
|
+
session("foreign-session689", outsider.network_id);
|
|
102
|
+
expect((await mint(member, "foreign-session689")).status).toBe(200);
|
|
103
|
+
session("foreign-holder689"); credential("foreign-holder689", holder, { network: holder.network_id });
|
|
104
|
+
await denied(holder, "foreign-holder689");
|
|
105
|
+
expect((await mint(outsider, "foreign-holder689")).body.error).toBe("no write access to this network");
|
|
106
|
+
});
|
|
107
|
+
test("administrators do not bypass an existing node owner", async () => {
|
|
108
|
+
db.run("INSERT INTO nodes(node_id,node_name,alias,network_id,owner_user_id) VALUES('n_owned689','owned689','owned689',?1,?2)",
|
|
109
|
+
[owner.network_id, holder.user.user_id]);
|
|
110
|
+
session("owned689", owner.network_id, "n_owned689");
|
|
111
|
+
await denied(admin, "owned689"); await denied(owner, "owned689", "n_owned689");
|
|
112
|
+
expect((await mint(holder, "owned689")).body.node_id).toBe("n_owned689");
|
|
113
|
+
});
|
|
114
|
+
test("viewer and restricted member gates still precede session recovery", async () => {
|
|
115
|
+
session("restricted689"); credential("restricted689");
|
|
116
|
+
db.run("UPDATE network_members SET agent_access='granted' WHERE network_id=?1 AND user_id=?2", [owner.network_id, holder.user.user_id]);
|
|
117
|
+
try { expect((await mint(holder, "restricted689")).body.error).toBe("restricted members cannot create network tokens"); }
|
|
118
|
+
finally { db.run("UPDATE network_members SET agent_access='all' WHERE network_id=?1 AND user_id=?2", [owner.network_id, holder.user.user_id]); }
|
|
119
|
+
db.run("UPDATE network_members SET role='viewer' WHERE network_id=?1 AND user_id=?2", [owner.network_id, member.user.user_id]);
|
|
120
|
+
try { expect((await mint(member, "restricted689")).body.error).toBe("no write access to this network"); }
|
|
121
|
+
finally { db.run("UPDATE network_members SET role='member' WHERE network_id=?1 AND user_id=?2", [owner.network_id, member.user.user_id]); }
|
|
122
|
+
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// #906 key-free existing Codex inventory. Identical public contract in each package.
|
|
2
|
+
export function validCodexInventory(v: any): boolean {
|
|
3
|
+
const fields = (o: any, allowed: string[]) => o && typeof o === 'object' && !Array.isArray(o)
|
|
4
|
+
&& Object.keys(o).every(k => allowed.includes(k));
|
|
5
|
+
const id = (s: any) => typeof s === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/.test(s);
|
|
6
|
+
const nullable = (s: any) => s === null || id(s);
|
|
7
|
+
if (!fields(v, ['observed_at', 'scope', 'rows', 'installation', 'local_discovery']) || !Number.isSafeInteger(v.observed_at) || v.observed_at <= 0
|
|
8
|
+
|| v.scope !== 'hub_bound_nodes' || !Array.isArray(v.rows) || v.rows.length > 200
|
|
9
|
+
|| new Set(v.rows.map((r: any) => r?.node_id)).size !== v.rows.length) return false;
|
|
10
|
+
if (v.installation !== undefined && (!fields(v.installation, ['status', 'version'])
|
|
11
|
+
|| !['found', 'missing', 'unknown'].includes(v.installation.status)
|
|
12
|
+
|| !(v.installation.version === null || (typeof v.installation.version === 'string' && /^\d+\.\d+\.\d+(?:[-+.][0-9A-Za-z.-]+)?$/.test(v.installation.version) && v.installation.version.length <= 64)))) return false;
|
|
13
|
+
if (v.local_discovery !== undefined) {
|
|
14
|
+
const local = v.local_discovery;
|
|
15
|
+
if (!fields(local, ['status', 'rows']) || !['observed', 'unavailable', 'limit'].includes(local.status)
|
|
16
|
+
|| !Array.isArray(local.rows) || (local.status !== 'observed' && local.rows.length !== 0)
|
|
17
|
+
|| !validCodexInventory({ observed_at: v.observed_at, scope: v.scope, rows: local.rows })
|
|
18
|
+
|| local.rows.some((r: any) => r.status !== 'observed' || r.config_revision !== null || v.rows.some((b: any) => b.node_id === r.node_id))) return false;
|
|
19
|
+
}
|
|
20
|
+
for (const r of v.rows) {
|
|
21
|
+
if (!r || !id(r.node_id) || typeof r.alias !== 'string' || !/^[\p{L}\p{N}][\p{L}\p{N}_.-]{0,99}$/u.test(r.alias)) return false;
|
|
22
|
+
if (['unavailable', 'not_codex'].includes(r.status)) {
|
|
23
|
+
if (!fields(r, ['node_id', 'alias', 'status'])) return false;
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
if (r.status !== 'observed' || !fields(r, ['node_id', 'alias', 'status', 'runtime', 'home_ref', 'home_source',
|
|
27
|
+
'config_status', 'configured_provider', 'configured_model', 'provider_ids', 'auth_kind', 'credential_status',
|
|
28
|
+
'account_fingerprint', 'verification', 'effective_state', 'node_configured_model', 'config_revision'])) return false;
|
|
29
|
+
if (r.config_revision !== undefined && r.config_revision !== null && (typeof r.config_revision !== 'string' || !/^[a-f0-9]{64}$/.test(r.config_revision))) return false;
|
|
30
|
+
if (!nullable(r.runtime) || !/^[a-f0-9]{16}$/.test(r.home_ref)
|
|
31
|
+
|| !['host_default', 'config.codexHome', 'node-codex-home', 'config.env'].includes(r.home_source)
|
|
32
|
+
|| !['read', 'missing', 'unreadable'].includes(r.config_status) || !nullable(r.configured_provider)
|
|
33
|
+
|| !nullable(r.configured_model) || !nullable(r.node_configured_model)
|
|
34
|
+
|| !Array.isArray(r.provider_ids) || r.provider_ids.length > 101 || !r.provider_ids.every(id)
|
|
35
|
+
|| !['unknown', 'chatgpt', 'api_key'].includes(r.auth_kind)
|
|
36
|
+
|| !['unknown', 'present', 'unreadable'].includes(r.credential_status)
|
|
37
|
+
|| !(r.account_fingerprint === null || /^[a-f0-9]{16}$/.test(r.account_fingerprint))
|
|
38
|
+
|| r.verification !== 'not_checked' || r.effective_state !== 'not_checked') return false;
|
|
39
|
+
}
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// #906 managed login transport: only explicit actions and secret-free projections.
|
|
2
|
+
export type LoginIntent = { action: 'start' | 'read' | 'cancel' | 'save' | 'accounts'; session_id?: string; label?: string };
|
|
3
|
+
const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
|
|
4
|
+
const object = (v: any) => v && typeof v === 'object' && !Array.isArray(v);
|
|
5
|
+
const keys = (v: any, names: string[]) => Object.keys(v).every(k => names.includes(k));
|
|
6
|
+
export function validLoginIntent(v: any): v is LoginIntent {
|
|
7
|
+
return object(v) && keys(v, ['action','session_id','label'])
|
|
8
|
+
&& ['start','read','cancel','save','accounts'].includes(v.action)
|
|
9
|
+
&& (v.action === 'accounts' ? v.session_id === undefined : typeof v.session_id === 'string' && uuid.test(v.session_id))
|
|
10
|
+
&& (v.action === 'save' ? typeof v.label === 'string' && !!v.label.trim() && v.label.length <= 100 && !/[\x00-\x1f\x7f]/.test(v.label) : v.label === undefined);
|
|
11
|
+
}
|
|
12
|
+
export function validLoginReceipt(v: any, intent: LoginIntent, network: string, daemon: string): boolean {
|
|
13
|
+
if (!object(v)) return false;
|
|
14
|
+
if (intent.action === 'accounts') return keys(v, ['accounts']) && Array.isArray(v.accounts) && v.accounts.length <= 100
|
|
15
|
+
&& v.accounts.every((a: any) => object(a) && keys(a, ['version','network_id','daemon_node_id','account_id','label','created_at','auth_state'])
|
|
16
|
+
&& a.version === 1 && a.network_id === network && a.daemon_node_id === daemon
|
|
17
|
+
&& typeof a.account_id === 'string' && uuid.test(a.account_id)
|
|
18
|
+
&& typeof a.label === 'string' && a.label.length <= 100
|
|
19
|
+
&& Number.isSafeInteger(a.created_at) && a.auth_state === 'not_checked');
|
|
20
|
+
if (!keys(v, ['request_id','status','error','challenge','account_id']) || v.request_id !== intent.session_id
|
|
21
|
+
|| !['idle','starting','awaiting_user','verifying','authenticated','cancelled','failed'].includes(v.status)) return false;
|
|
22
|
+
if (v.error !== undefined && !['login_start_failed','login_rejected','account_read_failed','login_process_exited','login_expired'].includes(v.error)) return false;
|
|
23
|
+
if (v.account_id !== undefined && (v.status !== 'authenticated' || typeof v.account_id !== 'string' || !uuid.test(v.account_id))) return false;
|
|
24
|
+
if (intent.action === 'cancel' && v.status !== 'cancelled') return false;
|
|
25
|
+
if (intent.action === 'save' && (v.status !== 'authenticated' || !v.account_id)) return false;
|
|
26
|
+
if (v.status === 'awaiting_user') return object(v.challenge) && keys(v.challenge, ['loginId','verificationUrl','userCode'])
|
|
27
|
+
&& typeof v.challenge.loginId === 'string' && uuid.test(v.challenge.loginId)
|
|
28
|
+
&& v.challenge.verificationUrl === 'https://auth.openai.com/codex/device'
|
|
29
|
+
&& typeof v.challenge.userCode === 'string' && /^[A-Z0-9-]{4,32}$/i.test(v.challenge.userCode);
|
|
30
|
+
return v.challenge === undefined;
|
|
31
|
+
}
|