31 lines
1.2 KiB
JavaScript
31 lines
1.2 KiB
JavaScript
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
import { homedir } from "node:os";
|
|
import { dirname, join, resolve } from "node:path";
|
|
|
|
export function ensurePiTrust(harnessDir, agentDir = join(homedir(), ".pi", "agent")) {
|
|
const trustPath = join(agentDir, "trust.json");
|
|
let trust = {};
|
|
try {
|
|
trust = JSON.parse(readFileSync(trustPath, "utf8"));
|
|
} catch (error) {
|
|
if (error?.code !== "ENOENT") throw error;
|
|
}
|
|
if (!trust || typeof trust !== "object" || Array.isArray(trust)) {
|
|
throw new Error(`Invalid Pi trust store: ${trustPath}`);
|
|
}
|
|
|
|
const canonicalHarness = resolve(harnessDir);
|
|
if (trust[canonicalHarness] === true) return false;
|
|
|
|
mkdirSync(dirname(trustPath), { recursive: true });
|
|
const next = { ...trust, [canonicalHarness]: true };
|
|
const temporaryPath = `${trustPath}.${process.pid}.tmp`;
|
|
writeFileSync(temporaryPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
|
|
renameSync(temporaryPath, trustPath);
|
|
return true;
|
|
}
|
|
|
|
if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) {
|
|
ensurePiTrust(process.argv[2] ?? process.env.THT_HARNESS_DIR ?? "/app/harness");
|
|
}
|