Explorar o código

Add native Cloudron Chat client

chat (ucmd_chat.c, top-bar Chat button) is an ngui client for Cloudron
Chat: channel/DM sidebar with unread badges and presence, a wrapped
timeline with avatars, day headers and reply snippets, sending with a
clientId, older paging, read markers, browse/join and new DM.  Updates
are REST polls (2 s conversation, 12 s directory) instead of the
WebSocket; keep-alive is only held while the window is focused and in
use, because an open socket pauses the netkexec watcher.

chat_login.c drives the Cloudron OIDC login API natively (login page
cloudron-config submitUrl, username/password/TOTP, consent) with a
pasted-cookie fallback for passkey/SSO accounts.  The password is never
stored; the session cookie goes to /share/chat.cfg.

Supporting changes: uhttp gains a cookie jar (uhttp_cookie.c), Accept
and extra headers, chunked request/body sends, longer URLs/header lines,
8 redirects and bodyless 1xx/204/304; ujson.c is an arena JSON parser;
ngui text fields gain secret masking, Tab NEXT and a 512-byte buffer.

Tests: make test-chat (host, ASan) and make test-chat-e2e (QEMU against
tools/mock_chat.py).

Co-Authored-By: Claude <noreply@anthropic.com>
Johannes Zellner hai 1 semana
pai
achega
e809ef0413
Modificáronse 26 ficheiros con 6063 adicións e 35 borrados
  1. 4 0
      .gitignore
  2. 65 5
      AGENTS.md
  3. 53 7
      Makefile
  4. 666 0
      chat_login.c
  5. 121 0
      chat_login.h
  6. 149 0
      chat_login_test.c
  7. 3 0
      docs/development.html
  8. 8 3
      docs/graphics.html
  9. 7 2
      docs/index.html
  10. 48 1
      docs/network.html
  11. 6 4
      docs/userland.html
  12. 42 0
      ngui.c
  13. 3 1
      ngui.h
  14. 492 0
      tools/mock_chat.py
  15. 406 0
      tools/qmp_chat_test.py
  16. 2502 0
      ucmd_chat.c
  17. 8 2
      ucmd_wm.c
  18. 58 6
      uhttp.c
  19. 12 4
      uhttp.h
  20. 423 0
      uhttp_cookie.c
  21. 62 0
      uhttp_cookie.h
  22. 154 0
      uhttp_cookie_test.c
  23. 519 0
      ujson.c
  24. 68 0
      ujson.h
  25. 177 0
      ujson_test.c
  26. 7 0
      wm_abi.h

+ 4 - 0
.gitignore

@@ -25,3 +25,7 @@ setjmp_test
 mujs_test
 third_party/mujs/*.o
 mkrootfs
+ujson_test
+uhttp_cookie_test
+chat_login_test
+chat-test-out/

+ 65 - 5
AGENTS.md

@@ -81,6 +81,8 @@ make test-mujs  # host smoke test for the vendored MuJS engine
 make test-font  # host TrueType parser/rasterizer specimen test
 make test-font-asan  # ASan/UBSan variant
 make test-touchpad  # host tests for the contact gesture engine
+make test-chat  # host tests: JSON parser, cookie jar, chat login parsers (ASan)
+make test-chat-e2e  # QEMU + tools/mock_chat.py chat end-to-end (CHAT_E2E=--totp...)
 make compat-serve  # serve the browser A/B ladder on port 8000
 make fonts      # regenerate fonts/*.ttf with pyftsubset + system fonts
 make clean
@@ -311,6 +313,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   The right-aligned date/time text is itself a click target: `draw_bar()`
   records its rectangle, the pointer highlights it, and a click spawns
   `/ramfs/bin/settime` (the `Clock` launcher still opens the analog clock).
+  The last launcher, `Chat`, spawns `/ramfs/bin/chat`; `WM_BTN_END_X`
+  (`wm_abi.h`) is the launchers' right edge, and the bar notice and the
+  right-aligned status never draw left of it.
   `terminal.c` keeps the privileged kernel command
   registry for the ring-3 terminal (`SYS_SPAWN_KCMD` / `term_kcmd_spawn`),
   but the kernel terminal entry/shell and the cell-window ABI are gone.
@@ -354,7 +359,11 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   Ctrl+Delete/Ctrl+Backspace word deletion and Ctrl+A select-all; typing or
   Backspace/Delete replaces a selection.  At the
   end of the line Ctrl+Delete removes the word before the caret instead of
-  doing nothing.
+  doing nothing.  A field with `secret` set is measured and painted from a
+  `*` mask (the real text is swapped back only for the edit loop, so caret,
+  selection and clicks follow the mask); Tab returns `NGUI_INPUT_NEXT` with
+  `NGUI_INPUT_CANCEL` so forms move the focus themselves.  `NGUI_INPUT_MAX`
+  is 512 (511 characters).
 - **Graphics**: `vga.c/h`, `vga_copy.S`, `blit.c/h`, `gpu.c`, `ati.c`, `nvidia.c`,
   `nv50.c`, `pci.h` — VESA LFB + shadow buffer.  Drawing goes into a
   `struct surface` render target: `vga_target()` is the screen's shadow buffer
@@ -843,8 +852,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   copy, then `BROWSER` on `root.img`/IDE/SATA fat mounts.  The launcher
   forwards its argument and cwd.
   `uhttp.c/h` is the shared ring-3 HTTP client extracted from curl: URL
-  parsing/resolution, redirects, chunked decoding, timeouts and TLS; curl and
-  the browser both use it.  `browser_html.c/h` is a tolerant HTML tree + the
+  parsing/resolution, redirects, chunked decoding, timeouts and TLS; curl,
+  the browser and chat use it.  `browser_html.c/h` is a tolerant HTML tree + the
   CSS subset: external `<link rel=stylesheet>` sheets (in document order,
   inline `<style>` last), tag/class/id and descendant/child selectors,
   colours/`rgba()`, legacy `bgcolor` attributes, solid backgrounds and
@@ -963,6 +972,43 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   loads FAT ELFs through `kmalloc` now (the old 16 KB `fat_load_buf` is gone)
   and wraps the load in `sys_fs_enter/exit`,
   since the floppy needs IRQ 6.
+- **Chat client**: `ucmd_chat.c` (`chat [config-path]`, top-bar `Chat`
+  button) is a native Cloudron Chat client on ngui: channel/DM sidebar with
+  unread badges, presence dots and previews; a timeline with initial-letter
+  avatars, author grouping, UTC times, day headers, reply snippets and an
+  attachments/thread/reaction line; a composer; browse/join and new-DM
+  pickers.  It talks to the Chat REST API (`/api/me`, `/api/channels`,
+  `/api/dms`, `/api/channels/public`, `/api/users`, messages with
+  `?limit=50`, `&before=` and `&after=`, POST messages with a `clientId`,
+  `/read`, `/join`, `/api/dms`) through one `struct uhttp` with a cookie
+  jar.  No WebSocket: the open conversation is polled every 2 s (5 s
+  unfocused), the directory every 12 s (20 s), polling waits 1 s after
+  input, and errors back off 2/5/10/30 s.  An open TCP socket pauses the
+  netkexec watcher (`tcp_client_count()`), so keep-alive is kept only while
+  the window is focused and the user was active in the last 30 s.  Up to
+  240 messages are held (Latin-1 bodies up to 4 KB via a UTF-8 mapping with
+  ASCII stand-ins for common typography/emoji); the response buffer is
+  512 KB and the JSON pool 16384 nodes, all from the libc heap.
+  `chat_login.c/h` is the native login: `GET /auth/login` (follows to the
+  Cloudron OIDC `/openid/interaction/<uid>` page), the page's
+  `cloudron-config` JSON `submitUrl`, `POST {"username","password",
+  "totpToken"}` (401 / `twoFactorRequired`+`totpRequired` / passkey-only /
+  `redirectTo`), then following `redirectTo` to `/auth/callback` (a consent
+  interaction is auto-confirmed) and validating with `/api/me`.  External
+  SSO and passkey accounts use the pasted-cookie screen.  The password is
+  wiped after each attempt and never stored; the Chat host's cookie header
+  and the server go to `/share/chat.cfg` (or the given path) and are
+  re-saved when the server rolls the cookie.  `uhttp_cookie.c/h` is the jar
+  (24 host-only cookies, Path prefix match, Secure, Max-Age/1970-Expires
+  deletion); uhttp stores every `Set-Cookie` (redirects too), sends matching
+  cookies on each hop, splits requests/bodies into 1024-byte TLS records or
+  MSS-sized TCP sends, takes `accept`/`extra_headers`, follows up to 8
+  redirects with 1 KB paths and 1.5 KB header lines, and treats 1xx/204/304
+  as bodyless.  `ujson.c/h` is the arena JSON DOM parser (caller-owned node
+  and string pools, \uXXXX/surrogates to UTF-8, depth 48).  Host tests:
+  `make test-chat`; `tools/mock_chat.py` mocks Chat + the OIDC provider on
+  two ports and `tools/qmp_chat_test.py` (`make test-chat-e2e`) drives the
+  app in QEMU.
 - **Image library + viewer**: `img.h`, `img.c`, `img_mem.c`, `img_blit.c`,
   `img_png.c`, `img_bmp.c`, `img_gif.c`, `img_jpeg.c`, `img_tga.c`,
   `img_pnm.c`, `img_file.c/h` — freestanding RGB565 decoders with an optional
@@ -1037,7 +1083,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`,
 `display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `touchpad [rightclick off|tap|corner|both] [tapclick on|off] [scroll on|off|natural|traditional]`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `meminfo`, `top`, `sched`, `format <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk), `install <target> [source]` (clone the live image; auto-detects the source, preferring `usb0`),
-`ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [auto|hlt|c1e|c3|c6]`, `power`, `powerinfo`, `cpufreq [auto|min|max|off|<pstate>]`, `spin [ms]`, `help`, `clear`, `serial test`, `kexec`, `dbg`, `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), and `browser [url|file]` (disk app launcher).
+`ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [auto|hlt|c1e|c3|c6]`, `power`, `powerinfo`, `cpufreq [auto|min|max|off|<pstate>]`, `spin [ms]`, `help`, `clear`, `serial test`, `kexec`, `dbg`, `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), `browser [url|file]` (disk app launcher), and `chat [config-path]` (Cloudron Chat client).
 
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
 DHCP client), `netdev [name]` (kernel command: show the active NIC driver or
@@ -1068,7 +1114,7 @@ nested). `/` is the read-only VFS root listing the mounted filesystems (the
 filesystem commands operate inside a mount, e.g. `cat /floppy1/HELLO.TXT`).
 
 `cpuinfo`, `ls`, `cat`, `save`, `rm`, `mkdir`, `rmdir`, `meminfo`, `top`, `spin`,
-`clock`, `colors`, `settime`, `date`, `files`, `gallery`, `view`, `sensors`, `powerinfo`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
+`clock`, `colors`, `settime`, `date`, `files`, `gallery`, `chat`, `view`, `sensors`, `powerinfo`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
 `pong`, `netsend`, `netrecv`, `netlog`, `netconsole`, `netregs`, `netloop`,
 `netreset`, `websrv`, `curl`, `solitaire` and `hello` are files in `/ramfs/bin`
 (packed by the Makefile), found through the shell's PATH; the rest are kernel
@@ -1814,3 +1860,17 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     armed bulk-IN transfer, so kexec relies on the next USB controller reset.
     QEMU's `usb-net` is full-speed, so `make run-rndis` exercises full-speed
     bulk on xHCI rather than the phone's high-speed path.
+
+34. Chat client limits (`ucmd_chat.c`): REST polling instead of the
+    WebSocket, so new messages appear within ~2 s, there are no typing
+    indicators, and other clients see the NebOS user as offline (presence is
+    WebSocket-driven).  Native login covers Cloudron username/password +
+    TOTP; passkeys and external SSO need the pasted `connect.sid` cookie.
+    The login depends on Cloudron's `cloudron-config` login API
+    (`chat_login.c` isolates it).  TLS is not verified (the login screen
+    says so), and the saved cookie in `/share/chat.cfg` is a bearer
+    credential (RAM-only unless a FAT path is chosen; concurrent chat
+    windows share the file).  No threads, reactions, polls, search,
+    attachments/images/GIFs, edits or deletes beyond what a reload shows;
+    messages over 4 KB are truncated, history holds 240 messages, times are
+    UTC and text is Latin-1.  Network calls block the UI for their duration.

+ 53 - 7
Makefile

@@ -66,7 +66,7 @@ EFI_LDFLAGS = -nostdlib -Wl,--subsystem,10 -Wl,-e,efi_main \
               -Wl,--image-base,0x0 -Wl,--dynamicbase \
               -Wl,--enable-reloc-section -Wl,--no-insert-timestamp
 
-.PHONY: all clean run run-smp run-floppy run-usb run-uhci run-ehci run-ehci-asix run-xhci run-xhci-asix run-net run-rndis run-e1000 run-ahci test-usb test-install run-serial floppy usb uefi run-uefi test-uefi flash dev net-dev cmds-dev net-cmds browser-dev gallery-dev compat-serve netmon monitor test-crypto test-images test-images-asan test-libc test-font test-font-asan test-touchpad fonts kernel-dev kernel-net-dev rootfs
+.PHONY: all clean run run-smp run-floppy run-usb run-uhci run-ehci run-ehci-asix run-xhci run-xhci-asix run-net run-rndis run-e1000 run-ahci test-usb test-install run-serial floppy usb uefi run-uefi test-uefi flash dev net-dev cmds-dev net-cmds browser-dev gallery-dev compat-serve netmon monitor test-crypto test-images test-images-asan test-libc test-font test-font-asan test-touchpad test-chat test-chat-e2e fonts kernel-dev kernel-net-dev rootfs
 
 all: floppy.img usb.img final.bin root.img
 
@@ -605,7 +605,7 @@ UCMDS = ucmd_cpuinfo ucmd_ls ucmd_cat ucmd_save ucmd_rm ucmd_mkdir ucmd_rmdir \
         ucmd_netsend ucmd_netrecv ucmd_ping ucmd_pong ucmd_netlog \
         ucmd_netconsole ucmd_netregs ucmd_netloop ucmd_netreset ucmd_net100 ucmd_netmac ucmd_curl \
         ucmd_files ucmd_view ucmd_sensors ucmd_powerinfo ucmd_mines ucmd_solitaire \
-        ucmd_settime ucmd_date ucmd_gallery ucmd_websrv ucmd_browser
+        ucmd_settime ucmd_date ucmd_gallery ucmd_websrv ucmd_browser ucmd_chat
 
 # Keep the linked ELFs around (make would treat them as disposable
 # intermediates between the pattern rules).
@@ -762,14 +762,60 @@ ucmd_view.elf: ucmd_view.o $(IMGLIB_OBJS) inflate.o ngui.o font_8x16.o $(UFONT_O
 # the host (make test-crypto).
 TLSLIB_OBJS = tls_sha256.o tls_chacha20.o tls_x25519.o tls_rng.o tls.o
 
-# Shared ring-3 HTTP/TLS client (curl and the browser).
-uhttp.o: uhttp.c uhttp.h ucmd_lib.h tls.h
+# Shared ring-3 HTTP/TLS client (curl, the browser and chat).  The cookie
+# jar and the JSON parser are pure C with host tests (make test-chat).
+uhttp.o: uhttp.c uhttp.h uhttp_cookie.h ucmd_lib.h tls.h
 	$(CC) $(CFLAGS) $(SECTION_CFLAGS) -o $@ $<
 
-ucmd_curl.elf: ucmd_curl.o uhttp.o $(TLSLIB_OBJS) ucmd.ld libc.a
+uhttp_cookie.o: uhttp_cookie.c uhttp_cookie.h
+	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -o $@ $<
+
+ujson.o: ujson.c ujson.h
+	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -o $@ $<
+
+# curl embeds struct uhttp, so it rebuilds when the header changes.
+ucmd_curl.o: uhttp.h uhttp_cookie.h
+
+ucmd_curl.elf: ucmd_curl.o uhttp.o uhttp_cookie.o $(TLSLIB_OBJS) ucmd.ld libc.a
 	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
+# chat: native Cloudron Chat client (ngui + uhttp/TLS + cookie jar + JSON +
+# the native OIDC login driver).
+chat_login.o: chat_login.c chat_login.h ujson.h uhttp.h uhttp_cookie.h ucmd_lib.h
+	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -o $@ $<
+
+ucmd_chat.o: ucmd_chat.c ucmd_lib.h syscall.h wm_abi.h ngui.h uhttp.h uhttp_cookie.h ujson.h chat_login.h $(LIBC_HEADERS)
+	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -Ilibc/include -o $@ $<
+
+ucmd_chat.elf: ucmd_chat.o chat_login.o ujson.o uhttp.o uhttp_cookie.o ngui.o font_8x16.o $(UFONT_OBJS) $(TLSLIB_OBJS) ucmd.ld libc.a
+	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
+	$(OBJCOPY) --strip-all $@ $@
+
+# Host tests for the chat client's pure modules: JSON, cookie jar and the
+# login page/reply/config parsers.
+CHAT_TEST_CFLAGS = -O1 -g -Wall -Wextra -fsanitize=address,undefined -I.
+ujson_test: ujson_test.c ujson.c ujson.h
+	gcc $(CHAT_TEST_CFLAGS) -o $@ ujson_test.c ujson.c
+
+uhttp_cookie_test: uhttp_cookie_test.c uhttp_cookie.c uhttp_cookie.h
+	gcc $(CHAT_TEST_CFLAGS) -o $@ uhttp_cookie_test.c uhttp_cookie.c
+
+chat_login_test: chat_login_test.c chat_login.c chat_login.h ujson.c ujson.h
+	gcc $(CHAT_TEST_CFLAGS) -DCHAT_LOGIN_PURE -o $@ chat_login_test.c chat_login.c ujson.c
+
+test-chat: ujson_test uhttp_cookie_test chat_login_test
+	./ujson_test
+	./uhttp_cookie_test
+	./chat_login_test
+
+# QEMU end-to-end chat test against tools/mock_chat.py (ports 18080/18081 on
+# the host, 10.0.2.2 in the guest).  CHAT_E2E=--totp|--consent|--passkey|
+# --wrong selects a login variant; screenshots land in chat-test-out/.
+CHAT_E2E ?=
+test-chat-e2e: floppy.img root.img
+	python3 tools/qmp_chat_test.py $(CHAT_E2E)
+
 # browser: the real app is a disk image (BROWSER) because it links ngui, the
 # image library, TLS and uhttp.  ucmd_browser.c is the tiny PATH launcher.
 # Compile this graph with function sections and link it with --gc-sections:
@@ -790,7 +836,7 @@ js_browser.o: js_browser.c js_browser.h browser_html.h ucmd_lib.h syscall.h \
 browser.o: browser.c ucmd_lib.h syscall.h wm_abi.h ngui.h browser_html.h js_browser.h uhttp.h img.h inflate.h $(LIBC_HEADERS)
 	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -Ilibc/include -o $@ $<
 
-browser.elf: browser.o browser_html.o js_browser.o uhttp.o ngui.o font_8x16.o $(UFONT_OBJS) $(IMGLIB_OBJS) inflate.o $(TLSLIB_OBJS) $(MUJS_OBJS) ucmd.ld libc.a
+browser.elf: browser.o browser_html.o js_browser.o uhttp.o uhttp_cookie.o ngui.o font_8x16.o $(UFONT_OBJS) $(IMGLIB_OBJS) inflate.o $(TLSLIB_OBJS) $(MUJS_OBJS) ucmd.ld libc.a
 	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
@@ -1208,4 +1254,4 @@ kernel-net-dev: kernel.bin netkexec_send
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 
 clean:
-	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o disk.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o ec.o cros_ec.o power_src.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o touchpad_gesture.o uhci.o ohci.o ehci.o xhci.o asix.o rndis.o usb.o usbmsc.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o sdhci.o ata.o ahci.o fatdetect.o fatformat.o format.o install.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netcore.o netkexec.o netlog.o dhcp.o dns.o ntp.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img hello.elf cmds.pack cmds_pack_gz.bin cmds_pack.o rootfs.bin cmds.img mkrootfs ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o browser.o browser_html.o uhttp.o browser.elf img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) gallery.o gallery.elf $(TLSLIB_OBJS) tls_test kexec_send netkexec_send netmonitor BOOTX64.EFI esp.img usb-efi.img efi/main.o efi/payload.o efi/tramp.o efi/tramp.elf efi/tramp.bin efi/efi_entry.h libc.a libc/*.o malloc_test format_test math_test div64_test setjmp_test mujs_test js_browser.o $(MUJS_DIR)/mujs.o ufont.o ufont_ttf.o ufont_draw.o ufont_file.o ufont_test ufont_test_asan touchpad_gesture_test
+	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o disk.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o ec.o cros_ec.o power_src.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o touchpad_gesture.o uhci.o ohci.o ehci.o xhci.o asix.o rndis.o usb.o usbmsc.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o sdhci.o ata.o ahci.o fatdetect.o fatformat.o format.o install.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netcore.o netkexec.o netlog.o dhcp.o dns.o ntp.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img hello.elf cmds.pack cmds_pack_gz.bin cmds_pack.o rootfs.bin cmds.img mkrootfs ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o browser.o browser_html.o uhttp.o browser.elf img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) gallery.o gallery.elf $(TLSLIB_OBJS) tls_test kexec_send netkexec_send netmonitor BOOTX64.EFI esp.img usb-efi.img efi/main.o efi/payload.o efi/tramp.o efi/tramp.elf efi/tramp.bin efi/efi_entry.h libc.a libc/*.o malloc_test format_test math_test div64_test setjmp_test mujs_test js_browser.o $(MUJS_DIR)/mujs.o ufont.o ufont_ttf.o ufont_draw.o ufont_file.o ufont_test ufont_test_asan touchpad_gesture_test ujson_test uhttp_cookie_test chat_login_test chat_login.o ujson.o uhttp_cookie.o

+ 666 - 0
chat_login.c

@@ -0,0 +1,666 @@
+/* chat_login: see chat_login.h. */
+
+#include "chat_login.h"
+
+/* ---- small string helpers (no libc: also built on the host) ---- */
+
+static unsigned int c_len(const char *s)
+{
+	unsigned int n = 0;
+
+	while (s && s[n])
+		n++;
+	return n;
+}
+
+static void c_copy(char *d, const char *s, unsigned int cap)
+{
+	unsigned int i = 0;
+
+	if (!cap)
+		return;
+	while (s && s[i] && i + 1 < cap) {
+		d[i] = s[i];
+		i++;
+	}
+	d[i] = '\0';
+}
+
+static int c_prefix(const char *s, const char *p)
+{
+	while (*p) {
+		if (*s != *p)
+			return 0;
+		s++;
+		p++;
+	}
+	return 1;
+}
+
+static int __attribute__((unused)) c_suffix(const char *s, const char *suf)
+{
+	unsigned int a = c_len(s), b = c_len(suf), i;
+
+	if (b > a)
+		return 0;
+	for (i = 0; i < b; i++)
+		if (s[a - b + i] != suf[i])
+			return 0;
+	return 1;
+}
+
+/* Find needle in hay[0..len); index or -1. */
+static int c_find(const char *hay, unsigned int len, const char *needle,
+		  unsigned int from)
+{
+	unsigned int n = c_len(needle), i, j;
+
+	if (!n || n > len)
+		return -1;
+	for (i = from; i + n <= len; i++) {
+		for (j = 0; j < n; j++)
+			if (hay[i + j] != needle[j])
+				break;
+		if (j == n)
+			return (int)i;
+	}
+	return -1;
+}
+
+/* ---- server URL / config file ---- */
+
+int chat_server_normalize(const char *in, char *out, unsigned int cap)
+{
+	unsigned int n = 0, i = 0, len;
+
+	while (in[i] == ' ' || in[i] == '\t')
+		i++;
+	if (!c_prefix(in + i, "https://") && !c_prefix(in + i, "http://")) {
+		const char *pre = "https://";
+
+		while (*pre && n + 1 < cap)
+			out[n++] = *pre++;
+	}
+	while (in[i] && in[i] != ' ' && in[i] != '\t' && n + 1 < cap)
+		out[n++] = in[i++];
+	out[n] = '\0';
+	if (in[i] && in[i] != ' ' && in[i] != '\t')
+		return -1;              /* did not fit */
+	while (in[i] == ' ' || in[i] == '\t')
+		i++;
+	if (in[i])
+		return -1;              /* embedded space */
+	while (n > 0 && out[n - 1] == '/')
+		out[--n] = '\0';
+	len = n;
+	/* need a host after the scheme */
+	if (c_prefix(out, "https://"))
+		return len > 8 ? 0 : -1;
+	return len > 7 ? 0 : -1;
+}
+
+int chat_config_parse(const char *text, unsigned int len, char *server,
+		      unsigned int scap, char *cookie, unsigned int ccap)
+{
+	unsigned int i = 0;
+	int found = 0;
+
+	if (scap)
+		server[0] = '\0';
+	if (ccap)
+		cookie[0] = '\0';
+	while (i < len) {
+		unsigned int s = i, e, k;
+		char *dst = 0;
+		unsigned int cap = 0;
+
+		while (i < len && text[i] != '\n')
+			i++;
+		e = i;
+		if (i < len)
+			i++;
+		while (e > s && (text[e - 1] == '\r' || text[e - 1] == ' '))
+			e--;
+		while (s < e && (text[s] == ' ' || text[s] == '\t'))
+			s++;
+		if (s == e || text[s] == '#')
+			continue;
+		if (e - s > 7 && c_prefix(text + s, "server=")) {
+			dst = server;
+			cap = scap;
+			s += 7;
+		} else if (e - s > 7 && c_prefix(text + s, "cookie=")) {
+			dst = cookie;
+			cap = ccap;
+			s += 7;
+		}
+		if (!dst || !cap)
+			continue;
+		for (k = 0; s + k < e && k + 1 < cap; k++)
+			dst[k] = text[s + k];
+		dst[k] = '\0';
+		found = 1;
+	}
+	return found ? 0 : -1;
+}
+
+int chat_config_format(char *out, unsigned int cap, const char *server,
+		       const char *cookie)
+{
+	unsigned int n = 0;
+
+#define APP(s) do { const char *ap = (s); \
+	while (*ap) { if (n + 1 >= cap) return -1; out[n++] = *ap++; } } while (0)
+	APP("# NebOS chat session (the cookie is a bearer credential)\n");
+	APP("server=");
+	APP(server);
+	APP("\n");
+	if (cookie && cookie[0]) {
+		APP("cookie=");
+		APP(cookie);
+		APP("\n");
+	}
+#undef APP
+	out[n] = '\0';
+	return (int)n;
+}
+
+int chat_login_body(char *out, unsigned int cap, const char *user,
+		    const char *pass, const char *totp)
+{
+	unsigned int n = 0;
+	int r;
+
+#define LIT(s) do { const char *ap = (s); \
+	while (*ap) { if (n + 1 >= cap) return -1; out[n++] = *ap++; } } while (0)
+#define STR(s) do { \
+		r = ujson_escape(out + n, cap - n, (s)); \
+		if (r < 0) \
+			return -1; \
+		n += (unsigned int)r; \
+	} while (0)
+	LIT("{\"username\":");
+	STR(user);
+	LIT(",\"password\":");
+	STR(pass);
+	LIT(",\"totpToken\":");
+	STR(totp ? totp : "");
+	LIT("}");
+#undef LIT
+#undef STR
+	out[n] = '\0';
+	return (int)n;
+}
+
+/* ---- page / reply parsing ---- */
+
+static struct ujson_node pnodes[512];
+static char psbuf[8192];
+
+/* Resolve href against an absolute base URL.  Handles absolute URLs,
+ * scheme-relative, absolute-path and directory-relative references. */
+static int resolve(const char *base, const char *href, char *out,
+		   unsigned int cap)
+{
+	unsigned int n = 0, i, origin_end, dir_end;
+
+	if (c_prefix(href, "http://") || c_prefix(href, "https://")) {
+		if (c_len(href) + 1 > cap)
+			return -1;
+		c_copy(out, href, cap);
+		return 0;
+	}
+	/* origin = scheme://host[:port] */
+	i = 0;
+	while (base[i] && base[i] != ':')
+		i++;
+	if (base[i] != ':' || base[i + 1] != '/' || base[i + 2] != '/')
+		return -1;
+	if (href[0] == '/' && href[1] == '/') {
+		if (i + 1 + c_len(href) + 1 > cap)
+			return -1;
+		for (n = 0; n <= i; n++)
+			out[n] = base[n];
+		c_copy(out + n, href, cap - n);
+		return 0;
+	}
+	i += 3;
+	while (base[i] && base[i] != '/' && base[i] != '?' && base[i] != '#')
+		i++;
+	origin_end = i;
+	dir_end = origin_end;
+	while (base[i] && base[i] != '?' && base[i] != '#') {
+		if (base[i] == '/')
+			dir_end = i;
+		i++;
+	}
+	if (href[0] == '/') {
+		if (origin_end + c_len(href) + 1 > cap)
+			return -1;
+		for (n = 0; n < origin_end; n++)
+			out[n] = base[n];
+		c_copy(out + n, href, cap - n);
+		return 0;
+	}
+	if (dir_end + 1 + c_len(href) + 1 > cap)
+		return -1;
+	for (n = 0; n < dir_end; n++)
+		out[n] = base[n];
+	out[n++] = '/';
+	c_copy(out + n, href, cap - n);
+	return 0;
+}
+
+int chat_login_parse_page(const char *html, unsigned int len,
+			  const char *base_url, char *submit_url,
+			  unsigned int cap, char *app_name,
+			  unsigned int name_cap)
+{
+	struct ujson j;
+	char raw[1024];
+	int at, s, e, root;
+
+	submit_url[0] = '\0';
+	if (name_cap)
+		app_name[0] = '\0';
+	raw[0] = '\0';
+	at = c_find(html, len, "id=\"cloudron-config\"", 0);
+	if (at >= 0) {
+		s = c_find(html, len, ">", (unsigned int)at);
+		e = s >= 0 ? c_find(html, len, "</script", (unsigned int)s) : -1;
+		if (s >= 0 && e > s) {
+			ujson_init(&j, pnodes, sizeof(pnodes) / sizeof(pnodes[0]),
+				   psbuf, sizeof(psbuf));
+			root = ujson_parse(&j, html + s + 1,
+					   (unsigned int)(e - s - 1));
+			if (root >= 0) {
+				c_copy(raw, ujson_get_str(&j, root, "submitUrl"),
+				       sizeof(raw));
+				if (name_cap)
+					c_copy(app_name,
+					       ujson_get_str(&j, root, "name"),
+					       name_cap);
+			}
+		}
+	}
+	if (!raw[0]) {
+		/* Fallback: a plain scan, unescaping \/ only. */
+		at = c_find(html, len, "\"submitUrl\":\"", 0);
+		if (at >= 0) {
+			unsigned int i = (unsigned int)at + 13, k = 0;
+
+			while (i < len && html[i] != '"' && k + 1 < sizeof(raw)) {
+				if (html[i] == '\\' && i + 1 < len)
+					i++;
+				raw[k++] = html[i++];
+			}
+			raw[k] = '\0';
+			if (i >= len || html[i] != '"')
+				raw[0] = '\0';
+		}
+	}
+	if (!raw[0])
+		return -1;
+	return resolve(base_url, raw, submit_url, cap);
+}
+
+int chat_login_parse_reply(int status, const char *body, unsigned int len,
+			   char *redirect, unsigned int rcap, char *msg,
+			   unsigned int mcap)
+{
+	struct ujson j;
+	int root;
+
+	if (rcap)
+		redirect[0] = '\0';
+	if (mcap)
+		msg[0] = '\0';
+	ujson_init(&j, pnodes, sizeof(pnodes) / sizeof(pnodes[0]), psbuf,
+		   sizeof(psbuf));
+	root = ujson_parse(&j, body, len);
+	if (root >= 0 && ujson_type(&j, root) == UJSON_OBJECT) {
+		const char *m = ujson_get_str(&j, root, "message");
+
+		if (!m[0])
+			m = ujson_get_str(&j, root, "error");
+		c_copy(msg, m, mcap);
+	}
+	if (status == 401 || status == 403)
+		return CHAT_REPLY_DENIED;
+	if (status != 200 || root < 0 || ujson_type(&j, root) != UJSON_OBJECT)
+		return CHAT_REPLY_ERROR;
+	if (ujson_truthy(&j, ujson_get(&j, root, "twoFactorRequired"))) {
+		if (ujson_truthy(&j, ujson_get(&j, root, "totpRequired")))
+			return CHAT_REPLY_TOTP;
+		return CHAT_REPLY_PASSKEY;
+	}
+	c_copy(redirect, ujson_get_str(&j, root, "redirectTo"), rcap);
+	if (!redirect[0])
+		return CHAT_REPLY_ERROR;
+	return CHAT_REPLY_REDIRECT;
+}
+
+#ifndef CHAT_LOGIN_PURE
+
+/* ---- HTTP helpers ---- */
+
+int chat_http_body(struct uhttp *h, char *buf, unsigned int cap)
+{
+	unsigned int n = 0;
+
+	for (;;) {
+		int r;
+
+		if (n + 1 >= cap) {
+			char scratch[1];
+
+			/* Full: is there more? */
+			r = uhttp_read(h, scratch, 1, UHTTP_IDLE_TIMEOUT_MS);
+			buf[n] = '\0';
+			if (r > 0) {
+				h->keepalive = 0;
+				uhttp_close(h);
+				return UHTTP_ERR_TOOLONG;
+			}
+			break;
+		}
+		r = uhttp_read(h, buf + n, cap - 1 - n, UHTTP_IDLE_TIMEOUT_MS);
+		if (r < 0) {
+			buf[n] = '\0';
+			h->keepalive = 0;
+			uhttp_close(h);
+			return r;
+		}
+		if (r == 0)
+			break;
+		n += (unsigned int)r;
+	}
+	buf[n] = '\0';
+	uhttp_close(h);
+	return (int)n;
+}
+
+int chat_http(struct uhttp *h, const char *method, const char *url,
+	      const char *json, char *buf, unsigned int cap,
+	      unsigned int *blen)
+{
+	int r;
+
+	if (blen)
+		*blen = 0;
+	h->keepalive = 1;
+	if (method && json)
+		uhttp_set_method(h, method, json, c_len(json),
+				 "application/json");
+	else if (method)
+		/* uhttp only sends Content-Length with a body, so a bodyless
+		 * POST carries an empty JSON object instead. */
+		uhttp_set_method(h, method, "{}", 2, "application/json");
+	else
+		uhttp_set_method(h, 0, 0, 0, 0);
+	r = uhttp_open(h, url, 0, 0);
+	if (r != 0)
+		return r;
+	r = chat_http_body(h, buf, cap);
+	if (r < 0)
+		return r;
+	if (blen)
+		*blen = (unsigned int)r;
+	return h->resp.status;
+}
+
+int chat_server_host(const char *server, char *host, unsigned int cap,
+		     int *secure)
+{
+	struct uhttp_url u;
+
+	if (uhttp_parse_url(server, &u) != 0)
+		return -1;
+	c_copy(host, u.host, cap);
+	if (secure)
+		*secure = u.secure;
+	return 0;
+}
+
+static void set_err(struct chat_login *l, const char *a, const char *b)
+{
+	unsigned int n = 0;
+
+	while (a && *a && n + 1 < sizeof(l->error))
+		l->error[n++] = *a++;
+	while (b && *b && n + 1 < sizeof(l->error))
+		l->error[n++] = *b++;
+	l->error[n] = '\0';
+}
+
+/* 1 when the response that ended at final_url is back on the Chat host. */
+static int on_server(const struct chat_login *l, const char *final_url)
+{
+	unsigned int n = c_len(l->server);
+	unsigned int i;
+
+	for (i = 0; i < n; i++)
+		if (final_url[i] != l->server[i])
+			return 0;
+	return final_url[n] == '\0' || final_url[n] == '/' ||
+	       final_url[n] == '?';
+}
+
+int chat_session_check(struct uhttp *h, struct uhttp_jar *jar,
+		       const char *server, char *buf, unsigned int cap,
+		       unsigned int *blen)
+{
+	char url[CHAT_SERVER_MAX + 16];
+	int st;
+
+	c_copy(url, server, sizeof(url));
+	c_copy(url + c_len(url), "/api/me", sizeof(url) - c_len(url));
+	h->jar = jar;
+	h->accept = "application/json";
+	st = chat_http(h, 0, url, 0, buf, cap, blen);
+	if (st == 200)
+		return 0;
+	if (st == 401 || st == 403)
+		return 1;
+	if (st > 0)
+		return -100 - st;
+	return st;
+}
+
+/* After a successful submit (or an existing provider session) the page may
+ * still be an interaction: a consent prompt (auto-confirmed, like the web
+ * UI does) or an abort page (no access to the app). */
+static int finish(struct chat_login *l, struct uhttp *h,
+		  struct uhttp_jar *jar, const char *url, char *buf,
+		  unsigned int cap)
+{
+	unsigned int len;
+	int st, round;
+	const char *method = 0;
+
+	c_copy(l->redirect, url, sizeof(l->redirect));
+	for (round = 0; round < 3; round++) {
+		h->jar = jar;
+		h->accept = "text/html,application/json,*/*";
+		st = chat_http(h, method, l->redirect, 0, buf, cap, &len);
+		if (st < 0) {
+			set_err(l, "Login redirect failed: ",
+				uhttp_error_string(st));
+			return CHAT_LOGIN_ERROR;
+		}
+		if (on_server(l, h->resp.final_url)) {
+			unsigned int me_len;
+
+			if (c_find(h->resp.final_url,
+				   c_len(h->resp.final_url),
+				   "error=auth_failed", 0) >= 0) {
+				set_err(l, "The Chat server rejected the login "
+					"(auth_failed)", 0);
+				return CHAT_LOGIN_ERROR;
+			}
+			st = chat_session_check(h, jar, l->server, buf, cap,
+						&me_len);
+			if (st == 0)
+				return CHAT_LOGIN_OK;
+			set_err(l, st == 1 ? "Signed in, but the Chat session "
+				"was not accepted" : "Session check failed", 0);
+			return CHAT_LOGIN_ERROR;
+		}
+		if (chat_login_parse_page(buf, len, h->resp.final_url,
+					  l->submit_url,
+					  sizeof(l->submit_url), l->app_name,
+					  sizeof(l->app_name)) != 0) {
+			set_err(l, "Login did not return to the Chat server", 0);
+			return CHAT_LOGIN_ERROR;
+		}
+		if (c_suffix(l->submit_url, "/confirm")) {
+			c_copy(l->redirect, l->submit_url, sizeof(l->redirect));
+			method = "POST";
+			continue;
+		}
+		if (c_suffix(l->submit_url, "/abort")) {
+			set_err(l, "This account has no access to the Chat app",
+				0);
+			return CHAT_LOGIN_ERROR;
+		}
+		/* Back at a login form: the provider wants credentials. */
+		return CHAT_LOGIN_FORM;
+	}
+	set_err(l, "Too many login interaction steps", 0);
+	return CHAT_LOGIN_ERROR;
+}
+
+int chat_login_start(struct chat_login *l, struct uhttp *h,
+		     struct uhttp_jar *jar, const char *server, char *buf,
+		     unsigned int cap)
+{
+	char url[CHAT_SERVER_MAX + 16];
+	unsigned int len;
+	int st;
+
+	l->error[0] = '\0';
+	l->submit_url[0] = '\0';
+	l->app_name[0] = '\0';
+	l->totp_required = 0;
+	if (chat_server_normalize(server, l->server, sizeof(l->server)) != 0) {
+		set_err(l, "Invalid server address", 0);
+		return CHAT_LOGIN_ERROR;
+	}
+	c_copy(url, l->server, sizeof(url));
+	c_copy(url + c_len(url), "/auth/login", sizeof(url) - c_len(url));
+	h->jar = jar;
+	h->accept = "text/html,*/*";
+	st = chat_http(h, 0, url, 0, buf, cap, &len);
+	if (st < 0) {
+		set_err(l, "Cannot reach the server: ", uhttp_error_string(st));
+		return CHAT_LOGIN_ERROR;
+	}
+	if (on_server(l, h->resp.final_url) && st == 200) {
+		/* The provider already knew us and sent us straight back. */
+		unsigned int me_len;
+
+		if (chat_session_check(h, jar, l->server, buf, cap,
+				       &me_len) == 0)
+			return CHAT_LOGIN_OK;
+	}
+	if (st != 200) {
+		char code[8];
+		unsigned int v = (unsigned int)st, k = 0, i;
+		char tmp[8];
+
+		while (v && k < sizeof(tmp)) {
+			tmp[k++] = (char)('0' + v % 10);
+			v /= 10;
+		}
+		for (i = 0; i < k; i++)
+			code[i] = tmp[k - 1 - i];
+		code[k] = '\0';
+		set_err(l, "Login page returned HTTP ", code);
+		return CHAT_LOGIN_ERROR;
+	}
+	if (chat_login_parse_page(buf, len, h->resp.final_url, l->submit_url,
+				  sizeof(l->submit_url), l->app_name,
+				  sizeof(l->app_name)) != 0) {
+		set_err(l, "No Cloudron login form (external SSO or passkey "
+			"login?) - use the cookie option", 0);
+		return CHAT_LOGIN_NOFORM;
+	}
+	if (c_suffix(l->submit_url, "/confirm") ||
+	    c_suffix(l->submit_url, "/abort"))
+		return finish(l, h, jar, h->resp.final_url, buf, cap);
+	return CHAT_LOGIN_FORM;
+}
+
+int chat_login_submit(struct chat_login *l, struct uhttp *h,
+		      struct uhttp_jar *jar, const char *user,
+		      const char *pass, const char *totp, char *buf,
+		      unsigned int cap)
+{
+	static char body[1600];
+	char msg[128];
+	unsigned int len;
+	int st, kind;
+
+	l->error[0] = '\0';
+	if (!l->submit_url[0]) {
+		set_err(l, "No login form", 0);
+		return CHAT_LOGIN_ERROR;
+	}
+	if (chat_login_body(body, sizeof(body), user, pass, totp) < 0) {
+		set_err(l, "Username or password too long", 0);
+		return CHAT_LOGIN_ERROR;
+	}
+	h->jar = jar;
+	h->accept = "application/json";
+	st = chat_http(h, "POST", l->submit_url, body, buf, cap, &len);
+	/* The body held the password: wipe it right away. */
+	{
+		unsigned int i;
+
+		for (i = 0; i < sizeof(body); i++)
+			body[i] = 0;
+	}
+	if (st < 0) {
+		set_err(l, "Login request failed: ", uhttp_error_string(st));
+		return CHAT_LOGIN_ERROR;
+	}
+	kind = chat_login_parse_reply(st, buf, len, l->redirect,
+				      sizeof(l->redirect), msg, sizeof(msg));
+	switch (kind) {
+	case CHAT_REPLY_DENIED:
+		set_err(l, msg[0] ? msg : "Username and password do not match",
+			0);
+		return CHAT_LOGIN_DENIED;
+	case CHAT_REPLY_TOTP:
+		l->totp_required = 1;
+		return CHAT_LOGIN_TOTP;
+	case CHAT_REPLY_PASSKEY:
+		set_err(l, "This account signs in with a passkey; use the "
+			"cookie option", 0);
+		return CHAT_LOGIN_PASSKEY;
+	case CHAT_REPLY_REDIRECT:
+		break;
+	default:
+		set_err(l, msg[0] ? msg : "Unexpected reply from the login "
+			"server", 0);
+		return CHAT_LOGIN_ERROR;
+	}
+	{
+		char next[CHAT_URL_MAX];
+
+		/* redirectTo may be relative to the submit URL. */
+		if (resolve(l->submit_url, l->redirect, next,
+			    sizeof(next)) != 0) {
+			set_err(l, "Bad login redirect", 0);
+			return CHAT_LOGIN_ERROR;
+		}
+		st = finish(l, h, jar, next, buf, cap);
+	}
+	if (st == CHAT_LOGIN_FORM) {
+		set_err(l, "The login server asked for the password again", 0);
+		return CHAT_LOGIN_ERROR;
+	}
+	return st;
+}
+
+#endif

+ 121 - 0
chat_login.h

@@ -0,0 +1,121 @@
+/* chat_login: native Cloudron OpenID login for the Chat client.
+ *
+ * The Cloudron Chat web login is a Vue SPA, which the browser cannot run, but
+ * the API underneath is plain HTTP + JSON:
+ *
+ *   1. GET <server>/auth/login redirects to the Cloudron OIDC provider's
+ *      /openid/interaction/<uid> page (cookies on both hosts).
+ *   2. That page embeds <script id="cloudron-config"> JSON with a relative
+ *      submitUrl.
+ *   3. POST {"username","password","totpToken"} to submitUrl answers 401
+ *      {"message"}, 200 {"twoFactorRequired":true,...} or 200 {"redirectTo"}.
+ *   4. Following redirectTo finishes the OIDC callback and sets the Chat
+ *      session cookie (connect.sid) on the Chat host.
+ *
+ * This module drives exactly those requests with a uhttp cookie jar; it
+ * never renders the page.  The password is only held by the caller and is
+ * never written anywhere.  The pure parsers (config/reply/config file) are
+ * compiled on the host for chat_login_test.c with CHAT_LOGIN_PURE. */
+#ifndef CHAT_LOGIN_H
+#define CHAT_LOGIN_H
+
+#include "ujson.h"
+
+#ifndef CHAT_LOGIN_PURE
+#include "uhttp.h"
+#endif
+
+#define CHAT_SERVER_MAX   192
+#define CHAT_URL_MAX      1280
+#define CHAT_COOKIE_MAX   2048
+#define CHAT_PATH_MAX     128
+
+/* chat_login_* results */
+#define CHAT_LOGIN_OK        0   /* session cookie captured and validated */
+#define CHAT_LOGIN_FORM      1   /* start: username/password form found */
+#define CHAT_LOGIN_TOTP      2   /* submit: a TOTP code is needed */
+#define CHAT_LOGIN_DENIED    3   /* submit: wrong credentials (l->error) */
+#define CHAT_LOGIN_NOFORM    4   /* start: no Cloudron login API (SSO) */
+#define CHAT_LOGIN_PASSKEY   5   /* submit: account needs a passkey */
+#define CHAT_LOGIN_ERROR   (-1)  /* network/protocol error (l->error) */
+
+/* Submit reply classification (pure). */
+#define CHAT_REPLY_REDIRECT  1
+#define CHAT_REPLY_TOTP      2
+#define CHAT_REPLY_DENIED    3
+#define CHAT_REPLY_PASSKEY   4
+#define CHAT_REPLY_ERROR     5
+
+struct chat_login {
+	char server[CHAT_SERVER_MAX];   /* https://chat.example.com */
+	char submit_url[CHAT_URL_MAX];  /* absolute */
+	char redirect[CHAT_URL_MAX];
+	char app_name[64];
+	char error[160];
+	int totp_required;
+};
+
+/* Normalize a server entry: add https:// when no scheme is given and drop
+ * trailing slashes.  0 ok, -1 invalid. */
+int chat_server_normalize(const char *in, char *out, unsigned int cap);
+
+/* Find the cloudron-config JSON in the login page and resolve its submitUrl
+ * against base_url.  Falls back to a plain "submitUrl":"..." scan.  0 when a
+ * submit URL was found. */
+int chat_login_parse_page(const char *html, unsigned int len,
+			  const char *base_url, char *submit_url,
+			  unsigned int cap, char *app_name,
+			  unsigned int name_cap);
+
+/* Classify a POST reply.  redirect receives redirectTo, msg the server's
+ * message (both may be empty). */
+int chat_login_parse_reply(int status, const char *body, unsigned int len,
+			   char *redirect, unsigned int rcap, char *msg,
+			   unsigned int mcap);
+
+/* Config file: "server=...\ncookie=...\n".  Unknown keys are ignored. */
+int chat_config_parse(const char *text, unsigned int len, char *server,
+		      unsigned int scap, char *cookie, unsigned int ccap);
+int chat_config_format(char *out, unsigned int cap, const char *server,
+		       const char *cookie);
+
+/* JSON body {"username":..,"password":..,"totpToken":..}; -1 if too long. */
+int chat_login_body(char *out, unsigned int cap, const char *user,
+		    const char *pass, const char *totp);
+
+#ifndef CHAT_LOGIN_PURE
+/* Read the whole response body of an opened request into buf (NUL
+ * terminated).  Returns the length, or a UHTTP_ERR_* (<0); a body larger
+ * than cap-1 is UHTTP_ERR_TOOLONG. */
+int chat_http_body(struct uhttp *h, char *buf, unsigned int cap);
+
+/* One request: method/url/JSON body, response body into buf.  Returns the
+ * HTTP status (>0) or a UHTTP_ERR_*.  *blen gets the body length. */
+int chat_http(struct uhttp *h, const char *method, const char *url,
+	      const char *json, char *buf, unsigned int cap,
+	      unsigned int *blen);
+
+/* Step 1: fetch the login page.  CHAT_LOGIN_FORM, CHAT_LOGIN_OK (the
+ * provider already had a session and sent us straight back),
+ * CHAT_LOGIN_NOFORM or CHAT_LOGIN_ERROR. */
+int chat_login_start(struct chat_login *l, struct uhttp *h,
+		     struct uhttp_jar *jar, const char *server, char *buf,
+		     unsigned int cap);
+
+/* Step 2/3: submit the credentials (totp may be ""). */
+int chat_login_submit(struct chat_login *l, struct uhttp *h,
+		      struct uhttp_jar *jar, const char *user,
+		      const char *pass, const char *totp, char *buf,
+		      unsigned int cap);
+
+/* GET /api/me with the jar: 200 -> 0, 401/403 -> 1, else <0 (network). */
+int chat_session_check(struct uhttp *h, struct uhttp_jar *jar,
+		       const char *server, char *buf, unsigned int cap,
+		       unsigned int *blen);
+
+/* Host of a server URL ("chat.example.com"), for jar export/import. */
+int chat_server_host(const char *server, char *host, unsigned int cap,
+		     int *secure);
+#endif
+
+#endif

+ 149 - 0
chat_login_test.c

@@ -0,0 +1,149 @@
+/* Host tests for the pure parts of chat_login.c (make test-chat). */
+
+#include <stdio.h>
+#include <string.h>
+
+#include "chat_login.h"
+
+static int failures;
+
+#define CHECK(cond) do { \
+	if (!(cond)) { \
+		printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
+		failures++; \
+	} \
+} while (0)
+
+/* Trimmed copy of the real Cloudron OIDC login page. */
+static const char page[] =
+	"<!DOCTYPE html>\n<html><head><title>Login</title>\n"
+	"    <script id=\"cloudron-config\" type=\"application/json\">\n"
+	"      {\"iconUrl\":\"/api/v1/apps/bc9e/icon\",\"name\":\"chat\",\"note\":\"\","
+	"\"submitUrl\":\"/openid/interaction/UdA3nm_PJ/login\","
+	"\"passkeyAuthOptionsUrl\":\"/openid/interaction/UdA3nm_PJ/passkey_auth_options\","
+	"\"footer\":\"&copy; 2026 [Cloudron](https://cloudron.io)\",\"language\":null}\n"
+	"    </script>\n"
+	"<script type=\"module\" crossorigin src=\"/assets/oidc_login.js\"></script>\n"
+	"</head><body><div id=\"app\"></div></body></html>\n";
+
+static void test_page(void)
+{
+	char url[1280], name[64];
+	const char *base = "https://my.example.com/openid/interaction/UdA3nm_PJ";
+
+	CHECK(chat_login_parse_page(page, sizeof(page) - 1, base, url,
+				    sizeof(url), name, sizeof(name)) == 0);
+	CHECK(strcmp(url, "https://my.example.com/openid/interaction/UdA3nm_PJ/login") == 0);
+	CHECK(strcmp(name, "chat") == 0);
+
+	/* Escaped slashes, no config id: the fallback scan. */
+	{
+		const char *p2 = "<script>var c={\"submitUrl\":\"\\/openid\\/x\\/login\"};</script>";
+
+		CHECK(chat_login_parse_page(p2, strlen(p2), "http://10.0.2.2:8080/a/b",
+					    url, sizeof(url), name, sizeof(name)) == 0);
+		CHECK(strcmp(url, "http://10.0.2.2:8080/openid/x/login") == 0);
+	}
+	/* Relative and absolute submit URLs. */
+	{
+		const char *p3 = "<script id=\"cloudron-config\">{\"submitUrl\":\"uid/login\"}</script>";
+		const char *p4 = "<script id=\"cloudron-config\">{\"submitUrl\":\"https://id.test/l\"}</script>";
+
+		CHECK(chat_login_parse_page(p3, strlen(p3), "https://h.test/openid/interaction/?x=1",
+					    url, sizeof(url), name, sizeof(name)) == 0);
+		CHECK(strcmp(url, "https://h.test/openid/interaction/uid/login") == 0);
+		CHECK(chat_login_parse_page(p4, strlen(p4), "https://h.test/",
+					    url, sizeof(url), name, sizeof(name)) == 0);
+		CHECK(strcmp(url, "https://id.test/l") == 0);
+	}
+	/* An SSO page without the config. */
+	{
+		const char *p5 = "<html><body><a href=\"https://sso\">Login</a></body></html>";
+
+		CHECK(chat_login_parse_page(p5, strlen(p5), "https://h.test/",
+					    url, sizeof(url), name, sizeof(name)) == -1);
+	}
+	/* Broken JSON in the config and no fallback string. */
+	{
+		const char *p6 = "<script id=\"cloudron-config\">{\"submitUrl\": </script>";
+
+		CHECK(chat_login_parse_page(p6, strlen(p6), "https://h.test/",
+					    url, sizeof(url), name, sizeof(name)) == -1);
+	}
+}
+
+static void test_reply(void)
+{
+	char red[256], msg[128];
+	const char *ok = "{\"redirectTo\":\"https://my.example.com/openid/auth/UdA3\"}";
+	const char *tfa = "{\"twoFactorRequired\":true,\"totpRequired\":true,\"passkeyOptions\":null}";
+	const char *pk = "{\"twoFactorRequired\":true,\"totpRequired\":false,\"passkeyOptions\":{}}";
+	const char *bad = "{\"status\":\"Unauthorized\",\"message\":\"Username and password does not match\"}";
+
+	CHECK(chat_login_parse_reply(200, ok, strlen(ok), red, sizeof(red), msg,
+				     sizeof(msg)) == CHAT_REPLY_REDIRECT);
+	CHECK(strcmp(red, "https://my.example.com/openid/auth/UdA3") == 0);
+	CHECK(chat_login_parse_reply(200, tfa, strlen(tfa), red, sizeof(red), msg,
+				     sizeof(msg)) == CHAT_REPLY_TOTP);
+	CHECK(chat_login_parse_reply(200, pk, strlen(pk), red, sizeof(red), msg,
+				     sizeof(msg)) == CHAT_REPLY_PASSKEY);
+	CHECK(chat_login_parse_reply(401, bad, strlen(bad), red, sizeof(red), msg,
+				     sizeof(msg)) == CHAT_REPLY_DENIED);
+	CHECK(strcmp(msg, "Username and password does not match") == 0);
+	CHECK(chat_login_parse_reply(500, "oops", 4, red, sizeof(red), msg,
+				     sizeof(msg)) == CHAT_REPLY_ERROR);
+	CHECK(chat_login_parse_reply(200, "{}", 2, red, sizeof(red), msg,
+				     sizeof(msg)) == CHAT_REPLY_ERROR);
+}
+
+static void test_config(void)
+{
+	char server[192], cookie[2048], out[2600];
+	const char *cfg = "# comment\r\nserver=https://chat.example.com\r\n"
+			  "junk=1\ncookie=connect.sid=s%3Aabc.def; theme=x  \n";
+
+	CHECK(chat_config_parse(cfg, strlen(cfg), server, sizeof(server), cookie,
+				sizeof(cookie)) == 0);
+	CHECK(strcmp(server, "https://chat.example.com") == 0);
+	CHECK(strcmp(cookie, "connect.sid=s%3Aabc.def; theme=x") == 0);
+	CHECK(chat_config_parse("", 0, server, sizeof(server), cookie,
+				sizeof(cookie)) == -1);
+	CHECK(chat_config_format(out, sizeof(out), "https://c.test",
+				 "connect.sid=1") > 0);
+	CHECK(chat_config_parse(out, strlen(out), server, sizeof(server), cookie,
+				sizeof(cookie)) == 0);
+	CHECK(strcmp(server, "https://c.test") == 0);
+	CHECK(strcmp(cookie, "connect.sid=1") == 0);
+	CHECK(chat_config_format(out, 10, "https://c.test", "x=1") == -1);
+}
+
+static void test_normalize_and_body(void)
+{
+	char s[192], body[256];
+
+	CHECK(chat_server_normalize("chat.example.com", s, sizeof(s)) == 0);
+	CHECK(strcmp(s, "https://chat.example.com") == 0);
+	CHECK(chat_server_normalize("  http://10.0.2.2:8080/// ", s, sizeof(s)) == 0);
+	CHECK(strcmp(s, "http://10.0.2.2:8080") == 0);
+	CHECK(chat_server_normalize("https://", s, sizeof(s)) == -1);
+	CHECK(chat_server_normalize("", s, sizeof(s)) == -1);
+	CHECK(chat_server_normalize("a b", s, sizeof(s)) == -1);
+
+	CHECK(chat_login_body(body, sizeof(body), "al\"ice", "p\\w", "") > 0);
+	CHECK(strcmp(body, "{\"username\":\"al\\\"ice\",\"password\":\"p\\\\w\",\"totpToken\":\"\"}") == 0);
+	CHECK(chat_login_body(body, 16, "alice", "secret", "123456") == -1);
+}
+
+int main(void)
+{
+	test_page();
+	test_reply();
+	test_config();
+	test_normalize_and_body();
+	if (failures) {
+		printf("chat_login_test: %d failure(s)\n", failures);
+		return 1;
+	}
+	printf("chat_login_test: all tests passed\n");
+	return 0;
+}

+ 3 - 0
docs/development.html

@@ -183,6 +183,8 @@
 					<tr><td><code>make test-mujs</code></td><td>Host smoke test for the vendored MuJS engine: arithmetic, strings, Math, Date, JSON, exceptions and the run limit.</td></tr>
 					<tr><td><code>make test-font</code> / <code>test-font-asan</code></td><td>Host specimen test for the fixed-point TrueType parser/rasterizer and glyph cache, with an AddressSanitizer/UBSan variant.</td></tr>
 					<tr><td><code>make test-touchpad</code></td><td>Host tests for the device-independent contact gesture engine: taps, right-click zones, physical-button latch, two-finger scroll, direction and pointer re-anchoring.</td></tr>
+					<tr><td><code>make test-chat</code></td><td>Host tests (ASan/UBSan) for the chat client's JSON parser, cookie jar and the OIDC login page/reply/config parsers.</td></tr>
+					<tr><td><code>make test-chat-e2e</code></td><td>Boots QEMU with an NE2000 on slirp, starts <code>tools/mock_chat.py</code> and drives <code>chat</code> through QMP: native login, send, live poll, read marker, older paging, browse/join, new DM, saved-session resume and sign-out.  <code>CHAT_E2E=--totp|--consent|--passkey|--wrong</code> runs a login variant.</td></tr>
 					<tr><td><code>make compat-serve</code></td><td>Serve the browser compatibility ladder from <code>testdata/browser/compat/</code> on port 8000 for the board or QEMU guest.</td></tr>
 					<tr><td><code>make fonts</code></td><td>Regenerate the checked-in Arimo/Liberation Mono subsets with <code>pyftsubset</code>.</td></tr>
 				</tbody>
@@ -270,6 +272,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><strong>Ring-3 libc.</strong> <code>make test-libc</code> runs the malloc stress test (32 MB simulated arena with poisoned pages), exact <code>snprintf</code> float/string checks against the host, x87 math values, the 64-bit division helpers and a 32-bit setjmp/longjmp test.</li>
 			<li><strong>Fonts.</strong> <code>make test-font</code> parses the checked-in Arimo subset on the host, measures Latin-1 text, renders composites (for example <code>Äé</code>) and writes a specimen PPM. The browser must also be exercised across a navigation to verify detach/reattach around <code>heap_reset()</code>.</li>
 			<li><strong>Touchpad gestures.</strong> <code>make test-touchpad</code> feeds synthetic contact frames to <span class="file">touchpad_gesture.c</span> and checks one/two-finger taps, the corner and physical-button mapping, scroll start/direction, pointer freeze and re-anchoring, and the option switches.</li>
+			<li><strong>Chat client.</strong> <code>make test-chat</code> covers the pure modules on the host.  <code>tools/mock_chat.py</code> is a two-origin mock of Cloudron Chat (port 18080) and the Cloudron OIDC login (18081) with <code>test</code>, <code>totp</code> (code 123456), <code>passkey</code> and <code>consent</code> accounts (password <code>test</code>) and <code>/debug/state</code>, <code>/debug/inject</code> endpoints; run it alone and enter <code>http://10.0.2.2:18080</code> in a QEMU guest's chat, or let <code>make test-chat-e2e</code> drive it.  Screenshots land in <code>chat-test-out/</code>.</li>
 			<li><strong>Browser compatibility.</strong> <code>make compat-serve</code> serves the numbered A/B ladder in <code>testdata/browser/compat/</code>. Open the index on the board (or at <code>http://10.0.2.2:8000/</code> from a QEMU guest with user networking) and compare each pair; the index table records the current status.</li>
 			<li><strong>UEFI.</strong> <code>make test-uefi</code> boots the dual image under OVMF headless and greps the serial log for the boot line.</li>
 			<li><strong>Compositor stats.</strong> The ring-3 WM overwrites <code>/share/wmstats</code> every two seconds with <code>frames</code>, total and worst compositing time in milliseconds, and the pixels drawn in the interval. Read it in a terminal or fetch it over WebDAV to measure a target.</li>

+ 8 - 3
docs/graphics.html

@@ -285,10 +285,11 @@
 			clipped RGB565 primitives, buttons, menu items, text fields, nine
 			procedural icons, a theme palette, layout cut helpers and scrolling
 			panes. It is linked into <code>files</code>, <code>mines</code>,
-			<code>solitaire</code> and the real <code>gallery.elf</code>.
+			<code>solitaire</code>, <code>chat</code> and the real
+			<code>gallery.elf</code>.
 		</p>
 		<ul>
-			<li><strong>Text fields</strong> support drag-selection, double-click select-all, Ctrl+Left/Right word jumps, Ctrl+Delete/Backspace word deletion and Ctrl+A. They use the proportional face with measured caret, selection and horizontal scrolling; a field marked <code>disabled</code> ignores pointer and keyboard input, drops the focus and paints its value dimmed in the same proportional face. The terminal and editor keep the 8×16 cell grid.</li>
+			<li><strong>Text fields</strong> support drag-selection, double-click select-all, Ctrl+Left/Right word jumps, Ctrl+Delete/Backspace word deletion and Ctrl+A. They use the proportional face with measured caret, selection and horizontal scrolling; a field marked <code>disabled</code> ignores pointer and keyboard input, drops the focus and paints its value dimmed in the same proportional face. A field marked <code>secret</code> is measured and painted from a <code>*</code> mask (caret, selection and click positions follow the mask, Ctrl+Left/Right jump to the ends), and Tab returns <code>NGUI_INPUT_NEXT</code> together with <code>NGUI_INPUT_CANCEL</code> so forms can move the focus. Fields hold up to 511 characters (<code>NGUI_INPUT_MAX</code> 512). The terminal and editor keep the 8×16 cell grid.</li>
 			<li><strong>Clip stack</strong> keeps nested panes and popups inside their parents.</li>
 			<li><strong>Layout cuts</strong> split a rectangle into rows, columns and fixed margins without a constraint solver.</li>
 			<li><strong>No retained widget tree.</strong> Apps redraw from state every frame, which keeps the toolkit small and predictable.</li>
@@ -319,6 +320,10 @@
 				<h3>gallery</h3>
 				<p>Live showcase of every ngui control and primitive. Ships in the pack as <code>bin/gallery.app</code>; a launcher prefers <code>/share/GALLERY</code> for development.</p>
 			</div>
+			<div class="card">
+				<h3>chat</h3>
+				<p>Cloudron Chat client: native OIDC login, channel/DM sidebar with unread badges and presence dots, a wrapped timeline with avatars, day headers and reply snippets, a composer and browse/new-DM pickers. The top-bar <em>Chat</em> button launches it.</p>
+			</div>
 			<div class="card">
 				<h3>solitaire</h3>
 				<p>Klondike with drag-and-drop, draw-one/three, scoring, animation and pixel-art cards on the canvas service.</p>
@@ -380,7 +385,7 @@
 			<li><code>ngui.c</code>, <code>ngui.h</code> — toolkit</li>
 			<li><code>ufont.c</code>, <code>ufont_ttf.c</code>, <code>ufont_draw.c</code> — fixed-point TrueType text</li>
 			<li><code>fonts/*.ttf</code> — Arimo / Liberation Mono subsets in the pack</li>
-			<li><code>ucmd_files.c</code>, <code>gallery.c</code>, <code>ucmd_solitaire.c</code></li>
+			<li><code>ucmd_files.c</code>, <code>gallery.c</code>, <code>ucmd_solitaire.c</code>, <code>ucmd_chat.c</code></li>
 			<li><code>img*.c</code> — image codecs</li>
 			<li><code>ati.c</code>, <code>nvidia.c</code>, <code>intel.c</code>, <code>nv50.c</code></li>
 		</ul>

+ 7 - 2
docs/index.html

@@ -78,7 +78,7 @@
 
 				<rect class="svg-box accent" x="100" y="8" width="720" height="72" rx="9"/>
 				<text class="svg-text" x="124" y="35">Ring 3 · commands &amp; GUI apps</text>
-				<text class="svg-sub" x="124" y="55">ls · cat · edit · view · files · browser · gallery · solitaire</text>
+				<text class="svg-sub" x="124" y="55">ls · cat · edit · view · files · browser · chat · gallery · solitaire</text>
 				<text class="svg-tiny" x="796" y="35" text-anchor="end">0x40000000</text>
 
 				<path class="svg-line" d="M460 80v22"/>
@@ -220,6 +220,11 @@
 				<p>NIC registry, ARP/ICMP/UDP, DHCP, DNS, NTP, TCP client and listener, TLS 1.3, USB tethering, netconsole and netkexec.</p>
 				<span class="card-tag">network.html</span>
 			</a>
+			<a class="card" href="network.html#chat">
+				<h3>Chat client</h3>
+				<p>Native Cloudron Chat app: OIDC username/password/TOTP login without a browser, a uhttp cookie jar, an arena JSON parser and REST polling.</p>
+				<span class="card-tag">network.html#chat</span>
+			</a>
 			<a class="card" href="userland.html">
 				<h3>Userland</h3>
 				<p>Ring-3 address space, ELF loading, syscall groups, the optional libc and malloc, PATH dispatch, the command pack and GUI apps.</p>
@@ -269,7 +274,7 @@
 					</tr>
 					<tr>
 						<td>Userland</td>
-						<td><span class="file">ucmd_*.c</span> <span class="file">ucmd_lib.h</span> <span class="file">libc/</span> <span class="file">third_party/mujs/</span> <span class="file">ngui.c</span> <span class="file">ufont.c</span> <span class="file">ufont_ttf.c</span> <span class="file">fonts/</span> <span class="file">browser.c</span> <span class="file">js_browser.c</span> <span class="file">gallery.c</span></td>
+						<td><span class="file">ucmd_*.c</span> <span class="file">ucmd_lib.h</span> <span class="file">libc/</span> <span class="file">third_party/mujs/</span> <span class="file">ngui.c</span> <span class="file">ufont.c</span> <span class="file">ufont_ttf.c</span> <span class="file">fonts/</span> <span class="file">browser.c</span> <span class="file">js_browser.c</span> <span class="file">gallery.c</span> <span class="file">ucmd_chat.c</span> <span class="file">chat_login.c</span> <span class="file">ujson.c</span> <span class="file">uhttp_cookie.c</span></td>
 					</tr>
 					<tr>
 						<td>Build &amp; pack</td>

+ 48 - 1
docs/network.html

@@ -63,6 +63,7 @@
 			<li><a href="#abi">sys_net ABI</a></li>
 			<li><a href="#console">Netconsole &amp; netkexec</a></li>
 			<li><a href="#http">HTTP clients</a></li>
+			<li><a href="#chat">Chat client &amp; OIDC login</a></li>
 			<li><a href="#security">Security posture</a></li>
 			<li><a href="#sources">Source map</a></li>
 		</ul>
@@ -335,7 +336,8 @@
 		<h2>HTTP clients</h2>
 		<ul>
 			<li><strong>curl</strong> — <code>http://</code> or <code>https://</code> GET with DNS, ARP, redirects (up to five hops), chunked decoding, status/headers/body dump and a TLS warning.</li>
-			<li><strong>uhttp</strong> — shared ring-3 HTTP/1.1 client used by curl and the browser: URL parsing, redirects, chunked decoding, timeouts and TLS.</li>
+			<li><strong>uhttp</strong> — shared ring-3 HTTP/1.1 client used by curl, the browser and chat: URL parsing, redirects (up to eight hops; 1 KB paths and 1.5 KB header lines, enough for OIDC URLs), chunked decoding, timeouts and TLS.  Requests and bodies of any size are split into pieces the transport accepts (1024-byte TLS records, one peer MSS for plain TCP).  Optional per-request fields set the <code>Accept</code> header, extra header lines and a cookie jar; 1xx/204/304 responses are treated as bodyless so keep-alive does not wait for an idle timeout.</li>
+			<li><strong>uhttp_cookie</strong> — the cookie jar (<span class="file">uhttp_cookie.c</span>, 24 cookies of up to 768 bytes).  Every <code>Set-Cookie</code>, including those on redirect responses, is stored; matching cookies are sent on every request and redirect hop.  Cookies are host-only (<code>Domain</code> is ignored), <code>Path</code> is a prefix match, <code>Secure</code> cookies only go over https, and <code>Max-Age&lt;=0</code> or a 1970 <code>Expires</code> deletes a cookie.  The jar outlives the connection, so a cross-origin redirect that reconnects keeps the session.</li>
 			<li><strong>browser</strong> — runs network fetches in up to three headless <code>curl __serve</code> workers, each with its own request/body/meta files under <code>/share/bf&lt;session&gt;_&lt;slot&gt;*</code>.  The session id comes from the browser pid, so multiple browser windows do not share queue files.  Images are prefetched in parallel and decoded as jobs complete, so the UI keeps drawing and scrolling.  Each worker keeps its own TCP/TLS connection.</li>
 			<li><strong>websrv</strong> — the server side, speaking HTTP/1.1 + WebDAV over the TCP listener; see <a href="filesystems.html#webdav">Filesystems → WebDAV</a>.</li>
 		</ul>
@@ -346,6 +348,47 @@
 		</p>
 	</section>
 
+	<section id="chat">
+		<h2>Chat client &amp; OIDC login</h2>
+		<p>
+			<code>chat</code> (<span class="file">ucmd_chat.c</span>) is a native
+			client for Cloudron Chat built on uhttp, the cookie jar, the
+			<span class="file">ujson.c</span> arena JSON parser (fixed node pool,
+			escapes, surrogate pairs) and ngui.  The web login is a Vue
+			ES-module SPA the browser cannot run, so
+			<span class="file">chat_login.c</span> drives the API underneath:
+		</p>
+		<ol>
+			<li><code>GET &lt;server&gt;/auth/login</code> follows the redirect to the Cloudron OIDC provider's <code>/openid/interaction/&lt;uid&gt;</code> page, collecting the PKCE pre-session cookie on the Chat host and the interaction cookies on the provider.</li>
+			<li>The page's <code>&lt;script id="cloudron-config"&gt;</code> JSON names a relative <code>submitUrl</code> (a plain <code>"submitUrl":"…"</code> scan is the fallback).  No config means external SSO: the client offers the cookie screen.</li>
+			<li><code>POST submitUrl {"username","password","totpToken"}</code> answers 401 with a message, <code>{"twoFactorRequired":true,"totpRequired":true}</code> (the client asks for the code and reposts), <code>totpRequired:false</code> (passkey-only: cookie screen) or <code>{"redirectTo"}</code>.</li>
+			<li>Following <code>redirectTo</code> ends at <code>/auth/callback</code> on the Chat host, which sets <code>connect.sid</code>.  A consent interaction on the way is confirmed like the web UI does; an abort page means the account has no access.  <code>GET /api/me</code> validates the session.</li>
+		</ol>
+		<p>
+			The password lives only in the form field and the request buffer;
+			both are wiped after the attempt.  The Chat host's cookie header is
+			saved with the server address in <code>/share/chat.cfg</code>
+			(RAM-only; another path can be given as the argument or on the login
+			screen) and is re-saved when the server rolls the cookie.  The saved
+			cookie is a bearer credential.  Passkey and external-SSO accounts
+			paste a <code>connect.sid</code> cookie from a signed-in browser
+			instead.
+		</p>
+		<p>
+			There is no WebSocket: the open conversation is polled with
+			<code>GET /api/channels/:id/messages?after=&lt;newest&gt;</code> every
+			2 s (5 s while the window is unfocused) and the directory
+			(<code>/api/channels</code>, <code>/api/dms</code>) every 12 s (20 s),
+			and polling waits 1 s after keyboard or pointer input.  Errors back
+			off 2/5/10/30 s.  Sends carry a <code>clientId</code> so a retried
+			POST cannot duplicate a message.  An open TCP socket pauses the
+			board's netkexec watcher, so the client only keeps its keep-alive
+			connection while its window is focused and the user was active in
+			the last 30 s; otherwise it closes it after each poll.  Other
+			clients see the NebOS user as offline (presence is WebSocket-based).
+		</p>
+	</section>
+
 	<section id="security">
 		<h2>Security posture</h2>
 		<div class="table-wrap">
@@ -357,6 +400,7 @@
 					<tr><td>TLS certificates</td><td>Not verified</td><td>Encryption without authentication; MITM is undetected.</td></tr>
 					<tr><td>TLS DRBG</td><td>Weak (RDTSC/ticks/MAC)</td><td>Not suitable for high-value secrets.</td></tr>
 					<tr><td>WebDAV</td><td>No authentication</td><td>Anyone on the LAN can read mounts and write <code>/share</code>.</td></tr>
+					<tr><td>Chat session</td><td>Cookie saved in <code>/share/chat.cfg</code></td><td>A bearer credential in RAM until sign-out; the password is sent over unverified TLS and never stored.</td></tr>
 					<tr><td>NTP</td><td>Unauthenticated SNTP</td><td>Anyone who can answer for the server name can set the clock.</td></tr>
 					<tr><td>NIC ownership</td><td>Raw lease for packet commands; shared TCP client table</td><td>Raw commands are mutually exclusive; up to twelve processes can hold one TCP connection each.  A killed owner is force-released.</td></tr>
 					<tr><td>Kernel/user isolation</td><td>None (identity map)</td><td>A ring-3 bug can reach any mapped kernel page.</td></tr>
@@ -378,6 +422,9 @@
 			<li><code>sys_net.c</code> — ring-3 service</li>
 			<li><code>netlog.c</code>, <code>netkexec.c</code></li>
 			<li><code>uhttp.c</code>, <code>ucmd_curl.c</code>, <code>ucmd_websrv.c</code></li>
+			<li><code>uhttp_cookie.c</code>, <code>ujson.c</code> — cookie jar, JSON parser</li>
+			<li><code>chat_login.c</code>, <code>ucmd_chat.c</code> — OIDC login driver, chat client</li>
+			<li><code>tools/mock_chat.py</code>, <code>tools/qmp_chat_test.py</code> — mock server, QEMU end-to-end test</li>
 		</ul>
 	</section>
 </main>

+ 6 - 4
docs/userland.html

@@ -4,7 +4,7 @@
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>Userland | NebOS Architecture</title>
-<meta name="description" content="NebOS userland: ring-3 address space, ELF loading, the syscall ABI, the shell and PATH dispatch, the 45-command pack, GUI applications and the browser.">
+<meta name="description" content="NebOS userland: ring-3 address space, ELF loading, the syscall ABI, the shell and PATH dispatch, the 46-command pack, GUI applications and the browser.">
 <link rel="icon" href="favicon.svg" type="image/svg+xml">
 <link rel="stylesheet" href="style.css">
 </head>
@@ -38,12 +38,12 @@
 			Ring-3 programs are static ELFs linked at <code>0x40000000</code>.
 			The shell resolves a command name against builtins, the per-terminal
 			PATH and the kernel command registry, then spawns it with one
-			argument string. The command pack supplies 45 PATH commands by default.
+			argument string. The command pack supplies 46 PATH commands by default.
 		</p>
 		<div class="meta">
 			<span class="pill">int 0x80</span>
 			<span class="pill">one string argument</span>
-			<span class="pill">45 PATH commands</span>
+			<span class="pill">46 PATH commands</span>
 			<span class="pill">8 TTYs · 8 windows</span>
 		</div>
 	</div>
@@ -315,7 +315,7 @@
 			</div>
 			<div class="card">
 				<h3>GUI</h3>
-				<p><code>wm</code> <code>term</code> <code>files</code> <code>view</code> <code>mines</code> <code>solitaire</code> <code>gallery</code> <code>browser</code> <code>clock</code> <code>colors</code> <code>settime</code></p>
+				<p><code>wm</code> <code>term</code> <code>files</code> <code>view</code> <code>mines</code> <code>solitaire</code> <code>gallery</code> <code>browser</code> <code>chat</code> <code>clock</code> <code>colors</code> <code>settime</code></p>
 			</div>
 		</div>
 		<p>
@@ -333,6 +333,7 @@
 		<ul>
 			<li><strong>files</strong> — browser for the VFS; opens text in <code>edit</code>, images in <code>view</code>, HTML in <code>browser</code>. First user of ngui.</li>
 			<li><strong>gallery</strong> — live widget and primitive showcase; the real app ships in the pack.</li>
+			<li><strong>chat</strong> — native Cloudron Chat client (top-bar <em>Chat</em> button, or <code>chat [config-path]</code>): username/password/TOTP login through the Cloudron OIDC API or a pasted session cookie, channels and DMs with unread badges and presence, history with older paging, sending, REST polling, read markers, browse/join and new DM.  The session cookie (never the password) is saved in <code>/share/chat.cfg</code> by default.  Keys: Enter sends, PgUp/PgDn scroll, Home at the top pages in older history, Ctrl+B browse, Ctrl+N new DM, Ctrl+R refresh, and with the composer unfocused (Esc) Up/Down switch conversations.  See <a href="network.html#chat">Network → Chat client</a>.</li>
 			<li><strong>solitaire</strong> — Klondike with drag-and-drop, scoring and a win animation.</li>
 			<li><strong>mines</strong> — second ngui canvas app; shares the toolkit and event model.</li>
 			<li><strong>view</strong> — fit/1:1/zoom/pan image viewer, animated GIF playback.</li>
@@ -415,6 +416,7 @@
 			<li><code>ufont.c</code>, <code>ufont_ttf.c</code> — fixed-point TrueType text</li>
 			<li><code>ngui.c</code> — GUI toolkit; <code>fonts/*.ttf</code> — UI subsets</li>
 			<li><code>browser.c</code>, <code>browser_html.c</code>, <code>js_browser.c/h</code>, <code>third_party/mujs/</code>, <code>gallery.c</code></li>
+			<li><code>ucmd_chat.c</code>, <code>chat_login.c</code>, <code>ujson.c</code>, <code>uhttp_cookie.c</code> — chat client</li>
 		</ul>
 	</section>
 </main>

+ 42 - 0
ngui.c

@@ -1376,6 +1376,31 @@ static void input_scroll_to_cursor(struct ngui *ui, struct ngui_input *in,
 		in->scroll = in->len;
 }
 
+/* Secret fields are measured and painted from a '*' mask: the real text is
+ * swapped out for everything except the edit loop, so the caret, selection
+ * and click positions all follow the masked width. */
+static char secret_save[NGUI_INPUT_MAX];
+
+static void secret_mask(struct ngui_input *in)
+{
+	unsigned int i;
+
+	for (i = 0; i <= in->len && i < NGUI_INPUT_MAX; i++) {
+		secret_save[i] = in->text[i];
+		in->text[i] = i < in->len ? '*' : '\0';
+	}
+}
+
+static void secret_unmask(struct ngui_input *in)
+{
+	unsigned int i;
+
+	for (i = 0; i <= in->len && i < NGUI_INPUT_MAX; i++) {
+		in->text[i] = secret_save[i];
+		secret_save[i] = 0;
+	}
+}
+
 int ngui_text_input(struct ngui *ui, unsigned int id, struct ngui_rect r,
 		    struct ngui_input *in)
 {
@@ -1395,6 +1420,8 @@ int ngui_text_input(struct ngui *ui, unsigned int id, struct ngui_rect r,
 	if (inner.h < 1)
 		inner.h = 1;
 	avail = inner.w;
+	if (in->secret)
+		secret_mask(in);
 
 	if (in->disabled) {
 		/* A field that became disabled while focused gives the focus
@@ -1447,13 +1474,24 @@ int ngui_text_input(struct ngui *ui, unsigned int id, struct ngui_rect r,
 		in->dragging = 0;
 
 	if (focused) {
+		if (in->secret)
+			secret_unmask(in);
 		while ((k = ngui_key(ui)) != 0) {
+			if (in->secret) {
+				/* No word boundaries inside a password. */
+				if (k == NGUI_KEY_CTRL_LEFT)
+					k = NGUI_KEY_HOME;
+				else if (k == NGUI_KEY_CTRL_RIGHT)
+					k = NGUI_KEY_END;
+			}
 			if (k == '\n' || k == '\r') {
 				result |= NGUI_INPUT_SUBMIT;
 				break;
 			}
 			if (k == NGUI_KEY_ESC || k == NGUI_KEY_TAB) {
 				result |= NGUI_INPUT_CANCEL;
+				if (k == NGUI_KEY_TAB)
+					result |= NGUI_INPUT_NEXT;
 				ui->focus = 0;
 				break;
 			}
@@ -1516,6 +1554,8 @@ int ngui_text_input(struct ngui *ui, unsigned int id, struct ngui_rect r,
 				changed = 1;
 			}
 		}
+		if (in->secret)
+			secret_mask(in);
 	}
 
 	ngui_fill_rect(ui, r, focused ? ui->theme.panel_alt : ui->theme.panel);
@@ -1555,6 +1595,8 @@ int ngui_text_input(struct ngui *ui, unsigned int id, struct ngui_rect r,
 				       ui->theme.accent);
 	}
 	ngui_pop_clip(ui);
+	if (in->secret)
+		secret_unmask(in);
 
 	if (changed)
 		result |= NGUI_INPUT_CHANGED;

+ 3 - 1
ngui.h

@@ -9,12 +9,13 @@
 #include "syscall.h"
 #include "wm_abi.h"
 
-#define NGUI_INPUT_MAX 128
+#define NGUI_INPUT_MAX 512
 #define NGUI_MOTION_REDRAW_MS 33
 
 #define NGUI_INPUT_CHANGED 1
 #define NGUI_INPUT_SUBMIT  2
 #define NGUI_INPUT_CANCEL  4
+#define NGUI_INPUT_NEXT    8   /* Tab: move to the next field (with CANCEL) */
 
 /* Key codes from io.c.  Arrows are 0x100..; the page/home/end keys are
  * produced by the extended PS/2 path. */
@@ -84,6 +85,7 @@ struct ngui_input {
 	unsigned int anchor;          /* mouse selection anchor (== cursor: none) */
 	int dragging;                 /* a press in the field is extending a selection */
 	int disabled;                 /* ignore input and paint the value dimmed */
+	int secret;                   /* paint '*' per character (passwords) */
 	const char *placeholder;
 	unsigned int last_click_ms;   /* previous press, for double-click select-all */
 };

+ 492 - 0
tools/mock_chat.py

@@ -0,0 +1,492 @@
+#!/usr/bin/env python3
+"""Mock Cloudron Chat server + Cloudron OIDC login for the NebOS chat client.
+
+Two plain-HTTP origins on the host, reachable from a QEMU slirp guest as
+10.0.2.2:
+
+  chat  (default port 18080): /auth/login, /auth/callback, /auth/return,
+        /auth/logout and the /api/* routes the client uses
+  login (default port 18081): /openid/auth, /openid/interaction/<uid>
+        (HTML with the cloudron-config JSON), POST .../login and .../confirm
+
+Accounts (password "test"):
+  test     plain login
+  totp     needs the TOTP code 123456
+  passkey  passkey-only (the client must fall back to the cookie screen)
+  consent  login is followed by a consent interaction (auto-confirmed)
+
+Debug endpoints on the chat port (no auth):
+  GET  /debug/state                 JSON dump (messages, reads, joins)
+  POST /debug/inject {"channel","body","user"}   message from another user
+  POST /debug/presence {"user","presence"}
+
+Usage: tools/mock_chat.py [--host 0.0.0.0] [--chat-port 18080]
+       [--login-port 18081] [--public-host 10.0.2.2] [--messages N]
+"""
+import argparse
+import datetime
+import json
+import secrets
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from urllib.parse import parse_qs, urlparse
+
+LOCK = threading.Lock()
+STATE = {
+    "users": {
+        "u-test": {"id": "u-test", "username": "test", "name": "Test User"},
+        "u-alice": {"id": "u-alice", "username": "alice", "name": "Alice Example"},
+        "u-bob": {"id": "u-bob", "username": "bob", "name": "Bob Böhm"},
+        "u-carol": {"id": "u-carol", "username": "carol", "name": "Carol"},
+        "u-totp": {"id": "u-totp", "username": "totp", "name": "Totp User"},
+        "u-consent": {"id": "u-consent", "username": "consent", "name": "Consent User"},
+    },
+    "channels": {},         # id -> {id,name,type,members:set,description}
+    "messages": {},         # channel id -> [msg]
+    "reads": {},            # (channel, user) -> last read message id
+    "presence": {"u-alice": "online", "u-bob": "away", "u-carol": "offline"},
+    "sessions": {},         # connect.sid -> user id (or None = pre-login)
+    "interactions": {},     # uid -> {"pre": sid, "user": None, "consent": bool}
+    "log": [],
+}
+SEQ = [0]
+ARGS = None
+
+
+def note(line):
+    STATE["log"].append(line)
+    if ARGS and ARGS.verbose:
+        print(line, flush=True)
+
+
+def now_iso():
+    SEQ[0] += 1
+    t = datetime.datetime(2026, 11, 9, 9, 0, 0) + datetime.timedelta(seconds=37 * SEQ[0])
+    return t.strftime("%Y-%m-%dT%H:%M:%S.") + "%03dZ" % (SEQ[0] % 1000)
+
+
+def add_channel(cid, name, ctype, members, description=""):
+    STATE["channels"][cid] = {"id": cid, "name": name, "type": ctype,
+                              "members": set(members), "description": description}
+    STATE["messages"][cid] = []
+
+
+def add_message(cid, uid, body, client_id=None, reply_to=None, extra=None):
+    msgs = STATE["messages"][cid]
+    m = {"id": "m%05d" % (SEQ[0] + 1), "clientId": client_id, "channelId": cid,
+         "userId": uid, "authorName": STATE["users"][uid]["name"],
+         "authorUsername": STATE["users"][uid]["username"], "body": body,
+         "type": None, "parentId": None, "replyToId": reply_to, "replyTo": None,
+         "createdAt": now_iso(), "deleted": False, "reactions": [],
+         "attachments": [], "threadCount": 0, "readBy": [], "pinned": False}
+    if reply_to:
+        target = next((x for x in msgs if x["id"] == reply_to), None)
+        if target:
+            m["replyTo"] = {"id": target["id"], "authorName": target["authorName"],
+                            "body": target["body"], "deleted": False}
+    if extra:
+        m.update(extra)
+    msgs.append(m)
+    return m
+
+
+def seed(n_general):
+    add_channel("c-general", "general", "public",
+                ["u-test", "u-alice", "u-bob", "u-carol", "u-totp", "u-consent"],
+                "Company-wide")
+    add_channel("c-random", "random", "public", ["u-alice", "u-bob"], "Off topic")
+    add_channel("c-design", "design", "public", ["u-alice"], "Design talk")
+    add_channel("c-secret", "secret", "private", ["u-test", "u-alice"])
+    add_channel("d-alice", None, "dm", ["u-test", "u-alice"])
+    who = ["u-alice", "u-bob", "u-carol"]
+    for i in range(n_general):
+        add_message("c-general", who[i % 3],
+                    "History message %d – “quoted” café \U0001F44D" % (i + 1))
+    first = STATE["messages"]["c-general"][-1]["id"] if n_general else None
+    add_message("c-general", "u-bob",
+                "A longer message that should wrap over several lines in the "
+                "NebOS chat timeline, because it keeps going and going with "
+                "plenty of words to test the greedy word wrapper.\nAnd a "
+                "second paragraph.", reply_to=first,
+                extra={"attachments": [{"id": "a1", "filename": "notes.txt",
+                                        "mime": "text/plain", "size": 12}],
+                       "threadCount": 2,
+                       "reactions": [{"emoji": "\U0001F44D", "count": 3}]})
+    add_message("c-secret", "u-alice", "Private channel, only us two.")
+    add_message("d-alice", "u-alice", "Hi Test, this is a direct message!")
+    # test has read general up to the history; the rest is unread
+    msgs = STATE["messages"]["c-general"]
+    if len(msgs) > 1:
+        STATE["reads"][("c-general", "u-test")] = msgs[-2]["id"]
+
+
+def unread(cid, uid):
+    msgs = [m for m in STATE["messages"][cid] if not m["deleted"]]
+    last = STATE["reads"].get((cid, uid))
+    if last is None:
+        return len([m for m in msgs if m["userId"] != uid])
+    idx = next((i for i, m in enumerate(msgs) if m["id"] == last), -1)
+    return len([m for m in msgs[idx + 1:] if m["userId"] != uid])
+
+
+def last_message(cid):
+    msgs = [m for m in STATE["messages"][cid] if not m["deleted"]]
+    if not msgs:
+        return None
+    m = msgs[-1]
+    return {"id": m["id"], "body": m["body"][:160], "createdAt": m["createdAt"],
+            "userId": m["userId"], "authorName": m["authorName"], "authorPicture": ""}
+
+
+def channel_json(c, uid):
+    return {"id": c["id"], "name": c["name"], "type": c["type"],
+            "description": c["description"], "archived": False,
+            "memberCount": len(c["members"]), "isSelf": False,
+            "unreadCount": unread(c["id"], uid), "lastMessage": last_message(c["id"])}
+
+
+def dm_json(c, uid):
+    other = next((m for m in c["members"] if m != uid), None)
+    u = STATE["users"].get(other)
+    return {"id": c["id"], "type": "dm", "isSelf": other is None,
+            "otherUser": dict(u, active=True) if u else None,
+            "otherUserId": other, "unreadCount": unread(c["id"], uid),
+            "lastMessage": last_message(c["id"]),
+            "presence": STATE["presence"].get(other, "offline")}
+
+
+class Base(BaseHTTPRequestHandler):
+    protocol_version = "HTTP/1.1"
+    server_version = "MockChat/1.0"
+
+    def log_message(self, fmt, *a):
+        note("%s %s" % (self.server.label, fmt % a))
+
+    def cookies(self):
+        out = {}
+        for part in (self.headers.get("Cookie") or "").split(";"):
+            if "=" in part:
+                k, v = part.strip().split("=", 1)
+                out[k] = v
+        return out
+
+    def body_json(self):
+        n = int(self.headers.get("Content-Length") or 0)
+        raw = self.rfile.read(n) if n else b""
+        if not raw:
+            return {}
+        try:
+            return json.loads(raw.decode())
+        except ValueError:
+            return None
+
+    def send(self, status, body=b"", ctype="application/json",
+             headers=None):
+        if isinstance(body, (dict, list)):
+            body = json.dumps(body).encode()
+        elif isinstance(body, str):
+            body = body.encode()
+        self.send_response(status)
+        for k, v in (headers or []):
+            self.send_header(k, v)
+        if status not in (204, 304):
+            self.send_header("Content-Type", ctype)
+            self.send_header("Content-Length", str(len(body)))
+        self.end_headers()
+        if status not in (204, 304):
+            self.wfile.write(body)
+
+    def redirect(self, status, location, headers=None):
+        self.send(status, "Redirecting to " + location, "text/plain",
+                  [("Location", location)] + (headers or []))
+
+    def chat_origin(self):
+        return "http://%s:%d" % (ARGS.public_host, ARGS.chat_port)
+
+    def login_origin(self):
+        return "http://%s:%d" % (ARGS.public_host, ARGS.login_port)
+
+
+LOGIN_PAGE = """<!DOCTYPE html>
+<html><head><title>Login</title>
+    <script id="cloudron-config" type="application/json">
+      %s
+    </script>
+<script type="module" crossorigin src="/assets/oidc_login.js"></script>
+</head><body><div id="app"></div></body></html>
+"""
+
+
+class LoginHandler(Base):
+    def do_GET(self):
+        u = urlparse(self.path)
+        parts = u.path.strip("/").split("/")
+        with LOCK:
+            if u.path == "/openid/auth":
+                q = parse_qs(u.query)
+                uid = secrets.token_urlsafe(12)
+                STATE["interactions"][uid] = {"pre": q.get("state", [""])[0],
+                                              "user": None, "consent": False,
+                                              "icookie": secrets.token_hex(8)}
+                it = STATE["interactions"][uid]
+                return self.redirect(303, "/openid/interaction/" + uid, [
+                    ("Set-Cookie", "_interaction=%s; path=/openid/interaction/%s; "
+                                   "expires=Mon, 09 Nov 2026 20:00:00 GMT; samesite=lax; httponly"
+                     % (it["icookie"], uid)),
+                    ("Set-Cookie", "_interaction_resume=%s; path=/openid/auth/%s; "
+                                   "httponly" % (it["icookie"], uid))])
+            if len(parts) == 3 and parts[:2] == ["openid", "interaction"]:
+                uid = parts[2]
+                it = STATE["interactions"].get(uid)
+                if not it or self.cookies().get("_interaction") != it["icookie"]:
+                    return self.send(400, {"message": "interaction cookie missing"})
+                if it["user"] and it["consent"]:
+                    cfg = {"name": "chat", "submitUrl": "/openid/interaction/%s/confirm" % uid}
+                else:
+                    cfg = {"iconUrl": "/icon", "name": "chat", "note": "",
+                           "submitUrl": "/openid/interaction/%s/login" % uid,
+                           "passkeyLoginUrl": "/openid/interaction/%s/passkey_login" % uid,
+                           "footer": "&copy; mock", "language": None}
+                return self.send(200, LOGIN_PAGE % json.dumps(cfg), "text/html")
+            if len(parts) == 3 and parts[:2] == ["openid", "auth"]:
+                uid = parts[2]
+                it = STATE["interactions"].get(uid)
+                if not it or self.cookies().get("_interaction_resume") != it["icookie"]:
+                    return self.send(400, {"message": "resume cookie missing"})
+                if not it["user"]:
+                    return self.redirect(303, "/openid/interaction/" + uid)
+                if it["consent"] and not it.get("confirmed"):
+                    return self.redirect(303, "/openid/interaction/" + uid)
+                code = secrets.token_hex(8)
+                STATE["interactions"][uid]["code"] = code
+                return self.redirect(303, "%s/auth/callback?code=%s&state=%s"
+                                     % (self.chat_origin(), code, it["pre"]))
+        self.send(404, {"message": "not found"})
+
+    def do_POST(self):
+        u = urlparse(self.path)
+        parts = u.path.strip("/").split("/")
+        body = self.body_json()
+        with LOCK:
+            if len(parts) == 4 and parts[:2] == ["openid", "interaction"]:
+                uid = parts[2]
+                it = STATE["interactions"].get(uid)
+                if not it or self.cookies().get("_interaction") != it["icookie"]:
+                    return self.send(400, {"message": "interaction cookie missing"})
+                if body is None:
+                    return self.send(400, {"message": "bad JSON"})
+                if parts[3] == "login":
+                    note("login attempt user=%r totp=%r"
+                         % (body.get("username"), body.get("totpToken")))
+                    user, pw = body.get("username"), body.get("password")
+                    if pw != "test" or user not in ("test", "totp", "passkey", "consent"):
+                        return self.send(401, {"status": "Unauthorized",
+                                               "message": "Username and password does not match"})
+                    if user == "passkey":
+                        return self.send(200, {"twoFactorRequired": True,
+                                               "totpRequired": False,
+                                               "passkeyOptions": {}})
+                    if user == "totp":
+                        tok = body.get("totpToken") or ""
+                        if not tok:
+                            return self.send(200, {"twoFactorRequired": True,
+                                                   "totpRequired": True,
+                                                   "passkeyOptions": None})
+                        if tok != "123456":
+                            return self.send(401, {"status": "Unauthorized",
+                                                   "message": "Invalid totpToken"})
+                    it["user"] = "u-" + user
+                    it["consent"] = user == "consent"
+                    return self.send(200, {"redirectTo": "%s/openid/auth/%s"
+                                           % (self.login_origin(), uid)})
+                if parts[3] == "confirm":
+                    if not it["user"]:
+                        return self.send(400, {"message": "not logged in"})
+                    it["confirmed"] = True
+                    return self.redirect(303, "/openid/auth/" + uid)
+        self.send(404, {"message": "not found"})
+
+
+class ChatHandler(Base):
+    def user(self):
+        return STATE["sessions"].get(self.cookies().get("connect.sid"))
+
+    def do_GET(self):
+        u = urlparse(self.path)
+        q = parse_qs(u.query)
+        p = u.path
+        with LOCK:
+            if p == "/auth/login":
+                sid = "pre-" + secrets.token_hex(8)
+                STATE["sessions"][sid] = None
+                return self.redirect(302, "%s/openid/auth?client_id=chat&state=%s"
+                                     % (self.login_origin(), sid),
+                                     [("Set-Cookie", "connect.sid=%s; Path=/; "
+                                       "Expires=Mon, 23 Nov 2026 18:03:29 GMT; HttpOnly; SameSite=Lax" % sid)])
+            if p == "/auth/callback":
+                sid = self.cookies().get("connect.sid")
+                state = q.get("state", [""])[0]
+                code = q.get("code", [""])[0]
+                it = next((i for i in STATE["interactions"].values()
+                           if i.get("code") == code), None)
+                if not sid or sid != state or sid not in STATE["sessions"] or not it:
+                    return self.redirect(302, "/?error=auth_failed")
+                new = "s%3A" + it["user"] + "." + secrets.token_hex(8)
+                del STATE["sessions"][sid]
+                STATE["sessions"][new] = it["user"]
+                return self.redirect(302, "/auth/return", [
+                    ("Set-Cookie", "connect.sid=%s; Path=/; HttpOnly" % new)])
+            if p == "/auth/return":
+                return self.redirect(302, "/")
+            if p == "/auth/logout":
+                STATE["sessions"].pop(self.cookies().get("connect.sid"), None)
+                return self.redirect(302, "/", [
+                    ("Set-Cookie", "connect.sid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT")])
+            if p == "/":
+                return self.send(200, "<!DOCTYPE html><html><body>chat SPA</body></html>",
+                                 "text/html")
+            if p == "/debug/state":
+                st = {"messages": STATE["messages"],
+                      "reads": {"%s|%s" % k: v for k, v in STATE["reads"].items()},
+                      "channels": {k: dict(v, members=sorted(v["members"]))
+                                   for k, v in STATE["channels"].items()},
+                      "sessions": STATE["sessions"], "log": STATE["log"][-200:]}
+                return self.send(200, st)
+            if p == "/api/config":
+                return self.send(200, {"providerName": "Mock", "gifEnabled": False})
+            uid = self.user()
+            if not uid:
+                return self.send(401, {"error": "Unauthorized"})
+            if p == "/api/me":
+                return self.send(200, dict(STATE["users"][uid], email="", picture="",
+                                           active=True))
+            if p == "/api/channels":
+                return self.send(200, [channel_json(c, uid) for c in STATE["channels"].values()
+                                       if c["type"] != "dm" and uid in c["members"]])
+            if p == "/api/channels/public":
+                return self.send(200, [channel_json(c, uid) for c in
+                                       sorted(STATE["channels"].values(),
+                                              key=lambda c: c["name"] or "")
+                                       if c["type"] == "public" and uid not in c["members"]])
+            if p == "/api/dms":
+                return self.send(200, [dm_json(c, uid) for c in STATE["channels"].values()
+                                       if c["type"] == "dm" and uid in c["members"]])
+            if p == "/api/users":
+                return self.send(200, [dict(x, email="", picture="", active=True)
+                                       for x in STATE["users"].values()])
+            parts = p.strip("/").split("/")
+            if len(parts) == 4 and parts[:2] == ["api", "channels"] and parts[3] == "messages":
+                c = STATE["channels"].get(parts[2])
+                if not c or uid not in c["members"]:
+                    return self.send(403, {"error": "Not a member"})
+                limit = min(int(q.get("limit", ["50"])[0]), 200)
+                msgs = STATE["messages"][c["id"]]
+                ids = [m["id"] for m in msgs]
+                if "after" in q:
+                    a = q["after"][0]
+                    if a not in ids:
+                        return self.send(404, {"error": "Message not found"})
+                    rows = msgs[ids.index(a) + 1:][:limit]
+                    return self.send(200, list(reversed(rows)))
+                end = len(msgs)
+                if "before" in q:
+                    b = q["before"][0]
+                    if b not in ids:
+                        return self.send(404, {"error": "Message not found"})
+                    end = ids.index(b)
+                rows = msgs[max(0, end - limit):end]
+                return self.send(200, list(reversed(rows)))
+        self.send(404, {"error": "Not found"})
+
+    def do_POST(self):
+        u = urlparse(self.path)
+        p = u.path
+        body = self.body_json()
+        with LOCK:
+            if p == "/debug/inject":
+                m = add_message(body["channel"], body.get("user", "u-alice"), body["body"])
+                return self.send(201, m)
+            if p == "/debug/presence":
+                STATE["presence"][body["user"]] = body["presence"]
+                return self.send(200, {})
+            uid = self.user()
+            if not uid:
+                return self.send(401, {"error": "Unauthorized"})
+            if body is None:
+                return self.send(400, {"error": "bad JSON"})
+            parts = p.strip("/").split("/")
+            if p == "/api/dms":
+                other = body.get("userId")
+                if other not in STATE["users"]:
+                    return self.send(400, {"error": "Unknown user"})
+                for c in STATE["channels"].values():
+                    if c["type"] == "dm" and c["members"] == {uid, other}:
+                        return self.send(200, dm_json(c, uid))
+                cid = "d-" + secrets.token_hex(4)
+                add_channel(cid, None, "dm", [uid, other])
+                return self.send(201, dm_json(STATE["channels"][cid], uid))
+            if len(parts) == 4 and parts[:2] == ["api", "channels"]:
+                c = STATE["channels"].get(parts[2])
+                if not c:
+                    return self.send(404, {"error": "Channel not found"})
+                if parts[3] == "join":
+                    if c["type"] != "public":
+                        return self.send(403, {"error": "Forbidden"})
+                    c["members"].add(uid)
+                    return self.send(200, channel_json(c, uid))
+                if uid not in c["members"]:
+                    return self.send(403, {"error": "Not a member"})
+                if parts[3] == "read":
+                    msgs = STATE["messages"][c["id"]]
+                    if msgs:
+                        STATE["reads"][(c["id"], uid)] = msgs[-1]["id"]
+                    return self.send(200, {"unreadCount": 0})
+                if parts[3] == "messages":
+                    text = (body.get("body") or "").strip()
+                    if not text:
+                        return self.send(400, {"error": "Message must not be empty"})
+                    cid_ = body.get("clientId")
+                    for m in STATE["messages"][c["id"]]:
+                        if cid_ and m["clientId"] == cid_:
+                            return self.send(201, m)
+                    m = add_message(c["id"], uid, text, client_id=cid_)
+                    STATE["reads"][(c["id"], uid)] = m["id"]
+                    return self.send(201, m)
+        self.send(404, {"error": "Not found"})
+
+
+def serve(handler, port, label):
+    srv = ThreadingHTTPServer((ARGS.host, port), handler)
+    srv.label = label
+    srv.daemon_threads = True
+    threading.Thread(target=srv.serve_forever, daemon=True).start()
+    return srv
+
+
+def main():
+    global ARGS
+    ap = argparse.ArgumentParser(description=__doc__,
+                                 formatter_class=argparse.RawDescriptionHelpFormatter)
+    ap.add_argument("--host", default="0.0.0.0")
+    ap.add_argument("--chat-port", type=int, default=18080)
+    ap.add_argument("--login-port", type=int, default=18081)
+    ap.add_argument("--public-host", default="10.0.2.2",
+                    help="address the guest uses to reach this host")
+    ap.add_argument("--messages", type=int, default=120,
+                    help="history messages seeded into #general")
+    ap.add_argument("-v", "--verbose", action="store_true")
+    ARGS = ap.parse_args()
+    seed(ARGS.messages)
+    serve(ChatHandler, ARGS.chat_port, "chat")
+    serve(LoginHandler, ARGS.login_port, "login")
+    print("mock chat on :%d, login on :%d (guest: http://%s:%d)"
+          % (ARGS.chat_port, ARGS.login_port, ARGS.public_host, ARGS.chat_port),
+          flush=True)
+    try:
+        threading.Event().wait()
+    except KeyboardInterrupt:
+        pass
+
+
+if __name__ == "__main__":
+    main()

+ 406 - 0
tools/qmp_chat_test.py

@@ -0,0 +1,406 @@
+#!/usr/bin/env python3
+"""Headless end-to-end test of the chat client against tools/mock_chat.py.
+
+Boots floppy.img/root.img in QEMU with an NE2000 on slirp plus a USB
+keyboard and mouse, starts the mock Chat + OIDC server on the host
+(reachable from the guest as 10.0.2.2), then drives the chat app with QMP
+send-key / input-send-event.
+
+Scenarios (one per run):
+  full (default)  native login, send, live poll + read marker, PgUp, older
+                  paging (Home), conversation switch (Esc, Down), browse +
+                  join (Ctrl+B), new DM (Ctrl+N), sign out (click) and a
+                  relaunch that resumes the saved /share/chat.cfg session
+  --totp          TOTP account: wrong code first, then the right one
+  --consent       login followed by the consent interaction
+  --passkey       passkey-only account: must land on the cookie screen
+  --wrong         wrong password first, then the right one
+
+Screenshots go to --out (PNG).  Exit code 0 = pass.
+
+  tools/qmp_chat_test.py [--out DIR] [--totp|--consent|--passkey|--wrong]
+"""
+import json
+import os
+import shutil
+import socket
+import struct
+import subprocess
+import sys
+import tempfile
+import time
+import urllib.request
+import zlib
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+CHAT_PORT = 18080
+LOGIN_PORT = 18081
+
+
+def qmp_recv(s):
+    buf = b""
+    while True:
+        chunk = s.recv(65536)
+        if not chunk:
+            raise RuntimeError("QMP connection closed")
+        buf += chunk
+        while b"\n" in buf:
+            line, buf = buf.split(b"\n", 1)
+            line = line.strip()
+            if line:
+                msg = json.loads(line)
+                if "event" in msg:
+                    continue
+                return msg
+
+
+def qmp_cmd(s, execute, arguments=None):
+    req = {"execute": execute}
+    if arguments is not None:
+        req["arguments"] = arguments
+    s.sendall((json.dumps(req) + "\n").encode())
+    msg = qmp_recv(s)
+    if "error" in msg:
+        print("QMP error:", msg)
+    return msg
+
+
+KEYMAP = {" ": ["spc"], ":": ["shift", "semicolon"], "/": ["slash"],
+          ".": ["dot"], "-": ["minus"], "_": ["shift", "minus"],
+          "\n": ["ret"], "\t": ["tab"], ",": ["comma"], "!": ["shift", "1"],
+          "@": ["shift", "2"], "?": ["shift", "slash"], "'": ["apostrophe"]}
+
+
+def key_list(ch):
+    if ch in KEYMAP:
+        return KEYMAP[ch]
+    if ch.isdigit() or ("a" <= ch <= "z"):
+        return [ch]
+    if "A" <= ch <= "Z":
+        return ["shift", ch.lower()]
+    raise ValueError("no qcode for %r" % ch)
+
+
+def send_keys(s, keys, delay=0.12):
+    qmp_cmd(s, "send-key", {"keys": [{"type": "qcode", "data": k} for k in keys]})
+    time.sleep(delay)
+
+
+def type_text(s, text):
+    for ch in text:
+        send_keys(s, key_list(ch))
+
+
+def ppm_to_png(ppm, png):
+    data = open(ppm, "rb").read()
+    parts = data.split(b"\n", 3)
+    w, h = [int(x) for x in parts[1].split()]
+    px = parts[3]
+    raw = b"".join(b"\x00" + px[y * w * 3:(y + 1) * w * 3] for y in range(h))
+
+    def chunk(tag, body):
+        return (struct.pack(">I", len(body)) + tag + body +
+                struct.pack(">I", zlib.crc32(tag + body) & 0xffffffff))
+    with open(png, "wb") as f:
+        f.write(b"\x89PNG\r\n\x1a\n")
+        f.write(chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)))
+        f.write(chunk(b"IDAT", zlib.compress(raw, 6)))
+        f.write(chunk(b"IEND", b""))
+
+
+def move(s, dx, dy):
+    while dx or dy:
+        ex = max(-100, min(100, dx))
+        ey = max(-100, min(100, dy))
+        qmp_cmd(s, "input-send-event", {"events": [
+            {"type": "rel", "data": {"axis": "x", "value": ex}},
+            {"type": "rel", "data": {"axis": "y", "value": ey}}]})
+        dx -= ex
+        dy -= ey
+        time.sleep(0.05)
+
+
+def click(s, x, y):
+    """Move to the top-left corner (the cursor clamps), then to x,y."""
+    move(s, -3000, -3000)
+    time.sleep(0.2)
+    move(s, x, y)
+    time.sleep(0.3)
+    for down in (True, False):
+        qmp_cmd(s, "input-send-event", {"events": [
+            {"type": "btn", "data": {"down": down, "button": "left"}}]})
+        time.sleep(0.2)
+
+
+def shot(s, workdir, out, name):
+    ppm = os.path.join(workdir, "s.ppm")
+    if os.path.exists(ppm):
+        os.unlink(ppm)
+    qmp_cmd(s, "screendump", {"filename": ppm})
+    for _ in range(50):
+        if os.path.exists(ppm) and os.path.getsize(ppm) > 100:
+            break
+        time.sleep(0.1)
+    time.sleep(0.3)
+    png = os.path.join(out, name + ".png")
+    ppm_to_png(ppm, png)
+    print("screenshot:", png)
+
+
+def mock_get(path):
+    with urllib.request.urlopen("http://127.0.0.1:%d%s" % (CHAT_PORT, path),
+                                timeout=5) as r:
+        return json.loads(r.read().decode())
+
+
+def mock_post(path, body):
+    req = urllib.request.Request("http://127.0.0.1:%d%s" % (CHAT_PORT, path),
+                                 data=json.dumps(body).encode(),
+                                 headers={"Content-Type": "application/json"})
+    with urllib.request.urlopen(req, timeout=5) as r:
+        return json.loads(r.read().decode())
+
+
+def wait_for(pred, timeout, what):
+    end = time.time() + timeout
+    while time.time() < end:
+        try:
+            if pred():
+                return True
+        except Exception:
+            pass
+        time.sleep(0.5)
+    print("TIMEOUT waiting for", what)
+    return False
+
+
+def main():
+    out = os.path.join(ROOT, "chat-test-out")
+    if "--out" in sys.argv:
+        out = sys.argv[sys.argv.index("--out") + 1]
+    os.makedirs(out, exist_ok=True)
+    totp = "--totp" in sys.argv
+    consent = "--consent" in sys.argv
+    passkey = "--passkey" in sys.argv
+    wrong = "--wrong" in sys.argv
+    full = not (totp or consent or passkey or wrong)
+    keep = "--keep" in sys.argv
+    mocklog = os.path.join(out, "mock.log")
+
+    def logged(sub):
+        return any(sub in l for l in open(mocklog))
+
+    for f in ("floppy.img", "root.img"):
+        if not os.path.exists(os.path.join(ROOT, f)):
+            print("%s missing - run `make all` first" % f)
+            return 1
+
+    workdir = tempfile.mkdtemp(prefix="nebos-chat-")
+    sock = os.path.join(workdir, "qmp.sock")
+    serial = os.path.join(out, "serial.log")
+    mock = subprocess.Popen([sys.executable, os.path.join(ROOT, "tools", "mock_chat.py"),
+                             "--chat-port", str(CHAT_PORT),
+                             "--login-port", str(LOGIN_PORT), "-v"],
+                            stdout=open(os.path.join(out, "mock.log"), "w"),
+                            stderr=subprocess.STDOUT)
+    qemu = ["qemu-system-i386", "-M", "pc", "-m", "512",
+            "-device", "pci-ohci", "-device", "usb-mouse", "-device", "usb-kbd",
+            "-device", "ne2k_pci,netdev=n0", "-netdev", "user,id=n0",
+            "-drive", "file=floppy.img,format=raw,if=floppy",
+            "-drive", "file=root.img,format=raw,if=floppy",
+            "-display", "none", "-serial", "file:" + serial,
+            "-qmp", "unix:%s,server,nowait" % sock]
+    proc = subprocess.Popen(qemu, cwd=ROOT, stdout=subprocess.DEVNULL,
+                            stderr=subprocess.DEVNULL)
+    results = []
+
+    def check(name, ok):
+        results.append((name, ok))
+        print("%-40s %s" % (name, "ok" if ok else "FAIL"), flush=True)
+        return ok
+
+    s = None
+    try:
+        for _ in range(100):
+            if os.path.exists(sock):
+                break
+            time.sleep(0.1)
+        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+        s.connect(sock)
+        qmp_recv(s)
+        qmp_cmd(s, "qmp_capabilities")
+        wait_for(lambda: b"booted" in open(serial, "rb").read(), 60, "boot line")
+        time.sleep(12.0)                  # WM, terminal, DHCP
+        shot(s, workdir, out, "0-desktop")
+
+        type_text(s, "chat\n")
+        time.sleep(6.0)
+        shot(s, workdir, out, "1-server")
+
+        send_keys(s, ["ctrl", "u"])
+        type_text(s, "http://10.0.2.2:%d\n" % CHAT_PORT)
+        check("login form fetched",
+              wait_for(lambda: any("interaction" in l and '" 200' in l
+                                   for l in open(os.path.join(out, "mock.log"))),
+                       30, "login page"))
+        time.sleep(2.0)
+        shot(s, workdir, out, "2-credentials")
+
+        user = "totp" if totp else "consent" if consent else \
+            "passkey" if passkey else "test"
+        if wrong:
+            type_text(s, user + "\t" + "nope\n")
+            check("wrong password rejected",
+                  wait_for(lambda: logged("login attempt user='test'") and
+                           logged('/login HTTP/1.1" 401'), 30, "401"))
+            time.sleep(2.0)
+            shot(s, workdir, out, "2a-wrong")
+            # the password field is cleared and focused
+            type_text(s, "test\n")
+        else:
+            type_text(s, user + "\t" + "test" + "\n")
+        if passkey:
+            check("passkey falls back to cookie screen",
+                  wait_for(lambda: logged("login attempt user='passkey'"), 30,
+                           "passkey attempt"))
+            time.sleep(3.0)
+            shot(s, workdir, out, "2c-passkey")
+            check("no session for passkey account",
+                  "u-passkey" not in mock_get("/debug/state")["sessions"].values())
+            raise StopIteration
+        if totp:
+            time.sleep(5.0)
+            shot(s, workdir, out, "2b-totp")
+            type_text(s, "654321\n")
+            check("wrong TOTP rejected",
+                  wait_for(lambda: logged("totp='654321'"), 30, "bad totp"))
+            time.sleep(3.0)
+            shot(s, workdir, out, "2b-totp-wrong")
+            type_text(s, "123456\n")
+        check("session established",
+              wait_for(lambda: ("u-" + user) in mock_get("/debug/state")["sessions"].values(),
+                       40, "session"))
+        if consent:
+            check("consent confirmed", logged("/confirm HTTP/1.1\" 303"))
+        check("history loaded",
+              wait_for(lambda: logged("/api/channels/c-general/messages?limit=50"),
+                       30, "history"))
+        time.sleep(4.0)
+        shot(s, workdir, out, "3-main")
+        if not full:
+            raise StopIteration
+
+        type_text(s, "Hello from NebOS, it works!\n")
+        check("message sent",
+              wait_for(lambda: any(m["body"] == "Hello from NebOS, it works!" and
+                                   m["userId"] == "u-" + user and
+                                   (m["clientId"] or "").startswith("nebos-")
+                                   for m in mock_get("/debug/state")["messages"]["c-general"]),
+                       30, "sent message"))
+        time.sleep(3.0)
+        shot(s, workdir, out, "4-sent")
+
+        injected = mock_post("/debug/inject", {"channel": "c-general", "user": "u-alice",
+                                               "body": "Live reply from Alice \u2013 polled"})
+        check("live message read",
+              wait_for(lambda: mock_get("/debug/state")["reads"].get(
+                  "c-general|u-" + user) == injected["id"], 30, "read marker"))
+        time.sleep(1.5)
+        shot(s, workdir, out, "5-live")
+
+        for _ in range(4):
+            send_keys(s, ["pgup"], 0.4)
+        time.sleep(2.0)
+        shot(s, workdir, out, "6-scrolled")
+
+        send_keys(s, ["esc"])
+        send_keys(s, ["home"])
+        check("older page loaded",
+              wait_for(lambda: logged("messages?limit=50&before="), 30, "older"))
+        time.sleep(3.0)
+        shot(s, workdir, out, "7-older")
+
+        send_keys(s, ["end"])
+        send_keys(s, ["down"])
+        check("switched to #secret",
+              wait_for(lambda: logged("/api/channels/c-secret/messages?limit=50") and
+                       logged("POST /api/channels/c-secret/read"), 30, "secret"))
+        time.sleep(2.0)
+        shot(s, workdir, out, "8-secret")
+
+        send_keys(s, ["ctrl", "b"])
+        check("public channels listed",
+              wait_for(lambda: logged("GET /api/channels/public"), 20, "browse"))
+        time.sleep(2.0)
+        shot(s, workdir, out, "9-browse")
+        send_keys(s, ["down"])          # sorted: design, random
+        send_keys(s, ["ret"])
+        check("joined #random",
+              wait_for(lambda: "u-test" in mock_get("/debug/state")["channels"]
+                       ["c-random"]["members"], 20, "join"))
+        time.sleep(3.0)
+        shot(s, workdir, out, "10-joined")
+
+        send_keys(s, ["ctrl", "n"])
+        check("users listed",
+              wait_for(lambda: logged("GET /api/users"), 20, "users"))
+        type_text(s, "Bob")
+        time.sleep(1.0)
+        shot(s, workdir, out, "11-newdm")
+        send_keys(s, ["ret"])
+        check("DM with Bob created",
+              wait_for(lambda: any(c["type"] == "dm" and
+                                   sorted(c["members"]) == ["u-bob", "u-test"]
+                                   for c in mock_get("/debug/state")["channels"].values()),
+                       20, "dm"))
+        time.sleep(3.0)
+        shot(s, workdir, out, "12-dm")
+        type_text(s, "Hi Bob\n")
+        check("DM message sent",
+              wait_for(lambda: any(m["body"] == "Hi Bob"
+                                   for cid, ms in mock_get("/debug/state")["messages"].items()
+                                   if cid.startswith("d-") for m in ms), 20, "dm msg"))
+
+        # Close the window (title-bar x), relaunch: the saved session in
+        # /share/chat.cfg must log in without the password.
+        click(s, 1028, 81)
+        time.sleep(2.0)
+        click(s, 200, 300)              # focus the terminal
+        time.sleep(1.0)
+        n_me = sum(1 for l in open(mocklog) if "GET /api/me" in l)
+        type_text(s, "chat\n")
+        check("saved session resumed",
+              wait_for(lambda: sum(1 for l in open(mocklog) if "GET /api/me" in l) > n_me and
+                       sum(1 for l in open(mocklog) if "GET /api/channels HTTP" in l) >= 2,
+                       40, "resume"))
+        time.sleep(4.0)
+        shot(s, workdir, out, "13-resumed")
+
+        click(s, 987, 112)              # Sign out
+        check("signed out",
+              wait_for(lambda: logged("GET /auth/logout"), 20, "logout"))
+        time.sleep(2.0)
+        shot(s, workdir, out, "14-signed-out")
+
+    except StopIteration:
+        pass                            # scenario finished early
+    finally:
+        try:
+            qmp_cmd(s, "quit")
+            proc.wait(timeout=10)
+        except Exception:
+            pass
+        if proc.poll() is None:
+            proc.kill()
+            proc.wait()
+        mock.terminate()
+        mock.wait()
+        if not keep:
+            shutil.rmtree(workdir, ignore_errors=True)
+    failed = [n for n, ok in results if not ok]
+    print("chat e2e: %s" % ("PASS" if results and not failed else "FAIL " + ", ".join(failed)))
+    return 0 if results and not failed else 1
+
+
+if __name__ == "__main__":
+    sys.exit(main())

+ 2502 - 0
ucmd_chat.c

@@ -0,0 +1,2502 @@
+/* chat: native client for Cloudron Chat on the ngui canvas toolkit.
+ *
+ * Login is the native Cloudron OIDC driver in chat_login.c (username,
+ * password, optional TOTP) or a pasted session cookie.  The session cookie is
+ * kept in a uhttp cookie jar and saved with the server address in a small
+ * config file (/share/chat.cfg by default, or the path given as argument).
+ * The password is never stored.
+ *
+ * Everything else is the Chat REST API over uhttp: the channel and DM
+ * directory, message pages (newest first, older paging with ?before=, live
+ * updates with ?after=), sending, read markers, joining public channels and
+ * opening DMs.  There is no WebSocket: the open conversation is polled every
+ * ~2 s and the directory every ~12 s, and polling waits while the user types.
+ *
+ * Network calls block the UI; the frame showing the "Loading" status is
+ * presented first.  TLS certificates are NOT verified (tls.c phase A), which
+ * the login screen says. */
+
+#include "ucmd_lib.h"
+#include "ngui.h"
+#include "uhttp.h"
+#include "ujson.h"
+#include "chat_login.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#define DEFAULT_CFG    "/share/chat.cfg"
+#define RESP_CAP       (512u * 1024u)
+#define JSON_NODES     16384u
+#define JSON_SCAP      (RESP_CAP + 2u * JSON_NODES)
+
+#define MAX_CONV       128
+#define MAX_MSG        240
+#define MAX_PICK       256
+#define BODY_MAX       4096
+#define PAGE_SIZE      50
+#define LIVE_PAGE      50
+
+#define POLL_CONV_MS        2000
+#define POLL_CONV_IDLE_MS   5000
+#define POLL_DIR_MS         12000
+#define POLL_DIR_IDLE_MS    20000
+#define TYPING_HOLD_MS      1000
+#define KEEPALIVE_IDLE_MS   30000
+
+/* widget IDs */
+enum {
+	ID_SERVER = 1, ID_CFG, ID_SIGNIN, ID_COOKIE_MODE, ID_USER, ID_PASS,
+	ID_TOTP, ID_BACK, ID_COOKIE, ID_USE_COOKIE, ID_COMPOSE, ID_SEND,
+	ID_REFRESH, ID_SIGNOUT, ID_BROWSE, ID_NEWDM, ID_OLDER, ID_NEWMSG,
+	ID_RETRY, ID_MODAL_CLOSE, ID_FILTER, ID_MODAL_ROW = 1000
+};
+
+enum screen { SCR_SERVER, SCR_CRED, SCR_TOTP, SCR_COOKIE, SCR_MAIN };
+enum modal { MODAL_NONE, MODAL_BROWSE, MODAL_NEWDM };
+
+/* pending actions, collected while drawing and run after the frame */
+enum {
+	ACT_NONE, ACT_START_LOGIN, ACT_SUBMIT, ACT_SUBMIT_TOTP, ACT_USE_COOKIE,
+	ACT_SEND, ACT_REFRESH, ACT_SIGNOUT, ACT_OPEN_CONV, ACT_OLDER,
+	ACT_BROWSE, ACT_NEWDM, ACT_JOIN, ACT_OPEN_DM, ACT_RETRY,
+	ACT_COOKIE_SCREEN, ACT_BACK
+};
+
+struct conv {
+	char id[48];
+	char name[64];
+	char preview[96];
+	char kind;              /* 'c' public, 'p' private, 'd' DM */
+	char presence;          /* DM: 'o' online, 'a' away, 'f' offline */
+	int unread;
+};
+
+struct msg {
+	char id[48];
+	char user_id[48];
+	char author[48];
+	char created[32];       /* ISO 8601 UTC, sorts as text */
+	char reply[96];         /* "Name: snippet" */
+	char extra[112];        /* attachments / thread / reactions line */
+	char *body;             /* Latin-1, malloc'd */
+	unsigned char action;   /* type "me" */
+	int height;
+	int layout_w;
+	int compact;
+	int day_header;
+};
+
+struct pick {
+	char id[48];
+	char name[64];
+	char sub[64];
+};
+
+static struct ngui ui;
+static struct uhttp http;
+static struct uhttp_jar jar;
+static struct chat_login login;
+static struct ujson json;
+static struct ujson_node *jnodes;
+static char *jsbuf;
+static char *resp;
+static unsigned int resp_len;
+
+static enum screen screen = SCR_SERVER;
+static enum modal modal = MODAL_NONE;
+static int action, action_arg;
+
+static char cfg_path[CHAT_PATH_MAX];
+static char server[CHAT_SERVER_MAX];
+static char server_host[UHTTP_HOST_MAX];
+static int server_secure;
+static char saved_cookie[CHAT_COOKIE_MAX];
+static unsigned int saved_jar_changes;
+
+static char me_id[48];
+static char me_name[64];
+
+static struct ngui_input server_in, cfg_in, user_in, pass_in, totp_in;
+static struct ngui_input cookie_in, compose_in, filter_in;
+
+static struct conv convs[MAX_CONV];
+static int nconv;
+static int cur = -1;            /* index into convs */
+static char cur_id[48];
+
+static struct msg msgs[MAX_MSG];
+static int nmsg;
+static int has_older;
+static unsigned int msgs_gen;   /* bumped whenever msgs[] changes */
+static int history_full;
+static struct ngui_scroll tl_scroll, side_scroll, modal_scroll;
+static int at_bottom = 1;
+static int new_below;
+
+static struct pick picks[MAX_PICK];
+static int npick;
+static int modal_sel;           /* keyboard selection among visible rows */
+static unsigned int last_older_ms;
+
+static char status[160];
+static int status_err;
+static char busy[96];
+static int offline;
+static unsigned int backoff_ms;
+static unsigned int next_conv_poll, next_dir_poll, retry_at;
+static unsigned int last_input_ms;
+static unsigned int last_net_ms;
+static unsigned int client_seq;
+
+/* ---- small string helpers ---- */
+
+static void s_copy(char *d, const char *s, unsigned int cap)
+{
+	unsigned int i = 0;
+
+	if (!cap)
+		return;
+	while (s && s[i] && i + 1 < cap) {
+		d[i] = s[i];
+		i++;
+	}
+	d[i] = '\0';
+}
+
+static void s_cat(char *d, const char *s, unsigned int cap)
+{
+	unsigned int n = (unsigned int)strlen(d);
+
+	if (n < cap)
+		s_copy(d + n, s, cap - n);
+}
+
+static void s_cat_uint(char *d, unsigned int v, unsigned int cap)
+{
+	char tmp[12];
+	int i = 11;
+
+	tmp[i] = '\0';
+	do {
+		tmp[--i] = (char)('0' + v % 10);
+		v /= 10;
+	} while (v && i > 0);
+	s_cat(d, tmp + i, cap);
+}
+
+static void set_status(const char *a, const char *b, int err)
+{
+	status[0] = '\0';
+	s_cat(status, a, sizeof(status));
+	if (b)
+		s_cat(status, b, sizeof(status));
+	status_err = err;
+	ngui_invalidate(&ui);
+}
+
+/* ---- UTF-8 -> Latin-1 display text ---- */
+
+static unsigned int put_ascii(char *d, unsigned int n, unsigned int cap,
+			      const char *s)
+{
+	while (*s && n + 1 < cap)
+		d[n++] = *s++;
+	return n;
+}
+
+/* Map a code point outside Latin-1 to a short ASCII stand-in; NULL to skip
+ * it entirely (joiners, variation selectors, skin tones). */
+static const char *cp_fallback(unsigned int cp)
+{
+	switch (cp) {
+	case 0x2018: case 0x2019: case 0x201A: case 0x2032: return "'";
+	case 0x201C: case 0x201D: case 0x201E: case 0x2033: return "\"";
+	case 0x2010: case 0x2011: case 0x2012: case 0x2013: return "-";
+	case 0x2014: case 0x2015: return "--";
+	case 0x2026: return "...";
+	case 0x2022: case 0x2023: case 0x25CF: return "\xb7";
+	case 0x20AC: return "EUR";
+	case 0x2122: return "TM";
+	case 0x2192: return "->";
+	case 0x2190: return "<-";
+	case 0x2264: return "<=";
+	case 0x2265: return ">=";
+	case 0x2260: return "!=";
+	case 0x2764: case 0x2665: return "<3";
+	case 0x2705: case 0x2714: case 0x2713: return "[v]";
+	case 0x274C: case 0x2716: return "[x]";
+	case 0x26A0: return "/!\\";
+	case 0x1F44D: return "(y)";
+	case 0x1F44E: return "(n)";
+	case 0x1F44B: return "o/";
+	case 0x1F64F: return "_/\\_";
+	case 0x1F389: case 0x1F38A: return "*\\o/*";
+	case 0x1F600: case 0x1F603: case 0x1F604: case 0x1F60A:
+	case 0x1F642: case 0x263A: return ":)";
+	case 0x1F601: case 0x1F606: case 0x1F602: case 0x1F923: return ":D";
+	case 0x1F609: return ";)";
+	case 0x1F61B: case 0x1F61C: case 0x1F61D: return ":P";
+	case 0x1F622: case 0x1F62D: case 0x1F641: case 0x2639: return ":(";
+	case 0x1F62E: case 0x1F632: return ":O";
+	case 0x1F914: return ":-/";
+	case 0x1F525: return "(fire)";
+	case 0x1F680: return "(rocket)";
+	case 0x1F440: return "(eyes)";
+	case 0x200B: case 0x200C: case 0x200D: case 0xFEFF:
+		return 0;
+	}
+	if (cp >= 0xFE00 && cp <= 0xFE0F)
+		return 0;               /* variation selectors */
+	if (cp >= 0x1F3FB && cp <= 0x1F3FF)
+		return 0;               /* skin tones */
+	if (cp >= 0x2000 && cp <= 0x200A)
+		return " ";
+	return "?";
+}
+
+/* Convert UTF-8 to Latin-1 display text.  Tabs become spaces, other control
+ * characters (except newline) are dropped. */
+static unsigned int to_latin1(char *d, unsigned int cap, const char *s)
+{
+	const unsigned char *p = (const unsigned char *)s;
+	unsigned int n = 0;
+
+	if (!cap)
+		return 0;
+	while (*p && n + 1 < cap) {
+		unsigned int cp, extra, i;
+
+		if (*p < 0x80) {
+			cp = *p++;
+		} else {
+			if ((*p & 0xE0) == 0xC0) {
+				cp = *p & 0x1F;
+				extra = 1;
+			} else if ((*p & 0xF0) == 0xE0) {
+				cp = *p & 0x0F;
+				extra = 2;
+			} else if ((*p & 0xF8) == 0xF0) {
+				cp = *p & 0x07;
+				extra = 3;
+			} else {
+				p++;
+				d[n++] = '?';
+				continue;
+			}
+			p++;
+			for (i = 0; i < extra; i++) {
+				if ((*p & 0xC0) != 0x80)
+					break;
+				cp = (cp << 6) | (*p++ & 0x3F);
+			}
+			if (i < extra) {
+				d[n++] = '?';
+				continue;
+			}
+		}
+		if (cp == '\t' || cp == 0xA0) {
+			d[n++] = ' ';
+		} else if (cp == '\n') {
+			d[n++] = '\n';
+		} else if (cp < 0x20 || cp == 0x7F || (cp >= 0x80 && cp < 0xA0)) {
+			continue;
+		} else if (cp < 0x100) {
+			d[n++] = (char)cp;
+		} else {
+			const char *f = cp_fallback(cp);
+
+			if (f)
+				n = put_ascii(d, n, cap, f);
+		}
+	}
+	d[n] = '\0';
+	return n;
+}
+
+/* One-line version (newlines become spaces), for previews/snippets. */
+static void to_latin1_line(char *d, unsigned int cap, const char *s)
+{
+	unsigned int i;
+
+	to_latin1(d, cap, s);
+	for (i = 0; d[i]; i++)
+		if (d[i] == '\n')
+			d[i] = ' ';
+}
+
+/* ---- config file ---- */
+
+static int read_file(const char *path, char *buf, unsigned int cap)
+{
+	int n = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)(cap - 1));
+
+	if (n < 0)
+		return n;
+	buf[n] = '\0';
+	return n;
+}
+
+static int write_file(const char *path, const char *buf, unsigned int len)
+{
+	return u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, (int)len);
+}
+
+static int set_server(const char *s)
+{
+	char norm[CHAT_SERVER_MAX];
+
+	if (chat_server_normalize(s, norm, sizeof(norm)) != 0)
+		return -1;
+	if (chat_server_host(norm, server_host, sizeof(server_host),
+			     &server_secure) != 0)
+		return -1;
+	s_copy(server, norm, sizeof(server));
+	return 0;
+}
+
+/* Export the Chat host's cookies and write the config file. */
+static void save_config(void)
+{
+	static char out[CHAT_COOKIE_MAX + CHAT_SERVER_MAX + 128];
+	int n;
+
+	uhttp_jar_header(&jar, server_host, "/api/me", server_secure,
+			 saved_cookie, sizeof(saved_cookie));
+	saved_jar_changes = jar.changes;
+	n = chat_config_format(out, sizeof(out), server, saved_cookie);
+	if (n < 0 || write_file(cfg_path, out, (unsigned int)n) < 0)
+		set_status("Could not save the session to ", cfg_path, 1);
+	memset(out, 0, sizeof(out));
+}
+
+/* A server may roll its session cookie: save when the jar changed. */
+static void maybe_save_cookie(void)
+{
+	char now[CHAT_COOKIE_MAX];
+
+	if (jar.changes == saved_jar_changes || screen != SCR_MAIN)
+		return;
+	uhttp_jar_header(&jar, server_host, "/api/me", server_secure, now,
+			 sizeof(now));
+	saved_jar_changes = jar.changes;
+	if (strcmp(now, saved_cookie) != 0)
+		save_config();
+}
+
+/* ---- HTTP / JSON plumbing ---- */
+
+static void paint_now(void);
+
+static void net_drop(void)
+{
+	http.keepalive = 0;
+	uhttp_close(&http);
+}
+
+/* Request server + path; JSON body or NULL.  Returns the HTTP status or a
+ * UHTTP_ERR_*; the body is in resp/resp_len. */
+static int api(const char *method, const char *path, const char *body)
+{
+	char url[CHAT_SERVER_MAX + 256];
+	unsigned int len = 0;
+	int st;
+
+	s_copy(url, server, sizeof(url));
+	s_cat(url, path, sizeof(url));
+	http.jar = &jar;
+	http.accept = "application/json";
+	st = chat_http(&http, method, url, body, resp, RESP_CAP, &len);
+	resp_len = st > 0 ? len : 0;
+	last_net_ms = u_ticks_ms();
+	maybe_save_cookie();
+	return st;
+}
+
+static int parse_resp(void)
+{
+	int root = ujson_parse(&json, resp, resp_len);
+
+	return root;
+}
+
+static void go_login(const char *why);
+
+/* Common error handling for API calls in the main screen.  Returns 1 when
+ * the status is a success. */
+static int api_ok(int st, const char *what)
+{
+	if (st >= 200 && st < 300) {
+		if (offline) {
+			offline = 0;
+			set_status("Connected", 0, 0);
+		}
+		backoff_ms = 0;
+		return 1;
+	}
+	if (st == 401) {
+		go_login("Session expired - please sign in again");
+		return 0;
+	}
+	if (st > 0) {
+		char code[64];
+
+		s_copy(code, what, sizeof(code));
+		s_cat(code, ": HTTP ", sizeof(code));
+		s_cat_uint(code, (unsigned int)st, sizeof(code));
+		set_status(code, 0, 1);
+		return 0;
+	}
+	offline = 1;
+	backoff_ms = backoff_ms == 0 ? 2000 : backoff_ms < 5000 ? 5000 :
+		     backoff_ms < 10000 ? 10000 : 30000;
+	retry_at = u_ticks_ms() + backoff_ms;
+	set_status("Offline: ", uhttp_error_string(st), 1);
+	net_drop();
+	return 0;
+}
+
+/* ---- conversations ---- */
+
+static int conv_find(const char *id)
+{
+	int i;
+
+	for (i = 0; i < nconv; i++)
+		if (strcmp(convs[i].id, id) == 0)
+			return i;
+	return -1;
+}
+
+static void conv_from_json(struct conv *c, int o, int dm)
+{
+	int last;
+
+	s_copy(c->id, ujson_get_str(&json, o, "id"), sizeof(c->id));
+	c->unread = (int)ujson_int(&json, ujson_get(&json, o, "unreadCount"), 0);
+	c->preview[0] = '\0';
+	last = ujson_get(&json, o, "lastMessage");
+	if (ujson_type(&json, last) == UJSON_OBJECT) {
+		char tmp[96];
+
+		to_latin1_line(tmp, sizeof(tmp),
+			       ujson_get_str(&json, last, "authorName"));
+		s_copy(c->preview, tmp, sizeof(c->preview));
+		s_cat(c->preview, ": ", sizeof(c->preview));
+		to_latin1_line(tmp, sizeof(tmp),
+			       ujson_get_str(&json, last, "body"));
+		s_cat(c->preview, tmp, sizeof(c->preview));
+	}
+	if (dm) {
+		int other = ujson_get(&json, o, "otherUser");
+		const char *pres = ujson_get_str(&json, o, "presence");
+		const char *nm = ujson_get_str(&json, other, "name");
+
+		if (!nm[0])
+			nm = ujson_get_str(&json, other, "username");
+		to_latin1_line(c->name, sizeof(c->name), nm[0] ? nm : "(unknown)");
+		c->kind = 'd';
+		c->presence = strcmp(pres, "online") == 0 ? 'o' :
+			      strcmp(pres, "away") == 0 ? 'a' : 'f';
+	} else {
+		to_latin1_line(c->name, sizeof(c->name),
+			       ujson_get_str(&json, o, "name"));
+		c->kind = strcmp(ujson_get_str(&json, o, "type"), "private") == 0 ?
+			  'p' : 'c';
+		c->presence = 0;
+	}
+}
+
+static int load_directory(void)
+{
+	static struct conv next[MAX_CONV];
+	int n = 0, st, root, it, pass;
+
+	for (pass = 0; pass < 2; pass++) {
+		st = api(0, pass ? "/api/dms" : "/api/channels", 0);
+		if (!api_ok(st, pass ? "Direct messages" : "Channels"))
+			return -1;
+		root = parse_resp();
+		if (root < 0) {
+			set_status("Bad directory reply: ", json.error, 1);
+			return -1;
+		}
+		for (it = ujson_first(&json, root); it >= 0 && n < MAX_CONV;
+		     it = ujson_next(&json, it)) {
+			if (ujson_truthy(&json, ujson_get(&json, it, "archived")))
+				continue;
+			if (pass && ujson_truthy(&json, ujson_get(&json, it,
+								  "isSelf")))
+				continue;
+			conv_from_json(&next[n], it, pass);
+			if (next[n].id[0])
+				n++;
+		}
+	}
+	memcpy(convs, next, sizeof(struct conv) * (unsigned int)n);
+	nconv = n;
+	cur = cur_id[0] ? conv_find(cur_id) : -1;
+	if (cur >= 0 && at_bottom)
+		convs[cur].unread = 0;  /* we are reading it */
+	ngui_invalidate(&ui);
+	return 0;
+}
+
+/* ---- messages ---- */
+
+static void msg_free(struct msg *m)
+{
+	free(m->body);
+	m->body = 0;
+}
+
+static void clear_messages(void)
+{
+	int i;
+
+	for (i = 0; i < nmsg; i++)
+		msg_free(&msgs[i]);
+	nmsg = 0;
+	msgs_gen++;
+	has_older = 0;
+	history_full = 0;
+	new_below = 0;
+}
+
+static int msg_find(const char *id)
+{
+	int i;
+
+	for (i = nmsg - 1; i >= 0; i--)
+		if (strcmp(msgs[i].id, id) == 0)
+			return i;
+	return -1;
+}
+
+static void build_extra(struct msg *m, int o)
+{
+	int it, n;
+
+	m->extra[0] = '\0';
+	for (it = ujson_first(&json, ujson_get(&json, o, "attachments"));
+	     it >= 0; it = ujson_next(&json, it)) {
+		char name[64];
+
+		to_latin1_line(name, sizeof(name),
+			       ujson_get_str(&json, it, "filename"));
+		if (m->extra[0])
+			s_cat(m->extra, ", ", sizeof(m->extra));
+		else
+			s_cat(m->extra, "[file] ", sizeof(m->extra));
+		s_cat(m->extra, name, sizeof(m->extra));
+	}
+	if (ujson_type(&json, ujson_get(&json, o, "gif")) == UJSON_OBJECT) {
+		if (m->extra[0])
+			s_cat(m->extra, "  ", sizeof(m->extra));
+		s_cat(m->extra, "[GIF]", sizeof(m->extra));
+	}
+	if (strcmp(ujson_get_str(&json, o, "type"), "poll") == 0) {
+		if (m->extra[0])
+			s_cat(m->extra, "  ", sizeof(m->extra));
+		s_cat(m->extra, "[poll - open in the web app]", sizeof(m->extra));
+	}
+	if (ujson_get_str(&json, o, "callUrl")[0]) {
+		if (m->extra[0])
+			s_cat(m->extra, "  ", sizeof(m->extra));
+		s_cat(m->extra, "[call]", sizeof(m->extra));
+	}
+	n = (int)ujson_int(&json, ujson_get(&json, o, "threadCount"), 0);
+	if (n > 0) {
+		if (m->extra[0])
+			s_cat(m->extra, "  \xb7 ", sizeof(m->extra));
+		s_cat_uint(m->extra, (unsigned int)n, sizeof(m->extra));
+		s_cat(m->extra, n == 1 ? " reply" : " replies", sizeof(m->extra));
+	}
+	n = 0;
+	for (it = ujson_first(&json, ujson_get(&json, o, "reactions"));
+	     it >= 0; it = ujson_next(&json, it)) {
+		int c = (int)ujson_int(&json, ujson_get(&json, it, "count"), 1);
+
+		n += c > 0 ? c : 1;
+	}
+	if (n > 0) {
+		if (m->extra[0])
+			s_cat(m->extra, "  \xb7 ", sizeof(m->extra));
+		s_cat_uint(m->extra, (unsigned int)n, sizeof(m->extra));
+		s_cat(m->extra, n == 1 ? " reaction" : " reactions",
+		      sizeof(m->extra));
+	}
+	if (ujson_truthy(&json, ujson_get(&json, o, "pinned"))) {
+		if (m->extra[0])
+			s_cat(m->extra, "  \xb7 ", sizeof(m->extra));
+		s_cat(m->extra, "pinned", sizeof(m->extra));
+	}
+}
+
+/* Fill m from a message object; 0 ok, -1 skip (deleted/thread reply). */
+static int msg_from_json(struct msg *m, int o)
+{
+	static char body[BODY_MAX + 8];
+	const char *nm;
+	int rt;
+	unsigned int len;
+
+	if (ujson_truthy(&json, ujson_get(&json, o, "deleted")))
+		return -1;
+	/* Thread replies live in the thread panel, not the timeline. */
+	if (ujson_get_str(&json, o, "parentId")[0])
+		return -1;
+	memset(m, 0, sizeof(*m));
+	s_copy(m->id, ujson_get_str(&json, o, "id"), sizeof(m->id));
+	if (!m->id[0])
+		return -1;
+	s_copy(m->user_id, ujson_get_str(&json, o, "userId"), sizeof(m->user_id));
+	nm = ujson_get_str(&json, o, "authorName");
+	if (!nm[0])
+		nm = ujson_get_str(&json, o, "authorUsername");
+	to_latin1_line(m->author, sizeof(m->author), nm[0] ? nm : "?");
+	s_copy(m->created, ujson_get_str(&json, o, "createdAt"),
+	       sizeof(m->created));
+	m->action = strcmp(ujson_get_str(&json, o, "type"), "me") == 0;
+	len = to_latin1(body, BODY_MAX, ujson_get_str(&json, o, "body"));
+	if (len + 1 >= BODY_MAX) {
+		/* truncated: mark it */
+		body[BODY_MAX - 4] = '.';
+		body[BODY_MAX - 3] = '.';
+		body[BODY_MAX - 2] = '.';
+		body[BODY_MAX - 1] = '\0';
+	}
+	/* Trim trailing newlines/spaces. */
+	len = (unsigned int)strlen(body);
+	while (len && (body[len - 1] == '\n' || body[len - 1] == ' '))
+		body[--len] = '\0';
+	m->body = strdup(body);
+	if (!m->body)
+		return -1;
+	rt = ujson_get(&json, o, "replyTo");
+	if (ujson_type(&json, rt) == UJSON_OBJECT) {
+		char tmp[96];
+
+		to_latin1_line(m->reply, sizeof(m->reply),
+			       ujson_get_str(&json, rt, "authorName"));
+		s_cat(m->reply, ": ", sizeof(m->reply));
+		if (ujson_truthy(&json, ujson_get(&json, rt, "deleted")))
+			s_copy(tmp, "(deleted)", sizeof(tmp));
+		else
+			to_latin1_line(tmp, sizeof(tmp),
+				       ujson_get_str(&json, rt, "body"));
+		if (!tmp[0])
+			s_copy(tmp, "(attachment)", sizeof(tmp));
+		s_cat(m->reply, tmp, sizeof(m->reply));
+	}
+	build_extra(m, o);
+	return 0;
+}
+
+static int msg_before(const struct msg *a, const struct msg *b)
+{
+	int c = strcmp(a->created, b->created);
+
+	return c < 0 || (c == 0 && strcmp(a->id, b->id) < 0);
+}
+
+/* Insert or update a message, keeping msgs sorted.  older: we are paging
+ * back in history (never evict old messages for it).  Returns 1 when a new
+ * message was added, 0 when updated/skipped. */
+static int msg_merge(struct msg *m, int older)
+{
+	int i = msg_find(m->id), pos;
+
+	msgs_gen++;
+	if (i >= 0) {
+		/* Edited body or new reactions: replace in place. */
+		msg_free(&msgs[i]);
+		msgs[i] = *m;
+		return 0;
+	}
+	if (nmsg >= MAX_MSG) {
+		if (older) {
+			history_full = 1;
+			msg_free(m);
+			return 0;
+		}
+		msg_free(&msgs[0]);
+		memmove(&msgs[0], &msgs[1], sizeof(struct msg) * (MAX_MSG - 1));
+		nmsg--;
+		has_older = 1;
+		history_full = 1;
+	}
+	pos = nmsg;
+	while (pos > 0 && msg_before(m, &msgs[pos - 1]))
+		pos--;
+	memmove(&msgs[pos + 1], &msgs[pos],
+		sizeof(struct msg) * (unsigned int)(nmsg - pos));
+	msgs[pos] = *m;
+	nmsg++;
+	return 1;
+}
+
+/* Merge every message of the parsed reply.  Returns the number added. */
+static int merge_reply(int root, int older, int *count)
+{
+	int it, added = 0, n = 0;
+
+	for (it = ujson_first(&json, root); it >= 0; it = ujson_next(&json, it)) {
+		struct msg m;
+		const char *id = ujson_get_str(&json, it, "id");
+
+		n++;
+		if (ujson_truthy(&json, ujson_get(&json, it, "deleted"))) {
+			/* A deletion we already show: drop it. */
+			int k = msg_find(id);
+
+			if (k >= 0) {
+				msg_free(&msgs[k]);
+				memmove(&msgs[k], &msgs[k + 1],
+					sizeof(struct msg) *
+					(unsigned int)(nmsg - k - 1));
+				nmsg--;
+				msgs_gen++;
+			}
+			continue;
+		}
+		if (msg_from_json(&m, it) == 0)
+			added += msg_merge(&m, older);
+	}
+	if (count)
+		*count = n;
+	return added;
+}
+
+static void mark_read(void)
+{
+	char path[96];
+	int st;
+
+	if (cur < 0)
+		return;
+	s_copy(path, "/api/channels/", sizeof(path));
+	s_cat(path, convs[cur].id, sizeof(path));
+	s_cat(path, "/read", sizeof(path));
+	st = api("POST", path, 0);
+	if (api_ok(st, "Mark read"))
+		convs[cur].unread = 0;
+}
+
+static void msgs_path(char *path, unsigned int cap, const char *query)
+{
+	s_copy(path, "/api/channels/", cap);
+	s_cat(path, cur_id, cap);
+	s_cat(path, "/messages?", cap);
+	s_cat(path, query, cap);
+}
+
+static void scroll_to_end(void)
+{
+	tl_scroll.offset = 1 << 28;     /* clamped when laid out */
+	at_bottom = 1;
+	new_below = 0;
+}
+
+static void open_conv(int idx)
+{
+	char path[160];
+	int st, root, n = 0;
+
+	if (idx < 0 || idx >= nconv)
+		return;
+	cur = idx;
+	s_copy(cur_id, convs[idx].id, sizeof(cur_id));
+	clear_messages();
+	scroll_to_end();
+	s_copy(busy, "Loading messages...", sizeof(busy));
+	paint_now();
+	msgs_path(path, sizeof(path), "limit=50");
+	st = api(0, path, 0);
+	busy[0] = '\0';
+	if (!api_ok(st, "Messages"))
+		return;
+	root = parse_resp();
+	if (root < 0) {
+		set_status("Bad message reply: ", json.error, 1);
+		return;
+	}
+	merge_reply(root, 1, &n);
+	has_older = n >= PAGE_SIZE;
+	scroll_to_end();
+	mark_read();
+	next_conv_poll = u_ticks_ms() + POLL_CONV_MS;
+	ngui_invalidate(&ui);
+}
+
+static int content_height(void);
+
+static void load_older(void)
+{
+	char path[200], q[96];
+	int st, root, n = 0, before_h, added;
+
+	if (cur < 0 || !nmsg || history_full)
+		return;
+	last_older_ms = u_ticks_ms();
+	s_copy(q, "limit=50&before=", sizeof(q));
+	s_cat(q, msgs[0].id, sizeof(q));
+	msgs_path(path, sizeof(path), q);
+	s_copy(busy, "Loading older messages...", sizeof(busy));
+	paint_now();
+	st = api(0, path, 0);
+	busy[0] = '\0';
+	if (!api_ok(st, "Older messages"))
+		return;
+	root = parse_resp();
+	if (root < 0)
+		return;
+	before_h = content_height();
+	added = merge_reply(root, 1, &n);
+	has_older = n >= PAGE_SIZE && !history_full;
+	/* Keep the view on the same message. */
+	if (added)
+		tl_scroll.offset += content_height() - before_h;
+	ngui_invalidate(&ui);
+}
+
+static void poll_conv(void)
+{
+	char path[200], q[96];
+	int st, root, added, n = 0;
+
+	if (cur < 0)
+		return;
+	if (!nmsg) {
+		msgs_path(path, sizeof(path), "limit=50");
+	} else {
+		s_copy(q, "limit=50&after=", sizeof(q));
+		s_cat(q, msgs[nmsg - 1].id, sizeof(q));
+		msgs_path(path, sizeof(path), q);
+	}
+	st = api(0, path, 0);
+	if (st == 404 && nmsg) {
+		/* The anchor message was deleted: reload the page. */
+		open_conv(cur);
+		return;
+	}
+	if (!api_ok(st, "Messages"))
+		return;
+	root = parse_resp();
+	if (root < 0) {
+		set_status("Bad message reply: ", json.error, 1);
+		return;
+	}
+	added = merge_reply(root, 0, &n);
+	if (n >= LIVE_PAGE) {
+		/* More than a page arrived: jump to the newest page. */
+		open_conv(cur);
+		return;
+	}
+	if (added) {
+		if (at_bottom) {
+			scroll_to_end();
+			mark_read();
+		} else {
+			new_below += added;
+		}
+		ngui_invalidate(&ui);
+	}
+}
+
+static void make_client_id(char *out, unsigned int cap)
+{
+	static const char hex[] = "0123456789abcdef";
+	unsigned int v = u_ticks_ms() ^ ((unsigned int)u_getpid() << 20);
+	unsigned int c = ++client_seq, i;
+
+	s_copy(out, "nebos-", cap);
+	for (i = 0; i < 8; i++) {
+		char ch[2] = { hex[(v >> (28 - 4 * i)) & 15], 0 };
+
+		s_cat(out, ch, cap);
+	}
+	s_cat(out, "-", cap);
+	s_cat_uint(out, c, cap);
+}
+
+static void send_message(void)
+{
+	static char body[NGUI_INPUT_MAX * 6 + 160];
+	char path[96], cid[40];
+	int st, root, r;
+	unsigned int n = 0;
+	const char *t = compose_in.text;
+
+	while (*t == ' ')
+		t++;
+	if (cur < 0 || !*t)
+		return;
+	make_client_id(cid, sizeof(cid));
+	s_copy(body, "{\"body\":", sizeof(body));
+	n = (unsigned int)strlen(body);
+	{
+		/* The field holds Latin-1/ASCII: encode as UTF-8 for JSON. */
+		static char utf8[NGUI_INPUT_MAX * 2 + 4];
+		unsigned int k = 0;
+		const unsigned char *p = (const unsigned char *)t;
+
+		while (*p && k + 3 < sizeof(utf8)) {
+			if (*p < 0x80) {
+				utf8[k++] = (char)*p;
+			} else {
+				utf8[k++] = (char)(0xC0 | (*p >> 6));
+				utf8[k++] = (char)(0x80 | (*p & 0x3F));
+			}
+			p++;
+		}
+		utf8[k] = '\0';
+		r = ujson_escape(body + n, sizeof(body) - n, utf8);
+	}
+	if (r < 0)
+		return;
+	n += (unsigned int)r;
+	s_cat(body, ",\"clientId\":\"", sizeof(body));
+	s_cat(body, cid, sizeof(body));
+	s_cat(body, "\"}", sizeof(body));
+	s_copy(path, "/api/channels/", sizeof(path));
+	s_cat(path, cur_id, sizeof(path));
+	s_cat(path, "/messages", sizeof(path));
+	s_copy(busy, "Sending...", sizeof(busy));
+	paint_now();
+	st = api("POST", path, body);
+	busy[0] = '\0';
+	if (!api_ok(st, "Send")) {
+		if (st > 0) {
+			char msg[96];
+
+			root = parse_resp();
+			s_copy(msg, root >= 0 ?
+			       ujson_get_str(&json, root, "error") : "", sizeof(msg));
+			if (msg[0])
+				set_status("Send failed: ", msg, 1);
+		}
+		return;              /* the text stays in the composer */
+	}
+	ngui_input_set(&compose_in, "");
+	root = parse_resp();
+	if (root >= 0 && ujson_type(&json, root) == UJSON_OBJECT) {
+		struct msg m;
+
+		if (msg_from_json(&m, root) == 0)
+			msg_merge(&m, 0);
+	}
+	scroll_to_end();
+	mark_read();
+	next_conv_poll = u_ticks_ms() + POLL_CONV_MS;
+	ngui_set_focus(&ui, ID_COMPOSE);
+}
+
+/* ---- browse / new DM ---- */
+
+static void load_picks(int dms)
+{
+	int st, root, it;
+
+	npick = 0;
+	ngui_input_set(&filter_in, "");
+	s_copy(busy, dms ? "Loading people..." : "Loading channels...",
+	       sizeof(busy));
+	paint_now();
+	st = api(0, dms ? "/api/users" : "/api/channels/public", 0);
+	busy[0] = '\0';
+	if (!api_ok(st, dms ? "Users" : "Public channels"))
+		return;
+	root = parse_resp();
+	if (root < 0)
+		return;
+	for (it = ujson_first(&json, root); it >= 0 && npick < MAX_PICK;
+	     it = ujson_next(&json, it)) {
+		struct pick *p = &picks[npick];
+		const char *nm;
+
+		s_copy(p->id, ujson_get_str(&json, it, "id"), sizeof(p->id));
+		if (!p->id[0])
+			continue;
+		if (dms) {
+			if (strcmp(p->id, me_id) == 0)
+				continue;
+			nm = ujson_get_str(&json, it, "name");
+			if (!nm[0])
+				nm = ujson_get_str(&json, it, "username");
+			to_latin1_line(p->name, sizeof(p->name), nm);
+			to_latin1_line(p->sub, sizeof(p->sub),
+				       ujson_get_str(&json, it, "username"));
+		} else {
+			to_latin1_line(p->name, sizeof(p->name),
+				       ujson_get_str(&json, it, "name"));
+			to_latin1_line(p->sub, sizeof(p->sub),
+				       ujson_get_str(&json, it, "description"));
+		}
+		npick++;
+	}
+	modal = dms ? MODAL_NEWDM : MODAL_BROWSE;
+	modal_scroll.offset = 0;
+	modal_sel = 0;
+	ngui_set_focus(&ui, ID_FILTER);
+}
+
+static void pick_action(int idx)
+{
+	char path[128], body[96], id[48];
+	int st, root;
+
+	if (idx < 0 || idx >= npick)
+		return;
+	if (modal == MODAL_BROWSE) {
+		s_copy(path, "/api/channels/", sizeof(path));
+		s_cat(path, picks[idx].id, sizeof(path));
+		s_cat(path, "/join", sizeof(path));
+		s_copy(busy, "Joining...", sizeof(busy));
+		paint_now();
+		st = api("POST", path, 0);
+		busy[0] = '\0';
+		if (!api_ok(st, "Join"))
+			return;
+		s_copy(id, picks[idx].id, sizeof(id));
+	} else {
+		s_copy(body, "{\"userId\":", sizeof(body));
+		if (ujson_escape(body + strlen(body), sizeof(body) - strlen(body),
+				 picks[idx].id) < 0)
+			return;
+		s_cat(body, "}", sizeof(body));
+		s_copy(busy, "Opening conversation...", sizeof(busy));
+		paint_now();
+		st = api("POST", "/api/dms", body);
+		busy[0] = '\0';
+		if (!api_ok(st, "New DM"))
+			return;
+		root = parse_resp();
+		s_copy(id, root >= 0 ? ujson_get_str(&json, root, "id") : "",
+		       sizeof(id));
+	}
+	modal = MODAL_NONE;
+	if (load_directory() == 0 && id[0]) {
+		int k = conv_find(id);
+
+		if (k >= 0)
+			open_conv(k);
+	}
+}
+
+/* ---- session ---- */
+
+static void enter_main(void)
+{
+	int root;
+
+	screen = SCR_MAIN;
+	offline = 0;
+	backoff_ms = 0;
+	root = parse_resp();         /* the /api/me reply */
+	if (root >= 0) {
+		const char *nm = ujson_get_str(&json, root, "name");
+
+		s_copy(me_id, ujson_get_str(&json, root, "id"), sizeof(me_id));
+		to_latin1_line(me_name, sizeof(me_name),
+			       nm[0] ? nm : ujson_get_str(&json, root, "username"));
+	}
+	set_status("Connected", 0, 0);
+	if (load_directory() == 0 && nconv > 0 && cur < 0) {
+		int i, pick = 0;
+
+		for (i = 0; i < nconv; i++) {
+			if (convs[i].kind != 'd' &&
+			    strcmp(convs[i].name, "general") == 0) {
+				pick = i;
+				break;
+			}
+		}
+		open_conv(pick);
+	}
+	next_dir_poll = u_ticks_ms() + POLL_DIR_MS;
+	ngui_set_focus(&ui, ID_COMPOSE);
+}
+
+static void go_login(const char *why)
+{
+	net_drop();
+	uhttp_jar_clear(&jar);
+	saved_jar_changes = jar.changes;
+	saved_cookie[0] = '\0';
+	screen = SCR_SERVER;
+	modal = MODAL_NONE;
+	clear_messages();
+	nconv = 0;
+	cur = -1;
+	cur_id[0] = '\0';
+	set_status(why, 0, why != 0);
+	ngui_set_focus(&ui, ID_SERVER);
+}
+
+/* After the jar holds a session: validate it with /api/me. */
+static int check_session(int keep_offline)
+{
+	unsigned int len = 0;
+	int r;
+
+	s_copy(busy, "Checking session...", sizeof(busy));
+	paint_now();
+	r = chat_session_check(&http, &jar, server, resp, RESP_CAP, &len);
+	busy[0] = '\0';
+	resp_len = len;
+	if (r == 0) {
+		save_config();
+		enter_main();
+		return 0;
+	}
+	if (r == 1) {
+		go_login("The saved session is no longer valid - sign in again");
+		return -1;
+	}
+	if (keep_offline) {
+		/* Network trouble: keep the cached session and retry. */
+		screen = SCR_MAIN;
+		offline = 1;
+		backoff_ms = 5000;
+		retry_at = u_ticks_ms() + backoff_ms;
+		set_status("Offline: ", r < 0 && r > -100 ?
+			   uhttp_error_string(r) : "server error", 1);
+		return -1;
+	}
+	set_status("Session check failed: ", r < 0 && r > -100 ?
+		   uhttp_error_string(r) : "server error", 1);
+	return -1;
+}
+
+static void start_login(void)
+{
+	int r;
+
+	if (set_server(server_in.text) != 0) {
+		set_status("Enter a server such as chat.example.com", 0, 1);
+		return;
+	}
+	if (cfg_in.text[0])
+		s_copy(cfg_path, cfg_in.text, sizeof(cfg_path));
+	uhttp_jar_clear(&jar);
+	s_copy(busy, "Contacting the server...", sizeof(busy));
+	paint_now();
+	r = chat_login_start(&login, &http, &jar, server, resp, RESP_CAP);
+	busy[0] = '\0';
+	net_drop();
+	if (r == CHAT_LOGIN_OK) {
+		resp_len = (unsigned int)strlen(resp);
+		save_config();
+		enter_main();
+		return;
+	}
+	if (r == CHAT_LOGIN_FORM) {
+		screen = SCR_CRED;
+		set_status("", 0, 0);
+		ngui_set_focus(&ui, user_in.len ? ID_PASS : ID_USER);
+		return;
+	}
+	if (r == CHAT_LOGIN_NOFORM) {
+		screen = SCR_COOKIE;
+		set_status(login.error, 0, 1);
+		ngui_set_focus(&ui, ID_COOKIE);
+		return;
+	}
+	set_status(login.error, 0, 1);
+}
+
+static void wipe_secrets(void)
+{
+	memset(pass_in.text, 0, sizeof(pass_in.text));
+	pass_in.len = pass_in.cursor = pass_in.anchor = pass_in.scroll = 0;
+	memset(totp_in.text, 0, sizeof(totp_in.text));
+	totp_in.len = totp_in.cursor = totp_in.anchor = totp_in.scroll = 0;
+}
+
+static void submit_login(int with_totp)
+{
+	int r;
+
+	if (!user_in.text[0] || !pass_in.text[0]) {
+		set_status("Enter the username and password", 0, 1);
+		return;
+	}
+	s_copy(busy, "Signing in...", sizeof(busy));
+	paint_now();
+	r = chat_login_submit(&login, &http, &jar, user_in.text, pass_in.text,
+			      with_totp ? totp_in.text : "", resp, RESP_CAP);
+	busy[0] = '\0';
+	net_drop();
+	if (r == CHAT_LOGIN_TOTP) {
+		if (with_totp) {
+			set_status("The code was not accepted", 0, 1);
+		} else {
+			screen = SCR_TOTP;
+			set_status("", 0, 0);
+		}
+		ngui_set_focus(&ui, ID_TOTP);
+		return;
+	}
+	if (r == CHAT_LOGIN_OK) {
+		wipe_secrets();
+		resp_len = (unsigned int)strlen(resp);
+		save_config();
+		enter_main();
+		return;
+	}
+	if (r == CHAT_LOGIN_DENIED && screen == SCR_TOTP) {
+		/* A wrong TOTP code is also a 401. */
+		set_status(login.error, 0, 1);
+		ngui_input_set(&totp_in, "");
+		return;
+	}
+	if (r == CHAT_LOGIN_DENIED) {
+		memset(pass_in.text, 0, sizeof(pass_in.text));
+		ngui_input_set(&pass_in, "");
+		ngui_set_focus(&ui, ID_PASS);
+	}
+	if (r == CHAT_LOGIN_PASSKEY || r == CHAT_LOGIN_ERROR)
+		wipe_secrets();
+	if (r == CHAT_LOGIN_PASSKEY)
+		screen = SCR_COOKIE;
+	set_status(login.error, 0, 1);
+}
+
+static void use_cookie(void)
+{
+	if (set_server(server_in.text) != 0) {
+		set_status("Enter a server such as chat.example.com", 0, 1);
+		return;
+	}
+	if (cfg_in.text[0])
+		s_copy(cfg_path, cfg_in.text, sizeof(cfg_path));
+	uhttp_jar_clear(&jar);
+	{
+		const char *c = cookie_in.text;
+
+		/* Accept a pasted "Cookie: ..." header too. */
+		if (strncmp(c, "Cookie:", 7) == 0 || strncmp(c, "cookie:", 7) == 0)
+			c += 7;
+		if (uhttp_jar_import(&jar, server_host, server_secure, c) <= 0) {
+			set_status("Paste the cookie as name=value", 0, 1);
+			return;
+		}
+	}
+	check_session(0);
+	if (screen == SCR_MAIN)
+		ngui_input_set(&cookie_in, "");
+}
+
+static void sign_out(void)
+{
+	/* Best effort: end the server session too. */
+	if (server[0]) {
+		s_copy(busy, "Signing out...", sizeof(busy));
+		paint_now();
+		api(0, "/auth/logout", 0);
+		busy[0] = '\0';
+	}
+	go_login("Signed out");
+	{
+		static char out[CHAT_SERVER_MAX + 80];
+		int n = chat_config_format(out, sizeof(out), server, "");
+
+		if (n > 0)
+			write_file(cfg_path, out, (unsigned int)n);
+	}
+}
+
+static void load_config(void)
+{
+	static char buf[CHAT_COOKIE_MAX + CHAT_SERVER_MAX + 256];
+	char srv[CHAT_SERVER_MAX];
+	int n = read_file(cfg_path, buf, sizeof(buf));
+
+	ngui_input_set(&cfg_in, cfg_path);
+	if (n <= 0 || chat_config_parse(buf, (unsigned int)n, srv, sizeof(srv),
+					saved_cookie,
+					sizeof(saved_cookie)) != 0) {
+		ngui_input_set(&server_in, "chat.cloudron.io");
+		saved_cookie[0] = '\0';
+		memset(buf, 0, sizeof(buf));
+		return;
+	}
+	memset(buf, 0, sizeof(buf));
+	ngui_input_set(&server_in, srv);
+	if (set_server(srv) != 0 || !saved_cookie[0])
+		return;
+	uhttp_jar_import(&jar, server_host, server_secure, saved_cookie);
+	saved_jar_changes = jar.changes;
+	check_session(1);
+}
+
+/* ---- text layout ---- */
+
+static int line_h(void)
+{
+	int h = ngui_text_line_height(&ui, ui.font_px, 0);
+
+	return h > 0 ? h : 16;
+}
+
+static int text_w(const char *s, unsigned int n, int bold)
+{
+	return (int)ngui_text_width_px(&ui, s, n, ui.font_px, bold, 0, 0);
+}
+
+/* Length of the next wrapped line of s (n bytes) for width maxw; *adv gets
+ * the bytes to skip to the next line. */
+static unsigned int wrap_line(const char *s, unsigned int n, int maxw,
+			      unsigned int *adv)
+{
+	unsigned int i = 0, end = 0, j;
+
+	if (n && s[0] == '\n') {
+		*adv = 1;
+		return 0;
+	}
+	for (;;) {
+		j = i;
+		while (j < n && s[j] == ' ')
+			j++;
+		while (j < n && s[j] != ' ' && s[j] != '\n')
+			j++;
+		if (j == i)
+			break;
+		if (text_w(s, j, 0) > maxw) {
+			if (end == 0) {
+				/* One word wider than the line: split it. */
+				unsigned int k = 1;
+
+				while (k < j && text_w(s, k + 1, 0) <= maxw)
+					k++;
+				*adv = k;
+				return k;
+			}
+			break;
+		}
+		end = j;
+		i = j;
+		if (j >= n || s[j] == '\n')
+			break;
+	}
+	*adv = end;
+	while (*adv < n && s[*adv] == ' ')
+		(*adv)++;
+	if (*adv < n && s[*adv] == '\n')
+		(*adv)++;
+	return end;
+}
+
+static int count_lines(const char *s, int maxw)
+{
+	unsigned int n = (unsigned int)strlen(s), pos = 0, adv;
+	int lines = 0;
+
+	if (!n)
+		return 0;
+	while (pos < n) {
+		wrap_line(s + pos, n - pos, maxw, &adv);
+		if (!adv)
+			adv = 1;
+		pos += adv;
+		lines++;
+	}
+	return lines;
+}
+
+#define AVATAR    32
+#define TEXT_X    52
+#define PAD_TOP   8
+#define PAD_GROUP 2
+
+static int same_day(const struct msg *a, const struct msg *b)
+{
+	return strncmp(a->created, b->created, 10) == 0;
+}
+
+static int same_group(const struct msg *a, const struct msg *b)
+{
+	unsigned int ta, tb;
+
+	if (strcmp(a->user_id, b->user_id) != 0 || !same_day(a, b) ||
+	    b->reply[0] || b->action)
+		return 0;
+	/* HH:MM at offsets 11..15: within five minutes */
+	ta = (unsigned int)atoi(a->created + 11) * 60 +
+	     (unsigned int)atoi(a->created + 14);
+	tb = (unsigned int)atoi(b->created + 11) * 60 +
+	     (unsigned int)atoi(b->created + 14);
+	return tb >= ta && tb - ta <= 5;
+}
+
+static void layout_msg(int i, int width)
+{
+	struct msg *m = &msgs[i];
+	int lh = line_h(), h, tw = width - TEXT_X - 12;
+
+	if (tw < 40)
+		tw = 40;
+	m->day_header = i == 0 || !same_day(&msgs[i - 1], m);
+	m->compact = i > 0 && !m->day_header && same_group(&msgs[i - 1], m);
+	h = m->compact ? PAD_GROUP : PAD_TOP + lh + 2;
+	if (m->day_header)
+		h += lh + 12;
+	if (m->reply[0])
+		h += lh + 2;
+	h += count_lines(m->body, tw) * lh;
+	if (m->extra[0])
+		h += lh + 2;
+	h += 2;
+	if (!m->compact && h < PAD_TOP + AVATAR + 4)
+		h = PAD_TOP + AVATAR + 4;
+	m->height = h;
+	m->layout_w = width;
+}
+
+static int tl_width;
+static unsigned int laid_gen;
+static int laid_font = -1;
+
+/* Heights depend on the width, the font and the neighbours (grouping and
+ * day headers), so any change re-lays out every message. */
+static int content_height(void)
+{
+	int i, h = has_older || history_full ? 36 : 8;
+	int all = laid_gen != msgs_gen || laid_font != line_h();
+
+	for (i = 0; i < nmsg; i++) {
+		if (all || msgs[i].layout_w != tl_width)
+			layout_msg(i, tl_width);
+		h += msgs[i].height;
+	}
+	laid_gen = msgs_gen;
+	laid_font = line_h();
+	return h + 8;
+}
+
+/* ---- drawing helpers ---- */
+
+static unsigned short avatar_color(const char *id)
+{
+	static const unsigned short pal[] = {
+		NGUI_RGB(0xd0, 0x5a, 0x5a), NGUI_RGB(0x5a, 0x9a, 0xd0),
+		NGUI_RGB(0x5a, 0xb0, 0x70), NGUI_RGB(0xc0, 0x8a, 0x3a),
+		NGUI_RGB(0x9a, 0x6a, 0xc8), NGUI_RGB(0x3a, 0xa8, 0xa8),
+		NGUI_RGB(0xc8, 0x6a, 0xa0), NGUI_RGB(0x80, 0x90, 0x40),
+	};
+	unsigned int h = 0;
+
+	while (*id)
+		h = h * 31 + (unsigned char)*id++;
+	return pal[h % (sizeof(pal) / sizeof(pal[0]))];
+}
+
+static void draw_avatar(int x, int y, int size, const char *name,
+			const char *id)
+{
+	struct ngui_rect r = { x, y, size, size };
+	char ini[2];
+	int tw;
+
+	ngui_fill_round_rect(&ui, r, size / 2, size / 2, size / 2, size / 2,
+			     avatar_color(id));
+	ini[0] = name[0] ? name[0] : '?';
+	if (ini[0] >= 'a' && ini[0] <= 'z')
+		ini[0] = (char)(ini[0] - 'a' + 'A');
+	ini[1] = '\0';
+	tw = text_w(ini, 1, 1);
+	ngui_text_px(&ui, x + (size - tw) / 2, y + (size - line_h()) / 2, ini, 1,
+		     NGUI_RGB(0xff, 0xff, 0xff), ui.font_px, 1, 0, 0);
+}
+
+static void draw_dot(int x, int y, int d, unsigned short color, int filled)
+{
+	struct ngui_rect r = { x, y, d, d };
+
+	if (filled)
+		ngui_fill_round_rect(&ui, r, d / 2, d / 2, d / 2, d / 2, color);
+	else
+		ngui_frame_round(&ui, r, d / 2, d / 2, d / 2, d / 2, 1, color);
+}
+
+static void draw_badge(int right, int y, int count)
+{
+	char num[12] = "";
+	int tw, w;
+	struct ngui_rect r;
+
+	if (count > 99)
+		s_copy(num, "99+", sizeof(num));
+	else
+		s_cat_uint(num, (unsigned int)count, sizeof(num));
+	tw = text_w(num, (unsigned int)strlen(num), 1);
+	w = tw + 12;
+	r.x = right - w;
+	r.y = y;
+	r.w = w;
+	r.h = line_h() + 2;
+	ngui_fill_round_rect(&ui, r, r.h / 2, r.h / 2, r.h / 2, r.h / 2,
+			     ui.theme.accent);
+	ngui_text_px(&ui, r.x + 6, y + 1, num, (unsigned int)strlen(num),
+		     NGUI_RGB(0xff, 0xff, 0xff), ui.font_px, 1, 0, 0);
+}
+
+static void draw_lock(int x, int y, unsigned short c)
+{
+	struct ngui_rect body = { x, y + 5, 9, 7 };
+	struct ngui_rect shackle = { x + 2, y + 1, 5, 6 };
+
+	ngui_frame_round(&ui, shackle, 2, 2, 0, 0, 1, c);
+	ngui_fill_rect(&ui, body, c);
+}
+
+static void label(struct ngui_rect *body, const char *text)
+{
+	struct ngui_rect r = ngui_cut_top(body, 20);
+
+	ngui_text(&ui, r.x, r.y + 2, text, ui.theme.text_dim);
+}
+
+/* ---- login screens ---- */
+
+static struct ngui_rect card_rect(int h)
+{
+	struct ngui_rect r;
+	int w = ui.w - 40 < 460 ? ui.w - 40 : 460;
+
+	if (w < 200)
+		w = ui.w;
+	r.w = w;
+	r.h = h;
+	r.x = (ui.w - w) / 2;
+	r.y = (ui.h - h) / 2 > 10 ? (ui.h - h) / 2 : 10;
+	return r;
+}
+
+static void field(struct ngui_rect *body, const char *text, unsigned int id,
+		  struct ngui_input *in, unsigned int next_id, int submit_act)
+{
+	int r;
+
+	label(body, text);
+	r = ngui_text_input(&ui, id, ngui_cut_top(body, 30), in);
+	ngui_cut_top(body, 8);
+	if (r & NGUI_INPUT_NEXT)
+		ngui_set_focus(&ui, next_id);
+	if ((r & NGUI_INPUT_SUBMIT) && submit_act)
+		action = submit_act;
+}
+
+static void draw_status_line(struct ngui_rect *body)
+{
+	struct ngui_rect r = ngui_cut_top(body, 22);
+
+	if (busy[0])
+		ngui_text_ellipsis(&ui, r, r.x, r.y + 2, busy, ui.theme.accent);
+	else if (status[0])
+		ngui_text_ellipsis(&ui, r, r.x, r.y + 2, status,
+				   status_err ? ui.theme.error : ui.theme.text_dim);
+}
+
+static void notice(struct ngui_rect *body, const char *text)
+{
+	struct ngui_rect r = ngui_cut_top(body, 18);
+
+	ngui_text_ellipsis(&ui, r, r.x, r.y, text, ui.theme.text_dim);
+}
+
+static void draw_login(void)
+{
+	struct ngui_rect all = { 0, 0, ui.w, ui.h };
+	struct ngui_rect card, body, r, b;
+	int h = screen == SCR_SERVER ? 380 : screen == SCR_COOKIE ? 400 :
+		screen == SCR_TOTP ? 250 : 300;
+
+	ngui_fill_rect(&ui, all, ui.theme.bg);
+	card = card_rect(h);
+	ngui_fill_rect(&ui, card, ui.theme.panel);
+	ngui_frame(&ui, card, ui.theme.border);
+	body = card;
+	ngui_inset(&body, 18);
+
+	r = ngui_cut_top(&body, 30);
+	ngui_text_px(&ui, r.x, r.y, "NebOS Chat", 10, ui.theme.text, 22, 1, 0, 0);
+
+	if (screen == SCR_SERVER) {
+		field(&body, "Server", ID_SERVER, &server_in, ID_CFG,
+		      ACT_START_LOGIN);
+		field(&body, "Config file (session cookie, RAM-only on /share)",
+		      ID_CFG, &cfg_in, ID_SERVER, ACT_START_LOGIN);
+		r = ngui_cut_top(&body, 32);
+		b = ngui_cut_left(&r, 110);
+		if (ngui_button(&ui, ID_SIGNIN, b, "Sign in"))
+			action = ACT_START_LOGIN;
+		ngui_cut_left(&r, 10);
+		b = ngui_cut_left(&r, 170);
+		if (ngui_button(&ui, ID_COOKIE_MODE, b, "Paste a cookie..."))
+			action = ACT_COOKIE_SCREEN;
+		ngui_cut_top(&body, 8);
+		draw_status_line(&body);
+		notice(&body, "TLS certificates are not verified: only sign in");
+		notice(&body, "on a trusted network.  Passkeys and external SSO");
+		notice(&body, "are not supported (use the cookie option).");
+	} else if (screen == SCR_CRED || screen == SCR_TOTP) {
+		r = ngui_cut_top(&body, 22);
+		{
+			char t[160];
+
+			s_copy(t, "Sign in to ", sizeof(t));
+			s_cat(t, login.app_name[0] ? login.app_name : "Chat",
+			      sizeof(t));
+			s_cat(t, " at ", sizeof(t));
+			s_cat(t, server_host, sizeof(t));
+			ngui_text_ellipsis(&ui, r, r.x, r.y, t, ui.theme.text_dim);
+		}
+		if (screen == SCR_CRED) {
+			field(&body, "Username or email", ID_USER, &user_in,
+			      ID_PASS, ACT_SUBMIT);
+			field(&body, "Password", ID_PASS, &pass_in, ID_USER,
+			      ACT_SUBMIT);
+		} else {
+			field(&body, "Two-factor code (authenticator app)",
+			      ID_TOTP, &totp_in, ID_TOTP, ACT_SUBMIT_TOTP);
+		}
+		r = ngui_cut_top(&body, 32);
+		b = ngui_cut_left(&r, 110);
+		if (ngui_button(&ui, ID_SIGNIN, b, "Sign in"))
+			action = screen == SCR_TOTP ? ACT_SUBMIT_TOTP : ACT_SUBMIT;
+		ngui_cut_left(&r, 10);
+		b = ngui_cut_left(&r, 90);
+		if (ngui_button(&ui, ID_BACK, b, "Back"))
+			action = ACT_BACK;
+		ngui_cut_top(&body, 8);
+		draw_status_line(&body);
+		notice(&body, "The password is sent over unverified TLS and");
+		notice(&body, "is never stored.");
+	} else {
+		field(&body, "Server", ID_SERVER, &server_in, ID_COOKIE,
+		      ACT_USE_COOKIE);
+		field(&body, "Session cookie (e.g. connect.sid=s%3A...)",
+		      ID_COOKIE, &cookie_in, ID_CFG, ACT_USE_COOKIE);
+		field(&body, "Config file", ID_CFG, &cfg_in, ID_SERVER,
+		      ACT_USE_COOKIE);
+		r = ngui_cut_top(&body, 32);
+		b = ngui_cut_left(&r, 130);
+		if (ngui_button(&ui, ID_USE_COOKIE, b, "Use cookie"))
+			action = ACT_USE_COOKIE;
+		ngui_cut_left(&r, 10);
+		b = ngui_cut_left(&r, 90);
+		if (ngui_button(&ui, ID_BACK, b, "Back"))
+			action = ACT_BACK;
+		ngui_cut_top(&body, 8);
+		draw_status_line(&body);
+		notice(&body, "Copy the connect.sid cookie from a signed-in web");
+		notice(&body, "browser.  It is a bearer credential: it is saved");
+		notice(&body, "in the config file until you sign out.");
+	}
+}
+
+/* ---- main screen ---- */
+
+#define SIDE_ROW   38
+#define SIDE_HEAD  26
+
+static void draw_sidebar(struct ngui_rect r)
+{
+	struct ngui_rect list, btns, b;
+	int y, i, section, row_w, scrolls;
+	int lh = line_h();
+
+	ngui_fill_rect(&ui, r, ui.theme.panel);
+	btns = ngui_cut_bottom(&r, 40);
+	ngui_inset(&btns, 6);
+	b = ngui_cut_left(&btns, (btns.w - 6) / 2);
+	if (ngui_button(&ui, ID_BROWSE, b, "Browse"))
+		action = ACT_BROWSE;
+	ngui_cut_left(&btns, 6);
+	if (ngui_button(&ui, ID_NEWDM, btns, "New DM"))
+		action = ACT_NEWDM;
+
+	list = r;
+	side_scroll.content_h = 2 * SIDE_HEAD + nconv * SIDE_ROW + 8;
+	ngui_scroll_begin(&ui, list, &side_scroll);
+	ngui_scroll_wheel(&ui, list, &side_scroll);
+	scrolls = side_scroll.content_h > side_scroll.view_h;
+	row_w = list.w - (scrolls ? 16 : 0);
+	y = list.y - side_scroll.offset;
+	for (section = 0; section < 2; section++) {
+		ngui_text_px(&ui, list.x + 10, y + 6,
+			     section ? "DIRECT MESSAGES" : "CHANNELS",
+			     section ? 15 : 8, ui.theme.text_dim, 12, 1, 0, 0);
+		y += SIDE_HEAD;
+		for (i = 0; i < nconv; i++) {
+			struct conv *c = &convs[i];
+			struct ngui_rect row = { list.x, y, row_w, SIDE_ROW - 2 };
+			int hot, nx, right;
+
+			if ((c->kind == 'd') != section)
+				continue;
+			hot = ui.inside && ngui_rect_contains(&row, ui.mouse_x,
+							      ui.mouse_y) &&
+			      ngui_rect_contains(&list, ui.mouse_x, ui.mouse_y);
+			if (i == cur)
+				ngui_fill_rect(&ui, row, ui.theme.selection);
+			else if (hot)
+				ngui_fill_rect(&ui, row, ui.theme.panel_alt);
+			if (ui.pressed && modal == MODAL_NONE &&
+			    ngui_rect_contains(&row, ui.press_x, ui.press_y) &&
+			    ngui_rect_contains(&list, ui.press_x, ui.press_y)) {
+				action = ACT_OPEN_CONV;
+				action_arg = i;
+			}
+			nx = list.x + 26;
+			if (c->kind == 'd') {
+				unsigned short pc = c->presence == 'o' ?
+					NGUI_RGB(0x40, 0xc0, 0x60) :
+					c->presence == 'a' ?
+					NGUI_RGB(0xe0, 0xb0, 0x30) :
+					ui.theme.text_dim;
+
+				draw_dot(list.x + 10, y + 6 + (lh - 9) / 2, 9, pc,
+					 c->presence != 'f');
+			} else if (c->kind == 'p') {
+				draw_lock(list.x + 9, y + 4, ui.theme.text_dim);
+			} else {
+				ngui_text(&ui, list.x + 10, y + 4, "#",
+					  ui.theme.text_dim);
+			}
+			right = list.x + row_w - 8;
+			if (c->unread > 0) {
+				draw_badge(right, y + 3, c->unread);
+				right -= 40;
+			}
+			{
+				struct ngui_rect nr = { nx, y, right - nx, lh + 6 };
+
+				ngui_push_clip(&ui, nr);
+				ngui_text_px(&ui, nx, y + 4, c->name,
+					     (unsigned int)strlen(c->name),
+					     ui.theme.text, ui.font_px,
+					     c->unread > 0, 0, 0);
+				ngui_pop_clip(&ui);
+			}
+			if (c->preview[0]) {
+				struct ngui_rect pr = { nx, y + 4 + lh,
+							list.x + row_w - 8 - nx,
+							lh };
+
+				ngui_push_clip(&ui, pr);
+				ngui_text_px(&ui, nx, y + 4 + lh, c->preview,
+					     (unsigned int)strlen(c->preview),
+					     ui.theme.text_dim, 12, 0, 0, 0);
+				ngui_pop_clip(&ui);
+			}
+			y += SIDE_ROW;
+		}
+	}
+	if (!nconv)
+		ngui_text(&ui, list.x + 10, list.y + SIDE_HEAD + 6,
+			  "(none yet)", ui.theme.text_dim);
+	ngui_scroll_end(&ui, list, &side_scroll);
+}
+
+static void draw_message(struct msg *m, int x, int y, int width)
+{
+	int lh = line_h(), tx = x + TEXT_X, tw = width - TEXT_X - 12;
+	unsigned int n, pos = 0, adv;
+
+	if (tw < 40)
+		tw = 40;
+	if (m->day_header) {
+		char d[16];
+		int dw;
+		struct ngui_rect line = { x + 12, y + 6 + lh / 2, width - 24, 1 };
+
+		s_copy(d, m->created, 11);
+		dw = text_w(d, (unsigned int)strlen(d), 0);
+		ngui_fill_rect(&ui, line, ui.theme.border);
+		ngui_fill_rect(&ui, (struct ngui_rect){ x + (width - dw) / 2 - 8,
+					y + 4, dw + 16, lh + 4 }, ui.theme.bg);
+		ngui_text(&ui, x + (width - dw) / 2, y + 6, d, ui.theme.text_dim);
+		y += lh + 12;
+	}
+	if (!m->compact) {
+		char tm[8];
+		int aw;
+
+		y += PAD_TOP;
+		draw_avatar(x + 10, y, AVATAR, m->author, m->user_id);
+		ngui_text_px(&ui, tx, y, m->author, (unsigned int)strlen(m->author),
+			     ui.theme.text, ui.font_px, 1, 0, 0);
+		aw = text_w(m->author, (unsigned int)strlen(m->author), 1);
+		s_copy(tm, m->created + 11, 6);
+		ngui_text_px(&ui, tx + aw + 10, y, tm, (unsigned int)strlen(tm),
+			     ui.theme.text_dim, 12, 0, 0, 0);
+		y += lh + 2;
+	} else {
+		y += PAD_GROUP;
+	}
+	if (m->reply[0]) {
+		struct ngui_rect rr = { tx, y, tw, lh };
+
+		ngui_fill_rect(&ui, (struct ngui_rect){ tx, y + 1, 3, lh - 2 },
+			       ui.theme.accent);
+		ngui_text_ellipsis(&ui, rr, tx + 8, y, m->reply,
+				   ui.theme.text_dim);
+		y += lh + 2;
+	}
+	n = (unsigned int)strlen(m->body);
+	while (pos < n) {
+		unsigned int len = wrap_line(m->body + pos, n - pos, tw, &adv);
+
+		if (!adv)
+			adv = 1;
+		ngui_text_px(&ui, tx, y, m->body + pos, len,
+			     m->action ? ui.theme.accent : ui.theme.text,
+			     ui.font_px, 0, m->action, 0);
+		pos += adv;
+		y += lh;
+	}
+	if (m->extra[0]) {
+		struct ngui_rect er = { tx, y + 2, tw, lh };
+
+		ngui_text_ellipsis(&ui, er, tx, y + 2, m->extra,
+				   ui.theme.text_dim);
+	}
+}
+
+static void draw_timeline(struct ngui_rect r)
+{
+	int i, y, total, scrolls, width;
+	int was_bottom;
+
+	ngui_fill_rect(&ui, r, ui.theme.bg);
+	if (cur < 0) {
+		ngui_text(&ui, r.x + 20, r.y + 20,
+			  nconv ? "Select a conversation" :
+			  "No conversations yet: browse the public channels",
+			  ui.theme.text_dim);
+		return;
+	}
+	tl_width = r.w - 16;
+	total = content_height();
+	tl_scroll.content_h = total;
+	ngui_scroll_begin(&ui, r, &tl_scroll);
+	if (ngui_scroll_wheel(&ui, r, &tl_scroll))
+		last_input_ms = u_ticks_ms();
+	scrolls = total > r.h;
+	width = r.w - (scrolls ? 16 : 0);
+	if (width != tl_width) {
+		tl_width = width;
+		total = content_height();
+		tl_scroll.content_h = total;
+	}
+	/* Scrolling to the very top pages in older history by itself (the
+	 * button stays for the pointer).  Rate-limited so a failing request
+	 * cannot spin. */
+	if (has_older && !history_full && scrolls && tl_scroll.offset <= 0 &&
+	    !offline && (unsigned int)(u_ticks_ms() - last_older_ms) > 1500)
+		action = ACT_OLDER;
+	was_bottom = tl_scroll.offset >= total - r.h - 4;
+	at_bottom = was_bottom || !scrolls;
+	if (at_bottom)
+		new_below = 0;
+
+	y = r.y - tl_scroll.offset;
+	if (has_older || history_full) {
+		struct ngui_rect b = { r.x + (width - 200) / 2, y + 4, 200, 28 };
+
+		if (history_full) {
+			ngui_text(&ui, b.x + 4, b.y + 6,
+				  "History limit reached", ui.theme.text_dim);
+		} else if (b.y + b.h > r.y &&
+			   (!ui.pressed ||
+			    ngui_rect_contains(&r, ui.press_x, ui.press_y))) {
+			if (ngui_button(&ui, ID_OLDER, b, "Load older messages"))
+				action = ACT_OLDER;
+		}
+		y += 36;
+	} else {
+		y += 8;
+	}
+	for (i = 0; i < nmsg; i++) {
+		struct msg *m = &msgs[i];
+
+		if (y + m->height > r.y && y < r.y + r.h)
+			draw_message(m, r.x, y, width);
+		y += m->height;
+	}
+	if (!nmsg)
+		ngui_text(&ui, r.x + 20, r.y + 50,
+			  "No messages yet - say hello!", ui.theme.text_dim);
+	ngui_scroll_end(&ui, r, &tl_scroll);
+
+	if (new_below > 0 && !at_bottom) {
+		char t[40] = "";
+		struct ngui_rect b;
+
+		s_cat_uint(t, (unsigned int)new_below, sizeof(t));
+		s_cat(t, new_below == 1 ? " new message" : " new messages",
+		      sizeof(t));
+		b.w = text_w(t, (unsigned int)strlen(t), 0) + 30;
+		b.h = 26;
+		b.x = r.x + (width - b.w) / 2;
+		b.y = r.y + r.h - b.h - 8;
+		if (ngui_button(&ui, ID_NEWMSG, b, t))
+			scroll_to_end();
+	}
+}
+
+static int total_unread(void)
+{
+	int i, n = 0;
+
+	for (i = 0; i < nconv; i++)
+		n += convs[i].unread > 0 ? convs[i].unread : 0;
+	return n;
+}
+
+static void draw_modal(void)
+{
+	struct ngui_rect all = { 0, 0, ui.w, ui.h };
+	struct ngui_rect card, body, r, list;
+	int w = ui.w * 7 / 10, h = ui.h * 8 / 10, i, y, shown = 0, vis;
+	int lh = line_h();
+
+	(void)all;
+	if (w < 320)
+		w = ui.w - 20;
+	if (h < 240)
+		h = ui.h - 20;
+	card.w = w;
+	card.h = h;
+	card.x = (ui.w - w) / 2;
+	card.y = (ui.h - h) / 2;
+	ngui_fill_rect(&ui, card, ui.theme.panel);
+	ngui_frame(&ui, card, ui.theme.accent);
+	body = card;
+	ngui_inset(&body, 14);
+	r = ngui_cut_top(&body, 28);
+	ngui_text_px(&ui, r.x, r.y, modal == MODAL_BROWSE ?
+		     "Browse public channels" : "New direct message",
+		     modal == MODAL_BROWSE ? 22 : 18, ui.theme.text, 18, 1, 0, 0);
+	if (ngui_button(&ui, ID_MODAL_CLOSE,
+			(struct ngui_rect){ r.x + r.w - 80, r.y, 80, 26 },
+			"Close"))
+		modal = MODAL_NONE;
+	ngui_cut_top(&body, 6);
+	filter_in.placeholder = "Filter... (Up/Down, Enter)";
+	for (i = 0; i < npick; i++)
+		if (!filter_in.text[0] || strstr(picks[i].name, filter_in.text) ||
+		    strstr(picks[i].sub, filter_in.text))
+			shown++;
+	{
+		int k = ngui_key_peek(&ui), fr;
+
+		if (k == NGUI_KEY_UP || k == NGUI_KEY_DOWN) {
+			ngui_key(&ui);
+			modal_sel += k == NGUI_KEY_UP ? -1 : 1;
+		}
+		fr = ngui_text_input(&ui, ID_FILTER, ngui_cut_top(&body, 30),
+				     &filter_in);
+		if (fr & NGUI_INPUT_CHANGED) {
+			modal_scroll.offset = 0;
+			modal_sel = 0;
+		}
+		if (modal_sel >= shown)
+			modal_sel = shown - 1;
+		if (modal_sel < 0)
+			modal_sel = 0;
+		if ((fr & NGUI_INPUT_SUBMIT) && shown) {
+			int vis = 0;
+
+			for (i = 0; i < npick; i++) {
+				if (filter_in.text[0] &&
+				    !strstr(picks[i].name, filter_in.text) &&
+				    !strstr(picks[i].sub, filter_in.text))
+					continue;
+				if (vis++ == modal_sel) {
+					action = modal == MODAL_BROWSE ?
+						 ACT_JOIN : ACT_OPEN_DM;
+					action_arg = i;
+					break;
+				}
+			}
+			ngui_set_focus(&ui, ID_FILTER);
+		}
+		if ((fr & NGUI_INPUT_CANCEL) && !(fr & NGUI_INPUT_NEXT))
+			modal = MODAL_NONE;
+	}
+	ngui_cut_top(&body, 8);
+	list = body;
+	ngui_fill_rect(&ui, list, ui.theme.bg);
+	modal_scroll.content_h = shown * 44;
+	ngui_scroll_begin(&ui, list, &modal_scroll);
+	ngui_scroll_wheel(&ui, list, &modal_scroll);
+	y = list.y - modal_scroll.offset;
+	vis = 0;
+	for (i = 0; i < npick; i++) {
+		struct pick *p = &picks[i];
+		struct ngui_rect row, b;
+
+		if (filter_in.text[0] && !strstr(p->name, filter_in.text) &&
+		    !strstr(p->sub, filter_in.text))
+			continue;
+		if (vis++ == modal_sel) {
+			if (y < list.y)
+				modal_scroll.offset -= list.y - y;
+			else if (y + 44 > list.y + list.h)
+				modal_scroll.offset += y + 44 - list.y - list.h;
+			y = list.y + (vis - 1) * 44 - modal_scroll.offset;
+			ngui_fill_rect(&ui, (struct ngui_rect){ list.x, y,
+						list.w - 16, 43 },
+				       ui.theme.selection);
+		}
+		row.x = list.x;
+		row.y = y;
+		row.w = list.w - 16;
+		row.h = 42;
+		if (y + 44 > list.y && y < list.y + list.h) {
+			ngui_fill_rect(&ui, (struct ngui_rect){ row.x, y + 43,
+						row.w, 1 }, ui.theme.border);
+			if (modal == MODAL_NEWDM)
+				draw_avatar(row.x + 8, y + 6, 30, p->name, p->id);
+			ngui_text_ellipsis(&ui, (struct ngui_rect){ row.x + 48, y,
+						 row.w - 160, lh + 4 },
+					   row.x + 48, y + 4,
+					   p->name,
+					   ui.theme.text);
+			ngui_text_ellipsis(&ui, (struct ngui_rect){ row.x + 48,
+						 y + 4 + lh, row.w - 160, lh },
+					   row.x + 48, y + 4 + lh, p->sub,
+					   ui.theme.text_dim);
+			if (modal == MODAL_BROWSE)
+				ngui_text(&ui, row.x + 14, y + 12, "#",
+					  ui.theme.text_dim);
+			b.x = row.x + row.w - 100;
+			b.y = y + 8;
+			b.w = 92;
+			b.h = 26;
+			if ((!ui.pressed ||
+			     ngui_rect_contains(&list, ui.press_x, ui.press_y)) &&
+			    ngui_button(&ui, ID_MODAL_ROW + (unsigned int)i, b,
+					modal == MODAL_BROWSE ? "Join" : "Message")) {
+				action = modal == MODAL_BROWSE ? ACT_JOIN :
+					 ACT_OPEN_DM;
+				action_arg = i;
+			}
+		}
+		y += 44;
+	}
+	if (!shown)
+		ngui_text(&ui, list.x + 12, list.y + 12,
+			  npick ? "Nothing matches the filter" :
+			  modal == MODAL_BROWSE ?
+			  "You are in every public channel" : "Nobody else here",
+			  ui.theme.text_dim);
+	ngui_scroll_end(&ui, list, &modal_scroll);
+}
+
+/* Keyboard shortcuts, handled before the composer swallows the keys:
+ * PgUp/PgDn scroll the timeline; Ctrl+B browse, Ctrl+N new DM, Ctrl+R
+ * refresh.  With the composer unfocused (Esc): Up/Down switch conversations,
+ * Home/End jump in the timeline, and typing refocuses the composer. */
+static void main_keys(void)
+{
+	for (;;) {
+		int k = ngui_key_peek(&ui);
+
+		if (!k)
+			return;
+		if (k == NGUI_KEY_PAGE_UP || k == NGUI_KEY_PAGE_DOWN) {
+			ngui_scroll_keys(&ui, &tl_scroll);
+			continue;
+		}
+		if (k == 0x02 || k == 0x0E || k == 0x12) {
+			ngui_key(&ui);
+			action = k == 0x02 ? ACT_BROWSE : k == 0x0E ? ACT_NEWDM :
+				 ACT_REFRESH;
+			return;
+		}
+		if (ui.focus)
+			return;
+		if (k == NGUI_KEY_HOME) {
+			ngui_key(&ui);
+			tl_scroll.offset = 0;
+		} else if (k == NGUI_KEY_END) {
+			ngui_key(&ui);
+			scroll_to_end();
+		} else if (k == NGUI_KEY_UP || k == NGUI_KEY_DOWN) {
+			int order[MAX_CONV], n = 0, i, pos = -1, sec;
+
+			ngui_key(&ui);
+			/* Sidebar order: channels first, then DMs. */
+			for (sec = 0; sec < 2; sec++)
+				for (i = 0; i < nconv; i++)
+					if ((convs[i].kind == 'd') == sec) {
+						if (i == cur)
+							pos = n;
+						order[n++] = i;
+					}
+			if (!n)
+				continue;
+			pos = pos < 0 ? 0 : k == NGUI_KEY_UP ?
+			      (pos > 0 ? pos - 1 : 0) :
+			      (pos + 1 < n ? pos + 1 : n - 1);
+			if (order[pos] != cur) {
+				action = ACT_OPEN_CONV;
+				action_arg = order[pos];
+				return;
+			}
+		} else if (k >= 0x20 && k <= 0x7E && cur >= 0) {
+			ngui_set_focus(&ui, ID_COMPOSE);
+			return;
+		} else {
+			return;
+		}
+	}
+}
+
+static void draw_main(void)
+{
+	struct ngui_rect all = { 0, 0, ui.w, ui.h };
+	struct ngui_rect top, side, bottom, comp, stat, b, tl;
+	int side_w = ui.w / 4;
+	char t[200];
+	unsigned int saved_pressed = ui.pressed;
+
+	/* Nothing under an open modal reacts to the pointer. */
+	if (modal != MODAL_NONE)
+		ui.pressed = 0;
+	if (side_w < 150)
+		side_w = 150;
+	if (side_w > 260)
+		side_w = 260;
+	ngui_fill_rect(&ui, all, ui.theme.bg);
+
+	/* top bar */
+	top = ngui_cut_top(&all, 38);
+	ngui_fill_rect(&ui, top, ui.theme.panel_alt);
+	ngui_fill_rect(&ui, (struct ngui_rect){ top.x, top.y + top.h - 1, top.w,
+				1 }, ui.theme.border);
+	{
+		struct ngui_rect tb = top;
+
+		ngui_inset(&tb, 6);
+		b = ngui_cut_right(&tb, 86);
+		if (ngui_button(&ui, ID_SIGNOUT, b, "Sign out"))
+			action = ACT_SIGNOUT;
+		ngui_cut_right(&tb, 6);
+		b = ngui_cut_right(&tb, 80);
+		if (ngui_button(&ui, ID_REFRESH, b, "Refresh"))
+			action = ACT_REFRESH;
+		t[0] = '\0';
+		if (cur >= 0) {
+			s_cat(t, convs[cur].kind == 'd' ? "@ " : "# ", sizeof(t));
+			s_cat(t, convs[cur].name, sizeof(t));
+		} else {
+			s_cat(t, "Chat", sizeof(t));
+		}
+		ngui_cut_right(&tb, 10);
+		ngui_push_clip(&ui, tb);
+		ngui_text_px(&ui, tb.x + 4, tb.y + (tb.h - 20) / 2, t,
+			     (unsigned int)strlen(t), ui.theme.text, 18, 1, 0, 0);
+		ngui_pop_clip(&ui);
+	}
+
+	if (modal == MODAL_NONE) {
+		/* A closed modal leaves its filter focused: hand the keyboard
+		 * back to the composer. */
+		if (ui.focus == ID_FILTER)
+			ngui_set_focus(&ui, cur >= 0 ? ID_COMPOSE : 0);
+		main_keys();
+	}
+
+	/* bottom: composer + status bar */
+	bottom = ngui_cut_bottom(&all, 70);
+	ngui_fill_rect(&ui, bottom, ui.theme.panel);
+	ngui_fill_rect(&ui, (struct ngui_rect){ bottom.x, bottom.y, bottom.w, 1 },
+		       ui.theme.border);
+	stat = ngui_cut_bottom(&bottom, 24);
+	comp = bottom;
+	ngui_inset(&comp, 7);
+	b = ngui_cut_right(&comp, 80);
+	compose_in.disabled = cur < 0;
+	compose_in.placeholder = cur < 0 ? "" : "Type a message...";
+	if (ngui_text_input(&ui, ID_COMPOSE,
+			    (struct ngui_rect){ comp.x, comp.y, comp.w - 8,
+						comp.h }, &compose_in) &
+	    NGUI_INPUT_SUBMIT)
+		action = ACT_SEND;
+	if (ngui_button(&ui, ID_SEND, b, "Send") && cur >= 0)
+		action = ACT_SEND;
+
+	ngui_fill_rect(&ui, stat, ui.theme.panel_alt);
+	{
+		struct ngui_rect sr = stat;
+		int un = total_unread();
+
+		ngui_inset(&sr, 3);
+		if (offline) {
+			b = ngui_cut_right(&sr, 70);
+			if (ngui_button(&ui, ID_RETRY, b, "Retry"))
+				action = ACT_RETRY;
+		}
+		t[0] = '\0';
+		if (busy[0]) {
+			s_cat(t, busy, sizeof(t));
+		} else {
+			s_cat(t, status[0] ? status : "Connected", sizeof(t));
+			if (offline && retry_at) {
+				int left = (int)(retry_at - u_ticks_ms());
+
+				if (left > 0) {
+					s_cat(t, " (retry in ", sizeof(t));
+					s_cat_uint(t, (unsigned int)(left + 999) / 1000,
+						   sizeof(t));
+					s_cat(t, " s)", sizeof(t));
+				}
+			}
+		}
+		s_cat(t, "  \xb7  ", sizeof(t));
+		s_cat(t, server_secure ? "TLS unverified" : "no TLS", sizeof(t));
+		if (me_name[0]) {
+			s_cat(t, "  \xb7  ", sizeof(t));
+			s_cat(t, me_name, sizeof(t));
+		}
+		if (un) {
+			s_cat(t, "  \xb7  ", sizeof(t));
+			s_cat_uint(t, (unsigned int)un, sizeof(t));
+			s_cat(t, " unread", sizeof(t));
+		}
+		ngui_text_ellipsis(&ui, sr, sr.x + 4, sr.y + 1, t,
+				   busy[0] ? ui.theme.accent :
+				   (offline || status_err) ? ui.theme.error :
+				   ui.theme.text_dim);
+	}
+
+	side = ngui_cut_left(&all, side_w);
+	ngui_fill_rect(&ui, (struct ngui_rect){ side.x + side.w - 1, side.y, 1,
+				side.h }, ui.theme.border);
+	side.w -= 1;
+	tl = all;
+	if (modal == MODAL_NONE) {
+		draw_sidebar(side);
+		draw_timeline(tl);
+	} else {
+		draw_sidebar(side);
+		draw_timeline(tl);
+		action = ACT_NONE;
+		ui.pressed = saved_pressed;
+		draw_modal();
+	}
+}
+
+/* ---- frame / main loop ---- */
+
+static void draw(void)
+{
+	if (screen == SCR_MAIN)
+		draw_main();
+	else
+		draw_login();
+}
+
+/* Present a frame now (status text before a blocking network call). */
+static void paint_now(void)
+{
+	int saved_action = action, saved_arg = action_arg;
+
+	ngui_invalidate(&ui);
+	if (ngui_begin(&ui)) {
+		draw();
+		ngui_end(&ui);
+	}
+	action = saved_action;
+	action_arg = saved_arg;
+}
+
+static void run_action(void)
+{
+	int a = action, arg = action_arg;
+
+	action = ACT_NONE;
+	switch (a) {
+	case ACT_START_LOGIN:
+		start_login();
+		break;
+	case ACT_SUBMIT:
+		submit_login(0);
+		break;
+	case ACT_SUBMIT_TOTP:
+		submit_login(1);
+		break;
+	case ACT_USE_COOKIE:
+		use_cookie();
+		break;
+	case ACT_COOKIE_SCREEN:
+		screen = SCR_COOKIE;
+		set_status("", 0, 0);
+		ngui_set_focus(&ui, ID_COOKIE);
+		break;
+	case ACT_BACK:
+		wipe_secrets();
+		screen = SCR_SERVER;
+		set_status("", 0, 0);
+		ngui_set_focus(&ui, ID_SERVER);
+		break;
+	case ACT_SEND:
+		send_message();
+		break;
+	case ACT_REFRESH:
+	case ACT_RETRY:
+		backoff_ms = 0;
+		retry_at = 0;
+		s_copy(busy, "Refreshing...", sizeof(busy));
+		paint_now();
+		busy[0] = '\0';
+		if (offline && !me_id[0]) {
+			check_session(1);
+			break;
+		}
+		if (load_directory() == 0) {
+			if (cur >= 0)
+				open_conv(cur);
+			else if (nconv)
+				open_conv(0);
+		}
+		next_dir_poll = u_ticks_ms() + POLL_DIR_MS;
+		break;
+	case ACT_SIGNOUT:
+		sign_out();
+		break;
+	case ACT_OPEN_CONV:
+		if (arg != cur)
+			open_conv(arg);
+		break;
+	case ACT_OLDER:
+		load_older();
+		break;
+	case ACT_BROWSE:
+		load_picks(0);
+		break;
+	case ACT_NEWDM:
+		load_picks(1);
+		break;
+	case ACT_JOIN:
+	case ACT_OPEN_DM:
+		pick_action(arg);
+		break;
+	}
+	ngui_invalidate(&ui);
+}
+
+static void poll_tick(void)
+{
+	unsigned int now = u_ticks_ms();
+	int focused = ui.focused;
+
+	if (screen != SCR_MAIN || modal != MODAL_NONE)
+		return;
+	if (offline) {
+		if (retry_at && (int)(now - retry_at) >= 0) {
+			retry_at = 0;
+			action = ACT_RETRY;
+			run_action();
+		}
+		return;
+	}
+	/* Do not interrupt typing or scrolling. */
+	if ((unsigned int)(now - last_input_ms) < TYPING_HOLD_MS)
+		return;
+	if ((int)(now - next_dir_poll) >= 0) {
+		load_directory();
+		next_dir_poll = now + (focused ? POLL_DIR_MS : POLL_DIR_IDLE_MS);
+		next_conv_poll = now;   /* follow with the conversation */
+	}
+	if (cur >= 0 && !offline && (int)(now - next_conv_poll) >= 0) {
+		poll_conv();
+		next_conv_poll = u_ticks_ms() +
+				 (focused ? POLL_CONV_MS : POLL_CONV_IDLE_MS);
+	}
+	/* An open TCP socket pauses the board's net-dev watcher: only keep
+	 * the connection while the user is actively chatting. */
+	if (http.connected &&
+	    (!focused || (unsigned int)(u_ticks_ms() - last_input_ms) >
+			 KEEPALIVE_IDLE_MS) &&
+	    (unsigned int)(u_ticks_ms() - last_net_ms) > 200)
+		net_drop();
+}
+
+void _start(const char *arg)
+{
+	struct win_info wi;
+	unsigned int w = 980, h = 660;
+	resp = (char *)malloc(RESP_CAP);
+	jnodes = (struct ujson_node *)malloc(sizeof(struct ujson_node) *
+					     JSON_NODES);
+	jsbuf = (char *)malloc(JSON_SCAP);
+	if (!resp || !jnodes || !jsbuf) {
+		u_puts("chat: out of memory\n");
+		u_exit(1);
+	}
+	ujson_init(&json, jnodes, JSON_NODES, jsbuf, JSON_SCAP);
+	uhttp_init(&http);
+	http.user_agent = "NebOS-Chat/1.0 (uhttp)";
+	uhttp_jar_init(&jar);
+
+	if (u_win_create(w, h, "Chat", &wi) != 0 &&
+	    u_win_create(w = 780, h = 540, "Chat", &wi) != 0 &&
+	    u_win_create(w = 600, h = 420, "Chat", &wi) != 0) {
+		u_puts("chat: no graphics window\n");
+		u_exit(1);
+	}
+	ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
+	ngui_font_attach(&ui);
+
+	server_in.placeholder = "chat.example.com";
+	user_in.placeholder = "username";
+	pass_in.secret = 1;
+	totp_in.placeholder = "123456";
+	cookie_in.placeholder = "connect.sid=...";
+	s_copy(cfg_path, arg && arg[0] ? arg : DEFAULT_CFG, sizeof(cfg_path));
+	ngui_set_focus(&ui, ID_SERVER);
+	last_input_ms = 0;
+
+	/* First frame, then the (possibly slow) session check. */
+	paint_now();
+	load_config();
+
+	for (;;) {
+		int redraw;
+
+		redraw = ngui_begin(&ui);
+		if (ui.key_head != ui.key_tail || ui.pressed || ui.scroll_y) {
+			last_input_ms = u_ticks_ms();
+			if (screen == SCR_MAIN && !offline)
+				maybe_save_cookie();
+		}
+		if (redraw) {
+			draw();
+			ngui_end(&ui);
+		} else {
+			ngui_end_ex(&ui, 0);
+		}
+		if (action != ACT_NONE)
+			run_action();
+		else
+			poll_tick();
+		/* The offline retry countdown needs a once-a-second repaint. */
+		if (offline && screen == SCR_MAIN) {
+			static unsigned int last_tick;
+
+			if (u_ticks_ms() - last_tick >= 1000) {
+				last_tick = u_ticks_ms();
+				ngui_invalidate(&ui);
+			}
+		}
+		u_sleep_ms(10);
+	}
+}

+ 8 - 2
ucmd_wm.c

@@ -238,9 +238,11 @@ static void draw_bar(void)
 		   WM_BTN_CARDS_H, "Cards");
 	bar_button(WM_BTN_GALLERY_X, WM_BTN_GALLERY_Y, WM_BTN_GALLERY_W,
 		   WM_BTN_GALLERY_H, "Gallery");
+	bar_button(WM_BTN_CHAT_X, WM_BTN_CHAT_Y, WM_BTN_CHAT_W,
+		   WM_BTN_CHAT_H, "Chat");
 	if (bar_msg_until &&
 	    (int)(u_ticks_ms() - bar_msg_until) < 0)
-		usurf_text(&screen, (int)(WM_BTN_GALLERY_X + WM_BTN_GALLERY_W + 8),
+		usurf_text(&screen, (int)(WM_BTN_END_X + 8),
 			   5, bar_msg, 0xFFD250u, 0, 0, fbw, WM_BAR_H);
 
 	/* Rainbow separator (same y as the kernel's old bar). */
@@ -272,7 +274,7 @@ static void draw_bar(void)
 	} else {
 		unsigned int clock_chars = 0;
 		int right = (int)fbw - 4;
-		int min_x = WM_BTN_GALLERY_X + (int)WM_BTN_GALLERY_W + 4;
+		int min_x = (int)WM_BTN_END_X + 4;
 
 		bar_clock_x = -1;
 		bar_clock_w = 0;
@@ -1055,6 +1057,10 @@ static void handle_mouse(struct wm_status *st)
 			   mx < WM_BTN_GALLERY_X + WM_BTN_GALLERY_W &&
 			   my < WM_BTN_GALLERY_Y + WM_BTN_GALLERY_H) {
 			spawn_app_checked("/ramfs/bin/gallery");
+		} else if (mx >= WM_BTN_CHAT_X && my >= WM_BTN_CHAT_Y &&
+			   mx < WM_BTN_CHAT_X + WM_BTN_CHAT_W &&
+			   my < WM_BTN_CHAT_Y + WM_BTN_CHAT_H) {
+			spawn_app_checked("/ramfs/bin/chat");
 		} else {
 			int idx = window_at((int)mx, (int)my);
 

+ 58 - 6
uhttp.c

@@ -359,11 +359,34 @@ static unsigned int parse_status(const char *line)
 
 /* ---- transport ---- */
 
+/* Send len bytes, split into pieces the transport accepts: one TLS record
+ * carries at most 1024 bytes and SYS_TCP_SEND at most one peer MSS. */
 static int xport_send(struct uhttp *h, const void *buf, unsigned int len)
 {
-	if (h->url.secure)
-		return tls_send(buf, len);
-	return (int)u_syscall2(SYS_TCP_SEND, (int)buf, (int)len);
+	const unsigned char *p = (const unsigned char *)buf;
+	unsigned int chunk;
+
+	if (h->url.secure) {
+		chunk = 1024;
+	} else {
+		int mss = u_syscall0(SYS_TCP_PEER_MSS);
+
+		chunk = mss > 0 ? (unsigned int)mss : 536;
+	}
+	while (len) {
+		unsigned int n = len < chunk ? len : chunk;
+		int rv;
+
+		if (h->url.secure)
+			rv = tls_send(p, n);
+		else
+			rv = (int)u_syscall2(SYS_TCP_SEND, (int)p, (int)n);
+		if (rv != 0)
+			return rv;
+		p += n;
+		len -= n;
+	}
+	return 0;
 }
 
 static int xport_recv(struct uhttp *h, void *buf, unsigned int max,
@@ -613,14 +636,27 @@ static int read_response_head(struct uhttp *h, char *location, int *have_loc)
 		} else if (hdr_match(line, "connection") &&
 			   contains_ci(line, "close")) {
 			h->peer_close = 1;
+		} else if (h->jar && hdr_match(line, "set-cookie")) {
+			char *v = line + 11;    /* past "set-cookie:" */
+
+			while (*v == ' ' || *v == '\t')
+				v++;
+			(void)uhttp_jar_set(h->jar, h->url.host, h->url.path, v);
 		}
 	}
+	/* 1xx/204/304 responses never carry a body; without this a kept-alive
+	 * 204 would be read until the idle timeout. */
+	if ((status >= 100 && status < 200) || status == 204 || status == 304) {
+		h->resp.chunked = 0;
+		h->resp.have_length = 1;
+		h->resp.content_length = 0;
+	}
 	return 0;
 }
 
 static int send_request(struct uhttp *h, unsigned int flags)
 {
-	char req[1024];
+	static char req[UHTTP_REQ_MAX];
 	unsigned int n = 0;
 	int rv;
 
@@ -635,7 +671,21 @@ static int send_request(struct uhttp *h, unsigned int flags)
 	}
 	n = req_app(req, n, sizeof(req), "\r\nUser-Agent: ");
 	n = req_app(req, n, sizeof(req), h->user_agent);
-	n = req_app(req, n, sizeof(req), "\r\nAccept: */*\r\n");
+	n = req_app(req, n, sizeof(req), "\r\nAccept: ");
+	n = req_app(req, n, sizeof(req), h->accept ? h->accept : "*/*");
+	n = req_app(req, n, sizeof(req), "\r\n");
+	if (h->jar) {
+		static char cookie[2048];
+
+		if (uhttp_jar_header(h->jar, h->url.host, h->url.path,
+				     h->url.secure, cookie, sizeof(cookie))) {
+			n = req_app(req, n, sizeof(req), "Cookie: ");
+			n = req_app(req, n, sizeof(req), cookie);
+			n = req_app(req, n, sizeof(req), "\r\n");
+		}
+	}
+	if (h->extra_headers)
+		n = req_app(req, n, sizeof(req), h->extra_headers);
 	if (flags & UHTTP_GZIP)
 		n = req_app(req, n, sizeof(req), "Accept-Encoding: gzip\r\n");
 	if (h->body_len) {
@@ -651,7 +701,9 @@ static int send_request(struct uhttp *h, unsigned int flags)
 		      "Connection: keep-alive\r\n\r\n" :
 		      "Connection: close\r\n\r\n");
 
-	if ((int)n > u_syscall0(SYS_TCP_PEER_MSS))
+	/* req_app stops one byte short of the end: a full buffer means the
+	 * request was truncated. */
+	if (n + 1 >= sizeof(req))
 		return UHTTP_ERR_TOOLONG;
 	rv = xport_send(h, req, n);
 	if (rv != 0)

+ 12 - 4
uhttp.h

@@ -12,13 +12,15 @@
 #define UHTTP_H
 
 #include "ucmd_lib.h"
+#include "uhttp_cookie.h"
 
 #define UHTTP_HOST_MAX       128
-#define UHTTP_PATH_MAX       512
-#define UHTTP_LOC_MAX        640
-#define UHTTP_LINE_MAX       320
+#define UHTTP_PATH_MAX       1024   /* path + query (OIDC URLs are long) */
+#define UHTTP_LOC_MAX        1280
+#define UHTTP_LINE_MAX       1536   /* Location / Set-Cookie header lines */
 #define UHTTP_READER_MAX     2048
-#define UHTTP_MAX_REDIRECTS  5
+#define UHTTP_REQ_MAX        4096   /* request line + headers */
+#define UHTTP_MAX_REDIRECTS  8
 #define UHTTP_IDLE_TIMEOUT_MS  10000
 #define UHTTP_TOTAL_TIMEOUT_MS 60000
 
@@ -79,6 +81,12 @@ struct uhttp {
 	const char *body;          /* request body for POST */
 	unsigned int body_len;
 	const char *content_type;
+	/* Optional cookie jar: every Set-Cookie (redirects included) is stored
+	 * and matching cookies are sent with each request and redirect hop.
+	 * The jar outlives the connection, so reconnects keep the session. */
+	struct uhttp_jar *jar;
+	const char *accept;        /* Accept header; NULL means star/star */
+	const char *extra_headers; /* verbatim "Name: value\r\n" lines */
 
 	unsigned char buf[UHTTP_READER_MAX];
 	unsigned int len, pos;

+ 423 - 0
uhttp_cookie.c

@@ -0,0 +1,423 @@
+/* uhttp_cookie: see uhttp_cookie.h. */
+
+#include "uhttp_cookie.h"
+
+static unsigned int c_len(const char *s)
+{
+	unsigned int n = 0;
+
+	while (s[n])
+		n++;
+	return n;
+}
+
+static char lower(char c)
+{
+	return (c >= 'A' && c <= 'Z') ? (char)(c - 'A' + 'a') : c;
+}
+
+static int eq_ci(const char *a, const char *b)
+{
+	while (*a && lower(*a) == lower(*b)) {
+		a++;
+		b++;
+	}
+	return lower(*a) == lower(*b);
+}
+
+static int eq(const char *a, const char *b)
+{
+	while (*a && *a == *b) {
+		a++;
+		b++;
+	}
+	return *a == *b;
+}
+
+/* Copy [s, s+n) into d (cap bytes); -1 when it does not fit. */
+static int copy_n(char *d, unsigned int cap, const char *s, unsigned int n)
+{
+	unsigned int i;
+
+	if (n + 1 > cap)
+		return -1;
+	for (i = 0; i < n; i++)
+		d[i] = s[i];
+	d[n] = '\0';
+	return 0;
+}
+
+static int is_ws(char c)
+{
+	return c == ' ' || c == '\t';
+}
+
+/* Trim [*s, *e) in place. */
+static void trim(const char **s, const char **e)
+{
+	while (*s < *e && is_ws(**s))
+		(*s)++;
+	while (*e > *s && is_ws((*e)[-1]))
+		(*e)--;
+}
+
+void uhttp_jar_init(struct uhttp_jar *jar)
+{
+	unsigned int i;
+
+	for (i = 0; i < sizeof(*jar); i++)
+		((unsigned char *)jar)[i] = 0;
+}
+
+void uhttp_jar_clear(struct uhttp_jar *jar)
+{
+	unsigned int changes = jar->changes;
+
+	uhttp_jar_init(jar);
+	jar->changes = changes + 1;
+}
+
+/* Length of the request path without query/fragment. */
+static unsigned int path_len(const char *path)
+{
+	unsigned int n = 0;
+
+	while (path[n] && path[n] != '?' && path[n] != '#')
+		n++;
+	return n;
+}
+
+/* RFC 6265 5.1.4 default-path: the directory of the request path. */
+static void default_path(const char *req, char *out, unsigned int cap)
+{
+	unsigned int n = path_len(req), i, last = 0;
+
+	if (n == 0 || req[0] != '/') {
+		copy_n(out, cap, "/", 1);
+		return;
+	}
+	for (i = 0; i < n; i++)
+		if (req[i] == '/')
+			last = i;
+	if (last == 0) {
+		copy_n(out, cap, "/", 1);
+		return;
+	}
+	if (copy_n(out, cap, req, last) != 0)
+		copy_n(out, cap, "/", 1);
+}
+
+static int path_match(const char *cpath, const char *req)
+{
+	unsigned int rn = path_len(req), cn = c_len(cpath), i;
+
+	if (cn == 0 || (cn == 1 && cpath[0] == '/'))
+		return 1;
+	if (rn < cn)
+		return 0;
+	for (i = 0; i < cn; i++)
+		if (cpath[i] != req[i])
+			return 0;
+	if (rn == cn)
+		return 1;
+	return cpath[cn - 1] == '/' || req[cn] == '/';
+}
+
+/* An Expires value in the past deletes the cookie.  Only the obvious case is
+ * recognized: servers clear cookies with a 1970 (epoch) date. */
+static int expires_past(const char *s, const char *e)
+{
+	while (s + 4 <= e) {
+		if (s[0] >= '0' && s[0] <= '9' && s[1] >= '0' && s[1] <= '9' &&
+		    s[2] >= '0' && s[2] <= '9' && s[3] >= '0' && s[3] <= '9' &&
+		    (s + 4 == e || s[4] < '0' || s[4] > '9')) {
+			unsigned int y = (unsigned int)(s[0] - '0') * 1000 +
+					 (unsigned int)(s[1] - '0') * 100 +
+					 (unsigned int)(s[2] - '0') * 10 +
+					 (unsigned int)(s[3] - '0');
+
+			return y < 2000;
+		}
+		s++;
+	}
+	return 0;
+}
+
+static int find(const struct uhttp_jar *jar, const char *host,
+		const char *path, const char *name)
+{
+	int i;
+
+	for (i = 0; i < UHTTP_COOKIE_MAX; i++) {
+		const struct uhttp_cookie *c = &jar->c[i];
+
+		if (c->used && eq_ci(c->host, host) && eq(c->path, path) &&
+		    eq(c->name, name))
+			return i;
+	}
+	return -1;
+}
+
+static int store(struct uhttp_jar *jar, const char *host, const char *path,
+		 const char *name, const char *value, int secure, int del)
+{
+	struct uhttp_cookie *c;
+	int i = find(jar, host, path, name);
+
+	if (del) {
+		if (i < 0)
+			return 0;
+		jar->c[i].used = 0;
+		jar->changes++;
+		return 1;
+	}
+	if (i >= 0) {
+		c = &jar->c[i];
+		if (eq(c->value, value) && c->secure == (secure ? 1 : 0))
+			return 0;
+		copy_n(c->value, sizeof(c->value), value, c_len(value));
+		c->secure = secure ? 1 : 0;
+		jar->changes++;
+		return 1;
+	}
+	for (i = 0; i < UHTTP_COOKIE_MAX; i++)
+		if (!jar->c[i].used)
+			break;
+	if (i == UHTTP_COOKIE_MAX) {
+		/* Full: evict the oldest cookie. */
+		int j, old = 0;
+
+		for (j = 1; j < UHTTP_COOKIE_MAX; j++)
+			if (jar->c[j].seq < jar->c[old].seq)
+				old = j;
+		i = old;
+	}
+	c = &jar->c[i];
+	if (copy_n(c->host, sizeof(c->host), host, c_len(host)) ||
+	    copy_n(c->path, sizeof(c->path), path, c_len(path)) ||
+	    copy_n(c->name, sizeof(c->name), name, c_len(name)) ||
+	    copy_n(c->value, sizeof(c->value), value, c_len(value))) {
+		c->used = 0;
+		return -1;
+	}
+	c->secure = secure ? 1 : 0;
+	c->used = 1;
+	c->seq = ++jar->seq;
+	jar->changes++;
+	return 1;
+}
+
+int uhttp_jar_set(struct uhttp_jar *jar, const char *host, const char *path,
+		  const char *set_cookie)
+{
+	char name[UHTTP_COOKIE_NAME_MAX];
+	char value[UHTTP_COOKIE_VALUE_MAX];
+	char cpath[UHTTP_COOKIE_PATH_MAX];
+	const char *p = set_cookie, *s, *e, *eqp;
+	int secure = 0, del = 0, have_path = 0;
+
+	if (!jar || !host || !host[0] || !set_cookie)
+		return -1;
+	/* name=value up to the first ';' */
+	s = p;
+	while (*p && *p != ';')
+		p++;
+	e = p;
+	trim(&s, &e);
+	eqp = s;
+	while (eqp < e && *eqp != '=')
+		eqp++;
+	if (eqp == e)
+		return -1;              /* no '=': ignore (RFC 6265 5.2) */
+	{
+		const char *ns = s, *ne = eqp, *vs = eqp + 1, *ve = e;
+
+		trim(&ns, &ne);
+		trim(&vs, &ve);
+		if (ns == ne)
+			return -1;
+		if (copy_n(name, sizeof(name), ns, (unsigned int)(ne - ns)) ||
+		    copy_n(value, sizeof(value), vs, (unsigned int)(ve - vs)))
+			return -1;
+	}
+
+	/* attributes */
+	while (*p == ';') {
+		const char *as, *ae, *ve, *vs;
+		char an[16];
+
+		p++;
+		as = p;
+		while (*p && *p != ';')
+			p++;
+		ae = p;
+		trim(&as, &ae);
+		vs = as;
+		while (vs < ae && *vs != '=')
+			vs++;
+		ve = ae;
+		{
+			const char *ne = vs;
+
+			while (ne > as && is_ws(ne[-1]))
+				ne--;
+			if (ne - as >= (int)sizeof(an))
+				continue;
+			copy_n(an, sizeof(an), as, (unsigned int)(ne - as));
+		}
+		if (vs < ae)
+			vs++;
+		trim(&vs, &ve);
+		if (eq_ci(an, "secure")) {
+			secure = 1;
+		} else if (eq_ci(an, "path")) {
+			if (vs < ve && *vs == '/' &&
+			    copy_n(cpath, sizeof(cpath), vs,
+				   (unsigned int)(ve - vs)) == 0)
+				have_path = 1;
+		} else if (eq_ci(an, "max-age")) {
+			const char *q = vs;
+			int neg = 0, nonzero = 0, digits = 0;
+
+			if (q < ve && *q == '-') {
+				neg = 1;
+				q++;
+			}
+			while (q < ve && *q >= '0' && *q <= '9') {
+				if (*q != '0')
+					nonzero = 1;
+				digits++;
+				q++;
+			}
+			if (digits && (neg || !nonzero))
+				del = 1;
+		} else if (eq_ci(an, "expires")) {
+			if (expires_past(vs, ve))
+				del = 1;
+		}
+	}
+	if (!have_path)
+		default_path(path ? path : "/", cpath, sizeof(cpath));
+	return store(jar, host, cpath, name, value, secure, del);
+}
+
+unsigned int uhttp_jar_header(const struct uhttp_jar *jar, const char *host,
+			      const char *path, int secure, char *out,
+			      unsigned int cap)
+{
+	int idx[UHTTP_COOKIE_MAX];
+	unsigned int plen[UHTTP_COOKIE_MAX];
+	int n = 0, i, j;
+	unsigned int len = 0;
+
+	if (cap)
+		out[0] = '\0';
+	if (!jar || !host)
+		return 0;
+	for (i = 0; i < UHTTP_COOKIE_MAX; i++) {
+		const struct uhttp_cookie *c = &jar->c[i];
+
+		if (!c->used || !eq_ci(c->host, host))
+			continue;
+		if (c->secure && !secure)
+			continue;
+		if (!path_match(c->path, path ? path : "/"))
+			continue;
+		idx[n] = i;
+		plen[n] = c_len(c->path);
+		n++;
+	}
+	/* Longer paths first, then creation order (RFC 6265 5.4). */
+	for (i = 1; i < n; i++) {
+		for (j = i; j > 0; j--) {
+			const struct uhttp_cookie *a = &jar->c[idx[j - 1]];
+			const struct uhttp_cookie *b = &jar->c[idx[j]];
+			int swap = plen[j] > plen[j - 1] ||
+				   (plen[j] == plen[j - 1] && b->seq < a->seq);
+
+			if (!swap)
+				break;
+			{
+				int ti = idx[j];
+				unsigned int tl = plen[j];
+
+				idx[j] = idx[j - 1];
+				plen[j] = plen[j - 1];
+				idx[j - 1] = ti;
+				plen[j - 1] = tl;
+			}
+		}
+	}
+	for (i = 0; i < n; i++) {
+		const struct uhttp_cookie *c = &jar->c[idx[i]];
+		unsigned int nl = c_len(c->name), vl = c_len(c->value);
+		unsigned int need = nl + 1 + vl + (len ? 2 : 0);
+		unsigned int k;
+
+		if (len + need + 1 > cap)
+			break;
+		if (len) {
+			out[len++] = ';';
+			out[len++] = ' ';
+		}
+		for (k = 0; k < nl; k++)
+			out[len++] = c->name[k];
+		out[len++] = '=';
+		for (k = 0; k < vl; k++)
+			out[len++] = c->value[k];
+		out[len] = '\0';
+	}
+	return len;
+}
+
+int uhttp_jar_import(struct uhttp_jar *jar, const char *host, int secure,
+		     const char *header)
+{
+	const char *p = header;
+	int count = 0;
+
+	if (!jar || !host || !header)
+		return 0;
+	while (*p) {
+		const char *s = p, *e, *eqp;
+		char name[UHTTP_COOKIE_NAME_MAX];
+		char value[UHTTP_COOKIE_VALUE_MAX];
+
+		while (*p && *p != ';')
+			p++;
+		e = p;
+		if (*p == ';')
+			p++;
+		trim(&s, &e);
+		eqp = s;
+		while (eqp < e && *eqp != '=')
+			eqp++;
+		if (eqp == e || eqp == s)
+			continue;
+		{
+			const char *ns = s, *ne = eqp, *vs = eqp + 1, *ve = e;
+
+			trim(&ns, &ne);
+			trim(&vs, &ve);
+			if (ns == ne ||
+			    copy_n(name, sizeof(name), ns,
+				   (unsigned int)(ne - ns)) ||
+			    copy_n(value, sizeof(value), vs,
+				   (unsigned int)(ve - vs)))
+				continue;
+		}
+		if (store(jar, host, "/", name, value, secure, 0) >= 0)
+			count++;
+	}
+	return count;
+}
+
+unsigned int uhttp_jar_count(const struct uhttp_jar *jar, const char *host)
+{
+	unsigned int i, n = 0;
+
+	for (i = 0; i < UHTTP_COOKIE_MAX; i++)
+		if (jar->c[i].used && eq_ci(jar->c[i].host, host))
+			n++;
+	return n;
+}

+ 62 - 0
uhttp_cookie.h

@@ -0,0 +1,62 @@
+/* uhttp_cookie: a small fixed-size cookie jar for ring-3 HTTP clients.
+ *
+ * Deliberately minimal (v1): cookies are host-only (the Domain attribute is
+ * ignored, so a cookie only goes back to the exact host that set it), the
+ * Path attribute is honoured as a prefix match, Secure cookies are only sent
+ * over https, and Max-Age<=0 or an Expires date in 1970 deletes the cookie.
+ * Other expiry dates, SameSite and HttpOnly are ignored: the jar lives as
+ * long as the process (or the config file it is exported to).
+ *
+ * Pure freestanding C with no includes, so uhttp_cookie_test.c exercises
+ * the same file on the host. */
+#ifndef UHTTP_COOKIE_H
+#define UHTTP_COOKIE_H
+
+#define UHTTP_COOKIE_MAX        24
+#define UHTTP_COOKIE_HOST_MAX   128
+#define UHTTP_COOKIE_PATH_MAX   160
+#define UHTTP_COOKIE_NAME_MAX   64
+#define UHTTP_COOKIE_VALUE_MAX  768
+
+struct uhttp_cookie {
+	char host[UHTTP_COOKIE_HOST_MAX];
+	char path[UHTTP_COOKIE_PATH_MAX];
+	char name[UHTTP_COOKIE_NAME_MAX];
+	char value[UHTTP_COOKIE_VALUE_MAX];
+	unsigned char used;
+	unsigned char secure;
+	unsigned int seq;               /* insertion order, for sending */
+};
+
+struct uhttp_jar {
+	struct uhttp_cookie c[UHTTP_COOKIE_MAX];
+	unsigned int seq;
+	unsigned int changes;           /* bumped on every add/update/delete */
+};
+
+void uhttp_jar_init(struct uhttp_jar *jar);
+void uhttp_jar_clear(struct uhttp_jar *jar);
+
+/* Apply one Set-Cookie header value (without the "Set-Cookie:" name) from a
+ * response to a request for host + path (the path may carry a query).
+ * Returns 1 when the jar changed, 0 when nothing changed, -1 on a malformed
+ * or oversized cookie. */
+int uhttp_jar_set(struct uhttp_jar *jar, const char *host, const char *path,
+		  const char *set_cookie);
+
+/* Build the Cookie header value ("a=1; b=2") for a request.  Returns its
+ * length (0 when no cookie matches); the output is truncated at whole
+ * cookies when it does not fit. */
+unsigned int uhttp_jar_header(const struct uhttp_jar *jar, const char *host,
+			      const char *path, int secure, char *out,
+			      unsigned int cap);
+
+/* Import a saved Cookie header ("a=1; b=2") as host-only cookies with
+ * Path=/ for host.  Returns the number of cookies stored. */
+int uhttp_jar_import(struct uhttp_jar *jar, const char *host, int secure,
+		     const char *header);
+
+/* Number of cookies currently stored for host. */
+unsigned int uhttp_jar_count(const struct uhttp_jar *jar, const char *host);
+
+#endif

+ 154 - 0
uhttp_cookie_test.c

@@ -0,0 +1,154 @@
+/* Host tests for uhttp_cookie.c (make test-chat). */
+
+#include <stdio.h>
+#include <string.h>
+
+#include "uhttp_cookie.h"
+
+static int failures;
+
+#define CHECK(cond) do { \
+	if (!(cond)) { \
+		printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
+		failures++; \
+	} \
+} while (0)
+
+static struct uhttp_jar jar;
+
+static const char *hdr(const char *host, const char *path, int secure)
+{
+	static char out[2048];
+
+	uhttp_jar_header(&jar, host, path, secure, out, sizeof(out));
+	return out;
+}
+
+static void test_basic(void)
+{
+	uhttp_jar_init(&jar);
+	CHECK(uhttp_jar_set(&jar, "chat.example.com", "/auth/login",
+			    "connect.sid=s%3Aabc.def; Path=/; Expires=Mon, 23 Nov 2026 18:03:29 GMT; HttpOnly; Secure; SameSite=Lax") == 1);
+	CHECK(strcmp(hdr("chat.example.com", "/api/me", 1),
+		     "connect.sid=s%3Aabc.def") == 0);
+	/* Secure cookie never goes over http. */
+	CHECK(strcmp(hdr("chat.example.com", "/api/me", 0), "") == 0);
+	/* Host-only: another host gets nothing, even a subdomain. */
+	CHECK(strcmp(hdr("my.chat.example.com", "/", 1), "") == 0);
+	CHECK(strcmp(hdr("CHAT.example.com", "/", 1),
+		     "connect.sid=s%3Aabc.def") == 0);
+	/* Same value again: no change. */
+	CHECK(uhttp_jar_set(&jar, "chat.example.com", "/",
+			    "connect.sid=s%3Aabc.def; Path=/; Secure") == 0);
+	/* Rolled value replaces it. */
+	CHECK(uhttp_jar_set(&jar, "chat.example.com", "/",
+			    "connect.sid=s%3Anew; Path=/; Secure") == 1);
+	CHECK(strcmp(hdr("chat.example.com", "/", 1),
+		     "connect.sid=s%3Anew") == 0);
+	CHECK(uhttp_jar_count(&jar, "chat.example.com") == 1);
+}
+
+static void test_paths(void)
+{
+	const char *uid = "/openid/interaction/UdA3nm";
+
+	uhttp_jar_init(&jar);
+	CHECK(uhttp_jar_set(&jar, "id.example.com", uid,
+			    "_interaction=abc; path=/openid/interaction/UdA3nm; httponly; samesite=lax; secure") == 1);
+	CHECK(uhttp_jar_set(&jar, "id.example.com", uid,
+			    "_interaction_resume=r1; path=/openid/auth/UdA3nm; secure") == 1);
+	CHECK(strcmp(hdr("id.example.com", "/openid/interaction/UdA3nm/login", 1),
+		     "_interaction=abc") == 0);
+	CHECK(strcmp(hdr("id.example.com", "/openid/interaction/UdA3nm", 1),
+		     "_interaction=abc") == 0);
+	CHECK(strcmp(hdr("id.example.com", "/openid/interaction/UdA3nmX", 1),
+		     "") == 0);
+	CHECK(strcmp(hdr("id.example.com", "/openid/auth/UdA3nm?x=1", 1),
+		     "_interaction_resume=r1") == 0);
+	/* Default path is the request directory. */
+	CHECK(uhttp_jar_set(&jar, "a.test", "/dir/page?q=1", "k=v") == 1);
+	CHECK(strcmp(hdr("a.test", "/dir/other", 0), "k=v") == 0);
+	CHECK(strcmp(hdr("a.test", "/dir", 0), "k=v") == 0);
+	CHECK(strcmp(hdr("a.test", "/", 0), "") == 0);
+	CHECK(uhttp_jar_set(&jar, "a.test", "/page", "root=1") == 1);
+	CHECK(strcmp(hdr("a.test", "/x", 0), "root=1") == 0);
+	/* Longer path first. */
+	CHECK(strcmp(hdr("a.test", "/dir/x", 0), "k=v; root=1") == 0);
+}
+
+static void test_delete_and_errors(void)
+{
+	uhttp_jar_init(&jar);
+	CHECK(uhttp_jar_set(&jar, "h", "/", "a=1; Path=/") == 1);
+	CHECK(uhttp_jar_set(&jar, "h", "/", "b = 2 ; Path=/") == 1);
+	CHECK(strcmp(hdr("h", "/", 0), "a=1; b=2") == 0);
+	CHECK(uhttp_jar_set(&jar, "h", "/", "a=; Path=/; Max-Age=0") == 1);
+	CHECK(strcmp(hdr("h", "/", 0), "b=2") == 0);
+	CHECK(uhttp_jar_set(&jar, "h", "/",
+			    "b=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT") == 1);
+	CHECK(strcmp(hdr("h", "/", 0), "") == 0);
+	/* Deleting a cookie that does not exist changes nothing. */
+	CHECK(uhttp_jar_set(&jar, "h", "/", "zz=; Max-Age=0") == 0);
+	CHECK(uhttp_jar_set(&jar, "h", "/", "novalue") == -1);
+	CHECK(uhttp_jar_set(&jar, "h", "/", "=v") == -1);
+	CHECK(uhttp_jar_set(&jar, "h", "/", "") == -1);
+	CHECK(uhttp_jar_set(&jar, "h", "/", "c=\"quoted\"; Max-Age=3600") == 1);
+	CHECK(strcmp(hdr("h", "/", 0), "c=\"quoted\"") == 0);
+}
+
+static void test_import_and_limits(void)
+{
+	char big[1000];
+	char out[32];
+	int i;
+
+	uhttp_jar_init(&jar);
+	CHECK(uhttp_jar_import(&jar, "chat.example.com", 1,
+			       "connect.sid=s%3Axyz;  theme=dark ; bad;=x") == 2);
+	CHECK(strcmp(hdr("chat.example.com", "/api/channels", 1),
+		     "connect.sid=s%3Axyz; theme=dark") == 0);
+	CHECK(strcmp(hdr("chat.example.com", "/api/channels", 0), "") == 0);
+
+	/* An oversized value is refused instead of truncated. */
+	memset(big, 'v', sizeof(big));
+	memcpy(big, "x=", 2);
+	big[sizeof(big) - 1] = '\0';
+	CHECK(uhttp_jar_set(&jar, "h", "/", big) == -1);
+
+	/* Truncation happens at whole cookies. */
+	uhttp_jar_init(&jar);
+	uhttp_jar_set(&jar, "h", "/", "aaaa=1111");
+	uhttp_jar_set(&jar, "h", "/", "bbbb=2222");
+	uhttp_jar_set(&jar, "h", "/", "cccc=3333");
+	CHECK(uhttp_jar_header(&jar, "h", "/", 0, out, 24) == 20);
+	CHECK(strcmp(out, "aaaa=1111; bbbb=2222") == 0);
+
+	/* A full jar evicts the oldest cookie. */
+	uhttp_jar_init(&jar);
+	for (i = 0; i < UHTTP_COOKIE_MAX + 2; i++) {
+		char c[32];
+
+		snprintf(c, sizeof(c), "n%d=v%d", i, i);
+		CHECK(uhttp_jar_set(&jar, "h", "/", c) == 1);
+	}
+	CHECK(uhttp_jar_count(&jar, "h") == UHTTP_COOKIE_MAX);
+	CHECK(strstr(hdr("h", "/", 0), "n0=") == NULL);
+	CHECK(strstr(hdr("h", "/", 0), "n1=") == NULL);
+	CHECK(strstr(hdr("h", "/", 0), "n2=v2") != NULL);
+	uhttp_jar_clear(&jar);
+	CHECK(uhttp_jar_count(&jar, "h") == 0);
+}
+
+int main(void)
+{
+	test_basic();
+	test_paths();
+	test_delete_and_errors();
+	test_import_and_limits();
+	if (failures) {
+		printf("uhttp_cookie_test: %d failure(s)\n", failures);
+		return 1;
+	}
+	printf("uhttp_cookie_test: all tests passed\n");
+	return 0;
+}

+ 519 - 0
ujson.c

@@ -0,0 +1,519 @@
+/* ujson: see ujson.h. */
+
+#include "ujson.h"
+
+struct pstate {
+	struct ujson *j;
+	const char *s;
+	unsigned int len, pos;
+	int depth;
+};
+
+static int fail(struct pstate *p, const char *msg)
+{
+	if (!p->j->error) {
+		p->j->error = msg;
+		p->j->error_pos = p->pos;
+	}
+	return -1;
+}
+
+static void skip_ws(struct pstate *p)
+{
+	while (p->pos < p->len) {
+		char c = p->s[p->pos];
+
+		if (c != ' ' && c != '\t' && c != '\n' && c != '\r')
+			break;
+		p->pos++;
+	}
+}
+
+static int new_node(struct pstate *p, unsigned char type)
+{
+	struct ujson *j = p->j;
+	struct ujson_node *n;
+
+	if (j->n >= j->cap)
+		return fail(p, "too many JSON nodes");
+	n = &j->nodes[j->n];
+	n->type = type;
+	n->key = 0;
+	n->str = 0;
+	n->len = 0;
+	n->child = -1;
+	n->next = -1;
+	return (int)j->n++;
+}
+
+static int sbuf_put(struct pstate *p, char c)
+{
+	struct ujson *j = p->j;
+
+	if (j->sn >= j->scap)
+		return fail(p, "JSON string pool full");
+	j->sbuf[j->sn++] = c;
+	return 0;
+}
+
+static int put_utf8(struct pstate *p, unsigned int cp)
+{
+	if (cp < 0x80)
+		return sbuf_put(p, (char)cp);
+	if (cp < 0x800) {
+		if (sbuf_put(p, (char)(0xC0 | (cp >> 6))) ||
+		    sbuf_put(p, (char)(0x80 | (cp & 0x3F))))
+			return -1;
+		return 0;
+	}
+	if (cp < 0x10000) {
+		if (sbuf_put(p, (char)(0xE0 | (cp >> 12))) ||
+		    sbuf_put(p, (char)(0x80 | ((cp >> 6) & 0x3F))) ||
+		    sbuf_put(p, (char)(0x80 | (cp & 0x3F))))
+			return -1;
+		return 0;
+	}
+	if (sbuf_put(p, (char)(0xF0 | (cp >> 18))) ||
+	    sbuf_put(p, (char)(0x80 | ((cp >> 12) & 0x3F))) ||
+	    sbuf_put(p, (char)(0x80 | ((cp >> 6) & 0x3F))) ||
+	    sbuf_put(p, (char)(0x80 | (cp & 0x3F))))
+		return -1;
+	return 0;
+}
+
+static int hex4(struct pstate *p, unsigned int *out)
+{
+	unsigned int v = 0, i;
+
+	if (p->pos + 4 > p->len)
+		return fail(p, "short \\u escape");
+	for (i = 0; i < 4; i++) {
+		char c = p->s[p->pos + i];
+		unsigned int d;
+
+		if (c >= '0' && c <= '9')
+			d = (unsigned int)(c - '0');
+		else if (c >= 'a' && c <= 'f')
+			d = (unsigned int)(c - 'a' + 10);
+		else if (c >= 'A' && c <= 'F')
+			d = (unsigned int)(c - 'A' + 10);
+		else
+			return fail(p, "bad \\u escape");
+		v = v * 16 + d;
+	}
+	p->pos += 4;
+	*out = v;
+	return 0;
+}
+
+/* Parse a string literal at p->pos (on the opening quote) into the pool. */
+static int parse_string(struct pstate *p, const char **out, unsigned int *olen)
+{
+	unsigned int start;
+
+	p->pos++;                     /* opening quote */
+	start = p->j->sn;
+	for (;;) {
+		unsigned char c;
+
+		if (p->pos >= p->len)
+			return fail(p, "unterminated string");
+		c = (unsigned char)p->s[p->pos++];
+		if (c == '"')
+			break;
+		if (c < 0x20)
+			return fail(p, "control character in string");
+		if (c != '\\') {
+			if (sbuf_put(p, (char)c))
+				return -1;
+			continue;
+		}
+		if (p->pos >= p->len)
+			return fail(p, "unterminated escape");
+		c = (unsigned char)p->s[p->pos++];
+		switch (c) {
+		case '"':  c = '"';  break;
+		case '\\': c = '\\'; break;
+		case '/':  c = '/';  break;
+		case 'b':  c = 8;    break;
+		case 'f':  c = 12;   break;
+		case 'n':  c = '\n'; break;
+		case 'r':  c = '\r'; break;
+		case 't':  c = '\t'; break;
+		case 'u': {
+			unsigned int cp, lo;
+
+			if (hex4(p, &cp))
+				return -1;
+			if (cp >= 0xD800 && cp <= 0xDBFF) {
+				/* High surrogate: a low one should follow. */
+				if (p->pos + 6 <= p->len &&
+				    p->s[p->pos] == '\\' &&
+				    p->s[p->pos + 1] == 'u') {
+					unsigned int save = p->pos;
+
+					p->pos += 2;
+					if (hex4(p, &lo))
+						return -1;
+					if (lo >= 0xDC00 && lo <= 0xDFFF) {
+						cp = 0x10000 +
+						     ((cp - 0xD800) << 10) +
+						     (lo - 0xDC00);
+					} else {
+						p->pos = save;
+						cp = 0xFFFD;
+					}
+				} else {
+					cp = 0xFFFD;
+				}
+			} else if (cp >= 0xDC00 && cp <= 0xDFFF) {
+				cp = 0xFFFD;
+			}
+			if (put_utf8(p, cp))
+				return -1;
+			continue;
+		}
+		default:
+			return fail(p, "bad escape");
+		}
+		if (sbuf_put(p, (char)c))
+			return -1;
+	}
+	*olen = p->j->sn - start;
+	if (sbuf_put(p, '\0'))
+		return -1;
+	*out = p->j->sbuf + start;
+	return 0;
+}
+
+static int match_word(struct pstate *p, const char *w)
+{
+	unsigned int i;
+
+	for (i = 0; w[i]; i++)
+		if (p->pos + i >= p->len || p->s[p->pos + i] != w[i])
+			return 0;
+	p->pos += i;
+	return 1;
+}
+
+static int parse_value(struct pstate *p);
+
+static int parse_number(struct pstate *p)
+{
+	unsigned int start = p->pos, i;
+	int idx, digits = 0;
+	struct ujson_node *n;
+
+	if (p->pos < p->len && p->s[p->pos] == '-')
+		p->pos++;
+	while (p->pos < p->len) {
+		char c = p->s[p->pos];
+
+		if (c >= '0' && c <= '9') {
+			digits++;
+		} else if (c != '.' && c != 'e' && c != 'E' &&
+			   c != '+' && c != '-') {
+			break;
+		}
+		p->pos++;
+	}
+	if (!digits)
+		return fail(p, "bad number");
+	idx = new_node(p, UJSON_NUMBER);
+	if (idx < 0)
+		return -1;
+	n = &p->j->nodes[idx];
+	n->str = p->j->sbuf + p->j->sn;
+	n->len = p->pos - start;
+	for (i = start; i < p->pos; i++)
+		if (sbuf_put(p, p->s[i]))
+			return -1;
+	if (sbuf_put(p, '\0'))
+		return -1;
+	return idx;
+}
+
+static int parse_container(struct pstate *p, int obj)
+{
+	int idx, last = -1;
+	char close = obj ? '}' : ']';
+
+	idx = new_node(p, obj ? UJSON_OBJECT : UJSON_ARRAY);
+	if (idx < 0)
+		return -1;
+	if (++p->depth > UJSON_MAX_DEPTH)
+		return fail(p, "JSON nested too deeply");
+	p->pos++;                       /* [ or { */
+	skip_ws(p);
+	if (p->pos < p->len && p->s[p->pos] == close) {
+		p->pos++;
+		p->depth--;
+		return idx;
+	}
+	for (;;) {
+		const char *key = 0;
+		unsigned int klen;
+		int child;
+
+		skip_ws(p);
+		if (obj) {
+			if (p->pos >= p->len || p->s[p->pos] != '"')
+				return fail(p, "expected member name");
+			if (parse_string(p, &key, &klen))
+				return -1;
+			skip_ws(p);
+			if (p->pos >= p->len || p->s[p->pos] != ':')
+				return fail(p, "expected ':'");
+			p->pos++;
+			skip_ws(p);
+		}
+		child = parse_value(p);
+		if (child < 0)
+			return -1;
+		p->j->nodes[child].key = key;
+		if (last < 0)
+			p->j->nodes[idx].child = child;
+		else
+			p->j->nodes[last].next = child;
+		last = child;
+		p->j->nodes[idx].len++;
+		skip_ws(p);
+		if (p->pos >= p->len)
+			return fail(p, "unterminated container");
+		if (p->s[p->pos] == ',') {
+			p->pos++;
+			continue;
+		}
+		if (p->s[p->pos] == close) {
+			p->pos++;
+			break;
+		}
+		return fail(p, obj ? "expected ',' or '}'" :
+				     "expected ',' or ']'");
+	}
+	p->depth--;
+	return idx;
+}
+
+static int parse_value(struct pstate *p)
+{
+	char c;
+	int idx;
+
+	skip_ws(p);
+	if (p->pos >= p->len)
+		return fail(p, "unexpected end of JSON");
+	c = p->s[p->pos];
+	if (c == '{')
+		return parse_container(p, 1);
+	if (c == '[')
+		return parse_container(p, 0);
+	if (c == '"') {
+		const char *s;
+		unsigned int n;
+
+		idx = new_node(p, UJSON_STRING);
+		if (idx < 0)
+			return -1;
+		if (parse_string(p, &s, &n))
+			return -1;
+		p->j->nodes[idx].str = s;
+		p->j->nodes[idx].len = n;
+		return idx;
+	}
+	if (c == '-' || (c >= '0' && c <= '9'))
+		return parse_number(p);
+	if (match_word(p, "true"))
+		return new_node(p, UJSON_TRUE);
+	if (match_word(p, "false"))
+		return new_node(p, UJSON_FALSE);
+	if (match_word(p, "null"))
+		return new_node(p, UJSON_NULL);
+	return fail(p, "unexpected character");
+}
+
+void ujson_init(struct ujson *j, struct ujson_node *nodes, unsigned int cap,
+		char *sbuf, unsigned int scap)
+{
+	j->nodes = nodes;
+	j->cap = cap;
+	j->n = 0;
+	j->sbuf = sbuf;
+	j->scap = scap;
+	j->sn = 0;
+	j->error = 0;
+	j->error_pos = 0;
+}
+
+int ujson_parse(struct ujson *j, const char *src, unsigned int len)
+{
+	struct pstate p;
+	int root;
+
+	j->n = 0;
+	j->sn = 0;
+	j->error = 0;
+	j->error_pos = 0;
+	p.j = j;
+	p.s = src;
+	p.len = len;
+	p.pos = 0;
+	p.depth = 0;
+	/* Skip a UTF-8 byte order mark. */
+	if (len >= 3 && (unsigned char)src[0] == 0xEF &&
+	    (unsigned char)src[1] == 0xBB && (unsigned char)src[2] == 0xBF)
+		p.pos = 3;
+	root = parse_value(&p);
+	if (root < 0)
+		return -1;
+	skip_ws(&p);
+	if (p.pos != p.len)
+		return fail(&p, "trailing data after JSON");
+	return root;
+}
+
+static int valid(const struct ujson *j, int idx)
+{
+	return idx >= 0 && (unsigned int)idx < j->n;
+}
+
+int ujson_type(const struct ujson *j, int idx)
+{
+	return valid(j, idx) ? j->nodes[idx].type : -1;
+}
+
+static int str_eq(const char *a, const char *b)
+{
+	while (*a && *a == *b) {
+		a++;
+		b++;
+	}
+	return *a == *b;
+}
+
+int ujson_get(const struct ujson *j, int idx, const char *key)
+{
+	int c;
+
+	if (!valid(j, idx) || j->nodes[idx].type != UJSON_OBJECT)
+		return -1;
+	for (c = j->nodes[idx].child; c >= 0; c = j->nodes[c].next)
+		if (j->nodes[c].key && str_eq(j->nodes[c].key, key))
+			return c;
+	return -1;
+}
+
+int ujson_first(const struct ujson *j, int idx)
+{
+	if (!valid(j, idx) || (j->nodes[idx].type != UJSON_ARRAY &&
+			       j->nodes[idx].type != UJSON_OBJECT))
+		return -1;
+	return j->nodes[idx].child;
+}
+
+int ujson_next(const struct ujson *j, int idx)
+{
+	return valid(j, idx) ? j->nodes[idx].next : -1;
+}
+
+unsigned int ujson_count(const struct ujson *j, int idx)
+{
+	if (!valid(j, idx) || (j->nodes[idx].type != UJSON_ARRAY &&
+			       j->nodes[idx].type != UJSON_OBJECT))
+		return 0;
+	return j->nodes[idx].len;
+}
+
+const char *ujson_str(const struct ujson *j, int idx)
+{
+	if (!valid(j, idx) || j->nodes[idx].type != UJSON_STRING)
+		return "";
+	return j->nodes[idx].str;
+}
+
+const char *ujson_get_str(const struct ujson *j, int obj, const char *key)
+{
+	return ujson_str(j, ujson_get(j, obj, key));
+}
+
+long ujson_int(const struct ujson *j, int idx, long def)
+{
+	const char *s;
+	long v = 0;
+	int neg = 0, digits = 0;
+
+	if (!valid(j, idx))
+		return def;
+	if (j->nodes[idx].type != UJSON_NUMBER &&
+	    j->nodes[idx].type != UJSON_STRING)
+		return def;
+	s = j->nodes[idx].str;
+	if (*s == '-') {
+		neg = 1;
+		s++;
+	}
+	while (*s >= '0' && *s <= '9') {
+		v = v * 10 + (*s - '0');
+		digits++;
+		s++;
+	}
+	if (!digits)
+		return def;
+	return neg ? -v : v;
+}
+
+int ujson_truthy(const struct ujson *j, int idx)
+{
+	if (!valid(j, idx))
+		return 0;
+	switch (j->nodes[idx].type) {
+	case UJSON_TRUE:
+		return 1;
+	case UJSON_NUMBER:
+		return ujson_int(j, idx, 0) != 0;
+	case UJSON_STRING:
+		return j->nodes[idx].len != 0;
+	default:
+		return 0;
+	}
+}
+
+int ujson_escape(char *out, unsigned int cap, const char *s)
+{
+	static const char hex[] = "0123456789abcdef";
+	unsigned int n = 0;
+
+#define PUT(ch) do { if (n + 1 >= cap) return -1; out[n++] = (ch); } while (0)
+	PUT('"');
+	for (; *s; s++) {
+		unsigned char c = (unsigned char)*s;
+
+		if (c == '"' || c == '\\') {
+			PUT('\\');
+			PUT((char)c);
+		} else if (c == '\n') {
+			PUT('\\');
+			PUT('n');
+		} else if (c == '\r') {
+			PUT('\\');
+			PUT('r');
+		} else if (c == '\t') {
+			PUT('\\');
+			PUT('t');
+		} else if (c < 0x20) {
+			PUT('\\');
+			PUT('u');
+			PUT('0');
+			PUT('0');
+			PUT(hex[c >> 4]);
+			PUT(hex[c & 15]);
+		} else {
+			PUT((char)c);
+		}
+	}
+	PUT('"');
+#undef PUT
+	out[n] = '\0';
+	return (int)n;
+}

+ 68 - 0
ujson.h

@@ -0,0 +1,68 @@
+/* ujson: small arena JSON DOM parser for ring-3 commands.
+ *
+ * The caller owns all memory: a node pool and a string pool.  Parsing never
+ * allocates; it fails cleanly when either pool is exhausted.  Strings (keys
+ * and values) are unescaped into the string pool as NUL-terminated UTF-8
+ * (\uXXXX escapes and surrogate pairs are decoded).  Numbers keep their raw
+ * text; ujson_int() converts the integer part.
+ *
+ * Pure freestanding C with no includes, so the host test (ujson_test.c) links
+ * the same file. */
+#ifndef UJSON_H
+#define UJSON_H
+
+#define UJSON_NULL   0
+#define UJSON_FALSE  1
+#define UJSON_TRUE   2
+#define UJSON_NUMBER 3
+#define UJSON_STRING 4
+#define UJSON_ARRAY  5
+#define UJSON_OBJECT 6
+
+#define UJSON_MAX_DEPTH 48
+
+struct ujson_node {
+	unsigned char type;
+	const char *key;        /* member name inside an object, else 0 */
+	const char *str;        /* STRING: decoded text; NUMBER: raw text */
+	unsigned int len;       /* STRING/NUMBER: bytes; ARRAY/OBJECT: count */
+	int child;              /* first child index, -1 none */
+	int next;               /* next sibling index, -1 none */
+};
+
+struct ujson {
+	struct ujson_node *nodes;
+	unsigned int cap, n;
+	char *sbuf;
+	unsigned int scap, sn;
+	const char *error;      /* static message after a failed parse */
+	unsigned int error_pos;
+};
+
+/* A string pool of len + 2 * nodes bytes is always large enough. */
+void ujson_init(struct ujson *j, struct ujson_node *nodes, unsigned int cap,
+		char *sbuf, unsigned int scap);
+/* Returns the root node index (0) or -1 on error (j->error says why). */
+int  ujson_parse(struct ujson *j, const char *src, unsigned int len);
+
+int  ujson_type(const struct ujson *j, int idx);
+/* Object member by name; -1 when idx is not an object or has no member. */
+int  ujson_get(const struct ujson *j, int idx, const char *key);
+/* Array/object iteration: first child and next sibling, -1 at the end. */
+int  ujson_first(const struct ujson *j, int idx);
+int  ujson_next(const struct ujson *j, int idx);
+unsigned int ujson_count(const struct ujson *j, int idx);
+/* "" when idx is not a string (or -1). */
+const char *ujson_str(const struct ujson *j, int idx);
+/* Convenience: ujson_str(ujson_get(obj, key)). */
+const char *ujson_get_str(const struct ujson *j, int obj, const char *key);
+/* Integer part of a number (or numeric string); def otherwise. */
+long ujson_int(const struct ujson *j, int idx, long def);
+/* 1 for true, a non-zero number or a non-empty string; 0 otherwise. */
+int  ujson_truthy(const struct ujson *j, int idx);
+
+/* Write s as a JSON string literal (with the quotes).  Returns the length
+ * written, or -1 when it does not fit in cap (including the NUL). */
+int  ujson_escape(char *out, unsigned int cap, const char *s);
+
+#endif

+ 177 - 0
ujson_test.c

@@ -0,0 +1,177 @@
+/* Host tests for ujson.c (make test-chat). */
+
+#include <stdio.h>
+#include <string.h>
+
+#include "ujson.h"
+
+static int failures;
+
+#define CHECK(cond) do { \
+	if (!(cond)) { \
+		printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
+		failures++; \
+	} \
+} while (0)
+
+static struct ujson_node nodes[4096];
+static char sbuf[65536];
+static struct ujson j;
+
+static int parse(const char *s)
+{
+	ujson_init(&j, nodes, sizeof(nodes) / sizeof(nodes[0]), sbuf,
+		   sizeof(sbuf));
+	return ujson_parse(&j, s, (unsigned int)strlen(s));
+}
+
+static void test_basic(void)
+{
+	int r = parse("{\"a\": 1, \"b\": [true, false, null, \"x\"],"
+		      " \"c\": {\"d\": -42.5e1}, \"e\": \"\"}");
+	int b, it;
+
+	CHECK(r == 0);
+	CHECK(ujson_type(&j, r) == UJSON_OBJECT);
+	CHECK(ujson_count(&j, r) == 4);
+	CHECK(ujson_int(&j, ujson_get(&j, r, "a"), -1) == 1);
+	b = ujson_get(&j, r, "b");
+	CHECK(ujson_type(&j, b) == UJSON_ARRAY);
+	CHECK(ujson_count(&j, b) == 4);
+	it = ujson_first(&j, b);
+	CHECK(ujson_type(&j, it) == UJSON_TRUE);
+	it = ujson_next(&j, it);
+	CHECK(ujson_type(&j, it) == UJSON_FALSE);
+	it = ujson_next(&j, it);
+	CHECK(ujson_type(&j, it) == UJSON_NULL);
+	it = ujson_next(&j, it);
+	CHECK(strcmp(ujson_str(&j, it), "x") == 0);
+	CHECK(ujson_next(&j, it) == -1);
+	CHECK(ujson_int(&j, ujson_get(&j, ujson_get(&j, r, "c"), "d"), 0) ==
+	      -42);
+	CHECK(strcmp(ujson_get_str(&j, r, "e"), "") == 0);
+	CHECK(ujson_get(&j, r, "missing") == -1);
+	CHECK(strcmp(ujson_get_str(&j, r, "missing"), "") == 0);
+	CHECK(strcmp(ujson_get_str(&j, r, "a"), "") == 0);
+	CHECK(ujson_truthy(&j, ujson_get(&j, r, "a")));
+	CHECK(!ujson_truthy(&j, ujson_get(&j, r, "e")));
+}
+
+static void test_escapes(void)
+{
+	int r = parse("[\"q\\\"b\\\\s\\/n\\n\\t\", \"\\u00e9\\u20ac\","
+		      " \"\\ud83d\\ude00\", \"\\ud800x\", \"caf\xc3\xa9\"]");
+	int it;
+
+	CHECK(r == 0);
+	it = ujson_first(&j, r);
+	CHECK(strcmp(ujson_str(&j, it), "q\"b\\s/n\n\t") == 0);
+	it = ujson_next(&j, it);
+	CHECK(strcmp(ujson_str(&j, it), "\xc3\xa9\xe2\x82\xac") == 0);
+	it = ujson_next(&j, it);
+	CHECK(strcmp(ujson_str(&j, it), "\xf0\x9f\x98\x80") == 0);
+	it = ujson_next(&j, it);
+	/* lone high surrogate -> U+FFFD */
+	CHECK(strcmp(ujson_str(&j, it), "\xef\xbf\xbdx") == 0);
+	it = ujson_next(&j, it);
+	CHECK(strcmp(ujson_str(&j, it), "caf\xc3\xa9") == 0);
+}
+
+static void test_errors(void)
+{
+	static const char *bad[] = {
+		"", "{", "[1,]", "{\"a\" 1}", "{\"a\":}", "[1 2]", "\"abc",
+		"tru", "{\"a\":1}x", "[\"\\x\"]", "[\"a\nb\"]", "-", "{1:2}",
+		"[\"\\u12\"]",
+	};
+	unsigned int i;
+
+	for (i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) {
+		int r = parse(bad[i]);
+
+		if (r != -1)
+			printf("FAIL: accepted bad JSON '%s'\n", bad[i]);
+		CHECK(r == -1);
+		CHECK(j.error != 0);
+	}
+}
+
+static void test_depth_and_pool(void)
+{
+	char deep[256];
+	struct ujson_node few[3];
+	char small[8];
+	int i;
+
+	for (i = 0; i < 100; i++)
+		deep[i] = '[';
+	for (i = 0; i < 100; i++)
+		deep[100 + i] = ']';
+	deep[200] = '\0';
+	CHECK(parse(deep) == -1);
+
+	ujson_init(&j, few, 3, sbuf, sizeof(sbuf));
+	CHECK(ujson_parse(&j, "[1,2,3]", 7) == -1);
+	ujson_init(&j, nodes, 64, small, sizeof(small));
+	CHECK(ujson_parse(&j, "\"0123456789\"", 12) == -1);
+}
+
+static void test_api_shape(void)
+{
+	/* A Chat /api/channels/:id/messages page (trimmed). */
+	const char *s =
+		"[{\"id\":\"m2\",\"clientId\":null,\"channelId\":\"c1\","
+		"\"userId\":\"u1\",\"authorName\":\"Alice\",\"body\":\"Hi \\ud83d\\udc4b\","
+		"\"type\":null,\"replyTo\":{\"id\":\"m1\",\"authorName\":\"Bob\","
+		"\"body\":\"earlier\"},\"createdAt\":\"2026-11-09T10:42:00.000Z\","
+		"\"deleted\":false,\"reactions\":[{\"emoji\":\"+1\",\"count\":2}],"
+		"\"attachments\":[{\"filename\":\"notes.txt\",\"size\":12}],"
+		"\"threadCount\":2,\"readBy\":[]},"
+		"{\"id\":\"m1\",\"userId\":\"u2\",\"authorName\":\"Bob\","
+		"\"body\":\"earlier\",\"createdAt\":\"2026-11-09T10:41:00.000Z\","
+		"\"deleted\":false,\"threadCount\":0}]";
+	int r = parse(s), m, rt, at;
+
+	CHECK(r == 0);
+	CHECK(ujson_count(&j, r) == 2);
+	m = ujson_first(&j, r);
+	CHECK(strcmp(ujson_get_str(&j, m, "authorName"), "Alice") == 0);
+	CHECK(strcmp(ujson_get_str(&j, m, "body"), "Hi \xf0\x9f\x91\x8b") == 0);
+	CHECK(ujson_type(&j, ujson_get(&j, m, "clientId")) == UJSON_NULL);
+	rt = ujson_get(&j, m, "replyTo");
+	CHECK(strcmp(ujson_get_str(&j, rt, "authorName"), "Bob") == 0);
+	at = ujson_first(&j, ujson_get(&j, m, "attachments"));
+	CHECK(strcmp(ujson_get_str(&j, at, "filename"), "notes.txt") == 0);
+	CHECK(ujson_int(&j, ujson_get(&j, m, "threadCount"), 0) == 2);
+	m = ujson_next(&j, m);
+	CHECK(strcmp(ujson_get_str(&j, m, "id"), "m1") == 0);
+}
+
+static void test_escape_out(void)
+{
+	char out[64];
+
+	CHECK(ujson_escape(out, sizeof(out), "a\"b\\c\nd\x01") > 0);
+	CHECK(strcmp(out, "\"a\\\"b\\\\c\\nd\\u0001\"") == 0);
+	CHECK(ujson_escape(out, 4, "abcdef") == -1);
+	/* round trip */
+	CHECK(ujson_escape(out, sizeof(out), "p@ss\"w\\rd") > 0);
+	CHECK(parse(out) == 0);
+	CHECK(strcmp(ujson_str(&j, 0), "p@ss\"w\\rd") == 0);
+}
+
+int main(void)
+{
+	test_basic();
+	test_escapes();
+	test_errors();
+	test_depth_and_pool();
+	test_api_shape();
+	test_escape_out();
+	if (failures) {
+		printf("ujson_test: %d failure(s)\n", failures);
+		return 1;
+	}
+	printf("ujson_test: all tests passed\n");
+	return 0;
+}

+ 7 - 0
wm_abi.h

@@ -42,6 +42,13 @@
 #define WM_BTN_GALLERY_Y WM_BTN_Y
 #define WM_BTN_GALLERY_W 72
 #define WM_BTN_GALLERY_H WM_BTN_H
+#define WM_BTN_CHAT_X (WM_BTN_GALLERY_X + WM_BTN_GALLERY_W + WM_BTN_GAP)
+#define WM_BTN_CHAT_Y WM_BTN_Y
+#define WM_BTN_CHAT_W 56
+#define WM_BTN_CHAT_H WM_BTN_H
+/* Right edge of the launcher buttons: the notice text and the right-aligned
+ * status (clock, sensors, power) never draw left of it. */
+#define WM_BTN_END_X (WM_BTN_CHAT_X + WM_BTN_CHAT_W)
 #define WM_TITLE_H 22
 #define WM_CLOSE_W 16