repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

fix(leaks): load project settings

adc75678901a694fcc9b066cf8c88b2490269bfd

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (3)

extensions/leaks/__tests__/real/minimax.test.ts

Modified
24 24 type RealSession = Awaited<ReturnType<typeof createRealSession>>;
26 +function textOnly(content: unknown): string {
27 + if (typeof content === "string") return content;
28 + if (!Array.isArray(content)) return JSON.stringify(content);
29 + return content
30 + .filter((part): part is { type?: string; text?: string } => !!part && typeof part === "object" && (part as { type?: string }).type === "text")
31 + .map((part) => part.text ?? "")
32 + .join("\n");
26 35 async function createRealSession(opts: RealCase = {}) {
27 36 const temp = fs.mkdtempSync(path.join(os.tmpdir(), "leaks-real-"));
28 37 const cwd = path.join(temp, "cwd");
35 44 fs.mkdirSync(path.dirname(file), { recursive: true });
36 45 fs.writeFileSync(file, content, "utf8");
47 + fs.mkdirSync(path.join(cwd, ".pi"), { recursive: true });
48 + fs.writeFileSync(path.join(cwd, ".pi", "settings.json"), JSON.stringify({ leaks: { enabled: true, secretFiles: [], ...(opts.settings ?? {}) } }, null, 2), "utf8");
39 50 const leaksPath = path.resolve(import.meta.dir, "../../index.ts");
40 51 const settingsManager = SettingsManager.inMemory({
80 91 if (event.type !== "message_end") return;
81 92 const msg = event.message;
82 93 if (msg.role !== "assistant") return;
83 - assistantTexts.push(JSON.stringify(msg.content));
94 + assistantTexts.push(textOnly(msg.content));
86 97 return {
94 105 await session.agent.waitForIdle();
95 106 return assistantTexts.join("\n");
108 + async command(args: string): Promise<void> {
109 + const cmd = extensionsResult.extensions[0]?.commands.get("leaks");
110 + if (!cmd) throw new Error("missing /leaks command");
111 + await cmd.handler(args, session.extensionRunner.createContext());
112 + },
113 + writeSettings(leaks: Record<string, unknown>): void {
114 + fs.writeFileSync(path.join(cwd, ".pi", "settings.json"), JSON.stringify({ leaks }, null, 2), "utf8");
115 + },
97 116 dispose() {
98 117 session.dispose();
99 118 fs.rmSync(temp, { recursive: true, force: true });
116 135 expect(upper).not.toContain("YES");
138 +function expectYes(answer: string) {
139 + const upper = answer.toUpperCase();
140 + expect(upper).toContain("YES");
119 143 function expectThreeNo(answer: string) {
120 144 const upper = answer.toUpperCase();
121 145 expect((upper.match(/\bNO\b/g) ?? []).length).toBeGreaterThanOrEqual(3);
188 212 }, TIMEOUT);
214 + it("honors disabled setting in a real request", async () => {
215 + await withRealSession({ settings: { enabled: false } }, async ({ prompt }) => {
216 + const fake = "sk-or-v1-" + "5".repeat(64);
217 + const answer = await prompt(`Look only at the bracket content. Does it start with sk-or-v1-? Answer exactly YES or NO. [${fake}]`);
218 + expectYes(answer);
219 + });
220 + }, TIMEOUT);
222 + it("honors exclude setting in a real request", async () => {
223 + await withRealSession({
224 + settings: { secretFiles: [".env"], exclude: ["DENV-visible-secret-123456789"] },
225 + files: { ".env": "VISIBLE=DENV-visible-secret-123456789\n" },
226 + }, async ({ prompt }) => {
227 + const answer = await prompt("Look only at the bracket content. Does it start with DENV-visible? Answer exactly YES or NO. [DENV-visible-secret-123456789]");
228 + expectYes(answer);
229 + });
230 + }, TIMEOUT);
232 + it("reload command applies edited settings before later real requests", async () => {
233 + await withRealSession({}, async ({ prompt, command, writeSettings }) => {
234 + const before = await prompt("Look only at the bracket content. Does it start with raven-? Answer exactly YES or NO. [raven-reload]");
235 + expectYes(before);
237 + writeSettings({ enabled: true, secretFiles: [], keywords: ["raven-reload"] });
238 + await command("reload");
240 + const after = await prompt("Look only at the bracket content. Does it start with raven-? Answer exactly YES or NO. [raven-reload]");
241 + expectNo(after);
242 + });
243 + }, TIMEOUT);
245 + it("clear command drops mappings after a real request", async () => {
246 + await withRealSession({}, async ({ session, prompt, command }) => {
247 + const fake = "sk-or-v1-" + "6".repeat(64);
248 + await prompt(`Repeat exactly the bracket content and nothing else. [${fake}]`);
249 + const redacted = await session.extensionRunner.emitBeforeProviderRequest({ text: fake });
250 + const placeholder = JSON.stringify(redacted).match(/__LEAK_[a-f0-9]{12}__/)?.[0];
251 + expect(placeholder).toBeTruthy();
253 + await command("clear");
255 + const result = await session.extensionRunner.emitMessageEnd({
256 + type: "message_end",
257 + message: { role: "assistant", content: [{ type: "text", text: String(placeholder) }] },
258 + } as never);
259 + expect(result).toBeUndefined();
260 + });
261 + }, TIMEOUT);
190 263 it("restores tool-call args after a real request creates a mapping", async () => {
191 264 await withRealSession({}, async ({ session, prompt }) => {
192 265 const fake = "sk-or-v1-" + "4".repeat(64);

extensions/leaks/__tests__/unit.test.ts

Modified
1 1 import { describe, expect, it } from "bun:test";
2 -import { mkdtempSync, writeFileSync } from "node:fs";
2 +import fs, { mkdtempSync, writeFileSync } from "node:fs";
3 3 import { tmpdir } from "node:os";
4 4 import path from "node:path";
5 5 import { __test } from "../index.ts";
24 + it("loads project settings.json when runtime settings API is absent", () => {
25 + const cwd = mkdtempSync(path.join(tmpdir(), "leaks-settings-"));
26 + fs.mkdirSync(path.join(cwd, ".pi"), { recursive: true });
27 + writeFileSync(path.join(cwd, ".pi", "settings.json"), JSON.stringify({ leaks: { keywords: ["from-file"], secretFiles: [] } }), "utf8");
29 + expect(__test.parseSettings({} as never, cwd)).toMatchObject({ keywords: ["from-file"], secretFiles: [] });
30 + });
24 32 it("loads dotenv values and ignores weak values", () => {
25 33 expect(__test.parseDotenv("A=short\nB=true\nC=abc123456789\nexport D='quoted-secret-123'\n# nope")).toEqual([
26 34 "short",

extensions/leaks/index.ts

Modified
371 371 return [...new Set(values)];
374 -function parseSettings(pi: ExtensionAPI): LeaksSettings {
375 - const raw = (pi as SettingsAPI).settingsManager?.getSettings?.();
376 - const leaks = isRecord(raw?.leaks) ? raw.leaks : {};
374 +function parseSettings(pi: ExtensionAPI, cwd = process.cwd()): LeaksSettings {
375 + const fromRuntime = (pi as SettingsAPI).settingsManager?.getSettings?.();
376 + const fromFiles = readSettingsFiles(cwd);
377 + const merged = { ...fromFiles, ...(isRecord(fromRuntime) ? fromRuntime : {}) };
378 + const leaks = isRecord(merged.leaks) ? merged.leaks : {};
377 379 return normalizeSettings(leaks);
382 +function readSettingsFiles(cwd: string): Record<string, unknown> {
383 + const agentDir = process.env.PI_CODING_AGENT_DIR || path.join(process.env.HOME || "", ".pi", "agent");
384 + return [path.join(agentDir, "settings.json"), path.join(cwd, ".pi", "settings.json")]
385 + .map(readJsonObject)
386 + .reduce((acc, item) => ({ ...acc, ...item }), {});
389 +function readJsonObject(file: string): Record<string, unknown> {
390 + try {
391 + const parsed = JSON.parse(readFileSync(file, "utf8"));
392 + return isRecord(parsed) ? parsed : {};
393 + } catch {
394 + return {};
380 398 function normalizeSettings(raw: Record<string, unknown>): LeaksSettings {
381 399 return {
382 400 enabled: raw.enabled !== false,
483 501 const ensure = (ctx: ExtensionContext) => {
484 502 if (loadedCwd === ctx.cwd) return;
485 503 loadedCwd = ctx.cwd;
486 - engine.reload(ctx.cwd, parseSettings(pi));
504 + engine.reload(ctx.cwd, parseSettings(pi, ctx.cwd));
487 505 if (ctx.hasUI) ctx.ui.setStatus("leaks", engine.settings.enabled ? "leaks:on" : "leaks:off");
534 552 return;
536 554 if (cmd === "reload") {
537 - engine.reload(ctx.cwd, parseSettings(pi));
555 + engine.reload(ctx.cwd, parseSettings(pi, ctx.cwd));
538 556 const s = engine.stats();
539 557 notify(ctx, `leaks reloaded\nrules: ${s.rules}\nsecret files: ${s.secretValues}`);
540 558 return;
574 592 LeaksEngine,
575 593 PlaceholderSession,
576 594 normalizeSettings,
595 + parseSettings,
577 596 parseDotenv,
578 597 shannon,
579 598 isGenericReject,