Repository navigation
[KB-04] Add scoped HTTP and MCP knowledge authoring - #5
Conversation
|
OpenRouter review posted ( |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
OpenRouter pull-request review
Verdict: issues
Scope: full-pr (full-pr)
Mode: initial
Commit: ca69a50874100febb1081cdb5d843187be1e8486
Judge: openai/gpt-5.6-luna (repaired(canonical+1): source coverage preserved before publication cap)
Cost: $0.7035 (lanes $0.6996 + judge $0.0039)
Lanes
meta/muse-spark-1.2: ok (5 finding(s), 77.8s, 723348+7450 tokens (345623 cached), 6 tool round(s), via Meta, $0.56)z-ai/glm-5.3-flash: ok (3 finding(s), 317.0s, 2934671+58775 tokens (2713792 cached), 27 tool round(s), via Together, $0.14)
Warning
z-ai/glm-5.3-flash: coverage claims 1 finding(s) in '.github/workflows/ci.yml' but 0 were reported
Findings
🔴 Issue 1 — IPv6 loopback bypass check compares wrong hostname form
packages/mcp/src/transport-common.ts:133 · bug · identified by meta/muse-spark-1.2
Concrete failure: a host that sets allowInsecureLoopback:true and configures http://[::1]/mcp will be rejected as invalid configuration, while the documented loopback proof is supposed to allow it.
configuredUrl tests url.hostname against "[::1]", but WHATWG URL.hostname for http://[::1]/ is "::1" without brackets (url.host keeps the brackets). The loopback allowlist therefore never matches IPv6, so validateKnowledgeAgentTransportOptions throws TypeError for a legitimate synthetic http://[::1]:port resource even with allowInsecureLoopback:true.
Evidence: packages/mcp/src/transport-common.ts loopback check around const loopback = ["localhost","127.0.0.1","[::1]"].includes(url.hostname).
Checked sibling URL handling and examples/agent/README.md which explicitly says the proof binds to 127.0.0.1, but the API docs advertise generic loopback support; the IPv6 path is therefore broken even though no existing test exercises it (tests use https://knowledge.example).
🟠 Issue 2 — Missing Host header bypasses Host authority check
packages/mcp/src/transport-common.ts:210 · risk · identified by meta/muse-spark-1.2
Concrete failure: a request with no Host header (allowed by Fetch runtimes) passes validHost without validation and then relies only on url.href exact match. A reverse proxy or worker that routes on Host could forward an attacker-controlled Host to a different backend while url.href still equals the configured endpointUrl string constructed from the request URL, allowing Host-rebinding confusion.
validHost returns true immediately when request.headers.get("Host")===null with comment "Fetch runtimes may omit Host: the absolute request URL remains mandatory." The subsequent authorizeKnowledgeAgentRequest still checks url.href !== configuration.endpointUrl, but the intended defense-in-depth of rejecting mismatched Host/authority is skipped for headerless requests.
Checked call sites in transport-common.ts and tests in tests/agent-security.test.ts which explicitly craft Host-header attacks but never assert the null-Host path is rejected.
🟠 Issue 3 — MCP adapter rejects every notification except notifications/initialized with a 400 JSON-RPC error, violating JSON-RPC 2.0 and MCP Streamable HTTP rules
packages/mcp/src/mcp.ts:308 · risk · identified by z-ai/glm-5.3-flash
An MCP client that cancels an in-flight tool call (user interrupt, timeout abort) sends a notifications/cancelled POST. This adapter answers it with HTTP 400 and a JSON-RPC error envelope addressed to id: null, although JSON-RPC 2.0 forbids replying to notifications and the MCP Streamable HTTP transport expects notifications to be accepted with 202. The SDK-based clients this PR targets (Codex, Claude Code) send cancellation notifications on abort, so the likely effect is a failed transport send / protocol error on the client instead of a silently accepted cancellation — exactly the unproven client-compatibility area the docs keep open.
Mechanism: packages/mcp/src/mcp.ts validates each body against rpcRequest, whose only notification branch is notifications/initialized (lines 137-142, 183); anything else falls through to the header check, where rpcHeader requires id (lines 129-130), so an id-less notification fails both schemas and reaches return json(protocolError(header.success ? header.data.id : null), 400) (line 308). Unknown request methods (e.g., resources/list) correctly get -32601; the gap is specific to well-formed notifications.
Evidence and gap: the method allowlist and the id-less 400 path are deterministic from the code. I searched the repo for notifications/ and initialized under tests/ and scripts/: only notifications/initialized appears (in mcp.ts), so neither the vitest suites nor the agent:proof fixture exercise any other notification, and the client-side blast radius could not be executed here. The spec violation itself is not in doubt; the severity of the client reaction (hard send failure versus logged warning) is the residual unknown.
🟠 Issue 4 — CI now runs release:check twice per matrix leg and adds network-heavy proof work inside a 30-minute job budget
scripts/agent-protocol-proof.mjs:165 · risk · identified by z-ai/glm-5.3-flash
.github/workflows/ci.yml gained a pnpm run agent:proof step, and that proof itself begins by re-running pnpm run release:check (scripts/agent-protocol-proof.mjs:162-165, "stage 2") — the same check CI already executed as its own step moments earlier. Each of the two matrix legs (Node 22 and 24) therefore builds all four packages via prepack, npm-packs them twice, installs two throwaway npm consumers from the public registry, then clones the pinned Agent Access producer from GitHub, runs a frozen producer pnpm install + build + pack, installs a third consumer with the official SDK, and runs the SDK fixture — all network-dependent, inside the job's timeout-minutes: 30 that also already runs pnpm test (three storage backends), pnpm example, and release:check.
Concrete cost: duplicated multi-minute release-check work on every PR and push, and reduced headroom so a slow npm/GitHub day can push the required gate into the job timeout, producing exactly the "pending/failing gates" state the workflow forbids bypassing. Individual commands are capped at 600 seconds (run()), but the sum is what the 30-minute job budget must absorb.
Evidence: the duplication is verifiable from the two files cited; I could not measure actual CI durations from the checkout, so the timeout risk is an estimate, not an observed failure. A fix can be mechanical: let the proof reuse the already-verified artifacts (or skip its internal release:check when invoked from CI) or raise the job budget deliberately.
🔵 Issue 5 — MCP server version hard-coded separately from package manifest
packages/mcp/src/mcp.ts:318 · nit · identified by meta/muse-spark-1.2
Concrete failure: the MCP adapter advertises version: "0.1.0" directly in createKnowledgeAgentMcp, while packages/mcp/package.json is the source of truth. A synchronized version bump in the next release that updates package.json but not the literal will publish mismatched agent/implementation versions and break client version checks that pin the package version.
Evidence: packages/mcp/src/mcp.ts new Server({ name: "@pegma/knowledge-base-mcp", version: "0.1.0" }, ...) versus packages/mcp/package.json:3 "version": "0.1.0".
No tooling in scripts/release-packages.mjs validates the two stay in sync.
🔵 Issue 6 — TextDecoder ignores BOM under strict UTF-8 contract
packages/mcp/src/transport-common.ts:400 · nit · identified by meta/muse-spark-1.2
Concrete failure: a request body beginning with a UTF-8 BOM (0xEF 0xBB 0xBF) is silently accepted because readKnowledgeAgentJsonRequest decodes with { fatal:true, ignoreBOM:true }. The AGENT_API advertises "strict UTF-8" and the parser is supposed to bound raw bytes before JSON.parse; BOM-prefixed JSON should be rejected as invalid_request but instead canonicalizes to valid JSON, allowing a client to smuggle a BOM that changes downstream hash or signature material.
Evidence: packages/mcp/src/transport-common.ts new TextDecoder("utf-8", { fatal:true, ignoreBOM:true }).
Checked docs/AGENT_API.md bounds section and tests/agent-security.test.ts UTF-8 rejection cases which test invalid bytes 0xC3 0x28 but not BOM.
🔵 Issue 7 — Release integrity double-hash uses hex shasum but registry prefers base64
scripts/release-packages.mjs:95 · nit · identified by meta/muse-spark-1.2
Concrete failure: artifact verification in release:check asserts shasum (hex SHA-1) and integrity (base64 SHA-512) match the tarball, but npm registry metadata has migrated to only publishing integrity; a future npm pack that omits shasum would cause the check to throw on undefined rather than reporting a clear mismatch, breaking CI after the planned four-package publication.
Evidence: scripts/release-packages.mjs validates createHash("sha1") against metadata.shasum and metadata.integrity. packages/mcp/package.json now adds the fourth tarball to that flow.
No blast-radius failure yet, but the check is not future-proof against npm dropping SHA-1.
🔵 Issue 8 — Host-tuned maxDepth/maxNodes/maxArrayLength/maxObjectKeys are not applied at the transport body pre-parse
packages/mcp/src/transport-common.ts:513 · nit · identified by z-ai/glm-5.3-flash
A host that tightens the component ceilings (e.g., createKnowledgeAgentDispatcher({ limits: { maxNodes: 128 } })) still pays the full default-bounded scan and JSON.parse per hostile request before the dispatcher rejects with capacity. readKnowledgeAgentJsonRequest only threads maxRequestBytes (packages/mcp/src/transport-common.ts:513 calls parseKnowledgeAgentJson(text, { maxRequestBytes: maxBytes })), so parseKnowledgeAgentJson re-resolves every other limit to its default (131,072 bytes, depth 12, 1,024 nodes, 32 arrays/keys). Correctness is preserved because the dispatcher snapshots the parsed value again under the configured limits, but the configured bound is enforced later than AGENT_API.md advertises ("The shared JSON parser checks raw UTF-8 bytes, nesting, and parse work before JSON.parse"). Concrete cost: with default maxResponseBytes a request carrying a legal-size 1,024-node graph against a host capped at 128 nodes is fully walked and parsed every time; also, request arrays up to 32 items and objects to 32 keys pass the read stage even when the host configured 4.
Checked: tests/agent-security.test.ts covers default-limit capacity rejections and dispatcher construction with tightened limits, but no test pins that tightened limits bound the transport read stage; I found no code path that forwards dispatcher.limits beyond maxRequestBytes into readKnowledgeAgentJsonRequest.
| configuredUrl(options.resource, allowLoopback); | ||
| configuredUrl(options.protectedResourceMetadataUrl, allowLoopback); | ||
| if ( | ||
| (transport !== "http" && transport !== "mcp") || |
There was a problem hiding this comment.
🔴 IPv6 loopback bypass check compares wrong hostname form (bug)
Concrete failure: a host that sets allowInsecureLoopback:true and configures http://[::1]/mcp will be rejected as invalid configuration, while the documented loopback proof is supposed to allow it.
configuredUrl tests url.hostname against "[::1]", but WHATWG URL.hostname for http://[::1]/ is "::1" without brackets (url.host keeps the brackets). The loopback allowlist therefore never matches IPv6, so validateKnowledgeAgentTransportOptions throws TypeError for a legitimate synthetic http://[::1]:port resource even with allowInsecureLoopback:true.
Evidence: packages/mcp/src/transport-common.ts loopback check around const loopback = ["localhost","127.0.0.1","[::1]"].includes(url.hostname).
Checked sibling URL handling and examples/agent/README.md which explicitly says the proof binds to 127.0.0.1, but the API docs advertise generic loopback support; the IPv6 path is therefore broken even though no existing test exercises it (tests use https://knowledge.example).
There was a problem hiding this comment.
The runtime premise is incorrect: WHATWG URL.hostname returns '[::1]' here, including brackets. I verified new URL('http://[::1]/').hostname on the supported runtime. The existing allowlist is correct; changing it to '::1' would break IPv6. A regression now constructs both IPv6 loopback adapters successfully.
| "Access-Control-Expose-Headers", | ||
| "WWW-Authenticate, Retry-After", | ||
| ); | ||
| } |
There was a problem hiding this comment.
🟠 Missing Host header bypasses Host authority check (risk)
Concrete failure: a request with no Host header (allowed by Fetch runtimes) passes validHost without validation and then relies only on url.href exact match. A reverse proxy or worker that routes on Host could forward an attacker-controlled Host to a different backend while url.href still equals the configured endpointUrl string constructed from the request URL, allowing Host-rebinding confusion.
validHost returns true immediately when request.headers.get("Host")===null with comment "Fetch runtimes may omit Host: the absolute request URL remains mandatory." The subsequent authorizeKnowledgeAgentRequest still checks url.href !== configuration.endpointUrl, but the intended defense-in-depth of rejecting mismatched Host/authority is skipped for headerless requests.
Checked call sites in transport-common.ts and tests in tests/agent-security.test.ts which explicitly craft Host-header attacks but never assert the null-Host path is rejected.
There was a problem hiding this comment.
The canonical absolute Request.url must equal the configured endpoint before authentication, independently of Host. A supplied Host is also validated. Fetch/HTTP2-style requests may legitimately omit a Host header; their absolute URL remains the authority. A proxy that fabricates a trusted URL while discarding the original authority violates the host request-adapter contract, rather than bypassing this guard. Requiring Host would reject legitimate Web Request inputs without fixing that upstream fabrication.
| stage = 2; | ||
| // The repository release checker builds/packs and verifies all four KB | ||
| // inventories and their clean-consumer public entrypoints first. | ||
| run(process.execPath, [pnpm, "run", "release:check"], root, env); |
There was a problem hiding this comment.
🟠 CI now runs release:check twice per matrix leg and adds network-heavy proof work inside a 30-minute job budget (risk)
.github/workflows/ci.yml gained a pnpm run agent:proof step, and that proof itself begins by re-running pnpm run release:check (scripts/agent-protocol-proof.mjs:162-165, "stage 2") — the same check CI already executed as its own step moments earlier. Each of the two matrix legs (Node 22 and 24) therefore builds all four packages via prepack, npm-packs them twice, installs two throwaway npm consumers from the public registry, then clones the pinned Agent Access producer from GitHub, runs a frozen producer pnpm install + build + pack, installs a third consumer with the official SDK, and runs the SDK fixture — all network-dependent, inside the job's timeout-minutes: 30 that also already runs pnpm test (three storage backends), pnpm example, and release:check.
Concrete cost: duplicated multi-minute release-check work on every PR and push, and reduced headroom so a slow npm/GitHub day can push the required gate into the job timeout, producing exactly the "pending/failing gates" state the workflow forbids bypassing. Individual commands are capped at 600 seconds (run()), but the sum is what the 30-minute job budget must absorb.
Evidence: the duplication is verifiable from the two files cited; I could not measure actual CI durations from the checkout, so the timeout risk is an estimate, not an observed failure. A fix can be mechanical: let the proof reuse the already-verified artifacts (or skip its internal release:check when invoked from CI) or raise the job budget deliberately.
There was a problem hiding this comment.
The duplicated artifact gate is intentional: agent:proof is independently runnable and proves its input artifacts before use. Actual current-head CI completed the entire Node22 job in4m21s and Node24 in4m46s (15:40:25→15:44:46/15:45:11), against a30-minute aggregate bound. No timeout or multi-minute artifact-check regression occurred. Native commands and the aggregate job are both bounded; a speculative future network outage does not establish a current defect.
| } catch { | ||
| return reject("invalid_request"); | ||
| } | ||
| if ( |
There was a problem hiding this comment.
🔵 TextDecoder ignores BOM under strict UTF-8 contract (nit)
Concrete failure: a request body beginning with a UTF-8 BOM (0xEF 0xBB 0xBF) is silently accepted because readKnowledgeAgentJsonRequest decodes with { fatal:true, ignoreBOM:true }. The AGENT_API advertises "strict UTF-8" and the parser is supposed to bound raw bytes before JSON.parse; BOM-prefixed JSON should be rejected as invalid_request but instead canonicalizes to valid JSON, allowing a client to smuggle a BOM that changes downstream hash or signature material.
Evidence: packages/mcp/src/transport-common.ts new TextDecoder("utf-8", { fatal:true, ignoreBOM:true }).
Checked docs/AGENT_API.md bounds section and tests/agent-security.test.ts UTF-8 rejection cases which test invalid bytes 0xC3 0x28 but not BOM.
There was a problem hiding this comment.
ignoreBOM:true preserves the BOM in decoded output; it does not strip it. The supported runtime returns first codepoint65279 (U+FEFF), and JSON.parse rejects that string. This was verified directly; new public HTTP and MCP regressions require400 for BOM-prefixed otherwise-valid JSON. No decoder weakening is needed.
|
Round1 triage: valid notification handling (r1-3) and complete pre-JSON.parse structural limits (r1-8) are fixed with focused tests; the artifact consumer now verifies MCP serverInfo against the packed manifest (r1-5), mechanically preventing version drift. r1-1/r1-2/r1-4/r1-6 have evidence-based inline replies. For summary-only r1-7: the current supported npm pack outputs and public npm registry metadata still supply both SHA-1 shasum and SHA-512 integrity (verified against the public Spine0.1.2 metadata); both Node22/24 artifact checks passed. A hypothetical future CLI schema removal is fail-closed and would require a reviewed tooling update. Removing an integrity check now would not fix a present failure. Invalid candidates remain visible for re-verification; fixes will be pushed after local gates. |
|
@codex security review |
|
Copilot's automatic review has not appeared after about35 minutes. An explicit review request was rejected by GitHub422 (reviewer is not a repository collaborator), matching the unavailable request path on the preceding component PR. This unavailable reviewer is recorded under the bounded review workflow. Actual current-head OpenRouter clean/zero-actionable ledger, completed security review, independent verification and every Node22/24/CodeQL/protocol gate remain required; none is waived. |
|
Round1 fixes are pushed in c897626. All32 affected tests pass across the three backends, as do formatting/types, composition, the four-package artifact gate including actual MCP initialization metadata, and the five-tarball authenticated SDK proof. The focused independent recheck is clean. Evidence-based replies for invalid candidates remain visible. Current-head CI and review verification must finish before merge. |
There was a problem hiding this comment.
OpenRouter pull-request review
Verdict: clean
Scope: latest-commit (commit-range)
Mode: verify
Commit: c897626de6c7b2ea574f4154b0bc7a7731ee106e
Judge: openai/gpt-5.6-luna
Cost: $0.2309 (lanes $0.2308 + judge $0.0001)
Lanes
meta/muse-spark-1.2: ok (0 finding(s), 57.0s, 139220+6164 tokens (22867 cached), 4 tool round(s), via Meta, $0.18)z-ai/glm-5.3-flash: ok (0 finding(s), 220.8s, 639349+39829 tokens (458944 cached), 11 tool round(s), via Together, $0.0557)
Round 2 resolution
- 🤝
r1-1disputed — IPv6 loopback bypass check compares wrong hostname form: No code change toconfiguredUrlloopback check ([::1]againsturl.hostname). Fixing agent assertsnew URL('http://[::1]/').hostname === '[::1]'on supported runtime so current allowlist is correct and added regression testaccepts explicit IPv6 loopback configuration for synthetic HTTP and MCP hostsconstructs both adapters. WHATWG spec/MDN saysURL.hostnameforhttp://[::1]/is `::1… - 🤝
r1-2disputed — Missing Host header bypasses Host authority check:validHoststill returns true whenHostheader is null (transport-common.ts:212with comment Fetch runtimes may omit Host). Fixing agent argues canonicalrequest.urlexact match (url.href === endpointUrl) is mandatory before auth and supplied Host is also validated, and requiring Host would reject legitimate Web/HTTP2-style Requests. Prior risk of Host-rebinding via proxy that fabricates … - ✅
r1-3fixed correctly — MCP adapter rejects every notification except notifications/initialized with a 400 JSON-RPC error, violating JSON-RPC 2.0 and MCP Streamable HTTP rules: Verified fixed.mcp.tsnow definesrpcNotificationcoveringnotifications/initialized,notifications/cancelled(withcancelledParams) and any unknown notification (return true), unioned intorpcRequest. Notifications are routed viaWebStandardStreamableHTTPServerTransportwhich returns 202, and handler returns 202 without dispatching tools. New test `authenticates and admits valid … - 🤝
r1-4disputed — CI now runs release:check twice per matrix leg and adds network-heavy proof work inside a 30-minute job budget: No change to.github/workflows/ci.yml(still haspnpm run release:checkthenpnpm run agent:proofwhich internally re-runsrelease:checkstage 2) andscripts/agent-protocol-proof.mjs:162-165still duplicates packing + frozen install + GitHub clone. Fixing agent notes duplication is intentional for independently-runnable proof (proves its own input artifacts) and cites measured CI times 4… - 4 nit finding(s) from earlier rounds retired (severity floor for follow-up rounds is
risk). - Open findings after this round: 0 (0 bug-severity).
No structured findings from the successful lane(s).
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
Local agents can use one versioned authoring contract over HTTP or MCP to get/create/update drafts, read validation requirements, and submit bound test evidence. The optional @pegma/knowledge-base-mcp package invokes the existing application; it never issues credentials or exposes publication, review, collection/evidence/provenance reads, staff, or admin commands.
Host authentication revalidates the bearer and current authority on every request. The boundary intersects the three consented scopes with current permissions, strips roles/entitlements, requires host admission control, validates endpoint/Host/Origin, and bounds input graphs, streamed bodies, complete responses, and mutation acknowledgements. MCP uses a fresh stateless SDK server and the supplied Worker-compatible validator. The three base packages retain their SDK/HTTP independence.
Validation:
This is the KB-04 source exit in the approved Knowledge/AI plan. All four KB packages and Agent Access remain unpublished. The pinned producer checkout is used only in a temporary test consumer, never as a production dependency. Actual site logins, Codex/Claude Code/Grok Bot desktop/T3 Code acceptance, publication, and host activation remain separately gated.