diff --git a/crates/izlek-core/migrations/0001_init.sql b/crates/izlek-core/migrations/0001_init.sql index 00ca779..5c61d9b 100644 --- a/crates/izlek-core/migrations/0001_init.sql +++ b/crates/izlek-core/migrations/0001_init.sql @@ -106,7 +106,10 @@ CREATE TABLE user ( photo BLOB, photo_mime TEXT, created_at TEXT NOT NULL, - last_signed_in_at TEXT + last_signed_in_at TEXT, + -- Where the person's "what changed for me" feed has been read to. NULL + -- until their first visit, which reads every line as news. + feed_seen_at TEXT ); CREATE UNIQUE INDEX user_email_unique ON user(workspace_id, email); @@ -126,7 +129,8 @@ CREATE TABLE signin_link ( token_hash TEXT NOT NULL, created_at TEXT NOT NULL, expires_at TEXT NOT NULL, - used_at TEXT + used_at TEXT, + kind TEXT NOT NULL DEFAULT 'join' ); CREATE UNIQUE INDEX signin_link_token ON signin_link(token_hash); diff --git a/crates/izlek-core/src/accounts.rs b/crates/izlek-core/src/accounts.rs index 5b54d27..9c415a0 100644 --- a/crates/izlek-core/src/accounts.rs +++ b/crates/izlek-core/src/accounts.rs @@ -17,7 +17,9 @@ use time::{Duration, OffsetDateTime}; use crate::Role; use crate::auth::{self, AuthError, PasswordProblem, Token, hash_password, verify_password}; -use crate::store::{NewUser, Session, Store, StoreError, User, Workspace}; +use crate::store::{ + LinkKind, NewUser, Session, Store, StoreError, User, Workspace, +}; /// How long a first-sign-in link is good for. The mockups say seven days, and /// an expired link is not a dead account: resending opens the same one. @@ -230,7 +232,7 @@ impl Accounts { let token = Token::mint(); let expires_at = OffsetDateTime::now_utc() + SIGNIN_LINK_LIFETIME; self.store - .create_signin_link(&user.id, &token.hash(), expires_at) + .create_signin_link(&user.id, &token.hash(), expires_at, LinkKind::Join) .await?; let subject = "Your İzlek sign-in link"; let body = format!( @@ -294,6 +296,13 @@ impl Accounts { return Err(AccountError::Rejected); } }; + // A reset link is not an invitation: the flow that spends it checks + // the password rules itself and signs the other browsers out. Same + // answer, same work. + if link.kind != LinkKind::Join { + let _ = hash_password(password); + return Err(AccountError::Rejected); + } // The rules are checked before the link is spent, so a rejected // password does not burn the invitation. @@ -319,7 +328,121 @@ impl Accounts { self.start_session(user).await } - // -- signing in -------------------------------------------------------- + // -- forgot password --------------------------------------------------- + + /// Mails a password-reset link to the address, if the address has an + /// account. The answer is the same whether it does or not: the miss path + /// pays for an Argon2 hash the way sign-in's pays for a verify, and only + /// the queued mail knows the difference. The token travels in the mail + /// and nowhere else — this method hands it to nobody. + /// + /// The client bucket refuses outright, like sign-in's. The address bucket + /// counts but stays silent: refusing by name would hand anyone who knows + /// a colleague's address a lock-out, so past the limit the request simply + /// mints nothing and answers the same success. + pub async fn request_password_reset(&self, email: &str, client: &str) -> Result<()> { + let now = OffsetDateTime::now_utc(); + let client_bucket = format!("client:{client}"); + self.check_rate(&client_bucket).await?; + self.store.record_auth_attempt(&client_bucket, now).await?; + + let address_bucket = format!("address:{}", email.trim().to_lowercase()); + let address_over_limit = self.over_limit(&address_bucket).await?; + self.store.record_auth_attempt(&address_bucket, now).await?; + + let user = match self.store.workspace().await? { + Some(workspace) => self.store.user_by_email(&workspace.id, email).await?, + None => None, + }; + let Some(user) = user else { + // Same work as the minting path, minus the effect. + let _ = hash_password(email); + return Ok(()); + }; + if address_over_limit { + // The request counts, the mail does not go: the answer above is + // still the answer a working reset gets. + return Ok(()); + } + + let token = Token::mint(); + let expires_at = now + SIGNIN_LINK_LIFETIME; + self.store + .create_signin_link(&user.id, &token.hash(), expires_at, LinkKind::Reset) + .await?; + let (subject, body) = reset_mail(&user, self.base().await?, &token.expose()); + self.store + .queue_notice(&user.email, &subject, &body, now) + .await?; + Ok(()) + } + + /// Redeems a reset link and sets the password the person chose, signing + /// every other browser out. Everything the invitation redeem refuses, + /// this refuses the same way — an unknown, expired, spent or wrong-kind + /// link is one [`AccountError::Rejected`], and every miss pays for a + /// hash. The limit is bucketed on the client, exactly as there. + pub async fn redeem_reset_link( + &self, + presented: &str, + password: &str, + client: &str, + ) -> Result { + let now = OffsetDateTime::now_utc(); + let client_bucket = format!("client:{client}"); + self.check_rate(&client_bucket).await?; + self.store.record_auth_attempt(&client_bucket, now).await?; + let digest = auth::hash_token(presented); + + let link = match self.store.signin_link_by_hash(&digest).await? { + Some(link) => link, + None => { + let _ = hash_password(password); + return Err(AccountError::Rejected); + } + }; + if !link.is_usable(now) { + let _ = hash_password(password); + return Err(AccountError::Rejected); + } + let user = match self.store.user(&link.user_id).await? { + Some(user) => user, + None => { + let _ = hash_password(password); + return Err(AccountError::Rejected); + } + }; + // An invitation is not a reset: it carries no expiry of the other + // browsers, so it must not be spendable on this screen. + if link.kind != LinkKind::Reset { + let _ = hash_password(password); + return Err(AccountError::Rejected); + } + + // The rules are checked before the link is spent, so a rejected + // password does not burn it. + auth::check_password(password, &user.email, &user.display_name)?; + let hash = hash_password(password)?; + + if !self.store.consume_signin_link(&link.id, now).await? { + return Err(AccountError::Rejected); + } + + self.store.set_password_hash(&user.id, &hash).await?; + // The charter the password change lives by: the new password signs + // the other browsers out, all of them. + self.store + .revoke_sessions_for_user(&user.id, now) + .await?; + self.store.mark_signed_in(&user.id, now).await?; + self.store.clear_auth_attempts(&client_bucket).await?; + let user = self + .store + .user(&user.id) + .await? + .ok_or(StoreError::NotFound)?; + self.start_session(user).await + } /// Signs a person in. `client` is whatever identifies the caller's machine /// — it only ever becomes a rate-limit bucket. @@ -506,3 +629,27 @@ impl Accounts { Ok(self.store.count_auth_attempts(bucket, since).await? >= RATE_LIMIT) } } + +/// The reset mail, in the account's own language. Terse like the invitation's: +/// what happened, the link, the once-only fact. +fn reset_mail(user: &User, base: String, token: &str) -> (String, String) { + if user.language == "tr" { + ( + "İzlek parolanı sıfırla".to_string(), + format!( + "Bu adres için bir İzlek parola sıfırlaması istendi.\n\n\ + {base}/reset/{token}\n\n\ + Bağlantı bir kez çalışır ve 7 gün içinde geçersiz olur.\n" + ), + ) + } else { + ( + "Reset your İzlek password".to_string(), + format!( + "A reset was asked for the İzlek password on this address.\n\n\ + {base}/reset/{token}\n\n\ + The link works once and expires in 7 days.\n" + ), + ) + } +} diff --git a/crates/izlek-core/src/board.rs b/crates/izlek-core/src/board.rs index 3c6b637..7790c2f 100644 --- a/crates/izlek-core/src/board.rs +++ b/crates/izlek-core/src/board.rs @@ -274,6 +274,33 @@ impl BoardView { pub fn blocked_count(&self) -> usize { self.cards().filter(|card| card.is_blocked()).count() } + + /// Keeps only the cards whose key or title answers `query`: a literal, + /// case-insensitive substring of either. The human key typed in any + /// case matches; a fragment of a title matches; nothing is + /// pattern-matched, so there are no wildcards to escape. + pub fn searching(&mut self, query: &str) { + let needle = query.to_lowercase(); + for column in &mut self.columns { + column.cards.retain(|card| { + card.task_key.to_lowercase().contains(&needle) + || card.title.to_lowercase().contains(&needle) + }); + } + } + + /// Keeps only the cards wearing `tag`, when one is named — the Project + /// filter, riding the same narrowing pass as [`BoardView::searching`]. + pub fn tagged(&mut self, tag_id: Option<&str>) { + let Some(tag_id) = tag_id else { + return; + }; + for column in &mut self.columns { + column + .cards + .retain(|card| card.tag.as_ref().is_some_and(|tag| tag.id == tag_id)); + } + } } /// `Sep 12` — the card chips are day-and-month, never a year. diff --git a/crates/izlek-core/src/mail.rs b/crates/izlek-core/src/mail.rs index 2df8214..8c64664 100644 --- a/crates/izlek-core/src/mail.rs +++ b/crates/izlek-core/src/mail.rs @@ -759,6 +759,12 @@ impl Engine { for one in sends { self.store.record_send_accepted(&one.id, now).await?; } + // A reminder that went out is a fact of the meeting's card, + // and a fact of the person's feed: the system did the + // reminding, the recipient is the line's subject. + for one in sends.iter().filter(|one| one.kind == SendKind::Reminder) { + self.record_reminded(one, now).await?; + } report.sent += 1; } Err(problem) if !problem.attempted => { @@ -792,6 +798,38 @@ impl Engine { } Ok(()) } + /// The trail line a delivered reminder writes: on the meeting's card, with + /// the system as the actor and the recipient as the subject, so the feed + /// a person reads carries the reminder they were sent. A recipient whose + /// account has since gone still gets the line — about nobody. + async fn record_reminded( + &self, + send: &ClaimedSend, + at: OffsetDateTime, + ) -> crate::store::Result<()> { + let Some(task_id) = send.task_id.as_deref() else { + return Ok(()); + }; + let subject = match self.store.workspace().await? { + Some(workspace) => self + .store + .user_by_email(&workspace.id, &send.recipient) + .await? + .map(|user| user.id), + None => None, + }; + self.store + .record_activity( + task_id, + None, + subject.as_deref(), + &ActivityKind::Other("reminded".to_string()), + &send.recipient, + at, + ) + .await?; + Ok(()) + } /// The mail itself, built from the facts as they were committed. async fn compose( diff --git a/crates/izlek-core/src/store/mod.rs b/crates/izlek-core/src/store/mod.rs index 0f59c39..2eb37c9 100644 --- a/crates/izlek-core/src/store/mod.rs +++ b/crates/izlek-core/src/store/mod.rs @@ -232,8 +232,36 @@ pub struct UserStats { pub comments: u32, } -/// A first-sign-in link. Only the hash of the token is ever stored; the -/// plaintext is shown once, when the link is created or resent. +/// What a link is for. The same table and the same token machinery carry +/// both; the kind decides which redeeming flow may spend it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LinkKind { + /// An invited person's first sign-in. + Join, + /// A self-serve password reset, mailed to the account's own address. + Reset, +} + +impl LinkKind { + pub fn as_str(&self) -> &'static str { + match self { + LinkKind::Join => "join", + LinkKind::Reset => "reset", + } + } + + pub fn from_str(raw: &str) -> Option { + match raw { + "join" => Some(LinkKind::Join), + "reset" => Some(LinkKind::Reset), + _ => None, + } + } +} + +/// A mailed link — an invitation or a password reset. Only the hash of the +/// token is ever stored; the plaintext is shown once, when the link is +/// created or mailed. #[derive(Debug, Clone, PartialEq)] pub struct SigninLink { pub id: String, @@ -241,6 +269,7 @@ pub struct SigninLink { pub created_at: OffsetDateTime, pub expires_at: OffsetDateTime, pub used_at: Option, + pub kind: LinkKind, } impl SigninLink { @@ -824,12 +853,13 @@ pub trait Store: BoardReads + DetailReads + 'static { // -- sign-in links ----------------------------------------------------- /// Stores the hash of a freshly minted link. The caller keeps the plaintext - /// and shows it once. + /// and shows it once. The kind decides which redeeming flow may spend it. async fn create_signin_link( &self, user_id: &str, token_hash: &str, expires_at: OffsetDateTime, + kind: LinkKind, ) -> Result; /// Looks a link up by the hash of the presented token. Returns the link @@ -1335,6 +1365,26 @@ pub trait Store: BoardReads + DetailReads + 'static { cursor: Option<&FeedCursor>, ) -> Result; + /// Puts `user_id` on a task's watchers. Idempotent: watching twice is + /// watching once. + async fn watch_task(&self, task_id: &str, user_id: &str) -> Result<()>; + + /// Takes `user_id` off a task's watchers. Absent watch, absent row: no + /// error. + async fn unwatch_task(&self, task_id: &str, user_id: &str) -> Result<()>; + + /// The "what changed for me" feed: activity events on the tasks the user + /// watches, plus events that name them (`subject_id` — an assignment + /// outlives the watch it created), minus the user's own actions. Newest + /// first, capped at `limit`. + async fn feed_for_user(&self, user_id: &str, limit: u32) -> Result>; + + /// How many feed lines have landed since the user last read the feed. + async fn count_feed_unseen(&self, user_id: &str) -> Result; + + /// Reads the feed to `at`: the unseen count resets, the history stays. + async fn mark_feed_seen(&self, user_id: &str, at: OffsetDateTime) -> Result<()>; + // -- who gets mailed --------------------------------------------------- /// The people a task points at. Viewers cannot be assigned, so none appear. diff --git a/crates/izlek-core/src/store/reconcile.rs b/crates/izlek-core/src/store/reconcile.rs index 35898f4..5353158 100644 --- a/crates/izlek-core/src/store/reconcile.rs +++ b/crates/izlek-core/src/store/reconcile.rs @@ -294,23 +294,30 @@ fn build_maps( maps.push(TableMap { name: "user", - columns: old_cols(&[ - "id", - "workspace_id", - "email", - "display_name", - "role", - "password_hash", - "invited_by", - "timezone", - "theme", - "language", - "ui", - "photo", - "photo_mime", - "created_at", - "last_signed_in_at", - ]), + columns: { + let mut columns = old_cols(&[ + "id", + "workspace_id", + "email", + "display_name", + "role", + "password_hash", + "invited_by", + "timezone", + "theme", + "language", + "ui", + "photo", + "photo_mime", + "created_at", + "last_signed_in_at", + ]); + // The feed's read marker is new with this schema: no database old + // enough to be reconciled ever carried it, so every copied row + // starts unseen rather than pretending to have been read. + columns.push(("feed_seen_at", "NULL".into())); + columns + } }); maps.push(TableMap { name: "workspace_owner", @@ -318,7 +325,21 @@ fn build_maps( }); maps.push(TableMap { name: "signin_link", - columns: old_cols(&["id", "user_id", "token_hash", "created_at", "expires_at", "used_at"]), + columns: { + let mut columns = old_cols(&[ + "id", + "user_id", + "token_hash", + "created_at", + "expires_at", + "used_at", + ]); + // The link's kind is new with this schema: every link a database + // old enough to be reconciled could carry is an invitation — + // resets did not exist to be mailed yet. + columns.push(("kind", "'join'".into())); + columns + } }); maps.push(TableMap { name: "session", diff --git a/crates/izlek-core/src/store/turso_store.rs b/crates/izlek-core/src/store/turso_store.rs index 21fe3b9..63962db 100644 --- a/crates/izlek-core/src/store/turso_store.rs +++ b/crates/izlek-core/src/store/turso_store.rs @@ -19,7 +19,7 @@ use super::{ Deletion, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule, MailSend, NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, SendState, SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, Tag, TaskCreated, Trigger, - User, UserStats, Workspace, + User, UserStats, Workspace, LinkKind, }; use super::{reconcile, ReconcileOptions, schema}; use crate::Role; @@ -863,6 +863,8 @@ fn signin_link_from(row: &Row) -> Result { created_at: parse_stamp(&text(row, 2)?)?, expires_at: parse_stamp(&text(row, 3)?)?, used_at: opt_stamp(row, 4)?, + kind: LinkKind::from_str(&text(row, 5)?) + .ok_or_else(|| StoreError::Corrupt("signin_link kind".into()))?, }) } @@ -1482,20 +1484,22 @@ impl Store for TursoStore { user_id: &str, token_hash: &str, expires_at: OffsetDateTime, + kind: LinkKind, ) -> Result { let id = Ulid::new().to_string(); self.conn .lock() .await .execute( - "INSERT INTO signin_link (id, user_id, token_hash, created_at, expires_at) \ - VALUES (?1, ?2, ?3, ?4, ?5)", + "INSERT INTO signin_link (id, user_id, token_hash, created_at, expires_at, kind) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", params![ id.clone(), user_id, token_hash, now_text()?, - stamp(expires_at)? + stamp(expires_at)?, + kind.as_str(), ], ) .await @@ -1503,7 +1507,8 @@ impl Store for TursoStore { self.announce([Topic::Members]); match self .one_row( - "SELECT id, user_id, created_at, expires_at, used_at FROM signin_link WHERE id = ?1", + "SELECT id, user_id, created_at, expires_at, used_at, kind \ + FROM signin_link WHERE id = ?1", params![id], ) .await? @@ -1516,8 +1521,8 @@ impl Store for TursoStore { async fn signin_link_by_hash(&self, token_hash: &str) -> Result> { match self .one_row( - "SELECT id, user_id, created_at, expires_at, used_at FROM signin_link \ - WHERE token_hash = ?1", + "SELECT id, user_id, created_at, expires_at, used_at, kind \ + FROM signin_link WHERE token_hash = ?1", params![token_hash], ) .await? @@ -1857,6 +1862,13 @@ impl Store for TursoStore { ], ) .await?; + // The maker watches what they made: its changes concern them + // until they say otherwise. + tx.execute( + "INSERT OR IGNORE INTO task_watcher (task_id, user_id) VALUES (?1, ?2)", + params![id.clone(), new.created_by], + ) + .await?; Ok::<_, turso::Error>(Ok((task_key, position))) } .await; @@ -2052,6 +2064,15 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + // Being assigned is being concerned: the assignee watches the task + // until an unassign takes the watch back off. Idempotent, so a + // no-change assign leaves the watch exactly as it is. + tx.execute( + "INSERT OR IGNORE INTO task_watcher (task_id, user_id) VALUES (?1, ?2)", + params![task_id, user_id], + ) + .await + .map_err(backend)?; // A no-change assign changes no facts, so the reminders stand as // they are. let reminded = if n > 0 { @@ -2091,6 +2112,14 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + // Leaving the task takes the watch back off: its changes stop + // concerning the person who left. + tx.execute( + "DELETE FROM task_watcher WHERE task_id = ?1 AND user_id = ?2", + params![task_id, user_id], + ) + .await + .map_err(backend)?; let reminded = if n > 0 { match self.sync_task_reminders(&tx, task_id, OffsetDateTime::now_utc()).await { Ok(reminded) => reminded, @@ -2294,6 +2323,11 @@ impl Store for TursoStore { ], ) .await?; + tx.execute( + "INSERT OR IGNORE INTO task_watcher (task_id, user_id) VALUES (?1, ?2)", + params![task_id, author_id], + ) + .await?; Ok::<_, turso::Error>(()) } .await; @@ -3944,6 +3978,122 @@ impl Store for TursoStore { row.as_ref().map(count_of).unwrap_or(Ok(0)) } + async fn watch_task(&self, task_id: &str, user_id: &str) -> Result<()> { + let conn = self.conn.lock().await; + conn.execute( + "INSERT OR IGNORE INTO task_watcher (task_id, user_id) VALUES (?1, ?2)", + params![task_id, user_id], + ) + .await + .map_err(backend)?; + drop(conn); + self.announce([Topic::Activity]); + Ok(()) + } + + async fn unwatch_task(&self, task_id: &str, user_id: &str) -> Result<()> { + let conn = self.conn.lock().await; + conn.execute( + "DELETE FROM task_watcher WHERE task_id = ?1 AND user_id = ?2", + params![task_id, user_id], + ) + .await + .map_err(backend)?; + drop(conn); + self.announce([Topic::Activity]); + Ok(()) + } + + async fn feed_for_user(&self, user_id: &str, limit: u32) -> Result> { + const SELECT: &str = "SELECT a.id, a.task_id, t.title, u.display_name, a.kind, a.detail, \ + a.created_at, t.task_key FROM activity a \ + JOIN task t ON t.id = a.task_id \ + LEFT JOIN user u ON u.id = a.actor_id"; + // Two ways an event can concern somebody, unioned: it happened on a + // task they watch, or it names them. An event arriving both ways is + // one row — UNION, not UNION ALL — and a person's own actions are + // nobody's news, not even their own (`IS NOT`, so the system's rows + // with no actor still pass). + let conn = self.conn.lock().await; + let sql = format!( + "{SELECT} JOIN task_watcher w ON w.task_id = a.task_id AND w.user_id = ?1 \ + WHERE a.actor_id IS NOT ?2 \ + UNION {SELECT} WHERE a.subject_id = ?3 AND a.actor_id IS NOT ?4 \ + ORDER BY created_at DESC, id DESC LIMIT ?5" + ); + let mut rows = conn + .query( + &sql, + params![user_id, user_id, user_id, user_id, i64::from(limit)], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(ActivityLine { + id: text(&row, 0)?, + task_id: opt_text(&row, 1)?, + title: opt_text(&row, 2)?, + actor_name: opt_text(&row, 3)?, + kind: ActivityKind::parse(&text(&row, 4)?), + detail: text(&row, 5)?, + at: parse_stamp(&text(&row, 6)?)?, + task_key: opt_text(&row, 7)?, + }); + } + Ok(out) + } + + async fn count_feed_unseen(&self, user_id: &str) -> Result { + const SELECT: &str = "SELECT a.id FROM activity a \ + JOIN task t ON t.id = a.task_id \ + LEFT JOIN user u ON u.id = a.actor_id"; + // Unseen is the same union as the feed, narrowed to rows that landed + // after the reader's marker. A reader who has never visited has no + // marker, and COALESCE with the empty string — which sorts before + // every stamp — reads the whole feed as news. + let conn = self.conn.lock().await; + let sql = format!( + "SELECT COUNT(*) FROM (\ + {SELECT} JOIN task_watcher w ON w.task_id = a.task_id AND w.user_id = ?1 \ + WHERE a.actor_id IS NOT ?2 \ + AND a.created_at > COALESCE((SELECT feed_seen_at FROM user WHERE id = ?3), '') \ + UNION \ + {SELECT} WHERE a.subject_id = ?4 AND a.actor_id IS NOT ?5 \ + AND a.created_at > COALESCE((SELECT feed_seen_at FROM user WHERE id = ?6), ''))" + ); + let mut rows = conn + .query( + &sql, + params![ + user_id, user_id, user_id, user_id, user_id, user_id, + ], + ) + .await + .map_err(backend)?; + let row = rows.next().await.map_err(backend)?; + match row { + Some(row) => { + let n: i64 = row.get(0).map_err(backend)?; + Ok(usize::try_from(n).unwrap_or(0) as u64) + } + None => Ok(0), + } + } + + async fn mark_feed_seen(&self, user_id: &str, at: OffsetDateTime) -> Result<()> { + let conn = self.conn.lock().await; + conn.execute( + "UPDATE user SET feed_seen_at = ?1 WHERE id = ?2", + params![stamp(at)?, user_id], + ) + .await + .map_err(backend)?; + drop(conn); + self.announce([Topic::Activity]); + Ok(()) + } + async fn count_activity_preceding( &self, filter: &ActivityFilter, diff --git a/crates/izlek-core/tests/store.rs b/crates/izlek-core/tests/store.rs index 1faed1d..4c171c8 100644 --- a/crates/izlek-core/tests/store.rs +++ b/crates/izlek-core/tests/store.rs @@ -1333,7 +1333,7 @@ async fn a_signin_link_stores_only_the_hash_and_is_used_once() { let now = OffsetDateTime::now_utc(); let link = scratch .store - .create_signin_link(&user.id, "hash-of-the-token", now + Duration::days(7)) + .create_signin_link(&user.id, "hash-of-the-token", now + Duration::days(7), izlek_core::store::LinkKind::Join) .await .unwrap(); assert!(link.is_usable(now)); @@ -1398,7 +1398,7 @@ async fn an_expired_link_is_still_a_live_account() { let now = OffsetDateTime::now_utc(); let stale = scratch .store - .create_signin_link(&user.id, "stale-hash", now - Duration::hours(1)) + .create_signin_link(&user.id, "stale-hash", now - Duration::hours(1), izlek_core::store::LinkKind::Join) .await .unwrap(); assert!(!stale.is_usable(now)); @@ -1406,7 +1406,7 @@ async fn an_expired_link_is_still_a_live_account() { // Resending opens the same account rather than making a new one. let fresh = scratch .store - .create_signin_link(&user.id, "fresh-hash", now + Duration::days(7)) + .create_signin_link(&user.id, "fresh-hash", now + Duration::days(7), izlek_core::store::LinkKind::Join) .await .unwrap(); assert_eq!(fresh.user_id, stale.user_id); @@ -1437,7 +1437,7 @@ async fn a_prefetched_link_is_consumed_exactly_once() { let token = Token::mint(); let now = OffsetDateTime::now_utc(); let link = store - .create_signin_link(&user_id, &token.hash(), now + Duration::days(7)) + .create_signin_link(&user_id, &token.hash(), now + Duration::days(7), izlek_core::store::LinkKind::Join) .await .unwrap(); @@ -1996,6 +1996,7 @@ async fn an_expired_link_is_refused_and_resending_opens_the_same_account() { &invitation.user.id, &stale.hash(), OffsetDateTime::now_utc() - Duration::minutes(1), + izlek_core::store::LinkKind::Join, ) .await .unwrap(); @@ -8543,3 +8544,447 @@ async fn a_change_back_to_the_same_password_is_refused_and_signs_nobody_out() { .await .unwrap(); } + +/// The board search keeps the cards whose key or title answers the query — +/// case-insensitively, each in the column it already sits in — and drops +/// the rest. +#[tokio::test] +async fn board_search_matches_keys_and_titles_in_place() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let panel = add_task(&scratch.store, &workspace, "Backlog", "Panel polish", None, &admin).await; + let wire = add_task(&scratch.store, &workspace, "In Progress", "Wire the exporter", None, &admin).await; + let panel_key = scratch + .store + .task(&panel) + .await + .unwrap() + .expect("panel task gone") + .row + .task_key; + + // The human key, typed in any case, finds its card — and only its card. + let mut board = izlek_core::board::load(&scratch.store, &workspace) + .await + .unwrap() + .unwrap(); + board.searching(&panel_key.to_lowercase()); + assert_eq!(board.task_count(), 1); + let backlog = board + .columns + .iter() + .find(|column| column.column.name == "Backlog") + .expect("no Backlog column"); + assert_eq!(backlog.cards.len(), 1); + assert_eq!(backlog.cards[0].id, panel); + assert!( + board + .columns + .iter() + .find(|column| column.column.name == "In Progress") + .expect("no In Progress column") + .cards + .is_empty() + ); + + // A title fragment, any case, the same story in the other column. + let mut board = izlek_core::board::load(&scratch.store, &workspace) + .await + .unwrap() + .unwrap(); + board.searching("EXPORT"); + assert_eq!(board.task_count(), 1); + let progress = board + .columns + .iter() + .find(|column| column.column.name == "In Progress") + .expect("no In Progress column"); + assert_eq!(progress.cards[0].id, wire); + + // A query nothing answers empties the board. + let mut board = izlek_core::board::load(&scratch.store, &workspace) + .await + .unwrap() + .unwrap(); + board.searching("no-such-card-anywhere"); + assert!(board.is_empty()); +} +// --------------------------------------------------------------------------- +// Self-serve password reset: a "Forgot it?" ask mails a reset link, the link +// redeems on its own screen only, and the new password signs every other +// browser out. The address's existence stays the requester's guess. +// --------------------------------------------------------------------------- + +/// The reset token out of the newest notice queued for the address — the mail +/// is the token's only carrier, so the test reads it like a recipient would. +async fn queued_reset_token( + store: &std::sync::Arc, + email: &str, +) -> Option { + let sends = store + .mail_queue(50, izlek_core::store::FeedPage::Newest) + .await + .unwrap(); + let body = sends + .into_iter() + .rev() + .find(|send| { + send.kind == izlek_core::store::SendKind::Notice && send.recipient == email + }) + .and_then(|send| send.body)?; + body.rsplit_once("/reset/") + .and_then(|(_, rest)| rest.split_whitespace().next()) + .map(str::to_string) +} + +#[tokio::test] +async fn a_reset_link_is_mailed_only_to_a_known_address() { + let (dir, store, workspace, _admin) = shared().await; + let _grace = member(&store, &workspace, "grace@izlek.sh", "Grace").await; + let store = store as std::sync::Arc; + let accounts = Accounts::new(store.clone(), "https://izlek.sh"); + + // One ask for an address with an account, one without: the caller sees + // two identical answers. + accounts + .request_password_reset("grace@izlek.sh", "203.0.113.9") + .await + .unwrap(); + accounts + .request_password_reset("nobody@izlek.sh", "203.0.113.9") + .await + .unwrap(); + + let link = scalar( + &dir.join("izlek.db").to_string_lossy(), + "SELECT COUNT(*) FROM signin_link WHERE kind = 'reset'", + ) + .await; + assert_eq!(link, 1, "only the known address gets a link"); + assert!( + queued_reset_token(&store, "grace@izlek.sh").await.is_some(), + "the known address was mailed a reset link" + ); + assert!( + queued_reset_token(&store, "nobody@izlek.sh").await.is_none(), + "the unknown address was mailed nothing" + ); + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test] +async fn a_reset_redeems_and_signs_the_other_browsers_out() { + let (_scratch, accounts, _admin) = claimed().await; + // A second browser, signed in before the reset. + let before = accounts + .sign_in("ada@izlek.sh", "tide-tables-1892", "198.51.100.7") + .await + .unwrap(); + + accounts + .request_password_reset("ada@izlek.sh", "203.0.113.9") + .await + .unwrap(); + let token = queued_reset_token(accounts.store(), "ada@izlek.sh") + .await + .expect("no reset mail queued"); + + let after = accounts + .redeem_reset_link(&token, "chronometer-1761", "203.0.113.10") + .await + .unwrap(); + + // The old password is gone, the new one signs in. + assert!(matches!( + accounts + .sign_in("ada@izlek.sh", "tide-tables-1892", "198.51.100.11") + .await, + Err(AccountError::Rejected) + )); + accounts + .sign_in("ada@izlek.sh", "chronometer-1761", "198.51.100.11") + .await + .unwrap(); + // The browser that was signed in before the reset is out; the redeeming + // browser's own session is alive. + assert!(matches!( + accounts.authenticate(&before.session_token.expose()).await.unwrap(), + None + )); + assert!(matches!( + accounts.authenticate(&after.session_token.expose()).await.unwrap(), + Some(_) + )); +} + +#[tokio::test] +async fn a_reset_link_only_redeems_once() { + let (_scratch, accounts, _admin) = claimed().await; + accounts + .request_password_reset("ada@izlek.sh", "203.0.113.9") + .await + .unwrap(); + let token = queued_reset_token(accounts.store(), "ada@izlek.sh") + .await + .expect("no reset mail queued"); + + accounts + .redeem_reset_link(&token, "chronometer-1761", "203.0.113.10") + .await + .unwrap(); + assert!(matches!( + accounts + .redeem_reset_link(&token, "chronometer-1761", "203.0.113.10") + .await, + Err(AccountError::Rejected) + )); +} + +#[tokio::test] +async fn an_expired_reset_link_is_refused() { + let (scratch, accounts, admin) = claimed().await; + let token = izlek_core::auth::Token::mint(); + scratch + .store + .create_signin_link( + &admin.id, + &token.hash(), + time::OffsetDateTime::now_utc() - time::Duration::seconds(1), + izlek_core::store::LinkKind::Reset, + ) + .await + .unwrap(); + assert!(matches!( + accounts + .redeem_reset_link(token.expose(), "chronometer-1761", "203.0.113.9") + .await, + Err(AccountError::Rejected) + )); +} + +#[tokio::test] +async fn each_link_redeems_only_on_its_own_screen() { + let (scratch, accounts, admin) = claimed().await; + // An invitation is not a reset: it must not spend itself where the other + // browsers get signed out. + let join = izlek_core::auth::Token::mint(); + scratch + .store + .create_signin_link( + &admin.id, + &join.hash(), + time::OffsetDateTime::now_utc() + SIGNIN_LINK_LIFETIME, + izlek_core::store::LinkKind::Join, + ) + .await + .unwrap(); + assert!(matches!( + accounts + .redeem_reset_link(&join.expose(), "chronometer-1761", "203.0.113.9") + .await, + Err(AccountError::Rejected) + )); + // And a reset link is not an invitation. + accounts + .request_password_reset("ada@izlek.sh", "203.0.113.9") + .await + .unwrap(); + let reset = queued_reset_token(accounts.store(), "ada@izlek.sh") + .await + .expect("no reset mail queued"); + assert!(matches!( + accounts + .redeem_signin_link(&reset, "chronometer-1761", "203.0.113.9") + .await, + Err(AccountError::Rejected) + )); +} + +#[tokio::test] +async fn reset_asks_are_rate_limited_per_client_and_silenced_per_address() { + let (dir, store, workspace, _admin) = shared().await; + let _grace = member(&store, &workspace, "grace@izlek.sh", "Grace").await; + let store = store as std::sync::Arc; + let accounts = Accounts::new(store.clone(), "https://izlek.sh"); + + // One machine asks RATE_LIMIT times: every ask answers the same, and the + // eleventh from that machine is refused by name. + for _ in 0..RATE_LIMIT { + accounts + .request_password_reset("grace@izlek.sh", "203.0.113.9") + .await + .unwrap(); + } + assert!(matches!( + accounts + .request_password_reset("grace@izlek.sh", "203.0.113.9") + .await, + Err(AccountError::RateLimited) + )); + // A fresh client hammering one address gets the same answer as ever, and + // the mailbox stays quiet: the address bucket caps the mail, not the + // answer. + accounts + .request_password_reset("grace@izlek.sh", "203.0.113.201") + .await + .unwrap(); + let queued = scalar( + &dir.join("izlek.db").to_string_lossy(), + "SELECT COUNT(*) FROM mail_send WHERE kind = 'notice'", + ) + .await; + assert_eq!(queued, RATE_LIMIT as i64, "the flood minted no mail"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Watches and the personal feed: creating, being assigned and commenting +/// each start a watch; an unassign ends it. The feed carries events on +/// watched tasks and events naming the reader, never the reader's own +/// actions; the unseen marker counts what landed since the last read. +#[tokio::test] +async fn the_personal_feed_follows_watches_names_and_the_marker() { + let (dir, store, workspace, admin) = shared().await; + let grace = member(&store, &workspace, "grace@izlek.sh", "Grace").await; + let now = OffsetDateTime::now_utc(); + let board = store.board(&workspace).await.unwrap().unwrap(); + let column_id = column_named(&store, &workspace, "Backlog").await; + let task = store + .create_task(NewTask { + board_id: &board.id, + column_id: &column_id, + parent_id: None, + title: "Feed me", + description: "", + deadline: None, + clock_at: None, + created_by: &admin, + }) + .await + .unwrap() + .row + .id; + + store.assign_task(&task, &grace).await.unwrap(); + + // Creating started Ada's watch; the assignment starts Grace's. Nobody's + // own actions are their own news: Ada's created line is Grace's news, + // and Grace's feed shows it while Ada's stays empty. + let grace_feed = store.feed_for_user(&grace, 50).await.unwrap(); + assert_eq!(grace_feed.len(), 1); + assert_eq!(grace_feed[0].kind, ActivityKind::Created); + assert_eq!(grace_feed[0].actor_name.as_deref(), Some("Ada")); + assert!(store.feed_for_user(&admin, 50).await.unwrap().is_empty()); + assert_eq!(store.count_feed_unseen(&grace).await.unwrap(), 1); + + // Grace's own comment is her own action: it is Ada's news, not hers. + store + .add_comment(&task, &grace, "Looking at it now", now) + .await + .unwrap(); + // Her feed keeps the created line; her own comment never comes back. + let grace_feed = store.feed_for_user(&grace, 50).await.unwrap(); + assert_eq!(grace_feed.len(), 1); + assert_eq!(grace_feed[0].kind, ActivityKind::Created); + let admin_feed = store.feed_for_user(&admin, 50).await.unwrap(); + assert_eq!(admin_feed.len(), 1); + assert_eq!(admin_feed[0].kind, ActivityKind::Commented); + assert_eq!(admin_feed[0].actor_name.as_deref(), Some("Grace")); + assert_eq!(store.count_feed_unseen(&admin).await.unwrap(), 1); + + // Reading the feed is reading it: the marker resets, the history stays. + store + .mark_feed_seen(&admin, now + Duration::seconds(5)) + .await + .unwrap(); + assert_eq!(store.count_feed_unseen(&admin).await.unwrap(), 0); + assert_eq!(store.feed_for_user(&admin, 50).await.unwrap().len(), 1); + + // Grace reads the feed too: her marker takes the created line off her + // unseen count, history included. + store + .mark_feed_seen(&grace, now + Duration::seconds(3)) + .await + .unwrap(); + assert_eq!(store.count_feed_unseen(&grace).await.unwrap(), 0); + assert_eq!(store.feed_for_user(&grace, 50).await.unwrap().len(), 1); + + // Ada's comment lands on a task Grace watches, after her marker: news. + store + .add_comment(&task, &admin, "Thanks — ship it", now + Duration::seconds(6)) + .await + .unwrap(); + assert_eq!(store.count_feed_unseen(&grace).await.unwrap(), 1); + let grace_feed = store.feed_for_user(&grace, 50).await.unwrap(); + assert_eq!(grace_feed.len(), 2, "{grace_feed:?}"); + assert_eq!(grace_feed[0].kind, ActivityKind::Commented); + assert_eq!(grace_feed[0].actor_name.as_deref(), Some("Ada")); + + // An unassign takes the watch back off: history on the task stops + // concerning the person who left. + store.unassign_task(&task, &grace).await.unwrap(); + assert!(store.feed_for_user(&grace, 50).await.unwrap().is_empty()); + assert_eq!(store.count_feed_unseen(&grace).await.unwrap(), 0); + + // An event that NAMES her concerns her with no watch at all — the + // second way into the feed. + store + .record_activity( + &task, + Some(&admin), + Some(&grace), + &ActivityKind::Assigned, + "Grace", + now + Duration::seconds(7), + ) + .await + .unwrap(); + let grace_feed = store.feed_for_user(&grace, 50).await.unwrap(); + assert_eq!(grace_feed.len(), 1); + assert_eq!(grace_feed[0].kind, ActivityKind::Assigned); + + let _ = std::fs::remove_dir_all(&dir); +} +#[tokio::test] +async fn a_delivered_reminder_writes_the_reminded_event() { + let (dir, store, workspace, admin) = shared().await; + let grace = member(&store, &workspace, "grace@izlek.sh", "Grace").await; + let clock = OffsetDateTime::now_utc() + Duration::hours(2); + let task = clocked_task(&store, &workspace, &admin, Some(clock)).await; + store.assign_task(&task, &grace).await.unwrap(); + + let engine = Engine::new( + store.clone() as std::sync::Arc, + Remembering::taking_everything(), + "https://izlek.sh", + ); + let later = clock - Duration::minutes(14); + assert_eq!(engine.deliver_owed(later, 10).await.unwrap().sent, 1); + + // The delivery wrote the trail line: on the meeting's card, about the + // person the reminder landed on, with the system as the actor. + let path = dir.join("izlek.db").to_string_lossy().into_owned(); + let events = scalar( + &path, + "SELECT COUNT(*) FROM activity WHERE kind = 'reminded' AND actor_id IS NULL", + ) + .await; + assert_eq!(events, 1, "one delivery, one line"); + let about = scalar( + &path, + &format!( + "SELECT COUNT(*) FROM activity WHERE kind = 'reminded' \ + AND subject_id = '{grace}' AND task_id = '{task}'" + ), + ) + .await; + assert_eq!(about, 1, "the line is about the reminded person"); + + // Sweeping again re-sends nothing and writes nothing. + engine.deliver_owed(later + Duration::minutes(1), 10).await.unwrap(); + let events = scalar( + &path, + "SELECT COUNT(*) FROM activity WHERE kind = 'reminded'", + ) + .await; + assert_eq!(events, 1); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/izlek-web/src/auth.rs b/crates/izlek-web/src/auth.rs index 3a95d59..ed0c5e6 100644 --- a/crates/izlek-web/src/auth.rs +++ b/crates/izlek-web/src/auth.rs @@ -339,3 +339,108 @@ struct InvitationForm { async fn invitation(cx: &Cx, Form(input): Form) -> Result>> { Ok(Json(invited_by_token(cx, &input.token).await?)) } + +/// Who a reset link was mailed to, looked up by the link's own token — the +/// reset page's "signing in as" line. Only a link of the reset kind resolves +/// here, and only while it is still usable: a spent or expired link shows +/// the same dead card an unknown token does. +pub async fn reset_by_token(cx: &Cx, token: &str) -> Result> { + use izlek_core::auth::hash_token; + use time::OffsetDateTime; + + let store = accounts(cx).store().clone(); + let digest = hash_token(token); + let Some(link) = store.signin_link_by_hash(&digest).await? else { + return Ok(None); + }; + if link.kind != izlek_core::store::LinkKind::Reset + || !link.is_usable(OffsetDateTime::now_utc()) + { + return Ok(None); + } + let Some(user) = store.user(&link.user_id).await? else { + return Ok(None); + }; + Ok(Some(Invited { + display_name: user.display_name, + email: user.email, + invited_by: None, + })) +} + +#[derive(Deserialize)] +struct ForgotPasswordForm { + email: String, +} + +/// Asks for a password-reset mail. The answer is the same whether the +/// address has an account or not — the difference is not the browser's +/// business. The request is the trail's fact either way; a rate-limited +/// client is refused by name. +#[route(POST "/api/forgot_password")] +async fn forgot_password(cx: &Cx, Form(input): Form) -> Redirect { + match accounts(cx) + .request_password_reset(&input.email, &client_label(cx)) + .await + { + Ok(()) => { + let _ = accounts(cx) + .store() + .record_event( + None, + &ActivityKind::Other("password_reset_requested".to_string()), + &input.email, + time::OffsetDateTime::now_utc(), + ) + .await; + // The sent note rides the redirect, the way `saved=` does: one + // sentence for every address. + let back = back_to(cx, "/forgot"); + let sep = if back.contains('?') { "&" } else { "?" }; + Ok(( + StatusCode::SEE_OTHER, + [(header::LOCATION, format!("{back}{sep}sent=forgot_password"))], + Json(None), + )) + } + Err(error) => redirect(cx, Some(error.into())), + } +} + +#[derive(Deserialize)] +struct RedeemResetForm { + token: String, + password: String, +} + +/// The reset link spends itself on the new password, and every other +/// browser is signed out — the promise the change-password pane makes. +#[route(POST "/api/redeem_reset")] +async fn redeem_reset(cx: &Cx, Form(input): Form) -> Redirect { + match accounts(cx) + .redeem_reset_link(&input.token, &input.password, &client_label(cx)) + .await + { + Ok(signed_in) => { + set_session_cookie(cx, signed_in.session_token.expose(), SESSION_LIFETIME); + let _ = accounts(cx) + .store() + .record_event( + Some(&signed_in.user.id), + &ActivityKind::Other("password_reset_completed".to_string()), + &signed_in.user.email, + time::OffsetDateTime::now_utc(), + ) + .await; + // The referring `/reset/{token}` names a spent link now; a + // browser that just signed in belongs on the board, the way the + // invitation redeem lands. + Ok(( + StatusCode::SEE_OTHER, + [(header::LOCATION, "/".to_string())], + Json(None), + )) + } + Err(error) => redirect(cx, Some(error.into())), + } +} diff --git a/crates/izlek-web/src/board.rs b/crates/izlek-web/src/board.rs index d824c14..40e262e 100644 --- a/crates/izlek-web/src/board.rs +++ b/crates/izlek-web/src/board.rs @@ -235,6 +235,15 @@ fn valid_tag(tag: Option<&str>, tags: &[izlek_core::store::Tag]) -> Option) -> Option { + query + .map(str::trim) + .filter(|query| !query.is_empty()) + .map(str::to_string) +} + /// `deadline` is the order [`izlek_core::board::load`] already hands back /// (soonest first); the other two re-order in place here so core stays free /// of a UI sort preference. `created` reads the task id, a ULID, which sorts @@ -252,6 +261,7 @@ async fn board_columns( cx: &Cx, sort: String, tag_filter: Option, + search: Option, default_tag_id: Option<&str>, ) -> Result { let user = match require_user(cx).await { @@ -274,14 +284,13 @@ async fn board_columns(

(t(lang, Key::SomethingWentWrong))

}; }; + if let Some(needle) = &search { + view_data.searching(needle); + } + view_data.tagged(tag_filter.as_deref()); for column in &mut view_data.columns { column.column.name = crate::i18n::column_name(lang, &column.column.name); sort_column_cards(&mut column.cards, &sort); - if let Some(tag_id) = &tag_filter { - column - .cards - .retain(|card| card.tag.as_ref().is_some_and(|tag| tag.id == *tag_id)); - } } let today = OffsetDateTime::now_utc().date(); let may_write = user.role.can_write_tasks(); @@ -569,6 +578,7 @@ struct BoardQuery { confirm: Option, new: Option, tag: Option, + q: Option, } /// The noun a sort key shows in the ` - for key in SORT_KEYS { - + + + (t(lang, Key::Project)) + Result {
- (t(lang, Key::Project)) - + + (t(lang, Key::Sort)) + Result {
+
if overdue > 0 { (format!("{overdue} {}", t(lang, Key::Overdue))) } if blocked > 0 { (format!("{blocked} {}", t(lang, Key::Blocked))) } @@ -692,9 +720,13 @@ pub async fn board_page(cx: &Cx, user: &User) -> Result {

(refusal.message_in(lang))

}
-
- (board_columns(cx, sort.clone(), tag_filter.clone(), default_tag_id).await?) -
+ if search.is_some() && view_data.is_empty() { +

(t(lang, Key::NoMatches))

+ } else { +
+ (board_columns(cx, sort.clone(), tag_filter.clone(), search.clone(), default_tag_id).await?) +
+ }
if let Some(task_id) = &open_task { (crate::detail::task_modal(cx, task_id, query.confirm.as_deref() == Some("delete"), open_tab).await?) diff --git a/crates/izlek-web/src/detail.rs b/crates/izlek-web/src/detail.rs index 6d7101b..4f32edc 100644 --- a/crates/izlek-web/src/detail.rs +++ b/crates/izlek-web/src/detail.rs @@ -1956,14 +1956,7 @@ pub async fn task_modal(cx: &Cx, task_id: &str, confirm_delete: bool, tab: Tab) }; let has_deps = !detail.blocked_by.is_empty() || !detail.blocks.is_empty(); let accept = (!allowed_file_types.is_empty()) - .then(|| { - allowed_file_types - .iter() - .map(|kind| format!(".{kind}")) - .collect::>() - .join(",") - }) - .unwrap_or_default(); + .then(|| crate::files::accept_attribute(&allowed_file_types)); // The delete confirmation is computed eagerly rather than fetched on // demand: there is no script here to hold the intermediate "did they @@ -2193,7 +2186,7 @@ pub async fn task_modal(cx: &Cx, task_id: &str, confirm_delete: bool, tab: Tab) (refused(cx, "upload_file", lang).await?) diff --git a/crates/izlek-web/src/feed.rs b/crates/izlek-web/src/feed.rs new file mode 100644 index 0000000..009e838 --- /dev/null +++ b/crates/izlek-web/src/feed.rs @@ -0,0 +1,111 @@ +//! "What changed for me": the events a signed-in person has a stake in. +//! +//! Every role gets it — a Viewer's feed is simply emptier, not hidden. Two +//! things put a line on someone's feed: it happened on a task they watch +//! (making a task, being assigned, commenting each start a watch; an +//! unassign ends it), or it names them. Nobody's own actions come back to +//! them — the store's feed query leaves those off. The watch and marker +//! mechanics live in the store (`feed_for_user`, `count_feed_unseen`, +//! `mark_feed_seen`); this page only reads and renders. +//! +//! Visiting is reading: the page marks the feed seen after fetching its +//! rows, so the badge on the next page anywhere — and on this one, which +//! renders after the mark — reads zero. New events announce on the live +//! channel like every other write, and the shell's refresh morph brings +//! both this page and the topbar badge back up to date. + +use time::OffsetDateTime; +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::{error::not_found, page}; +use topcoat::view::view; + + +use crate::i18n::{Key, Lang, t}; +use crate::server::{accounts, require_user}; + +/// How many lines one page draws, the same cap the logs page reads by: a +/// read a person can finish, panned inside the shell, never a document +/// growing past the viewport. +const LIMIT: u32 = 50; + +/// One rendered feed line: the strings the view stamps in, decided here so +/// the template stays a list of facts rather than a chain of lookups. +struct FeedRow { + task_label: String, + href: String, + actor: String, + sentence: String, + when: String, +} + +/// The person's feed. `/feed`. +#[page("/feed")] +async fn feed_page(cx: &Cx) -> Result { + let user = match require_user(cx).await { + Ok(user) => user, + Err(_) => return Err(not_found().into()), + }; + let lang = Lang::from_code(&user.language); + let store = accounts(cx).store().clone(); + let lines = store.feed_for_user(&user.id, LIMIT).await?; + // The visit is the marker, taken after the rows are read: the badge on + // the next page anywhere reads zero, and this page's own topbar — + // rendered after the mark — agrees with it. + store + .mark_feed_seen(&user.id, OffsetDateTime::now_utc()) + .await?; + let zone = izlek_core::detail::parse_zone(&user.timezone); + + let rows: Vec = lines + .iter() + .map(|line| FeedRow { + task_label: match (&line.task_key, &line.title) { + (Some(key), Some(title)) => format!("{key} · {title}"), + (Some(key), None) => key.clone(), + _ => line.title.clone().unwrap_or_default(), + }, + href: format!("/?task={}", line.task_id.as_deref().unwrap_or_default()), + actor: line + .actor_name + .clone() + .unwrap_or_else(|| t(lang, Key::TheSystem).to_string()), + sentence: crate::logs::activity_sentence(&line.kind, &line.detail, lang), + when: izlek_core::detail::moment_label_in(line.at, zone), + }) + .collect(); + + view! { + cx => +
+ (crate::layout::mark(cx).await?) + (crate::layout::topbar_nav(cx, crate::layout::NavPage::Feed, user.role, lang).await?) +
+ (crate::layout::user_menu(cx, &crate::detail::Me::from(&user), lang).await?) +
+ +
+
+
+

(t(lang, Key::NavFeed))

+
+ if rows.is_empty() { +

(t(lang, Key::FeedEmpty))

+ } else { +
    + for row in rows { +
  1. + (row.task_label) + + (row.actor) + (row.sentence) + + (row.when) +
  2. + } +
+ } +
+
+ } +} diff --git a/crates/izlek-web/src/files.rs b/crates/izlek-web/src/files.rs index e999258..0ea6463 100644 --- a/crates/izlek-web/src/files.rs +++ b/crates/izlek-web/src/files.rs @@ -69,6 +69,51 @@ fn label_of(file_name: &str) -> String { base.chars().filter(|c| !c.is_control()).collect() } +/// The `accept` attribute the task modal's upload input wears, built from +/// the workspace's allowed extensions. Known extensions travel as MIME +/// types — a mobile picker filters on MIME and opens on the documents +/// shelf, with the camera at most one option among many and never the +/// forced door; an unknown extension keeps its `.ext` form; an empty list +/// is no attribute at all, and the picker opens on the whole filesystem. +/// The word `capture` appears nowhere in this crate: it is the attribute +/// that turns a file input into a camera. +pub(crate) fn accept_attribute(allowed: &[String]) -> String { + allowed + .iter() + .map(|ext| { + let ext = ext.trim_start_matches('.').to_lowercase(); + match mime_of_extension(&ext) { + Some(mime) => mime.to_string(), + None => format!(".{ext}"), + } + }) + .collect::>() + .join(",") +} + +/// The MIME types a mobile picker understands, for the extensions a +/// workspace is likely to allow; anything else stays an extension hint. +fn mime_of_extension(ext: &str) -> Option<&'static str> { + match ext { + "png" => Some("image/png"), + "jpg" | "jpeg" => Some("image/jpeg"), + "gif" => Some("image/gif"), + "webp" => Some("image/webp"), + "svg" => Some("image/svg+xml"), + "pdf" => Some("application/pdf"), + "txt" | "md" => Some("text/plain"), + "csv" => Some("text/csv"), + "json" => Some("application/json"), + "zip" => Some("application/zip"), + "mp4" => Some("video/mp4"), + "webm" => Some("video/webm"), + "mp3" => Some("audio/mpeg"), + "wav" => Some("audio/wav"), + "ogg" => Some("audio/ogg"), + _ => None, + } +} + /// What the bytes are, decided from the bytes themselves — never from the /// part's `content_type()`, which is whatever the browser felt like sending. pub(crate) fn sniff(bytes: &[u8]) -> &'static str { @@ -291,14 +336,18 @@ struct DownloadQuery { dl: Option, } -/// Takes one file onto a task. The route this hangs off already caps the -/// whole request body at the widest limit any workspace could set -/// ([`crate::settings::WIDEST_ATTACHMENT_MB`], registered in `main.rs`); this handler enforces -/// the workspace's own, usually narrower, limit while the bytes are still -/// arriving rather than after they have all landed. +/// Takes the files a task's upload form carries onto that task — one per +/// `file` part, and a `multiple` picker posts several. The route this hangs +/// off already caps the whole request body at the widest limit any +/// workspace could set ([`crate::settings::WIDEST_ATTACHMENT_MB`], +/// registered in `main.rs`); this handler enforces the workspace's own, +/// usually narrower, limit per file while the bytes are still arriving +/// rather than after they have all landed, and a part that breaks it +/// refuses the whole post before anything is inserted. /// -/// Fields arrive in request order: `task_id` before `file`, so the task and -/// the workspace's limits are known before a byte of the file is kept. +/// Fields arrive in request order: `task_id` before the `file` parts, so +/// the task and the workspace's limits are known before a byte of any file +/// is kept. #[route(POST "/files")] async fn upload( cx: &Cx, @@ -314,8 +363,7 @@ async fn upload( let mut task_id: Option = None; let mut comment_id: Option = None; - let mut file_name: Option = None; - let mut bytes: Option> = None; + let mut files: Vec<(String, Vec)> = Vec::new(); let store = accounts(cx).store().clone(); @@ -374,8 +422,7 @@ async fn upload( } } - file_name = Some(name); - bytes = Some(collected); + files.push((name, collected)); } _ => {} } @@ -384,10 +431,9 @@ async fn upload( let Some(task_id) = task_id else { return Ok(home(Refusal::NotFound)); }; - let Some(file_name) = file_name else { + if files.is_empty() { return Ok(back_to(&task_id, Some(Refusal::NoFile))); - }; - let bytes = bytes.unwrap_or_default(); + } // A `comment_id` only travels if it names a comment that is actually on // this task; anything else is dropped rather than refused, since the @@ -404,32 +450,36 @@ async fn upload( None => None, }; - let label = label_of(&file_name); - let mime_type = sniff(&bytes); - - let added = store - .add_attachment(NewAttachment { - task_id: &task_id, - comment_id: comment_id.as_deref(), - file_name: &label, - mime_type, - bytes, - uploaded_by: &user.id, - at: OffsetDateTime::now_utc(), - }) - .await; - - if added.is_ok() && comment_id.is_none() { - let _ = store - .record_activity( - &task_id, - Some(&user.id), - None, - &izlek_core::detail::ActivityKind::FileAdded, - &label, - OffsetDateTime::now_utc(), - ) - .await; + let mut added: Result<(), izlek_core::store::StoreError> = Ok(()); + for (file_name, bytes) in files { + let label = label_of(&file_name); + let mime_type = sniff(&bytes); + + added = store + .add_attachment(NewAttachment { + task_id: &task_id, + comment_id: comment_id.as_deref(), + file_name: &label, + mime_type, + bytes, + uploaded_by: &user.id, + at: OffsetDateTime::now_utc(), + }) + .await + .map(|_| ()); + + if added.is_ok() && comment_id.is_none() { + let _ = store + .record_activity( + &task_id, + Some(&user.id), + None, + &izlek_core::detail::ActivityKind::FileAdded, + &label, + OffsetDateTime::now_utc(), + ) + .await; + } } Ok(match added { @@ -662,4 +712,18 @@ mod tests { "an empty file has no range to satisfy" ); } + + #[test] + fn accept_attribute_speaks_mime_for_known_extensions_and_dots_for_the_rest() { + let allowed: Vec = ["png", "PDF", ".txt", "weird1"] + .iter() + .map(|s| s.to_string()) + .collect(); + assert_eq!( + accept_attribute(&allowed), + "image/png,application/pdf,text/plain,.weird1", + "MIME types filter a mobile picker; the camera is never the only door" + ); + assert_eq!(accept_attribute(&[]), "", "no list, no attribute"); + } } diff --git a/crates/izlek-web/src/i18n.rs b/crates/izlek-web/src/i18n.rs index cb818ad..6d63be2 100644 --- a/crates/izlek-web/src/i18n.rs +++ b/crates/izlek-web/src/i18n.rs @@ -365,6 +365,19 @@ pub enum Key { ReminderMinutesLabel, ClockHour, ClockMinute, + Search, + NoMatches, + ForgotIt, + ForgotTitle, + ForgotSend, + ForgotSent, + ResetTitle, + ResetLinkDead, + ActResetRequested, + ActResetDone, + NavFeed, + ActReminded, + FeedEmpty, } /// The lone templated phrase — a name in the middle reads worse as two @@ -1039,6 +1052,33 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (ClockHour, Tr) => "Saat", (ClockMinute, En) => "Minute", (ClockMinute, Tr) => "Dakika", + + (Search, En) => "Search", + (Search, Tr) => "Ara", + (NoMatches, En) => "No matches", + (NoMatches, Tr) => "Eşleşme yok", + (ForgotIt, En) => "Forgot it?", + (ForgotIt, Tr) => "Parolamı unuttum", + (ForgotTitle, En) => "Reset the password", + (ForgotTitle, Tr) => "Parolayı sıfırla", + (ForgotSend, En) => "Send the link", + (ForgotSend, Tr) => "Bağlantıyı gönder", + (ForgotSent, En) => "If the address has an account, a reset link is on its way.", + (ForgotSent, Tr) => "Adres bir hesaba aitse sıfırlama bağlantısı yolda.", + (ResetTitle, En) => "Choose a new password", + (ResetTitle, Tr) => "Yeni parola seç", + (ResetLinkDead, En) => "This reset link no longer works", + (ResetLinkDead, Tr) => "Bu sıfırlama bağlantısı artık çalışmıyor", + (ActResetRequested, En) => "asked to reset the password", + (ActResetRequested, Tr) => "parola sıfırlaması istedi", + (ActResetDone, En) => "set a new password by reset link", + (ActResetDone, Tr) => "sıfırlama bağlantısıyla yeni parola aldı", + (ActReminded, En) => "sent a reminder mail", + (ActReminded, Tr) => "hatırlatma gönderdi", + (NavFeed, En) => "For me", + (NavFeed, Tr) => "Benim için", + (FeedEmpty, En) => "Nothing yet.", + (FeedEmpty, Tr) => "Henüz bir şey yok.", } } diff --git a/crates/izlek-web/src/layout.rs b/crates/izlek-web/src/layout.rs index 57435b7..cc63df9 100644 --- a/crates/izlek-web/src/layout.rs +++ b/crates/izlek-web/src/layout.rs @@ -133,10 +133,11 @@ pub async fn user_menu(cx: &Cx, me: &crate::detail::Me, lang: Lang) -> Result { } } -/// The five signed-in pages, as the topbar nav links between them. +/// The signed-in pages, as the topbar nav links between them. #[derive(Clone, Copy, PartialEq)] pub enum NavPage { Board, + Feed, Rules, Logs, Tags, @@ -144,11 +145,19 @@ pub enum NavPage { } impl NavPage { - const ALL: [Self; 5] = [Self::Board, Self::Rules, Self::Logs, Self::Tags, Self::Settings]; + const ALL: [Self; 6] = [ + Self::Board, + Self::Feed, + Self::Rules, + Self::Logs, + Self::Tags, + Self::Settings, + ]; fn href(self) -> &'static str { match self { Self::Board => "/", + Self::Feed => "/feed", Self::Rules => "/rules", Self::Logs => "/logs", Self::Tags => "/tags", @@ -159,6 +168,7 @@ impl NavPage { fn label(self) -> Key { match self { Self::Board => Key::NavBoard, + Self::Feed => Key::NavFeed, Self::Rules => Key::NavMailRules, Self::Logs => Key::NavLogs, Self::Tags => Key::NavTags, @@ -167,11 +177,21 @@ impl NavPage { } } -/// The topbar's page nav, shared by every signed-in page: the five pages -/// with the current one marked, the admin-only ones (rules, logs, tags) shown -/// only to roles that can administer. Plain ``s — the soft-nav forwarder -/// swaps them like any same-origin link, so `data-hard` stays off. +/// The topbar's page nav, shared by every signed-in page: the pages with the +/// current one marked, the admin-only ones (rules, logs, tags) shown only to +/// roles that can administer. The feed link carries the unread count — how +/// many lines have landed since the person last read their feed — as a chip +/// that disappears at zero. Plain ``s — the soft-nav forwarder swaps them +/// like any same-origin link, so `data-hard` stays off. pub async fn topbar_nav(cx: &Cx, active: NavPage, role: izlek_core::Role, lang: Lang) -> Result { + let unread = match current_user(cx).await { + Ok(Some(me)) => crate::server::accounts(cx) + .store() + .count_feed_unseen(&me.id) + .await + .unwrap_or(0), + _ => 0, + }; view! { cx =>