@zieglar/pi-chat-exchange 0.2.0 → 0.2.1
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 +95 -47
- package/dist/bin/ce-native.js +119 -0
- package/dist/control/mcp/server.js +1 -1
- package/dist/runtime/diagnostics.js +2 -2
- package/dist/runtime/executables.js +21 -26
- package/dist/runtime/native-readiness.js +131 -0
- package/dist/storage/connection.js +4 -3
- package/dist/storage/filesystem.js +58 -3
- package/dist/storage/native-artifact.js +234 -0
- package/dist/storage/native-compat.js +65 -0
- package/dist/storage/runtime.js +201 -58
- package/dist/storage/sqlite-driver-node.js +66 -0
- package/dist/storage/sqlite-driver-rust.js +121 -0
- package/dist/storage/sqlite-driver-selection.js +86 -0
- package/dist/storage/sqlite-driver.js +4 -0
- package/dist/storage/store.js +3 -3
- package/dist/storage/transaction.js +20 -23
- package/dist/tunnel/codes.js +1 -1
- package/package.json +8 -20
- package/pi-extension/index.ts +34 -0
- package/CHANGELOG.md +0 -70
- package/docs/architecture.md +0 -170
- package/docs/chatgpt-installation.md +0 -149
- package/docs/delivery-ack-contract.md +0 -86
- package/docs/independent-install.md +0 -156
- package/docs/multi-session-usage.md +0 -77
- package/docs/ownership-contract.md +0 -429
- package/docs/protocol-v2.md +0 -269
- package/docs/releases/0.2.0.md +0 -59
- package/docs/storage-contract.md +0 -1241
- package/docs/storage-security.md +0 -138
- package/docs/tunnel-manager-background.md +0 -169
- package/docs/tunnel-setup.md +0 -214
- package/pi-extension/README.md +0 -125
package/dist/storage/runtime.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { resolveSqliteDriver } from "./sqlite-driver-selection.js";
|
|
2
|
+
import { NATIVE_ABI_VERSION, NATIVE_DEFAULT_VERSION } from "./native-compat.js";
|
|
3
|
+
import { nativeTarget } from "./native-artifact.js";
|
|
4
|
+
/** Legacy release pins retained as diagnostics only; never the admission authority. */
|
|
3
5
|
export const APPROVED_NODE_VERSION = "v24.21.0";
|
|
4
6
|
export const APPROVED_SQLITE_VERSION = "3.53.4";
|
|
5
7
|
export const APPROVED_SQLITE_SOURCE_ID = "2026-07-24 19:02:57 bf7c7f30031888f4e796e429ab3978879485813aaca6f641c7b33e4e09459bcc";
|
|
@@ -8,19 +10,58 @@ export const APPROVED_SQLITE_SOURCE_ID = "2026-07-24 19:02:57 bf7c7f30031888f4e7
|
|
|
8
10
|
* NODE_PROBE subprocess battery — before either may report it as evidence. */
|
|
9
11
|
export const REQUIRED_SQLITE_CAPABILITIES = Object.freeze([
|
|
10
12
|
"defensive", "statement-get", "statement-all", "statement-run", "transaction-state",
|
|
13
|
+
"authorizer-transaction", "authorizer-savepoint",
|
|
14
|
+
"transaction-commit", "strict-tables", "json-functions", "check-constraints",
|
|
15
|
+
"foreign-key-enforcement", "triggers",
|
|
11
16
|
]);
|
|
12
17
|
const REQUIRED_COMPILE_OPTIONS = Object.freeze(["THREADSAFE=1", "MUTEX_PTHREADS"]);
|
|
13
18
|
const FORBIDDEN_COMPILE_OPTIONS = new Set(["OMIT_WAL", "OMIT_FOREIGN_KEY", "OMIT_TRIGGER", "OMIT_CHECK", "OMIT_COMPILEOPTION_DIAGS"]);
|
|
14
19
|
const SUPPORTED_TARGETS = Object.freeze(["darwin/arm64", "linux/x64"]);
|
|
15
|
-
/**
|
|
16
|
-
export const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
20
|
+
/** Matches the supported Pi 1.3.0 Host declaration; independent of node:sqlite. */
|
|
21
|
+
export const PI_HOST_MINIMUM_NODE_VERSION = "v22.19.0";
|
|
22
|
+
/** Node builtin driver candidate range only; Rust uses Node-API instead. */
|
|
23
|
+
export const CANDIDATE_NODE_RANGE = Object.freeze({ minimum: "v24.12.0", majors: Object.freeze([24, 25, 26]) });
|
|
24
|
+
const NODE_VERSION_PATTERN = /^v(\d+)\.(\d+)\.(\d+)$/;
|
|
25
|
+
export function isCandidateNodeVersion(nodeVersion) {
|
|
26
|
+
const match = NODE_VERSION_PATTERN.exec(nodeVersion ?? "");
|
|
27
|
+
if (match === null)
|
|
28
|
+
return false;
|
|
29
|
+
const [, major, minor, patch] = match;
|
|
30
|
+
if (![major, minor, patch].every((part) => {
|
|
31
|
+
const value = Number(part);
|
|
32
|
+
return Number.isSafeInteger(value) && String(value) === part;
|
|
33
|
+
}))
|
|
34
|
+
return false;
|
|
35
|
+
if (!CANDIDATE_NODE_RANGE.majors.includes(Number(major)))
|
|
36
|
+
return false;
|
|
37
|
+
return Number(major) !== 24 || Number(minor) >= Number(CANDIDATE_NODE_RANGE.minimum.split(".")[1]);
|
|
38
|
+
}
|
|
39
|
+
/** Discovery hints only, never the admission policy. */
|
|
40
|
+
export const MISE_DISCOVERY_NODE_VERSIONS = Object.freeze(["v24.21.0", "v24.22.0", "v24.22.1"]);
|
|
41
|
+
// Upstream-confirmed defect protection, NOT a locally reproduced corruption:
|
|
42
|
+
// https://sqlite.org/wal.html section 11. Affected: 3.7.0..3.51.2; fixed 3.51.3.
|
|
43
|
+
export const MINIMUM_SQLITE_VERSION = "3.51.3";
|
|
44
|
+
const SQLITE_VERSION_PATTERN = /^(\d+)\.(\d+)\.(\d+)$/;
|
|
45
|
+
function meetsSqliteFloor(sqliteVersion) {
|
|
46
|
+
const match = SQLITE_VERSION_PATTERN.exec(sqliteVersion ?? "");
|
|
47
|
+
if (match === null)
|
|
48
|
+
return false;
|
|
49
|
+
const [, major, minor, patch] = match;
|
|
50
|
+
if (![major, minor, patch].every((part) => {
|
|
51
|
+
const value = Number(part);
|
|
52
|
+
return Number.isSafeInteger(value) && String(value) === part;
|
|
53
|
+
}))
|
|
54
|
+
return false;
|
|
55
|
+
const floor = MINIMUM_SQLITE_VERSION.split(".").map(Number);
|
|
56
|
+
const parts = [Number(major), Number(minor), Number(patch)];
|
|
57
|
+
for (let index = 0; index < 3; index += 1) {
|
|
58
|
+
if (parts[index] !== floor[index])
|
|
59
|
+
return parts[index] > floor[index];
|
|
60
|
+
}
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
/** Source identity is a well-formedness observation, never an exact allowlist. */
|
|
64
|
+
const SQLITE_SOURCE_ID_PATTERN = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} [0-9a-f]{64}$/;
|
|
24
65
|
export class RuntimeEligibilityError extends Error {
|
|
25
66
|
code = "STORAGE_RUNTIME_INELIGIBLE";
|
|
26
67
|
constructor(message) {
|
|
@@ -32,71 +73,173 @@ function stringArray(value) {
|
|
|
32
73
|
return Array.isArray(value) && value.every((entry) => typeof entry === "string") && new Set(value).size === value.length;
|
|
33
74
|
}
|
|
34
75
|
export function assertRuntimeEligibility(identity) {
|
|
35
|
-
const
|
|
36
|
-
if (
|
|
37
|
-
|
|
76
|
+
const driver = identity.driver ?? "node-sqlite";
|
|
77
|
+
if (driver === "node-sqlite") {
|
|
78
|
+
if (!isCandidateNodeVersion(identity.nodeVersion)) {
|
|
79
|
+
throw new RuntimeEligibilityError(`durable storage requires Node >=${CANDIDATE_NODE_RANGE.minimum} within majors ${CANDIDATE_NODE_RANGE.majors.join("/")}; received ${identity.nodeVersion ?? "unavailable"}`);
|
|
80
|
+
}
|
|
81
|
+
// Real isolated qualification reproduced SIGSEGV when a transaction callback
|
|
82
|
+
// closes a connection with an active authorizer. Keep measured failures refused.
|
|
83
|
+
if (identity.nodeVersion === "v24.19.0" || identity.nodeVersion === "v25.9.0") {
|
|
84
|
+
throw new RuntimeEligibilityError("durable storage refuses this Node runtime: reproduced native transaction-close crash");
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
else if (driver === "rust-native") {
|
|
88
|
+
const node = NODE_VERSION_PATTERN.exec(identity.nodeVersion ?? "");
|
|
89
|
+
if (node === null || !node.slice(1).every((part) => Number.isSafeInteger(Number(part)) && String(Number(part)) === part)
|
|
90
|
+
|| Number(node[1]) < 22 || (Number(node[1]) === 22 && Number(node[2]) < 19)) {
|
|
91
|
+
throw new RuntimeEligibilityError(`Pi Host requires Node >=${PI_HOST_MINIMUM_NODE_VERSION}; received ${identity.nodeVersion ?? "unavailable"}`);
|
|
92
|
+
}
|
|
93
|
+
const napi = Number(identity.napiVersion ?? process.versions.napi);
|
|
94
|
+
if (!Number.isSafeInteger(napi) || napi < 8) {
|
|
95
|
+
throw new RuntimeEligibilityError(`Rust Native requires Node-API >= 8; received ${identity.napiVersion ?? "unavailable"}`);
|
|
96
|
+
}
|
|
97
|
+
const native = identity.native;
|
|
98
|
+
if (native === undefined
|
|
99
|
+
|| native.abiVersion !== NATIVE_ABI_VERSION
|
|
100
|
+
|| native.middlewareVersion !== NATIVE_DEFAULT_VERSION
|
|
101
|
+
|| native.target !== nativeTarget()) {
|
|
102
|
+
throw new RuntimeEligibilityError("Rust Native middleware version, ABI or target is not approved");
|
|
103
|
+
}
|
|
38
104
|
}
|
|
39
|
-
|
|
40
|
-
throw new RuntimeEligibilityError(
|
|
105
|
+
else {
|
|
106
|
+
throw new RuntimeEligibilityError("unknown SQLite driver");
|
|
41
107
|
}
|
|
42
|
-
if (identity.
|
|
43
|
-
throw new RuntimeEligibilityError(
|
|
108
|
+
if (!meetsSqliteFloor(identity.sqliteVersion)) {
|
|
109
|
+
throw new RuntimeEligibilityError(`durable storage requires SQLite >=${MINIMUM_SQLITE_VERSION} (upstream WAL-reset corruption fix; https://sqlite.org/wal.html section 11); received ${identity.sqliteVersion ?? "unavailable"}`);
|
|
44
110
|
}
|
|
45
|
-
if (!
|
|
111
|
+
if (!SQLITE_SOURCE_ID_PATTERN.test(identity.sqliteSourceId ?? "")) {
|
|
112
|
+
throw new RuntimeEligibilityError("durable storage SQLite source identity is missing or malformed");
|
|
113
|
+
}
|
|
114
|
+
if (!SUPPORTED_TARGETS.includes(`${identity.platform}/${identity.arch}`)) {
|
|
46
115
|
throw new RuntimeEligibilityError(`durable storage does not support ${identity.platform}/${identity.arch}`);
|
|
47
116
|
}
|
|
48
117
|
if (!stringArray(identity.compileOptions)
|
|
49
|
-
|| !
|
|
118
|
+
|| !REQUIRED_COMPILE_OPTIONS.every((option) => identity.compileOptions.includes(option))
|
|
50
119
|
|| identity.compileOptions.some((option) => FORBIDDEN_COMPILE_OPTIONS.has(option.split("=")[0] ?? ""))) {
|
|
51
120
|
throw new RuntimeEligibilityError("durable storage SQLite compile options are unavailable or unsafe");
|
|
52
121
|
}
|
|
53
122
|
if (!stringArray(identity.sqliteCapabilities)
|
|
54
|
-
|| !
|
|
123
|
+
|| !REQUIRED_SQLITE_CAPABILITIES.every((capability) => identity.sqliteCapabilities.includes(capability))) {
|
|
55
124
|
throw new RuntimeEligibilityError("durable storage SQLite APIs are unavailable or unsafe");
|
|
56
125
|
}
|
|
57
126
|
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
127
|
+
/** Self-contained so the admitted child executes the same compiled probe body.
|
|
128
|
+
* Keep this function free of module captures; only its connection argument is used. */
|
|
129
|
+
export function probeSqliteCapabilities(probe) {
|
|
130
|
+
// Require the expected SQLite result code: an unrelated busy/I/O failure
|
|
131
|
+
// does not prove authorization or constraint enforcement.
|
|
132
|
+
const rejectsWithCode = (write, expected) => {
|
|
133
|
+
try {
|
|
134
|
+
write();
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
return typeof error === "object" && error !== null && error.errcode === expected;
|
|
138
|
+
}
|
|
139
|
+
return false;
|
|
140
|
+
};
|
|
141
|
+
const active = () => probe.isTransaction;
|
|
142
|
+
const row = probe.prepare("SELECT sqlite_source_id() AS sourceId").get();
|
|
143
|
+
if (typeof row?.sourceId !== "string")
|
|
144
|
+
throw new Error("missing SQLite source identity");
|
|
145
|
+
const compileOptions = probe.prepare("PRAGMA compile_options").all().map((option) => {
|
|
146
|
+
const value = Object.values(option)[0];
|
|
147
|
+
if (typeof value !== "string")
|
|
148
|
+
throw new Error("malformed SQLite compile option");
|
|
149
|
+
return value;
|
|
150
|
+
}).sort();
|
|
151
|
+
probe.enableDefensive(true);
|
|
152
|
+
probe.exec("PRAGMA writable_schema=ON");
|
|
153
|
+
if (probe.prepare("PRAGMA writable_schema").get()?.writable_schema !== 0)
|
|
154
|
+
throw new Error("defensive mode unavailable");
|
|
155
|
+
probe.exec("CREATE TABLE runtime_probe (value INTEGER); BEGIN");
|
|
156
|
+
if (active() !== true)
|
|
157
|
+
throw new Error("transaction state unavailable");
|
|
158
|
+
const written = probe.prepare("INSERT INTO runtime_probe VALUES (?)").run(1);
|
|
159
|
+
if (written.changes !== 1 || probe.prepare("SELECT value FROM runtime_probe").get()?.value !== 1
|
|
160
|
+
|| probe.prepare("SELECT value FROM runtime_probe").all().length !== 1)
|
|
161
|
+
throw new Error("statement APIs unavailable");
|
|
162
|
+
probe.exec("ROLLBACK");
|
|
163
|
+
if (active() !== false)
|
|
164
|
+
throw new Error("transaction state unavailable");
|
|
165
|
+
// Parsed authorizer actions; preprepared statements must also be denied.
|
|
166
|
+
const savepoint = probe.prepare("SAVEPOINT runtime_probe_sp");
|
|
167
|
+
probe.setAuthorizerPolicy("deny-transaction-control");
|
|
168
|
+
const transactionDenied = rejectsWithCode(() => probe.exec("BEGIN"), 23);
|
|
169
|
+
const savepointDenied = rejectsWithCode(() => savepoint.run(), 23);
|
|
170
|
+
probe.setAuthorizerPolicy("off");
|
|
171
|
+
if (!transactionDenied || !savepointDenied || active() !== false) {
|
|
172
|
+
throw new Error("authorizer transaction/savepoint denial unavailable");
|
|
173
|
+
}
|
|
174
|
+
probe.exec("BEGIN");
|
|
175
|
+
probe.prepare("INSERT INTO runtime_probe VALUES (?)").run(2);
|
|
176
|
+
probe.exec("ROLLBACK");
|
|
177
|
+
if (active() !== false || probe.prepare("SELECT COUNT(*) AS remaining FROM runtime_probe").get()?.remaining !== 0) {
|
|
178
|
+
throw new Error("transaction reset/rollback unavailable");
|
|
179
|
+
}
|
|
180
|
+
// A committed row must remain visible after the transaction ends. Disk durability
|
|
181
|
+
// is qualified separately; this in-memory probe cannot establish it.
|
|
182
|
+
probe.exec("BEGIN");
|
|
183
|
+
probe.prepare("INSERT INTO runtime_probe VALUES (?)").run(3);
|
|
184
|
+
probe.exec("COMMIT");
|
|
185
|
+
if (active() !== false || probe.prepare("SELECT value FROM runtime_probe").get()?.value !== 3) {
|
|
186
|
+
throw new Error("transaction commit unavailable");
|
|
187
|
+
}
|
|
188
|
+
// STRICT typing: a TEXT write into an INTEGER STRICT column must be denied
|
|
189
|
+
// with SQLITE_CONSTRAINT_DATATYPE.
|
|
190
|
+
probe.exec("CREATE TABLE runtime_probe_strict (value INTEGER) STRICT");
|
|
191
|
+
if (!rejectsWithCode(() => probe.prepare("INSERT INTO runtime_probe_strict VALUES (?)").run("text"), 3091)) {
|
|
192
|
+
throw new Error("STRICT table enforcement unavailable");
|
|
193
|
+
}
|
|
194
|
+
// JSON1 functions are required by the durable schema.
|
|
195
|
+
if (probe.prepare("SELECT json_extract('{\"ce\":1}', '$.ce') AS extracted").get()?.extracted !== 1) {
|
|
196
|
+
throw new Error("JSON functions unavailable");
|
|
197
|
+
}
|
|
198
|
+
// CHECK constraints: violation denied with the expected extended code.
|
|
199
|
+
probe.exec("CREATE TABLE runtime_probe_check (value INTEGER CHECK (value > 0))");
|
|
200
|
+
if (!rejectsWithCode(() => probe.prepare("INSERT INTO runtime_probe_check VALUES (0)").run(), 275)
|
|
201
|
+
|| probe.prepare("INSERT INTO runtime_probe_check VALUES (1)").run().changes !== 1) {
|
|
202
|
+
throw new Error("CHECK constraint enforcement unavailable");
|
|
203
|
+
}
|
|
204
|
+
// Foreign-key enforcement: orphan insert and referenced-parent delete denied.
|
|
205
|
+
probe.exec("PRAGMA foreign_keys=ON");
|
|
206
|
+
probe.exec("CREATE TABLE runtime_probe_parent (id INTEGER PRIMARY KEY); CREATE TABLE runtime_probe_child (id INTEGER PRIMARY KEY, parent_id INTEGER NOT NULL REFERENCES runtime_probe_parent(id))");
|
|
207
|
+
if (!rejectsWithCode(() => probe.prepare("INSERT INTO runtime_probe_child VALUES (1, 9)").run(), 787)) {
|
|
208
|
+
throw new Error("foreign-key enforcement unavailable");
|
|
209
|
+
}
|
|
210
|
+
probe.prepare("INSERT INTO runtime_probe_parent VALUES (9)").run();
|
|
211
|
+
probe.prepare("INSERT INTO runtime_probe_child VALUES (2, 9)").run();
|
|
212
|
+
if (!rejectsWithCode(() => probe.prepare("DELETE FROM runtime_probe_parent WHERE id = 9").run(), 787)) {
|
|
213
|
+
throw new Error("foreign-key enforcement unavailable");
|
|
214
|
+
}
|
|
215
|
+
// Triggers: an AFTER INSERT trigger must fire and persist its effect.
|
|
216
|
+
probe.exec("CREATE TABLE runtime_probe_log (value INTEGER); CREATE TRIGGER runtime_probe_trigger AFTER INSERT ON runtime_probe BEGIN INSERT INTO runtime_probe_log VALUES (NEW.value); END");
|
|
217
|
+
probe.prepare("INSERT INTO runtime_probe VALUES (?)").run(4);
|
|
218
|
+
if (probe.prepare("SELECT value FROM runtime_probe_log").get()?.value !== 4) {
|
|
219
|
+
throw new Error("trigger execution unavailable");
|
|
220
|
+
}
|
|
221
|
+
return { sqliteSourceId: row.sourceId, compileOptions, sqliteCapabilities: [
|
|
222
|
+
"defensive", "statement-get", "statement-all", "statement-run", "transaction-state",
|
|
223
|
+
"authorizer-transaction", "authorizer-savepoint",
|
|
224
|
+
"transaction-commit", "strict-tables", "json-functions", "check-constraints",
|
|
225
|
+
"foreign-key-enforcement", "triggers",
|
|
226
|
+
] };
|
|
63
227
|
}
|
|
64
|
-
export function readRuntimeIdentity() {
|
|
228
|
+
export function readRuntimeIdentity(driver = resolveSqliteDriver()) {
|
|
65
229
|
let probe;
|
|
66
230
|
try {
|
|
67
|
-
probe =
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
const compileOptions = probe.prepare("PRAGMA compile_options").all().map((option) => {
|
|
72
|
-
const value = Object.values(option)[0];
|
|
73
|
-
if (typeof value !== "string")
|
|
74
|
-
throw new Error("malformed SQLite compile option");
|
|
75
|
-
return value;
|
|
76
|
-
}).sort();
|
|
77
|
-
probe.enableDefensive(true);
|
|
78
|
-
probe.exec("PRAGMA writable_schema=ON");
|
|
79
|
-
if (probe.prepare("PRAGMA writable_schema").get()?.writable_schema !== 0)
|
|
80
|
-
throw new Error("defensive mode unavailable");
|
|
81
|
-
probe.exec("CREATE TABLE runtime_probe (value INTEGER); BEGIN");
|
|
82
|
-
if (transactionState(probe) !== true)
|
|
83
|
-
throw new Error("transaction state unavailable");
|
|
84
|
-
const written = probe.prepare("INSERT INTO runtime_probe VALUES (?)").run(1);
|
|
85
|
-
if (written.changes !== 1 || probe.prepare("SELECT value FROM runtime_probe").get()?.value !== 1
|
|
86
|
-
|| probe.prepare("SELECT value FROM runtime_probe").all().length !== 1)
|
|
87
|
-
throw new Error("statement APIs unavailable");
|
|
88
|
-
probe.exec("ROLLBACK");
|
|
89
|
-
if (transactionState(probe) !== false)
|
|
90
|
-
throw new Error("transaction state unavailable");
|
|
91
|
-
return {
|
|
231
|
+
probe = driver.open(":memory:");
|
|
232
|
+
const identity = {
|
|
233
|
+
...probeSqliteCapabilities(probe),
|
|
234
|
+
driver: driver.kind,
|
|
92
235
|
nodeVersion: process.version,
|
|
93
|
-
|
|
94
|
-
|
|
236
|
+
...(process.versions.napi === undefined ? {} : { napiVersion: process.versions.napi }),
|
|
237
|
+
sqliteVersion: driver.kind === "node-sqlite" ? process.versions.sqlite : driver.nativeInfo?.sqliteVersion,
|
|
95
238
|
platform: process.platform,
|
|
96
239
|
arch: process.arch,
|
|
97
|
-
|
|
98
|
-
sqliteCapabilities: [...REQUIRED_SQLITE_CAPABILITIES],
|
|
240
|
+
...(driver.nativeInfo === undefined ? {} : { native: driver.nativeInfo }),
|
|
99
241
|
};
|
|
242
|
+
return identity;
|
|
100
243
|
}
|
|
101
244
|
catch {
|
|
102
245
|
throw new RuntimeEligibilityError("could not verify the required SQLite runtime identity and APIs");
|
|
@@ -105,8 +248,8 @@ export function readRuntimeIdentity() {
|
|
|
105
248
|
probe?.close();
|
|
106
249
|
}
|
|
107
250
|
}
|
|
108
|
-
export function assertHostRuntimeEligibility() {
|
|
109
|
-
const identity = readRuntimeIdentity();
|
|
251
|
+
export function assertHostRuntimeEligibility(driver) {
|
|
252
|
+
const identity = readRuntimeIdentity(driver);
|
|
110
253
|
assertRuntimeEligibility(identity);
|
|
111
254
|
return identity;
|
|
112
255
|
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/** Self-contained factory: stringified for the MCP child probe. Keep no module
|
|
2
|
+
* captures except the type-only import (erased at build time). */
|
|
3
|
+
export function createNodeSqliteDriver(sqliteModule) {
|
|
4
|
+
const { DatabaseSync, constants } = sqliteModule ?? process.getBuiltinModule("node:sqlite");
|
|
5
|
+
const stateError = (message) => Object.assign(new Error(message), { code: "ERR_INVALID_STATE" });
|
|
6
|
+
return {
|
|
7
|
+
kind: "node-sqlite",
|
|
8
|
+
open(path, options = {}) {
|
|
9
|
+
const db = new DatabaseSync(path, {
|
|
10
|
+
readOnly: options.readOnly ?? false,
|
|
11
|
+
defensive: options.defensive ?? true,
|
|
12
|
+
timeout: options.timeout ?? 0,
|
|
13
|
+
});
|
|
14
|
+
let closed = false;
|
|
15
|
+
let policy = "off";
|
|
16
|
+
let externalAuthorizer = false;
|
|
17
|
+
let denials = 0;
|
|
18
|
+
const ensureOpen = () => { if (closed)
|
|
19
|
+
throw stateError("database is not open"); };
|
|
20
|
+
return {
|
|
21
|
+
prepare(sql) {
|
|
22
|
+
ensureOpen();
|
|
23
|
+
const statement = db.prepare(sql);
|
|
24
|
+
return {
|
|
25
|
+
get: (...args) => { ensureOpen(); return statement.get(...args); },
|
|
26
|
+
all: (...args) => { ensureOpen(); return statement.all(...args); },
|
|
27
|
+
run: (...args) => { ensureOpen(); return { changes: Number(statement.run(...args).changes) }; },
|
|
28
|
+
};
|
|
29
|
+
},
|
|
30
|
+
exec(sql) { ensureOpen(); db.exec(sql); },
|
|
31
|
+
close() {
|
|
32
|
+
ensureOpen();
|
|
33
|
+
try {
|
|
34
|
+
db.close();
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
closed = true;
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
get isTransaction() { ensureOpen(); return db.isTransaction; },
|
|
41
|
+
enableDefensive(enabled) { ensureOpen(); db.enableDefensive(enabled); },
|
|
42
|
+
setAuthorizer(callback) { ensureOpen(); externalAuthorizer = true; db.setAuthorizer(callback); },
|
|
43
|
+
setAuthorizerPolicy(next) {
|
|
44
|
+
ensureOpen();
|
|
45
|
+
if (next === "off" && externalAuthorizer)
|
|
46
|
+
return;
|
|
47
|
+
externalAuthorizer = false;
|
|
48
|
+
policy = next;
|
|
49
|
+
if (next === "deny-transaction-control")
|
|
50
|
+
denials = 0;
|
|
51
|
+
db.setAuthorizer((action) => {
|
|
52
|
+
const deny = policy === "deny-all"
|
|
53
|
+
|| (policy === "deny-transaction-control" && (action === constants.SQLITE_TRANSACTION || action === constants.SQLITE_SAVEPOINT));
|
|
54
|
+
if (deny) {
|
|
55
|
+
denials += 1;
|
|
56
|
+
return constants.SQLITE_DENY;
|
|
57
|
+
}
|
|
58
|
+
return constants.SQLITE_OK;
|
|
59
|
+
});
|
|
60
|
+
},
|
|
61
|
+
authorizerDenials() { ensureOpen(); return externalAuthorizer ? 0 : denials; },
|
|
62
|
+
};
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
//# sourceMappingURL=sqlite-driver-node.js.map
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/** Capture-free factory. `requireFn` is supplied by the Host or child; the
|
|
2
|
+
* native path must already be trusted/verified by the artifact manager. */
|
|
3
|
+
export function createRustNativeDriver(requireFn, nativePath) {
|
|
4
|
+
const native = requireFn(nativePath);
|
|
5
|
+
let info;
|
|
6
|
+
try {
|
|
7
|
+
info = JSON.parse(native.info());
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
throw Object.assign(new Error("native module returned invalid identity"), { code: "CE_NATIVE_INFO_INVALID" });
|
|
11
|
+
}
|
|
12
|
+
const stateError = (message) => Object.assign(new Error(message), { code: "ERR_INVALID_STATE" });
|
|
13
|
+
const enrich = (caught) => {
|
|
14
|
+
if (!(caught instanceof Error) || !caught.message.startsWith("\u0001CE_SQLITE")) {
|
|
15
|
+
return caught instanceof Error ? caught : new Error(String(caught));
|
|
16
|
+
}
|
|
17
|
+
let payload;
|
|
18
|
+
try {
|
|
19
|
+
payload = JSON.parse(caught.message.slice("\u0001CE_SQLITE".length));
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return caught;
|
|
23
|
+
}
|
|
24
|
+
const error = new Error(payload.message ?? "SQLite driver failure");
|
|
25
|
+
if (payload.kind === "sqlite") {
|
|
26
|
+
Object.assign(error, { code: "ERR_SQLITE_ERROR", errcode: payload.code, errstr: payload.errstr });
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
Object.assign(error, { code: payload.kind === "state" ? "ERR_INVALID_STATE" : payload.kind === "range" ? "ERR_OUT_OF_RANGE" : payload.code });
|
|
30
|
+
}
|
|
31
|
+
return error;
|
|
32
|
+
};
|
|
33
|
+
const policyNumber = (policy) => policy === "off" ? 0 : policy === "deny-transaction-control" ? 1 : 2;
|
|
34
|
+
return {
|
|
35
|
+
kind: "rust-native",
|
|
36
|
+
nativeInfo: info,
|
|
37
|
+
nativePath,
|
|
38
|
+
open(path, options = {}) {
|
|
39
|
+
let raw;
|
|
40
|
+
try {
|
|
41
|
+
raw = new native.NativeConnection(path, {
|
|
42
|
+
readOnly: options.readOnly ?? false,
|
|
43
|
+
defensive: options.defensive ?? true,
|
|
44
|
+
timeout: options.timeout ?? 0,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
throw enrich(error);
|
|
49
|
+
}
|
|
50
|
+
let closed = false;
|
|
51
|
+
let externalAuthorizer = false;
|
|
52
|
+
const ensureOpen = () => { if (closed)
|
|
53
|
+
throw stateError("database is not open"); };
|
|
54
|
+
const call = (operation) => {
|
|
55
|
+
try {
|
|
56
|
+
return operation();
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
throw enrich(error);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
const rowObject = (names, values) => {
|
|
63
|
+
if (values === undefined)
|
|
64
|
+
return undefined;
|
|
65
|
+
const row = Object.create(null);
|
|
66
|
+
for (let index = 0; index < names.length; index += 1)
|
|
67
|
+
row[names[index]] = values[index];
|
|
68
|
+
return row;
|
|
69
|
+
};
|
|
70
|
+
return {
|
|
71
|
+
prepare(sql) {
|
|
72
|
+
ensureOpen();
|
|
73
|
+
call(() => raw.prepareOnly(sql));
|
|
74
|
+
return {
|
|
75
|
+
get: (...parameters) => {
|
|
76
|
+
ensureOpen();
|
|
77
|
+
const [names, rows] = call(() => raw.query(sql, parameters, 1));
|
|
78
|
+
return rowObject(names, rows[0]);
|
|
79
|
+
},
|
|
80
|
+
all: (...parameters) => {
|
|
81
|
+
ensureOpen();
|
|
82
|
+
const [names, rows] = call(() => raw.query(sql, parameters, 0xffffffff));
|
|
83
|
+
return rows.map((row) => rowObject(names, row));
|
|
84
|
+
},
|
|
85
|
+
run: (...parameters) => {
|
|
86
|
+
ensureOpen();
|
|
87
|
+
const [changes] = call(() => raw.execute(sql, parameters));
|
|
88
|
+
return { changes };
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
},
|
|
92
|
+
exec(sql) { ensureOpen(); call(() => raw.exec(sql)); },
|
|
93
|
+
close() {
|
|
94
|
+
ensureOpen();
|
|
95
|
+
try {
|
|
96
|
+
call(() => raw.close());
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
closed = true;
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
get isTransaction() { ensureOpen(); return call(() => raw.isTransaction()); },
|
|
103
|
+
enableDefensive(enabled) { ensureOpen(); call(() => raw.enableDefensive(enabled)); },
|
|
104
|
+
setAuthorizer(callback) {
|
|
105
|
+
ensureOpen();
|
|
106
|
+
externalAuthorizer = true;
|
|
107
|
+
call(() => raw.setAuthorizerPolicy(callback === null ? 0 : 2));
|
|
108
|
+
},
|
|
109
|
+
setAuthorizerPolicy(policy) {
|
|
110
|
+
ensureOpen();
|
|
111
|
+
if (policy === "off" && externalAuthorizer)
|
|
112
|
+
return;
|
|
113
|
+
externalAuthorizer = false;
|
|
114
|
+
call(() => raw.setAuthorizerPolicy(policyNumber(policy)));
|
|
115
|
+
},
|
|
116
|
+
authorizerDenials() { ensureOpen(); return externalAuthorizer ? 0 : call(() => raw.authorizerDenials()); },
|
|
117
|
+
};
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
//# sourceMappingURL=sqlite-driver-rust.js.map
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { closeSync, constants, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { createNodeSqliteDriver } from "./sqlite-driver-node.js";
|
|
7
|
+
import { createRustNativeDriver } from "./sqlite-driver-rust.js";
|
|
8
|
+
import { loadVerifiedNativeArtifact } from "./native-artifact.js";
|
|
9
|
+
import { NATIVE_COMPAT, parseNativeCompat } from "./native-compat.js";
|
|
10
|
+
export function defaultDriverSelectionFile() {
|
|
11
|
+
return join(homedir(), ".config", "pi-chat-exchange", "sqlite-driver.json");
|
|
12
|
+
}
|
|
13
|
+
function invalidSelection() {
|
|
14
|
+
throw Object.assign(new Error("invalid SQLite driver selection"), { code: "CE_SQLITE_DRIVER_SELECTION_INVALID" });
|
|
15
|
+
}
|
|
16
|
+
export function readDriverSelection(path = defaultDriverSelectionFile()) {
|
|
17
|
+
// Native is the only production driver. An absent file selects it at the declared default
|
|
18
|
+
// version; node-sqlite requires an explicit selection and is never a fallback.
|
|
19
|
+
if (!existsSync(path))
|
|
20
|
+
return { driver: "rust-native", nativeVersion: NATIVE_COMPAT.defaultVersion };
|
|
21
|
+
let parsed;
|
|
22
|
+
try {
|
|
23
|
+
parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return invalidSelection();
|
|
27
|
+
}
|
|
28
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
|
|
29
|
+
return invalidSelection();
|
|
30
|
+
const record = parsed;
|
|
31
|
+
if (record.version !== 1)
|
|
32
|
+
return invalidSelection();
|
|
33
|
+
if (record.driver === "node-sqlite" && Object.keys(record).length === 2)
|
|
34
|
+
return { driver: "node-sqlite" };
|
|
35
|
+
if (record.driver === "rust-native" && typeof record.nativeVersion === "string"
|
|
36
|
+
&& (Object.keys(record).length === 3 || (Object.keys(record).length === 4 && typeof record.manifestFile === "string"))) {
|
|
37
|
+
const manifestFile = record.manifestFile;
|
|
38
|
+
if (manifestFile !== undefined && (typeof manifestFile !== "string" || !manifestFile.startsWith("/") || manifestFile.includes("\u0000")))
|
|
39
|
+
return invalidSelection();
|
|
40
|
+
return { driver: "rust-native", nativeVersion: record.nativeVersion,
|
|
41
|
+
...(manifestFile === undefined ? {} : { manifestFile }) };
|
|
42
|
+
}
|
|
43
|
+
return invalidSelection();
|
|
44
|
+
}
|
|
45
|
+
/** Atomic replacement of the operator-selected driver file. */
|
|
46
|
+
export function writeDriverSelection(selection, path = defaultDriverSelectionFile()) {
|
|
47
|
+
const directory = join(path, "..");
|
|
48
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
49
|
+
const document = { version: 1, driver: selection.driver,
|
|
50
|
+
...(selection.nativeVersion === undefined ? {} : { nativeVersion: selection.nativeVersion }),
|
|
51
|
+
...(selection.manifestFile === undefined ? {} : { manifestFile: selection.manifestFile }) };
|
|
52
|
+
const temporary = join(directory, `.sqlite-driver-${randomUUID()}.tmp`);
|
|
53
|
+
const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
54
|
+
try {
|
|
55
|
+
writeFileSync(fd, `${JSON.stringify(document, null, 2)}\n`, "utf8");
|
|
56
|
+
fsyncSync(fd);
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
closeSync(fd);
|
|
60
|
+
}
|
|
61
|
+
renameSync(temporary, path);
|
|
62
|
+
}
|
|
63
|
+
/** Resolve the actual selected driver; never falls back after Native failure.
|
|
64
|
+
* `node:sqlite` is a non-default compatibility driver: it is loaded lazily and only
|
|
65
|
+
* when the operator explicitly selected it, so a Native deployment never imports it. */
|
|
66
|
+
export function resolveSqliteDriver(options = {}) {
|
|
67
|
+
const selection = readDriverSelection(options.selectionFile);
|
|
68
|
+
if (selection.driver === "node-sqlite")
|
|
69
|
+
return createNodeSqliteDriver();
|
|
70
|
+
let manifest = options.manifest ?? NATIVE_COMPAT;
|
|
71
|
+
if (selection.manifestFile !== undefined) {
|
|
72
|
+
try {
|
|
73
|
+
manifest = parseNativeCompat(JSON.parse(readFileSync(selection.manifestFile, "utf8")));
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return invalidSelection();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const verified = loadVerifiedNativeArtifact({
|
|
80
|
+
...(selection.nativeVersion === undefined ? {} : { version: selection.nativeVersion }),
|
|
81
|
+
...(options.root === undefined ? {} : { root: options.root }),
|
|
82
|
+
manifest,
|
|
83
|
+
});
|
|
84
|
+
return createRustNativeDriver(createRequire(import.meta.url), verified.path);
|
|
85
|
+
}
|
|
86
|
+
//# sourceMappingURL=sqlite-driver-selection.js.map
|
package/dist/storage/store.js
CHANGED
|
@@ -2,7 +2,7 @@ import { constants, copyFileSync, mkdtempSync, rmSync } from "node:fs";
|
|
|
2
2
|
import { tmpdir } from "node:os";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
|
-
import {
|
|
5
|
+
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";
|
|
@@ -51,7 +51,7 @@ function approvedManifest(version) {
|
|
|
51
51
|
const cached = approvedManifests[version];
|
|
52
52
|
if (cached !== undefined)
|
|
53
53
|
return cached;
|
|
54
|
-
const reference =
|
|
54
|
+
const reference = resolveSqliteDriver().open(":memory:");
|
|
55
55
|
try {
|
|
56
56
|
reference.exec(version === "v1"
|
|
57
57
|
? INITIAL_SCHEMA_SQL
|
|
@@ -342,7 +342,7 @@ function withStoreSnapshot(databasePath, validate) {
|
|
|
342
342
|
if (pathStat(`${databasePath}-wal`) !== undefined) {
|
|
343
343
|
copyFileSync(`${databasePath}-wal`, `${snapshot}-wal`, constants.COPYFILE_EXCL);
|
|
344
344
|
}
|
|
345
|
-
reader = withRestrictiveUmask(() =>
|
|
345
|
+
reader = withRestrictiveUmask(() => resolveSqliteDriver().open(snapshot, { readOnly: true, defensive: true }));
|
|
346
346
|
reader.exec("PRAGMA trusted_schema=OFF; BEGIN;");
|
|
347
347
|
return validate(reader);
|
|
348
348
|
}
|