@sleep2agi/commhub-server 0.9.0-preview.1 → 0.9.0-preview.101
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 +130 -10
- package/bin/commhub.ts +92 -11
- package/package.json +8 -7
- package/src/ack-create-request-transport.test.ts +159 -0
- package/src/ack-create-request.test.ts +331 -0
- package/src/admin-delete-network-http.test.ts +228 -0
- package/src/admin-networks-http.test.ts +88 -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 +520 -0
- package/src/agent-acl-slice3-http.test.ts +267 -0
- package/src/agent-groups-perf.test.ts +190 -0
- package/src/agent-notice.ts +48 -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 +271 -0
- package/src/api-nodes-shape.test.ts +188 -0
- package/src/auth-sessions-http.test.ts +250 -0
- package/src/auth-validate.test.ts +5 -1
- package/src/auth.ts +493 -35
- package/src/avatar-validate.test.ts +163 -0
- package/src/avatar-validate.ts +103 -0
- package/src/blocked-exit-on-reply.test.ts +122 -0
- package/src/boot-side-effect.test.ts +124 -0
- package/src/commhub-bin-args.test.ts +85 -0
- package/src/config-apply-sec1.test.ts +270 -1
- package/src/config-apply-validate.test.ts +92 -0
- package/src/config-apply-validate.ts +81 -3
- package/src/create-node-blocked-gate.test.ts +356 -0
- package/src/create-node-tool-schema.test.ts +39 -0
- package/src/create-node-validate.test.ts +275 -0
- package/src/create-node-validate.ts +288 -0
- package/src/create-node-workdir.test.ts +255 -0
- package/src/create-node.test.ts +354 -0
- package/src/create-node.ts +349 -0
- package/src/dashboard-slash-routing-http.test.ts +107 -0
- package/src/db-adapter-guard.test.ts +148 -0
- package/src/db-adapter-translate.test.ts +128 -0
- package/src/db-adapter.ts +323 -87
- package/src/db-timestamp.test.ts +38 -0
- package/src/db-timestamp.ts +15 -0
- package/src/db.ts +984 -34
- 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 +329 -0
- package/src/department-heads.ts +226 -0
- package/src/departments-http.test.ts +185 -0
- package/src/departments.ts +260 -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/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-redaction.test.ts +642 -0
- package/src/http-gzip.test.ts +94 -0
- package/src/http-gzip.ts +112 -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/inbox-count-sse.test.ts +310 -0
- package/src/inbox-count.ts +29 -0
- package/src/index.ts +15 -2172
- package/src/lifecycle-guard.ts +50 -0
- package/src/list-host-supervisors.test.ts +314 -0
- package/src/mcp-context-cost-http.test.ts +119 -0
- package/src/mcp-projects-events-http.test.ts +162 -0
- package/src/mcp-route-label-http.test.ts +120 -0
- package/src/mcp-write-network-resolution.test.ts +429 -0
- package/src/member-audit-network-id-http.test.ts +93 -0
- package/src/member-presence-http.test.ts +206 -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-scope.ts +224 -0
- package/src/network-token-membership-http.test.ts +139 -0
- package/src/node-attrs-validate.ts +88 -0
- package/src/node-attrs.test.ts +217 -0
- package/src/node-create-request-status-http.test.ts +92 -0
- package/src/node-files-transport.test.ts +344 -0
- package/src/node-health-dispatch-http.test.ts +279 -0
- package/src/node-health-guard.ts +105 -0
- package/src/node-health-passthrough.test.ts +115 -0
- package/src/node-health-store.ts +72 -0
- package/src/node-id-alias.test.ts +188 -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-lifecycle-controllable.test.ts +64 -0
- package/src/node-lifecycle-controllable.ts +51 -0
- package/src/node-logs-transport.test.ts +263 -0
- package/src/node-permissions-http.test.ts +276 -0
- package/src/node-permissions.ts +242 -0
- package/src/node-request-retention.test.ts +281 -0
- package/src/node-request-retention.ts +120 -0
- package/src/node-skills-transport.test.ts +209 -0
- package/src/node-token-privilege-http.test.ts +149 -0
- package/src/observer-avatar-http.test.ts +431 -0
- package/src/observer-push.test.ts +252 -0
- package/src/package-version-consistency.test.ts +25 -0
- package/src/peer-reply-atomic.test.ts +455 -0
- package/src/peer-reply-capability.test.ts +70 -0
- package/src/pg-worker.ts +87 -0
- package/src/probe-validate.test.ts +221 -0
- package/src/probe-validate.ts +104 -0
- package/src/probe.test.ts +80 -0
- package/src/probe.ts +200 -0
- package/src/project-viewer-can-http.test.ts +114 -0
- package/src/push.ts +429 -10
- package/src/redact-tokens.test.ts +65 -0
- package/src/redact-tokens.ts +40 -0
- package/src/rename.ts +7 -2
- package/src/reply-target-derivation.test.ts +96 -0
- package/src/report-status-host-schema.test.ts +211 -0
- package/src/report-status-resume-id-handover.test.ts +150 -0
- package/src/require-explicit-test-db.ts +9 -0
- package/src/requirement-due-reminders-http.test.ts +518 -0
- package/src/requirement-due-reminders.ts +369 -0
- package/src/requirement-events-http.test.ts +257 -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 +266 -0
- package/src/requirement-tags.ts +89 -0
- package/src/requirements-comment-http.test.ts +165 -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 +143 -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 +344 -0
- package/src/requirements-list-mcp-slim-http.test.ts +155 -0
- package/src/requirements-list-slim-http.test.ts +319 -0
- package/src/requirements-mcp.test.ts +163 -0
- package/src/requirements-migrate.ts +225 -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 +225 -0
- package/src/requirements-people.ts +127 -0
- package/src/requirements-priority-lowest.test.ts +114 -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 +288 -0
- package/src/requirements-stats.ts +164 -0
- package/src/requirements-status-participants-http.test.ts +220 -0
- package/src/requirements-upgrade-e2e.test.ts +126 -0
- package/src/requirements-upgrade-migration.test.ts +98 -0
- package/src/requirements.ts +1761 -0
- package/src/resolve-port.test.ts +57 -0
- package/src/resolve-port.ts +44 -0
- package/src/response-charset.test.ts +130 -0
- package/src/rest-explicit-columns-http.test.ts +222 -0
- package/src/rest-identity.test.ts +129 -0
- package/src/rest-identity.ts +100 -0
- package/src/rest-projections.ts +68 -0
- package/src/rest-write-network-resolution.test.ts +133 -0
- package/src/restricted-files.ts +73 -0
- package/src/retention.ts +15 -3
- package/src/route-callers-http.test.ts +120 -0
- package/src/route-timing.test.ts +211 -0
- package/src/route-timing.ts +258 -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/scheduled-doorbell-nodeless-session.test.ts +130 -0
- package/src/scheduled-failures-http.test.ts +233 -0
- package/src/scheduled-failures.ts +179 -0
- package/src/scheduled-reply-unread-http.test.ts +212 -0
- package/src/scheduled-run-terminal.test.ts +268 -0
- package/src/scheduled-skip-blocking-task.test.ts +120 -0
- package/src/scheduled-stuck-http.test.ts +238 -0
- package/src/scheduled-stuck.ts +153 -0
- package/src/scheduled-tasks-http.test.ts +638 -0
- package/src/scheduled-tasks.ts +650 -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 +38 -0
- package/src/serve-error.ts +27 -0
- package/src/server.ts +5038 -0
- package/src/shared/external-schedule-contract.ts +60 -0
- package/src/shared/probe-host-allowlist-drift.test.ts +54 -0
- package/src/shared/probe-host-allowlist.ts +128 -0
- package/src/shared/reserved-env-drift.test.ts +43 -0
- package/src/shared/reserved-env.test.ts +35 -0
- package/src/shared/reserved-env.ts +31 -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 +108 -0
- package/src/sqlite-close-checkpoint.test.ts +78 -0
- package/src/start-node.test.ts +109 -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 +122 -0
- package/src/stop-delete-node.test.ts +1164 -0
- package/src/task-access-http.test.ts +379 -0
- package/src/task-access.ts +413 -0
- package/src/task-auth-origin-http.test.ts +91 -0
- package/src/task-auth-origin.test.ts +24 -0
- package/src/task-auth-origin.ts +7 -0
- package/src/task-consumption.test.ts +482 -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 +313 -0
- package/src/task-idempotency-mcp.test.ts +142 -0
- package/src/task-idempotency.test.ts +60 -0
- package/src/task-idempotency.ts +75 -0
- package/src/task-lifecycle-watcher.test.ts +204 -0
- package/src/task-lifecycle-watcher.ts +49 -0
- package/src/task-network-resolution-http.test.ts +141 -0
- package/src/task-queue-ahead-http.test.ts +309 -0
- package/src/task-queue-ahead-scale.test.ts +211 -0
- package/src/task-queue-ahead.ts +186 -0
- package/src/task-stale-open-http.test.ts +290 -0
- package/src/task-stale-open.ts +103 -0
- package/src/tasks-pagination-http.test.ts +141 -0
- package/src/tool-audience-http.test.ts +195 -0
- package/src/tool-audience.ts +109 -0
- package/src/tools-list-json-schema.test.ts +67 -0
- package/src/tools.ts +4955 -300
- package/src/update-provider.test.ts +234 -0
- package/src/upload-early-reject-guard.test.ts +155 -0
- package/src/uploads-http.test.ts +97 -15
- package/src/uploads.test.ts +66 -0
- package/src/uploads.ts +138 -5
- 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/vault.test.ts +200 -0
- package/src/vault.ts +156 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// RFC-027 §2.3 race-free invariant — shared helper for the inbox-
|
|
2
|
+
// enqueue lifecycle guard.
|
|
3
|
+
//
|
|
4
|
+
// PR1.1 (#346) added an `assertNodeActive` helper inside the
|
|
5
|
+
// registerTools() closure and applied it at the 6 INSERT INTO inbox
|
|
6
|
+
// sites in server/src/tools.ts. PR1.1 review (通信龙 #346 ack) caught
|
|
7
|
+
// that the closure scope made the helper unreachable from REST
|
|
8
|
+
// handlers in server/src/index.ts — POST /api/task (:1631) and
|
|
9
|
+
// POST /api/broadcast (:1706) are dashboard's "Dispatch" entry
|
|
10
|
+
// points and bypassed the guard, leaving the §2.3 race open on the
|
|
11
|
+
// REST path.
|
|
12
|
+
//
|
|
13
|
+
// PR1.2a (#346 follow-up) extracts the helper to this module so both
|
|
14
|
+
// the MCP tools and the REST handlers can import the same code path,
|
|
15
|
+
// per team rule (grep every write site before adding a guard): any SQL-level
|
|
16
|
+
// guard's helper lives at module scope so every write site
|
|
17
|
+
// (MCP + REST + internal db.ts helpers) can use it.
|
|
18
|
+
//
|
|
19
|
+
// Behaviour:
|
|
20
|
+
// - no nodes row for the alias → ok:true (brand-new alias allowed;
|
|
21
|
+
// could be the first INSERT for a child about to register)
|
|
22
|
+
// - lifecycle_state = 'active' OR NULL (pre-RFC-027 row) → ok:true
|
|
23
|
+
// - anything else (stopping / stopped / stop_failed / deleting) →
|
|
24
|
+
// ok:false + structured `node_not_active` reply
|
|
25
|
+
//
|
|
26
|
+
// COALESCE on the WHERE keeps NULL-network inbox rows / legacy nodes
|
|
27
|
+
// rows correctly scoped (PR1 SF-5 lineage).
|
|
28
|
+
|
|
29
|
+
import { db } from "./db.js";
|
|
30
|
+
|
|
31
|
+
export type LifecycleGuardResult =
|
|
32
|
+
| { ok: true }
|
|
33
|
+
| { ok: false; error: "node_not_active"; lifecycle_state: string; alias: string };
|
|
34
|
+
|
|
35
|
+
export function assertNodeActive(
|
|
36
|
+
sessionAlias: string,
|
|
37
|
+
networkId: string | null,
|
|
38
|
+
): LifecycleGuardResult {
|
|
39
|
+
if (!sessionAlias) return { ok: true };
|
|
40
|
+
const row = db.get<{ lifecycle_state: string | null }>(
|
|
41
|
+
networkId
|
|
42
|
+
? `SELECT lifecycle_state FROM nodes WHERE alias = ?1 AND COALESCE(network_id, ?2) = ?2 LIMIT 1`
|
|
43
|
+
: `SELECT lifecycle_state FROM nodes WHERE alias = ?1 LIMIT 1`,
|
|
44
|
+
...(networkId ? [sessionAlias, networkId] : [sessionAlias]),
|
|
45
|
+
);
|
|
46
|
+
if (!row) return { ok: true };
|
|
47
|
+
const st = row.lifecycle_state ?? "active";
|
|
48
|
+
if (st === "active") return { ok: true };
|
|
49
|
+
return { ok: false, error: "node_not_active", lifecycle_state: st, alias: sessionAlias };
|
|
50
|
+
}
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { afterAll, beforeEach, describe, expect, test } from "bun:test";
|
|
2
|
+
import { db, hashToken, generateId } from "./db.js";
|
|
3
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
|
+
import { registerTools } from "./tools.js";
|
|
5
|
+
|
|
6
|
+
// RFC-026 §9.2 / #338 PR2 v2 — list_host_supervisors HANDLER tests.
|
|
7
|
+
//
|
|
8
|
+
// PR2 v1 used a mirror-SQL pattern (re-implemented the query in the test
|
|
9
|
+
// itself) → trivially passed but didn't exercise the handler. 通信龙 audit
|
|
10
|
+
// caught: that style misses the SEC-1 scope-derivation bug
|
|
11
|
+
// (`getNetworkId(clientNetId)` returns the unchecked client-supplied
|
|
12
|
+
// network_id for utok_ callers when enforceNetworkId is null, leaking
|
|
13
|
+
// cross-tenant daemons). This rewrite drives the registered MCP tool
|
|
14
|
+
// through registerTools() so the auth context is real.
|
|
15
|
+
//
|
|
16
|
+
// Covers:
|
|
17
|
+
// SEC-1.1 — cross-tenant utok_ caller with foreign network_id: DENIED
|
|
18
|
+
// SEC-1.2 — admin caller with own network_id: returns own daemons
|
|
19
|
+
// SEC-1.3 — caller with no network_id: returns daemons in all member networks
|
|
20
|
+
// masking — non-admin viewer: host_telemetry IP/cpu/mem stripped, alert_level still surfaces
|
|
21
|
+
// revoked — DELETEd token row (revokeToken path): daemon excluded
|
|
22
|
+
// revoked — revoked_at SET token: daemon excluded
|
|
23
|
+
// self-declare — runtimes_supported/allowed_secret_keys surface from columns
|
|
24
|
+
// pre-PR2 daemon — empty arrays on NULL columns (back-compat)
|
|
25
|
+
|
|
26
|
+
const NET_ALPHA = "net_lhs_alpha";
|
|
27
|
+
const NET_BETA = "net_lhs_beta";
|
|
28
|
+
|
|
29
|
+
interface ToolHandler { (args: any, extra?: any): Promise<{ content: Array<{ type: "text"; text: string }> }>; }
|
|
30
|
+
interface Reply { ok?: boolean; error?: string; daemons?: any[]; count?: number; }
|
|
31
|
+
|
|
32
|
+
function cleanup() {
|
|
33
|
+
for (const n of [NET_ALPHA, NET_BETA]) {
|
|
34
|
+
try { db.run("DELETE FROM nodes WHERE network_id = ?1", [n]); } catch {}
|
|
35
|
+
try { db.run("DELETE FROM sessions WHERE network_id = ?1", [n]); } catch {}
|
|
36
|
+
try { db.run("DELETE FROM api_tokens WHERE network_id = ?1", [n]); } catch {}
|
|
37
|
+
try { db.run("DELETE FROM network_members WHERE network_id = ?1", [n]); } catch {}
|
|
38
|
+
try { db.run("DELETE FROM networks WHERE network_id = ?1", [n]); } catch {}
|
|
39
|
+
}
|
|
40
|
+
try { db.run("DELETE FROM users WHERE user_id LIKE 'u_lhs_%'"); } catch {}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
beforeEach(cleanup);
|
|
44
|
+
afterAll(cleanup);
|
|
45
|
+
|
|
46
|
+
function seedUser(user_id: string) {
|
|
47
|
+
db.run(
|
|
48
|
+
`INSERT INTO users (user_id, username, password_hash, role, created_at)
|
|
49
|
+
VALUES (?1, ?2, 'x', 'user', datetime('now'))`,
|
|
50
|
+
[user_id, user_id],
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
function seedNetwork(net_id: string, owner_id = "u_lhs_owner") {
|
|
54
|
+
db.run(
|
|
55
|
+
`INSERT OR REPLACE INTO networks (network_id, network_name, owner_id, created_at)
|
|
56
|
+
VALUES (?1, ?2, ?3, datetime('now'))`,
|
|
57
|
+
[net_id, net_id, owner_id],
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
function seedMembership(user_id: string, net_id: string, role: "owner" | "admin" | "member" | "viewer" = "member") {
|
|
61
|
+
db.run(
|
|
62
|
+
`INSERT INTO network_members (user_id, network_id, role, joined_at)
|
|
63
|
+
VALUES (?1, ?2, ?3, datetime('now'))`,
|
|
64
|
+
[user_id, net_id, role],
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
function seedDaemon(opts: {
|
|
68
|
+
network_id: string, alias: string, node_id?: string,
|
|
69
|
+
role?: string,
|
|
70
|
+
runtimes?: string[],
|
|
71
|
+
secrets?: string[],
|
|
72
|
+
sessionAgeMs?: number,
|
|
73
|
+
mintToken?: boolean,
|
|
74
|
+
tokenRevokedAt?: boolean,
|
|
75
|
+
tokenDeleted?: boolean,
|
|
76
|
+
}) {
|
|
77
|
+
const node_id = opts.node_id || `node_${opts.network_id}_${opts.alias}`;
|
|
78
|
+
const snapshot = JSON.stringify({
|
|
79
|
+
model: "claude-opus", flags: {}, role: opts.role ?? "host_supervisor",
|
|
80
|
+
runtimes_supported: opts.runtimes ?? ["claude-agent-sdk"],
|
|
81
|
+
allowed_secret_keys: opts.secrets ?? [],
|
|
82
|
+
});
|
|
83
|
+
db.run(
|
|
84
|
+
`INSERT OR REPLACE INTO nodes (
|
|
85
|
+
node_id, node_name, alias, network_id,
|
|
86
|
+
runtimes_supported, allowed_secret_keys,
|
|
87
|
+
config_snapshot, hostname,
|
|
88
|
+
created_at, updated_at
|
|
89
|
+
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, datetime('now'), datetime('now'))`,
|
|
90
|
+
[node_id, opts.alias, opts.alias, opts.network_id,
|
|
91
|
+
JSON.stringify(opts.runtimes ?? ["claude-agent-sdk"]),
|
|
92
|
+
JSON.stringify(opts.secrets ?? []),
|
|
93
|
+
snapshot, `host-${opts.alias}`],
|
|
94
|
+
);
|
|
95
|
+
if (opts.sessionAgeMs !== undefined) {
|
|
96
|
+
const ts = new Date(Date.now() - opts.sessionAgeMs).toISOString().replace("T", " ").replace(/\..+/, "");
|
|
97
|
+
db.run(
|
|
98
|
+
`INSERT OR REPLACE INTO sessions (resume_id, alias, network_id, last_seen_at, status, cpu_cores, mem_total_gb, ip)
|
|
99
|
+
VALUES (?1, ?2, ?3, ?4, 'idle', 8, 16, '10.0.0.5')`,
|
|
100
|
+
[`s_${node_id}`, opts.alias, opts.network_id, ts],
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
if (opts.mintToken !== false && !opts.tokenDeleted) {
|
|
104
|
+
db.run(
|
|
105
|
+
`INSERT OR REPLACE INTO api_tokens (token_id, user_id, network_id, scope, name, token_hash, expires_at, revoked_at)
|
|
106
|
+
VALUES (?1, ?2, ?3, 'network', ?4, ?5, NULL, ?6)`,
|
|
107
|
+
[`tok_${node_id}`, `u_seed_${node_id}`, opts.network_id, `node:${opts.alias}`,
|
|
108
|
+
`hash_${node_id}`,
|
|
109
|
+
opts.tokenRevokedAt ? new Date().toISOString().replace("T", " ").replace(/\..+/, "") : null],
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
return node_id;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Build a server with registerTools wired to a specific enforceUserId. */
|
|
116
|
+
function buildToolHandler(enforceUserId: string | null): ToolHandler {
|
|
117
|
+
const server = new McpServer({ name: "test", version: "0" }) as any;
|
|
118
|
+
const tools: Record<string, ToolHandler> = {};
|
|
119
|
+
// Capture the registered tool function. The MCP SDK's server.tool stores
|
|
120
|
+
// the handler internally; we intercept by overriding before registerTools.
|
|
121
|
+
const origTool = server.tool.bind(server);
|
|
122
|
+
server.tool = (name: string, _desc: string, _schema: any, handler: ToolHandler) => {
|
|
123
|
+
tools[name] = handler;
|
|
124
|
+
return origTool(name, _desc, _schema, handler);
|
|
125
|
+
};
|
|
126
|
+
// Some tools use registerTool; intercept that too
|
|
127
|
+
const origRegisterTool = server.registerTool?.bind(server);
|
|
128
|
+
if (origRegisterTool) {
|
|
129
|
+
server.registerTool = (name: string, _cfg: any, handler: ToolHandler) => {
|
|
130
|
+
tools[name] = handler;
|
|
131
|
+
return origRegisterTool(name, _cfg, handler);
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
registerTools(
|
|
135
|
+
server,
|
|
136
|
+
/* clientIP */ undefined,
|
|
137
|
+
/* enforceNetworkId */ null,
|
|
138
|
+
/* enforceUserId */ enforceUserId,
|
|
139
|
+
/* callerAlias */ null,
|
|
140
|
+
/* callerTokenIsNetwork */ false,
|
|
141
|
+
/* callerTokenId */ null,
|
|
142
|
+
);
|
|
143
|
+
const h = tools["list_host_supervisors"];
|
|
144
|
+
if (!h) throw new Error("list_host_supervisors tool not registered");
|
|
145
|
+
return h;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function callList(handler: ToolHandler, args: any = {}): Promise<Reply> {
|
|
149
|
+
const r = await handler(args);
|
|
150
|
+
return JSON.parse(r.content[0].text) as Reply;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
describe("list_host_supervisors HANDLER tests (RFC-026 §9.2, PR2 v2)", () => {
|
|
154
|
+
test("SEC-1.1: cross-tenant utok_ caller with foreign network_id → DENIED", async () => {
|
|
155
|
+
const userA = "u_lhs_alice"; // belongs to NET_ALPHA only
|
|
156
|
+
seedUser(userA);
|
|
157
|
+
seedNetwork(NET_ALPHA);
|
|
158
|
+
seedNetwork(NET_BETA);
|
|
159
|
+
seedMembership(userA, NET_ALPHA, "admin");
|
|
160
|
+
seedDaemon({ network_id: NET_BETA, alias: "secret-beta-daemon" });
|
|
161
|
+
|
|
162
|
+
const handler = buildToolHandler(userA);
|
|
163
|
+
const reply = await callList(handler, { network_id: NET_BETA });
|
|
164
|
+
// PR2 v1 BUG: this returned ok:true with secret-beta-daemon in the list.
|
|
165
|
+
expect(reply.ok).toBe(false);
|
|
166
|
+
expect(reply.error).toMatch(/access denied|not a member/i);
|
|
167
|
+
// Belt: hostname not in error payload
|
|
168
|
+
expect(JSON.stringify(reply)).not.toContain("secret-beta-daemon");
|
|
169
|
+
expect(JSON.stringify(reply)).not.toContain("host-secret-beta-daemon");
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
test("SEC-1.2: admin caller with own network_id returns own daemons", async () => {
|
|
173
|
+
const userA = "u_lhs_alice";
|
|
174
|
+
seedUser(userA);
|
|
175
|
+
seedNetwork(NET_ALPHA);
|
|
176
|
+
seedMembership(userA, NET_ALPHA, "admin");
|
|
177
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "alpha-daemon-1" });
|
|
178
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "alpha-daemon-2" });
|
|
179
|
+
|
|
180
|
+
const handler = buildToolHandler(userA);
|
|
181
|
+
const reply = await callList(handler, { network_id: NET_ALPHA });
|
|
182
|
+
expect(reply.ok).toBe(true);
|
|
183
|
+
const aliases = (reply.daemons ?? []).map(d => d.alias).sort();
|
|
184
|
+
expect(aliases).toEqual(["alpha-daemon-1", "alpha-daemon-2"]);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
test("SEC-1.3: caller without network_id arg → returns daemons across member networks only", async () => {
|
|
188
|
+
const userA = "u_lhs_alice"; // member of NET_ALPHA only
|
|
189
|
+
seedUser(userA);
|
|
190
|
+
seedNetwork(NET_ALPHA);
|
|
191
|
+
seedNetwork(NET_BETA);
|
|
192
|
+
seedMembership(userA, NET_ALPHA, "member");
|
|
193
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "ok-daemon" });
|
|
194
|
+
seedDaemon({ network_id: NET_BETA, alias: "forbidden-daemon" });
|
|
195
|
+
|
|
196
|
+
const handler = buildToolHandler(userA);
|
|
197
|
+
const reply = await callList(handler);
|
|
198
|
+
expect(reply.ok).toBe(true);
|
|
199
|
+
const aliases = (reply.daemons ?? []).map(d => d.alias);
|
|
200
|
+
expect(aliases).toContain("ok-daemon");
|
|
201
|
+
expect(aliases).not.toContain("forbidden-daemon");
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
test("masking: member caller gets host_telemetry without IP/cpu/mem; admin gets full", async () => {
|
|
205
|
+
const userMember = "u_lhs_bob_member";
|
|
206
|
+
const userAdmin = "u_lhs_carol_admin";
|
|
207
|
+
seedUser(userMember);
|
|
208
|
+
seedUser(userAdmin);
|
|
209
|
+
seedNetwork(NET_ALPHA);
|
|
210
|
+
seedMembership(userMember, NET_ALPHA, "member");
|
|
211
|
+
seedMembership(userAdmin, NET_ALPHA, "admin");
|
|
212
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "telemetry-daemon", sessionAgeMs: 5_000 });
|
|
213
|
+
|
|
214
|
+
const memberHandler = buildToolHandler(userMember);
|
|
215
|
+
const memberReply = await callList(memberHandler, { network_id: NET_ALPHA });
|
|
216
|
+
expect(memberReply.daemons?.[0].host_telemetry.alert_level).toBeDefined();
|
|
217
|
+
expect(memberReply.daemons?.[0].host_telemetry).not.toHaveProperty("cpu_cores");
|
|
218
|
+
expect(memberReply.daemons?.[0].host_telemetry).not.toHaveProperty("mem_gb");
|
|
219
|
+
expect(memberReply.daemons?.[0].host_telemetry).not.toHaveProperty("ip_internal");
|
|
220
|
+
|
|
221
|
+
const adminHandler = buildToolHandler(userAdmin);
|
|
222
|
+
const adminReply = await callList(adminHandler, { network_id: NET_ALPHA });
|
|
223
|
+
expect(adminReply.daemons?.[0].host_telemetry.cpu_cores).toBe(8);
|
|
224
|
+
expect(adminReply.daemons?.[0].host_telemetry.mem_gb).toBe(16);
|
|
225
|
+
expect(adminReply.daemons?.[0].host_telemetry.ip_internal).toBe("10.0.0.5");
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
test("revoked: DELETEd token row (revokeToken path) excludes daemon", async () => {
|
|
229
|
+
const userA = "u_lhs_alice";
|
|
230
|
+
seedUser(userA);
|
|
231
|
+
seedNetwork(NET_ALPHA);
|
|
232
|
+
seedMembership(userA, NET_ALPHA, "admin");
|
|
233
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "alive-daemon" });
|
|
234
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "deleted-token-daemon", tokenDeleted: true });
|
|
235
|
+
|
|
236
|
+
const handler = buildToolHandler(userA);
|
|
237
|
+
const reply = await callList(handler, { network_id: NET_ALPHA });
|
|
238
|
+
const aliases = (reply.daemons ?? []).map(d => d.alias).sort();
|
|
239
|
+
expect(aliases).toContain("alive-daemon");
|
|
240
|
+
expect(aliases).not.toContain("deleted-token-daemon");
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
test("revoked: token with revoked_at SET also excludes daemon", async () => {
|
|
244
|
+
const userA = "u_lhs_alice";
|
|
245
|
+
seedUser(userA);
|
|
246
|
+
seedNetwork(NET_ALPHA);
|
|
247
|
+
seedMembership(userA, NET_ALPHA, "admin");
|
|
248
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "alive-daemon" });
|
|
249
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "revoked-at-daemon", tokenRevokedAt: true });
|
|
250
|
+
|
|
251
|
+
const handler = buildToolHandler(userA);
|
|
252
|
+
const reply = await callList(handler, { network_id: NET_ALPHA });
|
|
253
|
+
const aliases = (reply.daemons ?? []).map(d => d.alias).sort();
|
|
254
|
+
expect(aliases).toContain("alive-daemon");
|
|
255
|
+
expect(aliases).not.toContain("revoked-at-daemon");
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
test("role filter: regular member nodes (role=member) excluded after extraction", async () => {
|
|
259
|
+
const userA = "u_lhs_alice";
|
|
260
|
+
seedUser(userA);
|
|
261
|
+
seedNetwork(NET_ALPHA);
|
|
262
|
+
seedMembership(userA, NET_ALPHA, "admin");
|
|
263
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "real-daemon", role: "host_supervisor" });
|
|
264
|
+
seedDaemon({ network_id: NET_ALPHA, alias: "regular-node", role: "member" });
|
|
265
|
+
|
|
266
|
+
const handler = buildToolHandler(userA);
|
|
267
|
+
const reply = await callList(handler, { network_id: NET_ALPHA });
|
|
268
|
+
const aliases = (reply.daemons ?? []).map(d => d.alias).sort();
|
|
269
|
+
expect(aliases).toEqual(["real-daemon"]);
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
test("self-declare: runtimes_supported + allowed_secret_keys surface from columns", async () => {
|
|
273
|
+
const userA = "u_lhs_alice";
|
|
274
|
+
seedUser(userA);
|
|
275
|
+
seedNetwork(NET_ALPHA);
|
|
276
|
+
seedMembership(userA, NET_ALPHA, "admin");
|
|
277
|
+
seedDaemon({
|
|
278
|
+
network_id: NET_ALPHA, alias: "rich-daemon",
|
|
279
|
+
runtimes: ["claude-agent-sdk", "codex-sdk", "grok-build-acp"],
|
|
280
|
+
secrets: ["ANTHROPIC_API_KEY", "OPENAI_API_KEY"],
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
const handler = buildToolHandler(userA);
|
|
284
|
+
const reply = await callList(handler, { network_id: NET_ALPHA });
|
|
285
|
+
const d = reply.daemons?.[0];
|
|
286
|
+
expect(d.runtimes_supported).toEqual(["claude-agent-sdk", "codex-sdk", "grok-build-acp"]);
|
|
287
|
+
expect(d.allowed_secret_keys).toEqual(["ANTHROPIC_API_KEY", "OPENAI_API_KEY"]);
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
test("pre-PR2 daemon (NULL columns) extracts to empty arrays back-compat", async () => {
|
|
291
|
+
const userA = "u_lhs_alice";
|
|
292
|
+
seedUser(userA);
|
|
293
|
+
seedNetwork(NET_ALPHA);
|
|
294
|
+
seedMembership(userA, NET_ALPHA, "admin");
|
|
295
|
+
db.run(
|
|
296
|
+
`INSERT INTO nodes (node_id, node_name, alias, network_id, config_snapshot, runtimes_supported, allowed_secret_keys, created_at, updated_at)
|
|
297
|
+
VALUES (?1, 'legacy', 'legacy', ?2, ?3, NULL, NULL, datetime('now'), datetime('now'))`,
|
|
298
|
+
["node_legacy_alpha", NET_ALPHA, JSON.stringify({ role: "host_supervisor" })],
|
|
299
|
+
);
|
|
300
|
+
// Seed active token so the EXISTS guard lets it through
|
|
301
|
+
db.run(
|
|
302
|
+
`INSERT INTO api_tokens (token_id, user_id, network_id, scope, name, token_hash)
|
|
303
|
+
VALUES ('tok_legacy', 'u_seed_legacy', ?1, 'network', 'node:legacy', 'hash_legacy')`,
|
|
304
|
+
[NET_ALPHA],
|
|
305
|
+
);
|
|
306
|
+
|
|
307
|
+
const handler = buildToolHandler(userA);
|
|
308
|
+
const reply = await callList(handler, { network_id: NET_ALPHA });
|
|
309
|
+
const d = reply.daemons?.find(d => d.alias === "legacy");
|
|
310
|
+
expect(d).toBeTruthy();
|
|
311
|
+
expect(d.runtimes_supported).toEqual([]);
|
|
312
|
+
expect(d.allowed_secret_keys).toEqual([]);
|
|
313
|
+
});
|
|
314
|
+
});
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// #476(#469 MCP 审计的最后一项)—— Hub MCP 面的上下文成本。
|
|
2
|
+
//
|
|
3
|
+
// 钉住:
|
|
4
|
+
// 1. tools/list 的总字节有上限(TOOLS_LIST_MAX_BYTES):描述 / 参数说明不能悄悄长回去。每个工具也有上限,
|
|
5
|
+
// 单条工具描述有上限。要加新工具 / 新说明,改这里的数字 —— 改的时候就会被看见。
|
|
6
|
+
// 2. requirements_events 不带 requirement_id(全网动态)默认 50 条、从新到旧、next_cursor 翻更早的;
|
|
7
|
+
// 带 requirement_id 的单卡调用不变(默认 200);REST /api/requirements/events 不变(默认 200,App 用它)。
|
|
8
|
+
// 3. requirements_events 参数严格:不认识的参数 → -32602,列出能用的参数。
|
|
9
|
+
//
|
|
10
|
+
// 跑法:cd server && COMMHUB_DB=/tmp/x.db bun test src/mcp-context-cost-http.test.ts
|
|
11
|
+
// PG:COMMHUB_TEST_PG_URL=… COMMHUB_PG_EXPERIMENTAL=1(tests/test2123-hub-postgres-ladder 里注册)
|
|
12
|
+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
13
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
14
|
+
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
|
15
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
16
|
+
import { register } from "./auth.js";
|
|
17
|
+
import { registerTools } from "./tools.js";
|
|
18
|
+
|
|
19
|
+
const activeDbPath = process.env.COMMHUB_DB ?? (process.env.COMMHUB_TEST_PG_URL ? "postgres" : undefined);
|
|
20
|
+
if (!activeDbPath) throw new Error("mcp-context-cost requires COMMHUB_DB (or COMMHUB_TEST_PG_URL) before module import");
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* tools/list 整份 JSON 的字节上限。#476 之前(main,含 #475)74 个工具 76,824 B;修剪后 71,399 B。
|
|
24
|
+
* #478 起 tools/list 按调用者给:这里的调用者是用户令牌,看到 56 个工具 54,780 B(不含节点 / 协议工具)。
|
|
25
|
+
* 上限跟着收到用户这一档(~1.7 KB 余量);节点 / 全部工具的上限在 tool-audience-http.test.ts。
|
|
26
|
+
* 加工具或加说明超过它,就在这里改数字并在 PR 里说为什么。
|
|
27
|
+
*/
|
|
28
|
+
const TOOLS_LIST_MAX_BYTES = 56_500;
|
|
29
|
+
/** 单个工具(名字 + 描述 + 输入 schema)的上限;最大的是 report_status(节点心跳,~8.4 KB 的遥测结构)。 */
|
|
30
|
+
const TOOL_MAX_BYTES = 9_000;
|
|
31
|
+
/** 单条工具描述的上限(说明写进参数的 describe,或者拆短)。 */
|
|
32
|
+
const DESCRIPTION_MAX_BYTES = 1_000;
|
|
33
|
+
const NETWORK_EVENTS = 80;
|
|
34
|
+
|
|
35
|
+
let server: any;
|
|
36
|
+
let base = "";
|
|
37
|
+
let token = "", netId = "";
|
|
38
|
+
let close: () => Promise<void>;
|
|
39
|
+
let client: Client;
|
|
40
|
+
const call = async (name: string, args: Record<string, unknown>) => {
|
|
41
|
+
const r: any = await client.callTool({ name, arguments: args });
|
|
42
|
+
const text = String(r.content?.[0]?.text ?? "");
|
|
43
|
+
return r.isError ? { mcpError: true, text } : { ...JSON.parse(text), _bytes: Buffer.byteLength(text, "utf8") };
|
|
44
|
+
};
|
|
45
|
+
let busyId = "";
|
|
46
|
+
|
|
47
|
+
beforeAll(async () => {
|
|
48
|
+
const u = register(`ctx_${Date.now()}`, "CtxCost123!", undefined, "seed");
|
|
49
|
+
token = u.token!; netId = u.network_id!;
|
|
50
|
+
const s = new McpServer({ name: "ctx", version: "1" });
|
|
51
|
+
registerTools(s, undefined, null, u.user!.user_id, u.user!.username, false, "tok_user");
|
|
52
|
+
client = new Client({ name: "ctx-client", version: "1" });
|
|
53
|
+
const [ct, st] = InMemoryTransport.createLinkedPair();
|
|
54
|
+
await s.connect(st);
|
|
55
|
+
await client.connect(ct);
|
|
56
|
+
close = async () => { await client.close(); await s.close(); };
|
|
57
|
+
const mod: any = await import("./server.js");
|
|
58
|
+
server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
59
|
+
base = `http://127.0.0.1:${server.port}`;
|
|
60
|
+
// 一张卡上 60 条评论(单卡调用要能拿到 > 50 条),再加 20 张卡各一条
|
|
61
|
+
const busy = await call("requirements_create", { network_id: netId, name: "busy task" });
|
|
62
|
+
busyId = busy.requirement.id;
|
|
63
|
+
for (let i = 0; i < 60; i++) expect((await call("requirements_comment", { network_id: netId, id: busyId, text: `进展 ${i}:这一步完成了` })).ok).toBe(true);
|
|
64
|
+
for (let i = 0; i < NETWORK_EVENTS - 60; i++) {
|
|
65
|
+
const r = await call("requirements_create", { network_id: netId, name: `task ${i}` });
|
|
66
|
+
await call("requirements_comment", { network_id: netId, id: r.requirement.id, text: "已开始" });
|
|
67
|
+
}
|
|
68
|
+
}, 120_000);
|
|
69
|
+
afterAll(async () => { await close?.(); server?.stop?.(true); });
|
|
70
|
+
|
|
71
|
+
describe("#476 tools/list size", () => {
|
|
72
|
+
test("total, per tool and per description stay under their ceilings", async () => {
|
|
73
|
+
const { tools } = await client.listTools();
|
|
74
|
+
const total = Buffer.byteLength(JSON.stringify({ tools }), "utf8");
|
|
75
|
+
const sizes = tools.map((t: any) => ({ name: t.name, all: Buffer.byteLength(JSON.stringify(t)), desc: Buffer.byteLength(t.description ?? "") }));
|
|
76
|
+
sizes.sort((a, b) => b.all - a.all);
|
|
77
|
+
console.log(`tools/list: ${tools.length} tools, ${total} B; largest ${sizes.slice(0, 3).map(x => `${x.name}=${x.all}`).join(", ")}`);
|
|
78
|
+
expect(total).toBeLessThanOrEqual(TOOLS_LIST_MAX_BYTES);
|
|
79
|
+
for (const x of sizes) {
|
|
80
|
+
expect(x.all, x.name).toBeLessThanOrEqual(TOOL_MAX_BYTES);
|
|
81
|
+
expect(x.desc, x.name).toBeLessThanOrEqual(DESCRIPTION_MAX_BYTES);
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
describe("#476 requirements_events defaults", () => {
|
|
87
|
+
test("network-wide: 50 newest by default, next_cursor pages older events", async () => {
|
|
88
|
+
const p1 = await call("requirements_events", { network_id: netId });
|
|
89
|
+
expect(p1.events.length).toBe(50);
|
|
90
|
+
expect(typeof p1.next_cursor).toBe("string");
|
|
91
|
+
const times = p1.events.map((e: any) => e.at ?? e.created_at);
|
|
92
|
+
expect([...times].sort().reverse()).toEqual(times);
|
|
93
|
+
const p2 = await call("requirements_events", { network_id: netId, cursor: p1.next_cursor });
|
|
94
|
+
const ids = new Set([...p1.events, ...p2.events].map((e: any) => e.id));
|
|
95
|
+
expect(ids.size).toBe(p1.events.length + p2.events.length);
|
|
96
|
+
console.log(`network events page of 50: ${p1._bytes} B`);
|
|
97
|
+
expect(p1._bytes).toBeLessThan(25_000);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test("an explicit limit still wins; one task's timeline keeps its old default (200)", async () => {
|
|
101
|
+
expect((await call("requirements_events", { network_id: netId, limit: 70 })).events.length).toBe(70);
|
|
102
|
+
const one = await call("requirements_events", { network_id: netId, requirement_id: busyId });
|
|
103
|
+
expect(one.events.filter((e: any) => e.kind === "comment").length).toBe(60);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test("REST GET /api/requirements/events is unchanged (default 200)", async () => {
|
|
107
|
+
const res = await fetch(`${base}/api/requirements/events?network_id=${netId}`, { headers: { Authorization: `Bearer ${token}` } });
|
|
108
|
+
const body = await res.json() as any;
|
|
109
|
+
expect(res.status).toBe(200);
|
|
110
|
+
expect(body.events.length).toBeGreaterThan(50);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("unknown parameters → -32602 listing the valid ones", async () => {
|
|
114
|
+
const r = await call("requirements_events", { network_id: netId, task_id: busyId });
|
|
115
|
+
expect(r.mcpError).toBe(true);
|
|
116
|
+
expect(r.text).toContain("-32602");
|
|
117
|
+
expect(r.text).toContain("unknown parameter(s): task_id; valid parameters: network_id, requirement_id, since, limit, cursor");
|
|
118
|
+
});
|
|
119
|
+
});
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// MCP projects_create / projects_update / requirements_events(app 任务页审计 2026-10-02 M3:Agent 能做人能做的)。
|
|
2
|
+
// HTTP 集成测试(真实 Bun.serve,私有端口,临时库)。三个工具都走 app 用的同一套 REST 处理(handleRequirementsRequest),
|
|
3
|
+
// 所以这里不另抄一份权限规则:对每类调用者(网络 owner、全部任务成员、仅相关任务成员、viewer、节点令牌)都同时调
|
|
4
|
+
// MCP 和 REST,断言状态码 / 结果逐项一致。再钉住正向行为(建 / 改名 / 归档 / 取消归档、读流水、"#N")和工具出现在 tools/list 里。
|
|
5
|
+
|
|
6
|
+
import { describe, expect, test, beforeAll, afterAll } from "bun:test";
|
|
7
|
+
import { mkdtempSync, rmSync } from "fs";
|
|
8
|
+
import { join } from "path";
|
|
9
|
+
import { tmpdir } from "os";
|
|
10
|
+
import { register, createNetworkTokenForNode } from "./auth.js";
|
|
11
|
+
import { db } from "./db.js";
|
|
12
|
+
|
|
13
|
+
const DIR = mkdtempSync(join(tmpdir(), "anet-mcp-projects-events-"));
|
|
14
|
+
let BASE = "";
|
|
15
|
+
let hub: any = null;
|
|
16
|
+
const PW = "McpProjectsEventsPassw0rd!x";
|
|
17
|
+
let NET = "";
|
|
18
|
+
const U: Record<string, { token: string; id: string }> = {};
|
|
19
|
+
|
|
20
|
+
async function rest(token: string, method: string, path: string, body?: unknown) {
|
|
21
|
+
const res = await fetch(`${BASE}${path}`, { method, headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
22
|
+
const text = await res.text();
|
|
23
|
+
let json: any = null;
|
|
24
|
+
try { json = JSON.parse(text); } catch {}
|
|
25
|
+
return { status: res.status, body: json };
|
|
26
|
+
}
|
|
27
|
+
async function rpc(token: string, method: string, params?: unknown): Promise<any> {
|
|
28
|
+
const res = await fetch(`${BASE}/mcp`, {
|
|
29
|
+
method: "POST",
|
|
30
|
+
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-03-26" },
|
|
31
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, ...(params === undefined ? {} : { params }) }),
|
|
32
|
+
});
|
|
33
|
+
const raw = await res.text();
|
|
34
|
+
const lines = raw.split("\n").filter(x => x.startsWith("data:"));
|
|
35
|
+
return lines.length ? JSON.parse(lines.at(-1)!.slice(5).trim()) : JSON.parse(raw);
|
|
36
|
+
}
|
|
37
|
+
async function mcp(token: string, name: string, args: Record<string, unknown>): Promise<any> {
|
|
38
|
+
const out = await rpc(token, "tools/call", { name, arguments: args });
|
|
39
|
+
return JSON.parse(out.result.content[0].text);
|
|
40
|
+
}
|
|
41
|
+
// MCP error bodies from the REST handler carry its status (requirementsCall). Anything else that isn't ok (e.g. a tool-level
|
|
42
|
+
// gate) is NOT a success — a body without `status` must never be read as the 2xx (that hid a gate in the first draft).
|
|
43
|
+
const mcpStatus = (r: any, okStatus: number) => (r?.ok === true || (r && r.ok === undefined && (r.project || r.events)) ? okStatus : typeof r?.status === "number" ? r.status : -1);
|
|
44
|
+
|
|
45
|
+
beforeAll(async () => {
|
|
46
|
+
process.env.COMMHUB_DB ||= join(DIR, "hub.db");
|
|
47
|
+
process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
|
|
48
|
+
process.env.HOST = "127.0.0.1";
|
|
49
|
+
const a = register(`mpe_owner_${Date.now()}`, PW, undefined, "Owner");
|
|
50
|
+
expect(a.ok).toBe(true);
|
|
51
|
+
U.owner = { token: a.token!, id: a.user!.user_id };
|
|
52
|
+
NET = a.network_id!;
|
|
53
|
+
db.run("UPDATE users SET role = 'admin' WHERE user_id = ?1", [U.owner.id]);
|
|
54
|
+
const mod: any = await import("./server.js");
|
|
55
|
+
hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
56
|
+
BASE = `http://127.0.0.1:${hub.port}`;
|
|
57
|
+
const mk = async (username: string, role: string) => {
|
|
58
|
+
expect((await rest(U.owner.token, "POST", "/api/admin/users", { username, password: PW, network_id: NET, role })).status).toBe(200);
|
|
59
|
+
const login = await rest("", "POST", "/api/auth/login", { username, password: PW });
|
|
60
|
+
expect(login.status).toBe(200);
|
|
61
|
+
return { token: login.body.token as string, id: login.body.user.user_id as string };
|
|
62
|
+
};
|
|
63
|
+
const stamp = Date.now();
|
|
64
|
+
U.member = await mk(`mpe_member_${stamp}`, "member");
|
|
65
|
+
U.scoped = await mk(`mpe_scoped_${stamp}`, "member");
|
|
66
|
+
U.viewer = await mk(`mpe_viewer_${stamp}`, "viewer");
|
|
67
|
+
db.run("UPDATE network_members SET task_access = 'all' WHERE network_id = ?1 AND user_id = ?2", [NET, U.member.id]);
|
|
68
|
+
expect((await rest(U.owner.token, "PUT", `/api/networks/${NET}/members/${U.scoped.id}/task-grants`, { task_access: "scoped", project_grants: [] })).status).toBe(200);
|
|
69
|
+
const node = createNetworkTokenForNode(U.owner.id, NET, "mpe-node", "node_mpe");
|
|
70
|
+
U.node = { token: node.token!, id: "node_mpe" };
|
|
71
|
+
}, 30_000);
|
|
72
|
+
|
|
73
|
+
afterAll(() => {
|
|
74
|
+
try { hub?.stop?.(true); } catch {}
|
|
75
|
+
try { rmSync(DIR, { recursive: true, force: true }); } catch {}
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
describe("discoverable", () => {
|
|
79
|
+
test("tools/list carries the three tools with descriptions", async () => {
|
|
80
|
+
const list = await rpc(U.owner.token, "tools/list");
|
|
81
|
+
const byName = new Map((list.result.tools as any[]).map(t => [t.name, t]));
|
|
82
|
+
for (const n of ["projects_create", "projects_update", "requirements_events"]) {
|
|
83
|
+
expect(byName.has(n)).toBe(true);
|
|
84
|
+
expect(String(byName.get(n).description).length).toBeGreaterThan(40);
|
|
85
|
+
}
|
|
86
|
+
expect(String(byName.get("projects_list").description)).toContain("projects_create");
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
describe("projects_create / projects_update", () => {
|
|
91
|
+
test("owner: create, rename, recolour, archive, unarchive — same rows the app sees", async () => {
|
|
92
|
+
const created = await mcp(U.owner.token, "projects_create", { network_id: NET, name: "mpe-项目甲" });
|
|
93
|
+
expect(created.ok).toBe(true);
|
|
94
|
+
const id = created.project.id as string;
|
|
95
|
+
expect(created.project.name).toBe("mpe-项目甲");
|
|
96
|
+
const renamed = await mcp(U.owner.token, "projects_update", { network_id: NET, id, name: "mpe-项目乙", color: "#16a34a" });
|
|
97
|
+
expect(renamed.project.name).toBe("mpe-项目乙");
|
|
98
|
+
expect(renamed.project.color).toBe("#16a34a");
|
|
99
|
+
expect((await mcp(U.owner.token, "projects_update", { network_id: NET, id, archived: true })).project.archived).toBe(true);
|
|
100
|
+
const seen = await rest(U.owner.token, "GET", `/api/requirements/projects?network_id=${NET}`);
|
|
101
|
+
expect(seen.body.projects.find((p: any) => p.id === id).archived).toBe(true);
|
|
102
|
+
expect((await mcp(U.owner.token, "projects_update", { network_id: NET, id, archived: false })).project.archived).toBe(false);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
test("validation comes from the REST handler: duplicate name 409, unknown id 404", async () => {
|
|
106
|
+
await mcp(U.owner.token, "projects_create", { network_id: NET, name: "mpe-重名" });
|
|
107
|
+
const dup = await mcp(U.owner.token, "projects_create", { network_id: NET, name: "mpe-重名" });
|
|
108
|
+
expect(dup.ok).toBe(false);
|
|
109
|
+
expect(dup.status).toBe(409);
|
|
110
|
+
const missing = await mcp(U.owner.token, "projects_update", { network_id: NET, id: "proj_nobody", name: "x" });
|
|
111
|
+
expect(missing.status).toBe(404);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("permission parity with the app's REST path, for every kind of caller", async () => {
|
|
115
|
+
const results: Record<string, { mcp: number; rest: number }> = {};
|
|
116
|
+
for (const who of ["owner", "member", "scoped", "viewer", "node"]) {
|
|
117
|
+
const name = `mpe-parity-${who}`;
|
|
118
|
+
const viaMcp = await mcp(U[who].token, "projects_create", { network_id: NET, name: `${name}-mcp` });
|
|
119
|
+
const viaRest = await rest(U[who].token, "POST", `/api/requirements/projects?network_id=${NET}`, { name: `${name}-rest` });
|
|
120
|
+
results[who] = { mcp: mcpStatus(viaMcp, 201), rest: viaRest.status };
|
|
121
|
+
}
|
|
122
|
+
for (const r of Object.values(results)) expect(r.mcp).toBe(r.rest);
|
|
123
|
+
// the rule itself (RFC-038 §9): task-scoped members and viewers can't manage projects; the others can
|
|
124
|
+
expect(results.owner.rest).toBe(201);
|
|
125
|
+
expect(results.member.rest).toBe(201);
|
|
126
|
+
expect(results.scoped.rest).toBe(403);
|
|
127
|
+
expect(results.viewer.rest).toBe(403);
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
describe("requirements_events", () => {
|
|
132
|
+
test("one task's timeline by id and by #N, same rows as GET /api/requirements/events", async () => {
|
|
133
|
+
const card = await rest(U.owner.token, "POST", "/api/requirements", { network_id: NET, name: "mpe-流水示例" });
|
|
134
|
+
expect(card.status).toBe(201);
|
|
135
|
+
const id = card.body.requirement.id as string, seq = card.body.requirement.seq as number;
|
|
136
|
+
expect((await rest(U.owner.token, "PATCH", `/api/requirements/${id}?network_id=${NET}`, { priority: "high" })).status).toBe(200);
|
|
137
|
+
const viaMcp = await mcp(U.owner.token, "requirements_events", { network_id: NET, requirement_id: id });
|
|
138
|
+
const viaRest = await rest(U.owner.token, "GET", `/api/requirements/events?network_id=${NET}&requirement_id=${id}`);
|
|
139
|
+
expect(viaMcp.ok).toBe(true);
|
|
140
|
+
expect(viaMcp.events.length).toBeGreaterThan(0);
|
|
141
|
+
expect(viaMcp.events.map((e: any) => e.id)).toEqual(viaRest.body.events.map((e: any) => e.id));
|
|
142
|
+
expect(viaMcp.events.every((e: any) => e.requirement_id === id)).toBe(true);
|
|
143
|
+
const bySeq = await mcp(U.owner.token, "requirements_events", { network_id: NET, requirement_id: `#${seq}` });
|
|
144
|
+
expect(bySeq.events.map((e: any) => e.id)).toEqual(viaMcp.events.map((e: any) => e.id));
|
|
145
|
+
// paging / bad input come from the REST handler too
|
|
146
|
+
expect((await mcp(U.owner.token, "requirements_events", { network_id: NET, since: "not-a-date" })).status).toBe(400);
|
|
147
|
+
expect((await mcp(U.owner.token, "requirements_events", { network_id: NET, requirement_id: "#999999" })).status).toBe(404);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test("visibility parity: a task-scoped member doesn't get events for a task they can't see", async () => {
|
|
151
|
+
const hidden = await rest(U.owner.token, "POST", "/api/requirements", { network_id: NET, name: "mpe-看不见的" });
|
|
152
|
+
const id = hidden.body.requirement.id as string;
|
|
153
|
+
await rest(U.owner.token, "PATCH", `/api/requirements/${id}?network_id=${NET}`, { priority: "low" });
|
|
154
|
+
for (const who of ["scoped", "member", "node"]) {
|
|
155
|
+
const viaMcp = await mcp(U[who].token, "requirements_events", { network_id: NET, requirement_id: id });
|
|
156
|
+
const viaRest = await rest(U[who].token, "GET", `/api/requirements/events?network_id=${NET}&requirement_id=${id}`);
|
|
157
|
+
expect((viaMcp.events ?? []).map((e: any) => e.id)).toEqual((viaRest.body?.events ?? []).map((e: any) => e.id));
|
|
158
|
+
}
|
|
159
|
+
expect((await mcp(U.scoped.token, "requirements_events", { network_id: NET, requirement_id: id })).events ?? []).toHaveLength(0);
|
|
160
|
+
expect((await mcp(U.member.token, "requirements_events", { network_id: NET, requirement_id: id })).events.length).toBeGreaterThan(0);
|
|
161
|
+
});
|
|
162
|
+
});
|