@zieglar/pi-chat-exchange 0.2.0 → 0.2.2
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 +41 -61
- package/dist/bin/ce-native.js +119 -0
- package/dist/control/mcp/server.js +1 -1
- package/dist/host/mcp-binding-config.js +1 -1
- package/dist/runtime/diagnostics.js +3 -3
- package/dist/runtime/executables.js +37 -30
- package/dist/runtime/native-readiness.js +131 -0
- package/dist/runtime/wrapper-identity.js +53 -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/background-manager.js +5 -52
- package/dist/tunnel/codes.js +1 -1
- package/dist/tunnel/keychain.js +1 -1
- package/dist/tunnel/managed-binding.js +1 -1
- package/dist/tunnel/manager-panel.js +1 -1
- package/dist/tunnel/profile.js +4 -2
- package/dist/tunnel/setup-ui.js +3 -3
- package/dist/tunnel/tunnel-id.js +4 -0
- 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
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { normalize } from "node:path";
|
|
3
|
+
const MAX_WRAPPER_BYTES = 4096;
|
|
4
|
+
const SHEBANG_RE = /^#!(\/[^\s\u0000]+)$/;
|
|
5
|
+
// Double quotes still expand dollars and backticks; those are not literal paths.
|
|
6
|
+
const WRAPPER_EXEC_RE = /^exec "(\/[^"\\\r\n\u0000$`]+)" "\$@"$/;
|
|
7
|
+
export function resolveWrapperIdentityEvidence(clientPath, validateExecTarget) {
|
|
8
|
+
let text;
|
|
9
|
+
try {
|
|
10
|
+
const stat = statSync(clientPath);
|
|
11
|
+
if (!stat.isFile() || stat.size === 0 || stat.size > MAX_WRAPPER_BYTES)
|
|
12
|
+
return undefined;
|
|
13
|
+
text = readFileSync(clientPath, "utf8");
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
if (!text.startsWith("#!"))
|
|
19
|
+
return {};
|
|
20
|
+
const lines = text.split("\n");
|
|
21
|
+
const shebang = SHEBANG_RE.exec((lines[0] ?? "").replace(/\r$/, ""));
|
|
22
|
+
const shellPrefix = shebang !== null && /^[ -~]+$/.test(shebang[1]) && normalize(shebang[1]) === shebang[1]
|
|
23
|
+
? shebang[1]
|
|
24
|
+
: undefined;
|
|
25
|
+
const evidence = shellPrefix === undefined ? {} : { shellPrefix };
|
|
26
|
+
// The entire body must be one strict exec line, with only comments/blanks
|
|
27
|
+
// alongside it. Heredocs, extra statements and ambiguous argv yield no target.
|
|
28
|
+
const meaningful = lines.slice(1).filter((line) => {
|
|
29
|
+
const trimmed = line.trim();
|
|
30
|
+
return trimmed !== "" && !trimmed.startsWith("#");
|
|
31
|
+
});
|
|
32
|
+
if (meaningful.length !== 1)
|
|
33
|
+
return evidence;
|
|
34
|
+
const execMatch = WRAPPER_EXEC_RE.exec(meaningful[0]);
|
|
35
|
+
if (execMatch === null)
|
|
36
|
+
return evidence;
|
|
37
|
+
const target = execMatch[1];
|
|
38
|
+
if (!/^[ -~]+$/.test(target) || normalize(target) !== target)
|
|
39
|
+
return evidence;
|
|
40
|
+
// Admission must reject an invalid literal target before the identity-only
|
|
41
|
+
// parser can omit it. Do not replace the argv spelling with its canonical path.
|
|
42
|
+
validateExecTarget?.(target);
|
|
43
|
+
try {
|
|
44
|
+
if (!statSync(target).isFile())
|
|
45
|
+
return evidence;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return evidence;
|
|
49
|
+
}
|
|
50
|
+
evidence.execTarget = target;
|
|
51
|
+
return evidence;
|
|
52
|
+
}
|
|
53
|
+
//# sourceMappingURL=wrapper-identity.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { DatabaseSync } from "node:sqlite";
|
|
2
1
|
import { assertSecureDatabaseArtifacts, prepareDatabasePath, exclusivelyCreateDatabase, pathStat, withRestrictiveUmask, } from "./filesystem.js";
|
|
3
2
|
import { assertRuntimeEligibility, readRuntimeIdentity, } from "./runtime.js";
|
|
3
|
+
import { resolveSqliteDriver } from "./sqlite-driver-selection.js";
|
|
4
4
|
export const DEFAULT_BUSY_TIMEOUT_MS = 1_000;
|
|
5
5
|
export const MAX_BUSY_TIMEOUT_MS = 5_000;
|
|
6
6
|
export const WAL_AUTOCHECKPOINT_PAGES = 1_000;
|
|
@@ -12,7 +12,7 @@ export class ConnectionPolicyError extends Error {
|
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
14
|
export function assertStorageRuntimeEligibility(options) {
|
|
15
|
-
assertRuntimeEligibility((options.runtimeIdentity ?? readRuntimeIdentity)());
|
|
15
|
+
assertRuntimeEligibility((options.runtimeIdentity ?? (() => readRuntimeIdentity(options.driver)))());
|
|
16
16
|
}
|
|
17
17
|
function readPragma(db, name) {
|
|
18
18
|
const row = db.prepare(`PRAGMA ${name}`).get();
|
|
@@ -65,7 +65,8 @@ export function openStorageConnection(options, validateExisting, createExclusive
|
|
|
65
65
|
}
|
|
66
66
|
let db;
|
|
67
67
|
try {
|
|
68
|
-
|
|
68
|
+
const driver = options.driver ?? resolveSqliteDriver();
|
|
69
|
+
db = withRestrictiveUmask(() => driver.open(databasePath, { defensive: true, timeout: busyTimeoutMs }));
|
|
69
70
|
// Revalidate identity/compatibility before persistent writer PRAGMAs.
|
|
70
71
|
// A read transaction gives these checks one consistent schema/data snapshot.
|
|
71
72
|
if (validateExisting !== undefined) {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
1
2
|
import { closeSync, constants, openSync, lstatSync, mkdirSync, statfsSync, } from "node:fs";
|
|
2
3
|
import { homedir } from "node:os";
|
|
3
4
|
import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
|
|
@@ -8,8 +9,8 @@ export class FilesystemSafetyError extends Error {
|
|
|
8
9
|
this.name = "FilesystemSafetyError";
|
|
9
10
|
}
|
|
10
11
|
}
|
|
12
|
+
const DARWIN_LOCAL_FILESYSTEM_NAMES = new Set(["apfs", "hfs"]);
|
|
11
13
|
const LOCAL_FILESYSTEM_TYPES = {
|
|
12
|
-
darwin: new Set([17, 23, 26]), // HFS, HFS+, APFS
|
|
13
14
|
linux: new Set([
|
|
14
15
|
0xef53, // ext2/3/4
|
|
15
16
|
0x58465342, // XFS
|
|
@@ -35,7 +36,61 @@ function isWithin(path, parent) {
|
|
|
35
36
|
const child = relative(parent, path);
|
|
36
37
|
return child === "" || (!child.startsWith(`..${sep}`) && child !== "..");
|
|
37
38
|
}
|
|
38
|
-
|
|
39
|
+
function assertDarwinLocalFilesystem(directory) {
|
|
40
|
+
if (directory === undefined || !isAbsolute(directory)) {
|
|
41
|
+
throw new FilesystemSafetyError("a real mounted directory is required to verify the Darwin filesystem");
|
|
42
|
+
}
|
|
43
|
+
let directoryDevice;
|
|
44
|
+
try {
|
|
45
|
+
directoryDevice = lstatSync(directory).dev;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
throw new FilesystemSafetyError("unable to verify the Darwin filesystem identity");
|
|
49
|
+
}
|
|
50
|
+
let output;
|
|
51
|
+
try {
|
|
52
|
+
output = execFileSync("/sbin/mount", {
|
|
53
|
+
encoding: "utf8", shell: false, timeout: 5_000, killSignal: "SIGKILL", maxBuffer: 64 * 1024,
|
|
54
|
+
env: { PATH: "/usr/bin:/bin", LC_ALL: "C", LANG: "C" },
|
|
55
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
throw new FilesystemSafetyError("unable to verify the local Darwin filesystem");
|
|
60
|
+
}
|
|
61
|
+
let match;
|
|
62
|
+
for (const line of output.split(/\r?\n/)) {
|
|
63
|
+
const entry = /^.+? on (.+?) \(([^,\s]+)(?:,|\))/.exec(line);
|
|
64
|
+
if (entry === null)
|
|
65
|
+
continue;
|
|
66
|
+
const point = entry[1];
|
|
67
|
+
const name = entry[2];
|
|
68
|
+
if (point === undefined || name === undefined)
|
|
69
|
+
continue;
|
|
70
|
+
let mountedDevice;
|
|
71
|
+
try {
|
|
72
|
+
mountedDevice = lstatSync(point).dev;
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
// st_dev identifies the filesystem. Longest point only orders duplicate records deterministically.
|
|
78
|
+
if (mountedDevice === directoryDevice) {
|
|
79
|
+
if (match === undefined || point.length > match.point.length)
|
|
80
|
+
match = { point, name };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (match === undefined || !DARWIN_LOCAL_FILESYSTEM_NAMES.has(match.name)) {
|
|
84
|
+
throw new FilesystemSafetyError("filesystem type is not approved as local on darwin");
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
export function assertLocalFilesystemType(platform, type, directory) {
|
|
88
|
+
if (platform === "darwin") {
|
|
89
|
+
// VFS type numbers are registration-dependent. Use mount identity instead of
|
|
90
|
+
// treating a hosted runner's 0x19 or this machine's 0x1a as APFS constants.
|
|
91
|
+
assertDarwinLocalFilesystem(directory);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
39
94
|
const approved = LOCAL_FILESYSTEM_TYPES[platform];
|
|
40
95
|
if (approved === undefined || !approved.has(type)) {
|
|
41
96
|
throw new FilesystemSafetyError(`filesystem type 0x${type.toString(16)} is not approved as local on ${platform}`);
|
|
@@ -94,7 +149,7 @@ export function prepareDatabasePath(options) {
|
|
|
94
149
|
}
|
|
95
150
|
assertOwned(directoryStat, "database directory");
|
|
96
151
|
assertMode(directoryStat, 0o700, "database directory");
|
|
97
|
-
assertLocalFilesystemType(process.platform, statfsSync(directory).type);
|
|
152
|
+
assertLocalFilesystemType(process.platform, statfsSync(directory).type, directory);
|
|
98
153
|
const databasePath = resolve(directory, options.filename);
|
|
99
154
|
if (dirname(databasePath) !== directory) {
|
|
100
155
|
throw new FilesystemSafetyError("database path escapes its explicit directory");
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, isAbsolute, join, normalize } from "node:path";
|
|
5
|
+
import { closeSync, constants, existsSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
6
|
+
import { NATIVE_COMPAT } from "./native-compat.js";
|
|
7
|
+
const MAX_ASSET_BYTES = 64 * 1024 * 1024;
|
|
8
|
+
const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
|
|
9
|
+
export function nativeCacheRoot() {
|
|
10
|
+
return join(homedir(), ".config", "pi-chat-exchange", "native");
|
|
11
|
+
}
|
|
12
|
+
export function nativeTarget() {
|
|
13
|
+
if (process.platform === "darwin" && process.arch === "arm64")
|
|
14
|
+
return "aarch64-apple-darwin";
|
|
15
|
+
if (process.platform === "darwin" && process.arch === "x64")
|
|
16
|
+
return "x86_64-apple-darwin";
|
|
17
|
+
if (process.platform === "linux" && process.arch === "x64")
|
|
18
|
+
return "x86_64-unknown-linux-gnu";
|
|
19
|
+
if (process.platform === "linux" && process.arch === "arm64")
|
|
20
|
+
return "aarch64-unknown-linux-gnu";
|
|
21
|
+
throw Object.assign(new Error(`unsupported Native target ${process.platform}/${process.arch}`), { code: "CE_NATIVE_TARGET_UNSUPPORTED" });
|
|
22
|
+
}
|
|
23
|
+
function fail(code, message) {
|
|
24
|
+
throw Object.assign(new Error(message), { code });
|
|
25
|
+
}
|
|
26
|
+
function assetFor(manifest, version, target) {
|
|
27
|
+
if (!SEMVER.test(version))
|
|
28
|
+
fail("CE_NATIVE_VERSION_INVALID", "Native version must be canonical SemVer");
|
|
29
|
+
const versionEntry = manifest.versions[version];
|
|
30
|
+
if (versionEntry === undefined)
|
|
31
|
+
fail("CE_NATIVE_VERSION_UNSUPPORTED", `Native version ${version} is not in the CE compatibility manifest`);
|
|
32
|
+
const asset = versionEntry.assets[target];
|
|
33
|
+
if (asset === undefined)
|
|
34
|
+
fail("CE_NATIVE_TARGET_UNSUPPORTED", `Native version ${version} has no artifact for ${target}`);
|
|
35
|
+
if (asset.asset !== `ce-sqlite-${version}-${target}.node`) {
|
|
36
|
+
fail("CE_NATIVE_ASSET_INVALID", "Native asset name does not match the fixed version/target contract");
|
|
37
|
+
}
|
|
38
|
+
if (asset.sha256 === null || !/^[0-9a-f]{64}$/.test(asset.sha256)) {
|
|
39
|
+
fail("CE_NATIVE_ARTIFACT_UNPINNED", `Native ${version}/${target} has no verified SHA-256 in the CE manifest; prepare and loading are refused`);
|
|
40
|
+
}
|
|
41
|
+
return asset;
|
|
42
|
+
}
|
|
43
|
+
/** POSIX locks and dlopen require a path that other accounts cannot replace.
|
|
44
|
+
* Same-UID mutation remains outside this private-cache trust boundary. */
|
|
45
|
+
function assertCacheAncestors(path) {
|
|
46
|
+
if (!isAbsolute(path) || normalize(path) !== path)
|
|
47
|
+
fail("CE_NATIVE_CACHE_UNSAFE", "Native cache path must be absolute and normalized");
|
|
48
|
+
const uid = process.getuid?.();
|
|
49
|
+
if (uid === undefined)
|
|
50
|
+
fail("CE_NATIVE_CACHE_UNSAFE", "Native cache ownership is unavailable");
|
|
51
|
+
let directory = dirname(path);
|
|
52
|
+
for (;;) {
|
|
53
|
+
const stat = lstatSync(directory);
|
|
54
|
+
const stickyRoot = stat.uid === 0 && (stat.mode & 0o1000) !== 0;
|
|
55
|
+
if (stat.isSymbolicLink() || !stat.isDirectory() || (stat.uid !== uid && stat.uid !== 0)
|
|
56
|
+
|| ((stat.mode & 0o022) !== 0 && !stickyRoot)) {
|
|
57
|
+
fail("CE_NATIVE_CACHE_UNSAFE", "Native cache ancestor is not privately controlled");
|
|
58
|
+
}
|
|
59
|
+
const parent = dirname(directory);
|
|
60
|
+
if (parent === directory)
|
|
61
|
+
break;
|
|
62
|
+
directory = parent;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function assertPrivateFile(path) {
|
|
66
|
+
const stat = lstatSync(path);
|
|
67
|
+
if (stat.isSymbolicLink() || !stat.isFile())
|
|
68
|
+
fail("CE_NATIVE_CACHE_UNSAFE", "cached Native artifact must be a regular non-symlink file");
|
|
69
|
+
if (typeof process.getuid === "function" && stat.uid !== process.getuid())
|
|
70
|
+
fail("CE_NATIVE_CACHE_UNSAFE", "cached Native artifact owner mismatch");
|
|
71
|
+
if ((stat.mode & 0o777) !== 0o600)
|
|
72
|
+
fail("CE_NATIVE_CACHE_UNSAFE", "cached Native artifact must have mode 600");
|
|
73
|
+
}
|
|
74
|
+
function sha256File(path) {
|
|
75
|
+
return createHash("sha256").update(readFileSync(path)).digest("hex");
|
|
76
|
+
}
|
|
77
|
+
function ensurePrivateDirectory(path) {
|
|
78
|
+
const stat = lstatSync(path);
|
|
79
|
+
if (stat.isSymbolicLink() || !stat.isDirectory())
|
|
80
|
+
fail("CE_NATIVE_CACHE_UNSAFE", "Native cache directory must be a real directory");
|
|
81
|
+
if (typeof process.getuid === "function" && stat.uid !== process.getuid())
|
|
82
|
+
fail("CE_NATIVE_CACHE_UNSAFE", "Native cache directory owner mismatch");
|
|
83
|
+
if ((stat.mode & 0o777) !== 0o700)
|
|
84
|
+
fail("CE_NATIVE_CACHE_UNSAFE", "Native cache directory must have mode 700");
|
|
85
|
+
}
|
|
86
|
+
function makePrivateDirectory(path) {
|
|
87
|
+
if (existsSync(path)) {
|
|
88
|
+
ensurePrivateDirectory(path);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
mkdirSync(path, { recursive: true, mode: 0o700 });
|
|
92
|
+
ensurePrivateDirectory(path);
|
|
93
|
+
}
|
|
94
|
+
function fsyncDirectory(path) {
|
|
95
|
+
const fd = openSync(path, constants.O_RDONLY);
|
|
96
|
+
try {
|
|
97
|
+
fsyncSync(fd);
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
closeSync(fd);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
function writeAtomic(path, contents) {
|
|
104
|
+
const directory = join(path, "..");
|
|
105
|
+
makePrivateDirectory(directory);
|
|
106
|
+
const temporary = join(directory, `.tmp-${randomUUID()}`);
|
|
107
|
+
const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
108
|
+
try {
|
|
109
|
+
writeFileSync(fd, contents, "utf8");
|
|
110
|
+
fsyncSync(fd);
|
|
111
|
+
}
|
|
112
|
+
finally {
|
|
113
|
+
closeSync(fd);
|
|
114
|
+
}
|
|
115
|
+
renameSync(temporary, path);
|
|
116
|
+
fsyncDirectory(directory);
|
|
117
|
+
}
|
|
118
|
+
function artifactPaths(root, version, target, asset) {
|
|
119
|
+
const directory = join(root, "ce-sqlite", version, target);
|
|
120
|
+
return { directory, path: join(directory, asset), record: join(directory, "artifact.json") };
|
|
121
|
+
}
|
|
122
|
+
/** Runtime: only a cached, hash-pinned artifact can be loaded. No network access. */
|
|
123
|
+
export function loadVerifiedNativeArtifact(options = {}) {
|
|
124
|
+
const manifest = options.manifest ?? NATIVE_COMPAT;
|
|
125
|
+
const version = options.version ?? manifest.defaultVersion;
|
|
126
|
+
const root = options.root ?? nativeCacheRoot();
|
|
127
|
+
const target = nativeTarget();
|
|
128
|
+
const asset = assetFor(manifest, version, target);
|
|
129
|
+
const paths = artifactPaths(root, version, target, asset.asset);
|
|
130
|
+
if (!existsSync(paths.path))
|
|
131
|
+
fail("CE_NATIVE_CACHE_MISSING", `Native ${version}/${target} is not cached; run the explicit prepare command first`);
|
|
132
|
+
assertCacheAncestors(paths.path);
|
|
133
|
+
assertPrivateFile(paths.path);
|
|
134
|
+
const actual = sha256File(paths.path);
|
|
135
|
+
if (actual !== asset.sha256)
|
|
136
|
+
fail("CE_NATIVE_HASH_MISMATCH", `cached Native artifact hash mismatch for ${version}/${target}`);
|
|
137
|
+
assertCacheAncestors(paths.path);
|
|
138
|
+
const native = createRequire(import.meta.url)(paths.path);
|
|
139
|
+
if (native.abiVersion() !== manifest.abiVersion)
|
|
140
|
+
fail("CE_NATIVE_ABI_MISMATCH", `Native ABI ${native.abiVersion()} does not match CE ABI ${manifest.abiVersion}`);
|
|
141
|
+
let info;
|
|
142
|
+
try {
|
|
143
|
+
info = JSON.parse(native.info());
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
return fail("CE_NATIVE_INFO_INVALID", "Native module identity is not valid JSON");
|
|
147
|
+
}
|
|
148
|
+
if (info.middlewareVersion !== version || info.abiVersion !== manifest.abiVersion || info.target !== target) {
|
|
149
|
+
fail("CE_NATIVE_IDENTITY_MISMATCH", `Native identity mismatch: expected ${version}/${target}`);
|
|
150
|
+
}
|
|
151
|
+
return { path: paths.path, info, module: native };
|
|
152
|
+
}
|
|
153
|
+
/** Prepare: download a fixed asset to a temporary file, verify, and install
|
|
154
|
+
* without overwriting another version or an existing good cache entry. */
|
|
155
|
+
export async function prepareNativeArtifact(options = {}) {
|
|
156
|
+
const manifest = options.manifest ?? NATIVE_COMPAT;
|
|
157
|
+
const version = options.version ?? manifest.defaultVersion;
|
|
158
|
+
const root = options.root ?? nativeCacheRoot();
|
|
159
|
+
const target = nativeTarget();
|
|
160
|
+
const asset = assetFor(manifest, version, target);
|
|
161
|
+
const paths = artifactPaths(root, version, target, asset.asset);
|
|
162
|
+
if (existsSync(paths.path)) {
|
|
163
|
+
try {
|
|
164
|
+
return loadVerifiedNativeArtifact(options);
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
if (!options.repairCorrupt || error.code !== "CE_NATIVE_HASH_MISMATCH")
|
|
168
|
+
throw error;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const url = options.baseUrl === undefined
|
|
172
|
+
? `https://github.com/${manifest.repository}/releases/download/ce-sqlite-v${version}/${asset.asset}`
|
|
173
|
+
: `${options.baseUrl.replace(/\/$/, "")}/${asset.asset}`;
|
|
174
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
175
|
+
const response = await fetchImpl(url, { redirect: "follow" });
|
|
176
|
+
if (!response.ok)
|
|
177
|
+
fail("CE_NATIVE_DOWNLOAD_FAILED", `Native download failed with HTTP ${response.status}`);
|
|
178
|
+
const declaredLength = Number(response.headers.get("content-length") ?? "0");
|
|
179
|
+
if (declaredLength > MAX_ASSET_BYTES)
|
|
180
|
+
fail("CE_NATIVE_DOWNLOAD_FAILED", "Native asset exceeds the size limit");
|
|
181
|
+
const bytes = Buffer.from(await response.arrayBuffer());
|
|
182
|
+
if (bytes.byteLength === 0 || bytes.byteLength > MAX_ASSET_BYTES)
|
|
183
|
+
fail("CE_NATIVE_DOWNLOAD_FAILED", "Native asset is empty or exceeds the size limit");
|
|
184
|
+
const actual = createHash("sha256").update(bytes).digest("hex");
|
|
185
|
+
if (actual !== asset.sha256)
|
|
186
|
+
fail("CE_NATIVE_HASH_MISMATCH", `downloaded Native artifact hash mismatch for ${version}/${target}`);
|
|
187
|
+
makePrivateDirectory(paths.directory);
|
|
188
|
+
assertCacheAncestors(paths.path);
|
|
189
|
+
const temporary = join(paths.directory, `.download-${randomUUID()}.tmp`);
|
|
190
|
+
const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
191
|
+
try {
|
|
192
|
+
writeFileSync(fd, bytes);
|
|
193
|
+
fsyncSync(fd);
|
|
194
|
+
}
|
|
195
|
+
finally {
|
|
196
|
+
closeSync(fd);
|
|
197
|
+
}
|
|
198
|
+
try {
|
|
199
|
+
if (options.repairCorrupt && existsSync(paths.path)) {
|
|
200
|
+
// Recheck after download. Never replace unsafe entries or an already valid
|
|
201
|
+
// artifact installed by a concurrent preparer. The downloaded bytes have
|
|
202
|
+
// passed the fixed trust pin before the damaged file can be replaced.
|
|
203
|
+
assertCacheAncestors(paths.path);
|
|
204
|
+
assertPrivateFile(paths.path);
|
|
205
|
+
if (sha256File(paths.path) !== asset.sha256)
|
|
206
|
+
renameSync(temporary, paths.path);
|
|
207
|
+
else
|
|
208
|
+
unlinkSync(temporary);
|
|
209
|
+
}
|
|
210
|
+
else {
|
|
211
|
+
// link() is atomic and never overwrites an existing cache entry.
|
|
212
|
+
linkSync(temporary, paths.path);
|
|
213
|
+
unlinkSync(temporary);
|
|
214
|
+
}
|
|
215
|
+
fsyncDirectory(paths.directory);
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
rmSync(temporary, { force: true });
|
|
219
|
+
if (error.code !== "EEXIST")
|
|
220
|
+
throw error;
|
|
221
|
+
// A concurrent preparer won; verify its entry instead of replacing it.
|
|
222
|
+
}
|
|
223
|
+
const record = {
|
|
224
|
+
version,
|
|
225
|
+
target,
|
|
226
|
+
asset: asset.asset,
|
|
227
|
+
sha256: actual,
|
|
228
|
+
source: options.baseUrl === undefined ? "github-releases" : "fixture",
|
|
229
|
+
preparedAt: new Date().toISOString(),
|
|
230
|
+
};
|
|
231
|
+
writeAtomic(paths.record, `${JSON.stringify(record, null, 2)}\n`);
|
|
232
|
+
return loadVerifiedNativeArtifact(options);
|
|
233
|
+
}
|
|
234
|
+
//# sourceMappingURL=native-artifact.js.map
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** Native middleware compatibility is versioned independently of the CE npm
|
|
2
|
+
* package. The hashes below are the trust anchor shipped with CE source: a
|
|
3
|
+
* Release Asset and a checksum fetched from the same untrusted location are
|
|
4
|
+
* NOT sufficient by themselves. `null` means unpublished/unpinned and refuses
|
|
5
|
+
* both prepare and runtime loading. Fill only from the verified release gate. */
|
|
6
|
+
export const NATIVE_ABI_VERSION = 1;
|
|
7
|
+
export const NATIVE_DEFAULT_VERSION = "0.1.0";
|
|
8
|
+
export const NATIVE_REPOSITORY = "zieglar/pi-packages";
|
|
9
|
+
export function nativeAssetName(version, target) {
|
|
10
|
+
return `ce-sqlite-${version}-${target}.node`;
|
|
11
|
+
}
|
|
12
|
+
/** Validate operator-provided JSON once, before it becomes a trusted manifest. */
|
|
13
|
+
export function parseNativeCompat(value) {
|
|
14
|
+
const invalid = () => {
|
|
15
|
+
throw Object.assign(new Error("invalid Native compatibility manifest"), { code: "CE_NATIVE_MANIFEST_INVALID" });
|
|
16
|
+
};
|
|
17
|
+
const object = (entry) => typeof entry === "object" && entry !== null && !Array.isArray(entry);
|
|
18
|
+
const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?$/;
|
|
19
|
+
if (!object(value) || value.abiVersion !== NATIVE_ABI_VERSION
|
|
20
|
+
|| value.repository !== NATIVE_REPOSITORY || typeof value.defaultVersion !== "string"
|
|
21
|
+
|| !semver.test(value.defaultVersion) || !object(value.versions))
|
|
22
|
+
return invalid();
|
|
23
|
+
const targets = new Set(["aarch64-apple-darwin", "x86_64-apple-darwin",
|
|
24
|
+
"x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu"]);
|
|
25
|
+
for (const [version, entry] of Object.entries(value.versions)) {
|
|
26
|
+
if (!semver.test(version) || !object(entry) || !object(entry.assets)
|
|
27
|
+
|| Object.keys(entry.assets).length === 0)
|
|
28
|
+
return invalid();
|
|
29
|
+
for (const [target, asset] of Object.entries(entry.assets)) {
|
|
30
|
+
if (!targets.has(target) || !object(asset)
|
|
31
|
+
|| asset.asset !== nativeAssetName(version, target)
|
|
32
|
+
|| !(asset.sha256 === null || (typeof asset.sha256 === "string" && /^[0-9a-f]{64}$/.test(asset.sha256))))
|
|
33
|
+
return invalid();
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (!Object.hasOwn(value.versions, value.defaultVersion))
|
|
37
|
+
return invalid();
|
|
38
|
+
// SAFETY: every required nested field and asset has been narrowed above;
|
|
39
|
+
// TypeScript cannot retain that relationship through Object.entries.
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
// ce-sqlite-v0.1.0 immutable Release 427441708, source a8386aa…; verified by SHA256SUMS
|
|
43
|
+
// and all seven attestation subjects bound to that source commit.
|
|
44
|
+
const CE_SQLITE_V010_SHA256 = {
|
|
45
|
+
"aarch64-apple-darwin": "b3b0102931f4fd50459e435cd0ac3ad68f61f9c00c0c14366eb03ab5f4b71db3",
|
|
46
|
+
"x86_64-apple-darwin": "53f036cca6b43a75f340c192dc67b070919904ad3590f5e63fa56a6d408e180b",
|
|
47
|
+
"x86_64-unknown-linux-gnu": "d93db0cf84621495154ff98f3b293b615593967060050b38d9ceaee6871efaf7",
|
|
48
|
+
"aarch64-unknown-linux-gnu": "6186c334e362d283481182efd1c6e8eaa98702b76bd6c3e5e933d584263c99d2",
|
|
49
|
+
};
|
|
50
|
+
export const NATIVE_COMPAT = {
|
|
51
|
+
abiVersion: NATIVE_ABI_VERSION,
|
|
52
|
+
defaultVersion: NATIVE_DEFAULT_VERSION,
|
|
53
|
+
repository: NATIVE_REPOSITORY,
|
|
54
|
+
versions: {
|
|
55
|
+
[NATIVE_DEFAULT_VERSION]: {
|
|
56
|
+
assets: Object.fromEntries([
|
|
57
|
+
"aarch64-apple-darwin",
|
|
58
|
+
"x86_64-apple-darwin",
|
|
59
|
+
"x86_64-unknown-linux-gnu",
|
|
60
|
+
"aarch64-unknown-linux-gnu",
|
|
61
|
+
].map((target) => [target, { asset: nativeAssetName(NATIVE_DEFAULT_VERSION, target), sha256: CE_SQLITE_V010_SHA256[target] }])),
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
//# sourceMappingURL=native-compat.js.map
|