@sleep2agi/commhub-server 0.9.0-preview.274 → 0.9.0-preview.276
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/build-info.json +2 -2
- package/package.json +1 -1
- package/src/agent-access-batch.test.ts +7 -2
- package/src/agent-acl-slice3-http.test.ts +4 -1
- package/src/agent-groups-perf.test.ts +6 -1
- package/src/anet-variant-real-daemon-http.test.ts +184 -0
- package/src/build-commit-report-http.test.ts +90 -0
- package/src/config-apply-sec1.test.ts +37 -0
- package/src/config-apply-validate.ts +7 -3
- package/src/contracts/session-project-create.ts +14 -0
- package/src/contracts/session-source-delivery.ts +16 -0
- package/src/contracts/session-source-directory.ts +54 -0
- package/src/contracts/session-source-evidence.ts +72 -0
- package/src/contracts/session-source-execution.ts +24 -0
- package/src/contracts/session-source-transport.ts +18 -0
- package/src/create-node-tool-schema.test.ts +10 -0
- package/src/db.ts +35 -0
- package/src/node-permissions.ts +1 -1
- package/src/node-session-control-http.test.ts +90 -2
- package/src/node-session-control.ts +89 -31
- package/src/opencode-v2-catalog.test.ts +14 -0
- package/src/opencode-v2-catalog.ts +1 -0
- package/src/package-self-contained.test.ts +32 -0
- package/src/report-status-host-schema.test.ts +37 -0
- package/src/rules-file-transport.test.ts +9 -0
- package/src/server.ts +47 -4
- package/src/session-fork-store.test.ts +43 -0
- package/src/session-fork-store.ts +51 -0
- package/src/session-project-attach-migration.test.ts +22 -0
- package/src/session-project-attach-native.test.ts +121 -0
- package/src/session-project-create-http.test.ts +407 -0
- package/src/session-project-create-native.test.ts +290 -0
- package/src/session-project-create.ts +159 -0
- package/src/session-source-admission-store.ts +58 -0
- package/src/session-source-create.test.ts +155 -0
- package/src/session-source-create.ts +97 -0
- package/src/session-source-delivery.ts +109 -0
- package/src/session-source-directory-http.test.ts +192 -0
- package/src/session-source-evidence.test.ts +890 -0
- package/src/session-source-evidence.ts +191 -0
- package/src/session-source-execution.ts +87 -0
- package/src/session-source-grant.test.ts +117 -0
- package/src/session-source-grant.ts +78 -0
- package/src/session-source-issuer.test.ts +247 -0
- package/src/session-source-issuer.ts +158 -0
- package/src/session-source-transport.ts +368 -0
- package/src/task-not-found-error-domain.test.ts +4 -1
- package/src/token-usage-http.test.ts +10 -0
- package/src/tool-audience-http.test.ts +18 -0
- package/src/tool-audience.ts +1 -1
- package/src/tools.ts +154 -51
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { isSourceReadEvidence, type SourceReadEvidence } from "./session-source-evidence";
|
|
2
|
+
export type SourceExecutionTask = {
|
|
3
|
+
execution_id: string; admission_request_id: string; evidence: SourceReadEvidence;
|
|
4
|
+
authorized_until: number; owner_policy: "retain_existing_bridge_only";
|
|
5
|
+
};
|
|
6
|
+
export type SourceExecutionResult = {
|
|
7
|
+
execution_id: string; admission_request_id: string;
|
|
8
|
+
status: "session_ready" | "refused" | "unknown";
|
|
9
|
+
session_id?: string; bridge: "not_created";
|
|
10
|
+
};
|
|
11
|
+
const object = (v: unknown): v is Record<string, any> => !!v && typeof v === "object" && !Array.isArray(v);
|
|
12
|
+
export function isSourceExecutionTask(v: unknown): v is SourceExecutionTask {
|
|
13
|
+
return object(v) && Object.keys(v).length === 5 && typeof v.execution_id === "string" && /^srcx_[a-f0-9-]{36}$/.test(v.execution_id)
|
|
14
|
+
&& typeof v.admission_request_id === "string" && /^cr_[A-Za-z0-9_-]{1,190}$/.test(v.admission_request_id)
|
|
15
|
+
&& isSourceReadEvidence(v.evidence) && v.owner_policy === "retain_existing_bridge_only"
|
|
16
|
+
&& Number.isSafeInteger(v.authorized_until) && v.authorized_until > 0 && v.authorized_until <= v.evidence.request.expires_at;
|
|
17
|
+
}
|
|
18
|
+
export function isSourceExecutionResult(v: unknown, task: SourceExecutionTask): v is SourceExecutionResult {
|
|
19
|
+
if (!object(v) || Object.keys(v).some(k => !["execution_id", "admission_request_id", "status", "session_id", "bridge"].includes(k))
|
|
20
|
+
|| v.execution_id !== task.execution_id || v.admission_request_id !== task.admission_request_id || v.bridge !== "not_created") return false;
|
|
21
|
+
if (v.status === "unknown" || v.status === "refused") return v.session_id === undefined;
|
|
22
|
+
return v.status === "session_ready" && typeof v.session_id === "string" && /^ses_[A-Za-z0-9]+$/.test(v.session_id)
|
|
23
|
+
&& (task.evidence.request.mode === "attach_existing" ? v.session_id === task.evidence.request.session_id : v.session_id !== task.evidence.request.session_id);
|
|
24
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { SourceReadChallenge, SourceLeaseRecheck } from "./session-source-evidence";
|
|
2
|
+
import type { SourceExecutionTask } from "./session-source-execution";
|
|
3
|
+
import type { SourceNodeDelivery } from "./session-source-delivery";
|
|
4
|
+
export const SOURCE_FORK_ROOT = "/api/node-session-control/source";
|
|
5
|
+
export const SOURCE_FORK_CAPABILITY = "source-fork-transport-v1-opencode-2.0.22";
|
|
6
|
+
export type SourceForkSelection = { network_id: string; source_node_id: string; session_id: string;
|
|
7
|
+
mode: "fork_independent"; child_name: string; intent_id: string };
|
|
8
|
+
export type SourceForkTask = { request_id: string; intent_id: string; network_id: string; source_node_id: string;
|
|
9
|
+
daemon_node_id: string } & (
|
|
10
|
+
{ phase: "evidence"; task: SourceReadChallenge } | { phase: "recheck"; task: SourceLeaseRecheck }
|
|
11
|
+
| { phase: "execute"; task: SourceExecutionTask } | { phase: "deliver"; task: SourceNodeDelivery });
|
|
12
|
+
export type SourceForkStatus = "evidence_pending" | "evidence_claimed" | "recheck_pending" | "recheck_claimed"
|
|
13
|
+
| "execute_pending" | "execute_claimed" | "deliver_pending" | "deliver_claimed"
|
|
14
|
+
| "registration_confirmed" | "refused" | "unknown_rotation_required";
|
|
15
|
+
export type SourceForkReceipt = SourceForkSelection & { ok: true; request_id: string; daemon_node_id: string;
|
|
16
|
+
status: SourceForkStatus; expires_at: number; child_node_id?: string; child_session_id?: string;
|
|
17
|
+
native_acceptance: "not_verified"; dispatch_scope: "gated_preview" };
|
|
18
|
+
export const isSourceForkRequestId = (v: unknown): v is string => typeof v === "string" && /^srcf_[a-f0-9-]{36}$/.test(v);
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { describe, expect, test } from "bun:test";
|
|
2
2
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
3
|
import { registerTools } from "./tools.js";
|
|
4
|
+
import { z } from "zod";
|
|
4
5
|
|
|
5
6
|
type ToolHandler = (args: any) => Promise<any> | any;
|
|
6
7
|
|
|
@@ -17,6 +18,15 @@ function captureSchemas(): Record<string, Record<string, any>> {
|
|
|
17
18
|
}
|
|
18
19
|
|
|
19
20
|
describe("create_node MCP schema", () => {
|
|
21
|
+
test("source_ref is rejected instead of stripped into ordinary creation", () => {
|
|
22
|
+
const schema = z.object(captureSchemas().create_node);
|
|
23
|
+
const base = { daemon_node_id: "daemon_fixture", node_spec: { name: "source-node", runtime: "opencode-cli" } };
|
|
24
|
+
for (const source_ref of ["src_fixture", null, "", {}]) {
|
|
25
|
+
expect(schema.safeParse({ ...base, source_ref }).success).toBe(false);
|
|
26
|
+
expect(schema.safeParse({ ...base, node_spec: { ...base.node_spec, source_ref } }).success).toBe(false);
|
|
27
|
+
}
|
|
28
|
+
expect(schema.safeParse(base).success).toBe(true);
|
|
29
|
+
});
|
|
20
30
|
test("#829 rejects misplaced V2 controls instead of stripping them", () => {
|
|
21
31
|
const nodeSpec = captureSchemas().create_node.node_spec;
|
|
22
32
|
const base = { name: "v2-node", runtime: "opencode-cli" };
|
package/src/db.ts
CHANGED
|
@@ -1,7 +1,31 @@
|
|
|
1
1
|
import { refreshScheduledBackoff } from "./scheduled-backoff.js"; import { scheduledFailureCode } from "./scheduled-failure-code.js";
|
|
2
2
|
import { createAdapter, type DbAdapter } from "./db-adapter"; import { withStatementHook } from "./status-read-cache"; // #431 写 sessions 的语句让 /api/status 缓存失效
|
|
3
|
+
import { sessionSourceGrantSchema } from "./session-source-grant";
|
|
4
|
+
import { sessionSourceAdmissionSchema, sessionSourceExecutionSchema, sessionSourceDeliverySchema, sessionSourceTransportSchema, sessionProjectCreateSchema, migrateProjectOperationJournal } from "./session-source-admission-store";
|
|
5
|
+
import { sessionSourceCreateGuards } from "./session-source-create";
|
|
3
6
|
|
|
4
7
|
export const db: DbAdapter = withStatementHook(createAdapter());
|
|
8
|
+
db.exec(sessionSourceGrantSchema);
|
|
9
|
+
db.exec(sessionSourceAdmissionSchema);
|
|
10
|
+
db.exec(sessionSourceExecutionSchema);
|
|
11
|
+
db.exec(sessionSourceDeliverySchema);
|
|
12
|
+
db.exec(sessionSourceTransportSchema);
|
|
13
|
+
db.exec(sessionProjectCreateSchema);
|
|
14
|
+
migrateProjectOperationJournal(db);
|
|
15
|
+
|
|
16
|
+
// #590 additive journal. Keep intent tombstones: deleting one permits the
|
|
17
|
+
// same user intent to create a second child after an uncertain outcome.
|
|
18
|
+
db.exec(`CREATE TABLE IF NOT EXISTS session_fork_requests (
|
|
19
|
+
request_id TEXT PRIMARY KEY, intent_id TEXT NOT NULL,
|
|
20
|
+
network_id TEXT NOT NULL, node_id TEXT NOT NULL, token_id TEXT NOT NULL,
|
|
21
|
+
requester_token_id TEXT NOT NULL, requester_user_id TEXT NOT NULL,
|
|
22
|
+
session_id TEXT NOT NULL, binding_id TEXT NOT NULL, expires_at INTEGER NOT NULL,
|
|
23
|
+
status TEXT NOT NULL CHECK(status IN ('pending','in_progress','done','failed','unknown','expired')),
|
|
24
|
+
result_session_id TEXT, error TEXT,
|
|
25
|
+
UNIQUE(requester_user_id, network_id, intent_id)
|
|
26
|
+
);
|
|
27
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_session_fork_active_node
|
|
28
|
+
ON session_fork_requests(network_id,node_id) WHERE status IN ('pending','in_progress');`);
|
|
5
29
|
|
|
6
30
|
// Schema
|
|
7
31
|
db.exec(`
|
|
@@ -855,6 +879,17 @@ try {
|
|
|
855
879
|
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
856
880
|
}
|
|
857
881
|
|
|
882
|
+
// #4150/#590 internal source admission. Add after legacy table rebuilds;
|
|
883
|
+
// NULL leaves ordinary creation unchanged. PostgreSQL cannot enable admission.
|
|
884
|
+
try {
|
|
885
|
+
db.exec(`ALTER TABLE node_create_requests ADD COLUMN source_ref TEXT`);
|
|
886
|
+
} catch (e: any) {
|
|
887
|
+
if (!/duplicate column|already exists/i.test(e?.message || "")) throw e;
|
|
888
|
+
}
|
|
889
|
+
if (db.dialect === "sqlite" && db.atomicTransactions === true && db.transactionalFeaturesRefusal === null) {
|
|
890
|
+
db.exec(sessionSourceCreateGuards);
|
|
891
|
+
}
|
|
892
|
+
|
|
858
893
|
// #1493 — 把 user_inbox.network_id 升到 **schema 级 NOT NULL**(belt-and-suspenders,
|
|
859
894
|
// 叠在 send_desktop_message 的代码级三闸之上:canWrite / `!effectiveNetId` return /
|
|
860
895
|
// getUserNetworkRole,tools.ts)。「不产生 network_id=NULL 孤儿」现是代码级保证 + #1492
|
package/src/node-permissions.ts
CHANGED
|
@@ -464,7 +464,7 @@ export const NODE_TOOL_CLASS: Readonly<Record<string, ToolClass>> = {
|
|
|
464
464
|
// 只有人能做
|
|
465
465
|
upsert_network_secret: "human_only", upsert_provider: "human_only", update_provider: "human_only",
|
|
466
466
|
projects_create: "human_only", projects_update: "human_only", review_skill: "human_only",
|
|
467
|
-
read_opencode_catalog: "human_only", get_opencode_catalog: "human_only",
|
|
467
|
+
read_opencode_catalog: "human_only", get_opencode_catalog: "human_only", select_opencode_session_model: "human_only",
|
|
468
468
|
};
|
|
469
469
|
|
|
470
470
|
/**
|
|
@@ -6,6 +6,8 @@ import { join } from "node:path";
|
|
|
6
6
|
const dir = mkdtempSync(join(tmpdir(), "anet-session-control-"));
|
|
7
7
|
process.env.COMMHUB_DB ||= join(dir, "hub.db");
|
|
8
8
|
const root = "/api/node-session-control";
|
|
9
|
+
const previousForkPreview = process.env.COMMHUB_V2_FORK_PREVIEW;
|
|
10
|
+
const previousSourcePreview = process.env.COMMHUB_SOURCE_FORK_PREVIEW;
|
|
9
11
|
let server: any, base: string, db: any, net: string, otherNet: string;
|
|
10
12
|
let owner: any, admin: any, member: any, outsider: any, ntok: any, peer: any;
|
|
11
13
|
let legacyOwner: any, legacyAdmin: any, legacyMember: any, legacyOutsider: any, legacyFull: any, legacyNetwork: any;
|
|
@@ -28,6 +30,8 @@ const ack = (request: string, result: unknown, extra = {}) => api(ntok.token!, `
|
|
|
28
30
|
{ ...binding, status: "done", result, ...extra });
|
|
29
31
|
|
|
30
32
|
beforeAll(async () => {
|
|
33
|
+
process.env.COMMHUB_V2_FORK_PREVIEW = "1";
|
|
34
|
+
process.env.COMMHUB_SOURCE_FORK_PREVIEW = "1";
|
|
31
35
|
({ db } = await import("./db.js"));
|
|
32
36
|
const { register, addNetworkMember, createNetworkTokenForNode, createToken } = await import("./auth.js");
|
|
33
37
|
const stamp = Date.now();
|
|
@@ -65,9 +69,93 @@ beforeEach(async () => {
|
|
|
65
69
|
expect((await registerBridge()).status).toBe(200);
|
|
66
70
|
});
|
|
67
71
|
afterEach(() => setSystemTime());
|
|
68
|
-
afterAll(() => {
|
|
72
|
+
afterAll(() => {
|
|
73
|
+
if (previousSourcePreview === undefined) delete process.env.COMMHUB_SOURCE_FORK_PREVIEW;
|
|
74
|
+
else process.env.COMMHUB_SOURCE_FORK_PREVIEW = previousSourcePreview;
|
|
75
|
+
if (previousForkPreview === undefined) delete process.env.COMMHUB_V2_FORK_PREVIEW;
|
|
76
|
+
else process.env.COMMHUB_V2_FORK_PREVIEW = previousForkPreview;
|
|
77
|
+
server?.stop(true); rmSync(dir, { recursive: true, force: true });
|
|
78
|
+
});
|
|
69
79
|
|
|
70
80
|
describe("#2017 human-to-exact-Bridge HTTP relay", () => {
|
|
81
|
+
test("actual Hub dispatch mounts separate gated source REST without granting human scope to node credentials", async () => {
|
|
82
|
+
expect((await api(owner.token!, `${root}/source/daemon`, {})).status).toBe(403);
|
|
83
|
+
expect((await api(owner.token!, `${root}/source`, { network_id: net, source_node_id: nodeId,
|
|
84
|
+
session_id: "ses_Isolated", mode: "fork_independent", child_name: "child", intent_id: "hub-route", url: "forbidden" })).status).toBe(400);
|
|
85
|
+
expect((await api(ntok.token!, `${root}/source`, { network_id: net, source_node_id: nodeId,
|
|
86
|
+
session_id: "ses_Isolated", mode: "fork_independent", child_name: "child", intent_id: "hub-node" })).status).toBe(400);
|
|
87
|
+
});
|
|
88
|
+
test("fork write entry remains disabled without the explicit preview gate", async () => {
|
|
89
|
+
const { createNodeSessionControlRelay } = await import("./node-session-control");
|
|
90
|
+
delete process.env.COMMHUB_V2_FORK_PREVIEW;
|
|
91
|
+
let relay: ReturnType<typeof createNodeSessionControlRelay>;
|
|
92
|
+
try { relay = createNodeSessionControlRelay(); }
|
|
93
|
+
finally { process.env.COMMHUB_V2_FORK_PREVIEW = "1"; }
|
|
94
|
+
const request = new Request(`http://isolated${root}/bridge`, { method: "POST",
|
|
95
|
+
headers: { authorization: `Bearer ${ntok.token!}`, "content-type": "application/json" },
|
|
96
|
+
body: JSON.stringify({ ...binding, expected: { node_id: nodeId, network_id: net }, fork_supported: true }) });
|
|
97
|
+
const response = (await relay(request, new URL(request.url)))!;
|
|
98
|
+
expect(response.status).toBe(200);
|
|
99
|
+
expect((await response.json() as any).fork_supported).toBe(false);
|
|
100
|
+
const write = new Request(`http://isolated${root}`, { method: "POST",
|
|
101
|
+
headers: { authorization: `Bearer ${owner.token!}`, "content-type": "application/json" },
|
|
102
|
+
body: JSON.stringify({ network_id: net, node_id: nodeId, operation: "fork", expected: binding, intent_id: `fork_intent_${serial}_disabled` }) });
|
|
103
|
+
const refused = (await relay(write, new URL(write.url)))!;
|
|
104
|
+
expect((await refused.json() as any).error).toBe("session_control_unsupported");
|
|
105
|
+
});
|
|
106
|
+
test("fork intent survives another relay and two relays cannot claim it twice", async () => {
|
|
107
|
+
const intent = `fork_intent_${serial}_persistent`;
|
|
108
|
+
expect((await api(ntok.token!, `${root}/bridge`, { ...binding, expected: { node_id: nodeId, network_id: net }, fork_supported: true })).status).toBe(200);
|
|
109
|
+
const made = await enqueue("fork", { intent_id: intent });
|
|
110
|
+
expect(made.status).toBe(200);
|
|
111
|
+
expect(made.body.request_id).toMatch(/^fk_/);
|
|
112
|
+
expect((await enqueue("fork", { intent_id: intent })).body.request_id).toBe(made.body.request_id);
|
|
113
|
+
const { createNodeSessionControlRelay } = await import("./node-session-control");
|
|
114
|
+
const relay = createNodeSessionControlRelay();
|
|
115
|
+
const call = async (token: string, path: string, value?: unknown) => {
|
|
116
|
+
const req = new Request(`http://isolated${path}`, { method: value === undefined ? "GET" : "POST",
|
|
117
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
|
118
|
+
...(value === undefined ? {} : { body: JSON.stringify(value) }) });
|
|
119
|
+
const response = (await relay(req, new URL(req.url)))!;
|
|
120
|
+
return { status: response.status, body: await response.json() as any };
|
|
121
|
+
};
|
|
122
|
+
const recovered = await call(owner.token!, `${root}/intent/${intent}?network_id=${net}`);
|
|
123
|
+
expect(recovered.body).toMatchObject({ request_id: made.body.request_id, status: "pending" });
|
|
124
|
+
expect((await call(outsider.token!, `${root}/intent/${intent}?network_id=${net}`)).status).toBe(404);
|
|
125
|
+
expect((await call(ntok.token!, `${root}/bridge`, { ...binding, expected: { node_id: nodeId, network_id: net }, fork_supported: true })).status).toBe(200);
|
|
126
|
+
expect((await pull()).body.request.request_id).toBe(made.body.request_id);
|
|
127
|
+
expect((await call(ntok.token!, `${root}/pull`, binding)).body.request).toBeNull();
|
|
128
|
+
expect((await ack(made.body.request_id, { session_id: "ses_DurableChild" })).status).toBe(200);
|
|
129
|
+
expect((await call(owner.token!, `${root}/${made.body.request_id}?network_id=${net}`)).body).toMatchObject({ status: "done", result: { session_id: "ses_DurableChild" } });
|
|
130
|
+
expect((await enqueue("fork", { intent_id: intent })).body).toMatchObject({ request_id: made.body.request_id, status: "done" });
|
|
131
|
+
});
|
|
132
|
+
test("fork lost ACK becomes a durable unknown and the same intent cannot replay", async () => {
|
|
133
|
+
const intent = `fork_intent_${serial}_lost_ack`;
|
|
134
|
+
await api(ntok.token!, `${root}/bridge`, { ...binding, expected: { node_id: nodeId, network_id: net }, fork_supported: true });
|
|
135
|
+
const made = await enqueue("fork", { intent_id: intent });
|
|
136
|
+
expect(made.status).toBe(200); expect((await pull()).body.request.request_id).toBe(made.body.request_id);
|
|
137
|
+
setSystemTime(new Date(Date.now() + 16_000));
|
|
138
|
+
expect((await read(made.body.request_id)).body).toMatchObject({ status: "unknown", error: "session_fork_outcome_unknown" });
|
|
139
|
+
expect((await ack(made.body.request_id, { session_id: "ses_LateChild" })).status).toBe(409);
|
|
140
|
+
expect((await enqueue("fork", { intent_id: intent })).body).toMatchObject({ request_id: made.body.request_id, status: "unknown" });
|
|
141
|
+
expect((await pull()).body.request).toBeNull();
|
|
142
|
+
expect((await enqueue("fork", { intent_id: intent, expected: { ...binding, binding_id: "different_binding" } })).status).toBe(409);
|
|
143
|
+
});
|
|
144
|
+
test("fork requires a durable intent and explicit capability negotiation", async () => {
|
|
145
|
+
expect((await enqueue("fork")).status).toBe(400);
|
|
146
|
+
expect((await enqueue("fork", { intent_id: `fork_intent_${serial}_closed` })).body.error).toBe("session_control_unsupported");
|
|
147
|
+
});
|
|
148
|
+
test("fork without exact expected identity refuses before reserving an intent", async () => {
|
|
149
|
+
await api(ntok.token!, `${root}/bridge`, { ...binding, expected: { node_id: nodeId, network_id: net }, fork_supported: true });
|
|
150
|
+
const intent = `fork_intent_${serial}_no_identity`;
|
|
151
|
+
for (const expected of [undefined, null, {}, { session_id: binding.session_id }]) {
|
|
152
|
+
const result = await enqueue("fork", { intent_id: intent, expected });
|
|
153
|
+
expect(result.status).toBe(400);
|
|
154
|
+
expect(result.body.error).toBe("session_control_request_invalid");
|
|
155
|
+
}
|
|
156
|
+
expect((await api(owner.token!, `${root}/intent/${intent}?network_id=${net}`)).status).toBe(404);
|
|
157
|
+
expect((await pull()).body.request).toBeNull();
|
|
158
|
+
});
|
|
71
159
|
test("[2017 identity] missing or malformed expected is refused without fallback", async () => {
|
|
72
160
|
for (const expected of [undefined, {}, { node_id: nodeId }, { node_id: nodeId, network_id: net, token_id: ntok.token_id }]) {
|
|
73
161
|
const rejected = await api(ntok.token!, `${root}/bridge`, { ...binding, expected });
|
|
@@ -102,7 +190,7 @@ describe("#2017 human-to-exact-Bridge HTTP relay", () => {
|
|
|
102
190
|
const row = db.get("SELECT token_id,bound_node_id,network_id FROM api_tokens WHERE token_id=?1", ntok.token_id);
|
|
103
191
|
expect(response.status).toBe(200);
|
|
104
192
|
expect(response.body.identity).toEqual({ node_id: row.bound_node_id, network_id: row.network_id, token_id: row.token_id });
|
|
105
|
-
expect(Object.keys(response.body).sort()).toEqual(["expires_at", "identity", "ok"]);
|
|
193
|
+
expect(Object.keys(response.body).sort()).toEqual(["expires_at", "fork_supported", "identity", "ok"]);
|
|
106
194
|
expect(JSON.stringify(response.body)).not.toContain(ntok.token);
|
|
107
195
|
});
|
|
108
196
|
test("normal state and background receipts are separate from actual tool completion", async () => {
|
|
@@ -4,13 +4,14 @@ import { getUserNetworkRole, resolveToken, sessionIdleDays } from "./auth.js";
|
|
|
4
4
|
import { isAgentRestricted } from "./agent-access.js";
|
|
5
5
|
import { resolveNodeCaller } from "./create-node.js";
|
|
6
6
|
import { pushEvent } from "./push.js";
|
|
7
|
+
import { createSessionForkStore, type ForkEntry } from "./session-fork-store.js";
|
|
7
8
|
|
|
8
9
|
type Identity = { session_id: string; binding_id: string };
|
|
9
10
|
type Credential = { token_id: string; user_id: string; network_id: string | null;
|
|
10
11
|
bound_node_id: string | null; scope: string; role: string };
|
|
11
12
|
type Node = { node_id: string; network_id: string; owner_user_id: string | null; alias: string };
|
|
12
|
-
type Bridge = Identity & { tokenId: string; expires: number; retired: Set<string
|
|
13
|
-
type Entry = Identity & { request_id: string; operation: "state" | "background";
|
|
13
|
+
type Bridge = Identity & { tokenId: string; expires: number; retired: Set<string>; forkSupported: boolean };
|
|
14
|
+
type Entry = Identity & { request_id: string; operation: "state" | "background" | "fork";
|
|
14
15
|
networkId: string; nodeId: string; tokenId: string; requester: string; expires_at: number;
|
|
15
16
|
status: "pending" | "in_progress" | "done" | "failed" | "unknown" | "expired";
|
|
16
17
|
result?: unknown; error?: string };
|
|
@@ -31,7 +32,7 @@ const ok = (value: object) => Response.json({ ok: true, ...value });
|
|
|
31
32
|
|
|
32
33
|
// Recheck stored identities without storing plaintext bearer tokens. The SQL
|
|
33
34
|
// mirrors resolveToken's expiry/revoke/idle rules; membership is checked below.
|
|
34
|
-
function
|
|
35
|
+
export function readSessionControlCredential(tokenId: string): Credential | null {
|
|
35
36
|
const days = sessionIdleDays();
|
|
36
37
|
return db.get<Credential>(`SELECT t.token_id,t.user_id,t.network_id,t.bound_node_id,t.scope,u.role
|
|
37
38
|
FROM api_tokens t JOIN users u ON u.user_id=t.user_id WHERE t.token_id=?1
|
|
@@ -43,19 +44,19 @@ function credential(tokenId: string): Credential | null {
|
|
|
43
44
|
function node(nodeId: string): Node | null {
|
|
44
45
|
return db.get<Node>("SELECT node_id,network_id,owner_user_id,alias FROM nodes WHERE node_id=?1", nodeId) ?? null;
|
|
45
46
|
}
|
|
46
|
-
function isHumanCredential(c: Credential | null): c is Credential {
|
|
47
|
+
export function isHumanCredential(c: Credential | null): c is Credential {
|
|
47
48
|
return !!c && c.network_id === null && c.bound_node_id === null
|
|
48
49
|
&& (c.scope === "user" || c.scope === "full");
|
|
49
50
|
}
|
|
50
51
|
function human(tokenId: string, n: Node): boolean {
|
|
51
|
-
const c =
|
|
52
|
+
const c = readSessionControlCredential(tokenId);
|
|
52
53
|
if (!isHumanCredential(c) || !n.network_id) return false;
|
|
53
54
|
const role = getUserNetworkRole(c.user_id, n.network_id);
|
|
54
55
|
return !!role && role !== "viewer" && !isAgentRestricted(c.user_id, n.network_id)
|
|
55
56
|
&& (c.user_id === n.owner_user_id || role === "owner" || role === "admin" || c.role === "admin");
|
|
56
57
|
}
|
|
57
58
|
function bound(tokenId: string, n?: Node | null): Node | null {
|
|
58
|
-
const c =
|
|
59
|
+
const c = readSessionControlCredential(tokenId);
|
|
59
60
|
if (!c?.bound_node_id || !c.network_id || c.scope !== "network") return null;
|
|
60
61
|
const target = n ?? node(c.bound_node_id);
|
|
61
62
|
if (!target || c.bound_node_id !== target.node_id || c.network_id !== target.network_id
|
|
@@ -64,7 +65,8 @@ function bound(tokenId: string, n?: Node | null): Node | null {
|
|
|
64
65
|
return caller.ok && caller.kind === "node" && caller.nodeId === target.node_id
|
|
65
66
|
&& caller.networkId === target.network_id ? target : null;
|
|
66
67
|
}
|
|
67
|
-
|
|
68
|
+
export function resolveSessionControlNodeCaller(tokenId: string) { return bound(tokenId); }
|
|
69
|
+
export async function readSessionControlBody(req: Request, limit = 8192): Promise<Record<string, unknown> | null> {
|
|
68
70
|
const reader = req.body?.getReader();
|
|
69
71
|
if (!reader) return null;
|
|
70
72
|
const chunks: Uint8Array[] = []; let size = 0;
|
|
@@ -72,13 +74,14 @@ async function body(req: Request): Promise<Record<string, unknown> | null> {
|
|
|
72
74
|
for (;;) {
|
|
73
75
|
const part = await reader.read(); if (part.done) break;
|
|
74
76
|
size += part.value.byteLength;
|
|
75
|
-
if (size >
|
|
77
|
+
if (size > limit) { await reader.cancel(); return null; }
|
|
76
78
|
chunks.push(part.value);
|
|
77
79
|
}
|
|
78
80
|
const v: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
79
81
|
return object(v) ? v : null;
|
|
80
82
|
} catch { return null; }
|
|
81
83
|
}
|
|
84
|
+
const body = readSessionControlBody;
|
|
82
85
|
function state(value: unknown, e: Entry): boolean {
|
|
83
86
|
return object(value) && keys(value, ["session_id", "binding_id", "supported", "active", "can_request_background", "observed_at"])
|
|
84
87
|
&& same(value as Identity, e) && typeof value.supported === "boolean" && typeof value.active === "boolean"
|
|
@@ -88,39 +91,65 @@ function state(value: unknown, e: Entry): boolean {
|
|
|
88
91
|
}
|
|
89
92
|
function validResult(v: unknown, e: Entry): boolean {
|
|
90
93
|
if (e.operation === "state") return state(v, e);
|
|
94
|
+
if (e.operation === "fork") return object(v) && keys(v, ["session_id"])
|
|
95
|
+
&& typeof v.session_id === "string" && /^ses_[A-Za-z0-9]+$/.test(v.session_id) && v.session_id !== e.session_id;
|
|
91
96
|
return object(v) && keys(v, ["outcome", "state"])
|
|
92
97
|
&& (v.outcome === "request_processed" || v.outcome === "already_idle") && state(v.state, e)
|
|
93
98
|
&& (v.outcome !== "already_idle" || (object(v.state)
|
|
94
99
|
&& v.state.active === false && v.state.can_request_background === false));
|
|
95
100
|
}
|
|
96
101
|
|
|
97
|
-
/**
|
|
98
|
-
*
|
|
102
|
+
/** Background/state remain process-local; fork intents and claims are durable.
|
|
103
|
+
* Bridge registration still requires process affinity; the journal alone is
|
|
104
|
+
* not a distributed Server identity or authorization-generation registry.
|
|
99
105
|
* A claim authorizes one delivery, not proof that any tool moved to background.
|
|
100
106
|
*/
|
|
101
107
|
export function createNodeSessionControlRelay() {
|
|
102
108
|
const bridges = new Map<string, Bridge>();
|
|
103
109
|
const entries = new Map<string, Entry>();
|
|
110
|
+
const forks = createSessionForkStore(db);
|
|
111
|
+
// Journal coverage does not prove Server-generation authorization. Keep the
|
|
112
|
+
// new entry point opt-in until that independent delivery gate is satisfied.
|
|
113
|
+
const durableForks = process.env.COMMHUB_V2_FORK_PREVIEW === "1"
|
|
114
|
+
&& db.dialect === "sqlite" && db.transactionalFeaturesRefusal === null;
|
|
115
|
+
const allEntries = () => [...entries.values(), ...forks.active()];
|
|
116
|
+
const lookup = (requestId: string): Entry | undefined => requestId.startsWith("fk_") ? forks.get(requestId) : entries.get(requestId);
|
|
117
|
+
const outcomeUnknown = (e: Entry) => e.operation === "fork" ? "session_fork_outcome_unknown" : "session_background_outcome_unknown";
|
|
118
|
+
function persist(e: Entry, previous: "pending" | "in_progress") {
|
|
119
|
+
if (e.operation !== "fork") return;
|
|
120
|
+
const stored = forks.settle(e as ForkEntry, previous);
|
|
121
|
+
delete e.result; delete e.error;
|
|
122
|
+
Object.assign(e, stored);
|
|
123
|
+
}
|
|
104
124
|
const key = (n: Node) => JSON.stringify([n.network_id, n.node_id]);
|
|
105
125
|
function close(e: Entry, error: string) {
|
|
126
|
+
const previous = e.status as "pending" | "in_progress";
|
|
106
127
|
e.status = e.status === "in_progress" ? "unknown" : "failed";
|
|
107
|
-
e.error = e.status === "unknown" ?
|
|
128
|
+
e.error = e.status === "unknown" ? outcomeUnknown(e) : error;
|
|
129
|
+
persist(e, previous);
|
|
108
130
|
}
|
|
109
131
|
function refresh(e: Entry, now: number) {
|
|
110
132
|
if (e.status !== "pending" && e.status !== "in_progress") return;
|
|
111
133
|
if (now >= e.expires_at) {
|
|
134
|
+
const previous = e.status;
|
|
112
135
|
e.status = e.status === "in_progress" ? "unknown" : "expired";
|
|
113
|
-
e.error = e.status === "unknown" ?
|
|
136
|
+
e.error = e.status === "unknown" ? outcomeUnknown(e) : "session_control_request_expired";
|
|
137
|
+
persist(e, previous);
|
|
114
138
|
return;
|
|
115
139
|
}
|
|
116
140
|
const n = node(e.nodeId), b = n && bridges.get(key(n));
|
|
117
141
|
if (!n || n.network_id !== e.networkId || !human(e.requester, n) || !bound(e.tokenId, n)) {
|
|
118
142
|
close(e, "session_control_unavailable");
|
|
143
|
+
} else if (e.operation === "fork" && !b) {
|
|
144
|
+
// Another relay may own the live bridge. Absence here is not revocation;
|
|
145
|
+
// the persisted deadline will expire unclaimed work or mark it unknown.
|
|
146
|
+
return;
|
|
119
147
|
} else if (!b || b.expires <= now || b.tokenId !== e.tokenId || !same(b, e)) {
|
|
120
148
|
close(e, "session_control_changed");
|
|
121
149
|
}
|
|
122
150
|
}
|
|
123
151
|
function sweep(now: number) {
|
|
152
|
+
for (const e of forks.active()) refresh(e, now);
|
|
124
153
|
for (const [k, e] of entries) {
|
|
125
154
|
refresh(e, now);
|
|
126
155
|
if (now > e.expires_at + 60_000) entries.delete(k);
|
|
@@ -134,15 +163,17 @@ export function createNodeSessionControlRelay() {
|
|
|
134
163
|
const auth = resolveToken(raw);
|
|
135
164
|
if (!auth?.tokenId) return fail("session_control_unavailable", 401);
|
|
136
165
|
const tokenId = auth.tokenId;
|
|
137
|
-
const c =
|
|
166
|
+
const c = readSessionControlCredential(tokenId);
|
|
138
167
|
if (!c) return fail("session_control_unavailable", 401);
|
|
139
168
|
const isHuman = isHumanCredential(c);
|
|
140
169
|
const isNode = c.scope === "network" && !!c.network_id;
|
|
141
170
|
const suffix = url.pathname.slice(ROOT.length);
|
|
142
|
-
if (req.method === "GET" && /^\/(bg|sc)_\d{13}_[A-Za-z0-9_-]{8,64}$/.test(suffix)
|
|
143
|
-
|
|
171
|
+
if (req.method === "GET" && (/^\/(bg|sc|fk)_\d{13}_[A-Za-z0-9_-]{8,64}$/.test(suffix)
|
|
172
|
+
|| /^\/intent\/[A-Za-z0-9_-]{16,100}$/.test(suffix))) {
|
|
144
173
|
// Unknown/restarted Hub and unauthorized reads reveal no request data.
|
|
145
174
|
if (!isHuman) return fail("session_control_unavailable", 403);
|
|
175
|
+
const network = url.searchParams.get("network_id") ?? "";
|
|
176
|
+
const e = suffix.startsWith("/intent/") ? forks.intent(c.user_id, network, suffix.slice(8)) : lookup(suffix.slice(1));
|
|
146
177
|
if (!e) return fail("session_control_unavailable", 404);
|
|
147
178
|
const n = node(e.nodeId);
|
|
148
179
|
if (!n || url.searchParams.get("network_id") !== e.networkId || n.network_id !== e.networkId || !human(tokenId, n)) {
|
|
@@ -158,13 +189,14 @@ export function createNodeSessionControlRelay() {
|
|
|
158
189
|
const now = Date.now();
|
|
159
190
|
if (suffix === "/bridge") {
|
|
160
191
|
if (!isNode) return fail("session_control_unavailable", 403);
|
|
161
|
-
if (!keys(v, ["session_id", "binding_id", "expected"]) || !id(v.session_id) || !id(v.binding_id)
|
|
192
|
+
if (!keys(v, ["session_id", "binding_id", "expected", "fork_supported"]) || !id(v.session_id) || !id(v.binding_id)
|
|
193
|
+
|| (v.fork_supported !== undefined && typeof v.fork_supported !== "boolean")
|
|
162
194
|
|| !object(v.expected) || !keys(v.expected, ["node_id", "network_id"])
|
|
163
195
|
|| !id(v.expected.node_id) || !id(v.expected.network_id)) return fail("session_control_request_invalid", 400);
|
|
164
196
|
// Body reading is complete. This synchronous section rechecks authority
|
|
165
197
|
// and expected identity BEFORE sweep, retirement, or registration writes.
|
|
166
198
|
// expected is an assertion, never a source for binding or proof fields.
|
|
167
|
-
const c =
|
|
199
|
+
const c = readSessionControlCredential(tokenId), n = bound(tokenId);
|
|
168
200
|
if (!c || !n) return fail("session_control_unavailable", 403);
|
|
169
201
|
if (c.bound_node_id !== n.node_id || c.network_id !== n.network_id
|
|
170
202
|
|| v.expected.node_id !== c.bound_node_id || v.expected.network_id !== c.network_id) {
|
|
@@ -180,23 +212,36 @@ export function createNodeSessionControlRelay() {
|
|
|
180
212
|
sweep(now);
|
|
181
213
|
if (replacing) {
|
|
182
214
|
b.retired.add(generation(b.tokenId, b));
|
|
183
|
-
for (const e of
|
|
215
|
+
for (const e of allEntries()) if (e.nodeId === n.node_id && e.networkId === n.network_id
|
|
184
216
|
&& (e.status === "pending" || e.status === "in_progress")) close(e, "session_control_changed");
|
|
185
217
|
}
|
|
186
|
-
bridges.set(k, { ...registration, tokenId, expires: now + LEASE, retired: b?.retired ?? new Set() });
|
|
187
|
-
return ok({ expires_at: now + LEASE,
|
|
218
|
+
bridges.set(k, { ...registration, tokenId, expires: now + LEASE, retired: b?.retired ?? new Set(), forkSupported: durableForks && v.fork_supported === true });
|
|
219
|
+
return ok({ expires_at: now + LEASE, fork_supported: durableForks,
|
|
188
220
|
identity: { node_id: c.bound_node_id, network_id: c.network_id, token_id: c.token_id } });
|
|
189
221
|
}
|
|
190
222
|
sweep(now);
|
|
191
223
|
if (!suffix) {
|
|
192
224
|
if (!isHuman) return fail("session_control_unavailable", 403);
|
|
193
|
-
if (!keys(v, ["network_id", "node_id", "operation", "expected"]) || !id(v.network_id) || !id(v.node_id)
|
|
194
|
-
|| (v.operation !== "state" && v.operation !== "background")
|
|
195
|
-
|| (v.
|
|
225
|
+
if (!keys(v, ["network_id", "node_id", "operation", "expected", "intent_id"]) || !id(v.network_id) || !id(v.node_id)
|
|
226
|
+
|| (v.operation !== "state" && v.operation !== "background" && v.operation !== "fork")
|
|
227
|
+
|| (v.operation === "fork" ? typeof v.intent_id !== "string" || !/^[A-Za-z0-9_-]{16,100}$/.test(v.intent_id) : v.intent_id !== undefined)
|
|
228
|
+
|| (v.expected !== undefined && !identity(v.expected))
|
|
229
|
+
|| ((v.operation === "background" || v.operation === "fork") && !identity(v.expected))) {
|
|
196
230
|
return fail("session_control_request_invalid", 400);
|
|
197
231
|
}
|
|
198
232
|
const n = node(v.node_id);
|
|
199
233
|
if (!n || n.network_id !== v.network_id || !human(tokenId, n)) return fail("session_control_unavailable", 403);
|
|
234
|
+
const actor = readSessionControlCredential(tokenId);
|
|
235
|
+
if (!isHumanCredential(actor)) return fail("session_control_unavailable", 403);
|
|
236
|
+
if (v.operation === "fork") {
|
|
237
|
+
if (!durableForks) return fail("session_control_unsupported");
|
|
238
|
+
const previous = forks.intent(actor.user_id, n.network_id, v.intent_id as string);
|
|
239
|
+
if (previous) {
|
|
240
|
+
if (previous.nodeId !== n.node_id || !same(previous, v.expected as Identity)) return fail("session_control_changed");
|
|
241
|
+
refresh(previous, now);
|
|
242
|
+
return ok({ request_id: previous.request_id, status: previous.status, expires_at: previous.expires_at });
|
|
243
|
+
}
|
|
244
|
+
}
|
|
200
245
|
const b = bridges.get(key(n));
|
|
201
246
|
// A distinct code for "this node has no live bridge" (never registered, or
|
|
202
247
|
// its 75 s lease expired). #2014 needs it: the client can then say "upgrade
|
|
@@ -204,14 +249,22 @@ export function createNodeSessionControlRelay() {
|
|
|
204
249
|
// `session_control_unavailable` (which also covers permission refusals).
|
|
205
250
|
if (!b || b.expires <= now || !bound(b.tokenId, n)) return fail("session_control_bridge_missing");
|
|
206
251
|
if (v.expected && !same(v.expected as Identity, b)) return fail("session_control_changed");
|
|
207
|
-
if (
|
|
252
|
+
if (v.operation === "fork" && !b.forkSupported) return fail("session_control_unsupported");
|
|
253
|
+
if (entries.size + forks.active().length >= CAP || allEntries().some(e => e.nodeId === n.node_id
|
|
208
254
|
&& e.networkId === n.network_id && (e.status === "pending" || e.status === "in_progress"))) {
|
|
209
255
|
return fail("session_control_request_limit", 429);
|
|
210
256
|
}
|
|
211
|
-
const request_id = `${v.operation === "background" ? "bg" : "sc"}_${now}_${randomBytes(18).toString("base64url")}`;
|
|
212
|
-
|
|
257
|
+
const request_id = `${v.operation === "background" ? "bg" : v.operation === "fork" ? "fk" : "sc"}_${now}_${randomBytes(18).toString("base64url")}`;
|
|
258
|
+
const made = { session_id: b.session_id, binding_id: b.binding_id, request_id,
|
|
213
259
|
operation: v.operation, networkId: n.network_id, nodeId: n.node_id, tokenId: b.tokenId,
|
|
214
|
-
requester: tokenId, expires_at: now + TTL, status: "pending" }
|
|
260
|
+
requester: tokenId, expires_at: now + TTL, status: "pending" as const };
|
|
261
|
+
if (v.operation === "fork") {
|
|
262
|
+
const stored = forks.reserve({ ...made, operation: "fork", intent_id: v.intent_id as string, requesterUser: actor.user_id });
|
|
263
|
+
if (stored.request_id !== request_id) {
|
|
264
|
+
if (stored.nodeId !== n.node_id || !same(stored, v.expected as Identity)) return fail("session_control_changed");
|
|
265
|
+
return ok({ request_id: stored.request_id, status: stored.status, expires_at: stored.expires_at });
|
|
266
|
+
}
|
|
267
|
+
} else entries.set(request_id, made as Entry);
|
|
215
268
|
pushEvent(n.alias, { type: "session_control", request_id }, n.network_id);
|
|
216
269
|
return ok({ request_id, status: "pending", expires_at: now + TTL });
|
|
217
270
|
}
|
|
@@ -223,19 +276,20 @@ export function createNodeSessionControlRelay() {
|
|
|
223
276
|
if (suffix === "/pull") {
|
|
224
277
|
if (!identity(v)) return fail("session_control_request_invalid", 400);
|
|
225
278
|
if (!same(b, v)) return fail("session_control_changed");
|
|
226
|
-
const e =
|
|
279
|
+
const e = allEntries().find(e => e.nodeId === n.node_id && e.networkId === n.network_id && e.status === "pending");
|
|
227
280
|
if (!e) return ok({ request: null });
|
|
228
281
|
refresh(e, now);
|
|
229
282
|
if (e.status !== "pending") return ok({ request: null });
|
|
283
|
+
if (e.operation === "fork" && (!b.forkSupported || !forks.claim(e as ForkEntry, now))) return ok({ request: null });
|
|
230
284
|
// No await between authority recheck, claim, and response. Never requeue.
|
|
231
285
|
e.status = "in_progress";
|
|
232
286
|
return ok({ request: { request_id: e.request_id, operation: e.operation,
|
|
233
287
|
session_id: e.session_id, binding_id: e.binding_id, expires_at: e.expires_at } });
|
|
234
288
|
}
|
|
235
|
-
if (/^\/(bg|sc)_\d{13}_[A-Za-z0-9_-]{8,64}\/ack$/.test(suffix)) {
|
|
289
|
+
if (/^\/(bg|sc|fk)_\d{13}_[A-Za-z0-9_-]{8,64}\/ack$/.test(suffix)) {
|
|
236
290
|
if (!keys(v, ["session_id", "binding_id", "status", "result", "error"]) || !id(v.session_id) || !id(v.binding_id)
|
|
237
|
-
|| (v.status !== "done" && v.status !== "failed")) return fail("session_control_request_invalid", 400);
|
|
238
|
-
const e =
|
|
291
|
+
|| (v.status !== "done" && v.status !== "failed" && !(v.status === "unknown" && suffix.startsWith("/fk_")))) return fail("session_control_request_invalid", 400);
|
|
292
|
+
const e = lookup(suffix.split("/")[1]);
|
|
239
293
|
if (!e) return fail("session_control_unavailable", 404);
|
|
240
294
|
if (e.nodeId !== n.node_id || e.networkId !== n.network_id || e.tokenId !== tokenId || !same(e, v as Identity)
|
|
241
295
|
|| !same(b, e)) return fail("session_control_changed");
|
|
@@ -243,13 +297,17 @@ export function createNodeSessionControlRelay() {
|
|
|
243
297
|
if (e.status !== "in_progress") return fail("session_control_request_expired");
|
|
244
298
|
if (v.status === "done" && validResult(v.result, e) && v.error === undefined) {
|
|
245
299
|
e.status = "done"; e.result = v.result;
|
|
300
|
+
} else if (v.status === "unknown" && e.operation === "fork" && v.error === "session_fork_outcome_unknown" && v.result === undefined) {
|
|
301
|
+
e.status = "unknown"; e.error = "session_fork_outcome_unknown";
|
|
246
302
|
} else if (v.status === "failed" && typeof v.error === "string" && ERRORS.has(v.error) && v.result === undefined) {
|
|
247
303
|
e.status = "failed"; e.error = v.error;
|
|
248
304
|
} else {
|
|
249
305
|
// Invalid/untrusted runtime replies never become success or leak raw errors.
|
|
250
306
|
e.status = "unknown"; e.error = "session_control_invalid_response";
|
|
307
|
+
persist(e, "in_progress");
|
|
251
308
|
return fail(e.error, 400);
|
|
252
309
|
}
|
|
310
|
+
persist(e, "in_progress");
|
|
253
311
|
return ok({ request_id: e.request_id, status: e.status });
|
|
254
312
|
}
|
|
255
313
|
return fail("session_control_request_invalid", 404);
|
|
@@ -123,6 +123,20 @@ function snapshot(directory = PROJECT, overrides: Record<string, unknown> = {})
|
|
|
123
123
|
}
|
|
124
124
|
|
|
125
125
|
describe("hub authorizes an owned OpenCode V2 catalog read", () => {
|
|
126
|
+
test("session model write is denied by default and requires human admin", async () => {
|
|
127
|
+
seed();
|
|
128
|
+
const args = { daemon_node_id: DAEMON, node_id: V2, session_id: "ses_synthetic", model: { providerID: "stub", id: "model", variant: "high" } };
|
|
129
|
+
const admin = handlers(USER, false, null);
|
|
130
|
+
expect(await call(admin.out.select_opencode_session_model!, args)).toEqual({ ok: false, status: "rejected", reason: "unsupported" });
|
|
131
|
+
const viewer = handlers(VIEWER, false, null);
|
|
132
|
+
expect(await call(viewer.out.select_opencode_session_model!, args)).toEqual({ ok: false, error: "access_denied" });
|
|
133
|
+
const outsider = handlers(OUTSIDER, false, null);
|
|
134
|
+
expect(await call(outsider.out.select_opencode_session_model!, args)).toEqual({ ok: false, error: "access_denied" });
|
|
135
|
+
const node = handlers(USER, true, DAEMON_TOK);
|
|
136
|
+
expect(await call(node.out.select_opencode_session_model!, args)).toEqual({ ok: false, error: "user_token_required" });
|
|
137
|
+
const schema = (admin.server as any)._registeredTools.select_opencode_session_model.inputSchema;
|
|
138
|
+
expect((await schema.safeParseAsync({ ...args, model: { ...args.model, headers: { token: "fixture" } } })).success).toBe(false);
|
|
139
|
+
});
|
|
126
140
|
test("member queues, daemon reads the owned loopback, ready snapshot stays unverified", async () => {
|
|
127
141
|
seed();
|
|
128
142
|
const user = handlers(USER, false, null);
|
|
@@ -96,6 +96,7 @@ export const opencodeCatalogSnapshotSchema = z.object({
|
|
|
96
96
|
models: z.array(z.object({
|
|
97
97
|
providerId: identifier,
|
|
98
98
|
id: identifier,
|
|
99
|
+
variants: z.array(identifier).max(200).refine(values => new Set(values).size === values.length).optional(),
|
|
99
100
|
}).strict()).max(20_000),
|
|
100
101
|
defaultModel: z.object({ providerId: identifier, id: identifier }).strict().nullable(),
|
|
101
102
|
}).strict();
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// commhub-server ships only `src/`, `bin/` and build-info.json (package.json "files").
|
|
2
|
+
// A non-test module that imports a path outside this package works in the repo but
|
|
3
|
+
// makes the published Hub crash at startup ("Cannot find module ../../contracts/…",
|
|
4
|
+
// seen in the e2e npm-pack suite). Pin it: every relative import from shipped code
|
|
5
|
+
// must resolve inside server/.
|
|
6
|
+
import { expect, test } from "bun:test";
|
|
7
|
+
import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
8
|
+
import { dirname, join, resolve, sep } from "node:path";
|
|
9
|
+
|
|
10
|
+
const root = resolve(import.meta.dir, "..");
|
|
11
|
+
const IMPORT_RE = /(?:from|import\(|require\()\s*["'](\.{1,2}\/[^"']+)["']/g;
|
|
12
|
+
|
|
13
|
+
function shipped(dir: string): string[] {
|
|
14
|
+
const out: string[] = [];
|
|
15
|
+
for (const name of readdirSync(dir)) {
|
|
16
|
+
const p = join(dir, name);
|
|
17
|
+
if (statSync(p).isDirectory()) { if (name !== "node_modules" && name !== "fixtures") out.push(...shipped(p)); }
|
|
18
|
+
else if (/\.(ts|js|mjs)$/.test(name) && !/\.test\.(ts|js)$/.test(name)) out.push(p);
|
|
19
|
+
}
|
|
20
|
+
return out;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
test("shipped server code never imports outside the commhub-server package", () => {
|
|
24
|
+
const escapes: string[] = [];
|
|
25
|
+
for (const file of [...shipped(join(root, "src")), ...shipped(join(root, "bin"))]) {
|
|
26
|
+
for (const m of readFileSync(file, "utf8").matchAll(IMPORT_RE)) {
|
|
27
|
+
const target = resolve(dirname(file), m[1]);
|
|
28
|
+
if (!target.startsWith(root + sep)) escapes.push(`${file.slice(root.length + 1)} → ${m[1]}`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
expect(escapes).toEqual([]);
|
|
32
|
+
});
|