@sleep2agi/commhub-server 0.9.0-preview.25 → 0.9.0-preview.250
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/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 +228 -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 +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 +675 -0
- package/src/agent-acl-slice3-http.test.ts +717 -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 +95 -4
- 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 +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 +132 -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-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 +262 -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 +73 -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 +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 +445 -0
- package/src/daemon-provider-snapshots.ts +327 -0
- package/src/daemon-token-owner-http.test.ts +292 -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 +1264 -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/expiry-counters.test.ts +111 -0
- package/src/expiry-counters.ts +93 -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 +1 -1
- package/src/file-download-authz.test.ts +73 -18
- package/src/file-download-date-bucket.test.ts +8 -26
- 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 +483 -0
- package/src/group-messages.ts +297 -0
- package/src/health-anon-readers.ts +60 -0
- package/src/health-host-disk-2756.test.ts +71 -0
- package/src/health-redaction.test.ts +1541 -7
- 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 +641 -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 +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 +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-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 +347 -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.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 +257 -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 +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/project-dir-warn-clear-http.test.ts +132 -0
- package/src/project-viewer-can-http.test.ts +116 -0
- package/src/provider-tools-shape.test.ts +150 -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 +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 +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 +309 -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 +164 -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 +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 +475 -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 +285 -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 +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/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 +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 +5134 -503
- 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 +265 -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-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 +498 -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 +318 -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 +209 -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 +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/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 +4326 -420
- package/src/upload-early-reject-guard.test.ts +155 -0
- package/src/uploads-http.test.ts +86 -7
- package/src/uploads.ts +38 -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 +348 -0
- package/src/user-inbox-by-agent-http.test.ts +165 -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,25 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
import { Database } from "bun:sqlite";
|
|
3
|
+
|
|
4
|
+
test("existing users survive additive avatar migration and next process preserves it", async () => {
|
|
5
|
+
const path = process.env.COMMHUB_DB!;
|
|
6
|
+
expect(typeof path).toBe("string");
|
|
7
|
+
const old = new Database(path);
|
|
8
|
+
old.exec(`CREATE TABLE users (
|
|
9
|
+
user_id TEXT PRIMARY KEY, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL,
|
|
10
|
+
email TEXT, display_name TEXT, role TEXT DEFAULT 'user',
|
|
11
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
12
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
13
|
+
); INSERT INTO users (user_id, username, password_hash) VALUES ('old_user', 'old_user', 'test-only-hash');`);
|
|
14
|
+
old.close();
|
|
15
|
+
const { db } = await import("./db.js");
|
|
16
|
+
expect(db.get<any>("SELECT avatar_url, password_hash FROM users WHERE user_id = ?1", "old_user"))
|
|
17
|
+
.toEqual({ avatar_url: null, password_hash: "test-only-hash" });
|
|
18
|
+
db.run("UPDATE users SET avatar_url = ?1 WHERE user_id = ?2", ["/avatars/avatar-03.webp", "old_user"]);
|
|
19
|
+
const child = Bun.spawn([process.execPath, "-e", `
|
|
20
|
+
const { db } = await import('./src/db.ts');
|
|
21
|
+
const row = db.get('SELECT avatar_url, password_hash FROM users WHERE user_id = ?1', 'old_user');
|
|
22
|
+
if (row.avatar_url !== '/avatars/avatar-03.webp' || row.password_hash !== 'test-only-hash') process.exit(1);
|
|
23
|
+
`], { cwd: new URL("..", import.meta.url).pathname, env: process.env, stdout: "pipe", stderr: "pipe" });
|
|
24
|
+
expect(await child.exited).toBe(0);
|
|
25
|
+
});
|
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
import { register, createNetworkTokenForNode, addNetworkMember } from "./auth.js";
|
|
3
|
+
import { db } from "./db.js";
|
|
4
|
+
import { inspectAvatarImage, MAX_AVATAR_BYTES } from "./user-avatar-image.js";
|
|
5
|
+
import { deflateSync } from "node:zlib";
|
|
6
|
+
|
|
7
|
+
// 1×1 PNG(透明)。只用来走真实 multipart → 真实文件头校验。
|
|
8
|
+
const PNG_1X1 = Buffer.from(
|
|
9
|
+
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
|
|
10
|
+
"base64",
|
|
11
|
+
);
|
|
12
|
+
/** 真的 8-bit RGBA PNG:IHDR + 一段 zlib 压缩的扫描行 + IEND,CRC 全对。 */
|
|
13
|
+
function realPng(width: number, height: number): Buffer {
|
|
14
|
+
const crcTable = new Uint32Array(256).map((_, n) => {
|
|
15
|
+
let c = n;
|
|
16
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
17
|
+
return c >>> 0;
|
|
18
|
+
});
|
|
19
|
+
const crc = (buf: Buffer) => {
|
|
20
|
+
let c = 0xffffffff;
|
|
21
|
+
for (const byte of buf) c = crcTable[(c ^ byte) & 0xff] ^ (c >>> 8);
|
|
22
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
23
|
+
};
|
|
24
|
+
const chunk = (type: string, data: Buffer) => {
|
|
25
|
+
const len = Buffer.alloc(4); len.writeUInt32BE(data.length);
|
|
26
|
+
const body = Buffer.concat([Buffer.from(type, "ascii"), data]);
|
|
27
|
+
const sum = Buffer.alloc(4); sum.writeUInt32BE(crc(body));
|
|
28
|
+
return Buffer.concat([len, body, sum]);
|
|
29
|
+
};
|
|
30
|
+
const ihdr = Buffer.alloc(13);
|
|
31
|
+
ihdr.writeUInt32BE(width, 0); ihdr.writeUInt32BE(height, 4);
|
|
32
|
+
ihdr[8] = 8; ihdr[9] = 6; ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0; // 8-bit RGBA
|
|
33
|
+
const raw = Buffer.alloc((1 + width * 4) * height); // 每行前面一个 filter 字节 0
|
|
34
|
+
return Buffer.concat([
|
|
35
|
+
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
|
36
|
+
chunk("IHDR", ihdr),
|
|
37
|
+
chunk("IDAT", deflateSync(raw)),
|
|
38
|
+
chunk("IEND", Buffer.alloc(0)),
|
|
39
|
+
]);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
/** CRC 全对、但 IDAT 内容非法的 PNG:用来证明「结构通过 ≠ 图像有效」。 */
|
|
44
|
+
function pngWithIdat(idat: Buffer, opts: { colorType?: number; bitDepth?: number; width?: number; height?: number; interlace?: number } = {}): Buffer {
|
|
45
|
+
const crcTable = new Uint32Array(256).map((_, n) => {
|
|
46
|
+
let c = n;
|
|
47
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
48
|
+
return c >>> 0;
|
|
49
|
+
});
|
|
50
|
+
const crc = (buf: Buffer) => {
|
|
51
|
+
let c = 0xffffffff;
|
|
52
|
+
for (const byte of buf) c = crcTable[(c ^ byte) & 0xff] ^ (c >>> 8);
|
|
53
|
+
return (c ^ 0xffffffff) >>> 0;
|
|
54
|
+
};
|
|
55
|
+
const chunk = (type: string, data: Buffer) => {
|
|
56
|
+
const len = Buffer.alloc(4); len.writeUInt32BE(data.length);
|
|
57
|
+
const body = Buffer.concat([Buffer.from(type, "ascii"), data]);
|
|
58
|
+
const sum = Buffer.alloc(4); sum.writeUInt32BE(crc(body));
|
|
59
|
+
return Buffer.concat([len, body, sum]);
|
|
60
|
+
};
|
|
61
|
+
const ihdr = Buffer.alloc(13);
|
|
62
|
+
ihdr.writeUInt32BE(opts.width ?? 1, 0); ihdr.writeUInt32BE(opts.height ?? 1, 4);
|
|
63
|
+
ihdr[8] = opts.bitDepth ?? 8; ihdr[9] = opts.colorType ?? 6; ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = opts.interlace ?? 0;
|
|
64
|
+
return Buffer.concat([
|
|
65
|
+
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
|
66
|
+
chunk("IHDR", ihdr), chunk("IDAT", idat), chunk("IEND", Buffer.alloc(0)),
|
|
67
|
+
]);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
test("account avatar upload: user token only, PNG limits, visibility by shared network, revoke, atomic replace", async () => {
|
|
71
|
+
const a = register("avup_alice", "AvatarUpload1!");
|
|
72
|
+
const b = register("avup_bob", "AvatarUpload1!");
|
|
73
|
+
const outsider = register("avup_outsider", "AvatarUpload1!");
|
|
74
|
+
expect(a.ok && b.ok && outsider.ok).toBe(true);
|
|
75
|
+
expect(addNetworkMember(a.network_id!, b.user!.user_id, "member").ok).toBe(true);
|
|
76
|
+
const node = createNetworkTokenForNode(a.user!.user_id, a.network_id!, "avup_alice", "avup_node");
|
|
77
|
+
expect(node.ok).toBe(true);
|
|
78
|
+
|
|
79
|
+
const { bootServer } = await import("./server.js");
|
|
80
|
+
const hub = bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
81
|
+
const base = `http://127.0.0.1:${hub.port}`;
|
|
82
|
+
|
|
83
|
+
const upload = async (token: string | null, bytes: Buffer, fieldName = "file", extra?: [string, string]) => {
|
|
84
|
+
const form = new FormData();
|
|
85
|
+
form.append(fieldName, new Blob([new Uint8Array(bytes)], { type: "image/png" }), "a.png");
|
|
86
|
+
if (extra) form.append(extra[0], extra[1]);
|
|
87
|
+
const headers: Record<string, string> = {};
|
|
88
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
89
|
+
const res = await fetch(`${base}/api/auth/me/avatar/upload`, { method: "POST", headers, body: form });
|
|
90
|
+
const body = await res.json().catch(() => null);
|
|
91
|
+
return { status: res.status, body: body as any };
|
|
92
|
+
};
|
|
93
|
+
const getAvatar = async (token: string | null, path: string) => {
|
|
94
|
+
const res = await fetch(base + path, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
|
|
95
|
+
return { status: res.status, headers: res.headers, bytes: new Uint8Array(await res.arrayBuffer()) };
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
// 前置:陌生人之间没有共享网络。
|
|
100
|
+
expect(db.get("SELECT 1 AS ok FROM network_members m WHERE m.user_id=?1 AND m.network_id=?2", outsider.user!.user_id, a.network_id!)).toBeNull();
|
|
101
|
+
|
|
102
|
+
// 匿名/节点令牌都不是「本人」。
|
|
103
|
+
expect((await upload(null, PNG_1X1)).status).toBe(401);
|
|
104
|
+
expect((await upload(node.token!, PNG_1X1)).status).toBe(403);
|
|
105
|
+
|
|
106
|
+
// 畸形输入:非 PNG、超边长、空、多字段、非 multipart。
|
|
107
|
+
expect((await upload(a.token!, Buffer.from("not a png"))).body.error).toBe("invalid_image");
|
|
108
|
+
expect((await upload(a.token!, realPng(600, 600))).body.reason).toBe("too_big");
|
|
109
|
+
expect((await upload(a.token!, Buffer.alloc(0))).status).toBe(400);
|
|
110
|
+
expect((await upload(a.token!, PNG_1X1, "other")).status).toBe(400);
|
|
111
|
+
expect((await upload(a.token!, PNG_1X1, "file", ["avatar_url", "/etc/passwd"])).status).toBe(400);
|
|
112
|
+
const notMultipart = await fetch(`${base}/api/auth/me/avatar/upload`, {
|
|
113
|
+
method: "POST", headers: { Authorization: `Bearer ${a.token}`, "Content-Type": "application/json" }, body: "{}",
|
|
114
|
+
});
|
|
115
|
+
expect(notMultipart.status).toBe(415);
|
|
116
|
+
|
|
117
|
+
// 成功:URL 由 Hub 发,version 只含 URL 安全字符。
|
|
118
|
+
const ok1 = await upload(a.token!, PNG_1X1);
|
|
119
|
+
expect(ok1.status).toBe(200);
|
|
120
|
+
expect(ok1.body.ok).toBe(true);
|
|
121
|
+
expect(ok1.body.user_id).toBe(a.user!.user_id);
|
|
122
|
+
expect(ok1.body.avatar_url).toMatch(new RegExp(`^/api/users/${a.user!.user_id}/avatar/[A-Za-z0-9_-]{1,128}\\.png$`));
|
|
123
|
+
|
|
124
|
+
// 资料读取面必须同步看到这张头像(同一事务写 users.avatar_url)。
|
|
125
|
+
const meAfter = await fetch(`${base}/api/auth/me`, { headers: { Authorization: `Bearer ${a.token}` } });
|
|
126
|
+
const meBody = await meAfter.json() as any;
|
|
127
|
+
expect(meBody.user.avatar_url).toBe(ok1.body.avatar_url);
|
|
128
|
+
|
|
129
|
+
const first = await getAvatar(a.token!, ok1.body.avatar_url);
|
|
130
|
+
expect(first.status).toBe(200);
|
|
131
|
+
expect(first.headers.get("content-type")).toBe("image/png");
|
|
132
|
+
expect(first.headers.get("cache-control")).toBe("private, no-store");
|
|
133
|
+
expect(first.headers.get("location")).toBeNull();
|
|
134
|
+
expect(first.bytes.byteLength).toBe(PNG_1X1.byteLength);
|
|
135
|
+
|
|
136
|
+
// 同网络成员可读;不同网络的人读不到(与不存在同码,避免探测)。
|
|
137
|
+
expect((await getAvatar(b.token!, ok1.body.avatar_url)).status).toBe(200);
|
|
138
|
+
expect((await getAvatar(outsider.token!, ok1.body.avatar_url)).status).toBe(404);
|
|
139
|
+
expect((await getAvatar(null, ok1.body.avatar_url)).status).toBe(401);
|
|
140
|
+
expect((await getAvatar(node.token!, ok1.body.avatar_url)).status).toBe(403);
|
|
141
|
+
expect((await getAvatar(a.token!, `/api/users/${a.user!.user_id}/avatar/nope..%2F.png`)).status).toBe(404);
|
|
142
|
+
|
|
143
|
+
// 撤权后立刻读不到。
|
|
144
|
+
expect(db.run("DELETE FROM network_members WHERE user_id=?1 AND network_id=?2", [b.user!.user_id, a.network_id!]).changes).toBeGreaterThan(0);
|
|
145
|
+
expect((await getAvatar(b.token!, ok1.body.avatar_url)).status).toBe(404);
|
|
146
|
+
|
|
147
|
+
// 「CRC 正确但图像数据非法」也必须 400:结构通过不等于可解码。
|
|
148
|
+
const beforeInvalid = db.get<{ version: string; bytes: number }>(
|
|
149
|
+
"SELECT version, bytes FROM user_avatar_uploads WHERE user_id=?1", a.user!.user_id);
|
|
150
|
+
expect((await upload(a.token!, pngWithIdat(Buffer.alloc(0)))).body.reason).toBe("bad_image");
|
|
151
|
+
expect((await upload(a.token!, pngWithIdat(Buffer.from("not-a-zlib-stream")))).body.reason).toBe("bad_image");
|
|
152
|
+
// 解压成功但扫描行长度不符(声明 2×2 RGBA,实际只给 1×1)
|
|
153
|
+
expect((await upload(a.token!, pngWithIdat(deflateSync(Buffer.alloc(5)), { width: 2, height: 2 }))).body.reason).toBe("bad_image");
|
|
154
|
+
const afterInvalid = db.get<{ version: string; bytes: number }>(
|
|
155
|
+
"SELECT version, bytes FROM user_avatar_uploads WHERE user_id=?1", a.user!.user_id);
|
|
156
|
+
expect(afterInvalid).toEqual(beforeInvalid);
|
|
157
|
+
|
|
158
|
+
// P2:清空后旧托管 URL 立即失效(本人与同网络成员都不能再读到)。
|
|
159
|
+
const putProfile = async (token: string, avatar_url: string | null) => {
|
|
160
|
+
const res = await fetch(`${base}/api/auth/me/avatar`, {
|
|
161
|
+
method: "PUT", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
|
|
162
|
+
body: JSON.stringify({ avatar_url }),
|
|
163
|
+
});
|
|
164
|
+
return { status: res.status, body: await res.json() as any };
|
|
165
|
+
};
|
|
166
|
+
// 重新造一张可读的:此刻 b 已被撤权,先用 outsider 之外的同网成员做读校验
|
|
167
|
+
expect(addNetworkMember(a.network_id!, b.user!.user_id, "member").ok).toBe(true);
|
|
168
|
+
expect((await getAvatar(b.token!, ok1.body.avatar_url)).status).toBe(200);
|
|
169
|
+
expect((await putProfile(a.token!, null)).status).toBe(200);
|
|
170
|
+
expect((await getAvatar(a.token!, ok1.body.avatar_url)).status).toBe(404);
|
|
171
|
+
expect((await getAvatar(b.token!, ok1.body.avatar_url)).status).toBe(404);
|
|
172
|
+
const meCleared = await fetch(`${base}/api/auth/me`, { headers: { Authorization: `Bearer ${a.token}` } });
|
|
173
|
+
expect(((await meCleared.json()) as any).user.avatar_url).toBeNull();
|
|
174
|
+
expect(db.get("SELECT 1 AS ok FROM user_avatar_uploads WHERE user_id=?1", [a.user!.user_id])).toBeNull();
|
|
175
|
+
|
|
176
|
+
// 换成池里的一张(非托管 URL)也必须撤销旧托管行。
|
|
177
|
+
const again = await upload(a.token!, PNG_1X1);
|
|
178
|
+
expect(again.status).toBe(200);
|
|
179
|
+
expect((await getAvatar(a.token!, again.body.avatar_url)).status).toBe(200);
|
|
180
|
+
expect((await putProfile(a.token!, "/avatars/avatar-03.webp")).status).toBe(200);
|
|
181
|
+
expect((await getAvatar(a.token!, again.body.avatar_url)).status).toBe(404);
|
|
182
|
+
expect(db.get("SELECT 1 AS ok FROM user_avatar_uploads WHERE user_id=?1", [a.user!.user_id])).toBeNull();
|
|
183
|
+
|
|
184
|
+
// 原子替换:一次失败的上传不能把上一张弄丢;成功后旧 version 立刻 404。
|
|
185
|
+
const baseline = await upload(a.token!, PNG_1X1);
|
|
186
|
+
expect(baseline.status).toBe(200);
|
|
187
|
+
const beforeBad = db.get<{ version: string }>("SELECT version FROM user_avatar_uploads WHERE user_id=?1", [a.user!.user_id]);
|
|
188
|
+
expect(beforeBad?.version).toBeTruthy();
|
|
189
|
+
expect((await upload(a.token!, Buffer.from("broken"))).status).toBe(400);
|
|
190
|
+
expect(db.get<{ version: string }>("SELECT version FROM user_avatar_uploads WHERE user_id=?1", a.user!.user_id)!.version).toBe(beforeBad!.version);
|
|
191
|
+
expect((await getAvatar(a.token!, baseline.body.avatar_url)).status).toBe(200);
|
|
192
|
+
|
|
193
|
+
const ok2 = await upload(a.token!, realPng(512, 512));
|
|
194
|
+
expect(ok2.status).toBe(200);
|
|
195
|
+
expect(ok2.body.avatar_url).not.toBe(baseline.body.avatar_url);
|
|
196
|
+
expect((await getAvatar(a.token!, baseline.body.avatar_url)).status).toBe(404);
|
|
197
|
+
expect((await getAvatar(a.token!, ok2.body.avatar_url)).status).toBe(200);
|
|
198
|
+
expect(db.get<{ width: number }>("SELECT width FROM user_avatar_uploads WHERE user_id=?1", a.user!.user_id)!.width).toBe(512);
|
|
199
|
+
} finally {
|
|
200
|
+
db.run("DELETE FROM user_avatar_uploads WHERE user_id IN (?1, ?2, ?3)", [a.user!.user_id, b.user!.user_id, outsider.user!.user_id]);
|
|
201
|
+
await hub.stop?.();
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
test("deleted network leaves only ghost membership: member loses read, owner keeps it", async () => {
|
|
206
|
+
const owner = register("avup_netowner", "AvatarUpload1!");
|
|
207
|
+
const member = register("avup_netmember", "AvatarUpload1!");
|
|
208
|
+
expect(owner.ok && member.ok).toBe(true);
|
|
209
|
+
expect(addNetworkMember(owner.network_id!, member.user!.user_id, "member").ok).toBe(true);
|
|
210
|
+
const { bootServer } = await import("./server.js");
|
|
211
|
+
const hub = bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
212
|
+
const base = `http://127.0.0.1:${hub.port}`;
|
|
213
|
+
const read = async (token: string, path: string) => (await fetch(base + path, { headers: { Authorization: `Bearer ${token}` } })).status;
|
|
214
|
+
try {
|
|
215
|
+
const form = new FormData();
|
|
216
|
+
form.append("file", new Blob([new Uint8Array(PNG_1X1)], { type: "image/png" }), "a.png");
|
|
217
|
+
const up = await fetch(`${base}/api/auth/me/avatar/upload`, { method: "POST", headers: { Authorization: `Bearer ${owner.token}` }, body: form });
|
|
218
|
+
expect(up.status).toBe(200);
|
|
219
|
+
const url = ((await up.json()) as any).avatar_url as string;
|
|
220
|
+
expect(await read(member.token!, url)).toBe(200);
|
|
221
|
+
// 只删网络行,故意留下 network_members 残行:live membership 必须据此拒绝。
|
|
222
|
+
db.run("DELETE FROM networks WHERE network_id = ?1", [owner.network_id!]);
|
|
223
|
+
expect(await read(member.token!, url)).toBe(404);
|
|
224
|
+
expect(await read(owner.token!, url)).toBe(200); // 本人不依赖成员关系
|
|
225
|
+
} finally {
|
|
226
|
+
db.run("DELETE FROM user_avatar_uploads WHERE user_id = ?1", [owner.user!.user_id]);
|
|
227
|
+
db.run("UPDATE users SET avatar_url = NULL WHERE user_id = ?1", [owner.user!.user_id]);
|
|
228
|
+
await hub.stop?.();
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
test("upload is rate limited before multipart parsing, and rejects keepalive leftovers", async () => {
|
|
233
|
+
const u = register("avup_ratelimit", "AvatarUpload1!");
|
|
234
|
+
expect(u.ok).toBe(true);
|
|
235
|
+
const { bootServer } = await import("./server.js");
|
|
236
|
+
const hub = bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
237
|
+
const base = `http://127.0.0.1:${hub.port}`;
|
|
238
|
+
const send = async (body: BodyInit | null, contentType?: string) => {
|
|
239
|
+
const headers: Record<string, string> = { Authorization: `Bearer ${u.token}` };
|
|
240
|
+
if (contentType) headers["Content-Type"] = contentType;
|
|
241
|
+
const res = await fetch(`${base}/api/auth/me/avatar/upload`, { method: "POST", headers, body });
|
|
242
|
+
return { status: res.status, connection: res.headers.get("connection"), body: await res.json().catch(() => null) as any };
|
|
243
|
+
};
|
|
244
|
+
const multipart = () => {
|
|
245
|
+
const form = new FormData();
|
|
246
|
+
form.append("file", new Blob([PNG_1X1], { type: "image/png" }), "a.png");
|
|
247
|
+
return form;
|
|
248
|
+
};
|
|
249
|
+
try {
|
|
250
|
+
// 60 次成功用满这一小时的桶(每张 1×1,成本可忽略)。
|
|
251
|
+
for (let i = 0; i < 60; i++) {
|
|
252
|
+
const r = await send(multipart());
|
|
253
|
+
expect(r.status).toBe(200);
|
|
254
|
+
}
|
|
255
|
+
const limited = await send(multipart());
|
|
256
|
+
expect(limited.status).toBe(429);
|
|
257
|
+
expect(limited.body.error).toBe("rate_limited");
|
|
258
|
+
expect(limited.connection).toBe("close");
|
|
259
|
+
// 关键:限流在 multipart 解析之前——普通 JSON 也被先拒成 429,而不是 415。
|
|
260
|
+
const early = await send("{}", "application/json");
|
|
261
|
+
expect(early.status).toBe(429);
|
|
262
|
+
expect(early.connection).toBe("close");
|
|
263
|
+
} finally {
|
|
264
|
+
db.run("DELETE FROM user_avatar_uploads WHERE user_id = ?1", [u.user!.user_id]);
|
|
265
|
+
db.run("UPDATE users SET avatar_url = NULL WHERE user_id = ?1", [u.user!.user_id]);
|
|
266
|
+
await hub.stop?.();
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
test("image inspector: signature, shape and size limits", () => {
|
|
271
|
+
expect(inspectAvatarImage(PNG_1X1)).toEqual({ ok: true, width: 1, height: 1 });
|
|
272
|
+
expect(inspectAvatarImage(new Uint8Array(0))).toEqual({ ok: false, reason: "empty" });
|
|
273
|
+
expect(inspectAvatarImage(new Uint8Array(10))).toEqual({ ok: false, reason: "not_png" });
|
|
274
|
+
expect(inspectAvatarImage(Buffer.from(realPng(16, 16).subarray(0, 20)))).toEqual({ ok: false, reason: "truncated" });
|
|
275
|
+
expect(inspectAvatarImage(Buffer.from(realPng(16, 16).subarray(0, 40)))).toEqual({ ok: false, reason: "truncated" });
|
|
276
|
+
const truePng = realPng(16, 16);
|
|
277
|
+
const corrupt = Buffer.from(truePng); corrupt[corrupt.length - 20] ^= 0xff;
|
|
278
|
+
expect(inspectAvatarImage(corrupt).ok).toBe(false);
|
|
279
|
+
expect(inspectAvatarImage(realPng(513, 16))).toEqual({ ok: false, reason: "too_big" });
|
|
280
|
+
// Adam7 隔行:明确拒收(不按非隔行长度错算)
|
|
281
|
+
const interlaced = pngWithIdat(deflateSync(Buffer.alloc(6)), { width: 1, height: 1, interlace: 1 });
|
|
282
|
+
expect(inspectAvatarImage(interlaced)).toEqual({ ok: false, reason: "interlaced_unsupported" });
|
|
283
|
+
// 规范外取值 2..255:同样拒收(负控:扫描数据本来是非隔行的合法布局,
|
|
284
|
+
// 只有 interlace 字节非法,证明拦截来自 interlace 判断而不是解码失败)
|
|
285
|
+
for (const bad of [2, 3, 128, 255]) {
|
|
286
|
+
const invalidInterlace = pngWithIdat(deflateSync(Buffer.alloc(6)), { width: 1, height: 1, interlace: bad });
|
|
287
|
+
expect(inspectAvatarImage(invalidInterlace)).toEqual({ ok: false, reason: "interlaced_unsupported" });
|
|
288
|
+
}
|
|
289
|
+
const zeroWide = realPng(0, 1); // 宽 0 + 正确 CRC:专证 bad_dimensions 而不是 bad_crc
|
|
290
|
+
expect(inspectAvatarImage(zeroWide)).toEqual({ ok: false, reason: "bad_dimensions" });
|
|
291
|
+
const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xe0, ...new Array(40).fill(0)]);
|
|
292
|
+
expect(inspectAvatarImage(jpeg)).toEqual({ ok: false, reason: "not_png" });
|
|
293
|
+
expect(inspectAvatarImage(Buffer.alloc(MAX_AVATAR_BYTES + 1))).toEqual({ ok: false, reason: "too_large" });
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
// #2054 —— Hub-wide 头像总容量上界:公开注册可无限建账号,per-user 单条上限挡不住
|
|
297
|
+
// 轮换账号把主库撑大。这里在库里塞一条接近上界的行,断言上传被 503 拒绝,
|
|
298
|
+
// 且**不删除**任何既有用户的头像(别人的数据不动),随后清掉该行恢复。
|
|
299
|
+
test("account avatar upload: a hub-wide storage cap rejects the write and keeps existing rows", async () => {
|
|
300
|
+
const { MAX_AVATAR_STORAGE_BYTES } = await import("./user-avatar-image.js");
|
|
301
|
+
const victim = register("avcap_alice", "AvatarCap1!");
|
|
302
|
+
const uploader = register("avcap_bob", "AvatarCap1!");
|
|
303
|
+
expect(victim.ok && uploader.ok).toBe(true);
|
|
304
|
+
|
|
305
|
+
const { bootServer } = await import("./server.js");
|
|
306
|
+
const hub = bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
307
|
+
const base = `http://127.0.0.1:${hub.port}`;
|
|
308
|
+
const upload = async (token: string, bytes: Buffer) => {
|
|
309
|
+
const form = new FormData();
|
|
310
|
+
form.append("file", new Blob([bytes], { type: "image/png" }), "a.png");
|
|
311
|
+
const res = await fetch(`${base}/api/auth/me/avatar/upload`, {
|
|
312
|
+
method: "POST", headers: { Authorization: `Bearer ${token}` }, body: form,
|
|
313
|
+
});
|
|
314
|
+
return { status: res.status, body: (await res.json().catch(() => null)) as any };
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
const filler = Buffer.from("filler-avatar-bytes");
|
|
318
|
+
try {
|
|
319
|
+
// 先让 bob 正常上传一次,证明上界不是「谁都不能传」。
|
|
320
|
+
const ok = await upload(uploader.token!, PNG_1X1);
|
|
321
|
+
expect(ok.status).toBe(200);
|
|
322
|
+
|
|
323
|
+
// 塞一条「别人已经占满」的行:总量逼到上界之上。
|
|
324
|
+
db.run(
|
|
325
|
+
"INSERT INTO user_avatar_uploads (user_id, version, png, bytes, width, height, updated_at) VALUES (?1, ?2, ?3, ?4, 1, 1, datetime('now'))",
|
|
326
|
+
[victim.user!.user_id, "capver", filler, MAX_AVATAR_STORAGE_BYTES],
|
|
327
|
+
);
|
|
328
|
+
const before = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM user_avatar_uploads")!.n;
|
|
329
|
+
|
|
330
|
+
const blocked = await upload(uploader.token!, PNG_1X1);
|
|
331
|
+
expect(blocked.status).toBe(503);
|
|
332
|
+
expect(blocked.body.error).toBe("avatar_storage_full");
|
|
333
|
+
|
|
334
|
+
// 不回收别人的数据:行数与那条 filler 都还在。
|
|
335
|
+
const after = db.get<{ n: number }>("SELECT COUNT(*) AS n FROM user_avatar_uploads")!.n;
|
|
336
|
+
expect(after).toBe(before);
|
|
337
|
+
expect(db.get<any>("SELECT bytes FROM user_avatar_uploads WHERE user_id = ?1", [victim.user!.user_id])?.bytes)
|
|
338
|
+
.toBe(MAX_AVATAR_STORAGE_BYTES);
|
|
339
|
+
// 自己的额度要扣掉:上限全算在自己头上时,替换**自己**的头像不应被拒。
|
|
340
|
+
db.run("DELETE FROM user_avatar_uploads WHERE user_id = ?1", [victim.user!.user_id]);
|
|
341
|
+
db.run("UPDATE user_avatar_uploads SET bytes = ?1 WHERE user_id = ?2", [MAX_AVATAR_STORAGE_BYTES, uploader.user!.user_id]);
|
|
342
|
+
const replaced = await upload(uploader.token!, PNG_1X1);
|
|
343
|
+
expect(replaced.status).toBe(200);
|
|
344
|
+
} finally {
|
|
345
|
+
db.run("DELETE FROM user_avatar_uploads WHERE user_id = ?1", [victim.user!.user_id]);
|
|
346
|
+
hub.stop?.();
|
|
347
|
+
}
|
|
348
|
+
});
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// #1828 —— /api/messages?scope=user 按 agent 分的未读 + 用户 ack 覆盖 inbox 里的回复行。
|
|
2
|
+
//
|
|
3
|
+
// 生产 hub 24h:admin 收到的 70 条 agent 回复全在 `inbox`(session_name='admin', type='reply',
|
|
4
|
+
// acked 永远 0),`user_inbox` 只有 2 行;角标链只读 user_inbox,所以回复从不进未读(app#260)。
|
|
5
|
+
// 这里让 scope=user 同时给 `unread_by_agent`(两表合并)与 `unread_total`,`unread`/`pending_count`
|
|
6
|
+
// 口径不动(qa-hub-14 钉着);POST /api/messages/ack 也能 ack inbox 里发给调用者用户名的回复行。
|
|
7
|
+
//
|
|
8
|
+
// 承重的是两条边界:
|
|
9
|
+
// ① 只算/只 ack **调用者自己用户名** 的 inbox 行 —— B 拿 A 的 id 来 ack 匹配不到;
|
|
10
|
+
// ② 用户名与某节点 alias 撞名时,inbox 那半边整体跳过(那是节点的待办,不是用户的)。
|
|
11
|
+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
12
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
13
|
+
import { tmpdir } from "node:os";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
|
|
16
|
+
const PRIVATE_DB_DIR = mkdtempSync(join(tmpdir(), "anet-user-inbox-by-agent-"));
|
|
17
|
+
process.env.COMMHUB_DB ||= join(PRIVATE_DB_DIR, "hub.db");
|
|
18
|
+
|
|
19
|
+
let server: ReturnType<typeof Bun.serve>;
|
|
20
|
+
let base = "";
|
|
21
|
+
let aToken = "", bToken = "", cToken = "";
|
|
22
|
+
let aUserId = "", bUserId = "", cUserId = "", aNet = "", cNet = "";
|
|
23
|
+
let aName = "", bName = "", cName = "";
|
|
24
|
+
|
|
25
|
+
const get = async (path: string, token: string) => {
|
|
26
|
+
const r = await fetch(`${base}${path}`, { headers: { Authorization: `Bearer ${token}` } });
|
|
27
|
+
return { status: r.status, body: await r.json() as any };
|
|
28
|
+
};
|
|
29
|
+
const post = async (path: string, token: string, body: unknown) => {
|
|
30
|
+
const r = await fetch(`${base}${path}`, {
|
|
31
|
+
method: "POST",
|
|
32
|
+
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
|
|
33
|
+
body: JSON.stringify(body),
|
|
34
|
+
});
|
|
35
|
+
return { status: r.status, body: await r.json() as any };
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
function seedUserInbox(mid: string, userId: string, netId: string, from: string) {
|
|
39
|
+
const { db } = require("./db.js");
|
|
40
|
+
db.run(
|
|
41
|
+
`INSERT INTO user_inbox (message_id, network_id, user_id, from_session, kind, title, content, severity, meta_json, acked)
|
|
42
|
+
VALUES (?1, ?2, ?3, ?4, 'agent_message', NULL, 'dm', 'info', NULL, 0)`,
|
|
43
|
+
[mid, netId, userId, from],
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
function seedInbox(id: string, sessionName: string, netId: string, from: string, type = "reply", acked = 0) {
|
|
47
|
+
const { db } = require("./db.js");
|
|
48
|
+
db.run(
|
|
49
|
+
`INSERT INTO inbox (id, session_name, type, priority, content, from_session, acked, network_id, created_at)
|
|
50
|
+
VALUES (?1, ?2, ?3, 'normal', 'reply body', ?4, ?5, ?6, datetime('now'))`,
|
|
51
|
+
[id, sessionName, type, from, acked, netId],
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
beforeAll(async () => {
|
|
56
|
+
process.env.COMMHUB_AUTH_TOKEN ||= "legacy-master-token-for-test";
|
|
57
|
+
const { db } = await import("./db.js");
|
|
58
|
+
const { register, addNetworkMember } = await import("./auth.js");
|
|
59
|
+
const stamp = Date.now();
|
|
60
|
+
|
|
61
|
+
// 首个注册用户 = 全局 admin;探针 A/B/C 都不是 admin(admin 走不过滤分支,隔离断言会白过)。
|
|
62
|
+
const admin = register(`uba_admin_${stamp}`, "UbaAdmin-Strong-1!");
|
|
63
|
+
expect(admin.ok).toBe(true);
|
|
64
|
+
aName = `uba_a_${stamp}`; bName = `uba_b_${stamp}`; cName = `uba_c_${stamp}`;
|
|
65
|
+
const a = register(aName, "UbaA-Strong-1!");
|
|
66
|
+
const b = register(bName, "UbaB-Strong-1!");
|
|
67
|
+
const c = register(cName, "UbaC-Strong-1!");
|
|
68
|
+
expect(a.ok && b.ok && c.ok).toBe(true);
|
|
69
|
+
aToken = a.token!; bToken = b.token!; cToken = c.token!;
|
|
70
|
+
aNet = a.network_id!; cNet = c.network_id!;
|
|
71
|
+
const uid = (name: string) => db.get<{ user_id: string }>("SELECT user_id FROM users WHERE username = ?1", name)!.user_id;
|
|
72
|
+
aUserId = uid(aName); bUserId = uid(bName); cUserId = uid(cName);
|
|
73
|
+
for (const id of [aUserId, bUserId, cUserId]) {
|
|
74
|
+
expect(db.get<{ role: string }>("SELECT role FROM users WHERE user_id = ?1", id)?.role).toBe("user");
|
|
75
|
+
}
|
|
76
|
+
// B 与 A 同网:user_id / session_name 过滤是唯一的隔离手段。
|
|
77
|
+
expect(addNetworkMember(aNet, bUserId, "member").ok).toBe(true);
|
|
78
|
+
|
|
79
|
+
// A:user_inbox 两条(node-x),inbox 回复两条(peer-1)+ 一条已 ack + 一条 status 类(不算)。
|
|
80
|
+
seedUserInbox("dm_a1", aUserId, aNet, "node-x");
|
|
81
|
+
seedUserInbox("dm_a2", aUserId, aNet, "node-x");
|
|
82
|
+
seedInbox("ib_a1", aName, aNet, "peer-1");
|
|
83
|
+
seedInbox("ib_a2", aName, aNet, "peer-1");
|
|
84
|
+
seedInbox("ib_a_acked", aName, aNet, "peer-1", "reply", 1);
|
|
85
|
+
seedInbox("ib_a_status", aName, aNet, "peer-1", "status");
|
|
86
|
+
// B 同网:自己的一条回复;不该出现在 A 的数里。
|
|
87
|
+
seedInbox("ib_b1", bName, aNet, "peer-2");
|
|
88
|
+
// C:用户名撞节点 alias —— inbox 里那行是节点的待办。
|
|
89
|
+
db.run(
|
|
90
|
+
`INSERT INTO nodes (node_id, node_name, alias, network_id, created_at, updated_at)
|
|
91
|
+
VALUES (?1, ?2, ?3, ?4, datetime('now'), datetime('now'))`,
|
|
92
|
+
[`node_${stamp}`, cName, cName, cNet],
|
|
93
|
+
);
|
|
94
|
+
seedInbox("ib_c_node_task", cName, cNet, "leader", "task");
|
|
95
|
+
seedUserInbox("dm_c1", cUserId, cNet, "node-y");
|
|
96
|
+
|
|
97
|
+
const mod = await import("./server.js");
|
|
98
|
+
server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
99
|
+
base = `http://127.0.0.1:${server.port}`;
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
afterAll(() => {
|
|
103
|
+
try { server?.stop(true); } catch {}
|
|
104
|
+
try { rmSync(PRIVATE_DB_DIR, { recursive: true, force: true }); } catch {}
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
describe("#1828 GET /api/messages?scope=user unread_by_agent", () => {
|
|
108
|
+
test("A:user_inbox + inbox 回复按 agent 合并;unread/pending_count 口径不变", async () => {
|
|
109
|
+
const { status, body } = await get("/api/messages?scope=user", aToken);
|
|
110
|
+
expect(status).toBe(200);
|
|
111
|
+
expect(body.unread).toBe(2); // 只算 user_inbox(qa-hub-14 钉着)
|
|
112
|
+
expect(body.pending_count).toBe(2);
|
|
113
|
+
expect(body.unread_by_agent).toEqual({ "node-x": 2, "peer-1": 2 }); // 已 ack 与 status 类不算
|
|
114
|
+
expect(body.unread_total).toBe(4);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test("B(同网):只看到自己的回复,看不到 A 的", async () => {
|
|
118
|
+
const { body } = await get("/api/messages?scope=user", bToken);
|
|
119
|
+
expect(body.unread_by_agent).toEqual({ "peer-2": 1 });
|
|
120
|
+
expect(body.unread_total).toBe(1);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test("🔴 C 的用户名撞节点 alias:inbox 半边整体跳过,只剩 user_inbox", async () => {
|
|
124
|
+
const { body } = await get("/api/messages?scope=user", cToken);
|
|
125
|
+
expect(body.unread_by_agent).toEqual({ "node-y": 1 });
|
|
126
|
+
expect(body.unread_total).toBe(1);
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
describe("#1828 POST /api/messages/ack covers inbox reply rows", () => {
|
|
131
|
+
test("🔴 B 拿 A 的 inbox id 来 ack:匹配不到,A 的数不动", async () => {
|
|
132
|
+
const { body } = await post("/api/messages/ack", bToken, { message_ids: ["ib_a1"] });
|
|
133
|
+
expect(body).toMatchObject({ ok: true, acked: 0, acked_inbox: 0 });
|
|
134
|
+
// 2026-10-31 —— #3214:ack 的形状钉住(两个分桶 + 总数,客户端按这三个数更新未读角标)
|
|
135
|
+
expect(Object.keys(body).sort()).toEqual(["acked", "acked_inbox", "acked_user_inbox", "ok", "scope"]);
|
|
136
|
+
// 守恒:两个分桶之和 == 总数(否则角标与明细是两个读数)
|
|
137
|
+
expect(body.acked_inbox + body.acked_user_inbox).toBe(body.acked);
|
|
138
|
+
const a = await get("/api/messages?scope=user", aToken);
|
|
139
|
+
expect(a.body.unread_by_agent["peer-1"]).toBe(2);
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
test("A ack 一条 inbox 回复 + 一条 user_inbox:两边各减一,响应分开计数", async () => {
|
|
143
|
+
const { body } = await post("/api/messages/ack", aToken, { message_ids: ["ib_a1", "dm_a1"] });
|
|
144
|
+
expect(body).toMatchObject({ ok: true, acked: 2, acked_user_inbox: 1, acked_inbox: 1 });
|
|
145
|
+
const a = await get("/api/messages?scope=user", aToken);
|
|
146
|
+
expect(a.body.unread).toBe(1);
|
|
147
|
+
expect(a.body.unread_by_agent).toEqual({ "node-x": 1, "peer-1": 1 });
|
|
148
|
+
expect(a.body.unread_total).toBe(2);
|
|
149
|
+
// 再 ack 同一条:幂等,0 行。
|
|
150
|
+
const again = await post("/api/messages/ack", aToken, { message_ids: ["ib_a1"] });
|
|
151
|
+
expect(again.body.acked).toBe(0);
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
test("status 类 inbox 行不会被用户 ack 掉(不是发给用户的消息)", async () => {
|
|
155
|
+
const { body } = await post("/api/messages/ack", aToken, { message_ids: ["ib_a_status"] });
|
|
156
|
+
expect(body.acked_inbox).toBe(0);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
test("🔴 C 撞名:节点的待办不能被用户 ack 走", async () => {
|
|
160
|
+
const { body } = await post("/api/messages/ack", cToken, { message_ids: ["ib_c_node_task"] });
|
|
161
|
+
expect(body.acked_inbox).toBe(0);
|
|
162
|
+
const { db } = require("./db.js");
|
|
163
|
+
expect(db.get<{ acked: number }>("SELECT acked FROM inbox WHERE id = 'ib_c_node_task'")?.acked).toBe(0);
|
|
164
|
+
});
|
|
165
|
+
});
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// #1493 — user_inbox.network_id 升 schema 级 NOT NULL(belt-and-suspenders)。
|
|
2
|
+
//
|
|
3
|
+
// 「不产生 NULL 孤儿」原是代码级三闸(#1492 证不可达)。schema 级 NOT NULL 让**任何**
|
|
4
|
+
// 未来绕过那三闸写 NULL 的回归在 INSERT 处被 DB 直接拒,而不是产出 scoped-unreadable
|
|
5
|
+
// 的静默孤儿。生产 hub 已在 preview.41、user_inbox 有真实行 → 迁移必须:① 新库直接
|
|
6
|
+
// NOT NULL;② 存量库无损重建(建新表→copy→drop→rename);③ 迁移前若发现 NULL 行(理应
|
|
7
|
+
// 为 0)fail-closed 停下,不静默丢。
|
|
8
|
+
//
|
|
9
|
+
// 后两条要预置「旧 schema(nullable)」的库 → 用 bun:sqlite 手造库 + 子进程 import db.js
|
|
10
|
+
// 触发迁移(与 boot-side-effect.test.ts 同款子进程范式)。
|
|
11
|
+
|
|
12
|
+
import { describe, expect, test } from "bun:test";
|
|
13
|
+
import { Database } from "bun:sqlite";
|
|
14
|
+
import { mkdtempSync } from "fs";
|
|
15
|
+
import { join } from "path";
|
|
16
|
+
import { tmpdir } from "os";
|
|
17
|
+
import { db } from "./db.js";
|
|
18
|
+
|
|
19
|
+
const OLD_SCHEMA = `CREATE TABLE user_inbox (
|
|
20
|
+
message_id TEXT PRIMARY KEY, network_id TEXT, user_id TEXT NOT NULL, from_session TEXT,
|
|
21
|
+
kind TEXT NOT NULL DEFAULT 'info', title TEXT, content TEXT NOT NULL,
|
|
22
|
+
severity TEXT NOT NULL DEFAULT 'info', meta_json TEXT, acked INTEGER NOT NULL DEFAULT 0,
|
|
23
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')), acked_at TEXT)`;
|
|
24
|
+
|
|
25
|
+
/** 预置一个「旧 schema(network_id 可空)」的库文件,可选带若干行。返回文件路径。 */
|
|
26
|
+
function seedOldDb(rows: Array<{ mid: string; net: string | null; user: string }>): string {
|
|
27
|
+
const file = join(mkdtempSync(join(tmpdir(), "anet-1493-")), "hub.db");
|
|
28
|
+
const raw = new Database(file);
|
|
29
|
+
raw.exec(OLD_SCHEMA);
|
|
30
|
+
for (const r of rows) {
|
|
31
|
+
raw.run("INSERT INTO user_inbox (message_id, network_id, user_id, content) VALUES (?1, ?2, ?3, 'body')",
|
|
32
|
+
[r.mid, r.net, r.user]);
|
|
33
|
+
}
|
|
34
|
+
raw.close();
|
|
35
|
+
return file;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 子进程里 import db.js(触发迁移),回读一段结果。返回 {exitCode, stdout, stderr}。 */
|
|
39
|
+
function bootWithDb(file: string, probe: string) {
|
|
40
|
+
const script = `
|
|
41
|
+
process.env.COMMHUB_DB = ${JSON.stringify(file)};
|
|
42
|
+
const { db } = await import("./src/db.js");
|
|
43
|
+
${probe}
|
|
44
|
+
process.exit(0);
|
|
45
|
+
`;
|
|
46
|
+
const child = Bun.spawnSync({
|
|
47
|
+
cmd: ["bun", "-e", script],
|
|
48
|
+
cwd: `${import.meta.dir}/..`,
|
|
49
|
+
env: { ...process.env, COMMHUB_DB: file },
|
|
50
|
+
timeout: 20_000,
|
|
51
|
+
});
|
|
52
|
+
return {
|
|
53
|
+
exitCode: child.exitCode,
|
|
54
|
+
stdout: new TextDecoder().decode(child.stdout),
|
|
55
|
+
stderr: new TextDecoder().decode(child.stderr),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
describe("#1493 user_inbox.network_id NOT NULL (belt-and-suspenders)", () => {
|
|
60
|
+
test("new DB: network_id is NOT NULL and rejects a NULL insert", () => {
|
|
61
|
+
const col = db.all<{ name: string; notnull: number }>("PRAGMA table_info(user_inbox)").find(c => c.name === "network_id");
|
|
62
|
+
expect(col?.notnull).toBe(1);
|
|
63
|
+
// 绕过代码闸直接写 NULL → DB 拒(这正是 belt-and-suspenders 的价值)
|
|
64
|
+
expect(() => db.run(
|
|
65
|
+
"INSERT INTO user_inbox (message_id, user_id, content) VALUES (?1, ?2, ?3)",
|
|
66
|
+
[`dm_nn_${Date.now()}`, "u_nn", "hi"],
|
|
67
|
+
)).toThrow(/NOT NULL/i);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("migration: old nullable table with valid rows → rebuilt NOT NULL, rows preserved, index recreated", () => {
|
|
71
|
+
const file = seedOldDb([
|
|
72
|
+
{ mid: "dm_1", net: "net_a", user: "u_1" },
|
|
73
|
+
{ mid: "dm_2", net: "net_b", user: "u_2" },
|
|
74
|
+
]);
|
|
75
|
+
const r = bootWithDb(file, `
|
|
76
|
+
const col = db.all("PRAGMA table_info(user_inbox)").find(c => c.name === "network_id");
|
|
77
|
+
const rows = db.get("SELECT COUNT(*) AS n FROM user_inbox").n;
|
|
78
|
+
const idx = db.get("SELECT COUNT(*) AS n FROM sqlite_master WHERE type='index' AND name='idx_user_inbox_user_acked'").n;
|
|
79
|
+
let nullRejected = false;
|
|
80
|
+
try { db.run("INSERT INTO user_inbox (message_id, user_id, content) VALUES ('dm_z','u_z','x')"); }
|
|
81
|
+
catch { nullRejected = true; }
|
|
82
|
+
console.log("RESULT:" + JSON.stringify({ notnull: col.notnull, rows, idx, nullRejected }));
|
|
83
|
+
`);
|
|
84
|
+
expect(r.exitCode).toBe(0);
|
|
85
|
+
const m = r.stdout.match(/RESULT:(\{.*\})/);
|
|
86
|
+
expect(m).not.toBeNull();
|
|
87
|
+
const out = JSON.parse(m![1]);
|
|
88
|
+
expect(out.notnull).toBe(1); // 迁移后 NOT NULL
|
|
89
|
+
expect(out.rows).toBe(2); // 两行无损保留
|
|
90
|
+
expect(out.idx).toBe(1); // 索引重建
|
|
91
|
+
expect(out.nullRejected).toBe(true);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test("migration guard: old table with a network_id IS NULL row → fail-safe (warn + skip, hub boots, data intact)", () => {
|
|
95
|
+
const file = seedOldDb([
|
|
96
|
+
{ mid: "dm_ok", net: "net_a", user: "u_1" },
|
|
97
|
+
{ mid: "dm_orphan", net: null, user: "u_2" }, // 理应不可达;若真出现 → warn+跳过,不停机
|
|
98
|
+
]);
|
|
99
|
+
const r = bootWithDb(file, `
|
|
100
|
+
const col = db.all("PRAGMA table_info(user_inbox)").find(c => c.name === "network_id");
|
|
101
|
+
const rows = db.get("SELECT COUNT(*) AS n FROM user_inbox").n;
|
|
102
|
+
console.log("RESULT:" + JSON.stringify({ notnull: col.notnull, rows }));
|
|
103
|
+
`);
|
|
104
|
+
expect(r.exitCode).toBe(0); // hub 照常启动(fail-safe,不停机)
|
|
105
|
+
expect(r.stderr).toMatch(/migrate #1493/); // 大声 warn(明确运维信号)
|
|
106
|
+
expect(r.stderr).toMatch(/network_id IS NULL/);
|
|
107
|
+
const m = r.stdout.match(/RESULT:(\{.*\})/);
|
|
108
|
+
expect(m).not.toBeNull();
|
|
109
|
+
const out = JSON.parse(m![1]);
|
|
110
|
+
expect(out.notnull).toBe(0); // 迁移被跳过 → 列暂保持可空
|
|
111
|
+
expect(out.rows).toBe(2); // 数据没丢(没盲目清空)
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("idempotent: booting an already-migrated (NOT NULL) DB twice is a no-op", () => {
|
|
115
|
+
const file = seedOldDb([{ mid: "dm_a", net: "net_a", user: "u_1" }]);
|
|
116
|
+
const r1 = bootWithDb(file, `console.log("RESULT:" + db.all("PRAGMA table_info(user_inbox)").find(c=>c.name==="network_id").notnull);`);
|
|
117
|
+
expect(r1.exitCode).toBe(0);
|
|
118
|
+
const r2 = bootWithDb(file, `console.log("RESULT:" + db.all("PRAGMA table_info(user_inbox)").find(c=>c.name==="network_id").notnull);`);
|
|
119
|
+
expect(r2.exitCode).toBe(0);
|
|
120
|
+
expect(r2.stdout).toContain("RESULT:1"); // 第二次仍 NOT NULL、不炸
|
|
121
|
+
});
|
|
122
|
+
});
|