Skip to content

feat(server): credentialPolicy args-bag scan (#1529 L1) - #1535

Merged
bokelley merged 5 commits into
mainfrom
bokelley/credential-policy
May 4, 2026
Merged

bokelley merged 5 commits into
mainfrom
bokelley/credential-policy

Conversation

@bokelley

@bokelley bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor

Summary

Closes #1529 L1. Opt-in credentialPolicy: 'authInfo-only' scans every incoming request's args bag for credential-shaped keys at any depth and rejects with INVALID_REQUEST. Closes the buyer-args credential-smuggling vector class observed across three rounds of review on PR scope3data/agentic-adapters#248 — top-level <platform>_access_token, nested context.<platform>_access_token, nested ext.<platform>_access_token — at the framework boundary, regardless of how each adapter's extractContext reads from args.

Default mode is 'lax' (back-compat). Opt in to enforce.

Design

credentialPolicy accepts a string shorthand or a config object:

// simple
createAdcpServer({ credentialPolicy: 'authInfo-only' })

// extensible patterns + per-tool overrides
createAdcpServer({
  credentialPolicy: {
    policy: 'authInfo-only',
    patterns: { extend: [/^bearer$/i, /credentials/i] },
    tools: { activate_signal: 'lax' },
  },
})

Default patterns: _access_token$, _secret$, _password$, accessToken, refreshToken. Per the follow-up comment on #1529, the SDK ships configurable matchers from day one — adopters know their platform vocabulary best, and round-4 vectors land in adopter config rather than SDK releases.

The rejection envelope reports paths only (no values) and bypasses finalize so injectContextIntoResponse can't echo the offending params.context value back through the response. Tested explicitly.

Hook point: in toolHandler, before request schema validation. Uniform behavior across validation: 'off' | 'warn' | 'strict'.

Files

  • src/lib/server/credential-policy.ts (new) — scanArgsForCredentials, resolveCredentialPolicyForTool, getCredentialPatterns, DEFAULT_CREDENTIAL_PATTERNS, types
  • src/lib/server/create-adcp-server.ts — credentialPolicy? field on AdcpServerConfig, scan wired into toolHandler
  • src/lib/server/index.ts — re-exports
  • test/server-credential-policy.test.js (new) — 25 tests covering scanner, policy resolution, all three round-N vectors, no-echo invariant, per-tool override, extensible patterns
  • docs/guides/CTX-METADATA-SAFETY.md — defense-in-depth section
  • .changeset/credential-policy-l1.md — minor bump

Test plan

  • npm run build clean
  • npm run typecheck clean
  • npm run format:check clean
  • npm run lint baseline (no new errors)
  • 25/25 new credential-policy tests pass
  • 1210/1210 server-side test suite pass (test/server-*.test.js) — no regression
  • Rejection envelope does NOT echo offending value back (explicit test)
  • All three round-N vectors caught in a single call (explicit test)

What this is NOT

🤖 Generated with Claude Code

bokelley and others added 3 commits May 3, 2026 21:53
`sync-version` regenerates these from package.json on every build; the
release commit (#1507) bumped package.json to 6.9.0 but the generated
files weren't checked in. Catching them up so subsequent diffs stay
focused on real changes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Closes the buyer-args credential-smuggling vector class observed across
three rounds of review on PR scope3data/agentic-adapters#248: top-level
`<platform>_access_token`, nested `context.<platform>_access_token`,
nested `ext.<platform>_access_token`. Default `'lax'` preserves existing
behavior; opt into `'authInfo-only'` to scan args at any depth and
reject with INVALID_REQUEST listing the offending paths.

Patterns extensible via `credentialPolicy.patterns.extend` or fully
replaceable via `credentialPolicy.patterns.matcher`. Per-tool overrides
via `credentialPolicy.tools` for the rare legitimate buyer-creds tool.
Rejection envelope reports paths only and bypasses `params.context`
echo so the offending value does not round-trip through the response.

This is L1 of the design at #1529. L2 (typed wire-spec args, brand at
the operational boundary) ships separately after #1530 lands the
OperationalPlatform interface.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@bokelley

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Author here, but reviewing this with fresh eyes — feedback from the consumer side now that I've read the diff cold.

What I really like

  • finalize bypass for the rejection envelope. This is exactly the right call — injectContextIntoResponse echoing params.context would have round-tripped the credential the scan just caught. Easy detail to miss, comment captures the why well.
  • Hook point BEFORE request schema validation. Uniform across 'off' | 'warn' | 'strict'. Adopters in 'off' mode (e.g. running the comply test controller) get the same protection.
  • Cycle-safe via WeakSet. A buyer who sends a self-referential JSON object can't infinite-loop the scanner. Defensive and correct.
  • "The next platform-specific vector lives in adopter config, not in the SDK" — great framing in the changeset. Keeps the SDK honest, gives adopters real control.
  • 'lax' default for back-compat. Right call for a minor bump.

Concerns worth addressing in this PR

1. Default patterns leave easy escapes

The defaults catch _access_token$, _secret$, _password$, accessToken, refreshToken. They miss several common shapes:

  • api_key / apiKey — extremely common, esp. in retail-media adapters. criteo_api_key, audiostack_api_key, etc.
  • _token$ (without _access prefix) — bearer_token, id_token, session_token. Trivial to write, escapes the regex.
  • PascalCase variants of camelCase patterns — ^accessToken$ is anchored exact. AccessToken: 'x' (PascalCase) slips past. The _access_token$ regex uses /i but the camelCase ones don't. Asymmetry.

Suggested defaults extension:

/_token$/i,        // catches bearer_token, id_token, session_token
/api[_-]?key/i,    // catches api_key, apiKey, api-key
/^bearer$/i,

…and make the camelCase patterns case-insensitive (/^accessToken$/i).

2. The account ref pivot vector isn't covered — and shouldn't be conflated with credentials

The PR description says "closes the buyer-args credential-smuggling vector class" but Emma's round-3 review on scope3data/agentic-adapters#248 actually identified TWO categories:

  • Credentials — <platform>_access_token, secrets, etc. → credentialPolicy handles ✓
  • Identity — request.account: { brand: 'attacker.com' } to pivot onto a different ad account → NOT handled here

The mitigation for the second is AccountStore.resolve org-gating, not args-bag scanning. Worth either:

  • Documenting explicitly: "this closes credentials but not identity smuggling — see AccountStore.resolve for that"
  • Adding a separate identityPolicy flag (probably future work)

Recommend the doc note in this PR. Otherwise adopters who read this will think they're fully protected.

3. tools: { activate_signal: 'lax' } per-tool overrides are typo-fragile

If an adopter writes tools: { activte_signal: 'lax' } (typo), the override silently no-ops and 'authInfo-only' applies — which would actually fail-closed correctly for that case but the broader concern is the other direction: adopter writes tools: { my_legitimate_buyer_creds_tool: 'lax' }, typos the tool name, and prod traffic to that tool starts rejecting. The framework knows the registered tool names (it registers them). Could validate at server construction that Object.keys(policy.tools ?? {}) are all registered tools, throw at startup if not.

Could be follow-up — flag it now.

4. field: hits[0] under-discloses

adcpError('INVALID_REQUEST', { field: hits[0], details: { credential_paths: hits } }) — field is an AdCP-spec single-path indicator. Reporting only the first hit is slightly arbitrary when 3+ vectors are present together. Adopters debugging client integrations might miss the full picture.

Two options:

  • Set field to a non-path value like '__credential_policy__' (or omit) and put the full list in details.credential_paths only
  • If the spec allows array-of-fields, surface all paths

Minor, but the current shape implies "this one path" when the truth is "any of these".

DX observations

  • Consider shipping a lint rule (or npx adcp-doctor mode) that scans an adopter's extractContext implementations for args.<word>_access_token reads. The pattern is so widespread in v5-shaped adapters that build-time detection would be a much bigger DX win than runtime rejection.
  • For v7, recommend flipping default to 'authInfo-only' and requiring 'lax' to be explicit. Secure-by-default beats secure-by-opt-in for new adopters.
  • Documentation in CTX-METADATA-SAFETY.md should call out concretely the three round-N vectors with example payloads. Adopters who don't know what's at stake won't opt in.

Nits

  • getCredentialPatterns is a one-liner used once. Could be inlined.
  • extend + matcher precedence (matcher wins) is documented but could throw at config time when both are set, since the silent override is footgun-y.

🤖 Generated with Claude Code

Six concerns from the cold-eyes review:

1. **Default patterns broadened.** Previous set missed `bearer_token`,
   `id_token`, `session_token`, `api_key`, bare `bearer`, and PascalCase
   `AccessToken`. New defaults: `_token$/i`, `_secret$/i`, `_password$/i`,
   `api[_-]?key/i`, `^bearer$/i`, `^accessToken$/i`, `^refreshToken$/i`.
   Removed `_access_token$` (subsumed by `_token$`). camelCase patterns
   are now case-insensitive.

2. **Identity-pivot vector documented as out-of-scope.** New section in
   CTX-METADATA-SAFETY.md clarifies `credentialPolicy` does NOT cover
   `request.account: { brand: 'attacker.com' }` — that's `AccountStore`
   org-gating territory. Adopters who don't gate their resolver are not
   protected by this scan.

3. **Typo'd `tools[]` keys throw at construction.** New
   `validateCredentialPolicy(policy, knownToolNames)` runs after the
   tool-registration loop and throws when `tools` references an
   unregistered name. Catches `tools: { activte_signal: 'lax' }` before
   first traffic so the silent-no-op-then-fail-closed footgun is gone.

4. **`field` dropped from rejection envelope.** Previous `field: hits[0]`
   under-disclosed when several vectors were present together. Full
   list lives in `details.credential_paths` only.

5. **`extend` + `matcher` both set throws.** Previous behavior silently
   chose `matcher`. Now throws with a specific message at the helper
   AND at construction time via `validateCredentialPolicy`.

6. **Doc round-N example payloads.** Concrete top-level / nested-context
   / nested-ext payloads in the safety guide so adopters reading cold
   know what they're opting into.

Nit: `getCredentialPatterns` was a one-liner used once; inlined it.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@bokelley

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in e7dffa52. Walking the comment top-to-bottom:

In this PR

1. Default patterns broadened ✅
New set: /_token$/i, /_secret$/i, /_password$/i, /api[_-]?key/i, /^bearer$/i, /^accessToken$/i, /^refreshToken$/i. Dropped _access_token$ (subsumed by _token$). camelCase patterns now case-insensitive — catches AccessToken, ACCESSTOKEN, etc. Test coverage for each new vector.

Punted on broader *Token$ PascalCase suffix — paymentToken could be a legitimate wire field. Documented in the new pattern-set comment block; adopters extend.

2. Identity-pivot disclaimer ✅
New section in CTX-METADATA-SAFETY.md: "What credentialPolicy does NOT cover" with the concrete account: { brand: 'attacker.com' } example and the redirect to AccountStore.resolve org-gating. Explicit: "If your resolver doesn't gate on the principal's authorized accounts, credentialPolicy: 'authInfo-only' will not save you."

3. Typo'd tools[] keys throw at construction ✅
New validateCredentialPolicy(policy, knownToolNames) runs after the tool-registration loop. tools: { activte_signal: 'lax' } throws with the registered tool list in the error message before first traffic. Test covers the typo path.

4. field dropped from rejection envelope ✅
Was field: hits[0] (arbitrary single-path), now omitted. Full list still in details.credential_paths. Test asserts field === undefined.

5. extend + matcher both set throws ✅
Previous behavior silently chose matcher. Now throws both at the runtime helper and at construction-time validation. Tests cover both paths.

6. Round-N example payloads in docs ✅
Three concrete jsonc examples (top-level, nested context, nested ext) in CTX-METADATA-SAFETY.md showing exactly what 'authInfo-only' rejects.

Nit: getCredentialPatterns ✅
Inlined into create-adcp-server.ts. One ternary.

Deferred (with reasons)

v7 default flip to 'authInfo-only' — agreed in principle, but a major-bump default change. Filing separately.

Lint rule for v5 extractContext patterns — bigger DX project. The args.<word>_access_token pattern is so widespread that build-time detection would beat runtime rejection. Worth its own issue (@adcp/sdk/lint package?). Will file.

Test results

  • 36/36 credential-policy tests pass (+11 from previous 25)
  • 1199/1199 server suite pass (no regressions)
  • format / typecheck / lint clean

Ready for re-review.

@bokelley

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough walkthrough — the six addressed items look well-scoped and the deferred items (v7 default flip, lint rule) are sensible punts with clear rationale. 36/36 + 1199/1199 with no regressions is a clean baseline for re-review.


Generated by Claude Code

@bokelley

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Reviewed commit e7dffa5 against all four concerns. All addressed — verified locally (36/36 tests pass after rebuild):

  1. Default patterns broadened ✓ — _token$/i, api[_-]?key/i, /^bearer$/i added; accessToken/refreshToken now case-insensitive; _access_token$ dropped (subsumed by _token$).
  2. Identity-pivot vector documented ✓ — CTX-METADATA-SAFETY.md now has a clear "what credentialPolicy does NOT cover" section pointing to AccountStore.resolve org-gating.
  3. Typo'd tools[] keys throw at construction ✓ — validateCredentialPolicy(policy, knownToolNames) runs post-registration loop; activte_signal gets caught before first traffic.
  4. field under-disclosure fixed ✓ — field dropped entirely from the rejection envelope; full path list lives in details.credential_paths only.

Also caught that the upstream commit had a 5th fix (concurrent extend+matcher throws rather than silently dropping extend), which is a good catch.

One note for reviewers: the dist in this repo isn't committed, so the test failures visible in the pre-push validation were a stale-dist artifact — source is correct and all 36 tests pass against a fresh build.


Triaged by Claude Code. Session: https://claude.ai/code/session_01MmepaE5djoQso4ordzDyfP


Generated by Claude Code

@bokelley

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Glad the walkthrough landed cleanly. Marking ready for re-review — let me know if anything surfaces on your pass.


Generated by Claude Code

@bokelley

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Acknowledged — nothing to flag from my side on this pass. The design looks clean and the test coverage is solid. Ready for CODEOWNERS review.


Generated by Claude Code

@bokelley

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks — noted. No further action from this side; standing by for CODEOWNERS review.


Triaged by Claude Code. Session: https://claude.ai/code/session_016EyH4GRNRLKRnMttiVYYaH


Generated by Claude Code

Three independent expert reviews surfaced eight items; addressing all.

**Protocol-correctness (ad-tech-protocol-expert)**
- Error code `INVALID_REQUEST` → `PERMISSION_DENIED`. AdCP request
  schemas set `additionalProperties: true`, so a credential-bearing
  payload is structurally well-formed. The rejection is a SELLER POLICY
  violation, not schema drift. Spec text on `PERMISSION_DENIED`
  ("authenticated caller is not authorized for the requested action
  under the seller's own policies") matches exactly. Mirrors the
  existing buyer-agent-status rejection (`details.scope: 'agent'`,
  `recovery: 'correctable'`).

**Security (security-reviewer)**
- `validateCredentialPolicy` now runs AFTER `get_adcp_capabilities`
  registration so `tools: { get_adcp_capabilities: 'lax' }` doesn't
  spuriously throw. The typo-check claim "the registered tool set is
  authoritative" is now true for every tool.
- Walker hardened against accessor-property getters via
  `Object.getOwnPropertyDescriptors` — credential-named getters are
  flagged by name fail-closed, but the getter itself is never invoked.
  Defends hand-built / proxy-trapped inputs against
  throw-and-log-`params` DoS.
- Default patterns broadened to cover `^authorization$/i`, `^cookie$/i`,
  `private[_-]?key/i` (HTTPSig / JWT signing-key flows; HTTP-header
  smuggling). Documented exclusions: bare `key`/`principal`/`kid`/`pat`
  (too short to risk false positives).

**Code quality (code-reviewer)**
- `/g` and `/y` flags stripped from adopter-supplied `extend` regexes.
  `/credentials/gi` is a natural footgun — without stripping,
  `RegExp.prototype.test` advances `lastIndex` and skips alternating
  inputs across calls. `/i` and other intent-bearing flags preserved.
- `validateCredentialPolicy` and `resolveCredentialPolicyForTool`
  marked `@internal` and dropped from the public `index.ts` exports.
  Adopters can't construct `knownToolNames` outside the framework
  anyway; cleaner public surface.
- New tests: getter defense, `/g`/`/y` stripping, `/i` preservation,
  `matcher.path` parameter, idempotency-ordering pin (rejected
  credential-bearing payload doesn't poison the replay cache —
  retry with same idempotency_key + clean payload succeeds).
- Inlined single-method `ResolvedMatcher` interface as a function type.

43/43 credential-policy tests, 1238/1238 server suite, format /
typecheck / lint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@bokelley

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Ran the PR by three experts (security-reviewer, code-reviewer, ad-tech-protocol-expert) in parallel. Eight findings, all addressed in 7412f0ab.

Protocol-correctness — error code change

INVALID_REQUEST → PERMISSION_DENIED (per ad-tech-protocol-expert review)

The reviewer's spec citation was decisive: AdCP request schemas set additionalProperties: true, so a credential-bearing payload is structurally well-formed. INVALID_REQUEST is for schema violations; this is a seller POLICY violation. Spec text on PERMISSION_DENIED matches exactly: "the authenticated caller is not authorized for the requested action under the seller's own policies" (enums/error-code.json:99).

New envelope shape:

{
  "code": "PERMISSION_DENIED",
  "message": "Request args carry credential-shaped keys. Credentials must arrive on authInfo, not in the request body.",
  "recovery": "correctable",
  "details": {
    "scope": "credentials",
    "credential_paths": ["snap_access_token", "context.linkedin_access_token"]
  }
}

Mirrors the existing buyer-agent-status rejection (details.scope: 'agent').

Security findings

  • validateCredentialPolicy ordering bug: was running before get_adcp_capabilities was registered, so tools: { get_adcp_capabilities: 'lax' } would spuriously throw. Moved to after the capabilities-tool registration.
  • Getter defense: walker now uses Object.getOwnPropertyDescriptors and only recurses into data descriptors. Credential-named getters are flagged by name fail-closed, but the getter is never invoked. Defends hand-built / proxy-trapped inputs against throw-and-log-params DoS.
  • Default patterns broadened: added ^authorization$/i, ^cookie$/i, private[_-]?key/i (HTTP-header smuggling, JWT/HTTPSig signing keys).

Code quality findings

  • /g and /y flag stripping in extend regexes. /credentials/gi is a natural footgun — RegExp.prototype.test advances lastIndex and would skip alternating inputs across calls. /i preserved.
  • Public surface trimmed: validateCredentialPolicy and resolveCredentialPolicyForTool marked @internal and dropped from index.ts. Adopters can't construct knownToolNames outside the framework anyway.
  • ResolvedMatcher interface inlined as a function type — single-method interfaces add no type safety.

New test coverage

  • Getter defense: credential-named getter is flagged by name without invocation
  • /g//y stripping (state-leak between calls)
  • /i preservation when stripping /g//y
  • matcher.path parameter exercise (was untested)
  • Idempotency-ordering pin: a rejected credential-bearing payload does NOT poison the replay cache, so a retry with the same idempotency_key and a CLEAN payload succeeds. Locks in the dispatcher ordering.
  • New defaults: authorization / cookie / private_key variants

Deferred

Three items kept out of L1 scope, will file as follow-ups:

  1. Spec PR on adcontextprotocol/adcp clarifying credentials MUST arrive on authInfo (RFC 6750 §2 alignment).
  2. Scanning ctx.authInfo.extra as part of L2's broader perimeter.
  3. Per-tool { allow: [...] } granular allowlist (L2 — narrower than the current 'lax' opt-out).

Test results post-fix

  • 43/43 credential-policy tests pass (+7 from prior 36)
  • 1238/1238 server suite pass
  • Format / typecheck / lint clean

Ready for admin merge once CI greens.

@bokelley

bokelley commented May 4, 2026

Copy link
Copy Markdown
Contributor Author

Acknowledged. The INVALID_REQUEST → PERMISSION_DENIED correction is the right call per spec — credential-bearing payloads are structurally valid, so this is purely a policy violation on the seller's side. The getter defense and /g//y stripping are solid hardening. Will stand by for CI.


Triaged by Claude Code. Session: https://claude.ai/code/session_012Rg1koR28wmheYGdw8kbNT


Generated by Claude Code

@bokelley
bokelley merged commit f57a9c7 into main May 4, 2026
10 of 11 checks passed
@bokelley
bokelley deleted the bokelley/credential-policy branch May 4, 2026 02:37
bokelley added a commit that referenced this pull request May 4, 2026
* feat(server): WireSafe<T> brand + pickWireSpecFields (#1529 L2)

Closes #1529. Ships the L2 half of the credential-discipline plan
designed in `.context/operational-fanout-design.md`.

L1 (#1535 credentialPolicy) catches credential-shaped keys at the
buyer-facing dispatch boundary. L2 catches STRUCTURAL leakage at the
operational fan-out boundary — storefront fan-out code that picks
per-target args from a buyer request and forwards them upstream,
where the buyer-facing scan has already passed.

Three pieces:

1. **`WireSafe<T>` brand** via `unique symbol`. `{...buyerReq}` is
   `T`, not `WireSafe<T>` — so passing it where `WireSafe<T>` is
   required is a compile error. The brand is the load-bearing
   element: code that spreads a buyer request directly cannot
   satisfy it.

2. **`pickWireSpecFields(req, schemaName)`** — the canonical
   constructor of `WireSafe<T>`. Strips a buyer request to the AdCP
   wire-spec field allowlist for `schemaName`, returns a branded
   value. Drops top-level credential-shaped keys, unknown attacker
   payload, and anything not in the schema's `properties` list.

3. **`scrubExtensions(safe, options)`** — per-target ext/context
   scrub. Filters `ext` and `context` (which `pickWireSpecFields`
   keeps whole because they're wire-spec fields) to a caller-
   specified key allowlist, and merges in caller-injected values
   (storefront-resolved credentials/IDs). Returns `WireSafe<T>` so
   the brand survives the chain.

**Codegen.** `scripts/generate-wire-spec-fields.ts` walks
`schemas/cache/{version}/**/*-request.json` and emits
`src/lib/server/wire-spec-fields.generated.ts` with field arrays per
request type. Drift between the helper and the schema is
structurally impossible — both are emitted from the same codegen
pass. Restricted to fan-out-relevant request types (every mutating
tool in `MUTATING_TASKS` + `get_media_buy_delivery`); 29 types
total.

**Source-compatible with #1530.** `OperationalPlatform` method
signatures keep their existing plain-typed parameters
(`request: UpdateMediaBuyRequest`). The brand is opt-in at the type
level — adopters who use `pickWireSpecFields` get the safety benefit
at the picking site (compile error if they accidentally spread
buyer args into the variable typed `WireSafe<T>`). Adopters not
using the helper see no behavior change. If we want to make the
brand mandatory at the operational boundary in a future major bump,
that's a v7 change.

17/17 wire-safe tests, 1291/1291 server suite, format / typecheck
clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(wire-safe): expert review (#1544)

Two reviewers flagged convergent and independent findings; addressing
all in this commit.

**Recursive credential scan** (security M1, the load-bearing fix).
`pickWireSpecFields` keeps `ext` and `context` whole because they're
wire-spec fields — but a buyer hiding credentials at depth (e.g.
`ext.partner.partner_access_token`) survives both `pickWireSpecFields`
and a top-level-only `scrubExtensions` filter. Round-4 vector waiting
to happen.

`scrubExtensions` now recursively scans `ext` and `context` values
using the L1 credential-policy default pattern set, dropping
credential-shaped keys at any depth. New `recursiveCredentialScan`
option (default `true`) lets adopters opt out only when they've
validated surviving shapes themselves. Two tests pin the behavior:
nested credentials inside allowlisted top-level keys are dropped;
top-level credentials are dropped when no allowlist is set.

**Scan starts from depth 1 when an allowlist is set, depth 0 when
not.** When the adopter explicitly allowlists `scope3_api_key` at the
top level, the scan respects that affirmation — wouldn't second-
guess by name. When no allowlist runs, the scan walks every depth
including top-level.

**`__type` phantom in codegen** (code-reviewer #1). Codegen now emits
`{ fields: [...], __type: null as unknown as RequestType }` per entry,
imported from `../types` (the index that aggregates core.generated +
tools.generated). `pickWireSpecFields<K>` return type widened from
`WireSafe<Record<string, unknown>>` to
`WireSafe<(typeof WIRE_SPEC_FIELDS)[K]['__type']>` — adopters now get
strong per-schema narrowing instead of generic Record.

**Runtime-frozen arrays** (security L1). Codegen wraps each `fields`
array in `Object.freeze` and the outer object too. Test asserts
behavioral effect (length unchanged after push attempt) rather than
mode-dependent throw.

**`inject` JSDoc warning** (security L2). Explicit "values here MUST
be storefront-derived, never read from the incoming buyer request."

**Migration footgun warning** (security #8). CTX-METADATA-SAFETY.md
now spells out: `pickWireSpecFields` ALONE doesn't close round-2/3
vectors. Adopters MUST chain with `scrubExtensions`. Diff-atomic
migration recipe included.

**`scrubExtensions` constraint widened** to `T extends object`. Was
`T extends Record<string, unknown>` which fights `WireSafe<T>` brand.

**SI naming fix in codegen.** `si-*` filenames now correctly emit
`SI*` PascalCase (uppercase SI prefix matches `json-schema-to-
typescript`'s acronym handling).

20/20 wire-safe tests pass (was 17, +3 new), 1287/1287 server suite,
format / typecheck clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Lock down credential-bearing surfaces in adapter args (security hardening)

1 participant