Repository navigation
feat: 5.2.2 client integration ergonomics - #641
Merged
Merged
Conversation
Five additive changes unblocking external client adoption after the 5.2.1 spec-compliance rollup. - match() helper on TaskResult (src/lib/core/match.ts): exhaustive, compile-time-checked discriminated-union dispatcher. Eliminates manual `if (result.status === 'completed')` narrowing at response sites. Optional `_` catchall makes handlers optional. - createAdcpServer.signedRequests auto-wires the RFC 9421 verifier when the seller declares the `signed-requests` specialism. Startup-fails when one is declared without the other — closes the footgun where claiming the specialism didn't enforce it. - docs/guides/idempotency-crash-recovery.md: worked buyer-side recipe stitching IdempotencyConflictError + IdempotencyExpiredError + natural-key lookup + metadata.replayed into an end-to-end recovery flow. Cross-linked from README, llms.txt, and the seller SKILL. - skills/build-seller-agent/SKILL.md governance extension: GDPR Art 22 / EU AI Act Annex III worked example — plan.human_review_required threaded through createMediaBuy, buildHumanOverride on approval, decision table, regulated-category constants. - Webhook HMAC-SHA256 deprecated: one-time console.warn on first use (suppress with ADCP_SUPPRESS_HMAC_WARNING=1), @deprecated JSDoc on WebhookAuthentication.hmac_sha256, removal target @adcp/client 6.0.0. Migration guide section added. Test suite: 4277 pass, 1 pre-existing flake (task-executor timing, unrelated), 12 skipped. New tests: match (6), auto-signed-requests (10), webhook-hmac-deprecation (4) — all green. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Addresses review findings on PR #641 from code-reviewer, security-reviewer, dx-expert, and ad-tech-protocol-expert. Also fixes a production resource leak discovered by new test coverage. Blocking fixes: - Rewrite GDPR governance worked example in skills/build-seller-agent/SKILL.md to compile against real handler types (taskToolResponse for submitted path, state-store for persistence, guarded ctx.account access, separate approval function taking AdcpStateStore rather than stale ctx reference). - Fix resource leak on 401 path: buildSignedRequestsPreTransport now races the next-callback against the response's 'finish'/'close' events so the verifier's terminal 401 (which doesn't call next) resolves the wrapper promise. Without this every unsigned mutating request hung server-side and agentServer.close() never fired — slow resource exhaustion under signing-attack floods. Protocol alignment: - required_for default now derives from capabilities.request_signing.required_for (fallback chain: explicit signedRequests.required_for → capability → MUTATING_TASKS). Prevents SDK enforcing beyond what the seller advertises. - Specialism guard now throws when signed-requests is claimed but capabilities.request_signing.supported !== true (was a silent log; storyboard would skip the conformance run). DX: - Add TaskResult.match() fluent method via attachMatch() installer at public exit points (TaskExecutor, SingleAgentClient). Method and free function both exported; method form is discoverable via autocomplete. Non-enumerable property to keep JSON.stringify / spread clean. - Add match() and signedRequests auto-wire sections to docs/llms.txt so LLMs writing seller code find both via the primary doc. HMAC language softening (spec still supports HMAC as legacy fallback): - Warning message, migration doc, @deprecated tag, and changeset all reframe as SDK-flagged deprecation rather than hard-committing to 6.0.0 removal. SDK keeps supporting HMAC; guidance is to migrate when counterparties ready. Consistency + polish: - Error logging in create-adcp-server.ts and serve.ts narrowed to name+code (instead of full err object) to avoid JWKS URLs leaking into shared log aggregators. - Cookbook line 104: removed redundant getOrCreateKey call; carry the rotated/persisted key forward in a single variable. - 5 new signed-requests tests (non-mutating pass, required_for honors list, agentServer close on 401, WWW-Authenticate shape, replay-scope via auto-wire). Test suite: 4238 pass, 0 fail, 12 skipped. New production-bug regression test (401 close-spy) now passes with the hang-fix above. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… sync Addresses round-2 expert review of PR #641: - SECURITY: Fix signature bypass on client-disconnect race. The previous fix raced `res.once('finish')` and `res.once('close')` against the verifier's next-callback, but on 'close' (client aborted mid-JWKS-fetch) `handled` stayed false — serve.ts fell through to MCP dispatch and executed the tool handler WITHOUT a verified signature. Now tracks `verifierCompleted` and sets `handled=true` when close fires before the verifier resolves, so an attacker dropping TCP mid-flight cannot trigger side effects on unsigned requests. Regression test added. - Guard `match()` dispatch against prototype pollution: use `Object.prototype.hasOwnProperty.call(handlers, result.status)` before lookup so a hostile `result.status === '__proto__'` resolves to the `_` catchall instead of calling `Object.prototype` as a handler. - Fix docs/llms.txt match() example field accessors: `r.submitted?.taskId` / `r.metadata.taskId` / `r.deferred?.token` / `r.metadata.inputRequest?` — previous example used `r.task_id` which doesn't exist on any TaskResult variant. Also documents the `!` (non-null assertion) for TS users since `.match` is declared optional. - Schema sync: upstream AdCP added `governance-aware-seller` specialism. Ran `npm run sync-schemas && npm run generate-types` — regenerated core.generated.ts, tools.generated.ts, schemas.generated.ts. Test suite: 4302 pass, 0 fail, 12 skipped. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
docs/llms.txt is generated by scripts/generate-agent-docs.ts; direct edits get clobbered on regen. Moved the match() fluent dispatcher example and the crash-recovery cookbook cross-link into the generator template so they survive `npm run generate-agent-docs` and pass the ci:docs-check step. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
#641 - Alert #41 (js/prototype-pollution-utility, medium): GovernanceMiddleware setAtPath() already blocked __proto__/constructor/prototype via FORBIDDEN_PATH_SEGMENTS set, but CodeQL's pattern matcher only recognizes inline equality checks. Added explicit `part === '__proto__' || part === 'constructor' || part === 'prototype'` inline guard, plus hasOwnProperty traversal check so a malicious prototype-chained value can't be followed mid-path. Belt-and-suspenders. - Alerts #28 and #29 (js/clear-text-logging, high): manual test script .catch() handlers logged the full error object, which CodeQL traced back to OAuth metadata on auth failures. Narrowed to error.name and error.message; full stack restored via DEBUG=1. Test suite: 4288 pass, 0 fail, 12 skipped. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ocks CodeQL flagged 'useless conditional' in the verifier/preTransport error handlers. The err variable is already guaranteed truthy inside the guarded branch, so err && (err as Error).name collapses to just (err as Error).name. Both sites in src/lib/server/create-adcp-server.ts (line 1228) and src/lib/server/serve.ts (line 277) cleaned up. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…iewer followups Addresses final-pass reviewer feedback on PR #641: - ADCP_SIGNED_REQUESTS_STATE symbol + AdcpSignedRequestsState type on the returned McpServer. Carries {autoWired, specialismClaimed, capabilitySupported, mismatch} so operator boot diagnostics and integration tests can assert the wiring without parsing log output. Closes the claim-without-config asymmetry concern — the state is structured and testable; the logger.error still fires for the legacy manual-wiring path. - createWebhookEmitter({ suppressLegacyWarnings: true }) — programmatic equivalent of ADCP_SUPPRESS_HMAC_WARNING=1 for libraries embedded in agents where env vars are awkward. Threaded through deliverOnce → buildHeaders → maybeWarnHmacDeprecation. - attachMatch JSDoc: explicit note that shallow clones ({...result}) don't carry the non-enumerable method — use the free function or attachMatch() on clones. - Migration doc: HMAC timing window ("post-2026 H2 when buyer 9421 adoption telemetry stabilizes") + two suppression paths documented side-by-side (env var vs programmatic). New tests in test/server-auto-signed-requests.test.js: - exposes auto-wire state via ADCP_SIGNED_REQUESTS_STATE symbol - flags claim_without_config in state on legacy manual-wiring path - asserts specific error messages for each misconfig pattern (config + no claim; claim + supported:false; claim + request_signing omitted) - accepts non-tools/call JSON-RPC body (notifications/initialized) without triggering 401 — verifies operation=undefined falls through - populates VerifyResult.agent_url when agentUrlForKeyid returns a URL (direct unit test on verifyRequestSignature) Test suite: 4301 pass, 0 fail, 12 skipped. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…bcommand alias Addresses final reviewer feedback on PR #641: 1. Audience-binding caveat — auth.ts JSDoc now calls out that custom authenticate callbacks (not using verifyBearer) MUST validate aud themselves. Same-tenant tokens are replayable against any agent sharing the tenant without per-resource isolation. verifyBearer's audience is already required and strictly validated; this just documents the custom-auth footgun. 2. Multi-host caveat on serve().publicUrl — JSDoc expanded to name the exact failure mode: one Node process fronting multiple hostnames silently advertises the wrong resource to all but one. Run one serve() per host until a host-aware helper ships. 3. `adcp diagnose oauth <alias>` subcommand alias for `adcp diagnose-auth`. Canonical form stays hyphenated; the `<noun> <verb>` alias matches what some docs expect. Usage line updated. All four requested probe checks (wire trace, token claims pre/post refresh, well-known cross-wiring detection, WWW-Authenticate check) are already implemented by runAuthDiagnosis — H1 specifically is the "Resource URL mismatch between well-known and agent host" hypothesis that catches the cross-wiring case. PR #562 body updated separately via gh pr edit to close the "401 after successful authentication" known-limitation note — fully diagnosed as server-side (no verifier wired + well-known cross-wiring); client-side fix is complete. Test suite: 4305 pass, 0 fail, 12 skipped. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
# Conflicts: # src/lib/types/core.generated.ts # src/lib/types/schemas.generated.ts
3 of 6 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Five additive changes unblocking external client adoption after the 5.2.1 spec-compliance rollup:
match()helper onTaskResult(src/lib/core/match.ts) — exhaustive, compile-time-checked discriminated-union dispatcher. Eliminates manualif (result.status === ...)narrowing. Optional_catchall. Minor bump.createAdcpServer.signedRequestsauto-wires the RFC 9421 verifier when the seller declares thesigned-requestsspecialism. Startup-fails when one is declared without the other — closes the footgun where claiming the specialism didn't enforce it. Minor bump.docs/guides/idempotency-crash-recovery.md— worked buyer-side recipe:IdempotencyConflictError+IdempotencyExpiredError+ natural-key lookup +metadata.replayedside-effect gate + Postgres schema. Cross-linked from README,docs/llms.txt, andskills/build-seller-agent/SKILL.md. Patch bump.skills/build-seller-agent/SKILL.md—plan.human_review_requiredthreaded throughcreateMediaBuy,buildHumanOverrideon approval, decision table, regulated-category constants (REGULATED_HUMAN_REVIEW_CATEGORIES,ANNEX_III_POLICY_IDS). Patch bump.console.warnon first use (suppress withADCP_SUPPRESS_HMAC_WARNING=1),@deprecatedJSDoc onWebhookAuthentication.hmac_sha256, removal target@adcp/client6.0.0. Migration-doc section added with anchor the warning references. Patch bump.Five new changesets under
.changeset/.Rationale
These are the non-blocking ergonomic follow-ups from the pre-merge review thread. 5.2.1 closed the spec-compliance gaps that were blocking client adoption; 5.2.2 closes the integration-time footguns clients will hit in their first week: manual discriminated-union narrowing, manually wiring the verifier when they claim the specialism, not knowing what to do on idempotency crash recovery, not having a template for regulated governance, and not knowing when HMAC goes away.
Test plan
npm run build— clean.npm test— 4277 pass, 1 pre-existing flake (test/lib/task-executor-mocking-strategy.test.js:329— timing-sensitive, unchanged since 2024), 12 skipped.test/lib/match.test.js(6/6),test/server-auto-signed-requests.test.js(10/10),test/lib/webhook-hmac-deprecation.test.js(4/4).test/lib/webhook-emitter.test.jsHMAC tests still pass (silenced the new warning in the describe block so CI isn't spammed).Changeset Checkpasses (five new changesets included).import { match } from '@adcp/client'compiles and narrows correctly.signed-requestswithoutsignedRequestsconfig fails at startup with a clear error.🤖 Generated with Claude Code