pi-lean-host 0.1.1 → 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 +182 -62
- package/core/api-guide-types.ts +52 -1
- package/core/api-toggle.ts +20 -1
- package/core/auth.ts +186 -0
- package/core/guide-store.ts +0 -26
- package/core/helpers.ts +173 -57
- package/core/local-helpers.ts +2 -1
- package/core/parse-api-guide.ts +316 -55
- package/core/path-template.ts +30 -1
- package/core/secrets-command.ts +338 -0
- package/core/secrets-store.ts +180 -0
- package/core/ssrf-guard.ts +5 -0
- package/core/transport.ts +114 -26
- package/package.json +14 -1
- package/tools/api-fetch.ts +113 -26
- package/tools/api-guide.ts +13 -15
- package/tools/api-learn.ts +16 -19
- package/tools/api-probe.ts +528 -53
- package/tools/utils.ts +21 -0
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/api secrets [domain [name]]` — list and provision stored API secrets.
|
|
3
|
+
*
|
|
4
|
+
* - `secrets [--help]` — list stored domains + names (names only), or show help.
|
|
5
|
+
* - `secrets <domain>` — detail view + assisted entry for a domain.
|
|
6
|
+
* - `secrets <domain> <name>` — manual entry (escape valve for the chicken-and-egg case).
|
|
7
|
+
* - `secrets <domain> --delete` — delete all secrets for a domain (interactive confirm).
|
|
8
|
+
* - `secrets <domain> <name> --delete` — delete a single secret (no confirm).
|
|
9
|
+
*
|
|
10
|
+
* All values are entered via `ctx.ui.input()` and land only in the store; the
|
|
11
|
+
* value never touches a tool result, `pi.sendMessage`, or the session file.
|
|
12
|
+
* Returns metadata-only status lines (names, never values).
|
|
13
|
+
*
|
|
14
|
+
* Headless (`ctx.hasUI` false): print direct-file-write instructions; never
|
|
15
|
+
* prompt or hang. Full usage/file-format lives behind `--help`; the bare list
|
|
16
|
+
* shows a one-line hint instead of the whole block.
|
|
17
|
+
*
|
|
18
|
+
* Focus-mode guard is **not** applied — this is a peer of `status`/`helpers`/
|
|
19
|
+
* bare `/api`, not an actuation.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
23
|
+
import {
|
|
24
|
+
deleteDomain,
|
|
25
|
+
deleteSecret,
|
|
26
|
+
getSecretsDir,
|
|
27
|
+
listDomains,
|
|
28
|
+
listNames,
|
|
29
|
+
readSecret,
|
|
30
|
+
writeSecret,
|
|
31
|
+
} from "./secrets-store.js";
|
|
32
|
+
import { findGuidesByDomain } from "./guide-store.js";
|
|
33
|
+
|
|
34
|
+
/** One-line pointer to `--help`, used in place of the full instructions block. */
|
|
35
|
+
const HELP_HINT = "Run /api secrets --help for usage & storage details.";
|
|
36
|
+
|
|
37
|
+
/** Direct-file-write instructions for headless mode / manual provisioning. */
|
|
38
|
+
function fileWriteInstructions(): string {
|
|
39
|
+
return (
|
|
40
|
+
"Secrets are stored per-domain as JSON (0600), one file per domain:\n" +
|
|
41
|
+
` ${getSecretsDir()}/<domain>.json\n\n` +
|
|
42
|
+
"Each file maps secret name → value. To provision manually, write:\n" +
|
|
43
|
+
' { "api_key": "<value>" }\n' +
|
|
44
|
+
"into `<domain>.json`, then run /api secrets <domain> to verify."
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Full usage + storage docs, surfaced by `--help`. */
|
|
49
|
+
function helpText(): string {
|
|
50
|
+
return [
|
|
51
|
+
"Usage: /api secrets [domain [name]] [--delete]",
|
|
52
|
+
" /api secrets list stored secrets (names only)",
|
|
53
|
+
" /api secrets <domain> view + provision secrets for a domain",
|
|
54
|
+
" /api secrets <domain> <name> set a single secret by name",
|
|
55
|
+
" /api secrets <domain> --delete delete all secrets for a domain (confirm)",
|
|
56
|
+
" /api secrets <domain> <name> --delete delete a single secret",
|
|
57
|
+
" /api secrets --help this help",
|
|
58
|
+
"",
|
|
59
|
+
fileWriteInstructions(),
|
|
60
|
+
].join("\n");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Handle the `secrets` subcommand of `/api`.
|
|
65
|
+
*
|
|
66
|
+
* @param args The text after "secrets" ("" / "<domain>" / "<domain> <name>")
|
|
67
|
+
* @param ctx The extension command context
|
|
68
|
+
*/
|
|
69
|
+
export async function handleSecretsSubcommand(
|
|
70
|
+
args: string,
|
|
71
|
+
ctx: ExtensionCommandContext,
|
|
72
|
+
): Promise<void> {
|
|
73
|
+
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
74
|
+
|
|
75
|
+
// `--help` (or `help`) short-circuits before domain dispatch — it must
|
|
76
|
+
// never be mistaken for a domain name.
|
|
77
|
+
if (parts.includes("--help") || parts.includes("help")) {
|
|
78
|
+
ctx.ui.notify(helpText(), "info");
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Extract the `--delete` flag; it isn't a domain or secret name.
|
|
83
|
+
const deleteFlag = parts.includes("--delete");
|
|
84
|
+
const tokens = parts.filter((p) => p !== "--delete");
|
|
85
|
+
const domain = tokens[0];
|
|
86
|
+
const name = tokens[1];
|
|
87
|
+
|
|
88
|
+
if (deleteFlag && !domain) {
|
|
89
|
+
ctx.ui.notify(
|
|
90
|
+
"Usage: /api secrets <domain> [name] --delete — see /api secrets --help.",
|
|
91
|
+
"warning",
|
|
92
|
+
);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (domain && name) {
|
|
96
|
+
if (deleteFlag) {
|
|
97
|
+
await deleteOne(ctx, domain, name);
|
|
98
|
+
} else {
|
|
99
|
+
await provisionOne(ctx, domain, name);
|
|
100
|
+
}
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (domain) {
|
|
104
|
+
if (deleteFlag) {
|
|
105
|
+
await deleteAllSecrets(ctx, domain);
|
|
106
|
+
} else {
|
|
107
|
+
await assistedEntry(ctx, domain);
|
|
108
|
+
}
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
listAll(ctx);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ── No-arg list ────────────────────────────────────────────────────
|
|
115
|
+
|
|
116
|
+
function listAll(ctx: ExtensionCommandContext): void {
|
|
117
|
+
const domains = listDomains();
|
|
118
|
+
if (domains.length === 0) {
|
|
119
|
+
ctx.ui.notify("(no secrets stored)\n\n" + HELP_HINT, "info");
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const lines = domains.map((d) => {
|
|
124
|
+
const names = listNames(d);
|
|
125
|
+
const listing = names.length ? names.join(", ") : "(no names)";
|
|
126
|
+
return ` · ${d}: ${listing}`;
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
ctx.ui.notify(
|
|
130
|
+
["Stored secrets (names only):", ...lines, "", HELP_HINT].join("\n"),
|
|
131
|
+
"info",
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Declared secret store-names for a domain, from every registered guide's
|
|
137
|
+
* `auth.secretRefs` and `auth.secretQueryRefs` (values). Empty for guides
|
|
138
|
+
* without static-key auth.
|
|
139
|
+
*/
|
|
140
|
+
function declaredSecretNames(domain: string): string[] {
|
|
141
|
+
const names = new Set<string>();
|
|
142
|
+
for (const { guide } of findGuidesByDomain(domain)) {
|
|
143
|
+
if (guide.auth.kind !== "static-key") continue;
|
|
144
|
+
for (const n of Object.values(guide.auth.secretRefs ?? {})) names.add(n);
|
|
145
|
+
for (const n of Object.values(guide.auth.secretQueryRefs ?? {})) names.add(n);
|
|
146
|
+
}
|
|
147
|
+
return [...names].sort((a, b) => a.localeCompare(b));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The guide-declared header prefix for a secret name, or undefined. When a
|
|
152
|
+
* guide maps a secret to a prefixed header, the store must hold the raw
|
|
153
|
+
* credential (the guide adds the prefix at fetch time) — surface that in the
|
|
154
|
+
* provisioning prompt so the user pastes the raw token, not the prefixed form.
|
|
155
|
+
*/
|
|
156
|
+
function declaredPrefixHint(domain: string, name: string): string | undefined {
|
|
157
|
+
for (const { guide } of findGuidesByDomain(domain)) {
|
|
158
|
+
if (guide.auth.kind !== "static-key") continue;
|
|
159
|
+
for (const [headerName, secretName] of Object.entries(
|
|
160
|
+
guide.auth.secretRefs ?? {},
|
|
161
|
+
)) {
|
|
162
|
+
if (secretName === name && guide.auth.headerPrefixes?.[headerName]) {
|
|
163
|
+
return guide.auth.headerPrefixes[headerName];
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return undefined;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ── Assisted entry: /api secrets <domain> ──────────────────────────
|
|
171
|
+
|
|
172
|
+
async function assistedEntry(
|
|
173
|
+
ctx: ExtensionCommandContext,
|
|
174
|
+
domain: string,
|
|
175
|
+
): Promise<void> {
|
|
176
|
+
const stored = listNames(domain);
|
|
177
|
+
const storedLine = stored.length ? stored.join(", ") : "(none)";
|
|
178
|
+
const declared = declaredSecretNames(domain);
|
|
179
|
+
|
|
180
|
+
if (!ctx.hasUI) {
|
|
181
|
+
ctx.ui.notify(
|
|
182
|
+
`Stored secrets for '${domain}': ${storedLine}\n\n` +
|
|
183
|
+
fileWriteInstructions(),
|
|
184
|
+
"info",
|
|
185
|
+
);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const detailLines = [`🔐 Secrets for '${domain}'`, ` Stored: ${storedLine}`];
|
|
190
|
+
if (declared.length > 0) {
|
|
191
|
+
detailLines.push(` Declared (guide): ${declared.join(", ")}`);
|
|
192
|
+
const missing = declared.filter((n) => !stored.includes(n));
|
|
193
|
+
if (missing.length) detailLines.push(` Missing: ${missing.join(", ")}`);
|
|
194
|
+
}
|
|
195
|
+
ctx.ui.notify(detailLines.join("\n"), "info");
|
|
196
|
+
|
|
197
|
+
// Guide-aware assisted entry: exactly one declared secret name → prompt
|
|
198
|
+
// its value directly; multiple → a picker. No declared names (public API
|
|
199
|
+
// or no registered guide) → fall back to a name + value prompt.
|
|
200
|
+
if (declared.length === 1) {
|
|
201
|
+
await promptAndStore(ctx, domain, declared[0]!);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (declared.length > 1) {
|
|
205
|
+
const picked = await ctx.ui.select(
|
|
206
|
+
`Secret to provision for '${domain}'`,
|
|
207
|
+
declared,
|
|
208
|
+
);
|
|
209
|
+
if (picked === undefined) {
|
|
210
|
+
ctx.ui.notify("Cancelled — nothing stored.", "info");
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
await promptAndStore(ctx, domain, picked);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const newName = await ctx.ui.input(
|
|
218
|
+
`Secret name for '${domain}'`,
|
|
219
|
+
"e.g. api_key",
|
|
220
|
+
);
|
|
221
|
+
if (newName === undefined) return; // cancelled
|
|
222
|
+
const trimmedName = newName.trim();
|
|
223
|
+
if (!trimmedName) {
|
|
224
|
+
ctx.ui.notify("Aborted — empty secret name.", "warning");
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
await promptAndStore(ctx, domain, trimmedName);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Prompt for a secret's value and store it. Value never leaves the store. */
|
|
231
|
+
async function promptAndStore(
|
|
232
|
+
ctx: ExtensionCommandContext,
|
|
233
|
+
domain: string,
|
|
234
|
+
name: string,
|
|
235
|
+
): Promise<void> {
|
|
236
|
+
const prefix = declaredPrefixHint(domain, name);
|
|
237
|
+
const value = await ctx.ui.input(
|
|
238
|
+
prefix
|
|
239
|
+
? `Value for '${domain}'.${name} (raw token — the guide adds \`${prefix}\`)`
|
|
240
|
+
: `Value for '${domain}'.${name}`,
|
|
241
|
+
prefix ? "paste the raw token" : "paste the secret value",
|
|
242
|
+
);
|
|
243
|
+
if (value === undefined) return; // cancelled
|
|
244
|
+
const trimmed = value.trim();
|
|
245
|
+
if (!trimmed) {
|
|
246
|
+
ctx.ui.notify("Aborted — empty value.", "warning");
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
writeSecret(domain, name, trimmed);
|
|
250
|
+
ctx.ui.notify(`Stored secret '${name}' for '${domain}'.`, "info");
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// ── Delete: /api secrets <domain> [name] --delete ──────────────────
|
|
254
|
+
|
|
255
|
+
// Delete a single secret. Explicit by name — no confirmation, headless or not
|
|
256
|
+
// (deleting needs no value from the user, so headless never hangs).
|
|
257
|
+
async function deleteOne(
|
|
258
|
+
ctx: ExtensionCommandContext,
|
|
259
|
+
domain: string,
|
|
260
|
+
name: string,
|
|
261
|
+
): Promise<void> {
|
|
262
|
+
if (readSecret(domain, name) === null) {
|
|
263
|
+
ctx.ui.notify(`No secret '${name}' stored for '${domain}'.`, "warning");
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
deleteSecret(domain, name);
|
|
267
|
+
ctx.ui.notify(`Deleted secret '${name}' for '${domain}'.`, "info");
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Delete all secrets for a domain. The bigger hammer (wipes several keys at
|
|
271
|
+
// once) — confirm once in interactive mode. Headless skips the confirm and
|
|
272
|
+
// just does it; no prompt, no hang.
|
|
273
|
+
async function deleteAllSecrets(
|
|
274
|
+
ctx: ExtensionCommandContext,
|
|
275
|
+
domain: string,
|
|
276
|
+
): Promise<void> {
|
|
277
|
+
const names = listNames(domain);
|
|
278
|
+
if (names.length === 0) {
|
|
279
|
+
ctx.ui.notify(`No secrets stored for '${domain}'.`, "warning");
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
if (ctx.hasUI) {
|
|
283
|
+
const ok = await ctx.ui.confirm(
|
|
284
|
+
`Delete all secrets for '${domain}'?`,
|
|
285
|
+
`This removes: ${names.join(", ")}.`,
|
|
286
|
+
);
|
|
287
|
+
if (!ok) {
|
|
288
|
+
ctx.ui.notify("Cancelled — nothing deleted.", "info");
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
deleteDomain(domain);
|
|
293
|
+
ctx.ui.notify(`Deleted all secrets for '${domain}'.`, "info");
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// ── Manual entry: /api secrets <domain> <name> ─────────────────────
|
|
297
|
+
|
|
298
|
+
async function provisionOne(
|
|
299
|
+
ctx: ExtensionCommandContext,
|
|
300
|
+
domain: string,
|
|
301
|
+
name: string,
|
|
302
|
+
): Promise<void> {
|
|
303
|
+
if (!ctx.hasUI) {
|
|
304
|
+
ctx.ui.notify(
|
|
305
|
+
`No interactive UI — write the value for '${name}' in ` +
|
|
306
|
+
`${getSecretsDir()}/${domain}.json manually.\n\n` +
|
|
307
|
+
fileWriteInstructions(),
|
|
308
|
+
"info",
|
|
309
|
+
);
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// Escape-valve validation: when a guide declares secret names, a manual
|
|
314
|
+
// name outside them is likely a typo — warn but still store (this is the
|
|
315
|
+
// chicken-and-egg escape hatch).
|
|
316
|
+
const declared = declaredSecretNames(domain);
|
|
317
|
+
if (declared.length > 0 && !declared.includes(name)) {
|
|
318
|
+
ctx.ui.notify(
|
|
319
|
+
`⚠ '${name}' is not a declared secret for '${domain}' ` +
|
|
320
|
+
`(guide declares: ${declared.join(", ")}). Storing anyway.`,
|
|
321
|
+
"warning",
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const value = await ctx.ui.input(
|
|
326
|
+
`Value for '${domain}'.${name}`,
|
|
327
|
+
"paste the secret value",
|
|
328
|
+
);
|
|
329
|
+
if (value === undefined) return; // cancelled
|
|
330
|
+
const trimmed = value.trim();
|
|
331
|
+
if (!trimmed) {
|
|
332
|
+
ctx.ui.notify("Aborted — empty value.", "warning");
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
writeSecret(domain, name, trimmed);
|
|
337
|
+
ctx.ui.notify(`Stored secret '${name}' for '${domain}'.`, "info");
|
|
338
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Secrets store — per-domain secret name → value persistence.
|
|
3
|
+
*
|
|
4
|
+
* File backend: `~/.pi/agent/pi-lean-host/secrets/<domain>.json`, one flat
|
|
5
|
+
* JSON object per domain keyed by secret name → value (matches the `secretName`
|
|
6
|
+
* in the future `auth.secretRefs`/`auth.secretQueryRefs` schema fields).
|
|
7
|
+
*
|
|
8
|
+
* Security posture:
|
|
9
|
+
* - Files are written 0600.
|
|
10
|
+
* - The dir is created **lazily on write only**; reads/list never mkdir, so a
|
|
11
|
+
* read-only `$HOME` doesn't get a `secrets/` dir created under it.
|
|
12
|
+
* - Listing surfaces names only, never values.
|
|
13
|
+
*
|
|
14
|
+
* The store is swappable (the `SecretStore` interface + `setStore`) so the
|
|
15
|
+
* deferred OS-keychain backend is a drop-in without touching callers.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { join } from "node:path";
|
|
19
|
+
import { homedir } from "node:os";
|
|
20
|
+
import {
|
|
21
|
+
chmodSync,
|
|
22
|
+
existsSync,
|
|
23
|
+
mkdirSync,
|
|
24
|
+
readFileSync,
|
|
25
|
+
readdirSync,
|
|
26
|
+
rmSync,
|
|
27
|
+
writeFileSync,
|
|
28
|
+
} from "node:fs";
|
|
29
|
+
import { assertSafeDomain } from "./path-template.js";
|
|
30
|
+
|
|
31
|
+
/** A secret store: read/write/delete one name, list domain/name indexes. */
|
|
32
|
+
export interface SecretStore {
|
|
33
|
+
read(domain: string, name: string): string | null;
|
|
34
|
+
write(domain: string, name: string, value: string): void;
|
|
35
|
+
delete(domain: string, name: string): void;
|
|
36
|
+
deleteDomain(domain: string): void;
|
|
37
|
+
listDomains(): string[];
|
|
38
|
+
listNames(domain: string): string[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Reject a secret name that isn't a clean JSON key. */
|
|
42
|
+
function assertSecretName(name: string): void {
|
|
43
|
+
if (name.length === 0 || /[/\\\0]/.test(name)) {
|
|
44
|
+
throw new Error(
|
|
45
|
+
`Invalid secret name '${name}': must be a single name with no '/', '\\', or NUL.`,
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** File-backed store rooted at `dir` (one `<domain>.json` per domain). */
|
|
51
|
+
export function createFileStore(dir: string): SecretStore {
|
|
52
|
+
const domainPath = (domain: string): string => {
|
|
53
|
+
assertSafeDomain(domain);
|
|
54
|
+
return join(dir, `${domain}.json`);
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// Read a domain file as a flat name→value map. Missing/corrupt file → {}.
|
|
58
|
+
// Never touches the filesystem's dir structure (no mkdir).
|
|
59
|
+
const readFile = (domain: string): Record<string, string> => {
|
|
60
|
+
const p = domainPath(domain);
|
|
61
|
+
if (!existsSync(p)) return {};
|
|
62
|
+
try {
|
|
63
|
+
const parsed = JSON.parse(readFileSync(p, "utf-8"));
|
|
64
|
+
return parsed && typeof parsed === "object"
|
|
65
|
+
? (parsed as Record<string, string>)
|
|
66
|
+
: {};
|
|
67
|
+
} catch {
|
|
68
|
+
return {};
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
return {
|
|
73
|
+
read(domain, name) {
|
|
74
|
+
const value = readFile(domain)[name];
|
|
75
|
+
return typeof value === "string" ? value : null;
|
|
76
|
+
},
|
|
77
|
+
write(domain, name, value) {
|
|
78
|
+
const p = domainPath(domain); // also asserts domain safety
|
|
79
|
+
assertSecretName(name);
|
|
80
|
+
// Lazy mkdir on write only — never on read/list.
|
|
81
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
82
|
+
const file = readFile(domain);
|
|
83
|
+
file[name] = value;
|
|
84
|
+
writeFileSync(p, JSON.stringify(file, null, 2) + "\n", { mode: 0o600 });
|
|
85
|
+
try {
|
|
86
|
+
chmodSync(p, 0o600); // guard against umask overriding the mode
|
|
87
|
+
} catch {
|
|
88
|
+
// best-effort; file was already written
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
delete(domain, name) {
|
|
92
|
+
const p = domainPath(domain); // also asserts domain safety
|
|
93
|
+
assertSecretName(name);
|
|
94
|
+
if (!existsSync(p)) return;
|
|
95
|
+
const file = readFile(domain);
|
|
96
|
+
if (!Object.hasOwn(file, name)) return;
|
|
97
|
+
delete file[name];
|
|
98
|
+
if (Object.keys(file).length === 0) {
|
|
99
|
+
// Prune the empty file so the domain drops out of listDomains.
|
|
100
|
+
rmSync(p, { force: true });
|
|
101
|
+
} else {
|
|
102
|
+
writeFileSync(p, JSON.stringify(file, null, 2) + "\n", { mode: 0o600 });
|
|
103
|
+
try {
|
|
104
|
+
chmodSync(p, 0o600);
|
|
105
|
+
} catch {
|
|
106
|
+
// best-effort; file was already written
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
},
|
|
110
|
+
deleteDomain(domain) {
|
|
111
|
+
const p = domainPath(domain); // also asserts domain safety
|
|
112
|
+
if (existsSync(p)) rmSync(p, { force: true });
|
|
113
|
+
},
|
|
114
|
+
listDomains() {
|
|
115
|
+
if (!existsSync(dir)) return [];
|
|
116
|
+
return readdirSync(dir)
|
|
117
|
+
.filter((f) => f.endsWith(".json"))
|
|
118
|
+
.map((f) => f.slice(0, -".json".length))
|
|
119
|
+
.sort((a, b) => a.localeCompare(b));
|
|
120
|
+
},
|
|
121
|
+
listNames(domain) {
|
|
122
|
+
return Object.keys(readFile(domain)).sort((a, b) => a.localeCompare(b));
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
128
|
+
// Module singleton (default file backend) + override hooks
|
|
129
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
130
|
+
|
|
131
|
+
const DEFAULT_DIR = join(homedir(), ".pi", "agent", "pi-lean-host", "secrets");
|
|
132
|
+
|
|
133
|
+
let _dir = DEFAULT_DIR;
|
|
134
|
+
let _store: SecretStore = createFileStore(_dir);
|
|
135
|
+
|
|
136
|
+
/** Resolve the active store's directory (file backend). */
|
|
137
|
+
export function getSecretsDir(): string {
|
|
138
|
+
return _dir;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Point the file backend at a different directory (test hook). */
|
|
142
|
+
export function setSecretsDir(dir: string): void {
|
|
143
|
+
_dir = dir;
|
|
144
|
+
_store = createFileStore(dir);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Swap in a different store backend (e.g. OS-keychain, deferred). */
|
|
148
|
+
export function setStore(store: SecretStore): void {
|
|
149
|
+
_store = store;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Convenience API (delegates to the active store).
|
|
153
|
+
export function readSecret(domain: string, name: string): string | null {
|
|
154
|
+
return _store.read(domain, name);
|
|
155
|
+
}
|
|
156
|
+
export function writeSecret(domain: string, name: string, value: string): void {
|
|
157
|
+
_store.write(domain, name, value);
|
|
158
|
+
}
|
|
159
|
+
export function deleteSecret(domain: string, name: string): void {
|
|
160
|
+
_store.delete(domain, name);
|
|
161
|
+
}
|
|
162
|
+
export function deleteDomain(domain: string): void {
|
|
163
|
+
_store.deleteDomain(domain);
|
|
164
|
+
}
|
|
165
|
+
export function listDomains(): string[] {
|
|
166
|
+
return _store.listDomains();
|
|
167
|
+
}
|
|
168
|
+
export function listNames(domain: string): string[] {
|
|
169
|
+
return _store.listNames(domain);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Suffix naming the *other* provisioned domains (names only) for a store-miss
|
|
174
|
+
* note — " — provisioned domains: a, b" — or "" when none. Lets a miss tell
|
|
175
|
+
* the authoring agent where the key actually lives without an `ls`.
|
|
176
|
+
*/
|
|
177
|
+
export function provisionedDomainsSuffix(domain: string): string {
|
|
178
|
+
const others = listDomains().filter((d) => d !== domain);
|
|
179
|
+
return others.length > 0 ? ` — provisioned domains: ${others.join(", ")}` : "";
|
|
180
|
+
}
|
package/core/ssrf-guard.ts
CHANGED
|
@@ -29,6 +29,11 @@ const INTERNAL_IP_REGEX =
|
|
|
29
29
|
|
|
30
30
|
// ─── Guard ───────────────────────────────────────────────────────────
|
|
31
31
|
|
|
32
|
+
/**
|
|
33
|
+
* `reason` is hostname-only by design — never embed the full URL here:
|
|
34
|
+
* query secrets live in URLs, and transport surfaces `reason` verbatim
|
|
35
|
+
* (SsrfBlockedError, transport.ts).
|
|
36
|
+
*/
|
|
32
37
|
export function ssrfGuard(
|
|
33
38
|
rawUrl: string,
|
|
34
39
|
): { ok: true } | { ok: false; reason: string } {
|