pi-lean-host 0.1.1 → 0.2.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 +144 -43
- package/core/api-guide-types.ts +22 -1
- package/core/api-toggle.ts +20 -1
- package/core/auth.ts +149 -0
- package/core/helpers.ts +146 -50
- package/core/parse-api-guide.ts +219 -42
- package/core/secrets-command.ts +315 -0
- package/core/secrets-store.ts +170 -0
- package/core/transport.ts +126 -24
- package/package.json +4 -1
- package/tools/api-fetch.ts +110 -17
- package/tools/api-guide.ts +10 -6
- package/tools/api-probe.ts +298 -15
package/README.md
CHANGED
|
@@ -20,11 +20,11 @@
|
|
|
20
20
|
> SearXNG search, install
|
|
21
21
|
> [`pi-lean-search`](https://www.npmjs.com/package/pi-lean-search).
|
|
22
22
|
|
|
23
|
-
> ⚠️ **Early release (0.
|
|
23
|
+
> ⚠️ **Early release (0.2.0).** The API tools here work today, but this is a
|
|
24
24
|
> development preview. The recipe schema, tool surfaces, and guide format are
|
|
25
25
|
> still settling as we test more APIs to finalize the shape — **future
|
|
26
26
|
> compatibility is not guaranteed** until the package reaches lockstep with
|
|
27
|
-
> `pi-lean-dimension` 0.5.0. Guides authored against 0.
|
|
27
|
+
> `pi-lean-dimension` 0.5.0. Guides authored against 0.2.x may need revision
|
|
28
28
|
> as the schema firms up.
|
|
29
29
|
|
|
30
30
|
---
|
|
@@ -45,8 +45,9 @@
|
|
|
45
45
|
12. [`/api status` — Detailed Runtime Status](#api-status--detailed-runtime-status)
|
|
46
46
|
13. [Configuration (`settings.json`)](#configuration-settingsjson)
|
|
47
47
|
14. [Co-Installing with `pi-lean-portal`](#co-installing-with-pi-lean-portal)
|
|
48
|
-
15. [
|
|
49
|
-
16. [
|
|
48
|
+
15. [Authentication & Secrets](#authentication--secrets)
|
|
49
|
+
16. [Tips & Best Practices](#tips--best-practices)
|
|
50
|
+
17. [Security & Scope](#security--scope)
|
|
50
51
|
|
|
51
52
|
---
|
|
52
53
|
|
|
@@ -150,6 +151,7 @@ touches the other's tools.
|
|
|
150
151
|
| `/api` | Show current state and available sub-commands. |
|
|
151
152
|
| `/api status` | Detailed runtime status — state, active guides, domains, helpers. |
|
|
152
153
|
| `/api helpers` | List local user helpers (or `/api helpers <domain>` to view one's source). |
|
|
154
|
+
| `/api secrets [<domain> [<name>]]` | Manage stored API secrets — list, provision, delete (see [Authentication & Secrets](#authentication--secrets)). |
|
|
153
155
|
|
|
154
156
|
### Why a peer toggle?
|
|
155
157
|
|
|
@@ -188,8 +190,8 @@ read**, **network read**, **local write**, and **network read (exploratory)**:
|
|
|
188
190
|
|
|
189
191
|
```text
|
|
190
192
|
api-guide → list all available API guides (catalog)
|
|
191
|
-
api-guide domain="
|
|
192
|
-
api-guide domain="
|
|
193
|
+
api-guide domain="wikipedia.org" → disambiguation menu (two guides claim the domain)
|
|
194
|
+
api-guide domain="wikipedia.org" guide="Wikipedia REST" → selected guide
|
|
193
195
|
```
|
|
194
196
|
|
|
195
197
|
- No parameters → the full catalog (collapsed by `organization:`).
|
|
@@ -204,13 +206,13 @@ broken field instead of re-authoring from scratch.
|
|
|
204
206
|
### 2. `api-fetch` — Execute a Guided Operation (network read)
|
|
205
207
|
|
|
206
208
|
```text
|
|
207
|
-
api-fetch domain="
|
|
208
|
-
api-fetch domain="
|
|
209
|
+
api-fetch domain="wikipedia.org" operation="getPageSummary" params={title:"Albert_Einstein"}
|
|
210
|
+
api-fetch domain="wikipedia.org" operation="searchPages" params={srsearch:"climate"} gatherAll=true
|
|
209
211
|
```
|
|
210
212
|
|
|
211
213
|
**Parameters:**
|
|
212
214
|
|
|
213
|
-
- `domain` — a domain registered in a guide (e.g. `"
|
|
215
|
+
- `domain` — a domain registered in a guide (e.g. `"wikipedia.org"`).
|
|
214
216
|
- `operation` — an operation name from the guide (e.g. `"getPageSummary"`).
|
|
215
217
|
- `params` (optional) — path and query parameter values for the operation.
|
|
216
218
|
- `gatherAll` (optional) — `true` paginates to gather all items up to the
|
|
@@ -352,8 +354,12 @@ laws (capped at 1000 by the op override). The `boe-datefmt` helper formats the
|
|
|
352
354
|
| `docs` | guide | — | optional canonical API documentation URL (http/https); surfaced in api-guide detail |
|
|
353
355
|
| `verified` | guide | creation date | drift signal — **defaulted, not enforced** |
|
|
354
356
|
| `gatherAllMax` | guide / op | `1000` | `gatherAll` ceiling; an op can override |
|
|
355
|
-
| `auth.kind` | guide | `none` |
|
|
356
|
-
| `auth.headers` | guide | — |
|
|
357
|
+
| `auth.kind` | guide | `none` | `none` \| `static-key` (store-backed header/query secrets). `oauth2` is a declared-but-unrealized seam (rejected at parse) |
|
|
358
|
+
| `auth.headers` | guide | — | literal extra headers merged into every request (e.g. X-Api-Key: DEMO_KEY) — **literal values only**, never the path for real credentials |
|
|
359
|
+
| `auth.secretRefs` | guide | — | `Record<headerName, secretName>` — store-backed header injection (`static-key`) |
|
|
360
|
+
| `auth.secretQueryRefs` | guide | — | `Record<paramName, secretName>` — store-backed query-param injection (`static-key`) |
|
|
361
|
+
| `auth.requires` | guide | — | secret names the guide hard-requires; absent → `api-fetch` fails closed before the request |
|
|
362
|
+
| `auth.optional` | guide | — | secret names used if present, skipped if absent (e.g. GitHub rate-limit token) |
|
|
357
363
|
| `pagination.style` | guide / op | required when `via: paginate` | `offset-limit` \| `nextLink` \| `cursor` \| `page` \| `resumptionToken` \| `tokenBag` |
|
|
358
364
|
| `pagination.itemsPath` | guide / op | — | JSON path to the items array in the body |
|
|
359
365
|
| `pagination.totalCountPath` | guide / op | — | optional, any style → server-reported total surfaced as `serverTotal` / `server total: N` |
|
|
@@ -377,10 +383,9 @@ Three helpers, for v1. The agent never calls these directly — `api-fetch`
|
|
|
377
383
|
routes each operation through the one its `via` names:
|
|
378
384
|
|
|
379
385
|
- **`restGet`** — path templating, query params, Accept negotiation
|
|
380
|
-
(JSON/XML), and auth injection
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
lands.
|
|
386
|
+
(JSON/XML), and auth injection for `auth.kind: static-key` guides
|
|
387
|
+
(store-backed `secretRefs` / `secretQueryRefs`). See [Authentication &
|
|
388
|
+
Secrets](#authentication--secrets).
|
|
384
389
|
- **`paginate`** — wraps a list operation. The guide declares the style; the
|
|
385
390
|
helper follows it. Returns `{items, next?, serverTotal?}` so the agent can
|
|
386
391
|
stop or continue, plus a `gatherAll` flag for the "just get me everything"
|
|
@@ -500,7 +505,7 @@ Authoring is via `api-learn` in learn mode, or hand-editing the file.
|
|
|
500
505
|
## Pagination Styles
|
|
501
506
|
|
|
502
507
|
`paginate` follows the style declared in the recipe. Six styles cover the
|
|
503
|
-
patterns the bundled
|
|
508
|
+
patterns the bundled 23-recipe spread pressure-tested:
|
|
504
509
|
|
|
505
510
|
| Style | What it sends | Key fields |
|
|
506
511
|
|-------|---------------|------------|
|
|
@@ -557,19 +562,24 @@ you know you're in disambiguation territory.
|
|
|
557
562
|
|
|
558
563
|
## Bundled Reference Recipes
|
|
559
564
|
|
|
560
|
-
The repo ships **
|
|
565
|
+
The repo ships **23 reference recipes** under `api-guides/` (GitHub only —
|
|
561
566
|
**not in the npm tarball, never auto-loaded**). They are inert worked
|
|
562
|
-
examples spanning the no-auth
|
|
567
|
+
examples spanning the no-auth **and keyed** axes:
|
|
563
568
|
|
|
564
569
|
```
|
|
565
570
|
api.gbif.org api.github.com archive.org archive.org-wayback
|
|
566
|
-
arxiv.org boe.es data-api.ecb.europa.eu
|
|
567
|
-
earthquake.usgs.gov en.wikipedia.org en.wikipedia.org-action
|
|
568
|
-
gitlab.com loc.gov
|
|
569
|
-
resources.data.gov services.dnb.de
|
|
570
|
-
www.wikidata.org
|
|
571
|
+
arxiv.org boe.es coingecko.com data-api.ecb.europa.eu
|
|
572
|
+
datos.gob.es earthquake.usgs.gov en.wikipedia.org en.wikipedia.org-action
|
|
573
|
+
etherscan.io eutils.ncbi.nlm.nih.gov gitlab.com loc.gov
|
|
574
|
+
musicbrainz.org openlibrary.org resources.data.gov services.dnb.de
|
|
575
|
+
web.archive.org www.federalregister.gov www.wikidata.org
|
|
571
576
|
```
|
|
572
577
|
|
|
578
|
+
Five are **keyed** (`auth.kind: static-key`) reference recipes:
|
|
579
|
+
`api.github.com`, `coingecko.com`, `etherscan.io`, `eutils.ncbi.nlm.nih.gov`,
|
|
580
|
+
`gitlab.com` — the spread that exercises header-vs-query refs and the
|
|
581
|
+
required/optional split (see [Authentication & Secrets](#authentication--secrets)).
|
|
582
|
+
|
|
573
583
|
To use them, copy the guides into your own directory from a shallow clone of
|
|
574
584
|
the feature branch ([browse the folder on GitHub](https://github.com/coreyryanhanson/pi-lean-dimension/tree/feat/pi-lean-host-package/packages/pi-lean-host/api-guides)):
|
|
575
585
|
|
|
@@ -652,11 +662,12 @@ the toolset's packaged default:
|
|
|
652
662
|
|
|
653
663
|
### No other settings keys
|
|
654
664
|
|
|
655
|
-
There is no `host.*` settings block
|
|
656
|
-
|
|
657
|
-
caching) is configured internally;
|
|
658
|
-
|
|
659
|
-
|
|
665
|
+
There is no `host.*` settings block. The transport layer (per-domain undici
|
|
666
|
+
`Agent` with retry-on-429, redirect policy, timeouts, ETag/`Cache-Control`
|
|
667
|
+
caching) is configured internally; `apiHost` and operation paths live **in
|
|
668
|
+
the recipe frontmatter**, not in settings. Credentials are **not** stored in
|
|
669
|
+
`settings.json` — they live in the per-domain secrets store, provisioned via
|
|
670
|
+
`/api secrets` (see [Authentication & Secrets](#authentication--secrets)).
|
|
660
671
|
|
|
661
672
|
---
|
|
662
673
|
|
|
@@ -727,6 +738,97 @@ know it. The global fallback (`1000`) bounds undeclared guides.
|
|
|
727
738
|
|
|
728
739
|
---
|
|
729
740
|
|
|
741
|
+
## Authentication & Secrets
|
|
742
|
+
|
|
743
|
+
Many read APIs authenticate with a static key (`X-Api-Key`, `Authorization:
|
|
744
|
+
Bearer`, or a `?key=` query param). pi-lean-host supports these end-to-end
|
|
745
|
+
without the credential ever appearing in the agent's context — a guide
|
|
746
|
+
**declares the secret by name**, you provision the value once, and `api-fetch`
|
|
747
|
+
injects it in code.
|
|
748
|
+
|
|
749
|
+
### A candid note on storage and threat model
|
|
750
|
+
|
|
751
|
+
The secrets store is **plaintext JSON at rest** — mode `0600`, no encryption.
|
|
752
|
+
That matches pi's own posture for its credentials (an API key in
|
|
753
|
+
`settings.json` or the env). The threat this guards against is not another
|
|
754
|
+
process reading the file; it's accidental **transcript exfiltration**. You
|
|
755
|
+
provision a value once via `/api secrets`, it's written transcript-safely to
|
|
756
|
+
the store, and `api-fetch` injects it in code — the agent sees the name, not
|
|
757
|
+
the value.
|
|
758
|
+
|
|
759
|
+
That containment is plugin discipline, not a vault. `read`/`cat` on the
|
|
760
|
+
store file is one tool-call from the agent, which runs with your privileges,
|
|
761
|
+
so nothing here is a hard guarantee. **That's why the real rule is: store
|
|
762
|
+
read-only keys.** Scope every credential to the smallest read surface it needs
|
|
763
|
+
(e.g. a GitHub fine-grained token with read-only `contents`). A leaked read
|
|
764
|
+
key is a data-exposure incident; a leaked write key is a takeover — and the
|
|
765
|
+
plugin is GET-only, so a read-only key is always enough for what it does.
|
|
766
|
+
|
|
767
|
+
### Guide-side: declare the name, never the value
|
|
768
|
+
|
|
769
|
+
In `guide.md`, set `auth.kind: static-key` and point at store secrets by name.
|
|
770
|
+
The value never lives in the guide (a real key committed there would be one
|
|
771
|
+
`cat` from the agent's context).
|
|
772
|
+
|
|
773
|
+
```yaml
|
|
774
|
+
auth:
|
|
775
|
+
kind: static-key
|
|
776
|
+
secretRefs:
|
|
777
|
+
x-cg-demo-api-key: api_key # headerName: secretName
|
|
778
|
+
requires: [api_key] # absent → api-fetch fails closed
|
|
779
|
+
# secretQueryRefs: { apikey: api_key } # query-param injection (?key=)
|
|
780
|
+
# optional: [api_key] # used if present, skipped if absent
|
|
781
|
+
```
|
|
782
|
+
|
|
783
|
+
- **`auth.secretRefs`** — `Record<headerName, secretName>`: inject the store
|
|
784
|
+
value into that request header.
|
|
785
|
+
- **`auth.secretQueryRefs`** — `Record<paramName, secretName>`: inject the
|
|
786
|
+
store value as that query param.
|
|
787
|
+
- **`auth.requires`** — names the guide **hard-requires**. If one is absent
|
|
788
|
+
from the store, `api-fetch` **fails closed before the request** — no silent
|
|
789
|
+
unauthenticated fetch that could return partial data the agent mistakes for
|
|
790
|
+
complete.
|
|
791
|
+
- **`auth.optional`** — names usable-if-present. Absent → `api-fetch` proceeds
|
|
792
|
+
unauthenticated (e.g. GitHub: 60 req/hr unauth, 5000 with a token); present
|
|
793
|
+
→ injected like a required secret.
|
|
794
|
+
- **`auth.headers`** stays **literal-only** (demo keys, committed rate-limit
|
|
795
|
+
tokens) — it is not the path for real credentials.
|
|
796
|
+
|
|
797
|
+
### Provisioning
|
|
798
|
+
|
|
799
|
+
```text
|
|
800
|
+
/api secrets list stored domains + secret names (names only)
|
|
801
|
+
/api secrets <domain> view + provision for a guide (prompts the declared names)
|
|
802
|
+
/api secrets <domain> <name> set a single secret (manual escape valve)
|
|
803
|
+
/api secrets <domain> --delete delete all secrets for a domain (confirm)
|
|
804
|
+
/api secrets <domain> <name> --delete delete a single secret
|
|
805
|
+
```
|
|
806
|
+
|
|
807
|
+
Provisioning is interactive (`ctx.ui` dialogs — the value is captured
|
|
808
|
+
**transcript-safely** and written straight to the store, never returned). On
|
|
809
|
+
headless hosts there is no dialog, so `/api secrets` prints the direct
|
|
810
|
+
file-write instructions instead — write the `0600` file yourself before pi
|
|
811
|
+
starts (a one-line `install -m 600` + `cat >` step).
|
|
812
|
+
|
|
813
|
+
Secrets persist at `~/.pi/agent/pi-lean-host/secrets/<domain>.json` (mode
|
|
814
|
+
`0600`). **Only names are ever listed** — values never leave the store.
|
|
815
|
+
|
|
816
|
+
### The status footer
|
|
817
|
+
|
|
818
|
+
Every `api-guide` / `api-fetch` result on an auth-bearing guide (`secretRefs`
|
|
819
|
+
or `secretQueryRefs`) ends with a `🔑 auth:` line — `ok`, `requires <name>
|
|
820
|
+
— not provisioned`, or an optional state — showing name and presence only,
|
|
821
|
+
never the value, so it's safe anywhere it renders.
|
|
822
|
+
|
|
823
|
+
### Authoring keyed guides
|
|
824
|
+
|
|
825
|
+
`api-probe` accepts an inline `auth` block (injection fields only) plus a
|
|
826
|
+
`domain` selector, so you can prove a keyed shape before writing the guide —
|
|
827
|
+
a store miss reports the name and fetches unauthenticated (authoring is
|
|
828
|
+
human-in-the-loop, not fail-closed). One of the bundled keyed recipes is a
|
|
829
|
+
better starting template than `boe.es` for your first keyed guide — see
|
|
830
|
+
[`api-guides/CONTRIBUTING.md`](./api-guides/CONTRIBUTING.md).
|
|
831
|
+
|
|
730
832
|
## Security & Scope
|
|
731
833
|
|
|
732
834
|
### SSRF guard (server-supplied URLs only)
|
|
@@ -743,22 +845,21 @@ Agent-supplied URLs are **not** guarded. `restGet` assembles a URL from
|
|
|
743
845
|
The agent runs on your own machine with your own privileges and has `bash`,
|
|
744
846
|
`read`, and `write` over the filesystem; blocking `http://169.254.169.254/`
|
|
745
847
|
on `restGet` while `curl` is one tool-call away is a sieve with one hole
|
|
746
|
-
patched.
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
848
|
+
patched. With keyed auth shipped, the guard is now **load-bearing**: a server-supplied
|
|
849
|
+
`nextUrl` to an internal host would leak the attached `Authorization` header,
|
|
850
|
+
and any keyed `restGet`/`paginate` that redirects is forced through the
|
|
851
|
+
guarded loop — with injected secrets stripped on a cross-domain hop — so the
|
|
852
|
+
channel stays closed.
|
|
750
853
|
|
|
751
854
|
### v1 scope (what it is not)
|
|
752
855
|
|
|
753
856
|
- **GET-read only.** No mutation helper. Add one only when a real *retrieval*
|
|
754
857
|
guide needs it (e.g. a search-then-fetch POST), behind a real auth-review
|
|
755
|
-
gate
|
|
756
|
-
|
|
757
|
-
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
`requires`/`scopes` resolution, no secret-entry UX. The seam is what keeps
|
|
761
|
-
that future build additive rather than a retrofit.
|
|
858
|
+
gate.
|
|
859
|
+
- **Static-key auth only.** `auth.kind: static-key` is realized (store-backed
|
|
860
|
+
header/query-param secrets, `requires`/`optional`); `oauth2` and cookie-login
|
|
861
|
+
stay deferred. Values live in the `0600` secrets store, never in a guide —
|
|
862
|
+
see [Authentication & Secrets](#authentication--secrets).
|
|
762
863
|
- **Bundled recipes are inert.** Nothing the package ships executes until you
|
|
763
864
|
place it in `~/.pi/agent/pi-lean-host/` and opt in.
|
|
764
865
|
- **No inferred-link discovery.** Declared links only in v1; inference is v2.
|
|
@@ -779,10 +880,10 @@ machine; the package does not aim to make that easy.
|
|
|
779
880
|
|
|
780
881
|
> `pi-lean-host` is part of the
|
|
781
882
|
> [pi-lean-dimension](https://github.com/coreyryanhanson/pi-lean-dimension)
|
|
782
|
-
> web-tools suite. For the
|
|
783
|
-
> model and the
|
|
784
|
-
> [
|
|
785
|
-
>
|
|
883
|
+
> web-tools suite. For the security model behind the secrets store (the
|
|
884
|
+
> two-threat model and the output-channel audit), see
|
|
885
|
+
> [Authentication & Secrets](#authentication--secrets). For the helper
|
|
886
|
+
> escape-valve policy and the 23-recipe spread, see
|
|
786
887
|
> [`docs/design/api-helper-escape-valve.md`](docs/design/api-helper-escape-valve.md).
|
|
787
888
|
>
|
|
788
889
|
> License: AGPL-3.0-only
|
package/core/api-guide-types.ts
CHANGED
|
@@ -19,7 +19,7 @@ import type { Guide } from "./guide-loader.js";
|
|
|
19
19
|
*/
|
|
20
20
|
export const GATHER_ALL_MAX_FALLBACK = 1000;
|
|
21
21
|
|
|
22
|
-
/** Auth strategies recognized by the schema (the seam). v1 realizes
|
|
22
|
+
/** Auth strategies recognized by the schema (the seam). v1 realizes `none` and `static-key`; `oauth2` is rejected at parse. */
|
|
23
23
|
export const KNOWN_AUTH_KINDS: ReadonlySet<string> = new Set([
|
|
24
24
|
"none",
|
|
25
25
|
"static-key",
|
|
@@ -36,6 +36,27 @@ export interface AuthConfig {
|
|
|
36
36
|
kind: AuthKind;
|
|
37
37
|
/** Extra headers merged into every request (e.g. `X-Api-Key: DEMO_KEY`). */
|
|
38
38
|
headers?: Record<string, string>;
|
|
39
|
+
/**
|
|
40
|
+
* static-key only: maps request header name → secret store name. Values
|
|
41
|
+
* are injected at fetch time from the secrets store; the value never
|
|
42
|
+
* enters agent context. Every referenced name must also appear in
|
|
43
|
+
* `requires` or `optional` (parser-enforced).
|
|
44
|
+
*/
|
|
45
|
+
secretRefs?: Record<string, string>;
|
|
46
|
+
/**
|
|
47
|
+
* static-key only: maps query param name → secret store name.
|
|
48
|
+
* Values are injected below the agent-supplied params map at fetch time
|
|
49
|
+
* (never into it) and redacted from every surfaced URL. A param name
|
|
50
|
+
* colliding with any operation's `params` map is a parse error — the
|
|
51
|
+
* agent must not be able to supply a secretly-injected param. Every
|
|
52
|
+
* referenced name must also appear in `requires` or `optional`
|
|
53
|
+
* (parser-enforced, same rule as `secretRefs`).
|
|
54
|
+
*/
|
|
55
|
+
secretQueryRefs?: Record<string, string>;
|
|
56
|
+
/** static-key: secret names whose absence fails the request closed before it is sent. */
|
|
57
|
+
requires?: string[];
|
|
58
|
+
/** static-key: secret names that add value when present but are not required. */
|
|
59
|
+
optional?: string[];
|
|
39
60
|
}
|
|
40
61
|
|
|
41
62
|
// ═══════════════════════════════════════════════════════════════════
|
package/core/api-toggle.ts
CHANGED
|
@@ -29,6 +29,7 @@ import {
|
|
|
29
29
|
} from "pi-tool-masking";
|
|
30
30
|
import type { ToolsetSpec } from "pi-tool-masking";
|
|
31
31
|
import { handleHelpersSubcommand } from "./helpers-command.js";
|
|
32
|
+
import { handleSecretsSubcommand } from "./secrets-command.js";
|
|
32
33
|
import { loadAllGuides } from "./guide-store.js";
|
|
33
34
|
import { getAllHelpers, getDisabledHelperDomains } from "./local-helpers.js";
|
|
34
35
|
|
|
@@ -72,6 +73,16 @@ export function getApiToggleState(): boolean {
|
|
|
72
73
|
return _lastToggleState;
|
|
73
74
|
}
|
|
74
75
|
|
|
76
|
+
/**
|
|
77
|
+
* Learn-mode gate for api-probe's `listSecrets` discovery. Returns the
|
|
78
|
+
* cached learn state synced on session_start and toolset events. A hard
|
|
79
|
+
* runtime gate (not just toolset masking) so a `listSecrets` call under
|
|
80
|
+
* `/api on` is refused even if the tool is somehow reachable.
|
|
81
|
+
*/
|
|
82
|
+
export function isApiLearnEnabled(): boolean {
|
|
83
|
+
return _lastLearnState;
|
|
84
|
+
}
|
|
85
|
+
|
|
75
86
|
/** @internal Test-only read access to live learn state. */
|
|
76
87
|
export function _getApiLearnStateForTest(): boolean {
|
|
77
88
|
return _lastLearnState;
|
|
@@ -206,7 +217,7 @@ export default function initApiToggle(pi: ExtensionAPI): void {
|
|
|
206
217
|
pi.registerCommand("api", {
|
|
207
218
|
description:
|
|
208
219
|
"Enable/disable API tools. " +
|
|
209
|
-
"Usage: /api on | off | learn | status | helpers [domain]",
|
|
220
|
+
"Usage: /api on | off | learn | status | helpers [domain] | secrets [domain [name] | --help]",
|
|
210
221
|
handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
211
222
|
const trimmed = args.trim();
|
|
212
223
|
const parts = trimmed.split(/\s+/);
|
|
@@ -270,6 +281,13 @@ export default function initApiToggle(pi: ExtensionAPI): void {
|
|
|
270
281
|
return;
|
|
271
282
|
}
|
|
272
283
|
|
|
284
|
+
case "secrets": {
|
|
285
|
+
// Peer of status/helpers/bare — read/write to the secrets store,
|
|
286
|
+
// not a toolset actuation, so the focus-mode guard does not apply.
|
|
287
|
+
await handleSecretsSubcommand(rest, ctx);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
|
|
273
291
|
default: {
|
|
274
292
|
const apiStatus = apiToolset.isEnabled(pi) ? "✅ on" : "❌ off";
|
|
275
293
|
const learnStatus = learnToolset.isEnabled(pi) ? "✅ on" : "❌ off";
|
|
@@ -283,6 +301,7 @@ export default function initApiToggle(pi: ExtensionAPI): void {
|
|
|
283
301
|
` /api off disable all API tools`,
|
|
284
302
|
` /api status detailed status (guides, helpers)`,
|
|
285
303
|
` /api helpers list local helpers`,
|
|
304
|
+
` /api secrets list/provision stored secrets (names only)`,
|
|
286
305
|
` /api show this status`,
|
|
287
306
|
];
|
|
288
307
|
|
package/core/auth.ts
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Static-key auth — store-backed secret resolution + metadata-only footer.
|
|
3
|
+
*
|
|
4
|
+
* Both `api-fetch` (injection + fail-closed) and the `api-guide`/`api-fetch`
|
|
5
|
+
* footers share this module. It reads the secrets store and exposes names
|
|
6
|
+
* only — secret values never leave `resolveSecretHeaders`' resolved header
|
|
7
|
+
* map (which only the fetch pipeline consumes, never agent context).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { AuthConfig, ApiGuide } from "./api-guide-types.js";
|
|
11
|
+
import { readSecret } from "./secrets-store.js";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The canonical secret-store key for a guide: its primary browsable domain.
|
|
15
|
+
* `domains:` is parser-required (an `ApiGuide` always has a non-empty
|
|
16
|
+
* `domains` array), so `domains[0]` is always present. No override field,
|
|
17
|
+
* no organization chain, no dirName fallback.
|
|
18
|
+
*/
|
|
19
|
+
export function canonicalStoreDomain(guide: ApiGuide): string {
|
|
20
|
+
// `domains` is optional on the Guide base for web-guides, but parser-required
|
|
21
|
+
// (non-empty) on any ApiGuide — see requireStringArray in parse-api-guide.ts.
|
|
22
|
+
return guide.domains![0]!;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Result of resolving a guide's `auth.secretRefs` against the store. */
|
|
26
|
+
export interface SecretResolution {
|
|
27
|
+
/** headerName → resolved value, ready to merge into the request. */
|
|
28
|
+
headers: Record<string, string>;
|
|
29
|
+
/** secret names referenced by `requires` that are absent from the store. */
|
|
30
|
+
absentRequired: string[];
|
|
31
|
+
/** secret names referenced by `optional` that are absent from the store. */
|
|
32
|
+
absentOptional: string[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Resolve store-secret headers for a `static-key` guide (no-op otherwise). */
|
|
36
|
+
export function resolveSecretHeaders(
|
|
37
|
+
auth: AuthConfig,
|
|
38
|
+
domain: string,
|
|
39
|
+
): SecretResolution {
|
|
40
|
+
const headers: Record<string, string> = {};
|
|
41
|
+
const absentRequired: string[] = [];
|
|
42
|
+
const absentOptional: string[] = [];
|
|
43
|
+
const requires = auth.requires ?? [];
|
|
44
|
+
for (const [headerName, secretName] of Object.entries(auth.secretRefs ?? {})) {
|
|
45
|
+
const value = readSecret(domain, secretName);
|
|
46
|
+
if (value === null) {
|
|
47
|
+
if (requires.includes(secretName)) absentRequired.push(secretName);
|
|
48
|
+
else absentOptional.push(secretName);
|
|
49
|
+
} else {
|
|
50
|
+
headers[headerName] = value;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return { headers, absentRequired, absentOptional };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Result of resolving a guide's `auth.secretQueryRefs` against the store. */
|
|
57
|
+
export interface QuerySecretResolution {
|
|
58
|
+
/** paramName → resolved value, injected below the agent params map. */
|
|
59
|
+
queryParams: Record<string, string>;
|
|
60
|
+
/** secret names referenced by `requires` that are absent from the store. */
|
|
61
|
+
absentRequired: string[];
|
|
62
|
+
/** secret names referenced by `optional` that are absent from the store. */
|
|
63
|
+
absentOptional: string[];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Resolve store-secret query params for a `static-key` guide. Mirrors
|
|
68
|
+
* `resolveSecretHeaders`: reads the store, splits absents by requires vs
|
|
69
|
+
* optional. The values are injected below the agent-supplied params map by
|
|
70
|
+
* the fetch pipeline and never enter agent context.
|
|
71
|
+
*/
|
|
72
|
+
export function resolveSecretQueryParams(
|
|
73
|
+
auth: AuthConfig,
|
|
74
|
+
domain: string,
|
|
75
|
+
): QuerySecretResolution {
|
|
76
|
+
const queryParams: Record<string, string> = {};
|
|
77
|
+
const absentRequired: string[] = [];
|
|
78
|
+
const absentOptional: string[] = [];
|
|
79
|
+
const requires = auth.requires ?? [];
|
|
80
|
+
for (const [paramName, secretName] of Object.entries(
|
|
81
|
+
auth.secretQueryRefs ?? {},
|
|
82
|
+
)) {
|
|
83
|
+
const value = readSecret(domain, secretName);
|
|
84
|
+
if (value === null) {
|
|
85
|
+
if (requires.includes(secretName)) absentRequired.push(secretName);
|
|
86
|
+
else absentOptional.push(secretName);
|
|
87
|
+
} else {
|
|
88
|
+
queryParams[paramName] = value;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return { queryParams, absentRequired, absentOptional };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Metadata-only auth status footer line, shared by `api-guide` and `api-fetch`.
|
|
96
|
+
* Five states: no-auth (→ undefined) / ok / nudge-provision (required absent) /
|
|
97
|
+
* ok-optional (optionals provisioned) / optional-not-provisioned.
|
|
98
|
+
* Covers BOTH `secretRefs` (header) and `secretQueryRefs` (query) ref maps.
|
|
99
|
+
* Never renders a secret value — names only.
|
|
100
|
+
*/
|
|
101
|
+
export function authStatusLine(
|
|
102
|
+
auth: AuthConfig,
|
|
103
|
+
domain: string,
|
|
104
|
+
): string | undefined {
|
|
105
|
+
if (auth.kind !== "static-key") return undefined;
|
|
106
|
+
// Nothing to report when neither ref map has an entry (empty maps are valid
|
|
107
|
+
// = no injection). Length-based, matching the pre-query-ref "no footer"
|
|
108
|
+
// semantics for an empty `secretRefs`, while still covering query-only guides.
|
|
109
|
+
if (
|
|
110
|
+
Object.keys(auth.secretRefs ?? {}).length === 0 &&
|
|
111
|
+
Object.keys(auth.secretQueryRefs ?? {}).length === 0
|
|
112
|
+
)
|
|
113
|
+
return undefined;
|
|
114
|
+
const headerRes = resolveSecretHeaders(auth, domain);
|
|
115
|
+
const queryRes = resolveSecretQueryParams(auth, domain);
|
|
116
|
+
// Dedupe across the two ref maps: a secret injected into both a header
|
|
117
|
+
// and a query param must be named once, not twice.
|
|
118
|
+
const absentRequired = [
|
|
119
|
+
...new Set([...headerRes.absentRequired, ...queryRes.absentRequired]),
|
|
120
|
+
];
|
|
121
|
+
if (absentRequired.length > 0) {
|
|
122
|
+
return (
|
|
123
|
+
`🔑 auth: requires ${absentRequired.join(", ")} — not provisioned. ` +
|
|
124
|
+
`Run /api secrets ${domain}.`
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
// The optional dimension only exists for optional names actually referenced
|
|
128
|
+
// by a ref (an `optional` name with no ref is meaningless).
|
|
129
|
+
const refValues = new Set([
|
|
130
|
+
...Object.values(auth.secretRefs ?? {}),
|
|
131
|
+
...Object.values(auth.secretQueryRefs ?? {}),
|
|
132
|
+
]);
|
|
133
|
+
const referencedOptional = (auth.optional ?? []).filter((n) =>
|
|
134
|
+
refValues.has(n),
|
|
135
|
+
);
|
|
136
|
+
if (referencedOptional.length > 0) {
|
|
137
|
+
const absentOptional = [
|
|
138
|
+
...new Set([...headerRes.absentOptional, ...queryRes.absentOptional]),
|
|
139
|
+
];
|
|
140
|
+
if (absentOptional.length > 0) {
|
|
141
|
+
return (
|
|
142
|
+
`🔑 auth: ok (optional ${absentOptional.join(", ")} not ` +
|
|
143
|
+
`provisioned — unauthenticated; provision with /api secrets ${domain} for higher limits)`
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
return "🔑 auth: ok (optional provisioned)";
|
|
147
|
+
}
|
|
148
|
+
return "🔑 auth: ok";
|
|
149
|
+
}
|