diff --git a/CHANGELOG.md b/CHANGELOG.md index 24aaa58c..86e45444 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,21 @@ Dated history of structural work on this repo: the append-only narrative of what operating facts live in `CLAUDE.md` and the docs ([`docs/README.md`](docs/README.md)). +## [1.12.0] - 2026-12-01 + +- **People: manage accounts from the page.** The install's first user is now its admin, and their profile has a + **People** sheet: add a person, rename or delete one, create machine tokens, and connect each person's own Strava and + Garmin, without a shell. Another user becomes an admin with `user.js admin on`. +- **Password links.** The admin creates a one-time link for a person (valid 48 hours); the person opens it and chooses + their own password. The admin never knows it. `set-password` keeps working. +- **Coach view, by consent.** Each person has a **Share with my coach** switch in their profile, off by default. An + admin can open the page of a person who shares, read-only, under a banner that says whose page it is. Nothing can be + changed while viewing, and turning the switch off ends the view at once. The operator can set it for someone with + `user.js share on|off`. +- `user.js list` shows two more columns (`admin`, `shares`), and `user.js delete` refuses the only admin. +- Upgrading: nothing to do besides pulling the images; the database gains three small migrations at start. Nobody + shares until they turn it on. See [`docs/guides/several-people.md`](docs/guides/several-people.md). + ## [1.11.1] - 2026-11-30 - **Deleting a person while the server is busy leaves nothing behind.** A page build that was already waiting for that diff --git a/README.es.md b/README.es.md index 9ee0f478..5735c1aa 100644 --- a/README.es.md +++ b/README.es.md @@ -128,8 +128,8 @@ página) y la imagen `loop-web` (sirve la página). ```sh mkdir loop && cd loop - curl -fsSLO https://raw.githubusercontent.com/mralexsaavedra/loop/v1.11.1/docker/docker-compose.yml - curl -fsSL -o .env https://raw.githubusercontent.com/mralexsaavedra/loop/v1.11.1/docker/example.env + curl -fsSLO https://raw.githubusercontent.com/mralexsaavedra/loop/v1.12.0/docker/docker-compose.yml + curl -fsSL -o .env https://raw.githubusercontent.com/mralexsaavedra/loop/v1.12.0/docker/example.env mkdir -p files/import files/manuals files/documents ``` diff --git a/README.md b/README.md index bee31fe1..42217918 100644 --- a/README.md +++ b/README.md @@ -125,8 +125,8 @@ and the endpoint the iOS Shortcut sends your Apple Health data to. Three contain ```sh mkdir loop && cd loop - curl -fsSLO https://raw.githubusercontent.com/mralexsaavedra/loop/v1.11.1/docker/docker-compose.yml - curl -fsSL -o .env https://raw.githubusercontent.com/mralexsaavedra/loop/v1.11.1/docker/example.env + curl -fsSLO https://raw.githubusercontent.com/mralexsaavedra/loop/v1.12.0/docker/docker-compose.yml + curl -fsSL -o .env https://raw.githubusercontent.com/mralexsaavedra/loop/v1.12.0/docker/example.env mkdir -p files/import files/manuals files/documents ``` diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 4b8a3188..eb804352 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -50,12 +50,12 @@ services: loop-server: # the published image (Docker Hub); `docker compose up -d --build` builds it from a clone instead - image: mralexandersaavedra/loop-server:${HC_VERSION:-1.11.1} + image: mralexandersaavedra/loop-server:${HC_VERSION:-1.12.0} build: context: .. dockerfile: docker/loop-server.Dockerfile args: - VERSION: ${HC_VERSION:-1.11.1} + VERSION: ${HC_VERSION:-1.12.0} container_name: loop-server${HC_INSTANCE:+-${HC_INSTANCE}} restart: unless-stopped # SIGTERM lets in-flight requests finish for up to 10 s and stops a running build; docker waits this long @@ -132,12 +132,12 @@ services: loop-web: # the published image (Docker Hub); `docker compose up -d --build` builds it from a clone instead. The nginx # template and hosts.sh are baked in from services/loop-web (docker/loop-web.Dockerfile), never bind-mounted. - image: mralexandersaavedra/loop-web:${HC_VERSION:-1.11.1} + image: mralexandersaavedra/loop-web:${HC_VERSION:-1.12.0} build: context: .. dockerfile: docker/loop-web.Dockerfile args: - VERSION: ${HC_VERSION:-1.11.1} + VERSION: ${HC_VERSION:-1.12.0} container_name: loop-web${HC_INSTANCE:+-${HC_INSTANCE}} restart: unless-stopped # The same hardening as services/loop-web/docker-compose.yml: a read-only root filesystem; tmpfs for what the diff --git a/docker/example.env b/docker/example.env index e068071e..e0c14e7a 100644 --- a/docker/example.env +++ b/docker/example.env @@ -2,7 +2,7 @@ # and is never committed (docker/.gitignore). # The image tag: mralexandersaavedra/loop-server: and mralexandersaavedra/loop-web: -HC_VERSION=1.11.1 +HC_VERSION=1.12.0 # Empty for the first install; a short name (e.g. second) for another install on the same host HC_INSTANCE= diff --git a/docs/development.md b/docs/development.md index 1a4e84af..60d7a1d6 100644 --- a/docs/development.md +++ b/docs/development.md @@ -87,7 +87,7 @@ test fails (`e2e/.report/`, `e2e/.results/`, both gitignored). | Project | What it opens | Specs | | --- | --- | --- | | `static-phone` (Pixel 7), `static-desktop` (1280 × 800), `webkit-static` (iPhone 15), `webkit-static-es` (iPhone 15, the page built in Spanish, `es-ES` browser) | the example page (tracked seeds + the synthetic demo extract), built by `e2e/global-setup.mjs` into `web/.e2e-dist/-example/` (one per locale) and opened from `file://`, so every LAN-only feature is off | `e2e/static/`: tabs, dock, keys `1`–`4` and `?`, the URL hash and every deep link (`#detail/[/]`, view keys, `#d=`, `#monitor`), every visible card's detail sheet on every tab and the ways to close it, the sheet's controls (day, range, window, month, info, learn more, history fold, trend), the ⓘ notes, tab links and folds, both Customize sheets (hide, move, kept after a reload), the Tonight, session and journal-insights views, the profile sheet, the day stepper, layout on both sides of the 900 px breakpoint; in `webkit-static-es` the same specs against the Spanish copy (``, month and date wording) | -| `lan-setup` → `lan-phone` (Pixel 7) → `webkit-lan` (iPhone 15, the same specs, after `lan-phone` because specs own whole days of the shared database) → `lan-last` (Pixel 7); only with `TEST_DATABASE_URL` (`E2E_LAN=0` leaves them out of a run) | the personal page a real data service builds and serves: [`e2e/lan/stack.mjs`](../e2e/lan/stack.mjs) (Playwright's `webServer`) creates a fresh empty database on that Postgres, seeds a synthetic Health extract ending today (the demo generator), runs `services/loop-ingest` in container mode (its real migrations, `scripts/refresh.mjs` building the page into a temporary `HC_SITE_DIR`) and an nginx stand-in on `127.0.0.1:18290` (`E2E_LAN_PORT`) that mirrors loop-web's template: the page, `status.json` and the manuals are asked of the service's `GET /site` and its `X-Accel-Redirect` is followed into the same `/_open/` and `/_user/` file patterns with the same headers (`/users/…` and everything else is a `404`; with the service down it falls back to the owner's files only while the open-mode marker exists, else `503`), and it proxies exactly the `/api` routes with their rewrites and headers (`scripts/loop-web-config.test.mjs` checks the stand-in against the template and runs it against a fake service); the shared stack stays in open mode, and `e2e/lan/multi-user.spec.mjs` boots its OWN second stack (its own database and port, `startStack({ port })`, passwords set with `runUserScript`) behind a login: signed-out visitor, own page, `/users/2/` 404; everything (processes, database, folders, a build lock a killed build left) is removed on exit, also when it is stopped during startup | `e2e/lan/`: the first-run assistant end to end (`lan-setup`) and its branches (back, Enter, refused steps, the pregnancy and under-18 stops, the medical / eating limits, maintain / cut / bulk, the adjust grid, a failed save, Later, the Edit chip); the food log (quick, basic, product and recipe entries, past days, per-meal add, the add sheet's keyboard, Atwater and Save anyway, 500 / 429 / offline saves, a failed day load and its retry, the empty day, delete); products (label, barcode and text search with Open Food Facts stubbed at the page's `/api/food/off`, log by serving, edit, archive, field errors, cancel); recipes (several products, a basic, batch, edit, archive, cancel); the journal (answers read back, another day, the drink stepper, a failed save, behaviours off and on, insights); the profile (goal, target weight, a refused save); the "+" menu, the freshness popover, Sync and its failures; Home on a past day with the server's data; and last (`lan-last`) the language switch, which rebuilds the shared page in the other locale and, between the two switches, logs and deletes a food entry and saves the journal in that language | +| `lan-setup` → `lan-phone` (Pixel 7) → `webkit-lan` (iPhone 15, the same specs, after `lan-phone` because specs own whole days of the shared database) → `lan-last` (Pixel 7); only with `TEST_DATABASE_URL` (`E2E_LAN=0` leaves them out of a run) | the personal page a real data service builds and serves: [`e2e/lan/stack.mjs`](../e2e/lan/stack.mjs) (Playwright's `webServer`) creates a fresh empty database on that Postgres, seeds a synthetic Health extract ending today (the demo generator), runs `services/loop-ingest` in container mode (its real migrations, `scripts/refresh.mjs` building the page into a temporary `HC_SITE_DIR`) and an nginx stand-in on `127.0.0.1:18290` (`E2E_LAN_PORT`) that mirrors loop-web's template: the page, `status.json` and the manuals are asked of the service's `GET /site` and its `X-Accel-Redirect` is followed into the same `/_open/` and `/_user/` file patterns with the same headers (`/users/…` and everything else is a `404`; with the service down it falls back to the owner's files only while the open-mode marker exists, else `503`), and it proxies exactly the `/api` routes with their rewrites and headers (`scripts/loop-web-config.test.mjs` checks the stand-in against the template and runs it against a fake service); the shared stack stays in open mode, and `e2e/lan/multi-user.spec.mjs` boots its OWN second stack (its own database and port, `startStack({ port })`, passwords set with `runUserScript`) behind a login: signed-out visitor, own page, `/users/2/` 404, the admin adding a person and issuing a one-time password link, the person choosing a password through it and signing in, turning "Share with my coach" on and having no People area, the admin viewing them (banner, a refused write and its notice, back to their own page; screenshots `people-phone`, `people-person-phone`, `set-password-phone`, `set-password-done-phone`, `profile-share-phone`, `coach-banner-phone` in `e2e/.results/shots/`); everything (processes, database, folders, a build lock a killed build left) is removed on exit, also when it is stopped during startup | `e2e/lan/`: the first-run assistant end to end (`lan-setup`) and its branches (back, Enter, refused steps, the pregnancy and under-18 stops, the medical / eating limits, maintain / cut / bulk, the adjust grid, a failed save, Later, the Edit chip); the food log (quick, basic, product and recipe entries, past days, per-meal add, the add sheet's keyboard, Atwater and Save anyway, 500 / 429 / offline saves, a failed day load and its retry, the empty day, delete); products (label, barcode and text search with Open Food Facts stubbed at the page's `/api/food/off`, log by serving, edit, archive, field errors, cancel); recipes (several products, a basic, batch, edit, archive, cancel); the journal (answers read back, another day, the drink stepper, a failed save, behaviours off and on, insights); the profile (goal, target weight, a refused save); the "+" menu, the freshness popover, Sync and its failures; Home on a past day with the server's data; and last (`lan-last`) the language switch, which rebuilds the shared page in the other locale and, between the two switches, logs and deletes a food entry and saves the journal in that language | | `docker` (Pixel 7); only with `E2E_DOCKER_URL`, and then the only project | a running Docker stack's loop-web: `scripts/image-smoke.sh` with `SMOKE_BROWSER=1` points it at the stack it started | `e2e/docker/`: what only the published images can break — loop-web's security headers as served, the page clean of console errors and CSP violations, a food entry saved and deleted through nginx, Sync rebuilding the page inside loop-server | Shared rules ([`e2e/fixtures.mjs`](../e2e/fixtures.mjs), [`e2e/lan/fixtures.mjs`](../e2e/lan/fixtures.mjs)): the diff --git a/docs/guides/several-people.es.md b/docs/guides/several-people.es.md index d23d4d0d..db4cea2d 100644 --- a/docs/guides/several-people.es.md +++ b/docs/guides/several-people.es.md @@ -218,11 +218,31 @@ docker compose exec -it loop-server node services/loop-ingest/scripts/user.js de - Puedes borrar a una persona con el servidor en marcha, también mientras se construye su página: el servidor no arranca una construcción que la estuviera esperando y elimina lo que deje una construcción en curso. +## Desde la página: Personas, enlaces de contraseña y el modo entrenador + +Desde la 1.12.0 el primer usuario de la instalación es su **administrador**, y casi todo lo anterior se puede hacer +desde la página en vez de con una terminal. + +- **Personas.** El administrador abre su perfil → **Personas** → **Gestionar**. Ahí añade a una persona, la renombra o + la borra, crea tokens de máquina (se muestran una vez: cópialo en ese momento) y conecta el Strava propio de esa + persona (su id de cliente, luego el enlace de autorización, luego el secreto de cliente y el código) y su clave de + Garmin. +- **Enlace de contraseña.** En el panel de una persona, **Enlace de contraseña** crea un enlace que sirve una vez y + durante 48 horas. Se lo envías; lo abre y elige su propia contraseña. Un enlace nuevo anula el anterior. +- **Modo entrenador.** Cada persona puede activar **Compartir con mi entrenador** en su perfil (apagado por defecto). + El administrador ve entonces **Ver su página** en el panel de esa persona: la página se abre en solo lectura bajo una + barra con el botón **Volver a mi página**. Mientras se mira no se puede cambiar nada, y la persona puede dejar de + compartir cuando quiera, lo que termina la vista. +- Otro administrador: `user.js admin on` (y `off`; al único administrador no se le puede quitar). Compartir + en nombre de alguien que te lo ha pedido: `user.js share on`. + +Quien administra la instalación siempre puede leer la base de datos: el interruptor de compartir trata de lo que la +página enseña y a quién, no es una barrera frente al operador. + ## Lo que no existe -- **No hay registro propio**, ni restablecimiento de contraseña desde la página: lo hace el operador con la - herramienta. -- **No hay botón "conectar Strava"** en la página: el operador lo conecta con `strava` y `garmin`, como arriba. +- **No hay registro propio**: un administrador añade a cada persona. Una contraseña olvidada se resuelve con un enlace + de contraseña nuevo del administrador (o con `set-password`). - Una instalación en modo host (los servicios se ejecutan desde un clon) no admite contraseñas ni varias personas: usa las imágenes. diff --git a/docs/guides/several-people.md b/docs/guides/several-people.md index 5ee4106a..dd6a032f 100644 --- a/docs/guides/several-people.md +++ b/docs/guides/several-people.md @@ -209,10 +209,29 @@ docker compose exec -it loop-server node services/loop-ingest/scripts/user.js de - You can delete a person while the server is running, also while their page is being built: the server does not start a build that was waiting for them, and removes what a build in progress leaves behind. +## From the page: the People sheet, password links and the coach view + +Since 1.12.0 the install's first user is its **admin**, and most of the above can be done from the page instead of a +shell. + +- **People.** The admin opens their profile → **People** → **Manage**. There they add a person, rename or delete one, + create machine tokens (shown once: copy it then), and connect that person's own Strava (their client id, then the + authorisation link, then the client secret and the code) and Garmin key. +- **Password link.** In a person's panel, **Password link** makes a link that works once and for 48 hours. Send it to + them; they open it and choose their own password. A new link cancels the previous one. +- **Coach view.** Each person can turn on **Share with my coach** in their profile (off by default). The admin then + sees **View their page** in that person's panel: the page opens read-only under a banner with a **Back to my page** + button. Nothing can be changed while viewing, and the person can turn sharing off at any time, which ends the view. +- Another admin: `user.js admin on` (and `off`; the only admin cannot be turned off). Sharing for someone + who asked you to: `user.js share on`. + +The person who runs the install can always read the database: the sharing switch is about what the page shows and to +whom, not a barrier against the operator. + ## What is not there -- **No self sign-up**, and no password reset from the page: the operator does it with the tool. -- **No "connect Strava" button** in the page: the operator connects it with `strava` and `garmin` above. +- **No self sign-up**: an admin adds each person. A forgotten password is a new password link from the admin (or + `set-password`). - A host-mode install (the services run from a clone) does not support passwords or several people: use the images. ## Security notes diff --git a/docs/lan-services.md b/docs/lan-services.md index 5691ce20..a8dec6c6 100644 --- a/docs/lan-services.md +++ b/docs/lan-services.md @@ -138,7 +138,7 @@ the proxied routes answer `502` / `504` and the page itself is still served. Both modes serve the same page with the same nginx configuration (`services/loop-web/nginx.conf.template`, copied unchanged into the `loop-web` image), and the page is served to a person only through the service's session check ([how a page is served](#how-a-page-is-served)): gzipped (server level: the page, CSS / JS / JSON, ≥ 1 KB, level 5, `Vary`; -the six proxied data routes (`/api/sync`, `/api/sync/status`, `/api/food/`, `/api/journal/`, `/api/auth/`, +the seven proxied data routes (`/api/sync`, `/api/sync/status`, `/api/food/`, `/api/journal/`, `/api/auth/`, `/api/admin/`, `/ingest/health-auto-export`) are `gzip off` — their responses reflect request input next to stored data, a BREACH-style oracle; pinned by `scripts/loop-web-config.test.mjs`). The page is rebuilt hourly AND on demand under a **sequence protocol** (no clock comparison anywhere): @@ -178,7 +178,8 @@ BREACH-style oracle; pinned by `scripts/loop-web-config.test.mjs`). The page is plus the food log prefix `/api/food/*` → ingest `/food/*` (GET / POST / PUT / DELETE, 16 KB, the `X-HC-Food` header forwarded; see [`nutrition-food-log.md` → Security](nutrition-food-log.md#security)), the journal prefix `/api/journal/*` → ingest `/journal/*` (GET / PUT, 16 KB, the `X-HC-Journal` header forwarded; `docs/journal.md`), the login prefix `/api/auth/*` → - ingest `/auth/*` (GET / POST, 16 KB, the `X-HC-Auth` header and `X-Forwarded-Proto` forwarded; cookies pass through untouched) and EXACTLY `POST /ingest/health-auto-export` + ingest `/auth/*` (GET / POST, 16 KB, the `X-HC-Auth` header and `X-Forwarded-Proto` forwarded; cookies pass through untouched), the admin prefix `/api/admin/*` → + ingest `/admin/*` (GET / POST / PUT / DELETE, 16 KB, the `X-HC-Admin` header forwarded) and EXACTLY `POST /ingest/health-auto-export` → the same ingest route (the iOS Shortcut upload when loop-web is the public entry and ingest is not exposed: `Authorization` / `Automation-Name` / `Content-Type` forwarded, no `Bearer` token → `401` before the body is read, ingest checks the bearer, `client_max_body_size 8m` = ingest's @@ -214,8 +215,8 @@ BREACH-style oracle; pinned by `scripts/loop-web-config.test.mjs`). The page is `SETGID`; `loop-web`: `CHOWN`, `SETUID`, `SETGID`; `loop-server` / host-mode `loop-ingest`: none), `no-new-privileges`, memory / CPU / process limits and json-file logs rotated at 3 x 10 MB; `loop-web` has a healthcheck on `/nginx-health` (nginx answers it, no proxy). Details: each service's README; pinned by `scripts/loop-web-config.test.mjs`. -- **Rate limits.** nginx `limit_req` on the six proxied locations only (`429` over the burst, per client - address): `/api/sync`, `/api/sync/status`, `/api/food/*`, `/api/journal/*`, `/api/auth/*` share 10 r/s, burst 60; +- **Rate limits.** nginx `limit_req` on the seven proxied locations only (`429` over the burst, per client + address): `/api/sync`, `/api/sync/status`, `/api/food/*`, `/api/journal/*`, `/api/auth/*`, `/api/admin/*` share 10 r/s, burst 60; `/ingest/health-auto-export` 60 r/min, burst 20. The page, `status.json` and `/manuales/` are never limited (pinned by `scripts/loop-web-config.test.mjs`). - **Health + tokens.** `/healthz` stays 200 but adds `degraded: true` when Strava is configured and its @@ -288,8 +289,9 @@ BREACH-style oracle; pinned by `scripts/loop-web-config.test.mjs`). The page is `400 bad_request`; EVERY credential failure (unknown user, a user without a password, a wrong password, a username or password no user could have) is the same `401 {"error":"invalid_credentials"}`. `POST /auth/logout` → `204`, the session row deleted and the cookie cleared (`Max-Age=0`), also without a session. `GET /auth/session` → `200 - {"open":true}` in open mode, `200 {"open":false,"username":…}` with a session, `401 {"error":"unauthenticated"}` - without one. Unknown `/auth/*` path `404`, wrong method `405`. + {"open":true}` in open mode, `200 {"open":false,"username":…,"admin":…,"sharing":…}` with a session (`admin`: this user may + manage users and view the people who share; `sharing`: this user's consent to be viewed; both are read with the + session on every request, so a change holds at once), `401 {"error":"unauthenticated"}` without one. Unknown `/auth/*` path `404`, wrong method `405`. - **Session cookie** `hc_session`: 32 random bytes (base64url), `HttpOnly; SameSite=Lax; Path=/; Max-Age=2592000` and `Secure` when the browser used HTTPS. HTTPS is read from `X-Forwarded-Proto: https` only, which loop-web's nginx sets (`$hc_forwarded_proto`: the tunnel's own `https`, else the scheme nginx saw); a client reaching the @@ -327,8 +329,10 @@ BREACH-style oracle; pinned by `scripts/loop-web-config.test.mjs`). The page is `docker compose exec loop-server node services/loop-ingest/scripts/user.js …`): `add ` (no password: it cannot sign in), `set-password ` (asked twice without echo on a terminal, `-it`; with a piped stdin the whole input minus one trailing newline, `printf '%s' "$PW" | docker compose exec -T loop-server node … set-password andrea`; - never an argument; ends every session of that user), `list` (usernames, whether a password is set, created date; - never a hash), `rename ` (only the name changes: sessions, tokens and data keep working; a taken name is + never an argument; ends every session of that user), `list` (usernames, whether a password is set, created date, + admin, shares; never a hash), `admin on|off` (the admin flag of `sql/026`: the install's first user is the + admin after the migration; the only admin is never turned off) and `share on|off` (that user's consent to + be viewed read-only by the admins, off for every new user), `rename ` (only the name changes: sessions, tokens and data keep working; a taken name is refused), `delete ` (the user and **every** row and folder of theirs, **never undoable**: dump the database first; one transaction over every table of `IMPORT_TABLES`, then the folders `users//` under the data root, the site folder and the files folder, whose path is printed to remove by hand when it is read-only; the owner, user 1, is never @@ -336,6 +340,56 @@ BREACH-style oracle; pinned by `scripts/loop-web-config.test.mjs`). The page is `--dry-run` lists the rows per table and the folders and deletes nothing), and the `token` commands of the [machine tokens](#machine-tokens) below. Setting the first password ends open mode. A restart with NO password left (for example after restoring a backup taken before any password existed) starts in open mode again: every person route then acts for user 1 without a login, and the start-up log says `"mode":"open"`; set a password again before exposing the server. + - **Admin routes** (`src/admin-routes.js`, `/admin/*`, from the page `/api/admin/*`): the user management of the + script, for a signed-in **admin** (`app_user.is_admin`, `sql/026`: the install's first user after the migration; + `user.js admin on|off` for anybody else). Only a session counts: open mode is `403 login_required`, no + session `401`, a session that is not an admin `403 forbidden`, and a machine token or a run credential is never an + admin. The role is read with the session on every request. `GET /admin/users` (username, whether a password is set, + admin, sharing, created, `owner`, `self`; never a hash), `POST /admin/users {username}` (`201`; `409 + username_taken`, `400 invalid_username`), `PUT /admin/users/ {username}` (rename), `DELETE /admin/users/ + {confirm: }` (everything of that user, **never undoable**; `403 owner_never_deleted` for user 1, `403 + cannot_delete_self`, `400 confirmation_mismatch`; answers `{deleted, manual}` where `manual` lists a folder it could + not remove, the read-only files folder of the default install), `GET` / `POST /admin/users//tokens` (`POST + {label}` answers `{id, token}`: the token is in that one answer and nowhere else, only its hash is stored) and + `DELETE /admin/tokens/` (`204`). Strava and Garmin of any user: `GET /admin/users//providers` (`{strava, + garmin, garminExpires}`: what is connected, never a secret), `POST /admin/strava/authorize-url {clientId}` (`{url}`, + the address that person opens signed in to THEIR Strava), `PUT /admin/users//strava {clientId, clientSecret, + code}` (the user's own API app; `code` is the code or the whole redirected address; `200 {athlete, scope}`; `400 + invalid_client_id` / `invalid_client_secret` / `no_code`, `502 strava_refused` / `strava_no_refresh_token` / + `strava_unreachable`; nothing is stored on a failure and Strava's own text is never passed on), `PUT + /admin/users//garmin {apiKey, expires}` (`expires` a `YYYY-MM-DD` date or `''`; `204`) and `DELETE` on both + (`204`). A stored secret is never answered by any route, and a connection made or removed here holds for that + user's next sync at once. Same layers as the login routes with the header `X-HC-Admin: 1`; every change is + one log event with the admin's and the target's username, never a token. The rules shared with the script (token + label, token issue, the order of a delete, what a pasted secret may be, the Strava connection) live once in + `src/user-admin.js`; Strava's authorization steps are `src/strava-oauth.js`. + - **Password links** (`src/password-links.js`, `sql/027`): so that an admin never knows a password, `POST + /admin/users//password-link` answers `201 {token, expires}`, a one-time link token (`hcp_` + 32 random bytes; + only its SHA-256 is stored) valid for 48 hours; a user has at most one, a new one cancels the old one. Whoever holds + it sets that user's password once with `POST /auth/password {token, password}` → `204` (no session needed and none + started): the password is set, every session of that user ends and the link is deleted, in one statement, so two + requests with the same link cannot both win. `400 invalid_password` (12 to 256 characters; the link stays usable), + `410 invalid_link` for a link that is unknown, expired, used or malformed (one answer for all, and decided before any + password hashing). The route shares the login's per-address budget. Neither a link nor a password is ever logged. + The page puts the token in the address's fragment (`/#set-password=`), which browsers never send to a server. + - **Coach view** (`sql/026` + `sql/028`, `src/sessions.js`): an admin can look, **read-only**, at the page and data of + a person who agreed to it. Consent is `app_user.share_with_coach`, off for every new user: the person switches it + with `POST /auth/sharing {sharing}` (their own session only; the operator can set it for them with `user.js share + on|off`). `POST /auth/view {username}` starts the view on the admin's session (`403 not_shared` for + anything else: not an admin, no such user, a user who does not share, yourself; one answer), `POST /auth/unview` + ends it, and `GET /auth/session` says `viewing`. While a session views somebody: + every route a person uses (`/food/*`, `/journal/*`, `GET /sync/status`, the page, `status.json` and the manuals + through `GET /site`) answers the **viewed** user's data, and **every request that is not a `GET` or `HEAD` is `403 + {"error":"read_only"}`, whatever the route** (`/auth/*` excepted, so the view and the session can be ended): one + check in `server.js` before every other route, so a route added later cannot forget it, and `identify()` refuses + the same request again as a backstop. The view counts only while the viewer is an admin, the viewed user shares and + is somebody else; the three conditions are in the query that reads the session, so consent taken back, or a role + removed, ends the view at the very next request. It ENDS: the same statement that takes consent back (or removes + the role) clears the view from the sessions that had it, so giving consent again later starts nothing by itself. + While a session views somebody the `/admin/*` routes answer `403 viewing`, reads included. It lives on the session row: per browser, gone at sign-out, and + cleared when the viewed user is deleted. Starting a view is logged (`view_started`, who and whom). The server's + owner can always read the database: the switch is about what the page shows and to whom, not a technical barrier + against the person who runs the install. - **A second user is safe to add** now that [each person is served only their own page](#how-a-page-is-served): the page, `status.json` and the manuals go through the service's session check, and `/users//…` is not reachable by URL. What is still **per install** (not per user): the install defaults (`HC_LOCALE`, `HC_VERSION`); the provider accounts are per user diff --git a/docs/plan-page.md b/docs/plan-page.md index 9fa2f854..ad2b4f92 100644 --- a/docs/plan-page.md +++ b/docs/plan-page.md @@ -246,6 +246,7 @@ read these instead of redefining them (a test guards it). Tests load it with `we | `jsonApi(base, header, timeoutMs)` | THE fetch wrapper of the LAN JSON APIs (`food-core.ts`: `/api/food` + `X-HC-Food`, `journal.ts`: `/api/journal` + `X-HC-Journal`): `api(method, path, body?)` resolves a 2xx's JSON (`{}` without one), rejects `{code, field, status}` (`offline` / status 0 with no answer, a timeout or `file://`); built on `fetchTimeout`, the body read inside its timeout | | `fetchTimeout(url, init, ms, read?)` | THE timed fetch (`jsonApi`, `freshness.ts` via `fetchJson`, `profile.ts`'s `/manuales/` probe at 10 s): rejects `{name: 'TimeoutError'}` after `ms` and aborts the request (`AbortController` when present), so a hung service never leaves the Sync button busy. `read(res)` reads the body inside the same timeout (a stalled body times out too) and its result resolves. The caller's `init` is copied, never mutated; a caller `init.signal` is combined with the timeout's (`AbortSignal.any`, else relayed by hand) and its abort rejects at once with `{name: 'AbortError'}` | | `onUnauthenticated(fn)` | `fn` runs when ANY `/api/` call answers `401 {error: 'unauthenticated'}` (the session ended; the body is read on a clone, so the caller still gets the answer). `/api/auth/*` is excluded (its 401 is a wrong password), and nothing else notifies, so open mode, a 404 and a 5xx are untouched. One hook in `fetchTimeout`, so food, journal, settings, sync and freshness are all covered; its only listener is the sign-in sheet ([below](#sign-in-sheet)) | +| `onReadOnly(fn)` | the coach view's twin of `onUnauthenticated`: `fn` runs when ANY `/api/` call answers `403 {error: 'read_only'}` (the session is viewing another person, [below](#coach-view-banner-and-notice); the body is read on a clone). Same exclusions: `/api/auth/*` and anything outside `/api/` never notify, and a `403` with another error is untouched. One hook in `fetchTimeout`; its only listener is `signin.ts`, which writes the notice into the banner | | `fetchJson(url, init, ms)` | `fetchTimeout` + the JSON body of a 2xx (`null` otherwise), read inside the timeout: `freshness.ts`'s status reads + Sync POST at 15 s | | `esc` (`null` / `undefined` → `''`), `format`, `isoDate`, `todayIso`, `daysOld`, `shiftIso`, `MS_PER_DAY`, `STALE_DAYS` | string / ISO date helpers, constants | | `nf`, `num`, `int`, `pct`, `hours`, `duration` (h:mm), `numInput` (an input's value, never grouped) | thin wrappers adding the page `LOCALE` to `HC_FMT` | @@ -313,7 +314,7 @@ LOOP's own login ([`lan-services.md`](lan-services.md) → Login). It asks `GET | Answer | State | Page | | --- | --- | --- | | `200 {open: true}` | `open` (no user has a password: single-user mode) | as always; no sheet, no Sign out | -| `200 {open: false, username}` | `signedin` | as always; the profile sheet shows Sign out ([`profile.md`](profile.md)) | +| `200 {open: false, username, admin, sharing, viewing}` | `signedin` | as always; the profile sheet shows Sign out, the sharing switch and, for an admin, People ([`profile.md`](profile.md)); `viewing` set = the [coach view](#coach-view-banner-and-notice) | | `401` | `signedout` | the sign-in sheet opens | | anything else (404 from a server without `/auth`, 5xx, no answer, an odd body) | `unknown` | as always | @@ -331,6 +332,33 @@ case but `401` the page is exactly as it was before the login existed. the field the moment the form is submitted and lives only in one local variable: never in storage, the state or a global. On success the page reloads, which loads the live data exactly as a normal load does. - **Sign-out** lives in the profile sheet (`HCAuth.signOut()`, `POST /api/auth/logout`), then the sheet opens. +- **State and methods.** `HCAuth.state()` is `{status, username, admin, sharing, viewing}`: `admin` and `sharing` are booleans, `viewing` + is the viewed person's username or `null`; a server that predates them (or an odd value) means `false` / `false` / `null`, and + they are `false` / `false` / `null` outside `signedin`. `onChange` listeners hear a change of any of them. Beside `check()` and + `signOut()`: `setSharing(on)` (`POST /api/auth/sharing {sharing}`, resolves the saved value; the profile's switch), `view(name)` + (`POST /api/auth/view {username}`) and `unview()` (`POST /api/auth/unview`): after a successful `view` / `unview` the page + reloads, because the HTML itself belongs to another person; all three reject `{code, status}` on a failure. +- **Set-password mode.** The address fragment `#set-password=` (`^hcp_[A-Za-z0-9_-]{43}$`; the fragment never reaches a + server, [`lan-services.md`](lan-services.md) → Password links) turns the sign-in sheet / [sign-in page](#the-sign-in-page) + into a "Choose your password" form: two password fields (`new-password` autofill hints) with ONE show / hide control, 12 to + 256 characters and both equal (checked in the page, nothing is sent and the text stays on a mistake), then `POST + /api/auth/password {token, password}` with the `X-HC-Auth` header. `204` → the fragment is removed (`history.replaceState`) + and the normal form shows with "Password set. Sign in." (no session is started). Errors: `400 invalid_password`, `410 + invalid_link` ("This link is no longer valid. Ask for a new one."), `429 rate_limited`, offline, anything else generic; the + fields are cleared and the link is kept until it is spent. The token lives in one local variable: never logged, stored, + put in another URL, the state or a global (guarded in `signin.test.mjs`). + +#### Coach view: banner and notice + +While `viewing` is set (an admin looking, read-only, at a person who shares, [`lan-services.md`](lan-services.md) → Coach view) +`signin.ts` puts a banner as the FIRST element of `` (`#hc-coach`, `.coach-bar` in `profile.css`): "Viewing {name} · +read-only" and a "Back to my page" button (`HCAuth.unview()`, then the reload). It is in flow, so it covers nothing at rest, and +sticky, so it stays while scrolling; its top padding is the iOS safe area; it sits under the detail sheets (z 59, they are +full-screen) and the mini dial slides in below it (`html.coach-on`). Every write is refused by the server (`403 read_only`); +the page does not disable its controls: `HC.onReadOnly` makes the banner's text read "Read-only: you are viewing {name}'s +page." for five seconds (a live region, `#coach-txt`) instead of a generic failure. A refused write on a page that did not know +it was a view asks the session once and draws the banner. The sharing switch and the People area are not drawn while viewing. +Per-browser state: see [`profile.md`](profile.md) → Per-browser storage and the coach view. - The static page is not served without a session either: a visitor with no session gets the data-free [sign-in page](#the-sign-in-page) instead ([`lan-services.md` → How a page is served](lan-services.md#how-a-page-is-served)). diff --git a/docs/profile.md b/docs/profile.md index 79fd7714..b69ea9fc 100644 --- a/docs/profile.md +++ b/docs/profile.md @@ -39,7 +39,7 @@ A Strava / WHOOP-style profile, honest data only. ## The profile sheet -Order: header → goal → upcoming events → Body → Gear → Devices → Supplements → Strava → Account (only with a login on the server, below). +Order: header → goal → upcoming events → Body → Gear → Devices → Supplements → Strava → Account (only with a login on the server, below; for an admin it leads to the [People](#people-admin-only) sheet). ### Goal setting @@ -90,7 +90,69 @@ LOOP's own login ([`lan-services.md`](lan-services.md) → Login) has a page sid not answer, the section says so and the session stays. The section is drawn ONLY for that answer: open single-user mode (`{open: true}`, no password exists yet), a server that predates `/auth` (404), no answer, a page opened from a file and the example / demo build have no session, so the sheet is exactly as before. A sheet drawn before the session answer -(a `#profile` link) is drawn again when it arrives. Copy: `account` in `web/src/i18n/profile-templates.mjs`. +(a `#profile` link) is drawn again when it arrives (and again when who / admin / viewing changes; a sharing change is saved in +place). Copy: `account` in `web/src/i18n/profile-templates.mjs`. + +Two more rows, both hidden while the session is **viewing** somebody (they belong to the signed-in person, not to the page shown): + +- **Share with my coach** (`Compartir con mi entrenador`), for every signed-in person: a switch (`HC.switchBtn`, `role="switch"`) + with a one-line hint (it lets the admin see your page, read-only; turn it off any time). A tap calls `HCAuth.setSharing` + (`POST /api/auth/sharing`); the line below says "Saving…", "Saved" or "Not saved: {reason}" in the goal section's words and the + switch only flips once the server said so. Off for new people ([`lan-services.md`](lan-services.md) → Coach view). +- **People** (`Personas`) with a **Manage** button, for an admin only (`HCAuth.state().admin`): it opens the People sheet. + +### People (admin only) + +`registerView('people')` in `web/src/client/profile.ts`, its own sheet (opened from the Account row, so the profile stays short +and a phone gets one task per screen; copy `people` in `profile-templates.mjs`, es + en; no module of its own: a new script +would need the manifest and the baked copy). It does what `/api/admin/*` offers ([`lan-services.md`](lan-services.md) → Admin +routes, password links), through `HC.jsonApi('/api/admin', 'X-HC-Admin', …)`; usernames go into paths with +`encodeURIComponent`, a non-admin (or a viewing admin) sees "Only an admin can manage people." and the page makes no request. + +Layout: two cards, like the profile's own sections. The first lists everybody; a person's **Manage** opens their panel +right under THEIR row (`#pp-panel`, one slot that follows the open row; that row's button becomes **Close**), as an inset +card (`.pp-panel`). The panel starts with the everyday actions (View their page when they share, Password link); what is +rare (Rename, Machine tokens, Strava and Garmin, Delete) waits in closed folds (`details.pp-fold`), so opening a person +shows a few lines, not every form. The second card adds a person. The status line (`#pp-msg`) is at the top of the list. + +- **List** (`GET /users`): the username with small badges (Owner, You, Admin, No password yet, Shares) and **Manage**; **Add a + person** (`POST /users {username}`) opens that person's panel. +- **A person's panel** (one at a time, under the list): + **View their page** (only when they share and are not you: `HCAuth.view`, which reloads into the [coach view](plan-page.md#coach-view-banner-and-notice)); + **Password link** (`POST /users//password-link` → the page's own address + `#set-password=` in a read-only field + with **Copy** and the expiry; shown ONCE, held in memory only and dropped at the next action; the admin never sees a password); + **Rename** (`PUT /users/`); **Machine tokens** (`GET` / `POST /users//tokens {label}`: the token is shown once with + Copy; `DELETE /tokens/` revokes); **Strava** (client id → `POST /strava/authorize-url` → a link to open signed in to THEIR + Strava, only an `https:` address is ever drawn → client secret + pasted code or redirected address → `PUT /users//strava`; + **Remove** = `DELETE`); **Garmin** (`PUT /users//garmin {apiKey, expires}`, `expires` a `YYYY-MM-DD` date or `''`; **Remove**); + **Delete** (not offered for the owner or yourself: the admin types the username again, `DELETE /users/ {confirm}`; the + `manual` folders it could not remove are listed). +- **Secrets** are `type="password"` fields with `autocomplete="off"`, cleared after every use (success or not) and never written + back into the page; a stored secret is never answered by any route. Nothing of People touches `localStorage`. +- **Errors**: every code the routes document has its own readable line (`people.errors`: `invalid_username`, `username_taken`, + `confirmation_mismatch`, `strava_refused`, `strava_unreachable`, …, plus `forbidden`, `login_required`, `read_only`, + `rate_limited`, `offline`); an unknown code reads as a generic line, never the raw code. One request at a time. +- Not a deep link: `people` is not in `lib/nav/tabs.mjs` `VIEW_TAB`, so a reload on `#people` lands on the default tab. + +### Per-browser storage and the coach view + +The page keeps a few per-browser conveniences in `localStorage` / `sessionStorage` under keys that are NOT per person. +Two kinds: + +- **The person's data** (`nutri-day.ts`: `hc.nutri.goal`, `hc.nutri.goalPending`, `hc.nutri.dayType`, `hc.nutri.rideMin`, + `hc.nutri.guide`, `hc.nutri.planOpen`; `settings.ts` reads the pending goal through it). While the tab shows ANOTHER + person's page these are neither read nor written: `nutri-day.ts` answers "no storage" when `sessionStorage` + `hc.viewing` is set, and works in memory, as it does in a frame without storage. So the admin's cached goal is not + shown on the viewed page, is not overwritten by the viewed person's, and no pending goal of the admin is pushed. +- **Layout and fold preferences** (the Inicio order of `home-dash.ts` / `home-order.ts`, the Entreno window of + `training-activity.ts`, the History fold in `detail.ts`, `hc.onboarding.later`): the viewer's own taste, shared on + purpose; they hold nothing of anybody's data. + +`hc.viewing` (the viewed person's username, per tab) is written by `client/signin.ts`: before the reload of `view()` / +`unview()`, and corrected on every session answer. When the server's `viewing` and the tab's flag differ (a view started +or ended in another tab, consent taken back, an admin role removed) the flag is fixed and the page reloads once, so the +HTML and the data on screen always belong to the same person. A tab without working `sessionStorage` never reloads for +this (the banner still follows the server). ### Empty state and styles diff --git a/e2e/lan/multi-user.spec.mjs b/e2e/lan/multi-user.spec.mjs index fff8bc89..944b387d 100644 --- a/e2e/lan/multi-user.spec.mjs +++ b/e2e/lan/multi-user.spec.mjs @@ -7,6 +7,7 @@ import { test, expect } from './fixtures.mjs'; import { startStack, runUserScript, LAN_PORT } from './stack.mjs'; import { en as siEn } from '../../web/src/i18n/signin-templates.mjs'; +import { en as pfEn } from '../../web/src/i18n/profile-templates.mjs'; test.describe.configure({ mode: 'serial', timeout: 300_000 }); const ONLY_PROJECT = 'lan-phone'; @@ -16,6 +17,7 @@ test.beforeEach(({}, testInfo) => { const OWNER_PW = 'owner has a long password'; const ANDREA_PW = 'andrea has a long password'; +const CARLA_PW = 'carla chose this long password'; /** @type {Awaited> | null} */ let stack = null; @@ -118,7 +120,7 @@ test('signing in shows the person\'s OWN page; a different person in the same br expect(andreaStatus.publishedAt).toBeTruthy(); expect((await page.request.get(`${base}/`)).headers()['cache-control']).toBe('private, no-store'); const session = await (await page.request.get(`${base}/api/auth/session`, { headers: { 'x-hc-auth': '1' } })).json(); - expect(session).toEqual({ open: false, username: 'andrea' }); + expect(session).toEqual({ open: false, username: 'andrea', admin: false, sharing: false, viewing: null }); // sign out: the very next load of / is the sign-in page, not her page from a cache await page.evaluate(() => /** @type {any} */ (window).HCAuth.signOut()); @@ -133,5 +135,152 @@ test('signing in shows the person\'s OWN page; a different person in the same br const ownerStatus = await (await page.request.get(`${base}/status.json`)).json(); expect(ownerStatus.publishedAt).toBeTruthy(); expect(ownerStatus).not.toEqual(andreaStatus); - expect(await (await page.request.get(`${base}/api/auth/session`, { headers: { 'x-hc-auth': '1' } })).json()).toEqual({ open: false, username: 'owner' }); + // user 1 is the admin (sql/026) + expect(await (await page.request.get(`${base}/api/auth/session`, { headers: { 'x-hc-auth': '1' } })).json()).toEqual({ open: false, username: 'owner', admin: true, sharing: false, viewing: null }); +}); + +/* ---------- the admin manages people from the page; the coach view (docs/profile.md -> People, docs/plan-page.md -> Coach view) ---------- */ +/** the one-time password link the admin made for carla (test 1), used by test 1 only + * @type {string} */ +let carlaLink = ''; + +/** A person without a profile or a goal gets the onboarding assistant by itself at load (client/onboarding.ts), which covers + * the page; these tests are about the profile sheet, so the assistant is postponed the way its own "Later" button does it. + * @param {import('@playwright/test').Page} page */ +async function postponeOnboarding(page) { + await page.addInitScript(() => { try { localStorage.setItem('hc.onboarding.later', '1'); } catch { /* no storage: the test would say */ } }); +} + +/** @param {import('@playwright/test').Page} page the profile sheet, then the admin's People sheet */ +async function openPeople(page) { + await page.locator('#avatar-btn').click(); + await expect(page.locator('#detail')).toBeVisible(); + await page.locator('[data-pp-sheet]').click(); + await expect(page.locator('#detail #dt-title')).toHaveText(pfEn.people.title); +} + +test('the admin adds a person and makes a one-time password link; the person chooses a password with it and signs in', async ({ page, pageErrors }) => { + await postponeOnboarding(page); + pageErrors.allow(/status of 401/); + // the spent link, used again on purpose below + pageErrors.allow(/status of 410/); + await page.goto(`${base}/`); + await signIn(page, 'owner', OWNER_PW); + await expect(page.locator('#act-btn')).toBeVisible({ timeout: 240_000 }); + await openPeople(page); + await expect(page.locator('#pp-list')).toContainText('andrea'); + await expect(page.locator('#pp-list')).toContainText(pfEn.people.badges.owner); + await page.screenshot({ path: 'e2e/.results/shots/people-phone.png' }); + await page.locator('#pp-new').fill('carla'); + await page.locator('[data-pp-form="add"] button[type="submit"]').click(); + await expect(page.locator('#pp-msg')).toContainText('carla added'); + await expect(page.locator('.pp-panel')).toBeVisible(); + await expect(page.locator('#pp-list')).toContainText(pfEn.people.badges.noPassword); + // a person who does not share cannot be viewed; the owner and yourself cannot be deleted, a new person can + await expect(page.locator('[data-pp-act="view"]')).toHaveCount(0); + await page.locator('[data-pp-act="link"]').click(); + const field = page.locator('#pp-secret'); + await expect(field).toBeVisible(); + carlaLink = await field.inputValue(); + expect(carlaLink).toMatch(new RegExp(`^${base.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/#set-password=hcp_[A-Za-z0-9_-]{43}$`)); + await expect(page.locator('#pp-secret-box')).toContainText('send it to carla'); + await page.screenshot({ path: 'e2e/.results/shots/people-person-phone.png' }); + // what is not an everyday action waits in folds: one opens on a tap + await page.locator('.pp-fold summary', { hasText: pfEn.people.providers }).click(); + await expect(page.locator('#pp-sid')).toBeVisible(); + await page.screenshot({ path: 'e2e/.results/shots/people-fold-phone.png', fullPage: true }); + + // the person opens the link signed out: the "choose your password" form, not the sign-in form + await page.evaluate(() => /** @type {any} */ (window).HCAuth.signOut()); + await page.goto('about:blank'); + await page.goto(carlaLink); + await expect(page.locator('#signin-setpw')).toBeVisible(); + await expect(page.locator('#signin-user')).toHaveCount(0); + await page.screenshot({ path: 'e2e/.results/shots/set-password-phone.png' }); + await page.locator('#signin-new').fill(CARLA_PW); + await page.locator('#signin-again').fill(`${CARLA_PW} but different`); + await page.locator('#signin-go').click(); + await expect(page.locator('#signin-err')).toHaveText(siEn.setPassword.errors.mismatch); + await page.locator('#signin-again').fill(CARLA_PW); + await page.locator('#signin-go').click(); + await expect(page.locator('#signin-form')).toBeVisible(); + await expect(page.locator('#signin p[role="status"]')).toHaveText(siEn.setPassword.done); + expect(new URL(page.url()).hash, 'the link token is gone from the address').toBe(''); + await page.screenshot({ path: 'e2e/.results/shots/set-password-done-phone.png' }); + // the link is spent: the same one again is refused + await page.goto('about:blank'); + await page.goto(carlaLink); + await page.locator('#signin-new').fill(CARLA_PW); + await page.locator('#signin-again').fill(CARLA_PW); + await page.locator('#signin-go').click(); + await expect(page.locator('#signin-err')).toHaveText(siEn.setPassword.errors.invalid_link); + // and carla signs in with the password she chose + await page.goto(`${base}/`); + await signIn(page, 'carla', CARLA_PW); + const session = await (await page.request.get(`${base}/api/auth/session`, { headers: { 'x-hc-auth': '1' } })).json(); + expect(session).toEqual({ open: false, username: 'carla', admin: false, sharing: false, viewing: null }); +}); + +test('a person turns "Share with my coach" on from their profile and sees no People area', async ({ page, pageErrors }) => { + await postponeOnboarding(page); + pageErrors.allow(/status of 401/); + pageErrors.allow(/status of 403/); + await page.goto(`${base}/`); + await signIn(page, 'carla', CARLA_PW); + await expect(page.locator('#act-btn')).toBeVisible({ timeout: 240_000 }); + await page.locator('#avatar-btn').click(); + await expect(page.locator('#detail')).toBeVisible(); + await expect(page.locator('[data-pp-sheet]'), 'a non-admin has no People area').toHaveCount(0); + const sw = page.locator('#detail [data-pf-share]'); + await expect(sw).toHaveAttribute('role', 'switch'); + await expect(sw).toHaveAttribute('aria-checked', 'false'); + await sw.scrollIntoViewIfNeeded(); + await sw.click(); + await expect(sw).toHaveAttribute('aria-checked', 'true'); + await expect(page.locator('#pf-share-msg')).toHaveText(pfEn.goal.saved); + await page.screenshot({ path: 'e2e/.results/shots/profile-share-phone.png' }); + const session = await (await page.request.get(`${base}/api/auth/session`, { headers: { 'x-hc-auth': '1' } })).json(); + expect(session.sharing).toBe(true); + // the admin routes are the admin's alone + expect((await page.request.get(`${base}/api/admin/users`, { headers: { 'x-hc-admin': '1' } })).status()).toBe(403); +}); + +test('the admin views a person who shares: banner, their page, a write is refused with the notice, and a way back', async ({ page, pageErrors }) => { + await postponeOnboarding(page); + pageErrors.allow(/status of 401/); + pageErrors.allow(/status of 403/); + await page.goto(`${base}/`); + await signIn(page, 'owner', OWNER_PW); + await expect(page.locator('#act-btn')).toBeVisible({ timeout: 60_000 }); + await expect(page.locator('#hc-coach')).toHaveCount(0); + await openPeople(page); + await page.locator('[data-pp-act="manage"][data-name="carla"]').click(); + await expect(page.locator('[data-pp-act="view"][data-name="carla"]')).toBeVisible(); + const reloaded = page.waitForEvent('load'); + await page.locator('[data-pp-act="view"][data-name="carla"]').click(); + await reloaded; + // the page is carla's, under a banner that says so + await expect(page.locator('#hc-coach')).toBeVisible(); + await expect(page.locator('#hc-coach')).toContainText(siEn.coach.viewing.replace('{name}', 'carla')); + await expect(page.locator('#coach-back')).toHaveText(siEn.coach.back); + await expect(page.locator('#act-btn')).toBeVisible(); + const during = await (await page.request.get(`${base}/api/auth/session`, { headers: { 'x-hc-auth': '1' } })).json(); + expect(during).toEqual({ open: false, username: 'owner', admin: true, sharing: false, viewing: 'carla' }); + // a write goes to the server, which refuses it; the page says so in the banner, not with a generic failure + const code = await page.evaluate(() => /** @type {any} */ (window).HC.jsonApi('/api/food', 'X-HC-Food', 5000)('PUT', '/settings', { goal: 'maintain' }).then(() => 'ok', (/** @type {{code: string}} */ e) => e.code)); + expect(code).toBe('read_only'); + await expect(page.locator('#coach-txt')).toHaveText(siEn.coach.readOnly.replace('{name}', 'carla')); + await page.screenshot({ path: 'e2e/.results/shots/coach-banner-phone.png' }); + // while viewing, neither the sharing switch nor the People area is offered + await page.locator('#avatar-btn').click(); + await expect(page.locator('#detail')).toBeVisible(); + await expect(page.locator('[data-pf-share], [data-pp-sheet]')).toHaveCount(0); + await page.keyboard.press('Escape'); + // back to my page: the banner goes and the session no longer views anybody + const back = page.waitForEvent('load'); + await page.locator('#coach-back').click(); + await back; + await expect(page.locator('#hc-coach')).toHaveCount(0); + const after = await (await page.request.get(`${base}/api/auth/session`, { headers: { 'x-hc-auth': '1' } })).json(); + expect(after).toEqual({ open: false, username: 'owner', admin: true, sharing: false, viewing: null }); }); diff --git a/e2e/lan/stack.mjs b/e2e/lan/stack.mjs index 925dc7cb..a7ef19b8 100644 --- a/e2e/lan/stack.mjs +++ b/e2e/lan/stack.mjs @@ -159,6 +159,12 @@ export function upstreamFor(method, pathname) { ? { path: '/auth/' + pathname.slice('/api/auth/'.length), body: true, forwardHost: true, forwardProto: true } : { deny: true }; } + // nginx's /api/admin/ block: user management for a signed-in admin (ingest admin-routes.js) + if (pathname.startsWith('/api/admin/')) { + return ['GET', 'POST', 'PUT', 'DELETE'].includes(method) + ? { path: '/admin/' + pathname.slice('/api/admin/'.length), body: true, forwardHost: true } + : { deny: true }; + } if (pathname.startsWith('/api/journal/')) { return ['GET', 'PUT'].includes(method) ? { path: '/journal/' + pathname.slice('/api/journal/'.length), body: true, forwardHost: true } diff --git a/package-lock.json b/package-lock.json index 36e9dd3b..53f03663 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "loop", - "version": "1.11.1", + "version": "1.12.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "loop", - "version": "1.11.1", + "version": "1.12.0", "license": "MIT", "dependencies": { "astro": "7.3.8", diff --git a/package.json b/package.json index 4c41184e..36c960f3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "loop", - "version": "1.11.1", + "version": "1.12.0", "private": true, "description": "Tooling for the plan single source of truth (data/nutrition + data/training) and its Astro build (web/).", "license": "MIT", diff --git a/scripts/loop-web-config.test.mjs b/scripts/loop-web-config.test.mjs index 60ff54bb..ecfe1a36 100644 --- a/scripts/loop-web-config.test.mjs +++ b/scripts/loop-web-config.test.mjs @@ -31,16 +31,16 @@ function locations(conf) { return [...conf.matchAll(/location\s+((?:"[^"]*"|[^{"])+?)\s*\{((?:[^{}]|\{[^{}]*\})*)\}/g)].map((m) => ({ spec: m[1].trim(), body: m[2] })); } -test('nginx proxies ONLY /api/sync, /api/sync/status, /ingest/health-auto-export (exact), the /api/food/ + /api/journal/ + /api/auth/ prefixes and the internal page decision /_hc/site, to the loop-ingest service over loop-net', () => { +test('nginx proxies ONLY /api/sync, /api/sync/status, /ingest/health-auto-export (exact), the /api/food/ + /api/journal/ + /api/auth/ + /api/admin/ prefixes and the internal page decision /_hc/site, to the loop-ingest service over loop-net', () => { const proxied = locations(nginx).filter((l) => /proxy_pass\s/.test(l.body)); - assert.deepEqual(proxied.map((l) => l.spec).sort(), ['/api/auth/', '/api/food/', '/api/journal/', '= /_hc/site', '= /api/sync', '= /api/sync/status', '= /ingest/health-auto-export']); + assert.deepEqual(proxied.map((l) => l.spec).sort(), ['/api/admin/', '/api/auth/', '/api/food/', '/api/journal/', '= /_hc/site', '= /api/sync', '= /api/sync/status', '= /ingest/health-auto-export']); const target = (/** @type {string} */ spec) => /** @type {RegExpExecArray} */ (/proxy_pass\s+([^;]+);/.exec(/** @type {Location} */ (proxied.find((l) => l.spec === spec)).body))[1]; assert.equal(target('= /api/sync'), 'http://loop-ingest/sync'); assert.equal(target('= /api/sync/status'), 'http://loop-ingest/sync/status'); assert.equal(target('= /_hc/site'), 'http://loop-ingest/site'); assert.match(/** @type {Location} */ (proxied.find((l) => l.spec === '= /api/sync')).body, /limit_except POST/); assert.match(/** @type {Location} */ (proxied.find((l) => l.spec === '= /api/sync/status')).body, /limit_except GET/); - assert.equal((nginx.match(/proxy_pass\s/g) || []).length, 7, 'no other proxy_pass anywhere'); + assert.equal((nginx.match(/proxy_pass\s/g) || []).length, 8, 'no other proxy_pass anywhere'); }); test('nginx /api/food/: ingest /food/ only, GET/POST/PUT/DELETE, the body passed, 16 KB cap, the X-HC-Food header forwarded', () => { @@ -91,8 +91,20 @@ test('nginx /api/auth/: ingest /auth/ only, GET/POST, 16 KB cap, the X-HC-Auth h assert.deepEqual(map[1].split('\n').map((x) => x.trim().replace(/\s+/g, ' ')).filter(Boolean), ['default $scheme;', 'https https;']); }); -test('nginx /api/food/ + /api/journal/ + /api/auth/ forward the Host the browser asked for as X-Forwarded-Host (ingest binds the write Origin to it)', () => { - for (const spec of ['/api/food/', '/api/journal/', '/api/auth/']) { +test('nginx /api/admin/: ingest /admin/ only, GET/POST/PUT/DELETE, 16 KB cap, the X-HC-Admin header, no CORS', () => { + const a = locations(nginx).find((l) => l.spec === '/api/admin/'); + assert.ok(a, 'a prefix location for user management'); + assert.match(a.body, /proxy_pass\s+http:\/\/loop-ingest\/admin\/;/); + assert.match(a.body, /limit_except GET POST PUT DELETE \{ deny all; \}/); + assert.match(a.body, /client_max_body_size 16k;/, 'same cap as the service'); + assert.match(a.body, /proxy_set_header X-HC-Admin \$http_x_hc_admin;/); + assert.match(a.body, /proxy_set_header Host loop-ingest;/); + assert.match(a.body, /limit_req zone=hc_api burst=\d+ nodelay;/); + assert.doesNotMatch(a.body, /add_header\s+Access-Control/i, 'never approves a cross-site request'); +}); + +test('nginx /api/food/ + /api/journal/ + /api/auth/ + /api/admin/ forward the Host the browser asked for as X-Forwarded-Host (ingest binds the write Origin to it)', () => { + for (const spec of ['/api/food/', '/api/journal/', '/api/auth/', '/api/admin/']) { const l = locations(nginx).find((x) => x.spec === spec); assert.match(/** @type {Location} */ (l).body, /proxy_set_header X-Forwarded-Host \$http_host;/, spec); } @@ -310,7 +322,7 @@ test('nginx: no host.docker.internal / host port left; one upstream loop-ingest: const directives = nginx.split('\n').filter((l) => !/^\s*#/.test(l)).join('\n'); assert.doesNotMatch(directives, /host\.docker\.internal|INGEST_PORT/); const targets = [...directives.matchAll(/proxy_pass\s+([^;]+);/g)].map((m) => m[1]); - assert.equal(targets.length, 7); + assert.equal(targets.length, 8); for (const t of targets) assert.match(t, /^http:\/\/loop-ingest\//, t); assert.match(directives, /^resolver 127\.0\.0\.11 valid=\d+s ipv6=off;$/m, 'Docker embedded DNS: a recreated ingest container is followed'); assert.match(directives, /upstream loop-ingest \{\n\s+zone loop-ingest \d+k;\n\s+server loop-ingest:8088 resolve;\n\s*\}/, @@ -561,7 +573,7 @@ test('nginx limit_req: every proxied location is rate-limited (429), generously, const head = directives.slice(directives.indexOf('server {'), directives.indexOf('location ')); assert.match(head, /^\s*limit_req_status 429;/m); const proxied = locations(nginx).filter((l) => /proxy_pass\s/.test(l.body)); - assert.deepEqual(proxied.map((l) => l.spec).sort(), ['/api/auth/', '/api/food/', '/api/journal/', '= /_hc/site', '= /api/sync', '= /api/sync/status', '= /ingest/health-auto-export']); + assert.deepEqual(proxied.map((l) => l.spec).sort(), ['/api/admin/', '/api/auth/', '/api/food/', '/api/journal/', '= /_hc/site', '= /api/sync', '= /api/sync/status', '= /ingest/health-auto-export']); for (const l of proxied) { const zone = l.spec === '= /ingest/health-auto-export' ? 'hc_ingest' : l.spec === '= /_hc/site' ? 'hc_site' : 'hc_api'; const m = new RegExp(`limit_req zone=${zone} burst=(\\d+) nodelay;`).exec(l.body); diff --git a/services/loop-ingest/README.md b/services/loop-ingest/README.md index be0b9c82..3ed81eef 100644 --- a/services/loop-ingest/README.md +++ b/services/loop-ingest/README.md @@ -119,13 +119,23 @@ run the token user's own Strava / Garmin (their own credentials, [below](#provid | --- | --- | | `add ` | creates a user (lowercase `[a-z0-9._-]`, 1 to 64 characters) with no password: it cannot sign in yet | | `set-password ` | sets the password (12 to 256 characters; asked twice without echo on a terminal, or the whole piped stdin minus one trailing newline); ends every session of that user | -| `list` | usernames, whether a password is set, created date (never a hash) | +| `list` | usernames, whether a password is set, created date, admin, shares (never a hash) | +| `admin on\|off` | makes a user an admin, or stops it. The install's first user is the admin after `sql/026`; the only admin is never turned off (exit 1, nothing changed) | +| `share on\|off` | that user's consent to be viewed, read-only, by the admins; off for every new user | | `rename ` | renames a user (both names folded like every username): only `app_user.username` changes, so their sessions, tokens, provider credentials and data keep working; a taken name is refused (exit 1), an invalid one is a usage error (exit 2) | | `delete [--confirm ] [--dry-run]` | deletes a user and **every** row and folder of theirs; **it cannot be undone: dump the database first**. One transaction over every table of `IMPORT_TABLES` (children first) and then the user, rolled back entirely on any failure; only after it commits, their `users//` folders under the data root, the site folder and the files folder (read-only in the default install: its path is printed to remove by hand, exit 0). The owner (user 1) and an unknown user are refused (exit 1); the confirmation is the username typed again on a terminal, or `--confirm ` (the exact name) when scripted, and a missing or wrong one is exit 2 with nothing changed; `--dry-run` prints the rows per table and the folders and deletes nothing | | `token add [label]` | issues a machine token and prints it once, alone, on stdout (the confirmation goes to stderr) | | `token list ` | id, label, created, last used, revoked (never a token or a hash) | | `token revoke ` | revokes a token at once; the id is a positive safe integer (anything else is a usage error, exit 2) | +The same user management is available to a signed-in admin from the page through `/admin/*` (`src/admin-routes.js`; +routes and refusals in [`docs/lan-services.md`](../../docs/lan-services.md) → Security → Admin routes); both use the rules in +`src/user-admin.js`. `delete` also refuses the only admin (exit 1): make another user an admin first. + +An admin can also view, read-only, a user who shares (`POST /auth/view`, `POST /auth/unview`, `POST /auth/sharing`; +[`docs/lan-services.md`](../../docs/lan-services.md) → Security → Coach view): while a session views somebody, every +request that is not a `GET` or `HEAD` is `403 read_only`. + **The import script** (`scripts/import-install.js`, `src/import-install.js`; guide: [Moving another install in as a person](../../docs/guides/several-people.md#moving-another-install-in-as-a-person)). It moves another LOOP install into this one as an existing, empty user (`--as `): `SOURCE_DATABASE_URL= node services/loop-ingest/scripts/import-install.js --as andrea [--source-data ] [--with-providers] [--dry-run]`. diff --git a/services/loop-ingest/package-lock.json b/services/loop-ingest/package-lock.json index 84ddfb4f..c42e9222 100644 --- a/services/loop-ingest/package-lock.json +++ b/services/loop-ingest/package-lock.json @@ -1,12 +1,12 @@ { "name": "loop-ingest", - "version": "1.11.1", + "version": "1.12.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "loop-ingest", - "version": "1.11.1", + "version": "1.12.0", "license": "MIT", "dependencies": { "pg": "^8.13.1" diff --git a/services/loop-ingest/package.json b/services/loop-ingest/package.json index fe06526a..3c0f6e82 100644 --- a/services/loop-ingest/package.json +++ b/services/loop-ingest/package.json @@ -1,6 +1,6 @@ { "name": "loop-ingest", - "version": "1.11.1", + "version": "1.12.0", "private": true, "license": "MIT", "type": "module", diff --git a/services/loop-ingest/scripts/strava-auth.js b/services/loop-ingest/scripts/strava-auth.js index e0e7b7f7..4b2a9d64 100755 --- a/services/loop-ingest/scripts/strava-auth.js +++ b/services/loop-ingest/scripts/strava-auth.js @@ -15,10 +15,11 @@ import path from 'node:path' import { createInterface } from 'node:readline/promises' import { stdin, stdout } from 'node:process' import { fileURLToPath, pathToFileURL } from 'node:url' +import { REDIRECT_URI, SCOPE, authorizeUrl, extractCode, exchangeCode } from '../src/strava-oauth.js' export const ENV_PATH = fileURLToPath(new URL('../.env', import.meta.url)) -export const REDIRECT_URI = 'http://localhost/exchange_token' -export const SCOPE = 'read,activity:read_all,activity:write,profile:read_all' +// the OAuth steps live in src/strava-oauth.js (the admin routes use them too); re-exported for this script's callers +export { REDIRECT_URI, SCOPE, authorizeUrl, extractCode, exchangeCode } export const USAGE = `Usage: node scripts/strava-auth.js [--print] @@ -45,66 +46,6 @@ export function parseEnv (text) { return out } -/** @param {string} clientId @returns {string} */ -export function authorizeUrl (clientId) { - const url = new URL('https://www.strava.com/oauth/authorize') - url.searchParams.set('client_id', clientId) - url.searchParams.set('response_type', 'code') - url.searchParams.set('redirect_uri', REDIRECT_URI) - url.searchParams.set('approval_prompt', 'force') - url.searchParams.set('scope', SCOPE) - return url.toString() -} - -/** - * Accept either the bare code or the whole redirected URL — pasting the full - * address bar is the obvious thing to do, so handle it. - * @param {string} input - * @returns {string | null} - */ -export function extractCode (input) { - const trimmed = input.trim() - if (!trimmed) return null - - if (/^https?:\/\//i.test(trimmed)) { - const fromUrl = new URL(trimmed).searchParams.get('code') - return fromUrl?.trim() || null - } - - // A pasted query fragment, with or without a leading '?'. - if (trimmed.includes('code=')) { - return new URLSearchParams(trimmed.replace(/^\?/, '')).get('code')?.trim() || null - } - - return trimmed -} - -/** - * The code-for-token exchange (the one place that talks to Strava's token endpoint with an authorization code; scripts/user.js - * strava uses it too). Never throws on an answer: `{ ok: false, status, text }` for a refusal (the response text is - * the caller's to show or not), `{ ok: false, status, noRefreshToken: true }` for an answer without a refresh token, else - * `{ ok: true, refreshToken, scope, athlete }`. A network failure rejects. - * @param {{ clientId: string, clientSecret: string, code: string, fetchImpl?: typeof fetch }} options - * @returns {Promise<{ ok: true, refreshToken: string, scope: string | undefined, athlete: { firstname?: string, lastname?: string } | undefined } - * | { ok: false, status: number, text?: string, noRefreshToken?: boolean }>} - */ -export async function exchangeCode ({ clientId, clientSecret, code, fetchImpl = fetch }) { - const res = await fetchImpl('https://www.strava.com/oauth/token', { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ - client_id: clientId, - client_secret: clientSecret, - code, - grant_type: 'authorization_code' - }) - }) - if (!res.ok) return { ok: false, status: res.status, text: await res.text() } - const body = /** @type {{ scope?: string, refresh_token?: unknown, athlete?: { firstname?: string, lastname?: string } }} */ (await res.json()) - if (typeof body.refresh_token !== 'string' || !body.refresh_token) return { ok: false, status: res.status, noRefreshToken: true } - return { ok: true, refreshToken: body.refresh_token, scope: body.scope, athlete: body.athlete } -} - /** The .env text with STRAVA_REFRESH_TOKEN set to `token` (replaced, or appended). * @param {string} envText @param {string} token @returns {string} */ export function withRefreshToken (envText, token) { diff --git a/services/loop-ingest/scripts/user.js b/services/loop-ingest/scripts/user.js index fc3abecc..4d72dd59 100644 --- a/services/loop-ingest/scripts/user.js +++ b/services/loop-ingest/scripts/user.js @@ -50,20 +50,22 @@ import { pathToFileURL } from 'node:url' import { createAuthStore } from '../src/auth-db.js' import { createMachineTokenStore } from '../src/machine-token-db.js' import { createProviderCredentialStore } from '../src/provider-credentials-db.js' -import { garminKeyExpires } from '../src/garmin.js' -import { authorizeUrl, extractCode, exchangeCode } from './strava-auth.js' -import { newMachineToken, hashMachineToken } from '../src/machine-tokens.js' +import { authorizeUrl } from '../src/strava-oauth.js' +import { TOKEN_LABEL_MAX, validTokenLabel, issueMachineToken, deleteUserEverywhere, cleanSecret, validStravaClientId, garminExpiry, connectStravaApp } from '../src/user-admin.js' import { createAuthService } from '../src/sessions.js' import { OPEN_MARKER } from '../src/site-routes.js' import { normalizeUsername, validPassword, PASSWORD_MIN, PASSWORD_MAX } from '../src/password.js' -import { createUserEraser, removeUserFolders, assertRoots } from '../src/user-delete.js' +import { createUserEraser, assertRoots } from '../src/user-delete.js' import { userRoots, OWNER_USER_ID } from '../../../lib/user-paths.mjs' export const USAGE = `Usage: node scripts/user.js add create a user without a password set-password set the password (asked twice on a terminal, or the piped stdin); ends that user's sessions - list usernames, whether a password is set, created date + list usernames, whether a password is set, created date, admin, shares + admin on|off make a user an admin (manages users from the page, views the people who share), or stop it; + the only admin cannot be turned off + share on|off that user's consent to be viewed, read-only, by the admins (they can change it in their profile) rename rename a user: only the name changes, their sessions, tokens and data keep working delete [--confirm ] [--dry-run] delete a user and EVERY row and folder of theirs: it cannot be undone (dump the database first). @@ -81,7 +83,6 @@ export const USAGE = `Usage: node scripts/user.js Usernames: lowercase letters, digits, dot, underscore, dash (1-64). Passwords: ${PASSWORD_MIN}-${PASSWORD_MAX} characters, never an argument; neither is a client secret, an authorization code or a Garmin key.` -const LABEL_MAX = 64 /** A usage failure: exit 2, the message is safe to print (it never holds an argument). */ class UsageError extends Error {} @@ -212,9 +213,8 @@ async function tokenCommand ([sub, ...args], store, tokens, { out, stderr }) { } const label = args[1] ?? '' // a label is shown in `token list`, one line per token: printable, no tab or newline - if (label.length > LABEL_MAX || /[\u0000-\u001f\u007f]/.test(label)) throw new UsageError(`a label is at most ${LABEL_MAX} characters, without control characters`) - const token = newMachineToken() - const { id } = await tokens.add({ userId: user.id, tokenHash: hashMachineToken(token), label }) + if (!validTokenLabel(label)) throw new UsageError(`a label is at most ${TOKEN_LABEL_MAX} characters, without control characters`) + const { id, token } = await issueMachineToken(tokens, user.id, label) stderr.write(`token ${id} for ${username}${label ? ` (${label})` : ''}: shown once below, store it now (it cannot be shown again; revoke it with token revoke ${id})\n`) out(token) return 0 @@ -222,6 +222,43 @@ async function tokenCommand ([sub, ...args], store, tokens, { out, stderr }) { const USERNAME_RULE = 'a username is lowercase letters, digits, dot, underscore or dash, 1 to 64 characters' +/** + * `admin on|off` and `share on|off`: the two flags of sql/026. `admin` refuses to leave the install + * without an admin; `share` is the user's consent to the coach view, set here by the operator on their behalf. + * @param {'admin' | 'share'} command @param {string[]} args @param {import('../src/auth-db.js').AuthStore} store + * @param {{ out: (line: string) => void, stderr: NodeJS.WritableStream }} io @returns {Promise} + */ +async function flagCommand (command, args, store, { out, stderr }) { + if (args.length !== 2 || (args[1] !== 'on' && args[1] !== 'off')) throw new UsageError(`${command} takes two arguments: the username, then on or off`) + const username = normalizeUsername(args[0]) + if (username == null) throw new UsageError(USERNAME_RULE) + const on = args[1] === 'on' + const user = await store.findUserByUsername(username) + if (!user) { + stderr.write(`no user ${username}\n`) + return 1 + } + if (command === 'share') { + if (!(await store.setSharing(user.id, on))) { + stderr.write(`no user ${username}\n`) + return 1 + } + out(on ? `${username} now shares their page with the admins (the coach view, read-only)` : `${username} no longer shares their page; an open coach view of it ends at its next request`) + return 0 + } + const result = await store.setAdmin(user.id, on) + if (result === 'missing') { + stderr.write(`no user ${username}\n`) + return 1 + } + if (result === 'last') { + stderr.write(`${username} is the only admin; make another user an admin first. Nothing changed\n`) + return 1 + } + out(on ? `${username} is now an admin: they can manage users and view the people who share` : `${username} is no longer an admin`) + return 0 +} + /** * `rename `: both names are folded like every username; only `app_user.username` changes. * @param {string[]} args after `rename` @param {import('../src/auth-db.js').AuthStore} store @param {{ out: (line: string) => void, stderr: NodeJS.WritableStream }} io @@ -294,6 +331,11 @@ async function deleteCommand (args, store, { eraser, roots, rm, stdin, stderr, o stderr.write(`user ${username} is the owner of the install (user 1): it is never deleted\n`) return 1 } + // an install always keeps an admin (sql/026): the page's user management would have nobody left to use it + if (user.admin && (await store.listUsers()).filter((u) => u.admin).length === 1) { + stderr.write(`user ${username} is the only admin: make another user an admin first (admin on); nothing changed\n`) + return 1 + } if (roots) { try { assertRoots(roots) @@ -329,7 +371,8 @@ async function deleteCommand (args, store, { eraser, roots, rm, stdin, stderr, o return 2 } - const removed = await eraser.erase(user.id) + // the rows in one transaction, then (only after it committed) the folders: the one order user-admin.js keeps + const { rows: removed, folders: folderResults } = await deleteUserEverywhere({ eraser, roots, rm }, user.id) if (removed === null) { stderr.write(`no user ${username}\n`) return 1 @@ -341,7 +384,7 @@ async function deleteCommand (args, store, { eraser, roots, rm, stdin, stderr, o return 0 } let code = 0 - for (const f of await removeUserFolders(roots, user.id, rm ? { rm } : {})) { + for (const f of folderResults) { if (f.status === 'removed') out(`removed ${f.path}`) else if (f.status !== 'absent') { stderr.write(`could not remove the ${f.kind} folder (${f.status === 'refused' ? 'refused' : f.error}): remove it by hand: ${f.path}\n`) @@ -352,14 +395,6 @@ async function deleteCommand (args, store, { eraser, roots, rm, stdin, stderr, o return code } -const SECRET_MAX = 4096 - -/** A pasted secret value: trimmed, then non-blank, bounded, no whitespace or control character inside. @param {string} value @returns {string | null} */ -function cleanSecret (value) { - const v = value.trim() - return v.length >= 1 && v.length <= SECRET_MAX && !/[\s\u0000-\u001f\u007f]/.test(v) ? v : null -} - /** * `strava | garmin ...` (see the header). Secrets are read from the terminal without echo or from the piped stdin, * never from an argument; nothing secret is printed. Messages never hold an argument. @@ -398,11 +433,11 @@ async function providerCommand (provider, args, store, { credentials, fetchImpl, const username = normalizeUsername(positional[0]) if (username == null) throw new UsageError('a username is lowercase letters, digits, dot, underscore or dash, 1 to 64 characters') if (remove && (clientId !== null || expiresArg !== null)) throw new UsageError(`${provider} --remove takes no other option`) - if (!remove && provider === 'strava' && (clientId === null || !/^[A-Za-z0-9_-]{1,64}$/.test(clientId))) throw new UsageError('strava needs --client-id : the id of the Strava API app (letters, digits, dash, underscore)') + if (!remove && provider === 'strava' && !validStravaClientId(clientId)) throw new UsageError('strava needs --client-id : the id of the Strava API app (letters, digits, dash, underscore)') /** @type {string | null} */ let expires = null if (expiresArg !== null) { - expires = garminKeyExpires({ GARMIN_API_KEY_EXPIRES: expiresArg }) + expires = garminExpiry(expiresArg) ?? null if (!expires) throw new UsageError('--expires is a calendar date, YYYY-MM-DD') } @@ -449,28 +484,19 @@ async function providerCommand (provider, args, store, { credentials, fetchImpl, } const clientSecret = cleanSecret(secretRaw) if (!clientSecret) throw new UsageError('the client secret is blank, too long or contains whitespace') - const code = extractCode(pasted) - if (!code) { - stderr.write('no authorization code found in that input; nothing stored\n') - return 1 - } - const exchanged = await exchangeCode({ clientId: /** @type {string} */ (clientId), clientSecret, code, fetchImpl }) - if (!exchanged.ok) { - stderr.write(exchanged.noRefreshToken - ? 'Strava answered without a refresh token; nothing stored: run this again with a fresh code\n' - : `Strava refused the code (${exchanged.status}); nothing stored. A code is single-use and short-lived: run this again with a fresh one\n`) - return 1 - } - // the refresh token and the credential row in ONE transaction: both or neither (an orphan token would outlive a failed connect) - try { - await credentials.connectStrava(user.id, { clientId: /** @type {string} */ (clientId), clientSecret }, exchanged.refreshToken) - } catch { - // no message of the driver here: a one-line failure that can never hold a secret - stderr.write('could not store the Strava connection; nothing changed: run this again with a fresh code\n') + const connected = await connectStravaApp({ credentials, fetchImpl }, user.id, { clientId: /** @type {string} */ (clientId), clientSecret, pasted }) + if (!connected.ok) { + stderr.write({ + no_code: 'no authorization code found in that input; nothing stored\n', + no_refresh_token: 'Strava answered without a refresh token; nothing stored: run this again with a fresh code\n', + refused: `Strava refused the code (${connected.reason === 'refused' ? connected.status : ''}); nothing stored. A code is single-use and short-lived: run this again with a fresh one\n`, + // no message of the driver here: a one-line failure that can never hold a secret + store_failed: 'could not store the Strava connection; nothing changed: run this again with a fresh code\n' + }[connected.reason]) return 1 } - const athlete = [exchanged.athlete?.firstname, exchanged.athlete?.lastname].filter(Boolean).join(' ') - out(`Strava connected for ${username}${athlete ? ` (Strava athlete ${athlete})` : ''}; granted scopes: ${exchanged.scope ?? '(not reported)'}`) + const { athlete, scope } = connected + out(`Strava connected for ${username}${athlete ? ` (Strava athlete ${athlete})` : ''}; granted scopes: ${scope ?? '(not reported)'}`) out('A running server picks it up at that user\'s next Sync or its next scheduled pull.') return 0 } @@ -500,11 +526,12 @@ export async function run (argv, { pool, store: injected, tokenStore: injectedTo if (command === 'list') { if (rest.length) throw new UsageError('list takes no arguments') const users = await store.listUsers() - out('username\tpassword\tcreated') - for (const u of users) out(`${u.username}\t${u.hasPassword ? 'set' : 'not set'}\t${u.createdAt.toISOString().slice(0, 10)}`) + out('username\tpassword\tcreated\tadmin\tshares') + for (const u of users) out(`${u.username}\t${u.hasPassword ? 'set' : 'not set'}\t${u.createdAt.toISOString().slice(0, 10)}\t${u.admin ? 'yes' : 'no'}\t${u.sharing ? 'yes' : 'no'}`) return 0 } if (command === 'rename') return await renameCommand(rest, store, { out, stderr }) + if (command === 'admin' || command === 'share') return await flagCommand(command, rest, store, { out, stderr }) if (command === 'delete') { if (!eraser && !pool) throw new Error('run needs a pool or an eraser') return await deleteCommand(rest, store, { eraser: eraser ?? createUserEraser(/** @type {import('../src/db.js').Pool} */ (pool)), roots, rm, stdin, stderr, out }) diff --git a/services/loop-ingest/sql/026_roles.sql b/services/loop-ingest/sql/026_roles.sql new file mode 100644 index 00000000..313240d4 --- /dev/null +++ b/services/loop-ingest/sql/026_roles.sql @@ -0,0 +1,8 @@ +-- Roles and sharing consent (docs/lan-services.md -> Security -> Admin and coach view). `is_admin`: the user may manage +-- the other users from the page (the /admin routes) and view, read-only, the page of a user who shares. +-- `share_with_coach`: that user's consent to be viewed; only they change it from the page, and it is off for every new +-- user. The install's first user (id 1, sql/016) becomes the admin here, so an install always has one; nobody shares +-- until they (or the operator, with scripts/user.js) say so. Runs once (schema_migrations ledger), in one transaction. +ALTER TABLE app_user ADD COLUMN is_admin BOOLEAN NOT NULL DEFAULT false; +ALTER TABLE app_user ADD COLUMN share_with_coach BOOLEAN NOT NULL DEFAULT false; +UPDATE app_user SET is_admin = true WHERE id = 1; diff --git a/services/loop-ingest/sql/027_password_link.sql b/services/loop-ingest/sql/027_password_link.sql new file mode 100644 index 00000000..2b85e96c --- /dev/null +++ b/services/loop-ingest/sql/027_password_link.sql @@ -0,0 +1,11 @@ +-- One-time links to set a password (docs/lan-services.md -> Security -> Password links): an admin issues one for a user +-- from the page and hands it over; the person opens it and chooses their own password, so the admin never knows it. The +-- link carries 32 random bytes; the database holds only their SHA-256 (a leaked table or backup is no usable link). At +-- most ONE link per user (a new one replaces the old one), it ends at `expires_at`, and using it deletes it in the same +-- statement that sets the password. Deleting a user deletes their link. Runs once (schema_migrations ledger). +CREATE TABLE password_link ( + user_id BIGINT PRIMARY KEY REFERENCES app_user (id) ON DELETE CASCADE, + token_hash BYTEA NOT NULL UNIQUE CHECK (octet_length(token_hash) = 32), + created_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > created_at) +); diff --git a/services/loop-ingest/sql/028_session_view.sql b/services/loop-ingest/sql/028_session_view.sql new file mode 100644 index 00000000..aa67e1a0 --- /dev/null +++ b/services/loop-ingest/sql/028_session_view.sql @@ -0,0 +1,6 @@ +-- The coach view (docs/lan-services.md -> Security -> Coach view): a session of an admin may be VIEWING another user, +-- read-only. The state lives on the session row, so it is per browser, ends with the session, and is read with it on +-- every request. It only counts while the viewed user still shares (app_user.share_with_coach) and the session's user +-- is still an admin (auth-db.js joins both): consent taken back, or a role removed, ends the view at the next request. +-- Deleting the viewed user clears it. Runs once (schema_migrations ledger), in one transaction. +ALTER TABLE app_session ADD COLUMN viewing_user_id BIGINT REFERENCES app_user (id) ON DELETE SET NULL; diff --git a/services/loop-ingest/src/admin-routes.js b/services/loop-ingest/src/admin-routes.js new file mode 100644 index 00000000..d140f1a9 --- /dev/null +++ b/services/loop-ingest/src/admin-routes.js @@ -0,0 +1,283 @@ +/** + * The admin routes (docs/lan-services.md -> Security -> Admin), mounted by server.js under /admin/ and reached from the + * page through loop-web's /api/admin/ proxy. They do from the page what scripts/user.js does from a shell, with the + * same stores and the same rules (user-admin.js): + * + * GET /admin/users 200 {users: [{username, hasPassword, admin, sharing, created, owner, self}]} + * POST /admin/users {username} 201 {username}; 400 invalid_username, 409 username_taken + * PUT /admin/users/ {username} 200 {username} (rename: only the name changes); 404, 400, 409 + * DELETE /admin/users/ {confirm} 200 {deleted, manual: [folders to remove by hand]}; `confirm` must be the + * username again (400 confirmation_mismatch); 403 owner_never_deleted for + * user 1, 403 cannot_delete_self; it cannot be undone + * GET /admin/users//tokens 200 {tokens: [{id, label, created, lastUsed, revoked}]} (never a token or hash) + * POST /admin/users//tokens {label} 201 {id, token}: the token is in this one answer and nowhere else + * DELETE /admin/tokens/ 204 (also when it was revoked before); 404 + * POST /admin/users//password-link 201 {token, expires}: a one-time link token (password-links.js) the admin + * hands to that person, who sets their own password with it; it replaces the + * link that user had; the token is in this one answer and nowhere else + * GET /admin/users//providers 200 {strava, garmin, garminExpires}: whether each is connected, never a secret + * POST /admin/strava/authorize-url {clientId} 200 {url}: the address the person opens, signed in to THEIR Strava + * PUT /admin/users//strava {clientId, clientSecret, code} 200 {athlete, scope}: the user's OWN Strava API + * app; `code` is the code or the whole redirected address. 400 + * invalid_client_id / invalid_client_secret / no_code, 502 strava_refused / + * strava_no_refresh_token / strava_unreachable; nothing is stored on a failure + * DELETE /admin/users//strava 204 (also when there was none) + * PUT /admin/users//garmin {apiKey, expires} 204; `expires` is YYYY-MM-DD or ''. 400 invalid_api_key / invalid_expires + * DELETE /admin/users//garmin 204 (also when there was none) + * + * Secrets (a client secret, a Garmin key, a token, a link) only travel INTO the service or out ONCE at creation: no + * route ever answers a stored one. + * + * Who: ONLY a signed-in session whose user is an admin (sql/026). Open mode (no password exists, so nobody proved who + * they are) is 403 login_required; no session 401 unauthenticated; a session that is not an admin 403 forbidden; an + * admin's session while it views somebody (the coach view) 403 viewing, for every method. A + * machine token or a run credential is never an admin: this module asks the session service directly. The role is read + * with the session on every request, so an admin who is turned off loses these routes at once. + * + * Same layers as the login routes (auth-routes.js header): Host allowlist (421), the custom header `X-HC-Admin: 1` on + * every request (403), the Origin check on writes (403 forbidden_origin), `Content-Type: application/json` on a body + * (415), the 16 KB cap (413), 405 / 404. Bodies take exactly their keys (400 bad_request). Every change is logged as one + * event with the admin's and the target's username: never a token. + */ +import { httpError, send, isJson, readJson, hostAllowed, hostOfHeader, writeOriginOk } from './http.js' +import { normalizeUsername } from './password.js' +import { OWNER_USER_ID } from '../../../lib/user-paths.mjs' +import { validTokenLabel, issueMachineToken, deleteUserEverywhere, cleanSecret, validStravaClientId, garminExpiry, connectStravaApp } from './user-admin.js' +import { authorizeUrl } from './strava-oauth.js' + +/** @typedef {import('node:http').IncomingMessage} Req @typedef {import('node:http').ServerResponse} Res */ + +const USER_PATH = /^\/admin\/users\/([^/]+)$/ +const USER_TOKENS_PATH = /^\/admin\/users\/([^/]+)\/tokens$/ +const USER_LINK_PATH = /^\/admin\/users\/([^/]+)\/password-link$/ +const USER_PROVIDER_PATH = /^\/admin\/users\/([^/]+)\/(strava|garmin|providers)$/ +const TOKEN_PATH = /^\/admin\/tokens\/([1-9][0-9]{0,15})$/ + +/** The route of a path: its name, the methods it takes and its path parameter. @param {string} path */ +function routeOf (path) { + if (path === '/admin/users') return { name: 'users', methods: ['GET', 'POST'], param: '' } + let m = USER_PATH.exec(path) + if (m) return { name: 'user', methods: ['PUT', 'DELETE'], param: m[1] } + m = USER_TOKENS_PATH.exec(path) + if (m) return { name: 'userTokens', methods: ['GET', 'POST'], param: m[1] } + m = USER_LINK_PATH.exec(path) + if (m) return { name: 'userLink', methods: ['POST'], param: m[1] } + if (path === '/admin/strava/authorize-url') return { name: 'stravaUrl', methods: ['POST'], param: '' } + m = USER_PROVIDER_PATH.exec(path) + if (m) return { name: m[2], methods: m[2] === 'providers' ? ['GET'] : ['PUT', 'DELETE'], param: m[1] } + m = TOKEN_PATH.exec(path) + if (m) return { name: 'token', methods: ['DELETE'], param: m[1] } + return null +} + +/** The body, which must be a JSON object with exactly `keys`, all strings. @param {Req} req @param {string[]} keys @returns {Promise>} */ +async function bodyOf (req, keys) { + if (!isJson(req)) throw httpError(415, 'unsupported_media_type') + const body = await readJson(req) + if (!body || typeof body !== 'object' || Array.isArray(body)) throw httpError(400, 'bad_request') + const got = Object.keys(body) + if (got.length !== keys.length || keys.some((k) => !Object.hasOwn(body, k) || typeof body[k] !== 'string')) throw httpError(400, 'bad_request') + return body +} + +const iso = (/** @type {Date | null} */ at) => (at ? at.toISOString() : null) + +/** + * `providerStatus` looks at the user's credentials again (so a running server notices a change at once) and says what is connected. + * @param {{ auth: Pick, + * store: Pick, + * tokens: Pick, + * credentials: Pick, 'connectStrava' | 'setGarmin' | 'remove'>, + * providerStatus: (userId: number) => Promise<{ strava: boolean, garmin: boolean, garminExpires: string | null }>, + * fetchImpl?: typeof fetch, + * links: Pick, + * eraser: Pick, 'erase'>, + * roots: import('./user-admin.js').Roots | null, rm?: typeof import('node:fs').promises.rm, + * allowedHosts?: string[], log?: (line: string) => void, now?: () => number }} options + */ +export function createAdminRoutes ({ auth, store, tokens, links, credentials, providerStatus, fetchImpl = fetch, eraser, roots, rm, allowedHosts = [], log = console.log, now = Date.now }) { + /** The user a path names, or 404: the name must already be in its stored form (no folding in a path). @param {string} raw */ + async function userOf (raw) { + let name + try { name = decodeURIComponent(raw) } catch { throw httpError(404, 'not_found') } + if (normalizeUsername(name) !== name) throw httpError(404, 'not_found') + const user = await store.findUserByUsername(name) + if (!user) throw httpError(404, 'not_found') + return user + } + + /** @param {Req} req @param {Res} res @param {{ userId: number, username: string }} admin @param {NonNullable>} route */ + async function dispatch (req, res, admin, route) { + if (route.name === 'users' && req.method === 'GET') { + req.resume() + const users = (await store.listUsers()).map((u) => ({ + username: u.username, hasPassword: u.hasPassword, admin: u.admin, sharing: u.sharing, created: iso(u.createdAt), owner: u.id === OWNER_USER_ID, self: u.id === admin.userId + })) + return send(res, 200, { users }) + } + if (route.name === 'users') { + const { username: asked } = await bodyOf(req, ['username']) + const username = normalizeUsername(asked) + if (username == null) throw httpError(400, 'invalid_username', 'username') + if (!(await store.addUser(username))) throw httpError(409, 'username_taken', 'username') + log(JSON.stringify({ event: 'admin_user_added', by: admin.username, username })) + return send(res, 201, { username }) + } + if (route.name === 'user' && req.method === 'PUT') { + const user = await userOf(route.param) + const { username: asked } = await bodyOf(req, ['username']) + const to = normalizeUsername(asked) + if (to == null) throw httpError(400, 'invalid_username', 'username') + if (to !== user.username) { + const result = await store.renameUser(user.id, to) + if (result === 'taken') throw httpError(409, 'username_taken', 'username') + if (result === 'missing') throw httpError(404, 'not_found') + log(JSON.stringify({ event: 'admin_user_renamed', by: admin.username, from: user.username, to })) + } + return send(res, 200, { username: to }) + } + if (route.name === 'user') { + const user = await userOf(route.param) + const { confirm } = await bodyOf(req, ['confirm']) + if (user.id === OWNER_USER_ID) throw httpError(403, 'owner_never_deleted') + if (user.id === admin.userId) throw httpError(403, 'cannot_delete_self') + if (confirm !== user.username) throw httpError(400, 'confirmation_mismatch', 'confirm') + const { rows, folders } = await deleteUserEverywhere({ eraser, roots, rm }, user.id) + if (rows === null) throw httpError(404, 'not_found') + // a folder that could not be removed (the files folder is read-only in the default install) is the operator's to remove + const manual = folders.filter((f) => f.status !== 'removed' && f.status !== 'absent').map((f) => f.path) + log(JSON.stringify({ event: 'admin_user_deleted', by: admin.username, username: user.username, userId: user.id, rows: rows.reduce((n, r) => n + r.rows, 0), manual })) + return send(res, 200, { deleted: user.username, manual }) + } + if (route.name === 'userTokens' && req.method === 'GET') { + req.resume() + const user = await userOf(route.param) + const list = (await tokens.listForUser(user.id)).map((t) => ({ id: t.id, label: t.label, created: iso(t.createdAt), lastUsed: iso(t.lastUsedAt), revoked: iso(t.revokedAt) })) + return send(res, 200, { tokens: list }) + } + if (route.name === 'userTokens') { + const user = await userOf(route.param) + const { label } = await bodyOf(req, ['label']) + if (!validTokenLabel(label)) throw httpError(400, 'invalid_label', 'label') + const issued = await issueMachineToken(tokens, user.id, label) + log(JSON.stringify({ event: 'admin_token_added', by: admin.username, username: user.username, tokenId: issued.id })) + return send(res, 201, issued) + } + if (route.name === 'stravaUrl') { + const { clientId } = await bodyOf(req, ['clientId']) + if (!validStravaClientId(clientId)) throw httpError(400, 'invalid_client_id', 'clientId') + return send(res, 200, { url: authorizeUrl(clientId) }) + } + if (route.name === 'providers') { + req.resume() + const user = await userOf(route.param) + const { strava, garmin, garminExpires } = await providerStatus(user.id) + return send(res, 200, { strava, garmin, garminExpires }) + } + if (route.name === 'strava' || route.name === 'garmin') { + const provider = route.name + const user = await userOf(route.param) + if (req.method === 'DELETE') { + req.resume() + const had = await credentials.remove(user.id, provider) + if (had) log(JSON.stringify({ event: 'admin_provider_removed', by: admin.username, username: user.username, provider })) + } else if (provider === 'garmin') { + const body = await bodyOf(req, ['apiKey', 'expires']) + const apiKey = cleanSecret(body.apiKey) + if (!apiKey) throw httpError(400, 'invalid_api_key', 'apiKey') + const expires = garminExpiry(body.expires) + if (expires === undefined) throw httpError(400, 'invalid_expires', 'expires') + await credentials.setGarmin(user.id, { apiKey, expires }) + log(JSON.stringify({ event: 'admin_provider_connected', by: admin.username, username: user.username, provider })) + } else { + const body = await bodyOf(req, ['clientId', 'clientSecret', 'code']) + if (!validStravaClientId(body.clientId)) throw httpError(400, 'invalid_client_id', 'clientId') + const clientSecret = cleanSecret(body.clientSecret) + if (!clientSecret) throw httpError(400, 'invalid_client_secret', 'clientSecret') + if (body.code.length > 2048) throw httpError(400, 'no_code', 'code') + /** @type {Awaited>} */ + let connected + try { + connected = await connectStravaApp({ credentials, fetchImpl }, user.id, { clientId: body.clientId, clientSecret, pasted: body.code }) + } catch { + // the network call to Strava failed: nothing was stored, and no detail that could hold a secret is passed on + throw httpError(502, 'strava_unreachable') + } + if (!connected.ok) { + log(JSON.stringify({ event: 'admin_provider_connect_failed', by: admin.username, username: user.username, provider, reason: connected.reason })) + if (connected.reason === 'no_code') throw httpError(400, 'no_code', 'code') + if (connected.reason === 'store_failed') throw httpError(500, 'internal') + throw httpError(502, connected.reason === 'refused' ? 'strava_refused' : 'strava_no_refresh_token') + } + log(JSON.stringify({ event: 'admin_provider_connected', by: admin.username, username: user.username, provider })) + // the running server looks at this user's credentials again now, not at their next sync + await providerStatus(user.id).catch(() => {}) + return send(res, 200, { athlete: connected.athlete, scope: connected.scope }) + } + await providerStatus(user.id).catch(() => {}) + res.writeHead(204, { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }) + res.end() + return + } + if (route.name === 'userLink') { + req.resume() + const user = await userOf(route.param) + const { token, expiresAt } = await links.issue(user.id) + log(JSON.stringify({ event: 'admin_password_link_issued', by: admin.username, username: user.username })) + return send(res, 201, { token, expires: iso(expiresAt) }) + } + req.resume() + const id = Number(route.param) + if ((await tokens.revoke(id, new Date(now()))) === 'missing') throw httpError(404, 'not_found') + log(JSON.stringify({ event: 'admin_token_revoked', by: admin.username, tokenId: id })) + res.writeHead(204, { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }) + res.end() + } + + return { + /** Handles /admin and /admin/*; false for any other path (the caller keeps routing). + * @param {Req} req @param {Res} res @param {URL} url */ + async handle (req, res, url) { + const path = url.pathname + if (path !== '/admin' && !path.startsWith('/admin/')) return false + try { + if (!hostAllowed(hostOfHeader(req.headers.host), allowedHosts)) throw httpError(421, 'misdirected') + if (req.headers['x-hc-admin'] !== '1') throw httpError(403, 'forbidden') + const route = routeOf(path) + if (!route) throw httpError(404, 'not_found') + if (!route.methods.includes(req.method ?? '')) { + req.resume() + send(res, 405, { error: 'method_not_allowed' }, { allow: route.methods.join(', ') }) + return true + } + if (req.method !== 'GET' && !writeOriginOk(req.headers, allowedHosts)) throw httpError(403, 'forbidden_origin') + // nobody has proved who they are in open mode: there is no admin to be + if (await auth.isOpen()) throw httpError(403, 'login_required') + const who = await auth.sessionOf(req) + if (!who) throw httpError(401, 'unauthenticated') + if (!who.admin) throw httpError(403, 'forbidden') + // a session that is looking at somebody else's page manages nobody: not even a list (server.js already refuses its writes) + if (who.viewing) throw httpError(403, 'viewing') + await dispatch(req, res, who, route) + } catch (thrown) { + const err = /** @type {Partial | null | undefined} */ (thrown) + if (res.headersSent) return true + if (err && err.status && err.code) { + if (err.status === 413) { + // stop reading an oversized upload: answer, then drop the connection + res.on('finish', () => req.destroy()) + send(res, 413, { error: err.code }, { connection: 'close' }) + } else { + req.resume() + send(res, err.status, err.field ? { error: err.code, field: err.field } : { error: err.code }) + } + } else { + log(JSON.stringify({ event: 'admin_error', message: err?.message ?? String(err) })) + req.resume() + send(res, 500, { error: 'internal' }) + } + } + return true + } + } +} diff --git a/services/loop-ingest/src/auth-db.js b/services/loop-ingest/src/auth-db.js index 5af055cc..7e6d2607 100644 --- a/services/loop-ingest/src/auth-db.js +++ b/services/loop-ingest/src/auth-db.js @@ -18,10 +18,51 @@ export function createAuthStore (pool) { return rows[0] ? { id: Number(rows[0].id) } : null }, - /** @param {string} username @returns {Promise<{ id: number, username: string, passwordHash: string | null } | null>} */ + /** @param {string} username @returns {Promise<{ id: number, username: string, passwordHash: string | null, admin: boolean, sharing: boolean } | null>} */ async findUserByUsername (username) { - const { rows } = await pool.query('SELECT id, username, password_hash FROM app_user WHERE username = $1', [username]) - return rows[0] ? { id: Number(rows[0].id), username: rows[0].username, passwordHash: rows[0].password_hash } : null + const { rows } = await pool.query('SELECT id, username, password_hash, is_admin, share_with_coach FROM app_user WHERE username = $1', [username]) + return rows[0] ? { id: Number(rows[0].id), username: rows[0].username, passwordHash: rows[0].password_hash, admin: rows[0].is_admin === true, sharing: rows[0].share_with_coach === true } : null + }, + + /** Makes the user an admin, or stops them being one. `last` when they are the only admin (an install always keeps one: + * the admins are locked while they are counted, so two removals cannot both win), `missing` when there is no such user. + * @param {number} userId @param {boolean} admin @returns {Promise<'ok' | 'last' | 'missing'>} */ + async setAdmin (userId, admin) { + const id = assertUserId(userId) + if (admin) { + const { rowCount } = await pool.query('UPDATE app_user SET is_admin = true WHERE id = $1', [id]) + return (rowCount ?? 0) === 1 ? 'ok' : 'missing' + } + const { rows } = await pool.query('SELECT is_admin FROM app_user WHERE id = $1', [id]) + if (!rows[0]) return 'missing' + if (rows[0].is_admin !== true) return 'ok' + // with the role goes any coach view their sessions had (sql/028): it ENDS here, it does not come back with the role + const { rows: changed } = await pool.query( + `WITH u AS (UPDATE app_user SET is_admin = false + WHERE id = $1 AND (SELECT count(*) FROM (SELECT id FROM app_user WHERE is_admin FOR UPDATE) admins) > 1 + RETURNING id), + v AS (UPDATE app_session SET viewing_user_id = NULL WHERE user_id IN (SELECT id FROM u) AND viewing_user_id IS NOT NULL) + SELECT id FROM u`, + [id] + ) + if (changed.length === 1) return 'ok' + // nothing changed: either the last admin, or somebody else removed this one meanwhile (then it is done) + const after = await pool.query('SELECT is_admin FROM app_user WHERE id = $1', [id]) + if (!after.rows[0]) return 'missing' + return after.rows[0].is_admin === true ? 'last' : 'ok' + }, + + /** The user's consent to be viewed by an admin (the coach view). false when there is no such user. + * @param {number} userId @param {boolean} sharing @returns {Promise} */ + async setSharing (userId, sharing) { + // consent taken back ENDS every view of this user (sql/028), in the same statement: sharing again later starts nothing + const { rows } = await pool.query( + `WITH u AS (UPDATE app_user SET share_with_coach = $2 WHERE id = $1 RETURNING id), + v AS (UPDATE app_session SET viewing_user_id = NULL WHERE NOT $2 AND viewing_user_id IN (SELECT id FROM u)) + SELECT id FROM u`, + [assertUserId(userId), sharing === true] + ) + return rows.length === 1 }, /** Changes ONLY the username of the user (sessions, tokens, credentials and data are keyed by the id, so nothing else moves). @@ -55,10 +96,11 @@ export function createAuthStore (pool) { return rows.length === 1 }, - /** Usernames, whether a password is set, creation date: never a hash. @returns {Promise<{ id: number, username: string, hasPassword: boolean, createdAt: Date }[]>} */ + /** Usernames, whether a password is set, role, sharing, creation date: never a hash. + * @returns {Promise<{ id: number, username: string, hasPassword: boolean, admin: boolean, sharing: boolean, createdAt: Date }[]>} */ async listUsers () { - const { rows } = await pool.query('SELECT id, username, password_hash IS NOT NULL AS has_password, created_at FROM app_user ORDER BY id') - return rows.map((r) => ({ id: Number(r.id), username: r.username, hasPassword: r.has_password === true, createdAt: r.created_at })) + const { rows } = await pool.query('SELECT id, username, password_hash IS NOT NULL AS has_password, is_admin, share_with_coach, created_at FROM app_user ORDER BY id') + return rows.map((r) => ({ id: Number(r.id), username: r.username, hasPassword: r.has_password === true, admin: r.is_admin === true, sharing: r.share_with_coach === true, createdAt: r.created_at })) }, /** @param {{ tokenHash: Buffer, userId: number, now: Date, expiresAt: Date }} session */ @@ -70,15 +112,31 @@ export function createAuthStore (pool) { }, /** The live session (not expired at `now`) and its user, or null. @param {Buffer} tokenHash @param {Date} now - * @returns {Promise<{ userId: number, username: string, lastSeenAt: Date } | null>} */ + * `viewing`: the user this session views (sql/028), ONLY while the session's user is an admin, the viewed user shares and + * is somebody else: the three conditions are in the join, so a change of any of them holds at this very read (and + * setSharing / setAdmin also clear the column, so a view that ended does not come back when the condition does). + * @returns {Promise<{ userId: number, username: string, admin: boolean, sharing: boolean, lastSeenAt: Date, viewing: { userId: number, username: string } | null } | null>} */ async findSession (tokenHash, now) { const { rows } = await pool.query( - `SELECT s.user_id, u.username, s.last_seen_at + `SELECT s.user_id, u.username, u.is_admin, u.share_with_coach, s.last_seen_at, v.id AS viewing_id, v.username AS viewing_username FROM app_session s JOIN app_user u ON u.id = s.user_id + LEFT JOIN app_user v ON v.id = s.viewing_user_id AND v.share_with_coach AND u.is_admin AND v.id <> u.id WHERE s.token_hash = $1 AND s.expires_at > $2`, [tokenHash, now] ) - return rows[0] ? { userId: Number(rows[0].user_id), username: rows[0].username, lastSeenAt: rows[0].last_seen_at } : null + const r = rows[0] + if (!r) return null + return { + userId: Number(r.user_id), username: r.username, admin: r.is_admin === true, sharing: r.share_with_coach === true, lastSeenAt: r.last_seen_at, + viewing: r.viewing_id == null ? null : { userId: Number(r.viewing_id), username: r.viewing_username } + } + }, + + /** Sets (or, with null, clears) the user a live session views. The CALLER has checked the rules (sessions.js); the read + * above checks them again every time. false when there is no such live session. @param {Buffer} tokenHash @param {number | null} userId @param {Date} now */ + async setViewing (tokenHash, userId, now) { + const { rowCount } = await pool.query('UPDATE app_session SET viewing_user_id = $2 WHERE token_hash = $1 AND expires_at > $3', [tokenHash, userId == null ? null : assertUserId(userId), now]) + return (rowCount ?? 0) === 1 }, /** @param {Buffer} tokenHash @param {Date} now */ diff --git a/services/loop-ingest/src/auth-routes.js b/services/loop-ingest/src/auth-routes.js index 72b4b2a0..05d2aaed 100644 --- a/services/loop-ingest/src/auth-routes.js +++ b/services/loop-ingest/src/auth-routes.js @@ -4,8 +4,19 @@ * * POST /auth/login {username, password} -> 200 {username} + the session cookie; any failure 401 invalid_credentials * POST /auth/logout ends the session the cookie names, clears the cookie -> 204 (also without a session) + * POST /auth/password {token, password} -> 204: sets the password of the user a one-time link belongs to + * (password-links.js; an admin issued it). 400 invalid_password (12 to 256 characters; the link + * stays usable), 410 invalid_link for a link that is unknown, expired, used or malformed. It + * needs no session (the person cannot sign in yet) and counts against the per-address budget + * POST /auth/view {username} -> 200 {viewing}: the coach view. The session of an ADMIN starts viewing, read-only, a + * user who shares (sessions.js); 403 not_shared for anything else (not an admin, no such user, a + * user who does not share, yourself: one answer). POST /auth/unview -> 204 ends it + * POST /auth/sharing {sharing: true|false} -> 200 {sharing}: the signed-in user's OWN consent to be viewed; 403 + * read_only while this session is viewing somebody (nobody changes another person's consent) * GET /auth/session 200 {open: true} while no user has a password (open single-user mode: no login needed), - * 200 {open: false, username} with a session, 401 unauthenticated without one + * 200 {open: false, username, admin, sharing, viewing} with a session (admin: may manage users and use + * the coach view; sharing: this user's consent to be viewed; viewing: the username this session + * views, or null; always the session's OWN user, also while viewing), 401 without one * * Cookie `hc_session`: HttpOnly (the page's scripts never see it), SameSite=Lax, Path=/, Max-Age 30 days, and * Secure when the request arrived over HTTPS. HTTPS is read from X-Forwarded-Proto === 'https' only, the way @@ -51,7 +62,7 @@ export const CLIENT_ADDRESS_HEADER = 'x-hc-client-address' /** @typedef {import('node:http').IncomingMessage} Req @typedef {import('node:http').ServerResponse} Res */ /** path -> the one method it takes */ -const ROUTES = /** @type {Record} */ ({ '/auth/login': 'POST', '/auth/logout': 'POST', '/auth/session': 'GET' }) +const ROUTES = /** @type {Record} */ ({ '/auth/login': 'POST', '/auth/logout': 'POST', '/auth/session': 'GET', '/auth/password': 'POST', '/auth/view': 'POST', '/auth/unview': 'POST', '/auth/sharing': 'POST' }) /** Whether the browser reached nginx over HTTPS. @param {Req} req */ function viaHttps (req) { @@ -77,10 +88,10 @@ function cookie (value, maxAgeSeconds, secure) { } /** - * @param {{ auth: import('./sessions.js').AuthService, now?: () => number, log?: (line: string) => void, allowedHosts?: string[], + * @param {{ auth: import('./sessions.js').AuthService, links?: Pick | null, now?: () => number, log?: (line: string) => void, allowedHosts?: string[], * addressLimit?: number, usernameLimit?: number, windowMs?: number }} options */ -export function createAuthRoutes ({ auth, now = Date.now, log = console.log, allowedHosts = [], addressLimit = LOGIN_ADDRESS_LIMIT, usernameLimit = LOGIN_USERNAME_LIMIT, windowMs = LOGIN_WINDOW_MS }) { +export function createAuthRoutes ({ auth, links = null, now = Date.now, log = console.log, allowedHosts = [], addressLimit = LOGIN_ADDRESS_LIMIT, usernameLimit = LOGIN_USERNAME_LIMIT, windowMs = LOGIN_WINDOW_MS }) { const byAddress = createWindowLimiter({ limit: addressLimit, windowMs, now }) const byUsername = createWindowLimiter({ limit: usernameLimit, windowMs, now }) @@ -121,6 +132,66 @@ export function createAuthRoutes ({ auth, now = Date.now, log = console.log, all send(res, 200, { username: session.username }, { 'set-cookie': cookie(session.token, session.maxAgeSeconds, viaHttps(req)) }) } + /** @param {Req} req @param {Res} res */ + async function password (req, res) { + if (!links) throw httpError(404, 'not_found') + if (!isJson(req)) throw httpError(415, 'unsupported_media_type') + const remote = clientAddress(req) + // the same per-address budget as a login: a link is 256 random bits, the budget only bounds the work a stranger can ask for + if (!byAddress.take(remote)) { + log(JSON.stringify({ event: 'login_rate_limited', by: 'address', remote })) + throw httpError(429, 'rate_limited') + } + const body = await readJson(req) + if (!body || typeof body !== 'object' || Array.isArray(body)) throw httpError(400, 'bad_request') + const keys = Object.keys(body) + if (keys.length !== 2 || !keys.includes('token') || !keys.includes('password') || typeof body.token !== 'string' || typeof body.password !== 'string') throw httpError(400, 'bad_request') + const result = await links.redeem(body.token, body.password) + if (!result.ok) { + if (result.reason === 'invalid_password') throw httpError(400, 'invalid_password', 'password') + log(JSON.stringify({ event: 'password_link_refused', remote })) + throw httpError(410, 'invalid_link') + } + log(JSON.stringify({ event: 'password_set_by_link', username: result.username })) + res.writeHead(204, { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }) + res.end() + } + + /** @param {Req} req @param {Res} res */ + async function view (req, res) { + if (!isJson(req)) throw httpError(415, 'unsupported_media_type') + const body = await readJson(req) + if (!body || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).length !== 1 || typeof body.username !== 'string') throw httpError(400, 'bad_request') + if (await auth.isOpen()) throw httpError(403, 'not_shared') + const started = await auth.startView(req, body.username) + if (!started.ok) throw started.reason === 'unauthenticated' ? httpError(401, 'unauthenticated') : httpError(403, 'not_shared') + log(JSON.stringify({ event: 'view_started', by: started.viewer, username: started.viewing })) + send(res, 200, { viewing: started.viewing }) + } + + /** @param {Req} req @param {Res} res */ + async function unview (req, res) { + req.resume() + await auth.endView(req) + res.writeHead(204, { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }) + res.end() + } + + /** @param {Req} req @param {Res} res */ + async function sharing (req, res) { + if (!isJson(req)) throw httpError(415, 'unsupported_media_type') + const body = await readJson(req) + if (!body || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).length !== 1 || typeof body.sharing !== 'boolean') throw httpError(400, 'bad_request') + if (await auth.isOpen()) throw httpError(401, 'unauthenticated') + const who = await auth.sessionOf(req) + if (!who) throw httpError(401, 'unauthenticated') + // consent is the person's own: a session that is looking at somebody else changes nothing + if (who.viewing) throw httpError(403, 'read_only') + if (!(await auth.setSharing(who.userId, body.sharing))) throw httpError(401, 'unauthenticated') + log(JSON.stringify({ event: 'sharing_changed', username: who.username, sharing: body.sharing })) + send(res, 200, { sharing: body.sharing }) + } + /** @param {Req} req @param {Res} res */ async function logout (req, res) { req.resume() @@ -135,7 +206,7 @@ export function createAuthRoutes ({ auth, now = Date.now, log = console.log, all if (await auth.isOpen()) return send(res, 200, { open: true }) const who = await auth.sessionOf(req) if (!who) throw httpError(401, 'unauthenticated') - return send(res, 200, { open: false, username: who.username }) + return send(res, 200, { open: false, username: who.username, admin: who.admin, sharing: who.sharing, viewing: who.viewing ? who.viewing.username : null }) } return { @@ -157,6 +228,10 @@ export function createAuthRoutes ({ auth, now = Date.now, log = console.log, all if (method === 'POST' && !writeOriginOk(req.headers, allowedHosts)) throw httpError(403, 'forbidden_origin') if (path === '/auth/login') await login(req, res) else if (path === '/auth/logout') await logout(req, res) + else if (path === '/auth/password') await password(req, res) + else if (path === '/auth/view') await view(req, res) + else if (path === '/auth/unview') await unview(req, res) + else if (path === '/auth/sharing') await sharing(req, res) else await session(req, res) } catch (thrown) { const err = /** @type {Partial | null | undefined} */ (thrown) @@ -168,7 +243,7 @@ export function createAuthRoutes ({ auth, now = Date.now, log = console.log, all send(res, 413, { error: err.code }, { connection: 'close' }) } else { req.resume() - send(res, err.status, { error: err.code }) + send(res, err.status, err.field ? { error: err.code, field: err.field } : { error: err.code }) } } else { log(JSON.stringify({ event: 'auth_error', message: err?.message ?? String(err) })) diff --git a/services/loop-ingest/src/import-install.js b/services/loop-ingest/src/import-install.js index 440ef298..262c7b96 100644 --- a/services/loop-ingest/src/import-install.js +++ b/services/loop-ingest/src/import-install.js @@ -68,7 +68,8 @@ export const IMPORT_TABLES = [ { table: 'garmin_sync_state', mode: 'natural', note: 'history_complete and the freshness status that match the imported activities; one row per user' }, { table: 'provider_credential', mode: 'providers', note: 'the Strava app and the Garmin key: only with --with-providers' }, { table: 'app_session', mode: 'skip', note: 'sessions are never moved: the person signs in again on this install' }, - { table: 'machine_token', mode: 'skip', note: 'machine tokens are never moved (only their hash exists): issue new ones with user.js token add' } + { table: 'machine_token', mode: 'skip', note: 'machine tokens are never moved (only their hash exists): issue new ones with user.js token add' }, + { table: 'password_link', mode: 'skip', note: 'a pending one-time password link is never moved: issue a new one on this install' } ] /** @param {string} id */ diff --git a/services/loop-ingest/src/migrations.js b/services/loop-ingest/src/migrations.js index c9b4bbe8..4204b79b 100644 --- a/services/loop-ingest/src/migrations.js +++ b/services/loop-ingest/src/migrations.js @@ -25,7 +25,7 @@ import { createHash } from 'node:crypto' /** Whether each optional group's migrations ran ({group: false} = that feature is unavailable). * @typedef {Record} MigrationAvailability */ -export const CORE_MIGRATIONS = ['001_init.sql', '002_strava.sql', '003_sync.sql', '004_athlete.sql', '005_athlete_refresh.sql', '008_strava_hr.sql', '009_strava_hr_retry.sql', '016_tenancy_core.sql', '023_auth.sql', '024_machine_token.sql', '025_provider_credential.sql'] +export const CORE_MIGRATIONS = ['001_init.sql', '002_strava.sql', '003_sync.sql', '004_athlete.sql', '005_athlete_refresh.sql', '008_strava_hr.sql', '009_strava_hr_retry.sql', '016_tenancy_core.sql', '023_auth.sql', '024_machine_token.sql', '025_provider_credential.sql', '026_roles.sql', '027_password_link.sql', '028_session_view.sql'] // optional groups: a failure disables only that feature (its routes answer 503) export const OPTIONAL_MIGRATIONS = { food: ['006_food.sql', '014_food_serving_default.sql', '017_food_tenancy.sql'], settings: ['007_settings.sql', '013_settings_locale.sql', '018_settings_tenancy.sql'], profile: ['011_profile.sql', '019_profile_tenancy.sql'], journal: ['010_journal.sql', '020_journal_tenancy.sql'], documents: ['012_documents.sql', '021_documents_tenancy.sql'], garmin: ['015_garmin.sql', '022_garmin_tenancy.sql'] } diff --git a/services/loop-ingest/src/password-link-db.js b/services/loop-ingest/src/password-link-db.js new file mode 100644 index 00000000..4049370d --- /dev/null +++ b/services/loop-ingest/src/password-link-db.js @@ -0,0 +1,54 @@ +/** + * The persistence of the one-time password links (sql/027). Only SQL lives here; password-links.js decides what a link + * is. A link is stored by the SHA-256 of its token (a Buffer, 32 bytes): the token never reaches the database, and no + * function here logs or returns a hash. + */ +import { assertUserId } from './tenancy.js' + +/** @typedef {import('./db.js').Queryable} Queryable */ + +/** @param {Queryable} pool */ +export function createPasswordLinkStore (pool) { + return { + /** Stores the user's link, replacing the one they had (one statement: there is never a moment with two). + * A missing user is the foreign-key error (23503). @param {{ userId: number, tokenHash: Buffer, now: Date, expiresAt: Date }} link */ + async replace ({ userId, tokenHash, now, expiresAt }) { + await pool.query( + `INSERT INTO password_link (user_id, token_hash, created_at, expires_at) VALUES ($1, $2, $3, $4) + ON CONFLICT (user_id) DO UPDATE SET token_hash = EXCLUDED.token_hash, created_at = EXCLUDED.created_at, expires_at = EXCLUDED.expires_at`, + [assertUserId(userId), tokenHash, now, expiresAt] + ) + }, + + /** Whether a link with this hash is live at `now` (a cheap check BEFORE any password hashing). @param {Buffer} tokenHash @param {Date} now @returns {Promise} */ + async isLive (tokenHash, now) { + const { rows } = await pool.query('SELECT 1 FROM password_link WHERE token_hash = $1 AND expires_at > $2', [tokenHash, now]) + return rows.length === 1 + }, + + /** + * Uses the link: in ONE statement it deletes the live link, sets its user's password hash and ends every session of + * that user. All or nothing, and a link is used at most once (two requests with the same link: one gets the user, + * the other null). Null also for an unknown or expired link. + * @param {Buffer} tokenHash @param {Date} now @param {string} passwordHash @returns {Promise<{ userId: number, username: string } | null>} + */ + async redeem (tokenHash, now, passwordHash) { + const { rows } = await pool.query( + `WITH l AS (DELETE FROM password_link WHERE token_hash = $1 AND expires_at > $2 RETURNING user_id), + u AS (UPDATE app_user SET password_hash = $3 WHERE id IN (SELECT user_id FROM l) RETURNING id, username), + d AS (DELETE FROM app_session WHERE user_id IN (SELECT id FROM u)) + SELECT id, username FROM u`, + [tokenHash, now, passwordHash] + ) + return rows[0] ? { userId: Number(rows[0].id), username: rows[0].username } : null + }, + + /** Deletes every link past its end; the number deleted. @param {Date} now @returns {Promise} */ + async deleteExpired (now) { + const { rowCount } = await pool.query('DELETE FROM password_link WHERE expires_at <= $1', [now]) + return rowCount ?? 0 + } + } +} + +/** @typedef {ReturnType} PasswordLinkStore */ diff --git a/services/loop-ingest/src/password-links.js b/services/loop-ingest/src/password-links.js new file mode 100644 index 00000000..607ee35e --- /dev/null +++ b/services/loop-ingest/src/password-links.js @@ -0,0 +1,68 @@ +/** + * One-time links to set a password (docs/lan-services.md -> Security -> Password links; sql/027; the SQL is + * password-link-db.js). An admin issues a link for a user (admin-routes.js) and hands it over; whoever holds it sets + * that user's password ONCE, within PASSWORD_LINK_TTL_MS (auth-routes.js POST /auth/password). So the admin never knows + * a password, and a person never needs a shell. + * + * The token is `hcp_` + 32 random bytes (base64url); only its SHA-256 is stored. A user has at most one link: issuing a + * new one cancels the old one. Using a link sets the password, ends every session of that user and deletes the link, in + * one statement. An unknown, expired, used or malformed link is the same answer ('invalid'); the cheap "is it live" + * check runs BEFORE the password is hashed, so a junk link never costs a scrypt. + */ +import { createHash, randomBytes } from 'node:crypto' +import { hashPassword, validPassword, SCRYPT_DEFAULTS } from './password.js' + +/** How long a link can be used. */ +export const PASSWORD_LINK_TTL_MS = 48 * 3_600_000 +const PREFIX = 'hcp_' +const LINK_RE = /^hcp_[A-Za-z0-9_-]{43}$/ + +/** @param {unknown} value @returns {value is string} */ +export function isPasswordLink (value) { + return typeof value === 'string' && LINK_RE.test(value) +} + +/** The stored form of a link token: SHA-256 of its 32 bytes. @param {string} token */ +export function hashPasswordLink (token) { + return createHash('sha256').update(Buffer.from(token.slice(PREFIX.length), 'base64url')).digest() +} + +/** + * @param {{ store: import('./password-link-db.js').PasswordLinkStore, now?: () => number, ttlMs?: number, + * params?: import('./password.js').ScryptParams, onPasswordSet?: () => void }} options + * `onPasswordSet`: called after a link set a password (the login service drops its cached open-mode answer) + */ +export function createPasswordLinks ({ store, now = Date.now, ttlMs = PASSWORD_LINK_TTL_MS, params = SCRYPT_DEFAULTS, onPasswordSet = () => {} }) { + return { + /** A new link for the user, replacing the one they had; the token is returned ONCE. + * @param {number} userId @returns {Promise<{ token: string, expiresAt: Date }>} */ + async issue (userId) { + const token = PREFIX + randomBytes(32).toString('base64url') + const at = new Date(now()) + const expiresAt = new Date(at.getTime() + ttlMs) + await store.deleteExpired(at).catch(() => {}) + await store.replace({ userId, tokenHash: hashPasswordLink(token), now: at, expiresAt }) + return { token, expiresAt } + }, + + /** + * Sets the password of the link's user. 'invalid_password' when the password is not 12 to 256 characters (the link + * stays usable), 'invalid_link' for a link that is malformed, unknown, expired or already used. + * @param {unknown} token @param {unknown} password + * @returns {Promise<{ ok: true, username: string } | { ok: false, reason: 'invalid_link' | 'invalid_password' }>} + */ + async redeem (token, password) { + if (!isPasswordLink(token)) return { ok: false, reason: 'invalid_link' } + const hash = hashPasswordLink(token) + if (!(await store.isLive(hash, new Date(now())))) return { ok: false, reason: 'invalid_link' } + if (!validPassword(password)) return { ok: false, reason: 'invalid_password' } + const passwordHash = await hashPassword(/** @type {string} */ (password), params) + const user = await store.redeem(hash, new Date(now()), passwordHash) + if (!user) return { ok: false, reason: 'invalid_link' } + onPasswordSet() + return { ok: true, username: user.username } + } + } +} + +/** @typedef {ReturnType} PasswordLinks */ diff --git a/services/loop-ingest/src/server.js b/services/loop-ingest/src/server.js index c216de5c..98b1fc5a 100644 --- a/services/loop-ingest/src/server.js +++ b/services/loop-ingest/src/server.js @@ -35,6 +35,10 @@ import { DEFAULT_USER_ID, machineUserId } from './tenancy.js' import { createAuthStore } from './auth-db.js' import { createAuthService } from './sessions.js' import { createAuthRoutes } from './auth-routes.js' +import { createAdminRoutes } from './admin-routes.js' +import { createPasswordLinkStore } from './password-link-db.js' +import { createPasswordLinks } from './password-links.js' +import { createUserEraser } from './user-delete.js' import { createSiteRoutes, createSiteMarker } from './site-routes.js' /** @typedef {import('node:http').IncomingMessage} Req @typedef {import('node:http').ServerResponse} Res */ @@ -193,8 +197,8 @@ const NO_ROUTES = { handle: async () => false } * garminEnabled?: boolean | (() => boolean), garminSync?: Runnable | null, garminFor?: (userId: number) => Promise, garminAvailable?: () => boolean, * handleGarminExport?: (req: Req, res: Res, url: URL) => Promise, * foodRoutes: RouteModule, journalRoutes?: RouteModule, documentRoutes?: RouteModule, filesExportRoutes?: RouteModule, - * stravaAnnotateRoutes?: RouteModule, authRoutes?: RouteModule, siteRoutes?: RouteModule, - * identify: (req: Req) => Promise<{ userId: number } | null>, + * stravaAnnotateRoutes?: RouteModule, authRoutes?: RouteModule, adminRoutes?: RouteModule, siteRoutes?: RouteModule, + * identify: (req: Req) => Promise<{ userId: number } | null>, isViewing?: (req: Req) => Promise, * syncRoutes: { handleSync: (req: Req, res: Res, userId: number) => unknown, handleStatus: (req: Req, res: Res, userId: number) => Promise }, * handleExport: (req: Req, res: Res, url: URL) => Promise, handleStravaExport: (req: Req, res: Res, url: URL) => Promise, * handleAthleteExport: (req: Req, res: Res) => Promise @@ -223,11 +227,15 @@ export function createHandler ({ stravaAnnotateRoutes = NO_ROUTES, // POST /auth/login, /auth/logout, GET /auth/session (auth-routes.js) authRoutes = NO_ROUTES, + // /admin/*: user management for a signed-in admin (admin-routes.js) + adminRoutes = NO_ROUTES, // GET /site: which file of the site folder a request is served (site-routes.js); loop-web's nginx obeys its X-Accel-Redirect siteRoutes = NO_ROUTES, // who a PERSON's request acts for (sessions.js): an identity, or null = not signed in (401); every route a person // uses (/food, /journal, POST /sync, GET /sync/status) asks it; the bearer-token routes never do identify, + // whether the request's session is viewing another user (the coach view): then it may only read + isViewing = async () => false, syncRoutes, handleExport, handleStravaExport, @@ -307,6 +315,15 @@ export function createHandler ({ } if (await authRoutes.handle(req, res, url)) return + // THE COACH VIEW IS READ-ONLY (sessions.js, sql/028): a session that is viewing another user writes nothing, whatever + // the route (the login routes above are the exception: they end the view or the session). One place, before every + // other route, so a route added later cannot forget it; identify() refuses the same request again as a backstop. + if (req.method !== 'GET' && req.method !== 'HEAD' && await isViewing(req)) { + req.resume() + send(res, 403, { error: 'read_only' }) + return + } + if (await adminRoutes.handle(req, res, url)) return if (await siteRoutes.handle(req, res, url)) return if (await foodRoutes.handle(req, res, url)) return if (await journalRoutes.handle(req, res, url)) return @@ -507,7 +524,8 @@ async function main () { // user 1's; any other bearer token is a per-user machine token looked up by its hash (machine-tokens.js) // A refresh child of another user holds a short-lived run credential instead (run-credentials.js): checked in memory first. const runCredentials = createRunCredentials() - const resolveMachineToken = createTokenResolver({ store: createMachineTokenStore(pool) }) + const machineTokens = createMachineTokenStore(pool) + const resolveMachineToken = createTokenResolver({ store: machineTokens }) const checkBearer = createBearerCheck(INGEST_TOKEN, { resolveToken: resolveMachineToken, resolveRunToken: runCredentials.resolve }) const handleExport = createExportHandler({ pool, token: INGEST_TOKEN, checkBearer }) const handleStravaExport = createStravaExportHandler({ pool, token: INGEST_TOKEN, checkBearer }) @@ -525,9 +543,10 @@ async function main () { const fileSeq = () => (container ? readPublishedSeq(build.siteDir) : readTriggerSeq(TRIGGER_DIR)) // Garmin has its own optional tables (015): until 015_garmin.sql ran (or if it failed) the loop stays off and its routes answer 503. let garminReady = false + const providerCredentials = createProviderCredentialStore(pool) const providers = createProviderSyncs({ pool, - store: createProviderCredentialStore(pool), + store: providerCredentials, env: process.env, ownerId: DEFAULT_USER_ID, // read when a user's sync is built, after the composition below (builds is declared further down) @@ -561,11 +580,14 @@ async function main () { // install stays in open single-user mode (every person route acts as user 1, as before login existed); as soon as // one has, a session is required. One line at start-up says which mode this is (see start()). A request carrying a // run credential (a refresh child's reads of /food and /journal) is that run's user (run-credentials.js). - const auth = createAuthService({ store: createAuthStore(pool) }) + const authStore = createAuthStore(pool) + const auth = createAuthService({ store: authStore }) // who a person-route request is: a run credential (the refresh child), else a machine token (a coach clone acting for its // user), else the browser's session. The env token is NOT an identity here once a password exists. const identify = withRunCredential(withMachineToken((/** @type {Req} */ req) => auth.identify(req), resolveMachineToken), runCredentials) - const authRoutes = createAuthRoutes({ auth, allowedHosts: parseAllowedHosts(process.env.FOOD_ALLOWED_HOSTS) }) + // one-time links to set a password: an admin issues one (admin-routes.js), its holder uses it once (POST /auth/password) + const passwordLinks = createPasswordLinks({ store: createPasswordLinkStore(pool), onPasswordSet: () => auth.passwordChanged() }) + const authRoutes = createAuthRoutes({ auth, links: passwordLinks, allowedHosts: parseAllowedHosts(process.env.FOOD_ALLOWED_HOSTS) }) // PER-USER DISK (container mode; lib/user-paths.mjs is the one path rule, loaded here because the plain loop-ingest image // does not ship lib/): user 1's data root, files folder and site dir are the configured ones, every other user's sit @@ -575,6 +597,22 @@ async function main () { // the page build's output folder default, as scripts/refresh.mjs resolves it when HC_BUILD_DIR is unset const buildDirBase = path.resolve(String(process.env.HC_BUILD_DIR ?? '').trim() || path.join(os.tmpdir(), 'loop-build', 'personal')) const roots = userRoots ? { base: baseRoots, userRoots, userBuildDir, buildDirBase } : null + // user management from the page: the same stores and rules as scripts/user.js (user-admin.js), for a signed-in admin only + const adminRoutes = createAdminRoutes({ + auth, + store: authStore, + tokens: machineTokens, + links: passwordLinks, + credentials: providerCredentials, + // looks again at that user's credentials, so a connection made or removed from the page holds for the next sync at once + providerStatus: async (userId) => { + const [strava, garminNow] = await Promise.all([providers.strava.refresh(userId), providers.garmin.describe(userId)]) + return { strava, garmin: garminNow.configured, garminExpires: garminNow.keyExpires } + }, + eraser: createUserEraser(pool), + roots: baseRoots, + allowedHosts: parseAllowedHosts(process.env.FOOD_ALLOWED_HOSTS) + }) // On-demand refresh, sequence protocol: POST /sync assigns a sequence number, // kicks the (shared, never overlapping) Strava pull unless one succeeded in the @@ -699,7 +737,9 @@ async function main () { }), syncRoutes, identify, + isViewing: (req) => auth.isViewing(req), authRoutes, + adminRoutes, siteRoutes, handleExport, handleStravaExport, diff --git a/services/loop-ingest/src/sessions.js b/services/loop-ingest/src/sessions.js index 8ce1f423..f5b7213c 100644 --- a/services/loop-ingest/src/sessions.js +++ b/services/loop-ingest/src/sessions.js @@ -15,12 +15,18 @@ * setPassword() in THIS process drops it at once. A "required" answer is cached for the life of the process (the * safe direction: nothing in the service removes a password). A failing check throws: it never answers open. * + * Coach view (sql/028): a session of an admin may be viewing another user who shares. identify() then answers the + * VIEWED user, marked `readOnly`, for GET and HEAD only; for any other method it throws 403 read_only, so no route that + * asks identify can write as the viewed user (server.js refuses such a request earlier, with the same answer; this is + * the backstop). sessionOf() keeps answering the session's own user, with `viewing`: the login and admin routes ask it. + * * Login: the username is folded to lowercase; an unknown user, a user without a password and a wrong password all * return null after ONE password verification (the unknown ones against a dummy hash made with the same * parameters), so the answer and its cost do not tell which case it was. */ import { createHash, randomBytes } from 'node:crypto' import { DEFAULT_USER_ID } from './tenancy.js' +import { httpError } from './http.js' import { hashPassword, verifyPassword, validPassword, normalizeUsername, SCRYPT_DEFAULTS, PASSWORD_MIN, PASSWORD_MAX } from './password.js' /** The session cookie's name. */ @@ -51,7 +57,8 @@ export function hashToken (token) { } /** - * @typedef {{ userId: number, username: string | null, open: boolean }} Identity who a request acts for (username null in open mode) + * @typedef {{ userId: number, username: string | null, open: boolean, readOnly?: boolean, viewer?: { userId: number, username: string } }} Identity + * who a request acts for (username null in open mode); `readOnly` + `viewer`: an admin viewing this user (the coach view) * @param {{ store: import('./auth-db.js').AuthStore, now?: () => number, log?: (line: string) => void, * params?: import('./password.js').ScryptParams, verify?: (password: string, stored: string) => Promise, * ttlMs?: number, touchIntervalMs?: number, openCacheMs?: number }} options @@ -80,7 +87,8 @@ export function createAuthService ({ store, now = Date.now, log = console.log, p } /** The user of the session a request carries, refreshing its last-seen; null for none, junk or expired. - * @param {import('node:http').IncomingMessage} req @returns {Promise<{ userId: number, username: string } | null>} */ + * `admin` and `sharing` are read with the session on every request, so a role or a consent that changes holds at once. + * @param {import('node:http').IncomingMessage} req @returns {Promise<{ userId: number, username: string, admin: boolean, sharing: boolean, viewing: { userId: number, username: string } | null } | null>} */ async function sessionOf (req) { const presented = sessionTokenOf(req) if (!presented) return null @@ -97,7 +105,7 @@ export function createAuthService ({ store, now = Date.now, log = console.log, p // bookkeeping only: a failed refresh never fails the request await store.touchSession(presented.hash, at).catch((err) => log(JSON.stringify({ event: 'session_touch_failed', message: err.message }))) } - return { userId: found.userId, username: found.username } + return { userId: found.userId, username: found.username, admin: found.admin, sharing: found.sharing, viewing: found.viewing } } return { @@ -109,7 +117,48 @@ export function createAuthService ({ store, now = Date.now, log = console.log, p async identify (req) { if (await isOpen()) return { userId: DEFAULT_USER_ID, username: null, open: true } const s = await sessionOf(req) - return s ? { userId: s.userId, username: s.username, open: false } : null + if (!s) return null + if (!s.viewing) return { userId: s.userId, username: s.username, open: false } + // the coach view: the viewed user's data, to read only + if (req.method !== 'GET' && req.method !== 'HEAD') throw httpError(403, 'read_only') + return { userId: s.viewing.userId, username: s.viewing.username, open: false, readOnly: true, viewer: { userId: s.userId, username: s.username } } + }, + + /** + * Starts the coach view of `username` on the session a request carries. Only an admin's session, only a user who + * shares, never yourself: anything else is 'refused' (one answer: it does not say which rule failed). + * @param {import('node:http').IncomingMessage} req @param {unknown} username + * @returns {Promise<{ ok: true, viewer: string, viewing: string } | { ok: false, reason: 'unauthenticated' | 'refused' }>} + */ + async startView (req, username) { + const presented = sessionTokenOf(req) + const s = await sessionOf(req) + if (!presented || !s) return { ok: false, reason: 'unauthenticated' } + const name = normalizeUsername(username) + const target = name == null ? null : await store.findUserByUsername(name) + if (!s.admin || !target || !target.sharing || target.id === s.userId) return { ok: false, reason: 'refused' } + if (!(await store.setViewing(presented.hash, target.id, new Date(now())))) return { ok: false, reason: 'unauthenticated' } + return { ok: true, viewer: s.username, viewing: target.username } + }, + + /** Whether the request's session is viewing another user (the coach view): server.js lets such a request only read. + * Never without a session cookie, never in open mode (there is no session to carry a view). @param {import('node:http').IncomingMessage} req @returns {Promise} */ + async isViewing (req) { + // no session cookie, no view: a request without one (the Shortcut's upload, a coach clone) costs no database read here + if (!sessionTokenOf(req)) return false + if (await isOpen()) return false + return (await sessionOf(req))?.viewing != null + }, + + /** Ends the coach view of the session a request carries (no-op without one). @param {import('node:http').IncomingMessage} req */ + async endView (req) { + const presented = sessionTokenOf(req) + if (presented) await store.setViewing(presented.hash, null, new Date(now())) + }, + + /** The user's own consent to be viewed (sql/026). false when the user is gone. @param {number} userId @param {boolean} sharing */ + async setSharing (userId, sharing) { + return store.setSharing(userId, sharing) }, /** @@ -135,6 +184,11 @@ export function createAuthService ({ store, now = Date.now, log = console.log, p return { token: tokenBytes.toString('base64url'), username: user.username, maxAgeSeconds: Math.floor(ttlMs / 1000) } }, + /** A password was set outside setPassword() (a one-time link, password-links.js): drops the cached open-mode answer. */ + passwordChanged () { + openCheckedAt = null + }, + /** Ends the session a request presents (no-op without one). @param {import('node:http').IncomingMessage} req */ async logout (req) { const presented = sessionTokenOf(req) diff --git a/services/loop-ingest/src/strava-oauth.js b/services/loop-ingest/src/strava-oauth.js new file mode 100644 index 00000000..3232611c --- /dev/null +++ b/services/loop-ingest/src/strava-oauth.js @@ -0,0 +1,67 @@ +/** + * Strava's authorization-code steps, shared by scripts/strava-auth.js (the owner's env setup), scripts/user.js strava + * (another user's own API app) and the admin routes (admin-routes.js): the URL a person opens to authorize, reading the + * code out of what they paste back, and the one exchange of that code for a refresh token. No state, no storage. + */ +export const REDIRECT_URI = 'http://localhost/exchange_token' +export const SCOPE = 'read,activity:read_all,activity:write,profile:read_all' + +/** @param {string} clientId @returns {string} */ +export function authorizeUrl (clientId) { + const url = new URL('https://www.strava.com/oauth/authorize') + url.searchParams.set('client_id', clientId) + url.searchParams.set('response_type', 'code') + url.searchParams.set('redirect_uri', REDIRECT_URI) + url.searchParams.set('approval_prompt', 'force') + url.searchParams.set('scope', SCOPE) + return url.toString() +} + +/** + * Accept either the bare code or the whole redirected URL — pasting the full + * address bar is the obvious thing to do, so handle it. + * @param {string} input + * @returns {string | null} + */ +export function extractCode (input) { + const trimmed = input.trim() + if (!trimmed) return null + + if (/^https?:\/\//i.test(trimmed)) { + const fromUrl = new URL(trimmed).searchParams.get('code') + return fromUrl?.trim() || null + } + + // A pasted query fragment, with or without a leading '?'. + if (trimmed.includes('code=')) { + return new URLSearchParams(trimmed.replace(/^\?/, '')).get('code')?.trim() || null + } + + return trimmed +} + +/** + * The code-for-token exchange (the one place that talks to Strava's token endpoint with an authorization code; scripts/user.js + * strava uses it too). Never throws on an answer: `{ ok: false, status, text }` for a refusal (the response text is + * the caller's to show or not), `{ ok: false, status, noRefreshToken: true }` for an answer without a refresh token, else + * `{ ok: true, refreshToken, scope, athlete }`. A network failure rejects. + * @param {{ clientId: string, clientSecret: string, code: string, fetchImpl?: typeof fetch }} options + * @returns {Promise<{ ok: true, refreshToken: string, scope: string | undefined, athlete: { firstname?: string, lastname?: string } | undefined } + * | { ok: false, status: number, text?: string, noRefreshToken?: boolean }>} + */ +export async function exchangeCode ({ clientId, clientSecret, code, fetchImpl = fetch }) { + const res = await fetchImpl('https://www.strava.com/oauth/token', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + client_id: clientId, + client_secret: clientSecret, + code, + grant_type: 'authorization_code' + }) + }) + if (!res.ok) return { ok: false, status: res.status, text: await res.text() } + const body = /** @type {{ scope?: string, refresh_token?: unknown, athlete?: { firstname?: string, lastname?: string } }} */ (await res.json()) + if (typeof body.refresh_token !== 'string' || !body.refresh_token) return { ok: false, status: res.status, noRefreshToken: true } + return { ok: true, refreshToken: body.refresh_token, scope: body.scope, athlete: body.athlete } +} diff --git a/services/loop-ingest/src/user-admin.js b/services/loop-ingest/src/user-admin.js new file mode 100644 index 00000000..190ac536 --- /dev/null +++ b/services/loop-ingest/src/user-admin.js @@ -0,0 +1,99 @@ +/** + * The user operations the user script (scripts/user.js) and the admin routes (admin-routes.js) share, so a rule is + * written once: what a token label may be, how a token is issued, and the order of a delete (the rows in one + * transaction first, the folders only after it committed). Nothing here prints, prompts or answers HTTP. + */ +import { newMachineToken, hashMachineToken } from './machine-tokens.js' +import { assertRoots, removeUserFolders } from './user-delete.js' +import { extractCode, exchangeCode } from './strava-oauth.js' +import { garminKeyExpires } from './garmin.js' +import { OWNER_USER_ID } from '../../../lib/user-paths.mjs' + +/** The longest label of a machine token. */ +export const TOKEN_LABEL_MAX = 64 + +/** A label is shown in a list, one line per token: at most TOKEN_LABEL_MAX characters, no control character. @param {unknown} label @returns {label is string} */ +export function validTokenLabel (label) { + // eslint-disable-next-line no-control-regex + return typeof label === 'string' && label.length <= TOKEN_LABEL_MAX && !/[\u0000-\u001f\u007f]/.test(label) +} + +/** + * Issues a machine token for the user: only its hash is stored; the token is returned ONCE, to be shown once. + * @param {Pick} tokens @param {number} userId @param {string} label a validTokenLabel + * @returns {Promise<{ id: number, token: string }>} + */ +export async function issueMachineToken (tokens, userId, label) { + if (!validTokenLabel(label)) throw new RangeError(`a label is at most ${TOKEN_LABEL_MAX} characters, without control characters`) + const token = newMachineToken() + const { id } = await tokens.add({ userId, tokenHash: hashMachineToken(token), label }) + return { id, token } +} + +/** @typedef {{ dataDir: string, filesDir?: string | null, siteDir: string }} Roots */ + +/** + * Deletes a user and everything of theirs: every row in ONE transaction (user-delete.js), and only after it committed + * the user's folders under the roots. The owner of the install (user 1) is refused, and so is a root that cannot be + * used, BEFORE anything is deleted. `rows` is null when the user was already gone (nothing was deleted here). + * @param {{ eraser: Pick, 'erase'>, roots: Roots | null, rm?: typeof import('node:fs').promises.rm }} deps + * `roots` null: no folder is configured here, only the rows go + * @param {number} userId + * @returns {Promise<{ rows: { table: string, rows: number }[] | null, folders: Awaited> }>} + */ +export async function deleteUserEverywhere ({ eraser, roots, rm }, userId) { + if (userId === OWNER_USER_ID) throw new Error('the owner of the install (user 1) is never deleted') + if (roots) assertRoots(roots) + const rows = await eraser.erase(userId) + if (rows === null || !roots) return { rows, folders: [] } + return { rows, folders: await removeUserFolders(roots, userId, rm ? { rm } : {}) } +} + +/** The longest secret a person may paste (a client secret, a Garmin key). */ +export const SECRET_MAX = 4096 + +/** A pasted secret value: trimmed, then non-blank, bounded, no whitespace or control character inside. @param {unknown} value @returns {string | null} */ +export function cleanSecret (value) { + if (typeof value !== 'string') return null + const v = value.trim() + // eslint-disable-next-line no-control-regex + return v.length >= 1 && v.length <= SECRET_MAX && !/[\s\u0000-\u001f\u007f]/.test(v) ? v : null +} + +/** The id of a Strava API app: letters, digits, dash, underscore, 1 to 64. @param {unknown} id @returns {id is string} */ +export function validStravaClientId (id) { + return typeof id === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(id) +} + +/** A Garmin key's expiry as the caller gave it: null for none, the YYYY-MM-DD date, or undefined when it is not a calendar date. + * @param {unknown} value @returns {string | null | undefined} */ +export function garminExpiry (value) { + if (value == null || value === '') return null + if (typeof value !== 'string') return undefined + return garminKeyExpires({ GARMIN_API_KEY_EXPIRES: value }) ?? undefined +} + +/** + * Connects a user's OWN Strava API app: exchanges the authorization code the person pasted (the bare code or the whole + * redirected address) for a refresh token, then stores the app and the token in ONE transaction (both or neither). The + * caller has validated `clientId` (validStravaClientId) and `clientSecret` (cleanSecret). Nothing is stored unless `ok`. + * A failure never carries Strava's response text or a driver message: neither can hold a secret that way. + * @param {{ credentials: Pick, 'connectStrava'>, fetchImpl?: typeof fetch }} deps + * @param {number} userId @param {{ clientId: string, clientSecret: string, pasted: string }} input + * @returns {Promise<{ ok: true, athlete: string, scope: string | null } + * | { ok: false, reason: 'no_code' | 'no_refresh_token' | 'store_failed' } | { ok: false, reason: 'refused', status: number }>} + */ +export async function connectStravaApp ({ credentials, fetchImpl = fetch }, userId, { clientId, clientSecret, pasted }) { + /** @type {string | null} */ + let code + try { code = extractCode(pasted) } catch { code = null } + if (!code) return { ok: false, reason: 'no_code' } + const exchanged = await exchangeCode({ clientId, clientSecret, code, fetchImpl }) + if (!exchanged.ok) return exchanged.noRefreshToken ? { ok: false, reason: 'no_refresh_token' } : { ok: false, reason: 'refused', status: exchanged.status } + try { + await credentials.connectStrava(userId, { clientId, clientSecret }, exchanged.refreshToken) + } catch { + return { ok: false, reason: 'store_failed' } + } + return { ok: true, athlete: [exchanged.athlete?.firstname, exchanged.athlete?.lastname].filter(Boolean).join(' '), scope: exchanged.scope ?? null } +} diff --git a/services/loop-ingest/test/admin-routes.test.js b/services/loop-ingest/test/admin-routes.test.js new file mode 100644 index 00000000..071ee791 --- /dev/null +++ b/services/loop-ingest/test/admin-routes.test.js @@ -0,0 +1,453 @@ +/** + * The admin routes (src/admin-routes.js) over a real HTTP server with in-memory stores: who may use them (a signed-in + * admin's session and nothing else), every route's success and refusals, and what a delete does. The same operations + * over real rows are in test/pg/admin-routes.pg.test.js. Synthetic data only. + */ +import test from 'node:test' +import assert from 'node:assert/strict' +import http from 'node:http' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { createAuthService } from '../src/sessions.js' +import { createAdminRoutes } from '../src/admin-routes.js' +import { hashMachineToken, isMachineToken } from '../src/machine-tokens.js' +import { createPasswordLinks, isPasswordLink } from '../src/password-links.js' +import { memoryAuthStore, memoryLinkStore, FAST_SCRYPT } from './auth-helper.js' + +const PW = { owner: 'owner has a long password', andrea: 'andrea has a long password', maria: 'maria has a long password' } + +function memoryTokens () { + /** @type {{ id: number, userId: number, tokenHash: Buffer, label: string, createdAt: Date, lastUsedAt: Date | null, revokedAt: Date | null }[]} */ + const rows = [] + return { + rows, + /** @param {{ userId: number, tokenHash: Buffer, label: string }} t */ + async add (t) { rows.push({ id: rows.length + 1, ...t, createdAt: new Date('2030-01-02T00:00:00Z'), lastUsedAt: null, revokedAt: null }); return { id: rows.length } }, + /** @param {number} userId */ + async listForUser (userId) { return rows.filter((r) => r.userId === userId).map(({ tokenHash: _h, userId: _u, ...rest }) => rest) }, + /** @param {number} id @param {Date} now @returns {Promise<'revoked' | 'already' | 'missing'>} */ + async revoke (id, now) { + const r = rows.find((x) => x.id === id) + if (!r) return 'missing' + if (r.revokedAt) return 'already' + r.revokedAt = now + return 'revoked' + } + } +} + +/** @param {{ roots?: import('../src/user-admin.js').Roots | null, rm?: typeof fs.promises.rm }} [o] */ +async function setup ({ roots = null, rm } = {}) { + const store = memoryAuthStore() + const tokens = memoryTokens() + /** @type {string[]} */ + const events = [] + /** @type {number[]} */ + const erased = [] + const auth = createAuthService({ store, log: () => {}, params: FAST_SCRYPT }) + for (const name of ['owner', 'andrea', 'maria']) { + if (name !== 'owner') await store.addUser(name) + await auth.setPassword(name, PW[/** @type {keyof typeof PW} */ (name)]) + } + const eraser = { + /** @param {number} userId */ + async erase (userId) { + const i = store.users.findIndex((u) => u.id === userId) + if (i < 0) return null + store.users.splice(i, 1) + erased.push(userId) + return [{ table: 'food_log', rows: 3 }, { table: 'app_user', rows: 1 }] + } + } + /** @type {Map} */ + const stored = new Map() + /** @type {{ url: string, body: any }[]} */ + const stravaCalls = [] + const strava = { status: 200, body: /** @type {any} */ ({ refresh_token: 'r-secret', scope: 'read', athlete: { firstname: 'Ana', lastname: 'Ruiz' } }), fail: false, storeFails: false } + const credentials = { + /** @param {number} userId @param {{ clientId: string, clientSecret: string }} app @param {string} refreshToken */ + async connectStrava (userId, app, refreshToken) { + if (strava.storeFails) throw new Error('db down with secret s3cr3t') + stored.set(`${userId}:strava`, { ...app, refreshToken }) + }, + /** @param {number} userId @param {{ apiKey: string, expires?: string | null }} key */ + async setGarmin (userId, key) { stored.set(`${userId}:garmin`, key) }, + /** @param {number} userId @param {string} provider */ + async remove (userId, provider) { return stored.delete(`${userId}:${provider}`) } + } + /** @type {any} */ + const fetchImpl = async (/** @type {string} */ url, /** @type {{ body: string }} */ init) => { + stravaCalls.push({ url, body: JSON.parse(init.body) }) + if (strava.fail) throw new Error('network down') + return { ok: strava.status === 200, status: strava.status, text: async () => 'refused detail', json: async () => strava.body } + } + /** @type {number[]} */ + const looked = [] + const providerStatus = async (/** @type {number} */ userId) => { + looked.push(userId) + return { strava: stored.has(`${userId}:strava`), garmin: stored.has(`${userId}:garmin`), garminExpires: stored.get(`${userId}:garmin`)?.expires ?? null } + } + const linkStore = memoryLinkStore(store) + const links = createPasswordLinks({ store: linkStore, now: () => Date.parse('2030-01-10T12:00:00Z'), params: FAST_SCRYPT }) + const routes = createAdminRoutes({ auth, store, tokens, links, credentials, providerStatus, fetchImpl, eraser, roots, rm, log: (l) => events.push(l), now: () => Date.parse('2030-01-10T12:00:00Z') }) + const server = http.createServer(async (req, res) => { + const url = new URL(/** @type {string} */ (req.url), 'http://localhost') + if (!(await routes.handle(req, res, url))) { res.writeHead(404); res.end('{"error":"outer"}') } + }) + await /** @type {Promise} */ (new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))) + const port = /** @type {import('node:net').AddressInfo} */ (server.address()).port + /** @param {string} method @param {string} path @param {{ body?: unknown, raw?: string, headers?: Record, as?: string | null }} [opts] + * @returns {Promise<{ status: number | undefined, headers: http.IncomingHttpHeaders, body: any }>} */ + function call (method, path, { body, raw, headers = {}, as = 'owner' } = {}) { + const payload = raw ?? (body === undefined ? undefined : JSON.stringify(body)) + /** @type {Record} */ + const h = { host: `127.0.0.1:${port}`, 'x-hc-admin': '1' } + if (as) h.cookie = `hc_session=${cookies[as]}` + if (payload !== undefined) { h['content-type'] = 'application/json'; h['content-length'] = Buffer.byteLength(payload) } + for (const [k, v] of Object.entries(headers)) { if (v === undefined) delete h[k]; else h[k] = v } + return new Promise((resolve, reject) => { + const req = http.request({ host: '127.0.0.1', port, method, path, headers: h }, (res) => { + let text = '' + res.on('data', (c) => { text += c }) + res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body: text ? JSON.parse(text) : null })) + }) + req.on('error', reject) + req.end(payload) + }) + } + /** @type {Record} */ + const cookies = {} + for (const name of ['owner', 'andrea']) cookies[name] = /** @type {{ token: string }} */ (await auth.login(name, PW[/** @type {keyof typeof PW} */ (name)])).token + return { store, tokens, events, erased, auth, linkStore, links, stored, strava, stravaCalls, looked, call, close: () => new Promise((resolve) => server.close(resolve)) } +} + +test('only a signed-in admin: no session 401, a session that is not an admin 403, the header and the path are checked first', async () => { + const t = await setup() + try { + const every = /** @type {[string, string, unknown][]} */ ([ + ['GET', '/admin/users', undefined], ['POST', '/admin/users', { username: 'x' }], ['PUT', '/admin/users/maria', { username: 'x' }], + ['DELETE', '/admin/users/maria', { confirm: 'maria' }], ['GET', '/admin/users/maria/tokens', undefined], + ['POST', '/admin/users/maria/tokens', { label: '' }], ['DELETE', '/admin/tokens/1', undefined], + ['POST', '/admin/users/maria/password-link', undefined], ['GET', '/admin/users/maria/providers', undefined], + ['POST', '/admin/strava/authorize-url', { clientId: '123' }], ['PUT', '/admin/users/maria/strava', { clientId: '123', clientSecret: 's', code: 'c' }], + ['DELETE', '/admin/users/maria/strava', undefined], ['PUT', '/admin/users/maria/garmin', { apiKey: 'k', expires: '' }], ['DELETE', '/admin/users/maria/garmin', undefined] + ]) + for (const [method, path, body] of every) { + const none = await t.call(method, path, { body, as: null }) + assert.deepEqual([none.status, none.body], [401, { error: 'unauthenticated' }], `${method} ${path} without a session`) + const plain = await t.call(method, path, { body, as: 'andrea' }) + assert.deepEqual([plain.status, plain.body], [403, { error: 'forbidden' }], `${method} ${path} as a user who is not an admin`) + assert.equal((await t.call(method, path, { body, headers: { 'x-hc-admin': undefined } })).status, 403, `${method} ${path} without the header`) + assert.equal((await t.call(method, path, { body, headers: { host: 'evil.example' } })).status, 421, `${method} ${path} with a foreign Host`) + } + assert.equal(t.store.users.length, 3, 'nothing changed') + assert.equal(t.tokens.rows.length, 0) + assert.equal(t.linkStore.links.size, 0) + assert.equal(t.stored.size, 0) + assert.deepEqual(t.stravaCalls, [], 'Strava was never called') + assert.deepEqual(t.erased, []) + assert.deepEqual(t.events, []) + assert.equal((await t.call('GET', '/admin/nothing')).status, 404) + const wrong = await t.call('PATCH', '/admin/users') + assert.deepEqual([wrong.status, wrong.headers.allow], [405, 'GET, POST']) + assert.equal((await t.call('GET', '/other')).body.error, 'outer', 'other paths are not handled here') + } finally { await t.close() } +}) + +test('the role is read on every request: an admin who is turned off loses the routes at once, and a new admin gets them', async () => { + const t = await setup() + try { + assert.equal((await t.call('GET', '/admin/users')).status, 200) + t.store.users[1].admin = true + t.store.users[0].admin = false + assert.equal((await t.call('GET', '/admin/users')).status, 403) + assert.equal((await t.call('GET', '/admin/users', { as: 'andrea' })).status, 200) + } finally { await t.close() } +}) + +test('open mode (no password exists) has no admin: 403 login_required', async () => { + const store = memoryAuthStore() + const auth = createAuthService({ store, log: () => {}, params: FAST_SCRYPT }) + const routes = createAdminRoutes({ auth, store, tokens: memoryTokens(), links: { issue: async () => { throw new Error('never') } }, credentials: /** @type {any} */ ({}), providerStatus: async () => ({ strava: false, garmin: false, garminExpires: null }), eraser: { erase: async () => null }, roots: null, log: () => {} }) + /** @type {{ status?: number, body?: string }} */ + const got = {} + const res = /** @type {any} */ ({ headersSent: false, writeHead (/** @type {number} */ s) { got.status = s }, end (/** @type {string} */ b) { got.body = b }, on () {} }) + const req = /** @type {any} */ ({ method: 'GET', headers: { host: 'localhost', 'x-hc-admin': '1' }, resume () {} }) + assert.equal(await routes.handle(req, res, new URL('http://localhost/admin/users')), true) + assert.deepEqual([got.status, got.body], [403, '{"error":"login_required"}']) +}) + +test('a write from another origin is refused; a body must be JSON with exactly its keys', async () => { + const t = await setup() + try { + const cross = await t.call('POST', '/admin/users', { body: { username: 'x' }, headers: { origin: 'https://evil.example' } }) + assert.deepEqual([cross.status, cross.body], [403, { error: 'forbidden_origin' }]) + assert.equal((await t.call('POST', '/admin/users', { raw: '{"username":"x"}', headers: { 'content-type': 'text/plain' } })).status, 415) + assert.deepEqual((await t.call('POST', '/admin/users', { raw: '{' })).body, { error: 'bad_json' }) + for (const body of [{}, { username: 1 }, { username: 'x', admin: true }, ['x'], null]) { + assert.deepEqual((await t.call('POST', '/admin/users', { body })).body, { error: 'bad_request' }, JSON.stringify(body)) + } + assert.equal((await t.call('POST', '/admin/users', { raw: JSON.stringify({ username: 'x'.repeat(20_000) }) })).status, 413) + assert.equal(t.store.users.length, 3) + } finally { await t.close() } +}) + +test('GET /admin/users lists everyone without a hash or an id; POST adds a user without a password', async () => { + const t = await setup() + try { + t.store.users[1].sharing = true + const list = await t.call('GET', '/admin/users') + assert.equal(list.status, 200) + assert.equal(list.headers['cache-control'], 'no-store') + assert.deepEqual(list.body.users.map((/** @type {any} */ u) => [u.username, u.hasPassword, u.admin, u.sharing, u.owner, u.self]), + [['owner', true, true, false, true, true], ['andrea', true, false, true, false, false], ['maria', true, false, false, false, false]]) + assert.deepEqual(Object.keys(list.body.users[0]).sort(), ['admin', 'created', 'hasPassword', 'owner', 'self', 'sharing', 'username']) + + const added = await t.call('POST', '/admin/users', { body: { username: 'Pedro' } }) + assert.deepEqual([added.status, added.body], [201, { username: 'pedro' }]) + const pedro = t.store.users.find((u) => u.username === 'pedro') + assert.deepEqual([pedro?.passwordHash, pedro?.admin, pedro?.sharing], [null, false, false]) + assert.deepEqual((await t.call('POST', '/admin/users', { body: { username: 'pedro' } })).body, { error: 'username_taken', field: 'username' }) + assert.deepEqual((await t.call('POST', '/admin/users', { body: { username: 'bad name' } })).body, { error: 'invalid_username', field: 'username' }) + assert.deepEqual(t.events.map((e) => JSON.parse(e)), [{ event: 'admin_user_added', by: 'owner', username: 'pedro' }]) + } finally { await t.close() } +}) + +test('PUT /admin/users/ renames: only the name changes; taken, invalid and unknown are refused', async () => { + const t = await setup() + try { + const ok = await t.call('PUT', '/admin/users/maria', { body: { username: 'Mary' } }) + assert.deepEqual([ok.status, ok.body], [200, { username: 'mary' }]) + assert.deepEqual(t.store.users.map((u) => [u.id, u.username]), [[1, 'owner'], [2, 'andrea'], [3, 'mary']]) + assert.deepEqual((await t.call('PUT', '/admin/users/mary', { body: { username: 'andrea' } })).body, { error: 'username_taken', field: 'username' }) + assert.deepEqual((await t.call('PUT', '/admin/users/mary', { body: { username: 'a b' } })).body, { error: 'invalid_username', field: 'username' }) + for (const path of ['/admin/users/maria', '/admin/users/Mary', '/admin/users/%ZZ', '/admin/users/a%2Fb']) { + assert.equal((await t.call('PUT', path, { body: { username: 'zed' } })).status, 404, path) + } + assert.equal((await t.call('PUT', '/admin/users/mary', { body: { username: 'mary' } })).status, 200, 'the same name is no change') + assert.deepEqual(t.events.map((e) => JSON.parse(e)), [{ event: 'admin_user_renamed', by: 'owner', from: 'maria', to: 'mary' }]) + assert.equal((await t.call('GET', '/admin/users')).status, 200, 'an admin can rename themselves and stays signed in') + assert.equal((await t.call('PUT', '/admin/users/owner', { body: { username: 'boss' } })).status, 200) + assert.equal((await t.call('GET', '/admin/users')).body.users[0].username, 'boss') + } finally { await t.close() } +}) + +test('DELETE /admin/users/: needs the name again; never user 1, never yourself; reports folders left to remove by hand', async () => { + const t = await setup() + try { + assert.deepEqual((await t.call('DELETE', '/admin/users/maria', { body: { confirm: 'mari' } })).body, { error: 'confirmation_mismatch', field: 'confirm' }) + assert.deepEqual((await t.call('DELETE', '/admin/users/maria', { body: {} })).body, { error: 'bad_request' }) + assert.deepEqual((await t.call('DELETE', '/admin/users/owner', { body: { confirm: 'owner' } })).body, { error: 'owner_never_deleted' }) + t.store.users[1].admin = true + const self = await t.call('DELETE', '/admin/users/andrea', { body: { confirm: 'andrea' }, as: 'andrea' }) + assert.deepEqual([self.status, self.body], [403, { error: 'cannot_delete_self' }]) + assert.deepEqual((await t.call('DELETE', '/admin/users/owner', { body: { confirm: 'owner' }, as: 'andrea' })).body, { error: 'owner_never_deleted' }, 'also for another admin') + assert.equal((await t.call('DELETE', '/admin/users/nobody', { body: { confirm: 'nobody' } })).status, 404) + assert.deepEqual(t.erased, [], 'nothing was deleted so far') + + const done = await t.call('DELETE', '/admin/users/maria', { body: { confirm: 'maria' } }) + assert.deepEqual([done.status, done.body], [200, { deleted: 'maria', manual: [] }]) + assert.deepEqual(t.erased, [3]) + assert.deepEqual(t.store.users.map((u) => u.username), ['owner', 'andrea']) + assert.deepEqual(JSON.parse(t.events[0]), { event: 'admin_user_deleted', by: 'owner', username: 'maria', userId: 3, rows: 4, manual: [] }) + assert.equal((await t.call('DELETE', '/admin/users/maria', { body: { confirm: 'maria' } })).status, 404, 'gone') + } finally { await t.close() } +}) + +test('tokens: POST answers the token once and stores only its hash; GET never shows it; DELETE revokes', async () => { + const t = await setup() + try { + const made = await t.call('POST', '/admin/users/andrea/tokens', { body: { label: 'iPhone' } }) + assert.equal(made.status, 201) + assert.deepEqual(Object.keys(made.body).sort(), ['id', 'token']) + assert.ok(isMachineToken(made.body.token)) + assert.equal(t.tokens.rows.length, 1) + assert.deepEqual([t.tokens.rows[0].userId, t.tokens.rows[0].label], [2, 'iPhone']) + assert.ok(t.tokens.rows[0].tokenHash.equals(hashMachineToken(made.body.token)), 'only the hash is stored') + assert.ok(!t.events.join('\n').includes(made.body.token), 'the token is never logged') + assert.deepEqual(JSON.parse(t.events[0]), { event: 'admin_token_added', by: 'owner', username: 'andrea', tokenId: 1 }) + + for (const label of ['x'.repeat(65), 'a\tb', 'a\nb']) { + assert.deepEqual((await t.call('POST', '/admin/users/andrea/tokens', { body: { label } })).body, { error: 'invalid_label', field: 'label' }) + } + assert.equal((await t.call('POST', '/admin/users/nobody/tokens', { body: { label: '' } })).status, 404) + assert.equal(t.tokens.rows.length, 1) + + const list = await t.call('GET', '/admin/users/andrea/tokens') + assert.deepEqual(list.body, { tokens: [{ id: 1, label: 'iPhone', created: '2030-01-02T00:00:00.000Z', lastUsed: null, revoked: null }] }) + assert.deepEqual((await t.call('GET', '/admin/users/maria/tokens')).body, { tokens: [] }, 'another user sees none of them') + + assert.equal((await t.call('DELETE', '/admin/tokens/1')).status, 204) + assert.equal(t.tokens.rows[0].revokedAt?.toISOString(), '2030-01-10T12:00:00.000Z') + assert.equal((await t.call('DELETE', '/admin/tokens/1')).status, 204, 'already revoked is done') + assert.equal(t.tokens.rows[0].revokedAt?.toISOString(), '2030-01-10T12:00:00.000Z', 'the first date stays') + assert.equal((await t.call('DELETE', '/admin/tokens/9')).status, 404) + for (const path of ['/admin/tokens/0', '/admin/tokens/abc', '/admin/tokens/12345678901234567']) assert.equal((await t.call('DELETE', path)).status, 404, path) + } finally { await t.close() } +}) + +test('POST /admin/users//password-link: a one-time link token, 48 hours, replacing the one that user had; it sets that user\'s password once', async () => { + const t = await setup() + try { + const first = await t.call('POST', '/admin/users/maria/password-link') + assert.equal(first.status, 201) + assert.deepEqual(Object.keys(first.body).sort(), ['expires', 'token']) + assert.ok(isPasswordLink(first.body.token)) + assert.equal(first.body.expires, '2030-01-12T12:00:00.000Z') + assert.ok(!t.events.join('\n').includes(first.body.token), 'the link is never logged') + assert.deepEqual(JSON.parse(t.events[0]), { event: 'admin_password_link_issued', by: 'owner', username: 'maria' }) + const second = await t.call('POST', '/admin/users/maria/password-link') + assert.notEqual(second.body.token, first.body.token) + assert.equal(t.linkStore.links.size, 1, 'one link per user') + assert.deepEqual(await t.links.redeem(first.body.token, 'a brand new password'), { ok: false, reason: 'invalid_link' }, 'the replaced link is dead') + const before = t.store.users.map((u) => u.passwordHash) + assert.deepEqual(await t.links.redeem(second.body.token, 'a brand new password'), { ok: true, username: 'maria' }) + const after = t.store.users.map((u) => u.passwordHash) + assert.deepEqual([after[0], after[1]], [before[0], before[1]], 'only maria changed') + assert.notEqual(after[2], before[2]) + assert.equal((await t.auth.login('maria', 'a brand new password'))?.username, 'maria') + assert.equal((await t.call('POST', '/admin/users/nobody/password-link')).status, 404) + } finally { await t.close() } +}) + +test('Strava from the page: the authorize URL, then the user\'s own app and code are exchanged and stored; no answer or log line holds a secret', async () => { + const t = await setup() + try { + const url = await t.call('POST', '/admin/strava/authorize-url', { body: { clientId: '12345' } }) + assert.equal(url.status, 200) + assert.match(url.body.url, /^https:\/\/www\.strava\.com\/oauth\/authorize\?client_id=12345&/) + assert.deepEqual((await t.call('POST', '/admin/strava/authorize-url', { body: { clientId: 'a b' } })).body, { error: 'invalid_client_id', field: 'clientId' }) + + const ok = await t.call('PUT', '/admin/users/andrea/strava', { body: { clientId: '12345', clientSecret: ' app-secret ', code: 'http://localhost/exchange_token?state=&code=abc123&scope=read' } }) + assert.deepEqual([ok.status, ok.body], [200, { athlete: 'Ana Ruiz', scope: 'read' }]) + assert.deepEqual(t.stravaCalls[0].body, { client_id: '12345', client_secret: 'app-secret', code: 'abc123', grant_type: 'authorization_code' }) + assert.deepEqual(t.stored.get('2:strava'), { clientId: '12345', clientSecret: 'app-secret', refreshToken: 'r-secret' }) + assert.deepEqual([...t.stored.keys()], ['2:strava'], 'only that user') + assert.ok(t.looked.includes(2), 'the running server looks at that user again') + const said = JSON.stringify(ok.body) + t.events.join('\n') + assert.ok(!said.includes('app-secret') && !said.includes('r-secret') && !said.includes('abc123')) + assert.deepEqual(JSON.parse(t.events[0]), { event: 'admin_provider_connected', by: 'owner', username: 'andrea', provider: 'strava' }) + assert.deepEqual((await t.call('GET', '/admin/users/andrea/providers')).body, { strava: true, garmin: false, garminExpires: null }) + assert.deepEqual((await t.call('GET', '/admin/users/maria/providers')).body, { strava: false, garmin: false, garminExpires: null }) + + assert.equal((await t.call('DELETE', '/admin/users/andrea/strava')).status, 204) + assert.equal(t.stored.size, 0) + assert.equal((await t.call('DELETE', '/admin/users/andrea/strava')).status, 204, 'none left is done') + assert.equal((await t.call('PUT', '/admin/users/nobody/strava', { body: { clientId: '1', clientSecret: 's', code: 'c' } })).status, 404) + } finally { await t.close() } +}) + +test('Strava refusals store nothing: bad id, bad secret, no code, a refused code, no refresh token, Strava unreachable, a failing store', async () => { + const t = await setup() + try { + const put = (/** @type {any} */ body) => t.call('PUT', '/admin/users/andrea/strava', { body }) + assert.deepEqual((await put({ clientId: 'a b', clientSecret: 's', code: 'c' })).body, { error: 'invalid_client_id', field: 'clientId' }) + assert.deepEqual((await put({ clientId: '1', clientSecret: 'a b', code: 'c' })).body, { error: 'invalid_client_secret', field: 'clientSecret' }) + assert.deepEqual((await put({ clientId: '1', clientSecret: 's', code: ' ' })).body, { error: 'no_code', field: 'code' }) + assert.deepEqual((await put({ clientId: '1', clientSecret: 's', code: 'http://localhost/exchange_token?error=access_denied' })).body, { error: 'no_code', field: 'code' }) + assert.deepEqual((await put({ clientId: '1', clientSecret: 's' })).body, { error: 'bad_request' }) + assert.deepEqual(t.stravaCalls, [], 'Strava is not called for input that cannot work') + + t.strava.status = 400 + const refused = await put({ clientId: '1', clientSecret: 's', code: 'c' }) + assert.deepEqual([refused.status, refused.body], [502, { error: 'strava_refused' }], 'Strava\'s own text is not passed on') + t.strava.status = 200 + t.strava.body = { scope: 'read' } + assert.deepEqual((await put({ clientId: '1', clientSecret: 's', code: 'c' })).body, { error: 'strava_no_refresh_token' }) + t.strava.fail = true + assert.deepEqual((await put({ clientId: '1', clientSecret: 's', code: 'c' })).body, { error: 'strava_unreachable' }) + t.strava.fail = false + t.strava.body = { refresh_token: 'r-secret' } + t.strava.storeFails = true + const failed = await put({ clientId: '1', clientSecret: 's', code: 'c' }) + assert.deepEqual([failed.status, failed.body], [500, { error: 'internal' }]) + assert.equal(t.stored.size, 0) + assert.ok(!t.events.join('\n').includes('s3cr3t') && !t.events.join('\n').includes('r-secret'), 'no driver message or token in the log') + assert.ok(t.events.every((e) => JSON.parse(e).event === 'admin_provider_connect_failed')) + } finally { await t.close() } +}) + +test('Garmin from the page: the key and an optional expiry are stored for that user, removed again; bad input is refused', async () => { + const t = await setup() + try { + assert.equal((await t.call('PUT', '/admin/users/andrea/garmin', { body: { apiKey: ' key-123 ', expires: '2031-02-28' } })).status, 204) + assert.deepEqual(t.stored.get('2:garmin'), { apiKey: 'key-123', expires: '2031-02-28' }) + assert.deepEqual((await t.call('GET', '/admin/users/andrea/providers')).body, { strava: false, garmin: true, garminExpires: '2031-02-28' }) + assert.equal((await t.call('PUT', '/admin/users/andrea/garmin', { body: { apiKey: 'key-456', expires: '' } })).status, 204) + assert.deepEqual(t.stored.get('2:garmin'), { apiKey: 'key-456', expires: null }) + assert.ok(!t.events.join('\n').includes('key-'), 'a key is never logged') + assert.deepEqual((await t.call('PUT', '/admin/users/andrea/garmin', { body: { apiKey: 'a b', expires: '' } })).body, { error: 'invalid_api_key', field: 'apiKey' }) + for (const expires of ['2031-02-30', 'tomorrow', '31/12/2031']) { + assert.deepEqual((await t.call('PUT', '/admin/users/andrea/garmin', { body: { apiKey: 'k', expires } })).body, { error: 'invalid_expires', field: 'expires' }, expires) + } + assert.deepEqual(t.stored.get('2:garmin'), { apiKey: 'key-456', expires: null }, 'a refused change leaves the stored key') + assert.equal((await t.call('DELETE', '/admin/users/andrea/garmin')).status, 204) + assert.equal(t.stored.size, 0) + assert.equal((await t.call('GET', '/admin/users/nobody/providers')).status, 404) + } finally { await t.close() } +}) + +test('DELETE removes the user\'s folders under the three roots after the rows; a folder it cannot remove is answered in `manual`, the others still go', async (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'loop-admin-routes-')) + t.after(() => fs.rmSync(dir, { recursive: true, force: true })) + const roots = { dataDir: path.join(dir, 'data'), filesDir: path.join(dir, 'files'), siteDir: path.join(dir, 'site') } + for (const root of Object.values(roots)) { + for (const id of ['2', '3']) { + fs.mkdirSync(path.join(root, 'users', id), { recursive: true }) + fs.writeFileSync(path.join(root, 'users', id, 'x.txt'), id) + } + fs.writeFileSync(path.join(root, 'owner.txt'), 'owner') + } + const readOnly = path.join(roots.filesDir, 'users', '3') + /** @type {typeof fs.promises.rm} */ + const rm = async (target, options) => { + if (target === readOnly) throw Object.assign(new Error('EROFS: read-only file system'), { code: 'EROFS' }) + return fs.promises.rm(target, options) + } + const s = await setup({ roots, rm }) + try { + const done = await s.call('DELETE', '/admin/users/maria', { body: { confirm: 'maria' } }) + assert.deepEqual([done.status, done.body], [200, { deleted: 'maria', manual: [readOnly] }]) + assert.deepEqual(s.erased, [3]) + assert.equal(fs.existsSync(path.join(roots.dataDir, 'users', '3')), false) + assert.equal(fs.existsSync(path.join(roots.siteDir, 'users', '3')), false) + assert.equal(fs.existsSync(readOnly), true) + for (const root of Object.values(roots)) { + assert.equal(fs.readFileSync(path.join(root, 'users', '2', 'x.txt'), 'utf8'), '2', 'another user keeps their folder') + assert.equal(fs.readFileSync(path.join(root, 'owner.txt'), 'utf8'), 'owner', 'user 1 keeps the root') + } + assert.deepEqual(JSON.parse(s.events[0]).manual, [readOnly]) + } finally { await s.close() } +}) + +test('DELETE with a root that cannot be used deletes nothing: 500 and the user is still there', async () => { + const s = await setup({ roots: { dataDir: 'relative/data', filesDir: null, siteDir: '/tmp/site' } }) + try { + const r = await s.call('DELETE', '/admin/users/maria', { body: { confirm: 'maria' } }) + assert.deepEqual([r.status, r.body], [500, { error: 'internal' }]) + assert.deepEqual(s.erased, []) + assert.equal(s.store.users.length, 3) + } finally { await s.close() } +}) + +test('while the admin\'s session views somebody, every admin route is 403 viewing (reads included); ending the view gives them back', async () => { + const t = await setup() + try { + t.store.users[1].sharing = true + const owner = /** @type {{ token: string }} */ (await t.auth.login('owner', PW.owner)).token + const as = { cookie: `hc_session=${owner}` } + assert.deepEqual(await t.auth.startView(/** @type {any} */ ({ method: 'POST', headers: as }), 'andrea'), { ok: true, viewer: 'owner', viewing: 'andrea' }) + for (const [method, path, body] of /** @type {[string, string, unknown][]} */ ([ + ['GET', '/admin/users', undefined], ['GET', '/admin/users/andrea/tokens', undefined], ['GET', '/admin/users/andrea/providers', undefined], + ['POST', '/admin/users', { username: 'x' }], ['DELETE', '/admin/users/maria', { confirm: 'maria' }], ['POST', '/admin/users/maria/password-link', undefined] + ])) { + const r = await t.call(method, path, { body, headers: as, as: null }) + assert.deepEqual([r.status, r.body], [403, { error: 'viewing' }], `${method} ${path}`) + } + assert.equal(t.store.users.length, 3) + assert.deepEqual(t.events, []) + await t.auth.endView(/** @type {any} */ ({ method: 'POST', headers: as })) + assert.equal((await t.call('GET', '/admin/users', { headers: as, as: null })).status, 200) + } finally { await t.close() } +}) diff --git a/services/loop-ingest/test/auth-helper.js b/services/loop-ingest/test/auth-helper.js index d0b59e0b..b1207152 100644 --- a/services/loop-ingest/test/auth-helper.js +++ b/services/loop-ingest/test/auth-helper.js @@ -11,13 +11,13 @@ export const FAST_SCRYPT = { N: 1024, r: 8, p: 1, keylen: 32, saltLen: 16 } /** What `identify` answers in open mode: the routes act as user 1 without a session (the pre-login behaviour). */ export const openIdentify = async () => ({ userId: DEFAULT_USER_ID, username: null, open: true }) -/** @typedef {{ id: number, username: string, passwordHash: string | null, createdAt: Date }} MemUser */ -/** @typedef {{ userId: number, createdAt: Date, lastSeenAt: Date, expiresAt: Date }} MemSession */ +/** @typedef {{ id: number, username: string, passwordHash: string | null, createdAt: Date, admin: boolean, sharing: boolean }} MemUser */ +/** @typedef {{ userId: number, createdAt: Date, lastSeenAt: Date, expiresAt: Date, viewingUserId?: number | null }} MemSession */ /** In-memory auth store. `users` / `sessions` (keyed by the hex of the token hash) are exposed for assertions. */ export function memoryAuthStore () { /** @type {MemUser[]} */ - const users = [{ id: 1, username: 'owner', passwordHash: null, createdAt: new Date('2030-01-01T00:00:00Z') }] + const users = [{ id: 1, username: 'owner', passwordHash: null, createdAt: new Date('2030-01-01T00:00:00Z'), admin: true, sharing: false }] /** @type {Map} */ const sessions = new Map() const key = (/** @type {Buffer} */ h) => h.toString('hex') @@ -29,14 +29,30 @@ export function memoryAuthStore () { /** @param {string} username */ async addUser (username) { if (users.some((u) => u.username === username)) return null - const user = { id: Math.max(...users.map((u) => u.id)) + 1, username, passwordHash: null, createdAt: new Date() } + const user = { id: Math.max(...users.map((u) => u.id)) + 1, username, passwordHash: null, createdAt: new Date(), admin: false, sharing: false } users.push(user) return { id: user.id } }, /** @param {string} username */ async findUserByUsername (username) { const u = users.find((x) => x.username === username) - return u ? { id: u.id, username: u.username, passwordHash: u.passwordHash } : null + return u ? { id: u.id, username: u.username, passwordHash: u.passwordHash, admin: u.admin, sharing: u.sharing } : null + }, + /** @param {number} userId @param {boolean} admin @returns {Promise<'ok' | 'last' | 'missing'>} */ + async setAdmin (userId, admin) { + const u = users.find((x) => x.id === userId) + if (!u) return 'missing' + if (!admin && u.admin && users.filter((x) => x.admin).length === 1) return 'last' + u.admin = admin + if (!admin) for (const sess of sessions.values()) if (sess.userId === userId) sess.viewingUserId = null + return 'ok' + }, + /** @param {number} userId @param {boolean} sharing */ + async setSharing (userId, sharing) { + const u = users.find((x) => x.id === userId) + if (u) u.sharing = sharing + if (u && !sharing) for (const sess of sessions.values()) if (sess.viewingUserId === userId) sess.viewingUserId = null + return !!u }, /** @param {number} userId @param {string} username */ async renameUser (userId, username) { @@ -55,7 +71,7 @@ export function memoryAuthStore () { for (const [k, s] of sessions) if (s.userId === userId) sessions.delete(k) return true }, - async listUsers () { return users.map((u) => ({ id: u.id, username: u.username, hasPassword: u.passwordHash != null, createdAt: u.createdAt })) }, + async listUsers () { return users.map((u) => ({ id: u.id, username: u.username, hasPassword: u.passwordHash != null, admin: u.admin, sharing: u.sharing, createdAt: u.createdAt })) }, /** @param {{ tokenHash: Buffer, userId: number, now: Date, expiresAt: Date }} s */ async insertSession ({ tokenHash, userId, now, expiresAt }) { sessions.set(key(tokenHash), { userId, createdAt: now, lastSeenAt: now, expiresAt }) @@ -65,7 +81,17 @@ export function memoryAuthStore () { const s = sessions.get(key(tokenHash)) if (!s || s.expiresAt <= now) return null const u = users.find((x) => x.id === s.userId) - return u ? { userId: u.id, username: u.username, lastSeenAt: s.lastSeenAt } : null + if (!u) return null + const v = s.viewingUserId == null ? undefined : users.find((x) => x.id === s.viewingUserId) + const viewing = v && v.sharing && u.admin && v.id !== u.id ? { userId: v.id, username: v.username } : null + return { userId: u.id, username: u.username, admin: u.admin, sharing: u.sharing, lastSeenAt: s.lastSeenAt, viewing } + }, + /** @param {Buffer} tokenHash @param {number | null} userId @param {Date} now */ + async setViewing (tokenHash, userId, now) { + const s = sessions.get(key(tokenHash)) + if (!s || s.expiresAt <= now) return false + s.viewingUserId = userId + return true }, /** @param {Buffer} tokenHash @param {Date} now */ async touchSession (tokenHash, now) { @@ -85,3 +111,35 @@ export function memoryAuthStore () { /** sha-256 of a presented cookie token the way sessions.js stores it. @param {string} token */ export const hashOfToken = (token) => createHash('sha256').update(Buffer.from(token, 'base64url')).digest() + +/** In-memory password-link store with the contract of src/password-link-db.js, over a memoryAuthStore's users and sessions. + * `links` (keyed by user id) is exposed for assertions. @param {ReturnType} auth */ +export function memoryLinkStore (auth) { + /** @type {Map} */ + const links = new Map() + return { + links, + /** @param {{ userId: number, tokenHash: Buffer, now: Date, expiresAt: Date }} link */ + async replace ({ userId, tokenHash, expiresAt }) { links.set(userId, { tokenHash, expiresAt }) }, + /** @param {Buffer} tokenHash @param {Date} now */ + async isLive (tokenHash, now) { return [...links.values()].some((l) => l.tokenHash.equals(tokenHash) && l.expiresAt > now) }, + /** @param {Buffer} tokenHash @param {Date} now @param {string} passwordHash */ + async redeem (tokenHash, now, passwordHash) { + for (const [userId, l] of links) { + if (!l.tokenHash.equals(tokenHash) || l.expiresAt <= now) continue + links.delete(userId) + const u = auth.users.find((x) => x.id === userId) + if (!u) return null + await auth.setPassword(userId, passwordHash) + return { userId, username: u.username } + } + return null + }, + /** @param {Date} now */ + async deleteExpired (now) { + let n = 0 + for (const [k, l] of links) if (l.expiresAt <= now) { links.delete(k); n++ } + return n + } + } +} diff --git a/services/loop-ingest/test/auth-protected.test.js b/services/loop-ingest/test/auth-protected.test.js index 525cc9d7..546f2622 100644 --- a/services/loop-ingest/test/auth-protected.test.js +++ b/services/loop-ingest/test/auth-protected.test.js @@ -57,6 +57,7 @@ async function setup ({ passwords = { owner: PW1, andrea: PW2 } } = {}) { stravaEnabled: false, stravaSync: null, identify, + isViewing: (req) => auth.isViewing(req), authRoutes: createAuthRoutes({ auth, now, log: () => {}, addressLimit: 1000, usernameLimit: 1000 }), foodRoutes: createFoodRoutes({ store: /** @type {any} */ (recordingStore(storeCalls)), off: /** @type {any} */ ({}), identify, log: () => {} }), journalRoutes: createJournalRoutes({ store: /** @type {any} */ (recordingStore(storeCalls)), identify, log: () => {} }), @@ -225,3 +226,142 @@ test('a database failure while resolving the session is a 500, never an open doo } } finally { await t.close() } }) + +test('the coach view: an admin viewing a user who shares READS that user\'s rows on every route and can write nothing, anywhere', async () => { + const t = await setup() + try { + t.authStore.users[1].sharing = true + const coach = await t.session('owner', PW1) + const andrea = await t.session('andrea', PW2) + assert.deepEqual((await t.call('POST', '/auth/view', { cookie: coach, body: { username: 'andrea' } })).body, { viewing: 'andrea' }) + assert.deepEqual((await t.call('GET', '/auth/session', { cookie: coach })).body, { open: false, username: 'owner', admin: true, sharing: false, viewing: 'andrea' }) + + t.storeCalls.length = 0 + for (const [method, path] of PROTECTED.filter((p) => p[0] === 'GET' && !p[1].startsWith('/food/off') && !p[1].startsWith('/sync'))) { + const r = await t.call(method, path, { cookie: coach }) + assert.ok(r.status < 400, `${method} ${path} -> ${r.status}`) + } + assert.ok(t.storeCalls.length >= 6) + assert.deepEqual([...new Set(t.storeCalls.map((c) => c[1]))], [2], 'every read acted for the viewed user') + assert.deepEqual((await t.call('GET', '/sync/status', { cookie: coach })).body, { who: 2 }, 'the viewed user\'s status') + + t.storeCalls.length = 0 + const writes = /** @type {Array<[string, string, unknown?]>} */ ([ + ['POST', '/food/log', { date: '2030-01-10' }], ['PUT', '/food/settings', { goal: 'maintain' }], ['PUT', '/food/profile', {}], ['POST', '/food/products', {}], + ['PUT', '/food/products/1', {}], ['DELETE', '/food/products/1'], ['POST', '/food/recipes', {}], ['DELETE', '/food/recipes/1'], ['DELETE', '/food/log/5'], + ['PUT', '/journal/day?date=2030-01-10', {}], ['PUT', '/journal/settings', { behaviors: {} }], ['POST', '/sync'], + ['POST', '/admin/users', { username: 'x' }], ['DELETE', '/admin/users/andrea', { confirm: 'andrea' }], ['PUT', '/documents/plan', {}], + ['PATCH', '/food/log/5', {}], ['POST', '/anything/else', {}], ['DELETE', '/food/unknown'] + ]) + for (const [method, path, body] of writes) { + const r = await t.call(method, path, { cookie: coach, body }) + assert.deepEqual([r.status, r.body], [403, { error: 'read_only' }], `${method} ${path}`) + } + assert.deepEqual(t.storeCalls, [], 'no store was reached by a write') + assert.deepEqual(t.other, [], 'no ingest either') + + assert.deepEqual((await t.call('POST', '/auth/sharing', { cookie: coach, body: { sharing: true } })).body, { error: 'read_only' }, 'not even the consent switch') + assert.equal(t.authStore.users[0].sharing, false) + + // the viewed person is untouched and still writes their own rows + assert.deepEqual((await t.call('GET', '/auth/session', { cookie: andrea })).body.viewing, null) + const own = await t.call('PUT', '/journal/settings', { cookie: andrea, body: { behaviors: {} } }) + assert.notEqual(own.status, 403) + + assert.equal((await t.call('POST', '/auth/unview', { cookie: coach })).status, 204) + t.storeCalls.length = 0 + await t.call('GET', '/food/settings', { cookie: coach }) + assert.deepEqual([...new Set(t.storeCalls.map((c) => c[1]))], [1], 'back to their own rows') + assert.notEqual((await t.call('PUT', '/journal/settings', { cookie: coach, body: { behaviors: {} } })).status, 403, 'and they can write again') + } finally { await t.close() } +}) + +test('the coach view ends at the next request when consent is taken back, when the viewer stops being an admin, and at sign-out', async () => { + const t = await setup() + try { + t.authStore.users[1].sharing = true + const coach = await t.session('owner', PW1) + const andrea = await t.session('andrea', PW2) + const whose = async () => { t.storeCalls.length = 0; await t.call('GET', '/food/settings', { cookie: coach }); return t.storeCalls[0][1] } + await t.call('POST', '/auth/view', { cookie: coach, body: { username: 'andrea' } }) + assert.equal(await whose(), 2) + + assert.deepEqual((await t.call('POST', '/auth/sharing', { cookie: andrea, body: { sharing: false } })).body, { sharing: false }) + assert.equal(await whose(), 1, 'consent taken back: the very next request is the coach\'s own') + assert.equal((await t.call('GET', '/auth/session', { cookie: coach })).body.viewing, null) + assert.equal((await t.call('POST', '/auth/view', { cookie: coach, body: { username: 'andrea' } })).status, 403) + + await t.call('POST', '/auth/sharing', { cookie: andrea, body: { sharing: true } }) + assert.equal(await whose(), 1, 'the view ENDED: sharing again does not bring it back by itself') + assert.equal((await t.call('GET', '/auth/session', { cookie: coach })).body.viewing, null) + assert.deepEqual((await t.call('POST', '/auth/view', { cookie: coach, body: { username: 'andrea' } })).body, { viewing: 'andrea' }, 'the admin starts it again') + assert.equal(await whose(), 2) + + // the role: another admin exists, the coach loses theirs, and gets it back + t.authStore.users[1].admin = true + assert.equal(await t.authStore.setAdmin(1, false), 'ok') + assert.equal(await whose(), 1, 'no longer an admin: no view') + assert.equal(await t.authStore.setAdmin(1, true), 'ok') + assert.equal(await whose(), 1, 'the role back does not bring the view back') + await t.call('POST', '/auth/view', { cookie: coach, body: { username: 'andrea' } }) + assert.equal(await whose(), 2) + + await t.call('POST', '/auth/logout', { cookie: coach }) + assert.equal((await t.call('GET', '/food/settings', { cookie: coach })).status, 401) + const again = await t.session('owner', PW1) + assert.equal((await t.call('GET', '/auth/session', { cookie: again })).body.viewing, null, 'a new session views nobody') + } finally { await t.close() } +}) + +test('who may start a view: only an admin, only somebody who shares, never yourself; one refusal for all, 401 without a session', async () => { + const t = await setup() + try { + const coach = await t.session('owner', PW1) + const andrea = await t.session('andrea', PW2) + const view = (/** @type {string | undefined} */ cookie, /** @type {unknown} */ body) => t.call('POST', '/auth/view', { cookie, body }) + assert.deepEqual((await view(undefined, { username: 'andrea' })).body, { error: 'unauthenticated' }) + for (const username of ['andrea', 'nobody', 'owner', 'bad name', '']) { + const r = await view(coach, { username }) + assert.deepEqual([r.status, r.body], [403, { error: 'not_shared' }], username) + } + t.authStore.users[0].sharing = true + t.authStore.users[1].sharing = true + assert.deepEqual((await view(andrea, { username: 'owner' })).body, { error: 'not_shared' }, 'not an admin, even when the other shares') + assert.deepEqual((await view(coach, { username: 'owner' })).body, { error: 'not_shared' }, 'never yourself') + for (const body of [{}, { username: 1 }, { username: 'andrea', extra: 1 }, []]) assert.deepEqual((await view(coach, body)).body, { error: 'bad_request' }) + assert.equal((await t.call('GET', '/auth/session', { cookie: coach })).body.viewing, null) + assert.deepEqual((await view(coach, { username: 'Andrea' })).body, { viewing: 'andrea' }) + for (const body of [{}, { sharing: 'yes' }, { sharing: true, x: 1 }]) assert.deepEqual((await t.call('POST', '/auth/sharing', { cookie: andrea, body })).body, { error: 'bad_request' }) + assert.equal((await t.call('POST', '/auth/sharing', { body: { sharing: true } })).status, 401) + } finally { await t.close() } +}) + +test('identify is the backstop: a route that forgot the guard still cannot write as the viewed user', async () => { + const t = await setup() + try { + t.authStore.users[1].sharing = true + const coach = await t.session('owner', PW1) + await t.call('POST', '/auth/view', { cookie: coach, body: { username: 'andrea' } }) + const req = (/** @type {string} */ method) => /** @type {any} */ ({ method, headers: { cookie: coach } }) + assert.deepEqual(await t.auth.identify(req('GET')), { userId: 2, username: 'andrea', open: false, readOnly: true, viewer: { userId: 1, username: 'owner' } }) + for (const method of ['POST', 'PUT', 'DELETE', 'PATCH']) { + await assert.rejects(t.auth.identify(req(method)), (/** @type {any} */ err) => err.status === 403 && err.code === 'read_only', method) + } + } finally { await t.close() } +}) + +test('the read-only check costs nothing without a session cookie: a write without one never asks the database about a view', async () => { + const t = await setup() + try { + const before = t.authStore.calls.anyPassword + const lookups = { n: 0 } + const find = t.authStore.findSession + t.authStore.findSession = async (hash, now) => { lookups.n++; return find(hash, now) } + assert.equal(await t.auth.isViewing(/** @type {any} */ ({ method: 'POST', headers: {} })), false) + assert.equal(await t.auth.isViewing(/** @type {any} */ ({ method: 'POST', headers: { cookie: 'other=1' } })), false) + assert.deepEqual([t.authStore.calls.anyPassword - before, lookups.n], [0, 0]) + const r = await t.call('POST', '/ingest/health-auto-export', { headers: { authorization: `Bearer ${TOKEN}` }, body: { data: {} } }) + assert.notEqual(r.status, 403) + assert.equal(lookups.n, 0, 'the upload route did not read a session either') + } finally { await t.close() } +}) diff --git a/services/loop-ingest/test/auth-routes.test.js b/services/loop-ingest/test/auth-routes.test.js index 22cd2c49..7e7170be 100644 --- a/services/loop-ingest/test/auth-routes.test.js +++ b/services/loop-ingest/test/auth-routes.test.js @@ -4,7 +4,8 @@ import http from 'node:http' import { createAuthService } from '../src/sessions.js' import { createAuthRoutes } from '../src/auth-routes.js' import { hashPassword } from '../src/password.js' -import { memoryAuthStore, hashOfToken, FAST_SCRYPT } from './auth-helper.js' +import { createPasswordLinks } from '../src/password-links.js' +import { memoryLinkStore, memoryAuthStore, hashOfToken, FAST_SCRYPT } from './auth-helper.js' const PW = 'correct horse battery' const DAY = 86_400_000 @@ -21,7 +22,9 @@ async function setup ({ passwords = { owner: PW, andrea: 'andrea has a long pass if (name !== 'owner') await store.addUser(name) assert.equal(await auth.setPassword(name, pw), true) } - const routes = createAuthRoutes({ auth, now, log, addressLimit, usernameLimit, allowedHosts }) + const linkStore = memoryLinkStore(store) + const links = createPasswordLinks({ store: linkStore, now, params: FAST_SCRYPT, onPasswordSet: () => auth.passwordChanged() }) + const routes = createAuthRoutes({ auth, links, now, log, addressLimit, usernameLimit, allowedHosts }) const server = http.createServer(async (req, res) => { const url = new URL(/** @type {string} */ (req.url), 'http://localhost') if (!(await routes.handle(req, res, url))) { res.writeHead(404); res.end('{"error":"outer"}') } @@ -50,7 +53,7 @@ async function setup ({ passwords = { owner: PW, andrea: 'andrea has a long pass const login = (username, password, headers) => call('POST', '/auth/login', { body: { username, password }, headers }) /** The token out of a Set-Cookie. @param {{ headers: http.IncomingHttpHeaders }} r */ const tokenOf = (r) => /** @type {RegExpExecArray} */ (/^hc_session=([A-Za-z0-9_-]+);/.exec(String(r.headers['set-cookie']?.[0])))[1] - return { store, clock, auth, call, login, tokenOf, close: () => new Promise((resolve) => server.close(resolve)) } + return { store, clock, auth, links, linkStore, call, login, tokenOf, close: () => new Promise((resolve) => server.close(resolve)) } } test('POST /auth/login: 200 {username} and a session cookie (HttpOnly, SameSite=Lax, Path=/, 30 days), no Secure over plain HTTP', async () => { @@ -280,14 +283,18 @@ test('a rate-limited attempt does no password work (nothing to time)', async () } finally { await t.close() } }) -test('GET /auth/session: 401 without a session, {open:false, username} with one, 401 for junk or expired cookies', async () => { +test('GET /auth/session: 401 without a session, {open:false, username, admin, sharing, viewing} with one, 401 for junk or expired cookies', async () => { const t = await setup() try { const none = await t.call('GET', '/auth/session') assert.deepEqual([none.status, none.body], [401, { error: 'unauthenticated' }]) const token = t.tokenOf(await t.login('andrea', 'andrea has a long password')) const ok = await t.call('GET', '/auth/session', { headers: { cookie: `x=1; hc_session=${token}; y=2` } }) - assert.deepEqual([ok.status, ok.body], [200, { open: false, username: 'andrea' }]) + assert.deepEqual([ok.status, ok.body], [200, { open: false, username: 'andrea', admin: false, sharing: false, viewing: null }]) + const andrea = t.store.users.find((u) => u.username === 'andrea') + Object.assign(/** @type {object} */ (andrea), { admin: true, sharing: true }) + const now = await t.call('GET', '/auth/session', { headers: { cookie: `hc_session=${token}` } }) + assert.deepEqual(now.body, { open: false, username: 'andrea', admin: true, sharing: true, viewing: null }, 'read with the session on every request: a change holds at once') for (const junk of ['hc_session=', 'hc_session=abc', `hc_session=${'A'.repeat(43)}`, `hc_session=${'A'.repeat(100)}`, `hc_session=${token}x`, `other=${token}`, 'hc_session=%00']) { assert.equal((await t.call('GET', '/auth/session', { headers: { cookie: junk } })).status, 401, junk) } @@ -422,3 +429,59 @@ test('nothing secret is logged: no password, token, hash or cookie in any log li assert.ok(lines.some((l) => /login_failed/.test(l)), 'failures are audited') } finally { await t.close() } }) + +test('POST /auth/password: a live link sets that user\'s password once, ends their sessions and needs no session', async () => { + /** @type {string[]} */ + const lines = [] + const t = await setup({ log: (l) => lines.push(l) }) + try { + const old = t.tokenOf(await t.login('andrea', 'andrea has a long password')) + const { token } = await t.links.issue(2) + const short = await t.call('POST', '/auth/password', { body: { token, password: 'short' } }) + assert.deepEqual([short.status, short.body], [400, { error: 'invalid_password', field: 'password' }]) + assert.equal(t.linkStore.links.size, 1, 'a refused password leaves the link usable') + + const done = await t.call('POST', '/auth/password', { body: { token, password: 'a completely new password' } }) + assert.deepEqual([done.status, done.text], [204, '']) + assert.equal(done.headers['set-cookie'], undefined, 'it does not sign anybody in') + assert.equal((await t.call('GET', '/auth/session', { headers: { cookie: `hc_session=${old}` } })).status, 401, 'the old session ended') + assert.equal((await t.login('andrea', 'andrea has a long password')).status, 401, 'the old password is gone') + assert.equal((await t.login('andrea', 'a completely new password')).status, 200) + assert.equal((await t.login('owner', PW)).status, 200, 'nobody else changed') + + const again = await t.call('POST', '/auth/password', { body: { token, password: 'yet another password!' } }) + assert.deepEqual([again.status, again.body], [410, { error: 'invalid_link' }], 'used once') + assert.equal((await t.login('andrea', 'a completely new password')).status, 200) + assert.ok(!lines.join('\n').includes(token) && !lines.join('\n').includes('a completely new password'), 'neither the link nor a password is logged') + assert.ok(lines.some((l) => l.includes('"password_set_by_link"') && l.includes('"andrea"'))) + } finally { await t.close() } +}) + +test('POST /auth/password refusals: an expired, unknown or malformed link is the same 410; the shape, the header and the address budget are checked', async () => { + const t = await setup({ addressLimit: 6 }) + try { + const { token } = await t.links.issue(2) + const pw = 'a completely new password' + for (const bad of ['', 'hcp_', token.slice(0, -1), `hcp_${'A'.repeat(43)}`, token.replace('hcp_', 'hct_')]) { + const r = await t.call('POST', '/auth/password', { body: { token: bad, password: pw } }) + assert.deepEqual([r.status, r.body], [410, { error: 'invalid_link' }], bad) + } + assert.equal((await t.call('POST', '/auth/password', { body: { token: 'hcp_x', password: pw } })).status, 410, 'the sixth attempt of this address') + assert.equal((await t.call('POST', '/auth/password', { body: { token, password: pw } })).status, 429, 'the per-address budget of the login, even for a live link') + assert.equal((await t.login('andrea', 'andrea has a long password')).status, 429, 'shared with the login') + assert.equal(t.linkStore.links.size, 1, 'the link was not used') + t.clock.t += 48 * 3_600_000 + const expired = await t.call('POST', '/auth/password', { body: { token, password: pw } }) + assert.deepEqual([expired.status, expired.body], [410, { error: 'invalid_link' }], 'expired (a new window of the budget by then)') + } finally { await t.close() } + const u = await setup() + try { + for (const body of [{}, { token: 'x' }, { token: 1, password: 'x' }, { token: 'x', password: 'y', extra: 1 }, []]) { + assert.deepEqual((await u.call('POST', '/auth/password', { body })).body, { error: 'bad_request' }, JSON.stringify(body)) + } + assert.equal((await u.call('POST', '/auth/password', { body: { token: 'x', password: 'y' }, headers: { 'x-hc-auth': undefined } })).status, 403) + assert.equal((await u.call('POST', '/auth/password', { body: { token: 'x', password: 'y' }, headers: { origin: 'https://evil.example' } })).status, 403) + assert.equal((await u.call('GET', '/auth/password')).status, 405) + assert.equal((await u.call('POST', '/auth/password', { raw: '{}', headers: { 'content-type': 'text/plain' } })).status, 415) + } finally { await u.close() } +}) diff --git a/services/loop-ingest/test/import-install.test.js b/services/loop-ingest/test/import-install.test.js index 84aa0506..251fd536 100644 --- a/services/loop-ingest/test/import-install.test.js +++ b/services/loop-ingest/test/import-install.test.js @@ -85,7 +85,7 @@ test('the table list: every mode is known, each entry explains itself, parents c assert.ok(at('garmin_activity') < at('garmin_activity_workout')) assert.ok(at('food_product') < at('food_recipe') && at('food_recipe') < at('food_log')) assert.deepEqual(IMPORT_TABLES.filter((t) => t.mode === 'remap').map((t) => t.table), ['raw_payload', 'food_product', 'food_recipe', 'food_log']) - assert.deepEqual(IMPORT_TABLES.filter((t) => t.mode === 'skip').map((t) => t.table).sort(), ['app_session', 'machine_token', 'sync_status']) + assert.deepEqual(IMPORT_TABLES.filter((t) => t.mode === 'skip').map((t) => t.table).sort(), ['app_session', 'machine_token', 'password_link', 'sync_status']) assert.deepEqual(IMPORT_TABLES.filter((t) => t.mode === 'providers').map((t) => t.table).sort(), ['provider_credential', 'strava_token']) }) diff --git a/services/loop-ingest/test/pg/admin-routes.pg.test.js b/services/loop-ingest/test/pg/admin-routes.pg.test.js new file mode 100644 index 00000000..137a4483 --- /dev/null +++ b/services/loop-ingest/test/pg/admin-routes.pg.test.js @@ -0,0 +1,87 @@ +/** + * The admin routes (src/admin-routes.js) over a real Postgres with the real migrations and the real stores: add, rename, + * a token (only its hash stored; it resolves as that user) and a delete that takes the user's rows, sessions and tokens + * with it and leaves the other users alone. Skips without TEST_DATABASE_URL (pg-helper.js). + */ +import test from 'node:test' +import assert from 'node:assert/strict' +import http from 'node:http' +import { skip, freshDatabase } from './pg-helper.js' +import { createPool, migrate } from '../../src/db.js' +import { createAuthStore } from '../../src/auth-db.js' +import { createAuthService } from '../../src/sessions.js' +import { createMachineTokenStore } from '../../src/machine-token-db.js' +import { createTokenResolver } from '../../src/machine-tokens.js' +import { createUserEraser } from '../../src/user-delete.js' +import { createProviderCredentialStore } from '../../src/provider-credentials-db.js' +import { createAdminRoutes } from '../../src/admin-routes.js' +import { createPasswordLinkStore } from '../../src/password-link-db.js' +import { createPasswordLinks } from '../../src/password-links.js' +import { FAST_SCRYPT } from '../auth-helper.js' + +const quiet = () => {} +const PW = 'owner has a long password' + +test('add, rename, token and delete through the routes over real rows', { skip }, async (t) => { + const db = await freshDatabase() + const pool = createPool(db.url, { log: quiet }) + await migrate(pool, quiet) + const store = createAuthStore(pool) + const tokens = createMachineTokenStore(pool) + const auth = createAuthService({ store, log: quiet, params: FAST_SCRYPT }) + await auth.setPassword('owner', PW) + const credentials = createProviderCredentialStore(pool) + const links = createPasswordLinks({ store: createPasswordLinkStore(pool), params: FAST_SCRYPT }) + const routes = createAdminRoutes({ auth, store, tokens, links, credentials, providerStatus: async (id) => ({ strava: false, garmin: (await credentials.get(id, 'garmin')) !== null, garminExpires: null }), eraser: createUserEraser(pool), roots: null, log: quiet }) + const server = http.createServer(async (req, res) => { await routes.handle(req, res, new URL(/** @type {string} */ (req.url), 'http://localhost')) }) + await /** @type {Promise} */ (new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))) + t.after(async () => { await new Promise((resolve) => server.close(resolve)); await pool.end(); await db.drop() }) + const port = /** @type {import('node:net').AddressInfo} */ (server.address()).port + const session = /** @type {{ token: string }} */ (await auth.login('owner', PW)).token + /** @param {string} method @param {string} path @param {unknown} [body] @returns {Promise<{ status: number, body: any }>} */ + async function call (method, path, body) { + const r = await fetch(`http://127.0.0.1:${port}${path}`, { + method, + headers: { 'x-hc-admin': '1', cookie: `hc_session=${session}`, ...(body === undefined ? {} : { 'content-type': 'application/json' }) }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }) + }) + const text = await r.text() + return { status: r.status, body: text ? JSON.parse(text) : null } + } + + assert.equal((await call('POST', '/admin/users', { username: 'andrea' })).status, 201) + assert.equal((await call('POST', '/admin/users', { username: 'maria' })).status, 201) + assert.equal((await call('POST', '/admin/users', { username: 'maria' })).status, 409) + assert.equal((await call('PUT', '/admin/users/maria', { username: 'andrea' })).status, 409) + assert.deepEqual((await call('PUT', '/admin/users/maria', { username: 'mary' })).body, { username: 'mary' }) + + const made = await call('POST', '/admin/users/mary/tokens', { label: 'phone' }) + assert.equal(made.status, 201) + const mary = /** @type {{ id: number }} */ (await store.findUserByUsername('mary')) + const stored = await pool.query('SELECT user_id, label, token_hash FROM machine_token') + assert.deepEqual(stored.rows.map((r) => [Number(r.user_id), r.label]), [[mary.id, 'phone']]) + assert.ok(!stored.rows[0].token_hash.toString('hex').includes(made.body.token), 'not the token itself') + const resolve = createTokenResolver({ store: tokens, log: quiet }) + assert.equal((await resolve(made.body.token))?.userId, mary.id, 'the issued token is that user') + await tokens.add({ userId: 1, tokenHash: Buffer.alloc(32, 9), label: 'owner token' }) + await store.insertSession({ tokenHash: Buffer.alloc(32, 5), userId: mary.id, now: new Date(), expiresAt: new Date(Date.now() + 60_000) }) + + assert.equal((await call('PUT', '/admin/users/mary/garmin', { apiKey: 'garmin-key', expires: '2031-01-31' })).status, 204) + assert.deepEqual(await credentials.get(mary.id, 'garmin').then((c) => c && [c.provider, /** @type {any} */ (c).apiKey, /** @type {any} */ (c).expires]), ['garmin', 'garmin-key', '2031-01-31']) + assert.equal(await credentials.get(1, 'garmin'), null, 'only that user') + assert.deepEqual((await call('GET', '/admin/users/mary/providers')).body, { strava: false, garmin: true, garminExpires: null }) + + const link = await call('POST', '/admin/users/mary/password-link') + assert.equal(link.status, 201) + assert.deepEqual(await links.redeem(link.body.token, 'mary has a long password'), { ok: true, username: 'mary' }) + assert.equal((await auth.login('mary', 'mary has a long password'))?.username, 'mary', 'the link set a password she can sign in with') + assert.equal((await call('POST', '/admin/users/mary/password-link')).status, 201, 'a pending link goes with the user below') + + assert.deepEqual((await call('DELETE', '/admin/users/mary', { confirm: 'mary' })).body, { deleted: 'mary', manual: [] }) + assert.deepEqual((await store.listUsers()).map((u) => u.username), ['owner', 'andrea']) + assert.equal(await resolve(made.body.token), null, 'the deleted user\'s token is refused') + assert.equal((await pool.query('SELECT 1 FROM app_session WHERE user_id = $1', [mary.id])).rows.length, 0) + assert.equal((await pool.query('SELECT 1 FROM password_link')).rows.length, 0) + assert.deepEqual((await pool.query('SELECT label FROM machine_token')).rows.map((r) => r.label), ['owner token'], 'the other users keep theirs') + assert.equal((await call('GET', '/admin/users')).status, 200, 'the admin is still signed in') +}) diff --git a/services/loop-ingest/test/pg/auth.pg.test.js b/services/loop-ingest/test/pg/auth.pg.test.js index 4ba28fea..9fedfccb 100644 --- a/services/loop-ingest/test/pg/auth.pg.test.js +++ b/services/loop-ingest/test/pg/auth.pg.test.js @@ -34,7 +34,8 @@ async function withDb (fn) { test('upgrade: a database that ran 001-022 gains password_hash (NULL for everyone) and app_session; nothing else changes; a second boot runs nothing', { skip }, () => withDb(async (pool) => { await runMigrations(pool, { - core: CORE_MIGRATIONS.filter((f) => f !== '023_auth.sql'), + // every core file before the login: the later ones build on its tables (sql/028 alters app_session) + core: CORE_MIGRATIONS.filter((f) => f < '023_auth.sql'), optional: OPTIONAL_MIGRATIONS, readSql, log: quiet }) @@ -44,7 +45,8 @@ test('upgrade: a database that ran 001-022 gains password_hash (NULL for everyon /** @type {string[]} */ const events = [] assert.deepEqual(await migrate(pool, (l) => events.push(JSON.parse(l).file)), { food: true, settings: true, profile: true, journal: true, documents: true, garmin: true }) - assert.deepEqual(events, ['023_auth.sql'], 'only the new file ran') + assert.deepEqual(events, CORE_MIGRATIONS.filter((f) => f >= '023_auth.sql'), 'only the files it had not run, in order') + assert.equal(events[0], '023_auth.sql') const users = (await pool.query('SELECT id, username, password_hash FROM app_user ORDER BY id')).rows assert.deepEqual(users.map((u) => [Number(u.id), u.username, u.password_hash]), [[1, 'owner', null], [2, 'andrea', null]]) assert.equal((await pool.query('SELECT count(*)::int AS n FROM food_log WHERE user_id = 2')).rows[0].n, 1) @@ -73,7 +75,7 @@ test('session store: only the SHA-256 is stored, expiry is honoured, last-seen m assert.equal(new Date(row.expires_at).getTime() - new Date(row.created_at).getTime(), 30 * DAY) assert.equal(new Date(row.last_seen_at).getTime(), now.getTime()) - assert.deepEqual(await store.findSession(tokenHash, new Date(now.getTime() + DAY)), { userId: 2, username: 'andrea', lastSeenAt: now }) + assert.deepEqual(await store.findSession(tokenHash, new Date(now.getTime() + DAY)), { userId: 2, username: 'andrea', admin: false, sharing: false, lastSeenAt: now, viewing: null }) assert.equal(await store.findSession(hashToken(Buffer.alloc(32, 8).toString('base64url')), now), null, 'an unknown token') assert.equal(await store.findSession(tokenHash, new Date(now.getTime() + 30 * DAY)), null, 'expired at its end') const later = new Date(now.getTime() + 2 * DAY) @@ -153,7 +155,7 @@ test('login over real rows: sign in, session, wrong password, logout, and a pass assert.equal((await s.call('POST', '/auth/login', { body: { username: 'owner', password: 'wrong password here!' } })).status, 401) const ok = await s.call('POST', '/auth/login', { body: { username: 'Owner', password: 'owner has a long password' } }) assert.deepEqual([ok.status, ok.body], [200, { username: 'owner' }]) - assert.deepEqual((await s.call('GET', '/auth/session', { cookie: ok.cookie })).body, { open: false, username: 'owner' }) + assert.deepEqual((await s.call('GET', '/auth/session', { cookie: ok.cookie })).body, { open: false, username: 'owner', admin: true, sharing: false, viewing: null }) assert.equal((await pool.query('SELECT count(*)::int AS n FROM app_session')).rows[0].n, 1) assert.equal((await s.call('POST', '/auth/logout', { cookie: ok.cookie })).status, 204) assert.equal((await pool.query('SELECT count(*)::int AS n FROM app_session')).rows[0].n, 0) @@ -189,7 +191,7 @@ test('scripts/user.js: add, list, set-password (piped, never echoed, sessions re let list = await user(['list']) assert.equal(list.code, 0) - assert.match(list.out, /^username\tpassword\tcreated\nowner\tnot set\t\d{4}-\d\d-\d\d\nandrea\tnot set\t\d{4}-\d\d-\d\d\n$/) + assert.match(list.out, /^username\tpassword\tcreated\tadmin\tshares\nowner\tnot set\t\d{4}-\d\d-\d\d\tyes\tno\nandrea\tnot set\t\d{4}-\d\d-\d\d\tno\tno\n$/) // a password as an argument is refused without being echoed const asArg = await user(['set-password', 'andrea', PW]) diff --git a/services/loop-ingest/test/pg/import-install.pg.test.js b/services/loop-ingest/test/pg/import-install.pg.test.js index 44436968..5ba076ff 100644 --- a/services/loop-ingest/test/pg/import-install.pg.test.js +++ b/services/loop-ingest/test/pg/import-install.pg.test.js @@ -23,6 +23,7 @@ import { createJournalStore } from '../../src/journal-db.js' import { createDocumentStore } from '../../src/documents-db.js' import { createProviderCredentialStore } from '../../src/provider-credentials-db.js' import { createMachineTokenStore } from '../../src/machine-token-db.js' +import { createPasswordLinkStore } from '../../src/password-link-db.js' import { run } from '../../scripts/import-install.js' import { IMPORT_TABLES, openSourcePool, importInstall } from '../../src/import-install.js' @@ -116,6 +117,7 @@ async function fillSource (pool, { dangling = false } = {}) { await pool.query("UPDATE app_user SET password_hash = 'scrypt$source-hash' WHERE id = $1", [U]) await pool.query("INSERT INTO app_session (token_hash, user_id, created_at, last_seen_at, expires_at) VALUES ($1, $2, now(), now(), now() + interval '1 day')", [Buffer.alloc(32, 7), U]) await createMachineTokenStore(pool).add({ userId: U, tokenHash: Buffer.alloc(32, 9), label: 'phone' }) + await createPasswordLinkStore(pool).replace({ userId: U, tokenHash: Buffer.alloc(32, 19), now: new Date('2030-01-01T00:00:00Z'), expiresAt: new Date('2030-01-03T00:00:00Z') }) } /** This install: the owner (user 1) with data, `andrea` (the new user, id 2, a password hash already set), `third` (id 3) with data. @param {Pool} pool */ @@ -255,7 +257,7 @@ test('the import: another install\'s user 1 becomes a new user, ids remapped, no assert.equal(logs[1].ref_id, bowl) // never imported without --with-providers, and never at all: run state, sessions, machine tokens, the password - for (const table of ['sync_status', 'app_session', 'machine_token', ...PROVIDERS]) assert.equal(await count(i.target, table, 2), 0, `${table} of the new user stays empty`) + for (const table of ['sync_status', 'app_session', 'machine_token', 'password_link', ...PROVIDERS]) assert.equal(await count(i.target, table, 2), 0, `${table} of the new user stays empty`) assert.equal((await i.target.query("SELECT password_hash FROM app_user WHERE username = 'andrea'")).rows[0].password_hash, 'scrypt$andrea-hash', 'their password is untouched') assert.equal(await count(i.target, 'strava_sync_state', 2), 1) // S3: every other user's rows, user 1 of this install included, are byte-identical; S4: schema and ledger unchanged diff --git a/services/loop-ingest/test/pg/password-link.pg.test.js b/services/loop-ingest/test/pg/password-link.pg.test.js new file mode 100644 index 00000000..13f9786e --- /dev/null +++ b/services/loop-ingest/test/pg/password-link.pg.test.js @@ -0,0 +1,83 @@ +/** + * sql/027 on a real Postgres with the real migrations: one link per user, only a hash stored, a link sets the password + * and ends the sessions once (also when two requests race), expiry, and a user delete takes the link with it. Skips + * without TEST_DATABASE_URL (pg-helper.js); every test makes and drops its own database. + */ +import test from 'node:test' +import assert from 'node:assert/strict' +import { skip, freshDatabase } from './pg-helper.js' +import { createPool, migrate } from '../../src/db.js' +import { createAuthStore } from '../../src/auth-db.js' +import { createAuthService } from '../../src/sessions.js' +import { createPasswordLinkStore } from '../../src/password-link-db.js' +import { createPasswordLinks, hashPasswordLink } from '../../src/password-links.js' +import { createUserEraser } from '../../src/user-delete.js' +import { FAST_SCRYPT } from '../auth-helper.js' + +const quiet = () => {} + +/** @param {import('node:test').TestContext} t */ +async function database (t) { + const db = await freshDatabase() + const pool = createPool(db.url, { log: quiet }) + t.after(async () => { await pool.end(); await db.drop() }) + await migrate(pool, quiet) + const store = createAuthStore(pool) + const clock = { t: Date.parse('2030-01-10T12:00:00Z') } + const auth = createAuthService({ store, log: quiet, params: FAST_SCRYPT, now: () => clock.t }) + const links = createPasswordLinks({ store: createPasswordLinkStore(pool), params: FAST_SCRYPT, now: () => clock.t, onPasswordSet: () => auth.passwordChanged() }) + const andrea = /** @type {{ id: number }} */ (await store.addUser('andrea')) + return { pool, store, auth, links, clock, andrea } +} + +test('a link is stored as a hash, one per user, and sets that user\'s password once, ending their sessions', { skip }, async (t) => { + const { pool, store, auth, links, andrea } = await database(t) + await auth.setPassword('owner', 'owner has a long password') + await auth.setPassword('andrea', 'andrea has a long password') + const session = /** @type {{ token: string }} */ (await auth.login('andrea', 'andrea has a long password')) + assert.ok(session.token) + const first = await links.issue(andrea.id) + const second = await links.issue(andrea.id) + const rows = (await pool.query('SELECT user_id, token_hash, expires_at FROM password_link')).rows + assert.equal(rows.length, 1, 'the new link replaced the old one') + assert.ok(rows[0].token_hash.equals(hashPasswordLink(second.token))) + assert.equal(rows[0].expires_at.toISOString(), '2030-01-12T12:00:00.000Z') + assert.deepEqual(await links.redeem(first.token, 'a completely new password'), { ok: false, reason: 'invalid_link' }) + + assert.deepEqual(await links.redeem(second.token, 'short'), { ok: false, reason: 'invalid_password' }) + assert.equal((await pool.query('SELECT 1 FROM password_link')).rows.length, 1, 'a refused password keeps the link') + assert.deepEqual(await links.redeem(second.token, 'a completely new password'), { ok: true, username: 'andrea' }) + assert.equal((await pool.query('SELECT 1 FROM password_link')).rows.length, 0) + assert.equal((await pool.query('SELECT 1 FROM app_session WHERE user_id = $1', [andrea.id])).rows.length, 0, 'their sessions ended') + assert.equal(await auth.login('andrea', 'andrea has a long password'), null) + assert.equal((await auth.login('andrea', 'a completely new password'))?.username, 'andrea') + assert.equal((await auth.login('owner', 'owner has a long password'))?.username, 'owner', 'nobody else changed') + assert.deepEqual(await links.redeem(second.token, 'yet another password!'), { ok: false, reason: 'invalid_link' }, 'used once') + assert.equal((await store.listUsers()).length, 2) +}) + +test('two requests with the same link: exactly one sets the password', { skip }, async (t) => { + const { auth, links, andrea } = await database(t) + const { token } = await links.issue(andrea.id) + const results = await Promise.all([links.redeem(token, 'the first new password'), links.redeem(token, 'the second new password')]) + assert.deepEqual(results.map((r) => r.ok).sort(), [false, true]) + const winner = results[0].ok ? 'the first new password' : 'the second new password' + const loser = results[0].ok ? 'the second new password' : 'the first new password' + assert.equal((await auth.login('andrea', winner))?.username, 'andrea') + assert.equal(await auth.login('andrea', loser), null) +}) + +test('a link ends after 48 hours, a first password by link ends open mode at once, and deleting the user deletes their link', { skip }, async (t) => { + const { pool, auth, links, clock, andrea } = await database(t) + const old = await links.issue(andrea.id) + clock.t += 48 * 3_600_000 + assert.deepEqual(await links.redeem(old.token, 'a completely new password'), { ok: false, reason: 'invalid_link' }) + assert.equal(await auth.isOpen(), true) + const fresh = await links.issue(andrea.id) + assert.equal((await pool.query('SELECT 1 FROM password_link')).rows.length, 1) + assert.equal((await links.redeem(fresh.token, 'a completely new password')).ok, true) + assert.equal(await auth.isOpen(), false, 'no 2-second window in this process') + await links.issue(andrea.id) + assert.notEqual(await createUserEraser(pool).erase(andrea.id), null) + assert.equal((await pool.query('SELECT 1 FROM password_link')).rows.length, 0) +}) diff --git a/services/loop-ingest/test/pg/roles.pg.test.js b/services/loop-ingest/test/pg/roles.pg.test.js new file mode 100644 index 00000000..31af42f4 --- /dev/null +++ b/services/loop-ingest/test/pg/roles.pg.test.js @@ -0,0 +1,115 @@ +/** + * sql/026 on a real Postgres with the real migrations: the first user is the admin after the migration, new users are + * neither admin nor sharing, the session carries both flags, and the last admin is never turned off (also when two + * removals race). Skips without TEST_DATABASE_URL (pg-helper.js); every test makes and drops its own database. + */ +import test from 'node:test' +import assert from 'node:assert/strict' +import { skip, freshDatabase } from './pg-helper.js' +import { createPool, migrate } from '../../src/db.js' +import { createAuthStore } from '../../src/auth-db.js' + +const quiet = () => {} + +/** @param {import('node:test').TestContext} t */ +async function database (t) { + const db = await freshDatabase() + const pool = createPool(db.url, { log: quiet }) + t.after(async () => { await pool.end(); await db.drop() }) + await migrate(pool, quiet) + return { pool, store: createAuthStore(pool) } +} + +test('after the migration user 1 is the admin and nobody shares; a new user is neither', { skip }, async (t) => { + const { store } = await database(t) + const added = await store.addUser('andrea') + const flags = (await store.listUsers()).map((u) => [u.id, u.admin, u.sharing]) + assert.deepEqual(flags, [[1, true, false], [added?.id, false, false]]) + const andrea = await store.findUserByUsername('andrea') + assert.deepEqual([andrea?.admin, andrea?.sharing], [false, false]) +}) + +test('setSharing and setAdmin change one user; the session row reads both flags; unknown users are missing', { skip }, async (t) => { + const { store } = await database(t) + const andrea = /** @type {{ id: number }} */ (await store.addUser('andrea')) + const hash = Buffer.alloc(32, 7) + const now = new Date('2030-01-01T00:00:00Z') + await store.insertSession({ tokenHash: hash, userId: andrea.id, now, expiresAt: new Date(now.getTime() + 60_000) }) + const before = await store.findSession(hash, now) + assert.deepEqual([before?.admin, before?.sharing], [false, false]) + + assert.equal(await store.setSharing(andrea.id, true), true) + assert.equal(await store.setAdmin(andrea.id, true), 'ok') + const after = await store.findSession(hash, now) + assert.deepEqual([after?.admin, after?.sharing], [true, true]) + const owner = (await store.listUsers())[0] + assert.deepEqual([owner.admin, owner.sharing], [true, false], 'the other user is untouched') + + assert.equal(await store.setSharing(999, true), false) + assert.equal(await store.setAdmin(999, true), 'missing') + assert.equal(await store.setAdmin(999, false), 'missing') +}) + +test('the last admin is never turned off: alone, and when two admins are turned off at the same time', { skip }, async (t) => { + const { store } = await database(t) + const andrea = /** @type {{ id: number }} */ (await store.addUser('andrea')) + assert.equal(await store.setAdmin(1, false), 'last') + assert.equal(await store.setAdmin(andrea.id, false), 'ok', 'turning off a user who is not an admin changes nothing') + assert.equal((await store.listUsers())[0].admin, true) + + for (let round = 0; round < 5; round++) { + await store.setAdmin(1, true) + await store.setAdmin(andrea.id, true) + const results = await Promise.all([store.setAdmin(1, false), store.setAdmin(andrea.id, false)]) + assert.deepEqual([...results].sort(), ['last', 'ok'], `round ${round}`) + assert.equal((await store.listUsers()).filter((u) => u.admin).length, 1, `round ${round}`) + } +}) + +test('the view of a session (sql/028) counts only while the viewer is an admin, the viewed user shares and is somebody else; deleting the viewed user clears it', { skip }, async (t) => { + const { pool, store } = await database(t) + const andrea = /** @type {{ id: number }} */ (await store.addUser('andrea')) + const hash = Buffer.alloc(32, 3) + const now = new Date('2030-01-01T00:00:00Z') + await store.insertSession({ tokenHash: hash, userId: 1, now, expiresAt: new Date(now.getTime() + 60_000) }) + const viewing = async () => (await store.findSession(hash, now))?.viewing ?? null + assert.equal(await viewing(), null) + assert.equal(await store.setViewing(hash, andrea.id, now), true) + assert.equal(await viewing(), null, 'she does not share') + await store.setSharing(andrea.id, true) + assert.deepEqual(await viewing(), { userId: andrea.id, username: 'andrea' }) + await store.setAdmin(andrea.id, true) + await store.setAdmin(1, false) + assert.equal(await viewing(), null, 'the viewer is no longer an admin') + await store.setAdmin(1, true) + assert.equal(await viewing(), null, 'the view ended with the role: it does not come back with it') + assert.deepEqual((await pool.query('SELECT viewing_user_id FROM app_session')).rows, [{ viewing_user_id: null }]) + await store.setViewing(hash, andrea.id, now) + assert.deepEqual(await viewing(), { userId: andrea.id, username: 'andrea' }) + // a second session of another admin viewing somebody else is untouched by andrea's consent + const pablo = /** @type {{ id: number }} */ (await store.addUser('pablo')) + await store.setSharing(pablo.id, true) + const other = Buffer.alloc(32, 8) + await store.insertSession({ tokenHash: other, userId: andrea.id, now, expiresAt: new Date(now.getTime() + 60_000) }) + await store.setViewing(other, pablo.id, now) + await store.setSharing(andrea.id, true) + assert.deepEqual(await viewing(), { userId: andrea.id, username: 'andrea' }, 'turning sharing ON ends nothing') + await store.setSharing(andrea.id, false) + assert.equal(await viewing(), null) + await store.setSharing(andrea.id, true) + assert.equal(await viewing(), null, 'consent taken back ENDED the view: giving it again starts nothing') + assert.deepEqual((await store.findSession(other, now))?.viewing, { userId: pablo.id, username: 'pablo' }, 'another view is untouched') + await store.setViewing(hash, andrea.id, now) + await store.setViewing(hash, 1, now) + await store.setSharing(1, true) + assert.equal(await viewing(), null, 'never yourself') + assert.equal(await store.setViewing(hash, null, now), true) + assert.equal(await store.setViewing(Buffer.alloc(32, 4), andrea.id, now), false, 'no such session') + assert.equal(await store.setViewing(hash, andrea.id, new Date(now.getTime() + 120_000)), false, 'an expired session') + + await store.setViewing(hash, andrea.id, now) + await pool.query('DELETE FROM app_user WHERE id = $1', [andrea.id]) + const row = (await pool.query('SELECT viewing_user_id FROM app_session')).rows + assert.deepEqual(row, [{ viewing_user_id: null }], 'the session stays, the view is cleared') + assert.equal((await store.findSession(hash, now))?.userId, 1) +}) diff --git a/services/loop-ingest/test/pg/user-admin.pg.test.js b/services/loop-ingest/test/pg/user-admin.pg.test.js index 26a28573..27b508ae 100644 --- a/services/loop-ingest/test/pg/user-admin.pg.test.js +++ b/services/loop-ingest/test/pg/user-admin.pg.test.js @@ -22,6 +22,7 @@ import { createJournalStore } from '../../src/journal-db.js' import { createDocumentStore } from '../../src/documents-db.js' import { createProviderCredentialStore } from '../../src/provider-credentials-db.js' import { createMachineTokenStore } from '../../src/machine-token-db.js' +import { createPasswordLinkStore } from '../../src/password-link-db.js' import { createAuthStore } from '../../src/auth-db.js' import { createUserEraser } from '../../src/user-delete.js' import { IMPORT_TABLES } from '../../src/import-install.js' @@ -84,6 +85,7 @@ async function fillUser (pool, U) { await pool.query('UPDATE app_user SET password_hash = $2 WHERE id = $1', [U, `scrypt$hash-${U}`]) await pool.query("INSERT INTO app_session (token_hash, user_id, created_at, last_seen_at, expires_at) VALUES ($1, $2, now(), now(), now() + interval '1 day')", [Buffer.alloc(32, U), U]) await createMachineTokenStore(pool).add({ userId: U, tokenHash: Buffer.alloc(32, 90 + U), label: 'phone' }) + await createPasswordLinkStore(pool).replace({ userId: U, tokenHash: Buffer.alloc(32, 120 + U), now: new Date('2030-01-01T00:00:00Z'), expiresAt: new Date('2030-01-03T00:00:00Z') }) } /** The owner, `maria` (2) and `pablo` (3), each with data in every table. @param {Pool} pool */ @@ -192,7 +194,7 @@ test('delete: every row of the user in every table goes, then the user and the f const foldersBefore = tree(base) const done = await user(pool, ['delete', 'maria', '--confirm', 'maria'], { roots }) assert.deepEqual([done.code, done.err], [0, '']) - assert.match(done.out, /deleted user maria \(id 2\): \d+ rows in 21 tables/) + assert.match(done.out, /deleted user maria \(id 2\): \d+ rows in 22 tables/) for (const { table } of IMPORT_TABLES) assert.equal((await pool.query(`SELECT count(*)::int AS n FROM ${table} WHERE user_id = 2`)).rows[0].n, 0, table) assert.equal((await pool.query('SELECT count(*)::int AS n FROM app_user WHERE id = 2')).rows[0].n, 0) assert.deepEqual(await snapshot(pool, null), { ...rowsBefore, app_user: rowsBefore.app_user }, 'every row of every other user and the ledger') diff --git a/services/loop-ingest/test/site-routes.test.js b/services/loop-ingest/test/site-routes.test.js index aa8dd6c3..b09ec59b 100644 --- a/services/loop-ingest/test/site-routes.test.js +++ b/services/loop-ingest/test/site-routes.test.js @@ -315,3 +315,25 @@ test('marker: the timer keeps it in step and stops; an unwritable site dir is lo await bad.sync() assert.ok(logs.some((l) => /site_marker_failed/.test(l))) }) + +test('the coach view: an admin viewing a user who shares is served THAT user\'s tree; without consent, their own again', async () => { + const t = await setup() + try { + t.store.users[1].sharing = true + const owner = await t.session('owner') + const andrea = await t.session('andrea') + const req = /** @type {any} */ ({ method: 'POST', headers: { cookie: owner } }) + assert.deepEqual(await t.auth.startView(req, 'andrea'), { ok: true, viewer: 'owner', viewing: 'andrea' }) + for (const [asked, target] of [['/', '/_user/users/2/index.html'], ['/status.json', '/_user/users/2/status.json'], ['/manuales/m.pdf', '/_user/users/2/manuales/m.pdf']]) { + assert.equal(redirect(await t.ask(asked, { cookie: owner })), target, asked) + } + assert.equal(redirect(await t.ask('/', { cookie: andrea })), '/_user/users/2/index.html', 'she sees her own, as always') + t.store.users[1].sharing = false + assert.equal(redirect(await t.ask('/', { cookie: owner })), '/_user/index.html', 'consent taken back: the owner\'s own page') + // the other direction: an admin who is not user 1 viewing user 1 + t.store.users[1].admin = true + t.store.users[0].sharing = true + assert.deepEqual(await t.auth.startView(/** @type {any} */ ({ method: 'POST', headers: { cookie: andrea } }), 'owner'), { ok: true, viewer: 'andrea', viewing: 'owner' }) + assert.equal(redirect(await t.ask('/status.json', { cookie: andrea })), '/_user/status.json') + } finally { await t.close() } +}) diff --git a/services/loop-ingest/test/user-admin.test.js b/services/loop-ingest/test/user-admin.test.js index 703ad32e..9891a600 100644 --- a/services/loop-ingest/test/user-admin.test.js +++ b/services/loop-ingest/test/user-admin.test.js @@ -424,3 +424,18 @@ test('a delete that reaches run without roots says no folder was touched: it nev assert.match(r.out + r.err, /no .*folder/i) assert.equal(await store.findUserByUsername('maria'), null) }) + +test('delete refuses the only admin (exit 1, nothing erased); with another admin it goes through', async () => { + const { store, eraser, user } = harness() + await user(['add', 'andrea']) + await user(['admin', 'andrea', 'on']) + await user(['admin', 'owner', 'off']) + const only = await user(['delete', 'andrea', '--confirm', 'andrea']) + assert.deepEqual([only.code, only.out], [1, '']) + assert.match(only.err, /^user andrea is the only admin: make another user an admin first \(admin on\); nothing changed\n$/) + assert.deepEqual(eraser.calls, []) + assert.equal(store.users.length, 2) + await user(['admin', 'owner', 'on']) + assert.equal((await user(['delete', 'andrea', '--confirm', 'andrea'])).code, 0) + assert.deepEqual(eraser.calls, [['erase', 2]]) +}) diff --git a/services/loop-ingest/test/user-script.test.js b/services/loop-ingest/test/user-script.test.js index 0aa7ed89..ac0b126d 100644 --- a/services/loop-ingest/test/user-script.test.js +++ b/services/loop-ingest/test/user-script.test.js @@ -82,7 +82,7 @@ test('add, list and the usage errors run without a database (injected store)', a assert.deepEqual([again.code, again.err], [1, 'user andrea already exists\n']) assert.equal(store.users.length, 2) const list = await user(['list']) - assert.match(list.out, /^username\tpassword\tcreated\nowner\tnot set\t\d{4}-\d\d-\d\d\nandrea\tnot set\t\d{4}-\d\d-\d\d\n$/) + assert.match(list.out, /^username\tpassword\tcreated\tadmin\tshares\nowner\tnot set\t\d{4}-\d\d-\d\d\tyes\tno\nandrea\tnot set\t\d{4}-\d\d-\d\d\tno\tno\n$/) }) test('set-password with a piped stdin: the whole input minus one line ending; a password as an argument is refused unechoed', async () => { @@ -356,3 +356,39 @@ test('set-password: a marker that cannot be removed is said on stderr (remove it assert.equal(await store.anyPassword(), true) } finally { fs.rmSync(siteDir, { recursive: true, force: true }) } }) + +test('admin and share: on / off per user, the only admin is never turned off, unknown users and bad arguments are refused', async () => { + const { store, user } = harness() + await user(['add', 'andrea']) + for (const argv of [['admin'], ['admin', 'andrea'], ['admin', 'andrea', 'yes'], ['share', 'andrea', 'on', 'x'], ['share', 'bad name', 'on']]) { + assert.equal((await user(argv)).code, 2, argv.join(' ')) + } + assert.deepEqual(await user(['admin', 'nobody', 'on']), { code: 1, out: '', err: 'no user nobody\n' }) + assert.deepEqual(await user(['share', 'nobody', 'on']), { code: 1, out: '', err: 'no user nobody\n' }) + + const last = await user(['admin', 'owner', 'off']) + assert.deepEqual([last.code, last.out], [1, '']) + assert.match(last.err, /^owner is the only admin; make another user an admin first\. Nothing changed\n$/) + assert.equal(store.users[0].admin, true) + + const on = await user(['admin', 'Andrea', 'on']) + assert.deepEqual([on.code, on.err], [0, '']) + assert.match(on.out, /^andrea is now an admin/) + assert.equal(store.users[1].admin, true) + const off = await user(['admin', 'owner', 'off']) + assert.deepEqual([off.code, off.err, off.out], [0, '', 'owner is no longer an admin\n']) + assert.equal(store.users[0].admin, false) + assert.equal((await user(['admin', 'andrea', 'off'])).code, 1, 'andrea is the only admin now') + + assert.equal(store.users[1].sharing, false, 'a new user does not share') + const share = await user(['share', 'andrea', 'on']) + assert.deepEqual([share.code, share.err], [0, '']) + assert.match(share.out, /^andrea now shares their page with the admins/) + assert.equal(store.users[1].sharing, true) + assert.equal(store.users[0].sharing, false, 'only the named user changes') + const unshare = await user(['share', 'andrea', 'off']) + assert.match(unshare.out, /^andrea no longer shares their page/) + assert.equal(store.users[1].sharing, false) + const list = await user(['list']) + assert.match(list.out, /\nowner\tnot set\t[\d-]+\tno\tno\nandrea\tnot set\t[\d-]+\tyes\tno\n$/) +}) diff --git a/services/loop-web/nginx.conf.template b/services/loop-web/nginx.conf.template index 15d3b821..97b0e3cc 100644 --- a/services/loop-web/nginx.conf.template +++ b/services/loop-web/nginx.conf.template @@ -337,6 +337,23 @@ server { proxy_pass http://loop-ingest/auth/; } + # user management for a signed-in admin (ingest admin-routes.js): the session cookie is the identity, the service + # checks the role on every request; nothing here is cached + location /api/admin/ { + gzip off; + limit_req zone=hc_api burst=60 nodelay; + limit_except GET POST PUT DELETE { deny all; } + client_max_body_size 16k; + proxy_set_header X-HC-Admin $http_x_hc_admin; + # the hop's Host: a name the ingest Host check accepts (the browser's Origin is passed on) + proxy_set_header Host loop-ingest; + # the Host the browser asked for (port included): ingest refuses a write whose Origin is not exactly it + proxy_set_header X-Forwarded-Host $http_host; + proxy_connect_timeout 5s; + proxy_read_timeout 60s; + proxy_pass http://loop-ingest/admin/; + } + location = /ingest/health-auto-export { gzip off; limit_req zone=hc_ingest burst=20 nodelay; diff --git a/web/src/client/nutri-day.test.mjs b/web/src/client/nutri-day.test.mjs index 8669e2dc..7de1de82 100644 --- a/web/src/client/nutri-day.test.mjs +++ b/web/src/client/nutri-day.test.mjs @@ -355,6 +355,19 @@ test('goal choice (HCNutri.setGoal, from the profile sheet) persists; an unknown assert.equal(t.api.state().goal, 'bulk', 'works without storage'); }); +test('while the tab shows another person\'s page (sessionStorage hc.viewing) the viewer\'s own stored goal is neither read nor overwritten', () => { + const viewing = { sessionStorage: { getItem: (/** @type {string} */ k) => (k === 'hc.viewing' ? 'ana' : null) } }; + const storage = memStorage({ 'hc.nutri.goal': 'bulk' }); + const s = run({ storage, extra: viewing }); + assert.equal(s.api.state().goal, 'maintain', 'the page\'s own default, not the viewer\'s stored goal'); + s.api.setGoal('cut'); + assert.equal(s.api.state().goal, 'cut', 'it still works, in memory'); + assert.deepEqual(storage.data, { 'hc.nutri.goal': 'bulk' }, 'the viewer\'s storage is untouched'); + // an own page (no flag, or a sessionStorage that throws): storage as always + assert.equal(run({ storage: memStorage({ 'hc.nutri.goal': 'bulk' }), extra: { sessionStorage: { getItem: () => null } } }).api.state().goal, 'bulk'); + assert.equal(run({ storage: memStorage({ 'hc.nutri.goal': 'bulk' }) }).api.state().goal, 'bulk'); +}); + test('the orphaned hc.nutri.picks key (the removed choosable blocks) is cleared once on load; other keys stay', () => { const storage = memStorage({ 'hc.nutri.picks': '{"lunch":"x"}', 'hc.nutri.goal': 'cut', 'hc.nutri.guide': '{"picks":{}}' }); const s = run({ storage }); diff --git a/web/src/client/nutri-day.ts b/web/src/client/nutri-day.ts index 77c02c33..6af2d788 100644 --- a/web/src/client/nutri-day.ts +++ b/web/src/client/nutri-day.ts @@ -102,8 +102,13 @@ type RingTarget = { k: number; p: number; c: number; g: number; fatMax: number; var isBike = HC_FUEL.isBikeDay; /* ---------- storage (per-viewer convenience, never required) ---------- */ + // While this tab shows ANOTHER person's page (the admin's coach view; client/signin.ts keeps sessionStorage `hc.viewing`) + // there is no storage: the viewer's own cached goal must neither be shown on that page nor be overwritten by theirs. function store() { - try { return window.localStorage || null; } catch (e) { return null; } + try { + if (typeof sessionStorage !== 'undefined' && sessionStorage.getItem('hc.viewing')) return null; + return window.localStorage || null; + } catch (e) { return null; } } function load(key: string) { try { var s = store(); return s ? s.getItem(key) : null; } catch (e) { return null; } diff --git a/web/src/client/page-globals.d.ts b/web/src/client/page-globals.d.ts index dc70a5e2..22f3da02 100644 --- a/web/src/client/page-globals.d.ts +++ b/web/src/client/page-globals.d.ts @@ -105,7 +105,12 @@ declare global { HCProfile?: unknown; HCProgress?: any; HCSettings?: any; - HCAuth?: { state: () => { status: 'unknown' | 'open' | 'signedin' | 'signedout'; username: string | null }; check: () => Promise; signOut: () => Promise; onChange: (fn: (s: { status: string; username: string | null }) => void) => void }; + HCAuth?: { + state: () => { status: 'unknown' | 'open' | 'signedin' | 'signedout'; username: string | null; admin: boolean; sharing: boolean; viewing: string | null }; + check: () => Promise; signOut: () => Promise; setSharing: (on: boolean) => Promise; + view: (name: string) => Promise; unview: () => Promise; + onChange: (fn: (s: { status: string; username: string | null; admin: boolean; sharing: boolean; viewing: string | null }) => void) => void; + }; HCActivity?: unknown; HCDash?: unknown; HCDay?: any; diff --git a/web/src/client/profile.test.mjs b/web/src/client/profile.test.mjs index 73847297..061b96f3 100644 --- a/web/src/client/profile.test.mjs +++ b/web/src/client/profile.test.mjs @@ -41,10 +41,10 @@ const FULL = buildProfile({ manual: MANUAL, strava: STRAVA, weight: { kg: 71.4, /** * @typedef {{profile?: Record, locale?: string, now?: string, photo?: string | null, nutri?: unknown, * settings?: unknown, progress?: unknown, els?: Record, fetch?: unknown, links?: FakeLink[], - * location?: {protocol: string}, onb?: boolean, auth?: unknown, detail?: unknown}} SetupOpts + * location?: {protocol: string, origin?: string}, onb?: boolean, auth?: unknown, detail?: unknown, extra?: Record}} SetupOpts */ /** @param {SetupOpts} [opts] */ -function setup({ profile = FULL, locale = 'en', now = '2030-01-07', photo = null, nutri = null, settings = null, progress = null, els = {}, fetch = undefined, links = [], location, onb = false, auth = null, detail = null } = {}) { +function setup({ profile = FULL, locale = 'en', now = '2030-01-07', photo = null, nutri = null, settings = null, progress = null, els = {}, fetch = undefined, links = [], location, onb = false, auth = null, detail = null, extra = {} } = {}) { const img = photo ? { getAttribute: (/** @type {string} */ k) => (k === 'src' ? photo : null) } : null; /** @type {VmGlobals} */ const win = nutri ? { HCNutri: nutri } : {}; @@ -79,6 +79,7 @@ function setup({ profile = FULL, locale = 'en', now = '2030-01-07', photo = null I18N_DATE: locale === 'es' ? esDate : enDate, ...(onb ? { I18N_ONB: locale === 'es' ? esO : enO } : {}), LOCALE: locale, + ...extra, Date: FakeDate, Math, String, Number, Array, Object, JSON, isFinite, parseInt, setTimeout, clearTimeout, }; vm.createContext(ctx); @@ -664,3 +665,624 @@ test('account: the session answer arriving after the sheet was drawn (a #profile other.fns[0]({ status: 'signedin', username: 'ana' }); assert.equal(none.length, 0, 'another sheet is left alone'); }); + +/* ---------- the sharing switch (any signed-in person) and the admin's People area ---------- */ +/** @typedef {{status: string, username: string | null, admin: boolean, sharing: boolean, viewing: string | null}} AuthState */ +/** A HCAuth stand-in with the full state shape and recorded calls. + * @param {Partial} [state] @param {{setSharing?: (on: boolean) => Promise, view?: (n: string) => Promise, hear?: {fns: Function[]}}} [o] */ +function authFull(state = {}, o = {}) { + /** @type {AuthState} */ + const st = { status: 'signedin', username: 'alex', admin: false, sharing: false, viewing: null, ...state }; + /** @type {{sharing: boolean[], view: string[], check: number}} */ + const calls = { sharing: [], view: [], check: 0 }; + const hear = o.hear || { fns: [] }; + return { + calls, + state: () => ({ ...st }), + signOut: () => Promise.resolve(), + check: () => { calls.check++; return Promise.resolve(st); }, + setSharing: o.setSharing ? (/** @type {boolean} */ on) => { calls.sharing.push(on); return /** @type {NonNullable} */ (o.setSharing)(on); } : (/** @type {boolean} */ on) => { calls.sharing.push(on); return Promise.resolve(on); }, + view: o.view ? (/** @type {string} */ n) => { calls.view.push(n); return /** @type {NonNullable} */ (o.view)(n); } : (/** @type {string} */ n) => { calls.view.push(n); return Promise.resolve(); }, + onChange: (/** @type {Function} */ fn) => { hear.fns.push(fn); }, + }; +} +const SW = /' + - '

'); + '

' + + (own ? '
' + esc(A.share) + '' + HC.switchBtn(s.sharing, A.share, ' data-pf-share=""') + '
' + + '

' + esc(A.shareHint) + '

' : '') + + (own && s.admin ? '
' + esc(A.people) + '' + + '
' : '')); + } + // what a drawn Account section depends on: a change of any of it redraws an open profile sheet (the sharing + // switch is not in it: it updates itself in place) + var lastAuth = ''; + function authKey(s: { status?: string; username?: string | null; admin?: boolean; viewing?: string | null } | null | undefined) { + return s ? [s.status, s.username || '', s.admin ? 1 : 0, s.viewing || ''].join('\u0000') : ''; + } + // the sharing switch: the person's own consent to be viewed by the admin + function toggleShare(btn: Element) { + var a = auth(), G = T.goal, b = btn as HTMLButtonElement; + if (!a || typeof a.setSharing !== 'function' || b.disabled) return; + var next = b.getAttribute('aria-checked') !== 'true'; + b.disabled = true; + setText('pf-share-msg', G.saving); + a.setSharing(next).then(function (on) { + b.setAttribute('aria-checked', on ? 'true' : 'false'); + setText('pf-share-msg', G.saved); + }, function (e: { code?: string } | null) { + setText('pf-share-msg', format(G.failed, { reason: G.reasons[(e && e.code) as keyof typeof G.reasons] || G.reasons.generic })); + }).then(function () { b.disabled = false; }); } function signOut() { var a = auth(), A = T.account, btn = el('pf-signout') as HTMLButtonElement | null; @@ -269,13 +296,19 @@ type SettingsState = { pending?: boolean; last?: SaveStatus | null } | null | un document.addEventListener('click', function (e) { var t = (e && e.target) as Element | null; var hit = t && t.closest ? t.closest('[data-pf-signout]') : null; - if (hit) signOut(); + if (hit) { signOut(); return; } + var share = t && t.closest ? t.closest('[data-pf-share]') : null; + if (share) toggleShare(share); }); } // a profile sheet drawn before the session answer (a #profile link) gets its account section when it arrives var AU = auth(); if (AU && typeof AU.onChange === 'function') { - AU.onChange(function () { + lastAuth = authKey(AU.state()); + AU.onChange(function (s) { + // only what the section shows (who, admin, viewing) redraws it: a sharing change is saved in place + if (authKey(s) === lastAuth) return; + lastAuth = authKey(s); var D = window.HCDetail, open = D && typeof D.state === 'function' ? D.state() : null; if (open && open.key === 'profile') D.open('profile', null, {}); }); @@ -451,6 +484,387 @@ type SettingsState = { pending?: boolean; last?: SaveStatus | null } | null | un if (!O || !V || !V.onboarding || !HC.lan()) return ''; return ''; } + /* ---------- People: the admin's user management (its own sheet, opened from the Account section) ---------- + * Everything goes through /api/admin/* (docs/lan-services.md -> Admin routes) with the X-HC-Admin header. A secret + * (a password link, a machine token) is shown ONCE, from memory only (PS.secret), and dropped at the next action; + * the fields that take a secret (client secret, Garmin key, Strava code) are cleared after every use and never + * written back into the page. Nothing here touches storage. */ + type Person = { username: string; hasPassword?: boolean; admin?: boolean; sharing?: boolean; owner?: boolean; self?: boolean }; + type TokenRow = { id: number; label: string; created?: string; lastUsed?: string | null; revoked?: string | null }; + type Providers = { strava?: boolean; garmin?: boolean; garminExpires?: string | null }; + type ApiError = { code?: string } | null; + var PS = { + list: null as Person[] | null, listErr: '', open: null as string | null, busy: false, + secret: null as { kind: 'link' | 'token'; value: string; note: string } | null, + tokens: null as TokenRow[] | null, prov: null as Providers | null, stravaUrl: '', stravaId: '', + }; + var adminApi = HC.jsonApi('/api/admin', 'X-HC-Admin', 15000); + function PT() { return T.people; } + function isAdmin() { + var a = auth(), s = a ? a.state() : null; + return Boolean(s && s.status === 'signedin' && s.admin && !s.viewing); + } + function errText(e: ApiError) { + var errs = PT().errors as Record; + return e && e.code && Object.prototype.hasOwnProperty.call(errs, e.code) ? errs[e.code] : errs.generic; + } + function userPath(name: string, tail?: string) { + return '/users/' + encodeURIComponent(name) + (tail || ''); + } + function ppMsg(text: string) { + setText('pp-msg', text); + } + function setHtml(id: string, html: string) { + var x = el(id); + if (x) x.innerHTML = html; + } + function field(id: string, label: string, extra: string, value?: string) { + return '
' + + '
'; + } + function secretField(id: string, label: string) { + return field(id, label, 'type="password"'); + } + function btn(act: string, label: string, name?: string, cls?: string, type?: string) { + return ''; + } + function form(name: string, inner: string) { + return '' + inner + ''; + } + function badges(p: Person) { + var B = PT().badges, out: string[] = []; + if (p.owner) out.push(B.owner); + if (p.self) out.push(B.you); + if (p.admin) out.push(B.admin); + if (p.hasPassword === false) out.push(B.noPassword); + if (p.sharing) out.push(B.shares); + return out.map(function (b) { return '' + esc(b) + ''; }).join(''); + } + function listHtml() { + var P2 = PT(); + if (PS.list == null) { + return PS.listErr ? note(PS.listErr, 'pf-note-warn') + btn('reload', P2.retry) : note(P2.loading); + } + if (!PS.list.length) return note(P2.none); + // the open person's panel sits right under THEIR row (#pp-panel: one slot, after the open row, else empty at the end) + var slot = function (inner: string) { return '
  • ' + inner + '
  • '; }; + var open = PS.open, found = false; + var rows = PS.list.map(function (p) { + var on = open === p.username; + if (on) found = true; + return '
  • ' + esc(p.username) + '' + badges(p) + '
    ' + + '
  • ' + + (on ? slot(panelHtml()) : ''); + }).join(''); + return '
      ' + rows + (found ? '' : slot('')) + '
    '; + } + function dateOf(iso: string | null | undefined) { + var d = HC.isoDate(typeof iso === 'string' ? iso.slice(0, 10) : null); + return d ? HC.fmtDate(d) : ''; + } + function secretHtml() { + var S = PS.secret, P2 = PT(); + if (!S) return ''; + var label = S.kind === 'link' ? format(P2.linkLabel, { name: PS.open || '' }) : P2.tokenLabel; + return '
    ' + + '
    ' + + '
    ' + btn('copy', P2.copy) + '
    ' + note(S.note); + } + function tokensHtml(name: string) { + var P2 = PT(), rows = PS.tokens; + var inner = rows == null ? note(P2.loading) : !rows.length ? note(P2.tokensNone) : '
      ' + rows.map(function (t) { + var bits = [format(P2.tokenMeta, { created: dateOf(t.created) })]; + if (t.lastUsed) bits.push(format(P2.tokenUsed, { used: dateOf(t.lastUsed) })); + return '
    • ' + esc(t.label) + '' + + (t.revoked ? '' + esc(P2.tokenRevoked) + '' : '') + + '' + esc(bits.join(' · ')) + '
      ' + + (t.revoked ? '' : '') + '
    • '; + }).join('') + '
    '; + return inner + + form('token-add', field('pp-tlabel', P2.tokenName, 'type="text" maxlength="60"') + '
    ' + btn('token-add', P2.tokenAdd, name, 'food-btn-ghost', 'submit') + '
    '); + } + function providersHtml(name: string) { + var P2 = PT(), pr = PS.prov; + var st = function (on: boolean | undefined, extra?: string) { + return note(pr == null ? P2.loading : (on ? P2.connected : P2.notConnected) + (on && extra ? ' · ' + extra : '')); + }; + var until = pr && pr.garminExpires ? dateOf(pr.garminExpires) : ''; + var strava = '

    ' + esc(P2.strava) + '

    ' + st(pr ? pr.strava : false) + + (pr && pr.strava ? '
    ' + btn('strava-remove', P2.remove, name, 'food-btn-warn') + '
    ' : '') + + form('strava-url', field('pp-sid', P2.stravaId, 'type="text" inputmode="numeric"', PS.stravaId) + '
    ' + btn('strava-url', P2.stravaGet, name, 'food-btn-ghost', 'submit') + '
    ') + + (PS.stravaUrl ? note(P2.stravaOpen) + '

    ' + esc(P2.stravaLink) + '

    ' + + form('strava-save', secretField('pp-ssec', P2.stravaSecret) + field('pp-scode', P2.stravaCode, 'type="text"') + + '
    ' + btn('strava-save', P2.stravaConnect, name, 'food-btn-ghost', 'submit') + '
    ') : ''); + var garmin = '

    ' + esc(P2.garmin) + '

    ' + st(pr ? pr.garmin : false, until ? format(P2.garminUntil, { date: until }) : '') + + (pr && pr.garmin ? '
    ' + btn('garmin-remove', P2.remove, name, 'food-btn-warn') + '
    ' : '') + + form('garmin-save', secretField('pp-gkey', P2.garminKey) + field('pp-gexp', P2.garminExpires, 'type="date"') + + '
    ' + btn('garmin-save', P2.garminSave, name, 'food-btn-ghost', 'submit') + '
    '); + return strava + garmin; + } + // one fold of the person's panel: closed until asked for, so the panel opens calm (the actions first, the rest by name) + function fold(label: string, inner: string, cls?: string) { + return '
    ' + esc(label) + '' + inner + '
    '; + } + function panelHtml() { + var P2 = PT(), name = PS.open, p = name && PS.list ? PS.list.filter(function (x) { return x.username === name; })[0] : null; + if (!name || !p) return ''; + return '
    ' + + '
    ' + + (p.sharing && !p.self ? btn('view', P2.view, name, 'food-btn') : '') + btn('link', P2.link, name) + '
    ' + + (p.sharing && !p.self ? note(P2.viewHint) : '') + + '
    ' + secretHtml() + '
    ' + + fold(P2.rename, form('rename', field('pp-rename', P2.renameLabel, 'type="text"', name) + '
    ' + btn('rename', P2.rename, name, 'food-btn-ghost', 'submit') + '
    ')) + + fold(P2.tokens, '
    ' + tokensHtml(name) + '
    ') + + fold(P2.providers, '
    ' + providersHtml(name) + '
    ') + + (p.owner || p.self ? '' : fold(format(P2.deleteHead, { name: name }), note(P2.deleteHint) + + form('delete', field('pp-confirm', P2.deleteLabel, 'type="text"') + '
    ' + btn('delete', P2.delete, name, 'food-btn-warn', 'submit') + '
    '), 'pp-danger')) + + '
    '; + } + function peopleBody() { + var P2 = PT(); + if (!isAdmin()) return note(P2.denied); + // two cards, as the profile's own sections: who has an account (each person's panel opens under their row), then adding one + return '

    ' + esc(P2.list) + '

    ' + + '

    ' + listHtml() + '
    ' + + '

    ' + esc(P2.addLabel) + '

    ' + + form('add', field('pp-new', P2.addName, 'type="text"') + '' + esc(P2.addHint) + '' + + '
    ' + btn('add', P2.add, undefined, 'food-btn', 'submit') + '
    ') + '
    '; + } + function drawList() { setHtml('pp-list', listHtml()); } + function drawPanel() { setHtml('pp-panel', panelHtml()); } + function loadList() { + PS.listErr = ''; + adminApi('GET', '/users').then(function (d: { users?: Person[] }) { + PS.list = Array.isArray(d && d.users) ? d.users! : []; + if (PS.open && !PS.list.some(function (p) { return p.username === PS.open; })) PS.open = null; + drawList(); + drawPanel(); + }, function (e: ApiError) { + PS.list = null; + PS.listErr = errText(e); + drawList(); + }); + } + function loadPerson(name: string) { + PS.tokens = null; + PS.prov = null; + adminApi('GET', userPath(name, '/tokens')).then(function (d: { tokens?: TokenRow[] }) { + if (PS.open !== name) return; + PS.tokens = Array.isArray(d && d.tokens) ? d.tokens! : []; + setHtml('pp-tokens', tokensHtml(name)); + }, function (e: ApiError) { if (PS.open === name) ppMsg(errText(e)); }); + adminApi('GET', userPath(name, '/providers')).then(function (d: Providers) { + if (PS.open !== name) return; + PS.prov = d || {}; + setHtml('pp-prov', providersHtml(name)); + }, function (e: ApiError) { if (PS.open === name) ppMsg(errText(e)); }); + } + function openPerson(name: string | null) { + PS.open = name; + PS.secret = null; + PS.stravaUrl = ''; + PS.stravaId = ''; + ppMsg(''); + // the list too: the panel's slot moves under the opened row and that row's button becomes its Close + drawList(); + drawPanel(); + if (name) { + loadPerson(name); + var x = el('pp-panel'); + if (x && typeof x.scrollIntoView === 'function') x.scrollIntoView({ block: 'nearest' }); + } + } + // one request at a time: `go` runs it, `ok(result)` says what came of it; a failure is one readable line + function run(go: () => Promise, ok: (r: any) => void) { + if (PS.busy) return; + PS.busy = true; + PS.secret = null; + setHtml('pp-secret-box', ''); + ppMsg(PT().working); + go().then(function (r) { PS.busy = false; ok(r); }, function (e: ApiError) { PS.busy = false; ppMsg(errText(e)); }); + } + function val(id: string) { + var x = el(id) as HTMLInputElement | null; + return x ? String(x.value || '') : ''; + } + // a secret field is emptied once it was used, whatever came of it + function wipe(ids: string[]) { + ids.forEach(function (id) { var x = el(id) as HTMLInputElement | null; if (x) x.value = ''; }); + } + function showSecret(kind: 'link' | 'token', value: string, noteText: string) { + PS.secret = { kind: kind, value: value, note: noteText }; + setHtml('pp-secret-box', secretHtml()); + var f = el('pp-secret') as HTMLInputElement | null; + if (f && typeof f.focus === 'function') f.focus(); + if (f && typeof f.select === 'function') f.select(); + } + function copySecret() { + var f = el('pp-secret') as HTMLInputElement | null, P2 = PT(); + if (!f) return; + var manual = function () { + try { f!.focus(); f!.select(); ppMsg(document.execCommand && document.execCommand('copy') ? P2.copied : P2.copyManual); } catch (e) { ppMsg(P2.copyManual); } + }; + var c = typeof navigator !== 'undefined' && navigator && navigator.clipboard; + if (c && typeof c.writeText === 'function') c.writeText(f.value).then(function () { ppMsg(P2.copied); }, manual); + else manual(); + } + function addPerson() { + var name = val('pp-new').trim(); + if (!name) return; + run(function () { return adminApi('POST', '/users', { username: name }); }, function (r: { username?: string }) { + var who = r && typeof r.username === 'string' ? r.username : name; + wipe(['pp-new']); + ppMsg(format(PT().added, { name: who })); + PS.open = who; + loadList(); + loadPerson(who); + }); + } + function passwordLink(name: string) { + run(function () { return adminApi('POST', userPath(name, '/password-link')); }, function (r: { token?: string; expires?: string }) { + ppMsg(''); + if (!r || typeof r.token !== 'string') { ppMsg(PT().errors.generic); return; } + // the page's own address plus the fragment: a browser never sends a fragment to a server + showSecret('link', location.origin + '/#set-password=' + r.token, format(PT().linkNote, { date: dateOf(r.expires) })); + }); + } + function rename(name: string) { + var next = val('pp-rename').trim(); + if (!next || next === name) return; + run(function () { return adminApi('PUT', userPath(name), { username: next }); }, function (r: { username?: string }) { + var who = r && typeof r.username === 'string' ? r.username : next; + PS.open = who; + ppMsg(format(PT().renamed, { name: who })); + loadList(); + loadPerson(who); + // renaming yourself changes the name the session shows + var a = auth(); + if (a && typeof a.check === 'function') a.check(); + }); + } + function deletePerson(name: string) { + run(function () { return adminApi('DELETE', userPath(name), { confirm: val('pp-confirm') }); }, function (r: { manual?: string[] }) { + var manual = r && Array.isArray(r.manual) ? r.manual : []; + PS.open = null; + loadList(); + ppMsg(format(PT().deleted, { name: name }) + (manual.length ? ' ' + format(PT().manual, { list: manual.join(', ') }) : '')); + }); + } + function addToken(name: string) { + var label = val('pp-tlabel').trim(); + run(function () { return adminApi('POST', userPath(name, '/tokens'), { label: label }); }, function (r: { token?: string }) { + ppMsg(''); + loadPerson(name); + if (r && typeof r.token === 'string') showSecret('token', r.token, PT().tokenNote); + }); + } + function revokeToken(id: string) { + var name = PS.open; + if (!name || !/^[1-9][0-9]{0,15}$/.test(id)) return; + run(function () { return adminApi('DELETE', '/tokens/' + id); }, function () { + ppMsg(PT().tokenRevokedMsg); + loadPerson(name!); + }); + } + function stravaUrl() { + var id = val('pp-sid').trim(); + run(function () { return adminApi('POST', '/strava/authorize-url', { clientId: id }); }, function (r: { url?: string }) { + PS.stravaId = id; + // only an https address is ever put into a link + PS.stravaUrl = r && typeof r.url === 'string' && /^https:\/\//i.test(r.url) ? r.url : ''; + ppMsg(PS.stravaUrl ? '' : PT().errors.generic); + if (PS.open) setHtml('pp-prov', providersHtml(PS.open)); + }); + } + function stravaSave(name: string) { + var body = { clientId: PS.stravaId || val('pp-sid').trim(), clientSecret: val('pp-ssec'), code: val('pp-scode').trim() }; + wipe(['pp-ssec', 'pp-scode']); + run(function () { return adminApi('PUT', userPath(name, '/strava'), body); }, function () { + body.clientSecret = ''; + PS.stravaUrl = ''; + PS.stravaId = ''; + ppMsg(PT().stravaDone); + loadPerson(name); + }); + } + function providerRemove(name: string, which: 'strava' | 'garmin') { + run(function () { return adminApi('DELETE', userPath(name, '/' + which)); }, function () { + ppMsg(PT().removed); + loadPerson(name); + }); + } + function garminSave(name: string) { + var body = { apiKey: val('pp-gkey'), expires: val('pp-gexp').trim() }; + wipe(['pp-gkey']); + run(function () { return adminApi('PUT', userPath(name, '/garmin'), body); }, function () { + body.apiKey = ''; + ppMsg(PT().garminDone); + loadPerson(name); + }); + } + function viewPerson(name: string) { + var a = auth(); + if (!a || typeof a.view !== 'function') return; + // success reloads the page (HCAuth.view): the next page is that person's + run(function () { return a!.view(name); }, function () { /* the reload follows */ }); + } + function onPeopleClick(t: Element) { + var open = t.closest('[data-pp-sheet]'); + if (open) { + var D = window.HCDetail; + if (isAdmin() && D && typeof D.open === 'function') D.open('people', null, {}); + return; + } + var b = t.closest('[data-pp-act]'); + if (!b) return; + var act = b.getAttribute('data-pp-act'), name = b.getAttribute('data-name') || ''; + if (act === 'manage') openPerson(PS.open === name ? null : name); + else if (act === 'close') openPerson(null); + else if (act === 'reload') { PS.listErr = ''; drawList(); loadList(); } + else if (act === 'view') viewPerson(name); + else if (act === 'link') passwordLink(name); + else if (act === 'copy') copySecret(); + else if (act === 'token-revoke') revokeToken(b.getAttribute('data-id') || ''); + else if (act === 'strava-remove') providerRemove(name, 'strava'); + else if (act === 'garmin-remove') providerRemove(name, 'garmin'); + } + // a form's submit button (Enter in a field included): the form names the action; its person is the open panel's + function onPeopleSubmit(f: Element) { + var which = f.getAttribute('data-pp-form'), name = PS.open || ''; + if (which === 'add') addPerson(); + else if (!name) return; + else if (which === 'rename') rename(name); + else if (which === 'delete') deletePerson(name); + else if (which === 'token-add') addToken(name); + else if (which === 'strava-url') stravaUrl(); + else if (which === 'strava-save') stravaSave(name); + else if (which === 'garmin-save') garminSave(name); + } + if (document.addEventListener) { + document.addEventListener('click', function (e) { + var t = (e && e.target) as Element | null; + if (t && typeof t.closest === 'function') onPeopleClick(t); + }); + document.addEventListener('submit', function (e) { + var t = (e && e.target) as Element | null; + var f = t && t.closest ? t.closest('[data-pp-form]') : null; + if (!f) return; + if (e && typeof e.preventDefault === 'function') e.preventDefault(); + onPeopleSubmit(f); + }); + } + function peopleRender() { + // a fresh draw of the sheet starts from nothing shown: the list is asked again, no secret lingers + PS.secret = null; + PS.stravaUrl = ''; + if (isAdmin()) loadList(); + return { head: '', body: peopleBody() }; + } + HC.registerView('people', { title: function () { return PT().title; }, render: peopleRender }); + function render() { drawnWithSettings = !!settings(); if (!P.hasData) return { head: headHtml(), body: goalHtml() + langHtml() + note(T.onboarding, 'pf-onboard') + accountHtml() }; diff --git a/web/src/client/signin.test.mjs b/web/src/client/signin.test.mjs index 5a93c1ee..68561d69 100644 --- a/web/src/client/signin.test.mjs +++ b/web/src/client/signin.test.mjs @@ -44,8 +44,9 @@ const res = (status, body) => ({ ok: status >= 200 && status < 300, status, json const tick = () => new Promise((r) => setTimeout(r, 5)); /** @typedef {(url: string, init: FetchCall['init']) => unknown} Server */ -/** @param {{server?: Server | null, locale?: string, protocol?: string}} [o] */ -function setup({ server = null, locale = 'en', protocol = 'http:' } = {}) { +/** `tab`: a working sessionStorage (a plain map) instead of the inert stand-in. + * @param {{server?: Server | null, locale?: string, protocol?: string, hash?: string, tab?: Record | null}} [o] */ +function setup({ server = null, locale = 'en', protocol = 'http:', hash = '', tab = null } = {}) { /** @type {FetchCall[]} */ const calls = []; const body = new El(); @@ -53,15 +54,22 @@ function setup({ server = null, locale = 'en', protocol = 'http:' } = {}) { /** @type {Record void)[]>} */ const docListeners = {}; const wrap = new El(); const root = new El(); - const storage = { touched: 0, getItem() { this.touched++; return null; }, setItem() { this.touched++; }, removeItem() { this.touched++; } }; + // inert: keeps nothing. `written` records every value a script tried to store (the only storage use allowed is the + // tab's hc.viewing flag, a username: never a password or a link token) + const storage = { written: /** @type {string[]} */ ([]), getItem() { return null; }, setItem(/** @type {string} */ k, /** @type {string} */ v) { this.written.push(k + '=' + v); }, removeItem() {} }; let reloads = 0; + /** @type {string[]} */ const replaced = []; /** @type {VmGlobals} */ const ctx = { window: {}, LOCALE: locale, I18N_SIGNIN: locale === 'es' ? esS : enS, - location: { protocol, reload: () => { reloads++; } }, - localStorage: storage, sessionStorage: storage, + location: { protocol, hash, pathname: '/', search: '', reload: () => { reloads++; } }, + history: { replaceState: (/** @type {unknown} */ _s, /** @type {string} */ _t, /** @type {string} */ url) => { replaced.push(url); } }, + localStorage: storage, + sessionStorage: tab + ? { getItem: (/** @type {string} */ k) => (k in tab ? tab[k] : null), setItem: (/** @type {string} */ k, /** @type {string} */ v) => { tab[k] = String(v); }, removeItem: (/** @type {string} */ k) => { delete tab[k]; } } + : storage, document: { - body: { appendChild: (/** @type {El} */ e) => { appended.push(e); } }, + body: { appendChild: (/** @type {El & {parentNode?: unknown}} */ e) => { e.parentNode = { removeChild() {} }; appended.push(e); } }, documentElement: root, createElement: () => new El(), getElementById: () => null, @@ -75,7 +83,7 @@ function setup({ server = null, locale = 'en', protocol = 'http:' } = {}) { loadUtil(ctx); vm.runInContext(source, ctx); void body; - return { ctx, win: /** @type {VmGlobals} */ (ctx.window), calls, appended, wrap, root, storage, reloads: () => reloads, docListeners }; + return { ctx, win: /** @type {VmGlobals} */ (ctx.window), calls, appended, wrap, root, storage, reloads: () => reloads, docListeners, replaced }; } /** the sheet's form parts after it was built */ /** @param {El} sheet */ @@ -88,7 +96,7 @@ const session = (/** @type {number} */ status, /** @type {unknown} */ body) => ( test('session answer { open: true }: open single-user mode, no sheet, nothing changes', async () => { const s = setup({ server: session(200, { open: true }) }); await tick(); - assert.deepEqual({ ...s.win.HCAuth.state() }, { status: 'open', username: null }); + assert.deepEqual({ ...s.win.HCAuth.state() }, { status: 'open', username: null, admin: false, sharing: false, viewing: null }); assert.equal(s.appended.length, 0, 'no sign-in sheet'); assert.equal(s.wrap.attrs.inert, undefined, 'the page is not locked'); assert.equal(s.calls.length, 1); @@ -105,7 +113,7 @@ test('the session check is one GET /api/auth/session with the X-HC-Auth header', test('session answer { open: false, username }: signed in, no sheet, the username is known', async () => { const s = setup({ server: session(200, { open: false, username: 'ana' }) }); await tick(); - assert.deepEqual({ ...s.win.HCAuth.state() }, { status: 'signedin', username: 'ana' }); + assert.deepEqual({ ...s.win.HCAuth.state() }, { status: 'signedin', username: 'ana', admin: false, sharing: false, viewing: null }); assert.equal(s.appended.length, 0); }); @@ -312,7 +320,8 @@ test('the password is never stored: no storage call, not in the state, not on wi p.pass.value = 'S3cret-pass'; p.form.fire('submit'); await tick(); - assert.equal(s.storage.touched, 0); + assert.deepEqual(s.storage.written.filter((w) => !w.startsWith('hc.viewing=')), [], 'nothing but the view flag is ever stored'); + assert.ok(s.storage.written.every((w) => /^hc\.viewing=[a-z0-9._-]{1,64}$/.test(w)), 'and that flag is a username'); assert.doesNotMatch(JSON.stringify(s.win.HCAuth.state()), /S3cret/); assert.doesNotMatch(String(s.appended[0].innerHTML), /S3cret/); assert.doesNotMatch(JSON.stringify(Object.keys(s.win)), /S3cret/); @@ -381,3 +390,363 @@ test('es: the show / hide control is in Spanish', async () => { eye.fire('click'); assert.equal(eye.textContent, 'Ocultar'); }); + +/* ---------- the session flags, sharing, the coach view ---------- */ +const TOKEN = `hcp_${'Ab3_-'.repeat(8)}xyz`; // hcp_ + 43 base64url characters +assert.match(TOKEN, /^hcp_[A-Za-z0-9_-]{43}$/); +/** @param {Record} extra */ +const signedIn = (extra) => session(200, { open: false, username: 'alex', ...extra }); +/** @param {(url: string, init: FetchCall['init']) => unknown} next the answers after the session check + * @param {Record} [extra] */ +const withSession = (next, extra = {}) => (/** @type {string} */ url, /** @type {FetchCall['init']} */ init) => (url === '/api/auth/session' ? res(200, { open: false, username: 'alex', ...extra }) : next(url, init)); + +test('the session answer carries admin, sharing and viewing into the state; an older server that omits them means false / false / null', async () => { + const s = setup({ server: signedIn({ admin: true, sharing: true, viewing: 'ana' }) }); + await tick(); + assert.deepEqual({ ...s.win.HCAuth.state() }, { status: 'signedin', username: 'alex', admin: true, sharing: true, viewing: 'ana' }); + const old = setup({ server: signedIn({}) }); + await tick(); + assert.deepEqual({ ...old.win.HCAuth.state() }, { status: 'signedin', username: 'alex', admin: false, sharing: false, viewing: null }); + const odd = setup({ server: signedIn({ admin: 'yes', sharing: 1, viewing: 7 }) }); + await tick(); + assert.deepEqual({ ...odd.win.HCAuth.state() }, { status: 'signedin', username: 'alex', admin: false, sharing: false, viewing: null }, 'only real booleans and a string count'); +}); + +test('signed out and open mode carry no flags', async () => { + const s = setup({ server: session(401, { error: 'unauthenticated' }) }); + await tick(); + assert.deepEqual({ ...s.win.HCAuth.state() }, { status: 'signedout', username: null, admin: false, sharing: false, viewing: null }); +}); + +test('setSharing: POST /api/auth/sharing {sharing} with the X-HC-Auth header, the state follows and the listeners hear it', async () => { + const s = setup({ server: withSession((url, init) => (url === '/api/auth/sharing' ? res(200, { sharing: JSON.parse(init.body || '{}').sharing }) : res(500))) }); + await tick(); + /** @type {boolean[]} */ const seen = []; + s.win.HCAuth.onChange((/** @type {{sharing: boolean}} */ st) => seen.push(st.sharing)); + assert.equal(await s.win.HCAuth.setSharing(true), true); + const c = s.calls.find((x) => x.url === '/api/auth/sharing'); + assert.ok(c); + assert.equal(c.init.method, 'POST'); + assert.equal(c.init.headers?.['X-HC-Auth'], '1'); + assert.deepEqual(JSON.parse(c.init.body || ''), { sharing: true }); + assert.equal(s.win.HCAuth.state().sharing, true); + assert.equal(await s.win.HCAuth.setSharing(false), false); + assert.deepEqual(seen, [true, false]); + assert.equal(s.reloads(), 0, 'no reload for a consent change'); +}); + +test('setSharing that fails: it rejects with the error and the state stays', async () => { + const s = setup({ server: withSession(() => res(403, { error: 'read_only' }), { sharing: true }) }); + await tick(); + await assert.rejects(s.win.HCAuth.setSharing(false), (/** @type {{code: string, status: number}} */ e) => e.code === 'read_only' && e.status === 403); + assert.equal(s.win.HCAuth.state().sharing, true); +}); + +test('view(name): POST /api/auth/view {username}, then the page reloads (its HTML belongs to another person)', async () => { + const s = setup({ server: withSession((url) => (url === '/api/auth/view' ? res(200, { viewing: 'ana' }) : res(500)), { admin: true }) }); + await tick(); + await s.win.HCAuth.view('ana'); + const c = s.calls.find((x) => x.url === '/api/auth/view'); + assert.ok(c); + assert.equal(c.init.method, 'POST'); + assert.equal(c.init.headers?.['X-HC-Auth'], '1'); + assert.deepEqual(JSON.parse(c.init.body || ''), { username: 'ana' }); + assert.equal(s.reloads(), 1); +}); + +test('view(name) refused (403 not_shared): it rejects and nothing reloads', async () => { + const s = setup({ server: withSession(() => res(403, { error: 'not_shared' }), { admin: true }) }); + await tick(); + await assert.rejects(s.win.HCAuth.view('ana'), (/** @type {{code: string}} */ e) => e.code === 'not_shared'); + assert.equal(s.reloads(), 0); +}); + +test('unview(): POST /api/auth/unview, then the page reloads; a failure rejects without a reload', async () => { + let ok = true; + const s = setup({ server: withSession((url) => (url === '/api/auth/unview' ? (ok ? res(204) : res(500, { error: 'internal' })) : res(500)), { admin: true, viewing: 'ana' }) }); + await tick(); + ok = false; + await assert.rejects(s.win.HCAuth.unview()); + assert.equal(s.reloads(), 0); + ok = true; + await s.win.HCAuth.unview(); + const c = s.calls.filter((x) => x.url === '/api/auth/unview').pop(); + assert.equal(c?.init.method, 'POST'); + assert.equal(c?.init.headers?.['X-HC-Auth'], '1'); + assert.equal(s.reloads(), 1); +}); + +test('the coach banner: only while viewing, with the name (escaped), the reserved height class and a way back', async () => { + const none = setup({ server: signedIn({ admin: true }) }); + await tick(); + assert.equal(none.appended.length, 0, 'no banner when not viewing'); + assert.equal(none.root.classes.has('coach-on'), false); + const s = setup({ server: withSession((url) => (url === '/api/auth/unview' ? res(204) : res(500)), { admin: true, viewing: 'ana' }) }); + await tick(); + assert.equal(s.appended.length, 1); + const bar = s.appended[0]; + assert.equal(bar.attrs.role, 'region'); + assert.equal(bar.hidden, false); + assert.match(bar.innerHTML, /Viewing <b>ana<\/b> · read-only/); + assert.match(bar.innerHTML, /]*type="button"[^>]*id="coach-back"[^>]*>Back to my page c.url === '/api/auth/unview')); + assert.equal(s.reloads(), 1); +}); + +test('the coach banner back button that fails says so in the banner and does not reload', async () => { + const s = setup({ server: withSession(() => res(500, { error: 'internal' }), { admin: true, viewing: 'ana' }) }); + await tick(); + s.appended[0].querySelector('#coach-back').fire('click'); + await tick(); + assert.equal(s.reloads(), 0); + assert.equal(s.appended[0].querySelector('#coach-txt').textContent, 'Could not go back. Try again.'); +}); + +test('es: the banner is in Spanish', async () => { + const s = setup({ locale: 'es', server: signedIn({ admin: true, viewing: 'ana' }) }); + await tick(); + assert.match(s.appended[0].innerHTML, /Viendo a ana · solo lectura/); + assert.match(s.appended[0].innerHTML, />Volver a mi página { + const s = setup({ server: withSession(() => res(403, { error: 'read_only' }), { admin: true, viewing: 'ana' }) }); + await tick(); + const txt = s.appended[0].querySelector('#coach-txt'); + assert.match(s.appended[0].innerHTML, /id="coach-txt" role="status"/, 'a live region: the notice is announced'); + await s.ctx.HC.fetchTimeout('/api/auth/sharing', { method: 'POST' }, 1000); + await tick(); + assert.equal(txt.textContent, '', 'an /api/auth/ answer is not the page writing (the stub keeps the markup, not the text)'); + await s.ctx.HC.jsonApi('/api/food', 'X-HC-Food', 1000)('POST', '/log', {}).catch(() => {}); + await tick(); + assert.equal(txt.textContent, "Read-only: you are viewing ana's page."); + assert.equal(s.appended.length, 1, 'no second element'); +}); + +test('the read_only notice in es; a page that did not know it was a view asks the session once and then shows it', async () => { + const es = setup({ locale: 'es', server: withSession(() => res(403, { error: 'read_only' }), { viewing: 'ana' }) }); + await tick(); + await es.ctx.HC.fetchTimeout('/api/food/log', { method: 'POST' }, 1000); + await tick(); + assert.equal(es.appended[0].querySelector('#coach-txt').textContent, 'Solo lectura: estás viendo la página de ana.'); + // not viewing and still refused: the session is asked again, nothing is drawn when it says no + const anon = setup({ server: withSession(() => res(403, { error: 'read_only' })) }); + await tick(); + const before = anon.calls.length; + await anon.ctx.HC.fetchTimeout('/api/food/log', { method: 'POST' }, 1000); + await tick(); + assert.equal(anon.calls.filter((c) => c.url === '/api/auth/session').length, 2, 'one more session check'); + assert.ok(anon.calls.length > before); + assert.equal(anon.appended.length, 0); +}); + +/* ---------- set-password mode ---------- */ +/** @param {Record} [answers] by url after the 401 session check */ +function pwServer(answers = {}) { + return (/** @type {string} */ url) => { + if (url === '/api/auth/session') return res(401, { error: 'unauthenticated' }); + const a = answers[url]; + return a ? res(a[0], a[1]) : res(500, { error: 'unexpected' }); + }; +} +/** @param {El} sheet */ +const pw = (sheet) => ({ form: sheet.querySelector('#signin-setpw'), a: sheet.querySelector('#signin-new'), b: sheet.querySelector('#signin-again'), err: sheet.querySelector('#signin-err'), go: sheet.querySelector('#signin-go'), eye: sheet.querySelector('#signin-eye') }); +const LONG = 'a long enough password'; + +test('#set-password=: the sheet asks for a new password (two fields, autofill hints for a new password) instead of the sign-in form', async () => { + const s = setup({ server: pwServer(), hash: `#set-password=${TOKEN}` }); + await tick(); + const h = s.appended[0].innerHTML; + assert.match(h, /]*id="signin-setpw"/); + assert.doesNotMatch(h, /id="signin-user"|id="signin-form"/); + assert.match(h, /Choose your password/); + assert.match(h, /]*for="signin-new"[^>]*>New password]*for="signin-again"[^>]*>Repeat the password]*type="submit"[^>]*id="signin-go"[^>]*>Set password]*role="alert"/); + assert.doesNotMatch(h, new RegExp(TOKEN), 'the token is not in the markup'); + assert.ok(pw(s.appended[0]).a.focused); +}); + +test('a fragment that is not a link token (wrong prefix, length or alphabet, extra text) leaves the normal sign-in form', async () => { + for (const hash of ['#set-password=', '#set-password=hcp_short', `#set-password=${TOKEN}x`, `#set-password=${TOKEN.replace('hcp_', 'hcq_')}`, `#set-password=${TOKEN}&x=1`, `#x=set-password=${TOKEN}`, '#set-password=hcp_' + '!'.repeat(43)]) { + const s = setup({ server: pwServer(), hash }); + await tick(); + assert.match(s.appended[0].innerHTML, /id="signin-form"/, hash); + assert.doesNotMatch(s.appended[0].innerHTML, /signin-setpw/, hash); + } +}); + +test('es: the set-password form is in Spanish', async () => { + const s = setup({ locale: 'es', server: pwServer(), hash: `#set-password=${TOKEN}` }); + await tick(); + assert.match(s.appended[0].innerHTML, /Elige tu contraseña/); + assert.match(s.appended[0].innerHTML, />Guardar contraseña { + const s = setup({ server: pwServer(), hash: `#set-password=${TOKEN}` }); + await tick(); + const p = pw(s.appended[0]); + for (const bad of ['a'.repeat(11), 'a'.repeat(257)]) { + p.a.value = bad; + p.b.value = bad; + p.form.fire('submit'); + assert.equal(p.err.textContent, 'The password needs 12 to 256 characters.'); + assert.equal(p.a.value, bad, 'what was typed stays'); + } + p.a.value = LONG; + p.b.value = LONG + '!'; + p.form.fire('submit'); + assert.equal(p.err.textContent, 'The two passwords are not the same.'); + assert.ok(p.b.focused); + await tick(); + assert.equal(s.calls.filter((c) => c.url === '/api/auth/password').length, 0); + // the limits themselves are fine + for (const edge of ['a'.repeat(12), 'a'.repeat(256)]) { + p.a.value = edge; + p.b.value = edge; + p.form.fire('submit'); + await tick(); + } + assert.equal(s.calls.filter((c) => c.url === '/api/auth/password').length, 2); +}); + +test('set password: POST /api/auth/password {token, password} with X-HC-Auth; on 204 the fragment goes and the sign-in form shows with the confirmation', async () => { + const s = setup({ server: pwServer({ '/api/auth/password': [204, undefined] }), hash: `#set-password=${TOKEN}` }); + await tick(); + const sheet = s.appended[0]; + const p = pw(sheet); + p.a.value = LONG; + p.b.value = LONG; + p.form.fire('submit'); + assert.deepEqual([p.a.value, p.b.value], ['', ''], 'the fields are cleared at once'); + assert.equal(p.go.disabled, true); + await tick(); + const c = s.calls.find((x) => x.url === '/api/auth/password'); + assert.ok(c); + assert.equal(c.init.method, 'POST'); + assert.equal(c.init.headers?.['X-HC-Auth'], '1'); + assert.deepEqual(JSON.parse(c.init.body || ''), { token: TOKEN, password: LONG }); + assert.deepEqual(s.replaced, ['/'], 'the fragment is removed from the address'); + assert.match(sheet.innerHTML, /id="signin-form"/); + assert.match(sheet.innerHTML, /]*role="status"[^>]*>Password set\. Sign in\. { + /** @type {[number, unknown, string][]} */ + const cases = [ + [400, { error: 'invalid_password' }, 'The password needs 12 to 256 characters.'], + [410, { error: 'invalid_link' }, 'This link is no longer valid. Ask for a new one.'], + [429, { error: 'rate_limited' }, 'Too many attempts. Wait a few minutes and try again.'], + [500, { error: 'internal' }, 'Could not set the password. Try again in a moment.'], + [403, { error: 'forbidden_origin' }, 'Could not set the password. Try again in a moment.'], + ]; + for (const [status, body, text] of cases) { + const s = setup({ server: pwServer({ '/api/auth/password': [status, body] }), hash: `#set-password=${TOKEN}` }); + await tick(); + const p = pw(s.appended[0]); + p.a.value = LONG; + p.b.value = LONG; + p.form.fire('submit'); + await tick(); + assert.equal(p.err.textContent, text, String(status)); + assert.deepEqual([p.a.value, p.b.value], ['', '']); + assert.equal(p.go.disabled, false); + assert.deepEqual(s.replaced, [], 'the address is untouched on an error'); + assert.match(s.appended[0].innerHTML, /signin-setpw/, 'still the set-password form'); + } +}); + +test('set password with no answer: the offline message', async () => { + let down = false; + const s = setup({ server: (/** @type {string} */ url) => { if (url === '/api/auth/session') return res(401, { error: 'unauthenticated' }); if (down) throw new TypeError('x'); return res(204); }, hash: `#set-password=${TOKEN}` }); + await tick(); + down = true; + const p = pw(s.appended[0]); + p.a.value = LONG; + p.b.value = LONG; + p.form.fire('submit'); + await tick(); + assert.equal(p.err.textContent, 'The server did not answer. Check your connection and try again.'); +}); + +test('the show / hide control of the set-password form toggles both fields', async () => { + const s = setup({ server: pwServer(), hash: `#set-password=${TOKEN}` }); + await tick(); + const p = pw(s.appended[0]); + assert.match(s.appended[0].innerHTML, /id="signin-eye"[^>]*aria-controls="signin-new signin-again"[^>]*>Show { + const s = setup({ server: pwServer({ '/api/auth/password': [204, undefined] }), hash: `#set-password=${TOKEN}` }); + await tick(); + const p = pw(s.appended[0]); + p.a.value = LONG; + p.b.value = LONG; + p.form.fire('submit'); + await tick(); + assert.deepEqual(s.storage.written.filter((w) => !w.startsWith('hc.viewing=')), [], 'nothing but the view flag is ever stored'); + assert.ok(s.storage.written.every((w) => /^hc\.viewing=[a-z0-9._-]{1,64}$/.test(w)), 'and that flag is a username'); + for (const c of s.calls) assert.doesNotMatch(c.url, new RegExp(TOKEN + '|' + LONG)); + assert.equal(s.calls.filter((c) => /hcp_/.test(String(c.init.body))).length, 1, 'the token is only in the one POST body'); + assert.doesNotMatch(JSON.stringify(s.win.HCAuth.state()) + JSON.stringify(Object.keys(s.win)), new RegExp(TOKEN + '|' + LONG)); + assert.doesNotMatch(String(s.appended[0].innerHTML), new RegExp(TOKEN + '|' + LONG)); +}); + +/* ---------- whose page this tab shows (sessionStorage hc.viewing) ---------- */ + +test('view() / unview() write whose page the tab shows BEFORE the reload, so the next load knows it at once', async () => { + /** @type {Record} */ const tab = {}; + const s = setup({ tab, server: withSession((url) => (url === '/api/auth/view' ? res(200, { viewing: 'ana' }) : url === '/api/auth/unview' ? res(204) : res(500)), { admin: true }) }); + await tick(); + assert.deepEqual([tab['hc.viewing'], s.reloads()], [undefined, 0], 'an own page: no flag, no reload'); + await s.win.HCAuth.view('Ana'); + assert.deepEqual([tab['hc.viewing'], s.reloads()], ['ana', 1], 'the name the server answered'); + await s.win.HCAuth.unview(); + assert.deepEqual(['hc.viewing' in tab, s.reloads()], [false, 2]); +}); + +test('the session answer and the tab disagree: the flag is corrected and the page reloads ONCE; when they agree nothing happens', async () => { + /** @type {Record} */ const started = {}; + const a = setup({ tab: started, server: signedIn({ admin: true, viewing: 'ana' }) }); + await tick(); + assert.deepEqual([started['hc.viewing'], a.reloads()], ['ana', 1], 'a view started elsewhere'); + await a.win.HCAuth.check(); + assert.equal(a.reloads(), 1, 'now they agree: no second reload'); + + /** @type {Record} */ const ended = { 'hc.viewing': 'ana' }; + const b = setup({ tab: ended, server: signedIn({ admin: true }) }); + await tick(); + assert.deepEqual(['hc.viewing' in ended, b.reloads()], [false, 1], 'the view ended (consent taken back): this HTML is not the session\'s any more'); + + /** @type {Record} */ const other = { 'hc.viewing': 'ana' }; + const c = setup({ tab: other, server: signedIn({ admin: true, viewing: 'luis' }) }); + await tick(); + assert.deepEqual([other['hc.viewing'], c.reloads()], ['luis', 1]); + + /** @type {Record} */ const out = { 'hc.viewing': 'ana' }; + const d = setup({ tab: out, server: session(401, { error: 'unauthenticated' }) }); + await tick(); + assert.deepEqual(['hc.viewing' in out, d.reloads()], [false, 0], 'signed out: the flag goes, the sign-in sheet is the answer'); +}); + +test('a tab whose sessionStorage does not keep a value never reloads on a session answer (no loop)', async () => { + const s = setup({ server: signedIn({ admin: true, viewing: 'ana' }) }); + await tick(); + await s.win.HCAuth.check(); + assert.equal(s.reloads(), 0); + assert.equal(s.win.HCAuth.state().viewing, 'ana', 'the banner still follows the server'); +}); diff --git a/web/src/client/signin.ts b/web/src/client/signin.ts index c2963417..095b7bdf 100644 --- a/web/src/client/signin.ts +++ b/web/src/client/signin.ts @@ -7,6 +7,12 @@ * POST /login {username, password} -> 200 {username} + the session cookie (HttpOnly: this script never sees it); * 401 invalid_credentials / 429 rate_limited / 400 * POST /logout 204 + * POST /password {token, password} 204: the set-password form below (a one-time link from an admin) + * POST /sharing {sharing} 200 {sharing}: this person's consent to be viewed by the admin (profile sheet switch) + * POST /view {username} 200 {viewing}, POST /unview 204: the admin's coach view (a reload follows: the HTML belongs + * to the viewed person) + * The session answer also carries {admin, sharing, viewing} (docs/lan-services.md -> Coach view); an older server that + * omits them means false / false / null. * Anything else (404 from a server that predates /auth, 5xx, no answer, a body that is neither shape) is 'unknown': * no sheet, no change, the page exactly as without this script. A page opened from a file (HC.lan() false), the * example / demo build and a browser without fetch never ask anything. @@ -19,9 +25,20 @@ * password only ever lives in the field and one local variable: it is cleared from the field on submit, never put * in storage, the state or a global. * - * window.HCAuth = { state() -> {status: 'unknown' | 'open' | 'signedin' | 'signedout', username}, check(), - * signOut() (rejects when the server did not answer), onChange(fn) }. The profile sheet (client/profile.ts) - * shows "Sign out" only while status is 'signedin'. Copy: I18N_SIGNIN (i18n/signin-templates.mjs). + * Set-password mode: when the address fragment is `#set-password=` (`hcp_` + 43 base64url characters) the + * sheet / sign-in page shows a "choose your password" form instead of the sign-in form (two fields, 12 to 256 + * characters, both equal, checked here; one show / hide control). On 204 the fragment is removed and the normal form + * shows with "Password set. Sign in.". The token lives in one local variable: never logged, stored or sent anywhere + * but that one POST body. + * + * Coach view: while the session views somebody (`viewing`) a banner "Viewing {name} · read-only" with a "Back to my + * page" button is fixed at the top (its height is reserved by profile.css), and any /api/ `403 read_only` (HC.onReadOnly, + * util.ts) shows a short notice instead of a generic failure. + * + * window.HCAuth = { state() -> {status: 'unknown' | 'open' | 'signedin' | 'signedout', username, admin, sharing, + * viewing}, check(), signOut() (rejects when the server did not answer), onChange(fn), setSharing(on), view(name), + * unview() (view / unview reload the page on success; all three reject on failure) }. The profile sheet + * (client/profile.ts) shows "Sign out" only while status is 'signedin'. Copy: I18N_SIGNIN (i18n/signin-templates.mjs). * Module script (bundled into the page, docs/plan-page.md → Module scripts); reads window.HC (util.ts). */ import type { PageGlobals } from './page-globals'; @@ -30,52 +47,95 @@ declare const HC: PageGlobals['HC']; declare const I18N_SIGNIN: PageGlobals['I18N_SIGNIN'] | undefined; type Status = 'unknown' | 'open' | 'signedin' | 'signedout'; -type AuthState = { status: Status; username: string | null }; +type AuthState = { status: Status; username: string | null; admin: boolean; sharing: boolean; viewing: string | null }; +type Flags = { admin?: boolean; sharing?: boolean; viewing?: string | null }; (function () { if (typeof window === 'undefined' || typeof fetch !== 'function' || typeof I18N_SIGNIN === 'undefined' || !I18N_SIGNIN || !HC.lan()) return; var T = I18N_SIGNIN, esc = HC.esc; + // a one-time password link token (services/loop-ingest/src/password-links.js: `hcp_` + 32 random bytes, base64url) + var TOKEN_RE = /^hcp_[A-Za-z0-9_-]{43}$/; var api = HC.jsonApi('/api/auth', 'X-HC-Auth', 10000); var status: Status = 'unknown', username: string | null = null; + var admin = false, sharing = false, viewing: string | null = null; + // the set-password link's token, read from the address once (never logged, stored or put in another URL) + var pwToken: string | null = readToken(); + var done = false; // "Password set. Sign in." shows above the sign-in form var listeners: Array<(s: AuthState) => void> = []; var sheet: HTMLElement | null = null; var busy = false; + function readToken(): string | null { + var h = typeof location !== 'undefined' && location && typeof location.hash === 'string' ? location.hash : ''; + var m = /^#set-password=(.+)$/.exec(h); + return m && TOKEN_RE.test(m[1]) ? m[1] : null; + } function snapshot(): AuthState { - return { status: status, username: username }; + return { status: status, username: username, admin: admin, sharing: sharing, viewing: viewing }; } - function set(next: Status, name?: string | null) { - var changed = status !== next || username !== (next === 'signedin' ? name || null : null); - status = next; - username = next === 'signedin' ? name || null : null; - if (next === 'signedout') showSheet(); - if (!changed) return; + function key(): string { + return [status, username, admin, sharing, viewing].join('\u0000'); + } + function notify() { listeners.slice().forEach(function (fn) { try { fn(snapshot()); } catch (e) { /* a listener never breaks the others */ } }); } + function set(next: Status, name?: string | null, flags?: Flags) { + var before = key(), on = next === 'signedin', f = flags || {}; + status = next; + username = on ? name || null : null; + admin = on && f.admin === true; + sharing = on && f.sharing === true; + viewing = on && typeof f.viewing === 'string' && f.viewing ? f.viewing : null; + if (next === 'signedout') showSheet(); + drawBanner(); + if (key() !== before) notify(); + } - function markup(): string { + function brand(): string { // the brand mark is the favicon's three arcs (sleep, recovery, strain), coloured by the tokens in profile.css var arc = function (cls: string, turn: string) { return ''; }; - return '' + '' + '' + ''; } + // the "choose your password" form of a one-time link (#set-password=) + function setPasswordMarkup(): string { + var P = T.setPassword; + return ''; + } // the page behind (and an open detail sheet) cannot be reached while the sheet is up function lockPage() { var wrap = document.querySelector ? document.querySelector('.wrap') : null; @@ -98,25 +158,35 @@ type AuthState = { status: Status; username: string | null }; el.setAttribute('role', 'dialog'); el.setAttribute('aria-modal', 'true'); el.setAttribute('aria-labelledby', 'signin-title'); - el.innerHTML = markup(); sheet = el; - part('signin-form').addEventListener('submit', submit); - part('signin-eye').addEventListener('click', function () { reveal(!shown, true); }); + draw(); document.body.appendChild(el); } sheet.hidden = false; lockPage(); - var u = part('signin-user'); + focusFirst(); + } + // (re)build the form in the sheet for the current mode and wire it + function draw() { + shown = false; + sheet!.innerHTML = markup(); + if (pwToken) part('signin-setpw').addEventListener('submit', submitSetPassword); + else part('signin-form').addEventListener('submit', submit); + part('signin-eye').addEventListener('click', function () { reveal(!shown, true); }); + } + function focusFirst() { + var u = part(pwToken ? 'signin-new' : 'signin-user'); if (u && typeof u.focus === 'function') u.focus(); } // show or hide what is typed in the password field; the text and the focus stay where they are var shown = false; function reveal(on: boolean, refocus: boolean) { - var pass = part('signin-pass'), eye = part('signin-eye'); + var pass = part(pwToken ? 'signin-new' : 'signin-pass'), btn = part('signin-eye'); shown = on; pass.setAttribute('type', on ? 'text' : 'password'); - eye.setAttribute('aria-pressed', on ? 'true' : 'false'); - eye.textContent = on ? T.hide : T.show; + if (pwToken) part('signin-again').setAttribute('type', on ? 'text' : 'password'); + btn.setAttribute('aria-pressed', on ? 'true' : 'false'); + btn.textContent = on ? T.hide : T.show; if (refocus && typeof pass.focus === 'function') pass.focus(); } function reason(e: { code?: string } | null): string { @@ -154,15 +224,108 @@ type AuthState = { status: Status; username: string | null }; pw = ''; } + function pwReason(e: { code?: string } | null): string { + var errs = T.setPassword.errors; + return errs[(e && e.code && Object.prototype.hasOwnProperty.call(errs, e.code) ? e.code : 'generic') as keyof typeof errs]; + } + function submitSetPassword(ev: Event) { + if (ev && typeof ev.preventDefault === 'function') ev.preventDefault(); + if (busy || !pwToken) return; + var a = part('signin-new'), b = part('signin-again'), err = part('signin-err'), go = part('signin-go'); + var pw = String(a.value || ''), again = String(b.value || ''); + err.textContent = ''; + // checked here before anything is sent: the text stays in the fields for the person to fix + if (pw.length < 12 || pw.length > 256) { err.textContent = T.setPassword.errors.length; a.focus(); return; } + if (pw !== again) { err.textContent = T.setPassword.errors.mismatch; b.focus(); return; } + if (shown) reveal(false, false); + a.value = ''; + b.value = ''; + busy = true; + go.disabled = true; + go.textContent = T.setPassword.busy; + api('POST', '/password', { token: pwToken, password: pw }).then(function () { + busy = false; + // the link is spent: the fragment goes, the normal form shows + pwToken = null; + done = true; + if (typeof history !== 'undefined' && history && typeof history.replaceState === 'function' && typeof location !== 'undefined') { + history.replaceState(null, '', String(location.pathname || '/') + String(location.search || '')); + } + draw(); + focusFirst(); + }, function (e: { code?: string }) { + busy = false; + go.disabled = false; + go.textContent = T.setPassword.submit; + err.textContent = pwReason(e); + a.focus(); + }); + pw = ''; + again = ''; + } + + /* ---------- the coach view: banner, notice ---------- */ + // the notice for a refused write replaces the banner's words for a few seconds (one bar, no second element) + var banner: HTMLElement | null = null, drawn: string | null = null, noticeTimer: ReturnType | null = null; + function bannerText(): string { + return HC.format(T.coach.viewing, { name: viewing }); + } + function drawBanner() { + var root = document.documentElement; + if (viewing === drawn) return; + drawn = viewing; + if (!viewing) { + if (banner) { + banner.hidden = true; + if (banner.parentNode) banner.parentNode.removeChild(banner); + } + if (root && root.classList) root.classList.remove('coach-on'); + return; + } + if (!banner) { + banner = document.createElement('div'); + banner.id = 'hc-coach'; + banner.className = 'coach-bar'; + banner.setAttribute('role', 'region'); + } + banner.setAttribute('aria-label', bannerText()); + banner.innerHTML = '' + esc(bannerText()) + '' + + ''; + banner.hidden = false; + // the first thing in the body: in flow (nothing is covered at rest) and sticky (profile.css) + if (!banner.parentNode) { + if (document.body.firstChild && typeof document.body.insertBefore === 'function') document.body.insertBefore(banner, document.body.firstChild); + else document.body.appendChild(banner); + } + if (root && root.classList) root.classList.add('coach-on'); + banner.querySelector('#coach-back')!.addEventListener('click', function () { + unview().catch(function () { showNotice(T.coach.backFailed); }); + }); + } + function showNotice(text: string) { + var txt = banner ? banner.querySelector('#coach-txt') : null; + if (!txt) return; + txt.textContent = text; + if (noticeTimer != null) clearTimeout(noticeTimer); + noticeTimer = setTimeout(function () { if (viewing) txt!.textContent = bannerText(); }, 5000); + } + function readOnlyNotice() { + // a refused write while the page does not know it is a view (the session changed elsewhere): ask once, the banner follows + if (!viewing) { check().then(function (s) { if (s.viewing) readOnlyNotice(); }); return; } + showNotice(HC.format(T.coach.readOnly, { name: viewing })); + } + function check(): Promise { - return api('GET', '/session').then(function (d: { open?: unknown; username?: unknown }) { + return api('GET', '/session').then(function (d: { open?: unknown; username?: unknown; admin?: unknown; sharing?: unknown; viewing?: unknown }) { if (d && d.open === true) set('open'); - else if (d && d.open === false && typeof d.username === 'string') set('signedin', d.username); - else set('unknown'); + else if (d && d.open === false && typeof d.username === 'string') { + set('signedin', d.username, { admin: d.admin === true, sharing: d.sharing === true, viewing: typeof d.viewing === 'string' ? d.viewing : null }); + reconcileView(viewing); + } else set('unknown'); return snapshot(); }, function (e: { status?: number }) { // only a 401 means "log in"; a 404 (a server without /auth), a 5xx or no answer is not a login screen - if (e && e.status === 401) set('signedout'); + if (e && e.status === 401) { set('signedout'); setViewFlag(null); } else set('unknown'); return snapshot(); }); @@ -170,8 +333,55 @@ type AuthState = { status: Status; username: string | null }; function signOut(): Promise { return api('POST', '/logout').then(function () { set('signedout'); }); } + // the person's own consent to be viewed by the admin; resolves the saved value + function setSharing(on: boolean): Promise { + return api('POST', '/sharing', { sharing: Boolean(on) }).then(function (d: { sharing?: unknown }) { + sharing = d && typeof d.sharing === 'boolean' ? d.sharing : Boolean(on); + notify(); + return sharing; + }); + } + function reload() { + if (typeof location !== 'undefined' && typeof location.reload === 'function') location.reload(); + } + /* WHOSE page this tab has loaded, for the scripts that run before the session answer: sessionStorage `hc.viewing` holds + the viewed person's name while this tab shows somebody else's page (nutri-day.ts then keeps its per-viewer storage + untouched: the admin's own cached goal is neither shown on the other person's page nor overwritten by theirs). It is + written before the reload that view() / unview() make, and reconciled with every session answer: when the server's + `viewing` and the flag differ (the view was started or ended elsewhere, or consent was taken back), the flag is + corrected and the page reloaded ONCE, so the HTML and the data are the same person's again. Without sessionStorage + nothing is written and nothing reloads. */ + var VIEW_FLAG = 'hc.viewing'; + function viewFlag(): string | null { + try { return typeof sessionStorage !== 'undefined' ? sessionStorage.getItem(VIEW_FLAG) : null; } catch (e) { return null; } + } + function setViewFlag(name: string | null): boolean { + try { + if (typeof sessionStorage === 'undefined') return false; + if (name) sessionStorage.setItem(VIEW_FLAG, name); else sessionStorage.removeItem(VIEW_FLAG); + return viewFlag() === (name || null); + } catch (e) { return false; } + } + function reconcileView(serverViewing: string | null) { + if (viewFlag() === serverViewing) return; + if (setViewFlag(serverViewing)) reload(); + } + // the admin starts / ends the coach view: the page's HTML belongs to the viewed person, so a reload follows + function view(name: string): Promise { + return api('POST', '/view', { username: String(name) }).then(function (d: { viewing?: unknown }) { + setViewFlag(d && typeof d.viewing === 'string' ? d.viewing : String(name)); + reload(); + }); + } + function unview(): Promise { + return api('POST', '/unview').then(function () { setViewFlag(null); reload(); }); + } HC.onUnauthenticated(function () { set('signedout'); }); - window.HCAuth = { state: snapshot, check: check, signOut: signOut, onChange: function (fn: (s: AuthState) => void) { listeners.push(fn); } }; + if (typeof HC.onReadOnly === 'function') HC.onReadOnly(readOnlyNotice); + window.HCAuth = { + state: snapshot, check: check, signOut: signOut, setSharing: setSharing, view: view, unview: unview, + onChange: function (fn: (s: AuthState) => void) { listeners.push(fn); }, + }; check(); })(); diff --git a/web/src/client/util.test.mjs b/web/src/client/util.test.mjs index ecf0eca3..e2712290 100644 --- a/web/src/client/util.test.mjs +++ b/web/src/client/util.test.mjs @@ -491,7 +491,7 @@ test('each registered view key belongs to ONE client script, always a string lit owner.set(lit[2], f); } } - assert.deepEqual([...owner.keys()].sort(), ['dash-edit', 'food-add', 'home-edit', 'hoy-session', 'journal', 'journal-insights', 'onboarding', 'profile', 'shortcuts', 'tonight']); + assert.deepEqual([...owner.keys()].sort(), ['dash-edit', 'food-add', 'home-edit', 'hoy-session', 'journal', 'journal-insights', 'onboarding', 'people', 'profile', 'shortcuts', 'tonight']); }); test('only util.ts writes window.HCViews: every other client script registers through HC.registerView', () => { @@ -545,3 +545,54 @@ test('onUnauthenticated: a throwing listener never breaks the others or the requ await new Promise((r) => setTimeout(r, 5)); assert.equal(calls, 1); }); + +/** a real Response can be cloned: the answer is peeked at on the clone, the caller reads the original + * @param {number} status @param {unknown} body */ +const cloneable = (status, body) => ({ ...res(status, body), clone: () => res(status, body) }); + +/* HC.onReadOnly: the coach view's trigger (client/signin.ts). A 403 `read_only` from any /api/* call (not /api/auth/*) + * is reported once per answer; nothing else is, and the unauthenticated hook keeps its own rules. */ +test('onReadOnly: a 403 read_only from an /api/ call notifies the listeners once per answer (and still rejects as before)', async () => { + let calls = 0, unauth = 0; + const HC = apiCtx({ fetch: () => Promise.resolve(cloneable(403, { error: 'read_only' })) }); + HC.onReadOnly(() => { calls++; }); + HC.onUnauthenticated(() => { unauth++; }); + await assert.rejects(HC.jsonApi('/api/food', 'X-HC-Food', 1000)('POST', '/log', {}), (/** @type {ApiError} */ e) => e.code === 'read_only' && e.status === 403); + await new Promise((r) => setTimeout(r, 5)); + assert.equal(calls, 1); + const r = await HC.fetchTimeout('/api/journal/x', { method: 'PUT' }, 1000); + assert.equal(r.status, 403, 'the caller still gets the answer'); + await new Promise((r2) => setTimeout(r2, 5)); + assert.equal(calls, 2); + assert.equal(unauth, 0, 'a 403 is never the expired-session trigger'); +}); + +test('onReadOnly: nothing but an /api/ 403 read_only notifies', async () => { + let calls = 0; + /** @param {string} url @param {number} status @param {unknown} [body] */ + const run = async (url, status, body) => { + const answer = { ...res(status, body), clone: () => res(status, body) }; + const HC = apiCtx({ fetch: () => Promise.resolve(answer) }); + HC.onReadOnly(() => { calls++; }); + await HC.fetchTimeout(url, {}, 1000); + await new Promise((r) => setTimeout(r, 5)); + }; + await run('/api/food/log', 200, { ok: true }); + await run('/api/food/log', 403, { error: 'forbidden' }); + await run('/api/food/log', 401, { error: 'read_only' }); + await run('/api/auth/sharing', 403, { error: 'read_only' }); + await run('/api/admin/users', 403, { error: 'forbidden' }); + await run('/status.json', 403, { error: 'read_only' }); + await run('/api/food/log', 403, undefined); + assert.equal(calls, 0); +}); + +test('onReadOnly: a throwing listener never breaks the others or the request', async () => { + let calls = 0; + const HC = apiCtx({ fetch: () => Promise.resolve(cloneable(403, { error: 'read_only' })) }); + HC.onReadOnly(() => { throw new Error('boom'); }); + HC.onReadOnly(() => { calls++; }); + await HC.fetchTimeout('/api/journal/x', {}, 1000); + await new Promise((r) => setTimeout(r, 5)); + assert.equal(calls, 1); +}); diff --git a/web/src/client/util.ts b/web/src/client/util.ts index 575a8b94..63b03abd 100644 --- a/web/src/client/util.ts +++ b/web/src/client/util.ts @@ -110,18 +110,27 @@ var HC = (function () { function onUnauthenticated(fn: () => void): void { unauthListeners.push(fn); } - function tellUnauthenticated(): void { - unauthListeners.slice().forEach(function (fn) { + // The coach view (docs/lan-services.md -> Coach view): while a session views another person's page the server + // answers every write 403 {error: 'read_only'}. Same mechanism and exclusions as above: any /api/ answer (not + // /api/auth/*) tells the HC.onReadOnly listeners once (client/signin.ts shows the notice). + var readOnlyListeners: Array<() => void> = []; + function onReadOnly(fn: () => void): void { + readOnlyListeners.push(fn); + } + function tell(listeners: Array<() => void>): void { + listeners.slice().forEach(function (fn) { try { fn(); } catch (e) { /* a listener never breaks the request */ } }); } - function watchUnauthenticated(url: string, r: Response | null): void { - if (!r || r.status !== 401 || typeof url !== 'string' || url.indexOf('/api/') !== 0 || url.indexOf('/api/auth/') === 0) return; - if (typeof r.clone !== 'function') { tellUnauthenticated(); return; } + function watchAnswers(url: string, r: Response | null): void { + if (!r || (r.status !== 401 && r.status !== 403) || typeof url !== 'string' || url.indexOf('/api/') !== 0 || url.indexOf('/api/auth/') === 0) return; + var unauth = r.status === 401; + if (typeof r.clone !== 'function') { if (unauth) tell(unauthListeners); return; } try { r.clone().json().then(function (d: { error?: unknown } | null) { - if (d && d.error === 'unauthenticated') tellUnauthenticated(); - }, function () { /* no JSON body: not the server's unauthenticated answer */ }); + if (unauth && d && d.error === 'unauthenticated') tell(unauthListeners); + else if (!unauth && d && d.error === 'read_only') tell(readOnlyListeners); + }, function () { /* no JSON body: not one of the server's answers */ }); } catch (e) { /* ditto */ } } // The ONE timed fetch (jsonApi above, client/freshness.ts, client/profile.ts): fetch(url, init) that rejects @@ -162,7 +171,7 @@ var HC = (function () { } if (settled) return; try { - fetch(url, opts).then(function (r) { watchUnauthenticated(url, r); return read ? read(r) : r; }) + fetch(url, opts).then(function (r) { watchAnswers(url, r); return read ? read(r) : r; }) .then(function (v) { finish(resolve, v); }, function (e) { finish(reject, e); }); } catch (e) { finish(reject, e); @@ -705,6 +714,7 @@ var HC = (function () { jsonApi: jsonApi, fetchTimeout: fetchTimeout, onUnauthenticated: onUnauthenticated, + onReadOnly: onReadOnly, fetchJson: fetchJson, DASH: HC_FMT.DASH, int: int, diff --git a/web/src/i18n/profile-templates.mjs b/web/src/i18n/profile-templates.mjs index a1f1e3af..38ab1a25 100644 --- a/web/src/i18n/profile-templates.mjs +++ b/web/src/i18n/profile-templates.mjs @@ -38,6 +38,105 @@ export const en = { signOut: 'Sign out', signingOut: 'Signing out…', failed: 'Could not sign out. Try again.', + // the sharing consent (any signed-in person) and the entry to the admin's People sheet; the save / failed lines are goal's + share: 'Share with my coach', + shareHint: 'Lets the admin see your page, read-only. You can turn it off any time.', + people: 'People', + peopleOpen: 'Manage', + }, + // the admin's People sheet (client/profile.ts, only for an admin on a LOOP server: /api/admin/*, docs/lan-services.md) + people: { + title: 'People', + denied: 'Only an admin can manage people.', + loading: 'Loading…', + retry: 'Try again', + working: 'Working…', + list: 'Everybody with an account', + none: 'Nobody yet.', + badges: { owner: 'Owner', you: 'You', admin: 'Admin', noPassword: 'No password yet', shares: 'Shares' }, + manage: 'Manage', + manageOf: 'Manage {name}', + close: 'Close', + closeOf: 'Close {name}', + addName: 'Username', + providers: 'Strava and Garmin', + addLabel: 'Add a person', + addHint: 'Letters, digits, dots, dashes and underscores. They get a link to set their own password.', + add: 'Add', + added: '{name} added. Create a password link for them.', + view: 'View their page', + viewHint: 'Read-only. Only while they share with their coach.', + link: 'Password link', + linkLabel: 'Password link: send it to {name} (shown once)', + linkNote: 'Valid until {date}. A new link cancels this one. Opening it lets the person choose their own password.', + tokenLabel: 'Access token (shown once)', + tokenNote: 'Copy it now: it is not stored and cannot be shown again.', + copy: 'Copy', + copied: 'Copied.', + copyManual: 'Select the text and copy it.', + renameLabel: 'New username', + rename: 'Rename', + renamed: 'Renamed to {name}.', + tokens: 'Machine tokens', + tokensNone: 'No tokens.', + tokenName: 'Label', + tokenAdd: 'Create token', + tokenRevoke: 'Revoke', + tokenRevoked: 'Revoked', + tokenRevokedMsg: 'Token revoked.', + tokenMeta: 'Created {created}', + tokenUsed: 'last used {used}', + strava: 'Strava', + garmin: 'Garmin', + connected: 'Connected', + notConnected: 'Not connected', + garminUntil: 'Key valid until {date}', + remove: 'Remove', + removed: 'Removed.', + stravaId: 'Client id', + stravaGet: 'Get the authorisation link', + stravaOpen: 'Open it signed in to their Strava, authorise, then paste the code or the whole address you land on.', + stravaLink: 'Open Strava', + stravaSecret: 'Client secret', + stravaCode: 'Code or redirected address', + stravaConnect: 'Connect', + stravaDone: 'Strava connected.', + garminKey: 'API key', + garminExpires: 'Valid until (optional)', + garminSave: 'Save', + garminDone: 'Garmin saved.', + deleteHead: 'Delete {name}', + deleteHint: 'Deletes all their data. It cannot be undone. Type the username to confirm.', + deleteLabel: 'Username', + delete: 'Delete', + deleted: '{name} deleted.', + manual: 'Remove these folders by hand: {list}', + errors: { + bad_request: 'The request was not valid.', + invalid_username: 'That username is not valid.', + username_taken: 'That username is already taken.', + not_found: 'That person or item no longer exists.', + invalid_label: 'The label is not valid.', + invalid_client_id: 'The Strava client id is not valid.', + invalid_client_secret: 'The Strava client secret is not valid.', + invalid_api_key: 'The API key is not valid.', + invalid_expires: 'The date is not valid.', + no_code: 'Paste the code or the whole address you landed on.', + strava_refused: 'Strava refused the connection. Check the id, the secret and the code.', + strava_no_refresh_token: 'Strava did not give a refresh token. Authorise again.', + strava_unreachable: 'Strava did not answer. Try again in a moment.', + confirmation_mismatch: 'The username does not match.', + owner_never_deleted: 'The first account is never deleted.', + cannot_delete_self: 'You cannot delete yourself.', + not_shared: 'This person does not share their page.', + forbidden: 'Only an admin can do this.', + login_required: 'Sign in with a password first: this server has no login yet.', + unauthenticated: 'Your session ended. Sign in again.', + read_only: 'Read-only: you are viewing another page.', + rate_limited: 'Too many requests. Try again in a minute.', + offline: 'The server did not answer. Check your connection and try again.', + generic: 'That did not work. Try again in a moment.', + }, }, open: 'Open profile', // the initials button's name starts with what it shows (WCAG 2.5.3 Label in Name) @@ -133,6 +232,103 @@ export const es = { signOut: 'Cerrar sesión', signingOut: 'Cerrando sesión…', failed: 'No se pudo cerrar la sesión. Inténtalo de nuevo.', + share: 'Compartir con mi entrenador', + shareHint: 'Permite que el administrador vea tu página, solo en lectura. Puedes desactivarlo cuando quieras.', + people: 'Personas', + peopleOpen: 'Gestionar', + }, + people: { + title: 'Personas', + denied: 'Solo un administrador puede gestionar personas.', + loading: 'Cargando…', + retry: 'Reintentar', + working: 'Un momento…', + list: 'Todas las cuentas', + none: 'Todavía no hay nadie.', + badges: { owner: 'Titular', you: 'Tú', admin: 'Admin', noPassword: 'Sin contraseña', shares: 'Comparte' }, + manage: 'Gestionar', + manageOf: 'Gestionar a {name}', + close: 'Cerrar', + closeOf: 'Cerrar {name}', + addName: 'Nombre de usuario', + providers: 'Strava y Garmin', + addLabel: 'Añadir una persona', + addHint: 'Letras, cifras, puntos, guiones y guiones bajos. Recibirá un enlace para elegir su propia contraseña.', + add: 'Añadir', + added: '{name} añadido. Crea un enlace de contraseña para esa persona.', + view: 'Ver su página', + viewHint: 'Solo lectura. Solo mientras comparta con su entrenador.', + link: 'Enlace de contraseña', + linkLabel: 'Enlace de contraseña: envíaselo a {name} (se muestra una vez)', + linkNote: 'Válido hasta el {date}. Un enlace nuevo anula este. Al abrirlo, la persona elige su propia contraseña.', + tokenLabel: 'Token de acceso (se muestra una vez)', + tokenNote: 'Cópialo ahora: no se guarda y no se puede volver a mostrar.', + copy: 'Copiar', + copied: 'Copiado.', + copyManual: 'Selecciona el texto y cópialo.', + renameLabel: 'Usuario nuevo', + rename: 'Renombrar', + renamed: 'Ahora se llama {name}.', + tokens: 'Tokens de máquina', + tokensNone: 'Sin tokens.', + tokenName: 'Etiqueta', + tokenAdd: 'Crear token', + tokenRevoke: 'Revocar', + tokenRevoked: 'Revocado', + tokenRevokedMsg: 'Token revocado.', + tokenMeta: 'Creado el {created}', + tokenUsed: 'último uso el {used}', + strava: 'Strava', + garmin: 'Garmin', + connected: 'Conectado', + notConnected: 'Sin conectar', + garminUntil: 'Clave válida hasta el {date}', + remove: 'Quitar', + removed: 'Quitado.', + stravaId: 'Client id', + stravaGet: 'Obtener el enlace de autorización', + stravaOpen: 'Ábrelo con la sesión de su Strava, autoriza y pega el código o la dirección completa a la que llegues.', + stravaLink: 'Abrir Strava', + stravaSecret: 'Client secret', + stravaCode: 'Código o dirección de redirección', + stravaConnect: 'Conectar', + stravaDone: 'Strava conectado.', + garminKey: 'Clave de API', + garminExpires: 'Válida hasta (opcional)', + garminSave: 'Guardar', + garminDone: 'Garmin guardado.', + deleteHead: 'Eliminar a {name}', + deleteHint: 'Elimina todos sus datos. No se puede deshacer. Escribe el usuario para confirmar.', + deleteLabel: 'Usuario', + delete: 'Eliminar', + deleted: '{name} eliminado.', + manual: 'Quita estas carpetas a mano: {list}', + errors: { + bad_request: 'La petición no era válida.', + invalid_username: 'Ese usuario no es válido.', + username_taken: 'Ese usuario ya existe.', + not_found: 'Esa persona o elemento ya no existe.', + invalid_label: 'La etiqueta no es válida.', + invalid_client_id: 'El client id de Strava no es válido.', + invalid_client_secret: 'El client secret de Strava no es válido.', + invalid_api_key: 'La clave de API no es válida.', + invalid_expires: 'La fecha no es válida.', + no_code: 'Pega el código o la dirección completa a la que llegaste.', + strava_refused: 'Strava rechazó la conexión. Revisa el id, el secret y el código.', + strava_no_refresh_token: 'Strava no devolvió un token de renovación. Autoriza de nuevo.', + strava_unreachable: 'Strava no responde. Inténtalo de nuevo en un momento.', + confirmation_mismatch: 'El usuario no coincide.', + owner_never_deleted: 'La primera cuenta nunca se elimina.', + cannot_delete_self: 'No puedes eliminarte a ti mismo.', + not_shared: 'Esta persona no comparte su página.', + forbidden: 'Solo un administrador puede hacerlo.', + login_required: 'Primero hay que iniciar sesión con contraseña: este servidor todavía no tiene inicio de sesión.', + unauthenticated: 'Tu sesión ha terminado. Inicia sesión de nuevo.', + read_only: 'Solo lectura: estás viendo otra página.', + rate_limited: 'Demasiadas peticiones. Inténtalo de nuevo en un minuto.', + offline: 'El servidor no responde. Revisa tu conexión y vuelve a probar.', + generic: 'No ha funcionado. Inténtalo de nuevo en un momento.', + }, }, open: 'Abrir perfil', openIni: '{initials}, abrir perfil', diff --git a/web/src/i18n/signin-templates.mjs b/web/src/i18n/signin-templates.mjs index ef2f1146..3d9334f3 100644 --- a/web/src/i18n/signin-templates.mjs +++ b/web/src/i18n/signin-templates.mjs @@ -17,6 +17,30 @@ export const en = { offline: 'The server did not answer. Check your connection and try again.', generic: 'Could not sign in. Try again in a moment.', }, + setPassword: { + title: 'Choose your password', + intro: 'Choose the password you will sign in with. It needs 12 to 256 characters.', + password: 'New password', + repeat: 'Repeat the password', + submit: 'Set password', + busy: 'Saving…', + done: 'Password set. Sign in.', + errors: { + length: 'The password needs 12 to 256 characters.', + mismatch: 'The two passwords are not the same.', + invalid_password: 'The password needs 12 to 256 characters.', + invalid_link: 'This link is no longer valid. Ask for a new one.', + rate_limited: 'Too many attempts. Wait a few minutes and try again.', + offline: 'The server did not answer. Check your connection and try again.', + generic: 'Could not set the password. Try again in a moment.', + }, + }, + coach: { + viewing: 'Viewing {name} · read-only', + back: 'Back to my page', + backFailed: 'Could not go back. Try again.', + readOnly: "Read-only: you are viewing {name}'s page.", + }, }; export const es = { @@ -35,4 +59,28 @@ export const es = { offline: 'El servidor no responde. Revisa tu conexión y vuelve a probar.', generic: 'No se pudo iniciar sesión. Inténtalo de nuevo en un momento.', }, + setPassword: { + title: 'Elige tu contraseña', + intro: 'Elige la contraseña con la que vas a entrar. Necesita entre 12 y 256 caracteres.', + password: 'Contraseña nueva', + repeat: 'Repite la contraseña', + submit: 'Guardar contraseña', + busy: 'Guardando…', + done: 'Contraseña guardada. Inicia sesión.', + errors: { + length: 'La contraseña necesita entre 12 y 256 caracteres.', + mismatch: 'Las dos contraseñas no coinciden.', + invalid_password: 'La contraseña necesita entre 12 y 256 caracteres.', + invalid_link: 'Este enlace ya no es válido. Pide uno nuevo.', + rate_limited: 'Demasiados intentos. Espera unos minutos y vuelve a probar.', + offline: 'El servidor no responde. Revisa tu conexión y vuelve a probar.', + generic: 'No se pudo guardar la contraseña. Inténtalo de nuevo en un momento.', + }, + }, + coach: { + viewing: 'Viendo a {name} · solo lectura', + back: 'Volver a mi página', + backFailed: 'No se pudo volver. Inténtalo de nuevo.', + readOnly: 'Solo lectura: estás viendo la página de {name}.', + }, }; diff --git a/web/src/styles/profile.css b/web/src/styles/profile.css index fa410d3d..add7f7c9 100644 --- a/web/src/styles/profile.css +++ b/web/src/styles/profile.css @@ -635,3 +635,55 @@ letter-spacing: var(--label-track); text-transform: uppercase; } + +/* Coach view (client/signin.ts, docs/plan-page.md): while an admin views a person's page (read-only) a banner stays at the + top of the page, the first thing in the body (in flow, so it covers nothing at rest; sticky, so it stays while scrolling), + its safe-area padding keeping it clear of the notch. It sits under the detail sheets (z 59 < 60), which cover the whole + screen. A refused write (403 read_only) shows its notice in the same bar. The mini dial slides in below it. */ +.coach-bar { + position: sticky; + top: 0; + z-index: 59; + display: flex; + align-items: center; + justify-content: space-between; + padding: env(safe-area-inset-top) var(--sp-5) 0; + background: var(--card-bg); + box-shadow: 0 2px var(--accent); +} +.coach-on .dial-mini { + top: calc(44px + env(safe-area-inset-top)); +} + +/* People (client/profile.ts, the admin's sheet): the open person's panel sits under their row as an inset card; what is + not an everyday action (rename, tokens, Strava and Garmin, delete) waits in folds. */ +.pp-slot:empty, +.pp-slot > :empty { + display: none; +} +.pp-on .pf-item-name { + color: var(--accent); +} +.pp-panel { + margin: var(--sp-2) 0 var(--sp-5); + padding: var(--sp-5); + border-radius: var(--card-radius); + background: var(--ground); +} +.pp-panel form, +.pp-panel .pf-note { + margin-top: var(--sp-4); +} +.pp-fold { + border-top: 1px solid var(--line-soft); +} +.pp-fold summary { + color: inherit; + font-weight: 600; +} +.pp-fold[open] { + padding-bottom: var(--sp-5); +} +.pp-danger summary { + color: var(--mid); +} diff --git a/web/test/css-slim.test.mjs b/web/test/css-slim.test.mjs index 4e2df2f0..42d57dc8 100644 --- a/web/test/css-slim.test.mjs +++ b/web/test/css-slim.test.mjs @@ -23,7 +23,7 @@ const DIST = path.join(path.dirname(here), '.test-dist'); // Re-measured 2026-10-15 (page quality pass): 109.9 KB before, 108.9 KB after deleting ~1.4 KB of dead rules // (.mac*, .meal-desc, .day-panel[hidden], .dash-sec*, .sc-sub, .sc-comp*, .sc-gated, .dial-foot) and adding // the 44 px hit bands (.chip::before, .day-lbl::before); budget lowered to keep a ~1 KB margin. -const CSS_BUDGET = 112_000; // 110_000 until 2026-11-30 (the sign-in screen's own look, owner-approved); 111_000 until 2026-10-15; 108_000 until 2026-10-14 (onboarding visual pass, owner-approved) +const CSS_BUDGET = 113_000; // 112_000 until 2026-12-01 (the coach view's banner, owner-approved); 110_000 until 2026-11-30 (the sign-in screen's own look, owner-approved); 111_000 until 2026-10-15; 108_000 until 2026-10-14 (onboarding visual pass, owner-approved) const FONT_FACE = /@font-face\{[^}]*\}/g; /** @param {string} html */ diff --git a/web/test/fixtures/css-expected.json b/web/test/fixtures/css-expected.json index 16803790..14892f84 100644 --- a/web/test/fixtures/css-expected.json +++ b/web/test/fixtures/css-expected.json @@ -2437,11 +2437,7 @@ "|||.pf-ev-left|||font-size": "var(--fs-sm)", "|||.pf-ev-left|||font-weight": "var(--label-weight)", "|||.pf-ev-left|||text-align": "right", - "|||.pf-foot|||color": "var(--faint)", - "|||.pf-foot|||font-size": "var(--fs-xs)", "|||.pf-goal legend|||padding": "0", - "|||.pf-goal-desc|||color": "var(--muted)", - "|||.pf-goal-desc|||font-size": "var(--fs-sm)", "|||.pf-goal-name|||font-weight": "600", "|||.pf-goal-opt input|||accent-color": "var(--accent)", "|||.pf-goal-opt input|||flex": "none", @@ -2491,12 +2487,7 @@ "|||.pf-item|||justify-content": "space-between", "|||.pf-item|||min-height": "44px", "|||.pf-item|||padding": "var(--sp-3) 0", - "|||.pf-km|||font-size": "var(--fs-2xl)", "|||.pf-list .pf-item:first-child|||border-top": "0", - "|||.pf-list|||list-style": "none", - "|||.pf-manual:focus-visible|||outline": "2px solid var(--accent)", - "|||.pf-manual:focus-visible|||outline-offset": "2px", - "|||.pf-manual[hidden]|||display": "none", "|||.pf-manual|||align-items": "center", "|||.pf-manual|||border": "1px solid var(--line)", "|||.pf-manual|||border-radius": "var(--r-pill)", @@ -2519,10 +2510,6 @@ "|||.pf-name|||font-weight": "700", "|||.pf-name|||line-height": "1.2", "|||.pf-name|||overflow-wrap": "anywhere", - "|||.pf-note|||color": "var(--muted)", - "|||.pf-note|||font-size": "var(--fs-sm)", - "|||.pf-num small|||color": "var(--muted)", - "|||.pf-num small|||font-size": "var(--fs-sm)", "|||.pf-num|||align-items": "baseline", "|||.pf-num|||display": "inline-flex", "|||.pf-num|||gap": "var(--sp-1)", @@ -2532,23 +2519,18 @@ "|||.pf-photo|||object-fit": "cover", "|||.pf-photo|||width": "100%", "|||.pf-progress .pf-lbl|||margin-right": "var(--sp-2)", - "|||.pf-retired .pf-item-name, .pf-retired .pf-km|||color": "var(--muted)", - "|||.pf-retired summary:focus-visible|||outline": "2px solid var(--accent)", - "|||.pf-retired summary:focus-visible|||outline-offset": "2px", "|||.pf-retired summary|||align-items": "center", "|||.pf-retired summary|||color": "var(--muted)", "|||.pf-retired summary|||cursor": "pointer", "|||.pf-retired summary|||display": "flex", "|||.pf-retired summary|||font-size": "var(--fs-sm)", "|||.pf-retired summary|||min-height": "44px", - "|||.pf-retired|||margin-top": "var(--sp-3)", "|||.pf-row-val|||font-size": "var(--fs-lg)", "|||.pf-row|||align-items": "baseline", "|||.pf-row|||display": "flex", "|||.pf-row|||gap": "var(--sp-5)", "|||.pf-row|||justify-content": "space-between", "|||.pf-row|||min-height": "32px", - "|||.pf-sec .pf-note|||margin-top": "var(--sp-3)", "|||.pf-sec|||background": "var(--card-bg)", "|||.pf-sec|||border-radius": "var(--card-radius)", "|||.pf-sec|||padding": "var(--sp-7)", @@ -2558,10 +2540,7 @@ "|||.pf-stats|||display": "grid", "|||.pf-stats|||gap": "var(--sp-6)", "|||.pf-stats|||grid-template-columns": "repeat(auto-fit, minmax(140px, 1fr))", - "|||.pf-status:empty|||display": "none", "|||.pf-sub-h|||margin": "var(--sp-6) 0 var(--sp-2)", - "|||.pf-sub, .pf-item-sub|||color": "var(--faint)", - "|||.pf-sub, .pf-item-sub|||font-size": "var(--fs-xs)", "|||.pf-target|||margin": "var(--sp-5) 0 0", "|||.pf-target|||max-width": "260px", "|||.pf-val, .pf-km|||color": "var(--ink)", @@ -4280,7 +4259,6 @@ "|||.onb .onb-big .food-in|||font-size": "var(--fs-hero)", "|||.onb .onb-big .food-in|||text-align": "center", "|||.onb .onb-big [type=date]|||font-size": "var(--fs-num-card)", - "|||.onb-top .lnk|||color": "var(--muted)", "|||.onb-steps|||margin": "var(--sp-6) 0", "(min-width:900px)|||.onb-nav|||position": "static", "(min-width:900px)|||.onb-nav|||background": "none", @@ -4359,7 +4337,6 @@ "|||.act-m-hybrid|||fill": "var(--strain)", "|||.act-m-hybrid|||background": "var(--strain)", "(min-width:900px)|||.signin-sheet|||padding": "0", - "(min-width:900px)|||.signin-sheet .signin-panel|||min-height": "100%", "(min-width:900px)|||.signin-sheet .signin-panel|||padding": "var(--sp-12) var(--sp-10)", "|||.signin-sheet|||background": "var(--ground)", "|||.signin-sheet .signin-panel|||display": "flex", @@ -4431,5 +4408,50 @@ "|||.signin-eye|||font-size": "var(--fs-label)", "|||.signin-eye|||font-weight": "var(--label-weight)", "|||.signin-eye|||letter-spacing": "var(--label-track)", - "|||.signin-eye|||text-transform": "uppercase" + "|||.signin-eye|||text-transform": "uppercase", + "|||.coach-bar|||position": "sticky", + "|||.coach-bar|||top": "0", + "|||.coach-bar|||z-index": "59", + "|||.coach-bar|||display": "flex", + "|||.coach-bar|||align-items": "center", + "|||.coach-bar|||justify-content": "space-between", + "|||.coach-bar|||padding": "env(safe-area-inset-top) var(--sp-5) 0", + "|||.coach-bar|||background": "var(--card-bg)", + "|||.coach-bar|||box-shadow": "0 2px var(--accent)", + "|||.coach-on .dial-mini|||top": "calc(44px + env(safe-area-inset-top))", + "(min-width:900px)|||.signin-sheet .signin-panel|||min-height": "100%", + "|||.pf-goal-desc|||font-size": "var(--fs-sm)", + "|||.pf-goal-desc|||color": "var(--muted)", + "|||.pf-num small|||color": "var(--muted)", + "|||.pf-num small|||font-size": "var(--fs-sm)", + "|||.pf-km|||font-size": "var(--fs-2xl)", + "|||.pf-sub, .pf-item-sub|||color": "var(--faint)", + "|||.pf-sub, .pf-item-sub|||font-size": "var(--fs-xs)", + "|||.pf-list|||list-style": "none", + "|||.pf-manual[hidden]|||display": "none", + "|||.pf-manual:focus-visible|||outline": "2px solid var(--accent)", + "|||.pf-manual:focus-visible|||outline-offset": "2px", + "|||.pf-retired|||margin-top": "var(--sp-3)", + "|||.pf-retired summary:focus-visible|||outline": "2px solid var(--accent)", + "|||.pf-retired summary:focus-visible|||outline-offset": "2px", + "|||.pf-retired .pf-item-name, .pf-retired .pf-km|||color": "var(--muted)", + "|||.pf-note|||color": "var(--muted)", + "|||.pf-note|||font-size": "var(--fs-sm)", + "|||.pf-sec .pf-note|||margin-top": "var(--sp-3)", + "|||.pf-foot|||font-size": "var(--fs-xs)", + "|||.pf-foot|||color": "var(--faint)", + "|||.pf-status:empty|||display": "none", + "|||.onb-top .lnk|||color": "var(--muted)", + "|||.pp-slot:empty, .pp-slot>:empty|||display": "none", + "|||.pp-on .pf-item-name|||color": "var(--accent)", + "|||.pp-panel|||margin": "var(--sp-2) 0 var(--sp-5)", + "|||.pp-panel|||padding": "var(--sp-5)", + "|||.pp-panel|||border-radius": "var(--card-radius)", + "|||.pp-panel|||background": "var(--ground)", + "|||.pp-panel form, .pp-panel .pf-note|||margin-top": "var(--sp-4)", + "|||.pp-fold|||border-top": "1px solid var(--line-soft)", + "|||.pp-fold summary|||color": "inherit", + "|||.pp-fold summary|||font-weight": "600", + "|||.pp-fold[open]|||padding-bottom": "var(--sp-5)", + "|||.pp-danger summary|||color": "var(--mid)" }