Cabin Chat 4.0: accounts, https, PWA, mentions, notifications

- accounts with name + password (salted sha256), one account on several
  devices at once, profile menu: change password, profile picture,
  link another device (QR code + one-time link), logout, delete account
- @mentions with picker and highlighting
- https by default with the router web admin's certificate; --http,
  --cert/--key installer options
- logo/favicon, app manifest, service worker (installable PWA)
- browser notifications via the service worker, no internet needed
- devserver: https option, ignore connections reset by the browser

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal Suter
2026-11-16 15:28:11 +01:00
co-authored by Claude Opus 5.5
parent 863d30eeba
commit 1459b3228d
15 changed files with 4118 additions and 353 deletions
+71 -10
View File
@@ -8,6 +8,11 @@ Browser-based group chat for a GL.iNet travel router (or any OpenWrt box).
Nothing to install on the phones, no extra packages on the router: it runs on
the built-in `uhttpd` web server with one small shell CGI script.
Group chat and private chats, photos, replies, emoji, @mentions, typing
notices, accounts with passwords (one account on several devices at once),
profile pictures, device linking by QR code, installable as an app (PWA) and
browser notifications. Messages disappear after 24 hours.
## Install on the router
Straight from git, in an SSH session on the router (`ssh root@192.168.8.1`):
@@ -22,20 +27,70 @@ Or copy it over from a checkout:
scp -O dist/install-cabinchat.sh root@192.168.8.1:/tmp/
ssh root@192.168.8.1 sh /tmp/install-cabinchat.sh
Running a newer installer over an existing install upgrades it and keeps
messages, photos and the port. Other commands: `-p <port>`, `wipe`, `uninstall`.
Open `https://192.168.8.1:8088` (or `https://chat.lan:8088`) on the router's WiFi.
Open `http://192.168.8.1:8088` (or `http://chat.lan:8088`) on the router's WiFi.
Running a newer installer over an existing install upgrades it and keeps
accounts, messages, photos, the port and the http/https choice. Options:
-p <port> port (default 8088)
--http plain http instead of https
--cert <file> --key <file> https with your own certificate (PEM, kept on upgrades)
wipe delete all messages and photos (accounts stay)
uninstall remove everything
## HTTPS, app install and notifications
By default the chat uses https with the certificate of the router's web admin
(GL.iNet: the one nginx uses). That certificate is self-signed, so every
browser shows a warning once; accept it to continue. If the router has no
certificate or uhttpd lacks TLS support, the installer falls back to http.
Browsers only offer some features on a *trusted* https connection:
| | trusted cert | router's self-signed cert | `--http` |
|---|---|---|---|
| chat, photos, accounts | ✓ | ✓ (after the warning) | ✓ |
| install as app (Android/desktop) | ✓ | no | no |
| Add to Home Screen (iOS) | ✓ | ✓ | ✓ |
| notifications | ✓ | usually blocked (browser-dependent) | no |
To get everything, give the installer a certificate the phones trust, e.g. a
Let's Encrypt certificate for a name in a domain you own (obtained at home via
DNS challenge), and point that name at the router:
`uci add_list dhcp.@dnsmasq[0].address='/chat.example.com/192.168.8.1'`.
Checking a certificate needs no internet, so this works in the air.
Notifications work while the chat is open in the background: in another tab,
or minimized with the screen on. Real push to a closed app needs the browser
maker's push service (internet), so phones that freeze background apps stop
getting notified until the chat is opened again.
## Accounts
Joining asks for a name and a password. A new name creates an account; an
existing name needs its password. Log in with the same name on more devices
to use them in parallel, or use *Link another device* in the profile menu
(click your name at the bottom of the chat list): it shows a QR code and a
link that log the other device in. Each link works once, for 10 minutes. The
profile menu also changes the password, sets a profile picture, controls
notifications, logs out and deletes the account (with everything it posted).
Passwords are stored as salted SHA-256 hashes (busybox has nothing slower).
Without https they cross the WiFi in plain text.
## Project layout
www/index.html the whole web app (HTML/CSS/JS, no external files)
www/cgi-bin/chat backend (POSIX sh + busybox); the API is described at its top
www/sw.js service worker (app install, notification clicks, offline page)
www/manifest.json app manifest
www/logo.svg logo and favicon; PNG icons are made from it by icons.sh
www/VERSION version string, bump it for a new release
data/, www/img/ chat data while developing (created on first use)
installer.sh.in installer template
build.sh bundles www/ into dist/install-cabinchat.sh
devserver.py dev server that behaves like uhttpd (stdlib Python)
icons.sh regenerates the PNG icons (needs inkscape + Pillow)
## Develop on a notebook or in Termux
@@ -44,8 +99,11 @@ Open `http://192.168.8.1:8088` (or `http://chat.lan:8088`) on the router's WiFi.
Edit `www/`, reload the browser. Chat data lives in `data/` and photos in
`www/img/` (delete both to start over). Open the page in two browsers (or a
normal and a private window) to test private chats and typing notices. When you're happy: bump `www/VERSION`, run `sh build.sh`, copy
`dist/install-cabinchat.sh` to the router.
normal and a private window) to test private chats, mentions and typing
notices. App install and notifications work on `localhost`; to try them from
a phone, run `devserver.py --cert cert.pem --key key.pem`. When you're happy:
bump `www/VERSION`, run `sh build.sh`, copy `dist/install-cabinchat.sh` to the
router.
> **Before every commit, run `sh build.sh` and commit the rebuilt
> `dist/install-cabinchat.sh` together with your changes.** The built
@@ -55,8 +113,11 @@ normal and a private window) to test private chats and typing notices. When you'
## Storage
On the router's flash: `/www-chat/data/messages` (one line per message) and
`seq`, outside the web root; photos in `/www-chat/htdocs/img/` with random file
names. Messages older than 24 h are dropped on the fly. Photos are refused once
they pass 50 MB. Presence, typing notices and the long-poll event token live in
RAM under `/tmp/cabinchat/`. Limits are at the top of `www/cgi-bin/chat`.
On the router's flash, outside the web root: `/www-chat/data/messages` (one
line per message), `seq`, `gen`, and `accounts/`, `names/`, `sessions/`,
`avatars/` (one small file per account, name, logged-in device and profile
picture); photos in `/www-chat/htdocs/img/` with random file names. Messages
older than 24 h are dropped on the fly. Photos are refused once they pass
50 MB. Presence, typing notices, device-link codes and the long-poll event
token live in RAM under `/tmp/cabinchat/`. Limits are at the top of
`www/cgi-bin/chat`.
+9 -2
View File
@@ -12,12 +12,19 @@ PAYLOAD=dist/.payload
mkdir -p dist
(cd www && find . -type f ! -path './img/*' ! -name '.*' | sort) | while IFS= read -r f; do
f=${f#./}
dir=$(dirname "$f")
[ "$dir" = . ] || echo " mkdir -p \"\$STAGE/$dir\""
case $f in *.png|*.jpg|*.ico)
# binary: octal escapes for the shell's printf builtin, 16 bytes per line
echo " {"
od -An -v -to1 "www/$f" | awk 'NF { s = ""; for (i = 1; i <= NF; i++) s = s "\\" $i; print "\tprintf '\''" s "'\''" }'
echo " } > \"\$STAGE/$f\""
continue ;;
esac
if grep -q "^$DELIM\$" "www/$f"; then
echo "build: $f contains the line $DELIM - cannot embed it" >&2
exit 1
fi
dir=$(dirname "$f")
[ "$dir" = . ] || echo " mkdir -p \"\$STAGE/$dir\""
echo " cat > \"\$STAGE/$f\" <<'$DELIM'"
cat "www/$f"
[ -z "$(tail -c 1 "www/$f")" ] || echo
+26 -9
View File
@@ -8,6 +8,9 @@ under /cgi-bin/. Python standard library only, so it runs on a notebook
python3 devserver.py # http://localhost:8088, reachable from your LAN
python3 devserver.py -p 9000 # other port
python3 devserver.py --local # only this machine
python3 devserver.py --cert c.pem --key k.pem # https (to test the app
# install and notifications from a phone;
# on localhost they work over http too)
Chat data is stored in ./data/ and photos in www/img/ (delete both to start
fresh); presence and typing state live in $TMPDIR/cabinchat/. CGI scripts are
@@ -19,6 +22,7 @@ import functools
import os
import shutil
import socket
import ssl
import subprocess
import sys
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
@@ -113,13 +117,18 @@ class Handler(SimpleHTTPRequestHandler):
else:
headers.append((k, v))
self.send_response(code, reason)
for k, v in headers:
self.send_header(k, v)
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
if self.command != "HEAD":
self.wfile.write(payload)
try:
self.send_response(code, reason)
for k, v in headers:
self.send_header(k, v)
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
if self.command != "HEAD":
self.wfile.write(payload)
except (BrokenPipeError, ConnectionResetError):
# the browser gave up on this request (usually an aborted long poll:
# tab reopened, phone woke up, page closed) - nothing to do
self.close_connection = True
def lan_ip():
@@ -139,6 +148,8 @@ def main():
ap.add_argument("--local", action="store_true", help="listen on 127.0.0.1 only")
ap.add_argument("--root", default=os.path.join(HERE, "www"), help="web root (default: ./www)")
ap.add_argument("-q", "--quiet", action="store_true", help="don't log requests")
ap.add_argument("--cert", help="TLS certificate (PEM): serve https")
ap.add_argument("--key", help="TLS private key (PEM), with --cert")
a = ap.parse_args()
root = os.path.abspath(a.root)
@@ -147,12 +158,18 @@ def main():
Handler.quiet = a.quiet
bind = "127.0.0.1" if a.local else "0.0.0.0"
srv = ThreadingHTTPServer((bind, a.port), functools.partial(Handler, directory=root))
scheme = "http"
if a.cert:
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain(a.cert, a.key)
srv.socket = ctx.wrap_socket(srv.socket, server_side=True)
scheme = "https"
print(f"Cabin Chat dev server - serving {root}")
print(f" http://localhost:{a.port}/")
print(f" {scheme}://localhost:{a.port}/")
ip = None if a.local else lan_ip()
if ip:
print(f" http://{ip}:{a.port}/ (other devices on your network)")
print(f" {scheme}://{ip}:{a.port}/ (other devices on your network)")
print("Ctrl+C to stop")
try:
srv.serve_forever()
+2935 -167
View File
File diff suppressed because it is too large Load Diff
+24
View File
@@ -0,0 +1,24 @@
#!/bin/sh
# Regenerate the PNG app icons in www/ from www/logo.svg (only needed when the
# logo changes; the PNGs are committed). Needs inkscape, plus python3 with
# Pillow to recompress the files.
set -e
cd "$(dirname "$0")/www"
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
# full-bleed square with the artwork inside the 80% safe zone, for Android's
# maskable icon and the iOS home screen (both round the corners themselves)
sed -e 's|<rect width="512" height="512" rx="112" fill="url(#bg)"/>|<rect width="512" height="512" fill="url(#bg)"/><g transform="translate(51.2 51.2) scale(.8)">|' \
-e 's|</svg>|</g></svg>|' logo.svg > "$tmp/full.svg"
inkscape logo.svg -w 192 -o icon-192.png
inkscape "$tmp/full.svg" -w 512 -o icon-maskable-512.png
inkscape "$tmp/full.svg" -w 180 -o apple-touch-icon.png
python3 - <<'EOF'
from PIL import Image
for f in ("icon-192.png", "icon-maskable-512.png", "apple-touch-icon.png"):
Image.open(f).convert("RGBA").save(f, optimize=True)
EOF
ls -l icon-*.png apple-touch-icon.png
+91 -15
View File
@@ -3,11 +3,15 @@
# Uses only what the firmware already ships (uhttpd, busybox, uci).
#
# sh install-cabinchat.sh install, or upgrade an existing install
# (keeps messages, photos and the port)
# (keeps accounts, messages, photos, port)
# sh install-cabinchat.sh -p 8090 install/upgrade on a specific port
# sh install-cabinchat.sh --http plain http instead of https
# sh install-cabinchat.sh --cert C --key K https with your own certificate
# sh install-cabinchat.sh wipe delete all messages and photos
# sh install-cabinchat.sh uninstall remove Cabin Chat completely
#
# https uses the certificate of the router's web admin unless --cert is given.
#
# Generated by build.sh - edit www/ and installer.sh.in instead of this file.
VERSION="@@VERSION@@"
@@ -24,16 +28,35 @@ info() { echo ">> $*"; }
warn() { echo "WARNING: $*" >&2; }
die() { echo "ERROR: $*" >&2; rm -rf "$STAGE"; exit 1; }
usage() {
if [ -f "$0" ]; then sed -n '4,9p' "$0" | sed 's/^# \{0,1\}//'
else echo "usage: sh install-cabinchat.sh [-p <port> | wipe | uninstall]"; fi
if [ -f "$0" ]; then sed -n '4,13p' "$0" | sed 's/^# \{0,1\}//'
else echo "usage: sh install-cabinchat.sh [-p <port>] [--http | --cert <file> --key <file>] [wipe | uninstall]"; fi
}
listening() { netstat -tln 2>/dev/null | grep -qE "[:.]$1[[:space:]]"; }
configured_port() {
uci -q get uhttpd.chat.listen_http | tr ' ' '\n' | sed -n 's/.*:\([0-9][0-9]*\)$/\1/p' | head -n 1
{ uci -q get uhttpd.chat.listen_https; uci -q get uhttpd.chat.listen_http; } |
tr ' ' '\n' | sed -n 's/.*:\([0-9][0-9]*\)$/\1/p' | head -n 1
}
# the certificate of the router's own web admin -> CERT, KEY
# (GL.iNet firmware: nginx; plain OpenWrt: uhttpd)
admin_cert() {
for f in /etc/nginx/conf.d/*.conf /etc/nginx/nginx.conf; do
[ -f "$f" ] || continue
c=$(sed -n 's/^[[:space:]]*ssl_certificate[[:space:]]\{1,\}\([^;[:space:]]*\);.*/\1/p' "$f" | head -n 1)
k=$(sed -n 's/^[[:space:]]*ssl_certificate_key[[:space:]]\{1,\}\([^;[:space:]]*\);.*/\1/p' "$f" | head -n 1)
if [ -s "$c" ] && [ -s "$k" ]; then CERT=$c; KEY=$k; return 0; fi
done
c=$(uci -q get uhttpd.main.cert); k=$(uci -q get uhttpd.main.key)
if [ -s "$c" ] && [ -s "$k" ]; then CERT=$c; KEY=$k; return 0; fi
if [ -s /etc/uhttpd.crt ] && [ -s /etc/uhttpd.key ]; then CERT=/etc/uhttpd.crt; KEY=/etc/uhttpd.key; return 0; fi
return 1
}
# uhttpd does TLS through libustream-ssl
have_tls() { ls /lib/libustream-ssl.so* /usr/lib/libustream-ssl.so* >/dev/null 2>&1; }
remove_config() {
if uci -q get uhttpd.chat >/dev/null; then
uci delete uhttpd.chat
@@ -85,6 +108,31 @@ do_install() {
die "port $PORT is already in use - choose another one with -p <port>"
fi
# https unless asked otherwise; an upgrade of a 4.x+ http install stays on http
OLDCERT=$(uci -q get uhttpd.chat.cert)
if [ -z "$TLS" ]; then
TLS=1
case $OLDVER in [4-9].*|[1-9][0-9]*)
uci -q get uhttpd.chat.listen_https >/dev/null || TLS=0 ;;
esac
fi
CERT=; KEY=
if [ "$TLS" = 1 ]; then
if [ -n "$CERT_ARG" ]; then
[ -s "$CERT_ARG" ] && [ -s "$KEY_ARG" ] || die "--cert and --key need two existing files (PEM)"
elif [ "$OLDCERT" = "$DATA/tls/cert.pem" ] && [ -s "$OLDCERT" ] && [ -s "$DATA/tls/key.pem" ]; then
CERT=$OLDCERT; KEY=$DATA/tls/key.pem # keep the certificate given last time
elif ! admin_cert; then
warn "no certificate of the router's web admin found - using plain http"
TLS=0
fi
if [ "$TLS" = 1 ] && ! have_tls; then
warn "uhttpd has no TLS support (libustream-ssl missing) - using plain http"
TLS=0
fi
fi
[ "$TLS" = 1 ] && SCHEME=https || SCHEME=http
if [ -n "$OLDVER" ]; then
info "upgrading Cabin Chat $OLDVER -> $VERSION"
else
@@ -125,9 +173,23 @@ do_install() {
rm -rf "$KEEPIMG"
[ -f "$CLOCK" ] || date +%s > "$CLOCK"
info "configuring web server on $LANIP:$PORT"
if [ "$TLS" = 1 ] && [ -n "$CERT_ARG" ]; then
mkdir -p "$DATA/tls"
cp "$CERT_ARG" "$DATA/tls/cert.pem" && cp "$KEY_ARG" "$DATA/tls/key.pem" || die "cannot copy the certificate"
chmod 600 "$DATA/tls/key.pem"
CERT=$DATA/tls/cert.pem; KEY=$DATA/tls/key.pem
fi
info "configuring web server on $SCHEME://$LANIP:$PORT"
uci set uhttpd.chat=uhttpd
uci add_list uhttpd.chat.listen_http="$LANIP:$PORT"
if [ "$TLS" = 1 ]; then
info "certificate: $CERT"
uci add_list uhttpd.chat.listen_https="$LANIP:$PORT"
uci set uhttpd.chat.cert="$CERT"
uci set uhttpd.chat.key="$KEY"
else
uci add_list uhttpd.chat.listen_http="$LANIP:$PORT"
fi
uci set uhttpd.chat.home="$WEB"
uci set uhttpd.chat.cgi_prefix='/cgi-bin'
uci set uhttpd.chat.index_page='index.html'
@@ -152,17 +214,22 @@ do_install() {
sleep 1
listening "$PORT" || die "uhttpd is not listening on port $PORT - check: logread | grep uhttpd"
if command -v wget >/dev/null; then
case $(wget -q -O - "http://$LANIP:$PORT/cgi-bin/chat?k=00000000000000000000000000000000&since=0" 2>/dev/null | head -n 1) in
@*) info "self-test passed" ;;
*) warn "the chat backend did not answer as expected - check: logread | grep uhttpd" ;;
case $(wget -q --no-check-certificate -O - "$SCHEME://$LANIP:$PORT/cgi-bin/chat?a=ping" 2>/dev/null | head -n 1) in
@cabinchat*) info "self-test passed" ;;
*) warn "the chat backend did not answer as expected - check: logread | grep uhttpd"
[ "$TLS" = 1 ] && warn "if https is the problem, run the installer again with --http" ;;
esac
fi
n=$(grep -c . "$DATA/messages" 2>/dev/null); n=${n:-0}
a=$(ls "$DATA/accounts" 2>/dev/null | grep -c .); a=${a:-0}
echo
info "Cabin Chat $VERSION is running ($n messages from the last 24 h kept)"
echo " http://$LANIP:$PORT"
echo " http://$DNSNAME:$PORT"
info "Cabin Chat $VERSION is running ($a accounts, $n messages from the last 24 h kept)"
echo " $SCHEME://$LANIP:$PORT"
echo " $SCHEME://$DNSNAME:$PORT"
if [ "$TLS" = 1 ] && [ -z "$CERT_ARG" ] && [ "$CERT" != "$DATA/tls/cert.pem" ]; then
echo " (the router's certificate is self-signed: browsers warn once, accept it to continue)"
fi
}
# ------------------------------------------------------------------ uninstall
@@ -177,19 +244,28 @@ do_uninstall() {
do_wipe() {
[ -d "$APP" ] || die "Cabin Chat is not installed"
rm -rf "$DATA" "$WEB/img"
mkdir -p "$DATA" "$WEB/img"
rm -rf "$DATA/messages" "$DATA/seq" "$WEB/img"
mkdir -p "$WEB/img"
g=$(cat "$DATA/gen" 2>/dev/null); case $g in ''|*[!0-9]*) g=0 ;; esac
echo $((g + 1)) > "$DATA/gen"
# wake up waiting browsers so they notice the empty chat
[ -d "$RUN" ] && echo "wipe.$$" > "$RUN/ev"
info "all messages and photos deleted"
info "all messages and photos deleted (accounts are kept)"
}
# ------------------------------------------------------------------ main
CMD=install
PORT=
TLS=
CERT_ARG=
KEY_ARG=
while [ $# -gt 0 ]; do
case $1 in
-p|--port) [ -n "$2" ] || die "-p needs a port number"; PORT=$2; shift 2 ;;
--http|--no-https) TLS=0; shift ;;
--https) TLS=1; shift ;;
--cert) [ -n "$2" ] || die "--cert needs a file"; CERT_ARG=$2; TLS=1; shift 2 ;;
--key) [ -n "$2" ] || die "--key needs a file"; KEY_ARG=$2; shift 2 ;;
[0-9]*) PORT=$1; shift ;;
install|upgrade) CMD=install; shift ;;
uninstall|remove) CMD=uninstall; shift ;;
+1 -1
View File
@@ -1 +1 @@
3.0.0
4.0.0
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

+289 -85
View File
@@ -8,26 +8,44 @@
# id ts type from to re nick payload
# type t: payload = text
# type i: payload = "<file> <width> <height>" (file in img/)
# to: "*" = everyone, otherwise the recipient's public id
# to: "*" = everyone, otherwise the recipient's user id
# re: id of the quoted message, 0 = none
# APP/data/seq last message id (never decreases)
# /tmp/cabinchat/ volatile state: presence, typing, event token, key cache
# APP/data/gen bumped when messages are deleted (clients reload)
# APP/data/accounts/UID "namehex salt sha256(salt+password) avatar-version|-"
# APP/data/names/LNAME UID (LNAME = hex of the ASCII-lowercased name)
# APP/data/sessions/TOK "UID created" - one per logged-in device
# APP/data/avatars/UID.jpg
# /tmp/cabinchat/ volatile state: presence, typing, link codes, event token
# data/ is outside the web root, so private messages can't be downloaded directly;
# photo file names contain a random part, so they can't be guessed.
#
# Identity: each browser keeps a random secret key (k, 32 hex). The server derives a
# public id from it (first 16 hex of its MD5). Only public ids are ever sent out.
# Identity: an account is a name + password. Logging in (or redeeming a link code
# from another device) gives the browser a random session token (k, 32 hex).
# A user id (UID, 16 hex) is public; tokens are never sent to other users.
#
# API
# GET chat?k=KEY&n=NICKHEX&since=ID&ev=TOKEN&w=1
# API (k = session token)
# GET chat?k=K&since=ID&ev=TOKEN&w=1
# Long poll: if nothing changed since TOKEN, waits up to HOLD seconds.
# Reply: @now <TAB> lastid <TAB> token <TAB> my-public-id
# U <TAB> id <TAB> nickhex <TAB> last-seen (users seen in 24 h)
# W <TAB> id <TAB> to <TAB> ts (who is typing)
# Reply: @now <TAB> lastid <TAB> token <TAB> my-uid <TAB> gen
# U <TAB> uid <TAB> namehex <TAB> last-seen <TAB> avatar-version|-
# W <TAB> uid <TAB> to <TAB> ts (who is typing)
# messages with since < id <= lastid that this user may see
# POST chat?a=text&k=KEY&n=NICKHEX&to=*|ID&re=ID body: UTF-8 text
# POST chat?a=img&k=KEY&n=NICKHEX&to=*|ID&re=ID&w=W&h=H&r=RND body: JPEG
# POST chat?a=typing&k=KEY&n=NICKHEX&to=*|ID|- (- = stopped)
# GET chat?a=avatar&u=UID profile picture (JPEG)
# GET chat?a=check&n=NAMEHEX "1" if the name is taken, else "0"
# GET chat?a=ping "@cabinchat VERSION" (installer self-test)
# POST chat?a=login&n=NAMEHEX[&ok=OLDKEY] body: password -> "token <TAB> uid <TAB> new"
# unknown name: creates the account; OLDKEY (a 3.x browser key) keeps its old id
# POST chat?a=redeem&c=CODE -> "token <TAB> uid" (link a device)
# POST chat?a=link&k=K -> "code <TAB> seconds-valid"
# POST chat?a=logout&k=K
# POST chat?a=passwd&k=K body: old-password LF new-password
# POST chat?a=delete&k=K body: password (removes account + posts)
# POST chat?a=avatar&k=K body: JPEG
# POST chat?a=noavatar&k=K
# POST chat?a=text&k=K&to=*|UID&re=ID body: UTF-8 text
# POST chat?a=img&k=K&to=*|UID&re=ID&w=W&h=H&r=RND body: JPEG
# POST chat?a=typing&k=K&to=*|UID|- (- = stopped)
#
# Timestamps come from the router's clock; clients only show relative ages.
# To keep that clock sane after a power cut (no RTC, no NTP in the air), the
@@ -38,8 +56,11 @@ KEEP=86400 # rolling window: 24 h
HOLD=25 # long-poll hold time, seconds
ONLINE=70 # seen within this many seconds = online (clients do the math)
TYPING=8 # a typing notice lives this long
LINK_TTL=600 # a "link a device" code is valid this long
MAX_TEXT=4000 # bytes per text message
MAX_IMG=400000 # bytes per photo (the client aims for ~100 kB)
MAX_AVATAR=100000 # bytes per profile picture (the client sends ~20 kB)
MAX_NAME=192 # hex digits per name (the client allows 24 characters)
MAX_DATA_KB=51200 # refuse new photos once img/ exceeds 50 MB
case $0 in */*) WEB=${0%/*}; WEB=${WEB%/*} ;; *) WEB=.. ;; esac
@@ -47,17 +68,25 @@ DATA=${CABINCHAT_DATA:-$WEB/../data}
IMG=$WEB/img
LOG=$DATA/messages
SEQ=$DATA/seq
GEN=$DATA/gen
ACC=$DATA/accounts
NAMES=$DATA/names
SESS=$DATA/sessions
AVA=$DATA/avatars
RUN=${TMPDIR:-/tmp}/cabinchat
EV=$RUN/ev
LOCKDIR=$RUN/lock
CLOCK=${CABINCHAT_CLOCK-/etc/cabinchat.clock}
NOW=$(date +%s)
NL='
'
qs="&$QUERY_STRING&"
me=
# ---------------------------------------------------------------- helpers
hdr() { printf 'Status: %s\r\nContent-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\n\r\n' "$1"; }
fail() { hdr "$1"; echo "$2"; exit 0; }
ok() { hdr "200 OK"; printf '%s\n' "${1:-ok}"; exit 0; }
# get NAME -> $v (raw value from the query string, empty if missing)
get() { v=${qs#*"&$1="}; if [ "$v" = "$qs" ]; then v=; else v=${v%%&*}; fi; }
@@ -65,6 +94,7 @@ get() { v=${qs#*"&$1="}; if [ "$v" = "$qs" ]; then v=; else v=${v%%&*}; fi; }
num() { case $1 in ''|*[!0-9]*) return 1 ;; esac; }
hex() { case $1 in ''|*[!0-9a-f]*) return 1 ;; esac; }
pubid() { hex "$1" && [ ${#1} -eq 16 ]; }
tok32() { hex "$1" && [ ${#1} -eq 32 ]; }
take_lock() {
i=0
@@ -82,6 +112,11 @@ bump() { echo "$NOW.$$" > "$EV"; }
read_body() {
if head -c 1 </dev/null >/dev/null 2>&1; then head -c "$cl"; else cat; fi
}
body_len() { # max-bytes -> $cl, fails if missing or too long
cl=${CONTENT_LENGTH:-0}; num "$cl" || cl=0
[ "$cl" -gt 0 ] || fail "400 Bad Request" "empty"
[ "$cl" -le "$1" ] || fail "413 Payload Too Large" "too large"
}
hash16() {
if command -v md5sum >/dev/null 2>&1; then printf '%s' "$1" | md5sum | cut -c 1-16
@@ -89,28 +124,65 @@ hash16() {
else printf '%016x\n' "$(printf '%s' "$1" | cksum | cut -d ' ' -f 1)"
fi
}
# k -> $me (public id); cached in RAM so the hash runs once per browser
identify() {
get k; key=$v
hex "$key" && [ ${#key} -eq 32 ] || fail "400 Bad Request" "bad key"
[ -f "$RUN/keys/$key" ] && read -r me < "$RUN/keys/$key"
if ! pubid "$me"; then
me=$(hash16 "$key")
printf '%s\n' "$me" > "$RUN/keys/$key"
sha() {
if command -v sha256sum >/dev/null 2>&1; then sha256sum | cut -c 1-64
elif command -v shasum >/dev/null 2>&1; then shasum -a 256 | cut -c 1-64
else openssl dgst -sha256 -r | cut -c 1-64
fi
}
rnd() { # N -> N random hex digits (N <= 64)
{ dd if=/dev/urandom bs=32 count=1 2>/dev/null; date; echo "$$"; } | sha | cut -c "1-$1"
}
pwhash() { printf '%s%s' "$1" "$2" | sha; } # salt password
# hex of a UTF-8 name -> same with ASCII A-Z lowercased (hex 41-5a -> 61-7a)
lower() {
printf '%s\n' "$1" | awk '{
s = ""
for (i = 1; i <= length($0); i += 2) {
p = substr($0, i, 2)
if (p >= "41" && p <= "5a") p = (substr(p, 1, 1) == "4" ? "6" : "7") substr(p, 2, 1)
s = s p
}
print s
}'
}
valid_name() { hex "$1" && [ $((${#1} % 2)) -eq 0 ] && [ ${#1} -le $MAX_NAME ]; }
# UID -> a_name a_salt a_hash a_ava
read_account() {
a_name=; a_salt=; a_hash=; a_ava=
[ -f "$ACC/$1" ] && read -r a_name a_salt a_hash a_ava < "$ACC/$1"
[ -n "$a_hash" ]
}
write_account() { # UID name salt hash avatar
printf '%s %s %s %s\n' "$2" "$3" "$4" "${5:--}" > "$ACC/$1.tmp" && mv "$ACC/$1.tmp" "$ACC/$1"
}
new_session() { # UID -> $tok
tok=$(rnd 32)
printf '%s %s\n' "$1" "$NOW" > "$SESS/$tok"
}
# k -> $me (user id), $nick (name hex); 401 makes the client show the login
identify() {
get k; tok=$v
tok32 "$tok" && [ -f "$SESS/$tok" ] || fail "401 Unauthorized" "login"
read -r me _ < "$SESS/$tok"
if ! pubid "$me" || ! read_account "$me"; then
rm -f "$SESS/$tok"
fail "401 Unauthorized" "login"
fi
nick=$a_name
}
# record that $me is here; wake everybody if that is news
seen_me() {
get n; nick=$v
hex "$nick" && [ ${#nick} -le 200 ] || nick=
[ -n "$nick" ] || return 0
f=$RUN/users/$me; ps=0; pn=
[ -f "$f" ] && read -r ps pn < "$f"
f=$RUN/seen/$me; ps=0
[ -f "$f" ] && read -r ps < "$f"
num "$ps" || ps=0
printf '%s %s\n' "$NOW" "$nick" > "$f"
if [ "$ps" -lt $((NOW - ONLINE + 20)) ] || [ "$pn" != "$nick" ]; then bump; fi
printf '%s\n' "$NOW" > "$f"
[ "$ps" -ge $((NOW - ONLINE + 20)) ] || bump
}
# a power cut can leave a half-written last line: make sure we start on a new one
@@ -127,6 +199,8 @@ next_id() {
}
read_seq() { lastid=0; [ -f "$SEQ" ] && read -r lastid < "$SEQ"; num "$lastid" || lastid=0; }
read_gen() { gen=0; [ -f "$GEN" ] && read -r gen < "$GEN"; num "$gen" || gen=0; }
next_gen() { read_gen; printf '%s\n' $((gen + 1)) > "$GEN.tmp" && mv "$GEN.tmp" "$GEN"; }
needs_prune() {
[ -s "$LOG" ] || return 1
@@ -135,6 +209,15 @@ needs_prune() {
[ "$first" -lt $((NOW - KEEP)) ]
}
# delete the photos listed in DATA/.del (written by the awk filters below)
del_photos() {
[ -f "$DATA/.del" ] || return 0
while IFS= read -r f; do
case $f in .*|*[!0-9a-f.-]*) ;; *.jpg) rm -f "$IMG/$f" ;; esac
done < "$DATA/.del"
rm -f "$DATA/.del"
}
# drop expired (and malformed) lines, delete their photos; call with lock held
prune() {
needs_prune || return 0
@@ -142,12 +225,7 @@ prune() {
NF == 8 && $1 ~ /^[0-9]+$/ && $2 >= c { print; next }
$3 == "i" { split($8, a, " "); print a[1] > del }
' "$LOG" > "$LOG.tmp" && mv "$LOG.tmp" "$LOG"
if [ -f "$DATA/.del" ]; then
while IFS= read -r f; do
case $f in .*|*[!0-9a-f.-]*) ;; *.jpg) rm -f "$IMG/$f" ;; esac
done < "$DATA/.del"
rm -f "$DATA/.del"
fi
del_photos
# photos whose message line never got written (power cut during upload)
find "$IMG" -type f -mtime +2 -exec rm -f {} \; 2>/dev/null
}
@@ -164,20 +242,92 @@ append() { # type payload
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$id" "$NOW" "$1" "$me" "$to" "$re" "$nick" "$2" >> "$LOG"
}
for d in "$DATA" "$IMG" "$RUN/keys" "$RUN/users" "$RUN/typing"; do
# body = JPEG of at most $1 bytes -> file $2 (or fail)
save_jpeg() {
body_len "$1"
read_body > "$2.$$"
size=$(wc -c < "$2.$$"); size=$((size))
if [ "$size" -ne "$cl" ]; then rm -f "$2.$$"; fail "400 Bad Request" "incomplete upload"; fi
if [ "$(head -c 3 "$2.$$")" != "$(printf '\377\330\377')" ]; then
rm -f "$2.$$"; fail "415 Unsupported Media Type" "JPEG expected"
fi
mv "$2.$$" "$2"
}
for d in "$DATA" "$IMG" "$ACC" "$NAMES" "$SESS" "$AVA" "$RUN/seen" "$RUN/typing" "$RUN/links"; do
[ -d "$d" ] || mkdir -p "$d" || fail "500 Internal Server Error" "cannot create $d"
done
[ -f "$EV" ] || bump
get a; act=$v
# ---------------------------------------------------------------- public GETs
if [ "$REQUEST_METHOD" != POST ]; then
case $act in
avatar)
get u; u=$v
pubid "$u" && [ -f "$AVA/$u.jpg" ] || fail "404 Not Found" "no picture"
printf 'Status: 200 OK\r\nContent-Type: image/jpeg\r\nCache-Control: max-age=31536000, immutable\r\n\r\n'
cat "$AVA/$u.jpg"
exit 0 ;;
check)
get n; valid_name "$v" || fail "400 Bad Request" "bad name"
[ -f "$NAMES/$(lower "$v")" ] && ok 1 || ok 0 ;;
ping)
ok "@cabinchat $(cat "$WEB/VERSION" 2>/dev/null)" ;;
esac
fi
# ---------------------------------------------------------------- POST
if [ "$REQUEST_METHOD" = POST ]; then
case $act in
login)
get n; name=$v
valid_name "$name" || fail "400 Bad Request" "bad name"
body_len 1024
pw=$(read_body)
[ -n "$pw" ] || fail "400 Bad Request" "empty password"
lk=$(lower "$name")
take_lock
uid=; [ -f "$NAMES/$lk" ] && read -r uid < "$NAMES/$lk"
if pubid "$uid" && read_account "$uid"; then
drop_lock
if [ "$(pwhash "$a_salt" "$pw")" != "$a_hash" ]; then
sleep 1 # slows down guessing
fail "403 Forbidden" "wrong password"
fi
new=0
else
# new account; a 3.x browser hands in its old key to keep its id (and messages)
get ok; uid=
tok32 "$v" && uid=$(hash16 "$v")
while ! pubid "$uid" || [ -f "$ACC/$uid" ]; do uid=$(rnd 16); done
salt=$(rnd 16)
write_account "$uid" "$name" "$salt" "$(pwhash "$salt" "$pw")" -
printf '%s\n' "$uid" > "$NAMES/$lk"
drop_lock
bump
new=1
fi
new_session "$uid"
ok "$tok $uid $new" ;;
redeem)
get c; code=$v
tok32 "$code" && [ -f "$RUN/links/$code" ] || fail "403 Forbidden" "invalid link"
read -r uid ts < "$RUN/links/$code"
rm -f "$RUN/links/$code" # one device per code
num "$ts" && [ "$ts" -ge $((NOW - LINK_TTL)) ] || fail "403 Forbidden" "link expired"
pubid "$uid" && read_account "$uid" || fail "403 Forbidden" "account deleted"
new_session "$uid"
ok "$tok $uid" ;;
esac
identify
seen_me
[ -n "$nick" ] || fail "400 Bad Request" "bad nick"
get a; act=$v
get to; to=$v
if [ "$act" = typing ]; then
case $act in
typing)
case $to in
-) rm -f "$RUN/typing/$me" ;;
'*') printf '* %s\n' "$NOW" > "$RUN/typing/$me" ;;
@@ -185,49 +335,103 @@ if [ "$REQUEST_METHOD" = POST ]; then
printf '%s %s\n' "$to" "$NOW" > "$RUN/typing/$me" ;;
esac
bump
hdr "200 OK"; echo ok
exit 0
fi
ok ;;
[ "$to" = '*' ] || pubid "$to" || fail "400 Bad Request" "bad recipient"
get re; re=$v; num "$re" || re=0
cl=${CONTENT_LENGTH:-0}; num "$cl" || cl=0
[ "$cl" -gt 0 ] || fail "400 Bad Request" "empty"
logout)
rm -f "$SESS/$tok"
ok ;;
case $act in
text)
[ "$cl" -le $MAX_TEXT ] || fail "413 Payload Too Large" "message too long"
msg=$(read_body | tr '\t\r\n' ' ')
case $msg in *[![:space:]]*) ;; *) fail "400 Bad Request" "empty" ;; esac
take_lock; prune; next_id; append t "$msg"; drop_lock
;;
img)
[ "$cl" -le $MAX_IMG ] || fail "413 Payload Too Large" "photo too large"
used=$(du -sk "$IMG" 2>/dev/null | cut -f 1); num "$used" || used=0
[ "$used" -lt $MAX_DATA_KB ] || fail "507 Insufficient Storage" "storage full"
get w; w=$v; num "$w" || w=0
get h; h=$v; num "$h" || h=0
get r; rnd=$v
hex "$rnd" && [ ${#rnd} -eq 16 ] || fail "400 Bad Request" "bad r"
tmp=$IMG/.upload.$$
read_body > "$tmp"
size=$(wc -c < "$tmp"); size=$((size))
if [ "$size" -ne "$cl" ]; then rm -f "$tmp"; fail "400 Bad Request" "incomplete upload"; fi
if [ "$(head -c 3 "$tmp")" != "$(printf '\377\330\377')" ]; then
rm -f "$tmp"; fail "415 Unsupported Media Type" "JPEG expected"
link)
for f in "$RUN"/links/*; do # forget expired codes
[ -f "$f" ] || continue
read -r u ts < "$f"
num "$ts" && [ "$ts" -ge $((NOW - LINK_TTL)) ] || rm -f "$f"
done
code=$(rnd 32)
printf '%s %s\n' "$me" "$NOW" > "$RUN/links/$code"
ok "$code $LINK_TTL" ;;
passwd)
body_len 2048
body=$(read_body)
old=${body%%"$NL"*}; pw=${body#*"$NL"}
[ "$old" != "$body" ] && [ -n "$pw" ] || fail "400 Bad Request" "bad request"
take_lock
read_account "$me"
if [ "$(pwhash "$a_salt" "$old")" != "$a_hash" ]; then
drop_lock; sleep 1; fail "403 Forbidden" "wrong password"
fi
take_lock; prune; next_id
mv "$tmp" "$IMG/$id-$rnd.jpg"
append i "$id-$rnd.jpg $w $h"
salt=$(rnd 16)
write_account "$me" "$a_name" "$salt" "$(pwhash "$salt" "$pw")" "$a_ava"
drop_lock
;;
ok ;;
delete)
body_len 1024
pw=$(read_body)
[ "$(pwhash "$a_salt" "$pw")" = "$a_hash" ] || { sleep 1; fail "403 Forbidden" "wrong password"; }
take_lock
rm -f "$ACC/$me" "$NAMES/$(lower "$nick")" "$AVA/$me.jpg" "$RUN/seen/$me" "$RUN/typing/$me"
for f in "$SESS"/*; do
[ -f "$f" ] || continue
read -r u _ < "$f"
[ "$u" = "$me" ] && rm -f "$f"
done
# everything this user posted goes too
if [ -s "$LOG" ]; then
awk -F '\t' -v me="$me" -v del="$DATA/.del" '
$4 == me { if ($3 == "i") { split($8, a, " "); print a[1] > del }; next }
{ print }
' "$LOG" > "$LOG.tmp" && mv "$LOG.tmp" "$LOG"
del_photos
fi
next_gen
drop_lock
bump
ok ;;
avatar|noavatar)
ver=-
if [ "$act" = avatar ]; then
save_jpeg $MAX_AVATAR "$AVA/$me.jpg"
ver=$(rnd 8)
else
rm -f "$AVA/$me.jpg"
fi
take_lock
read_account "$me" && write_account "$me" "$a_name" "$a_salt" "$a_hash" "$ver"
drop_lock
bump
ok "$ver" ;;
text|img)
[ "$to" = '*' ] || pubid "$to" || fail "400 Bad Request" "bad recipient"
get re; re=$v; num "$re" || re=0
if [ "$act" = text ]; then
body_len $MAX_TEXT
msg=$(read_body | tr '\t\r\n' ' ')
case $msg in *[![:space:]]*) ;; *) fail "400 Bad Request" "empty" ;; esac
take_lock; prune; next_id; append t "$msg"; drop_lock
else
used=$(du -sk "$IMG" 2>/dev/null | cut -f 1); num "$used" || used=0
[ "$used" -lt $MAX_DATA_KB ] || fail "507 Insufficient Storage" "storage full"
get w; w=$v; num "$w" || w=0
get h; h=$v; num "$h" || h=0
get r; rnd=$v
hex "$rnd" && [ ${#rnd} -eq 16 ] || fail "400 Bad Request" "bad r"
save_jpeg $MAX_IMG "$IMG/.upload-$$"
take_lock; prune; next_id
mv "$IMG/.upload-$$" "$IMG/$id-$rnd.jpg"
append i "$id-$rnd.jpg $w $h"
drop_lock
fi
rm -f "$RUN/typing/$me"
bump
touch_clock
ok "$id" ;;
*) fail "400 Bad Request" "unknown action" ;;
esac
rm -f "$RUN/typing/$me"
bump
touch_clock
hdr "200 OK"; echo "$id"
exit 0
fi
# ---------------------------------------------------------------- GET (long poll)
@@ -252,22 +456,22 @@ if [ "$wait" = 1 ] && [ "$cev" = "$ev" ] && [ "$since" -ge "$lastid" ]; then
done
NOW=$(date +%s)
read_seq
[ -n "$nick" ] && printf '%s %s\n' "$NOW" "$nick" > "$RUN/users/$me"
[ -f "$ACC/$me" ] && printf '%s\n' "$NOW" > "$RUN/seen/$me"
fi
read_gen
touch_clock
hdr "200 OK"
printf '@%s\t%s\t%s\t%s\n' "$NOW" "$lastid" "$ev" "$me"
printf '@%s\t%s\t%s\t%s\t%s\n' "$NOW" "$lastid" "$ev" "$me" "$gen"
for f in "$RUN"/users/*; do
for f in "$ACC"/*; do
[ -f "$f" ] || continue
read -r s n < "$f"
num "$s" || continue
if [ "$s" -ge $((NOW - KEEP)) ]; then
printf 'U\t%s\t%s\t%s\n' "${f##*/}" "$n" "$s"
else
rm -f "$f"
fi
u=${f##*/}
pubid "$u" || continue
read -r n _ _ av < "$f"
s=0; [ -f "$RUN/seen/$u" ] && read -r s < "$RUN/seen/$u"
num "$s" || s=0
printf 'U\t%s\t%s\t%s\t%s\n' "$u" "$n" "$s" "${av:--}"
done
for f in "$RUN"/typing/*; do
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

+612 -64
View File
@@ -8,8 +8,12 @@
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="Cabin Chat">
<title>Cabin Chat</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E%E2%9C%88%EF%B8%8F%3C/text%3E%3C/svg%3E">
<link rel="icon" href="logo.svg" type="image/svg+xml">
<link rel="icon" href="icon-192.png" sizes="192x192" type="image/png">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="manifest" href="manifest.json">
<style>
:root{
--bg:#0e1014; --panel:#14171d; --panel2:#1d2129; --line:#252a34;
@@ -209,6 +213,54 @@ footer{flex:none;background:var(--panel);border-top:1px solid var(--line);paddin
box-shadow:0 8px 24px rgba(0,0,0,.5);opacity:0;pointer-events:none;transition:opacity .25s,transform .25s}
#toast.show{opacity:1;transform:translate(-50%,0)}
#toast.click{pointer-events:auto;cursor:pointer}
/* profile pictures */
.avatar img{width:100%;height:100%;border-radius:50%;object-fit:cover;display:block}
.name{display:flex;align-items:center;gap:6px}
.name .avatar{width:20px;height:20px;font-size:11px}
.name .avatar .on{display:none}
.chip{display:flex;align-items:center;gap:8px;padding:5px 14px 5px 5px}
.chip .avatar{width:28px;height:28px;font-size:13px}
.chip span{overflow:hidden;text-overflow:ellipsis}
/* mentions */
.mention{color:#9cc0ff;font-weight:600}
.mine .mention{color:#fff;text-decoration:underline;text-underline-offset:2px}
.mention.me{background:rgba(250,204,21,.18);color:#fde68a;border-radius:5px;padding:0 2px}
.bubble.atme:not(.media){box-shadow:inset 3px 0 0 #facc15}
#mentions{position:absolute;left:10px;right:10px;bottom:100%;margin-bottom:6px;max-width:360px;padding:5px;
border:1px solid var(--line);border-radius:14px;background:#232833;box-shadow:0 12px 36px rgba(0,0,0,.6);z-index:5}
#mentions button{display:flex;align-items:center;gap:10px;width:100%;padding:7px 9px;border:0;border-radius:10px;
background:none;text-align:left;font-size:15px}
#mentions button.on{background:rgba(255,255,255,.09)}
#mentions .avatar{width:30px;height:30px;font-size:14px}
footer{position:relative}
/* login & profile */
.card .logo{width:72px;height:72px;margin:0 auto 12px;display:block}
.card input+input{margin-top:10px}
.err{min-height:20px;margin-top:8px;color:var(--bad);font-size:14px}
#sheetBack{position:fixed;inset:0;z-index:11;background:rgba(5,6,9,.7);-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);
display:flex;justify-content:center;align-items:flex-start;padding:max(6vh,env(safe-area-inset-top)) 16px 16px;overflow-y:auto}
#sheet{position:relative;padding-top:22px;text-align:left}
#sheet h2{text-align:center}
#sheet>p{text-align:center}
#sheet .avatar.big{width:86px;height:86px;font-size:38px;margin:0 auto 10px;cursor:pointer}
.xbtn{position:absolute;top:10px;right:10px}
.items{display:flex;flex-direction:column;gap:2px;margin-top:8px}
.items button{display:flex;align-items:center;gap:12px;width:100%;padding:12px;border:0;border-radius:12px;background:none;
text-align:left;font-size:15.5px}
.items button:active,.items button:hover{background:rgba(255,255,255,.06)}
.items button small{margin-left:auto;color:var(--muted);font-size:13px}
.items svg{flex:none;width:21px;height:21px;color:var(--muted)}
.items .danger,.items .danger svg{color:var(--bad)}
.primary.danger{background:var(--bad)}
.ghost{width:100%;margin-top:8px;padding:11px;border:0;border-radius:14px;background:var(--panel2);font-size:15px}
#sheet input{text-align:left}
.qr{display:block;width:220px;height:220px;margin:4px auto 12px;border-radius:12px;background:#fff}
.linkbox{display:block;padding:10px 12px;border-radius:12px;background:var(--panel2);font:13px/1.4 ui-monospace,monospace;
color:var(--muted);overflow-wrap:anywhere;user-select:all;-webkit-user-select:all}
.note{margin-top:12px;color:var(--muted);font-size:13.5px;text-align:center}
</style>
</head>
<body>
@@ -222,7 +274,7 @@ footer{flex:none;background:var(--panel);border-top:1px solid var(--line);paddin
</div>
<div id="plist"></div>
<div class="pfoot">
<button class="chip" id="me" title="Change your name"></button>
<button class="chip" id="me" title="Your profile"></button>
<span class="ver" id="ver"></span>
</div>
</aside>
@@ -252,6 +304,7 @@ footer{flex:none;background:var(--panel);border-top:1px solid var(--line);paddin
</main>
<footer>
<div id="mentions" hidden></div>
<div id="replyBar" hidden>
<div class="rq"><b id="rName"></b><span id="rText"></span></div>
<button type="button" class="icon" id="rCancel" aria-label="Cancel reply">
@@ -285,15 +338,20 @@ footer{flex:none;background:var(--panel);border-top:1px solid var(--line);paddin
<div id="viewer" hidden><img alt=""></div>
<div id="modal" hidden>
<form class="card" id="nameForm" autocomplete="off">
<div class="avatar group">✈️</div>
<h2 id="mTitle">Welcome aboard</h2>
<p>Pick a name your fellow passengers will see.</p>
<input id="nameIn" maxlength="24" placeholder="Your name" enterkeyhint="done">
<button class="primary">Join the chat</button>
<form class="card" id="loginForm">
<img class="logo" src="logo.svg" alt="">
<h2>Welcome aboard</h2>
<p id="lHint">Pick a name and a password. Use the same name and password to join from your other devices.</p>
<input id="nameIn" name="username" autocomplete="username" maxlength="24" placeholder="Your name" autocapitalize="words" enterkeyhint="next">
<input id="pwIn" name="password" type="password" autocomplete="current-password" maxlength="100" placeholder="Password" enterkeyhint="go">
<div class="err" id="lErr"></div>
<button class="primary" id="lBtn">Join the chat</button>
</form>
</div>
<div id="sheetBack" hidden><div class="card" id="sheet"></div></div>
<input type="file" id="avatarFile" accept="image/*" hidden>
<div id="toast"></div>
<script>
@@ -322,12 +380,12 @@ const ALL = '*';
const ICON_SMILE = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><circle cx="12" cy="12" r="9"/><path d="M8.3 14.2c.9 1.3 2.2 2 3.7 2s2.8-.7 3.7-2"/><circle cx="9" cy="9.8" r=".9" fill="currentColor" stroke="none"/><circle cx="15" cy="9.8" r=".9" fill="currentColor" stroke="none"/></svg>';
const ICON_KBD = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><rect x="2.5" y="6" width="19" height="12" rx="2.5"/><path d="M6 10h.01M9 10h.01M12 10h.01M15 10h.01M18 10h.01M6 13h.01M18 13h.01M8.5 14.5h7"/></svg>';
// identity: a secret key stays in this browser; the server only ever shows a public id
let key = store.get('cc.key');
if (!/^[0-9a-f]{32}$/.test(key || '')) { key = randHex(16); store.set('cc.key', key); }
// identity: logging in gives this device a session token; the server only ever shows user ids
let tok = store.get('cc.tok') || '';
if (!/^[0-9a-f]{32}$/.test(tok)) tok = '';
const oldKey = store.get('cc.key'); // 3.x browser key: lets the first login keep the old id
const legacyId = store.get('cc.uid'); // id used by version 2, to recognise own old messages
let nick = store.get('cc.nick') || '';
let me = ''; // public id, told by the server
let me = store.get('cc.me') || ''; // user id
/* ================================================================ state */
const msgs = new Map(); // id -> message (all conversations)
@@ -338,7 +396,7 @@ let readMarks = {}; // conversation key -> last read id
try { readMarks = JSON.parse(store.get('cc.read') || '{}') || {}; } catch (e) {}
const firstVisit = !store.get('cc.read');
let conv = ALL; // the open conversation
let since = 0, ev = '', offset = 0, online = null, loaded = false;
let since = 0, ev = '', gen = '', offset = 0, online = null, loaded = false;
let stick = true, unseen = 0, prev = null, replyTo = null;
/* ================================================================ time */
@@ -361,12 +419,15 @@ const nickOf = id => (users.get(id) || {}).nick || '?';
const isOnline = id => { const u = users.get(id); return !!u && serverNow() - u.seen < ONLINE; };
const isTyping = (id, to) => { const t = typing.get(id); return !!t && t.to === to && serverNow() - t.ts < TYPING_SHOW; };
function avatar(id, small) {
const avatarUrl = id => { const u = users.get(id); return u && u.ava && u.ava !== '-' ? 'cgi-bin/chat?a=avatar&u=' + id + '&v=' + u.ava : ''; };
function avatar(id) {
const a = el('div', 'avatar');
if (id === ALL) { a.classList.add('group'); a.textContent = '👥'; return a; }
a.textContent = (Array.from(nickOf(id).trim())[0] || '?').toUpperCase();
const src = avatarUrl(id);
if (src) { const im = new Image(); im.alt = ''; im.src = src; a.appendChild(im); }
else a.textContent = (Array.from(nickOf(id).trim())[0] || '?').toUpperCase();
a.style.background = 'hsl(' + hue(id) + ' 42% 34%)';
if (isOnline(id)) a.appendChild(el('span', 'on'));
if (id !== me && isOnline(id)) a.appendChild(el('span', 'on'));
return a;
}
@@ -404,6 +465,41 @@ function markReadIfSeen() { if (!document.hidden && stick && loaded) markRead(co
const snippet = m => m.type === 'i' ? '📷 Photo' : (m.text.length > 120 ? m.text.slice(0, 120) + '…' : m.text);
/* ================================================================ mentions */
// "@Name" where Name is a known user; names may contain spaces, so the longest match wins
let wordChar = /\w/;
try { wordChar = new RegExp('[\\p{L}\\p{N}_]', 'u'); } catch (e) {}
function knownNames() {
const s = new Set();
for (const u of users.values()) if (u.nick && u.nick !== '?') s.add(u.nick);
return [...s].sort((a, b) => b.length - a.length);
}
function mentionParts(text, names) { // -> strings and {name, text} pieces
const out = [], low = text.toLowerCase();
let last = 0;
for (let i = text.indexOf('@'); i >= 0; i = text.indexOf('@', i + 1)) {
if (i > 0 && wordChar.test(text[i - 1])) continue;
const n = names.find(n => low.startsWith(n.toLowerCase(), i + 1) && !wordChar.test(text.charAt(i + 1 + n.length)));
if (!n) continue;
if (i > last) out.push(text.slice(last, i));
out.push({ name: n, text: text.slice(i, i + 1 + n.length) });
i += n.length; last = i + 1;
}
if (last < text.length) out.push(text.slice(last));
return out;
}
const isMe = name => name.toLowerCase() === nickOf(me).toLowerCase();
const mentionsMe = m => m.type === 't' && !isMine(m) && m.text.includes('@') &&
mentionParts(m.text, knownNames()).some(p => typeof p === 'object' && isMe(p.name));
function textEl(text) {
const s = el('span');
for (const p of mentionParts(text, knownNames())) {
if (typeof p === 'string') s.appendChild(document.createTextNode(p));
else s.appendChild(el('span', 'mention' + (isMe(p.name) ? ' me' : ''), p.text));
}
return s;
}
/* ================================================================ message rendering */
let emojiOnly = null;
try { emojiOnly = new RegExp('^(?:\\p{Extended_Pictographic}|\\p{Emoji_Modifier}|\\p{Regional_Indicator}|\\u200d|\\ufe0f|\\s)+$', 'u'); } catch (e) {}
@@ -454,7 +550,8 @@ function render(m) {
const row = el('div', 'row last' + (mine ? ' mine' : '') + (grouped ? '' : ' first'));
if (grouped) prev.row.classList.remove('last');
if (!grouped && !mine && conv === ALL) {
const n = el('div', 'name', m.nick);
const n = el('div', 'name');
n.append(avatar(m.from), el('span', null, m.nick));
n.style.color = nameColor(m.from);
row.appendChild(n);
}
@@ -466,7 +563,8 @@ function render(m) {
b.append(photoEl('img/' + m.file, m.w, m.h, 'photo'), metaEl(m.ts));
} else {
if (!m.re && emojiOnly && m.text.length <= 16 && emojiOnly.test(m.text)) b.classList.add('jumbo');
b.append(el('span', null, m.text), metaEl(m.ts));
if (mentionsMe(m)) b.classList.add('atme');
b.append(textEl(m.text), metaEl(m.ts));
}
row.appendChild(b);
row.dataset.ts = m.ts;
@@ -512,7 +610,7 @@ function expire() {
}
/* ================================================================ header, people list, typing */
let listSig = '';
let listSig = '', headSig = '', meSig = '';
function refreshUI() {
// header
const sub = $('hSub');
@@ -527,7 +625,10 @@ function refreshUI() {
else { const u = users.get(conv); text = u && u.seen ? 'last seen ' + ago(u.seen) : 'offline'; }
sub.textContent = text; sub.className = 'status ' + cls;
$('hTitle').textContent = conv === ALL ? 'Everyone' : nickOf(conv);
const ha = $('hAvatar'); ha.textContent = ''; ha.appendChild(avatar(conv));
const hsig = conv + avatarUrl(conv) + nickOf(conv) + isOnline(conv);
if (hsig !== headSig) { headSig = hsig; const ha = $('hAvatar'); ha.textContent = ''; ha.appendChild(avatar(conv)); }
const msig = nickOf(me) + avatarUrl(me);
if (me && msig !== meSig) { meSig = msig; $('me').textContent = ''; $('me').append(avatar(me), el('span', null, nickOf(me))); }
// typing bubble at the bottom of the open chat
const names = typersIn(conv);
@@ -549,7 +650,7 @@ function refreshUI() {
function peopleIds() {
const ids = new Set();
for (const id of users.keys()) ids.add(id);
for (const [id, u] of users) if (serverNow() - u.seen < KEEP) ids.add(id); // accounts stay; show the recent ones
for (const c of convs.keys()) if (c !== ALL) ids.add(c);
for (const m of convs.get(ALL) || []) ids.add(m.from);
ids.delete(me); ids.delete(ALL); if (legacyId) ids.delete(legacyId);
@@ -572,7 +673,7 @@ function renderList() {
} else if (isTyping(c, me)) { sub = 'typing…'; typ = true; }
else if (last) sub = (isMine(last) ? 'You: ' : '') + snippet(last);
else sub = isOnline(c) ? 'online' : (users.get(c) && users.get(c).seen ? 'last seen ' + ago(users.get(c).seen) : 'offline');
return { c, name: c === ALL ? 'Everyone' : nickOf(c), sub, typ, n, time: last ? shortAgo(last.ts) : '', on: c !== ALL && isOnline(c) };
return { c, name: c === ALL ? 'Everyone' : nickOf(c), sub, typ, n, time: last ? shortAgo(last.ts) : '', on: c !== ALL && isOnline(c), ava: avatarUrl(c) };
});
const sig = conv + JSON.stringify(rows);
if (sig === listSig) return;
@@ -674,8 +775,8 @@ function kick() { // restart the long poll right now
function setOnline(v) { if (v !== online) { online = v; refreshUI(); } }
function resetAll() {
msgs.clear(); convs.clear(); since = 0; ev = '';
function resetAll() { // reload everything with the next poll (quietly, like the first load)
msgs.clear(); convs.clear(); users.clear(); since = 0; ev = ''; loaded = false;
renderConv();
}
@@ -694,10 +795,12 @@ function handle(text) {
const lines = text.split('\n');
lines.pop(); // '' or a half-written line
const h = (lines.shift() || '').split('\t');
if (h.length < 4 || h[0][0] !== '@') throw new Error('bad response');
if (h.length < 5 || h[0][0] !== '@') throw new Error('bad response');
offset = +h[0].slice(1) - Date.now() / 1000;
const last = +h[1];
me = h[3];
if (me !== h[3]) { me = h[3]; store.set('cc.me', me); }
if (gen && h[4] !== gen) { gen = h[4]; resetAll(); return; } // messages were deleted
gen = h[4];
if (last < since) { resetAll(); return; } // chat was wiped on the router
ev = h[2];
@@ -705,8 +808,8 @@ function handle(text) {
typing = new Map();
for (const l of lines) {
if (l[0] === 'U') {
const [, id, n, s] = l.split('\t');
if (id !== me) users.set(id, { nick: fromHex(n) || '?', seen: +s });
const [, id, n, s, ava] = l.split('\t');
users.set(id, { nick: fromHex(n) || '?', seen: +s, ava: ava || '-' });
} else if (l[0] === 'W') {
const [, id, to, ts] = l.split('\t');
typing.set(id, { to, ts: +ts });
@@ -726,8 +829,9 @@ function handle(text) {
} else if (fresh.length) {
let here = 0, theirs = 0;
for (const m of fresh) {
if (convOf(m) === conv) { render(m); here++; if (!isMine(m)) theirs++; }
else if (!isMine(m)) notify(m);
const inView = convOf(m) === conv;
if (inView) { render(m); here++; if (!isMine(m)) theirs++; }
if (!isMine(m)) notify(m, inView);
}
if (here) { if (stick) toBottom(); else { unseen += theirs; updateJump(); } }
}
@@ -739,8 +843,9 @@ async function pollOnce() {
kicked = false;
const watchdog = setTimeout(() => ctrl.abort(), 40000); // dead connection (router reboot, WiFi drop)
try {
const url = 'cgi-bin/chat?k=' + key + '&n=' + toHex(nick) + '&since=' + since + '&ev=' + ev + '&w=' + (ev ? 1 : 0);
const url = 'cgi-bin/chat?k=' + tok + '&since=' + since + '&ev=' + ev + '&w=' + (ev ? 1 : 0);
const r = await fetch(url, { cache: 'no-store', signal: ctrl.signal });
if (r.status === 401) { signedOut(); return 0; }
if (!r.ok) throw new Error(r.status);
handle(await r.text());
fails = 0;
@@ -756,12 +861,28 @@ async function pollOnce() {
return document.hidden ? 3000 : 0; // background: fewer wake-ups
}
let running = false;
async function loop() {
for (;;) {
if (running) return;
running = true;
while (tok) {
const d = await pollOnce();
if (d) await nap(d);
if (d && tok) await nap(d);
wake = null;
}
running = false;
}
// POST to the backend; resolves with the reply text, rejects with the server's message
async function api(act, body, extra) {
const r = await fetch('cgi-bin/chat?a=' + act + (tok ? '&k=' + tok : '') + (extra || ''), {
method: 'POST', body,
headers: { 'Content-Type': body instanceof Blob ? 'image/jpeg' : 'text/plain;charset=utf-8' }
});
const t = (await r.text()).trim();
if (r.status === 401 && tok) { signedOut(); throw new Error('Please log in again'); }
if (!r.ok) throw new Error(t || 'error ' + r.status);
return t;
}
document.addEventListener('visibilitychange', () => {
@@ -769,12 +890,12 @@ document.addEventListener('visibilitychange', () => {
});
const postUrl = (act, extra) =>
'cgi-bin/chat?a=' + act + '&k=' + key + '&n=' + toHex(nick) + '&to=' + encodeURIComponent(conv) + (extra || '');
'cgi-bin/chat?a=' + act + '&k=' + tok + '&to=' + encodeURIComponent(conv) + (extra || '');
/* ================================================================ typing notices */
let typingSent = 0, typingConv = null;
function sendTyping(to) {
fetch('cgi-bin/chat?a=typing&k=' + key + '&n=' + toHex(nick) + '&to=' + encodeURIComponent(to), { method: 'POST' }).catch(() => {});
fetch('cgi-bin/chat?a=typing&k=' + tok + '&to=' + encodeURIComponent(to), { method: 'POST' }).catch(() => {});
}
function onTyping() {
const now = Date.now();
@@ -792,7 +913,7 @@ async function sendText() {
const m = clean(input.value).slice(0, 1000);
if (!m) return;
const re = replyTo;
input.value = ''; updateSend(); cancelReply();
input.value = ''; updateSend(); cancelReply(); hideMentions();
typingSent = 0; typingConv = null; // the server clears our typing notice
try {
const r = await fetch(postUrl('text', re ? '&re=' + re : ''), { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: m });
@@ -870,7 +991,7 @@ $('file').addEventListener('change', () => {
function openViewer(src) { $('viewer').firstElementChild.src = src; $('viewer').hidden = false; }
$('viewer').addEventListener('click', () => { $('viewer').hidden = true; });
addEventListener('keydown', e => { if (e.key === 'Escape') { $('viewer').hidden = true; closeMenu(); cancelReply(); } });
addEventListener('keydown', e => { if (e.key === 'Escape') { $('viewer').hidden = true; closeMenu(); cancelReply(); closeSheet(); } });
/* ================================================================ replies (quotes) */
function setReply(id) {
@@ -1002,12 +1123,52 @@ function toast(t, onClick) {
clearTimeout(toastTimer);
toastTimer = setTimeout(() => e.classList.remove('show'), onClick ? 4500 : 3200);
}
function notify(m) {
if (document.hidden) return;
const where = m.to === ALL ? m.nick + ' in Everyone' : m.nick;
const c = convOf(m);
toast('💬 ' + where + ': ' + snippet(m), () => openConv(c));
// system notifications: shown while the chat runs in the background (another tab or app,
// screen on). Without internet there is no push service, so a closed chat can't be woken up.
// cc.notify: 'all' | 'direct' (private messages and mentions) | 'off'
let swReg = null;
const canNotify = () => 'Notification' in window && window.isSecureContext;
const notifyPref = () => store.get('cc.notify') || 'all';
function notify(m, inView) {
const c = convOf(m), where = m.to === ALL ? m.nick + ' in Everyone' : m.nick;
if (document.hidden || !document.hasFocus()) { sysNotify(m, c, where); return; }
if (!inView) toast((mentionsMe(m) ? '@ ' : '💬 ') + where + ': ' + snippet(m), () => openConv(c));
}
function sysNotify(m, c, where) {
if (!canNotify() || Notification.permission !== 'granted') return;
const pref = notifyPref();
if (pref === 'off' || (pref === 'direct' && m.to === ALL && !mentionsMe(m))) return;
const at = mentionsMe(m), title = (at ? '@ ' : '') + where;
// one notification per chat (newest replaces older ones); mentions stay
const opts = { body: snippet(m), tag: at ? 'cc-at-' + m.id : 'cc-' + c, renotify: true, icon: 'icon-192.png', data: { conv: c } };
if (swReg) { swReg.showNotification(title, opts).catch(() => {}); return; }
try {
const n = new Notification(title, opts);
n.onclick = () => { focus(); openConv(c); n.close(); };
} catch (e) {}
}
async function askNotify() {
if (!canNotify()) {
toast(window.isSecureContext ? 'This browser has no notifications' : 'Notifications need the https:// address');
return false;
}
let p = Notification.permission;
if (p === 'default') p = await Notification.requestPermission();
if (p !== 'granted') toast('Notifications are blocked – allow them in the browser’s site settings');
return p === 'granted';
}
if ('serviceWorker' in navigator && window.isSecureContext) {
navigator.serviceWorker.register('sw.js').then(r => { swReg = r; }).catch(() => {});
navigator.serviceWorker.addEventListener('message', e => {
if (e.data && e.data.cc === 'open' && e.data.conv) openConv(e.data.conv);
});
}
// "install as app": Chrome/Edge/Android offer a prompt, iOS needs Share → Add to Home Screen
let installPrompt = null;
addEventListener('beforeinstallprompt', e => { e.preventDefault(); installPrompt = e; });
const standalone = () => matchMedia('(display-mode: standalone)').matches || navigator.standalone === true;
const ios = /iPhone|iPad|iPod/.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
/* ================================================================ emoji */
const EMOJI = [
@@ -1073,41 +1234,428 @@ input.addEventListener('focus', () => { if (touch && emojiPanel.classList.contai
/* ================================================================ composer */
function updateSend() { sendBtn.disabled = !input.value.trim(); }
input.addEventListener('input', () => { updateSend(); onTyping(); });
input.addEventListener('input', () => { updateSend(); onTyping(); updateMentions(); });
$('bar').addEventListener('submit', e => { e.preventDefault(); sendText(); });
/* ================================================================ name */
function askName(first) {
$('mTitle').textContent = first ? 'Welcome aboard' : 'Change your name';
$('nameForm').querySelector('.primary').textContent = first ? 'Join the chat' : 'Save';
$('nameIn').value = nick;
$('modal').hidden = false;
setTimeout(() => $('nameIn').focus(), 60);
/* ================================================================ mention picker */
let pick = null; // {start, end, ids, sel}
function updateMentions() {
const pos = input.selectionStart ?? input.value.length;
const m = /(?:^|\s)@([^@]{0,24})$/.exec(input.value.slice(0, pos));
if (!m) return hideMentions();
const q = m[1].toLowerCase();
const ids = [...users.keys()].filter(id => {
const n = nickOf(id).toLowerCase();
return id !== me && n !== '?' && (n.startsWith(q) || n.split(/\s+/).some(w => w.startsWith(q)));
}).sort((a, b) => (isOnline(b) - isOnline(a)) || (activity(b) - activity(a))).slice(0, 6);
if (!ids.length) return hideMentions();
pick = { start: pos - m[1].length - 1, end: pos, ids, sel: 0 };
drawMentions();
}
$('nameForm').addEventListener('submit', e => {
e.preventDefault();
const n = clean($('nameIn').value).slice(0, 24);
if (!n) { $('nameIn').focus(); return; }
const first = !nick;
nick = n; store.set('cc.nick', n);
$('me').textContent = n;
$('modal').hidden = true;
$('nameIn').blur();
if (first) loop(); else kick(); // tell everybody the new name
function drawMentions() {
const box = $('mentions');
box.textContent = '';
pick.ids.forEach((id, i) => {
const b = el('button', i === pick.sel ? 'on' : '');
b.type = 'button'; b.dataset.id = id;
b.append(avatar(id), el('span', null, nickOf(id)));
box.appendChild(b);
});
box.hidden = false;
}
function hideMentions() { pick = null; $('mentions').hidden = true; }
function choose(id) {
if (!pick) return;
input.setRangeText('@' + nickOf(id) + ' ', pick.start, pick.end, 'end');
hideMentions(); updateSend(); onTyping(); input.focus();
}
$('mentions').addEventListener('mousedown', e => e.preventDefault());
$('mentions').addEventListener('click', e => { const b = e.target.closest('button'); if (b) choose(b.dataset.id); });
input.addEventListener('keydown', e => {
if (!pick) return;
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
pick.sel = (pick.sel + (e.key === 'ArrowDown' ? 1 : pick.ids.length - 1)) % pick.ids.length;
drawMentions(); e.preventDefault();
} else if (e.key === 'Enter' || e.key === 'Tab') { choose(pick.ids[pick.sel]); e.preventDefault(); }
else if (e.key === 'Escape') { hideMentions(); e.stopPropagation(); }
});
$('modal').addEventListener('click', e => { if (e.target === $('modal') && nick) $('modal').hidden = true; });
$('me').addEventListener('click', () => askName(false));
input.addEventListener('blur', () => setTimeout(hideMentions, 150));
/* ================================================================ login */
const errMsg = e => /wrong password/.test(e.message) ? 'Wrong password'
: /expired|invalid link/.test(e.message) ? 'This link has expired or was already used'
: /fetch|network|load/i.test(e.message) ? 'Can’t reach the chat – are you on the chat WiFi?' : e.message;
const cleanName = s => clean(s).replace(/@/g, '').slice(0, 24);
let checkTimer = 0, nameTaken = null;
function showLogin(msg) {
$('modal').hidden = false;
$('lErr').textContent = msg || '';
setTimeout(() => ($('nameIn').value ? $('pwIn') : $('nameIn')).focus(), 60);
}
function setTaken(t) {
nameTaken = t;
$('lHint').textContent = t === true ? 'Welcome back! Enter the password for this name.'
: t === false ? 'New name: choose a password (at least 4 characters) to keep it yours.'
: 'Pick a name and a password. Use the same name and password to join from your other devices.';
$('lBtn').textContent = t === true ? 'Log in' : t === false ? 'Create account' : 'Join the chat';
$('pwIn').autocomplete = t === false ? 'new-password' : 'current-password';
}
$('nameIn').addEventListener('input', () => {
clearTimeout(checkTimer);
$('lErr').textContent = '';
const n = cleanName($('nameIn').value);
if (!n) return setTaken(null);
checkTimer = setTimeout(() => fetch('cgi-bin/chat?a=check&n=' + toHex(n), { cache: 'no-store' })
.then(r => r.ok ? r.text() : '')
.then(t => { t = t.trim(); if (cleanName($('nameIn').value) === n) setTaken(t === '1' ? true : t === '0' ? false : null); })
.catch(() => {}), 300);
});
$('loginForm').addEventListener('submit', async e => {
e.preventDefault();
const n = cleanName($('nameIn').value), pw = $('pwIn').value;
if (!n) return $('nameIn').focus();
if (!pw) return $('pwIn').focus();
if (nameTaken === false && pw.length < 4) { $('lErr').textContent = 'Please use at least 4 characters'; return; }
$('lBtn').disabled = true;
try {
const ok = /^[0-9a-f]{32}$/.test(oldKey || '') ? '&ok=' + oldKey : '';
const [k, uid] = (await api('login', pw, '&n=' + toHex(n) + ok)).split('\t');
if (!/^[0-9a-f]{32}$/.test(k)) throw new Error('Unexpected answer from the chat');
signedIn(k, uid);
} catch (err) {
$('lErr').textContent = /wrong password/.test(err.message) ? 'Wrong password for this name' : errMsg(err);
}
$('lBtn').disabled = false;
});
function signedIn(k, uid) {
tok = k; me = uid;
store.set('cc.tok', k); store.set('cc.me', uid);
try { localStorage.removeItem('cc.key'); localStorage.removeItem('cc.nick'); } catch (e) {}
$('modal').hidden = true;
$('pwIn').value = '';
if (document.activeElement) document.activeElement.blur();
loop();
setTimeout(offerNotify, 2500);
}
function signedOut() { // forget this device's session and start over
tok = '';
for (const k of ['cc.tok', 'cc.me', 'cc.read', 'cc.conv']) try { localStorage.removeItem(k); } catch (e) {}
location.replace(location.pathname);
}
function offerNotify() { // permission prompts need a tap, so offer one once per device
if (!canNotify() || Notification.permission !== 'default' || store.get('cc.asked')) return;
store.set('cc.asked', '1');
toast('🔔 Tap here to get notifications for new messages', askNotify);
}
// a "link another device" URL: chat/#link=CODE logs this browser in
async function redeemLink() {
const m = /^#link=([0-9a-f]{32})$/.exec(location.hash);
if (!m) return false;
history.replaceState(null, '', location.pathname + location.search);
try {
const [k, uid] = (await api('redeem', undefined, '&c=' + m[1])).split('\t');
if (!/^[0-9a-f]{32}$/.test(k)) throw new Error('Unexpected answer from the chat');
if (uid !== me) for (const x of ['cc.read', 'cc.conv']) try { localStorage.removeItem(x); } catch (e) {}
store.set('cc.tok', k); store.set('cc.me', uid);
location.replace(location.pathname);
return true;
} catch (e) { toast(errMsg(e)); return false; }
}
/* ================================================================ profile */
const SVG = p => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' + p + '</svg>';
const ICONS = {
photo: '<rect x="3" y="5" width="18" height="14" rx="3.5"/><circle cx="12" cy="12" r="3.2"/>',
nophoto: '<rect x="3" y="5" width="18" height="14" rx="3.5"/><path d="M9 9l6 6M15 9l-6 6"/>',
link: '<rect x="7" y="2.5" width="10" height="19" rx="2.5"/><path d="M11 18.5h2"/>',
bell: '<path d="M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z"/><path d="M10 20.5a2.2 2.2 0 0 0 4 0"/>',
install: '<path d="M12 4v11M7.5 10.5L12 15l4.5-4.5"/><path d="M5 19.5h14"/>',
key: '<circle cx="8" cy="15" r="4"/><path d="M11 12l8-8M16 7l2.5 2.5"/>',
out: '<path d="M14 4h4a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-4"/><path d="M10 16l-4-4 4-4M6 12h10"/>',
trash: '<path d="M4 7h16M9 7V4.5h6V7M6.5 7l1 13h9l1-13"/>'
};
const CLOSE = SVG('<path d="M6 6l12 12M18 6L6 18"/>');
let linkTimer = 0;
function sheet(build) {
clearInterval(linkTimer);
const s = $('sheet');
s.textContent = '';
const x = el('button', 'icon xbtn'); x.type = 'button'; x.innerHTML = CLOSE; x.setAttribute('aria-label', 'Close');
x.addEventListener('click', closeSheet);
s.appendChild(x);
build(s);
$('sheetBack').hidden = false;
}
function closeSheet() { clearInterval(linkTimer); $('sheetBack').hidden = true; $('sheet').textContent = ''; }
$('sheetBack').addEventListener('click', e => { if (e.target === $('sheetBack')) closeSheet(); });
function item(icon, label, fn, side, cls) {
const b = el('button', cls);
b.type = 'button';
b.innerHTML = SVG(ICONS[icon]);
b.appendChild(el('span', null, label));
if (side) b.appendChild(el('small', null, side));
b.addEventListener('click', fn);
return b;
}
function notifyLabel() {
if (!canNotify()) return 'not available';
if (Notification.permission === 'denied') return 'blocked';
if (Notification.permission !== 'granted') return 'off';
return { all: 'all messages', direct: 'private & @me', off: 'off' }[notifyPref()];
}
async function cycleNotify() {
if (!canNotify() || Notification.permission !== 'granted') {
if (await askNotify()) store.set('cc.notify', 'all');
} else store.set('cc.notify', { all: 'direct', direct: 'off', off: 'all' }[notifyPref()]);
profile();
}
function profile() {
sheet(s => {
const a = avatar(me);
a.classList.add('big'); a.title = 'Change profile picture';
a.addEventListener('click', () => $('avatarFile').click());
s.append(a, el('h2', null, nickOf(me)));
const list = el('div', 'items'), has = !!avatarUrl(me);
list.appendChild(item('photo', has ? 'Change profile picture' : 'Add a profile picture', () => $('avatarFile').click()));
if (has) list.appendChild(item('nophoto', 'Remove profile picture', setAvatar.bind(null, null)));
list.appendChild(item('link', 'Link another device', linkDevice));
list.appendChild(item('bell', 'Notifications', cycleNotify, notifyLabel()));
if (installPrompt || (ios && !standalone())) list.appendChild(item('install', 'Install as app', install));
list.appendChild(item('key', 'Change password', changePassword));
list.appendChild(item('out', 'Log out on this device', () => api('logout').catch(() => {}).then(signedOut)));
list.appendChild(item('trash', 'Delete account', deleteAccount, null, 'danger'));
s.appendChild(list);
});
}
$('me').addEventListener('click', profile);
async function install() {
if (installPrompt) {
installPrompt.prompt();
try { await installPrompt.userChoice; } catch (e) {}
installPrompt = null;
profile();
} else toast('Tap the Share button, then “Add to Home Screen”');
}
function pwField(ph, ac) {
const i = el('input'); i.type = 'password'; i.placeholder = ph; i.autocomplete = ac; i.maxLength = 100;
return i;
}
function formSheet(title, text, fields, btn, danger, run) {
sheet(s => {
s.appendChild(el('h2', null, title));
if (text) s.appendChild(el('p', null, text));
const f = el('form'), user = el('input'), err = el('div', 'err'), b = el('button', 'primary' + (danger ? ' danger' : ''), btn);
user.autocomplete = 'username'; user.value = nickOf(me); user.hidden = true; // for password managers
const back = el('button', 'ghost', 'Back'); back.type = 'button'; back.addEventListener('click', profile);
f.append(user, ...fields, err, b, back);
f.addEventListener('submit', async e => {
e.preventDefault();
err.textContent = ''; b.disabled = true;
try { await run(err); } catch (x) { err.textContent = errMsg(x); }
b.disabled = false;
});
s.appendChild(f);
setTimeout(() => fields[0].focus(), 60);
});
}
function changePassword() {
const o = pwField('Current password', 'current-password'), n1 = pwField('New password', 'new-password'), n2 = pwField('Repeat the new password', 'new-password');
formSheet('Change password', 'Your other devices stay logged in.', [o, n1, n2], 'Save', false, async err => {
if (n1.value.length < 4) { err.textContent = 'Please use at least 4 characters'; return; }
if (n1.value !== n2.value) { err.textContent = 'The new passwords don’t match'; return; }
await api('passwd', o.value + '\n' + n1.value);
closeSheet(); toast('Password changed');
});
}
function deleteAccount() {
const p = pwField('Your password', 'current-password');
formSheet('Delete account', 'This deletes your account, your profile picture and every message and photo you posted, for everyone, and logs out all your devices. Your name becomes free again.',
[p], 'Delete my account', true, async () => { await api('delete', p.value); signedOut(); });
}
// profile picture: square crop, 256 px JPEG (~20 kB); null removes it
async function setAvatar(file) {
try {
let ver;
if (file) {
const img = await loadImage(file);
const S = 256, w = img.naturalWidth, h = img.naturalHeight, m = Math.min(w, h);
const c = document.createElement('canvas'), ctx = c.getContext('2d');
c.width = c.height = S;
ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, S, S);
ctx.drawImage(img, (w - m) / 2, (h - m) / 2, m, m, 0, 0, S, S);
const blob = await new Promise(r => c.toBlob(r, 'image/jpeg', 0.85));
if (!blob) throw new Error('Could not process the picture');
ver = await api('avatar', blob);
} else ver = await api('noavatar');
const u = users.get(me);
if (u) u.ava = ver;
listSig = ''; refreshUI(); renderConv();
if (!$('sheetBack').hidden) profile();
toast(file ? 'Profile picture updated' : 'Profile picture removed');
} catch (e) { toast(errMsg(e)); }
}
$('avatarFile').addEventListener('change', () => {
const f = $('avatarFile').files[0];
$('avatarFile').value = '';
if (f) setAvatar(f);
});
async function linkDevice() {
let t;
try { t = await api('link'); } catch (e) { toast(errMsg(e)); return; }
const [code, ttl] = t.split('\t');
const url = location.origin + location.pathname + '#link=' + code, until = Date.now() + (+ttl || 600) * 1000;
sheet(s => {
s.append(el('h2', null, 'Link another device'),
el('p', null, 'Scan this code with the other device’s camera or open the link there – it will be logged in as ' + nickOf(me) + '.'));
const q = qrSvg(url);
if (q) { const d = el('div'); d.innerHTML = q; d.firstChild.setAttribute('class', 'qr'); s.appendChild(d.firstChild); }
const copy = el('button', 'ghost', 'Copy link'); copy.type = 'button'; copy.addEventListener('click', () => copyText(url));
const back = el('button', 'ghost', 'Back'); back.type = 'button'; back.addEventListener('click', profile);
const note = el('div', 'note');
s.append(el('div', 'linkbox', url), copy, back, note);
const tick = () => {
const left = Math.max(0, Math.round((until - Date.now()) / 1000));
note.textContent = left ? 'Works once · valid for ' + Math.floor(left / 60) + ':' + String(left % 60).padStart(2, '0') : 'This link has expired.';
if (!left) clearInterval(linkTimer);
};
tick();
linkTimer = setInterval(tick, 1000);
});
}
/* ================================================================ QR code */
// byte mode, error correction level M, versions 1-10 (up to 213 bytes) -> SVG markup
function qrSvg(text) {
const RS = [0, [10, 1, 16], [16, 1, 28], [26, 1, 44], [18, 2, 32], [24, 2, 43], [16, 4, 27], [18, 4, 31],
[22, 2, 38, 2, 39], [22, 3, 36, 2, 37], [26, 4, 43, 1, 44]]; // ec per block, (blocks, data bytes)...
const AL = [0, [], [6, 18], [6, 22], [6, 26], [6, 30], [6, 34], [6, 22, 38], [6, 24, 42], [6, 26, 46], [6, 28, 50]];
const data = enc.encode(text);
let v = 1, cap = 0;
for (; v <= 10; v++) {
const t = RS[v]; cap = t[1] * t[2] + (t[3] || 0) * (t[4] || 0);
if (4 + (v < 10 ? 8 : 16) + data.length * 8 <= cap * 8) break;
}
if (v > 10) return '';
const bits = [], put = (x, n) => { for (let i = n - 1; i >= 0; i--) bits.push(x >>> i & 1); };
put(4, 4); put(data.length, v < 10 ? 8 : 16);
for (const b of data) put(b, 8);
put(0, Math.min(4, cap * 8 - bits.length));
while (bits.length % 8) bits.push(0);
const bytes = [];
for (let i = 0; i < bits.length; i += 8) bytes.push(parseInt(bits.slice(i, i + 8).join(''), 2));
for (let p = 0xec; bytes.length < cap; p ^= 0xec ^ 0x11) bytes.push(p);
// Reed-Solomon over GF(256)
const EXP = [], LOG = [];
for (let i = 0, x = 1; i < 255; i++) { EXP[i] = EXP[i + 255] = x; LOG[x] = i; x <<= 1; if (x & 256) x ^= 0x11d; }
const mul = (a, b) => a && b ? EXP[LOG[a] + LOG[b]] : 0;
const t = RS[v], ecn = t[0];
let g = [1];
for (let i = 0; i < ecn; i++) {
const n = Array(g.length + 1).fill(0);
g.forEach((c, j) => { n[j] ^= c; n[j + 1] ^= mul(c, EXP[i]); });
g = n;
}
const blocks = [], ecs = [];
for (let k = 1, pos = 0; k < t.length; k += 2) for (let b = 0; b < t[k]; b++) {
const blk = bytes.slice(pos, pos += t[k + 1]), r = blk.concat(Array(ecn).fill(0));
for (let i = 0; i < blk.length; i++) { const c = r[i]; if (c) g.forEach((x, j) => { r[i + j] ^= mul(x, c); }); }
blocks.push(blk); ecs.push(r.slice(blk.length));
}
const cw = [];
for (let i = 0; i < t[t.length - 1]; i++) for (const b of blocks) if (i < b.length) cw.push(b[i]);
for (let i = 0; i < ecn; i++) for (const e of ecs) cw.push(e[i]);
// matrix: M[y][x] dark?, F[y][x] function module?
const N = v * 4 + 17, M = [], F = [];
for (let i = 0; i < N; i++) { M.push(Array(N).fill(0)); F.push(Array(N).fill(false)); }
const set = (x, y, d) => { M[y][x] = d ? 1 : 0; F[y][x] = true; };
for (const [fx, fy] of [[3, 3], [N - 4, 3], [3, N - 4]])
for (let dy = -4; dy <= 4; dy++) for (let dx = -4; dx <= 4; dx++) {
const x = fx + dx, y = fy + dy, d = Math.max(Math.abs(dx), Math.abs(dy));
if (x >= 0 && y >= 0 && x < N && y < N) set(x, y, d !== 2 && d !== 4);
}
for (let i = 8; i < N - 8; i++) { set(6, i, i % 2 === 0); set(i, 6, i % 2 === 0); }
const al = AL[v], last = al.length - 1;
al.forEach((ay, i) => al.forEach((ax, j) => {
if ((i === 0 && j === 0) || (i === 0 && j === last) || (i === last && j === 0)) return;
for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) set(ax + dx, ay + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
}));
const format = mask => {
const d = mask; // level M = 00
let r = d; for (let i = 0; i < 10; i++) r = (r << 1) ^ ((r >>> 9) * 0x537);
const b = ((d << 10) | r) ^ 0x5412, bit = i => (b >>> i & 1) === 1;
for (let i = 0; i <= 5; i++) set(8, i, bit(i));
set(8, 7, bit(6)); set(8, 8, bit(7)); set(7, 8, bit(8));
for (let i = 9; i < 15; i++) set(14 - i, 8, bit(i));
for (let i = 0; i < 8; i++) set(N - 1 - i, 8, bit(i));
for (let i = 8; i < 15; i++) set(8, N - 15 + i, bit(i));
set(8, N - 8, true);
};
format(0);
if (v >= 7) {
let r = v; for (let i = 0; i < 12; i++) r = (r << 1) ^ ((r >>> 11) * 0x1f25);
const b = v << 12 | r;
for (let i = 0; i < 18; i++) { const d = b >>> i & 1, a = N - 11 + i % 3, c = Math.floor(i / 3); set(a, c, d); set(c, a, d); }
}
let k = 0;
for (let right = N - 1; right >= 1; right -= 2) {
if (right === 6) right = 5;
for (let vert = 0; vert < N; vert++) for (let j = 0; j < 2; j++) {
const x = right - j, y = ((right + 1) & 2) === 0 ? N - 1 - vert : vert;
if (!F[y][x] && k < cw.length * 8) { M[y][x] = cw[k >>> 3] >>> (7 - (k & 7)) & 1; k++; }
}
}
const MASKS = [(x, y) => (x + y) % 2, (x, y) => y % 2, (x, y) => x % 3, (x, y) => (x + y) % 3,
(x, y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2, (x, y) => x * y % 2 + x * y % 3,
(x, y) => (x * y % 2 + x * y % 3) % 2, (x, y) => ((x + y) % 2 + x * y % 3) % 2];
const flip = m => { for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) if (!F[y][x] && !MASKS[m](x, y)) M[y][x] ^= 1; };
const penalty = () => { // the standard's 4 rules, slightly simplified
let p = 0, dark = 0;
const line = get => {
let run = 1, s = '';
for (let i = 0; i < N; i++) {
const c = get(i); s += c;
if (i && c === get(i - 1)) { run++; if (run === 5) p += 3; else if (run > 5) p++; } else run = 1;
}
for (const pat of ['10111010000', '00001011101']) for (let i = s.indexOf(pat); i >= 0; i = s.indexOf(pat, i + 1)) p += 40;
};
for (let i = 0; i < N; i++) { line(j => M[i][j]); line(j => M[j][i]); }
for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) {
dark += M[y][x];
if (x < N - 1 && y < N - 1) { const c = M[y][x]; if (c === M[y][x + 1] && c === M[y + 1][x] && c === M[y + 1][x + 1]) p += 3; }
}
return p + 10 * Math.floor(Math.abs(dark * 20 - N * N * 10) / (N * N));
};
let best = 0, bestP = Infinity;
for (let m = 0; m < 8; m++) { flip(m); format(m); const p = penalty(); if (p < bestP) { bestP = p; best = m; } flip(m); }
flip(best); format(best);
let path = '';
for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) if (M[y][x]) path += 'M' + (x + 4) + ' ' + (y + 4) + 'h1v1h-1z';
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ' + (N + 8) + ' ' + (N + 8) +
'" shape-rendering="crispEdges"><rect width="100%" height="100%" fill="#fff"/><path d="' + path + '" fill="#000"/></svg>';
}
fetch('VERSION', { cache: 'no-store' }).then(r => r.ok ? r.text() : '')
.then(v => { v = v.trim(); if (/^[\w.\-]{1,20}$/.test(v)) $('ver').textContent = 'Cabin Chat v' + v; }).catch(() => {});
/* ================================================================ start */
conv = store.get('cc.conv') || ALL;
const hc = /^#c=([0-9a-f]{16}|\*)$/.exec(location.hash); // opened from a notification
if (hc) { conv = hc[1]; history.replaceState(null, '', location.pathname + location.search); }
renderConv();
refreshUI();
setInterval(() => { expire(); refreshUI(); }, 1000); // typing / online state expire on their own
setInterval(updateAges, 15000);
if (nick) { $('me').textContent = nick; loop(); } else askName(true);
redeemLink().then(done => { if (done) return; if (tok) loop(); else showLogin(); });
})();
</script>
</body>
+14
View File
@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#3d7bfd"/><stop offset="1" stop-color="#8b5cf6"/></linearGradient>
<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#2f6be6"/><stop offset=".6" stop-color="#6fb3ff"/><stop offset="1" stop-color="#bfe3ff"/></linearGradient>
<clipPath id="win"><rect x="205" y="146" width="102" height="164" rx="51"/></clipPath>
</defs>
<rect width="512" height="512" rx="112" fill="url(#bg)"/>
<path d="M256 92c-99 0-180 68-180 152 0 46 24 87 63 115l-17 67 76-38c18 5 37 8 58 8 99 0 180-68 180-152S355 92 256 92z" fill="#fff"/>
<rect x="191" y="132" width="130" height="192" rx="65" fill="#dde6f8"/>
<rect x="205" y="146" width="102" height="164" rx="51" fill="url(#sky)"/>
<g clip-path="url(#win)" fill="#fff">
<circle cx="226" cy="282" r="22"/><circle cx="256" cy="270" r="28"/><circle cx="290" cy="284" r="22"/><rect x="200" y="284" width="112" height="40"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

+16
View File
@@ -0,0 +1,16 @@
{
"name": "Cabin Chat",
"short_name": "Cabin Chat",
"description": "Group chat on the travel router - no internet needed",
"id": "./",
"start_url": "./",
"scope": "./",
"display": "standalone",
"background_color": "#0e1014",
"theme_color": "#14171d",
"icons": [
{ "src": "icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" },
{ "src": "logo.svg", "sizes": "any", "type": "image/svg+xml" }
]
}
+30
View File
@@ -0,0 +1,30 @@
// Cabin Chat service worker: makes the chat installable as an app, opens the
// app from a notification and shows the last loaded page when the router is out
// of reach. Network first, so a new version on the router is used right away.
// Chat data (cgi-bin) and photos are never cached here.
const CACHE = 'cabinchat';
self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', e => e.waitUntil(self.clients.claim()));
self.addEventListener('fetch', e => {
const req = e.request, url = new URL(req.url);
if (req.method !== 'GET' || url.origin !== location.origin || /\/(cgi-bin|img)\//.test(url.pathname)) return;
e.respondWith(fetch(req).then(res => {
if (res.ok) { const copy = res.clone(); caches.open(CACHE).then(c => c.put(req, copy)); }
return res;
}).catch(() => caches.match(req, { ignoreSearch: true })
.then(r => r || (req.mode === 'navigate' ? caches.match('./') : Response.error()))));
});
self.addEventListener('notificationclick', e => {
e.notification.close();
const conv = (e.notification.data || {}).conv || '';
e.waitUntil(self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(list => {
for (const c of list) {
c.postMessage({ cc: 'open', conv });
return c.focus();
}
return self.clients.openWindow('./' + (conv ? '#c=' + conv : ''));
}));
});