feat: add account avatars and a deployable image

Accounts get a profile page with an uploaded picture, shown in the
sidebar, the room bar, and every human message. Pictures live in the
SQLite database and are served through an authenticated route.

Hardening from the security audit: preview hosts expire after 24 hours
and carry no-referrer; removing a member or archiving a room ends their
event feed, presence socket, and terminal within seconds; previews and
the terminal pin the SSH host key; invites are claimed atomically;
missing accounts spend the same argon2 time as wrong passwords;
registration is closed by default; WebSockets check the origin; and the
master key is created with mode 0600.

The Dockerfile builds one image with the static client and the server.
The Helm chart runs a single replica with a SQLite volume, a wildcard
preview ingress, and the proxy settings the event feed and uploads
need. It refuses more than one replica because state is in process.
This commit is contained in:
vhaudiquet committed 2026-11-28 02:07:26 +01:00
1 parent 7e7a1d2bb6
commit 3b82719d56
38 files changed
+1283 -82

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
.git
.rhema
.github
deploy
specs
target
data
web/.nuxt
web/.output
web/node_modules
web/.data
*.db
*.db-shm
*.db-wal
*.key
+46
View File
@@ -0,0 +1,46 @@
# syntax=docker/dockerfile:1
# The client is static; Nuxt generate leaves .output/public.
FROM node:22-bookworm-slim AS web
WORKDIR /app/web
RUN npm install --global pnpm@11.22.0
COPY web/package.json web/pnpm-lock.yaml web/pnpm-workspace.yaml ./
RUN pnpm install --frozen-lockfile
COPY web/ ./
RUN pnpm build
# The server consumes the Rhema crates. The clone is pinned so an image
# does not move when the framework's main branch does.
FROM rust:1.98.1-bookworm AS server
ARG RHEMA_REPOSITORY=https://github.com/vhaudiquet/rhema.git
ARG RHEMA_REF=v0.5.1
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates cmake git pkg-config \
&& rm -rf /var/lib/apt/lists/*
RUN git clone --depth 1 --branch "${RHEMA_REF}" "${RHEMA_REPOSITORY}" /rhema
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
RUN sed -i 's#path = "../rhema/#path = "/rhema/#g' Cargo.toml
COPY src ./src
RUN cargo build --release
FROM debian:bookworm-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates \
&& rm -rf /var/lib/apt/lists/* \
&& groupadd --gid 10001 together \
&& useradd --uid 10001 --gid 10001 --home-dir /data --shell /usr/sbin/nologin --no-create-home together \
&& install -d -o together -g together /data
WORKDIR /app
COPY --from=server /app/target/release/rhema-together /app/rhema-together
COPY --from=web /app/web/.output/public /app/web
ENV TOGETHER_LISTEN=0.0.0.0:7800 \
TOGETHER_DATABASE=/data/together.db \
TOGETHER_SECRET_KEY_FILE=/data/secret.key \
TOGETHER_WEB_DIR=/app/web \
HOME=/data \
RUST_LOG=rhema_together=info,tower_http=warn
USER 10001:10001
VOLUME ["/data"]
EXPOSE 7800
ENTRYPOINT ["/app/rhema-together"]
+46 -8
View File
@@ -35,7 +35,7 @@ one SQLite file.
## Build ## Build
Requirements: Rust 1.89+, Node 22+, pnpm, and an SSH server reachable Requirements: Rust 1.98+, Node 22+, pnpm, and an SSH server reachable
from the machine that runs rhema-together. from the machine that runs rhema-together.
```sh ```sh
@@ -70,6 +70,30 @@ During client development, run `pnpm dev` in `web/` (port 3000) and
keep the server on port 7800; the Nuxt dev proxy forwards `/api`, keep the server on port 7800; the Nuxt dev proxy forwards `/api`,
including the terminal WebSocket. including the terminal WebSocket.
## Deploy
The repository builds a self-contained image. The Dockerfile clones the
Rhema framework at the tag it names, builds the client and server, and
runs the result as UID 10001 with a writable `/data` volume.
```sh
docker build -t registry.example.com/rhema-together:0.1.0 .
docker run --rm -p 7800:7800 -v together-data:/data \
-e TOGETHER_PUBLIC_URL=https://together.example.com \
-e TOGETHER_ALLOW_REGISTRATION=false \
-e TOGETHER_PREVIEW_ORIGIN=https://preview.together.example.com \
registry.example.com/rhema-together:0.1.0
```
For Kubernetes, the chart in `deploy/helm/rhema-together` adds the
deployment, service, ingress, and persistent volume. It also documents
the wildcard DNS, wildcard TLS certificate, proxy buffering, and body
size the app needs. Read that README before exposing the service.
The preview host is a signed subdomain, so the ingress must route all
of `*.preview.<your-domain>` to the same service. The app does not
issue certificates.
## First room ## First room
1. **Settings → Providers.** Add a provider kind, model, and key. Keys 1. **Settings → Providers.** Add a provider kind, model, and key. Keys
@@ -104,12 +128,14 @@ https://preview.together.example.com production
``` ```
Each preview is served from Each preview is served from
`<scheme>://r<room>-p<port>-<hmac>.<preview host>/`. The HMAC covers the `<scheme>://r<room>-p<port>-<expiry>-<hmac>.<preview host>/`. The HMAC
room and port and is derived from the server's master key, so a room id covers the room, port, and expiry and is derived from the server's
alone is not enough to reach a preview. DNS must resolve every subdomain master key, so a room id alone is not enough to reach a preview. The
of the preview host to the server (a wildcard `*.preview` record), and address expires after 24 hours; reloading the pane mints a new one. DNS
TLS must cover the wildcard. A copied preview URL works for anyone who must resolve every subdomain of the preview host to the server (a
has it; treat it as a read capability for that port. wildcard `*.preview` record), and TLS must cover the wildcard. A copied
preview URL works for anyone who has it until it expires; treat it as a
read capability for that port.
The proxy forwards ordinary HTTP through an ssh `direct-tcpip` channel The proxy forwards ordinary HTTP through an ssh `direct-tcpip` channel
to `127.0.0.1:<port>` inside the sandbox. WebSocket upgrades (Vite HMR) to `127.0.0.1:<port>` inside the sandbox. WebSocket upgrades (Vite HMR)
@@ -147,7 +173,7 @@ Every field can be set in the YAML file (`TOGETHER_CONFIG`, default
| `TOGETHER_SECRET_KEY_FILE` | `data/secret.key` | 32-byte master key (created, mode 0600) | | `TOGETHER_SECRET_KEY_FILE` | `data/secret.key` | 32-byte master key (created, mode 0600) |
| `TOGETHER_WEB_DIR` | `web/.output/public` | built client | | `TOGETHER_WEB_DIR` | `web/.output/public` | built client |
| `TOGETHER_MAX_TURN_STEPS` | `48` | step cap per turn | | `TOGETHER_MAX_TURN_STEPS` | `48` | step cap per turn |
| `TOGETHER_ALLOW_REGISTRATION` | `true` | whether `/register` works | | `TOGETHER_ALLOW_REGISTRATION` | `false` | whether `/register` works |
## Security model ## Security model
@@ -159,6 +185,18 @@ Every field can be set in the YAML file (`TOGETHER_CONFIG`, default
mutating calls. mutating calls.
- Guests can chat, interrupt, use the terminal, and read files. Only - Guests can chat, interrupt, use the terminal, and read files. Only
full accounts create rooms, providers, and targets. full accounts create rooms, providers, and targets.
- Registration is closed by default; setup and invite links work
without it. A full account can make the server open an SSH connection
to a host it names, so open signup also makes the server reachable
from anywhere as a port scanner. Turn it on only when you trust
everyone who can reach `/register`.
- A preview host is a signed capability for one room and port. It
expires after 24 hours, and preview responses carry
`Referrer-Policy: no-referrer`. A copied URL works until it expires.
- Removing a member or archiving a room ends that account's event feed,
presence socket, and terminal within a few seconds. The terminal and
preview proxy pin the SSH host key on first login and refuse a
changed key.
- Preview URLs are signed capabilities, not authenticated pages. - Preview URLs are signed capabilities, not authenticated pages.
- The app sets a CSP that frames only `*.<preview host>`, and refuses - The app sets a CSP that frames only `*.<preview host>`, and refuses
to frame itself elsewhere. to frame itself elsewhere.
+11
View File
@@ -0,0 +1,11 @@
apiVersion: v2
name: rhema-together
description: A shared room where people and a Rhema agent work on the same code.
type: application
version: 0.1.0
appVersion: "0.1.0"
home: https://git.vhaudiquet.fr/vhaudiquet/rhema-together
sources:
- https://git.vhaudiquet.fr/vhaudiquet/rhema-together
maintainers:
- name: Valentin Haudiquet
+112
View File
@@ -0,0 +1,112 @@
# Rhema Together Helm chart
This chart runs one rhema-together pod with a persistent volume for the
SQLite database and the master key. The pod serves the API, the built
client, the terminal WebSocket, the event stream, and the preview proxy.
## Build the image
```sh
docker build -t registry.example.com/rhema-together:0.1.0 .
docker push registry.example.com/rhema-together:0.1.0
```
The Dockerfile clones the Rhema framework at `v0.5.1` because this
repository consumes its crates by path. Override the pin with
`--build-arg RHEMA_REF=<tag>` if you move the framework.
## Values
Copy `values.yaml` and change at least these fields:
```yaml
image:
repository: registry.example.com/rhema-together
tag: "0.1.0"
app:
publicUrl: "https://together.example.com"
previewOrigin: "https://preview.together.example.com"
allowRegistration: false
ingress:
enabled: true
className: nginx
annotations:
nginx.ingress.kubernetes.io/proxy-body-size: "4m"
nginx.ingress.kubernetes.io/proxy-buffering: "off"
nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"
hosts:
- host: together.example.com
paths:
- path: /
pathType: Prefix
- host: "*.preview.together.example.com"
paths:
- path: /
pathType: Prefix
tls:
- secretName: rhema-together-tls
hosts:
- together.example.com
- "*.preview.together.example.com"
```
`publicUrl` and `previewOrigin` must match the hosts and scheme in the
ingress. Cookies use `Secure` only when `publicUrl` starts with
`https://`; if the browser reaches the app on a different origin, login
fails or invite links point elsewhere.
The preview host is a wildcard because each preview gets a signed
subdomain. Point `*.preview.example.com` at the ingress and issue a
certificate for that wildcard. With cert-manager, that requires a
DNS-01 solver for the zone; an HTTP-01 solver cannot issue wildcards.
The nginx annotations are not cosmetic. The event feed is server-sent
events, so proxy buffering must be off. Avatar uploads are up to 2 MB,
so the body size must exceed nginx's 1 MB default. The terminal and
preview tunnels use WebSockets and long-lived connections, hence the
timeouts.
## Install
```sh
helm upgrade --install together deploy/helm/rhema-together \
--namespace together --create-namespace \
-f my-values.yaml
```
The first-run setup token is in the pod log:
```sh
kubectl logs deploy/together-rhema-together -n together | grep setup
```
Open the app, finish setup, add a provider and an SSH sandbox under
Settings, then create a room.
## Operational notes
- Run one replica. The database is SQLite and preview tunnels and turn
state live in the process. The chart refuses a higher `replicaCount`.
- The chart uses `Recreate`, so an upgrade stops the old pod before the
new one starts. A rolling update would put two writers on one SQLite
file.
- The data volume holds `together.db`, its WAL files, and `secret.key`.
Losing `secret.key` makes the stored provider and SSH keys unreadable.
Back up the volume, or snapshot the PVC, as one unit.
- Registration is closed by default. Set `app.allowRegistration: true`
only when any visitor should be able to make an account. Setup and
invite links work with it closed.
- A real account can add an SSH target, and the server then connects
where that account says. Keep registration closed unless you trust
everyone who can reach the signup page.
- Preview hosts are signed capabilities that expire after 24 hours.
Reloading the room mints a fresh address; a copied address works for
that port until it expires.
- The container runs as UID 10001 with a read-only root filesystem.
`/data` and `/tmp` are writable. An existing PVC must be writable by
GID 10001; the chart sets `fsGroup` for that.
- Set `app.previewOrigin: ""` to disable previews. The ingress wildcard
can then be removed.
@@ -0,0 +1,22 @@
Rhema Together is installed.
{{- if .Values.ingress.enabled }}
Open {{ .Values.app.publicUrl }}.
{{- else }}
Port-forward the service:
kubectl port-forward svc/{{ include "rhema-together.fullname" . }} 7800:{{ .Values.service.port }} -n {{ .Release.Namespace }}
Then open http://localhost:7800. Set app.publicUrl to that same origin before inviting anyone.
{{- end }}
The first-run setup token is printed by the server:
kubectl logs deploy/{{ include "rhema-together.fullname" . }} -n {{ .Release.Namespace }} | grep setup
{{- if .Values.app.previewOrigin }}
Previews use {{ .Values.app.previewOrigin }}. Every preview host under that origin must resolve to this ingress, and the TLS certificate must cover the wildcard host.
{{- else }}
Previews are disabled.
{{- end }}
{{- if not .Values.persistence.enabled }}
Persistence is disabled. Accounts, rooms, and keys disappear when the pod is replaced.
{{- end }}
@@ -0,0 +1,36 @@
{{- define "rhema-together.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- define "rhema-together.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}
{{- define "rhema-together.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- define "rhema-together.labels" -}}
helm.sh/chart: {{ include "rhema-together.chart" . }}
{{ include "rhema-together.selectorLabels" . }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
{{- define "rhema-together.selectorLabels" -}}
app.kubernetes.io/name: {{ include "rhema-together.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{- define "rhema-together.image" -}}
{{- printf "%s:%s" .Values.image.repository (default .Chart.AppVersion .Values.image.tag) }}
{{- end }}
@@ -0,0 +1,111 @@
{{- if ne (int .Values.replicaCount) 1 }}
{{- fail "replicaCount must be 1: state lives in one SQLite file and in-process tunnels" }}
{{- end }}
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "rhema-together.fullname" . }}
labels:
{{- include "rhema-together.labels" . | nindent 4 }}
spec:
replicas: {{ .Values.replicaCount }}
strategy:
type: Recreate
selector:
matchLabels:
{{- include "rhema-together.selectorLabels" . | nindent 6 }}
template:
metadata:
labels:
{{- include "rhema-together.selectorLabels" . | nindent 8 }}
{{- with .Values.podLabels }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.podAnnotations }}
annotations:
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
{{- with .Values.image.pullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
securityContext:
{{- toYaml .Values.podSecurityContext | nindent 8 }}
containers:
- name: rhema-together
image: {{ include "rhema-together.image" . | quote }}
imagePullPolicy: {{ .Values.image.pullPolicy }}
securityContext:
{{- toYaml .Values.securityContext | nindent 12 }}
ports:
- name: http
containerPort: 7800
protocol: TCP
env:
- name: TOGETHER_LISTEN
value: "0.0.0.0:7800"
- name: TOGETHER_PUBLIC_URL
value: {{ required "set app.publicUrl" .Values.app.publicUrl | quote }}
- name: TOGETHER_PREVIEW_ORIGIN
value: {{ .Values.app.previewOrigin | quote }}
- name: TOGETHER_DATABASE
value: /data/together.db
- name: TOGETHER_SECRET_KEY_FILE
value: /data/secret.key
- name: TOGETHER_WEB_DIR
value: /app/web
- name: TOGETHER_ALLOW_REGISTRATION
value: {{ .Values.app.allowRegistration | quote }}
- name: TOGETHER_MAX_TURN_STEPS
value: {{ .Values.app.maxTurnSteps | quote }}
- name: RUST_LOG
value: {{ .Values.app.logLevel | quote }}
{{- with .Values.app.extraEnv }}
{{- toYaml . | nindent 12 }}
{{- end }}
volumeMounts:
- name: data
mountPath: /data
- name: tmp
mountPath: /tmp
readinessProbe:
httpGet:
path: /api/bootstrap
port: http
initialDelaySeconds: 3
periodSeconds: 10
timeoutSeconds: 3
failureThreshold: 3
livenessProbe:
httpGet:
path: /api/bootstrap
port: http
initialDelaySeconds: 15
periodSeconds: 20
timeoutSeconds: 3
failureThreshold: 3
resources:
{{- toYaml .Values.resources | nindent 12 }}
volumes:
- name: data
{{- if .Values.persistence.enabled }}
persistentVolumeClaim:
claimName: {{ .Values.persistence.existingClaim | default (printf "%s-data" (include "rhema-together.fullname" .)) }}
{{- else }}
emptyDir: {}
{{- end }}
- name: tmp
emptyDir: {}
{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
@@ -0,0 +1,35 @@
{{- if .Values.ingress.enabled }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: {{ include "rhema-together.fullname" . }}
labels:
{{- include "rhema-together.labels" . | nindent 4 }}
{{- with .Values.ingress.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- with .Values.ingress.className }}
ingressClassName: {{ . }}
{{- end }}
{{- with .Values.ingress.tls }}
tls:
{{- toYaml . | nindent 4 }}
{{- end }}
rules:
{{- range .Values.ingress.hosts }}
- host: {{ .host | quote }}
http:
paths:
{{- range .paths }}
- path: {{ .path }}
pathType: {{ .pathType }}
backend:
service:
name: {{ include "rhema-together.fullname" $ }}
port:
name: http
{{- end }}
{{- end }}
{{- end }}
@@ -0,0 +1,17 @@
{{- if and .Values.persistence.enabled (not .Values.persistence.existingClaim) }}
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: {{ include "rhema-together.fullname" . }}-data
labels:
{{- include "rhema-together.labels" . | nindent 4 }}
spec:
accessModes:
- {{ .Values.persistence.accessMode | quote }}
resources:
requests:
storage: {{ .Values.persistence.size | quote }}
{{- with .Values.persistence.storageClass }}
storageClassName: {{ . | quote }}
{{- end }}
{{- end }}
@@ -0,0 +1,15 @@
apiVersion: v1
kind: Service
metadata:
name: {{ include "rhema-together.fullname" . }}
labels:
{{- include "rhema-together.labels" . | nindent 4 }}
spec:
type: {{ .Values.service.type }}
ports:
- name: http
port: {{ .Values.service.port }}
targetPort: http
protocol: TCP
selector:
{{- include "rhema-together.selectorLabels" . | nindent 4 }}
+76
View File
@@ -0,0 +1,76 @@
replicaCount: 1
image:
repository: git.vhaudiquet.fr/vhaudiquet/rhema-together
# Defaults to Chart.AppVersion.
tag: ""
pullPolicy: IfNotPresent
pullSecrets: []
nameOverride: ""
fullnameOverride: ""
app:
# The browser URL. Invite links and cookies use this exact origin.
publicUrl: "https://together.example.com"
# Previews are served from this origin. Set it to "" to disable them.
previewOrigin: "https://preview.together.example.com"
# Closed by default: the setup account and invite links are enough.
# Open it only when any visitor should be able to make an account.
allowRegistration: false
maxTurnSteps: 48
logLevel: "rhema_together=info,tower_http=warn"
extraEnv: []
service:
type: ClusterIP
port: 7800
ingress:
enabled: false
className: ""
annotations: {}
hosts:
- host: together.example.com
paths:
- path: /
pathType: Prefix
- host: "*.preview.together.example.com"
paths:
- path: /
pathType: Prefix
tls: []
# - secretName: rhema-together-tls
# hosts:
# - together.example.com
# - "*.preview.together.example.com"
persistence:
enabled: true
existingClaim: ""
storageClass: ""
accessMode: ReadWriteOnce
size: 5Gi
podAnnotations: {}
podLabels: {}
podSecurityContext:
fsGroup: 10001
fsGroupChangePolicy: OnRootMismatch
securityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
resources: {}
nodeSelector: {}
tolerations: []
affinity: {}
+12 -9
View File
@@ -341,13 +341,14 @@ Layout, one wildcard record:
``` ```
app https://together.<domain>/room/<id>/ app https://together.<domain>/room/<id>/
preview https://r<room>-p<port>-<sig>.preview.<domain>/ preview https://r<room>-p<port>-<expiry>-<sig>.preview.<domain>/
``` ```
The room, port, and a 24-hex HMAC signature form the first label. The The room, port, expiry, and a 24-hex HMAC signature form the first
signature is minted by the app when the pane opens and checked by the label. The signature is minted by the app when the pane opens and
proxy, so the URL is not guessable from a room id. It does not expire; checked by the proxy, so the URL is not guessable from a room id. It
treat a copied preview URL as a room read capability. expires after 24 hours, and loading the room mints a fresh one. Treat a
copied preview URL as a read capability for that port until it expires.
The preview needs its own hostname. It is repo code, and on the app's The preview needs its own hostname. It is repo code, and on the app's
origin it could call the API with the viewer's cookie, which turns every origin it could call the API with the viewer's cookie, which turns every
@@ -364,8 +365,9 @@ rewriting. Vite's HMR WebSocket is not proxied in v1; reload with the
button after an edit, or disable HMR in the previewed server. button after an edit, or disable HMR in the previewed server.
Auth: the preview host carries no app cookie, and the signed label is Auth: the preview host carries no app cookie, and the signed label is
the whole capability. Responses are not framed by policy on the preview the whole capability. Preview responses carry `Referrer-Policy:
side; the app's CSP names `*.<preview host>` in `frame-src`. no-referrer` so the signed host does not leak to third-party resources.
The app's CSP names `*.<preview host>` in `frame-src`.
Refresh: a button and a reload when a turn ends. Refresh: a button and a reload when a turn ends.
@@ -623,8 +625,9 @@ Settled:
2. Provider and model: the room owner picks both, and only the owner 2. Provider and model: the room owner picks both, and only the owner
changes them. Every turn spends from that config. changes them. Every turn spends from that config.
3. Interrupts: any member. v1 has no rate limit. 3. Interrupts: any member. v1 has no rate limit.
4. Preview auth: a per-room, per-port signed host label with no expiry. 4. Preview auth: a per-room, per-port signed host label with a 24-hour
A copied preview URL is a read capability for that port. expiry. A copied preview URL is a read capability for that port until
it expires.
5. Terminal sharing: private shells, one per browser connection. The 5. Terminal sharing: private shells, one per browser connection. The
room log does not record terminal contents. room log does not record terminal contents.
+20 -3
View File
@@ -8,7 +8,8 @@ use serde::Deserialize;
use serde_json::{Value, json}; use serde_json::{Value, json};
use crate::auth::{ use crate::auth::{
self, AuthUser, clean_display_name, hash_password, valid_handle, verify_password, self, AuthUser, clean_display_name, dummy_password_hash, hash_password, valid_handle,
verify_password,
}; };
use crate::error::{AppError, AppResult}; use crate::error::{AppError, AppResult};
use crate::models::User; use crate::models::User;
@@ -109,6 +110,7 @@ pub async fn setup(
handle, handle,
display_name, display_name,
kind: "user".into(), kind: "user".into(),
avatar_updated_at: None,
}), }),
)) ))
} }
@@ -176,6 +178,7 @@ pub async fn register(
handle, handle,
display_name, display_name,
kind: "user".into(), kind: "user".into(),
avatar_updated_at: None,
}), }),
)) ))
} }
@@ -196,7 +199,9 @@ pub async fn login(
.db .db
.conn() .conn()
.query_row( .query_row(
"SELECT id, handle, display_name, kind, password_hash FROM accounts "SELECT id, handle, display_name, kind, password_hash,
(SELECT updated_at FROM avatars WHERE account_id = accounts.id)
FROM accounts
WHERE handle = ?1 OR (email IS NOT NULL AND email = ?1) WHERE handle = ?1 OR (email IS NOT NULL AND email = ?1)
LIMIT 1", LIMIT 1",
rusqlite::params![identifier], rusqlite::params![identifier],
@@ -207,11 +212,22 @@ pub async fn login(
row.get::<_, String>(2)?, row.get::<_, String>(2)?,
row.get::<_, String>(3)?, row.get::<_, String>(3)?,
row.get::<_, Option<String>>(4)?, row.get::<_, Option<String>>(4)?,
row.get::<_, Option<i64>>(5)?,
)) ))
}, },
) )
.ok(); .ok();
let Some((id, handle, display_name, kind, Some(password_hash))) = row else { let (id, handle, display_name, kind, password_hash, avatar_updated_at) = match row {
Some(row) => row,
None => {
// Spend the same argon2 work as a real check so the response
// time does not reveal whether the handle exists.
let _ = verify_password(dummy_password_hash(), &body.password);
return Err(AppError::unauthorized("wrong handle or password"));
}
};
let Some(password_hash) = password_hash else {
let _ = verify_password(dummy_password_hash(), &body.password);
return Err(AppError::unauthorized("wrong handle or password")); return Err(AppError::unauthorized("wrong handle or password"));
}; };
if !verify_password(&password_hash, &body.password) { if !verify_password(&password_hash, &body.password) {
@@ -227,6 +243,7 @@ pub async fn login(
handle, handle,
display_name, display_name,
kind, kind,
avatar_updated_at,
}), }),
)) ))
} }
+9 -1
View File
@@ -6,6 +6,7 @@ use std::time::Duration;
use axum::Json; use axum::Json;
use axum::extract::ws::WebSocketUpgrade; use axum::extract::ws::WebSocketUpgrade;
use axum::extract::{Path, Query, State}; use axum::extract::{Path, Query, State};
use axum::http::HeaderMap;
use axum::response::Response; use axum::response::Response;
use rhema_sandbox::Sandbox; use rhema_sandbox::Sandbox;
use rhema_sandbox::exec_util::shquote; use rhema_sandbox::exec_util::shquote;
@@ -233,9 +234,16 @@ pub async fn terminal(
user: AuthUser, user: AuthUser,
State(state): State<Shared>, State(state): State<Shared>,
Path(room): Path<String>, Path(room): Path<String>,
headers: HeaderMap,
ws: WebSocketUpgrade, ws: WebSocketUpgrade,
) -> AppResult<Response> { ) -> AppResult<Response> {
if !super::websocket_origin_ok(&state.config, &headers) {
return Err(AppError::forbidden("websocket origin does not match"));
}
member_of(&state, &room, &user.user.id)?; member_of(&state, &room, &user.user.id)?;
let (workspace, target) = room_workspace(&state, &room)?; let (workspace, target) = room_workspace(&state, &room)?;
Ok(ws.on_upgrade(move |socket| crate::ssh::terminal(socket, state, workspace, target))) let account = user.user.id.clone();
Ok(ws.on_upgrade(move |socket| {
crate::ssh::terminal(socket, state, room, account, workspace, target)
}))
} }
+49 -4
View File
@@ -7,6 +7,7 @@ use std::time::Duration;
use axum::Json; use axum::Json;
use axum::extract::ws::{Message as WsMessage, WebSocket, WebSocketUpgrade}; use axum::extract::ws::{Message as WsMessage, WebSocket, WebSocketUpgrade};
use axum::extract::{Path, Query, State}; use axum::extract::{Path, Query, State};
use axum::http::HeaderMap;
use axum::response::Response; use axum::response::Response;
use axum::response::sse::{Event as SseEvent, KeepAlive, KeepAliveStream, Sse}; use axum::response::sse::{Event as SseEvent, KeepAlive, KeepAliveStream, Sse};
use futures::{SinkExt, Stream, StreamExt}; use futures::{SinkExt, Stream, StreamExt};
@@ -130,7 +131,15 @@ pub async fn events(
Query(query): Query<Since>, Query(query): Query<Since>,
) -> AppResult<Sse<KeepAliveStream<EventStream>>> { ) -> AppResult<Sse<KeepAliveStream<EventStream>>> {
member_of(&state, &room, &user.user.id)?; member_of(&state, &room, &user.user.id)?;
let since = query.since.unwrap_or(0) as i64; let requested = query.since.unwrap_or(0).min(i64::MAX as u64) as i64;
let max_seq: i64 = state.db.scalar(
"SELECT COALESCE(MAX(seq), 0) FROM events WHERE room_id = ?1",
rusqlite::params![room],
)?;
// A client asking for a future sequence must not skip everything
// that arrives after it.
let since = requested.min(max_seq);
let user_id = user.user.id.clone();
// Subscribe before reading the backlog: an event that lands between // Subscribe before reading the backlog: an event that lands between
// the two is then either in the backlog or on the feed, never lost. // the two is then either in the backlog or on the feed, never lost.
let mut rx = state.hub.subscribe(&state.db, &room); let mut rx = state.hub.subscribe(&state.db, &room);
@@ -161,9 +170,20 @@ pub async fn events(
let data = serde_json::to_string(&envelope).unwrap_or_else(|_| "{}".into()); let data = serde_json::to_string(&envelope).unwrap_or_else(|_| "{}".into());
yield Ok(SseEvent::default().id(envelope.seq.to_string()).data(data)); yield Ok(SseEvent::default().id(envelope.seq.to_string()).data(data));
} }
let mut access = tokio::time::interval(Duration::from_secs(2));
loop { loop {
match rx.recv().await { tokio::select! {
_ = access.tick() => {
if member_of(&state, &room, &user_id).is_err() {
break;
}
}
message = rx.recv() => {
match message {
Ok(envelope) => { Ok(envelope) => {
if member_of(&state, &room, &user_id).is_err() {
break;
}
if envelope.seq <= last { if envelope.seq <= last {
continue; continue;
} }
@@ -172,12 +192,17 @@ pub async fn events(
yield Ok(SseEvent::default().id(envelope.seq.to_string()).data(data)); yield Ok(SseEvent::default().id(envelope.seq.to_string()).data(data));
} }
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => { Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
if member_of(&state, &room, &user_id).is_err() {
break;
}
let data = json!({ "seq": last, "kind": "lag", "data": {} }).to_string(); let data = json!({ "seq": last, "kind": "lag", "data": {} }).to_string();
yield Ok(SseEvent::default().event("lag").data(data)); yield Ok(SseEvent::default().event("lag").data(data));
} }
Err(tokio::sync::broadcast::error::RecvError::Closed) => break, Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
} }
} }
}
}
}; };
let stream: EventStream = Box::pin(stream); let stream: EventStream = Box::pin(stream);
Ok(Sse::new(stream).keep_alive( Ok(Sse::new(stream).keep_alive(
@@ -192,13 +217,24 @@ pub async fn presence(
user: AuthUser, user: AuthUser,
State(state): State<Shared>, State(state): State<Shared>,
Path(room): Path<String>, Path(room): Path<String>,
headers: HeaderMap,
ws: WebSocketUpgrade, ws: WebSocketUpgrade,
) -> AppResult<Response> { ) -> AppResult<Response> {
if !super::websocket_origin_ok(&state.config, &headers) {
return Err(AppError::forbidden("websocket origin does not match"));
}
let member = member_of(&state, &room, &user.user.id)?; let member = member_of(&state, &room, &user.user.id)?;
Ok(ws.on_upgrade(move |socket| presence_loop(socket, state, room, member))) let account = user.user.id.clone();
Ok(ws.on_upgrade(move |socket| presence_loop(socket, state, room, account, member)))
} }
async fn presence_loop(socket: WebSocket, state: Shared, room: String, member: Membership) { async fn presence_loop(
socket: WebSocket,
state: Shared,
room: String,
account: String,
member: Membership,
) {
let (mut sink, mut source) = socket.split(); let (mut sink, mut source) = socket.split();
let peer = Peer { let peer = Peer {
member_id: member.id.clone(), member_id: member.id.clone(),
@@ -209,8 +245,14 @@ async fn presence_loop(socket: WebSocket, state: Shared, room: String, member: M
let (id, snapshot, mut updates) = state.presence.join(&room, peer); let (id, snapshot, mut updates) = state.presence.join(&room, peer);
let _ = send_presence(&mut sink, &snapshot).await; let _ = send_presence(&mut sink, &snapshot).await;
let mut ping = tokio::time::interval(Duration::from_secs(25)); let mut ping = tokio::time::interval(Duration::from_secs(25));
let mut access = tokio::time::interval(Duration::from_secs(2));
loop { loop {
tokio::select! { tokio::select! {
_ = access.tick() => {
if member_of(&state, &room, &account).is_err() {
break;
}
}
message = source.next() => { message = source.next() => {
match message { match message {
Some(Ok(WsMessage::Text(text))) => { Some(Ok(WsMessage::Text(text))) => {
@@ -230,6 +272,9 @@ async fn presence_loop(socket: WebSocket, state: Shared, room: String, member: M
} }
} }
_ = ping.tick() => { _ = ping.tick() => {
if member_of(&state, &room, &account).is_err() {
break;
}
if sink.send(WsMessage::Ping(Vec::new().into())).await.is_err() { if sink.send(WsMessage::Ping(Vec::new().into())).await.is_err() {
break; break;
} }
+37 -2
View File
@@ -4,13 +4,14 @@
pub mod auth; pub mod auth;
pub mod files; pub mod files;
pub mod messages; pub mod messages;
pub mod profile;
pub mod rooms; pub mod rooms;
pub mod settings; pub mod settings;
use axum::Router; use axum::Router;
use axum::body::Body; use axum::body::Body;
use axum::extract::{Request, State}; use axum::extract::{DefaultBodyLimit, Request, State};
use axum::http::{HeaderValue, StatusCode, Uri, header}; use axum::http::{HeaderMap, HeaderValue, StatusCode, Uri, header};
use axum::middleware::{self, Next}; use axum::middleware::{self, Next};
use axum::response::{Html, IntoResponse, Response}; use axum::response::{Html, IntoResponse, Response};
use axum::routing::{delete, get, post}; use axum::routing::{delete, get, post};
@@ -28,6 +29,13 @@ pub fn router(state: Shared) -> Router {
.route("/register", post(auth::register)) .route("/register", post(auth::register))
.route("/login", post(auth::login)) .route("/login", post(auth::login))
.route("/logout", post(auth::logout)) .route("/logout", post(auth::logout))
.route(
"/profile/avatar",
post(profile::upload_avatar)
.delete(profile::delete_avatar)
.layer(DefaultBodyLimit::max(profile::MAX_AVATAR_BYTES + 64 * 1024)),
)
.route("/avatars/{account}", get(profile::get_avatar))
.route( .route(
"/provider-configs", "/provider-configs",
get(settings::list_providers).post(settings::create_provider), get(settings::list_providers).post(settings::create_provider),
@@ -72,6 +80,27 @@ pub fn router(state: Shared) -> Router {
.with_state(state) .with_state(state)
} }
/// Whether a browser WebSocket handshake came from the app's origin.
/// A client that sends no `Origin` is not a browser page and is left to
/// the cookie check.
pub(crate) fn websocket_origin_ok(config: &crate::config::Config, headers: &HeaderMap) -> bool {
let Some(origin) = headers
.get(header::ORIGIN)
.and_then(|value| value.to_str().ok())
else {
return true;
};
let origin = origin.trim_end_matches('/');
let public = config.public_url.trim_end_matches('/');
if origin == public {
return true;
}
// The Nuxt dev server proxies the sockets from port 3000 while the
// API keeps its own port. Both are loopback, so accept that pair.
let loopback = public.starts_with("http://localhost") || public.starts_with("http://127.0.0.1");
loopback && (origin.starts_with("http://localhost:") || origin.starts_with("http://127.0.0.1:"))
}
/// Rejects a mutating API request without the matching CSRF header. /// Rejects a mutating API request without the matching CSRF header.
/// Setup, login, registration, and joining with an invite happen before /// Setup, login, registration, and joining with an invite happen before
/// the client has a CSRF cookie. /// the client has a CSRF cookie.
@@ -122,6 +151,12 @@ async fn headers(State(state): State<Shared>, request: Request, next: Next) -> R
HeaderValue::from_static("strict-origin-when-cross-origin"), HeaderValue::from_static("strict-origin-when-cross-origin"),
); );
h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY")); h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
if state.config.secure_cookies() {
h.insert(
header::STRICT_TRANSPORT_SECURITY,
HeaderValue::from_static("max-age=31536000"),
);
}
let frame_src = match state.config.preview_frame_source() { let frame_src = match state.config.preview_frame_source() {
Some(source) => format!("'self' {source}"), Some(source) => format!("'self' {source}"),
None => "'self'".to_owned(), None => "'self'".to_owned(),
+142
View File
@@ -0,0 +1,142 @@
//! The account's picture: a small image served back to rooms and the
//! sidebar. The client resizes before upload; the server checks the
//! magic bytes and the size so a crafted request cannot store markup.
use axum::Json;
use axum::body::Bytes;
use axum::extract::{Path, State};
use axum::http::{HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use crate::auth::AuthUser;
use crate::error::{AppError, AppResult};
use crate::models::User;
use crate::state::Shared;
use crate::util::now_ms;
/// Two megabytes fits a 512px JPEG many times over.
pub const MAX_AVATAR_BYTES: usize = 2 * 1024 * 1024;
/// The image type named by the file's first bytes. SVG is deliberately
/// absent: it can carry script when opened as a document.
fn image_mime(bytes: &[u8]) -> Option<&'static str> {
if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
Some("image/png")
} else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
Some("image/jpeg")
} else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
Some("image/gif")
} else if bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP" {
Some("image/webp")
} else {
None
}
}
/// The stored picture. Any signed-in account may read one.
pub async fn get_avatar(
_user: AuthUser,
State(state): State<Shared>,
Path(account): Path<String>,
) -> AppResult<Response> {
let row = state
.db
.conn()
.query_row(
"SELECT mime, bytes FROM avatars WHERE account_id = ?1",
rusqlite::params![account],
|row| Ok((row.get::<_, String>(0)?, row.get::<_, Vec<u8>>(1)?)),
)
.ok();
let Some((mime, bytes)) = row else {
return Err(AppError::not_found("no picture for this account"));
};
let mut response = bytes.into_response();
let headers = response.headers_mut();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static(match mime.as_str() {
"image/png" => "image/png",
"image/jpeg" => "image/jpeg",
"image/gif" => "image/gif",
"image/webp" => "image/webp",
_ => "application/octet-stream",
}),
);
headers.insert(
header::CACHE_CONTROL,
HeaderValue::from_static("private, max-age=300"),
);
headers.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
Ok(response)
}
/// Replaces the caller's picture with the raw request body.
pub async fn upload_avatar(
user: AuthUser,
State(state): State<Shared>,
body: Bytes,
) -> AppResult<Json<User>> {
if body.is_empty() {
return Err(AppError::bad_request("the picture is empty"));
}
if body.len() > MAX_AVATAR_BYTES {
return Err(AppError::new(
StatusCode::PAYLOAD_TOO_LARGE,
"the picture must be 2 MB or smaller",
));
}
let mime = image_mime(&body).ok_or_else(|| {
AppError::bad_request("the picture must be a PNG, JPEG, GIF, or WebP image")
})?;
let mut account = user.user;
let now = now_ms();
state.db.conn().execute(
"INSERT INTO avatars (account_id, mime, bytes, updated_at)
VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(account_id) DO UPDATE SET
mime = excluded.mime,
bytes = excluded.bytes,
updated_at = excluded.updated_at",
rusqlite::params![&account.id, mime, body.as_ref(), now],
)?;
account.avatar_updated_at = Some(now);
Ok(Json(account))
}
/// Removes the caller's picture and falls the avatar back to initials.
pub async fn delete_avatar(user: AuthUser, State(state): State<Shared>) -> AppResult<Json<User>> {
let mut account = user.user;
state.db.conn().execute(
"DELETE FROM avatars WHERE account_id = ?1",
rusqlite::params![&account.id],
)?;
account.avatar_updated_at = None;
Ok(Json(account))
}
#[cfg(test)]
mod tests {
use super::image_mime;
#[test]
fn recognizes_the_four_image_types() {
assert_eq!(image_mime(b"\x89PNG\r\n\x1a\nrest"), Some("image/png"));
assert_eq!(image_mime(&[0xFF, 0xD8, 0xFF, 0xE0]), Some("image/jpeg"));
assert_eq!(image_mime(b"GIF89a..."), Some("image/gif"));
assert_eq!(image_mime(b"RIFF\0\0\0\0WEBPVP8 "), Some("image/webp"));
}
#[test]
fn rejects_markup_and_unknown_bytes() {
assert_eq!(
image_mime(b"<svg xmlns=\"http://www.w3.org/2000/svg\">"),
None
);
assert_eq!(image_mime(b"RIFF\0\0\0\0WAVEfmt "), None);
assert_eq!(image_mime(b""), None);
}
}
+20 -4
View File
@@ -88,8 +88,10 @@ fn load_members(state: &Shared, room: &str) -> AppResult<Vec<Member>> {
let online = state.presence.online(room); let online = state.presence.online(room);
let conn = state.db.conn(); let conn = state.db.conn();
let mut stmt = conn.prepare( let mut stmt = conn.prepare(
"SELECT id, account_id, display_name, role, color FROM members "SELECT m.id, m.account_id, m.display_name, m.role, m.color,
WHERE room_id = ?1 ORDER BY created_at ASC", (SELECT updated_at FROM avatars WHERE account_id = m.account_id)
FROM members m
WHERE m.room_id = ?1 ORDER BY m.created_at ASC",
)?; )?;
let rows = stmt.query_map(rusqlite::params![room], |row| { let rows = stmt.query_map(rusqlite::params![room], |row| {
Ok(Member { Ok(Member {
@@ -98,6 +100,7 @@ fn load_members(state: &Shared, room: &str) -> AppResult<Vec<Member>> {
display_name: row.get(2)?, display_name: row.get(2)?,
role: row.get(3)?, role: row.get(3)?,
color: row.get(4)?, color: row.get(4)?,
avatar_updated_at: row.get(5)?,
online: false, online: false,
}) })
})?; })?;
@@ -504,6 +507,18 @@ pub async fn join(
return Err(AppError::gone("this invite has expired")); return Err(AppError::gone("this invite has expired"));
} }
let display_name = clean_display_name(&body.display_name)?; let display_name = clean_display_name(&body.display_name)?;
// Claim the invite before creating an account or a member. The
// conditional update is atomic, so two requests racing with the
// same link cannot both redeem it.
let token_hash = sha256_hex(token.as_bytes());
let claimed = state.db.conn().execute(
"UPDATE invites SET used_at = ?1
WHERE token_hash = ?2 AND used_at IS NULL AND expires_at >= ?1",
rusqlite::params![now_ms(), &token_hash],
)?;
if claimed == 0 {
return Err(AppError::gone("this invite was already used"));
}
let existing = auth::user_from_headers(&state, &headers); let existing = auth::user_from_headers(&state, &headers);
let mut new_session = false; let mut new_session = false;
let account = match existing { let account = match existing {
@@ -522,6 +537,7 @@ pub async fn join(
handle, handle,
display_name, display_name,
kind: "guest".into(), kind: "guest".into(),
avatar_updated_at: None,
} }
} }
}; };
@@ -559,8 +575,8 @@ pub async fn join(
} }
}; };
state.db.conn().execute( state.db.conn().execute(
"UPDATE invites SET used_at = ?1, used_by = ?2 WHERE token_hash = ?3", "UPDATE invites SET used_by = ?1 WHERE token_hash = ?2",
rusqlite::params![now_ms(), account.id, sha256_hex(token.as_bytes())], rusqlite::params![account.id, token_hash],
)?; )?;
let cookies = if new_session { let cookies = if new_session {
let raw = auth::create_session(&state, &account.id)?; let raw = auth::create_session(&state, &account.id)?;
+1
View File
@@ -257,6 +257,7 @@ pub async fn delete_target(
"DELETE FROM sandbox_targets WHERE id = ?1 AND account_id = ?2", "DELETE FROM sandbox_targets WHERE id = ?1 AND account_id = ?2",
rusqlite::params![id, user.user.id], rusqlite::params![id, user.user.id],
)?; )?;
state.previews.forget(&id);
Ok(Json(json!({ "ok": true }))) Ok(Json(json!({ "ok": true })))
} }
+10 -1
View File
@@ -58,7 +58,8 @@ pub fn user_from_token(state: &Shared, token_hash: &str) -> Option<User> {
.db .db
.conn() .conn()
.query_row( .query_row(
"SELECT a.id, a.handle, a.display_name, a.kind, s.expires_at "SELECT a.id, a.handle, a.display_name, a.kind, s.expires_at,
(SELECT updated_at FROM avatars WHERE account_id = a.id)
FROM auth_sessions s JOIN accounts a ON a.id = s.account_id FROM auth_sessions s JOIN accounts a ON a.id = s.account_id
WHERE s.token_hash = ?1", WHERE s.token_hash = ?1",
rusqlite::params![token_hash], rusqlite::params![token_hash],
@@ -69,6 +70,7 @@ pub fn user_from_token(state: &Shared, token_hash: &str) -> Option<User> {
handle: row.get(1)?, handle: row.get(1)?,
display_name: row.get(2)?, display_name: row.get(2)?,
kind: row.get(3)?, kind: row.get(3)?,
avatar_updated_at: row.get(5)?,
}, },
row.get::<_, i64>(4)?, row.get::<_, i64>(4)?,
)) ))
@@ -105,6 +107,13 @@ pub fn hash_password(password: &str) -> AppResult<String> {
.map_err(|_| AppError::internal("could not hash the password")) .map_err(|_| AppError::internal("could not hash the password"))
} }
/// A valid hash used to keep a missing account's login time close to a
/// wrong password's. Generated once, then reused.
pub(crate) fn dummy_password_hash() -> &'static str {
static HASH: std::sync::OnceLock<String> = std::sync::OnceLock::new();
HASH.get_or_init(|| hash_password("rhema-together-login-timing").unwrap_or_default())
}
/// Verifies a password against a stored argon2 hash. /// Verifies a password against a stored argon2 hash.
pub fn verify_password(stored: &str, password: &str) -> bool { pub fn verify_password(stored: &str, password: &str) -> bool {
let Ok(hash) = PasswordHash::new(stored) else { let Ok(hash) = PasswordHash::new(stored) else {
+2 -6
View File
@@ -31,7 +31,7 @@ pub struct Config {
pub allowed_frame_ancestors: Vec<String>, pub allowed_frame_ancestors: Vec<String>,
/// Whether anyone may create an account. Off leaves setup and /// Whether anyone may create an account. Off leaves setup and
/// invites as the only doors. /// invites as the only doors.
#[serde(default = "default_true")] #[serde(default)]
pub allow_registration: bool, pub allow_registration: bool,
} }
@@ -39,10 +39,6 @@ fn default_steps() -> u32 {
48 48
} }
fn default_true() -> bool {
true
}
impl Default for Config { impl Default for Config {
fn default() -> Self { fn default() -> Self {
Self { Self {
@@ -54,7 +50,7 @@ impl Default for Config {
web_dir: PathBuf::from("web/.output/public"), web_dir: PathBuf::from("web/.output/public"),
max_turn_steps: default_steps(), max_turn_steps: default_steps(),
allowed_frame_ancestors: Vec::new(), allowed_frame_ancestors: Vec::new(),
allow_registration: true, allow_registration: false,
} }
} }
} }
+12 -3
View File
@@ -1,6 +1,7 @@
//! Symmetric protection for the credentials the server stores: provider //! Symmetric protection for the credentials the server stores: provider
//! API keys and ssh private keys. The key comes from a 0600 file. //! API keys and ssh private keys. The key comes from a 0600 file.
use std::io::Write;
use std::path::Path; use std::path::Path;
use base64::Engine; use base64::Engine;
@@ -22,6 +23,11 @@ impl Secrets {
/// bytes nor base64 for 32 bytes is refused. /// bytes nor base64 for 32 bytes is refused.
pub fn load_or_create(path: &Path) -> anyhow::Result<Self> { pub fn load_or_create(path: &Path) -> anyhow::Result<Self> {
let key = if path.exists() { let key = if path.exists() {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}
let raw = std::fs::read(path)?; let raw = std::fs::read(path)?;
decode_key(&raw)? decode_key(&raw)?
} else { } else {
@@ -31,12 +37,15 @@ impl Secrets {
use rand::RngCore; use rand::RngCore;
let mut key = [0u8; 32]; let mut key = [0u8; 32];
rand::rngs::OsRng.fill_bytes(&mut key); rand::rngs::OsRng.fill_bytes(&mut key);
std::fs::write(path, key)?; let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)] #[cfg(unix)]
{ {
use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::OpenOptionsExt;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; options.mode(0o600);
} }
let mut file = options.open(path)?;
file.write_all(&key)?;
key key
}; };
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
+7
View File
@@ -63,6 +63,13 @@ CREATE TABLE IF NOT EXISTS accounts (
created_at INTEGER NOT NULL created_at INTEGER NOT NULL
) STRICT; ) STRICT;
CREATE TABLE IF NOT EXISTS avatars (
account_id TEXT PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE,
mime TEXT NOT NULL,
bytes BLOB NOT NULL,
updated_at INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS auth_sessions ( CREATE TABLE IF NOT EXISTS auth_sessions (
token_hash TEXT PRIMARY KEY, token_hash TEXT PRIMARY KEY,
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
+3
View File
@@ -52,6 +52,7 @@ pub struct Member {
pub display_name: String, pub display_name: String,
pub role: String, pub role: String,
pub color: String, pub color: String,
pub avatar_updated_at: Option<i64>,
pub online: bool, pub online: bool,
} }
@@ -62,6 +63,8 @@ pub struct User {
pub handle: String, pub handle: String,
pub display_name: String, pub display_name: String,
pub kind: String, pub kind: String,
/// When the account last replaced its picture, or `None`.
pub avatar_updated_at: Option<i64>,
} }
/// One server-sent event. Durable events are also rows in `events`; /// One server-sent event. Durable events are also rows in `events`;
+107 -18
View File
@@ -43,7 +43,7 @@ impl PreviewTunnels {
.insert(target.to_owned(), handle); .insert(target.to_owned(), handle);
} }
fn forget(&self, target: &str) { pub(crate) fn forget(&self, target: &str) {
self.handles self.handles
.lock() .lock()
.unwrap_or_else(|err| err.into_inner()) .unwrap_or_else(|err| err.into_inner())
@@ -75,6 +75,10 @@ pub fn is_preview_host(config: &Config, host: &str) -> bool {
name.ends_with(&format!(".{domain}")) name.ends_with(&format!(".{domain}"))
} }
/// How long a preview host stays valid. The browser keeps using the
/// host it was given; a reload of the room mints a fresh one.
const PREVIEW_TTL_SECONDS: i64 = 24 * 60 * 60;
/// The signed URL for one room and port. /// The signed URL for one room and port.
pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResult<String> { pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResult<String> {
let Some((scheme, domain)) = domain(config) else { let Some((scheme, domain)) = domain(config) else {
@@ -82,7 +86,8 @@ pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResu
"the preview proxy is not configured", "the preview proxy is not configured",
)); ));
}; };
let signature = secrets.sign(&format!("{room}:{port}")); let expires = crate::util::now_ms() / 1000 + PREVIEW_TTL_SECONDS;
let signature = secrets.sign(&format!("{room}:{port}:{expires}"));
let port_part = config let port_part = config
.preview_origin .preview_origin
.split_once("://") .split_once("://")
@@ -93,23 +98,44 @@ pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResu
.map(|(_, value)| format!(":{value}")) .map(|(_, value)| format!(":{value}"))
.unwrap_or_default(); .unwrap_or_default();
Ok(format!( Ok(format!(
"{scheme}://r{room}-p{port}-{signature}.{domain}{port_part}/" "{scheme}://r{room}-p{port}-{expires}-{signature}.{domain}{port_part}/"
)) ))
} }
/// Splits `r<room>-p<port>-<sig>` from the Host header. /// Splits `r<room>-p<port>-<expiry>-<sig>` from the Host header.
fn target_of_host(config: &Config, host: &str) -> Option<(String, u16, String)> { fn target_of_host(config: &Config, host: &str) -> Option<(String, u16, i64, String)> {
let (_, domain) = domain(config)?; let (_, domain) = domain(config)?;
let name = host.split(':').next().unwrap_or(host); let name = host.split(':').next().unwrap_or(host);
let label = name.strip_suffix(&format!(".{domain}"))?; let label = name.strip_suffix(&format!(".{domain}"))?;
let rest = label.strip_prefix('r')?; let rest = label.strip_prefix('r')?;
let (room, port) = rest.rsplit_once("-p")?; let (room, rest) = rest.rsplit_once("-p")?;
let (port, signature) = port.rsplit_once('-')?; let mut fields = rest.split('-');
if room.is_empty() || signature.is_empty() { let port: u16 = fields.next()?.parse().ok()?;
let expires: i64 = fields.next()?.parse().ok()?;
let signature = fields.next()?;
if room.is_empty() || signature.is_empty() || fields.next().is_some() {
return None; return None;
} }
let port: u16 = port.parse().ok()?; Some((room.to_owned(), port, expires, signature.to_owned()))
Some((room.to_owned(), port, signature.to_owned())) }
fn signatures_match(a: &str, b: &str) -> bool {
if a.len() != b.len() {
return false;
}
let mut diff = 0u8;
for (left, right) in a.as_bytes().iter().zip(b.as_bytes()) {
diff |= left ^ right;
}
diff == 0
}
fn no_referrer(mut response: Response) -> Response {
response.headers_mut().insert(
header::REFERRER_POLICY,
HeaderValue::from_static("no-referrer"),
);
response
} }
/// Verifies the signature in the Host header against the room and port /// Verifies the signature in the Host header against the room and port
@@ -121,20 +147,25 @@ pub async fn proxy(state: Shared, request: Request<Body>) -> Response {
.and_then(|value| value.to_str().ok()) .and_then(|value| value.to_str().ok())
.unwrap_or("") .unwrap_or("")
.to_owned(); .to_owned();
let Some((room, port, signature)) = target_of_host(&state.config, &host) else { let Some((room, port, expires, signature)) = target_of_host(&state.config, &host) else {
return (StatusCode::NOT_FOUND, "not a preview host").into_response(); return (StatusCode::NOT_FOUND, "not a preview host").into_response();
}; };
let expected = state.secrets.sign(&format!("{room}:{port}")); if expires < crate::util::now_ms() / 1000 {
if signature != expected { return (StatusCode::NOT_FOUND, "this preview link has expired").into_response();
}
let expected = state.secrets.sign(&format!("{room}:{port}:{expires}"));
if !signatures_match(&signature, &expected) {
return (StatusCode::NOT_FOUND, "not a preview host").into_response(); return (StatusCode::NOT_FOUND, "not a preview host").into_response();
} }
match try_proxy(&state, &room, port, request).await { match try_proxy(&state, &room, port, request).await {
Ok(response) => response, Ok(response) => no_referrer(response),
Err(message) => ( Err(message) => no_referrer(
(
StatusCode::BAD_GATEWAY, StatusCode::BAD_GATEWAY,
format!("the preview did not answer: {message}"), format!("the preview did not answer: {message}"),
) )
.into_response(), .into_response(),
),
} }
} }
@@ -153,7 +184,9 @@ async fn try_proxy(
let handle = match state.previews.get(&target.id) { let handle = match state.previews.get(&target.id) {
Some(handle) => handle, Some(handle) => handle,
None => { None => {
let handle = Arc::new(crate::ssh::connect_handle(&target, &key).await?); let (handle, learned) = crate::ssh::connect_handle(&target, &key).await?;
crate::ssh::remember_host_key(state, &target, learned);
let handle = Arc::new(handle);
state.previews.put(&target.id, handle.clone()); state.previews.put(&target.id, handle.clone());
handle handle
} }
@@ -165,7 +198,9 @@ async fn try_proxy(
Ok(channel) => channel, Ok(channel) => channel,
Err(_) => { Err(_) => {
state.previews.forget(&target.id); state.previews.forget(&target.id);
let handle = Arc::new(crate::ssh::connect_handle(&target, &key).await?); let (handle, learned) = crate::ssh::connect_handle(&target, &key).await?;
crate::ssh::remember_host_key(state, &target, learned);
let handle = Arc::new(handle);
state.previews.put(&target.id, handle.clone()); state.previews.put(&target.id, handle.clone());
handle handle
.channel_open_direct_tcpip("127.0.0.1", port as u32, "127.0.0.1", 0) .channel_open_direct_tcpip("127.0.0.1", port as u32, "127.0.0.1", 0)
@@ -208,7 +243,7 @@ async fn try_proxy(
*out.status_mut() = parts.status; *out.status_mut() = parts.status;
*out.headers_mut() = parts.headers; *out.headers_mut() = parts.headers;
strip_hop_by_hop(out.headers_mut()); strip_hop_by_hop(out.headers_mut());
Ok(out) Ok(no_referrer(out))
} }
fn strip_hop_by_hop(headers: &mut HeaderMap) { fn strip_hop_by_hop(headers: &mut HeaderMap) {
@@ -225,3 +260,57 @@ fn strip_hop_by_hop(headers: &mut HeaderMap) {
headers.remove(name); headers.remove(name);
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
fn secrets() -> (Secrets, std::path::PathBuf) {
let path = std::env::temp_dir().join(format!(
"rhema-together-preview-test-{}.key",
crate::util::random_id(10)
));
let secrets = Secrets::load_or_create(&path).expect("test key");
(secrets, path)
}
#[test]
fn a_preview_host_carries_room_port_expiry_and_signature() {
let mut config = Config::default();
config.preview_origin = "https://preview.example.com".into();
let (secrets, path) = secrets();
let url = url(&config, &secrets, "room123", 5173).expect("url");
let host = url
.trim_start_matches("https://")
.split('/')
.next()
.expect("host");
let (room, port, expires, signature) = target_of_host(&config, host).expect("parsed host");
assert_eq!(room, "room123");
assert_eq!(port, 5173);
assert!(expires >= crate::util::now_ms() / 1000);
assert_eq!(signature, secrets.sign(&format!("room123:5173:{expires}")));
let _ = std::fs::remove_file(path);
}
#[test]
fn the_old_host_shape_is_not_accepted() {
let mut config = Config::default();
config.preview_origin = "https://preview.example.com".into();
assert!(
target_of_host(
&config,
"rroom123-p5173-0123456789abcdef01234567.preview.example.com"
)
.is_none()
);
}
#[test]
fn signatures_compare_by_value() {
assert!(signatures_match("abcd", "abcd"));
assert!(!signatures_match("abcd", "abce"));
assert!(!signatures_match("abcd", "abc"));
}
}
+32 -13
View File
@@ -46,13 +46,26 @@ impl client::Handler for HostKey {
} }
} }
/// Opens a connection for the preview proxy. /// Opens a connection for the preview proxy, returning the host-key
/// fingerprint when this was the first contact.
pub(crate) async fn connect_handle( pub(crate) async fn connect_handle(
target: &TargetRow, target: &TargetRow,
private_key: &str, private_key: &str,
) -> Result<Handle<HostKey>, String> { ) -> Result<(Handle<HostKey>, Option<String>), String> {
let (handle, _fingerprint) = connect(target, private_key).await?; connect(target, private_key).await
Ok(handle) }
/// Pins a learned host key after a successful login. A later connection
/// then refuses a different key.
pub(crate) fn remember_host_key(state: &Shared, target: &TargetRow, learned: Option<String>) {
if target.host_fingerprint.is_none()
&& let Some(fingerprint) = learned
{
let _ = state.db.conn().execute(
"UPDATE sandbox_targets SET host_fingerprint = ?1 WHERE id = ?2",
rusqlite::params![fingerprint, target.id],
);
}
} }
async fn connect( async fn connect(
@@ -95,7 +108,14 @@ async fn connect(
/// Attaches a browser socket to an interactive shell in the room's /// Attaches a browser socket to an interactive shell in the room's
/// sandbox. /// sandbox.
pub async fn terminal(socket: WebSocket, state: Shared, workspace: String, target: TargetRow) { pub async fn terminal(
socket: WebSocket,
state: Shared,
room: String,
account: String,
workspace: String,
target: TargetRow,
) {
let (mut sink, mut source) = socket.split(); let (mut sink, mut source) = socket.split();
let key = match state.secrets.open_str(&target.private_key_ciphertext) { let key = match state.secrets.open_str(&target.private_key_ciphertext) {
Ok(key) => key, Ok(key) => key,
@@ -125,14 +145,7 @@ pub async fn terminal(socket: WebSocket, state: Shared, workspace: String, targe
}; };
// Learn the host key once the login succeeded, not before: a // Learn the host key once the login succeeded, not before: a
// server that refuses us should not become known. // server that refuses us should not become known.
if target.host_fingerprint.is_none() remember_host_key(&state, &target, learned);
&& let Some(fingerprint) = learned
{
let _ = state.db.conn().execute(
"UPDATE sandbox_targets SET host_fingerprint = ?1 WHERE id = ?2",
rusqlite::params![fingerprint, target.id],
);
}
let mut channel = match connection.channel_open_session().await { let mut channel = match connection.channel_open_session().await {
Ok(channel) => channel, Ok(channel) => channel,
Err(err) => { Err(err) => {
@@ -160,8 +173,14 @@ pub async fn terminal(socket: WebSocket, state: Shared, workspace: String, targe
json!({ "type": "ready" }).to_string().into(), json!({ "type": "ready" }).to_string().into(),
)) ))
.await; .await;
let mut access = tokio::time::interval(std::time::Duration::from_secs(2));
loop { loop {
tokio::select! { tokio::select! {
_ = access.tick() => {
if crate::api::rooms::member_of(&state, &room, &account).is_err() {
break;
}
}
message = channel.wait() => { message = channel.wait() => {
match message { match message {
Some(ChannelMsg::Data { data }) => { Some(ChannelMsg::Data { data }) => {
+81
View File
@@ -418,6 +418,7 @@ button {
width: 28px; width: 28px;
height: 28px; height: 28px;
flex: none; flex: none;
overflow: hidden;
border-radius: var(--r-avatar); border-radius: var(--r-avatar);
border: 1px solid color-mix(in srgb, var(--member, var(--muted)) 28%, transparent); border: 1px solid color-mix(in srgb, var(--member, var(--muted)) 28%, transparent);
background: color-mix(in srgb, var(--member, var(--muted)) 14%, var(--surface)); background: color-mix(in srgb, var(--member, var(--muted)) 14%, var(--surface));
@@ -439,6 +440,19 @@ button {
font-size: var(--fs-small); font-size: var(--fs-small);
} }
.avatar-xl {
width: 72px;
height: 72px;
font-size: var(--fs-section);
}
.avatar-img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.avatar-offline { .avatar-offline {
opacity: 0.45; opacity: 0.45;
} }
@@ -651,6 +665,23 @@ button {
min-width: 0; min-width: 0;
} }
.sidebar-account-link {
display: flex;
align-items: center;
gap: var(--sp-2);
flex: 1;
min-width: 0;
color: var(--text);
}
.sidebar-account-link:hover {
text-decoration: none;
}
.sidebar-account-link:hover .sidebar-account-name {
color: var(--accent);
}
.sidebar-account-name { .sidebar-account-name {
flex: 1; flex: 1;
min-width: 0; min-width: 0;
@@ -800,6 +831,21 @@ button {
min-width: 0; min-width: 0;
} }
.msg-human {
display: flex;
align-items: flex-start;
gap: var(--sp-3);
}
.msg-human > .avatar {
margin-top: 1px;
}
.msg-body {
flex: 1;
min-width: 0;
}
.msg-head { .msg-head {
display: flex; display: flex;
align-items: baseline; align-items: baseline;
@@ -1443,6 +1489,41 @@ button {
white-space: nowrap; white-space: nowrap;
} }
.profile-card {
display: flex;
align-items: flex-start;
gap: var(--sp-5);
padding: var(--sp-5);
border: 1px solid var(--border);
border-radius: var(--r-card);
background: var(--surface);
}
.profile-body {
display: flex;
flex-direction: column;
gap: var(--sp-1);
min-width: 0;
}
.profile-name {
font-size: var(--fs-section);
font-weight: 600;
line-height: var(--lh-heading);
overflow-wrap: anywhere;
}
.profile-actions {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2);
margin-top: var(--sp-3);
}
.file-input {
display: none;
}
.settings-row { .settings-row {
display: flex; display: flex;
align-items: flex-start; align-items: flex-start;
+15 -4
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed } from 'vue' import { computed, ref, watch } from 'vue'
import { initials } from '~/utils/format' import { initials } from '~/utils/format'
import { memberColorVar } from '~/utils/member' import { memberColorVar } from '~/utils/member'
@@ -7,15 +7,25 @@ const props = withDefaults(
defineProps<{ defineProps<{
name: string name: string
color?: string | null color?: string | null
size?: 'sm' | 'md' | 'lg' size?: 'sm' | 'md' | 'lg' | 'xl'
src?: string | null
offline?: boolean offline?: boolean
}>(), }>(),
{ color: null, size: 'md', offline: false }, { color: null, size: 'md', src: null, offline: false },
)
const failed = ref(false)
watch(
() => props.src,
() => {
failed.value = false
},
) )
const style = computed(() => ({ '--member': memberColorVar(props.color) })) const style = computed(() => ({ '--member': memberColorVar(props.color) }))
const className = computed(() => ({ const className = computed(() => ({
'avatar-lg': props.size === 'lg', 'avatar-lg': props.size === 'lg',
'avatar-xl': props.size === 'xl',
'avatar-sm': props.size === 'sm', 'avatar-sm': props.size === 'sm',
'avatar-offline': props.offline, 'avatar-offline': props.offline,
})) }))
@@ -23,6 +33,7 @@ const className = computed(() => ({
<template> <template>
<span class="avatar" :class="className" :style="style" :title="name" role="img" :aria-label="name"> <span class="avatar" :class="className" :style="style" :title="name" role="img" :aria-label="name">
{{ initials(name) }} <img v-if="src && !failed" class="avatar-img" :src="src" alt="" @error="failed = true">
<template v-else>{{ initials(name) }}</template>
</span> </span>
</template> </template>
+5 -2
View File
@@ -4,7 +4,7 @@ import type { Message } from '~/types'
import { fullTime, relativeTime } from '~/utils/format' import { fullTime, relativeTime } from '~/utils/format'
import { memberColorVar } from '~/utils/member' import { memberColorVar } from '~/utils/member'
const props = defineProps<{ message: Message; color?: string | null }>() const props = defineProps<{ message: Message; color?: string | null; avatar?: string | null }>()
const segments = computed(() => { const segments = computed(() => {
const parts = props.message.text.split(/(@rhema\b)/gi) const parts = props.message.text.split(/(@rhema\b)/gi)
@@ -34,7 +34,9 @@ const style = computed(() => ({ '--member': memberColorVar(props.color) }))
</div> </div>
</div> </div>
<div v-else class="msg"> <div v-else class="msg msg-human">
<AppAvatar :name="message.author_name" :color="color" :src="avatar" size="sm" />
<div class="msg-body">
<div class="msg-head"> <div class="msg-head">
<span class="msg-author member-name" :style="style">{{ message.author_name }}</span> <span class="msg-author member-name" :style="style">{{ message.author_name }}</span>
<span class="msg-time" :title="fullTime(message.created_at)">{{ relativeTime(message.created_at) }}</span> <span class="msg-time" :title="fullTime(message.created_at)">{{ relativeTime(message.created_at) }}</span>
@@ -46,4 +48,5 @@ const style = computed(() => ({ '--member': memberColorVar(props.color) }))
</template> </template>
</div> </div>
</div> </div>
</div>
</template> </template>
+6 -1
View File
@@ -96,7 +96,12 @@ function toggleFullscreen() {
<p v-if="error" class="preview-message form-error" role="alert">{{ error }}</p> <p v-if="error" class="preview-message form-error" role="alert">{{ error }}</p>
<div v-if="url" class="preview-frame-wrap"> <div v-if="url" class="preview-frame-wrap">
<iframe class="preview-frame" :src="url" :title="`Preview on port ${port}`" /> <iframe
class="preview-frame"
:src="url"
:title="`Preview on port ${port}`"
sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
/>
</div> </div>
<p v-else-if="!error" class="preview-message"> <p v-else-if="!error" class="preview-message">
Enter the port the room serves and choose Go. Enter the port the room serves and choose Go.
+6
View File
@@ -14,6 +14,11 @@ const props = defineProps<{
const emit = defineEmits<{ invite: []; togglePane: []; settings: [] }>() const emit = defineEmits<{ invite: []; togglePane: []; settings: [] }>()
const online = computed(() => new Set(props.onlineIds)) const online = computed(() => new Set(props.onlineIds))
function avatarUrl(member: Member): string | null {
if (!member.avatar_updated_at) return null
return `/api/avatars/${member.account_id}?v=${member.avatar_updated_at}`
}
const visible = computed(() => props.members.slice(0, 5)) const visible = computed(() => props.members.slice(0, 5))
const extra = computed(() => props.members.slice(5)) const extra = computed(() => props.members.slice(5))
const extraTitle = computed(() => extra.value.map((member) => member.display_name).join(', ')) const extraTitle = computed(() => extra.value.map((member) => member.display_name).join(', '))
@@ -32,6 +37,7 @@ const extraTitle = computed(() => extra.value.map((member) => member.display_nam
:key="member.id" :key="member.id"
:name="member.display_name" :name="member.display_name"
:color="member.color" :color="member.color"
:src="avatarUrl(member)"
:offline="!online.has(member.id)" :offline="!online.has(member.id)"
size="sm" size="sm"
/> />
+8
View File
@@ -6,6 +6,7 @@ interface RequestOptions {
method?: ApiMethod method?: ApiMethod
body?: unknown body?: unknown
query?: Record<string, string | number | boolean | undefined> query?: Record<string, string | number | boolean | undefined>
contentType?: string
} }
const PUBLIC_PREFIXES = ['/setup', '/login', '/register', '/join'] const PUBLIC_PREFIXES = ['/setup', '/login', '/register', '/join']
@@ -22,6 +23,7 @@ export function useApi() {
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> { async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
const method = options.method ?? 'GET' const method = options.method ?? 'GET'
const headers: Record<string, string> = { Accept: 'application/json' } const headers: Record<string, string> = { Accept: 'application/json' }
if (options.contentType) headers['Content-Type'] = options.contentType
if (method !== 'GET' && csrf.value) headers['X-CSRF-Token'] = csrf.value if (method !== 'GET' && csrf.value) headers['X-CSRF-Token'] = csrf.value
try { try {
return await $fetch<T>(path, { return await $fetch<T>(path, {
@@ -45,6 +47,12 @@ export function useApi() {
return { return {
get: <T>(path: string, query?: RequestOptions['query']) => request<T>(path, { query }), get: <T>(path: string, query?: RequestOptions['query']) => request<T>(path, { query }),
post: <T>(path: string, body?: unknown) => request<T>(path, { method: 'POST', body }), post: <T>(path: string, body?: unknown) => request<T>(path, { method: 'POST', body }),
upload: <T>(path: string, body: Blob) =>
request<T>(path, {
method: 'POST',
body,
contentType: body.type || 'application/octet-stream',
}),
patch: <T>(path: string, body?: unknown) => request<T>(path, { method: 'PATCH', body }), patch: <T>(path: string, body?: unknown) => request<T>(path, { method: 'PATCH', body }),
del: <T>(path: string) => request<T>(path, { method: 'DELETE' }), del: <T>(path: string) => request<T>(path, { method: 'DELETE' }),
ApiRequestError, ApiRequestError,
+5
View File
@@ -47,6 +47,10 @@ export function useSession() {
return inflight return inflight
} }
function setUser(next: User | null) {
state.value = { ...state.value, user: next }
}
async function signOut() { async function signOut() {
try { try {
await api.post('/logout') await api.post('/logout')
@@ -61,6 +65,7 @@ export function useSession() {
session: state, session: state,
user: computed(() => state.value.user), user: computed(() => state.value.user),
load, load,
setUser,
signOut, signOut,
} }
} }
+15 -2
View File
@@ -1,8 +1,13 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, watch } from 'vue' import { computed, onMounted, watch } from 'vue'
import { LogOut, Plus, Settings } from 'lucide-vue-next' import { LogOut, Plus, Settings } from 'lucide-vue-next'
const { user, signOut, session } = useSession() const { user, signOut, session } = useSession()
const avatarSrc = computed(() => {
if (!user.value?.avatar_updated_at) return null
return `/api/avatars/${user.value.id}?v=${user.value.avatar_updated_at}`
})
const { const {
rooms: roomList, rooms: roomList,
loading: roomsLoading, loading: roomsLoading,
@@ -70,8 +75,16 @@ async function onSignOut() {
<span>Settings</span> <span>Settings</span>
</NuxtLink> </NuxtLink>
<div class="sidebar-account"> <div class="sidebar-account">
<AppAvatar v-if="user" :name="user.display_name" color="var(--member-1)" size="sm" /> <NuxtLink to="/profile" class="sidebar-account-link" title="Open profile">
<AppAvatar
v-if="user"
:name="user.display_name"
color="var(--member-1)"
:src="avatarSrc"
size="sm"
/>
<span class="sidebar-account-name" :title="user?.handle">{{ user?.display_name }}</span> <span class="sidebar-account-name" :title="user?.handle">{{ user?.display_name }}</span>
</NuxtLink>
<button <button
type="button" type="button"
class="icon-btn" class="icon-btn"
+125
View File
@@ -0,0 +1,125 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { Camera, Trash2 } from 'lucide-vue-next'
import type { User } from '~/types'
import { apiErrorMessage } from '~/utils/errors'
useHead({ title: 'Profile · Rhema Together' })
const api = useApi()
const { user, setUser, load } = useSession()
const fileInput = ref<HTMLInputElement | null>(null)
const busy = ref(false)
const error = ref('')
const notice = ref('')
const avatarSrc = computed(() => {
if (!user.value?.avatar_updated_at) return null
return `/api/avatars/${user.value.id}?v=${user.value.avatar_updated_at}`
})
onMounted(async () => {
if (!user.value) await load(true)
})
function pickFile() {
fileInput.value?.click()
}
async function onFile(event: Event) {
const input = event.target as HTMLInputElement
const file = input.files?.[0]
input.value = ''
if (!file || busy.value) return
if (!['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(file.type)) {
error.value = 'Choose a PNG, JPEG, GIF, or WebP image.'
return
}
if (file.size > 2 * 1024 * 1024) {
error.value = 'The picture must be 2 MB or smaller.'
return
}
busy.value = true
error.value = ''
notice.value = ''
try {
const updated = await api.upload<User>('/profile/avatar', file)
setUser(updated)
notice.value = 'Picture updated.'
} catch (err) {
error.value = apiErrorMessage(err)
} finally {
busy.value = false
}
}
async function removePicture() {
if (busy.value || !avatarSrc.value) return
busy.value = true
error.value = ''
notice.value = ''
try {
const updated = await api.del<User>('/profile/avatar')
setUser(updated)
notice.value = 'Picture removed.'
} catch (err) {
error.value = apiErrorMessage(err)
} finally {
busy.value = false
}
}
</script>
<template>
<div class="page">
<div class="page-head">
<h1 class="page-title">Profile</h1>
</div>
<section class="section">
<div v-if="user" class="profile-card">
<AppAvatar
:name="user.display_name"
color="var(--member-1)"
:src="avatarSrc"
size="xl"
/>
<div class="profile-body">
<div class="profile-name">{{ user.display_name }}</div>
<div class="meta">@{{ user.handle }}</div>
<div class="profile-actions">
<button type="button" class="btn btn-primary btn-sm" :disabled="busy" @click="pickFile">
<Camera :size="14" aria-hidden="true" />
{{ busy ? 'Uploading' : 'Change picture' }}
</button>
<button
v-if="avatarSrc"
type="button"
class="btn btn-sm btn-quiet"
:disabled="busy"
@click="removePicture"
>
<Trash2 :size="14" aria-hidden="true" />
Remove picture
</button>
</div>
<p class="hint">PNG, JPEG, GIF or WebP, up to 2 MB. The picture is shown cropped to a square.</p>
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
<p v-if="notice" class="meta" role="status">{{ notice }}</p>
</div>
</div>
<p v-else class="meta">Loading profile.</p>
<input
ref="fileInput"
class="file-input"
type="file"
accept="image/png,image/jpeg,image/gif,image/webp"
@change="onFile"
>
</section>
</div>
</template>
+10 -1
View File
@@ -3,6 +3,7 @@ import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
import type { import type {
DeltaData, DeltaData,
Envelope, Envelope,
Member,
Message, Message,
MessagePage, MessagePage,
NoticeData, NoticeData,
@@ -87,7 +88,7 @@ const isOwner = computed(
) )
const memberById = computed(() => { const memberById = computed(() => {
const map = new Map<string, { color: string }>() const map = new Map<string, Member>()
for (const member of detail.value?.members ?? []) map.set(member.id, member) for (const member of detail.value?.members ?? []) map.set(member.id, member)
return map return map
}) })
@@ -450,6 +451,13 @@ function colorFor(message: Message): string | null {
return memberById.value.get(message.author_id)?.color ?? null return memberById.value.get(message.author_id)?.color ?? null
} }
function avatarFor(message: Message): string | null {
if (!message.author_id) return null
const member = memberById.value.get(message.author_id)
if (!member?.avatar_updated_at) return null
return `/api/avatars/${member.account_id}?v=${member.avatar_updated_at}`
}
function isNearBottom(element: HTMLElement) { function isNearBottom(element: HTMLElement) {
return element.scrollHeight - element.scrollTop - element.clientHeight < 80 return element.scrollHeight - element.scrollTop - element.clientHeight < 80
} }
@@ -651,6 +659,7 @@ onBeforeUnmount(() => {
v-if="entry.kind === 'message'" v-if="entry.kind === 'message'"
:message="entry.message" :message="entry.message"
:color="colorFor(entry.message)" :color="colorFor(entry.message)"
:avatar="avatarFor(entry.message)"
/> />
<p <p
v-else-if="entry.kind === 'notice'" v-else-if="entry.kind === 'notice'"
+2
View File
@@ -3,6 +3,7 @@ export interface User {
handle: string handle: string
display_name: string display_name: string
kind: string kind: string
avatar_updated_at: number | null
} }
export interface BootstrapResponse { export interface BootstrapResponse {
@@ -66,6 +67,7 @@ export interface Member {
display_name: string display_name: string
role: string role: string
color: string color: string
avatar_updated_at: number | null
online: boolean online: boolean
} }