Skip to content
Open
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
4 changes: 4 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ these entries stays in the GitHub releases and the Git history.

## Unreleased

### Added
- Redirect from a route with `http::redirectReply(status, location)` and the statuses `found` (302), `seeOther` (303), `temporaryRedirect` (307) and `permanentRedirect` (308), written with their reason phrase (#741, `docs/HTTP_ASSETS.md`).
- Answer the root path `/` from the application with `app.addRootRoute(handler)`, before the document root's `index.html`, while `/s/<id>/` of a family of spaces keeps serving it: a session lobby redirects `/` to a new session in one step (#740, `docs/SPACES.md`).

## [1.3.0] - 2026-11-28

WebFront 1.3 ships with developer environment 1.3.0. The developer environment gains inspectors of the running application
Expand Down
20 changes: 20 additions & 0 deletions docs/HTTP_ASSETS.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,26 @@ header that could split the response or that the server owns (`Content-Length`,
500. The registration handle removes the route when destroyed; a request already running keeps its handler. The
binding of a request to a connection (#469) is not part of this mechanism yet.

A route redirects with `http::redirectReply(status, location)` (#741): `Response::movedPermanently` (301),
`found` (302), `seeOther` (303), `temporaryRedirect` (307) or `permanentRedirect` (308), each written with its reason phrase
(`HTTP/1.1 303 See Other`). The reply carries `Location` and an empty body, and the temporary ones (302, 303, 307) also
`Cache-Control: no-store`, so that a browser asks again on its next visit: a route that hands out a new session answers
`303`, since a `301` would be cached and send every later visit to the same session. Another status, an empty location or
one with a control character throws `std::invalid_argument`.

```cpp
auto lobby = app.addRoute("/new/", [&](const http::RouteRequest&) {
return http::redirectReply(http::Response::seeOther, "/s/" + sessions.create() + "/");
});
```

`app.addRootRoute(handler)` (#740) answers the root path `/` itself, any query included, for `GET` and `HEAD`, before the
file providers that would serve `index.html` of the document root. It covers `/` alone (the forms the server reads as `/`,
such as `//`, included): `/index.html`, `/other/` and every other path keep their routes and files, and under a family of
spaces `/s/<id>/` still serves `index.html`, since the root route belongs to the application, not to the spaces. A prefix
route cannot be `/`, and there is one root route at a time (`std::invalid_argument`). Without one, nothing changes. The
lobby of a multi-session application, which redirects `/` to a new session, is described in `docs/SPACES.md`.

`app.addRoute(prefix, handler, http::RouteOptions{.postBodyLimit = n})` also answers `POST` (#619), for a small request
such as a JSON-RPC call: the body, announced by `Content-Length` and at most `n` bytes, is read whole before the handler
runs and reaches it as `RouteRequest::body`. `Expect: 100-continue` gets `100 Continue` first. The server refuses, without
Expand Down
18 changes: 18 additions & 0 deletions docs/SPACES.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,24 @@ and a target that is not a safe path are answered 404 without calling the resolv
segment is cut before it is decoded, so `/s/alpha%2Fdata/` names no space and never reaches `alpha`. Creating a space
applies the same rule, so every space that can be created is reachable.

## A session lobby

A multi-session application often hands out sessions at its root: `GET /` creates one and redirects to it. The root path
belongs to the application, not to the spaces, so `app.addRootRoute(handler)` answers `/` (and only it, any query
included) before the file providers would serve `index.html`, while `/s/<id>/` keeps serving that same `index.html` for
each space. A `303 See Other` sends the browser to the new session without being cached, so that each visit of `/` gets
its own (a `301` would send every later visit to the first session):

```cpp
auto lobby = app.addRootRoute([&](const webfront::http::RouteRequest&) {
return webfront::http::redirectReply(webfront::http::Response::seeOther, "/s/" + newSessionId() + "/");
});
```

The handler runs on a worker thread of the server, not on its context: guard what it shares with the resolver. `GET` and
`HEAD` reach it, other methods get 405 (or `POST` with `RouteOptions::postBodyLimit`). `/index.html` and every other path
keep their routing, and a single root route can exist at a time. Without one, `/` serves `index.html` as before.

## What a space offers

A space has the members of the application that concern its pages, with the same signatures, and its `UI` type is the
Expand Down
11 changes: 11 additions & 0 deletions include/webfront/WebFront.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,17 @@ class BasicWF {
return httpServer.addRoute(std::move(prefix), std::move(handler), std::move(options));
}

/** @brief Answers the root path `/` itself (with any query), for `GET` and `HEAD`, before the file providers that would
* serve the document root's `index.html`: a lobby that hands out a session and redirects to it with
* `http::redirectReply`, for instance. Only `/`: `/index.html` and every other path keep their routes and files, and
* the root of a space (spaces(), `/s/abc/`) still serves its `index.html`. One root route at a time; lasts as long as
* the returned registration. `options` as for addRoute (`secretPath` is refused). Throws std::invalid_argument for an
* empty handler or a second root route. Thread-safe. See docs/SPACES.md (a session lobby).
*/
[[nodiscard]] http::RouteTable::Registration addRootRoute(http::RouteHandler handler, http::RouteOptions options = {}) {
return httpServer.addRootRoute(std::move(handler), std::move(options));
}

/** @brief Declares that the segment following `prefix` (absolute, ending with '/', such as "/s/") is a secret, a capability
* such as a session's identifier: WebFront never writes it to its logs, for files, routes, WebSocket upgrades and their
* failures alike ("/s/<id>/index.html" is logged with a star in place of `<id>`), nor the message of an error raised
Expand Down
109 changes: 91 additions & 18 deletions include/webfront/http/HTTPServer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,10 @@ struct Response : Headers {
accepted = 202,
partialContent = 206,
movedPermanently = 301,
found = 302,
seeOther = 303,
temporaryRedirect = 307,
permanentRedirect = 308,
badRequest = 400,
unauthorized = 401,
forbidden = 403,
Expand Down Expand Up @@ -325,13 +329,17 @@ struct Response : Headers {
mutable std::string httpStatus;

[[nodiscard]] static std::string toString(StatusCode code) {
static constexpr std::array<std::pair<StatusCode, std::string_view>, 19> names{
static constexpr std::array<std::pair<StatusCode, std::string_view>, 23> names{
{{continue_, "Continue"},
{switchingProtocols, "Switching Protocols"},
{ok, "OK"},
{accepted, "Accepted"},
{partialContent, "Partial Content"},
{movedPermanently, "Moved Permanently"},
{found, "Found"},
{seeOther, "See Other"},
{temporaryRedirect, "Temporary Redirect"},
{permanentRedirect, "Permanent Redirect"},
{badRequest, "Bad Request"},
{unauthorized, "Unauthorized"},
{forbidden, "Forbidden"},
Expand Down Expand Up @@ -393,7 +401,8 @@ struct RouteOptions {
std::optional<std::size_t> postBodyLimit{};
};

/// The dynamic routes of a server. Prefixes never overlap, so at most one route matches a path.
/// The dynamic routes of a server. Prefixes never overlap, so at most one route matches a path. The root route
/// (addRoot) answers the path "/" alone, not the paths under it.
class RouteTable {
public:
struct Entry {
Expand All @@ -405,6 +414,8 @@ class RouteTable {
std::function<void(RouteReply&)> harden;
/// See RouteOptions::postBodyLimit: unset, the route refuses `POST` with 405.
std::optional<std::size_t> postBodyLimit;
/// The route answers its prefix alone ("/" for the root route), not the paths under it.
bool exact = false;
};

private:
Expand Down Expand Up @@ -470,26 +481,34 @@ class RouteTable {
// The log redaction recognizes the services space only: a secret route elsewhere could not be masked reliably.
if (options.secretPath && !prefix.starts_with("/webfront/services/"))
throw std::invalid_argument("A secret route must live under /webfront/services/, not '" + prefix + "'");
auto entry = std::make_shared<Entry>(
Entry{std::move(prefix), std::move(handler), options.secretPath, std::move(options.harden), options.postBodyLimit});
std::lock_guard lock(state->mutex);
for (const auto& other : state->entries)
if (other->prefix.starts_with(entry->prefix) || entry->prefix.starts_with(other->prefix))
throw std::invalid_argument("Route prefix '" + entry->prefix + "' collides with '" + other->prefix + "'");
state->entries.push_back(entry);
return {state, std::move(entry)};
return insert(
std::make_shared<Entry>(Entry{std::move(prefix), std::move(handler), options.secretPath, std::move(options.harden), options.postBodyLimit, false}));
}

/// @return the route whose prefix starts the path, kept alive for as long as the caller holds it.
[[nodiscard]] std::shared_ptr<const Entry> find(std::string_view path) const {
/// Registers the root route: it answers the path "/" alone (with any query), every other path keeps its route or
/// goes to the file providers. Only RouteOptions::secretPath is refused, since a secret route lives under
/// /webfront/services/.
/// @throws std::invalid_argument for an empty handler, a secret path, or a root route already registered.
[[nodiscard]] Registration addRoot(RouteHandler handler, RouteOptions options = {}) {
if (!handler)
throw std::invalid_argument("A route needs a handler");
if (options.secretPath)
throw std::invalid_argument("A secret route must live under /webfront/services/, not '/'");
return insert(std::make_shared<Entry>(Entry{"/", std::move(handler), false, std::move(options.harden), options.postBodyLimit, true}));
}

/// @return the route whose prefix starts the path, or the root route for "/" (and unless `withRoot` is false), kept
/// alive for as long as the caller holds it.
[[nodiscard]] std::shared_ptr<const Entry> find(std::string_view path, bool withRoot = true) const {
std::lock_guard lock(state->mutex);
for (const auto& entry : state->entries)
if (path.starts_with(entry->prefix))
if (entry->exact ? withRoot && path == entry->prefix : path.starts_with(entry->prefix))
return entry;
return {};
}

/// True for an absolute path ending with '/', other than "/", without "..", "//", "/./", control or reserved characters.
/// True for an absolute path ending with '/', other than "/" (see addRoot), without "..", "//", "/./", control or
/// reserved characters.
[[nodiscard]] static bool validPrefix(std::string_view prefix) {
if (prefix.size() < 2 || !prefix.starts_with('/') || !prefix.ends_with('/'))
return false;
Expand All @@ -501,6 +520,20 @@ class RouteTable {
}

private:
// A prefix route covers the paths that start with its prefix, an exact one only its own: two routes collide when one
// would answer a path of the other.
Registration insert(std::shared_ptr<Entry> entry) {
const auto covers = [](const Entry& route, const Entry& other) {
return route.exact ? other.exact && other.prefix == route.prefix : other.prefix.starts_with(route.prefix);
};
std::lock_guard lock(state->mutex);
for (const auto& other : state->entries)
if (covers(*entry, *other) || covers(*other, *entry))
throw std::invalid_argument("Route prefix '" + entry->prefix + "' collides with '" + other->prefix + "'");
state->entries.push_back(entry);
return {state, std::move(entry)};
}

std::shared_ptr<State> state = std::make_shared<State>();
};

Expand Down Expand Up @@ -544,6 +577,38 @@ using MountResolver = std::function<MountAnswer(std::string_view segment)>;
return reply;
}

/// A redirection to `location`, with an empty body: `301` and `308` are permanent, which browsers may cache; `302`, `303`
/// and `307` are temporary and carry `Cache-Control: no-store`, so that a later visit asks again (a lobby that hands out a
/// new session answers `303 See Other`). `307` and `308` keep the method and body of the request, `303` turns them into a
/// `GET`. Throws std::invalid_argument for a status that is not a redirection, or a location that is empty or holds a
/// control character, which would split the header.
[[nodiscard]] inline RouteReply redirectReply(Response::StatusCode status, std::string location) {
switch (status) {
case Response::movedPermanently:
case Response::found:
case Response::seeOther:
case Response::temporaryRedirect:
case Response::permanentRedirect:
break;
default:
throw std::invalid_argument("redirectReply takes a redirection status (301, 302, 303, 307 or 308), not " + std::to_string(status));
}
if (location.empty() || std::any_of(location.begin(), location.end(), [](char c) {
return static_cast<unsigned char>(c) < 32 || c == 127;
}))
throw std::invalid_argument("redirectReply takes a non-empty location without control characters");
RouteReply reply;
reply.status = status;
reply.headers.emplace_back("Location", std::move(location));
if (status != Response::movedPermanently && status != Response::permanentRedirect)
reply.headers.emplace_back("Cache-Control", "no-store");
reply.contentLength = 0;
reply.body = [](std::span<char>) {
return std::size_t{0};
};
return reply;
}

namespace routing {

/// True when a request target may carry a read token (it names the services space): its text is then never logged,
Expand Down Expand Up @@ -1300,6 +1365,13 @@ class Server {
return routes.add(std::move(prefix), std::move(handler), std::move(options));
}

/// Answers the root path "/" (any query) before the file providers, which would serve its `index.html`: a lobby that
/// redirects to a new session, for instance. Every other path keeps its routing, and the root of a space under a mount
/// ("/s/abc/") still serves its `index.html`. One root route at a time (std::invalid_argument); see RouteTable::addRoot.
[[nodiscard]] RouteTable::Registration addRootRoute(RouteHandler handler, RouteOptions options = {}) {
return routes.addRoot(std::move(handler), std::move(options));
}

/// Called, on the context's thread, with the socket of a connection upgraded to a WebSocket. A handler that also takes a
/// `const UpgradeSpace&` receives the space of the upgrade, as its mount resolved it (empty outside the mounts), and the
/// path of the upgrade request.
Expand Down Expand Up @@ -1598,16 +1670,17 @@ class Server {

// A request, other than a WebSocket upgrade, under a registered prefix. Every method under a prefix
// belongs to the route (405 for those it does not serve): its URLs never fall through to the providers.
// The routes of a space (`own`) come before the server's.
std::optional<RouteMatch> matchRoute(const Request& request, const RouteTable* own = nullptr) const {
// The routes of a space (`own`) come before the server's. Under a mount (`mounted`), the server's root route belongs
// to the application, not to the spaces: "/s/abc/" still serves the space's index.html.
std::optional<RouteMatch> matchRoute(const Request& request, const RouteTable* own = nullptr, bool mounted = false) const {
if (request.isUpgradeRequest("websocket"))
return {};
auto split = routing::splitTarget(request.uri);
if (!split)
return {};
auto route = own ? own->find(split->first) : nullptr;
if (!route)
route = routes.find(split->first);
route = routes.find(split->first, !mounted);
if (!route)
return {};
return RouteMatch{std::move(route), std::move(split->first), std::move(split->second)};
Expand Down Expand Up @@ -1846,7 +1919,7 @@ class Server {
throw BadRequestException();
space.requestPath = std::move(target->first);
}
auto match = matchRoute(request, spaceRoutes.get());
auto match = matchRoute(request, spaceRoutes.get(), !mountPrefix.empty());
// Under a mount, the logs show the whole path as it came, the mount's segment and the secret segments masked; a
// secret prefix covers it as the server read it and as the space reads it. The query may quote a URL: never shown.
const auto shown = [&](std::string_view path) {
Expand Down
Loading
Loading