diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..9e5c0d8 --- /dev/null +++ b/.dockerignore @@ -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 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..7718098 --- /dev/null +++ b/Dockerfile @@ -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"] diff --git a/README.md b/README.md index 9ffd201..7bf43ec 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ one SQLite file. ## 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. ```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`, 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.` to the same service. The app does not +issue certificates. + ## First room 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 -`://r-p-./`. The HMAC covers the -room and port and is derived from the server's master key, so a room id -alone is not enough to reach a preview. DNS must resolve every subdomain -of the preview host to the server (a wildcard `*.preview` record), and -TLS must cover the wildcard. A copied preview URL works for anyone who -has it; treat it as a read capability for that port. +`://r-p--./`. The HMAC +covers the room, port, and expiry and is derived from the server's +master key, so a room id alone is not enough to reach a preview. The +address expires after 24 hours; reloading the pane mints a new one. DNS +must resolve every subdomain of the preview host to the server (a +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 to `127.0.0.1:` 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_WEB_DIR` | `web/.output/public` | built client | | `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 @@ -159,6 +185,18 @@ Every field can be set in the YAML file (`TOGETHER_CONFIG`, default mutating calls. - Guests can chat, interrupt, use the terminal, and read files. Only 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. - The app sets a CSP that frames only `*.`, and refuses to frame itself elsewhere. diff --git a/deploy/helm/rhema-together/Chart.yaml b/deploy/helm/rhema-together/Chart.yaml new file mode 100644 index 0000000..bc102ef --- /dev/null +++ b/deploy/helm/rhema-together/Chart.yaml @@ -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 diff --git a/deploy/helm/rhema-together/README.md b/deploy/helm/rhema-together/README.md new file mode 100644 index 0000000..35b6855 --- /dev/null +++ b/deploy/helm/rhema-together/README.md @@ -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=` 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. diff --git a/deploy/helm/rhema-together/templates/NOTES.txt b/deploy/helm/rhema-together/templates/NOTES.txt new file mode 100644 index 0000000..1cd4423 --- /dev/null +++ b/deploy/helm/rhema-together/templates/NOTES.txt @@ -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 }} diff --git a/deploy/helm/rhema-together/templates/_helpers.tpl b/deploy/helm/rhema-together/templates/_helpers.tpl new file mode 100644 index 0000000..3c0dd65 --- /dev/null +++ b/deploy/helm/rhema-together/templates/_helpers.tpl @@ -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 }} diff --git a/deploy/helm/rhema-together/templates/deployment.yaml b/deploy/helm/rhema-together/templates/deployment.yaml new file mode 100644 index 0000000..d5eadab --- /dev/null +++ b/deploy/helm/rhema-together/templates/deployment.yaml @@ -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 }} diff --git a/deploy/helm/rhema-together/templates/ingress.yaml b/deploy/helm/rhema-together/templates/ingress.yaml new file mode 100644 index 0000000..d38835a --- /dev/null +++ b/deploy/helm/rhema-together/templates/ingress.yaml @@ -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 }} diff --git a/deploy/helm/rhema-together/templates/pvc.yaml b/deploy/helm/rhema-together/templates/pvc.yaml new file mode 100644 index 0000000..509465d --- /dev/null +++ b/deploy/helm/rhema-together/templates/pvc.yaml @@ -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 }} diff --git a/deploy/helm/rhema-together/templates/service.yaml b/deploy/helm/rhema-together/templates/service.yaml new file mode 100644 index 0000000..9dc8f4f --- /dev/null +++ b/deploy/helm/rhema-together/templates/service.yaml @@ -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 }} diff --git a/deploy/helm/rhema-together/values.yaml b/deploy/helm/rhema-together/values.yaml new file mode 100644 index 0000000..2f16e0f --- /dev/null +++ b/deploy/helm/rhema-together/values.yaml @@ -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: {} diff --git a/specs/rhema-together.md b/specs/rhema-together.md index 66816a1..d084963 100644 --- a/specs/rhema-together.md +++ b/specs/rhema-together.md @@ -341,13 +341,14 @@ Layout, one wildcard record: ``` app https://together./room// -preview https://r-p-.preview./ +preview https://r-p--.preview./ ``` -The room, port, and a 24-hex HMAC signature form the first label. The -signature is minted by the app when the pane opens and checked by the -proxy, so the URL is not guessable from a room id. It does not expire; -treat a copied preview URL as a room read capability. +The room, port, expiry, and a 24-hex HMAC signature form the first +label. The signature is minted by the app when the pane opens and +checked by the proxy, so the URL is not guessable from a room id. It +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 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. 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 -side; the app's CSP names `*.` in `frame-src`. +the whole capability. Preview responses carry `Referrer-Policy: +no-referrer` so the signed host does not leak to third-party resources. +The app's CSP names `*.` in `frame-src`. 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 changes them. Every turn spends from that config. 3. Interrupts: any member. v1 has no rate limit. -4. Preview auth: a per-room, per-port signed host label with no expiry. - A copied preview URL is a read capability for that port. +4. Preview auth: a per-room, per-port signed host label with a 24-hour + 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 room log does not record terminal contents. diff --git a/src/api/auth.rs b/src/api/auth.rs index 06195ff..af4a3eb 100644 --- a/src/api/auth.rs +++ b/src/api/auth.rs @@ -8,7 +8,8 @@ use serde::Deserialize; use serde_json::{Value, json}; 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::models::User; @@ -109,6 +110,7 @@ pub async fn setup( handle, display_name, kind: "user".into(), + avatar_updated_at: None, }), )) } @@ -176,6 +178,7 @@ pub async fn register( handle, display_name, kind: "user".into(), + avatar_updated_at: None, }), )) } @@ -196,7 +199,9 @@ pub async fn login( .db .conn() .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) LIMIT 1", rusqlite::params![identifier], @@ -207,11 +212,22 @@ pub async fn login( row.get::<_, String>(2)?, row.get::<_, String>(3)?, row.get::<_, Option>(4)?, + row.get::<_, Option>(5)?, )) }, ) .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")); }; if !verify_password(&password_hash, &body.password) { @@ -227,6 +243,7 @@ pub async fn login( handle, display_name, kind, + avatar_updated_at, }), )) } diff --git a/src/api/files.rs b/src/api/files.rs index 6377b24..288a10a 100644 --- a/src/api/files.rs +++ b/src/api/files.rs @@ -6,6 +6,7 @@ use std::time::Duration; use axum::Json; use axum::extract::ws::WebSocketUpgrade; use axum::extract::{Path, Query, State}; +use axum::http::HeaderMap; use axum::response::Response; use rhema_sandbox::Sandbox; use rhema_sandbox::exec_util::shquote; @@ -233,9 +234,16 @@ pub async fn terminal( user: AuthUser, State(state): State, Path(room): Path, + headers: HeaderMap, ws: WebSocketUpgrade, ) -> AppResult { + if !super::websocket_origin_ok(&state.config, &headers) { + return Err(AppError::forbidden("websocket origin does not match")); + } member_of(&state, &room, &user.user.id)?; 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) + })) } diff --git a/src/api/messages.rs b/src/api/messages.rs index de85230..84f0d74 100644 --- a/src/api/messages.rs +++ b/src/api/messages.rs @@ -7,6 +7,7 @@ use std::time::Duration; use axum::Json; use axum::extract::ws::{Message as WsMessage, WebSocket, WebSocketUpgrade}; use axum::extract::{Path, Query, State}; +use axum::http::HeaderMap; use axum::response::Response; use axum::response::sse::{Event as SseEvent, KeepAlive, KeepAliveStream, Sse}; use futures::{SinkExt, Stream, StreamExt}; @@ -130,7 +131,15 @@ pub async fn events( Query(query): Query, ) -> AppResult>> { 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 // the two is then either in the backlog or on the feed, never lost. let mut rx = state.hub.subscribe(&state.db, &room); @@ -161,21 +170,37 @@ pub async fn events( let data = serde_json::to_string(&envelope).unwrap_or_else(|_| "{}".into()); yield Ok(SseEvent::default().id(envelope.seq.to_string()).data(data)); } + let mut access = tokio::time::interval(Duration::from_secs(2)); loop { - match rx.recv().await { - Ok(envelope) => { - if envelope.seq <= last { - continue; + tokio::select! { + _ = access.tick() => { + if member_of(&state, &room, &user_id).is_err() { + break; } - last = envelope.seq; - let data = serde_json::to_string(&envelope).unwrap_or_else(|_| "{}".into()); - yield Ok(SseEvent::default().id(envelope.seq.to_string()).data(data)); } - Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => { - let data = json!({ "seq": last, "kind": "lag", "data": {} }).to_string(); - yield Ok(SseEvent::default().event("lag").data(data)); + message = rx.recv() => { + match message { + Ok(envelope) => { + if member_of(&state, &room, &user_id).is_err() { + break; + } + if envelope.seq <= last { + continue; + } + last = envelope.seq; + let data = serde_json::to_string(&envelope).unwrap_or_else(|_| "{}".into()); + yield Ok(SseEvent::default().id(envelope.seq.to_string()).data(data)); + } + 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(); + yield Ok(SseEvent::default().event("lag").data(data)); + } + Err(tokio::sync::broadcast::error::RecvError::Closed) => break, + } } - Err(tokio::sync::broadcast::error::RecvError::Closed) => break, } } }; @@ -192,13 +217,24 @@ pub async fn presence( user: AuthUser, State(state): State, Path(room): Path, + headers: HeaderMap, ws: WebSocketUpgrade, ) -> AppResult { + 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)?; - 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 peer = Peer { 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 _ = send_presence(&mut sink, &snapshot).await; let mut ping = tokio::time::interval(Duration::from_secs(25)); + let mut access = tokio::time::interval(Duration::from_secs(2)); loop { tokio::select! { + _ = access.tick() => { + if member_of(&state, &room, &account).is_err() { + break; + } + } message = source.next() => { match message { Some(Ok(WsMessage::Text(text))) => { @@ -230,6 +272,9 @@ async fn presence_loop(socket: WebSocket, state: Shared, room: String, member: M } } _ = ping.tick() => { + if member_of(&state, &room, &account).is_err() { + break; + } if sink.send(WsMessage::Ping(Vec::new().into())).await.is_err() { break; } diff --git a/src/api/mod.rs b/src/api/mod.rs index e0e8ce9..158787f 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -4,13 +4,14 @@ pub mod auth; pub mod files; pub mod messages; +pub mod profile; pub mod rooms; pub mod settings; use axum::Router; use axum::body::Body; -use axum::extract::{Request, State}; -use axum::http::{HeaderValue, StatusCode, Uri, header}; +use axum::extract::{DefaultBodyLimit, Request, State}; +use axum::http::{HeaderMap, HeaderValue, StatusCode, Uri, header}; use axum::middleware::{self, Next}; use axum::response::{Html, IntoResponse, Response}; use axum::routing::{delete, get, post}; @@ -28,6 +29,13 @@ pub fn router(state: Shared) -> Router { .route("/register", post(auth::register)) .route("/login", post(auth::login)) .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( "/provider-configs", get(settings::list_providers).post(settings::create_provider), @@ -72,6 +80,27 @@ pub fn router(state: Shared) -> Router { .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. /// Setup, login, registration, and joining with an invite happen before /// the client has a CSRF cookie. @@ -122,6 +151,12 @@ async fn headers(State(state): State, request: Request, next: Next) -> R HeaderValue::from_static("strict-origin-when-cross-origin"), ); 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() { Some(source) => format!("'self' {source}"), None => "'self'".to_owned(), diff --git a/src/api/profile.rs b/src/api/profile.rs new file mode 100644 index 0000000..4ac41cb --- /dev/null +++ b/src/api/profile.rs @@ -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, + Path(account): Path, +) -> AppResult { + 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>(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, + body: Bytes, +) -> AppResult> { + 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) -> AppResult> { + 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""), + None + ); + assert_eq!(image_mime(b"RIFF\0\0\0\0WAVEfmt "), None); + assert_eq!(image_mime(b""), None); + } +} diff --git a/src/api/rooms.rs b/src/api/rooms.rs index fe46c62..f7528d2 100644 --- a/src/api/rooms.rs +++ b/src/api/rooms.rs @@ -88,8 +88,10 @@ fn load_members(state: &Shared, room: &str) -> AppResult> { let online = state.presence.online(room); let conn = state.db.conn(); let mut stmt = conn.prepare( - "SELECT id, account_id, display_name, role, color FROM members - WHERE room_id = ?1 ORDER BY created_at ASC", + "SELECT m.id, m.account_id, m.display_name, m.role, m.color, + (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| { Ok(Member { @@ -98,6 +100,7 @@ fn load_members(state: &Shared, room: &str) -> AppResult> { display_name: row.get(2)?, role: row.get(3)?, color: row.get(4)?, + avatar_updated_at: row.get(5)?, online: false, }) })?; @@ -504,6 +507,18 @@ pub async fn join( return Err(AppError::gone("this invite has expired")); } 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 mut new_session = false; let account = match existing { @@ -522,6 +537,7 @@ pub async fn join( handle, display_name, kind: "guest".into(), + avatar_updated_at: None, } } }; @@ -559,8 +575,8 @@ pub async fn join( } }; state.db.conn().execute( - "UPDATE invites SET used_at = ?1, used_by = ?2 WHERE token_hash = ?3", - rusqlite::params![now_ms(), account.id, sha256_hex(token.as_bytes())], + "UPDATE invites SET used_by = ?1 WHERE token_hash = ?2", + rusqlite::params![account.id, token_hash], )?; let cookies = if new_session { let raw = auth::create_session(&state, &account.id)?; diff --git a/src/api/settings.rs b/src/api/settings.rs index 1dbdee2..aa48de4 100644 --- a/src/api/settings.rs +++ b/src/api/settings.rs @@ -257,6 +257,7 @@ pub async fn delete_target( "DELETE FROM sandbox_targets WHERE id = ?1 AND account_id = ?2", rusqlite::params![id, user.user.id], )?; + state.previews.forget(&id); Ok(Json(json!({ "ok": true }))) } diff --git a/src/auth.rs b/src/auth.rs index 51e0e1e..97e28d1 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -58,7 +58,8 @@ pub fn user_from_token(state: &Shared, token_hash: &str) -> Option { .db .conn() .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 WHERE s.token_hash = ?1", rusqlite::params![token_hash], @@ -69,6 +70,7 @@ pub fn user_from_token(state: &Shared, token_hash: &str) -> Option { handle: row.get(1)?, display_name: row.get(2)?, kind: row.get(3)?, + avatar_updated_at: row.get(5)?, }, row.get::<_, i64>(4)?, )) @@ -105,6 +107,13 @@ pub fn hash_password(password: &str) -> AppResult { .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 = 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. pub fn verify_password(stored: &str, password: &str) -> bool { let Ok(hash) = PasswordHash::new(stored) else { diff --git a/src/config.rs b/src/config.rs index 814093e..ae550d1 100644 --- a/src/config.rs +++ b/src/config.rs @@ -31,7 +31,7 @@ pub struct Config { pub allowed_frame_ancestors: Vec, /// Whether anyone may create an account. Off leaves setup and /// invites as the only doors. - #[serde(default = "default_true")] + #[serde(default)] pub allow_registration: bool, } @@ -39,10 +39,6 @@ fn default_steps() -> u32 { 48 } -fn default_true() -> bool { - true -} - impl Default for Config { fn default() -> Self { Self { @@ -54,7 +50,7 @@ impl Default for Config { web_dir: PathBuf::from("web/.output/public"), max_turn_steps: default_steps(), allowed_frame_ancestors: Vec::new(), - allow_registration: true, + allow_registration: false, } } } diff --git a/src/crypto.rs b/src/crypto.rs index 61673f4..e22c652 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -1,6 +1,7 @@ //! Symmetric protection for the credentials the server stores: provider //! API keys and ssh private keys. The key comes from a 0600 file. +use std::io::Write; use std::path::Path; use base64::Engine; @@ -22,6 +23,11 @@ impl Secrets { /// bytes nor base64 for 32 bytes is refused. pub fn load_or_create(path: &Path) -> anyhow::Result { 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)?; decode_key(&raw)? } else { @@ -31,12 +37,15 @@ impl Secrets { use rand::RngCore; let mut key = [0u8; 32]; 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)] { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); } + let mut file = options.open(path)?; + file.write_all(&key)?; key }; use sha2::{Digest, Sha256}; diff --git a/src/db.rs b/src/db.rs index cb29c56..191ae52 100644 --- a/src/db.rs +++ b/src/db.rs @@ -63,6 +63,13 @@ CREATE TABLE IF NOT EXISTS accounts ( created_at INTEGER NOT NULL ) 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 ( token_hash TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, diff --git a/src/models.rs b/src/models.rs index 2c46d4f..44403ea 100644 --- a/src/models.rs +++ b/src/models.rs @@ -52,6 +52,7 @@ pub struct Member { pub display_name: String, pub role: String, pub color: String, + pub avatar_updated_at: Option, pub online: bool, } @@ -62,6 +63,8 @@ pub struct User { pub handle: String, pub display_name: String, pub kind: String, + /// When the account last replaced its picture, or `None`. + pub avatar_updated_at: Option, } /// One server-sent event. Durable events are also rows in `events`; diff --git a/src/preview.rs b/src/preview.rs index 2fb6a45..89ff634 100644 --- a/src/preview.rs +++ b/src/preview.rs @@ -43,7 +43,7 @@ impl PreviewTunnels { .insert(target.to_owned(), handle); } - fn forget(&self, target: &str) { + pub(crate) fn forget(&self, target: &str) { self.handles .lock() .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}")) } +/// 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. pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResult { 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", )); }; - 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 .preview_origin .split_once("://") @@ -93,23 +98,44 @@ pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResu .map(|(_, value)| format!(":{value}")) .unwrap_or_default(); Ok(format!( - "{scheme}://r{room}-p{port}-{signature}.{domain}{port_part}/" + "{scheme}://r{room}-p{port}-{expires}-{signature}.{domain}{port_part}/" )) } -/// Splits `r-p-` from the Host header. -fn target_of_host(config: &Config, host: &str) -> Option<(String, u16, String)> { +/// Splits `r-p--` from the Host header. +fn target_of_host(config: &Config, host: &str) -> Option<(String, u16, i64, String)> { let (_, domain) = domain(config)?; let name = host.split(':').next().unwrap_or(host); let label = name.strip_suffix(&format!(".{domain}"))?; let rest = label.strip_prefix('r')?; - let (room, port) = rest.rsplit_once("-p")?; - let (port, signature) = port.rsplit_once('-')?; - if room.is_empty() || signature.is_empty() { + let (room, rest) = rest.rsplit_once("-p")?; + let mut fields = rest.split('-'); + 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; } - let port: u16 = port.parse().ok()?; - Some((room.to_owned(), port, signature.to_owned())) + Some((room.to_owned(), port, expires, 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 @@ -121,20 +147,25 @@ pub async fn proxy(state: Shared, request: Request) -> Response { .and_then(|value| value.to_str().ok()) .unwrap_or("") .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(); }; - let expected = state.secrets.sign(&format!("{room}:{port}")); - if signature != expected { + if expires < crate::util::now_ms() / 1000 { + 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(); } match try_proxy(&state, &room, port, request).await { - Ok(response) => response, - Err(message) => ( - StatusCode::BAD_GATEWAY, - format!("the preview did not answer: {message}"), - ) - .into_response(), + Ok(response) => no_referrer(response), + Err(message) => no_referrer( + ( + StatusCode::BAD_GATEWAY, + format!("the preview did not answer: {message}"), + ) + .into_response(), + ), } } @@ -153,7 +184,9 @@ async fn try_proxy( let handle = match state.previews.get(&target.id) { Some(handle) => handle, 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()); handle } @@ -165,7 +198,9 @@ async fn try_proxy( Ok(channel) => channel, Err(_) => { 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()); handle .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.headers_mut() = parts.headers; strip_hop_by_hop(out.headers_mut()); - Ok(out) + Ok(no_referrer(out)) } fn strip_hop_by_hop(headers: &mut HeaderMap) { @@ -225,3 +260,57 @@ fn strip_hop_by_hop(headers: &mut HeaderMap) { 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")); + } +} diff --git a/src/ssh.rs b/src/ssh.rs index 53964bc..f803daf 100644 --- a/src/ssh.rs +++ b/src/ssh.rs @@ -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( target: &TargetRow, private_key: &str, -) -> Result, String> { - let (handle, _fingerprint) = connect(target, private_key).await?; - Ok(handle) +) -> Result<(Handle, Option), String> { + connect(target, private_key).await +} + +/// 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) { + 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( @@ -95,7 +108,14 @@ async fn connect( /// Attaches a browser socket to an interactive shell in the room's /// 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 key = match state.secrets.open_str(&target.private_key_ciphertext) { 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 // server that refuses us should not become known. - 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], - ); - } + remember_host_key(&state, &target, learned); let mut channel = match connection.channel_open_session().await { Ok(channel) => channel, Err(err) => { @@ -160,8 +173,14 @@ pub async fn terminal(socket: WebSocket, state: Shared, workspace: String, targe json!({ "type": "ready" }).to_string().into(), )) .await; + let mut access = tokio::time::interval(std::time::Duration::from_secs(2)); loop { tokio::select! { + _ = access.tick() => { + if crate::api::rooms::member_of(&state, &room, &account).is_err() { + break; + } + } message = channel.wait() => { match message { Some(ChannelMsg::Data { data }) => { diff --git a/web/app/assets/css/main.css b/web/app/assets/css/main.css index 68e2b80..5d86e50 100644 --- a/web/app/assets/css/main.css +++ b/web/app/assets/css/main.css @@ -418,6 +418,7 @@ button { width: 28px; height: 28px; flex: none; + overflow: hidden; border-radius: var(--r-avatar); 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)); @@ -439,6 +440,19 @@ button { 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 { opacity: 0.45; } @@ -651,6 +665,23 @@ button { 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 { flex: 1; min-width: 0; @@ -800,6 +831,21 @@ button { 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 { display: flex; align-items: baseline; @@ -1443,6 +1489,41 @@ button { 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 { display: flex; align-items: flex-start; diff --git a/web/app/components/AppAvatar.vue b/web/app/components/AppAvatar.vue index 7591c0e..da7f42a 100644 --- a/web/app/components/AppAvatar.vue +++ b/web/app/components/AppAvatar.vue @@ -1,5 +1,5 @@ + + diff --git a/web/app/pages/room/[id].vue b/web/app/pages/room/[id].vue index 2f1f7fe..3a4e934 100644 --- a/web/app/pages/room/[id].vue +++ b/web/app/pages/room/[id].vue @@ -3,6 +3,7 @@ import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue' import type { DeltaData, Envelope, + Member, Message, MessagePage, NoticeData, @@ -87,7 +88,7 @@ const isOwner = computed( ) const memberById = computed(() => { - const map = new Map() + const map = new Map() for (const member of detail.value?.members ?? []) map.set(member.id, member) return map }) @@ -450,6 +451,13 @@ function colorFor(message: Message): string | 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) { return element.scrollHeight - element.scrollTop - element.clientHeight < 80 } @@ -651,6 +659,7 @@ onBeforeUnmount(() => { v-if="entry.kind === 'message'" :message="entry.message" :color="colorFor(entry.message)" + :avatar="avatarFor(entry.message)" />