Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion codewiki/src/be/qa/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,20 @@
import json
import logging
import os
import re
import socket
import threading
from collections.abc import Iterable
from urllib.parse import urlparse

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse, JSONResponse, Response, StreamingResponse
from fastapi.responses import (
FileResponse,
HTMLResponse,
JSONResponse,
Response,
StreamingResponse,
)
from pydantic import BaseModel, Field

from codewiki import __version__
Expand All @@ -34,6 +41,7 @@

# Never served: the dependency graph / caches under temp/ and dotfiles.
_HIDDEN_PREFIXES = ("temp/", ".")
SERVE_MARKER = '<meta name="codewiki-serve" content="1">'


class AskRequest(BaseModel):
Expand Down Expand Up @@ -241,6 +249,19 @@ def static(path: str):
full = os.path.realpath(os.path.join(docs_dir, rel))
if not full.startswith(os.path.realpath(docs_dir) + os.sep) or not os.path.isfile(full):
raise HTTPException(404)
if full.endswith(".html"):
# Tell the page it is served by `codewiki serve`, so its chat uses this origin.
# Elsewhere (GitHub Pages) probing the own origin's /api/health only 404s.
with open(full, encoding="utf-8") as f:
html = f.read()
html = re.sub(
r"<head(?:\s[^>]*)?>",
lambda m: m.group(0) + SERVE_MARKER,
html,
count=1,
flags=re.I,
)
return HTMLResponse(html)
return FileResponse(full)

return app
Expand Down
5 changes: 3 additions & 2 deletions codewiki/templates/github_pages/viewer_template.html
Original file line number Diff line number Diff line change
Expand Up @@ -3493,8 +3493,9 @@ <h4>Generation Info</h4>

function chatCandidates() {
const out = [];
// Served by `codewiki serve` itself: same origin, no cross-site request.
if (location.protocol === 'http:' || location.protocol === 'https:') out.push(location.origin);
// Served by `codewiki serve` itself (it marks the page): same origin, no cross-site
// request. Elsewhere, e.g. GitHub Pages, /api/health on this origin is only a 404.
if (document.querySelector('meta[name="codewiki-serve"]')) out.push(location.origin);
(CHAT_CONFIG.endpoints || ['http://127.0.0.1:8765']).forEach(function(e) {
const base = String(e).replace(/\/+$/, '');
if (out.indexOf(base) === -1) out.push(base);
Expand Down
17 changes: 17 additions & 0 deletions tests/test_qa_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,3 +336,20 @@ def test_serve_finds_the_repo_from_a_relative_or_an_old_absolute_path(tmp_path):
meta["generation_info"]["repo_path"] = recorded
meta_path.write_text(json.dumps(meta))
assert QAIndex(str(elsewhere)).repo_path == str(repo.resolve()), recorded


def test_serve_marks_the_pages_it_serves(tmp_path):
"""The docs site probes its own origin's /api/health only when `codewiki serve` served it;
on GitHub Pages that probe was always a 404 in the console."""
_, docs_dir = build(tmp_path)
(docs_dir / "index.html").write_text(
"<html><head lang=en><title>t</title></head><body><header>x</header>"
)
c = TestClient(create_app(str(docs_dir), set()))
html = c.get("/").text
assert html.count('name="codewiki-serve"') == 1
assert html.index('name="codewiki-serve"') < html.index(
"<title>"
) # inside <head>, not <header>
page = c.get("/overview.md")
assert "codewiki-serve" not in page.text and page.status_code == 200
14 changes: 14 additions & 0 deletions tests/test_viewer_browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -390,3 +390,17 @@ def test_chat_says_when_the_browser_blocks_localhost(site, browser):
ctx.close()
finally:
public.close()


def test_a_site_not_served_by_codewiki_does_not_probe_its_own_origin(site, browser):
ctx = browser.new_context()
pg = ctx.new_page()
probes = []
pg.on("request", lambda r: probes.append(r.url) if r.url.endswith("/api/health") else None)
pg.goto(site + "/")
pg.wait_for_selector(".nav-item")
pg.click("#chat-trigger")
pg.wait_for_selector(".chat-offline")
assert probes, "the configured localhost ports are still probed"
assert not [u for u in probes if u.startswith(site + "/")] # no 404 on the site's own origin
ctx.close()
Loading