encryption
runner nix smoke / nix label and flake smoke (push) Canceled after 0s

This commit is contained in:
2026-10-15 00:40:41 +00:00
parent 7bceeb255e
commit 60d2e5d80f
13 changed files with 799 additions and 118 deletions
+14 -3
View File
@@ -4,6 +4,10 @@ Small PostgreSQL-backed HTTP service for one-off tasks and daily, weekly, or
monthly routine tasks. The server generates future task occurrences and can
send due reminders through the Telegram Bot API.
The server stores an obligatory public title and an optional client-encrypted
payload. It never receives an age identity and Telegram always uses the public
title.
## Configuration
| Variable | Default | Purpose |
@@ -27,7 +31,7 @@ Create a weekly routine:
curl -X POST http://127.0.0.1:8090/v1/routines \
-H 'Content-Type: application/json' \
-d '{
"title": "Exercise",
"public_title": "Exercise",
"section": "evening",
"priority": "should",
"schedule": {"kind": "weekly", "weekdays": [1, 3, 5]},
@@ -39,7 +43,7 @@ Create a monthly routine that moves day 31 to a shorter month's final day:
```json
{
"title": "Review finances",
"public_title": "Review finances",
"section": "work",
"priority": "must",
"schedule": {
@@ -55,12 +59,19 @@ Routes:
```text
GET /health
GET /v1/tasks?date=YYYY-MM-DD
GET /v1/tasks/archived
POST /v1/tasks
POST /v1/tasks/{id}/complete
POST /v1/tasks/{id}/archive
POST /v1/tasks/{id}/restore
POST /v1/tasks/{id}/reschedule
DELETE /v1/tasks/{id}
DELETE /v1/tasks/{id} (archived tasks only)
GET /v1/routines
POST /v1/routines
```
Weekly days use ISO numbers: Monday is `1`, Sunday is `7`.
When private data is present, `encrypted_payload`, `encryption_version`, and
`content_id` must all be set. `encrypted_payload` is an ASCII-armored age file
containing the client's versioned JSON document.
+1 -1
View File
@@ -57,7 +57,7 @@ fn worker_tick(
while let Some(notification) = store.next_due_notification(&date, &time)? {
let text = format!(
"Routine reminder: {} [{} / {}]",
notification.title, notification.section, notification.priority
notification.public_title, notification.section, notification.priority
);
telegram.send_message(&text)?;
store.mark_notification_sent(notification.task_id)?;
+21 -9
View File
@@ -57,9 +57,13 @@ fn default_true() -> bool {
#[derive(Debug, Deserialize)]
pub struct CreateTask {
pub title: String,
pub public_title: String,
#[serde(default)]
pub notes: Option<String>,
pub encrypted_payload: Option<String>,
#[serde(default)]
pub encryption_version: Option<i16>,
#[serde(default)]
pub content_id: Option<String>,
pub section: Section,
pub priority: Priority,
pub scheduled_date: String,
@@ -76,8 +80,10 @@ pub struct RescheduleTask {
pub struct Task {
pub id: i64,
pub routine_id: Option<i64>,
pub title: String,
pub notes: Option<String>,
pub public_title: String,
pub encrypted_payload: Option<String>,
pub encryption_version: Option<i16>,
pub content_id: Option<String>,
pub section: String,
pub priority: String,
pub scheduled_date: String,
@@ -88,9 +94,13 @@ pub struct Task {
#[derive(Debug, Deserialize)]
pub struct CreateRoutine {
pub title: String,
pub public_title: String,
#[serde(default)]
pub notes: Option<String>,
pub encrypted_payload: Option<String>,
#[serde(default)]
pub encryption_version: Option<i16>,
#[serde(default)]
pub content_id: Option<String>,
pub section: Section,
pub priority: Priority,
pub schedule: Schedule,
@@ -101,8 +111,10 @@ pub struct CreateRoutine {
#[derive(Debug, Clone, Serialize)]
pub struct Routine {
pub id: i64,
pub title: String,
pub notes: Option<String>,
pub public_title: String,
pub encrypted_payload: Option<String>,
pub encryption_version: Option<i16>,
pub content_id: Option<String>,
pub section: String,
pub priority: String,
pub schedule: Schedule,
@@ -113,7 +125,7 @@ pub struct Routine {
#[derive(Debug, Clone)]
pub struct DueNotification {
pub task_id: i64,
pub title: String,
pub public_title: String,
pub section: String,
pub priority: String,
}
+8 -2
View File
@@ -44,6 +44,10 @@ fn handle(mut request: Request, store: &Store, api_token: Option<&str>) {
parse_json::<CreateTask>(&mut request).and_then(|input| store.create_task(input));
respond_created(request, result);
}
(&Method::Get, "/v1/tasks/archived") => match store.list_archived_tasks() {
Ok(tasks) => respond_json(request, 200, &tasks),
Err(error) => respond_failure(request, &error),
},
(&Method::Get, "/v1/routines") => match store.list_routines() {
Ok(routines) => respond_json(request, 200, &routines),
Err(error) => respond_failure(request, &error),
@@ -80,11 +84,13 @@ fn handle_task_action(mut request: Request, store: &Store, path: &str) {
let changed = match (request.method(), segments.get(3).copied()) {
(&Method::Post, Some("complete")) if segments.len() == 4 => store.complete_task(id),
(&Method::Post, Some("archive")) if segments.len() == 4 => store.archive_task(id),
(&Method::Post, Some("restore")) if segments.len() == 4 => store.restore_task(id),
(&Method::Post, Some("reschedule")) if segments.len() == 4 => {
parse_json::<RescheduleTask>(&mut request)
.and_then(|input| store.reschedule_task(id, &input.scheduled_date))
}
(&Method::Delete, None) if segments.len() == 3 => store.delete_task(id),
(&Method::Delete, None) if segments.len() == 3 => store.delete_archived_task(id),
_ => {
respond_error(request, 404, "route not found");
return;
@@ -93,7 +99,7 @@ fn handle_task_action(mut request: Request, store: &Store, path: &str) {
match changed {
Ok(true) => respond_json(request, 200, &StatusResponse { status: "ok" }),
Ok(false) => respond_error(request, 404, "task not found or already completed"),
Ok(false) => respond_error(request, 404, "task not found or action not allowed"),
Err(error) => respond_failure(request, &error),
}
}
+163 -56
View File
@@ -27,40 +27,59 @@ impl Store {
.batch_execute(
"CREATE TABLE IF NOT EXISTS routines (
id BIGSERIAL PRIMARY KEY,
title TEXT NOT NULL,
notes TEXT,
public_title TEXT NOT NULL,
encrypted_payload TEXT,
encryption_version SMALLINT,
content_id TEXT,
section TEXT NOT NULL,
priority TEXT NOT NULL,
schedule_json JSONB NOT NULL,
reminder_time TIME,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CHECK ((encrypted_payload IS NULL AND encryption_version IS NULL AND content_id IS NULL)
OR (encrypted_payload IS NOT NULL AND encryption_version IS NOT NULL AND content_id IS NOT NULL))
);
CREATE TABLE IF NOT EXISTS tasks (
id BIGSERIAL PRIMARY KEY,
routine_id BIGINT REFERENCES routines(id),
title TEXT NOT NULL,
notes TEXT,
public_title TEXT NOT NULL,
encrypted_payload TEXT,
encryption_version SMALLINT,
content_id TEXT,
section TEXT NOT NULL,
priority TEXT NOT NULL,
scheduled_date DATE NOT NULL,
reminder_time TIME,
status TEXT NOT NULL DEFAULT 'pending',
status_before_archive TEXT,
completed_at TIMESTAMPTZ,
archived_at TIMESTAMPTZ,
notification_sent_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE(routine_id, scheduled_date)
UNIQUE(routine_id, scheduled_date),
CHECK ((encrypted_payload IS NULL AND encryption_version IS NULL AND content_id IS NULL)
OR (encrypted_payload IS NOT NULL AND encryption_version IS NOT NULL AND content_id IS NOT NULL))
);
CREATE INDEX IF NOT EXISTS tasks_by_date
ON tasks(scheduled_date, status);
CREATE INDEX IF NOT EXISTS tasks_due_notification
ON tasks(scheduled_date, reminder_time, notification_sent_at);",
ON tasks(scheduled_date, reminder_time, notification_sent_at);
ALTER TABLE tasks
ADD COLUMN IF NOT EXISTS status_before_archive TEXT;
ALTER TABLE tasks
ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ;",
)
.map_err(db_error)
}
pub fn create_task(&self, task: CreateTask) -> Result<i64> {
validate_title(&task.title)?;
validate_public_title(&task.public_title)?;
validate_encrypted_fields(
task.encrypted_payload.as_deref(),
task.encryption_version,
task.content_id.as_deref(),
)?;
let scheduled_date = parse_date(&task.scheduled_date)?;
let reminder_time = parse_reminder(task.reminder_time.as_deref())?;
@@ -68,12 +87,15 @@ impl Store {
let row = client
.query_one(
"INSERT INTO tasks (
title, notes, section, priority, scheduled_date, reminder_time
) VALUES ($1, $2, $3, $4, $5, $6)
public_title, encrypted_payload, encryption_version, content_id,
section, priority, scheduled_date, reminder_time
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id",
&[
&task.title.trim(),
&task.notes,
&task.public_title.trim(),
&task.encrypted_payload,
&task.encryption_version,
&task.content_id,
&task.section.as_str(),
&task.priority.as_str(),
&scheduled_date,
@@ -89,11 +111,13 @@ impl Store {
let mut client = self.connect()?;
let rows = client
.query(
"SELECT id, routine_id, title, notes, section, priority,
"SELECT id, routine_id, public_title, encrypted_payload,
encryption_version, content_id, section, priority,
scheduled_date, reminder_time, status,
EXTRACT(EPOCH FROM completed_at)::BIGINT
FROM tasks
WHERE scheduled_date = $1
AND status != 'archived'
ORDER BY
CASE section
WHEN 'morning' THEN 0
@@ -109,25 +133,24 @@ impl Store {
&[&date],
)
.map_err(db_error)?;
Ok(rows
.into_iter()
.map(|row| {
let scheduled_date: NaiveDate = row.get(6);
let reminder_time: Option<NaiveTime> = row.get(7);
Task {
id: row.get(0),
routine_id: row.get(1),
title: row.get(2),
notes: row.get(3),
section: row.get(4),
priority: row.get(5),
scheduled_date: scheduled_date.to_string(),
reminder_time: reminder_time.map(|time| time.format("%H:%M").to_string()),
status: row.get(8),
completed_at: row.get(9),
}
})
.collect())
Ok(rows.into_iter().map(task_from_row).collect())
}
pub fn list_archived_tasks(&self) -> Result<Vec<Task>> {
let mut client = self.connect()?;
let rows = client
.query(
"SELECT id, routine_id, public_title, encrypted_payload,
encryption_version, content_id, section, priority,
scheduled_date, reminder_time, status,
EXTRACT(EPOCH FROM completed_at)::BIGINT
FROM tasks
WHERE status = 'archived'
ORDER BY archived_at DESC, id DESC",
&[],
)
.map_err(db_error)?;
Ok(rows.into_iter().map(task_from_row).collect())
}
pub fn complete_task(&self, id: i64) -> Result<bool> {
@@ -136,7 +159,7 @@ impl Store {
.execute(
"UPDATE tasks
SET status = 'completed', completed_at = now()
WHERE id = $1 AND status != 'completed'",
WHERE id = $1 AND status NOT IN ('completed', 'archived')",
&[&id],
)
.map(|changed| changed == 1)
@@ -150,23 +173,61 @@ impl Store {
.execute(
"UPDATE tasks
SET scheduled_date = $1, notification_sent_at = NULL
WHERE id = $2",
WHERE id = $2 AND status != 'archived'",
&[&date, &id],
)
.map(|changed| changed == 1)
.map_err(db_error)
}
pub fn delete_task(&self, id: i64) -> Result<bool> {
pub fn archive_task(&self, id: i64) -> Result<bool> {
let mut client = self.connect()?;
client
.execute("DELETE FROM tasks WHERE id = $1", &[&id])
.execute(
"UPDATE tasks
SET status_before_archive = status,
status = 'archived',
archived_at = now()
WHERE id = $1 AND status != 'archived'",
&[&id],
)
.map(|changed| changed == 1)
.map_err(db_error)
}
pub fn restore_task(&self, id: i64) -> Result<bool> {
let mut client = self.connect()?;
client
.execute(
"UPDATE tasks
SET status = COALESCE(status_before_archive, 'pending'),
status_before_archive = NULL,
archived_at = NULL
WHERE id = $1 AND status = 'archived'",
&[&id],
)
.map(|changed| changed == 1)
.map_err(db_error)
}
pub fn delete_archived_task(&self, id: i64) -> Result<bool> {
let mut client = self.connect()?;
client
.execute(
"DELETE FROM tasks WHERE id = $1 AND status = 'archived'",
&[&id],
)
.map(|changed| changed == 1)
.map_err(db_error)
}
pub fn create_routine(&self, routine: CreateRoutine) -> Result<i64> {
validate_title(&routine.title)?;
validate_public_title(&routine.public_title)?;
validate_encrypted_fields(
routine.encrypted_payload.as_deref(),
routine.encryption_version,
routine.content_id.as_deref(),
)?;
validate_schedule(&routine.schedule)?;
let reminder_time = parse_reminder(routine.reminder_time.as_deref())?;
let schedule_json = serde_json::to_value(&routine.schedule).map_err(json_error)?;
@@ -175,12 +236,15 @@ impl Store {
let row = client
.query_one(
"INSERT INTO routines (
title, notes, section, priority, schedule_json, reminder_time
) VALUES ($1, $2, $3, $4, $5, $6)
public_title, encrypted_payload, encryption_version, content_id,
section, priority, schedule_json, reminder_time
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id",
&[
&routine.title.trim(),
&routine.notes,
&routine.public_title.trim(),
&routine.encrypted_payload,
&routine.encryption_version,
&routine.content_id,
&routine.section.as_str(),
&routine.priority.as_str(),
&schedule_json,
@@ -195,7 +259,8 @@ impl Store {
let mut client = self.connect()?;
let rows = client
.query(
"SELECT id, title, notes, section, priority, schedule_json,
"SELECT id, public_title, encrypted_payload, encryption_version,
content_id, section, priority, schedule_json,
reminder_time, enabled
FROM routines ORDER BY id",
&[],
@@ -203,18 +268,20 @@ impl Store {
.map_err(db_error)?;
rows.into_iter()
.map(|row| {
let schedule_json: serde_json::Value = row.get(5);
let schedule_json: serde_json::Value = row.get(7);
let schedule = serde_json::from_value(schedule_json).map_err(json_error)?;
let reminder_time: Option<NaiveTime> = row.get(6);
let reminder_time: Option<NaiveTime> = row.get(8);
Ok(Routine {
id: row.get(0),
title: row.get(1),
notes: row.get(2),
section: row.get(3),
priority: row.get(4),
public_title: row.get(1),
encrypted_payload: row.get(2),
encryption_version: row.get(3),
content_id: row.get(4),
section: row.get(5),
priority: row.get(6),
schedule,
reminder_time: reminder_time.map(|time| time.format("%H:%M").to_string()),
enabled: row.get(7),
enabled: row.get(9),
})
})
.collect()
@@ -237,14 +304,17 @@ impl Store {
inserted += client
.execute(
"INSERT INTO tasks (
routine_id, title, notes, section, priority,
routine_id, public_title, encrypted_payload,
encryption_version, content_id, section, priority,
scheduled_date, reminder_time
) VALUES ($1, $2, $3, $4, $5, $6, $7)
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
ON CONFLICT (routine_id, scheduled_date) DO NOTHING",
&[
&routine.id,
&routine.title,
&routine.notes,
&routine.public_title,
&routine.encrypted_payload,
&routine.encryption_version,
&routine.content_id,
&routine.section,
&routine.priority,
&date,
@@ -263,7 +333,7 @@ impl Store {
let mut client = self.connect()?;
let row = client
.query_opt(
"SELECT id, title, section, priority
"SELECT id, public_title, section, priority
FROM tasks
WHERE scheduled_date = $1
AND reminder_time IS NOT NULL
@@ -277,7 +347,7 @@ impl Store {
.map_err(db_error)?;
Ok(row.map(|row| DueNotification {
task_id: row.get(0),
title: row.get(1),
public_title: row.get(1),
section: row.get(2),
priority: row.get(3),
}))
@@ -295,7 +365,26 @@ impl Store {
}
}
fn validate_title(title: &str) -> Result<()> {
fn task_from_row(row: postgres::Row) -> Task {
let scheduled_date: NaiveDate = row.get(8);
let reminder_time: Option<NaiveTime> = row.get(9);
Task {
id: row.get(0),
routine_id: row.get(1),
public_title: row.get(2),
encrypted_payload: row.get(3),
encryption_version: row.get(4),
content_id: row.get(5),
section: row.get(6),
priority: row.get(7),
scheduled_date: scheduled_date.to_string(),
reminder_time: reminder_time.map(|time| time.format("%H:%M").to_string()),
status: row.get(10),
completed_at: row.get(11),
}
}
fn validate_public_title(title: &str) -> Result<()> {
if title.trim().is_empty() {
Err("title must not be empty".to_owned())
} else if title.len() > 300 {
@@ -305,6 +394,24 @@ fn validate_title(title: &str) -> Result<()> {
}
}
fn validate_encrypted_fields(
payload: Option<&str>,
version: Option<i16>,
content_id: Option<&str>,
) -> Result<()> {
if payload.map(str::len).unwrap_or(0) > 128 * 1024 {
return Err("encrypted_payload must be at most 128 KiB".to_owned());
}
if content_id.map(str::len).unwrap_or(0) > 128 {
return Err("content_id must be at most 128 bytes".to_owned());
}
if payload.is_some() == version.is_some() && version.is_some() == content_id.is_some() {
Ok(())
} else {
Err("encrypted_payload, encryption_version, and content_id must be set together".to_owned())
}
}
fn parse_date(date: &str) -> Result<NaiveDate> {
NaiveDate::parse_from_str(date, "%Y-%m-%d").map_err(|_| "date must use YYYY-MM-DD".to_owned())
}