pi-lean-host 0.4.0 → 0.6.0
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 +194 -557
- package/core/api-guide-types.ts +250 -47
- package/core/api-toggle.ts +244 -39
- package/core/auth.ts +997 -76
- package/core/delete-command.ts +1 -1
- package/core/fs-0600.ts +39 -0
- package/core/guide-catalog.ts +349 -0
- package/core/guide-picker.ts +76 -61
- package/core/guide-store.ts +2 -2
- package/core/helpers.ts +532 -151
- package/core/local-helpers.ts +7 -0
- package/core/oauth-command.ts +913 -0
- package/core/oauth-flow.ts +392 -0
- package/core/oauth-store.ts +306 -0
- package/core/parse-api-guide.ts +1125 -596
- package/core/path-template.ts +101 -0
- package/core/portal-projection.ts +3 -4
- package/core/resolve-op.ts +113 -67
- package/core/response-spill.ts +10 -7
- package/core/secrets-command.ts +18 -13
- package/core/secrets-store.ts +11 -44
- package/core/select-picker.ts +171 -0
- package/core/staging.ts +29 -0
- package/core/transport.ts +322 -35
- package/core/verify-command.ts +93 -65
- package/docs/migration-v1.md +56 -0
- package/index.ts +12 -10
- package/package.json +16 -6
- package/tools/api-fetch.ts +45 -18
- package/tools/api-guide.ts +37 -67
- package/tools/api-learn.ts +148 -103
- package/tools/api-probe.ts +458 -294
- package/tools/api-scaffold.ts +34 -63
- package/tools/api-store.ts +381 -0
- package/tools/oauth-mint.ts +338 -0
- package/tools/utils.ts +70 -1
- package/core/verify-ship-manifest.ts +0 -118
- package/tools/index.ts +0 -8
package/core/path-template.ts
CHANGED
|
@@ -5,12 +5,98 @@
|
|
|
5
5
|
* and parse-api-guide.ts) so the executor (`restGet`/`paginate`), the
|
|
6
6
|
* authoring tool (`api-probe`), and the parser share one implementation.
|
|
7
7
|
*
|
|
8
|
+
* - `tokenizeJsonPath` — tokenize a JSON path into key/index segments.
|
|
9
|
+
* Shared by the executor (`helpers.ts`) and the parser
|
|
10
|
+
* (`parse-api-guide.ts`, which must not import the executor module) so
|
|
11
|
+
* the path grammar exists exactly once.
|
|
8
12
|
* - `extractPathTokens` — pull `{token}` names out of a templated path.
|
|
9
13
|
* - `fillPathTemplate` — substitute `{token}` placeholders from params.
|
|
10
14
|
* - `joinUrl` — join a base host + path + query string into a full URL.
|
|
11
15
|
* - `assertSafeDomain` — reject a domain that could escape the guides dir.
|
|
12
16
|
*/
|
|
13
17
|
|
|
18
|
+
/**
|
|
19
|
+
* Tokenize a JSON path into key/index segments in a single pass.
|
|
20
|
+
*
|
|
21
|
+
* - Dot segments split on `.` as before (unquoted legacy paths parse
|
|
22
|
+
* identically to the old regex-rewrite tokenizer).
|
|
23
|
+
* - Numeric brackets `[3]` become index segments.
|
|
24
|
+
* - Quoted brackets `['@odata.nextLink']` / `["@odata.nextLink"]` become
|
|
25
|
+
* ATOMIC key segments — the dot inside is part of the key name, not a
|
|
26
|
+
* separator. The old rewrite turned the quoted segment into `.nextLink`
|
|
27
|
+
* and silently missed the literal key.
|
|
28
|
+
*
|
|
29
|
+
* Syntax limits (documented, not handled): a quoted segment's content may
|
|
30
|
+
* not contain `]` or a quote character — either ends the capture. So
|
|
31
|
+
* `['a]b']` does NOT resolve (it accidentally resolved under the legacy
|
|
32
|
+
* regex; a miss is the acceptable outcome for a pathological key).
|
|
33
|
+
*
|
|
34
|
+
* Returns null for a malformed path (unterminated bracket, non-numeric
|
|
35
|
+
* unquoted bracket, `[-0]`) — the caller resolves that to `undefined`, never
|
|
36
|
+
* a silent wrong match. Returns [] for the root path (`"$"`, `"."`) —
|
|
37
|
+
* callers that need a data-bearing path must reject the empty tokenization
|
|
38
|
+
* themselves (a root `errorPath` would resolve the whole parsed body).
|
|
39
|
+
*/
|
|
40
|
+
export function tokenizeJsonPath(path: string): string[] | null {
|
|
41
|
+
const s = path.replace(/^\$\.?/, "");
|
|
42
|
+
const parts: string[] = [];
|
|
43
|
+
let buf = "";
|
|
44
|
+
let i = 0;
|
|
45
|
+
const flush = () => {
|
|
46
|
+
if (buf.length > 0) parts.push(buf);
|
|
47
|
+
buf = "";
|
|
48
|
+
};
|
|
49
|
+
while (i < s.length) {
|
|
50
|
+
const ch = s[i]!;
|
|
51
|
+
if (ch === ".") {
|
|
52
|
+
flush();
|
|
53
|
+
i++;
|
|
54
|
+
} else if (ch === "[") {
|
|
55
|
+
flush();
|
|
56
|
+
i++;
|
|
57
|
+
const q = s[i];
|
|
58
|
+
if (q === "'" || q === '"') {
|
|
59
|
+
// Quoted segment: atomic key, dots included. Content ends at the
|
|
60
|
+
// closing quote (which must be followed by `]`); `]` or a quote
|
|
61
|
+
// inside the content is a syntax limit → malformed.
|
|
62
|
+
i++;
|
|
63
|
+
let content = "";
|
|
64
|
+
while (i < s.length && s[i] !== q && s[i] !== "]") {
|
|
65
|
+
content += s[i];
|
|
66
|
+
i++;
|
|
67
|
+
}
|
|
68
|
+
if (i >= s.length || s[i] !== q || s[i + 1] !== "]") return null;
|
|
69
|
+
parts.push(content);
|
|
70
|
+
i += 2;
|
|
71
|
+
} else {
|
|
72
|
+
// Unquoted bracket: numeric index, optionally negative (`[3]`, `[-1]`).
|
|
73
|
+
let neg = false;
|
|
74
|
+
if (s[i] === "-") {
|
|
75
|
+
neg = true;
|
|
76
|
+
i++;
|
|
77
|
+
}
|
|
78
|
+
let digits = "";
|
|
79
|
+
while (i < s.length && s[i]! >= "0" && s[i]! <= "9") {
|
|
80
|
+
digits += s[i];
|
|
81
|
+
i++;
|
|
82
|
+
}
|
|
83
|
+
if (digits.length === 0 || s[i] !== "]") return null;
|
|
84
|
+
// Reject `[-0]`/`[-00]`: parseInt yields -0 and `-0 < 0` is false in
|
|
85
|
+
// JS, so the resolver's negative guard would never fire and `[-0]`
|
|
86
|
+
// would silently match element 0.
|
|
87
|
+
if (neg && /^0+$/.test(digits)) return null;
|
|
88
|
+
parts.push((neg ? "-" : "") + digits);
|
|
89
|
+
i++;
|
|
90
|
+
}
|
|
91
|
+
} else {
|
|
92
|
+
buf += ch;
|
|
93
|
+
i++;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
flush();
|
|
97
|
+
return parts;
|
|
98
|
+
}
|
|
99
|
+
|
|
14
100
|
/** Extract `{token}` names from a templated path, in order, deduplicated. */
|
|
15
101
|
export function extractPathTokens(path: string): string[] {
|
|
16
102
|
const out: string[] = [];
|
|
@@ -78,6 +164,21 @@ export function assertSafeDomain(domain: string): string {
|
|
|
78
164
|
return domain;
|
|
79
165
|
}
|
|
80
166
|
|
|
167
|
+
/**
|
|
168
|
+
* Wire param name for a dotted/bracketed JSON path: the last dot segment
|
|
169
|
+
* with any quoted-bracket dress stripped ("continue.rccontinue" →
|
|
170
|
+
* "rccontinue", "['next']" → "next"). Shared by `advancePagination`
|
|
171
|
+
* (runtime tokenBag wire keys) and the parser's `listStyle` collision guard
|
|
172
|
+
* so the derivation exists exactly once and can't drift.
|
|
173
|
+
*/
|
|
174
|
+
export function wireParamName(key: string): string {
|
|
175
|
+
return key
|
|
176
|
+
.split(".")
|
|
177
|
+
.pop()!
|
|
178
|
+
.replace(/^\[['"]?/, "")
|
|
179
|
+
.replace(/['"]?\]$/, "");
|
|
180
|
+
}
|
|
181
|
+
|
|
81
182
|
/**
|
|
82
183
|
* Non-decomposable Latin letters NFD can't split (single codepoints with no
|
|
83
184
|
* canonical decomposition: ø ß æ œ ð þ ł). NFD handles the rest of the Latin
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
import type { Guide } from "./guide-loader.js";
|
|
16
16
|
import { loadAllGuides } from "./guide-store.js";
|
|
17
|
-
import { projectToGuide } from "./
|
|
17
|
+
import { projectToGuide } from "./guide-catalog.js";
|
|
18
18
|
import { getApiToggleState } from "./api-toggle.js";
|
|
19
19
|
|
|
20
20
|
// The global key portal's index.ts sets at load time.
|
|
@@ -24,9 +24,8 @@ let _registered = false;
|
|
|
24
24
|
|
|
25
25
|
/**
|
|
26
26
|
* Build a snapshot of host's guide projections.
|
|
27
|
-
* Recipe fields
|
|
28
|
-
*
|
|
29
|
-
* Self-gates on the /api toggle state.
|
|
27
|
+
* Recipe fields are stripped by projectToGuide(); only the presentation
|
|
28
|
+
* slice + kind remain. Self-gates on the /api toggle state.
|
|
30
29
|
*/
|
|
31
30
|
function buildProjection(): Record<string, Guide> {
|
|
32
31
|
if (!getApiToggleState()) return {};
|
package/core/resolve-op.ts
CHANGED
|
@@ -11,9 +11,10 @@
|
|
|
11
11
|
* successful executor result or a structured non-run outcome.
|
|
12
12
|
*
|
|
13
13
|
* Throws `HelperError` / transport errors up to the caller (both call sites
|
|
14
|
-
* catch); returns a non-`ok` result only for the
|
|
15
|
-
* *not* run failures: a session-disabled local helper (skip, not fail)
|
|
16
|
-
*
|
|
14
|
+
* catch); returns a non-`ok` result only for the conditions that are
|
|
15
|
+
* *not* run failures: a session-disabled local helper (skip, not fail), a
|
|
16
|
+
* fail-closed missing `requires` secret, and a fail-closed missing OAuth
|
|
17
|
+
* token (both short-circuit before dispatch).
|
|
17
18
|
*/
|
|
18
19
|
|
|
19
20
|
import {
|
|
@@ -21,15 +22,20 @@ import {
|
|
|
21
22
|
paginate,
|
|
22
23
|
type RestGetResult,
|
|
23
24
|
type PaginateResult,
|
|
25
|
+
type PaginateOptions,
|
|
26
|
+
type SecretAuthOpts,
|
|
24
27
|
} from "./helpers.js";
|
|
25
28
|
import { callHelper, loadTransform } from "./local-helpers.js";
|
|
26
29
|
import {
|
|
30
|
+
pathScrubValues,
|
|
27
31
|
resolveSecretHeaders,
|
|
28
32
|
resolveSecretQueryParams,
|
|
33
|
+
resolveSecretPathParams,
|
|
34
|
+
missingRequiredSecrets,
|
|
35
|
+
resolveAccessToken,
|
|
29
36
|
authStatusLine,
|
|
30
37
|
canonicalStoreDomain,
|
|
31
|
-
|
|
32
|
-
type QuerySecretResolution,
|
|
38
|
+
OAuthTokenMissingError,
|
|
33
39
|
} from "./auth.js";
|
|
34
40
|
import type { ApiGuide, ExecutorVia, Operation } from "./api-guide-types.js";
|
|
35
41
|
|
|
@@ -42,19 +48,21 @@ export interface ResolveOpOptions {
|
|
|
42
48
|
userParams?: Record<string, unknown>;
|
|
43
49
|
/** paginate: gather all items up to the guide's ceiling. */
|
|
44
50
|
gatherAll?: boolean;
|
|
51
|
+
/** Skip the transport cache read and suppress If-None-Match — force a
|
|
52
|
+
* full network fetch for this op (forwarded to both executors). Nothing
|
|
53
|
+
* sets it yet except `/api verify` (always fresh) and the api-fetch
|
|
54
|
+
* `fresh` param. */
|
|
55
|
+
fresh?: boolean;
|
|
45
56
|
/** paginate: bypass the nextLink SSRF guard (test hook only). */
|
|
46
57
|
skipSsrfGuard?: boolean;
|
|
47
58
|
}
|
|
48
59
|
|
|
49
60
|
/** Store-injected auth opts, forwarded to the executor and reused by the
|
|
50
|
-
* caller for the output-channel audit (secret scrub).
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
secretQueryParams?: Record<string, string>;
|
|
56
|
-
secretQueryParamNames?: Set<string>;
|
|
57
|
-
}
|
|
61
|
+
* caller for the output-channel audit (secret scrub). Field declarations
|
|
62
|
+
* live in helpers.ts (SecretAuthOpts) — the executor boundary is typed
|
|
63
|
+
* against the same interface, so a producer-side field can't be silently
|
|
64
|
+
* dropped. */
|
|
65
|
+
export type AuthOpts = SecretAuthOpts;
|
|
58
66
|
|
|
59
67
|
export type ResolveOpResult =
|
|
60
68
|
| {
|
|
@@ -77,6 +85,12 @@ export type ResolveOpResult =
|
|
|
77
85
|
reason: "auth_required_not_provisioned";
|
|
78
86
|
/** The secret names a `requires` block wants but the store lacks. */
|
|
79
87
|
missing: string[];
|
|
88
|
+
}
|
|
89
|
+
| {
|
|
90
|
+
ok: false;
|
|
91
|
+
reason: "oauth_token_missing";
|
|
92
|
+
/** Human-readable nudge (points at /api oauth <domain>). */
|
|
93
|
+
message: string;
|
|
80
94
|
};
|
|
81
95
|
|
|
82
96
|
// ═══════════════════════════════════════════════════════════════════
|
|
@@ -126,64 +140,95 @@ export async function resolveOpForExecution(
|
|
|
126
140
|
);
|
|
127
141
|
}
|
|
128
142
|
|
|
129
|
-
// 3. Auth resolution
|
|
130
|
-
//
|
|
131
|
-
//
|
|
132
|
-
//
|
|
133
|
-
|
|
134
|
-
let
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
143
|
+
// 3. Auth resolution — resolve store-injected headers/query params
|
|
144
|
+
// (static-key) or an OAuth2 access token (oauth2) up front so a
|
|
145
|
+
// missing required secret / unmintable token fails closed BEFORE any
|
|
146
|
+
// request. Values never leave this scope — only header/param and
|
|
147
|
+
// secret NAMES ever surface to the caller.
|
|
148
|
+
let authOpts: AuthOpts = {};
|
|
149
|
+
switch (guide.auth.kind) {
|
|
150
|
+
case "none":
|
|
151
|
+
break;
|
|
152
|
+
case "static-key": {
|
|
153
|
+
const headerRes = resolveSecretHeaders(guide.auth, storeDomain);
|
|
154
|
+
const queryRes = resolveSecretQueryParams(guide.auth, storeDomain);
|
|
155
|
+
const pathRes = resolveSecretPathParams(guide.auth, storeDomain);
|
|
156
|
+
const missingRequired = missingRequiredSecrets(headerRes, queryRes, pathRes);
|
|
157
|
+
if (missingRequired.length > 0) {
|
|
158
|
+
return {
|
|
159
|
+
ok: false,
|
|
160
|
+
reason: "auth_required_not_provisioned",
|
|
161
|
+
missing: missingRequired,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
const headerValues = [
|
|
165
|
+
...Object.values(headerRes.headers),
|
|
166
|
+
...headerRes.rawHeaderValues,
|
|
167
|
+
];
|
|
168
|
+
const queryValues = Object.values(queryRes.queryParams);
|
|
169
|
+
// Scrub set: raw + both hex-encoded forms (see pathScrubValues).
|
|
170
|
+
// The URL channel's redaction (redactSecretPathValues) handles
|
|
171
|
+
// the hex cases independently.
|
|
172
|
+
authOpts = {
|
|
173
|
+
...(Object.keys(headerRes.headers).length > 0
|
|
174
|
+
? {
|
|
175
|
+
authHeaders: headerRes.headers,
|
|
176
|
+
secretHeaderNames: new Set(
|
|
177
|
+
Object.keys(headerRes.headers).map((h) => h.toLowerCase()),
|
|
178
|
+
),
|
|
179
|
+
}
|
|
180
|
+
: {}),
|
|
181
|
+
...(Object.keys(queryRes.queryParams).length > 0
|
|
182
|
+
? {
|
|
183
|
+
secretQueryParams: queryRes.queryParams,
|
|
184
|
+
secretQueryParamNames: new Set(Object.keys(queryRes.queryParams)),
|
|
185
|
+
}
|
|
186
|
+
: {}),
|
|
187
|
+
...(Object.keys(pathRes.values).length > 0
|
|
188
|
+
? { secretPathParams: pathRes.values }
|
|
189
|
+
: {}),
|
|
190
|
+
secretValues: [
|
|
191
|
+
...headerValues,
|
|
192
|
+
...queryValues,
|
|
193
|
+
...pathScrubValues(pathRes.values),
|
|
194
|
+
],
|
|
147
195
|
};
|
|
196
|
+
break;
|
|
148
197
|
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
authHeaders: headerRes.headers,
|
|
160
|
-
secretHeaderNames: new Set(
|
|
161
|
-
Object.keys(headerRes.headers).map((h) => h.toLowerCase()),
|
|
162
|
-
),
|
|
163
|
-
}
|
|
164
|
-
: {}),
|
|
165
|
-
...(queryRes
|
|
166
|
-
? {
|
|
167
|
-
secretQueryParams: queryRes.queryParams,
|
|
168
|
-
secretQueryParamNames: new Set(Object.keys(queryRes.queryParams)),
|
|
169
|
-
}
|
|
170
|
-
: {}),
|
|
171
|
-
secretValues: [...headerValues, ...queryValues],
|
|
198
|
+
case "oauth2": {
|
|
199
|
+
try {
|
|
200
|
+
authOpts = await resolveAccessToken(guide.auth, storeDomain);
|
|
201
|
+
} catch (err) {
|
|
202
|
+
if (err instanceof OAuthTokenMissingError) {
|
|
203
|
+
return {
|
|
204
|
+
ok: false,
|
|
205
|
+
reason: "oauth_token_missing",
|
|
206
|
+
message: err.message,
|
|
207
|
+
};
|
|
172
208
|
}
|
|
173
|
-
|
|
209
|
+
throw err;
|
|
210
|
+
}
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
default: {
|
|
214
|
+
const _exhaustive: never = guide.auth;
|
|
215
|
+
throw new Error(`Unhandled auth kind: ${_exhaustive}`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Post-resolution footer: an oauth2 auto-mint inside the switch writes the
|
|
220
|
+
// token store, so the footer must be computed AFTER resolution to report
|
|
221
|
+
// the post-mint state (not the stale pre-mint "no token").
|
|
174
222
|
const authFooter = authStatusLine(guide.auth, storeDomain);
|
|
175
223
|
|
|
176
224
|
// 4. Execute via the declared executor.
|
|
177
225
|
if (op.via === "restGet") {
|
|
178
|
-
const result = await restGet(
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
transformFn ?? undefined,
|
|
185
|
-
helperDirName,
|
|
186
|
-
);
|
|
226
|
+
const result = await restGet(guide.apiHost, op, executeParams, guide, {
|
|
227
|
+
...authOpts,
|
|
228
|
+
transformFn: transformFn ?? undefined,
|
|
229
|
+
dirName: helperDirName,
|
|
230
|
+
...(opts?.fresh === undefined ? {} : { fresh: opts.fresh }),
|
|
231
|
+
});
|
|
187
232
|
return {
|
|
188
233
|
ok: true,
|
|
189
234
|
via: "restGet",
|
|
@@ -194,10 +239,13 @@ export async function resolveOpForExecution(
|
|
|
194
239
|
}
|
|
195
240
|
|
|
196
241
|
if (op.via === "paginate") {
|
|
197
|
-
const paginateOpts:
|
|
242
|
+
const paginateOpts: PaginateOptions = {
|
|
198
243
|
...authOpts,
|
|
199
244
|
...(opts?.skipSsrfGuard ? { skipSsrfGuard: true } : {}),
|
|
200
245
|
...(opts?.gatherAll === undefined ? {} : { gatherAll: opts.gatherAll }),
|
|
246
|
+
...(opts?.fresh === undefined ? {} : { fresh: opts.fresh }),
|
|
247
|
+
transformFn: transformFn ?? undefined,
|
|
248
|
+
dirName: helperDirName,
|
|
201
249
|
};
|
|
202
250
|
const result = await paginate(
|
|
203
251
|
guide.apiHost,
|
|
@@ -205,8 +253,6 @@ export async function resolveOpForExecution(
|
|
|
205
253
|
executeParams,
|
|
206
254
|
guide,
|
|
207
255
|
paginateOpts,
|
|
208
|
-
transformFn ?? undefined,
|
|
209
|
-
helperDirName,
|
|
210
256
|
);
|
|
211
257
|
return {
|
|
212
258
|
ok: true,
|
package/core/response-spill.ts
CHANGED
|
@@ -17,6 +17,12 @@ import { join } from "node:path";
|
|
|
17
17
|
|
|
18
18
|
// ─── Constants ──────────────────────────────────────────────────────────
|
|
19
19
|
|
|
20
|
+
/**
|
|
21
|
+
* Truncation threshold shared with api-fetch's renderer — the same number
|
|
22
|
+
* governs where inline output is cut and where disk spill begins.
|
|
23
|
+
*/
|
|
24
|
+
export const INLINE_LIMIT = 4000;
|
|
25
|
+
|
|
20
26
|
/** Max cached spill files per session (conversation). */
|
|
21
27
|
// ponytail: cap; raise if agent reads >8 distinct ops concurrently
|
|
22
28
|
const MAX_FILES_PER_SESSION = 8;
|
|
@@ -75,7 +81,7 @@ function safeSessionKey(s: string): string {
|
|
|
75
81
|
/**
|
|
76
82
|
* Spill a full JSON response to a temp file.
|
|
77
83
|
*
|
|
78
|
-
* Writes only when `json` is longer than
|
|
84
|
+
* Writes only when `json` is longer than INLINE_LIMIT chars (truncation will
|
|
79
85
|
* occur). Gracefully degrades to a no-op on any filesystem error.
|
|
80
86
|
* Evicts the oldest file per session when the count exceeds
|
|
81
87
|
* MAX_FILES_PER_SESSION.
|
|
@@ -88,7 +94,7 @@ export function spillResponse(
|
|
|
88
94
|
json: string,
|
|
89
95
|
sessionKey: string,
|
|
90
96
|
): SpillResult | null {
|
|
91
|
-
if (json.length <=
|
|
97
|
+
if (json.length <= INLINE_LIMIT) {
|
|
92
98
|
return null;
|
|
93
99
|
}
|
|
94
100
|
|
|
@@ -113,10 +119,7 @@ export function spillResponse(
|
|
|
113
119
|
// Evict oldest if over limit
|
|
114
120
|
if (entries.length > MAX_FILES_PER_SESSION) {
|
|
115
121
|
entries.sort((a, b) => a.timestamp - b.timestamp);
|
|
116
|
-
const toRemove = entries.splice(
|
|
117
|
-
0,
|
|
118
|
-
entries.length - MAX_FILES_PER_SESSION,
|
|
119
|
-
);
|
|
122
|
+
const toRemove = entries.splice(0, entries.length - MAX_FILES_PER_SESSION);
|
|
120
123
|
for (const entry of toRemove) {
|
|
121
124
|
try {
|
|
122
125
|
rmSync(entry.path, { force: true });
|
|
@@ -166,7 +169,7 @@ export function formatSpillNotice(
|
|
|
166
169
|
): string {
|
|
167
170
|
if (!spill) {
|
|
168
171
|
return (
|
|
169
|
-
`\n_Response truncated at
|
|
172
|
+
`\n_Response truncated at ${INLINE_LIMIT} chars. Full response has ${jsonLength} chars ` +
|
|
170
173
|
`(disk spill unavailable — re-call api-fetch to regenerate)._`
|
|
171
174
|
);
|
|
172
175
|
}
|
package/core/secrets-command.ts
CHANGED
|
@@ -30,6 +30,7 @@ import {
|
|
|
30
30
|
writeSecret,
|
|
31
31
|
} from "./secrets-store.js";
|
|
32
32
|
import { findGuidesByDomain } from "./guide-store.js";
|
|
33
|
+
import { declaredSecretRefNames } from "./auth.js";
|
|
33
34
|
|
|
34
35
|
/** One-line pointer to `--help`, used in place of the full instructions block. */
|
|
35
36
|
const HELP_HINT = "Run /api secrets --help for usage & storage details.";
|
|
@@ -134,16 +135,14 @@ function listAll(ctx: ExtensionCommandContext): void {
|
|
|
134
135
|
|
|
135
136
|
/**
|
|
136
137
|
* Declared secret store-names for a domain, from every registered guide's
|
|
137
|
-
*
|
|
138
|
-
*
|
|
138
|
+
* auth block — a thin domain-level fan-out over the shared per-guide
|
|
139
|
+
* scanner in core/auth.ts (single source of truth for the declared/gap
|
|
140
|
+
* report too).
|
|
139
141
|
*/
|
|
140
142
|
function declaredSecretNames(domain: string): string[] {
|
|
141
143
|
const names = new Set<string>();
|
|
142
|
-
for (const { guide } of findGuidesByDomain(domain))
|
|
143
|
-
|
|
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
|
-
}
|
|
144
|
+
for (const { guide } of findGuidesByDomain(domain))
|
|
145
|
+
for (const name of declaredSecretRefNames(guide)) names.add(name);
|
|
147
146
|
return [...names].sort((a, b) => a.localeCompare(b));
|
|
148
147
|
}
|
|
149
148
|
|
|
@@ -155,12 +154,18 @@ function declaredSecretNames(domain: string): string[] {
|
|
|
155
154
|
*/
|
|
156
155
|
function declaredPrefixHint(domain: string, name: string): string | undefined {
|
|
157
156
|
for (const { guide } of findGuidesByDomain(domain)) {
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
157
|
+
switch (guide.auth.kind) {
|
|
158
|
+
case "static-key":
|
|
159
|
+
for (const ref of Object.values(guide.auth.secretRefs ?? {})) {
|
|
160
|
+
if (ref.secret === name && ref.prefix) return ref.prefix;
|
|
161
|
+
}
|
|
162
|
+
break;
|
|
163
|
+
case "oauth2":
|
|
164
|
+
case "none":
|
|
165
|
+
break;
|
|
166
|
+
default: {
|
|
167
|
+
const _exhaustive: never = guide.auth;
|
|
168
|
+
throw new Error(`Unhandled auth kind: ${_exhaustive}`);
|
|
164
169
|
}
|
|
165
170
|
}
|
|
166
171
|
}
|
package/core/secrets-store.ts
CHANGED
|
@@ -11,22 +11,15 @@
|
|
|
11
11
|
* read-only `$HOME` doesn't get a `secrets/` dir created under it.
|
|
12
12
|
* - Listing surfaces names only, never values.
|
|
13
13
|
*
|
|
14
|
-
* The store is swappable (the `SecretStore` interface + `
|
|
15
|
-
* deferred OS-keychain backend is a drop-in without touching callers.
|
|
14
|
+
* The store is swappable (the `SecretStore` interface + `createFileStore`)
|
|
15
|
+
* so the deferred OS-keychain backend is a drop-in without touching callers.
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
18
|
import { join } from "node:path";
|
|
19
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";
|
|
20
|
+
import { existsSync, readdirSync, rmSync } from "node:fs";
|
|
29
21
|
import { assertSafeDomain } from "./path-template.js";
|
|
22
|
+
import { readJsonObject, writeJson0600 } from "./fs-0600.js";
|
|
30
23
|
|
|
31
24
|
/** A secret store: read/write/delete one name, list domain/name indexes. */
|
|
32
25
|
export interface SecretStore {
|
|
@@ -54,20 +47,10 @@ export function createFileStore(dir: string): SecretStore {
|
|
|
54
47
|
return join(dir, `${domain}.json`);
|
|
55
48
|
};
|
|
56
49
|
|
|
57
|
-
// Read a domain file as a flat name→value map
|
|
58
|
-
//
|
|
59
|
-
const readFile = (domain: string): Record<string, string> =>
|
|
60
|
-
|
|
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
|
-
};
|
|
50
|
+
// Read a domain file as a flat name→value map; corrupt entries (non-string
|
|
51
|
+
// values) drop out at the `read` boundary. Never mkdirs.
|
|
52
|
+
const readFile = (domain: string): Record<string, string> =>
|
|
53
|
+
readJsonObject(domainPath(domain)) as Record<string, string>;
|
|
71
54
|
|
|
72
55
|
return {
|
|
73
56
|
read(domain, name) {
|
|
@@ -77,16 +60,10 @@ export function createFileStore(dir: string): SecretStore {
|
|
|
77
60
|
write(domain, name, value) {
|
|
78
61
|
const p = domainPath(domain); // also asserts domain safety
|
|
79
62
|
assertSecretName(name);
|
|
80
|
-
// Lazy mkdir on write only — never on read/list.
|
|
81
|
-
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
63
|
+
// Lazy mkdir on write only — never on read/list (writeJson0600 mkdirs).
|
|
82
64
|
const file = readFile(domain);
|
|
83
65
|
file[name] = value;
|
|
84
|
-
|
|
85
|
-
try {
|
|
86
|
-
chmodSync(p, 0o600); // guard against umask overriding the mode
|
|
87
|
-
} catch {
|
|
88
|
-
// best-effort; file was already written
|
|
89
|
-
}
|
|
66
|
+
writeJson0600(p, file);
|
|
90
67
|
},
|
|
91
68
|
delete(domain, name) {
|
|
92
69
|
const p = domainPath(domain); // also asserts domain safety
|
|
@@ -99,12 +76,7 @@ export function createFileStore(dir: string): SecretStore {
|
|
|
99
76
|
// Prune the empty file so the domain drops out of listDomains.
|
|
100
77
|
rmSync(p, { force: true });
|
|
101
78
|
} else {
|
|
102
|
-
|
|
103
|
-
try {
|
|
104
|
-
chmodSync(p, 0o600);
|
|
105
|
-
} catch {
|
|
106
|
-
// best-effort; file was already written
|
|
107
|
-
}
|
|
79
|
+
writeJson0600(p, file);
|
|
108
80
|
}
|
|
109
81
|
},
|
|
110
82
|
deleteDomain(domain) {
|
|
@@ -144,11 +116,6 @@ export function setSecretsDir(dir: string): void {
|
|
|
144
116
|
_store = createFileStore(dir);
|
|
145
117
|
}
|
|
146
118
|
|
|
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
119
|
// Convenience API (delegates to the active store).
|
|
153
120
|
export function readSecret(domain: string, name: string): string | null {
|
|
154
121
|
return _store.read(domain, name);
|