Chat
Chat is a small chat app with three rooms. A visitor chooses a name and a room. Each line they write appears at once on the page of every visitor in the same room. A new visitor sees the last 50 lines of the room, which the app keeps in a SQLite database.
The chat uses WebSockets. A WebSocket is a connection that stays open, so the browser and the
server can send each other messages at any time. The browser opens it with new WebSocket(...),
which every browser has. Novis sends the pages and runs every WebSocket connection from one process.
You need no separate WebSocket server, no message queue and no JavaScript library.
The app shows how these parts work together:
Core\Sessionkeeps the name of each visitor on the server.Core\Socket::upgradeturns a request into a WebSocket connection.- Each connection runs its own small program,
Connection::run, with its own memory limit. Core\Topicsends each chat line to every connection in the room.- The connection checks every message from the browser, and it limits how fast a visitor can write.
- Novis checks the
Originheader, so another website cannot open a connection with the cookies of your visitor. - The browser script connects again by itself when the connection breaks.
- The folder
deployhas the production configuration and the proxy configuration.
The code
Section titled “The code”Each tab shows one file of the app. These are the same files that you download below.
- nvs.toml
- public/chat.js
- public/index.nvs
- public/style.css
- src/App.nvs
- src/AppTest.nvs
- src/CheckTest.nvs
- src/Connection.nvs
- src/Gate.nvs
- src/History.nvs
- src/HistoryTest.nvs
- src/Incoming.nvs
- src/Limiter.nvs
- src/Line.nvs
- src/LiveTest.nvs
- src/Nickname.nvs
- src/Pages.nvs
- src/Rooms.nvs
- deploy/Caddyfile
- deploy/nginx.conf
- deploy/production.toml
- README.md
# The server listens on port 8144. The other apps in this repository use other ports,# so all of them can run at the same time.[server]listen = ["127.0.0.1:8144"]
# These limits are for each WebSocket connection. A chat line is short, so a message from# the browser may have at most 16 KB. A connection with no message for 5 minutes is closed.[server.connection]max_message = 16384idle_timeout = "5m"
# The browser may load scripts, styles and images only from this server, and open# connections only to this server. The pages have no inline script, so this strict policy works.# Novis adds `frame-ancestors 'none'` by itself, so no other website can show the pages in a frame.[http.headers]content_security_policy = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'"
# The last lines of each room are kept in the SQLite file `chat.sqlite`, next to this file.# Novis creates the file when the first connection opens the database.[db.chat]driver = "sqlite"path = "chat.sqlite"
# The tests use this database. It is kept in memory and deleted when the tests end.[db.scratch]driver = "sqlite"path = ":memory:"
# The program may open these two databases and no other.[capabilities.db]connect = ["chat", "scratch"]// The browser side of the chat. It uses the `WebSocket` class that every browser has,// so the page needs no library.const main = document.querySelector('main[data-socket]')const list = document.getElementById('lines')const form = document.getElementById('say')const status = document.getElementById('status')
let socket = null// The id of the newest line on the page. A line with this id or a smaller one is already shown.let lastId = 0// How long to wait before the next try to connect, in milliseconds.let wait = 1000
// Opens the WebSocket. The address is the room page's `data-socket`, with `ws:` or `wss:`.function connect() { const url = new URL(main.dataset.socket, location.href) url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:' socket = new WebSocket(url) socket.onopen = () => { status.textContent = 'Connected.' wait = 1000 } socket.onmessage = (event) => show(JSON.parse(event.data)) // When the connection closes, the page tries again. The wait doubles each time, up to 30 seconds. socket.onclose = () => { status.textContent = 'The connection is lost. Connecting again …' setTimeout(connect, wait) wait = Math.min(wait * 2, 30000) }}
// Shows one message from the server. `kind` says what the message is.function show(message) { if (message.kind === 'history') message.lines.forEach(addLine) if (message.kind === 'line') addLine(message.line) if (message.kind === 'joined') addNotice(`${message.name} joined the room.`) if (message.kind === 'left') addNotice(`${message.name} left the room.`) if (message.kind === 'problem') addNotice(message.text)}
// Adds one chat line to the list. `append` with a string adds it as text, so HTML in a line is never run.function addLine(line) { if (line.id <= lastId) return lastId = line.id const time = document.createElement('time') time.textContent = new Date(line.at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) const name = document.createElement('b') name.textContent = line.name const item = document.createElement('li') item.append(time, ' ', name, ': ', line.text) addItem(item)}
function addNotice(text) { const item = document.createElement('li') item.className = 'notice' item.textContent = text addItem(item)}
function addItem(item) { list.append(item) list.scrollTop = list.scrollHeight}
// Sends the text of the form as one chat line.form.addEventListener('submit', (event) => { event.preventDefault() const text = form.elements.text.value.trim() if (text === '' || socket.readyState !== WebSocket.OPEN) return socket.send(JSON.stringify({ kind: 'say', text })) form.elements.text.value = ''})
// The server closes a connection with no message for 5 minutes.// A `ping` message each minute keeps the connection open while the page is open.setInterval(() => { if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ kind: 'ping' }))}, 60000)
connect()<?nvs// This is the entry file. `nvs serve public/index.nvs` runs it once for each request.// The `autoload` line reads each class `Chat\...` from the folder `src`.autoload 'Chat' from '../src';
// `dispatch` finds the route for the request and calls its method.// `Chat\Gate` decides if the method may run, and it shows the error pages.Core\Router::dispatch(new Chat\Gate());/* The styles of every page of the chat. */body { font-family: system-ui, sans-serif; max-width: 40rem; margin: 2rem auto; padding: 0 1rem;}.problem { color: #b00020;}.status { color: #555;}#lines { list-style: none; padding: 0; height: 60vh; overflow-y: auto; border: 1px solid #ccc; border-radius: 6px;}#lines li { padding: 0.25rem 0.5rem;}#lines time { color: #777; font-size: 0.85em;}#lines .notice { color: #777; font-style: italic;}#say { display: flex; gap: 0.5rem;}#say input { flex: 1;}<?nvsnamespace Chat;
use Core\Access;use Core\Audience;use Core\Http\Method;use Core\Request;use Core\Response;use Core\Route;use Core\Router;use Core\Session;use Core\Str;
// The routes of the app. Each method with a `Route` handles one kind of request.// `Core\Router::dispatch` in `public/index.nvs` calls the method of the route that matches.final class App{ // Shows the form where a visitor chooses a name and a room. #[Route(path: '/', method: Method::Get)] #[Access(allow: Audience::Public)] public static function home(): void { Response::sendHtml(Pages::home('', 'lobby', null)); }
// Checks the form, saves the name in the session, then opens the page of the room. #[Route(path: '/join', method: Method::Post)] #[Access(allow: Audience::Public)] public static function join(): void { tainted string $name = Str::trim(Request::formField('name') ?? ''); ?string $room = Rooms::find(Request::formField('room') ?? ''); ?string $problem = $room == null ? 'Please choose a room.' : Nickname::problem($name); if ($room == null || $problem != null) { // 422 means the server understood the request, but the data is not valid. Response::setStatus(422); Response::sendHtml(Pages::home($name, $room ?? 'lobby', $problem)); return; } // The session keeps the name on the server. The browser only gets a random identifier in a cookie. // `regenerate` gives the session a new identifier, as after a sign-in. Session::regenerate(); Session::setShortLived('name', $name); Response::redirect(Router::url(App::room, ['room' => $room])); }
// Shows the page of one room. Its script opens the WebSocket at `/rooms/{room}/socket`. #[Route(path: '/rooms/{room}', method: Method::Get)] #[Access(allow: Audience::Public)] public static function room(tainted string $room): void { ?string $found = Rooms::find($room); if ($found == null) { Response::setStatus(404); Response::sendHtml(Pages::notFound()); return; } ?tainted string $name = App::name(); if ($name == null) { // Without a valid name, the visitor goes back to the form. Response::redirect(Router::url(App::home)); return; } Response::sendHtml(Pages::room($found, $name, Router::url(App::socket, ['room' => $found]))); }
// Turns the request into a WebSocket connection. // The connection runs `Connection::run` with the room and the name, and with at most 8 MB of memory. #[Route(path: '/rooms/{room}/socket', method: Method::Get)] #[Access(allow: Audience::Public)] public static function socket(tainted string $room): void { // The room and the name are checked again here. A WebSocket client does not have to use the form. ?string $found = Rooms::find($room); ?tainted string $name = App::name(); if ($found == null || $name == null) { Response::setStatus(404); Response::sendText("There is no such room, or you have no valid name.\n"); return; } // A normal page request to this address gets the status 426: it must ask for a WebSocket. if (Str::lower(Request::header('upgrade') ?? '') != 'websocket') { Response::setStatus(426); Response::sendText("This address is for a WebSocket connection.\n"); return; } Core\Socket::upgrade(Connection::run, arguments: ['room' => $found, 'name' => $name], limits: { memory: '8M' }); }
// Sends the script of the room page. A server in production mode sends no file by itself, so this route sends it. // The path starts at the folder of this file. A request may read the files in `public`. #[Route(path: '/chat.js', method: Method::Get)] #[Access(allow: Audience::Public)] public static function script(): void { Response::sendFile('../public/chat.js'); }
// Sends the style sheet of every page. #[Route(path: '/style.css', method: Method::Get)] #[Access(allow: Audience::Public)] public static function style(): void { Response::sendFile('../public/style.css'); }
// Returns the name that `App::join` saved in the session, or `null` when the visitor has none. private static function name(): ?tainted string { // The default comes before the conversion, because `null as string` is an empty string. tainted string $name = (Session::get('name') ?? '') as string; return $name == '' ? null : $name; }}<?nvsnamespace Chat;
use Core\Config;use Core\Http\Method;use Core\Str;use Core\Test;
// Tests that send requests to the app. `Test::request` runs the app without a server.final class AppTest{ #[Test] public function theHomePageShowsTheForm(): void { var $response = Test::request(Method::Get, '/'); Test::assertEquals($response->status(), 200); Test::assertTrue(Str::contains($response->body(), '<form method="post" action="/join">')); }
#[Test] public function joiningWithoutANameShowsTheProblem(): void { var $response = AppTest::join('lobby', ''); Test::assertEquals($response->status(), 422); Test::assertTrue(Str::contains($response->body(), 'Please enter a name.')); }
#[Test] public function joiningStartsASessionAndOpensTheRoom(): void { var $response = AppTest::join('help', 'Ana Lee'); Test::assertEquals($response->status(), 303); Test::assertEquals($response->header('location'), '/rooms/help'); // The cookie has the random identifier of the session. The name stays on the server. string $session = $response->cookies()['nvsid'] ?? ''; Test::assertTrue(Str::length($session) >= 20); Test::assertSame(Str::contains($session, 'Ana'), false); }
#[Test] public function theRoomPageHasTheAddressOfItsSocket(): void { var $response = Test::request(Method::Get, '/rooms/help', { headers: AppTest::signedIn('Ana') }); Test::assertEquals($response->status(), 200); Test::assertTrue(Str::contains($response->body(), 'data-socket="/rooms/help/socket"')); Test::assertTrue(Str::contains($response->body(), '<b>Ana</b>')); }
#[Test] public function aVisitorWithoutASessionGoesToTheForm(): void { var $response = Test::request(Method::Get, '/rooms/help'); Test::assertEquals($response->status(), 303); Test::assertEquals($response->header('location'), '/'); // A made-up session identifier finds no session, so it gives the same result. var $guessed = Test::request(Method::Get, '/rooms/help', { headers: ['cookie' => 'nvsid=made-up'] }); Test::assertEquals($guessed->status(), 303); }
#[Test] public function anUnknownRoomIsNotFound(): void { array<string> $headers = AppTest::signedIn('Ana'); Test::assertEquals(Test::request(Method::Get, '/rooms/kitchen', { headers: $headers })->status(), 404); Test::assertEquals(Test::request(Method::Get, '/rooms/kitchen/socket', { headers: $headers })->status(), 404); }
#[Test] public function aPageRequestToTheSocketGets426(): void { // 426 means "upgrade required": this address only accepts a WebSocket. var $response = Test::request(Method::Get, '/rooms/lobby/socket', { headers: AppTest::signedIn('Ana') }); Test::assertEquals($response->status(), 426); }
#[Test] public function theScriptAndTheStylesAreSent(): void { var $script = Test::request(Method::Get, '/chat.js'); Test::assertEquals($script->status(), 200); Test::assertEquals($script->header('content-type'), 'text/javascript; charset=utf-8'); Test::assertTrue(Str::contains($script->body(), 'new WebSocket(url)')); Test::assertEquals(Test::request(Method::Get, '/style.css')->status(), 200); }
#[Test] public function thePagesMayLoadFilesOnlyFromThisServer(): void { // The server adds this header to every response. `Test::request` returns only the headers // that the program sets, so the test reads the setting from `nvs.toml`. string $policy = Config::get('http.headers.content_security_policy') ?? ''; Test::assertTrue(Str::contains($policy, "script-src 'self'")); Test::assertTrue(Str::contains($policy, "connect-src 'self'")); Test::assertSame(Str::contains($policy, 'unsafe-inline'), false); }
// Sends the form of the home page with this room and name. public static function join(string $room, string $name): Core\Test\Response { array<string> $headers = ['content-type' => 'application/x-www-form-urlencoded']; string $body = Core\Uri::buildQuery(['room' => $room, 'name' => $name]); return Test::request(Method::Post, '/join', { headers: $headers, body: $body }); }
// The headers of a browser that joined with this name. The cookie `nvsid` has the identifier of its session. // The name is saved with the short lifetime, so the browser also sends the cookie `nvsid-short`. public static function signedIn(string $name): array<string> { array<string> $cookies = AppTest::join('lobby', $name)->cookies(); string $session = $cookies['nvsid'] ?? ''; string $short = $cookies['nvsid-short'] ?? ''; return ['cookie' => 'nvsid=' . $session . '; nvsid-short=' . $short]; }}<?nvsnamespace Chat;
use Core\Test;
// Tests the checks on names, rooms, chat lines and the speed of a visitor.final class CheckTest{ #[Test] public function aShortNameIsValid(): void { Test::assertNull(Nickname::problem('Ana')); Test::assertNull(Nickname::problem(' Ana ')); }
#[Test] public function anEmptyOrLongNameIsNotValid(): void { Test::assertSame(Nickname::problem(' '), 'Please enter a name.'); Test::assertSame(Nickname::problem('Anastasia Alexandrovna'), 'A name can have at most 20 characters.'); Test::assertSame(Nickname::problem("Ana\nBen"), 'A name can only have letters, digits, spaces and punctuation.'); }
#[Test] public function onlyTheListedRoomsExist(): void { Test::assertSame(Rooms::find('help'), 'help'); Test::assertNull(Rooms::find('kitchen')); Test::assertSame(Rooms::topic('help'), 'room:help'); }
#[Test] public function aChatLineMustHaveText(): void { Test::assertNull((new Incoming('say', 'Hello'))->problem()); Test::assertSame((new Incoming('say', ' '))->problem(), 'A chat line cannot be empty.'); Test::assertSame((new Incoming('say', Core\Str::repeat('a', 501)))->problem(), 'A chat line can have at most 500 characters.'); }
// The clock of this test is fixed, and `Test::advance` moves it without waiting. #[Test(at: '2026-03-01T09:00:00Z')] public function theLimiterAllowsFiveLinesInTenSeconds(): void { Limiter $limiter = new Limiter(5, 10s); for (uint $i = 0; $i < 5; $i++) { Test::assertTrue($limiter->allow()); } Test::assertSame($limiter->allow(), false); Test::advance(10s); Test::assertTrue($limiter->allow()); }}<?nvsnamespace Chat;
use Core\Json;use Core\Socket;use Core\Socket\Message;use Core\Str;use Core\Topic;use ParseError;
// The program of one WebSocket connection. `App::socket` starts it for each visitor in a room.// It runs until the visitor closes the page. It knows only the room and the name it was given.final class Connection{ public static function run(string $room, tainted string $name): void { Socket $socket = Socket::current(); History $history = History::open(); Limiter $limiter = new Limiter(5, 10s); string $topic = Rooms::topic($room);
// The connection joins the room first. Then it sends the last 50 lines of the room. // A line that arrives in between can come twice, so the browser skips a line it already has. Topic::subscribe($topic); $socket->send(Json::encode({ kind: 'history', lines: $history->recent($room, 50) })); Topic::publish($topic, Json::encode({ kind: 'joined', name: $name }));
// `receive()` waits for the next message from the browser or from the room. // It returns `null` when the visitor closes the page, and then the loop ends. ?Message $message = $socket->receive(); while ($message != null) { if ($message->topic() != null) { // A message from the room is JSON text already, so it goes to the browser as it is. $socket->send($message->value() as string); } else { Connection::fromBrowser($socket, $message, $room, $name, $history, $limiter); } $message = $socket->receive(); } Topic::publish($topic, Json::encode({ kind: 'left', name: $name })); }
// Handles one message from the browser. A valid chat line is saved and sent to the whole room. // For a message that is not valid, only this browser gets a `problem` message. private static function fromBrowser(Socket $socket, Message $message, string $room, tainted string $name, History $history, Limiter $limiter): void { try { Incoming $incoming = Json::decodeAs<Incoming>($message->text() ?? ''); } catch (ParseError $error) { Connection::problem($socket, 'The message must be JSON text, such as {"kind": "say", "text": "Hello"}.'); return; } if ($incoming->kind == 'ping') { return; } if ($incoming->kind != 'say') { Connection::problem($socket, 'The kind of a message must be "say" or "ping".'); return; } ?string $problem = $incoming->problem(); if ($problem != null) { Connection::problem($socket, $problem); return; } if (!$limiter->allow()) { Connection::problem($socket, 'You are sending too fast. Please wait a few seconds.'); return; } Line $line = $history->add($room, $name, Str::trim($incoming->text)); Topic::publish(Rooms::topic($room), Json::encode({ kind: 'line', line: $line })); }
// Sends a problem to this browser only. private static function problem(Socket $socket, string $text): void { $socket->send(Json::encode({ kind: 'problem', text: $text })); }}<?nvsnamespace Chat;
use Core\Audience;use Core\Response;use Core\Router\Refusal;use Throwable;
// The gate of the app. `Core\Router::dispatch` calls it for every request.// It decides if a route method may run, and it shows the error pages.final class Gate implements Core\Router\Gate{ // Runs before each route method. The method runs only when this returns `true`. // Every route of this app is public, so this checks for `Audience::Public`. public function allows(Core\Router\Match $route): bool { return $route->accessAs<Audience>() == Audience::Public; }
// Shows a page when no route method can handle the request. // `dispatch` has already set the status code, such as 404 or 403. public function refused(Refusal $reason, ?Core\Router\Match $route): void { if ($reason == Refusal::NotFound) { Response::sendHtml(Pages::notFound()); return; } string $text = match ($reason) { Refusal::MethodNotAllowed => 'This address does not accept this kind of request.', Refusal::Csrf => 'This request came from another website, so it is not allowed.', default => 'This request is not allowed.', }; Response::sendHtml(Pages::problem('Not possible', $text)); }
// Shows a page when a route method throws an error. The status code is 500. public function failed(?Core\Router\Match $route, ?Throwable $error): void { Response::sendHtml(Pages::problem('Something went wrong', 'Please try again later.')); }}<?nvsnamespace Chat;
use Core\Db;use Core\Db\Connection;use Core\Db\Row;use Core\Time;
// Saves the chat lines of each room, so a new visitor can read what was said before.// Only the newest 100 lines of a room are kept, so the file does not grow forever.final class History{ private Connection $db;
public function constructor(Connection $db) { $this->db = $db; }
// Opens the database `chat` from `nvs.toml` and creates the table when it is missing. public static function open(): History { var $history = new History(Db::connect('chat')); $history->setUp(); return $history; }
// Creates the table `lines` if it does not exist yet. public function setUp(): void { $this->db->execute('create table if not exists lines (id integer primary key, room text not null, name text not null, text text not null, at integer not null)', []); }
// Saves a new line in a room and returns it. // Each `?` is a placeholder. The database gets the text apart from the SQL, so the text cannot change the SQL. public function add(string $room, tainted string $name, tainted string $text): Line { int $at = Time::now()->toEpochMillis(); var $write = $this->db->execute('insert into lines (room, name, text, at) values (?, ?, ?, ?)', [$room, $name, $text, $at]); uint $id = $write->lastId() ?? 0; // Deletes the lines of this room that are older than the newest 100. $this->db->execute('delete from lines where room = ? and id not in (select id from lines where room = ? order by id desc limit 100)', [$room, $room]); return new Line($id, $name, $text, $at); }
// Returns the newest lines of a room, at most `$count` of them. The oldest line is first. public function recent(string $room, uint $count): array<Line> { array<Line> $lines = []; var $rows = $this->db->query('select id, name, text, at from (select * from lines where room = ? order by id desc limit ?) order by id', [$room, $count]); foreach ($rows as Row $row) { $lines[] = new Line($row->uint('id') ?? 0, $row->string('name') ?? '', $row->string('text') ?? '', $row->int('at') ?? 0); } return $lines; }}<?nvsnamespace Chat;
use Core\Db;use Core\Test;
// Tests the saved lines. They use the database `scratch`, which is kept in memory.final class HistoryTest{ #[Test] public function theNewestLinesComeInTheOrderTheyWereWritten(): void { var $history = HistoryTest::empty(); $history->add('lobby', 'Ana', 'one'); $history->add('lobby', 'Ben', 'two'); $history->add('lobby', 'Ana', 'three'); array<Line> $lines = $history->recent('lobby', 2); Test::assertCount($lines, 2); Test::assertSame($lines[0]->text, 'two'); Test::assertSame($lines[1]->text, 'three'); }
#[Test] public function eachRoomHasItsOwnLines(): void { var $history = HistoryTest::empty(); $history->add('lobby', 'Ana', 'hello'); Test::assertCount($history->recent('help', 50), 0); }
#[Test] public function aRoomKeepsItsNewest100Lines(): void { var $history = HistoryTest::empty(); for (uint $i = 1; $i <= 105; $i++) { $history->add('lobby', 'Ana', 'line ' . $i); } array<Line> $lines = $history->recent('lobby', 500); Test::assertCount($lines, 100); Test::assertSame($lines[0]->text, 'line 6'); }
private static function empty(): History { var $db = Db::connect('scratch'); $db->execute('drop table if exists lines', []); var $history = new History($db); $history->setUp(); return $history; }}<?nvsnamespace Chat;
use Core\Str;
// A JSON message from the browser: `{"kind": "say", "text": "Hello"}` is a chat line.// `{"kind": "ping"}` keeps a quiet connection open, and the server sends nothing back.#[Core\Json\Derive]final class Incoming{ public tainted string $kind; public tainted string $text;
public function constructor(tainted string $kind, tainted string $text = '') { $this->kind = $kind; $this->text = $text; }
// Returns the problem with a chat line, or `null` when the line is valid. public function problem(): ?string { if (Str::trim($this->text) == '') { return 'A chat line cannot be empty.'; } if (Str::length($this->text) > 500) { return 'A chat line can have at most 500 characters.'; } return null; }}<?nvsnamespace Chat;
use Core\Time;use Core\Time\Duration;use Core\Time\Instant;
// Counts the chat lines of one connection. It allows at most `$max` lines in each `$window`.// One visitor who sends too fast cannot fill the room for everybody else.final class Limiter{ private uint $max; private Duration $window; private Instant $start; private uint $count = 0;
public function constructor(uint $max, Duration $window) { $this->max = $max; $this->window = $window; $this->start = Time::now(); }
// Returns `true` and counts the line when one more line is allowed now. // Returns `false` when the visitor must wait. public function allow(): bool { Instant $now = Time::now(); // A new window starts when the old one is over. Then the count starts again at 0. if ($now->since($this->start)->compareTo($this->window) >= 0) { $this->start = $now; $this->count = 0; } if ($this->count >= $this->max) { return false; } $this->count = $this->count + 1; return true; }}<?nvsnamespace Chat;
// One saved chat line. `at` is the time it was written, in milliseconds since 1970,// so each browser can show it in the time zone of its visitor.#[Core\Json\Derive]final class Line{ public uint $id; public tainted string $name; public tainted string $text; public int $at;
public function constructor(uint $id, tainted string $name, tainted string $text, int $at) { $this->id = $id; $this->name = $name; $this->text = $text; $this->at = $at; }}<?nvsnamespace Chat;
use Core\Db;use Core\Http\Client;use Core\Http\Socket;use Core\Str;use Core\Test;use RuntimeError;
// Tests with real WebSocket connections. `server: true` starts a server for each test.// The tests write lines into `chat.sqlite`, and each test deletes its own lines at the end.final class LiveTest{ #[Test(server: true)] public function twoVisitorsTalkInOneRoom(): void { string $ana = LiveTest::name(); string $ben = LiveTest::name(); Socket $first = LiveTest::open('random', $ana); LiveTest::waitFor($first, 'history'); Socket $second = LiveTest::open('random', $ben); // When the history arrives, the connection of Ben is in the room. LiveTest::waitFor($second, 'history'); // Ana first gets her own `joined` message, and then the one for Ben. LiveTest::waitFor($first, 'joined', $ben);
$first->send('{"kind": "say", "text": "Hello, Ben!"}'); // Other tests use the same room at the same time, so the test waits for its own line. tainted string $line = LiveTest::waitFor($second, 'line', 'Hello, Ben!'); Test::assertTrue(Str::contains($line, '"text":"Hello, Ben!"')); Test::assertTrue(Str::contains($line, $ana));
// When Ben closes the page, Ana gets a `left` message. $second->close(); LiveTest::waitFor($first, 'left', $ben); $first->close(); LiveTest::forget($ana); }
#[Test(server: true)] public function aNewVisitorGetsTheHistory(): void { string $ana = LiveTest::name(); Socket $first = LiveTest::open('random', $ana); LiveTest::waitFor($first, 'history'); $first->send('{"kind": "say", "text": "Is anybody here?"}'); LiveTest::waitFor($first, 'line', 'Is anybody here?'); $first->close();
Socket $later = LiveTest::open('random', LiveTest::name()); Test::assertTrue(Str::contains(LiveTest::waitFor($later, 'history'), '"text":"Is anybody here?"')); $later->close(); LiveTest::forget($ana); }
#[Test(server: true)] public function aWrongMessageGetsAProblemOnlyForItsSender(): void { Socket $socket = LiveTest::open('random', LiveTest::name()); LiveTest::waitFor($socket, 'history'); $socket->send('hello'); Test::assertTrue(Str::contains(LiveTest::waitFor($socket, 'problem'), 'must be JSON text')); $socket->send('{"kind": "say", "text": ""}'); Test::assertTrue(Str::contains(LiveTest::waitFor($socket, 'problem'), 'cannot be empty')); $socket->close(); }
#[Test(server: true)] public function aVisitorWhoSendsTooFastMustWait(): void { string $ana = LiveTest::name(); Socket $socket = LiveTest::open('random', $ana); LiveTest::waitFor($socket, 'history'); for (uint $i = 1; $i <= 6; $i++) { $socket->send('{"kind": "say", "text": "line ' . $i . '"}'); } Test::assertTrue(Str::contains(LiveTest::waitFor($socket, 'problem'), 'You are sending too fast.')); $socket->close(); LiveTest::forget($ana); }
#[Test(server: true)] public function aSocketFromAnotherWebsiteIsNotAllowed(): void { // A browser sends the `Origin` header with the address of the page that opens the socket. // The session is valid, so only the other website stops this request, with the status 403. array<string> $headers = AppTest::signedIn('Ana'); $headers['origin'] = 'https://example.com'; Test::assertThrows(fn() => Client::openSocket(LiveTest::address('random'), { headers: $headers, idle: 5s }), RuntimeError::class); // The same session from this website opens the socket. Socket $socket = Client::openSocket(LiveTest::address('random'), { headers: AppTest::signedIn('Ana'), idle: 5s }); LiveTest::waitFor($socket, 'history'); $socket->close(); }
// Opens a WebSocket to the test server, the same way the room page does. // The browser sends its session cookie, and the test sends it as a header. private static function open(string $room, string $name): Socket { return Client::openSocket(LiveTest::address($room), { headers: AppTest::signedIn($name), idle: 5s }); }
// The test server's address starts with `http`. A WebSocket address starts with `ws`. private static function address(string $room): string { string $base = Test::serverUrl() ?? ''; return 'ws' . Str::slice($base, 4) . '/rooms/' . $room . '/socket'; }
// Reads messages until one of this kind arrives that contains `$with`, and returns it as JSON text. // When no message arrives for 5 seconds, `receive()` throws an error and the test fails. private static function waitFor(Socket $socket, string $kind, string $with = ''): tainted string { ?Core\Socket\Message $message = $socket->receive(); while ($message != null) { tainted string $text = $message->text() ?? ''; if (Str::startsWith($text, '{"kind":"' . $kind . '"') && Str::contains($text, $with)) { return $text; } $message = $socket->receive(); } throw new RuntimeError('The connection closed before a "' . $kind . '" message arrived.'); }
// A name that no other test uses, such as `Test 482193`. private static function name(): string { return 'Test ' . Core\Random::int(100000, 999999); }
// Deletes the lines that a test wrote. private static function forget(string $name): void { Db::connect('chat')->execute('delete from lines where name = ?', [$name]); }}<?nvsnamespace Chat;
use Core\Str;use Core\Validate;
// The checks on the name that a visitor chooses.final class Nickname{ // Returns the problem with a name, or `null` when the name is valid. public static function problem(tainted string $name): ?string { tainted string $trimmed = Str::trim($name); if ($trimmed == '') { return 'Please enter a name.'; } if (Str::length($trimmed) > 20) { return 'A name can have at most 20 characters.'; } // A name with a new line or a tab could look like two lines in the chat. if (!Validate::isPrintable($trimmed)) { return 'A name can only have letters, digits, spaces and punctuation.'; } return null; }}<?nvsnamespace Chat;
use Core\Html\Markup;
// Builds the HTML pages. Each `{$name}` in an `html` literal is escaped, so a `<` in a name prints as `<`.final class Pages{ // The home page: a form for the name and the room. public static function home(tainted string $name, string $room, ?string $problem): Markup { var $options = html``; foreach (Rooms::all() as string $slug => string $title) { $options = $options + ($slug == $room ? html`<option value="{$slug}" selected>{$title}</option>` : html`<option value="{$slug}">{$title}</option>`); } var $error = $problem == null ? html`` : html`<p class="problem">{$problem}</p>`; return Pages::layout('Chat', html`<h1>Chat</h1><form method="post" action="/join">{$error}<p><label>Your name <input name="name" value="{$name}" maxlength="20" required></label></p><p><label>Room <select name="room">{$options}</select></label></p><p><button>Join</button></p></form>`); }
// The page of one room. `data-socket` is the address of its WebSocket, and `chat.js` reads it. public static function room(string $room, tainted string $name, string $socket): Markup { string $title = Rooms::title($room); var $links = html``; foreach (Rooms::all() as string $slug => string $other) { if ($slug != $room) { string $href = Core\Router::url(App::room, ['room' => $slug]); $links = $links + html` <a href="{$href}">{$other}</a>`; } } return Pages::layout($title, html`<main data-socket="{$socket}"><h1>{$title}</h1><p class="status">You are <b>{$name}</b>. <span id="status">Connecting …</span> Other rooms:{$links}</p><ol id="lines"></ol><form id="say"><input name="text" maxlength="500" autocomplete="off" placeholder="Write a message" required><button>Send</button></form></main><script src="/chat.js" defer></script>`); }
// The page for a path that has no route, or for a room that does not exist. public static function notFound(): Markup { return Pages::problem('Not found', 'There is no page at this address.'); }
// A page with a title, one sentence and a link to the home page. public static function problem(string $title, string $text): Markup { return Pages::layout($title, html`<h1>{$title}</h1><p>{$text}</p><p><a href="/">Choose a room</a></p>`); }
private static function layout(string $title, Markup $content): Markup { return html`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{$title}</title><link rel="stylesheet" href="/style.css"></head><body>{$content}</body></html>`; }}<?nvsnamespace Chat;
// The chat rooms. A visitor can only join a room from this list.final class Rooms{ // The name of each room in the address, and the title that the page shows. public static function all(): array<string> { return ['lobby' => 'Lobby', 'help' => 'Help', 'random' => 'Random']; }
// Returns the room with this name, or `null` when there is no such room. // The result comes from the list above and not from the request, so it is not `tainted`. public static function find(tainted string $asked): ?string { foreach (Rooms::all() as string $room => string $title) { if ($room == $asked) { return $room; } } return null; }
// Returns the title of a room, such as `Lobby`. public static function title(string $room): string { return Rooms::all()[$room] ?? $room; }
// Returns the topic of a room. Every connection in the room subscribes to it. // A topic name cannot be `tainted`, so a visitor can never choose a topic. public static function topic(string $room): string { return 'room:' . $room; }}# Caddy in front of Chat. Copy this file to /etc/caddy/Caddyfile and write your own# host name in place of chat.example.com. Caddy gets the certificate from Let's Encrypt,# redirects HTTP to HTTPS, and speaks HTTP/2 and HTTP/3.{ servers { timeouts { # A client has 10 seconds to send the request headers, the same as Novis. read_header 10s } }}
chat.example.com { # The forms of Chat are small. A larger body gets the status 413. request_body { max_size 64KB }
# Caddy passes WebSocket requests to Novis without any setting. It sends the `Host` # unchanged and sets `X-Forwarded-For` and `X-Forwarded-Proto`. reverse_proxy 127.0.0.1:8144 { # With a Unix socket, write `reverse_proxy unix//run/chat/nvs.sock` in place of the address. transport http { # Shorter than the 75 seconds after which Novis closes an unused connection. keepalive 60s } }}# nginx in front of Chat. Copy this file to /etc/nginx/conf.d/chat.conf and write your own# host name in place of chat.example.com. The certificate paths are the ones of Let's Encrypt.
# Each client address may send 20 requests per second, with short bursts of up to 100.limit_req_zone $binary_remote_addr zone=chat:10m rate=20r/s;# Each client address may keep 20 connections open. Each open room page needs one.limit_conn_zone $binary_remote_addr zone=chat_conn:10m;
# A WebSocket request sends "Connection: upgrade" to Novis.# Every other request sends an empty value, so the connection to Novis stays open.map $http_upgrade $connection_upgrade { default upgrade; '' '';}
upstream chat { server 127.0.0.1:8144; # With a Unix socket, write this line in place of the line above: # server unix:/run/chat/nvs.sock;
# Keep up to 16 unused connections to Novis open for each nginx worker. keepalive 16; # Shorter than the 75 seconds after which Novis closes an unused connection. keepalive_timeout 60s;}
# Plain HTTP only redirects to HTTPS.server { listen 80; listen [::]:80; server_name chat.example.com; return 301 https://$host$request_uri;}
server { listen 443 ssl; listen [::]:443 ssl; http2 on; server_name chat.example.com; server_tokens off;
ssl_certificate /etc/letsencrypt/live/chat.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/chat.example.com/privkey.pem; ssl_protocols TLSv1.2 TLSv1.3;
# The forms of Chat are small. A larger body gets the status 413. client_max_body_size 64k; # The same limit as `header_timeout` in Novis. client_header_timeout 10s;
limit_req zone=chat burst=100 nodelay; limit_req_status 429; limit_conn chat_conn 20; limit_conn_status 429;
location / { proxy_pass http://chat; # A WebSocket starts from an HTTP/1.1 request, so nginx must speak HTTP/1.1 to Novis. proxy_http_version 1.1; # Novis compares the `Origin` of the browser with this host. Keep it unchanged. proxy_set_header Host $host; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; # nginx closes a connection that sends nothing for 60 seconds by default. # 6 minutes is longer than the 5 minutes after which Novis closes a quiet WebSocket. proxy_read_timeout 6m; proxy_send_timeout 6m; }}# The settings for a server on the internet, behind a proxy on the same machine.# Start the server with `--config nvs.toml --config deploy/production.toml`.# The server reads the two files in this order. Each setting below replaces the one from `nvs.toml`.
# Production mode. Error pages do not show the message of an error,# and the server sends no file and runs no `.nvs` file by its path.[mode]default = "production"
[server]# Only programs on this machine can connect. The reverse proxy is one of them.listen = ["127.0.0.1:8144"]# On Linux, a Unix socket is better. Write these two lines in place of `listen` above,# and add the account of the proxy to the group of the server:## listen = ["/run/chat/nvs.sock"]# socket_mode = "0660"
# The proxy connects from this address. Novis then reads `X-Forwarded-Proto` and# `X-Forwarded-For` from it. Without this line, every WebSocket gets the status 403,# because the `Origin` of the browser starts with `https` and Novis sees `http`.# Keep this line with a Unix socket too: an empty list reads no forwarded header.trusted_proxies = ["127.0.0.1"]
# The database is outside the folder of the app. The account of the service may write# here, and it does not need to write to the code of the app.[db.chat]path = "/var/lib/chat/chat.sqlite"
# The server opens only the database of the chat. The tests use `scratch`, and they do not run here.[capabilities.db]connect = ["chat"]
# A request and a WebSocket connection may each use at most 32 MB of memory.# `App::socket` gives each connection a lower limit of 8 MB.# A request may run for at most 30 seconds. This also ends the request that opens a WebSocket.# The connection stays open. `[server.connection] max_lifetime` closes it after one day.[limits]memory = "32M"wall_time = "30s"
# No program may raise its memory limit above 64 MB.[limits.hard]memory = "64M"# Chat
A chat app written in Novis. Visitors talk in rooms over a WebSocket, and each room keeps its lastlines in SQLite. The same server sends the pages and runs every WebSocket connection.
Run these commands in this folder:
```shnvs serve public/index.nvs # open http://127.0.0.1:8144/nvs test . # runs the tests```
In a clone of the repository, `bun nv app chat` starts the app from any folder.
The folder `deploy` has the production settings and the proxy files for Caddy and nginx. On aserver, start the app with both configuration files:
```shnvs serve public/index.nvs --config nvs.toml --config deploy/production.toml```
The page [Example apps: Chat](https://novis-lang.org/guides/example-apps/chat/) explains each fileand each step of the deploy.Get it running
Section titled “Get it running”Install Novis first. Then download only the folder apps/chat of the Novis
repository. A sparse clone (a clone that checks out only the folders you name) does this:
git clone --depth 1 --filter=blob:none --sparse https://github.com/novis-lang/novis.gitcd novisgit sparse-checkout set apps/chatcd apps/chatStart the server from the folder apps/chat:
nvs serve public/index.nvsOpen http://127.0.0.1:8144/, enter a name and join the lobby. Then open the same address in a
second browser, or in a private window, and join with another name. Each line you write in one
window appears at once in the other.
The first connection creates the file chat.sqlite in the same folder. The last lines of each room
are kept there, so they are still there after a restart.
Run the tests
Section titled “Run the tests”nvs test .nvs test . reads every .nvs file in the folder as one program and runs each #[Test] method:
Chat\AppTest ✓ theHomePageShowsTheForm 0.6 ms ✓ joiningWithoutANameShowsTheProblem 0.4 ms ✓ joiningStartsASessionAndOpensTheRoom 9.3 ms ✓ theRoomPageHasTheAddressOfItsSocket 56.1 ms ✓ aVisitorWithoutASessionGoesToTheForm 0.4 ms ✓ anUnknownRoomIsNotFound 3.0 ms ✓ aPageRequestToTheSocketGets426 40.7 ms ✓ theScriptAndTheStylesAreSent 0.6 ms ✓ thePagesMayLoadFilesOnlyFromThisServer 0.1 ms Chat\CheckTest ✓ aShortNameIsValid 0.1 ms ✓ anEmptyOrLongNameIsNotValid 0.1 ms ✓ onlyTheListedRoomsExist 0.1 ms ✓ aChatLineMustHaveText 0.2 ms ✓ theLimiterAllowsFiveLinesInTenSeconds 0.1 ms Chat\HistoryTest ✓ theNewestLinesComeInTheOrderTheyWereWritten 1.4 ms ✓ eachRoomHasItsOwnLines 1.3 ms ✓ aRoomKeepsItsNewest100Lines 7.1 ms Chat\LiveTest ✓ twoVisitorsTalkInOneRoom 59.3 ms ✓ aNewVisitorGetsTheHistory 34.3 ms ✓ aWrongMessageGetsAProblemOnlyForItsSender 16.4 ms ✓ aVisitorWhoSendsTooFastMustWait 28.7 ms ✓ aSocketFromAnotherWebsiteIsNotAllowed 62.4 ms
0 failed, 22 passed, 0 skipped, 0 flaky in 128 msThe tests in LiveTest open real WebSocket connections. #[Test(server: true)] starts a server
for each of these tests, and Core\Http\Client::openSocket connects to it the way a browser does.
Each test joins first, and sends the session cookie with its WebSocket request.
What each file does
Section titled “What each file does”chat/ nvs.toml the configuration: the port, the limits of a connection, the security policy and the databases deploy/ production.toml the settings for a server on the internet Caddyfile the configuration of Caddy, if Caddy is your proxy nginx.conf the configuration of nginx, if nginx is your proxy public/ index.nvs the entry file: every request starts here chat.js the browser script: opens the WebSocket and shows the messages style.css the styles of the pages src/ App.nvs the routes: one method for each kind of request AppTest.nvs sends requests to the app and checks the responses CheckTest.nvs tests the checks on names, rooms, lines and speed Connection.nvs the program of one WebSocket connection Gate.nvs decides which routes may run, and shows the error pages History.nvs saves the lines of each room in the database HistoryTest.nvs tests saving and reading lines Incoming.nvs a message from the browser, and the checks on it Limiter.nvs counts the lines of one connection Line.nvs one saved chat line LiveTest.nvs tests with real WebSocket connections Nickname.nvs the checks on a name Pages.nvs the HTML pages Rooms.nvs the list of rooms[server] listen in nvs.toml sets the port of the server to 8144. The other example apps use
other ports, so you can run them at the same time. [server.connection] sets two limits for each
WebSocket. A message from the browser may have at most 16 KB. A connection with no message for 5
minutes is closed.
[http.headers] sets a strict Content-Security-Policy. The browser may load scripts and styles
only from this server, and it may open connections only to this server. The pages have no inline
script, so the policy breaks nothing. If somebody finds a way to put HTML into a page, the browser
still runs no script from it.
src/App.nvs has one method for each route. App::join checks the form and saves the name in the
session. The browser gets only the random identifier of the session, in the cookie nvsid.
App::socket reads the name from the session, checks the room again, and calls
Core\Socket::upgrade.
The request ends, and the connection stays open. It runs Connection::run
in its own isolate (a separate copy of the program that shares no memory with the request). The
isolate gets the room and the name through arguments:, and nothing else from the request.
src/Connection.nvs is the program of one connection. It joins the topic of its room first. Then
it sends the last 50 lines of the room.
After that, one loop handles every message. receive() returns the next message from the browser
or from the room. topic() is null for a message from the browser, and it is the name of the
topic for a message from the room. When the visitor closes the page, receive() returns null,
and the connection tells the room that the visitor left.
src/Rooms.nvs has the list of rooms. The name of a room in the address is tainted, because it
comes from the request. Rooms::find returns the name from its own list, which is not tainted.
Only that name is used for the topic.
public/chat.js opens the WebSocket and shows each message. It writes text with textContent and
append, so no chat line can become HTML. When the connection breaks, the script waits and
connects again. The wait doubles each time, up to 30 seconds. Each minute, it sends a ping
message, so a quiet connection stays open.
App::script and App::style send chat.js and style.css. In development, nvs serve also
sends files from public by itself. A server in production mode sends no file by itself, so the
routes are needed there.
The messages
Section titled “The messages”Every message is JSON text. The browser sends two kinds:
| Message | What the server does |
|---|---|
{"kind": "say", "text": "Hello"} |
Checks the line, saves it and sends it to the room. |
{"kind": "ping"} |
Nothing. The message only keeps the connection open. |
The server sends five kinds:
| Message | When |
|---|---|
{"kind": "history", "lines": [...]} |
Once, when the connection opens: the last 50 lines of the room. |
{"kind": "line", "line": {"id": 7, "name": "Ana", "text": "Hello", "at": 1793000000000}} |
A visitor in the room wrote a line. at is the time in milliseconds since 1970. |
{"kind": "joined", "name": "Ana"} |
A visitor opened the room. |
{"kind": "left", "name": "Ana"} |
A visitor closed the room. |
{"kind": "problem", "text": "..."} |
The last message from this browser was not valid. Only this browser gets it. |
A line can arrive twice: in the history and as a line message. So each line has an id, and the
script skips a line whose id it already shows.
The routes
Section titled “The routes”| Method and path | What it does |
|---|---|
GET / |
Shows the form for the name and the room. |
POST /join |
Checks the form, saves the name in the session, then goes to the room. If the form is not valid, it shows the form again with the status 422. |
GET /rooms/{room} |
Shows the page of a room. Without a name in the session, it goes back to /. A room that does not exist gets the status 404. |
GET /rooms/{room}/socket |
Opens the WebSocket of the room. A normal page request gets the status 426. |
GET /chat.js |
Sends the browser script. |
GET /style.css |
Sends the styles. |
How a line reaches the room
Section titled “How a line reaches the room”These five steps send a chat line to the room:
- Ana’s browser sends
{"kind": "say", "text": "Hello"}on her WebSocket. - Ana’s connection checks the line, saves it, and calls
Topic::publish('room:lobby', ...). - Every connection in the lobby receives a copy, Ana’s own connection too.
- Each connection sends the line to its browser.
chat.jsin each browser adds the line to the page.
All five steps happen in one Novis process. Topic::publish returns at once and never waits for a
slow browser. The connection publishes the JSON text, so each connection only forwards it.
Each connection has a queue for the messages it has not sent yet. A browser that reads too slowly fills its queue. Novis then closes that one connection, and the other visitors are not affected. The script connects again and gets the history of the room.
Deploy it
Section titled “Deploy it”The folder deploy has the files for a server on the internet. On a Linux server, these steps put
the app at https://chat.example.com.
| File | What it does |
|---|---|
deploy/production.toml |
Changes the settings of nvs.toml for production: production mode, trusted_proxies, the database outside the folder of the code, and the limits. |
deploy/Caddyfile |
The proxy for Caddy. Caddy also gets the certificate. |
deploy/nginx.conf |
The proxy for nginx. |
Novis reads both configuration files when you name each with --config. It reads them in that order,
so each setting in production.toml replaces the one in nvs.toml. So nvs.toml stays the same on
your computer and on the server.
-
Copy the folder
chatto the server, for example to/srv/chat. Only an administrator should be able to change the files in it. -
Read
deploy/production.toml. It sets production mode, the address of the server, the address of the proxy, the memory limits and the path of the database. On Linux, a Unix socket is better than a port. The comments in the file show the two lines for it. -
Create the account
chatand the folder/var/lib/chat, and let only that account write to the folder. The database is kept there. -
Install the server as a service. It then starts at every boot, and again after a failure.
--account chatruns it as the accountchat. Run as a service explains each part of this command:Terminal window nvs service install chat --account chat -- serve /srv/chat/public/index.nvs --config /srv/chat/nvs.toml --config /srv/chat/deploy/production.toml -
Copy
deploy/Caddyfileordeploy/nginx.confto your proxy, and write your own host name in place ofchat.example.com.
production.toml sets wall_time to 30 seconds. This limit ends a request that runs too long. It
does not close a WebSocket connection, which stays open after its request ends. The memory limit,
the size limit of a message and the 5 minutes without a message bound each connection.
[server.connection] max_lifetime closes a connection after one day.
The proxy
Section titled “The proxy”A WebSocket starts as a normal GET request with the headers Upgrade: websocket and
Connection: Upgrade. The proxy must send both headers to Novis. Caddy does this by itself.
deploy/nginx.conf has the lines nginx needs:
proxy_http_version 1.1, because a WebSocket starts from an HTTP/1.1 request.- The
mapblock, which sendsConnection: upgradeonly for a WebSocket request. proxy_read_timeout 6m. By default, nginx closes a connection that sends nothing for 60 seconds. 6 minutes is longer than the 5 minutes of Novis, so Novis closes a quiet connection first.limit_conn, which counts each open room page as one connection.
Behind a reverse proxy explains the other settings.
Why trusted_proxies matters
Section titled “Why trusted_proxies matters”The browser sends the header Origin: https://chat.example.com with each WebSocket request. Novis
compares it with the scheme and the host of the request. The proxy ends HTTPS, so the request
reaches Novis over plain HTTP.
Novis reads X-Forwarded-Proto: https only from an address in trusted_proxies. Without that
line, Novis sees http. The two do not match, and every WebSocket gets the status 403. The proxy
must also send the Host header unchanged. Both proxy files do this.
Limits and security
Section titled “Limits and security”- Each connection has its own memory limit.
Socket::upgradegetslimits: { memory: '8M' }. A connection that needs more is closed, and the other connections keep running. - Each message has a size limit.
[server.connection] max_messageis 16 KB. A larger message closes the connection. - Each visitor has a speed limit.
Limiterallows 5 lines in 10 seconds. A faster visitor gets aproblemmessage, and the line is not sent. - Another website cannot open a connection. A browser sends cookies with a WebSocket request
from any page. So Novis checks the
Originheader first, and a request from another website gets the status403.LiveTesttests this. - A topic name never contains user input. The room in the address is
tainted, and a topic name that istaintedis not allowed.Rooms::findreturns a name from its own list. - The name stays on the server. The session has the name, and the cookie has only a random
identifier. A visitor cannot change the name by changing the cookie.
App::joingives the session a new identifier, as a login does. - The connection gets only what it needs. It gets the room and the name through
arguments:. It does not see the session, the cookies or the other headers of the request. - Two visitors can choose the same name. The chat has no accounts, so a name is not proof of a
person. For a real chat, add a login. Check it in
App::socket, and pass the id of the user to the connection througharguments:. - The browser loads files only from this server. The
Content-Security-Policyinnvs.tomlallows no inline script and no other host. - Topics work inside one process. All connections of a room must reach the same
nvs serve. If you run your app on several machines, send each line to the other machines in your own code. A message queue such as Redis or NATS can do this.
Start your own app from it
Section titled “Start your own app from it”- Copy the folder
apps/chatand give it the name of your app. - Choose a namespace for your app, for example
Support. Changenamespace Chat;in each file undersrc/, and theautoloadline andChat\Gateinpublic/index.nvs. - In
nvs.toml, rename the databasechatand its file. Change the name in[capabilities.db]and in the call toCore\Db::connectinsrc/History.nvs. - Change the port in
nvs.tomlanddeploy/production.toml, and the host name and the port in the two proxy files. - Use the same pattern for each live part of your app. An ordinary request checks who the visitor
is and calls
Socket::upgrade. The connection joins its topics, and one loop handles every message. - Run
nvs test .after each change.
When the server only sends updates and the browser only reads them, an event stream is simpler. The Poll app shows one.
Read more
Section titled “Read more”- Live updates explains when to use a WebSocket and when an event stream.
Core\Socket::upgradeexplains the connection and its options.Core\Socket::receiveexplains the loop of a connection.Core\Topic::publishexplains what happens to each subscriber.Core\Session::setShortLivedexplains how long a session keeps a value.- Security checklist lists what to check before the first request.
- Poll is a live poll with server-sent events.
