@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,191 @@
|
|
|
1
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
2
|
+
import { db } from "./db";
|
|
3
|
+
import { resolveToken } from "./auth";
|
|
4
|
+
import { readSessionControlCredential } from "./node-session-control";
|
|
5
|
+
import { resolveNodeCaller } from "./create-node";
|
|
6
|
+
import { canRestWriteNetwork } from "./network-scope";
|
|
7
|
+
import { createSessionSourceIssuer, type SourceSelection } from "./session-source-issuer";
|
|
8
|
+
import { createSessionSourceCreateAdapter, type SourceCreateReceipt, type VerifiedSourceCreateContext } from "./session-source-create";
|
|
9
|
+
import { createSessionSourceGrantStore, type SessionSourceBinding } from "./session-source-grant";
|
|
10
|
+
import { validateName } from "./create-node-validate";
|
|
11
|
+
import { isSourceReadEvidence, sameSourceChallenge, isSourceLeaseConfirmation, sameSourceRecheck,
|
|
12
|
+
type SourceLeaseRecheck, type SourceReadChallenge, type SourceReadEvidence } from "./contracts/session-source-evidence";
|
|
13
|
+
|
|
14
|
+
export type SourceAdmissionReceipt = SourceCreateReceipt & {
|
|
15
|
+
source_ref: string; scope: "admission_only"; intent_id: string;
|
|
16
|
+
execution: { protocol: "source-aware-v1-required"; guard: "daemon_recheck_in_execution_context_required";
|
|
17
|
+
lease_kind: "process_local_lease"; lease_id: string; evidence_request_id: string; recheck_request_id: string;
|
|
18
|
+
authorized_until: number; mode: SourceSelection["mode"]; dispatchable: false };
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
// Internal, explicitly opt-in, process-local queue. No HTTP/MCP registration or
|
|
22
|
+
// SSE doorbell. No secret/config path is in a challenge. Restart loses all rows.
|
|
23
|
+
export function createSessionSourceEvidenceQueue(options: { enabled?: boolean } = {}) {
|
|
24
|
+
const issuer = createSessionSourceIssuer();
|
|
25
|
+
type Entry = { q: SourceReadChallenge; selection: SourceSelection; userId: string; tokenId: string;
|
|
26
|
+
daemonTokenId?: string; evidence?: SourceReadEvidence;
|
|
27
|
+
recheck?: { q: SourceLeaseRecheck; taken: boolean; confirmed: boolean } };
|
|
28
|
+
const entries = new Map<string, Entry>();
|
|
29
|
+
const available = (id: string) => {
|
|
30
|
+
const e = entries.get(id);
|
|
31
|
+
if (!options.enabled || !e || Date.now() >= e.q.expires_at) { entries.delete(id); return null; }
|
|
32
|
+
const current = issuer.inspectStoredRequester(e.tokenId, e.userId, e.selection);
|
|
33
|
+
const source = db.get<{ alias: string }>("SELECT alias FROM nodes WHERE node_id=?1 AND network_id=?2", e.q.source_node_id, e.q.network_id);
|
|
34
|
+
if (!("permissions_verified" in current) || source?.alias !== e.q.alias) { entries.delete(id); return null; }
|
|
35
|
+
return e;
|
|
36
|
+
};
|
|
37
|
+
const daemon = (req: Request, e: Entry): string | null => {
|
|
38
|
+
const auth = resolveToken(req.headers.get("authorization")?.match(/^Bearer (\S+)$/)?.[1] ?? "");
|
|
39
|
+
if (!auth?.tokenId || auth.networkId !== e.q.network_id) return null;
|
|
40
|
+
const c = readSessionControlCredential(auth.tokenId), n = resolveNodeCaller(auth.tokenId);
|
|
41
|
+
return c?.scope === "network" && c.bound_node_id === e.q.daemon_node_id
|
|
42
|
+
&& n.ok && n.kind === "node" && n.nodeId === e.q.daemon_node_id && n.networkId === e.q.network_id
|
|
43
|
+
&& canRestWriteNetwork({ userId: c.user_id, networkId: c.network_id }, e.q.network_id, false) ? auth.tokenId : null;
|
|
44
|
+
};
|
|
45
|
+
const api = {
|
|
46
|
+
/** Authenticated admission lookup for the source-aware execution queue only.
|
|
47
|
+
* Reads immutable rows; a caller cannot provide a receipt/binding payload. */
|
|
48
|
+
executionSource(req: Request, admissionId: string) {
|
|
49
|
+
const row = db.get<SessionSourceBinding & { evidence_request_id: string; lease_id: string; recheck_request_id: string; authorized_until: number }>(`SELECT g.*,i.evidence_request_id,i.lease_id,i.recheck_request_id,i.authorized_until
|
|
50
|
+
FROM session_source_admission_intents i JOIN node_create_requests n ON n.request_id=i.create_request_id AND n.source_ref=i.source_ref
|
|
51
|
+
JOIN session_source_grants g ON g.source_ref=n.source_ref AND g.create_request_id=n.request_id
|
|
52
|
+
WHERE n.request_id=?1 AND n.status='source_reserved' AND i.state='reserved' AND g.state='claimed'
|
|
53
|
+
AND g.binding_id=i.recheck_request_id AND g.server_generation='process_local:' || i.lease_id
|
|
54
|
+
AND n.network_id=g.network_id AND n.daemon_node_id=g.daemon_node_id AND n.workdir=g.canonical_directory
|
|
55
|
+
AND i.user_id=g.user_id AND i.network_id=g.network_id
|
|
56
|
+
AND i.execution_guard='daemon_recheck_in_execution_context_required'`, admissionId);
|
|
57
|
+
if (!row || Date.now() >= row.authorized_until) return null;
|
|
58
|
+
const evidence = api.result(req, row.evidence_request_id), e = available(row.evidence_request_id);
|
|
59
|
+
if (!e?.daemonTokenId || !evidence || evidence.lease_id !== row.lease_id || row.user_id !== evidence.request.user_id
|
|
60
|
+
|| row.network_id !== evidence.request.network_id || row.source_node_id !== evidence.request.source_node_id
|
|
61
|
+
|| row.daemon_node_id !== evidence.request.daemon_node_id || row.session_id !== evidence.request.session_id
|
|
62
|
+
|| row.mode !== evidence.request.mode || row.canonical_directory !== evidence.canonical_directory) return null;
|
|
63
|
+
return { evidence, daemonTokenId: e.daemonTokenId, authorized_until: row.authorized_until };
|
|
64
|
+
},
|
|
65
|
+
queue(req: Request, selection: SourceSelection, sessionId: string): SourceReadChallenge | null {
|
|
66
|
+
if (!options.enabled || !/^ses_[A-Za-z0-9]{1,190}$/.test(sessionId)) return null;
|
|
67
|
+
for (const [id, e] of entries) if (Date.now() >= e.q.expires_at) entries.delete(id);
|
|
68
|
+
if (entries.size >= 128 || !("permissions_verified" in issuer.inspect(req, selection))) return null;
|
|
69
|
+
const auth = resolveToken(req.headers.get("authorization")?.match(/^Bearer (\S+)$/)?.[1] ?? "");
|
|
70
|
+
if (!auth?.tokenId) return null;
|
|
71
|
+
const source = db.get<{ alias: string }>("SELECT alias FROM nodes WHERE node_id=?1 AND network_id=?2", selection.source_node_id, selection.network_id);
|
|
72
|
+
if (!source?.alias) return null;
|
|
73
|
+
const q: SourceReadChallenge = { request_id: `srcq_${randomUUID()}`, challenge: randomBytes(32).toString("base64url"),
|
|
74
|
+
network_id: selection.network_id, daemon_node_id: selection.daemon_node_id, source_node_id: selection.source_node_id,
|
|
75
|
+
alias: source.alias, session_id: sessionId, expires_at: Date.now() + 15000,
|
|
76
|
+
user_id: auth.user.user_id, requester_token_id: auth.tokenId, mode: selection.mode };
|
|
77
|
+
entries.set(q.request_id, { q, selection: structuredClone(selection), userId: auth.user.user_id, tokenId: auth.tokenId });
|
|
78
|
+
return structuredClone(q);
|
|
79
|
+
},
|
|
80
|
+
take(req: Request, id: string): SourceReadChallenge | null {
|
|
81
|
+
const e = available(id); if (!e || e.daemonTokenId) return null;
|
|
82
|
+
const tokenId = daemon(req, e); if (!tokenId) return null;
|
|
83
|
+
e.daemonTokenId = tokenId;
|
|
84
|
+
return structuredClone(e.q);
|
|
85
|
+
},
|
|
86
|
+
ack(req: Request, value: unknown): boolean {
|
|
87
|
+
if (!isSourceReadEvidence(value)) return false;
|
|
88
|
+
const e = available(value.request.request_id);
|
|
89
|
+
if (!e || e.evidence || !e.daemonTokenId || daemon(req, e) !== e.daemonTokenId
|
|
90
|
+
|| !sameSourceChallenge(e.q, value.request)) return false;
|
|
91
|
+
e.evidence = structuredClone(value); return true;
|
|
92
|
+
},
|
|
93
|
+
result(req: Request, id: string): SourceReadEvidence | null {
|
|
94
|
+
const e = available(id); if (!e?.evidence) return null;
|
|
95
|
+
const c = e.daemonTokenId ? readSessionControlCredential(e.daemonTokenId) : null;
|
|
96
|
+
const n = e.daemonTokenId ? resolveNodeCaller(e.daemonTokenId) : null;
|
|
97
|
+
if (!c || c.scope !== "network" || c.bound_node_id !== e.q.daemon_node_id || c.network_id !== e.q.network_id
|
|
98
|
+
|| !n?.ok || n.kind !== "node" || n.nodeId !== e.q.daemon_node_id || n.networkId !== e.q.network_id
|
|
99
|
+
|| !canRestWriteNetwork({ userId: c.user_id, networkId: c.network_id }, e.q.network_id, false)) return null;
|
|
100
|
+
const auth = resolveToken(req.headers.get("authorization")?.match(/^Bearer (\S+)$/)?.[1] ?? "");
|
|
101
|
+
return auth?.user.user_id === e.userId && auth.tokenId === e.tokenId ? structuredClone(e.evidence) : null;
|
|
102
|
+
},
|
|
103
|
+
takeRecheck(req: Request, evidenceRequestId: string): SourceLeaseRecheck | null {
|
|
104
|
+
const e = available(evidenceRequestId), r = e?.recheck;
|
|
105
|
+
if (!e || !r || r.taken || Date.now() >= r.q.expires_at || daemon(req, e) !== e.daemonTokenId) return null;
|
|
106
|
+
r.taken = true; return structuredClone(r.q);
|
|
107
|
+
},
|
|
108
|
+
ackRecheck(req: Request, value: unknown): boolean {
|
|
109
|
+
if (!isSourceLeaseConfirmation(value)) return false;
|
|
110
|
+
const e = available(value.request.evidence.request.request_id), r = e?.recheck;
|
|
111
|
+
if (!e || !r || !r.taken || r.confirmed || Date.now() >= r.q.expires_at
|
|
112
|
+
|| daemon(req, e) !== e.daemonTokenId || !sameSourceRecheck(r.q, value.request)) return false;
|
|
113
|
+
r.confirmed = true; return true;
|
|
114
|
+
},
|
|
115
|
+
/** Internal async issuer + admission. dispatchRecheck only wakes the private
|
|
116
|
+
* authenticated pull/ack transport; its return value is never evidence.
|
|
117
|
+
* No await, HTTP, credential mint or SSE occurs in the SQL transaction. */
|
|
118
|
+
async admit(req: Request, id: string, intentId: string, name: string,
|
|
119
|
+
dispatchRecheck: (evidenceRequestId: string) => Promise<void>): Promise<SourceAdmissionReceipt> {
|
|
120
|
+
if (db.dialect !== "sqlite" || db.atomicTransactions !== true || db.transactionalFeaturesRefusal !== null)
|
|
121
|
+
throw Error("source_create_transactions_unsupported");
|
|
122
|
+
if (!/^[A-Za-z0-9_-]{1,200}$/.test(intentId)) throw Error("source_intent_invalid");
|
|
123
|
+
const childName = validateName(name), evidence = api.result(req, id), e = available(id);
|
|
124
|
+
if (!e || !evidence) throw Error("source_evidence_unavailable");
|
|
125
|
+
const r = { q: { request_id: `srcr_${randomUUID()}`, challenge: randomBytes(32).toString("base64url"), evidence,
|
|
126
|
+
intent_id: intentId, child_name: childName, expires_at: Math.min(e.q.expires_at, Date.now() + 5000) }, taken: false, confirmed: false };
|
|
127
|
+
// Persist the intent before awaiting. Conflict is an explicit refusal,
|
|
128
|
+
// including retries with a new evidence request or another queue instance.
|
|
129
|
+
try {
|
|
130
|
+
db.run(`INSERT INTO session_source_admission_intents
|
|
131
|
+
(user_id,network_id,intent_id,evidence_request_id,requester_token_id,child_name,lease_id,recheck_request_id,authorized_until,execution_guard,state)
|
|
132
|
+
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,'daemon_recheck_in_execution_context_required','checking')`,
|
|
133
|
+
[e.userId, e.q.network_id, intentId, id, e.tokenId, childName, evidence.lease_id, r.q.request_id, r.q.expires_at]);
|
|
134
|
+
} catch { throw Error("source_intent_already_associated"); }
|
|
135
|
+
e.recheck = r;
|
|
136
|
+
try {
|
|
137
|
+
await dispatchRecheck(id);
|
|
138
|
+
const revalidate = (): VerifiedSourceCreateContext => {
|
|
139
|
+
const current = api.result(req, id);
|
|
140
|
+
if (entries.get(id) !== e || e.recheck !== r || !r.confirmed || Date.now() >= r.q.expires_at || !current
|
|
141
|
+
|| !sameSourceRecheck(r.q, { ...r.q, evidence: current })) throw Error("source_lease_recheck_required");
|
|
142
|
+
// This is an expiring process-local observation, not durable generation.
|
|
143
|
+
return { requesterTokenId: e.tokenId, binding: { user_id: e.userId, network_id: e.q.network_id,
|
|
144
|
+
daemon_node_id: e.q.daemon_node_id, source_node_id: e.q.source_node_id, session_id: e.q.session_id,
|
|
145
|
+
mode: e.selection.mode, canonical_directory: evidence.canonical_directory,
|
|
146
|
+
binding_id: r.q.request_id, server_generation: `process_local:${evidence.lease_id}` } };
|
|
147
|
+
};
|
|
148
|
+
return db.transaction(() => {
|
|
149
|
+
const context = revalidate(), now = Date.now();
|
|
150
|
+
const row = db.get<{ state: string }>(`SELECT state FROM session_source_admission_intents
|
|
151
|
+
WHERE user_id=?1 AND network_id=?2 AND intent_id=?3 AND evidence_request_id=?4 AND requester_token_id=?5 AND child_name=?6
|
|
152
|
+
AND lease_id=?7 AND recheck_request_id=?8 AND authorized_until=?9
|
|
153
|
+
AND execution_guard='daemon_recheck_in_execution_context_required'`,
|
|
154
|
+
e.userId, e.q.network_id, intentId, id, e.tokenId, childName, evidence.lease_id, r.q.request_id, r.q.expires_at);
|
|
155
|
+
if (row?.state !== "checking") throw Error("source_intent_already_associated");
|
|
156
|
+
const ref = createSessionSourceGrantStore(db).issue(context.binding, now, r.q.expires_at);
|
|
157
|
+
const receipt = createSessionSourceCreateAdapter(db).reserve(ref, childName, revalidate, now);
|
|
158
|
+
db.run(`UPDATE session_source_admission_intents SET state='reserved',source_ref=?1,create_request_id=?2
|
|
159
|
+
WHERE evidence_request_id=?3 AND state='checking'`, [ref, receipt.request_id, id]);
|
|
160
|
+
if (Date.now() >= r.q.expires_at) throw Error("source_lease_expired");
|
|
161
|
+
return { ...receipt, source_ref: ref, scope: "admission_only" as const, intent_id: intentId,
|
|
162
|
+
execution: { protocol: "source-aware-v1-required" as const, guard: "daemon_recheck_in_execution_context_required" as const,
|
|
163
|
+
lease_kind: "process_local_lease" as const, lease_id: evidence.lease_id, evidence_request_id: id,
|
|
164
|
+
recheck_request_id: r.q.request_id, authorized_until: r.q.expires_at, mode: e.selection.mode, dispatchable: false as const } };
|
|
165
|
+
});
|
|
166
|
+
} catch (error) {
|
|
167
|
+
db.run("UPDATE session_source_admission_intents SET state='refused' WHERE evidence_request_id=?1 AND state='checking'", [id]);
|
|
168
|
+
throw error;
|
|
169
|
+
} finally { e.recheck = undefined; }
|
|
170
|
+
},
|
|
171
|
+
/** Historical, read-only lost-response recovery. No lease continuation and
|
|
172
|
+
* deliberately no execution authorization, even while a daemon is live. */
|
|
173
|
+
recoverAdmission(req: Request, selection: SourceSelection, intentId: string) {
|
|
174
|
+
if (!options.enabled || !("permissions_verified" in issuer.inspect(req, selection))) return null;
|
|
175
|
+
const auth = resolveToken(req.headers.get("authorization")?.match(/^Bearer (\S+)$/)?.[1] ?? "");
|
|
176
|
+
if (!auth?.tokenId) return null;
|
|
177
|
+
const row = db.get<SessionSourceBinding & { source_ref: string }>(`SELECT g.* FROM session_source_admission_intents i
|
|
178
|
+
JOIN session_source_grants g ON g.source_ref=i.source_ref AND g.create_request_id=i.create_request_id
|
|
179
|
+
WHERE i.user_id=?1 AND i.network_id=?2 AND i.intent_id=?3 AND i.requester_token_id=?4 AND i.state='reserved'
|
|
180
|
+
AND g.source_node_id=?5 AND g.daemon_node_id=?6 AND g.mode=?7`, auth.user.user_id, selection.network_id, intentId,
|
|
181
|
+
auth.tokenId, selection.source_node_id, selection.daemon_node_id, selection.mode);
|
|
182
|
+
if (!row) return null;
|
|
183
|
+
const receipt = createSessionSourceCreateAdapter(db).recover(row.source_ref, () => {
|
|
184
|
+
if (!("permissions_verified" in issuer.inspect(req, selection))) throw Error("source_auth_required");
|
|
185
|
+
return { requesterTokenId: auth.tokenId!, binding: row };
|
|
186
|
+
});
|
|
187
|
+
return receipt ? { ...receipt, scope: "historical_admission_only" as const, execution: "not_authorized" as const, dispatchable: false as const } : null;
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
return api;
|
|
191
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { db } from "./db";
|
|
3
|
+
import { resolveToken } from "./auth";
|
|
4
|
+
import { readSessionControlCredential } from "./node-session-control";
|
|
5
|
+
import { resolveNodeCaller } from "./create-node";
|
|
6
|
+
import { canRestWriteNetwork } from "./network-scope";
|
|
7
|
+
import { createSessionSourceIssuer } from "./session-source-issuer";
|
|
8
|
+
import type { createSessionSourceEvidenceQueue } from "./session-source-evidence";
|
|
9
|
+
import { isSourceExecutionTask, isSourceExecutionResult, type SourceExecutionTask, type SourceExecutionResult } from "./contracts/session-source-execution";
|
|
10
|
+
|
|
11
|
+
type Row = { execution_id: string; admission_request_id: string; task_json: string; user_id: string;
|
|
12
|
+
requester_token_id: string; daemon_token_id: string; state: string; result_json: string | null };
|
|
13
|
+
const auth = (req: Request) => resolveToken(req.headers.get("authorization")?.match(/^Bearer (\S+)$/)?.[1] ?? "");
|
|
14
|
+
/** Separate source-aware journal. No mutation of source_reserved, no ordinary
|
|
15
|
+
* daemon event/fallback. Constructor remains opt-in and no endpoints register. */
|
|
16
|
+
export function createSessionSourceExecutionQueue(evidenceQueue: ReturnType<typeof createSessionSourceEvidenceQueue>, options: { enabled?: boolean } = {}) {
|
|
17
|
+
const issuer = createSessionSourceIssuer();
|
|
18
|
+
const row = (id: string) => db.get<Row>("SELECT * FROM session_source_executions WHERE execution_id=?1", id);
|
|
19
|
+
const task = (r: Row): SourceExecutionTask | null => {
|
|
20
|
+
try { const v = JSON.parse(r.task_json); return isSourceExecutionTask(v) ? v : null; } catch { return null; }
|
|
21
|
+
};
|
|
22
|
+
const permissions = (r: Row, t: SourceExecutionTask) => {
|
|
23
|
+
const q = t.evidence.request;
|
|
24
|
+
return "permissions_verified" in issuer.inspectStoredRequester(r.requester_token_id, r.user_id,
|
|
25
|
+
{ network_id: q.network_id, daemon_node_id: q.daemon_node_id, source_node_id: q.source_node_id, mode: q.mode });
|
|
26
|
+
};
|
|
27
|
+
const daemon = (req: Request, r: Row, t: SourceExecutionTask) => {
|
|
28
|
+
const a = auth(req), c = a?.tokenId ? readSessionControlCredential(a.tokenId) : null;
|
|
29
|
+
const n = a?.tokenId ? resolveNodeCaller(a.tokenId) : null, q = t.evidence.request;
|
|
30
|
+
return a?.tokenId === r.daemon_token_id && c?.bound_node_id === q.daemon_node_id && c.network_id === q.network_id
|
|
31
|
+
&& c.scope === "network" && n?.ok && n.kind === "node" && n.nodeId === q.daemon_node_id && n.networkId === q.network_id
|
|
32
|
+
&& canRestWriteNetwork({ userId: c.user_id, networkId: c.network_id }, q.network_id, false);
|
|
33
|
+
};
|
|
34
|
+
return {
|
|
35
|
+
deliverySource(req: Request, id: string) {
|
|
36
|
+
if (!options.enabled) return null;
|
|
37
|
+
const r = row(id), t = r ? task(r) : null, a = auth(req);
|
|
38
|
+
if (!r || !t || !r.result_json || r.state !== "session_ready" || a?.tokenId !== r.requester_token_id
|
|
39
|
+
|| a.user.user_id !== r.user_id || !permissions(r, t)) return null;
|
|
40
|
+
const v = JSON.parse(r.result_json);
|
|
41
|
+
if (!isSourceExecutionResult(v, t) || v.status !== "session_ready") return null;
|
|
42
|
+
if (!evidenceQueue.executionSource(req, r.admission_request_id)) return null;
|
|
43
|
+
const intent = db.get<{ child_name: string }>("SELECT child_name FROM session_source_admission_intents WHERE create_request_id=?1 AND state='reserved'", r.admission_request_id);
|
|
44
|
+
return intent ? { task: t, result: v, child_name: intent.child_name, daemonTokenId: r.daemon_token_id } : null;
|
|
45
|
+
},
|
|
46
|
+
queue(req: Request, admissionId: string): string | null {
|
|
47
|
+
if (!options.enabled || db.dialect !== "sqlite" || db.atomicTransactions !== true) return null;
|
|
48
|
+
const source = evidenceQueue.executionSource(req, admissionId), a = auth(req);
|
|
49
|
+
if (!source || !a?.tokenId) return null;
|
|
50
|
+
const t: SourceExecutionTask = { execution_id: `srcx_${randomUUID()}`, admission_request_id: admissionId,
|
|
51
|
+
evidence: source.evidence, authorized_until: source.authorized_until, owner_policy: "retain_existing_bridge_only" };
|
|
52
|
+
try {
|
|
53
|
+
db.run(`INSERT INTO session_source_executions (execution_id,admission_request_id,task_json,user_id,requester_token_id,daemon_token_id,state)
|
|
54
|
+
VALUES (?1,?2,?3,?4,?5,?6,'pending')`, [t.execution_id, admissionId, JSON.stringify(t), a.user.user_id, a.tokenId, source.daemonTokenId]);
|
|
55
|
+
return t.execution_id;
|
|
56
|
+
} catch { return null; } // one execution association per immutable admission
|
|
57
|
+
},
|
|
58
|
+
take(req: Request, id: string): SourceExecutionTask | null {
|
|
59
|
+
if (!options.enabled) return null;
|
|
60
|
+
return db.transaction(() => {
|
|
61
|
+
const r = row(id), t = r ? task(r) : null;
|
|
62
|
+
if (!r || !t || r.state !== "pending" || Date.now() >= t.authorized_until || !daemon(req, r, t) || !permissions(r, t)) return null;
|
|
63
|
+
// Durable BEFORE any daemon API. Lost delivery never permits re-take.
|
|
64
|
+
if (db.run("UPDATE session_source_executions SET state='claimed' WHERE execution_id=?1 AND state='pending'", [id]).changes !== 1) return null;
|
|
65
|
+
return structuredClone(t);
|
|
66
|
+
});
|
|
67
|
+
},
|
|
68
|
+
ack(req: Request, value: unknown): boolean {
|
|
69
|
+
if (!options.enabled || !value || typeof value !== "object") return false;
|
|
70
|
+
const r = row((value as any).execution_id), t = r ? task(r) : null;
|
|
71
|
+
if (!r || !t || !isSourceExecutionResult(value, t) || !daemon(req, r, t)) return false;
|
|
72
|
+
// Completion may arrive after observation expiry. Record an outcome, not
|
|
73
|
+
// authorization; it cannot dispatch another operation or regain a lease.
|
|
74
|
+
return db.run(`UPDATE session_source_executions SET state=?1,session_id=?2,result_json=?3
|
|
75
|
+
WHERE execution_id=?4 AND state='claimed'`, [value.status, value.session_id ?? null, JSON.stringify(value), r.execution_id]).changes === 1;
|
|
76
|
+
},
|
|
77
|
+
recover(req: Request, id: string): SourceExecutionResult | null {
|
|
78
|
+
if (!options.enabled) return null;
|
|
79
|
+
const r = row(id), t = r ? task(r) : null, a = auth(req);
|
|
80
|
+
if (!r || !t || a?.tokenId !== r.requester_token_id || a.user.user_id !== r.user_id || !permissions(r, t)) return null;
|
|
81
|
+
if (r.result_json) { const v = JSON.parse(r.result_json); return isSourceExecutionResult(v, t) ? v : null; }
|
|
82
|
+
// Read-only uncertain outcome: no reset, requeue or second POST, including
|
|
83
|
+
// after Hub process restart. Claimed state itself permanently blocks take.
|
|
84
|
+
return r.state === "claimed" ? { execution_id: id, admission_request_id: r.admission_request_id, status: "unknown", bridge: "not_created" } : null;
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
import { Database } from "bun:sqlite";
|
|
3
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { SQLiteAdapter } from "./db-adapter";
|
|
7
|
+
import type { DbAdapter } from "./db-adapter";
|
|
8
|
+
import { createSessionSourceGrantStore, sessionSourceGrantSchema, type SessionSourceBinding } from "./session-source-grant";
|
|
9
|
+
|
|
10
|
+
test("source grant binds every authority dimension and claims once across connections and reopen", () => {
|
|
11
|
+
const root = mkdtempSync(join(tmpdir(), "source4150-")), file = join(root, "grants.db");
|
|
12
|
+
const a = new SQLiteAdapter(new Database(file));
|
|
13
|
+
let b = new SQLiteAdapter(new Database(file));
|
|
14
|
+
try {
|
|
15
|
+
a.exec(sessionSourceGrantSchema);
|
|
16
|
+
const first = createSessionSourceGrantStore(a), second = createSessionSourceGrantStore(b);
|
|
17
|
+
const source: SessionSourceBinding = { user_id: "user_a", network_id: "net_a", source_node_id: "node_source",
|
|
18
|
+
daemon_node_id: "daemon_a", session_id: "ses_Source", binding_id: "binding_a",
|
|
19
|
+
server_generation: "generation_proof_a", canonical_directory: "/workspace/source", mode: "attach_existing" };
|
|
20
|
+
const ref = first.issue(source, 1000, 2000);
|
|
21
|
+
expect(ref).toMatch(/^src_[A-Za-z0-9_-]{43}$/);
|
|
22
|
+
expect(first.claimedRequest(ref, source)).toBeNull();
|
|
23
|
+
for (const field of Object.keys(source) as (keyof SessionSourceBinding)[]) {
|
|
24
|
+
const changed = { ...source, [field]: field === "mode" ? "fork_independent" : `${source[field]}_other` };
|
|
25
|
+
expect(second.claim(ref, changed as SessionSourceBinding, "cr_wrong", 1500)).toBe(false);
|
|
26
|
+
}
|
|
27
|
+
expect(second.claim(ref, source, "cr_early", 999)).toBe(false);
|
|
28
|
+
expect(second.claim(ref, source, "cr_expired", 2000)).toBe(false);
|
|
29
|
+
expect(first.claim(ref, source, "cr_first", 1500)).toBe(true);
|
|
30
|
+
expect(second.claimedRequest(ref, source)).toBe("cr_first");
|
|
31
|
+
for (const field of Object.keys(source) as (keyof SessionSourceBinding)[]) {
|
|
32
|
+
const changed = { ...source, [field]: field === "mode" ? "fork_independent" : `${source[field]}_other` };
|
|
33
|
+
expect(second.claimedRequest(ref, changed as SessionSourceBinding)).toBeNull();
|
|
34
|
+
}
|
|
35
|
+
expect(second.claim(ref, source, "cr_second", 1500)).toBe(false);
|
|
36
|
+
expect(second.claim(ref, source, "cr_first", 1500)).toBe(false);
|
|
37
|
+
b.close(); b = new SQLiteAdapter(new Database(file));
|
|
38
|
+
expect(createSessionSourceGrantStore(b).claimedRequest(ref, source)).toBe("cr_first");
|
|
39
|
+
expect(createSessionSourceGrantStore(b).claim(ref, source, "cr_late_replay", 3000)).toBe(false);
|
|
40
|
+
expect(createSessionSourceGrantStore(b).claimedRequest(ref, source)).toBe("cr_first");
|
|
41
|
+
expect(createSessionSourceGrantStore(b).claim(ref, source, "cr_after_restart", 1500)).toBe(false);
|
|
42
|
+
const other = first.issue(source, 1000, 2000);
|
|
43
|
+
expect(first.claim(other, source, "cr_first", 1500)).toBe(false);
|
|
44
|
+
expect(first.revoke(other)).toBe(true);
|
|
45
|
+
expect(first.claimedRequest(other, source)).toBeNull();
|
|
46
|
+
expect(first.claim(other, source, "cr_revoked", 1500)).toBe(false);
|
|
47
|
+
expect(first.revoke(ref)).toBe(false);
|
|
48
|
+
expect(() => first.issue(source, 1000, 61_001)).toThrow("session_source_grant_invalid");
|
|
49
|
+
expect(() => first.issue({ ...source, canonical_directory: "bad\npath" }, 1000, 2000)).toThrow();
|
|
50
|
+
expect(() => first.issue({ ...source, session_id: "latest" }, 1000, 2000)).toThrow();
|
|
51
|
+
expect(first.claim("not_a_ref", source, "cr_test", 1500)).toBe(false);
|
|
52
|
+
expect(first.claimedRequest("not_a_ref", source)).toBeNull();
|
|
53
|
+
const forkSource = { ...source, mode: "fork_independent" as const };
|
|
54
|
+
const forkRef = first.issue(forkSource, 1000, 2000);
|
|
55
|
+
const reopened = createSessionSourceGrantStore(b);
|
|
56
|
+
expect(reopened.claim(forkRef, forkSource, "cr_fork", 1500)).toBe(true);
|
|
57
|
+
expect(reopened.claim(forkRef, forkSource, "cr_fork", 1500)).toBe(false);
|
|
58
|
+
} finally { a.close(); b.close(); rmSync(root, { recursive: true, force: true }); }
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test("source grants refuse unsupported adapters before issuing any SQL", () => {
|
|
62
|
+
const db = { dialect: "postgres", transactionalFeaturesRefusal: null,
|
|
63
|
+
run: () => { throw Error("SQL must not execute"); } } as unknown as DbAdapter;
|
|
64
|
+
const store = createSessionSourceGrantStore(db);
|
|
65
|
+
const source: SessionSourceBinding = { user_id: "u", network_id: "n", source_node_id: "s", daemon_node_id: "d",
|
|
66
|
+
session_id: "ses_Source", binding_id: "b", server_generation: "g", canonical_directory: "/work", mode: "attach_existing" };
|
|
67
|
+
expect(() => store.issue(source, 1000, 2000)).toThrow("session_source_grant_invalid");
|
|
68
|
+
expect(store.claim(`src_${"a".repeat(43)}`, source, "cr_test", 1500)).toBe(false);
|
|
69
|
+
expect(store.revoke(`src_${"a".repeat(43)}`)).toBe(false);
|
|
70
|
+
expect(store.claimedRequest(`src_${"a".repeat(43)}`, source)).toBeNull();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test("source grants require affirmative atomic transaction support", () => {
|
|
74
|
+
const source: SessionSourceBinding = { user_id: "u", network_id: "n", source_node_id: "s", daemon_node_id: "d",
|
|
75
|
+
session_id: "ses_Source", binding_id: "b", server_generation: "g", canonical_directory: "/work", mode: "attach_existing" };
|
|
76
|
+
for (const atomicTransactions of [false, undefined]) {
|
|
77
|
+
const db = { dialect: "sqlite", atomicTransactions, transactionalFeaturesRefusal: null,
|
|
78
|
+
run: () => { throw Error("SQL must not execute"); } } as unknown as DbAdapter;
|
|
79
|
+
const store = createSessionSourceGrantStore(db);
|
|
80
|
+
expect(() => store.issue(source, 1000, 2000)).toThrow("session_source_grant_invalid");
|
|
81
|
+
expect(store.claim(`src_${"a".repeat(43)}`, source, "cr_test", 1500)).toBe(false);
|
|
82
|
+
expect(store.revoke(`src_${"a".repeat(43)}`)).toBe(false);
|
|
83
|
+
expect(store.claimedRequest(`src_${"a".repeat(43)}`, source)).toBeNull();
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test("source claim composes with same-connection intent insertion without partial admission", () => {
|
|
88
|
+
const db = new SQLiteAdapter(new Database(":memory:"));
|
|
89
|
+
try {
|
|
90
|
+
db.exec(sessionSourceGrantSchema);
|
|
91
|
+
// Storage composition fixture, NOT the production create-node adapter.
|
|
92
|
+
db.exec("CREATE TABLE admission_fixture (request_id TEXT PRIMARY KEY, name TEXT NOT NULL UNIQUE)");
|
|
93
|
+
const store = createSessionSourceGrantStore(db);
|
|
94
|
+
const source: SessionSourceBinding = { user_id: "u", network_id: "n", source_node_id: "s", daemon_node_id: "d",
|
|
95
|
+
session_id: "ses_Source", binding_id: "b", server_generation: "g", canonical_directory: "/work", mode: "attach_existing" };
|
|
96
|
+
const ref = store.issue(source, 1000, 2000);
|
|
97
|
+
db.run("INSERT INTO admission_fixture VALUES (?1,?2)", ["cr_existing", "taken"]);
|
|
98
|
+
expect(() => db.transaction(() => {
|
|
99
|
+
expect(store.claim(ref, source, "cr_new", 1500)).toBe(true);
|
|
100
|
+
db.run("INSERT INTO admission_fixture VALUES (?1,?2)", ["cr_new", "taken"]);
|
|
101
|
+
})).toThrow();
|
|
102
|
+
expect(db.get("SELECT state,create_request_id FROM session_source_grants WHERE source_ref=?1", ref))
|
|
103
|
+
.toEqual({ state: "issued", create_request_id: null });
|
|
104
|
+
expect(db.get("SELECT request_id FROM admission_fixture WHERE request_id=?1", "cr_new")).toBeNull();
|
|
105
|
+
db.transaction(() => {
|
|
106
|
+
expect(store.claim(ref, source, "cr_new", 1500)).toBe(true);
|
|
107
|
+
db.run("INSERT INTO admission_fixture VALUES (?1,?2)", ["cr_new", "available"]);
|
|
108
|
+
});
|
|
109
|
+
expect(db.get("SELECT state,create_request_id FROM session_source_grants WHERE source_ref=?1", ref))
|
|
110
|
+
.toEqual({ state: "claimed", create_request_id: "cr_new" });
|
|
111
|
+
expect(db.get("SELECT request_id FROM admission_fixture WHERE request_id=?1", "cr_new"))
|
|
112
|
+
.toEqual({ request_id: "cr_new" });
|
|
113
|
+
// A lost response after commit must not reopen the grant or replay creation.
|
|
114
|
+
expect(store.claim(ref, source, "cr_new", 1500)).toBe(false);
|
|
115
|
+
expect(db.get<{ count: number }>("SELECT count(*) AS count FROM admission_fixture")?.count).toBe(2);
|
|
116
|
+
} finally { db.close(); }
|
|
117
|
+
});
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import type { DbAdapter } from "./db-adapter";
|
|
3
|
+
|
|
4
|
+
/** Internal storage only. No HTTP/MCP issuer is enabled. A caller must obtain
|
|
5
|
+
* these fields from authenticated live daemon evidence, not client input, and
|
|
6
|
+
* independently enforce create_node and source-session access on every claim. */
|
|
7
|
+
export type SessionSourceBinding = {
|
|
8
|
+
user_id: string; network_id: string; source_node_id: string; daemon_node_id: string;
|
|
9
|
+
session_id: string; binding_id: string; server_generation: string; canonical_directory: string;
|
|
10
|
+
mode: "attach_existing" | "fork_independent";
|
|
11
|
+
};
|
|
12
|
+
// server_generation is a legacy storage key, NOT automatically incarnation
|
|
13
|
+
// proof. Internal async admission uses process_local:<opaque lease> explicitly;
|
|
14
|
+
// such grants only reserve admission, never authorize daemon execution/restart.
|
|
15
|
+
const fields = ["user_id", "network_id", "source_node_id", "daemon_node_id", "session_id",
|
|
16
|
+
"binding_id", "server_generation", "canonical_directory", "mode"] as const;
|
|
17
|
+
export const sessionSourceGrantSchema = `CREATE TABLE IF NOT EXISTS session_source_grants (
|
|
18
|
+
source_ref TEXT PRIMARY KEY,
|
|
19
|
+
user_id TEXT NOT NULL, network_id TEXT NOT NULL, source_node_id TEXT NOT NULL,
|
|
20
|
+
daemon_node_id TEXT NOT NULL, session_id TEXT NOT NULL, binding_id TEXT NOT NULL,
|
|
21
|
+
server_generation TEXT NOT NULL, canonical_directory TEXT NOT NULL, mode TEXT NOT NULL
|
|
22
|
+
CHECK(mode IN ('attach_existing','fork_independent')),
|
|
23
|
+
issued_at INTEGER NOT NULL, expires_at INTEGER NOT NULL,
|
|
24
|
+
state TEXT NOT NULL CHECK(state IN ('issued','claimed','revoked')),
|
|
25
|
+
create_request_id TEXT UNIQUE
|
|
26
|
+
);`;
|
|
27
|
+
|
|
28
|
+
const valid = (b: SessionSourceBinding) => fields.every(f => typeof b[f] === "string"
|
|
29
|
+
&& b[f].length > 0 && b[f].length <= (f === "canonical_directory" ? 4096 : 200)
|
|
30
|
+
&& !/[\x00-\x1f\x7f]/.test(b[f])) && /^ses_[A-Za-z0-9]+$/.test(b.session_id)
|
|
31
|
+
&& (b.mode === "attach_existing" || b.mode === "fork_independent");
|
|
32
|
+
const refValid = (ref: string) => /^src_[A-Za-z0-9_-]{43}$/.test(ref);
|
|
33
|
+
|
|
34
|
+
export function createSessionSourceGrantStore(db: DbAdapter) {
|
|
35
|
+
const supported = () => db.dialect === "sqlite" && db.atomicTransactions === true
|
|
36
|
+
&& db.transactionalFeaturesRefusal === null;
|
|
37
|
+
return {
|
|
38
|
+
issue(binding: SessionSourceBinding, now: number, expiresAt: number): string {
|
|
39
|
+
if (!supported() || !valid(binding) || !Number.isSafeInteger(now) || now < 0
|
|
40
|
+
|| !Number.isSafeInteger(expiresAt) || expiresAt <= now || expiresAt - now > 60_000) {
|
|
41
|
+
throw Error("session_source_grant_invalid");
|
|
42
|
+
}
|
|
43
|
+
const ref = `src_${randomBytes(32).toString("base64url")}`;
|
|
44
|
+
db.run(`INSERT INTO session_source_grants (source_ref,${fields.join(",")},issued_at,expires_at,state)
|
|
45
|
+
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,'issued')`,
|
|
46
|
+
[ref, ...fields.map(f => binding[f]), now, expiresAt]);
|
|
47
|
+
return ref;
|
|
48
|
+
},
|
|
49
|
+
/** CAS consumes before dispatch; never unclaim on timeout/ACK loss. An
|
|
50
|
+
* identical retry is also refused: recover the creation receipt separately.
|
|
51
|
+
* Binding must be freshly revalidated at launch, not just when issued. */
|
|
52
|
+
claim(ref: string, binding: SessionSourceBinding, createRequestId: string, now: number): boolean {
|
|
53
|
+
if (!supported() || !refValid(ref) || !valid(binding) || !Number.isSafeInteger(now)
|
|
54
|
+
|| !/^cr_[A-Za-z0-9_-]{1,190}$/.test(createRequestId)) return false;
|
|
55
|
+
return db.run(`UPDATE session_source_grants SET state='claimed',create_request_id=?1
|
|
56
|
+
WHERE source_ref=?2 AND state='issued' AND issued_at<=?3 AND expires_at>?3
|
|
57
|
+
AND ${fields.map((f, i) => `${f}=?${i + 4}`).join(" AND ")}
|
|
58
|
+
AND NOT EXISTS (SELECT 1 FROM session_source_grants WHERE create_request_id=?1)`,
|
|
59
|
+
[createRequestId, ref, now, ...fields.map(f => binding[f])]).changes === 1;
|
|
60
|
+
},
|
|
61
|
+
/** Read-only recovery after a lost admission response, including after the
|
|
62
|
+
* grant deadline. The caller must reauthenticate and reauthorize access;
|
|
63
|
+
* possession of ref or a client-supplied binding is not authority. This ID
|
|
64
|
+
* is not creation/launch success and must never cause a second dispatch. */
|
|
65
|
+
claimedRequest(ref: string, binding: SessionSourceBinding): string | null {
|
|
66
|
+
if (!supported() || !refValid(ref) || !valid(binding)) return null;
|
|
67
|
+
const row = db.get<{ create_request_id: string | null }>(
|
|
68
|
+
`SELECT create_request_id FROM session_source_grants WHERE source_ref=?1 AND state='claimed'
|
|
69
|
+
AND ${fields.map((f, i) => `${f}=?${i + 2}`).join(" AND ")}`,
|
|
70
|
+
ref, ...fields.map(f => binding[f]));
|
|
71
|
+
return row?.create_request_id ?? null;
|
|
72
|
+
},
|
|
73
|
+
revoke(ref: string): boolean {
|
|
74
|
+
if (!supported() || !refValid(ref)) return false;
|
|
75
|
+
return db.run(`UPDATE session_source_grants SET state='revoked' WHERE source_ref=?1 AND state='issued'`, [ref]).changes === 1;
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
}
|