pi-lean-host 0.1.0 → 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 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.1.0).** The API tools here work today, but this is a
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.1.0 may need revision
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. [Tips & Best Practices](#tips--best-practices)
49
- 16. [Security & Scope](#security--scope)
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
 
@@ -105,6 +106,21 @@ This kills two whole classes of recurring mistakes before they exist:
105
106
  bundled recipes are inert, the only code that ever runs is code you
106
107
  explicitly placed in your own directory.
107
108
 
109
+ ### Why not just a skill?
110
+
111
+ A skill is prose the agent re-interprets each turn; this plugin is a fixed
112
+ executor it calls through. For a single clean endpoint you call
113
+ occasionally, a few skill lines are the lazier answer. It earns its keep
114
+ where re-derived curl goes wrong — **pagination to exhaustion** (cursor,
115
+ nextLink, OAI-PMH tokens, Wikimedia continuation dicts walked in one call by
116
+ reviewed code), **charset traps** (Latin-1 APIs serving bytes without a
117
+ charset parameter — fixed once in the transport, not re-applied and
118
+ forgotten), and **in-process TypeScript helpers** that transform params or
119
+ responses directly (a skill can only instruct the agent to write and run
120
+ that code). A skill is also always in context; the guide store loads on
121
+ demand. A skill is pure text with no in-process eval, whereas a loaded
122
+ `helper.ts` runs with the agent's privileges.
123
+
108
124
  ### Three tiers of code, separated by trust
109
125
 
110
126
  | Tier | Where it lives | Who writes it | Ships in tarball? | Trust |
@@ -135,6 +151,7 @@ touches the other's tools.
135
151
  | `/api` | Show current state and available sub-commands. |
136
152
  | `/api status` | Detailed runtime status — state, active guides, domains, helpers. |
137
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)). |
138
155
 
139
156
  ### Why a peer toggle?
140
157
 
@@ -173,8 +190,8 @@ read**, **network read**, **local write**, and **network read (exploratory)**:
173
190
 
174
191
  ```text
175
192
  api-guide → list all available API guides (catalog)
176
- api-guide domain="en.wikipedia.org" → disambiguation menu (two guides claim the domain)
177
- api-guide domain="en.wikipedia.org" guide="Wikipedia REST" → selected guide
193
+ api-guide domain="wikipedia.org" → disambiguation menu (two guides claim the domain)
194
+ api-guide domain="wikipedia.org" guide="Wikipedia REST" → selected guide
178
195
  ```
179
196
 
180
197
  - No parameters → the full catalog (collapsed by `organization:`).
@@ -189,13 +206,13 @@ broken field instead of re-authoring from scratch.
189
206
  ### 2. `api-fetch` — Execute a Guided Operation (network read)
190
207
 
191
208
  ```text
192
- api-fetch domain="en.wikipedia.org" operation="getPageSummary" params={title:"Albert_Einstein"}
193
- api-fetch domain="en.wikipedia.org" operation="searchPages" params={srsearch:"climate"} gatherAll=true
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
194
211
  ```
195
212
 
196
213
  **Parameters:**
197
214
 
198
- - `domain` — a domain registered in a guide (e.g. `"en.wikipedia.org"`).
215
+ - `domain` — a domain registered in a guide (e.g. `"wikipedia.org"`).
199
216
  - `operation` — an operation name from the guide (e.g. `"getPageSummary"`).
200
217
  - `params` (optional) — path and query parameter values for the operation.
201
218
  - `gatherAll` (optional) — `true` paginates to gather all items up to the
@@ -337,8 +354,12 @@ laws (capped at 1000 by the op override). The `boe-datefmt` helper formats the
337
354
  | `docs` | guide | — | optional canonical API documentation URL (http/https); surfaced in api-guide detail |
338
355
  | `verified` | guide | creation date | drift signal — **defaulted, not enforced** |
339
356
  | `gatherAllMax` | guide / op | `1000` | `gatherAll` ceiling; an op can override |
340
- | `auth.kind` | guide | `none` | strategy seam — **v1 realizes only `none`** (others error) |
341
- | `auth.headers` | guide | — | optional extra headers merged into every request (e.g. X-Api-Key: DEMO_KEY) |
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) |
342
363
  | `pagination.style` | guide / op | required when `via: paginate` | `offset-limit` \| `nextLink` \| `cursor` \| `page` \| `resumptionToken` \| `tokenBag` |
343
364
  | `pagination.itemsPath` | guide / op | — | JSON path to the items array in the body |
344
365
  | `pagination.totalCountPath` | guide / op | — | optional, any style → server-reported total surfaced as `serverTotal` / `server total: N` |
@@ -362,10 +383,9 @@ Three helpers, for v1. The agent never calls these directly — `api-fetch`
362
383
  routes each operation through the one its `via` names:
363
384
 
364
385
  - **`restGet`** — path templating, query params, Accept negotiation
365
- (JSON/XML), and auth injection *when a guide declares a strategy*. v1 ships
366
- only `auth.kind: none`, so no v1 guide declares a strategy — the dispatch
367
- exists as a seam, but the injection path is cold code until a keyed guide
368
- lands.
386
+ (JSON/XML), and auth injection for `auth.kind: static-key` guides
387
+ (store-backed `secretRefs` / `secretQueryRefs`). See [Authentication &
388
+ Secrets](#authentication--secrets).
369
389
  - **`paginate`** — wraps a list operation. The guide declares the style; the
370
390
  helper follows it. Returns `{items, next?, serverTotal?}` so the agent can
371
391
  stop or continue, plus a `gatherAll` flag for the "just get me everything"
@@ -485,7 +505,7 @@ Authoring is via `api-learn` in learn mode, or hand-editing the file.
485
505
  ## Pagination Styles
486
506
 
487
507
  `paginate` follows the style declared in the recipe. Six styles cover the
488
- patterns the bundled 17-recipe spread pressure-tested:
508
+ patterns the bundled 23-recipe spread pressure-tested:
489
509
 
490
510
  | Style | What it sends | Key fields |
491
511
  |-------|---------------|------------|
@@ -542,18 +562,24 @@ you know you're in disambiguation territory.
542
562
 
543
563
  ## Bundled Reference Recipes
544
564
 
545
- The repo ships **17 reference recipes** under `api-guides/` (GitHub only —
565
+ The repo ships **23 reference recipes** under `api-guides/` (GitHub only —
546
566
  **not in the npm tarball, never auto-loaded**). They are inert worked
547
- examples spanning the no-auth axes the helper set was validated against:
567
+ examples spanning the no-auth **and keyed** axes:
548
568
 
549
569
  ```
550
- api.gbif.org api.github.com archive.org archive.org-wayback
551
- boe.es datos.gob.es earthquake.usgs.gov en.wikipedia.org
552
- en.wikipedia.org-action loc.gov musicbrainz.org openlibrary.org
553
- resources.data.gov services.dnb.de web.archive.org www.federalregister.gov
554
- www.wikidata.org
570
+ api.gbif.org api.github.com archive.org archive.org-wayback
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
555
576
  ```
556
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
+
557
583
  To use them, copy the guides into your own directory from a shallow clone of
558
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)):
559
585
 
@@ -636,11 +662,12 @@ the toolset's packaged default:
636
662
 
637
663
  ### No other settings keys
638
664
 
639
- There is no `host.*` settings block in v1. The transport layer (per-domain
640
- undici `Agent` with retry-on-429, redirect policy, timeouts, ETag/`Cache-Control`
641
- caching) is configured internally; auth has no keyed strategy yet, so there
642
- are no secrets or endpoints to configure. `apiHost` and operation paths live
643
- **in the recipe frontmatter**, not in settings.
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)).
644
671
 
645
672
  ---
646
673
 
@@ -711,6 +738,97 @@ know it. The global fallback (`1000`) bounds undeclared guides.
711
738
 
712
739
  ---
713
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
+
714
832
  ## Security & Scope
715
833
 
716
834
  ### SSRF guard (server-supplied URLs only)
@@ -727,22 +845,21 @@ Agent-supplied URLs are **not** guarded. `restGet` assembles a URL from
727
845
  The agent runs on your own machine with your own privileges and has `bash`,
728
846
  `read`, and `write` over the filesystem; blocking `http://169.254.169.254/`
729
847
  on `restGet` while `curl` is one tool-call away is a sieve with one hole
730
- patched. The guard becomes load-bearing the moment keyed auth ships (a
731
- server-supplied `nextUrl` to an internal host would leak the attached
732
- `Authorization` header) — it is in place now so that channel is closed before
733
- the credential-bearing path arrives.
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.
734
853
 
735
854
  ### v1 scope (what it is not)
736
855
 
737
856
  - **GET-read only.** No mutation helper. Add one only when a real *retrieval*
738
857
  guide needs it (e.g. a search-then-fetch POST), behind a real auth-review
739
- gate — and that gate's foundation is a scoped secrets schema, deferred past
740
- v1.
741
- - **`auth.kind: none` only.** The `auth.kind` field + dispatch is a seam for
742
- future `static-key` / `oauth2` strategies; only `none` is realized. No
743
- secrets store ships in v1 — no OS-native store, no file fallback, no
744
- `requires`/`scopes` resolution, no secret-entry UX. The seam is what keeps
745
- 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).
746
863
  - **Bundled recipes are inert.** Nothing the package ships executes until you
747
864
  place it in `~/.pi/agent/pi-lean-host/` and opt in.
748
865
  - **No inferred-link discovery.** Declared links only in v1; inference is v2.
@@ -763,10 +880,10 @@ machine; the package does not aim to make that easy.
763
880
 
764
881
  > `pi-lean-host` is part of the
765
882
  > [pi-lean-dimension](https://github.com/coreyryanhanson/pi-lean-dimension)
766
- > web-tools suite. For the deferred secrets-store track (the two-threat
767
- > model and the first-keyed-guide build checklist), see
768
- > [`docs/design/api-secrets-roadmap.md`](docs/design/api-secrets-roadmap.md).
769
- > For the helper escape-valve policy and the 17-recipe spread, see
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
770
887
  > [`docs/design/api-helper-escape-valve.md`](docs/design/api-helper-escape-valve.md).
771
888
  >
772
889
  > License: AGPL-3.0-only
@@ -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 only `none`. */
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
  // ═══════════════════════════════════════════════════════════════════
@@ -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
+ }