@sleep2agi/commhub-server 0.9.0-preview.275 → 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/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 +33 -3
- 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/tool-audience-http.test.ts +18 -0
- package/src/tool-audience.ts +1 -1
- package/src/tools.ts +154 -51
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test";
|
|
2
|
+
import { db } from "./db";
|
|
3
|
+
import { register, createNetworkTokenForNode } from "./auth";
|
|
4
|
+
import { createSessionSourceIssuer, SourceIssuerError, type SourceSelection } from "./session-source-issuer";
|
|
5
|
+
import { createSessionSourceGrantStore } from "./session-source-grant";
|
|
6
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
7
|
+
import { registerTools } from "./tools";
|
|
8
|
+
import { createSessionSourceTransport } from "./session-source-transport";
|
|
9
|
+
import { buildConfigSnapshot } from "../../agent-node/src/runtime/config-apply";
|
|
10
|
+
import { SOURCE_FORK_CAPABILITY } from "../../contracts/session-source-transport";
|
|
11
|
+
import { SOURCE_DELIVERY_CAPABILITY } from "../../contracts/session-source-delivery";
|
|
12
|
+
|
|
13
|
+
const v2Snapshot = () => buildConfigSnapshot({ runtime: "opencode-cli", opencodeGeneration: "v2", opencodeMode: "copresence" }, false, 0);
|
|
14
|
+
|
|
15
|
+
const issuer = createSessionSourceIssuer();
|
|
16
|
+
let owner: ReturnType<typeof register>, member: ReturnType<typeof register>, bootstrap: ReturnType<typeof register>;
|
|
17
|
+
let sourceToken: ReturnType<typeof createNetworkTokenForNode>, daemonToken: ReturnType<typeof createNetworkTokenForNode>;
|
|
18
|
+
let selection: SourceSelection;
|
|
19
|
+
const request = (token?: string) => new Request("http://isolated.invalid/internal-only", {
|
|
20
|
+
headers: token ? { authorization: `Bearer ${token}` } : {},
|
|
21
|
+
});
|
|
22
|
+
const counts = () => ["session_source_grants", "node_create_requests"].map(table => db.get<{ n: number }>(`SELECT COUNT(*) AS n FROM ${table}`)!.n);
|
|
23
|
+
const inspect = () => issuer.inspect(request(owner.token), selection);
|
|
24
|
+
beforeAll(() => {
|
|
25
|
+
bootstrap = register("issuer_bootstrap", "Fixture-Strong-4150!");
|
|
26
|
+
owner = register("issuer_owner", "Fixture-Strong-4150!");
|
|
27
|
+
member = register("issuer_member", "Fixture-Strong-4150!");
|
|
28
|
+
expect(bootstrap.ok && owner.ok && member.ok).toBe(true);
|
|
29
|
+
const net = owner.network_id!, uid = owner.user!.user_id;
|
|
30
|
+
selection = { network_id: net, source_node_id: "n_source", daemon_node_id: "n_daemon", mode: "attach_existing" };
|
|
31
|
+
sourceToken = createNetworkTokenForNode(uid, net, "source", "n_source");
|
|
32
|
+
daemonToken = createNetworkTokenForNode(uid, net, "daemon", "n_daemon");
|
|
33
|
+
expect(sourceToken.ok && daemonToken.ok).toBe(true);
|
|
34
|
+
db.run(`INSERT INTO network_members (network_id,user_id,role,agent_access) VALUES (?1,?2,'member','granted')`, [net, member.user!.user_id]);
|
|
35
|
+
db.run(`INSERT INTO sessions (resume_id,alias,node_id,network_id,last_seen_at) VALUES
|
|
36
|
+
('issuer_source','source','n_source',?1,datetime('now')),('issuer_daemon','daemon','n_daemon',?1,datetime('now'))`, [net]);
|
|
37
|
+
db.run(`INSERT INTO node_create_requests
|
|
38
|
+
(request_id,daemon_node_id,child_name,network_id,runtime,flags_json,env_keys,status,child_node_id,created_at,created_by_token,workdir)
|
|
39
|
+
VALUES ('cr_original','n_daemon','source',?1,'opencode-cli','{}','[]','succeeded','n_source',1000,?2,'/reported/path')`, [net, owner.token_id!]);
|
|
40
|
+
});
|
|
41
|
+
beforeEach(() => {
|
|
42
|
+
db.run("UPDATE users SET role='user' WHERE user_id=?1", [owner.user!.user_id]);
|
|
43
|
+
db.run("UPDATE network_members SET role='owner',agent_access='all' WHERE user_id=?1 AND network_id=?2", [owner.user!.user_id, owner.network_id!]);
|
|
44
|
+
db.run("UPDATE network_members SET role='member',agent_access='granted' WHERE user_id=?1 AND network_id=?2", [member.user!.user_id, owner.network_id!]);
|
|
45
|
+
db.run("DELETE FROM network_member_agent_grants WHERE user_id=?1", [member.user!.user_id]);
|
|
46
|
+
db.run("UPDATE api_tokens SET revoked_at=NULL,expires_at=NULL,last_used_at=datetime('now') WHERE user_id=?1", [owner.user!.user_id]);
|
|
47
|
+
db.run("UPDATE api_tokens SET bound_node_id='n_source' WHERE token_id=?1", [sourceToken.token_id!]);
|
|
48
|
+
db.run("UPDATE nodes SET network_id=?1 WHERE node_id IN ('n_source','n_daemon')", [owner.network_id!]);
|
|
49
|
+
db.run("UPDATE nodes SET runtime='opencode-cli',config_snapshot=?1 WHERE node_id='n_source'", [JSON.stringify(v2Snapshot())]);
|
|
50
|
+
db.run("UPDATE nodes SET config_snapshot=?1 WHERE node_id='n_daemon'", [JSON.stringify({ role: "host_supervisor", daemon_capabilities: { can_create_nodes: true } })]);
|
|
51
|
+
db.run("UPDATE sessions SET last_seen_at=datetime('now') WHERE resume_id IN ('issuer_source','issuer_daemon')");
|
|
52
|
+
db.run("UPDATE node_create_requests SET status='succeeded',daemon_node_id='n_daemon' WHERE request_id='cr_original'");
|
|
53
|
+
db.run("DELETE FROM node_daemon_bindings WHERE node_id='n_source'");
|
|
54
|
+
db.run("DELETE FROM session_project_creates WHERE request_id='issuer_project'");
|
|
55
|
+
});
|
|
56
|
+
afterAll(() => db.close());
|
|
57
|
+
|
|
58
|
+
test("actual CLI registration: explicit V2 copresence admits; SDK/V1/unknown/host and foreign scope refuse", async () => {
|
|
59
|
+
const server = new McpServer({ name: "source-guard-diagnosis", version: "0" }) as any;
|
|
60
|
+
let report: any;
|
|
61
|
+
const original = server.tool.bind(server);
|
|
62
|
+
server.tool = (name: string, desc: string, schema: any, handler: any) => {
|
|
63
|
+
if (name === "report_status") report = handler;
|
|
64
|
+
return original(name, desc, schema, handler);
|
|
65
|
+
};
|
|
66
|
+
registerTools(server, undefined, owner.network_id!, owner.user!.user_id, "source", true, sourceToken.token_id!);
|
|
67
|
+
// project-new mints a bound credential but does not precreate a nodes row.
|
|
68
|
+
db.run("DELETE FROM nodes WHERE node_id='n_source'");
|
|
69
|
+
const registerSnapshot = async (config_snapshot: any, agent = "agent-node:opencode") => report({
|
|
70
|
+
resume_id: "issuer_source", alias: "source", node_id: "n_source", network_id: owner.network_id!,
|
|
71
|
+
status: "idle", agent, session_id: "ses_DiagnosticOnly", config_snapshot });
|
|
72
|
+
const registration = await registerSnapshot(v2Snapshot());
|
|
73
|
+
expect(JSON.parse(registration.content[0].text).error).toBeUndefined();
|
|
74
|
+
const stored = db.get<{ runtime: string }>("SELECT runtime FROM nodes WHERE node_id='n_source'")!;
|
|
75
|
+
expect(stored.runtime).toBe("opencode-sdk");
|
|
76
|
+
expect(inspect()).toMatchObject({ permissions_verified: true });
|
|
77
|
+
const url = new URL("http://isolated.invalid/api/node-session-control/source");
|
|
78
|
+
const transport = createSessionSourceTransport({ enabled: true });
|
|
79
|
+
const post = async (suffix: string, token: string, body: any) => transport(new Request(url + suffix, { method: "POST",
|
|
80
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify(body) }), new URL(url + suffix));
|
|
81
|
+
db.run("UPDATE nodes SET config_snapshot=?1 WHERE node_id='n_daemon'", [JSON.stringify({ role: "host_supervisor", daemon_capabilities: {
|
|
82
|
+
source_fork_transport: SOURCE_FORK_CAPABILITY, source_node_delivery: SOURCE_DELIVERY_CAPABILITY } })]);
|
|
83
|
+
db.run("UPDATE sessions SET env_transport='loopback' WHERE node_id='n_daemon'");
|
|
84
|
+
expect((await post("/daemon", daemonToken.token!, { expected: { node_id: "n_daemon", network_id: owner.network_id! },
|
|
85
|
+
capability: SOURCE_FORK_CAPABILITY, instance_id: "11111111-1111-4111-8111-111111111111" }))!.status).toBe(200);
|
|
86
|
+
const input = { network_id: owner.network_id!, source_node_id: "n_source", session_id: "ses_DiagnosticOnly",
|
|
87
|
+
mode: "fork_independent", child_name: "diagnostic-fork", intent_id: "diagnostic-fork" };
|
|
88
|
+
const admitted = await post("", owner.token!, input);
|
|
89
|
+
expect(admitted!.status).toBe(200); expect(await admitted!.json()).toMatchObject({ status: "evidence_pending" });
|
|
90
|
+
for (const config of [{ runtime: "opencode-cli" }, { runtime: "opencode-cli", opencodeGeneration: "v1", opencodeMode: "copresence" },
|
|
91
|
+
{ runtime: "opencode-cli", opencodeGeneration: "v2", opencodeMode: "headless" },
|
|
92
|
+
{ runtime: "opencode-cli", opencodeGeneration: "v9", opencodeMode: "copresence" },
|
|
93
|
+
{ runtime: "opencode-cli", opencodeGeneration: "v2", opencodeMode: "copresence", role: "host_supervisor" }]) {
|
|
94
|
+
await registerSnapshot(buildConfigSnapshot(config, false, 0));
|
|
95
|
+
expect(inspect()).toEqual({ ok: false, error: "source_runtime_unsupported" });
|
|
96
|
+
expect((await post("", owner.token!, input))!.status).toBe(403);
|
|
97
|
+
}
|
|
98
|
+
await registerSnapshot(v2Snapshot(), "agent-node:claude");
|
|
99
|
+
expect(inspect()).toEqual({ ok: false, error: "source_runtime_unsupported" });
|
|
100
|
+
await registerSnapshot(v2Snapshot());
|
|
101
|
+
expect((await post("", bootstrap.token!, input))!.status).toBe(403);
|
|
102
|
+
db.run("UPDATE node_create_requests SET daemon_node_id='other' WHERE request_id='cr_original'");
|
|
103
|
+
expect((await post("", owner.token!, input))!.status).not.toBe(200);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test("project-new historical registration is management only, pending/unknown and conflicting daemon refuse", () => {
|
|
107
|
+
db.run("UPDATE node_create_requests SET status='failed' WHERE request_id='cr_original'");
|
|
108
|
+
db.run(`INSERT INTO session_project_creates(request_id,user_id,requester_token_id,network_id,source_node_id,daemon_node_id,
|
|
109
|
+
daemon_token_id,daemon_instance_id,intent_id,selection_scope,snapshot_id,project_id,child_name,accepted_at,expires_at,state,child_node_id)
|
|
110
|
+
VALUES ('issuer_project',?1,?2,?3,'anchor','n_daemon',?4,'instance','issuer_project','scope','snap','project','source',1,2,'delivery_claimed','n_source')`,
|
|
111
|
+
[owner.user!.user_id, owner.token_id!, owner.network_id!, daemonToken.token_id!]);
|
|
112
|
+
expect(inspect()).toEqual({ ok: false, error: "source_daemon_unverified" });
|
|
113
|
+
db.run("UPDATE session_project_creates SET state='registration_confirmed' WHERE request_id='issuer_project'");
|
|
114
|
+
expect(inspect()).toMatchObject({ error: "source_evidence_unavailable", management: "created" });
|
|
115
|
+
db.run("UPDATE node_create_requests SET status='succeeded',daemon_node_id='other' WHERE request_id='cr_original'");
|
|
116
|
+
expect(inspect()).toEqual({ ok: false, error: "source_daemon_mismatch" });
|
|
117
|
+
db.run("UPDATE node_create_requests SET status='failed' WHERE request_id='cr_original'");
|
|
118
|
+
db.run("UPDATE session_project_creates SET state='unknown_rotation_required' WHERE request_id='issuer_project'");
|
|
119
|
+
expect(inspect()).toEqual({ ok: false, error: "source_daemon_unverified" });
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test("real persisted bearer auth: missing, fabricated, network, expired, revoked and idle tokens refuse", () => {
|
|
123
|
+
const before = counts();
|
|
124
|
+
for (const token of [undefined, "tok_owner_id_is_not_auth", owner.network_token, sourceToken.token]) {
|
|
125
|
+
expect(issuer.issue(request(token), selection)).toEqual({ ok: false, error: "source_auth_required" });
|
|
126
|
+
}
|
|
127
|
+
for (const assignment of ["revoked_at=datetime('now')", "expires_at=datetime('now','-1 minute')",
|
|
128
|
+
"last_used_at=datetime('now','-400 days'),created_at=datetime('now','-400 days')"]) {
|
|
129
|
+
db.run(`UPDATE api_tokens SET ${assignment} WHERE token_id=?1`, [owner.token_id!]);
|
|
130
|
+
expect(inspect()).toEqual({ ok: false, error: "source_auth_required" });
|
|
131
|
+
db.run("UPDATE api_tokens SET revoked_at=NULL,expires_at=NULL,last_used_at=datetime('now') WHERE token_id=?1", [owner.token_id!]);
|
|
132
|
+
}
|
|
133
|
+
expect(counts()).toEqual(before);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
test("current network membership and source visibility are checked before creation permission", () => {
|
|
137
|
+
expect(issuer.issue(request(bootstrap.token), selection)).toEqual({ ok: false, error: "source_network_forbidden" });
|
|
138
|
+
expect(issuer.issue(request(owner.token), { ...selection, network_id: member.network_id! }))
|
|
139
|
+
.toEqual({ ok: false, error: "source_network_forbidden" });
|
|
140
|
+
expect(issuer.issue(request(member.token), selection)).toEqual({ ok: false, error: "source_read_forbidden" });
|
|
141
|
+
db.run("INSERT INTO network_member_agent_grants (network_id,user_id,node_id,can_message) VALUES (?1,?2,'n_source',0)", [owner.network_id!, member.user!.user_id]);
|
|
142
|
+
expect(issuer.issue(request(member.token), selection)).toEqual({ ok: false, error: "insufficient_role_for_create_node" });
|
|
143
|
+
db.run("UPDATE nodes SET network_id=?1 WHERE node_id='n_source'", [member.network_id!]);
|
|
144
|
+
expect(inspect()).toEqual({ ok: false, error: "source_read_forbidden" });
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test("create_node role rules recheck demotion and do not infer create permission from source ownership", () => {
|
|
148
|
+
for (const role of ["member", "viewer"]) {
|
|
149
|
+
db.run("UPDATE network_members SET role=?1 WHERE user_id=?2 AND network_id=?3", [role, owner.user!.user_id, owner.network_id!]);
|
|
150
|
+
expect(inspect()).toEqual({ ok: false, error: "insufficient_role_for_create_node" });
|
|
151
|
+
}
|
|
152
|
+
db.run("UPDATE network_members SET role='admin' WHERE user_id=?1 AND network_id=?2", [owner.user!.user_id, owner.network_id!]);
|
|
153
|
+
expect(inspect().error).toBe("source_evidence_unavailable");
|
|
154
|
+
db.run("DELETE FROM network_members WHERE user_id=?1 AND network_id=?2", [owner.user!.user_id, owner.network_id!]);
|
|
155
|
+
expect(inspect()).toEqual({ ok: false, error: "source_network_forbidden" });
|
|
156
|
+
db.run("INSERT INTO network_members (network_id,user_id,role) VALUES (?1,?2,'owner')", [owner.network_id!, owner.user!.user_id]);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
test("target daemon network/capability and actual managed-source relation are mandatory", () => {
|
|
160
|
+
db.run("UPDATE nodes SET network_id=?1 WHERE node_id='n_daemon'", [member.network_id!]);
|
|
161
|
+
expect(inspect()).toEqual({ ok: false, error: "daemon_not_found" });
|
|
162
|
+
db.run("UPDATE nodes SET network_id=?1,config_snapshot=?2 WHERE node_id='n_daemon'", [owner.network_id!, JSON.stringify({ role: "host_supervisor", daemon_capabilities: { can_create_nodes: false } })]);
|
|
163
|
+
expect(inspect()).toEqual({ ok: false, error: "daemon_cannot_create_nodes" });
|
|
164
|
+
db.run("UPDATE nodes SET config_snapshot=?1 WHERE node_id='n_daemon'", [JSON.stringify({ role: "host_supervisor" })]);
|
|
165
|
+
db.run("UPDATE node_create_requests SET daemon_node_id='other_daemon' WHERE request_id='cr_original'");
|
|
166
|
+
expect(inspect()).toEqual({ ok: false, error: "source_daemon_mismatch" });
|
|
167
|
+
db.run("UPDATE node_create_requests SET status='pending' WHERE request_id='cr_original'");
|
|
168
|
+
expect(inspect()).toEqual({ ok: false, error: "source_daemon_unverified" });
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
test("malformed/ordinary daemon snapshots and non-OpenCode sources are not source authority", () => {
|
|
172
|
+
for (const raw of ["not-json", "[]", "{}", JSON.stringify({ role: "ordinary" }),
|
|
173
|
+
JSON.stringify({ role: "host_supervisor", daemon_capabilities: { runtimes_supported: ["codex-sdk"] } })]) {
|
|
174
|
+
db.run("UPDATE nodes SET config_snapshot=?1 WHERE node_id='n_daemon'", [raw]);
|
|
175
|
+
expect(inspect()).toEqual({ ok: false, error: "daemon_cannot_create_nodes" });
|
|
176
|
+
}
|
|
177
|
+
db.run("UPDATE nodes SET config_snapshot=?1 WHERE node_id='n_daemon'", [JSON.stringify({ role: "host_supervisor" })]);
|
|
178
|
+
db.run("UPDATE nodes SET runtime='codex-app-server' WHERE node_id='n_source'");
|
|
179
|
+
expect(inspect()).toEqual({ ok: false, error: "source_runtime_unsupported" });
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
test("acknowledged adoption is a management relation, not canonical-directory or Server authority", () => {
|
|
183
|
+
db.run("UPDATE node_create_requests SET status='failed' WHERE request_id='cr_original'");
|
|
184
|
+
db.run(`INSERT INTO node_daemon_bindings
|
|
185
|
+
(request_id,node_id,network_id,daemon_node_id,workdir,requested_by,status,created_at,updated_at)
|
|
186
|
+
VALUES ('adopt_source','n_source',?1,'n_daemon','http://untrusted.invalid/path',?2,'active',1000,1000)`, [owner.network_id!, owner.user!.user_id]);
|
|
187
|
+
expect(inspect()).toEqual({ ok: false, error: "source_evidence_unavailable", permissions_verified: true,
|
|
188
|
+
management: "adopted", missing: ["server_session_generation", "canonical_directory_ownership"] });
|
|
189
|
+
db.run("UPDATE node_daemon_bindings SET daemon_node_id='other_daemon' WHERE request_id='adopt_source'");
|
|
190
|
+
db.run("UPDATE node_create_requests SET status='succeeded' WHERE request_id='cr_original'");
|
|
191
|
+
expect(inspect()).toEqual({ ok: false, error: "source_daemon_mismatch" });
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
test("freshness uses Hub receipt times and currently valid immutable node credentials", () => {
|
|
195
|
+
for (const offset of ["-2 minutes", "+2 minutes"]) {
|
|
196
|
+
db.run("UPDATE sessions SET last_seen_at=datetime('now',?1) WHERE resume_id='issuer_source'", [offset]);
|
|
197
|
+
expect(inspect()).toEqual({ ok: false, error: "source_evidence_stale" });
|
|
198
|
+
}
|
|
199
|
+
db.run("UPDATE sessions SET last_seen_at=datetime('now') WHERE resume_id='issuer_source'");
|
|
200
|
+
for (const tokenId of [sourceToken.token_id!, daemonToken.token_id!]) {
|
|
201
|
+
db.run("UPDATE api_tokens SET revoked_at=datetime('now') WHERE token_id=?1", [tokenId]);
|
|
202
|
+
expect(inspect()).toEqual({ ok: false, error: "source_evidence_stale" });
|
|
203
|
+
db.run("UPDATE api_tokens SET revoked_at=NULL WHERE token_id=?1", [tokenId]);
|
|
204
|
+
}
|
|
205
|
+
db.run("UPDATE api_tokens SET expires_at=datetime('now','-1 minute') WHERE token_id=?1", [sourceToken.token_id!]);
|
|
206
|
+
expect(inspect()).toEqual({ ok: false, error: "source_evidence_stale" });
|
|
207
|
+
db.run("UPDATE api_tokens SET expires_at=NULL,bound_node_id=NULL WHERE token_id=?1", [sourceToken.token_id!]);
|
|
208
|
+
expect(inspect()).toEqual({ ok: false, error: "source_evidence_stale" });
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
test("reported binding, directory and URL never become verified proof; issue adds no grant", () => {
|
|
212
|
+
const before = counts();
|
|
213
|
+
db.run("UPDATE nodes SET config_snapshot=?1 WHERE node_id='n_source'", [JSON.stringify({
|
|
214
|
+
...v2Snapshot(),
|
|
215
|
+
session_id: "ses_Forged", binding_id: "claimed_binding", server_generation: "claimed_generation",
|
|
216
|
+
canonical_directory: "/reported/canonical", server_url: "http://untrusted.invalid" })]);
|
|
217
|
+
for (const mode of ["attach_existing", "fork_independent"] as const) {
|
|
218
|
+
expect(issuer.issue(request(owner.token), { ...selection, mode })).toEqual({ ok: false, error: "source_evidence_unavailable",
|
|
219
|
+
permissions_verified: true, management: "created", missing: ["server_session_generation", "canonical_directory_ownership"] });
|
|
220
|
+
}
|
|
221
|
+
for (const extra of [{ binding: {} }, { canonical_directory: "/client/path" }, { server_url: "http://untrusted.invalid" }, { user_id: owner.user!.user_id }]) {
|
|
222
|
+
expect(issuer.issue(request(owner.token), { ...selection, ...extra })).toEqual({ ok: false, error: "source_selection_invalid" });
|
|
223
|
+
}
|
|
224
|
+
expect(counts()).toEqual(before);
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
test("real revalidation composes with existing admission/store but never consumes an unproven grant", () => {
|
|
228
|
+
// Test-only pre-existing store row, NOT claimed as an issuer-produced proof.
|
|
229
|
+
const store = createSessionSourceGrantStore(db), now = Date.now();
|
|
230
|
+
const ref = store.issue({ ...selection, user_id: owner.user!.user_id, session_id: "ses_Fixture",
|
|
231
|
+
binding_id: "test_only", server_generation: "test_only", canonical_directory: "/test-only" }, now, now + 60_000);
|
|
232
|
+
const before = counts(), callback = issuer.revalidation(request(owner.token), selection);
|
|
233
|
+
expect(() => callback()).toThrow(SourceIssuerError);
|
|
234
|
+
expect(() => issuer.reserve(request(owner.token), selection, ref, "never-launched")).toThrow("source_evidence_unavailable");
|
|
235
|
+
expect(() => issuer.recover(request(owner.token), selection, ref)).toThrow("source_evidence_unavailable");
|
|
236
|
+
db.run("UPDATE network_members SET role='viewer' WHERE user_id=?1 AND network_id=?2", [owner.user!.user_id, owner.network_id!]);
|
|
237
|
+
expect(() => callback()).toThrow("insufficient_role_for_create_node");
|
|
238
|
+
db.run("UPDATE network_members SET role='owner' WHERE user_id=?1 AND network_id=?2", [owner.user!.user_id, owner.network_id!]);
|
|
239
|
+
db.run("UPDATE nodes SET network_id=?1 WHERE node_id='n_source'", [member.network_id!]);
|
|
240
|
+
expect(() => callback()).toThrow("source_read_forbidden");
|
|
241
|
+
db.run("UPDATE nodes SET network_id=?1 WHERE node_id='n_source'", [owner.network_id!]);
|
|
242
|
+
db.run("UPDATE api_tokens SET revoked_at=datetime('now') WHERE token_id=?1", [owner.token_id!]);
|
|
243
|
+
expect(() => callback()).toThrow("source_auth_required");
|
|
244
|
+
expect(counts()).toEqual(before);
|
|
245
|
+
expect(db.get("SELECT state,create_request_id FROM session_source_grants WHERE source_ref=?1", ref))
|
|
246
|
+
.toEqual({ state: "issued", create_request_id: null });
|
|
247
|
+
});
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { db } from "./db";
|
|
2
|
+
import { resolveToken, getUserNetworkRole } from "./auth";
|
|
3
|
+
import { canSeeAgent } from "./agent-access";
|
|
4
|
+
import { canRestWriteNetwork, getUserNetworkIds } from "./network-scope";
|
|
5
|
+
import { resolveNodeCaller } from "./create-node";
|
|
6
|
+
import { parseDbTimestampMs } from "./db-timestamp";
|
|
7
|
+
import { createSessionSourceCreateAdapter, type VerifiedSourceCreateContext } from "./session-source-create";
|
|
8
|
+
import type { SessionSourceBinding } from "./session-source-grant";
|
|
9
|
+
import { readSessionControlCredential, isHumanCredential } from "./node-session-control";
|
|
10
|
+
import { isOpenCodeV2CopresenceRuntime, readOpencodeSnapshotFlags } from "./config-apply-validate";
|
|
11
|
+
|
|
12
|
+
/** Routing assertions only. No binding, session, directory, URL or user proof. */
|
|
13
|
+
export type SourceSelection = {
|
|
14
|
+
network_id: string; source_node_id: string; daemon_node_id: string;
|
|
15
|
+
mode: SessionSourceBinding["mode"];
|
|
16
|
+
};
|
|
17
|
+
export type SourceIssuerCode = "source_selection_invalid" | "source_auth_required" | "source_network_forbidden"
|
|
18
|
+
| "source_read_forbidden" | "insufficient_role_for_create_node" | "daemon_not_found"
|
|
19
|
+
| "daemon_cannot_create_nodes" | "source_runtime_unsupported" | "source_daemon_unverified"
|
|
20
|
+
| "source_daemon_mismatch" | "source_evidence_stale" | "source_evidence_unavailable";
|
|
21
|
+
export type SourceIssuerRefusal = { ok: false; error: SourceIssuerCode };
|
|
22
|
+
export class SourceIssuerError extends Error {
|
|
23
|
+
constructor(public readonly code: SourceIssuerCode) { super(code); this.name = "SourceIssuerError"; }
|
|
24
|
+
}
|
|
25
|
+
type NodeRow = { node_id: string; alias: string; network_id: string; runtime: string | null; config_snapshot: string | null };
|
|
26
|
+
type Permissions = { selection: SourceSelection };
|
|
27
|
+
const fail = (error: SourceIssuerCode): SourceIssuerRefusal => ({ ok: false, error });
|
|
28
|
+
const object = (v: unknown): v is Record<string, any> => !!v && typeof v === "object" && !Array.isArray(v);
|
|
29
|
+
const snapshot = (n: NodeRow): Record<string, any> => {
|
|
30
|
+
try { const v = JSON.parse(n.config_snapshot || "{}"); return object(v) ? v : {}; } catch { return {}; }
|
|
31
|
+
};
|
|
32
|
+
function selectionValid(s: SourceSelection): boolean {
|
|
33
|
+
return object(s) && Object.keys(s).every(k => ["network_id", "source_node_id", "daemon_node_id", "mode"].includes(k))
|
|
34
|
+
&& [s.network_id, s.source_node_id, s.daemon_node_id].every(v => typeof v === "string" && /^[A-Za-z0-9_-]{1,200}$/.test(v))
|
|
35
|
+
&& (s.mode === "attach_existing" || s.mode === "fork_independent");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function permissions(req: Request, selection: SourceSelection): Permissions | SourceIssuerRefusal {
|
|
39
|
+
if (!selectionValid(selection)) return fail("source_selection_invalid");
|
|
40
|
+
// Same persisted-token authentication as session-control, without master/dev
|
|
41
|
+
// fallbacks. Re-resolve on every call; no caller-supplied user/token-id proof.
|
|
42
|
+
const raw = req.headers.get("authorization")?.match(/^Bearer (\S+)$/)?.[1] ?? "";
|
|
43
|
+
if (!raw) return fail("source_auth_required");
|
|
44
|
+
const auth = resolveToken(raw);
|
|
45
|
+
if (!auth?.tokenId) return fail("source_auth_required");
|
|
46
|
+
return storedPermissions(auth.tokenId, auth.user.user_id, selection);
|
|
47
|
+
}
|
|
48
|
+
function storedPermissions(tokenId: string, userId: string, selection: SourceSelection): Permissions | SourceIssuerRefusal {
|
|
49
|
+
if (!selectionValid(selection)) return fail("source_selection_invalid");
|
|
50
|
+
const token = readSessionControlCredential(tokenId);
|
|
51
|
+
if (!isHumanCredential(token) || token.user_id !== userId) return fail("source_auth_required");
|
|
52
|
+
const net = selection.network_id;
|
|
53
|
+
if (!getUserNetworkIds(userId).includes(net)) return fail("source_network_forbidden");
|
|
54
|
+
const source = db.get<NodeRow>("SELECT node_id,alias,network_id,runtime,config_snapshot FROM nodes WHERE node_id=?1 AND network_id=?2",
|
|
55
|
+
selection.source_node_id, net);
|
|
56
|
+
if (!source || !canSeeAgent(userId, net, { nodeId: source.node_id, alias: source.alias })) return fail("source_read_forbidden");
|
|
57
|
+
// create_node's shared write gate + exact network admin/owner rule. A Hub
|
|
58
|
+
// admin outside the network does not receive a new bypass here.
|
|
59
|
+
const role = getUserNetworkRole(userId, net);
|
|
60
|
+
if (!canRestWriteNetwork({ userId, networkId: token.network_id }, net, false)
|
|
61
|
+
|| (role !== "owner" && role !== "admin")) return fail("insufficient_role_for_create_node");
|
|
62
|
+
const daemon = db.get<NodeRow>("SELECT node_id,alias,network_id,runtime,config_snapshot FROM nodes WHERE node_id=?1 AND network_id=?2",
|
|
63
|
+
selection.daemon_node_id, net);
|
|
64
|
+
if (!daemon) return fail("daemon_not_found");
|
|
65
|
+
const snap = snapshot(daemon);
|
|
66
|
+
// A reported host role is necessary, not proof of Server or local ownership.
|
|
67
|
+
const runtimes = snap.daemon_capabilities?.runtimes_supported;
|
|
68
|
+
if (snap.role !== "host_supervisor" || snap.daemon_capabilities?.can_create_nodes === false
|
|
69
|
+
|| (Array.isArray(runtimes) && !runtimes.includes("opencode-cli"))) return fail("daemon_cannot_create_nodes");
|
|
70
|
+
const flags = readOpencodeSnapshotFlags(source.config_snapshot);
|
|
71
|
+
if (!isOpenCodeV2CopresenceRuntime(source.runtime, flags.opencodeGeneration, flags.opencodeMode)
|
|
72
|
+
|| snapshot(source).role === "host_supervisor") return fail("source_runtime_unsupported");
|
|
73
|
+
return { selection };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export type SourceEvidenceRead = {
|
|
77
|
+
ok: false; error: "source_evidence_unavailable";
|
|
78
|
+
permissions_verified: true;
|
|
79
|
+
management: "created" | "adopted";
|
|
80
|
+
missing: readonly ["server_session_generation", "canonical_directory_ownership"];
|
|
81
|
+
};
|
|
82
|
+
function readEvidence(p: Permissions): SourceEvidenceRead | SourceIssuerRefusal {
|
|
83
|
+
const { selection: s } = p;
|
|
84
|
+
// Read actual server journal relations, not hostname, node-id prefix, profile
|
|
85
|
+
// paths or client claims. Fail closed on ambiguous/conflicting management.
|
|
86
|
+
const created = db.all<{ daemon_node_id: string }>(`SELECT DISTINCT daemon_node_id FROM node_create_requests
|
|
87
|
+
WHERE child_node_id=?1 AND network_id=?2 AND status='succeeded' AND source_ref IS NULL
|
|
88
|
+
UNION SELECT daemon_node_id FROM session_project_creates
|
|
89
|
+
WHERE child_node_id=?1 AND network_id=?2 AND state='registration_confirmed'`, s.source_node_id, s.network_id);
|
|
90
|
+
const adopted = db.all<{ daemon_node_id: string }>(`SELECT daemon_node_id FROM node_daemon_bindings
|
|
91
|
+
WHERE node_id=?1 AND network_id=?2 AND status='active'`, s.source_node_id, s.network_id);
|
|
92
|
+
const owners = new Set([...created, ...adopted].map(r => r.daemon_node_id));
|
|
93
|
+
if (!owners.size) return fail("source_daemon_unverified");
|
|
94
|
+
if (owners.size !== 1 || !owners.has(s.daemon_node_id)) return fail("source_daemon_mismatch");
|
|
95
|
+
// Hub receipt time is a liveness prerequisite only, NOT a generation lease.
|
|
96
|
+
// Immutable token binding is deliberately stricter than legacy alias fallback.
|
|
97
|
+
for (const nodeId of [s.source_node_id, s.daemon_node_id]) {
|
|
98
|
+
const seen = db.get<{ last_seen_at: string | null }>(`SELECT last_seen_at FROM sessions
|
|
99
|
+
WHERE node_id=?1 AND network_id=?2 ORDER BY last_seen_at DESC LIMIT 1`, nodeId, s.network_id);
|
|
100
|
+
const time = parseDbTimestampMs(seen?.last_seen_at ?? "");
|
|
101
|
+
const age = Date.now() - time;
|
|
102
|
+
if (!Number.isFinite(time) || age < 0 || age > 75_000) return fail("source_evidence_stale");
|
|
103
|
+
const tokens = db.all<{ token_id: string; user_id: string }>(`SELECT t.token_id,t.user_id FROM api_tokens t JOIN users u ON u.user_id=t.user_id
|
|
104
|
+
JOIN network_members m ON m.user_id=t.user_id AND m.network_id=t.network_id
|
|
105
|
+
WHERE t.bound_node_id=?1 AND t.network_id=?2 AND t.scope='network' AND t.revoked_at IS NULL
|
|
106
|
+
AND (t.expires_at IS NULL OR t.expires_at>datetime('now'))`, nodeId, s.network_id);
|
|
107
|
+
if (!tokens.some(t => {
|
|
108
|
+
const caller = resolveNodeCaller(t.token_id);
|
|
109
|
+
return caller.ok && caller.kind === "node" && caller.nodeId === nodeId && caller.networkId === s.network_id
|
|
110
|
+
&& canRestWriteNetwork({ userId: t.user_id, networkId: s.network_id }, s.network_id, false);
|
|
111
|
+
})) return fail("source_evidence_stale");
|
|
112
|
+
}
|
|
113
|
+
// node-session-control's node-reported process-local session/binding lease
|
|
114
|
+
// has neither Server-generation authorization nor canonical directory proof.
|
|
115
|
+
// Adoption workdir and config_snapshot/project_dir are not substitutes.
|
|
116
|
+
return { ok: false, error: "source_evidence_unavailable", permissions_verified: true,
|
|
117
|
+
management: created.length ? "created" : "adopted",
|
|
118
|
+
missing: ["server_session_generation", "canonical_directory_ownership"] };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Real authentication/permission/evidence reader. No public endpoint, injectable
|
|
122
|
+
* proof provider or successful fake-binding branch. Currently cannot issue a
|
|
123
|
+
* grant: the daemon's independent Server/session/directory proof is absent. */
|
|
124
|
+
export function createSessionSourceIssuer() {
|
|
125
|
+
const adapter = createSessionSourceCreateAdapter(db);
|
|
126
|
+
const inspect = (req: Request, selection: SourceSelection): SourceIssuerRefusal | SourceEvidenceRead => {
|
|
127
|
+
const p = permissions(req, selection);
|
|
128
|
+
return "ok" in p ? p : readEvidence(p);
|
|
129
|
+
};
|
|
130
|
+
const revalidation = (req: Request, selection: SourceSelection): (() => VerifiedSourceCreateContext) => () => {
|
|
131
|
+
const refusal = inspect(req, selection);
|
|
132
|
+
throw new SourceIssuerError(refusal.error);
|
|
133
|
+
};
|
|
134
|
+
return {
|
|
135
|
+
inspect,
|
|
136
|
+
// Directory grants are explicit daemon-local authorities, not evidence that
|
|
137
|
+
// this source owns any Server. Reuse only human/network/create/read gates.
|
|
138
|
+
directoryPermissions(tokenId: string, userId: string, selection: SourceSelection): boolean {
|
|
139
|
+
return !("ok" in storedPermissions(tokenId, userId, selection));
|
|
140
|
+
},
|
|
141
|
+
/** Only for a requester authenticated and frozen by an internal queue.
|
|
142
|
+
* A token ID itself is NOT authentication; never expose this as an endpoint. */
|
|
143
|
+
inspectStoredRequester(tokenId: string, userId: string, selection: SourceSelection) {
|
|
144
|
+
const p = storedPermissions(tokenId, userId, selection);
|
|
145
|
+
return "ok" in p ? p : readEvidence(p);
|
|
146
|
+
},
|
|
147
|
+
// No store.issue call until a real evidence reader can return an authorized
|
|
148
|
+
// binding. This method returns a typed refusal rather than a bogus grant.
|
|
149
|
+
issue: inspect,
|
|
150
|
+
revalidation,
|
|
151
|
+
reserve(req: Request, selection: SourceSelection, sourceRef: string, name: string) {
|
|
152
|
+
return adapter.reserve(sourceRef, name, revalidation(req, selection));
|
|
153
|
+
},
|
|
154
|
+
recover(req: Request, selection: SourceSelection, sourceRef: string) {
|
|
155
|
+
return adapter.recover(sourceRef, revalidation(req, selection));
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|