pi-lean-host 0.3.1 → 0.5.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.
@@ -9,10 +9,12 @@
9
9
  */
10
10
 
11
11
  import { parse as yamlParse } from "yaml";
12
- import { readFileSync, readdirSync, existsSync, statSync } from "node:fs";
13
- import { join } from "node:path";
14
- import type { Guide } from "./guide-loader.js";
15
- import { extractPathTokens } from "./path-template.js";
12
+ import { fileURLToPath } from "node:url";
13
+ import {
14
+ extractPathTokens,
15
+ tokenizeJsonPath,
16
+ wireParamName,
17
+ } from "./path-template.js";
16
18
  import {
17
19
  GATHER_ALL_MAX_FALLBACK,
18
20
  GUIDE_SCHEMA_VERSION,
@@ -30,10 +32,21 @@ import {
30
32
  type ResponseCharset,
31
33
  type AuthConfig,
32
34
  type AuthKind,
35
+ type SecretRef,
36
+ type StaticKeyAuth,
37
+ type OAuth2Auth,
38
+ type OAuth2ParamStyle,
39
+ type OAuth2TokenEndpointAuthMethod,
40
+ isOAuth2Grant,
41
+ isOAuth2TokenEndpointAuthMethod,
42
+ isListStyle,
43
+ LIST_STYLES,
44
+ oauth2GrantIssue,
45
+ OAUTH2_GRANTS,
46
+ OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS,
33
47
  type ExecutorVia,
34
48
  type AcceptType,
35
49
  type QueryParamSpec,
36
- type LoadedApiGuides,
37
50
  } from "./api-guide-types.js";
38
51
 
39
52
  // ═══════════════════════════════════════════════════════════════════
@@ -62,8 +75,7 @@ export function stampFrontmatterField(
62
75
  const content = match[2] ?? "";
63
76
  const nl = /^---(\r?\n)/.exec(raw)?.[1] ?? "\n";
64
77
  const lines = fm.split(nl);
65
- const keyRe = new RegExp(`^${key}:\\s*.+$`);
66
- const idx = lines.findIndex((l) => keyRe.test(l));
78
+ const idx = lines.findIndex((l) => l.startsWith(`${key}:`));
67
79
  const line = `${key}: ${value}`;
68
80
  if (idx === -1) {
69
81
  // Insert-only separation: a new key would land flush against the
@@ -81,6 +93,17 @@ export function stampFrontmatterField(
81
93
  }
82
94
 
83
95
  const VALID_VIA: ReadonlySet<string> = new Set(["restGet", "paginate"]);
96
+ // Closed param-spec key allowlist — the unknown-key tripwire rejects
97
+ // anything else (typo'd `listStyl:` / `requried:` must not silently no-op).
98
+ // Exported for the allowlist↔parser tripwire in
99
+ // __tests__/parse-api-guide.test.ts (same two-direction shape as
100
+ // AUTH_ALLOWLISTS / PAGINATION_ALLOWLISTS).
101
+ export const PARAM_SPEC_KEYS: ReadonlySet<string> = new Set([
102
+ "required",
103
+ "default",
104
+ "description",
105
+ "listStyle",
106
+ ]);
84
107
  // accept is a free-form string — any media type is valid (`json`/`xml`
85
108
  // shorthands are mapped by the helper).
86
109
  const VALID_FORMAT: ReadonlySet<string> = new Set(["json", "xml", "text"]);
@@ -98,27 +121,169 @@ const VALID_PAGINATION_STYLE: ReadonlySet<string> = new Set([
98
121
  "tokenBag",
99
122
  ]);
100
123
 
101
- // Strict auth schema: the only keys validateAuth reads. Any other key
102
- // under `auth` is rejected at parse — the parser used to silently drop
103
- // unknowns, so a wrong-but-plausible shape (e.g. `name`/`secret`) saved a
104
- // guide the executor then silently couldn't honor.
105
- const KNOWN_AUTH_KEYS: ReadonlySet<string> = new Set([
124
+ // Per-variant auth field allowlists — each kind rejects fields not legal for
125
+ // it (stricter than the old single global set: a `tokenUrl` on a static-key
126
+ // block or a `headerPrefixes` on an oauth2 block now fails at parse). The old
127
+ // `none`-kind field-presence check is subsumed by the NoneAuth allowlist.
128
+ // Exported for the allowlist↔parser tripwire in __tests__/parse-api-guide.test.ts
129
+ // (same two-direction shape as PAGINATION_ALLOWLISTS).
130
+ export const AUTH_ALLOWLISTS: Record<AuthKind, ReadonlySet<string>> = {
131
+ none: new Set(["kind", "headers"]),
132
+ "static-key": new Set([
133
+ "kind",
134
+ "headers",
135
+ "secretRefs",
136
+ "secretQueryRefs",
137
+ "secretPathRefs",
138
+ ]),
139
+ oauth2: new Set([
140
+ "kind",
141
+ "grant",
142
+ "tokenUrl",
143
+ "clientId",
144
+ "clientSecret",
145
+ "secretRefs",
146
+ "scopes",
147
+ "paramStyle",
148
+ "tokenEndpointAuthMethod",
149
+ "authorizeUrl",
150
+ "revokeUrl",
151
+ ]),
152
+ };
153
+
154
+ // Per-style pagination field allowlists — same pattern as AUTH_ALLOWLISTS:
155
+ // each style rejects keys not legal for it, so a typo (`itemPath:`) or a
156
+ // wrong-style key (`cursorPath:` on a nextLink block) fails at parse instead
157
+ // of silently single-paging at runtime.
158
+ // Post-landing note: any schema change touching pagination fields updates
159
+ // these allowlists in the same commit — every future optional pagination
160
+ // field must be added to its style's set here (the allowlist↔parser tripwire
161
+ // in __tests__/parse-api-guide.test.ts enforces the parser side mechanically).
162
+ export const PAGINATION_ALLOWLISTS: Record<
163
+ PaginationStyle,
164
+ ReadonlySet<string>
165
+ > = {
166
+ "offset-limit": new Set([
167
+ "style",
168
+ "itemsPath",
169
+ "pageParam",
170
+ "pageSizeParam",
171
+ "pageSize",
172
+ "base",
173
+ "totalCountPath",
174
+ "hasMorePath",
175
+ ]),
176
+ page: new Set([
177
+ "style",
178
+ "itemsPath",
179
+ "pageParam",
180
+ "pageSizeParam",
181
+ "pageSize",
182
+ "base",
183
+ "totalCountPath",
184
+ "hasMorePath",
185
+ ]),
186
+ nextLink: new Set([
187
+ "style",
188
+ "itemsPath",
189
+ "nextLinkPath",
190
+ "totalCountPath",
191
+ "hasMorePath",
192
+ ]),
193
+ cursor: new Set([
194
+ "style",
195
+ "itemsPath",
196
+ "cursorParam",
197
+ "cursorPath",
198
+ "pageSizeParam",
199
+ "pageSize",
200
+ "totalCountPath",
201
+ "hasMorePath",
202
+ ]),
203
+ resumptionToken: new Set([
204
+ "style",
205
+ "itemsPath",
206
+ "tokenParam",
207
+ "tokenPath",
208
+ "totalCountPath",
209
+ "hasMorePath",
210
+ ]),
211
+ tokenBag: new Set([
212
+ "style",
213
+ "itemsPath",
214
+ "continuationParams",
215
+ "totalCountPath",
216
+ "hasMorePath",
217
+ ]),
218
+ };
219
+
220
+ // Op-block key allowlist — the closed-schema pass's largest surface. An
221
+ // unknown op key (`errorPaths:` instead of `errorPath:`) used to parse clean
222
+ // and silently no-op the intended behavior — worst case, a typo'd error
223
+ // envelope never fires. Exported for the allowlist↔parser tripwire in
224
+ // __tests__/parse-api-guide.test.ts (same two-direction shape as
225
+ // PAGINATION_ALLOWLISTS). Not `pathParamDocs` — that's a parser-derived
226
+ // OUTPUT field built from params.<token>.description, never authored.
227
+ export const OP_ALLOWLIST: ReadonlySet<string> = new Set([
228
+ "name",
229
+ "via",
230
+ "path",
231
+ "accept",
232
+ "params",
233
+ "requiresAnyOf",
234
+ "dateParams",
235
+ "helper",
236
+ "transform",
237
+ "passthrough",
238
+ "parse",
239
+ "errorPath",
240
+ "pagination",
241
+ "gatherAllMax",
242
+ ]);
243
+
244
+ // responseShape block allowlist — same closed-schema pass, same philosophy:
245
+ // only `format` and `charset` are read; anything else is a typo.
246
+ // Exported for the allowlist↔parser tripwire in
247
+ // __tests__/parse-api-guide.test.ts.
248
+ export const RESPONSE_SHAPE_ALLOWLIST: ReadonlySet<string> = new Set([
249
+ "format",
250
+ "charset",
251
+ ]);
252
+
253
+ // Guide-frontmatter key allowlist — the closed-schema pass's third surface.
254
+ // Exactly the 16 keys parseApiGuide reads from the parsed YAML mapping: the
255
+ // 15 literal m["…"] sites plus `domains` (read via requireStringArray).
256
+ // Deliberately NOT Object.keys(const guide) — that would drag in derived
257
+ // non-authored fields (`content`, `category`, `source`). Exported for the
258
+ // allowlist↔parser tripwire in __tests__/parse-api-guide.test.ts.
259
+ export const GUIDE_ALLOWLIST: ReadonlySet<string> = new Set([
106
260
  "kind",
107
- "headers",
108
- "secretRefs",
109
- "secretQueryRefs",
110
- "requires",
111
- "optional",
112
- "headerPrefixes",
261
+ "domains",
262
+ "shortName",
263
+ "updated",
264
+ "icon",
265
+ "apiHost",
266
+ "verified",
267
+ "docs",
268
+ "organization",
269
+ "description",
270
+ "schemaVersion",
271
+ "gatherAllMax",
272
+ "auth",
273
+ "responseShape",
274
+ "operations",
275
+ "pagination",
113
276
  ]);
114
- // Set insertion order — used to render the known-key list in error strings
115
- // (expected + fallback fix) so they can't drift from the set.
116
- const KNOWN_AUTH_KEYS_LIST = [...KNOWN_AUTH_KEYS].join(", ");
117
277
 
118
278
  // ═══════════════════════════════════════════════════════════════════
119
279
  // Error helper
120
280
  // ═══════════════════════════════════════════════════════════════════
121
281
 
282
+ // The migration doc for the current schema bump, resolved from this module's
283
+ // own location so no hardcoded install path is ever rendered — the doc ships
284
+ // in the npm tarball (enforced by ship-manifest.test.ts).
285
+ const MIGRATION_DOC_NOTE = `See the migration guide for this schema bump: ${fileURLToPath(new URL("../docs/migration-v1.md", import.meta.url))}.`;
286
+
122
287
  function fail(
123
288
  file: string | undefined,
124
289
  field: string,
@@ -193,21 +358,47 @@ interface ReservedPlainHit {
193
358
  * relative to the frontmatter block (matching yamlParse) and count from the
194
359
  * raw line, indentation included. Advisory: only fires on the reserved-char
195
360
  * class, which the parser would reject anyway.
361
+ *
362
+ * Block-scalar aware: a `key: >` / `key: |` line opens a folded/literal block
363
+ * whose continuation lines are free-form prose (markdown backticks, `field:
364
+ * value` snippets) — not `key: value` pairs — so they are skipped until a line
365
+ * dedents back to the header's indentation. Without this, a folded
366
+ * `description: >` block containing e.g. `` `all:` `` would be misread as a
367
+ * plain scalar starting with a reserved char.
196
368
  */
197
369
  function scanReservedPlainStarts(fm: string): ReservedPlainHit[] {
198
370
  const hits: ReservedPlainHit[] = [];
199
371
  const lines = fm.split("\n");
372
+ // Indentation of the currently-open block scalar header line, or -1 when
373
+ // not inside one. Content stays inside until a line dedents to <= this.
374
+ let blockIndent = -1;
200
375
  for (let i = 0; i < lines.length; i++) {
201
376
  const raw = lines[i] ?? "";
377
+ const indent = raw.length - raw.trimStart().length;
202
378
  const line = raw.trimStart();
203
- // Skip blank, comment, and list-item lines (op headers like
204
- // `- name: …` — the backtick footgun lives in `description:`-style
205
- // value lines, which are never `- `-prefixed).
206
- if (line === "" || line.startsWith("#") || line.startsWith("- ")) continue;
379
+ if (blockIndent >= 0) {
380
+ // Blank lines are block content too; only a non-blank dedent ends it.
381
+ if (line === "" || indent > blockIndent) continue;
382
+ blockIndent = -1;
383
+ }
384
+ // Skip blank and comment lines.
385
+ if (line === "" || line.startsWith("#")) continue;
207
386
  const m = /^[^:#]+: /.exec(line);
208
387
  if (!m) continue;
209
388
  const ch = line[m[0].length];
210
- if (ch === undefined || !RESERVED_PLAIN_START.has(ch)) continue;
389
+ if (ch === undefined) continue;
390
+ // `>` / `|` value → block scalar opener (also on `- `-prefixed list
391
+ // items like `- description: >`). Enter block mode; its content lines
392
+ // are prose and must not be scanned.
393
+ if (ch === ">" || ch === "|") {
394
+ blockIndent = indent;
395
+ continue;
396
+ }
397
+ // List-item lines (op headers like `- name: …`) are not top-level
398
+ // `key:` pairs — the backtick footgun lives in `description:`-style
399
+ // value lines, which are never `- `-prefixed.
400
+ if (line.startsWith("- ")) continue;
401
+ if (!RESERVED_PLAIN_START.has(ch)) continue;
211
402
  hits.push({
212
403
  line: i + 1,
213
404
  col: raw.length - line.length + m[0].length + 1,
@@ -321,6 +512,21 @@ function validatePagination(
321
512
  }
322
513
  const style = styleRaw as PaginationStyle;
323
514
 
515
+ // Per-style allowlist — reject keys not legal for this style (a typo like
516
+ // `itemPath:` or a `cursorPath:` on a nextLink block fails here instead of
517
+ // silently single-paging at runtime). Format mirrors AUTH_ALLOWLISTS.
518
+ const allowlist = PAGINATION_ALLOWLISTS[style];
519
+ const unknownKeys = Object.keys(p).filter((k) => !allowlist.has(k));
520
+ if (unknownKeys.length > 0) {
521
+ const first = unknownKeys[0]!; // guarded by the length check above
522
+ return fail(
523
+ file,
524
+ `${fieldPrefix}.${first}`,
525
+ `a known pagination key for style: ${style} (${[...allowlist].join(", ")})`,
526
+ `unknown key(s): ${unknownKeys.join(", ")}`,
527
+ );
528
+ }
529
+
324
530
  const itemsPath = p["itemsPath"];
325
531
  if (typeof itemsPath !== "string" || itemsPath === "") {
326
532
  return fail(
@@ -395,6 +601,41 @@ function validatePagination(
395
601
  }
396
602
  Object.assign(cfg, { [req]: v });
397
603
  }
604
+ // Optional, validated-if-present (both were silently dropped before).
605
+ const cPsp = p["pageSizeParam"];
606
+ if (cPsp !== undefined) {
607
+ if (typeof cPsp !== "string" || cPsp === "") {
608
+ return fail(
609
+ file,
610
+ `${fieldPrefix}.pageSizeParam`,
611
+ "a string param name",
612
+ describeFound(cPsp),
613
+ );
614
+ }
615
+ cfg.pageSizeParam = cPsp;
616
+ }
617
+ const cPs = p["pageSize"];
618
+ if (cPs !== undefined) {
619
+ if (typeof cPs !== "number" || !Number.isFinite(cPs) || cPs <= 0) {
620
+ return fail(
621
+ file,
622
+ `${fieldPrefix}.pageSize`,
623
+ "a positive number",
624
+ describeFound(cPs),
625
+ );
626
+ }
627
+ cfg.pageSize = cPs;
628
+ }
629
+ // pageSize without pageSizeParam is inert (the executor seeds only
630
+ // when both are present) — reject rather than silently no-op.
631
+ if (cPs !== undefined && cPsp === undefined) {
632
+ return fail(
633
+ file,
634
+ `${fieldPrefix}.pageSize`,
635
+ "set alongside pageSizeParam (cursor: the seed only applies with both)",
636
+ describeFound(cPs),
637
+ );
638
+ }
398
639
  } else if (style === "resumptionToken") {
399
640
  for (const req of ["tokenParam", "tokenPath"] as const) {
400
641
  const v = p[req];
@@ -446,6 +687,21 @@ function validatePagination(
446
687
  cfg.totalCountPath = tcp;
447
688
  }
448
689
 
690
+ // optional hasMorePath (any style) — JSON path to a boolean/numeric
691
+ // "more pages" flag; a resolved falsy value stops the walk cleanly.
692
+ const hmp = p["hasMorePath"];
693
+ if (hmp !== undefined) {
694
+ if (typeof hmp !== "string" || hmp === "") {
695
+ return fail(
696
+ file,
697
+ `${fieldPrefix}.hasMorePath`,
698
+ "a non-empty string (JSON path to the has-more flag)",
699
+ describeFound(hmp),
700
+ );
701
+ }
702
+ cfg.hasMorePath = hmp;
703
+ }
704
+
449
705
  return cfg;
450
706
  }
451
707
 
@@ -468,6 +724,25 @@ function validateResponseShape(
468
724
  }
469
725
  const r = raw as Record<string, unknown>;
470
726
 
727
+ // responseShape allowlist — same closed-schema pass as OP_ALLOWLIST: only
728
+ // format/charset are read, so anything else is a typo that would
729
+ // silently no-op.
730
+ const unknownKeys = Object.keys(r).filter(
731
+ (k) => !RESPONSE_SHAPE_ALLOWLIST.has(k),
732
+ );
733
+ if (unknownKeys.length > 0) {
734
+ const first = unknownKeys[0]!; // guarded by the length check above
735
+ return fail(
736
+ file,
737
+ `${fieldPrefix}.${first}`,
738
+ `a known responseShape key (${[...RESPONSE_SHAPE_ALLOWLIST].join(", ")})`,
739
+ `unknown key(s): ${unknownKeys.join(", ")}`,
740
+ {
741
+ fix: `Remove ${fieldPrefix}.${first} — the responseShape schema is closed.`,
742
+ },
743
+ );
744
+ }
745
+
471
746
  const formatRaw = r["format"];
472
747
  let format: ResponseFormat = "json";
473
748
  if (formatRaw !== undefined) {
@@ -540,65 +815,6 @@ function isParseErr<T>(v: T | ParseApiGuideResult): v is ParseApiGuideResult {
540
815
  );
541
816
  }
542
817
 
543
- /** Levenshtein edit distance — spots near-miss auth keys (e.g. `requiers:` →
544
- * `requires`) so the unknown-key error can say "did you mean X?" instead of a
545
- * bare rejection. */
546
- function editDistance(a: string, b: string): number {
547
- const m = a.length;
548
- const n = b.length;
549
- if (m === 0) return n;
550
- if (n === 0) return m;
551
- let prev = Array.from({ length: n + 1 }, (_, j) => j);
552
- for (let i = 1; i <= m; i++) {
553
- const cur = new Array<number>(n + 1);
554
- cur[0] = i;
555
- for (let j = 1; j <= n; j++) {
556
- cur[j] = Math.min(
557
- prev[j]! + 1,
558
- cur[j - 1]! + 1,
559
- prev[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1),
560
- );
561
- }
562
- prev = cur;
563
- }
564
- return prev[n]!;
565
- }
566
-
567
- /** Nearest known auth key within edit distance ≤ 2, or undefined. */
568
- function nearestKnownKey(
569
- key: string,
570
- known: ReadonlySet<string>,
571
- ): string | undefined {
572
- let best: string | undefined;
573
- let bestDist = Infinity;
574
- for (const k of known) {
575
- const d = editDistance(key, k);
576
- if (d < bestDist) {
577
- bestDist = d;
578
- best = k;
579
- }
580
- }
581
- return bestDist <= 2 ? best : undefined;
582
- }
583
-
584
- /**
585
- * Adaptive fix for an unknown-auth-key rejection: near-miss → "did you mean
586
- * X?"; the observed wrong shape (`name`/`secret` under static-key) → point at
587
- * the real secretRefs/requires shape; anything else → list the known keys.
588
- */
589
- function authUnknownKeyFix(unknownKeys: string[]): string {
590
- for (const key of unknownKeys) {
591
- const known = nearestKnownKey(key, KNOWN_AUTH_KEYS);
592
- if (known !== undefined) {
593
- return `Unknown auth key "${key}" — did you mean "${known}"?`;
594
- }
595
- }
596
- if (unknownKeys.includes("name") || unknownKeys.includes("secret")) {
597
- return `The keyed-header shape is auth.secretRefs: { <header>: <secret-name> } with the secret declared in auth.requires (or auth.optional) — replace name/secret with secretRefs + requires.`;
598
- }
599
- return `Unknown auth key(s): ${unknownKeys.join(", ")} — known keys: ${KNOWN_AUTH_KEYS_LIST}.`;
600
- }
601
-
602
818
  function validateAuth(
603
819
  raw: unknown,
604
820
  file: string | undefined,
@@ -622,7 +838,7 @@ function validateAuth(
622
838
  "a string",
623
839
  kindRaw === undefined ? "missing" : describeFound(kindRaw),
624
840
  {
625
- fix: "kind is one of: none | static-key — use `kind: none` (public) or `kind: static-key` (keyed header); or call api-learn({domain, new: true}) for a full skeleton",
841
+ fix: "kind is one of: none | static-key | oauth2 — use `kind: none` (public), `kind: static-key` (keyed header), or `kind: oauth2`; or call api-learn({domain, new: true}) for a full skeleton",
626
842
  },
627
843
  );
628
844
  }
@@ -632,36 +848,175 @@ function validateAuth(
632
848
  "auth.kind",
633
849
  "one of: none | static-key | oauth2",
634
850
  kindRaw,
635
- { fix: "Use `kind: none` (public) or `kind: static-key` (keyed header)" },
851
+ {
852
+ fix: "Use `kind: none` (public), `kind: static-key` (keyed header), or `kind: oauth2`.",
853
+ },
636
854
  );
637
855
  }
638
- // oauth2 is a declared seam, not realized — reject at parse so a recipe
639
- // can't load an auth mode the transport can't honor.
640
- if (kindRaw === "oauth2") {
641
- return fail(file, "auth.kind", "one of: none | static-key", "oauth2", {
642
- fix: "OAuth2 is not yet implemented. Use kind: none (public) or kind: static-key (keyed header) for now.",
643
- });
644
- }
645
- // Strict auth schema — reject unknown keys. The parser used to
646
- // silently drop unknown keys (a wrong-but-plausible shape like
647
- // `name`/`secret` saved a guide the executor then silently couldn't
648
- // honor). Reject, don't infer: the fix is adaptive (near-miss → "did you
649
- // mean X?", wrong shape → secretRefs/requires).
650
- const unknownKeys = Object.keys(a).filter((k) => !KNOWN_AUTH_KEYS.has(k));
856
+ const kind = kindRaw as AuthKind;
857
+ // Per-variant allowlist — reject keys not legal for this kind (a
858
+ // `tokenUrl` on a static-key block or a `headerPrefixes` on an oauth2
859
+ // block fails here, not silently downstream).
860
+ const allowlist = AUTH_ALLOWLISTS[kind];
861
+ const unknownKeys = Object.keys(a).filter((k) => !allowlist.has(k));
651
862
  if (unknownKeys.length > 0) {
652
863
  const first = unknownKeys[0]!;
653
864
  return fail(
654
865
  file,
655
866
  `auth.${first}`,
656
- `a known auth key (${KNOWN_AUTH_KEYS_LIST})`,
867
+ `a known auth key for kind: ${kind} (${[...allowlist].join(", ")})`,
657
868
  `unknown key(s): ${unknownKeys.join(", ")}`,
658
869
  {
659
870
  snippet: snippetFor(fm, "auth"),
660
- fix: authUnknownKeyFix(unknownKeys),
661
871
  },
662
872
  );
663
873
  }
664
- // Parse optional headers (per-kind extra headers, e.g. X-Api-Key for DEMO_KEY).
874
+
875
+ switch (kind) {
876
+ case "none": {
877
+ let headers: Record<string, string> | undefined;
878
+ if (a["headers"] !== undefined) {
879
+ const hr = parseStringRecord(
880
+ a["headers"],
881
+ file,
882
+ fm,
883
+ "auth.headers",
884
+ "a YAML mapping of string → string",
885
+ );
886
+ if (isParseErr(hr)) return hr;
887
+ headers = hr;
888
+ }
889
+ return { kind: "none", ...(headers === undefined ? {} : { headers }) };
890
+ }
891
+ case "static-key": {
892
+ return validateStaticKeyAuth(a, file, fm);
893
+ }
894
+ case "oauth2": {
895
+ return validateOAuth2Auth(a, file, fm);
896
+ }
897
+ default: {
898
+ const never: never = kind;
899
+ throw new Error(`Unhandled auth kind: ${never}`);
900
+ }
901
+ }
902
+ }
903
+
904
+ /**
905
+ * Parse a nested `Record<string, SecretRef>` (header/form-field name → ref).
906
+ * Each ref is self-contained: `secret` (store name), optional `prefix`, and
907
+ * optional `optional`. The old three-field consistency checks (ref→declared,
908
+ * declared→ref, prefix→ref) are structurally impossible here — there is no
909
+ * `requires`/`optional` roster to diverge from, and `prefix` lives on the ref
910
+ * it applies to.
911
+ */
912
+ function parseSecretRefs(
913
+ raw: unknown,
914
+ file: string | undefined,
915
+ fm: string,
916
+ field: string,
917
+ ): Record<string, SecretRef> | ParseApiGuideResult {
918
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
919
+ return fail(
920
+ file,
921
+ field,
922
+ "a YAML mapping of name → { secret: <store name>, prefix?, optional? }",
923
+ describeFound(raw),
924
+ { snippet: snippetFor(fm, "auth") },
925
+ );
926
+ }
927
+ const out: Record<string, SecretRef> = {};
928
+ for (const [name, v] of Object.entries(raw)) {
929
+ const r = parseSecretRefValue(v, file, fm, `${field}.${name}`);
930
+ if (isParseErr(r)) return r;
931
+ out[name] = r;
932
+ }
933
+ return out;
934
+ }
935
+
936
+ /**
937
+ * Parse a single self-contained `SecretRef` value ({ secret, prefix?,
938
+ * optional? }). Used per-entry by `parseSecretRefs` and directly for the
939
+ * oauth2 named `clientId` / `clientSecret` fields.
940
+ */
941
+ function parseSecretRefValue(
942
+ raw: unknown,
943
+ file: string | undefined,
944
+ fm: string,
945
+ field: string,
946
+ ): SecretRef | ParseApiGuideResult {
947
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
948
+ return fail(
949
+ file,
950
+ field,
951
+ "a mapping with secret: <store name>",
952
+ describeFound(raw),
953
+ { snippet: snippetFor(fm, "auth") },
954
+ );
955
+ }
956
+ const ref = raw as Record<string, unknown>;
957
+ const unknownRefKeys = Object.keys(ref).filter(
958
+ (k) => !["secret", "prefix", "optional"].includes(k),
959
+ );
960
+ if (unknownRefKeys.length > 0) {
961
+ return fail(
962
+ file,
963
+ field,
964
+ "a mapping with only secret/prefix/optional keys",
965
+ `unknown key(s): ${unknownRefKeys.join(", ")}`,
966
+ { snippet: snippetFor(fm, "auth") },
967
+ );
968
+ }
969
+ const secret = ref["secret"];
970
+ if (typeof secret !== "string" || secret.length === 0) {
971
+ return fail(
972
+ file,
973
+ `${field}.secret`,
974
+ "a non-empty store name",
975
+ describeFound(secret),
976
+ { snippet: snippetFor(fm, "auth") },
977
+ );
978
+ }
979
+ let prefix: string | undefined;
980
+ if (ref["prefix"] !== undefined) {
981
+ if (
982
+ typeof ref["prefix"] !== "string" ||
983
+ /^\{[a-zA-Z0-9_]+\}$/.test(ref["prefix"])
984
+ ) {
985
+ return fail(
986
+ file,
987
+ `${field}.prefix`,
988
+ "a string prefix (empty allowed; not a bare {placeholder})",
989
+ describeFound(ref["prefix"]),
990
+ { snippet: snippetFor(fm, "auth") },
991
+ );
992
+ }
993
+ prefix = ref["prefix"];
994
+ }
995
+ let optional: boolean | undefined;
996
+ if (ref["optional"] !== undefined) {
997
+ if (typeof ref["optional"] !== "boolean") {
998
+ return fail(
999
+ file,
1000
+ `${field}.optional`,
1001
+ "a boolean",
1002
+ describeFound(ref["optional"]),
1003
+ { snippet: snippetFor(fm, "auth") },
1004
+ );
1005
+ }
1006
+ optional = ref["optional"];
1007
+ }
1008
+ return {
1009
+ secret,
1010
+ ...(prefix === undefined ? {} : { prefix }),
1011
+ ...(optional === undefined ? {} : { optional }),
1012
+ };
1013
+ }
1014
+
1015
+ function validateStaticKeyAuth(
1016
+ a: Record<string, unknown>,
1017
+ file: string | undefined,
1018
+ fm: string,
1019
+ ): StaticKeyAuth | ParseApiGuideResult {
665
1020
  let headers: Record<string, string> | undefined;
666
1021
  if (a["headers"] !== undefined) {
667
1022
  const hr = parseStringRecord(
@@ -674,202 +1029,314 @@ function validateAuth(
674
1029
  if (isParseErr(hr)) return hr;
675
1030
  headers = hr;
676
1031
  }
677
-
678
- // static-key reference fields (secretRefs/requires/optional).
679
- let secretRefs: Record<string, string> | undefined;
1032
+ let secretRefs: Record<string, SecretRef> | undefined;
680
1033
  if (a["secretRefs"] !== undefined) {
681
- const sr = parseStringRecord(
682
- a["secretRefs"],
683
- file,
684
- fm,
685
- "auth.secretRefs",
686
- "a YAML mapping of header name → secret name",
687
- );
1034
+ const sr = parseSecretRefs(a["secretRefs"], file, fm, "auth.secretRefs");
688
1035
  if (isParseErr(sr)) return sr;
689
1036
  secretRefs = sr;
690
1037
  }
691
-
692
- // Query-param secrets: maps query param name → secret store name.
693
- // Same shape + consistency rules as secretRefs; the collision-with-op-`params`
694
- // rule is enforced in parseApiGuide (auth is parsed before operations).
695
- let secretQueryRefs: Record<string, string> | undefined;
1038
+ let secretQueryRefs: Record<string, SecretRef> | undefined;
696
1039
  if (a["secretQueryRefs"] !== undefined) {
697
- const qr = parseStringRecord(
1040
+ const qr = parseSecretRefs(
698
1041
  a["secretQueryRefs"],
699
1042
  file,
700
1043
  fm,
701
1044
  "auth.secretQueryRefs",
702
- "a YAML mapping of query param name → secret name",
703
1045
  );
704
1046
  if (isParseErr(qr)) return qr;
705
1047
  secretQueryRefs = qr;
706
1048
  }
707
-
708
- let requires: string[] | undefined;
709
- const reqRaw = a["requires"];
710
- if (reqRaw !== undefined) {
711
- if (
712
- !Array.isArray(reqRaw) ||
713
- reqRaw.length === 0 ||
714
- reqRaw.some((v) => typeof v !== "string")
715
- ) {
716
- return fail(
717
- file,
718
- "auth.requires",
719
- "a non-empty list of secret names",
720
- describeFound(reqRaw),
721
- { snippet: snippetFor(fm, "auth") },
722
- );
1049
+ let secretPathRefs: Record<string, SecretRef> | undefined;
1050
+ if (a["secretPathRefs"] !== undefined) {
1051
+ const pr = parseSecretRefs(
1052
+ a["secretPathRefs"],
1053
+ file,
1054
+ fm,
1055
+ "auth.secretPathRefs",
1056
+ );
1057
+ if (isParseErr(pr)) return pr;
1058
+ // Path-ref entry checks — fail loud, never silently ignore:
1059
+ // - `prefix` is rejected: path injection is the raw value (the store
1060
+ // value fills {name} verbatim).
1061
+ // - `optional` is rejected (presence, not just `true`): path refs are
1062
+ // required-only — an absent token fails closed in fillPathStrict
1063
+ // before any request, so an optional arm is an error-shaped
1064
+ // pseudostate, not a feature.
1065
+ // - a non-\w name is rejected: fillPathTemplate/extractPathTokens
1066
+ // only match {\w+}, so such a name could never fill — reject with
1067
+ // the grammar message instead of a confusing declared-but-unused
1068
+ // typo error downstream.
1069
+ for (const [name, ref] of Object.entries(pr)) {
1070
+ if (!/^\w+$/.test(name)) {
1071
+ return fail(
1072
+ file,
1073
+ `auth.secretPathRefs.${name}`,
1074
+ "a \\w+ path-token name (the {token} grammar matches \\w+ only)",
1075
+ `"${name}"`,
1076
+ {
1077
+ snippet: snippetFor(fm, "auth"),
1078
+ fix: `Rename the ref to an \\w+ name that matches a {token} in some operation's path — e.g. bot_token → {bot_token}.`,
1079
+ },
1080
+ );
1081
+ }
1082
+ if (ref.prefix !== undefined) {
1083
+ return fail(
1084
+ file,
1085
+ `auth.secretPathRefs.${name}.prefix`,
1086
+ "no prefix key — path injection is the raw secret value",
1087
+ `prefix: ${JSON.stringify(ref.prefix)}`,
1088
+ {
1089
+ snippet: snippetFor(fm, "auth"),
1090
+ fix: `Remove prefix from secretPathRefs.${name} — the value fills {${name}} in the path verbatim.`,
1091
+ },
1092
+ );
1093
+ }
1094
+ if (ref.optional !== undefined) {
1095
+ return fail(
1096
+ file,
1097
+ `auth.secretPathRefs.${name}.optional`,
1098
+ "no optional key — path refs are required-only (an absent path token fails closed before the request)",
1099
+ `optional: ${JSON.stringify(ref.optional)}`,
1100
+ {
1101
+ snippet: snippetFor(fm, "auth"),
1102
+ fix: `Remove optional from secretPathRefs.${name} — a path-keyed API has no unauthenticated state.`,
1103
+ },
1104
+ );
1105
+ }
723
1106
  }
724
- requires = reqRaw as string[];
1107
+ secretPathRefs = pr;
725
1108
  }
1109
+ const result: StaticKeyAuth = { kind: "static-key" };
1110
+ if (headers !== undefined) result.headers = headers;
1111
+ if (secretRefs !== undefined) result.secretRefs = secretRefs;
1112
+ if (secretQueryRefs !== undefined) result.secretQueryRefs = secretQueryRefs;
1113
+ if (secretPathRefs !== undefined) result.secretPathRefs = secretPathRefs;
1114
+ return result;
1115
+ }
726
1116
 
727
- let optional: string[] | undefined;
728
- const optRaw = a["optional"];
729
- if (optRaw !== undefined) {
730
- if (
731
- !Array.isArray(optRaw) ||
732
- optRaw.length === 0 ||
733
- optRaw.some((v) => typeof v !== "string")
734
- ) {
735
- return fail(
736
- file,
737
- "auth.optional",
738
- "a non-empty list of secret names",
739
- describeFound(optRaw),
740
- { snippet: snippetFor(fm, "auth") },
741
- );
742
- }
743
- optional = optRaw as string[];
1117
+ function validateOAuth2Auth(
1118
+ a: Record<string, unknown>,
1119
+ file: string | undefined,
1120
+ fm: string,
1121
+ ): OAuth2Auth | ParseApiGuideResult {
1122
+ const grant = a["grant"];
1123
+ if (!isOAuth2Grant(grant)) {
1124
+ return fail(
1125
+ file,
1126
+ "auth.grant",
1127
+ OAUTH2_GRANTS.join(" | "),
1128
+ describeFound(grant),
1129
+ {
1130
+ fix: "grant: client_credentials (server-to-server, no browser) or grant: authorization_code (interactive, PKCE).",
1131
+ },
1132
+ );
744
1133
  }
745
-
746
- // static-key header prefixes: header name → non-empty prefix string
747
- // prepended to the resolved secret value. Same mapping shape as secretRefs;
748
- // every key must also be a secretRefs header (a prefix for a non-secret
749
- // header is a mistake).
750
- let headerPrefixes: Record<string, string> | undefined;
751
- if (a["headerPrefixes"] !== undefined) {
752
- const hp = parseStringRecord(
753
- a["headerPrefixes"],
1134
+ const tokenUrl = requireHttpUrl(a["tokenUrl"], "auth.tokenUrl", file, fm, {
1135
+ protocolFix: "Use https:// as the scheme",
1136
+ invalidFix: "Include the scheme, e.g. https://api.example.com/oauth/token",
1137
+ });
1138
+ if (typeof tokenUrl !== "string") return tokenUrl;
1139
+ if (a["clientId"] === undefined) {
1140
+ return fail(
754
1141
  file,
755
- fm,
756
- "auth.headerPrefixes",
757
- "a YAML mapping of header name → non-empty prefix string",
758
- (v) =>
759
- typeof v === "string" && v.length > 0 && !/^\{[a-zA-Z0-9_]+\}$/.test(v),
1142
+ "auth.clientId",
1143
+ "a secret ref ({ secret: <store name> })",
1144
+ "missing",
1145
+ {
1146
+ snippet: snippetFor(fm, "auth"),
1147
+ fix: "Add clientId: { secret: client_id } — the store name provisioned via /api secrets <domain>. A shippable guide must not bake in one app's client id.",
1148
+ },
760
1149
  );
761
- if (isParseErr(hp)) return hp;
762
- headerPrefixes = hp;
763
1150
  }
764
-
765
- // Fail-closed consistency rules.
766
- if (
767
- kindRaw === "none" &&
768
- (secretRefs || secretQueryRefs || requires || optional || headerPrefixes)
769
- ) {
1151
+ const clientId = parseSecretRefValue(a["clientId"], file, fm, "auth.clientId");
1152
+ if (isParseErr(clientId)) return clientId;
1153
+ if (clientId.prefix !== undefined || clientId.optional !== undefined) {
770
1154
  return fail(
771
1155
  file,
772
- "auth.secretRefs",
773
- "absent when auth.kind is none",
774
- "secretRefs/secretQueryRefs/requires/optional with kind: none",
1156
+ "auth.clientId",
1157
+ "a ref with only { secret } — prefix/optional are meaningless on the client id (it is always required and always used verbatim)",
1158
+ JSON.stringify(clientId),
775
1159
  {
776
- fix: "Use auth.kind: static-key to reference stored secrets, or remove the auth fields for a public API.",
1160
+ snippet: snippetFor(fm, "auth"),
1161
+ fix: "Remove prefix/optional from clientId — keep clientId: { secret: <store name> }.",
777
1162
  },
778
1163
  );
779
1164
  }
780
- if (requires || optional || secretRefs || secretQueryRefs) {
781
- const declared = new Set([...(requires ?? []), ...(optional ?? [])]);
782
- const refNames = new Set([
783
- ...Object.values(secretRefs ?? {}),
784
- ...Object.values(secretQueryRefs ?? {}),
785
- ]);
786
- const checkRefs = (
787
- refs: Record<string, string>,
788
- field: string,
789
- ): ParseApiGuideResult | null => {
790
- for (const outName of Object.keys(refs)) {
791
- const secretName = refs[outName]!;
792
- if (!declared.has(secretName)) {
793
- return fail(
794
- file,
795
- `${field}.${outName}`,
796
- "a secret name declared in auth.requires or auth.optional",
797
- `"${secretName}" is not in requires/optional`,
798
- {
799
- fix: `Add "${secretName}" to auth.requires or auth.optional (or fix the reference).`,
800
- },
801
- );
802
- }
803
- }
804
- return null;
805
- };
806
- const r1 = checkRefs(secretRefs ?? {}, "auth.secretRefs");
807
- if (r1) return r1;
808
- const r2 = checkRefs(secretQueryRefs ?? {}, "auth.secretQueryRefs");
809
- if (r2) return r2;
810
- const both = (requires ?? []).filter((n) => (optional ?? []).includes(n));
811
- if (both.length > 0) {
1165
+ let clientSecret: SecretRef | undefined;
1166
+ if (a["clientSecret"] !== undefined) {
1167
+ const cs = parseSecretRefValue(
1168
+ a["clientSecret"],
1169
+ file,
1170
+ fm,
1171
+ "auth.clientSecret",
1172
+ );
1173
+ if (isParseErr(cs)) return cs;
1174
+ if (cs.prefix !== undefined) {
812
1175
  return fail(
813
1176
  file,
814
- "auth.requires",
815
- "secret names not duplicated across requires and optional",
816
- `in both: ${both.join(", ")}`,
1177
+ "auth.clientSecret.prefix",
1178
+ "absent — the prefix would be silently ignored (the raw store value is sent as the client secret)",
1179
+ JSON.stringify(cs.prefix),
817
1180
  {
818
- fix: `Move "${both[0]}" to either requires or optional, not both.`,
1181
+ snippet: snippetFor(fm, "auth"),
1182
+ fix: "Remove prefix from clientSecret — keep clientSecret: { secret: <store name> }.",
819
1183
  },
820
1184
  );
821
1185
  }
822
- const checkDeclared = (
823
- names: string[],
824
- field: string,
825
- ): ParseApiGuideResult | null => {
826
- for (const name of names) {
827
- if (!refNames.has(name)) {
828
- return fail(
829
- file,
830
- field,
831
- "a secret name referenced by auth.secretRefs or auth.secretQueryRefs",
832
- `"${name}" is declared here but not referenced by any header/query ref`,
833
- {
834
- fix: `Reference "${name}" from auth.secretRefs or auth.secretQueryRefs, or remove it from ${field}.`,
835
- },
836
- );
837
- }
838
- }
839
- return null;
840
- };
841
- const r3 = checkDeclared(requires ?? [], "auth.requires");
842
- if (r3) return r3;
843
- const r4 = checkDeclared(optional ?? [], "auth.optional");
844
- if (r4) return r4;
845
- }
846
- // Every headerPrefixes key must target a secret-injected header; a prefix
847
- // for a header that isn't in secretRefs is a mistake. Checked outside the
848
- // secretRefs/requires/optional block so a headerPrefixes-only guide fails
849
- // too (the prefix would otherwise be dead at fetch time silently).
850
- if (headerPrefixes) {
851
- for (const headerName of Object.keys(headerPrefixes)) {
852
- if (!secretRefs || !(headerName in secretRefs)) {
1186
+ if (cs.optional !== undefined && grant === "client_credentials") {
1187
+ return fail(
1188
+ file,
1189
+ "auth.clientSecret.optional",
1190
+ "absent for grant: client_credentials (clientSecret is parser-required there; optional can never fire)",
1191
+ "optional: true",
1192
+ {
1193
+ snippet: snippetFor(fm, "auth"),
1194
+ fix: "Remove optional from clientSecret — keep clientSecret: { secret: <store name> }.",
1195
+ },
1196
+ );
1197
+ }
1198
+ clientSecret = cs;
1199
+ }
1200
+ let secretRefs: Record<string, SecretRef> | undefined;
1201
+ if (a["secretRefs"] !== undefined) {
1202
+ const sr = parseSecretRefs(a["secretRefs"], file, fm, "auth.secretRefs");
1203
+ if (isParseErr(sr)) return sr;
1204
+ secretRefs = sr;
1205
+ }
1206
+ let scopes: string[] | undefined;
1207
+ if (a["scopes"] !== undefined) {
1208
+ if (
1209
+ !Array.isArray(a["scopes"]) ||
1210
+ a["scopes"].some((s) => typeof s !== "string")
1211
+ ) {
1212
+ return fail(
1213
+ file,
1214
+ "auth.scopes",
1215
+ "a list of scope strings",
1216
+ describeFound(a["scopes"]),
1217
+ { snippet: snippetFor(fm, "auth") },
1218
+ );
1219
+ }
1220
+ scopes = a["scopes"] as string[];
1221
+ }
1222
+ let paramStyle: OAuth2ParamStyle | undefined;
1223
+ if (a["paramStyle"] !== undefined) {
1224
+ if (a["paramStyle"] !== "bearer-header" && a["paramStyle"] !== "query") {
1225
+ return fail(
1226
+ file,
1227
+ "auth.paramStyle",
1228
+ "bearer-header | query",
1229
+ describeFound(a["paramStyle"]),
1230
+ { snippet: snippetFor(fm, "auth") },
1231
+ );
1232
+ }
1233
+ paramStyle = a["paramStyle"];
1234
+ }
1235
+ let tokenEndpointAuthMethod: OAuth2TokenEndpointAuthMethod | undefined;
1236
+ if (a["tokenEndpointAuthMethod"] !== undefined) {
1237
+ const m = a["tokenEndpointAuthMethod"];
1238
+ if (!isOAuth2TokenEndpointAuthMethod(m)) {
1239
+ return fail(
1240
+ file,
1241
+ "auth.tokenEndpointAuthMethod",
1242
+ OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS.join(" | "),
1243
+ describeFound(m),
1244
+ { snippet: snippetFor(fm, "auth") },
1245
+ );
1246
+ }
1247
+ tokenEndpointAuthMethod = m;
1248
+ }
1249
+ let authorizeUrl: string | undefined;
1250
+ if (a["authorizeUrl"] !== undefined) {
1251
+ const au = requireHttpUrl(a["authorizeUrl"], "auth.authorizeUrl", file, fm);
1252
+ if (typeof au !== "string") return au;
1253
+ authorizeUrl = au;
1254
+ }
1255
+ let revokeUrl: string | undefined;
1256
+ if (a["revokeUrl"] !== undefined) {
1257
+ const rv = requireHttpUrl(a["revokeUrl"], "auth.revokeUrl", file, fm);
1258
+ if (typeof rv !== "string") return rv;
1259
+ revokeUrl = rv;
1260
+ }
1261
+
1262
+ // Grant invariants — the single shared statement of OAuth2 grant
1263
+ // semantics (also enforced by buildSyntheticOAuth2Auth in core/auth.ts
1264
+ // for the bootstrap surfaces). Adding a grant or invariant: edit
1265
+ // oauth2GrantIssue, then extend both callers' message maps.
1266
+ const issue = oauth2GrantIssue({
1267
+ grant,
1268
+ hasClientSecret: clientSecret !== undefined,
1269
+ authorizeUrl,
1270
+ tokenEndpointAuthMethod,
1271
+ });
1272
+ if (issue) {
1273
+ switch (issue.code) {
1274
+ case "noneWithSecret":
1275
+ return fail(
1276
+ file,
1277
+ "auth.clientSecret",
1278
+ "absent when tokenEndpointAuthMethod: none",
1279
+ "present",
1280
+ {
1281
+ snippet: snippetFor(fm, "auth"),
1282
+ fix: "Remove clientSecret — tokenEndpointAuthMethod: none sends no client credentials (PKCE public clients have no secret).",
1283
+ },
1284
+ );
1285
+ case "ccRequiresSecret":
1286
+ return fail(
1287
+ file,
1288
+ "auth.clientSecret",
1289
+ "a clientSecret ref for grant: client_credentials",
1290
+ "missing",
1291
+ {
1292
+ snippet: snippetFor(fm, "auth"),
1293
+ fix: "Add clientSecret: { secret: client_secret } — the store name provisioned via /api secrets <domain>.",
1294
+ },
1295
+ );
1296
+ case "ccRejectsAuthorizeUrl":
853
1297
  return fail(
854
1298
  file,
855
- `auth.headerPrefixes.${headerName}`,
856
- "a header name present in auth.secretRefs",
857
- `"${headerName}" is not a secret-injected header`,
1299
+ "auth.authorizeUrl",
1300
+ "absent for grant: client_credentials",
1301
+ "authorizeUrl present",
858
1302
  {
859
- fix: `Add "${headerName}" to auth.secretRefs (or remove the prefix).`,
1303
+ fix: "Remove authorizeUrl — client_credentials is server-to-server with no browser flow.",
860
1304
  },
861
1305
  );
1306
+ case "acRequiresAuthorizeUrl":
1307
+ return fail(
1308
+ file,
1309
+ "auth.authorizeUrl",
1310
+ "a URL for grant: authorization_code",
1311
+ "missing",
1312
+ {
1313
+ fix: "Add authorizeUrl — the provider's authorization endpoint. The redirect URI is the runtime convention http://127.0.0.1/callback (RFC 8252 §7.3); register it on your OAuth app.",
1314
+ },
1315
+ );
1316
+ default: {
1317
+ // Compile-time exhaustiveness tripwire: a new OAuth2GrantIssue
1318
+ // code must extend this switch (the builder's message map is
1319
+ // already forced via its return type). Unreachable at runtime.
1320
+ const uncovered: never = issue.code;
1321
+ throw new Error(`unhandled OAuth2 grant invariant: ${String(uncovered)}`);
862
1322
  }
863
1323
  }
864
1324
  }
865
1325
 
866
- const result: AuthConfig = { kind: kindRaw as AuthKind };
867
- if (headers !== undefined) result.headers = headers;
1326
+ const result: OAuth2Auth = {
1327
+ kind: "oauth2",
1328
+ grant,
1329
+ tokenUrl,
1330
+ clientId,
1331
+ ...(clientSecret === undefined ? {} : { clientSecret }),
1332
+ };
868
1333
  if (secretRefs !== undefined) result.secretRefs = secretRefs;
869
- if (headerPrefixes !== undefined) result.headerPrefixes = headerPrefixes;
870
- if (secretQueryRefs !== undefined) result.secretQueryRefs = secretQueryRefs;
871
- if (requires !== undefined) result.requires = requires;
872
- if (optional !== undefined) result.optional = optional;
1334
+ if (scopes !== undefined) result.scopes = scopes;
1335
+ if (paramStyle !== undefined) result.paramStyle = paramStyle;
1336
+ if (tokenEndpointAuthMethod !== undefined)
1337
+ result.tokenEndpointAuthMethod = tokenEndpointAuthMethod;
1338
+ if (authorizeUrl !== undefined) result.authorizeUrl = authorizeUrl;
1339
+ if (revokeUrl !== undefined) result.revokeUrl = revokeUrl;
873
1340
  return result;
874
1341
  }
875
1342
 
@@ -882,6 +1349,9 @@ function validateOperation(
882
1349
  index: number,
883
1350
  file: string | undefined,
884
1351
  topPagination: PaginationConfig | undefined,
1352
+ guideResponseShape: ResponseShape,
1353
+ injectedQuerySecretNames: ReadonlySet<string>,
1354
+ authKind: string,
885
1355
  ): Operation | ParseApiGuideResult {
886
1356
  const fieldPath = (leaf: string) => `operations[${index}].${leaf}`;
887
1357
 
@@ -895,6 +1365,23 @@ function validateOperation(
895
1365
  }
896
1366
  const o = raw as Record<string, unknown>;
897
1367
 
1368
+ // Op-block allowlist — reject keys not legal for an op (a typo like
1369
+ // `errorPaths:` would silently no-op the intended behavior). Format
1370
+ // mirrors the pagination per-style allowlist check.
1371
+ const unknownKeys = Object.keys(o).filter((k) => !OP_ALLOWLIST.has(k));
1372
+ if (unknownKeys.length > 0) {
1373
+ const first = unknownKeys[0]!; // guarded by the length check above
1374
+ return fail(
1375
+ file,
1376
+ fieldPath(first),
1377
+ `a known op-block key (${[...OP_ALLOWLIST].join(", ")})`,
1378
+ `unknown key(s): ${unknownKeys.join(", ")}`,
1379
+ {
1380
+ fix: `Remove operations[${index}].${first} — the op-block schema is closed.`,
1381
+ },
1382
+ );
1383
+ }
1384
+
898
1385
  // name
899
1386
  const name = o["name"];
900
1387
  if (typeof name !== "string" || name === "") {
@@ -1028,6 +1515,24 @@ function validateOperation(
1028
1515
  );
1029
1516
  }
1030
1517
  const s = spec as Record<string, unknown>;
1518
+ // Unknown-key tripwire — the param-spec schema is closed
1519
+ // (required/default/description/listStyle). A typo'd key
1520
+ // (`listStyl:`, `requried:`) must not be silently dropped: that's
1521
+ // the silent-wrong-wire class. Same philosophy as the
1522
+ // pagination/auth allowlists.
1523
+ for (const k of Object.keys(s)) {
1524
+ if (!PARAM_SPEC_KEYS.has(k)) {
1525
+ return fail(
1526
+ file,
1527
+ fieldPath(`params.${key}.${k}`),
1528
+ `one of: ${[...PARAM_SPEC_KEYS].join(" | ")} (unknown param-spec key)`,
1529
+ `key "${k}"`,
1530
+ {
1531
+ fix: `Remove params.${key}.${k} — did you mean one of: ${[...PARAM_SPEC_KEYS].join(", ")}?`,
1532
+ },
1533
+ );
1534
+ }
1535
+ }
1031
1536
  const paramSpec: QueryParamSpec = {};
1032
1537
  if (s["required"] !== undefined) {
1033
1538
  if (typeof s["required"] !== "boolean") {
@@ -1054,6 +1559,93 @@ function validateOperation(
1054
1559
  }
1055
1560
  paramSpec.description = s["description"];
1056
1561
  }
1562
+ if (s["listStyle"] !== undefined) {
1563
+ if (!isListStyle(s["listStyle"])) {
1564
+ return fail(
1565
+ file,
1566
+ fieldPath(`params.${key}.listStyle`),
1567
+ `one of: ${LIST_STYLES.join(" | ")}`,
1568
+ describeFound(s["listStyle"]),
1569
+ );
1570
+ }
1571
+ paramSpec.listStyle = s["listStyle"];
1572
+ }
1573
+ // bracket double-dress — the style dresses the wire key with []
1574
+ // itself; a declared name already ending in [] would double-dress
1575
+ // (id[] + [] → id[][]=).
1576
+ if (s["listStyle"] === "bracket" && key.endsWith("[]")) {
1577
+ return fail(
1578
+ file,
1579
+ fieldPath(`params.${key}.listStyle`),
1580
+ "a param name that does not already end in [] (bracket adds the dress itself)",
1581
+ `"${key}" already ends in [] — the wire key would double-dress (id[][]=)`,
1582
+ {
1583
+ fix: `Declare the clean name (params.${key.slice(0, -2)}) with listStyle: bracket — the style appends [] to the wire key.`,
1584
+ },
1585
+ );
1586
+ }
1587
+ // Array default validation — both arms, same pass. An array default
1588
+ // on a non-listStyle param would throw on every call at runtime
1589
+ // (arrays are loud errors there once the serializer widening lands);
1590
+ // catch the authoring error at parse time. On a listStyle param the
1591
+ // elements are validated by the same rules the runtime serializer
1592
+ // enforces (scalars only; no comma-bearing element on comma — the
1593
+ // joined wire form can't distinguish it from a longer list).
1594
+ if (Array.isArray(paramSpec.default)) {
1595
+ if (paramSpec.listStyle === undefined) {
1596
+ return fail(
1597
+ file,
1598
+ fieldPath(`params.${key}.default`),
1599
+ "a scalar default (an array default requires listStyle)",
1600
+ "an array default on a param without listStyle",
1601
+ {
1602
+ fix: `Declare listStyle: ${LIST_STYLES.join(" | ")} on params.${key}, or use a scalar default — an array value on a non-listStyle param fails on every call.`,
1603
+ },
1604
+ );
1605
+ }
1606
+ // Empty array default — the same every-call-throw class as the
1607
+ // styleless case above: the runtime serializer rejects [] (the
1608
+ // param would be silently dropped), so a defaulted call with no
1609
+ // override always fails. Catch it at parse time.
1610
+ if (paramSpec.default.length === 0) {
1611
+ return fail(
1612
+ file,
1613
+ fieldPath(`params.${key}.default`),
1614
+ "a non-empty array default (an empty array default throws on every defaulted call — the param would be silently dropped)",
1615
+ "an empty array default ([])",
1616
+ {
1617
+ fix: `Omit params.${key}.default entirely, or default to a non-empty array — a caller-supplied [] on a listStyle param still fails per-call by design.`,
1618
+ },
1619
+ );
1620
+ }
1621
+ for (const el of paramSpec.default) {
1622
+ if (
1623
+ el === null ||
1624
+ (typeof el !== "string" &&
1625
+ typeof el !== "number" &&
1626
+ typeof el !== "boolean")
1627
+ ) {
1628
+ return fail(
1629
+ file,
1630
+ fieldPath(`params.${key}.default`),
1631
+ "an array of scalar (string | number | boolean) elements",
1632
+ `array contains ${describeFound(el)}`,
1633
+ );
1634
+ }
1635
+ if (
1636
+ paramSpec.listStyle === "comma" &&
1637
+ typeof el === "string" &&
1638
+ el.includes(",")
1639
+ ) {
1640
+ return fail(
1641
+ file,
1642
+ fieldPath(`params.${key}.default`),
1643
+ "comma-free elements (listStyle: comma joins with ',' — a comma-bearing element is indistinguishable from a longer list on the wire)",
1644
+ `element "${el}" contains a comma`,
1645
+ );
1646
+ }
1647
+ }
1648
+ }
1057
1649
  params[key] = paramSpec;
1058
1650
  }
1059
1651
  }
@@ -1064,7 +1656,9 @@ function validateOperation(
1064
1656
  // member-exists, path-param reject, no `required: true` overlap, no
1065
1657
  // `default` on a member. A group member that is `required` would defeat
1066
1658
  // the group at runtime; a `default` would fire alongside a caller-supplied
1067
- // sibling (the members are mutually exclusive peers).
1659
+ // sibling. Semantics are at-least-one-of with all supplied members sent
1660
+ // (members may combine freely); multi-group lands only as the reserved
1661
+ // `requiresAnyOfGroups` sibling key, never a union on this field.
1068
1662
  const requiresAnyOfRaw = o["requiresAnyOf"];
1069
1663
  let requiresAnyOf: string[] | undefined;
1070
1664
  if (requiresAnyOfRaw !== undefined) {
@@ -1109,7 +1703,7 @@ function validateOperation(
1109
1703
  "a param that is not also required: true",
1110
1704
  `"${member}" is required: true`,
1111
1705
  {
1112
- fix: `Remove required: true from params.${member} — it is governed by the requiresAnyOf group, not per-param required.`,
1706
+ fix: `Remove required: true from params.${member} — it is governed by the requiresAnyOf at-least-one-of group, not per-param required.`,
1113
1707
  },
1114
1708
  );
1115
1709
  }
@@ -1120,7 +1714,7 @@ function validateOperation(
1120
1714
  "a param that does not also declare a default",
1121
1715
  `"${member}" has a default`,
1122
1716
  {
1123
- fix: `Remove the default from params.${member} — requiresAnyOf members are mutually exclusive peers, so a default would fire alongside a caller-supplied sibling.`,
1717
+ fix: `Remove the default from params.${member} — requiresAnyOf members are at-least-one-of peers (all supplied members are sent), so a default would fire alongside a caller-supplied sibling.`,
1124
1718
  },
1125
1719
  );
1126
1720
  }
@@ -1155,6 +1749,20 @@ function validateOperation(
1155
1749
  describeFound(fmt),
1156
1750
  );
1157
1751
  }
1752
+ // Declared-but-dead: date normalization runs only in query assembly
1753
+ // (buildQueryParams), while fillPathTemplate fills path tokens raw —
1754
+ // a dateParams entry naming a path token can never fire.
1755
+ if (pathParams.includes(k)) {
1756
+ return fail(
1757
+ file,
1758
+ fieldPath(`dateParams.${k}`),
1759
+ "a query param name (not a path param)",
1760
+ `"${k}" is a path param — dateParams normalization runs only in query assembly, and path tokens are filled raw, so the declaration can never fire`,
1761
+ {
1762
+ fix: `Put the ISO date directly in the path (the real pattern: Polygon.io aggregates {from}/{to}, Frankfurter /{date}) — a future normalization for path tokens would be additive.`,
1763
+ },
1764
+ );
1765
+ }
1158
1766
  }
1159
1767
  dateParams = dateParamsRaw as Record<string, DateParamFormat>;
1160
1768
  }
@@ -1211,6 +1819,62 @@ function validateOperation(
1211
1819
  parseOverride = pr;
1212
1820
  }
1213
1821
 
1822
+ // errorPath — present-only-on-error envelope path. Guards (all parse-time,
1823
+ // fail-loud in front of the author):
1824
+ // - non-empty string (wrong type → ParseError)
1825
+ // - tokenizeable — a malformed path would resolve `undefined` at runtime,
1826
+ // i.e. declared-absent → success: the exact confidently-wrong failure
1827
+ // mode this field exists to kill. Parse is the only code that runs
1828
+ // exactly once, in front of the author who can fix it.
1829
+ // - non-empty tokenization — the root path ("$", ".") tokenizes to [] and
1830
+ // would resolve the entire parsed body, which is always defined
1831
+ // post-parseResponse — every call would fail.
1832
+ // - effective shape not text — parseResponse returns the raw body string
1833
+ // for text ops and resolveJsonPath against a string always resolves
1834
+ // undefined (declared-then-dead). Covers an op-level parse override AND
1835
+ // an op without one under a text guide-level responseShape.
1836
+ const errorPathRaw = o["errorPath"];
1837
+ let errorPath: string | undefined;
1838
+ if (errorPathRaw !== undefined) {
1839
+ if (typeof errorPathRaw !== "string" || errorPathRaw === "") {
1840
+ return fail(
1841
+ file,
1842
+ fieldPath("errorPath"),
1843
+ "a non-empty string JSON path",
1844
+ describeFound(errorPathRaw),
1845
+ );
1846
+ }
1847
+ const tokens = tokenizeJsonPath(errorPathRaw);
1848
+ if (tokens === null) {
1849
+ return fail(
1850
+ file,
1851
+ fieldPath("errorPath"),
1852
+ "a tokenizeable JSON path",
1853
+ `"${errorPathRaw}" is malformed (unterminated or non-numeric bracket)`,
1854
+ {
1855
+ fix: 'Fix the path syntax — e.g. "OAI-PMH.error" or "result[0].message".',
1856
+ },
1857
+ );
1858
+ }
1859
+ if (tokens.length === 0) {
1860
+ return fail(
1861
+ file,
1862
+ fieldPath("errorPath"),
1863
+ "a JSON path to an error element (not the document root)",
1864
+ `"${errorPathRaw}" resolves the entire parsed body — every call would fail`,
1865
+ );
1866
+ }
1867
+ if ((parseOverride ?? guideResponseShape).format === "text") {
1868
+ return fail(
1869
+ file,
1870
+ fieldPath("errorPath"),
1871
+ "an op whose effective response shape is not format: text",
1872
+ "errorPath can never fire on a text op — parseResponse yields the raw body string, not a resolvable shape",
1873
+ );
1874
+ }
1875
+ errorPath = errorPathRaw;
1876
+ }
1877
+
1214
1878
  // pagination (op-level override)
1215
1879
  const opPaginationRaw = o["pagination"];
1216
1880
  let opPagination: PaginationConfig | undefined;
@@ -1236,6 +1900,97 @@ function validateOperation(
1236
1900
  );
1237
1901
  }
1238
1902
 
1903
+ // listStyle collision guard — under keyed supersession, pagination /
1904
+ // tokenBag continuation writes REPLACE same-named base params, so a
1905
+ // listStyle param colliding with an effective pagination wire name is
1906
+ // dead (its listStyle could never reach the wire). Checked against the
1907
+ // EFFECTIVE config (op-level ?? guide-level) — a guide-level pageParam
1908
+ // collides too. Scoped to via: paginate — the supersession writes only
1909
+ // happen in the paginate executor loop, so a restGet op's params are
1910
+ // never replaced and no collision is possible there. tokenBag wire names
1911
+ // derive via the same wireParamName helper advancePagination uses at
1912
+ // runtime — one derivation, two consumers, no drift. Scope: listStyle
1913
+ // params only; scalar collisions stay legal (the seeded
1914
+ // `page: {default: 0}` + pageParam: page pattern).
1915
+ if (via === "paginate" && effectivePagination !== undefined) {
1916
+ const wireNames: string[] = [];
1917
+ if (effectivePagination.style === "tokenBag") {
1918
+ for (const key of effectivePagination.continuationParams ?? []) {
1919
+ wireNames.push(wireParamName(key));
1920
+ }
1921
+ } else {
1922
+ if (effectivePagination.pageParam)
1923
+ wireNames.push(effectivePagination.pageParam);
1924
+ if (effectivePagination.pageSizeParam)
1925
+ wireNames.push(effectivePagination.pageSizeParam);
1926
+ if (effectivePagination.cursorParam)
1927
+ wireNames.push(effectivePagination.cursorParam);
1928
+ if (effectivePagination.tokenParam)
1929
+ wireNames.push(effectivePagination.tokenParam);
1930
+ }
1931
+ for (const [key, spec] of Object.entries(params)) {
1932
+ if (spec.listStyle === undefined) continue;
1933
+ if (wireNames.includes(key)) {
1934
+ return fail(
1935
+ file,
1936
+ fieldPath(`params.${key}.listStyle`),
1937
+ "a param name not colliding with this operation's pagination wire params",
1938
+ `"${key}" is a pagination wire param (pagination.style: ${effectivePagination.style})`,
1939
+ {
1940
+ fix: `Rename params.${key} — pagination/tokenBag writes replace same-named base params, so the declared listStyle would never reach the wire.`,
1941
+ },
1942
+ );
1943
+ }
1944
+ }
1945
+ // Injected query-secret names vs pagination wire names — the paginate
1946
+ // URL is built as { ...pageParams, ...secretParams } (core/helpers.ts),
1947
+ // so the secret spreads last and overwrites the pagination value on
1948
+ // every page request: pagination silently never advances (valid-looking
1949
+ // 200s, page one forever). Injected names = static-key secretQueryRefs
1950
+ // key names plus oauth2 paramStyle: query's access_token — the same
1951
+ // secretQueryParams seam (core/auth.ts), merged last in the same spread.
1952
+ // Scoped to via: paginate like the listStyle guard — a restGet op never
1953
+ // builds pageParams, so a colliding name is legal there (the guide-level
1954
+ // secretQueryRefs-vs-params check must NOT extend to wire names).
1955
+ for (const secretName of injectedQuerySecretNames) {
1956
+ if (wireNames.includes(secretName)) {
1957
+ const isOAuth2 = authKind === "oauth2";
1958
+ return fail(
1959
+ file,
1960
+ isOAuth2 ? "auth.paramStyle" : `auth.secretQueryRefs.${secretName}`,
1961
+ "an injected query-secret name not colliding with this operation's pagination wire params",
1962
+ `"${secretName}" is a pagination wire param of operation "${name}" (pagination.style: ${effectivePagination.style}) — the injected secret overwrites the pagination value on every page request, so pagination never advances past page one`,
1963
+ {
1964
+ fix: isOAuth2
1965
+ ? `Set auth.paramStyle to bearer-header (or rename the wire param in operation "${name}"'s pagination block) — the query-injected access_token is merged after the pagination params and wins every page request.`
1966
+ : `Rename the secret ref in auth.secretQueryRefs (or the wire param in operation "${name}"'s pagination block) — the secret is merged after the pagination params and wins every page request.`,
1967
+ },
1968
+ );
1969
+ }
1970
+ }
1971
+ }
1972
+
1973
+ // listStyle × dateParams — mutually exclusive by design: date params are
1974
+ // single-valued (the runtime serializer throws before normalization on any
1975
+ // array), so a declared listStyle can never reach the wire. A defaulted
1976
+ // listStyle date param would additionally throw on every defaulted call —
1977
+ // the same every-call-throw class the array-default guard above exists for.
1978
+ if (dateParams !== undefined) {
1979
+ for (const key of Object.keys(dateParams)) {
1980
+ if (params[key]?.listStyle !== undefined) {
1981
+ return fail(
1982
+ file,
1983
+ fieldPath(`dateParams.${key}`),
1984
+ "a param not declaring listStyle (date params are single-valued — listStyle can never apply)",
1985
+ `"${key}" declares both listStyle: ${params[key]!.listStyle} and a dateParams entry`,
1986
+ {
1987
+ fix: `Drop one of the two — keep dateParams.${key} for date normalization, or remove it and declare listStyle on params.${key} if the API truly accepts multi-value dates.`,
1988
+ },
1989
+ );
1990
+ }
1991
+ }
1992
+ }
1993
+
1239
1994
  // gatherAllMax (op-level override)
1240
1995
  const opGatherAllMaxRaw = o["gatherAllMax"];
1241
1996
  let opGatherAllMax: number | undefined;
@@ -1269,6 +2024,7 @@ function validateOperation(
1269
2024
  ...(dateParams === undefined ? {} : { dateParams }),
1270
2025
  ...(requiresAnyOf === undefined ? {} : { requiresAnyOf }),
1271
2026
  ...(parseOverride ? { parse: parseOverride } : {}),
2027
+ ...(errorPath === undefined ? {} : { errorPath }),
1272
2028
  ...(opPagination ? { pagination: opPagination } : {}),
1273
2029
  ...(opGatherAllMax === undefined ? {} : { gatherAllMax: opGatherAllMax }),
1274
2030
  };
@@ -1387,6 +2143,24 @@ export function parseApiGuide(
1387
2143
  }
1388
2144
  const m = meta as Record<string, unknown>;
1389
2145
 
2146
+ // Frontmatter allowlist — reject keys parseApiGuide never reads (a typo'd
2147
+ // top-level key would be silently ignored today and hard-fail later once
2148
+ // the schema is published). Same closed-schema check as the op-block
2149
+ // allowlist; format mirrors the pagination per-style allowlist check.
2150
+ const unknownFmKeys = Object.keys(m).filter((k) => !GUIDE_ALLOWLIST.has(k));
2151
+ if (unknownFmKeys.length > 0) {
2152
+ const first = unknownFmKeys[0]!; // guarded by the length check above
2153
+ return fail(
2154
+ file,
2155
+ first,
2156
+ `a known frontmatter key (${[...GUIDE_ALLOWLIST].join(", ")})`,
2157
+ `unknown key(s): ${unknownFmKeys.join(", ")}`,
2158
+ {
2159
+ fix: `Remove ${first} from the frontmatter — the guide schema is closed.`,
2160
+ },
2161
+ );
2162
+ }
2163
+
1390
2164
  // ── projection slice ──────────────────────────────────────────
1391
2165
  const kindRaw = m["kind"];
1392
2166
  if (kindRaw !== undefined && kindRaw !== "api") {
@@ -1485,14 +2259,13 @@ export function parseApiGuide(
1485
2259
  description = descriptionRaw;
1486
2260
  }
1487
2261
 
1488
- // schemaVersion — breaking-change detection (design: "schemaVersion is
1489
- // detection, not enforcement"). Stamped on save by api-learn; absent-on-
1490
- // read defaults to 0 (the floor), so an unversioned guide flags as
1491
- // potentially stale after any schema bump rather than silently inheriting
1492
- // the new current. A valid-integer frontmatter value overrides the floor.
1493
- // A stale value (< current) warns non-blockingly in the api-guide catalog/
1494
- // detail and on api-fetch; never gates. A malformed (non-integer/negative)
1495
- // value falls back to 0 and never rejects a guide.
2262
+ // schemaVersion — breaking-change detection, enforced by the hard gate.
2263
+ // Stamped on save by api-learn; absent-on-read defaults to 0 (the floor),
2264
+ // so an unversioned guide is treated as pre-v1. A valid-integer frontmatter
2265
+ // value overrides the floor. A stale value (< current) fails to parse and
2266
+ // routes to malformed (the gate below). A malformed (non-integer/negative)
2267
+ // value also falls to the floor 0 and is caught by the same gate — one
2268
+ // code path, one message.
1496
2269
  let schemaVersion = 0;
1497
2270
  const schemaVersionRaw = m["schemaVersion"];
1498
2271
  if (
@@ -1502,6 +2275,20 @@ export function parseApiGuide(
1502
2275
  ) {
1503
2276
  schemaVersion = schemaVersionRaw;
1504
2277
  }
2278
+ if (isStaleSchema(schemaVersion, GUIDE_SCHEMA_VERSION)) {
2279
+ return fail(
2280
+ file,
2281
+ "schemaVersion",
2282
+ `>= ${GUIDE_SCHEMA_VERSION} (current)`,
2283
+ describeFound(schemaVersionRaw),
2284
+ {
2285
+ fix:
2286
+ `Guide ${file ?? "this guide"} was authored against schema ${schemaVersion}; the current schema is ${GUIDE_SCHEMA_VERSION}. ` +
2287
+ `Re-stamp its frontmatter to schemaVersion: ${GUIDE_SCHEMA_VERSION}, hand-fixing any breaking changes listed in the migration doc. ${MIGRATION_DOC_NOTE} ` +
2288
+ `Ask your agent to make this fix, then /reload.`,
2289
+ },
2290
+ );
2291
+ }
1505
2292
 
1506
2293
  let gatherAllMax = GATHER_ALL_MAX_FALLBACK;
1507
2294
  const gatherAllMaxRaw = m["gatherAllMax"];
@@ -1561,10 +2348,30 @@ export function parseApiGuide(
1561
2348
  );
1562
2349
  }
1563
2350
  const operations: Operation[] = [];
2351
+ // Injected query-secret names (the secretQueryParams seam in core/auth.ts):
2352
+ // static-key secretQueryRefs key names, plus oauth2 paramStyle: query's
2353
+ // access_token. Derived once here (auth is validated above) and passed to
2354
+ // every validateOperation for the paginate wire-name collision check.
2355
+ const injectedQuerySecretNames: ReadonlySet<string> = new Set([
2356
+ ...(auth.kind === "static-key" && auth.secretQueryRefs
2357
+ ? Object.keys(auth.secretQueryRefs)
2358
+ : []),
2359
+ ...(auth.kind === "oauth2" && auth.paramStyle === "query"
2360
+ ? ["access_token"]
2361
+ : []),
2362
+ ]);
1564
2363
  for (let i = 0; i < opsRaw.length; i++) {
1565
2364
  const opRaw = opsRaw[i];
1566
2365
  if (opRaw === undefined) continue;
1567
- const opRes = validateOperation(opRaw, i, file, pagination);
2366
+ const opRes = validateOperation(
2367
+ opRaw,
2368
+ i,
2369
+ file,
2370
+ pagination,
2371
+ responseShape,
2372
+ injectedQuerySecretNames,
2373
+ auth.kind,
2374
+ );
1568
2375
  if (!("name" in opRes)) return opRes as ParseApiGuideResult;
1569
2376
  operations.push(opRes);
1570
2377
  }
@@ -1593,6 +2400,82 @@ export function parseApiGuide(
1593
2400
  }
1594
2401
  }
1595
2402
 
2403
+ // Cross-field (oauth2 arm of the same D1 class): on paramStyle: query the
2404
+ // injected access_token must not be a declared op param — it spreads last
2405
+ // in `{ ...query, ...secretParams }`, so the agent's value would be
2406
+ // silently overwritten. Scoped to paramStyle: query — with the default
2407
+ // bearer-header the token rides the Authorization header and a legit
2408
+ // access_token query param is legal. Paginate ops with access_token as a
2409
+ // wire name are already rejected earlier by the wire-name collision check.
2410
+ if (auth.kind === "oauth2" && auth.paramStyle === "query") {
2411
+ for (const dOp of operations) {
2412
+ if ("access_token" in dOp.params) {
2413
+ return fail(
2414
+ file,
2415
+ "auth.paramStyle",
2416
+ "an injected query-secret name not declared in any operation's params",
2417
+ `also a param of operation "${dOp.name}"`,
2418
+ {
2419
+ fix: `Remove access_token from operation "${dOp.name}"'s params map — it is code-injected from the token store on paramStyle: query and the agent must not be able to set it.`,
2420
+ },
2421
+ );
2422
+ }
2423
+ }
2424
+ }
2425
+
2426
+ // Cross-field: secretPathRefs rules. Every path-ref name is a
2427
+ // secret-owned path token — the agent must never be able to set it, and
2428
+ // it must be load-bearing. Checked after operations (the operative fact
2429
+ // is that this runs after BOTH parses):
2430
+ // - a name in any op's `params` map (agent-suppliable). Path-token-keyed
2431
+ // params entries never reach dOp.params (the parser routes them to
2432
+ // pathParamDocs, description-only), so `in dOp.params` is exactly
2433
+ // "agent-suppliable" — a docs-only params.<name>.description entry
2434
+ // stays legal.
2435
+ // - a name in NO op's path as {name} → declared-but-unused (typo).
2436
+ // - a name shared with secretQueryRefs — would inject one secret into
2437
+ // the path and another into the query under the same name.
2438
+ if (auth.kind === "static-key" && auth.secretPathRefs) {
2439
+ for (const paramName of Object.keys(auth.secretPathRefs)) {
2440
+ if (auth.secretQueryRefs && paramName in auth.secretQueryRefs) {
2441
+ return fail(
2442
+ file,
2443
+ `auth.secretPathRefs.${paramName}`,
2444
+ "a path-token name not shared with secretQueryRefs",
2445
+ `also a secretQueryRefs key`,
2446
+ {
2447
+ fix: `"${paramName}" is declared in both secretPathRefs and secretQueryRefs — one would fill it in the path and the other in the query under the same name. Rename one.`,
2448
+ },
2449
+ );
2450
+ }
2451
+ for (const dOp of operations) {
2452
+ if (paramName in dOp.params) {
2453
+ return fail(
2454
+ file,
2455
+ `auth.secretPathRefs.${paramName}`,
2456
+ "a path-token name not declared in any operation's params",
2457
+ `also a param of operation "${dOp.name}"`,
2458
+ {
2459
+ fix: `Remove "${paramName}" from operation "${dOp.name}"'s params map — it is code-injected from the secrets store and the agent must not be able to set it. (A docs-only params.${paramName}.description entry is fine.)`,
2460
+ },
2461
+ );
2462
+ }
2463
+ }
2464
+ const used = operations.some((dOp) => dOp.pathParams.includes(paramName));
2465
+ if (!used) {
2466
+ return fail(
2467
+ file,
2468
+ `auth.secretPathRefs.${paramName}`,
2469
+ `a path-token name used by at least one operation's path as {${paramName}}`,
2470
+ "no operation's path contains {" + paramName + "}",
2471
+ {
2472
+ fix: `Use {${paramName}} in at least one operation's path, or remove the secretPathRefs entry (declared-but-unused is usually a typo).`,
2473
+ },
2474
+ );
2475
+ }
2476
+ }
2477
+ }
2478
+
1596
2479
  const guide: ApiGuide = {
1597
2480
  content,
1598
2481
  updated,
@@ -1617,80 +2500,8 @@ export function parseApiGuide(
1617
2500
  return { ok: true, guide };
1618
2501
  }
1619
2502
 
1620
- // ═══════════════════════════════════════════════════════════════════
1621
- // projectToGuide — strips recipe fields, keeps presentation + kind
1622
- // ═══════════════════════════════════════════════════════════════════
1623
-
1624
- export function projectToGuide(guide: ApiGuide): Guide {
1625
- const projection: Guide = {
1626
- content: guide.content,
1627
- updated: guide.updated,
1628
- category: guide.category,
1629
- source: guide.source,
1630
- icon: guide.icon,
1631
- shortName: guide.shortName,
1632
- kind: guide.kind,
1633
- ...(guide.domains ? { domains: guide.domains } : {}),
1634
- };
1635
- return projection;
1636
- }
1637
-
1638
- // ═══════════════════════════════════════════════════════════════════
1639
- // Directory loader — one malformed guide doesn't block the store.
1640
- //
1641
- // Loads from per-domain subdirectories: <dir>/<domain>/guide.md.
1642
- // Flat top-level .md files are no longer loaded (pre-ship break;
1643
- // no production user guides exist before this change).
1644
- // ═══════════════════════════════════════════════════════════════════
1645
-
1646
- export function loadApiGuidesFromDir(dir: string): LoadedApiGuides {
1647
- const result: LoadedApiGuides = { guides: {}, malformed: [] };
1648
- if (!existsSync(dir)) return result;
1649
- let entries: string[];
1650
- try {
1651
- entries = readdirSync(dir);
1652
- } catch {
1653
- return result;
1654
- }
1655
- for (const entry of entries) {
1656
- const entryPath = join(dir, entry);
1657
- try {
1658
- if (!statSync(entryPath).isDirectory()) continue;
1659
- } catch {
1660
- continue;
1661
- }
1662
- const guidePath = join(entryPath, "guide.md");
1663
- try {
1664
- if (!statSync(guidePath).isFile()) continue;
1665
- } catch {
1666
- continue;
1667
- }
1668
- const name = entry; // domain name = subdir name
1669
- let raw: string;
1670
- try {
1671
- raw = readFileSync(guidePath, "utf-8");
1672
- } catch {
1673
- continue;
1674
- }
1675
- const parsed = parseApiGuide(raw, {
1676
- file: guidePath,
1677
- filename: name,
1678
- });
1679
- if (parsed.ok) {
1680
- result.guides[name] = parsed.guide;
1681
- } else {
1682
- result.malformed.push({
1683
- file: guidePath,
1684
- filename: name,
1685
- error: parsed.error,
1686
- });
1687
- }
1688
- }
1689
- return result;
1690
- }
1691
-
1692
2503
  // ════════════════════════════════════════════════════════════════════
1693
- // Schema-version staleness — detection, never a gate
2504
+ // Schema-version staleness — the hard gate's predicate
1694
2505
  // ════════════════════════════════════════════════════════════════════
1695
2506
 
1696
2507
  /**
@@ -1704,203 +2515,3 @@ export function isStaleSchema(
1704
2515
  ): boolean {
1705
2516
  return guideSchemaVersion < currentSchemaVersion;
1706
2517
  }
1707
-
1708
- /**
1709
- * Non-blocking stale-schema warning line for a guide, or undefined when the
1710
- * guide is current. Peer of the `⚠ malformed` catalog line — detection,
1711
- * never a gate (the guide still loads and runs). `current` defaults to
1712
- * GUIDE_SCHEMA_VERSION; tests pass a bumped value to force staleness.
1713
- */
1714
- export function staleSchemaLine(
1715
- guide: ApiGuide,
1716
- current: number = GUIDE_SCHEMA_VERSION,
1717
- ): string | undefined {
1718
- const v = guide.schemaVersion ?? 0;
1719
- if (!isStaleSchema(v, current)) return undefined;
1720
- return ` ⚠ schemaVersion ${v} < current ${current} — guide may need updating`;
1721
- }
1722
-
1723
- // ════════════════════════════════════════════════════════════════════
1724
- // Disambiguation helpers — shared by the api-guide menu and the
1725
- // api-fetch ambiguous-operation error. One rendering of the per-guide
1726
- // listing so the two surfaces stay visually consistent.
1727
- // ════════════════════════════════════════════════════════════════════
1728
-
1729
- /**
1730
- * Truncated op-name summary for disambiguation surfaces:
1731
- * "N ops: a, b, c, d, e, +K more" (first 5 names, then the remaining count).
1732
- * A 50-op guide must not dump 50 names into context — the menu exists to
1733
- * help pick a guide cheaply; the full op list is one api-guide call away.
1734
- */
1735
- function formatOpSummary(ops: { name: string }[]): string {
1736
- const names = ops.map((o) => o.name);
1737
- const count = names.length;
1738
- const head = names.slice(0, 5);
1739
- const remaining = count - head.length;
1740
- const tail = remaining > 0 ? `, +${remaining} more` : "";
1741
- return `${count} ops: ${head.join(", ")}${tail}`;
1742
- }
1743
-
1744
- /**
1745
- * Per-guide listing lines for a disambiguation surface (the api-guide
1746
- * multi-guide menu and the api-fetch ambiguous-op error). Each entry:
1747
- * `icon shortName` [+ ` — description` when present] then the truncated
1748
- * op-name list. When `description:` is absent the line falls back to
1749
- * shortName + op names only (the status-quo shape), so un-backfilled
1750
- * guides render consistently with those that have a one-line summary.
1751
- */
1752
- export function formatGuideListings(
1753
- entries: { guide: ApiGuide }[],
1754
- current: number = GUIDE_SCHEMA_VERSION,
1755
- ): string {
1756
- const lines: string[] = [];
1757
- for (const { guide } of entries) {
1758
- lines.push(
1759
- ` ${guide.icon} ${guide.shortName}` +
1760
- (guide.description ? ` — ${guide.description}` : ""),
1761
- );
1762
- lines.push(` ${formatOpSummary(guide.operations)}`);
1763
- const stale = staleSchemaLine(guide, current);
1764
- if (stale) lines.push(stale);
1765
- }
1766
- return lines.join("\n");
1767
- }
1768
-
1769
- /**
1770
- * Resolve a guide by shortName across a domain's matches (exact,
1771
- * case-insensitive). Shared by api-guide, api-learn's fetch-recipe, and
1772
- * /api verify — three call sites, one resolution rule (a drifted copy would
1773
- * ship a known second bug). Returns a structured outcome; each caller renders
1774
- * its own message (tool result vs command notify).
1775
- */
1776
- export function selectGuideByShortName(
1777
- matches: { guide: ApiGuide; dirName: string }[],
1778
- selector: string,
1779
- ):
1780
- | { ok: true; guide: ApiGuide; dirName: string }
1781
- | { ok: false; reason: "no_match"; valid: string[] }
1782
- | { ok: false; reason: "ambiguous"; directories: string[] } {
1783
- const lc = selector.toLowerCase();
1784
- const sel = matches.filter((m) => m.guide.shortName.toLowerCase() === lc);
1785
- if (sel.length === 0) {
1786
- return {
1787
- ok: false,
1788
- reason: "no_match",
1789
- valid: matches.map((m) => m.guide.shortName),
1790
- };
1791
- }
1792
- if (sel.length > 1) {
1793
- return {
1794
- ok: false,
1795
- reason: "ambiguous",
1796
- directories: sel.map((s) => s.dirName),
1797
- };
1798
- }
1799
- return { ok: true, guide: sel[0]!.guide, dirName: sel[0]!.dirName };
1800
- }
1801
-
1802
- /**
1803
- * Render the no-match / ambiguous error text for a failed
1804
- * `selectGuideByShortName` result. `callToAction` is the trailing
1805
- * "how to see the menu" sentence — it differs per surface (tool vs
1806
- * command), so callers pass their own.
1807
- */
1808
- export function shortNameErrorText(
1809
- sel: Extract<ReturnType<typeof selectGuideByShortName>, { ok: false }>,
1810
- domain: string,
1811
- selector: string,
1812
- callToAction: string,
1813
- ): string {
1814
- if (sel.reason === "no_match") {
1815
- return (
1816
- `No guide named '${selector}' for '${domain}'. ` +
1817
- `Available guides: ${sel.valid.join(", ")}. ` +
1818
- callToAction
1819
- );
1820
- }
1821
- return (
1822
- `Ambiguous guide '${selector}' for '${domain}' — ` +
1823
- `${sel.directories.length} guides share shortName '${selector}' ` +
1824
- `(directories: ${sel.directories.join(", ")}). Rename one guide's shortName to ` +
1825
- `disambiguate. ` +
1826
- callToAction
1827
- );
1828
- }
1829
-
1830
- // ════════════════════════════════════════════════════════════════════
1831
- // Catalog rendering — healthy + ⚠ malformed together
1832
- //
1833
- // Base catalog is collapsed by `organization:`: one line per org with its
1834
- // guide count and domain set. Guides without `organization:` fall back to
1835
- // the per-guide line, so the un-backfilled corpus renders unchanged (no
1836
- // forced migration). Op counts live on the per-domain disambiguation menu
1837
- // (api-guide {domain}), where they're useful for picking a guide — not
1838
- // here, where they'd bloat context for orgs with many guides.
1839
- // ════════════════════════════════════════════════════════════════════
1840
-
1841
- export function formatApiGuideCatalog(
1842
- loaded: LoadedApiGuides,
1843
- current: number = GUIDE_SCHEMA_VERSION,
1844
- ): string {
1845
- const lines: string[] = ["API guides:"];
1846
-
1847
- // Org-grouped rows preserve first-appearance order; guides without
1848
- // organization fall back to the per-guide line (no forced migration).
1849
- const orgRows: { org: string; guides: ApiGuide[] }[] = [];
1850
- const orgIndex = new Map<string, number>();
1851
- const orgless: { name: string; guide: ApiGuide }[] = [];
1852
- for (const [name, guide] of Object.entries(loaded.guides)) {
1853
- if (guide.organization) {
1854
- const idx = orgIndex.get(guide.organization);
1855
- if (idx === undefined) {
1856
- orgIndex.set(guide.organization, orgRows.length);
1857
- orgRows.push({ org: guide.organization, guides: [guide] });
1858
- } else {
1859
- orgRows[idx]!.guides.push(guide);
1860
- }
1861
- } else {
1862
- orgless.push({ name, guide });
1863
- }
1864
- }
1865
-
1866
- for (const row of orgRows) {
1867
- const domains = new Set<string>();
1868
- for (const g of row.guides) {
1869
- for (const d of g.domains ?? []) domains.add(d);
1870
- }
1871
- const domList = domains.size > 0 ? [...domains].join(", ") : "—";
1872
- const n = row.guides.length;
1873
- // Collapsed org row: a trailing ⚠ glyph when ANY guide in it is stale
1874
- // (hint only — the per-guide ⚠ line lives on the menu / detail view).
1875
- const stale = row.guides.some((g) =>
1876
- isStaleSchema(g.schemaVersion ?? 0, current),
1877
- );
1878
- lines.push(
1879
- ` 🏛️ ${row.org} — ${n} guide${n > 1 ? "s" : ""} (${domList})${stale ? " ⚠" : ""}`,
1880
- );
1881
- }
1882
- for (const { name, guide } of orgless) {
1883
- const domains =
1884
- guide.domains && guide.domains.length > 0 ? guide.domains.join(", ") : name;
1885
- lines.push(
1886
- ` ${guide.icon} ${guide.shortName} — ${domains} (verified ${guide.verified}, ${guide.operations.length} ops)`,
1887
- );
1888
- const stale = staleSchemaLine(guide, current);
1889
- if (stale) lines.push(stale);
1890
- }
1891
- for (const mal of loaded.malformed) {
1892
- lines.push(
1893
- ` ⚠ malformed — ${mal.filename}: ${mal.error.field} — expected ${mal.error.expected}; found ${mal.error.found}`,
1894
- );
1895
- }
1896
- if (Object.keys(loaded.guides).length === 0 && loaded.malformed.length === 0) {
1897
- lines.push(
1898
- " (no guides — call api-learn({domain, recipeFile}) to author one)",
1899
- );
1900
- }
1901
- lines.push("");
1902
- lines.push(
1903
- 'Call api-guide({domain: "<name>"}) for detail. Multiple guides for a domain show a disambiguation menu.',
1904
- );
1905
- return lines.join("\n");
1906
- }