@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
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
// #1473 (#909) — the Hub's Skills / secrets / Provider catalogs had MCP tools
|
|
2
|
+
// but no HTTP read surface, so the desktop client shipped a fixture page
|
|
3
|
+
// (agent-network-app/src/hub-scope-demo.ts: "Hub 这些写接口还没接通 ... 不发请求").
|
|
4
|
+
//
|
|
5
|
+
// These three endpoints are read-only and user-token only. The load-bearing
|
|
6
|
+
// properties are:
|
|
7
|
+
// * a NODE token cannot enumerate the network's catalogs;
|
|
8
|
+
// * a plain member of another network cannot read this network's catalogs;
|
|
9
|
+
// * pending SkillHub submissions stay invisible unless the caller reviews;
|
|
10
|
+
// * NO secret value ever appears in a response body (asserted with a
|
|
11
|
+
// sentinel that would be trivially visible if a value were serialized).
|
|
12
|
+
//
|
|
13
|
+
// The sentinel test is deliberately byte-level on the raw response text: a
|
|
14
|
+
// future field like `value_preview` would pass a JSON-shape assertion while
|
|
15
|
+
// still leaking the secret.
|
|
16
|
+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
17
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
18
|
+
import { tmpdir } from "node:os";
|
|
19
|
+
import { join } from "node:path";
|
|
20
|
+
|
|
21
|
+
const PRIVATE_DB_DIR = mkdtempSync(join(tmpdir(), "anet-hub-catalog-"));
|
|
22
|
+
process.env.COMMHUB_DB ||= join(PRIVATE_DB_DIR, "hub.db");
|
|
23
|
+
// The vault encrypts on write; set the master key before db.ts/vault.ts load.
|
|
24
|
+
process.env.ANET_HUB_SECRET_VAULT_KEY ||= "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff";
|
|
25
|
+
|
|
26
|
+
let server: ReturnType<typeof Bun.serve>;
|
|
27
|
+
let base = "";
|
|
28
|
+
let ownerToken = "", strangerToken = "", nodeToken = "";
|
|
29
|
+
let ownerNet = "", strangerNet = "", ownerUserId = "";
|
|
30
|
+
const SECRET_NAME = "PROVIDER_SENTINEL_KEY";
|
|
31
|
+
const SECRET_VALUE = "sentinel-value-DO-NOT-LEAK-4f9a2c";
|
|
32
|
+
|
|
33
|
+
const get = async (path: string, token: string) => {
|
|
34
|
+
const r = await fetch(`${base}${path}`, { headers: { Authorization: `Bearer ${token}` } });
|
|
35
|
+
const text = await r.text();
|
|
36
|
+
let body: any = null;
|
|
37
|
+
try { body = JSON.parse(text); } catch { body = null; }
|
|
38
|
+
return { status: r.status, body, text };
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
beforeAll(async () => {
|
|
42
|
+
const { db } = await import("./db.js");
|
|
43
|
+
const { register, createNetworkTokenForNode } = await import("./auth.js");
|
|
44
|
+
const { vaultUpsert } = await import("./vault.js");
|
|
45
|
+
const stamp = Date.now();
|
|
46
|
+
|
|
47
|
+
const owner = register(`hc_owner_${stamp}`, "HcOwner-Strong-1!");
|
|
48
|
+
const stranger = register(`hc_stranger_${stamp}`, "HcStranger-Strong-1!");
|
|
49
|
+
expect(owner.ok && stranger.ok).toBe(true);
|
|
50
|
+
ownerToken = owner.token!;
|
|
51
|
+
strangerToken = stranger.token!;
|
|
52
|
+
ownerNet = owner.network_id!;
|
|
53
|
+
strangerNet = stranger.network_id!;
|
|
54
|
+
ownerUserId = db.get<{ user_id: string }>("SELECT user_id FROM users WHERE username = ?1", `hc_owner_${stamp}`)!.user_id;
|
|
55
|
+
|
|
56
|
+
// A node token in the SAME network: it must still be refused, because a node
|
|
57
|
+
// is not a person and may not enumerate catalogs.
|
|
58
|
+
const nodeTok = createNetworkTokenForNode(ownerUserId, ownerNet, "hc-node", "n_hc_test");
|
|
59
|
+
expect(nodeTok.ok).toBe(true);
|
|
60
|
+
nodeToken = nodeTok.token!;
|
|
61
|
+
|
|
62
|
+
// Published + pending skills in the owner's network.
|
|
63
|
+
const skill = (id: string, status: string, slug: string) => db.run(
|
|
64
|
+
`INSERT INTO skillhub_skills (skill_id, network_id, slug, name, description, content, content_hash, version, status, source_type, source_alias, created_at, updated_at)
|
|
65
|
+
VALUES (?1, ?2, ?3, ?3, 'd', '# SKILL body', 'hash-' || ?1, '1.0.0', ?4, 'node', 'hc-node', datetime('now'), datetime('now'))`,
|
|
66
|
+
[id, ownerNet, slug, status],
|
|
67
|
+
);
|
|
68
|
+
skill("skill_hc_pub", "published", "hc-published");
|
|
69
|
+
skill("skill_hc_pending", "pending", "hc-pending");
|
|
70
|
+
|
|
71
|
+
// The sentinel secret. Names may be shown; values never.
|
|
72
|
+
vaultUpsert(ownerNet, SECRET_NAME, SECRET_VALUE);
|
|
73
|
+
|
|
74
|
+
db.run(
|
|
75
|
+
`INSERT INTO hub_provider_configs (network_id, provider_id, revision, config_json, secret_key_ref, updated_at)
|
|
76
|
+
VALUES (?1, 'hc-provider', 3, ?2, ?3, ?4)`,
|
|
77
|
+
[ownerNet, JSON.stringify({ id: "hc-provider", label: "HC Provider", enabled: true, protocol: "openai-responses", baseUrl: "https://example.test/v1", models: ["m1"] }), "HC_PROVIDER_KEY", Date.now()],
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
const mod = await import("./server.js");
|
|
81
|
+
server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
82
|
+
base = `http://127.0.0.1:${server.port}`;
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
afterAll(() => {
|
|
86
|
+
try { server?.stop(true); } catch {}
|
|
87
|
+
try { rmSync(PRIVATE_DB_DIR, { recursive: true, force: true }); } catch {}
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
describe("GET /api/skills", () => {
|
|
91
|
+
test("owner sees published skills and no content body", async () => {
|
|
92
|
+
const r = await get(`/api/skills?network_id=${ownerNet}`, ownerToken);
|
|
93
|
+
expect(r.status).toBe(200);
|
|
94
|
+
expect(r.body.ok).toBe(true);
|
|
95
|
+
expect(r.body.reviewer).toBe(true);
|
|
96
|
+
expect(r.body.network_id).toBe(ownerNet);
|
|
97
|
+
const slugs = r.body.skills.map((s: any) => s.slug);
|
|
98
|
+
expect(slugs).toContain("hc-published");
|
|
99
|
+
// Pending is opt-in even for a reviewer.
|
|
100
|
+
expect(slugs).not.toContain("hc-pending");
|
|
101
|
+
// The list is metadata only — a body field would mean SKILL.md text leaked.
|
|
102
|
+
for (const s of r.body.skills) expect(s.content).toBeUndefined();
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
test("reviewer may ask for pending submissions", async () => {
|
|
106
|
+
const r = await get(`/api/skills?network_id=${ownerNet}&include_pending=1`, ownerToken);
|
|
107
|
+
expect(r.status).toBe(200);
|
|
108
|
+
const slugs = r.body.skills.map((s: any) => s.slug);
|
|
109
|
+
expect(slugs).toContain("hc-pending");
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
// 2026-10-31 —— **两条「providers」读的是不同的表**,而空数组在载荷里长得一样:
|
|
113
|
+
// GET /api/providers → hub_provider_configs | MCP list_providers → providers / provider_models
|
|
114
|
+
// 客户端「没有可选模型」既可能是前者空,也可能是后者空 ⇒ 必须能在载荷里区分。
|
|
115
|
+
test("an empty registry says which table it read, and whether the CLI registry has rows", async () => {
|
|
116
|
+
const { db } = await import("./db.js");
|
|
117
|
+
// strangerNet 里没有 hub_provider_configs 行;先看「两张表都空」这一档
|
|
118
|
+
const before = await get(`/api/providers?network_id=${strangerNet}`, strangerToken);
|
|
119
|
+
expect(before.status).toBe(200);
|
|
120
|
+
expect(before.body.state).toBe("unconfigured");
|
|
121
|
+
expect(before.body.source_table).toBe("hub_provider_configs");
|
|
122
|
+
expect(before.body.counts.providers).toBe(0);
|
|
123
|
+
expect(before.body.hint).toContain("hub_provider_configs");
|
|
124
|
+
|
|
125
|
+
// 再给 CLI 注册表塞一行(另一张表),本端点**仍然为空**,但 hint 必须改口
|
|
126
|
+
db.run(
|
|
127
|
+
`INSERT OR REPLACE INTO providers (provider_id, network_id, name, vendor, base_url, secret_key_ref, created_at, created_by, enabled)
|
|
128
|
+
VALUES ('hc-cli-only', ?1, 'hc-cli-only', 'openai', 'https://api.example.com', 'K', ?2, 'test', 1)`,
|
|
129
|
+
[strangerNet, Date.now()],
|
|
130
|
+
);
|
|
131
|
+
const after = await get(`/api/providers?network_id=${strangerNet}`, strangerToken);
|
|
132
|
+
expect(after.body.providers).toHaveLength(0); // 本端点还是空
|
|
133
|
+
expect(after.body.counts.providers_in_cli_registry).toBeGreaterThan(0);
|
|
134
|
+
expect(after.body.hint).toContain("不会自动出现在本端点");
|
|
135
|
+
// 反向:有行时不该带 hint(载荷不变胖,且「有理由」与「没理由」可区分)
|
|
136
|
+
const owner = await get(`/api/providers?network_id=${ownerNet}`, ownerToken);
|
|
137
|
+
expect(owner.body.state).toBe("configured");
|
|
138
|
+
expect("hint" in owner.body).toBe(false);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
test("a member of another network is refused", async () => {
|
|
142
|
+
const r = await get(`/api/skills?network_id=${ownerNet}`, strangerToken);
|
|
143
|
+
expect(r.status).toBe(403);
|
|
144
|
+
// Cross-network access is refused by REST scope resolution BEFORE the role
|
|
145
|
+
// check runs, so the error names the scope gate. Either way: 403, no data.
|
|
146
|
+
expect(String(r.body.error)).toMatch(/access denied|permission_denied/);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
test("a node token is refused even inside its own network", async () => {
|
|
150
|
+
const r = await get(`/api/skills?network_id=${ownerNet}`, nodeToken);
|
|
151
|
+
expect(r.status).toBe(403);
|
|
152
|
+
expect(r.body.error).toBe("user_token_required");
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
test("include_pending is ignored for a non-reviewer of that network", async () => {
|
|
156
|
+
// The stranger's own network has no skills; the point is that asking for
|
|
157
|
+
// pending must not widen what they can see when they ask about their own.
|
|
158
|
+
const r = await get(`/api/skills?network_id=${strangerNet}&include_pending=1`, strangerToken);
|
|
159
|
+
expect(r.status).toBe(200);
|
|
160
|
+
expect(r.body.reviewer).toBe(true); // they own their own network
|
|
161
|
+
expect(r.body.skills).toEqual([]);
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
describe("GET /api/secrets", () => {
|
|
166
|
+
test("returns key names and timestamps, never the value", async () => {
|
|
167
|
+
const r = await get(`/api/secrets?network_id=${ownerNet}`, ownerToken);
|
|
168
|
+
expect(r.status).toBe(200);
|
|
169
|
+
const names = r.body.keys.map((k: any) => k.key);
|
|
170
|
+
expect(names).toContain(SECRET_NAME);
|
|
171
|
+
// <-- The load-bearing assertion: raw body text must not contain the value.
|
|
172
|
+
expect(r.text).not.toContain(SECRET_VALUE);
|
|
173
|
+
expect(r.text).not.toContain("ciphertext");
|
|
174
|
+
expect(r.text).not.toContain("iv");
|
|
175
|
+
expect(r.text).not.toContain("tag");
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
test("a member of another network is refused and learns no key names", async () => {
|
|
179
|
+
const r = await get(`/api/secrets?network_id=${ownerNet}`, strangerToken);
|
|
180
|
+
expect(r.status).toBe(403);
|
|
181
|
+
expect(r.text).not.toContain(SECRET_NAME);
|
|
182
|
+
expect(r.text).not.toContain(SECRET_VALUE);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
test("a node token is refused", async () => {
|
|
186
|
+
const r = await get(`/api/secrets?network_id=${ownerNet}`, nodeToken);
|
|
187
|
+
expect(r.status).toBe(403);
|
|
188
|
+
expect(r.body.error).toBe("user_token_required");
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
describe("GET /api/providers", () => {
|
|
193
|
+
test("returns the registry without secret references", async () => {
|
|
194
|
+
const r = await get(`/api/providers?network_id=${ownerNet}`, ownerToken);
|
|
195
|
+
expect(r.status).toBe(200);
|
|
196
|
+
expect(r.body.providers).toHaveLength(1);
|
|
197
|
+
expect(r.body.providers[0]).toMatchObject({ id: "hc-provider", label: "HC Provider", source: "hub" });
|
|
198
|
+
// The vault key NAME is a hint an attacker does not need; `exposeRefs` is
|
|
199
|
+
// false here on purpose.
|
|
200
|
+
expect(r.body.providers[0].secret_key_ref).toBeUndefined();
|
|
201
|
+
expect(r.text).not.toContain("HC_PROVIDER_KEY");
|
|
202
|
+
expect(r.text).not.toContain(SECRET_VALUE);
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
test("a member of another network is refused", async () => {
|
|
206
|
+
const r = await get(`/api/providers?network_id=${ownerNet}`, strangerToken);
|
|
207
|
+
expect(r.status).toBe(403);
|
|
208
|
+
expect(r.text).not.toContain("hc-provider");
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
test("a node token is refused", async () => {
|
|
212
|
+
const r = await get(`/api/providers?network_id=${ownerNet}`, nodeToken);
|
|
213
|
+
expect(r.status).toBe(403);
|
|
214
|
+
expect(r.body.error).toBe("user_token_required");
|
|
215
|
+
});
|
|
216
|
+
// 2026-10-31 —— **写侧原来只有 MCP**:客户端能显示「还没有 provider」,却没办法把它变成「有」。
|
|
217
|
+
// 这条把「第一行」确认成一次 HTTP 调用,并核对三件事:落库、读回来一致、revision 冲突是 409。
|
|
218
|
+
test("PUT /api/providers creates the first row, and the read side sees it", async () => {
|
|
219
|
+
const body = {
|
|
220
|
+
revision: 0,
|
|
221
|
+
provider: {
|
|
222
|
+
id: "hc-first", label: "First Provider", enabled: true,
|
|
223
|
+
protocol: "openai-chat-completions", baseUrl: "https://api.example.com/v1",
|
|
224
|
+
models: ["gpt-x"], key: "sk-test-not-a-real-secret",
|
|
225
|
+
},
|
|
226
|
+
};
|
|
227
|
+
const r = await fetch(`${base}/api/providers?network_id=${ownerNet}`, {
|
|
228
|
+
method: "PUT",
|
|
229
|
+
headers: { Authorization: `Bearer ${ownerToken}`, "content-type": "application/json" },
|
|
230
|
+
body: JSON.stringify(body),
|
|
231
|
+
});
|
|
232
|
+
const saved = await r.json() as any;
|
|
233
|
+
expect(r.status).toBe(200);
|
|
234
|
+
expect(saved.ok).toBe(true);
|
|
235
|
+
expect(saved.provider.id).toBe("hc-first");
|
|
236
|
+
expect(saved.provider.revision).toBe(1);
|
|
237
|
+
// 密钥永不回显
|
|
238
|
+
expect(JSON.stringify(saved)).not.toContain("sk-test-not-a-real-secret");
|
|
239
|
+
|
|
240
|
+
const read = await get(`/api/providers?network_id=${ownerNet}`, ownerToken);
|
|
241
|
+
const ids = read.body.providers.map((p: any) => p.id);
|
|
242
|
+
expect(ids).toContain("hc-first");
|
|
243
|
+
|
|
244
|
+
// 用旧 revision 再写一次 ⇒ 409(乐观锁;这正是「两个人同时改」的那一格)
|
|
245
|
+
const stale = await fetch(`${base}/api/providers?network_id=${ownerNet}`, {
|
|
246
|
+
method: "PUT",
|
|
247
|
+
headers: { Authorization: `Bearer ${ownerToken}`, "content-type": "application/json" },
|
|
248
|
+
body: JSON.stringify({ ...body, revision: 0, provider: { ...body.provider, label: "Second Writer" } }),
|
|
249
|
+
});
|
|
250
|
+
expect(stale.status).toBe(409);
|
|
251
|
+
expect((await stale.json() as any).error).toBe("hub_provider_revision_conflict");
|
|
252
|
+
|
|
253
|
+
// 别的网络成员不许写
|
|
254
|
+
const foreign = await fetch(`${base}/api/providers?network_id=${ownerNet}`, {
|
|
255
|
+
method: "PUT",
|
|
256
|
+
headers: { Authorization: `Bearer ${strangerToken}`, "content-type": "application/json" },
|
|
257
|
+
body: JSON.stringify({ ...body, revision: 1 }),
|
|
258
|
+
});
|
|
259
|
+
expect(foreign.status).toBe(403);
|
|
260
|
+
|
|
261
|
+
// 清理:这条测试造了一行,后面的断言按「1 行」计数,不能留痕
|
|
262
|
+
const { db } = await import("./db.js");
|
|
263
|
+
db.run(`DELETE FROM hub_provider_configs WHERE network_id = ?1 AND provider_id = 'hc-first'`, [ownerNet]);
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
});
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// 2026-10-31 —— **本地直跑会看到 3 条红,那不是回归**。
|
|
2
|
+
// 这 7 条里有 3 条(HTTP 端点 / names-only 密钥 / daemon 队列)依赖
|
|
3
|
+
// `.github/workflows/hub-provider-core.yml` 里的容器环境(`tests/test907-hub-provider/run.sh`,
|
|
4
|
+
// `--network none` + 特定 host 映射);在仓外 `bun test src/hub-provider-config.test.ts`
|
|
5
|
+
// 会看到 `status: "failed"`(服务端 URL 走不到 secure transport)。
|
|
6
|
+
// ⇒ 按本仓规矩把环境依赖写在文件头:否则下一个人会把 3 条环境红当成自己改坏的。
|
|
7
|
+
// ⇒ 判定这条文件是否健康,看那套 Docker 测试,不看本地 bun test。
|
|
8
|
+
|
|
9
|
+
import './require-explicit-test-db';
|
|
10
|
+
import { afterAll, beforeEach, expect, test } from 'bun:test';
|
|
11
|
+
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
|
|
12
|
+
import { tmpdir } from 'node:os';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import { db } from './db';
|
|
15
|
+
import { registerTools } from './tools';
|
|
16
|
+
import { vaultGet } from './vault';
|
|
17
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
18
|
+
import { reconcileProviderSnapshots, secureProviderTransport } from '../../agent-node/src/runtime/daemon-provider-snapshot';
|
|
19
|
+
import { DaemonProviderStore } from '../../agent-network/src/daemon-provider-store';
|
|
20
|
+
const net = 'net_hub907', user = 'u_hub907', daemonId = 'n_hub907', alias = 'daemon907', token = 'tok_hub907';
|
|
21
|
+
const root = mkdtempSync(join(tmpdir(), 'hub907-')), key = 'TEST-ONLY-shared-provider-key';
|
|
22
|
+
function cleanup() {
|
|
23
|
+
for (const t of ['daemon_provider_writes', 'daemon_provider_applications', 'daemon_provider_logins']) db.run(`DELETE FROM ${t} WHERE request_id IN (SELECT request_id FROM daemon_provider_snapshots WHERE network_id=?1)`, [net]);
|
|
24
|
+
for (const t of ['hub_provider_bindings', 'hub_provider_configs', 'network_secrets', 'daemon_provider_snapshots', 'nodes', 'api_tokens', 'network_members']) db.run(`DELETE FROM ${t} WHERE network_id=?1`, [net]);
|
|
25
|
+
db.run('DELETE FROM networks WHERE network_id=?1', [net]); db.run('DELETE FROM users WHERE user_id=?1', [user]);
|
|
26
|
+
}
|
|
27
|
+
beforeEach(() => {
|
|
28
|
+
cleanup(); rmSync(join(root, '.anet'), { recursive: true, force: true });
|
|
29
|
+
process.env.ANET_HUB_SECRET_VAULT_KEY = '42'.repeat(32);
|
|
30
|
+
db.run("INSERT INTO users(user_id,username,password_hash,role) VALUES(?1,?1,'x','user')", [user]);
|
|
31
|
+
db.run('INSERT INTO networks(network_id,network_name,owner_id) VALUES(?1,?1,?2)', [net, user]);
|
|
32
|
+
db.run("INSERT INTO network_members(user_id,network_id,role) VALUES(?1,?2,'owner')", [user, net]);
|
|
33
|
+
db.run('INSERT INTO nodes(node_id,node_name,alias,network_id,config_snapshot) VALUES(?1,?2,?2,?3,?4)', [daemonId, alias, net, JSON.stringify({ role: 'host_supervisor' })]);
|
|
34
|
+
db.run("INSERT INTO api_tokens(token_id,user_id,network_id,scope,name,token_hash) VALUES(?1,?2,?3,'network',?4,?5)", [token, user, net, `node:${alias}`, `hash_${token}`]);
|
|
35
|
+
const dir = join(root, '.anet/nodes', alias); mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
36
|
+
writeFileSync(join(dir, 'config.json'), JSON.stringify({ role: 'host_supervisor', node_id: daemonId, network_id: net }), { mode: 0o600 });
|
|
37
|
+
});
|
|
38
|
+
afterAll(() => { cleanup(); rmSync(root, { recursive: true, force: true }); });
|
|
39
|
+
function client(kind = 'human') {
|
|
40
|
+
const handlers: Record<string, any> = {}, server = new McpServer({ name: 'test907', version: '0' }) as any;
|
|
41
|
+
const tool = server.tool.bind(server), register = server.registerTool.bind(server);
|
|
42
|
+
server.tool = (name: string, desc: any, shape: any, handler: any) => { handlers[name] = handler; return tool(name, desc, shape, handler); };
|
|
43
|
+
server.registerTool = (name: string, config: any, handler: any) => { handlers[name] = handler; return register(name, config, handler); };
|
|
44
|
+
registerTools(server, undefined, kind === 'daemon' ? net : null, kind === 'anonymous' ? null : user, alias, kind === 'daemon', kind === 'daemon' ? token : null);
|
|
45
|
+
return async (name: string, args: any = {}) => JSON.parse((await handlers[name](args)).content[0].text);
|
|
46
|
+
}
|
|
47
|
+
const provider = () => ({ id: 'shared', label: 'Shared model', enabled: true, protocol: 'openai-responses', baseUrl: 'https://provider.example/v1', models: ['fixture-model'], key });
|
|
48
|
+
const save = (human: ReturnType<typeof client>, value = provider(), revision = 0) => human('daemon_provider_snapshot', { action: 'hub_put', id: value.id, network_id: net, revision, provider: value });
|
|
49
|
+
const bind = (human: ReturnType<typeof client>, target = daemonId, revision = 1) => human('daemon_provider_snapshot', { action: 'hub_bind', network_id: net, id: 'shared', revision, provider: { daemon_node_id: target, daemon_revision: 0, confirm: true } });
|
|
50
|
+
test('HTTP Hub and API endpoint support save, explicit bind and exact private-store readback', async () => {
|
|
51
|
+
expect(secureProviderTransport('http://hub907.example.test')).toBe(true);
|
|
52
|
+
expect(secureProviderTransport('ftp://hub907.example.test')).toBe(false);
|
|
53
|
+
expect(secureProviderTransport('http://user:password@hub907.example.test')).toBe(false);
|
|
54
|
+
const human = client(), daemon = client('daemon');
|
|
55
|
+
const config = { ...provider(), baseUrl: 'http://provider.example/v1' };
|
|
56
|
+
const saved = await save(human, config); expect(saved.ok).toBe(true);
|
|
57
|
+
expect(saved.provider.baseUrl).toBe(config.baseUrl);
|
|
58
|
+
const queued = await bind(human); expect(queued.ok).toBe(true);
|
|
59
|
+
await reconcileProviderSnapshots({ workDir: root, alias, networkId: net, daemonId,
|
|
60
|
+
serverUrl: 'http://hub907.example.test', callCommHub: daemon, warn: message => console.warn(message) });
|
|
61
|
+
const receipt = await human('daemon_provider_snapshot', { action: 'read', id: queued.request_id, network_id: net });
|
|
62
|
+
expect(receipt.status).toBe('succeeded');
|
|
63
|
+
expect(receipt.snapshot.providers[0].runtimes[0].auth[0].baseUrl).toBe(config.baseUrl);
|
|
64
|
+
expect(JSON.stringify([saved, queued, receipt])).not.toContain(key);
|
|
65
|
+
const store = new DaemonProviderStore(join(root, '.anet/nodes', alias));
|
|
66
|
+
await store.withApiKey({ revision: 1, providerId: queued.provider_reference.daemon_provider_id, authId: 'hub_key', model: 'fixture-model' }, async actual => {
|
|
67
|
+
expect(actual.baseUrl).toBe(config.baseUrl); expect(actual.key).toBe(key);
|
|
68
|
+
}); // Exact synthetic key in local callback, no external model request.
|
|
69
|
+
for (const baseUrl of ['ftp://provider.example/v1', 'http://user:pass@provider.example/v1', 'http://provider.example/v1?key=secret']) {
|
|
70
|
+
expect(await save(human, { ...provider(), id: 'invalid', baseUrl })).toMatchObject({ ok: false, error: 'invalid_hub_provider' });
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
test('existing names-only vault key → Provider reference → actual daemon store, without re-entering key', async () => {
|
|
74
|
+
const human = client(), daemon = client('daemon');
|
|
75
|
+
expect(await human('upsert_network_secret', { network_id: net, key: 'SHARED_API_KEY', value: key })).toMatchObject({ ok: true });
|
|
76
|
+
const { key: ignored, ...config } = provider();
|
|
77
|
+
const saved = await save(human, { ...config, secretKeyRef: 'SHARED_API_KEY' } as any);
|
|
78
|
+
expect(saved.provider).toMatchObject({ secret_key_ref: 'SHARED_API_KEY', credential_present: true });
|
|
79
|
+
expect(db.get<any>('SELECT secret_key_ref FROM hub_provider_configs WHERE network_id=?1', net).secret_key_ref).toBe('SHARED_API_KEY');
|
|
80
|
+
const legacy = await human('daemon_provider_snapshot', { action: 'hub_read', id: 'hub', network_id: net });
|
|
81
|
+
expect(legacy.providers[0].secret_key_ref).toBeUndefined(); // older strict client shape unchanged
|
|
82
|
+
const modern = await human('daemon_provider_snapshot', { action: 'hub_read', id: 'hub', network_id: net, provider: { include_secret_refs: true } });
|
|
83
|
+
expect(modern.secret_reference_supported).toBe(true); expect(modern.providers[0].secret_key_ref).toBe('SHARED_API_KEY');
|
|
84
|
+
expect(JSON.stringify([saved, legacy, modern])).not.toContain(key);
|
|
85
|
+
const queued = await bind(human); expect(queued.ok).toBe(true);
|
|
86
|
+
await reconcileProviderSnapshots({ workDir: root, alias, networkId: net, daemonId, serverUrl: 'https://hub907.example.test', callCommHub: daemon, warn: message => console.warn(message) });
|
|
87
|
+
const receipt = await human('daemon_provider_snapshot', { action: 'read', id: queued.request_id, network_id: net });
|
|
88
|
+
expect(receipt.status).toBe('succeeded'); expect(receipt.snapshot.providers[0].runtimes[0].auth[0].credential_present).toBe(true);
|
|
89
|
+
const store = new DaemonProviderStore(join(root, '.anet/nodes', alias));
|
|
90
|
+
await store.withApiKey({ revision: receipt.snapshot.revision, providerId: queued.provider_reference.daemon_provider_id, authId: 'hub_key', model: 'fixture-model' }, async profile => {
|
|
91
|
+
expect(profile.key).toBe(key); expect(profile.baseUrl).toBe(config.baseUrl);
|
|
92
|
+
}); // synthetic local callback only; no model/vendor request
|
|
93
|
+
expect(JSON.stringify(receipt)).not.toContain(key);
|
|
94
|
+
// Switching back to Provider-owned plaintext never changes the reusable named key.
|
|
95
|
+
await save(human, { ...provider(), key: 'TEST-ONLY-provider-specific' }, 1);
|
|
96
|
+
expect(vaultGet(net, 'SHARED_API_KEY')).toBe(key);
|
|
97
|
+
expect(db.get<any>('SELECT secret_key_ref FROM hub_provider_configs WHERE network_id=?1', net).secret_key_ref).not.toBe('SHARED_API_KEY');
|
|
98
|
+
});
|
|
99
|
+
test('missing or ambiguous references do not save; explicit ref replacement updates the stored reference', async () => {
|
|
100
|
+
const human = client(); const { key: ignored, ...config } = provider();
|
|
101
|
+
expect(await save(human, { ...config, secretKeyRef: 'MISSING_KEY' } as any)).toMatchObject({ ok: false, error: 'provider_secret_reference_missing' });
|
|
102
|
+
expect(await save(human, { ...provider(), secretKeyRef: 'SHARED_API_KEY' } as any)).toMatchObject({ ok: false, error: 'invalid_provider_secret_reference' });
|
|
103
|
+
await save(human);
|
|
104
|
+
await human('upsert_network_secret', { network_id: net, key: 'SECOND_API_KEY', value: 'TEST-ONLY-second-key' });
|
|
105
|
+
expect((await save(human, { ...config, secretKeyRef: 'SECOND_API_KEY' } as any, 1)).provider.secret_key_ref).toBe('SECOND_API_KEY');
|
|
106
|
+
expect(db.get<any>('SELECT secret_key_ref FROM hub_provider_configs WHERE network_id=?1', net).secret_key_ref).toBe('SECOND_API_KEY');
|
|
107
|
+
});
|
|
108
|
+
test('actual Hub tool atomically saves encrypted Provider; metadata read and conflict never echo key', async () => {
|
|
109
|
+
const human = client(); const result = await save(human); expect(result.ok).toBe(true);
|
|
110
|
+
expect(result.provider).toMatchObject({ id: 'shared', revision: 1, source: 'hub', credential_present: true, compatible_runtimes: ['codex-tui'] });
|
|
111
|
+
const read = await human('daemon_provider_snapshot', { action: 'hub_read', id: 'hub', network_id: net }); expect(read.providers).toHaveLength(1);
|
|
112
|
+
// 2026-10-31 —— **精确键集**(#3171):客户端「可选模型」这一面直接消费这两个投影,
|
|
113
|
+
// 而多给一个键(尤其 secret_key_ref)在这条线上是最严重的那类改动。
|
|
114
|
+
// 实际四键(我第一版漏了 network_id —— 断言当场纠正)。
|
|
115
|
+
expect(Object.keys(read).sort()).toEqual(["network_id", "ok", "providers", "source"]);
|
|
116
|
+
// provider 视图实际 12 键(我第一版写了 6 个,漏了 baseUrl/enabled/models/protocol/updated_at/verification)
|
|
117
|
+
expect(Object.keys(result.provider).sort()).toEqual([
|
|
118
|
+
"baseUrl", "compatible_runtimes", "credential_present", "enabled", "id", "label",
|
|
119
|
+
"models", "protocol", "revision", "source", "updated_at", "verification",
|
|
120
|
+
]);
|
|
121
|
+
expect(JSON.stringify([result, read])).not.toContain(key);
|
|
122
|
+
expect(await save(human)).toMatchObject({ ok: false, error: 'hub_provider_revision_conflict' });
|
|
123
|
+
const secret = db.get<any>('SELECT ciphertext FROM network_secrets WHERE network_id=?1', net);
|
|
124
|
+
expect(Buffer.from(secret.ciphertext).toString()).not.toContain(key);
|
|
125
|
+
});
|
|
126
|
+
test('Hub → actual daemon queue → pinned CLI store → redacted receipt, not runtime application', async () => {
|
|
127
|
+
const human = client(), daemon = client('daemon'); await save(human);
|
|
128
|
+
const queued = await bind(human); expect(queued.ok).toBe(true); expect(queued.status).toBe('pending');
|
|
129
|
+
expect(JSON.stringify(queued)).not.toContain(key);
|
|
130
|
+
await reconcileProviderSnapshots({ workDir: root, alias, networkId: net, daemonId, serverUrl: 'https://hub907.example.test', callCommHub: daemon, warn: message => console.warn(message) });
|
|
131
|
+
const read = await human('daemon_provider_snapshot', { action: 'read', id: queued.request_id, network_id: net });
|
|
132
|
+
expect(read.status).toBe('succeeded'); expect(read.snapshot.revision).toBe(1);
|
|
133
|
+
expect(read.snapshot.providers[0]).toMatchObject({ id: queued.provider_reference.daemon_provider_id, label: 'Hub · Shared model' });
|
|
134
|
+
expect(read.snapshot.providers[0].runtimes[0].auth[0]).toMatchObject({ id: 'hub_key', models: ['fixture-model'], application: 'not_applied', verification: 'not_checked' });
|
|
135
|
+
expect(JSON.stringify(read)).not.toContain(key);
|
|
136
|
+
});
|
|
137
|
+
test('scope/role boundaries: no node or anonymous writes, no viewer distribution or foreign daemon', async () => {
|
|
138
|
+
expect(await save(client('daemon'))).toMatchObject({ ok: false, error: 'user_token_required' });
|
|
139
|
+
expect(await save(client('anonymous'))).toMatchObject({ ok: false, error: 'user_token_required' });
|
|
140
|
+
const human = client(); await save(human);
|
|
141
|
+
expect(await human('daemon_provider_snapshot', { action: 'hub_read', id: 'hub', network_id: 'foreign' })).toMatchObject({ ok: false, error: 'provider_access_denied' });
|
|
142
|
+
expect(await bind(human, 'foreign')).toMatchObject({ ok: false, error: 'daemon_not_found' });
|
|
143
|
+
db.run("UPDATE network_members SET role='viewer' WHERE network_id=?1 AND user_id=?2", [net, user]);
|
|
144
|
+
expect(await bind(human)).toMatchObject({ ok: false, error: 'provider_access_denied' });
|
|
145
|
+
expect(await save(human)).toMatchObject({ ok: false, error: 'provider_owner_required' });
|
|
146
|
+
});
|
|
147
|
+
test('protocol mismatch never queues Codex; editing source cancels pending distribution, not installed copies', async () => {
|
|
148
|
+
const human = client(); await save(human, { ...provider(), protocol: 'openai-chat-completions' });
|
|
149
|
+
expect(await bind(human)).toMatchObject({ ok: false, error: 'runtime_protocol_not_supported' });
|
|
150
|
+
await save(human, provider(), 1);
|
|
151
|
+
const queued = await bind(human, daemonId, 2);
|
|
152
|
+
expect(queued.ok).toBe(true); await save(human, { ...provider(), enabled: false }, 2);
|
|
153
|
+
const read = await human('daemon_provider_snapshot', { action: 'read', id: queued.request_id, network_id: net });
|
|
154
|
+
expect(read).toMatchObject({ status: 'failed', error: 'hub_provider_source_changed' });
|
|
155
|
+
expect(db.get('SELECT request_id FROM daemon_provider_writes WHERE request_id=?1', queued.request_id)).toBeNull();
|
|
156
|
+
});
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// #907: real network-scoped catalog + explicit dispatch; not a Provider proxy.
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { db } from './db';
|
|
4
|
+
import { getUserNetworkRole } from './auth';
|
|
5
|
+
import { vaultUpsert, vaultGet, vaultListKeys, VaultError } from './vault';
|
|
6
|
+
import { requestProviderWrite } from './daemon-provider-snapshots';
|
|
7
|
+
type Human = { userId?: string | null; isNode: boolean; networkId: string | null };
|
|
8
|
+
type Config = { id: string; label: string; enabled: boolean; protocol: 'openai-responses' | 'openai-chat-completions' | 'anthropic-messages'; baseUrl: string; models: string[] };
|
|
9
|
+
const denied = (error: string) => ({ ok: false as const, error });
|
|
10
|
+
const idValid = (id: unknown) => typeof id === 'string' && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(id);
|
|
11
|
+
function auth(h: Human, write: boolean, owner = false) {
|
|
12
|
+
if (h.isNode || !h.userId || !h.networkId) return denied('user_token_required');
|
|
13
|
+
const role = getUserNetworkRole(h.userId, h.networkId);
|
|
14
|
+
if (!role || (owner && role !== 'owner') || (write && !['owner', 'admin'].includes(role))) return denied(owner ? 'provider_owner_required' : 'provider_access_denied');
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
function validConfig(value: any): value is Config {
|
|
18
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
19
|
+
|| Object.keys(value).some(k => !['id', 'label', 'enabled', 'protocol', 'baseUrl', 'models', 'key', 'secretKeyRef'].includes(k))
|
|
20
|
+
|| !idValid(value.id) || typeof value.label !== 'string' || !value.label.trim() || value.label.length > 100
|
|
21
|
+
|| /[\x00-\x1f\x7f]/.test(value.label) || typeof value.enabled !== 'boolean'
|
|
22
|
+
|| !['openai-responses', 'openai-chat-completions', 'anthropic-messages'].includes(value.protocol)
|
|
23
|
+
|| typeof value.baseUrl !== 'string' || value.baseUrl.length > 2048
|
|
24
|
+
|| !Array.isArray(value.models) || !value.models.length || value.models.length > 200
|
|
25
|
+
|| new Set(value.models).size !== value.models.length
|
|
26
|
+
|| value.models.some((m: unknown) => typeof m !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/.test(m))) return false;
|
|
27
|
+
try { const u = new URL(value.baseUrl); return ['https:', 'http:'].includes(u.protocol) && !u.username && !u.password && !u.search && !u.hash; }
|
|
28
|
+
catch { return false; }
|
|
29
|
+
}
|
|
30
|
+
type Row = { revision: number; config_json: string; secret_key_ref: string; updated_at: number };
|
|
31
|
+
function row(networkId: string, id: string) {
|
|
32
|
+
return db.get<Row>('SELECT revision,config_json,secret_key_ref,updated_at FROM hub_provider_configs WHERE network_id=?1 AND provider_id=?2', networkId, id);
|
|
33
|
+
}
|
|
34
|
+
function publicRow(networkId: string, stored: Row, exposeRef = false) {
|
|
35
|
+
const config = JSON.parse(stored.config_json) as Config;
|
|
36
|
+
return { ...config, ...(exposeRef ? { secret_key_ref: stored.secret_key_ref } : {}), revision: stored.revision, updated_at: stored.updated_at, source: 'hub',
|
|
37
|
+
credential_present: vaultListKeys(networkId).includes(stored.secret_key_ref), verification: 'not_checked',
|
|
38
|
+
compatible_runtimes: config.protocol === 'openai-responses' ? ['codex-tui'] : [] };
|
|
39
|
+
}
|
|
40
|
+
export function readHubProviders(h: Human, exposeRefs = false) {
|
|
41
|
+
const refusal = auth(h, false); if (refusal) return refusal;
|
|
42
|
+
const rows = db.all<Row>('SELECT revision,config_json,secret_key_ref,updated_at FROM hub_provider_configs WHERE network_id=?1 ORDER BY provider_id', h.networkId!);
|
|
43
|
+
// 2026-10-31 —— **这个端点的空数组也必须自报家门**(与 MCP list_providers 同一课)。
|
|
44
|
+
// 关键事实:两条「providers」读的是**不同的表** ——
|
|
45
|
+
// GET /api/providers → hub_provider_configs(网络自有的 provider 配置,本函数)
|
|
46
|
+
// MCP list_providers → providers / provider_models
|
|
47
|
+
// 于是「客户端没有可选模型」既可能是「这张表空」,也可能是「另一张表空」,
|
|
48
|
+
// 而两者在载荷里长得一模一样。⇒ 在 source 之外再说清 state 与「另一处叫什么」。
|
|
49
|
+
const otherSource = db.get<{ cnt: number }>(
|
|
50
|
+
'SELECT COUNT(*) AS cnt FROM providers WHERE network_id=?1 AND enabled=1', h.networkId!);
|
|
51
|
+
const otherCount = otherSource?.cnt ?? 0;
|
|
52
|
+
const state = rows.length > 0 ? 'configured' as const : 'unconfigured' as const;
|
|
53
|
+
return { ok: true as const, network_id: h.networkId!, source: 'hub' as const,
|
|
54
|
+
// 读的是哪张表 —— 名字直接写出来,避免下一个人拿这个结果去解释另一个接口
|
|
55
|
+
source_table: 'hub_provider_configs' as const,
|
|
56
|
+
state,
|
|
57
|
+
counts: { providers: rows.length, providers_in_cli_registry: otherCount },
|
|
58
|
+
...(state === 'unconfigured' ? {
|
|
59
|
+
hint: otherCount > 0
|
|
60
|
+
? '本端点读 hub_provider_configs(网络自有 provider 配置),此处为空;但要给客户端选模型,还需要这里至少一行 —— CLI 注册表里的 ' + otherCount + ' 条不会自动出现在本端点。'
|
|
61
|
+
: '本端点读 hub_provider_configs,此处为空,且 CLI 注册表(providers)也是 0 条 ⇒ 客户端没有任何可选模型;需要管理员先录入第一行。',
|
|
62
|
+
} : {}),
|
|
63
|
+
...(exposeRefs ? { secret_reference_supported: true } : {}), providers: rows.map(r => publicRow(h.networkId!, r, exposeRefs)) };
|
|
64
|
+
}
|
|
65
|
+
export function putHubProvider(h: Human, revision: number, input: unknown) {
|
|
66
|
+
// This operation stores/rotates a shared secret: same OWNER boundary as vault writes.
|
|
67
|
+
const refusal = auth(h, true, true); if (refusal) return refusal;
|
|
68
|
+
if (!Number.isSafeInteger(revision) || revision < 0 || revision >= Number.MAX_SAFE_INTEGER) return denied('invalid_revision');
|
|
69
|
+
if (!validConfig(input)) return denied('invalid_hub_provider');
|
|
70
|
+
const value = input as Config & { key?: string; secretKeyRef?: string };
|
|
71
|
+
if (value.key !== undefined && (typeof value.key !== 'string' || !value.key || value.key.length > 8192 || /[\s\x00-\x1f\x7f]/.test(value.key))) return denied('invalid_provider_key');
|
|
72
|
+
if (value.secretKeyRef !== undefined && (typeof value.secretKeyRef !== 'string' || !/^[A-Z][A-Z0-9_]{0,63}$/.test(value.secretKeyRef)
|
|
73
|
+
|| value.key !== undefined)) return denied('invalid_provider_secret_reference');
|
|
74
|
+
if (value.secretKeyRef && !vaultListKeys(h.networkId!).includes(value.secretKeyRef)) return denied('provider_secret_reference_missing');
|
|
75
|
+
const old = row(h.networkId!, value.id);
|
|
76
|
+
if ((old?.revision ?? 0) !== revision) return denied('hub_provider_revision_conflict');
|
|
77
|
+
const previous = old ? JSON.parse(old.config_json) as Config : null;
|
|
78
|
+
if (!value.key && !value.secretKeyRef && (!old || previous?.baseUrl !== value.baseUrl || previous?.protocol !== value.protocol)) return denied('provider_key_required');
|
|
79
|
+
// A new plaintext key belongs to this Provider. Never overwrite a separately
|
|
80
|
+
// named shared key merely because the previous config referenced it.
|
|
81
|
+
const privateRef = `HUB_PROVIDER_${createHash('sha256').update(JSON.stringify([h.networkId, value.id])).digest('hex').slice(0, 32).toUpperCase()}`;
|
|
82
|
+
const ref = value.secretKeyRef ?? (value.key ? privateRef : old!.secret_key_ref);
|
|
83
|
+
const { key, secretKeyRef, ...config } = value;
|
|
84
|
+
try {
|
|
85
|
+
db.transaction(() => {
|
|
86
|
+
if ((row(h.networkId!, value.id)?.revision ?? 0) !== revision) throw new Error('hub_provider_revision_conflict');
|
|
87
|
+
if (key) vaultUpsert(h.networkId!, ref, key);
|
|
88
|
+
db.run(`INSERT INTO hub_provider_configs(network_id,provider_id,revision,config_json,secret_key_ref,updated_at) VALUES(?1,?2,?3,?4,?5,?6)
|
|
89
|
+
ON CONFLICT(network_id,provider_id) DO UPDATE SET revision=excluded.revision,config_json=excluded.config_json,secret_key_ref=excluded.secret_key_ref,updated_at=excluded.updated_at`,
|
|
90
|
+
[h.networkId!, value.id, revision + 1, JSON.stringify(config), ref, Date.now()]);
|
|
91
|
+
// Cancel still-pending dispatches when the source is edited/rotated/disabled.
|
|
92
|
+
// Already installed copies are NOT remotely revoked by this change.
|
|
93
|
+
db.run(`UPDATE daemon_provider_snapshots SET status='failed',error='hub_provider_source_changed'
|
|
94
|
+
WHERE status='pending' AND request_id IN (SELECT request_id FROM hub_provider_bindings WHERE network_id=?1 AND provider_id=?2)`, [h.networkId!, value.id]);
|
|
95
|
+
db.run(`DELETE FROM daemon_provider_writes WHERE request_id IN (SELECT b.request_id FROM hub_provider_bindings b
|
|
96
|
+
JOIN daemon_provider_snapshots s ON s.request_id=b.request_id WHERE b.network_id=?1 AND b.provider_id=?2 AND s.status!='pending')`, [h.networkId!, value.id]);
|
|
97
|
+
});
|
|
98
|
+
return { ok: true as const, network_id: h.networkId!, provider: publicRow(h.networkId!, row(h.networkId!, value.id)!, secretKeyRef !== undefined) };
|
|
99
|
+
} catch (error) { return denied(error instanceof VaultError ? error.code : 'hub_provider_save_failed'); }
|
|
100
|
+
}
|
|
101
|
+
export function bindHubProvider(h: Human, input: { id: string; revision: number; daemon_node_id: string; daemon_revision: number; confirm: boolean }) {
|
|
102
|
+
const refusal = auth(h, true); if (refusal) return refusal;
|
|
103
|
+
if (!input || !idValid(input.id) || input.confirm !== true || !Number.isSafeInteger(input.revision)
|
|
104
|
+
|| !Number.isSafeInteger(input.daemon_revision) || input.daemon_revision < 0) return denied('invalid_hub_provider_binding');
|
|
105
|
+
const stored = row(h.networkId!, input.id);
|
|
106
|
+
if (!stored || stored.revision !== input.revision) return denied('hub_provider_revision_conflict');
|
|
107
|
+
const config = JSON.parse(stored.config_json) as Config;
|
|
108
|
+
if (!config.enabled) return denied('hub_provider_disabled');
|
|
109
|
+
// Never silently treat Chat Completions/Anthropic as Codex Responses.
|
|
110
|
+
if (config.protocol !== 'openai-responses') return denied('runtime_protocol_not_supported');
|
|
111
|
+
const targetId = `hub_${createHash('sha256').update(JSON.stringify([h.networkId, input.id])).digest('hex').slice(0, 24)}`;
|
|
112
|
+
try {
|
|
113
|
+
const key = vaultGet(h.networkId!, stored.secret_key_ref); if (!key) return denied('provider_key_missing');
|
|
114
|
+
const queued = requestProviderWrite(h, input.daemon_node_id, input.daemon_revision, { id: targetId,
|
|
115
|
+
label: `Hub · ${config.label}`.slice(0, 100), enabled: true, runtimes: [{ runtime: 'codex-tui', auth: [
|
|
116
|
+
{ id: 'hub_key', kind: 'api_key', models: config.models, baseUrl: config.baseUrl, key },
|
|
117
|
+
] }] });
|
|
118
|
+
if (!queued.ok) return queued;
|
|
119
|
+
db.run(`INSERT INTO hub_provider_bindings(request_id,network_id,provider_id,provider_revision,daemon_node_id,daemon_provider_id,created_at)
|
|
120
|
+
VALUES(?1,?2,?3,?4,?5,?6,?7)`, [queued.request_id, h.networkId!, input.id, input.revision, input.daemon_node_id, targetId, Date.now()]);
|
|
121
|
+
return { ...queued, daemon_node_id: input.daemon_node_id,
|
|
122
|
+
provider_reference: { network_id: h.networkId!, id: input.id, revision: input.revision, daemon_provider_id: targetId } };
|
|
123
|
+
} catch (error) { return denied(error instanceof VaultError ? error.code : 'hub_provider_binding_failed'); }
|
|
124
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { parseHubTimestamp } from "./hub-timestamp";
|
|
3
|
+
|
|
4
|
+
const RAW = "2026-08-30 21:11:24"; // sessions.last_seen_at 的真实取值
|
|
5
|
+
const TRUE_UTC = Date.UTC(2026, 7, 30, 21, 11, 24);
|
|
6
|
+
|
|
7
|
+
describe("parseHubTimestamp (#1650)", () => {
|
|
8
|
+
test("🔴 非 UTC 时区下也必须解出同一个 UTC 时刻", () => {
|
|
9
|
+
// `bun test` 把测试进程时区固定成 UTC(getTimezoneOffset() === 0)。
|
|
10
|
+
// 在 UTC 下,「补 Z」和「不补 Z」解析出**同一个数** —— 这个函数存在的那个
|
|
11
|
+
// 缺陷在测试进程里**结构上不可见**。所以这一条必须开 TZ≠UTC 的子进程。
|
|
12
|
+
// 实测:去掉补 Z,本文件其余各条**全绿**。
|
|
13
|
+
const child = `import { parseHubTimestamp } from ${JSON.stringify(import.meta.dir + "/hub-timestamp.ts")};
|
|
14
|
+
process.stdout.write(new Date().getTimezoneOffset() + "," + parseHubTimestamp(${JSON.stringify(RAW)}));`;
|
|
15
|
+
const r = Bun.spawnSync(["bun", "-e", child], { env: { ...process.env, TZ: "Asia/Shanghai" } });
|
|
16
|
+
const [offset, parsed] = r.stdout.toString().trim().split(",");
|
|
17
|
+
// 🔴 先断言控制生效:子进程真的不在 UTC。否则 TZ 被忽略时这条又变成空测试。
|
|
18
|
+
expect(Number(offset)).not.toBe(0);
|
|
19
|
+
expect(parsed).toBe(String(TRUE_UTC));
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test("已带 Z / ±HH:MM 的串不再追加时区", () => {
|
|
23
|
+
expect(parseHubTimestamp("2026-08-30T21:11:24Z")).toBe(TRUE_UTC);
|
|
24
|
+
expect(parseHubTimestamp("2026-08-30T22:11:24+01:00")).toBe(TRUE_UTC);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test("拿不到就返回 null,不返回一个看起来合理的数", () => {
|
|
28
|
+
for (const bad of [undefined, null, "", " ", 0, 1788124284000, {}, [], "2026-08-30", "垃圾"]) {
|
|
29
|
+
expect(parseHubTimestamp(bad as unknown)).toBeNull();
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("🔴 INTEGER 列(epoch 毫秒)不归它管 —— 传数字必须返回 null,而不是悄悄接受", () => {
|
|
34
|
+
// external_schedule_edits.* 是 INTEGER。如果有人把本函数用在那儿,
|
|
35
|
+
// 应当立刻拿到 null 而不是一个错的时刻。
|
|
36
|
+
expect(parseHubTimestamp(TRUE_UTC)).toBeNull();
|
|
37
|
+
});
|
|
38
|
+
});
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #1650 — hub 的 TEXT 时间戳列是 SQLite `datetime('now')` 写的,
|
|
3
|
+
* 形如 `2026-08-30 21:11:24`:**UTC,但不带任何时区标记**。
|
|
4
|
+
*
|
|
5
|
+
* 🔴 `new Date(raw)` / `Date.parse(raw)` 对这种串按**本地时间**解析(ES 规范:
|
|
6
|
+
* 带时间的形式无偏移时视为本地时间),误差恰好等于主机时区偏移,**而且不报错**:
|
|
7
|
+
*
|
|
8
|
+
* TZ=UTC 误差 0h
|
|
9
|
+
* TZ=Asia/Shanghai 误差 -8h (看起来更陈旧)
|
|
10
|
+
* TZ=America/Los_Angeles 误差 +7h (看起来更新鲜 ← 朝好的一侧错)
|
|
11
|
+
*
|
|
12
|
+
* 🔴 **只对 TEXT 列用它。** 同一个字段名在不同表里可能是不同类型:
|
|
13
|
+
* sessions.last_seen_at / licenses.expires_at → TEXT(要用本函数)
|
|
14
|
+
* external_schedule_edits.expires_at 等 4 列 → INTEGER(epoch 毫秒,直接 new Date 就对)
|
|
15
|
+
* 按字段名判会判错 —— 见 #1650 里的更正。
|
|
16
|
+
*
|
|
17
|
+
* 与 agent-network 侧的同名函数是**有意的重复**:server 包不依赖 agent-network,
|
|
18
|
+
* 仓里也没有共享 lib。两边各自带测试。
|
|
19
|
+
*/
|
|
20
|
+
export function parseHubTimestamp(raw: unknown): number | null {
|
|
21
|
+
if (typeof raw !== "string") return null;
|
|
22
|
+
const t = raw.trim();
|
|
23
|
+
if (!/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/.test(t)) return null;
|
|
24
|
+
const hasZone = /([Zz]|[+-]\d{2}:?\d{2})$/.test(t);
|
|
25
|
+
const ms = Date.parse(t.replace(" ", "T") + (hasZone ? "" : "Z"));
|
|
26
|
+
return Number.isFinite(ms) ? ms : null;
|
|
27
|
+
}
|