@zieglar/pi-chat-exchange 0.3.4 → 0.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/bin/mcp-stdio.js +21 -12
- package/dist/control/mcp/endpoint-discovery.js +2 -1
- package/dist/control/mcp/http-transport.js +48 -0
- package/dist/control/mcp/messaging-tools.js +9 -5
- package/dist/control/mcp/server.js +36 -4
- package/dist/host/bound-endpoint.js +5 -2
- package/dist/host/endpoint-host.js +51 -3
- package/dist/runtime/private-unix-socket.js +51 -0
- package/dist/storage/creation.js +14 -2
- package/dist/storage/messaging.js +142 -3
- package/dist/storage/migration.js +17 -1
- package/dist/storage/ownership.js +10 -0
- package/dist/storage/schema.js +2 -1
- package/dist/storage/store.js +15 -9
- package/dist/storage/task-association-schema.js +71 -0
- package/dist/storage/transaction.js +11 -2
- package/dist/tunnel/background-manager.js +54 -1
- package/dist/tunnel/background-scope.js +18 -2
- package/dist/tunnel/live-mcp-composition.js +16 -4
- package/dist/tunnel/live-session-policy.js +27 -4
- package/package.json +1 -1
- package/pi-extension/index.ts +88 -2
- package/pi-extension/native-inbound.ts +2 -0
- package/pi-extension/session-onboarding.ts +5 -1
|
@@ -76,25 +76,164 @@ function requireStableSender(tx, participantId, endpoint) {
|
|
|
76
76
|
/** Session-authorized durable send. Authorization, replay, admission, Message,
|
|
77
77
|
* idempotency, and audit all serialize in one IMMEDIATE transaction. */
|
|
78
78
|
export function sendMessage(store, input, seams = {}) {
|
|
79
|
-
const fields = captureFields(input, ["participantId", "sessionId", "fencingToken", "capability", "message"], ["participantId", "sessionId", "fencingToken", "capability", "message"], "request");
|
|
79
|
+
const fields = captureFields(input, ["participantId", "sessionId", "fencingToken", "capability", "message", "association"], ["participantId", "sessionId", "fencingToken", "capability", "message"], "request");
|
|
80
80
|
const authority = authorityRequest(fields);
|
|
81
81
|
const request = normalizeCreateMessageRequest(fields.message);
|
|
82
|
+
let association;
|
|
83
|
+
if (fields.association !== undefined) {
|
|
84
|
+
const a = captureFields(fields.association, ["requestMessageId", "policyId", "selectionVersion", "targetRuntimeSessionId", "bindingEpoch"], [], "association");
|
|
85
|
+
if (a.policyId !== undefined)
|
|
86
|
+
requireText(a.policyId, "policyId", 256);
|
|
87
|
+
if (a.requestMessageId !== undefined && (typeof a.requestMessageId !== "string" || !MESSAGE_ID_PATTERN.test(a.requestMessageId)))
|
|
88
|
+
throw new ParticipantRequestError("invalid request Message ID");
|
|
89
|
+
if (a.selectionVersion !== undefined && (!Number.isSafeInteger(a.selectionVersion) || a.selectionVersion < 1))
|
|
90
|
+
throw new ParticipantRequestError("invalid selection version");
|
|
91
|
+
if (a.targetRuntimeSessionId !== undefined && (typeof a.targetRuntimeSessionId !== "string" || a.targetRuntimeSessionId.length < 1 || a.targetRuntimeSessionId.length > 256))
|
|
92
|
+
throw new ParticipantRequestError("invalid target session");
|
|
93
|
+
if (a.bindingEpoch !== undefined && (!Number.isSafeInteger(a.bindingEpoch) || a.bindingEpoch < 1))
|
|
94
|
+
throw new ParticipantRequestError("invalid binding epoch");
|
|
95
|
+
association = a;
|
|
96
|
+
}
|
|
82
97
|
return runMessagingTransaction(store, "Authorized Message send", (tx) => {
|
|
83
98
|
// Sample only after BEGIN IMMEDIATE owns the writer lock.
|
|
84
99
|
const now = clock(seams);
|
|
85
100
|
authorizeCurrentOwner(tx, store, { ...authority, scope: "send", now });
|
|
86
|
-
requireMembership(tx, request.exchangeId, authority.participantId);
|
|
101
|
+
const membership = requireMembership(tx, request.exchangeId, authority.participantId);
|
|
87
102
|
requireStableSender(tx, authority.participantId, request.from);
|
|
103
|
+
if (association?.requestMessageId !== undefined) {
|
|
104
|
+
const original = readMessageMetadataInTransaction(tx, request.exchangeId, association.requestMessageId);
|
|
105
|
+
if (!original || original.from.adapter !== request.to.adapter || original.from.endpointId !== request.to.endpointId ||
|
|
106
|
+
original.to.adapter !== request.from.adapter || original.to.endpointId !== request.from.endpointId ||
|
|
107
|
+
messageCreatedAuditSequence(tx, original) <= membership.joinBoundarySeq)
|
|
108
|
+
refuse("MESSAGE_READ_REJECTED");
|
|
109
|
+
const originalLink = tx.prepare("SELECT request_message_id, target_owner_session_id, target_owner_fencing_token FROM message_association WHERE exchange_id=? AND message_id=?").get(request.exchangeId, original.messageId);
|
|
110
|
+
if (!originalLink || originalLink.request_message_id !== original.messageId || originalLink.target_owner_session_id !== authority.sessionId || originalLink.target_owner_fencing_token !== authority.fencingToken)
|
|
111
|
+
refuse("MESSAGE_READ_REJECTED");
|
|
112
|
+
}
|
|
113
|
+
const targetOwner = tx.prepare("SELECT p.participant_id, o.session_id, o.fencing_token, o.expires_at, o.lease_started_at FROM participant p JOIN participant_ownership o ON o.participant_id=p.participant_id JOIN exchange_membership m ON m.participant_id=p.participant_id WHERE p.endpoint_adapter=? AND p.endpoint_id=? AND m.exchange_id=?").get(request.to.adapter, request.to.endpointId, request.exchangeId);
|
|
114
|
+
const ownerActive = targetOwner && typeof targetOwner.session_id === "string" && typeof targetOwner.fencing_token === "number" &&
|
|
115
|
+
typeof targetOwner.expires_at === "string" && typeof targetOwner.lease_started_at === "string" && targetOwner.lease_started_at <= now && now < targetOwner.expires_at;
|
|
116
|
+
if (association?.selectionVersion !== undefined && !ownerActive)
|
|
117
|
+
refuse("MESSAGE_READ_REJECTED");
|
|
118
|
+
if (association?.selectionVersion !== undefined) {
|
|
119
|
+
const binding = tx.prepare("SELECT runtime_session_id, binding_epoch FROM native_session_binding WHERE participant_id=? AND session_id=? AND fencing_token=?").get(targetOwner.participant_id, targetOwner.session_id, targetOwner.fencing_token);
|
|
120
|
+
if (!binding || binding.runtime_session_id !== association.targetRuntimeSessionId || binding.binding_epoch !== association.bindingEpoch)
|
|
121
|
+
refuse("MESSAGE_READ_REJECTED");
|
|
122
|
+
if (!association.policyId)
|
|
123
|
+
refuse("MESSAGE_READ_REJECTED");
|
|
124
|
+
const selection = tx.prepare("SELECT participant_id, session_id, fencing_token, runtime_session_id, binding_epoch FROM selected_session_binding WHERE policy_id=? AND selection_version=?").get(association.policyId, association.selectionVersion);
|
|
125
|
+
if (!selection || selection.participant_id !== targetOwner.participant_id || selection.session_id !== targetOwner.session_id || selection.fencing_token !== targetOwner.fencing_token || selection.runtime_session_id !== association.targetRuntimeSessionId || selection.binding_epoch !== association.bindingEpoch)
|
|
126
|
+
refuse("MESSAGE_READ_REJECTED");
|
|
127
|
+
}
|
|
128
|
+
const targetBinding = ownerActive ? tx.prepare("SELECT runtime_session_id, binding_epoch FROM native_session_binding WHERE participant_id=? AND session_id=? AND fencing_token=?").get(targetOwner.participant_id, targetOwner.session_id, targetOwner.fencing_token) : undefined;
|
|
129
|
+
const effectiveAssociation = { ...association,
|
|
130
|
+
...(association?.selectionVersion === undefined && targetBinding && typeof targetBinding.runtime_session_id === "string" && typeof targetBinding.binding_epoch === "number" ? { targetRuntimeSessionId: targetBinding.runtime_session_id, bindingEpoch: targetBinding.binding_epoch } : {}),
|
|
131
|
+
...(ownerActive ? { targetOwnerSessionId: targetOwner.session_id, targetOwnerFencingToken: targetOwner.fencing_token } : {}) };
|
|
88
132
|
const time = Date.parse(now);
|
|
89
133
|
const transaction = createMessageInTransaction(tx, request, {
|
|
90
134
|
messageId: generateEntityId("msg_", time),
|
|
91
135
|
eventId: generateEntityId("evt_", time),
|
|
92
136
|
createdAt: now,
|
|
93
|
-
}, seams);
|
|
137
|
+
}, seams, effectiveAssociation);
|
|
94
138
|
const auditSequence = messageCreatedAuditSequence(tx, transaction.creation.message);
|
|
95
139
|
return Object.freeze({ ...transaction.creation, auditSequence });
|
|
96
140
|
});
|
|
97
141
|
}
|
|
142
|
+
/** Persist the Pi runtime's own registration against its current CE ownership. */
|
|
143
|
+
export function bindNativeSession(store, input, seams = {}) {
|
|
144
|
+
const fields = captureFields(input, ["participantId", "sessionId", "fencingToken", "capability", "runtimeSessionId", "bindingEpoch"], ["participantId", "sessionId", "fencingToken", "capability", "runtimeSessionId", "bindingEpoch"], "request");
|
|
145
|
+
const authority = authorityRequest(fields);
|
|
146
|
+
const runtimeSessionId = requireText(fields.runtimeSessionId, "runtimeSessionId", 256);
|
|
147
|
+
if (!Number.isSafeInteger(fields.bindingEpoch) || fields.bindingEpoch < 1)
|
|
148
|
+
throw new ParticipantRequestError("invalid binding epoch");
|
|
149
|
+
runMessagingTransaction(store, "Native Session binding", tx => {
|
|
150
|
+
authorizeCurrentOwner(tx, store, { ...authority, scope: "send", now: clock(seams) });
|
|
151
|
+
const row = tx.prepare("SELECT runtime_session_id, binding_epoch FROM native_session_binding WHERE participant_id=? AND session_id=? AND fencing_token=?").get(authority.participantId, authority.sessionId, authority.fencingToken);
|
|
152
|
+
if (row !== undefined) {
|
|
153
|
+
if (row.runtime_session_id !== runtimeSessionId || row.binding_epoch !== fields.bindingEpoch)
|
|
154
|
+
refuse("MESSAGE_READ_REJECTED");
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
tx.prepare("INSERT INTO native_session_binding(participant_id,session_id,fencing_token,runtime_session_id,binding_epoch) VALUES (?,?,?,?,?)").run(authority.participantId, authority.sessionId, authority.fencingToken, runtimeSessionId, fields.bindingEpoch);
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
/** Freeze the target owner observed while a policy selection is committed. */
|
|
161
|
+
export function bindSelectedSession(store, input, seams = {}) {
|
|
162
|
+
const keys = ["participantId", "sessionId", "fencingToken", "capability", "exchangeId", "endpointId", "policyId", "selectionVersion", "runtimeSessionId", "bindingEpoch"];
|
|
163
|
+
const fields = captureFields(input, keys, keys, "request");
|
|
164
|
+
const authority = authorityRequest(fields);
|
|
165
|
+
const exchangeId = requireText(fields.exchangeId, "exchangeId", 29);
|
|
166
|
+
const endpointId = requireText(fields.endpointId, "endpointId", 256);
|
|
167
|
+
const policyId = requireText(fields.policyId, "policyId", 256);
|
|
168
|
+
const runtime = requireText(fields.runtimeSessionId, "runtimeSessionId", 256);
|
|
169
|
+
if (!Number.isSafeInteger(fields.selectionVersion) || fields.selectionVersion < 1 || !Number.isSafeInteger(fields.bindingEpoch) || fields.bindingEpoch < 1)
|
|
170
|
+
throw new ParticipantRequestError("invalid selection identity");
|
|
171
|
+
runMessagingTransaction(store, "Selected Session binding", tx => {
|
|
172
|
+
const now = clock(seams);
|
|
173
|
+
authorizeCurrentOwner(tx, store, { ...authority, scope: "send", now });
|
|
174
|
+
requireMembership(tx, exchangeId, authority.participantId);
|
|
175
|
+
const owner = tx.prepare("SELECT p.participant_id, o.session_id, o.fencing_token, o.expires_at, o.lease_started_at, b.runtime_session_id, b.binding_epoch FROM participant p JOIN participant_ownership o ON o.participant_id=p.participant_id JOIN exchange_membership m ON m.participant_id=p.participant_id JOIN native_session_binding b ON b.participant_id=p.participant_id AND b.session_id=o.session_id AND b.fencing_token=o.fencing_token WHERE p.endpoint_adapter='pi' AND p.endpoint_id=? AND m.exchange_id=?").get(endpointId, exchangeId);
|
|
176
|
+
if (!owner || owner.runtime_session_id !== runtime || owner.binding_epoch !== fields.bindingEpoch || typeof owner.expires_at !== "string" || typeof owner.lease_started_at !== "string" || owner.lease_started_at > now || now >= owner.expires_at)
|
|
177
|
+
refuse("MESSAGE_READ_REJECTED");
|
|
178
|
+
tx.prepare("INSERT INTO selected_session_binding(policy_id,selection_version,participant_id,session_id,fencing_token,runtime_session_id,binding_epoch) VALUES (?,?,?,?,?,?,?)").run(policyId, fields.selectionVersion, owner.participant_id, owner.session_id, owner.fencing_token, runtime, fields.bindingEpoch);
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
/** Check task routing without granting payload access or consuming a message. */
|
|
182
|
+
export function verifyTaskTarget(store, input, seams = {}) {
|
|
183
|
+
const keys = ["participantId", "sessionId", "fencingToken", "capability", "exchangeId", "messageId"];
|
|
184
|
+
const fields = captureFields(input, keys, keys, "request");
|
|
185
|
+
const authority = authorityRequest(fields);
|
|
186
|
+
const exchangeId = requireText(fields.exchangeId, "exchangeId", 29);
|
|
187
|
+
const messageId = requireText(fields.messageId, "messageId", 30);
|
|
188
|
+
if (!EXCHANGE_ID_PATTERN.test(exchangeId) || !MESSAGE_ID_PATTERN.test(messageId))
|
|
189
|
+
throw new ParticipantRequestError("invalid message identity");
|
|
190
|
+
return runMessagingTransaction(store, "Task target verification", tx => {
|
|
191
|
+
authorizeCurrentOwner(tx, store, { ...authority, scope: "read", now: clock(seams) });
|
|
192
|
+
const membership = requireMembership(tx, exchangeId, authority.participantId);
|
|
193
|
+
const message = readMessageMetadataInTransaction(tx, exchangeId, messageId);
|
|
194
|
+
if (!message || !stableEndpointMatches(tx, authority.participantId, message.to) || messageCreatedAuditSequence(tx, message) <= membership.joinBoundarySeq)
|
|
195
|
+
refuse("MESSAGE_READ_REJECTED");
|
|
196
|
+
const link = tx.prepare("SELECT selection_version, target_owner_session_id, target_owner_fencing_token FROM message_association WHERE exchange_id=? AND message_id=?").get(exchangeId, messageId);
|
|
197
|
+
return link !== undefined && link.target_owner_session_id === authority.sessionId && link.target_owner_fencing_token === authority.fencingToken;
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
/** Sender-authorized lookup of immutable reply identities; payload reads remain separate. */
|
|
201
|
+
export function findMessageReplies(store, input, seams = {}) {
|
|
202
|
+
const fields = captureFields(input, ["participantId", "sessionId", "fencingToken", "capability", "exchangeId", "requestMessageId", "afterMessageId"], ["participantId", "sessionId", "fencingToken", "capability", "exchangeId", "requestMessageId"], "request");
|
|
203
|
+
const authority = authorityRequest(fields);
|
|
204
|
+
const exchangeId = requireText(fields.exchangeId, "exchangeId", 29);
|
|
205
|
+
const requestId = requireText(fields.requestMessageId, "requestMessageId", 30);
|
|
206
|
+
const afterMessageId = fields.afterMessageId === undefined ? null : requireText(fields.afterMessageId, "afterMessageId", 30);
|
|
207
|
+
if (afterMessageId !== null && !MESSAGE_ID_PATTERN.test(afterMessageId))
|
|
208
|
+
throw new ParticipantRequestError("invalid reply cursor");
|
|
209
|
+
if (!EXCHANGE_ID_PATTERN.test(exchangeId) || !MESSAGE_ID_PATTERN.test(requestId))
|
|
210
|
+
throw new ParticipantRequestError("invalid message identity");
|
|
211
|
+
return runMessagingTransaction(store, "Reply discovery", tx => {
|
|
212
|
+
authorizeCurrentOwner(tx, store, { ...authority, scope: "read", now: clock(seams) });
|
|
213
|
+
const membership = requireMembership(tx, exchangeId, authority.participantId);
|
|
214
|
+
const original = readMessageMetadataInTransaction(tx, exchangeId, requestId);
|
|
215
|
+
if (!original || !stableEndpointMatches(tx, authority.participantId, original.from) || messageCreatedAuditSequence(tx, original) <= membership.joinBoundarySeq)
|
|
216
|
+
refuse("MESSAGE_READ_REJECTED");
|
|
217
|
+
const link = tx.prepare("SELECT request_message_id, from_endpoint_json, to_endpoint_json, selection_version FROM message_association WHERE exchange_id=? AND message_id=?").get(exchangeId, requestId);
|
|
218
|
+
if (!link || link.request_message_id !== requestId || link.from_endpoint_json !== JSON.stringify(original.from) || link.to_endpoint_json !== JSON.stringify(original.to))
|
|
219
|
+
refuse("MESSAGE_READ_REJECTED");
|
|
220
|
+
if (afterMessageId !== null && !tx.prepare("SELECT 1 FROM message_association WHERE exchange_id=? AND request_message_id=? AND message_id=? AND message_id<>request_message_id").get(exchangeId, requestId, afterMessageId))
|
|
221
|
+
refuse("MESSAGE_READ_REJECTED");
|
|
222
|
+
const rows = tx.prepare("SELECT a.message_id, a.from_endpoint_json, a.to_endpoint_json FROM message_association a JOIN message m ON m.message_id=a.message_id AND m.exchange_id=a.exchange_id WHERE a.exchange_id=? AND a.request_message_id=? AND a.message_id<>? AND (? IS NULL OR m.rowid>(SELECT rowid FROM message WHERE message_id=? AND exchange_id=?)) ORDER BY m.rowid LIMIT 51").all(exchangeId, requestId, requestId, afterMessageId, afterMessageId, exchangeId);
|
|
223
|
+
const replies = rows.slice(0, 50).map(row => {
|
|
224
|
+
if (typeof row.message_id !== "string")
|
|
225
|
+
refuse("MESSAGE_READ_REJECTED");
|
|
226
|
+
const reply = readMessageMetadataInTransaction(tx, exchangeId, row.message_id);
|
|
227
|
+
if (!reply || reply.from.adapter !== original.to.adapter || reply.from.endpointId !== original.to.endpointId ||
|
|
228
|
+
reply.to.adapter !== original.from.adapter || reply.to.endpointId !== original.from.endpointId ||
|
|
229
|
+
row.from_endpoint_json !== JSON.stringify(reply.from) || row.to_endpoint_json !== JSON.stringify(reply.to) ||
|
|
230
|
+
messageCreatedAuditSequence(tx, reply) <= membership.joinBoundarySeq)
|
|
231
|
+
refuse("MESSAGE_READ_REJECTED");
|
|
232
|
+
return Object.freeze({ messageId: reply.messageId });
|
|
233
|
+
});
|
|
234
|
+
return Object.freeze({ requestMessageId: requestId, target: original.to.endpointId, selectionVersion: link.selection_version, replies: Object.freeze(replies), hasMore: rows.length > 50 });
|
|
235
|
+
});
|
|
236
|
+
}
|
|
98
237
|
/** Repeatable recipient-only protected metadata read. It deliberately takes the
|
|
99
238
|
* same serialization lock as mutations so ownership authority and eligibility
|
|
100
239
|
* are evaluated against one current durable snapshot. */
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { assertStorageRuntimeEligibility, openStorageConnection } from "./connection.js";
|
|
2
2
|
import { StoreLifecycleError } from "./errors.js";
|
|
3
3
|
import { assertSecureDatabaseArtifacts, pathStat, prepareDatabasePath } from "./filesystem.js";
|
|
4
|
-
import { V2_ADDITIVE_SQL, V2_MIGRATION_CHECKSUM, V2_MIGRATION_NAME, V3_ADDITIVE_SQL, V3_MIGRATION_CHECKSUM, V3_MIGRATION_NAME, V4_ADDITIVE_SQL, V4_MIGRATION_CHECKSUM, V4_MIGRATION_NAME, V5_ADDITIVE_SQL, V5_MIGRATION_CHECKSUM, V5_MIGRATION_NAME, V6_CREATE_COPY_SQL, V6_MIGRATION_CHECKSUM, V6_MIGRATION_NAME, V6_SWAP_SQL, } from "./schema.js";
|
|
4
|
+
import { V2_ADDITIVE_SQL, V2_MIGRATION_CHECKSUM, V2_MIGRATION_NAME, V3_ADDITIVE_SQL, V3_MIGRATION_CHECKSUM, V3_MIGRATION_NAME, V4_ADDITIVE_SQL, V4_MIGRATION_CHECKSUM, V4_MIGRATION_NAME, V5_ADDITIVE_SQL, V5_MIGRATION_CHECKSUM, V5_MIGRATION_NAME, V6_CREATE_COPY_SQL, V6_MIGRATION_CHECKSUM, V6_MIGRATION_NAME, V6_SWAP_SQL, V8_ASSOCIATION_SQL, V8_MIGRATION_NAME, V8_MIGRATION_CHECKSUM, } from "./schema.js";
|
|
5
5
|
import { assertPreV4SessionState } from "./session-state.js";
|
|
6
|
+
import { assertStoredOwnershipConsistent } from "./ownership.js";
|
|
6
7
|
import { classifyStoreShape, openMigratedStore, openStore, preflightStoreShape, } from "./store.js";
|
|
7
8
|
import { classifyRecoveryFailure } from "./recovery.js";
|
|
8
9
|
import { withImmediateTransaction } from "./transaction.js";
|
|
@@ -195,6 +196,21 @@ const APPROVED_PATHS = [
|
|
|
195
196
|
[5, 6],
|
|
196
197
|
];
|
|
197
198
|
export function migrateStore(options) {
|
|
199
|
+
if (options.fromVersion === 7 && options.toVersion === 8) {
|
|
200
|
+
assertStorageRuntimeEligibility(options);
|
|
201
|
+
const databasePath = prepareDatabasePath(options);
|
|
202
|
+
assertSecureDatabaseArtifacts(databasePath);
|
|
203
|
+
if (pathStat(databasePath) === undefined)
|
|
204
|
+
throw new StoreLifecycleError("STORAGE_FOREIGN_STORE", "no initialized store exists at the explicit path");
|
|
205
|
+
runMigrationStep(options, databasePath, "v7", (tx, appliedAt) => {
|
|
206
|
+
// Preserve live and expired owners; validate identity and fencing under the migration writer lock.
|
|
207
|
+
assertStoredOwnershipConsistent(tx);
|
|
208
|
+
tx.exec(V8_ASSOCIATION_SQL);
|
|
209
|
+
tx.prepare("INSERT INTO schema_migrations(version, name, checksum, applied_at) VALUES (?, ?, ?, ?)").run(8, V8_MIGRATION_NAME, V8_MIGRATION_CHECKSUM, appliedAt);
|
|
210
|
+
tx.exec("PRAGMA user_version=8");
|
|
211
|
+
}, writer => validateTrustRoot(databasePath, writer));
|
|
212
|
+
return openStore(options);
|
|
213
|
+
}
|
|
198
214
|
assertStorageRuntimeEligibility(options);
|
|
199
215
|
const approved = APPROVED_PATHS.some(([fromVersion, toVersion]) => options.fromVersion === fromVersion && options.toVersion === toVersion);
|
|
200
216
|
if (!approved) {
|
|
@@ -248,6 +248,16 @@ function loadOwnershipState(handle, participantId) {
|
|
|
248
248
|
}
|
|
249
249
|
return { ownership, highWater: highWater ?? 0 };
|
|
250
250
|
}
|
|
251
|
+
/** Validate every preserved ownership tuple without interpreting or changing its lease. */
|
|
252
|
+
export function assertStoredOwnershipConsistent(tx) {
|
|
253
|
+
const rows = tx.prepare("SELECT participant_id FROM participant_ownership ORDER BY participant_id").all();
|
|
254
|
+
for (const row of rows) {
|
|
255
|
+
const participantId = requireParticipantId(row.participant_id, "participantId");
|
|
256
|
+
if (readParticipantRow(tx, participantId) === undefined)
|
|
257
|
+
corrupt();
|
|
258
|
+
loadOwnershipState(tx, participantId);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
251
261
|
/** Evaluates the lease against the persisted term boundaries only. A request
|
|
252
262
|
* TTL is never an input: a stored term is never reinterpreted. A legacy v2 row
|
|
253
263
|
* (NULL start) is expired at every instant, so no lease start is fabricated
|
package/dist/storage/schema.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
export const APPLICATION_ID = "@zieglar/pi-chat-exchange";
|
|
3
3
|
export const SQLITE_APPLICATION_ID = 0x50434558; // "PCEX"
|
|
4
|
-
export const CURRENT_SCHEMA_VERSION =
|
|
4
|
+
export const CURRENT_SCHEMA_VERSION = 8;
|
|
5
|
+
export { V8_FOUNDATION_NAME, V8_FOUNDATION_SQL, V8_FOUNDATION_CHECKSUM, V8_ASSOCIATION_SQL, V8_MIGRATION_NAME, V8_MIGRATION_CHECKSUM } from "./task-association-schema.js";
|
|
5
6
|
export { V7_FOUNDATION_NAME, V7_FOUNDATION_SQL, V7_FOUNDATION_CHECKSUM } from "./current-schema.js";
|
|
6
7
|
export const INITIAL_MIGRATION_NAME = "durable-storage-foundation";
|
|
7
8
|
export const V2_MIGRATION_NAME = "b3-communication-lifecycle-migration";
|
package/dist/storage/store.js
CHANGED
|
@@ -6,7 +6,7 @@ import { resolveSqliteDriver } from "./sqlite-driver-selection.js";
|
|
|
6
6
|
import { assertStorageRuntimeEligibility, openStorageConnection } from "./connection.js";
|
|
7
7
|
import { FilesystemSafetyError, prepareDatabasePath, assertSecureDatabaseArtifacts, pathStat, withRestrictiveUmask, } from "./filesystem.js";
|
|
8
8
|
import { assertHostRuntimeEligibility, RuntimeEligibilityError } from "./runtime.js";
|
|
9
|
-
import { APPLICATION_ID, CURRENT_SCHEMA_VERSION, INITIAL_MIGRATION_CHECKSUM, INITIAL_MIGRATION_NAME, INITIAL_SCHEMA_SQL, SQLITE_APPLICATION_ID, V2_FOUNDATION_CHECKSUM, V2_FOUNDATION_NAME, V2_FOUNDATION_SQL, V2_MIGRATION_CHECKSUM, V2_MIGRATION_NAME, V3_FOUNDATION_CHECKSUM, V3_FOUNDATION_NAME, V3_FOUNDATION_SQL, V3_MIGRATION_CHECKSUM, V3_MIGRATION_NAME, V4_FOUNDATION_CHECKSUM, V4_FOUNDATION_NAME, V4_FOUNDATION_SQL, V4_MIGRATION_CHECKSUM, V4_MIGRATION_NAME, V5_FOUNDATION_CHECKSUM, V5_FOUNDATION_NAME, V5_FOUNDATION_SQL, V5_MIGRATION_CHECKSUM, V5_MIGRATION_NAME, V6_FOUNDATION_CHECKSUM, V6_FOUNDATION_NAME, V6_FOUNDATION_SQL, V6_MIGRATION_CHECKSUM, V6_MIGRATION_NAME, V7_FOUNDATION_SQL, V7_FOUNDATION_NAME, V7_FOUNDATION_CHECKSUM, } from "./schema.js";
|
|
9
|
+
import { APPLICATION_ID, CURRENT_SCHEMA_VERSION, INITIAL_MIGRATION_CHECKSUM, INITIAL_MIGRATION_NAME, INITIAL_SCHEMA_SQL, SQLITE_APPLICATION_ID, V2_FOUNDATION_CHECKSUM, V2_FOUNDATION_NAME, V2_FOUNDATION_SQL, V2_MIGRATION_CHECKSUM, V2_MIGRATION_NAME, V3_FOUNDATION_CHECKSUM, V3_FOUNDATION_NAME, V3_FOUNDATION_SQL, V3_MIGRATION_CHECKSUM, V3_MIGRATION_NAME, V4_FOUNDATION_CHECKSUM, V4_FOUNDATION_NAME, V4_FOUNDATION_SQL, V4_MIGRATION_CHECKSUM, V4_MIGRATION_NAME, V5_FOUNDATION_CHECKSUM, V5_FOUNDATION_NAME, V5_FOUNDATION_SQL, V5_MIGRATION_CHECKSUM, V5_MIGRATION_NAME, V6_FOUNDATION_CHECKSUM, V6_FOUNDATION_NAME, V6_FOUNDATION_SQL, V6_MIGRATION_CHECKSUM, V6_MIGRATION_NAME, V7_FOUNDATION_SQL, V7_FOUNDATION_NAME, V7_FOUNDATION_CHECKSUM, V8_FOUNDATION_SQL, V8_FOUNDATION_NAME, V8_FOUNDATION_CHECKSUM, V8_MIGRATION_NAME, V8_MIGRATION_CHECKSUM, } from "./schema.js";
|
|
10
10
|
import { withImmediateTransaction, StorageTransactionError } from "./transaction.js";
|
|
11
11
|
import { StoreLifecycleError } from "./errors.js";
|
|
12
12
|
import { assertTrustRootAbsent, createHostSecretFile, validateTrustRoot } from "./trust-root.js";
|
|
@@ -63,7 +63,7 @@ function approvedManifest(version) {
|
|
|
63
63
|
? V4_FOUNDATION_SQL
|
|
64
64
|
: version === "v5"
|
|
65
65
|
? V5_FOUNDATION_SQL
|
|
66
|
-
: version === "v6" ? V6_FOUNDATION_SQL : V7_FOUNDATION_SQL);
|
|
66
|
+
: version === "v6" ? V6_FOUNDATION_SQL : version === "v7" ? V7_FOUNDATION_SQL : V8_FOUNDATION_SQL);
|
|
67
67
|
const manifest = schemaManifest(reference);
|
|
68
68
|
approvedManifests[version] = manifest;
|
|
69
69
|
return manifest;
|
|
@@ -216,7 +216,9 @@ export function classifyStoreShape(db, currentOnly = false) {
|
|
|
216
216
|
? 5
|
|
217
217
|
: V6_LEDGERS.some((ledger) => ledgerMatches(migrations, ledger))
|
|
218
218
|
? 6
|
|
219
|
-
: ledgerMatches(migrations, [[7, V7_FOUNDATION_NAME, V7_FOUNDATION_CHECKSUM]]) ? 7
|
|
219
|
+
: ledgerMatches(migrations, [[7, V7_FOUNDATION_NAME, V7_FOUNDATION_CHECKSUM]]) ? 7
|
|
220
|
+
: ledgerMatches(migrations, [[8, V8_FOUNDATION_NAME, V8_FOUNDATION_CHECKSUM]]) ||
|
|
221
|
+
ledgerMatches(migrations, [[7, V7_FOUNDATION_NAME, V7_FOUNDATION_CHECKSUM], [8, V8_MIGRATION_NAME, V8_MIGRATION_CHECKSUM]]) ? 8 : undefined;
|
|
220
222
|
if (shapeVersion === undefined) {
|
|
221
223
|
throw new StoreLifecycleError("STORAGE_MIGRATION_CHECKSUM_MISMATCH", "store migration ledger does not match the approved schema");
|
|
222
224
|
}
|
|
@@ -230,7 +232,7 @@ export function classifyStoreShape(db, currentOnly = false) {
|
|
|
230
232
|
sqliteSchemaVersion !== shapeVersion) {
|
|
231
233
|
throw new StoreLifecycleError("STORAGE_INCOMPATIBLE", "store schema requires an explicitly approved migration");
|
|
232
234
|
}
|
|
233
|
-
if (currentOnly && shapeVersion !==
|
|
235
|
+
if (currentOnly && shapeVersion !== 8) {
|
|
234
236
|
throw new StoreLifecycleError("STORAGE_INCOMPATIBLE", "unsupported Store; separate operator-approved Dev Reset required");
|
|
235
237
|
}
|
|
236
238
|
const requiredTables = shapeVersion === 1 ? V1_REQUIRED_TABLES : V2_REQUIRED_TABLES;
|
|
@@ -239,7 +241,7 @@ export function classifyStoreShape(db, currentOnly = false) {
|
|
|
239
241
|
throw new StoreLifecycleError("STORAGE_INCOMPATIBLE", `required private table ${table} is missing`);
|
|
240
242
|
}
|
|
241
243
|
}
|
|
242
|
-
if (shapeVersion
|
|
244
|
+
if (shapeVersion >= 7 && !tables.has("delivery_ack_receipt")) {
|
|
243
245
|
throw new StoreLifecycleError("STORAGE_INCOMPATIBLE", "current receipt schema is missing");
|
|
244
246
|
}
|
|
245
247
|
assertApprovedSchema(db, shapeKind(shapeVersion));
|
|
@@ -257,16 +259,20 @@ function shapeKind(version) {
|
|
|
257
259
|
? "v4"
|
|
258
260
|
: version === 5
|
|
259
261
|
? "v5"
|
|
260
|
-
: version === 6 ? "v6" : "v7";
|
|
262
|
+
: version === 6 ? "v6" : version === 7 ? "v7" : "v8";
|
|
261
263
|
}
|
|
262
264
|
/** Normal open is current-only. Old shapes are recognized for truthful refusal,
|
|
263
265
|
* never upgraded or rebuilt through this path. The host root is checked on every open. */
|
|
264
266
|
function readAndValidateStore(db, databasePath) {
|
|
265
267
|
const shape = classifyStoreShape(db, true);
|
|
266
|
-
if (shape.kind !== "
|
|
268
|
+
if (shape.kind !== "v8") {
|
|
267
269
|
throw new StoreLifecycleError("STORAGE_INCOMPATIBLE", "unsupported Store; separate operator-approved Dev Reset required");
|
|
268
270
|
}
|
|
269
271
|
validateTrustRoot(databasePath, db);
|
|
272
|
+
// A permit is transaction-local in normal operation; a committed one is foreign state.
|
|
273
|
+
if (!db.isTransaction && db.prepare("SELECT 1 FROM v8_write_permit LIMIT 1").get() !== undefined) {
|
|
274
|
+
throw new StoreLifecycleError("STORAGE_CORRUPT", "committed v8 writer permit");
|
|
275
|
+
}
|
|
270
276
|
return shape.metadata;
|
|
271
277
|
}
|
|
272
278
|
export function initializeStore(options) {
|
|
@@ -306,9 +312,9 @@ export function initializeStore(options) {
|
|
|
306
312
|
};
|
|
307
313
|
const secretDigest = createHostSecretFile(databasePath, safeSecretBytes);
|
|
308
314
|
withImmediateTransaction(db, (tx) => {
|
|
309
|
-
tx.exec(
|
|
315
|
+
tx.exec(V8_FOUNDATION_SQL);
|
|
310
316
|
tx.prepare("INSERT INTO store_metadata(singleton, store_uuid, application_id, schema_version, created_at) VALUES (1, ?, ?, ?, ?)").run(storeUuid, APPLICATION_ID, CURRENT_SCHEMA_VERSION, appliedAt);
|
|
311
|
-
tx.prepare("INSERT INTO schema_migrations(version, name, checksum, applied_at) VALUES (?, ?, ?, ?)").run(CURRENT_SCHEMA_VERSION,
|
|
317
|
+
tx.prepare("INSERT INTO schema_migrations(version, name, checksum, applied_at) VALUES (?, ?, ?, ?)").run(CURRENT_SCHEMA_VERSION, V8_FOUNDATION_NAME, V8_FOUNDATION_CHECKSUM, appliedAt);
|
|
312
318
|
tx.prepare("INSERT INTO restore_hold(singleton, held) VALUES (1, 0)").run();
|
|
313
319
|
tx.prepare("INSERT INTO host_trust_root(generation, secret_digest, created_at, private_revision) VALUES (1, ?, ?, 1)").run(secretDigest, appliedAt);
|
|
314
320
|
tx.exec(`PRAGMA application_id=${SQLITE_APPLICATION_ID}; PRAGMA user_version=${CURRENT_SCHEMA_VERSION};`);
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { V7_FOUNDATION_SQL } from "./current-schema.js";
|
|
3
|
+
// A permit exists only inside a v8 writer transaction. SQLite serializes writers,
|
|
4
|
+
// so connections opened by older code cannot borrow another transaction's permit.
|
|
5
|
+
const V8_GUARDED_TABLES = ["store_metadata", "schema_migrations", "restore_hold", "exchange", "message", "attempt", "current_claim", "fencing_high_water", "result", "idempotency_record", "evidence_envelope", "evidence_application", "reconciliation", "disposition", "audit_event", "participant", "participant_capability", "participant_session", "exchange_membership", "participant_ownership", "participant_fencing_high_water", "delivery_cursor", "host_trust_root", "delivery_ack_receipt", "message_association", "native_session_binding", "selected_session_binding"];
|
|
6
|
+
const V8_WRITER_GUARDS = `CREATE TABLE v8_write_permit (singleton INTEGER PRIMARY KEY CHECK (singleton=1)) STRICT;\n` +
|
|
7
|
+
V8_GUARDED_TABLES.flatMap(table => ["INSERT", "UPDATE", "DELETE"].map(operation => `CREATE TRIGGER v8_guard_${table}_${operation.toLowerCase()} BEFORE ${operation} ON ${table} WHEN NOT EXISTS (SELECT 1 FROM v8_write_permit WHERE singleton=1) BEGIN SELECT RAISE(ABORT, 'v8 writer required'); END;`)).join("\n");
|
|
8
|
+
/** The association is private metadata; the frozen public Message is unchanged. */
|
|
9
|
+
export const V8_ASSOCIATION_SQL = `
|
|
10
|
+
CREATE TABLE message_association (
|
|
11
|
+
message_id TEXT PRIMARY KEY,
|
|
12
|
+
exchange_id TEXT NOT NULL,
|
|
13
|
+
request_message_id TEXT NOT NULL,
|
|
14
|
+
from_endpoint_json TEXT NOT NULL CHECK (json_valid(from_endpoint_json) AND json_type(from_endpoint_json) = 'object'),
|
|
15
|
+
to_endpoint_json TEXT NOT NULL CHECK (json_valid(to_endpoint_json) AND json_type(to_endpoint_json) = 'object'),
|
|
16
|
+
policy_id TEXT,
|
|
17
|
+
selection_version INTEGER CHECK (selection_version IS NULL OR selection_version >= 1),
|
|
18
|
+
target_runtime_session_id TEXT,
|
|
19
|
+
binding_epoch INTEGER CHECK (binding_epoch IS NULL OR binding_epoch >= 1),
|
|
20
|
+
target_owner_session_id TEXT,
|
|
21
|
+
target_owner_fencing_token INTEGER CHECK (target_owner_fencing_token IS NULL OR target_owner_fencing_token >= 1),
|
|
22
|
+
created_at TEXT NOT NULL,
|
|
23
|
+
FOREIGN KEY (exchange_id, message_id) REFERENCES message(exchange_id, message_id) DEFERRABLE INITIALLY DEFERRED,
|
|
24
|
+
FOREIGN KEY (exchange_id, request_message_id) REFERENCES message(exchange_id, message_id) DEFERRABLE INITIALLY DEFERRED
|
|
25
|
+
) STRICT;
|
|
26
|
+
CREATE TABLE native_session_binding (
|
|
27
|
+
participant_id TEXT NOT NULL REFERENCES participant(participant_id),
|
|
28
|
+
session_id TEXT NOT NULL,
|
|
29
|
+
fencing_token INTEGER NOT NULL CHECK (fencing_token >= 1),
|
|
30
|
+
runtime_session_id TEXT NOT NULL,
|
|
31
|
+
binding_epoch INTEGER NOT NULL CHECK (binding_epoch >= 1),
|
|
32
|
+
PRIMARY KEY(participant_id, session_id, fencing_token)
|
|
33
|
+
) STRICT;
|
|
34
|
+
CREATE TABLE selected_session_binding (
|
|
35
|
+
policy_id TEXT NOT NULL,
|
|
36
|
+
selection_version INTEGER NOT NULL,
|
|
37
|
+
participant_id TEXT NOT NULL,
|
|
38
|
+
session_id TEXT NOT NULL,
|
|
39
|
+
fencing_token INTEGER NOT NULL,
|
|
40
|
+
runtime_session_id TEXT NOT NULL,
|
|
41
|
+
binding_epoch INTEGER NOT NULL,
|
|
42
|
+
PRIMARY KEY(policy_id, selection_version)
|
|
43
|
+
) STRICT;
|
|
44
|
+
CREATE INDEX idx_message_association_request ON message_association(exchange_id, request_message_id, message_id);
|
|
45
|
+
CREATE TRIGGER native_session_binding_immutable BEFORE UPDATE ON native_session_binding
|
|
46
|
+
BEGIN SELECT RAISE(ABORT, 'native binding is immutable'); END;
|
|
47
|
+
CREATE TRIGGER native_session_binding_nodelete BEFORE DELETE ON native_session_binding
|
|
48
|
+
BEGIN SELECT RAISE(ABORT, 'native binding is immutable'); END;
|
|
49
|
+
CREATE TRIGGER selected_session_binding_immutable BEFORE UPDATE ON selected_session_binding
|
|
50
|
+
BEGIN SELECT RAISE(ABORT, 'selection binding is immutable'); END;
|
|
51
|
+
CREATE TRIGGER selected_session_binding_nodelete BEFORE DELETE ON selected_session_binding
|
|
52
|
+
BEGIN SELECT RAISE(ABORT, 'selection binding is immutable'); END;
|
|
53
|
+
CREATE TRIGGER message_association_immutable BEFORE UPDATE ON message_association
|
|
54
|
+
BEGIN SELECT RAISE(ABORT, 'message association is immutable'); END;
|
|
55
|
+
CREATE TRIGGER message_association_nodelete BEFORE DELETE ON message_association
|
|
56
|
+
BEGIN SELECT RAISE(ABORT, 'message association is immutable'); END;
|
|
57
|
+
CREATE TRIGGER message_association_required BEFORE INSERT ON message
|
|
58
|
+
WHEN NOT EXISTS (SELECT 1 FROM message_association a WHERE a.message_id = NEW.message_id
|
|
59
|
+
AND a.exchange_id = NEW.exchange_id AND a.from_endpoint_json = NEW.from_endpoint_json
|
|
60
|
+
AND a.to_endpoint_json = NEW.to_endpoint_json)
|
|
61
|
+
BEGIN SELECT RAISE(ABORT, 'message association required'); END;
|
|
62
|
+
CREATE TRIGGER message_endpoints_immutable BEFORE UPDATE OF from_endpoint_json, to_endpoint_json ON message
|
|
63
|
+
WHEN NEW.from_endpoint_json IS NOT OLD.from_endpoint_json OR NEW.to_endpoint_json IS NOT OLD.to_endpoint_json
|
|
64
|
+
BEGIN SELECT RAISE(ABORT, 'message endpoints are immutable'); END;
|
|
65
|
+
` + V8_WRITER_GUARDS;
|
|
66
|
+
export const V8_FOUNDATION_SQL = V7_FOUNDATION_SQL + V8_ASSOCIATION_SQL;
|
|
67
|
+
export const V8_FOUNDATION_NAME = "direct-current-message-association";
|
|
68
|
+
export const V8_FOUNDATION_CHECKSUM = createHash("sha256").update(V8_FOUNDATION_SQL, "utf8").digest("hex");
|
|
69
|
+
export const V8_MIGRATION_NAME = "v7-to-v8-message-association";
|
|
70
|
+
export const V8_MIGRATION_CHECKSUM = createHash("sha256").update(V8_ASSOCIATION_SQL, "utf8").digest("hex");
|
|
71
|
+
//# sourceMappingURL=task-association-schema.js.map
|
|
@@ -105,6 +105,13 @@ export function withImmediateTransaction(db, callback) {
|
|
|
105
105
|
cause: error, busy: isBusyError(error), outcome: "ROLLED_BACK",
|
|
106
106
|
});
|
|
107
107
|
}
|
|
108
|
+
let v8PermitIssued = false;
|
|
109
|
+
const ensureV8Permit = () => {
|
|
110
|
+
if (!v8PermitIssued && db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name='v8_write_permit'").get()) {
|
|
111
|
+
db.prepare("INSERT INTO v8_write_permit(singleton) VALUES (1)").run();
|
|
112
|
+
v8PermitIssued = true;
|
|
113
|
+
}
|
|
114
|
+
};
|
|
108
115
|
let capabilityActive = true;
|
|
109
116
|
const assertActive = () => {
|
|
110
117
|
if (!capabilityActive)
|
|
@@ -113,13 +120,13 @@ export function withImmediateTransaction(db, callback) {
|
|
|
113
120
|
throw new StorageTransactionError("owned transaction ended unexpectedly", "callback");
|
|
114
121
|
};
|
|
115
122
|
const tx = Object.freeze({
|
|
116
|
-
exec(sql) { assertActive(); db.exec(sql); },
|
|
123
|
+
exec(sql) { assertActive(); ensureV8Permit(); db.exec(sql); },
|
|
117
124
|
prepare(sql) {
|
|
118
125
|
assertActive();
|
|
119
126
|
const statement = db.prepare(sql);
|
|
120
127
|
return Object.freeze({
|
|
121
128
|
// Every supplied argument is forwarded unchanged to SQLite's typed method.
|
|
122
|
-
run: (...args) => { assertActive(); return statement.run(...args); },
|
|
129
|
+
run: (...args) => { assertActive(); ensureV8Permit(); return statement.run(...args); },
|
|
123
130
|
get: (...args) => { assertActive(); return statement.get(...args); },
|
|
124
131
|
all: (...args) => { assertActive(); return statement.all(...args); },
|
|
125
132
|
});
|
|
@@ -131,6 +138,8 @@ export function withImmediateTransaction(db, callback) {
|
|
|
131
138
|
// invalidated by setAuthorizer. Not a SQL-prefix/regex filter.
|
|
132
139
|
db.setAuthorizerPolicy("deny-transaction-control");
|
|
133
140
|
assertVoidResult(callback(tx));
|
|
141
|
+
if (v8PermitIssued && db.prepare("DELETE FROM v8_write_permit WHERE singleton=1").run().changes !== 1)
|
|
142
|
+
throw new Error("v8 writer permit lost");
|
|
134
143
|
if (db.authorizerDenials() > 0)
|
|
135
144
|
throw new Error("callback attempted owned transaction control");
|
|
136
145
|
if (!db.isTransaction)
|
|
@@ -167,6 +167,7 @@ import { dirname, isAbsolute, join, normalize } from "node:path";
|
|
|
167
167
|
import { TunnelRefusal } from "./codes.js";
|
|
168
168
|
import { TUNNEL_ID_PATTERN } from "./tunnel-id.js";
|
|
169
169
|
import { resolveTunnelClient } from "../runtime/executables.js";
|
|
170
|
+
import { assertPrivateUnixSocket } from "../runtime/private-unix-socket.js";
|
|
170
171
|
import { resolveWrapperIdentityEvidence } from "../runtime/wrapper-identity.js";
|
|
171
172
|
import { createBackgroundAuthorizationStore } from "./background-authorization.js";
|
|
172
173
|
import { captureBackgroundAuthorizationScope } from "./background-scope.js";
|
|
@@ -231,6 +232,11 @@ export function parseTunnelProfile(text) {
|
|
|
231
232
|
};
|
|
232
233
|
let section;
|
|
233
234
|
let inCommands = false;
|
|
235
|
+
let inServerUrls = false;
|
|
236
|
+
let httpConfigured = false;
|
|
237
|
+
let httpItemSeen = false;
|
|
238
|
+
let httpUrl;
|
|
239
|
+
let httpSocket;
|
|
234
240
|
let itemOpen = false;
|
|
235
241
|
const seen = new Set();
|
|
236
242
|
const found = {};
|
|
@@ -242,6 +248,7 @@ export function parseTunnelProfile(text) {
|
|
|
242
248
|
if (indent === 0) {
|
|
243
249
|
itemOpen = false;
|
|
244
250
|
inCommands = false;
|
|
251
|
+
inServerUrls = false;
|
|
245
252
|
if (line === "config_version: 1") {
|
|
246
253
|
section = undefined;
|
|
247
254
|
continue;
|
|
@@ -258,6 +265,29 @@ export function parseTunnelProfile(text) {
|
|
|
258
265
|
if (section === undefined)
|
|
259
266
|
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "profile");
|
|
260
267
|
if (section === "mcp") {
|
|
268
|
+
if (!inCommands && !inServerUrls && indent === 2 && line === "server_urls:") {
|
|
269
|
+
inServerUrls = true;
|
|
270
|
+
httpConfigured = true;
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
if (inServerUrls) {
|
|
274
|
+
if (indent === 4 && line === "- channel: main" && !httpItemSeen) {
|
|
275
|
+
httpItemSeen = true;
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
if (!httpItemSeen || indent !== 6)
|
|
279
|
+
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "mcp.server_urls");
|
|
280
|
+
const kv = /^(\w+):\s*(.+)$/.exec(line);
|
|
281
|
+
if (kv === null)
|
|
282
|
+
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "mcp.server_urls");
|
|
283
|
+
if (kv[1] === "url" && httpUrl === undefined)
|
|
284
|
+
httpUrl = quoted(kv[2], "mcp.server_urls.url");
|
|
285
|
+
else if (kv[1] === "unix_socket" && httpSocket === undefined)
|
|
286
|
+
httpSocket = quoted(kv[2], "mcp.server_urls.unix_socket");
|
|
287
|
+
else
|
|
288
|
+
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "mcp.server_urls");
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
261
291
|
if (!inCommands) {
|
|
262
292
|
if (indent !== 2 || line !== "commands:")
|
|
263
293
|
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "mcp");
|
|
@@ -351,6 +381,13 @@ export function parseTunnelProfile(text) {
|
|
|
351
381
|
if (found.urlFile === undefined || !isAbsolute(found.urlFile) || normalize(found.urlFile) !== found.urlFile) {
|
|
352
382
|
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "health.url_file");
|
|
353
383
|
}
|
|
384
|
+
if (httpConfigured) {
|
|
385
|
+
if (!httpItemSeen || httpUrl !== "http://localhost/mcp" || httpSocket === undefined || !isAbsolute(httpSocket) || normalize(httpSocket) !== httpSocket) {
|
|
386
|
+
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "mcp.server_urls");
|
|
387
|
+
}
|
|
388
|
+
return { tunnelId: found.tunnelId, organizationId: found.organizationId, keyFile, urlFile: found.urlFile, mcpCommand: undefined,
|
|
389
|
+
mcpHttp: { url: "http://localhost/mcp", unixSocket: httpSocket } };
|
|
390
|
+
}
|
|
354
391
|
return { tunnelId: found.tunnelId, organizationId: found.organizationId, keyFile, urlFile: found.urlFile, mcpCommand: found.mcpCommand };
|
|
355
392
|
}
|
|
356
393
|
export function checkKeyFileMetadata(path) {
|
|
@@ -606,7 +643,8 @@ export function createBackgroundTunnelManager(options) {
|
|
|
606
643
|
const profileText = readFileSync(profilePath, "utf8");
|
|
607
644
|
const facts = parseTunnelProfile(profileText);
|
|
608
645
|
checkKeyFileMetadata(facts.keyFile);
|
|
609
|
-
return captureBackgroundAuthorizationScope({ profilePath, profileText, credentialPath: facts.keyFile,
|
|
646
|
+
return captureBackgroundAuthorizationScope({ profilePath, profileText, credentialPath: facts.keyFile,
|
|
647
|
+
mcpCommand: facts.mcpCommand, mcpHttp: facts.mcpHttp, clientPath });
|
|
610
648
|
};
|
|
611
649
|
const authorizationStatus = () => {
|
|
612
650
|
const selected = authorizationStore.readSelection();
|
|
@@ -1311,6 +1349,10 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1311
1349
|
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "profile");
|
|
1312
1350
|
}
|
|
1313
1351
|
const facts = parseTunnelProfile(profileText);
|
|
1352
|
+
// The legacy environment opt-in does not authorize a new HTTP socket.
|
|
1353
|
+
if (facts.mcpHttp !== undefined && authorizationStatus() !== "granted") {
|
|
1354
|
+
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED", "authorization.http");
|
|
1355
|
+
}
|
|
1314
1356
|
checkKeyFileMetadata(facts.keyFile);
|
|
1315
1357
|
const profileSha256 = createHash("sha256").update(profileText, "utf8").digest("hex");
|
|
1316
1358
|
if (expectedProfileSha256 !== undefined && expectedProfileSha256 !== profileSha256)
|
|
@@ -1383,6 +1425,17 @@ export function createBackgroundTunnelManager(options) {
|
|
|
1383
1425
|
// Admission uses this final grant snapshot. A concurrent revoke cannot
|
|
1384
1426
|
// retract an admitted start; Stop is the explicit process cleanup barrier.
|
|
1385
1427
|
assertAuthorization();
|
|
1428
|
+
if (facts.mcpHttp !== undefined) {
|
|
1429
|
+
// Recheck the explicit grant and the trusted socket immediately before spawn.
|
|
1430
|
+
if (authorizationStatus() !== "granted")
|
|
1431
|
+
throw new TunnelRefusal("CE_TUNNEL_BACKGROUND_UNAUTHORIZED", "authorization.http");
|
|
1432
|
+
try {
|
|
1433
|
+
assertPrivateUnixSocket(facts.mcpHttp.unixSocket);
|
|
1434
|
+
}
|
|
1435
|
+
catch {
|
|
1436
|
+
throw new TunnelRefusal("CE_TUNNEL_PROFILE_INVALID", "mcp.server_urls.unix_socket");
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1386
1439
|
if (clientPath === undefined)
|
|
1387
1440
|
throw new TunnelRefusal("CE_TUNNEL_SPAWN_FAILED", "client");
|
|
1388
1441
|
const runId = `bg-${randomUUID()}`;
|
|
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync } from "node:fs";
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
4
|
import { admitExecutable, qualifyNodeExecutable } from "../runtime/executables.js";
|
|
5
|
+
import { assertPrivateSocketDirectory } from "../runtime/private-unix-socket.js";
|
|
5
6
|
import { resolveWrapperIdentityEvidence } from "../runtime/wrapper-identity.js";
|
|
6
7
|
import { parseMcpBindingConfig } from "../host/mcp-binding-config.js";
|
|
7
8
|
import { parseTunnelMcpCommand } from "./profile.js";
|
|
@@ -34,8 +35,8 @@ function safeDocument(path, key) {
|
|
|
34
35
|
* admits the selected client; grant validation rechecks these file identities before spawn. */
|
|
35
36
|
export function captureBackgroundAuthorizationScope(input) {
|
|
36
37
|
try {
|
|
37
|
-
if (input.clientPath === undefined || input.mcpCommand === undefined)
|
|
38
|
-
throw new Error("missing");
|
|
38
|
+
if (input.clientPath === undefined || (input.mcpCommand === undefined) === (input.mcpHttp === undefined))
|
|
39
|
+
throw new Error("missing or ambiguous transport");
|
|
39
40
|
const key = lstatSync(input.credentialPath);
|
|
40
41
|
if (safeDocument(input.profilePath, key) !== input.profileText)
|
|
41
42
|
throw new Error("drift");
|
|
@@ -43,6 +44,21 @@ export function captureBackgroundAuthorizationScope(input) {
|
|
|
43
44
|
if (!client.isFile() || (client.uid !== process.geteuid?.() && client.uid !== 0) || (client.mode & 0o022) !== 0)
|
|
44
45
|
throw new Error("client");
|
|
45
46
|
const wrapper = resolveWrapperIdentityEvidence(input.clientPath);
|
|
47
|
+
if (input.mcpHttp !== undefined) {
|
|
48
|
+
if (input.mcpHttp.url !== "http://localhost/mcp")
|
|
49
|
+
throw new Error("HTTP URL");
|
|
50
|
+
assertPrivateSocketDirectory(input.mcpHttp.unixSocket);
|
|
51
|
+
const profileSha256 = sha(input.profileText);
|
|
52
|
+
// A separate versioned grant binds the exact private socket and profile.
|
|
53
|
+
// Within that socket, same-UID processes share the operator's authority.
|
|
54
|
+
const scope = { version: 2, profilePath: input.profilePath, profileSha256,
|
|
55
|
+
credential: [input.credentialPath, ...identity(key)], client: [input.clientPath, ...identity(client)],
|
|
56
|
+
wrapper: wrapper?.execTarget === undefined ? null : [wrapper.execTarget, ...identity(lstatSync(wrapper.execTarget))],
|
|
57
|
+
http: { url: input.mcpHttp.url, unixSocket: input.mcpHttp.unixSocket } };
|
|
58
|
+
return { digest: sha(JSON.stringify(scope)), profileSha256, clientPath: input.clientPath, credentialPath: input.credentialPath };
|
|
59
|
+
}
|
|
60
|
+
if (input.mcpCommand === undefined)
|
|
61
|
+
throw new Error("stdio command");
|
|
46
62
|
const parsed = parseTunnelMcpCommand(input.mcpCommand);
|
|
47
63
|
const scriptPath = fileURLToPath(new URL("../../dist/bin/mcp-stdio.js", import.meta.url));
|
|
48
64
|
// Persistent permission never authorizes an arbitrary script with a familiar basename.
|