5 Commits
Author SHA1 Message Date
Mateusz PstruchaandClaude Opus 5.5 08c2b1b286 Bump to 0.8.5
CI / test (push) Successful in 4m20s
Release / image (push) Successful in 3m26s
Release account editing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:55:22 +01:00
Mateusz PstruchaandClaude Opus 5.5 53d7e2a612 Ignore local Claude and tooling files
CI / test (push) Successful in 4m28s
CLAUDE.md, scripts/ and .claude/ are per-machine coordination and
tooling files; they stay untracked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:50:09 +01:00
mtps b93c50b8ac Merge pull request 'Release builds the image only, ygg/deployments deploys it' (#1) from claude/release-image-only into master
CI / test (push) Successful in 50s
2026-11-09 18:58:59 +01:00
Mateusz PstruchaandClaude Opus 5.5 30a8d52500 Release builds the image only, ygg/deployments deploys it
CI / test (pull_request) Successful in 4m13s
Production now runs from ygg/deployments, so a deploy from here would write
over it. Renovate opens a PR there for the new version, and merging it deploys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 16:37:24 +01:00
Mateusz PstruchaandClaude Opus 5.5 56e2c89999 Allow editing an account
CI / test (push) Failing after 3m23s
PUT /api/accounts/:id replaces an account's settings; the password is
kept unless a new one is given. Accounts now have an updated_at, and
the sync manager restarts a task whose account changed since it
started — the task holds its own copy of the settings. Its status is
reset to pending so the old error doesn't linger.

Mail already synced stays when it's still the same mailbox (new
password, renamed host); a genuinely different mailbox shows up as a
UIDVALIDITY change on connect and re-syncs, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 14:11:10 +02:00
13 changed files with 166 additions and 177 deletions

No files matched your search

+2 -22
View File
@@ -1,5 +1,7 @@
name: Release
# Builds and pushes the image. Production runs from ygg/deployments: Renovate
# opens a PR there for the new version, and merging it deploys.
on:
push:
tags: ['v*']
@@ -7,9 +9,6 @@ on:
jobs:
image:
runs-on: rocky-10
outputs:
version: ${{ steps.image.outputs.version }}
digest: ${{ steps.image.outputs.digest }}
steps:
- name: Check out source
uses: actions/checkout@v4
@@ -31,22 +30,3 @@ jobs:
DIGEST: ${{ steps.image.outputs.digest }}
run: |
printf 'tags: %s\ndigest: %s\n' "$TAGS" "$DIGEST"
# Deploys the image just pushed to tern-api.mtps.pl (deploy/compose on
# the app host; see deploy/README.md).
deploy:
needs: image
runs-on: rocky-10
steps:
- name: Check out source
uses: actions/checkout@v4
- name: Deploy
uses: https://git.app.ygg/ygg/actions/deploy@v2
with:
type: compose
dist-path: deploy/compose.yml
extra-vars: |
version=${{ needs.image.outputs.version }}
ssh-key: ${{ secrets.DEPLOY_SSH_KEY }}
known-hosts: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
+5
View File
@@ -3,3 +3,8 @@
/data
*.log
.DS_Store
# Local coordination and tooling files, kept out of the repo
/CLAUDE.md
/scripts/
/.claude/
Generated
+1 -1
View File
@@ -3047,7 +3047,7 @@ dependencies = [
[[package]]
name = "tern-server"
version = "0.8.4"
version = "0.8.5"
dependencies = [
"aes-gcm",
"anyhow",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tern-server"
version = "0.8.4"
version = "0.8.5"
edition = "2021"
description = "Tern sync server — the only component that speaks IMAP/SMTP"
+1 -1
View File
@@ -97,7 +97,7 @@ Only the first user can sign up, which is how a new server gets its owner. After
## Deployment
[`deploy/`](deploy/README.md) holds the production deployment to tern-api.mtps.pl: the server and its Postgres as one compose project, deployed by this repo's release workflow through the shared `ygg/actions/deploy` action. The webapp deploys separately, from tern-web. The image's `HEALTHCHECK` runs `tern-server healthcheck`, so `docker compose up --wait` only succeeds once the server answers `/healthz`.
A `v*` tag builds the image and pushes it to the registry. Production, tern-api.mtps.pl, is defined in [`ygg/deployments`](https://git.app.ygg/ygg/deployments/src/branch/main/deployments/tern-server.yml), secrets included: Renovate opens a PR there for the new version, and merging it deploys. The webapp is released separately, from tern-web. Back up `CREDENTIAL_KEY` outside the deployments repository: without it, the stored IMAP/SMTP passwords and the VAPID key can't be decrypted. The image's `HEALTHCHECK` runs `tern-server healthcheck`, so `docker compose up --wait` only succeeds once the server answers `/healthz`.
## Sessions
-62
View File
@@ -1,62 +0,0 @@
# Deployment
[`compose.yml`](compose.yml) deploys tern-server to **tern-api.mtps.pl**. It's one compose project with two services:
- `db`: `postgres:16-alpine`, with its data in the `db-data` volume.
- `server`: `git.app.ygg/mtps/tern-server:<version>`, with mail and attachments in the `blob-data` volume.
The server publishes port **11901** on the app host. The existing nginx proxies the domain to it, using the management repo's `site` role, with `websocket.conf` included so live updates (`/api/ws`) pass through. The server mounts the host's CA bundle, so mail and push servers behind the internal CA are trusted.
The webapp deploys separately, from tern-web's own release, to tern.mtps.pl. It calls this API cross-origin. That works because clients authenticate with a bearer token rather than a cookie, and the server allows cross-origin requests.
## How a release deploys
tern-server's release workflow has two jobs:
1. **`image`** builds and pushes `tern-server:<version>` and `:latest` with [`ygg/actions/push-image`](https://git.app.ygg/ygg/actions/src/branch/main/push-image).
2. **`deploy`** sends this file inline through [`ygg/actions/deploy`](https://git.app.ygg/ygg/actions/src/branch/main/deploy) (`type: compose`), with `version=<version>`.
On the app host, `docker compose up --wait` replaces the containers. The deploy only succeeds once every service is healthy. The image's `HEALTHCHECK` runs `tern-server healthcheck`, which passes once the server answers `/healthz`, after migrations have run. So a server that can't start fails the workflow instead of leaving the API down.
## One-time setup
1. **Secrets on kara:** `/opt/ygg/secrets/env/tern-server.env`. It's copied next to the compose file as `.env`.
```ini
POSTGRES_PASSWORD=<openssl rand -hex 24>
CREDENTIAL_KEY=<openssl rand -hex 32>
# optional: PUSH_URL_REWRITE, PUSH_TLS_INSECURE, PUSH_VAPID_SUBJECT,
# SESSION_TTL_HOURS, TRASH_RETENTION_DAYS, OPEN_REGISTRATION, RUST_LOG
```
- `CREDENTIAL_KEY` is 32 bytes, as 64 hex digits or base64.
- The database password can contain any characters, because it reaches the server as `PGPASSWORD`, not inside a URL.
- Back up `CREDENTIAL_KEY` somewhere other than kara. Without it, the stored IMAP/SMTP passwords and the VAPID key can't be decrypted.
2. **Secrets on the `mtps/tern-server` repository:** `DEPLOY_SSH_KEY` and `DEPLOY_KNOWN_HOSTS`. The `ygg` org's secrets don't reach `mtps` repositories.
3. **PyYAML on the runner** (`dnf install python3-pyyaml`). The deploy action converts this YAML file to JSON before sending it.
4. **Create your user.** Only the first user can register unless `OPEN_REGISTRATION=true` is set. Sign up once in the Android app (*Create a new user on this server*), or with:
```bash
curl -X POST https://tern-api.mtps.pl/api/auth/register \
-H 'Content-Type: application/json' -d '{"username":"…","password":"…"}'
```
## By hand
The same deploy, run directly on kara with this file copied to the dist directory:
```bash
/opt/ygg/play.sh deploy/compose -e @/opt/ygg/dist/compose/tern-server.yml -e version=0.9.0
```
To take it down, add `-e compose_state=destroy`. That stops the project and removes the nginx site, but keeps the `db-data` and `blob-data` volumes.
## Escaping in `compose.yml`
The file is processed twice, so some characters need care:
- **Ansible** templates `{{ … }}`. That's how `{{ version }}` gets filled in. Wrap anything else that looks like Jinja in `{% raw %}`.
- **Docker compose** interpolates `$`. That's how `${POSTGRES_PASSWORD}` comes from `.env`. Write a literal `$` as `$$`.
-68
View File
@@ -1,68 +0,0 @@
# tern-server's deployment: the server and its Postgres as one compose
# project on the app host (deploy/compose in the ygg management repo), run
# by this repo's release workflow through ygg/actions/deploy. See
# deploy/README.md.
#
# `version` arrives as an extra var (the release tag without its v) and is
# templated in by Ansible. Secrets come from
# /opt/ygg/secrets/env/tern-server.env on kara, copied next to compose.yml
# as .env — never put them in here: this file is sent on the command line.
compose_project: tern-server
# The existing nginx proxies the domain to site_port on the app host; the
# include passes WebSocket upgrades through for live updates (/api/ws).
domain: tern-api.mtps.pl
cert: mtps.pl
site_port: 11901
site_includes: websocket.conf
compose:
services:
db:
image: postgres:16-alpine
restart: unless-stopped
environment:
POSTGRES_USER: tern
POSTGRES_DB: tern
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in tern-server.env}
volumes:
- db-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U tern -d tern"]
interval: 5s
timeout: 5s
retries: 20
server:
image: "git.app.ygg/mtps/tern-server:{{ version }}"
restart: unless-stopped
depends_on:
db:
condition: service_healthy
environment:
# The password goes in separately (libpq's PGPASSWORD, which sqlx
# reads), so it never needs URL-escaping inside DATABASE_URL.
DATABASE_URL: postgres://tern@db:5432/tern
PGPASSWORD: ${POSTGRES_PASSWORD}
BIND_ADDR: 0.0.0.0:8080
CREDENTIAL_KEY: ${CREDENTIAL_KEY:?set CREDENTIAL_KEY in tern-server.env}
BLOB_STORAGE_DIR: /data/blobs
SESSION_TTL_HOURS: ${SESSION_TTL_HOURS:-720}
TRASH_RETENTION_DAYS: ${TRASH_RETENTION_DAYS:-30}
OPEN_REGISTRATION: ${OPEN_REGISTRATION:-false}
PUSH_URL_REWRITE: ${PUSH_URL_REWRITE:-}
PUSH_TLS_INSECURE: ${PUSH_TLS_INSECURE:-false}
PUSH_VAPID_SUBJECT: ${PUSH_VAPID_SUBJECT:-mailto:postmaster@mtps.pl}
RUST_LOG: ${RUST_LOG:-tern_server=info}
ports:
- "11901:8080"
volumes:
- blob-data:/data/blobs
# The host's trust store, so IMAP/SMTP and push servers behind the
# internal CA are trusted like public ones.
- /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem:/etc/ssl/certs/ca-certificates.crt:ro
volumes:
db-data: {}
blob-data: {}
+4
View File
@@ -0,0 +1,4 @@
-- When an account's settings last changed. The sync manager compares it
-- with the version its running task started from, and restarts the task
-- after an edit (new password, host, …) — the task holds its own copy.
ALTER TABLE accounts ADD COLUMN updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
+123 -7
View File
@@ -63,23 +63,42 @@ pub async fn list(
}
/// Catches what would otherwise only fail later, in the sync task's log.
fn validate(req: &CreateAccountRequest) -> ApiResult<()> {
fn validate_settings(
name: &str,
imap_host: &str,
imap_port: i32,
smtp_host: &str,
smtp_port: i32,
username: &str,
) -> ApiResult<()> {
let blank = |s: &str| s.trim().is_empty();
if blank(&req.name) || blank(&req.imap_host) || blank(&req.smtp_host) || blank(&req.username) {
if blank(name) || blank(imap_host) || blank(smtp_host) || blank(username) {
return Err(ApiError::BadRequest(
"name, IMAP server, SMTP server and login are all required".into(),
));
}
for (what, port) in [("IMAP", imap_port), ("SMTP", smtp_port)] {
if !(1..=65535).contains(&port) {
return Err(ApiError::BadRequest(format!("{what} port must be 1–65535")));
}
}
Ok(())
}
fn validate(req: &CreateAccountRequest) -> ApiResult<()> {
validate_settings(
&req.name,
&req.imap_host,
req.imap_port,
&req.smtp_host,
req.smtp_port,
&req.username,
)?;
if req.password.is_empty() {
return Err(ApiError::BadRequest(
"the mailbox password is required".into(),
));
}
for (what, port) in [("IMAP", req.imap_port), ("SMTP", req.smtp_port)] {
if !(1..=65535).contains(&port) {
return Err(ApiError::BadRequest(format!("{what} port must be 1–65535")));
}
}
Ok(())
}
@@ -127,6 +146,103 @@ pub async fn create(
Ok(Json(account.into()))
}
/// The account's settings, replaced as a whole — except the password,
/// which stays as it is unless a new one is given.
#[derive(Deserialize)]
pub struct UpdateAccountRequest {
pub name: String,
pub imap_host: String,
pub imap_port: i32,
pub smtp_host: String,
pub smtp_port: i32,
pub username: String,
/// Omitted or empty: keep the stored password.
pub password: Option<String>,
pub email_address: Option<String>,
pub display_name: Option<String>,
/// Defaults by port, as when creating.
pub smtp_use_starttls: Option<bool>,
}
/// Edits an account. Its sync task is restarted with the new settings.
/// Mail already synced stays when it's still the same mailbox (say, a new
/// password or a renamed host); pointing it at a different mailbox shows up
/// as a UIDVALIDITY change on the next connect, and that re-syncs it.
pub async fn update(
State(state): State<AppState>,
user: CurrentUser,
axum::extract::Path(account_id): axum::extract::Path<Uuid>,
AppJson(req): AppJson<UpdateAccountRequest>,
) -> ApiResult<Json<AccountPublic>> {
validate_settings(
&req.name,
&req.imap_host,
req.imap_port,
&req.smtp_host,
req.smtp_port,
&req.username,
)?;
let sealed = match req.password.as_deref().filter(|p| !p.is_empty()) {
Some(p) => Some(state.cipher.encrypt(p)?),
None => None,
};
let account: Option<Account> = sqlx::query_as(
"UPDATE accounts SET \
name = $3, imap_host = $4, imap_port = $5, smtp_host = $6, smtp_port = $7, \
username = $8, \
email_address = COALESCE($9, CASE WHEN $8 LIKE '%@%' THEN $8 END), \
display_name = $10, smtp_use_starttls = $11, \
encrypted_password = COALESCE($12, encrypted_password), \
password_nonce = COALESCE($13, password_nonce), \
updated_at = now() \
WHERE id = $1 AND user_id = $2 RETURNING *",
)
.bind(account_id)
.bind(user.user_id)
.bind(req.name.trim())
.bind(req.imap_host.trim())
.bind(req.imap_port)
.bind(req.smtp_host.trim())
.bind(req.smtp_port)
.bind(req.username.trim())
.bind(
req.email_address
.as_deref()
.map(str::trim)
.filter(|e| !e.is_empty()),
)
.bind(
req.display_name
.as_deref()
.map(str::trim)
.filter(|n| !n.is_empty()),
)
.bind(req.smtp_use_starttls.unwrap_or(req.smtp_port != 465))
.bind(sealed.as_ref().map(|s| &s.ciphertext))
.bind(sealed.as_ref().map(|s| &s.nonce))
.fetch_optional(&state.pool)
.await?;
let account = account.ok_or(ApiError::NotFound)?;
// The old status described the old settings.
sqlx::query(
"UPDATE sync_state SET status = 'pending', last_error = NULL, updated_at = now() \
WHERE account_id = $1",
)
.bind(account_id)
.execute(&state.pool)
.await?;
// Restart its sync task now rather than at the manager's next poll.
state.sync_wake.notify_one();
state
.events
.emit(user.user_id, Change::config(ConfigKind::Accounts))
.await;
Ok(Json(account.into()))
}
pub async fn delete(
State(state): State<AppState>,
user: CurrentUser,
+5 -2
View File
@@ -3,7 +3,7 @@ use crate::api::{
accounts, auth, devices, events, folders, messages, outbox, rules, tags, threads,
};
use axum::http::header::{AUTHORIZATION, CONTENT_TYPE};
use axum::routing::{delete, get, post, put};
use axum::routing::{get, post, put};
use axum::Router;
use tower_http::cors::{Any, CorsLayer};
use tower_http::trace::TraceLayer;
@@ -13,7 +13,10 @@ pub fn build(state: AppState) -> Router {
.route("/api/auth/register", post(auth::register))
.route("/api/auth/login", post(auth::login))
.route("/api/accounts", get(accounts::list).post(accounts::create))
.route("/api/accounts/:id", delete(accounts::delete))
.route(
"/api/accounts/:id",
put(accounts::update).delete(accounts::delete),
)
.route("/api/folders", get(folders::list).post(folders::create))
.route(
"/api/folders/:id",
+22 -13
View File
@@ -1,14 +1,16 @@
//! Spawns and tracks one sync task per account, and stops the task of an
//! account that was removed. Woken by the API when accounts change, and
//! polls as a fallback.
//! Spawns and tracks one sync task per account; stops the task of an
//! account that was removed, and restarts the task of one that was edited
//! (it holds its own copy of the settings). Woken by the API when accounts
//! change, and polls as a fallback.
use crate::crypto::CredentialCipher;
use crate::events::EventHub;
use crate::imap_sync::connection::AccountSyncer;
use crate::models::account::Account;
use crate::storage::BlobStore;
use chrono::{DateTime, Utc};
use sqlx::PgPool;
use std::collections::{HashMap, HashSet};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Notify;
@@ -23,10 +25,11 @@ pub async fn run(
events: EventHub,
wake: Arc<Notify>,
) {
let mut running: HashMap<Uuid, tokio::task::JoinHandle<()>> = HashMap::new();
// Each task, with the account version (updated_at) it was started from.
let mut running: HashMap<Uuid, (tokio::task::JoinHandle<()>, DateTime<Utc>)> = HashMap::new();
loop {
running.retain(|_, handle| !handle.is_finished());
running.retain(|_, (handle, _)| !handle.is_finished());
match sqlx::query_as::<_, Account>("SELECT * FROM accounts")
.fetch_all(&pool)
@@ -35,14 +38,20 @@ pub async fn run(
Ok(accounts) => {
// A removed account's task would otherwise retry forever
// against rows that no longer exist.
let present: HashSet<Uuid> = accounts.iter().map(|a| a.id).collect();
running.retain(|id, handle| {
let keep = present.contains(id);
if !keep {
let present: HashMap<Uuid, DateTime<Utc>> =
accounts.iter().map(|a| (a.id, a.updated_at)).collect();
running.retain(|id, (handle, version)| match present.get(id) {
None => {
tracing::info!(account_id = %id, "account removed; stopping sync task");
handle.abort();
false
}
keep
Some(current) if current != version => {
tracing::info!(account_id = %id, "account edited; restarting sync task");
handle.abort();
false
}
Some(_) => true,
});
for account in accounts {
if running.contains_key(&account.id) {
@@ -56,9 +65,9 @@ pub async fn run(
blobs: blobs.clone(),
events: events.clone(),
};
let id = syncer.account.id;
let (id, version) = (syncer.account.id, syncer.account.updated_at);
let handle = tokio::spawn(syncer.run());
running.insert(id, handle);
running.insert(id, (handle, version));
}
}
Err(e) => tracing::error!(error = %e, "failed to list accounts for sync manager"),
+1
View File
@@ -20,6 +20,7 @@ pub struct Account {
pub created_at: DateTime<Utc>,
pub email_address: Option<String>,
pub display_name: Option<String>,
pub updated_at: DateTime<Utc>,
}
impl Account {
+1
View File
@@ -70,6 +70,7 @@ async fn parameterised_routes_match() {
("GET", format!("/api/messages/{id}")),
("GET", format!("/api/threads/{id}")),
("DELETE", format!("/api/accounts/{id}")),
("PUT", format!("/api/accounts/{id}")),
("POST", format!("/api/threads/{id}/read")),
("PUT", format!("/api/outbox/{id}")),
("DELETE", format!("/api/outbox/{id}")),