> For the complete documentation index, see [llms.txt](https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/.spec_system/archive/sessions/phase38-session05-runtime-bridge-hardening/spec.md).

# Session Specification

**Session ID**: `phase38-session05-runtime-bridge-hardening` **Phase**: 38 - Claude OS v2.8.1 Semantic Port **Status**: Not Started **Created**: 2026-06-29

***

## 1. Session Overview

This session hardens the local request-time bridge layer for Hermes, Knowledge Graph Graphify, Dream run control, and Vite local control-plane endpoints. Sessions 01 through 04 are complete, so graph/yolo chat semantics, shared platform helpers, Dream health metadata, and Dream scheduling are already in place; the next executable gap is making the live endpoint paths use those helpers and reject DNS-rebinding style requests.

The upstream Claude OS v2.8.1 change implemented this mostly inside `vite.config.ts`. AI OS has diverged into shared modules, so this plan ports the behavior semantically: binary and venv path resolution belongs in `scripts/lib/platform.ts` and `scripts/lib/tool-detection.ts`, bridge behavior belongs in the bridge modules, and Host-header validation belongs in a testable local guard that Vite uses for every privileged local endpoint.

The delivery bar is endpoint behavior, not unused guard code. Real route handlers must still reject non-loopback requests, bad tokens, disabled admin mode, malformed bodies, and unsafe paths while also rejecting hostile Host headers such as `localhost.evil.com` even when the socket remote address is loopback.

***

## 2. Objectives

1. Reuse shared platform and CLI resolution helpers for request-time Hermes and Graphify command discovery across Windows and POSIX installs.
2. Support Windows venv `Scripts`, `%APPDATA%\npm`, `%LOCALAPPDATA%\Programs`, PATHEXT expansion, `.cmd` wrappers, and POSIX fallback candidates in live bridge paths.
3. Add exact local Host-header validation to the Vite local control-plane guard without weakening existing loopback, token, admin, body-size, or path gates.
4. Add focused tests that exercise Hermes chat, Graphify status/ingest, Dream run guard behavior, and hostile Host rejection through the actual modules.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase38-session01-tier-0-parity-fixes` - Provides the Hermes graph/yolo chat option split that this session must preserve.
* [x] `phase38-session02-platform-foundation` - Provides shared platform, app-data, executable-name, venv, and CLI directory helpers.
* [x] `phase38-session03-aggregate-and-dream-health` - Provides Dream health and aggregate evidence that the Dream run endpoint must preserve.
* [x] `phase38-session04-dream-scheduling-and-setup` - Provides Windows-aware Dream runner ownership and setup context that must not be regressed.

### Required Tools Or Knowledge

* Bun 1.3.14, Vitest, TypeScript, and the existing bridge test harnesses.
* Upstream reference: `/home/aiwithapex/projects/claudeos/claude-os-v2.8.1/vite.config.ts`.
* Current AI OS targets: `vite.config.ts`, `scripts/lib/platform.ts`, `scripts/lib/tool-detection.ts`, `scripts/lib/hermes-admin-bridge.ts`, `scripts/lib/hermes-dev-bridge.ts`, and `scripts/lib/knowledge-graph-admin-bridge.ts`.

### Environment Requirements

* Repository root is `/home/aiwithapex/projects/aios`.
* Native Windows verification can be represented by injected platform/env harness tests when a Windows host is unavailable.
* No secrets, bearer headers, token-shaped strings, raw bridge stderr, or private local paths may be emitted into browser-visible responses.

***

## 4. Scope

### In Scope (MVP)

* Hermes chat resolves the source checkout Python entry point through platform-aware venv helpers before falling back to configured or PATH-visible `hermes` wrappers.
* Graphify admin status and ingest resolve `GRAPHIFY_BIN`, `.notebooklm-venv`, PATH/PATHEXT, app-data npm, local programs, and POSIX candidates through shared CLI resolution.
* Vite local endpoints reject Host headers whose exact hostname is not `localhost`, `127.0.0.1`, `::1`, or `[::1]`, while still allowing valid loopback requests and internal requests without Host.
* Existing loopback-only privileged endpoint checks remain active for Hermes read status, Hermes chat, Knowledge Graph graphify status/ingest, Dream run, token exchange, refresh, and local run-control paths.
* Tests cover Windows venv `Scripts`, `%APPDATA%\npm\*.cmd`, valid loopback hosts, loopback socket plus hostile Host rejection, and existing endpoint regressions.

### Out Of Scope (Deferred)

* Voice endpoint exposure - Reason: owned by Session 08 and depends on this guard work.
* Hermes chat product redesign - Reason: this session owns request-time resolution and guard behavior only.
* Public hosted bridge behavior - Reason: these are local dev/control-plane endpoints and remain unavailable in public hosted mode.
* Aggregate-only app detection changes - Reason: already owned by Session 03.
* Broad documentation and license updates - Reason: owned by Session 06.

***

## 5. Technical Approach

### Architecture

Add or extend a small testable local control-plane guard under `scripts/lib/` and make `vite.config.ts` use it from the existing `isLoopback` function. This keeps every caller that already depends on `isLoopback` covered, including registered bridge modules and inline run-control endpoints. The guard should parse the socket remote address and Host header independently, then require an exact local host match rather than prefix matching.

For runtime command resolution, keep the Phase 38 platform foundation as the source of truth. Hermes admin chat should preserve the source-entrypoint preference, but build the Python candidate with `venvBin` so Windows resolves `Scripts/python.exe` and POSIX resolves `bin/python`. Wrapper fallback should go through shared CLI detection so configured `HERMES_BIN`, PATH, `.cmd` wrappers, app-data npm, local programs, and POSIX fallback directories are handled consistently.

Graphify admin should stop maintaining a separate PATH splitter and fixed candidate list that only understands POSIX paths. It should use the same shared CLI resolver for `GRAPHIFY_BIN`, `.notebooklm-venv`, and PATH candidates while preserving the existing `configured`, `path`, and `missing` status semantics and all ingest safety checks.

### Design Patterns

* Shared guard helper: Host validation stays pure and testable while Vite owns endpoint registration.
* Shared runtime resolver: CLI path behavior lives in script helpers rather than being copied into each bridge.
* Preserve bridge contracts: Update command discovery without changing JSON result shapes, SSE event shapes, or existing error codes except where Host rejection needs a clear local-control-plane response.
* Defense in depth: Host validation is added alongside socket loopback and token checks, not as a replacement for them.

***

## 6. Deliverables

### Files To Create

| File                                                                                    | Purpose                                                                                             | Est. Lines |
| --------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | ---------- |
| `scripts/lib/local-control-plane-guard.ts`                                              | Pure helpers for loopback socket and exact Host-header validation used by Vite local endpoints.     | \~120      |
| `scripts/lib/__tests__/local-control-plane-guard.test.ts`                               | Cover valid local hosts, IPv6 bracket handling, absent Host, remote sockets, and hostile hostnames. | \~140      |
| `.spec_system/specs/phase38-session05-runtime-bridge-hardening/implementation-notes.md` | Record implementation evidence, commands, and Host/CLI verification results during implementation.  | \~160      |

### Files To Modify

| File                                                         | Changes                                                                                                                    | Est. Lines |
| ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `scripts/lib/platform.ts`                                    | Extend or reuse platform helpers for runtime venv and CLI candidate construction if gaps appear during bridge wiring.      | \~30       |
| `scripts/lib/tool-detection.ts`                              | Add runtime resolver affordances for configured candidates, source labels, and injected platform/env tests if needed.      | \~80       |
| `scripts/lib/hermes-admin-bridge.ts`                         | Resolve Hermes source Python and wrapper binaries through shared platform/tool helpers while preserving SSE chat behavior. | \~80       |
| `scripts/lib/knowledge-graph-admin-bridge.ts`                | Resolve Graphify commands through shared CLI detection while preserving status, ingest, and error semantics.               | \~90       |
| `vite.config.ts`                                             | Route local endpoint loopback checks through exact Host-header validation without weakening token or admin gates.          | \~60       |
| `scripts/lib/__tests__/platform.test.ts`                     | Preserve Windows app-data, local-programs, venv `Scripts`, and PATHEXT expectations used by runtime bridge resolution.     | \~40       |
| `scripts/lib/__tests__/tool-detection.test.ts`               | Cover configured runtime candidates and Windows `.cmd` fallback resolution.                                                | \~80       |
| `scripts/lib/__tests__/hermes-admin-bridge.test.ts`          | Cover Windows source venv Python, `%APPDATA%\npm\hermes.cmd`, configured wrappers, graph/yolo args, and failure paths.     | \~120      |
| `scripts/lib/__tests__/knowledge-graph-admin-bridge.test.ts` | Cover Graphify configured/path/missing states, Windows `.cmd` candidates, status, ingest, and failed command redaction.    | \~120      |

***

## 7. Success Criteria

### Functional Requirements

* [ ] `/__hermes_chat` resolves a valid Hermes source Python entry point on POSIX and Windows venv layouts and falls back to configured/PATH wrapper binaries without shell interpolation.
* [ ] Knowledge Graph Graphify admin status and ingest find configured, PATH-visible, app-data npm, local-programs, `.cmd`, and venv candidates through shared CLI resolution.
* [ ] Local Vite privileged endpoints reject loopback requests with hostile Host headers such as `localhost.evil.com`, `127.0.0.1.evil.com`, and non-local hostnames.
* [ ] Valid loopback requests with `localhost`, `127.0.0.1`, `[::1]`, `::1`, optional ports, or no Host header still pass to the existing endpoint token/admin/method checks.
* [ ] Existing Hermes chat, Knowledge Graph graphify, Dream run, token, and refresh endpoint regressions continue to pass.

### Testing Requirements

* [ ] Unit tests written and passing for local Host guard parsing and runtime CLI resolution helpers.
* [ ] Bridge tests written and passing for Hermes and Graphify Windows/POSIX command candidates and failure-path handling.
* [ ] Targeted tests run with `bun run test -- scripts/lib/__tests__/local-control-plane-guard.test.ts scripts/lib/__tests__/platform.test.ts scripts/lib/__tests__/tool-detection.test.ts`.
* [ ] Bridge regressions run with `bun run test -- scripts/lib/__tests__/hermes-admin-bridge.test.ts scripts/lib/__tests__/hermes-dev-bridge.test.ts scripts/lib/__tests__/knowledge-graph-admin-bridge.test.ts`.
* [ ] Type checks run with `bun run typecheck:scripts` and `bun run typecheck`.

### Non-Functional Requirements

* [ ] Host validation uses exact hostname matching and does not accept prefix, suffix, encoded, credentialed, or control-character host tricks.
* [ ] Command resolution does not execute a shell and keeps prompt, path, and URL values in argv or validated fields only.
* [ ] Command failures and missing-tool responses remain actionable without leaking tokens, raw private paths, or raw stderr.
* [ ] No new runtime dependency or lockfile change is introduced.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] No product-facing UI route changes.

***

## 8. Implementation Notes

### Working Assumptions

* A pure guard helper plus Vite wiring is the correct way to test Host-header behavior: importing `vite.config.ts` directly has startup side effects, while using the helper from the existing Vite `isLoopback` function proves the same predicate is applied to registered bridge and run-control endpoints.
* Faithful injected Windows platform/env tests are acceptable for command candidate behavior when a native Windows host is unavailable: Phase 38 explicitly allows faithful harness proof for Windows-facing work, and the command-resolution branch is deterministic from platform, env, and file existence.
* `scripts/lib/hermes-dev-bridge.ts` does not need new CLI resolution for Hermes status in this session: current status reads bounded local Hermes files, while the endpoint itself receives Host hardening from the shared Vite guard.

### Conflict Resolutions

* Upstream keeps `venvBin`, `cliBinCandidates`, `resolveCliBin`, Graphify status, Hermes status, Hermes chat, and Host-header checks in one `vite.config.ts`; AI OS keeps platform helpers, bridge modules, and Vite registration separate. The AI OS module boundaries win because they are the current codebase architecture and are named by the Phase 38 stub.
* The Session 05 stub asks for Windows candidate support, but Session 02 already created most platform primitives. This plan reuses and extends those helpers only where live bridge wiring exposes a real gap.
* Upstream Graphify ingest inlines command lookup and graph handling in Vite; AI OS already owns Graphify status and ingest in `scripts/lib/knowledge-graph-admin-bridge.ts`, so only runtime resolution is ported there.

### Key Considerations

* Session 08 voice launch behavior depends on this Host-header hardening.
* Current security posture has no open findings; this session should preserve that by keeping loopback, token, admin, body-size, path-safety, and schema gates intact.
* No public hosted bridge behavior should be introduced.

### Potential Challenges

* Host parsing can accidentally accept `localhost.evil.com`: use URL/authority style parsing carefully and assert exact hostname matches in tests.
* Windows path behavior is easy to regress on POSIX hosts: inject platform, env, and candidate directories in tests rather than relying on the runner OS.
* Hermes source-entrypoint fallback can change SSE behavior if args move: preserve the existing `chat -Q -q` argv order and graph/yolo flags.

### Relevant Considerations

* \[P00] **Stack conventions**: Use Bun, Vite 8, TypeScript, Vitest, and the existing script/module structure.
* \[P04] **Hermes bridge guardrails must stay intact**: Preserve loopback plus token checks and disabled-by-default admin mode.
* \[P21] **Claude OAuth material stays script-only**: Do not expose token-shaped strings, bearer headers, or credential-shaped values in responses or logs.
* \[P26] **Knowledge Graph contract alignment**: Keep Graphify bridge status and ingest result contracts stable for Knowledge Graph UI consumers.
* \[Security Recommendation 9] Preserve loopback, token, admin, body-size, path, and schema gates for Hermes, Knowledge Graph, scheduler, and run-control bridges.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* DNS-rebinding style Host headers reach privileged local endpoints despite loopback sockets.
* Windows Hermes or Graphify installs look unavailable because live bridge code does not use the shared platform helper paths.
* A command failure leaks private paths, token-shaped strings, or raw stderr into browser-visible responses.

***

## 9. Testing Strategy

### Unit Tests

* Add `scripts/lib/__tests__/local-control-plane-guard.test.ts` for loopback remote addresses, valid local Host forms, optional ports, absent Host, IPv6 brackets, malformed headers, control characters, and hostile hostnames.
* Extend `scripts/lib/__tests__/tool-detection.test.ts` and `scripts/lib/__tests__/platform.test.ts` for configured candidates, Windows `.cmd` resolution, app-data npm, local programs, and venv `Scripts`.

### Integration Tests

* Extend `scripts/lib/__tests__/hermes-admin-bridge.test.ts` for Hermes source venv resolution, wrapper fallback, graph/yolo arg preservation, missing binary errors, spawn failures, and sanitized nonzero exits.
* Extend `scripts/lib/__tests__/knowledge-graph-admin-bridge.test.ts` for Graphify configured/path/missing status, Windows candidates, ingest command selection, command failure mapping, and private-path redaction.
* Rerun `scripts/lib/__tests__/hermes-dev-bridge.test.ts` to prove read-only Hermes status contracts remain stable.

### Runtime Verification

* Run targeted Vitest suites for guard, platform/tool detection, Hermes admin, Hermes dev, and Knowledge Graph admin bridge behavior.
* Run `bun run typecheck:scripts` and `bun run typecheck`.
* Record whether native Windows verification was unavailable and what faithful harness cases covered.

### Edge Cases

* Host headers with ports, IPv6 brackets, upper-case local hostnames, `localhost.evil.com`, `127.0.0.1.evil.com`, credentials, whitespace, and control characters.
* Hermes installed as source checkout venv, configured `HERMES_BIN`, PATH wrapper, app-data npm `.cmd`, and missing command.
* Graphify installed as configured `GRAPHIFY_BIN`, `.notebooklm-venv`, PATH executable, app-data npm `.cmd`, and missing command.
* Non-loopback sockets, invalid tokens, disabled admin mode, unsupported methods, oversized bodies, failed command execution, and malformed graph output.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase38-session01-tier-0-parity-fixes`, `phase38-session02-platform-foundation`, `phase38-session03-aggregate-and-dream-health`, `phase38-session04-dream-scheduling-and-setup`.
* Depended by: `phase38-session06-policy-docs-and-catalogs`, `phase38-session08-voice-broker`, `phase38-session09-intelligence-portal`, `phase38-session10-hunk-reconciliation-and-release-gate`.

***

## Next Steps

Run the `implement` workflow step to begin implementation.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/.spec_system/archive/sessions/phase38-session05-runtime-bridge-hardening/spec.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
