No description
  • Rust 39.8%
  • JavaScript 34%
  • Python 16.7%
  • CSS 6.9%
  • HTML 2.1%
  • Other 0.5%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Brian c90fbfb6dd
All checks were successful
Build and Deploy / build-frontend (push) Successful in 19s
Build and Deploy / test-backend (push) Successful in 30s
Build and Deploy / build-borg-agent (push) Successful in 2m31s
Build and Deploy / build-backend (push) Successful in 2m57s
Build and Deploy / deploy (push) Successful in 5s
Add llama.cpp (OpenAI-compatible) as a label-scanning provider
Admins can pick llama.cpp's llama-server, or any OpenAI-compatible server,
alongside Anthropic and Ollama for reading bottle labels. New settings
llamacpp_url/model/api_key, admin test + model-list routes, and the
admin card swaps in the llama.cpp fields when it is chosen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Eq42w9L32PoGRegkCVdoBy
2026-11-11 15:30:22 -07:00
.claude MedSync server: API, web app and Borg agent 2026-10-03 00:34:34 -06:00
.forgejo/workflows MedSync server: API, web app and Borg agent 2026-10-03 00:34:34 -06:00
agent MedSync server: API, web app and Borg agent 2026-10-03 00:34:34 -06:00
frontend Add llama.cpp (OpenAI-compatible) as a label-scanning provider 2026-11-11 15:30:22 -07:00
server Add llama.cpp (OpenAI-compatible) as a label-scanning provider 2026-11-11 15:30:22 -07:00
tests Chart patches across the time they're worn 2026-10-27 08:54:00 -06:00
.dockerignore MedSync server: API, web app and Borg agent 2026-10-03 00:34:34 -06:00
.env.example Harden accounts for a public server 2026-10-05 17:32:35 -06:00
.gitignore MedSync server: API, web app and Borg agent 2026-10-03 00:34:34 -06:00
build.sh MedSync server: API, web app and Borg agent 2026-10-03 00:34:34 -06:00
Cargo.lock Email, password reset, per-user timezones and managed profiles 2026-10-05 23:36:49 -06:00
Cargo.toml License the server under AGPL-3.0-or-later 2026-10-05 23:08:44 -06:00
docker-compose.portainer.yml MedSync server: API, web app and Borg agent 2026-10-03 00:34:34 -06:00
docker-compose.yml MedSync server: API, web app and Borg agent 2026-10-03 00:34:34 -06:00
Dockerfile.backend MedSync server: API, web app and Borg agent 2026-10-03 00:34:34 -06:00
Dockerfile.borg-agent MedSync server: API, web app and Borg agent 2026-10-03 00:34:34 -06:00
LICENSE License the server under AGPL-3.0-or-later 2026-10-05 23:08:44 -06:00
README.md Add llama.cpp (OpenAI-compatible) as a label-scanning provider 2026-11-11 15:30:22 -07:00

MedSync Server

The server side of MedSync, a self-hosted medication tracker: the API, the web app (a PWA), and the Borg backup agent, deployed together as one Docker stack.

The Android app lives in its own repository, brian/medsync. It talks to this server's API and isn't part of the deploy here; API changes that affect it need a matching change there.

Stack

Part Tech Image
API Rust · axum · SQLite (rusqlite) medsync-backend (port 3001)
Web app React 18 · Vite · PWA, served by nginx medsync-frontend (port 80)
Borg agent Rust · borgbackup · Docker socket medsync-borg-agent (port 3010, internal)

Bottle-label scanning and the in-app assistant use Claude (or, for scanning, a local vision model on Ollama or llama.cpp's llama-server, or any other OpenAI-compatible server). Reminders go out as web push, ntfy and Twilio SMS.


Quick start

cp .env.example .env      # all optional; see the comments
docker compose up -d --build

Web app: http://localhost:3002 · API: http://localhost:3001/api/health

The first account created (by registration or OIDC sign-in) becomes the admin.

Configuration

Nothing has to come from the environment. Every setting — Anthropic key, VAPID keys, Twilio, ntfy, OIDC, Nextcloud, Borg, the display timezone — is editable on the Admin screen and stored in the database; the .env values (see .env.example) only seed a setting until an admin first saves it.

Variable Default
JWT_SECRET generated Signs session tokens. Left unset, a random secret is generated on first start and kept in the data volume as .jwt-secret; set it only to keep an existing one. Changing it signs everyone out. The old changeme-insecure-default is ignored.
DB_PATH /app/data/medsync.db
PILL_IMAGES_DIR /app/data/pill_images
FRONTEND_URL same origin Only if the web app is on another origin.
NTFY_PRIORITY default
MEDSYNC_LISTEN 0.0.0.0:3001
MEDSYNC_WORKER_THREADS 2
ANTHROPIC_BASE_URL Anthropic For a proxy or a test stub.

The Borg agent reads MEDSYNC_DATA_DIR (/data), BORG_HOME (/borg) and AGENT_LISTEN (0.0.0.0:3010). It shares an access token with the backend through the data volume (.borg-agent-token), so there is nothing to configure.


OIDC Single Sign-On (Authentik)

MedSync can tie accounts to an OIDC provider such as Authentik. When configured, the login page shows a Sign in with Authentik button and existing users can connect their identity from Settings → Connected accounts.

  1. In Authentik, create an OAuth2/OpenID confidential provider:
    • Redirect URI: https://<your-host>/api/auth/oidc/callback
    • Scopes: openid profile email
  2. Copy the client id/secret and the provider's issuer URL into .env (OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET, OIDC_REDIRECT_URI).
  3. Restart the backend, or enter the same values under Admin → Login. The feature auto-enables once these are set.

Account linking behaviour:

  • A first OIDC login auto-links to an existing account when the email claim matches that account's confirmed email address. Matching by preferred_username happens only when registration is invite-only or closed; on an open server, a stranger could register the name first and receive the link.
  • Otherwise a new account is provisioned from the OIDC claims (no local password).
  • Logged-in users can explicitly connect/disconnect from Settings.

Username/password login keeps working alongside SSO.


Admin & User Management

The first account created (whether by registration or OIDC sign-in) automatically becomes an admin. On an existing database with no admin, the earliest user is promoted on next startup.

Admins get an Admin tab, organised into sub-sections down the left-hand side. Each one is its own URL, so a link to a particular screen can be bookmarked and the back button works normally:

Sub-section /admin/… What lives there
General general Server timezone (each person can pick their own), Anthropic API key
Login login Who can register, invite codes, OIDC / single sign-on
Users users Create accounts, promote/demote, reset passwords, delete
Notifications notifications Email (SMTP), ntfy server, web push (VAPID), Twilio SMS
Backup backup Whole-instance archives to Nextcloud, and restore
Borg backup borg Deduplicated backups to a remote Borg server

The app refuses to demote or delete the last remaining admin. Admins delete their own account from Settings like anyone else, once someone else is an admin.

Registration

Admin → Login → Registration decides who can create an account:

Mode
Anyone can register The default.
Invite only Registering needs a single-use code from Invite codes on the same screen. Each code expires after 14 days; Copy link gives a /register?invite=… link that fills it in.
Closed Only an admin can add people (Users).

The very first account can always be created, whatever the mode. OIDC sign-in still creates accounts on an invite-only server (the identity provider decides who gets in), but not on a closed one.

Sessions and sign-in limits

Each sign-in is a session that lasts 90 days from its last use; the web app and the Android app renew it whenever they start. Settings → Signed-in devices lists them and can sign any of them out. Signing out ends the session on the server, and an admin resetting someone's password signs that person out everywhere. Tokens issued before sessions existed keep working for 30 days after the upgrade, so clients can swap them for one.

Ten wrong passwords for one account lock it for 15 minutes; one address gets 60 sign-in attempts per 15 minutes and 10 registrations per hour. These count per visitor only when the backend can see the visitor's address: the bundled nginx takes it from X-Forwarded-For as reported by a reverse proxy on a private network (10/8, 172.16/12, 192.168/16, loopback). Behind a proxy elsewhere, add it to set_real_ip_from in frontend/nginx.conf.

Email, passwords and timezones

With Admin → Notifications → Email set up (any SMTP server; Send test email mails the address on your own account), MedSync can:

  • confirm addresses. People add an email when they register or in Settings, and get a link to confirm it. Only a confirmed address can receive a password reset or be matched by SSO sign-in. Admin → Login → Registration can require an address to register.
  • reset forgotten passwords. Forgot password? on the sign-in page emails a one-hour link to the account's confirmed address. It answers the same way whether or not the account exists. Resetting signs the account out everywhere.

Public URL on the same card is the address the links point to; left blank, it is worked out from each request (or FRONTEND_URL).

Anyone can change their password in Settings → Password; their other devices are signed out. Someone who only ever signed in through SSO can set a first password there.

Each person picks their own timezone in Settings (a new account starts with the device's). Without one, the server's applies. A day ("today", a backdated time typed without an offset) is the medication owner's day.

Deleting an account

Settings → Account → Delete account removes the account with every medication, dose, photo, group, API key and caretaker link. A password account confirms with its password; one created by SSO sign-in without a password confirms by typing its username.

Every setting on these screens is stored in the database, not the environment. The .env values only seed the initial value of a setting that has never been edited — once an admin saves one, the database wins and the env var is ignored.

Caretakers

A caretaker sees and logs another person's medications. Either side can ask, from Settings → Caretaker: invite someone by username, saying whether you will look after them or they will look after you. Nothing is shared until the other person accepts, and either of you can end the link at any time. (Links made before invites existed are kept.)

Pill photos follow the same rule: they are served only to the medication's owner and their caretakers, never to someone who merely has the link.

For someone who won't sign in themselves (a child, a parent without a phone), add a profile instead: Settings → Caretaker → Add someone without an account. A profile has no login. Its owner keeps its medications, and its reminders go to the owner's ntfy, SMS and push, titled with the person's name. Deleting the profile, or the owner's account, deletes everything recorded for it.


Backup & Restore

Two independent levels, both reachable from the UI and both able to write either to your browser's Downloads folder or to a Nextcloud server over WebDAV — plus a third, admin-only destination: a remote Borg repository over SSH.

Full system backup (Admin tab)

A single .zip holding a consistent snapshot of the SQLite database plus every uploaded pill photo — all accounts, medications, dose history and stored settings.

  • Download archive — streams the archive straight to the browser.
  • Back up to Nextcloud — uploads it to the configured destination.
  • Automatic backups — an optional nightly run at a chosen hour (in the instance's display timezone), keeping the newest N archives and deleting the rest.
  • Restore — from an archive listed on Nextcloud, or from a file you upload.

The database snapshot is taken with SQLite's online-backup API, not a file copy, so it is consistent even though the app runs in WAL mode and is serving requests at the time.

⚠️ A full archive contains password hashes, API-key hashes and every stored integration credential (Anthropic key, VAPID private key, Twilio token, OIDC secret). Treat it as sensitive.

⚠️ Restoring replaces everything — every account and dose logged since that backup is lost. The database being replaced is kept on the server next to the live one as medsync.db.pre-restore-<timestamp> (the newest three are retained), so a mistaken restore is still recoverable from the filesystem.

Borg backup (Admin → Borg backup)

Deduplicated, compressed, encrypted, incremental backups pushed to a remote Borg repository over SSH. Unlike the Nextcloud archive — a fresh full zip every night — only the chunks that actually changed cross the wire, so months of nightly history costs little more than a single archive.

This one runs in its own container, borg-agent, because it needs three things the backend should not have: the borg binary, an SSH private key, and the ability to stop MedSync itself.

browser ──▶ backend ──▶ borg-agent ──▶ ssh ──▶ your Borg server
                            │
                            ├── stops/starts medsync-backend (Docker socket)
                            ├── holds the SSH key (medsync-borg volume)
                            └── reads the database + photos (medsync-data volume)

Setting it up

  1. Generate an SSH key under SSH identity. The private half is created inside the agent container and never leaves it; copy the public key shown and add it to ~/.ssh/authorized_keys on your Borg server (or to your provider's key list — BorgBase, rsync.net and Hetzner Storage Box all work).
  2. Set the repository, e.g. ssh://borg@backup.example.com:22/./medsync. The scp-style borg@host:medsync also works, as does an absolute path if you mount a disk into the agent container.
  3. Generate a passphrase — or type your own — and write it down somewhere else. It is stored here so nightly backups can run unattended, but the archives cannot be read without it, and losing both the instance and the passphrase means losing the backups.
  4. Save settings, then Create repository (borg init --encryption repokey-blake2). This only works on an empty path; point at an existing repository and skip this step.
  5. Test connection to confirm SSH, the key and the passphrase all line up.

Host keys are trusted on first use by default and pinned thereafter. Scan host key pins one explicitly, which lets you switch Host key checking to strict.

Cold vs hot

Stop MedSync while the backup runs is on by default. The agent stops the listed containers, takes the archive, then starts them again in reverse order — nothing can be mid-write while the data is read, at the cost of the app being unavailable for as long as the archive takes (seconds, after the first run has seeded the repository).

Turn it off and the app stays up: the database is still captured consistently through SQLite's online-backup API, but a pill photo uploaded during the run may miss the archive.

A restore always stops MedSync, whatever this setting says — swapping the database out from under a running backend is not survivable.

Because a cold backup stops the very process the browser is talking to, the panel works a little differently from the rest of the app: starting a backup returns a job, the job id is remembered across a page reload, and a failed poll is treated as "still running" rather than an error. The outcome is written into the run log by the agent itself, so it survives the backend being restarted underneath it.

⚠️ The agent mounts /var/run/docker.sock, which is effectively root on the host. That is what lets it stop and start containers. If you'd rather not grant that, drop the socket mount from docker-compose.yml and turn the cold-backup toggle off — backups keep working, restores do not.

Retention

After each successful backup the agent applies borg prune with the keep daily / weekly / monthly counts from the panel, then borg compact to actually release the space. Setting one of the three to 0 keeps none of that kind. Pruning failures are reported but never fail a backup that has already been written.

Personal backup (Settings tab)

Each user can back up and restore their own data — every medication they've added with its ingredients and pill photo, their groups, and the complete record of what they took and when.

Format Contents Restorable
.zip Everything, including pill photos ✅
.json The same document without photos ✅
.csv Dose history only, for spreadsheets ➖

Restoring offers two modes:

  • Replace — clear the account's medications and history, then rebuild from the backup.
  • Merge — keep what's there and add only what's missing. Medications are matched by name and doses by medication + timestamp, so merging the same bundle twice is a no-op.

A user bundle carries no credentials and restores into the account doing the restoring, never as an account — so it can't be used to take over a login, and restoring someone else's exported file simply copies that data into your own account.

Caretakers can back up and restore for a patient they manage, using the same for_user_id access check as the rest of the app.

Configuring Nextcloud

Both levels use Nextcloud's WebDAV endpoint (/remote.php/dav/files/<user>/) with HTTP Basic auth. Create an app password under Settings → Security in Nextcloud rather than using your account password, so it can be revoked independently.

The instance-wide destination is set by an admin and is stored in the database (an admin-editable setting, like the ntfy server). Each user's personal destination lives on their own account and is entirely separate — a user's backups never touch the admin's credentials or folder, and vice versa. Both offer a Test connection button that verifies the credentials and creates the target folder.


Public API (for other apps)

MedSync exposes a small, scoped API so other apps and scripts can view your medications and log doses without your login credentials.

📖 Full reference: https://your-host/api/public/docs — a self-contained page covering every key-accessible endpoint, its parameters, response fields, and worked curl examples. It needs no login, so you can hand the URL to whoever is writing the integration. The summary below is just an orientation.

API keys

Generate a key by calling the management endpoints with a normal logged-in session (JWT). Keys are shown once at creation — store them securely.

# Create a key (returns the plaintext "key" exactly once)
curl -X POST https://your-host/api/auth/api-keys \
  -H "Authorization: Bearer <your-jwt>" \
  -H "Content-Type: application/json" \
  -d '{"name": "Home Assistant"}'
# → {"id": 1, "name": "Home Assistant", "key_prefix": "msk_AbC12345", "key": "msk_…"}

curl https://your-host/api/auth/api-keys   -H "Authorization: Bearer <your-jwt>"   # list
curl -X DELETE https://your-host/api/auth/api-keys/1 -H "Authorization: Bearer <your-jwt>"  # revoke

Only the SHA-256 hash of a key is stored; a lost key can only be replaced, not recovered. Managing keys requires a real login — an API key cannot mint or revoke keys.

Using a key

Pass the key as a bearer token, exactly like a JWT:

Authorization: Bearer msk_…

Scope — an API key can only view and log. It cannot delete medications, edit your profile, manage caretakers, or reach admin settings; those stay login-only. A key inherits the owner's caretaker access, so for_user_id works for patients they care for. Use GET /api/caretaker/patients to discover those patient ids — it lists who the key's owner cares for, but linking and unlinking patients remains login-only.

Capability Endpoint
List the patients you're a caretaker for (id, username, display_name) GET /api/caretaker/patients
List medications & supplements (with next_due / overdue) GET /api/medications
List groups and their members GET /api/groups
Dose history (rolling window, or start/end for a past range) GET /api/medications/history?days=7
Log a dose (now, or backdated via taken_at) POST /api/medications/{id}/log
Log every med in a group at once POST /api/groups/{id}/log

Supplements are simply medications with category: "supplement", so they appear in the same lists. When a medication is next due is returned as the next_due (ISO-8601) and overdue (boolean) fields on each medication; next_due is null for paused meds, as-needed (PRN) meds, and ones never taken.

overdue means "MedSync would chase you for this", not merely "past its time": it is false for an as_needed med (no schedule at all) and for one with reminders_enabled: 0 (muted on purpose, so it still reports a past next_due without ever alerting). Compare next_due to the clock yourself if you want raw lateness rather than MedSync's judgement.

# View what's due
curl https://your-host/api/medications -H "Authorization: Bearer msk_…"

# Log a dose taken two hours ago
curl -X POST https://your-host/api/medications/42/log \
  -H "Authorization: Bearer msk_…" -H "Content-Type: application/json" \
  -d '{"taken_at": "2026-07-14T10:00:00+00:00"}'

Repository layout

server/                medsync-backend
  src/routes/            one module per API area (auth, medications, groups, …)
  src/validate.rs        request validation and the 422 error format
  src/isotime.rs         timestamp parsing/formatting and timezone rules
  src/db.rs              schema, migrations, connection handling
  src/prompts/           label-scanning prompts
  src/routes/public_docs.html   the public API page (/api/public/docs)
agent/                 medsync-borg-agent
frontend/              the web app (Vite + React)
Dockerfile.backend     Dockerfile.borg-agent     frontend/Dockerfile
docker-compose.yml             build and run locally
docker-compose.portainer.yml   the production stack (deployed by CI)
tests/
  api/                 HTTP API suite (pytest) against a live server
  integrations/        Anthropic, Ollama, Nextcloud, ntfy, OIDC, web push and
                       the Borg agent, against stub.py
  e2e/                 a real Borg backup → change → restore

Development

No local Rust toolchain is needed: ./build.sh runs cargo in the official rust:1-bookworm image (registry cache in ~/.cache/medsync-cargo).

./build.sh test                 # unit tests (server and agent)
./build.sh build --release
tests/api/run.sh                # HTTP API suite; extra args go to pytest
tests/integrations/run.sh       # outside services, against stub.py
tests/e2e/run.sh                # Borg round trip (needs the Docker socket)

cd frontend && npm install && npm run dev   # proxies /api to localhost:3001

The HTTP suites build what they need and run in throwaway containers on a private network. npm install needs NPM_TOKEN for the git.thenymans.com npm registry (see frontend/.npmrc).

Data compatibility matters more than usual here: timestamps are stored and compared as text in one exact format, the schema's CREATE text is kept stable, and backup archives must restore across versions. src/isotime.rs, src/db.rs and src/backup.rs explain the rules.

Deployment

.forgejo/workflows/build-deploy.yaml runs on every push to main: cargo test, then builds and pushes the three images to git.thenymans.com/brian (with registry-backed build caches), then redeploys the Portainer stack medsync from docker-compose.portainer.yml, keeping the stack's environment variables. It uses the REGISTRY_USER, REGISTRY_PASSWORD and PORTAINER_TOKEN secrets.

Put a reverse proxy with HTTPS in front — camera access and push notifications need a secure context:

medsync.yourdomain.com {
    reverse_proxy localhost:3002
}

License

MedSync Server is free software under the GNU Affero General Public License v3.0 or later. You can self-host, change and share it; if you run a modified version as a service for other people, you must offer them its source under the same license.