From d7960b3e0d2a975518b58c3dc70438fa56bb596f Mon Sep 17 00:00:00 2001 From: Stcant <102866802+Stcant@users.noreply.github.com> Date: Wed, 14 Oct 2026 07:06:46 +0200 Subject: [PATCH 1/3] feat: add authenticated persistent company workspace --- .github/workflows/ci.yml | 34 +- Cargo.lock | 85 ++++ Cargo.toml | 9 +- crates/hph-core/src/lib.rs | 8 + harness/PROJECT_STATE.md | 16 + migrations/0002_workspace.sql | 54 +++ public/assets/fonts.css | 1 + public/assets/hph-mark.svg | 1 + scripts/browser-smoke.mjs | 67 +++ src/app.rs | 6 +- src/auth.rs | 196 +++++++++ src/database.rs | 13 + src/lib.rs | 9 + src/main.rs | 39 +- src/module_repository.rs | 2 + src/operations.rs | 663 ++++++++++++++++++++++++++++++ src/workspace_tests.rs | 355 ++++++++++++++++ src/workspace_ui.rs | 738 ++++++++++++++++++++++++++++++++++ src/workspace_web.rs | 400 ++++++++++++++++++ style/workspace.css | 6 + 20 files changed, 2696 insertions(+), 6 deletions(-) create mode 100644 migrations/0002_workspace.sql create mode 100644 public/assets/fonts.css create mode 100644 public/assets/hph-mark.svg create mode 100644 scripts/browser-smoke.mjs create mode 100644 src/auth.rs create mode 100644 src/operations.rs create mode 100644 src/workspace_tests.rs create mode 100644 src/workspace_ui.rs create mode 100644 src/workspace_web.rs create mode 100644 style/workspace.css diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 52280a2..40ddafd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -67,6 +67,38 @@ jobs: HPH_TEST_DATABASE_URL="$HPH_TEST_ADMIN_DATABASE_URL" cargo test --features ssr database::tests::sqlx_pool_migrates_and_scopes_tenant_context --locked docker run --rm --network host -e PGPASSWORD=postgres postgres:18 \ psql -h 127.0.0.1 -U postgres -d hph_app_test -v ON_ERROR_STOP=1 \ - -c "GRANT USAGE ON SCHEMA public TO hph_runtime; GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO hph_runtime;" + -c "GRANT USAGE ON SCHEMA public TO hph_runtime; GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO hph_runtime; GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO hph_runtime;" cargo test --features ssr module_repository::tests::company_module_selection_is_tenant_scoped_and_admin_only --locked cargo test --features ssr membership_repository::tests::actor_resolution_uses_only_active_membership_in_selected_tenant --locked + cargo test --features ssr workspace_web::tests::operational_http_workflow_is_persistent_scoped_and_authorized --locked + - name: Build operational workspace and bootstrap synthetic portfolio company + env: + HPH_MIGRATION_DATABASE_URL: postgres://postgres:postgres@127.0.0.1:5432/hph_app_test + HPH_BOOTSTRAP_EMAIL: portfolio@example.test + HPH_BOOTSTRAP_PASSWORD: portfolio test password + HPH_BOOTSTRAP_NAME: Alex Morgan + HPH_BOOTSTRAP_COMPANY: Studio Aurora + HPH_BOOTSTRAP_SLUG: studio-aurora + run: | + cargo build --features ssr --locked + target/debug/hph --bootstrap + - name: Browser workflow and real portfolio captures + env: + HPH_DATABASE_URL: postgres://hph_runtime:hph_runtime@127.0.0.1:5432/hph_app_test + HPH_ORIGIN: http://127.0.0.1:3000 + run: | + npm install --no-save --package-lock=false playwright@1.62.1 + npx playwright install --with-deps chromium + target/debug/hph > /tmp/hph.log 2>&1 & + HPH_PID=$! + trap 'kill "$HPH_PID"' EXIT + for attempt in $(seq 1 30); do + if curl --fail --silent http://127.0.0.1:3000/health; then break; fi + sleep 1 + done + node scripts/browser-smoke.mjs + - uses: actions/upload-artifact@v4 + if: always() + with: + name: workspace-browser-captures + path: artifacts/browser diff --git a/Cargo.lock b/Cargo.lock index f44c07d..49f92b5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -44,6 +44,18 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures 0.2.17", + "password-hash", +] + [[package]] name = "async-lock" version = "3.4.2" @@ -190,6 +202,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bitflags" version = "2.13.2" @@ -199,6 +217,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest 0.10.7", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -281,6 +308,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "chrono-tz" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3" +dependencies = [ + "chrono", + "phf", +] + [[package]] name = "cmov" version = "0.5.4" @@ -500,6 +537,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", "crypto-common 0.1.7", + "subtle", ] [[package]] @@ -899,9 +937,12 @@ dependencies = [ name = "hph" version = "0.1.0" dependencies = [ + "argon2", "axum", "chrono", + "chrono-tz", "console_error_panic_hook", + "getrandom 0.3.4", "hph-core", "http-body-util", "leptos", @@ -910,10 +951,13 @@ dependencies = [ "leptos_router", "serde", "serde_json", + "serde_urlencoded", + "sha2 0.10.9", "sqlx", "tokio", "toml 0.9.12+spec-1.1.0", "tower", + "tower-http", "wasm-bindgen", ] @@ -1651,6 +1695,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "paste" version = "1.0.15" @@ -1669,6 +1724,24 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "phf" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7" +dependencies = [ + "phf_shared", +] + +[[package]] +name = "phf_shared" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project" version = "1.1.13" @@ -1835,6 +1908,12 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + [[package]] name = "rand_core" version = "0.9.5" @@ -2277,6 +2356,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + [[package]] name = "slab" version = "0.4.12" diff --git a/Cargo.toml b/Cargo.toml index c892492..1dc8ed5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,11 +26,18 @@ sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", wasm-bindgen = { version = "0.2", optional = true } console_error_panic_hook = { version = "0.1", optional = true } +tower-http = { version = "0.6", features = ["fs"], optional = true } +argon2 = { version = "0.5", optional = true } +sha2 = { version = "0.10", optional = true } +getrandom = { version = "0.3", optional = true } +chrono-tz = { version = "0.10", optional = true } + [features] hydrate = ["leptos/hydrate", "dep:wasm-bindgen", "dep:console_error_panic_hook"] -ssr = ["dep:axum", "dep:leptos_axum", "dep:tokio", "dep:chrono", "dep:toml", "dep:sqlx", "leptos/ssr", "leptos_meta/ssr", "leptos_router/ssr"] +ssr = ["dep:tower-http", "dep:argon2", "dep:sha2", "dep:getrandom", "dep:chrono-tz", "dep:axum", "dep:leptos_axum", "dep:tokio", "dep:chrono", "dep:toml", "dep:sqlx", "leptos/ssr", "leptos_meta/ssr", "leptos_router/ssr"] [dev-dependencies] +serde_urlencoded = "0.7" tower = { version = "0.5", features = ["util"] } http-body-util = "0.1" serde_json = "1" diff --git a/crates/hph-core/src/lib.rs b/crates/hph-core/src/lib.rs index 9eba3f3..6b3ea79 100644 --- a/crates/hph-core/src/lib.rs +++ b/crates/hph-core/src/lib.rs @@ -7,6 +7,7 @@ pub enum ModuleId { People, Attendance, Reports, + Notes, } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -19,6 +20,13 @@ pub struct ModuleDefinition { pub fn catalog() -> Vec { vec![ + ModuleDefinition { + id: ModuleId::Notes, + name: "Team notes".into(), + description: "A shared company noticeboard. A small example of a complete module." + .into(), + dependencies: vec![ModuleId::People], + }, ModuleDefinition { id: ModuleId::People, name: "People".into(), diff --git a/harness/PROJECT_STATE.md b/harness/PROJECT_STATE.md index 2d06823..a4ad295 100644 --- a/harness/PROJECT_STATE.md +++ b/harness/PROJECT_STATE.md @@ -1,5 +1,21 @@ # HPH — Project state +## Active implementation — 2026-10-13 + +Status: in_progress on `feat/company-workspace`, based on `d6ee299822a8e0efe1f543406a25d317e82afe95`. User authorized all proposed features and PR/merge work. A clean local Git checkout and Rust toolchain are now available. + +| Deliverable | Acceptance / verification | Status | +| --- | --- | --- | +| Account login, logout and company selection | Opaque expiring DB sessions; Argon2 passwords; CSRF/origin checks; revoked membership denied; HTTP and DB tests | in_progress | +| Persistent people and time entries | Admin create/edit/deactivate/roles; employee self-clock; idempotent writes; invalid sequences rejected; survives restart | pending | +| Attendance and corrections | Company timezone; daily/monthly closed intervals split at midnight; reason and immutable audit; valid corrected sequence | pending | +| Template customization | Company name, theme, accent and safe local logo; persisted module selection; working Notes module example | pending | +| Browser/portfolio and documentation | Desktop/mobile workflow tests; real screenshot and GIF; English docs; configured CI; PR merge only after gates pass | pending | + +Design: keep the existing explicit loopback demo. Add an authenticated server-rendered Rust workspace with standard HTML forms, PostgreSQL transactions and per-operation membership checks. No external identity service, email delivery or deployment is required. All requested scope remains active; this plan does not mark later deliverables complete. + +Next action: implement and verify authenticated operational workspace, then complete all rows above. Historical evidence below describes previous increments only. + ## Goal and phase Build a reusable modular business management application with a Rust frontend/backend and a carefully designed interface. The preference for Rust on the frontend supersedes the open frontend choice from the kickoff. diff --git a/migrations/0002_workspace.sql b/migrations/0002_workspace.sql new file mode 100644 index 0000000..b7ae345 --- /dev/null +++ b/migrations/0002_workspace.sql @@ -0,0 +1,54 @@ +-- Additive migration: existing demo/schema data is preserved. +ALTER TABLE hph_people ADD COLUMN active boolean NOT NULL DEFAULT true; +ALTER TABLE hph_organizations ADD COLUMN logo_path text NOT NULL DEFAULT ''; +ALTER TABLE hph_organizations ADD COLUMN accent text NOT NULL DEFAULT '#173d32' + CHECK (accent ~ '^#[0-9a-fA-F]{6}$'); + +CREATE TABLE hph_credentials ( + user_id uuid PRIMARY KEY REFERENCES hph_users(id) ON DELETE CASCADE, + password_hash text NOT NULL, + failed_attempts integer NOT NULL DEFAULT 0, + locked_until timestamptz, + updated_at timestamptz NOT NULL DEFAULT now() +); +CREATE TABLE hph_sessions ( + token_hash text PRIMARY KEY, + user_id uuid NOT NULL REFERENCES hph_users(id) ON DELETE CASCADE, + organization_id uuid REFERENCES hph_organizations(id) ON DELETE CASCADE, + expires_at timestamptz NOT NULL DEFAULT now() + interval '8 hours' +); +CREATE INDEX hph_sessions_expiry_idx ON hph_sessions(expires_at); +CREATE TABLE hph_audit ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + organization_id uuid NOT NULL REFERENCES hph_organizations(id) ON DELETE CASCADE, + actor_user_id uuid NOT NULL REFERENCES hph_users(id), + action text NOT NULL, + detail text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); +ALTER TABLE hph_audit ENABLE ROW LEVEL SECURITY; +ALTER TABLE hph_audit FORCE ROW LEVEL SECURITY; +CREATE POLICY tenant_scope ON hph_audit + USING (organization_id = hph_current_tenant_id()) + WITH CHECK (organization_id = hph_current_tenant_id()); +-- Audit rows are append-only, including for runtime roles with broad table grants. +CREATE FUNCTION hph_audit_immutable() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN RAISE EXCEPTION 'Audit records are immutable'; END $$; +CREATE TRIGGER hph_audit_immutable BEFORE UPDATE OR DELETE ON hph_audit + FOR EACH ROW EXECUTE FUNCTION hph_audit_immutable(); + +ALTER TABLE hph_company_modules DROP CONSTRAINT hph_company_modules_module_id_check; +ALTER TABLE hph_company_modules ADD CONSTRAINT hph_company_modules_module_id_check + CHECK (module_id IN ('people', 'attendance', 'reports', 'notes')); +CREATE TABLE hph_notes ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + organization_id uuid NOT NULL REFERENCES hph_organizations(id) ON DELETE CASCADE, + author_user_id uuid NOT NULL REFERENCES hph_users(id), + body text NOT NULL CHECK (length(trim(body)) BETWEEN 1 AND 2000), + created_at timestamptz NOT NULL DEFAULT now() +); +ALTER TABLE hph_notes ENABLE ROW LEVEL SECURITY; +ALTER TABLE hph_notes FORCE ROW LEVEL SECURITY; +CREATE POLICY tenant_scope ON hph_notes + USING (organization_id = hph_current_tenant_id()) + WITH CHECK (organization_id = hph_current_tenant_id()); diff --git a/public/assets/fonts.css b/public/assets/fonts.css new file mode 100644 index 0000000..ffe106c --- /dev/null +++ b/public/assets/fonts.css @@ -0,0 +1 @@ +/* System fonts keep the workspace independent of external font services. */ diff --git a/public/assets/hph-mark.svg b/public/assets/hph-mark.svg new file mode 100644 index 0000000..7a8b6d5 --- /dev/null +++ b/public/assets/hph-mark.svg @@ -0,0 +1 @@ +h diff --git a/scripts/browser-smoke.mjs b/scripts/browser-smoke.mjs new file mode 100644 index 0000000..782cb44 --- /dev/null +++ b/scripts/browser-smoke.mjs @@ -0,0 +1,67 @@ +// Development/CI only: the application itself does not require Node or JavaScript. +import { chromium } from 'playwright'; +import { mkdir } from 'node:fs/promises'; +import assert from 'node:assert/strict'; +const output = process.env.HPH_SCREENSHOT_DIR || 'artifacts/browser'; +await mkdir(output, { recursive: true }); +const browser = await chromium.launch({ headless: true }); +const context = await browser.newContext({ viewport: { width: 1440, height: 1050 } }); +const page = await context.newPage(); +const errors = []; +page.on('pageerror', e => errors.push(e.message)); +const base = process.env.HPH_ORIGIN || 'http://127.0.0.1:3000'; +const visit = async tab => { await page.goto(`${base}/app?tab=${tab}`); await page.locator('main h1').waitFor(); }; +const clickSubmit = async (locator) => { await Promise.all([page.waitForNavigation(), locator.click()]); assert(!await page.getByRole('alert').count(), await page.title()); }; +try { + await page.goto(`${base}/login`); + await page.screenshot({ path: `${output}/login.png`, fullPage: true }); + await page.getByLabel('Work email').fill('portfolio@example.test'); + await page.getByLabel('Password', { exact: true }).fill('portfolio test password'); + await clickSubmit(page.getByRole('button', { name: 'Sign in' })); + await clickSubmit(page.getByRole('button', { name: /Studio Aurora/ })); + await visit('people'); + for (const [name, number, job, department] of [['Elena Conti','E001','People manager','People & Culture'],['Marco Riva','E002','Product designer','Design'],['Sofia Bianchi','E003','Software engineer','Engineering']]) { + await page.getByLabel('Full name').fill(name); + await page.getByLabel('Employee number').fill(number); + await page.getByLabel('Department', { exact: true }).fill(department); + await page.getByLabel('Job title').fill(job); + await clickSubmit(page.getByRole('button', { name: 'Save employee' })); + } + await visit('overview'); + await page.screenshot({ path: `${output}/workspace-desktop.png`, fullPage: true }); + await visit('attendance'); + await page.screenshot({ path: `${output}/clock-0.png` }); + for (const [i,name] of ['Clock in','Start break','End break','Clock out'].entries()) { + await page.waitForTimeout(1100); // Server records one event per second per employee. + await clickSubmit(page.getByRole('button', { name, exact: true })); + await page.screenshot({ path: `${output}/clock-${i+1}.png` }); + } + await page.reload(); + assert.equal(await page.locator('tbody tr').count(), 4); + await visit('settings'); + await page.getByLabel('Team notes', { exact: false }).check(); + await clickSubmit(page.getByRole('button', { name: 'Save modules' })); + await visit('notes'); + await page.getByLabel('Your note').fill('Welcome to Studio Aurora. A little less admin, a little more room for people.'); + await clickSubmit(page.getByRole('button', { name: 'Post note' })); + assert(await page.getByText('Welcome to Studio Aurora.', { exact: false }).count()); + await visit('settings'); + await page.getByLabel('Theme', { exact: true }).selectOption('indigo'); + await page.getByLabel('Accent color').fill('#423c69'); + await clickSubmit(page.getByRole('button', { name: 'Save appearance' })); + await visit('overview'); + await page.screenshot({ path: `${output}/workspace-indigo.png`, fullPage: true }); + await page.setViewportSize({ width: 390, height: 844 }); + for (const tab of ['overview','people','attendance','reports','settings','notes','account']) { + await visit(tab); + const fits = await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth); + assert(fits, `Horizontal overflow on ${tab}`); + } + await visit('overview'); + await page.screenshot({ path: `${output}/workspace-mobile.png`, fullPage: true }); + await clickSubmit(page.getByRole('button', { name: 'Sign out', exact: true })); + await page.goto(`${base}/app`); + assert(page.url().endsWith('/login'), 'Logout must revoke the session'); + assert.deepEqual(errors, []); + console.log('PASS: desktop/mobile login, employee creation, clock/break cycle, persistence, modules, notes, themes and logout.'); +} finally { await browser.close(); } diff --git a/src/app.rs b/src/app.rs index ce64010..a1df0bf 100644 --- a/src/app.rs +++ b/src/app.rs @@ -217,7 +217,7 @@ fn Overview( - +

"Your team"

"People at the heart of every day."

{people.then(|| view! { })}
{if people { view! { }.into_any() } else { view! {

"Enable the People module to get started."

}.into_any() }}
@@ -306,8 +306,8 @@ fn Modules( let cards = data.catalog.into_iter().map(|definition| { let id = definition.id; let enabled = data.workspace.modules.contains(id); - let dependency = match id { ModuleId::People => "No dependencies", ModuleId::Attendance => "Requires People", ModuleId::Reports => "Requires Time and attendance" }; - let icon = match id { ModuleId::People => "people", ModuleId::Attendance => "clock", ModuleId::Reports => "chart" }; + let dependency = match id { ModuleId::Notes => "Requires People", ModuleId::People => "No dependencies", ModuleId::Attendance => "Requires People", ModuleId::Reports => "Requires Time and attendance" }; + let icon = match id { ModuleId::Notes => "modules", ModuleId::People => "people", ModuleId::Attendance => "clock", ModuleId::Reports => "chart" }; let label = format!("{} {}", if enabled { "Disable" } else { "Enable" }, definition.name); view! {
{if enabled { "Active" } else { "Available" }}

{definition.name}

{definition.description}

{dependency}
} }).collect_view(); diff --git a/src/auth.rs b/src/auth.rs new file mode 100644 index 0000000..e42dd7b --- /dev/null +++ b/src/auth.rs @@ -0,0 +1,196 @@ +//! Local account authentication. Passwords and opaque session tokens never enter HTML/logs. +use crate::{ + database::Database, + operations::{AppError, AppResult}, +}; +use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier, password_hash::SaltString}; +use sha2::{Digest, Sha256}; +use sqlx::types::Uuid; + +#[derive(Clone)] +pub struct Session { + pub hash: String, + pub user: Uuid, + pub tenant: Option, + pub csrf: String, +} + +pub fn random_token() -> AppResult { + let mut bytes = [0u8; 32]; + getrandom::fill(&mut bytes).map_err(|_| AppError::Internal)?; + Ok(bytes.iter().map(|b| format!("{b:02x}")).collect()) +} +pub fn digest(value: &str) -> String { + format!("{:x}", Sha256::digest(value.as_bytes())) +} + +pub async fn password_hash(password: String) -> AppResult { + if !(12..=128).contains(&password.len()) { + return Err(AppError::Invalid( + "Use a password between 12 and 128 bytes.", + )); + } + tokio::task::spawn_blocking(move || { + let mut salt = [0u8; 16]; + getrandom::fill(&mut salt).map_err(|_| AppError::Internal)?; + let salt = SaltString::encode_b64(&salt).map_err(|_| AppError::Internal)?; + Argon2::default() + .hash_password(password.as_bytes(), &salt) + .map(|hash| hash.to_string()) + .map_err(|_| AppError::Internal) + }) + .await + .map_err(|_| AppError::Internal)? +} + +pub async fn verify(password: String, hash: String) -> bool { + tokio::task::spawn_blocking(move || { + PasswordHash::new(&hash).ok().is_some_and(|hash| { + Argon2::default() + .verify_password(password.as_bytes(), &hash) + .is_ok() + }) + }) + .await + .unwrap_or(false) +} + +pub async fn login(db: &Database, email: &str, password: String, dummy: &str) -> AppResult { + if email.len() > 254 || password.len() > 128 { + return Err(AppError::Unauthorized); + } + let mut tx = db.pool().begin().await?; + let row: Option<(Uuid, String, bool)> = sqlx::query_as( + "SELECT u.id, c.password_hash, COALESCE(c.locked_until > now(), false) \ + FROM hph_users u JOIN hph_credentials c ON c.user_id=u.id \ + WHERE lower(u.email)=$1 FOR UPDATE OF c", + ) + .bind(email.trim().to_lowercase()) + .fetch_optional(&mut *tx) + .await?; + let hash = row + .as_ref() + .map(|r| r.1.as_str()) + .unwrap_or(dummy) + .to_owned(); + let valid = verify(password, hash).await; + let Some((user, _, locked)) = row else { + return Err(AppError::Unauthorized); + }; + if locked || !valid { + if !locked { + sqlx::query("UPDATE hph_credentials SET failed_attempts=CASE WHEN locked_until <= now() THEN 1 ELSE failed_attempts+1 END, locked_until=CASE WHEN failed_attempts >= 4 AND (locked_until IS NULL OR locked_until > now()) THEN now()+interval '15 minutes' ELSE NULL END WHERE user_id=$1") + .bind(user).execute(&mut *tx).await?; + } + tx.commit().await?; + return Err(AppError::Unauthorized); + } + sqlx::query("UPDATE hph_credentials SET failed_attempts=0, locked_until=NULL WHERE user_id=$1") + .bind(user) + .execute(&mut *tx) + .await?; + sqlx::query("DELETE FROM hph_sessions WHERE expires_at <= now()") + .execute(&mut *tx) + .await?; + let token = random_token()?; + sqlx::query("INSERT INTO hph_sessions (token_hash,user_id) VALUES ($1,$2)") + .bind(digest(&token)) + .bind(user) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(token) +} + +pub async fn session(db: &Database, token: &str) -> AppResult { + if token.len() != 64 || !token.bytes().all(|c| c.is_ascii_hexdigit()) { + return Err(AppError::Unauthorized); + } + let hash = digest(token); + let row: Option<(Uuid, Option)> = sqlx::query_as( + "SELECT user_id, organization_id FROM hph_sessions WHERE token_hash=$1 AND expires_at>now()") + .bind(&hash).fetch_optional(db.pool()).await?; + let (user, tenant) = row.ok_or(AppError::Unauthorized)?; + Ok(Session { + hash, + user, + tenant, + csrf: digest(&format!( + "csrf:{token}:{}", + tenant.map(|id| id.to_string()).unwrap_or_default() + )), + }) +} + +/// Administrative CLI bootstrap uses the separate migration connection, never a web route. +/// Existing users must prove their password before a second company can be added. +pub async fn bootstrap( + db: &Database, + email: String, + password: String, + name: String, + company: String, + slug: String, +) -> AppResult<()> { + crate::operations::validate_text(&name, 160)?; + crate::operations::validate_text(&company, 160)?; + crate::operations::validate_email(&email)?; + let hash = password_hash(password.clone()).await?; + let mut tx = db.pool().begin().await?; + let existing: Option<(Uuid, String)> = sqlx::query_as("SELECT u.id,c.password_hash FROM hph_users u JOIN hph_credentials c ON c.user_id=u.id WHERE lower(u.email)=lower($1) FOR UPDATE OF c") + .bind(&email).fetch_optional(&mut *tx).await?; + let user = if let Some((id, existing_hash)) = existing { + if !verify(password, existing_hash).await { + return Err(AppError::Unauthorized); + } + id + } else { + let id: Uuid = sqlx::query_scalar( + "INSERT INTO hph_users(email,display_name) VALUES(lower($1),$2) RETURNING id", + ) + .bind(&email) + .bind(&name) + .fetch_one(&mut *tx) + .await?; + sqlx::query("INSERT INTO hph_credentials(user_id,password_hash) VALUES($1,$2)") + .bind(id) + .bind(hash) + .execute(&mut *tx) + .await?; + id + }; + let tenant: Uuid = + sqlx::query_scalar("INSERT INTO hph_organizations(slug,name) VALUES($1,$2) RETURNING id") + .bind(slug) + .bind(company) + .fetch_one(&mut *tx) + .await?; + let person: Uuid=sqlx::query_scalar("INSERT INTO hph_people(organization_id,employee_number,display_name,email) VALUES($1,'ADMIN',$2,$3) RETURNING id") + .bind(tenant).bind(name).bind(email).fetch_one(&mut *tx).await?; + sqlx::query("INSERT INTO hph_memberships(organization_id,user_id,person_id,role) VALUES($1,$2,$3,'admin')") + .bind(tenant).bind(user).bind(person).execute(&mut *tx).await?; + for id in ["people", "attendance", "reports"] { + sqlx::query("INSERT INTO hph_company_modules(organization_id,module_id) VALUES($1,$2)") + .bind(tenant) + .bind(id) + .execute(&mut *tx) + .await?; + } + tx.commit().await?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[tokio::test] + async fn passwords_are_salted_and_verified() { + let password = "long test password!".to_owned(); + let first = password_hash(password.clone()).await.unwrap(); + let second = password_hash(password.clone()).await.unwrap(); + assert_ne!(first, second); + assert!(verify(password, first.clone()).await); + assert!(!verify("incorrect".into(), first).await); + assert!(password_hash("short".into()).await.is_err()); + } +} diff --git a/src/database.rs b/src/database.rs index 62189c9..fbf86c9 100644 --- a/src/database.rs +++ b/src/database.rs @@ -64,6 +64,19 @@ impl Database { Ok(transaction) } + /// Operational requests must never bypass company RLS or own application tables. + pub async fn verify_runtime_role(&self) -> Result<(), sqlx::Error> { + let unsafe_role: bool = sqlx::query_scalar( + "SELECT r.rolsuper OR r.rolbypassrls OR EXISTS (SELECT 1 FROM pg_tables WHERE schemaname='public' AND tablename LIKE 'hph_%' AND tableowner=current_user) FROM pg_roles r WHERE r.rolname=current_user" + ).fetch_one(&self.pool).await?; + if unsafe_role { + return Err(sqlx::Error::Protocol( + "Use a non-owner PostgreSQL runtime role without SUPERUSER or BYPASSRLS".into(), + )); + } + Ok(()) + } + pub(crate) fn pool(&self) -> &PgPool { &self.pool } diff --git a/src/lib.rs b/src/lib.rs index 1db9a99..5c01aed 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,3 +19,12 @@ pub fn hydrate() { console_error_panic_hook::set_once(); leptos::mount::hydrate_body(app::App); } + +#[cfg(feature = "ssr")] +pub mod auth; +#[cfg(feature = "ssr")] +pub mod operations; +#[cfg(feature = "ssr")] +pub mod workspace_ui; +#[cfg(feature = "ssr")] +pub mod workspace_web; diff --git a/src/main.rs b/src/main.rs index 019e2e4..c519c9f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,8 +8,45 @@ async fn main() -> Result<(), Box> { use leptos::prelude::*; use std::sync::Arc; + if std::env::args().any(|arg| arg == "--bootstrap") { + let db = Database::connect(&std::env::var("HPH_MIGRATION_DATABASE_URL")?).await?; + db.migrate().await?; + hph::auth::bootstrap( + &db, + std::env::var("HPH_BOOTSTRAP_EMAIL")?, + std::env::var("HPH_BOOTSTRAP_PASSWORD")?, + std::env::var("HPH_BOOTSTRAP_NAME")?, + std::env::var("HPH_BOOTSTRAP_COMPANY")?, + std::env::var("HPH_BOOTSTRAP_SLUG")?, + ) + .await?; + println!("Company and administrator created. Sign in to select the workspace."); + db.close().await; + return Ok(()); + } if std::env::var("HPH_DEMO").as_deref() != Ok("true") { - return Err("This version is a local demo. Set HPH_DEMO=true; authentication and production database integration are not implemented yet.".into()); + let database = Database::connect(&std::env::var("HPH_DATABASE_URL")?).await?; + database.verify_runtime_role().await?; + let origin = std::env::var("HPH_ORIGIN").unwrap_or_else(|_| "http://127.0.0.1:3000".into()); + let state = hph::workspace_web::WebState::new(database, origin).await?; + let address: std::net::SocketAddr = std::env::var("HPH_BIND") + .unwrap_or_else(|_| "127.0.0.1:3000".into()) + .parse()?; + if !state.secure && !address.ip().is_loopback() { + return Err("HTTP development mode must bind to loopback. Configure an HTTPS origin behind a TLS proxy for other deployments.".into()); + } + let app = hph::workspace_web::router(state); + let listener = tokio::net::TcpListener::bind(address).await?; + println!("HPH workspace · listening on {address}"); + axum::serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .with_graceful_shutdown(async { + let _ = tokio::signal::ctrl_c().await; + }) + .await?; + return Ok(()); } let options = get_configuration(None)?.leptos_options; let address = options.site_addr; diff --git a/src/module_repository.rs b/src/module_repository.rs index 7328a36..81552a8 100644 --- a/src/module_repository.rs +++ b/src/module_repository.rs @@ -103,6 +103,7 @@ impl<'a> CompanyModuleRepository<'a> { "people" => Ok(ModuleId::People), "attendance" => Ok(ModuleId::Attendance), "reports" => Ok(ModuleId::Reports), + "notes" => Ok(ModuleId::Notes), _ => Err(CompanyModuleError::InvalidConfiguration( "Unknown module ID.".into(), )), @@ -148,6 +149,7 @@ impl<'a> CompanyModuleRepository<'a> { (ModuleId::People, "people"), (ModuleId::Attendance, "attendance"), (ModuleId::Reports, "reports"), + (ModuleId::Notes, "notes"), ] { sqlx::query( "INSERT INTO hph_company_modules (organization_id, module_id, enabled) \ diff --git a/src/operations.rs b/src/operations.rs new file mode 100644 index 0000000..e30ba5c --- /dev/null +++ b/src/operations.rs @@ -0,0 +1,663 @@ +//! Company operations share one transaction and company lock, including authorization. +use crate::{auth::Session, database::Database}; +use chrono::{DateTime, Datelike, NaiveDate, TimeZone, Utc}; +use chrono_tz::Tz; +use hph_core::{ModuleId, ModuleSet, PunchKind, WorkState}; +use sqlx::{Postgres, Transaction, types::Uuid}; +use std::collections::BTreeMap; + +#[derive(Debug)] +pub enum AppError { + Unauthorized, + Forbidden, + Invalid(&'static str), + Internal, +} +pub type AppResult = Result; +impl From for AppError { + fn from(error: sqlx::Error) -> Self { + if let sqlx::Error::Database(ref e) = error { + if e.is_unique_violation() { + return Self::Invalid("That identifier or email is already in use."); + } + } + eprintln!( + "HPH database operation failed (details withheld): {}", + match error { + sqlx::Error::RowNotFound => "row not found", + _ => "database error", + } + ); + Self::Internal + } +} +impl std::fmt::Display for AppError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Unauthorized => "Sign in again. The credentials or session are not valid.", + Self::Forbidden => "You do not have permission for this operation.", + Self::Invalid(message) => message, + Self::Internal => "The operation could not be completed. Please try again.", + }) + } +} +impl std::error::Error for AppError {} + +pub fn validate_text(value: &str, max: usize) -> AppResult<()> { + if value.trim().is_empty() || value.len() > max || value.chars().any(|c| c.is_control()) { + return Err(AppError::Invalid( + "Check the required text fields and their length.", + )); + } + Ok(()) +} +pub fn validate_email(value: &str) -> AppResult<()> { + validate_text(value, 254)?; + if !value.contains('@') || value.contains(char::is_whitespace) { + return Err(AppError::Invalid("Enter a valid email address.")); + } + Ok(()) +} +pub fn uuid(value: &str) -> AppResult { + Uuid::parse_str(value).map_err(|_| AppError::Invalid("Invalid identifier.")) +} +pub fn new_id() -> AppResult { + let mut bytes = [0; 16]; + getrandom::fill(&mut bytes).map_err(|_| AppError::Internal)?; + Ok(Uuid::from_bytes(bytes)) +} +pub fn module_id(value: &str) -> AppResult { + match value { + "people" => Ok(ModuleId::People), + "attendance" => Ok(ModuleId::Attendance), + "reports" => Ok(ModuleId::Reports), + "notes" => Ok(ModuleId::Notes), + _ => Err(AppError::Invalid("Unknown module.")), + } +} +pub fn kind(value: &str) -> AppResult { + match value { + "in" => Ok(PunchKind::In), + "out" => Ok(PunchKind::Out), + "break_start" => Ok(PunchKind::BreakStart), + "break_end" => Ok(PunchKind::BreakEnd), + _ => Err(AppError::Invalid("Unknown time event.")), + } +} +pub fn kind_id(value: PunchKind) -> &'static str { + match value { + PunchKind::In => "in", + PunchKind::Out => "out", + PunchKind::BreakStart => "break_start", + PunchKind::BreakEnd => "break_end", + } +} + +pub struct Access { + pub tenant: Uuid, + pub person: Uuid, + pub admin: bool, +} +pub async fn begin<'a>( + db: &'a Database, + s: &Session, +) -> AppResult<(Transaction<'a, Postgres>, Access)> { + let tenant = s.tenant.ok_or(AppError::Forbidden)?; + let mut tx = db.begin_tenant_transaction(s.user, tenant).await?; + // Serializes mutations, membership revocations and reads into a consistent company snapshot. + let exists: Option = + sqlx::query_scalar("SELECT id FROM hph_organizations WHERE id=$1 FOR UPDATE") + .bind(tenant) + .fetch_optional(&mut *tx) + .await?; + if exists.is_none() { + return Err(AppError::Forbidden); + } + let member:Option<(Uuid,String)>=sqlx::query_as("SELECT m.person_id,m.role FROM hph_memberships m JOIN hph_people p ON p.organization_id=m.organization_id AND p.id=m.person_id WHERE m.organization_id=$1 AND m.user_id=$2 AND m.active AND p.active") + .bind(tenant).bind(s.user).fetch_optional(&mut *tx).await?; + let (person, role) = member.ok_or(AppError::Forbidden)?; + Ok(( + tx, + Access { + tenant, + person, + admin: role == "admin", + }, + )) +} +fn admin(a: &Access) -> AppResult<()> { + if a.admin { + Ok(()) + } else { + Err(AppError::Forbidden) + } +} +pub async fn modules(tx: &mut Transaction<'_, Postgres>, tenant: Uuid) -> AppResult { + let names: Vec = sqlx::query_scalar( + "SELECT module_id FROM hph_company_modules WHERE organization_id=$1 AND enabled", + ) + .bind(tenant) + .fetch_all(&mut **tx) + .await?; + ModuleSet::from_enabled( + names + .iter() + .map(|s| module_id(s)) + .collect::>>()?, + ) + .map_err(|_| AppError::Invalid("Invalid company module dependencies.")) +} +pub async fn require_module( + tx: &mut Transaction<'_, Postgres>, + tenant: Uuid, + id: ModuleId, +) -> AppResult<()> { + if modules(tx, tenant).await?.contains(id) { + Ok(()) + } else { + Err(AppError::Invalid("This module is disabled.")) + } +} +async fn audit( + tx: &mut Transaction<'_, Postgres>, + s: &Session, + action: &str, + detail: String, +) -> AppResult<()> { + sqlx::query( + "INSERT INTO hph_audit(organization_id,actor_user_id,action,detail) VALUES($1,$2,$3,$4)", + ) + .bind(s.tenant) + .bind(s.user) + .bind(action) + .bind(detail) + .execute(&mut **tx) + .await?; + Ok(()) +} + +pub struct Company { + pub name: String, + pub timezone: String, + pub theme: String, + pub logo: String, + pub accent: String, +} +pub struct Person { + pub id: Uuid, + pub number: String, + pub name: String, + pub email: String, + pub department: String, + pub job: String, + pub active: bool, + pub role: String, +} +#[derive(Clone)] +pub struct Event { + pub id: Uuid, + pub person: Uuid, + pub kind: PunchKind, + pub at: i64, +} +pub struct Snapshot { + pub company: Company, + pub access: Access, + pub modules: ModuleSet, + pub people: Vec, + pub events: Vec, + pub notes: Vec<(String, String)>, + pub audit: Vec<(String, String, String)>, +} + +pub async fn events(tx: &mut Transaction<'_, Postgres>, tenant: Uuid) -> AppResult> { + let rows:Vec<(Uuid,Uuid,String,i64)>=sqlx::query_as("SELECT id,person_id,kind,extract(epoch FROM occurred_at)::bigint FROM hph_attendance_events WHERE organization_id=$1 ORDER BY occurred_at,created_at,id") + .bind(tenant).fetch_all(&mut **tx).await?; + rows.into_iter() + .map(|(id, person, k, at)| { + Ok(Event { + id, + person, + kind: kind(&k)?, + at, + }) + }) + .collect() +} +pub fn sequence(events: &[Event], person: Uuid) -> AppResult { + events + .iter() + .filter(|e| e.person == person) + .try_fold(WorkState::Off, |state, e| { + state.next(e.kind).map_err(|_| { + AppError::Invalid( + "The change would create an invalid clock-in, break or clock-out sequence.", + ) + }) + }) +} +pub async fn snapshot(db: &Database, s: &Session) -> AppResult { + let (mut tx, access) = begin(db, s).await?; + let (name, timezone, theme, logo, accent): (String, String, String, String, String) = + sqlx::query_as( + "SELECT name,timezone,theme,logo_path,accent FROM hph_organizations WHERE id=$1", + ) + .bind(access.tenant) + .fetch_one(&mut *tx) + .await?; + let modules = modules(&mut tx, access.tenant).await?; + let rows:Vec<(Uuid,String,String,String,String,String,bool,String)>=sqlx::query_as("SELECT p.id,p.employee_number,p.display_name,COALESCE(p.email,''),COALESCE(p.department,''),COALESCE(p.job_title,''),p.active,COALESCE(m.role,'') FROM hph_people p LEFT JOIN hph_memberships m ON m.organization_id=p.organization_id AND m.person_id=p.id WHERE p.organization_id=$1 AND ($2 OR p.id=$3) ORDER BY p.display_name") + .bind(access.tenant).bind(access.admin).bind(access.person).fetch_all(&mut *tx).await?; + let people = rows + .into_iter() + .map( + |(id, number, name, email, department, job, active, role)| Person { + id, + number, + name, + email, + department, + job, + active, + role, + }, + ) + .collect(); + let events = events(&mut tx, access.tenant) + .await? + .into_iter() + .filter(|e| access.admin || e.person == access.person) + .collect(); + let notes = if modules.contains(ModuleId::Notes) { + sqlx::query_as("SELECT body,to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD HH24:MI') FROM hph_notes WHERE organization_id=$1 ORDER BY created_at DESC LIMIT 50").bind(access.tenant).fetch_all(&mut *tx).await? + } else { + vec![] + }; + let audit = if access.admin { + sqlx::query_as("SELECT action,detail,to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD HH24:MI:SS') FROM hph_audit WHERE organization_id=$1 ORDER BY id DESC LIMIT 50").bind(access.tenant).fetch_all(&mut *tx).await? + } else { + vec![] + }; + tx.commit().await?; + Ok(Snapshot { + company: Company { + name, + timezone, + theme, + logo, + accent, + }, + access, + modules, + people, + events, + notes, + audit, + }) +} + +pub async fn companies(db: &Database, s: &Session) -> AppResult> { + let mut tx = db.begin_tenant_transaction(s.user, Uuid::nil()).await?; + let ids: Vec = sqlx::query_scalar( + "SELECT organization_id FROM hph_memberships WHERE user_id=$1 AND active", + ) + .bind(s.user) + .fetch_all(&mut *tx) + .await?; + let mut result = vec![]; + for id in ids { + sqlx::query("SELECT set_config('hph.tenant_id',$1,true)") + .bind(id.to_string()) + .execute(&mut *tx) + .await?; + let name:Option=sqlx::query_scalar("SELECT o.name FROM hph_organizations o JOIN hph_memberships m ON m.organization_id=o.id JOIN hph_people p ON p.organization_id=m.organization_id AND p.id=m.person_id WHERE o.id=$1 AND m.user_id=$2 AND m.active AND p.active") + .bind(id).bind(s.user).fetch_optional(&mut *tx).await?; + if let Some(name) = name { + result.push((id, name)); + } + } + tx.commit().await?; + Ok(result) +} +pub async fn select_company(db: &Database, s: &Session, id: Uuid) -> AppResult<()> { + let mut selected = s.clone(); + selected.tenant = Some(id); + let (mut tx, _) = begin(db, &selected).await?; + sqlx::query("UPDATE hph_sessions SET organization_id=$1 WHERE token_hash=$2 AND user_id=$3 AND expires_at>now()") + .bind(id).bind(&s.hash).bind(s.user).execute(&mut *tx).await?; + tx.commit().await?; + Ok(()) +} + +pub struct PersonInput { + pub id: Option, + pub number: String, + pub name: String, + pub email: String, + pub department: String, + pub job: String, + pub active: bool, + pub role: String, + pub password: String, +} +pub async fn save_person(db: &Database, s: &Session, input: PersonInput) -> AppResult<()> { + validate_text(&input.number, 80)?; + validate_text(&input.name, 160)?; + if !input.email.is_empty() { + validate_email(&input.email)?; + } + if input.department.len() > 160 + || input.job.len() > 160 + || !["employee", "admin"].contains(&input.role.as_str()) + { + return Err(AppError::Invalid("Invalid employee details.")); + } + // Expensive hashing happens only after permission checks and outside the company lock. + let (tx, a) = begin(db, s).await?; + admin(&a)?; + drop(tx); + let hash = if input.id.is_none() && !input.password.is_empty() { + Some(crate::auth::password_hash(input.password).await?) + } else { + None + }; + let (mut tx, a) = begin(db, s).await?; + admin(&a)?; + require_module(&mut tx, a.tenant, ModuleId::People).await?; + let id = if let Some(id) = input.id { + if id == a.person && (!input.active || input.role != "admin") { + return Err(AppError::Invalid( + "You cannot deactivate or demote your own administrator account.", + )); + } + let all = events(&mut tx, a.tenant).await?; + if !input.active && sequence(&all, id)? != WorkState::Off { + return Err(AppError::Invalid( + "Close the employee's work session before deactivating them.", + )); + } + let n=sqlx::query("UPDATE hph_people SET employee_number=$1,display_name=$2,email=$3,department=$4,job_title=$5,active=$6 WHERE organization_id=$7 AND id=$8") + .bind(&input.number).bind(&input.name).bind(&input.email).bind(&input.department).bind(&input.job).bind(input.active).bind(a.tenant).bind(id).execute(&mut *tx).await?.rows_affected(); + if n != 1 { + return Err(AppError::Forbidden); + } + sqlx::query("UPDATE hph_memberships SET active=$1,role=$2 WHERE organization_id=$3 AND person_id=$4") + .bind(input.active).bind(&input.role).bind(a.tenant).bind(id).execute(&mut *tx).await?; + id + } else { + let id:Uuid=sqlx::query_scalar("INSERT INTO hph_people(organization_id,employee_number,display_name,email,department,job_title,active) VALUES($1,$2,$3,$4,$5,$6,$7) RETURNING id") + .bind(a.tenant).bind(&input.number).bind(&input.name).bind(&input.email).bind(&input.department).bind(&input.job).bind(input.active).fetch_one(&mut *tx).await?; + if let Some(hash) = hash { + validate_email(&input.email)?; + // Never overwrite an existing global user's password from a company admin screen. + let user: Uuid = sqlx::query_scalar( + "INSERT INTO hph_users(email,display_name) VALUES(lower($1),$2) RETURNING id", + ) + .bind(&input.email) + .bind(&input.name) + .fetch_one(&mut *tx) + .await?; + sqlx::query("INSERT INTO hph_credentials(user_id,password_hash) VALUES($1,$2)") + .bind(user) + .bind(hash) + .execute(&mut *tx) + .await?; + sqlx::query("INSERT INTO hph_memberships(organization_id,user_id,person_id,role,active) VALUES($1,$2,$3,$4,$5)") + .bind(a.tenant).bind(user).bind(id).bind(input.role).bind(input.active).execute(&mut *tx).await?; + } + id + }; + audit( + &mut tx, + s, + "person.saved", + format!("person={id}; active={}", input.active), + ) + .await?; + tx.commit().await?; + Ok(()) +} + +pub async fn punch(db: &Database, s: &Session, k: PunchKind, key: Uuid) -> AppResult<()> { + let (mut tx, a) = begin(db, s).await?; + require_module(&mut tx, a.tenant, ModuleId::Attendance).await?; + let existing:Option=sqlx::query_scalar("SELECT kind FROM hph_attendance_events WHERE organization_id=$1 AND person_id=$2 AND idempotency_key=$3") + .bind(a.tenant).bind(a.person).bind(key).fetch_optional(&mut *tx).await?; + if let Some(existing) = existing { + return if existing == kind_id(k) { + Ok(()) + } else { + Err(AppError::Invalid( + "This request key was already used for a different event.", + )) + }; + } + let all = events(&mut tx, a.tenant).await?; + sequence(&all, a.person)?.next(k).map_err(|_| { + AppError::Invalid("Refresh the page: this time entry is not valid for your current status.") + })?; + let at = Utc::now().timestamp(); + if all.iter().any(|e| e.person == a.person && e.at >= at) { + return Err(AppError::Invalid( + "Wait one second before recording the next event.", + )); + } + let id:Uuid=sqlx::query_scalar("INSERT INTO hph_attendance_events(organization_id,person_id,created_by_user_id,kind,occurred_at,idempotency_key) VALUES($1,$2,$3,$4,to_timestamp($5),$6) RETURNING id") + .bind(a.tenant).bind(a.person).bind(s.user).bind(kind_id(k)).bind(at as f64).bind(key).fetch_one(&mut *tx).await?; + audit( + &mut tx, + s, + "attendance.recorded", + format!("event={id}; person={}; kind={}", a.person, kind_id(k)), + ) + .await?; + tx.commit().await?; + Ok(()) +} + +/// Correct the timestamp of an existing event only; preserve original values in immutable audit. +pub async fn correct(db: &Database, s: &Session, id: Uuid, at: i64, reason: &str) -> AppResult<()> { + validate_text(reason, 500)?; + if at > Utc::now().timestamp() || at < 0 { + return Err(AppError::Invalid( + "The corrected time must be a valid past timestamp.", + )); + } + let (mut tx, a) = begin(db, s).await?; + admin(&a)?; + require_module(&mut tx, a.tenant, ModuleId::Attendance).await?; + let mut all = events(&mut tx, a.tenant).await?; + let e = all + .iter_mut() + .find(|e| e.id == id) + .ok_or(AppError::Forbidden)?; + let old = e.at; + let person = e.person; + e.at = at; + all.sort_by_key(|e| e.at); + if all + .iter() + .filter(|e| e.person == person && e.at == at) + .count() + > 1 + { + return Err(AppError::Invalid( + "Two events cannot have the same timestamp.", + )); + } + sequence(&all, person)?; + sqlx::query("UPDATE hph_attendance_events SET occurred_at=to_timestamp($1) WHERE organization_id=$2 AND id=$3") + .bind(at as f64).bind(a.tenant).bind(id).execute(&mut *tx).await?; + audit( + &mut tx, + s, + "attendance.corrected", + format!("event={id}; from={old}; to={at}; reason={reason}"), + ) + .await?; + tx.commit().await?; + Ok(()) +} +pub async fn set_modules(db: &Database, s: &Session, names: Vec) -> AppResult<()> { + let selected = ModuleSet::from_enabled( + names + .iter() + .map(|n| module_id(n)) + .collect::>>()?, + ) + .map_err(|_| AppError::Invalid("Enable each module's dependencies first."))?; + let (mut tx, a) = begin(db, s).await?; + admin(&a)?; + if !selected.contains(ModuleId::Attendance) { + let all = events(&mut tx, a.tenant).await?; + for e in &all { + if sequence(&all, e.person)? != WorkState::Off { + return Err(AppError::Invalid( + "Close all work sessions before disabling attendance.", + )); + } + } + } + for name in ["people", "attendance", "reports", "notes"] { + sqlx::query("INSERT INTO hph_company_modules(organization_id,module_id,enabled) VALUES($1,$2,$3) ON CONFLICT(organization_id,module_id) DO UPDATE SET enabled=excluded.enabled,updated_at=now()") + .bind(a.tenant).bind(name).bind(selected.contains(module_id(name)?)).execute(&mut *tx).await?; + } + audit(&mut tx, s, "modules.saved", names.join(", ")).await?; + tx.commit().await?; + Ok(()) +} +pub async fn settings(db: &Database, s: &Session, c: Company) -> AppResult<()> { + validate_text(&c.name, 160)?; + c.timezone + .parse::() + .map_err(|_| AppError::Invalid("Use an IANA timezone such as Europe/Rome."))?; + if !["sage", "indigo"].contains(&c.theme.as_str()) + || c.accent.len() != 7 + || !c.accent.starts_with('#') + || !c.accent[1..].bytes().all(|b| b.is_ascii_hexdigit()) + { + return Err(AppError::Invalid( + "Choose a supported theme and a six-digit hex color.", + )); + } + // Logos must be deployment-owned local assets, not remote trackers or executable data URLs. + if !c.logo.is_empty() + && (!c.logo.starts_with("/assets/") + || c.logo.contains("..") + || !c + .logo + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"/._-".contains(&b))) + { + return Err(AppError::Invalid("Use a local logo path under /assets/.")); + } + let (mut tx, a) = begin(db, s).await?; + admin(&a)?; + sqlx::query("UPDATE hph_organizations SET name=$1,timezone=$2,theme=$3,logo_path=$4,accent=$5 WHERE id=$6") + .bind(c.name).bind(c.timezone).bind(c.theme).bind(c.logo).bind(c.accent).bind(a.tenant).execute(&mut *tx).await?; + audit( + &mut tx, + s, + "company.settings", + "Updated company appearance and timezone".into(), + ) + .await?; + tx.commit().await?; + Ok(()) +} +pub async fn add_note(db: &Database, s: &Session, body: &str) -> AppResult<()> { + validate_text(body, 2000)?; + let (mut tx, a) = begin(db, s).await?; + require_module(&mut tx, a.tenant, ModuleId::Notes).await?; + sqlx::query("INSERT INTO hph_notes(organization_id,author_user_id,body) VALUES($1,$2,$3)") + .bind(a.tenant) + .bind(s.user) + .bind(body) + .execute(&mut *tx) + .await?; + audit(&mut tx, s, "note.created", "Company note added".into()).await?; + tx.commit().await?; + Ok(()) +} + +/// Split closed work intervals at local calendar boundaries, including DST and overnight work. +pub fn daily_totals( + events: &[Event], + person: Uuid, + tz: Tz, + month: NaiveDate, +) -> AppResult> { + let mut result = BTreeMap::new(); + let mut start = None; + for e in events.iter().filter(|e| e.person == person) { + match e.kind { + PunchKind::In | PunchKind::BreakEnd => start = Some(e.at), + PunchKind::BreakStart | PunchKind::Out => { + if let Some(mut from) = start.take() { + while from < e.at { + let date = DateTime::from_timestamp(from, 0) + .ok_or(AppError::Internal)? + .with_timezone(&tz) + .date_naive(); + let next = date.succ_opt().ok_or(AppError::Internal)?; + // A local midnight may not exist in historical timezone transitions. + let mut naive = next.and_hms_opt(0, 0, 0).ok_or(AppError::Internal)?; + let boundary = loop { + if let Some(t) = tz.from_local_datetime(&naive).earliest() { + break t.timestamp(); + } + naive += chrono::Duration::minutes(1); + }; + let until = e.at.min(boundary); + if date.year() == month.year() && date.month() == month.month() { + *result.entry(date).or_insert(0) += until - from; + } + from = until; + } + } + } + } + } + Ok(result) +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn reports_split_midnight_and_daylight_saving() { + let person = Uuid::nil(); + let tz: Tz = "Europe/Rome".parse().unwrap(); + let event = |kind, at: &str| Event { + id: Uuid::nil(), + person, + kind, + at: DateTime::parse_from_rfc3339(at).unwrap().timestamp(), + }; + let rows = vec![ + event(PunchKind::In, "2026-03-28T23:00:00+01:00"), + event(PunchKind::Out, "2026-03-29T04:00:00+02:00"), + ]; + let totals = daily_totals( + &rows, + person, + tz, + NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(), + ) + .unwrap(); + assert_eq!( + totals.values().copied().collect::>(), + vec![3600, 10800] + ); + let rows = vec![event(PunchKind::In, "2026-03-29T04:00:00+02:00")]; + assert!( + daily_totals( + &rows, + person, + tz, + NaiveDate::from_ymd_opt(2026, 3, 1).unwrap() + ) + .unwrap() + .is_empty() + ); + } +} diff --git a/src/workspace_tests.rs b/src/workspace_tests.rs new file mode 100644 index 0000000..8cda1f7 --- /dev/null +++ b/src/workspace_tests.rs @@ -0,0 +1,355 @@ +//! Integration tests run against a disposable PostgreSQL database and restricted runtime role. +use super::*; +use axum::{body::Body, http::Request}; +use http_body_util::BodyExt; +use tower::ServiceExt; + +async fn request( + app: Router, + path: &str, + body: Option<&[(&str, &str)]>, + cookie: Option<&str>, + origin: bool, +) -> (StatusCode, HeaderMap, String) { + let mut request = Request::builder().uri(path); + if let Some(cookie) = cookie { + request = request.header(header::COOKIE, cookie); + } + if origin { + request = request.header(header::ORIGIN, "http://127.0.0.1:3000"); + } + let encoded = body + .map(|f| serde_urlencoded::to_string(f).unwrap()) + .unwrap_or_default(); + if body.is_some() { + request = request + .method("POST") + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); + } + let response = app + .oneshot(request.body(Body::from(encoded)).unwrap()) + .await + .unwrap(); + let status = response.status(); + let headers = response.headers().clone(); + let bytes = response.into_body().collect().await.unwrap().to_bytes(); + (status, headers, String::from_utf8(bytes.to_vec()).unwrap()) +} +async fn sign_in(app: Router, email: &str) -> String { + let (status, headers, body) = request( + app, + "/auth/login", + Some(&[ + ("email", email), + ("password", "correct horse battery staple"), + ]), + None, + true, + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER, "{body}"); + let cookie = headers.get(header::SET_COOKIE).unwrap().to_str().unwrap(); + assert!(cookie.contains("HttpOnly; SameSite=Strict")); + cookie.split(';').next().unwrap().to_owned() +} +#[tokio::test] +async fn operational_http_workflow_is_persistent_scoped_and_authorized() { + let Ok(runtime_url) = std::env::var("HPH_TEST_DATABASE_URL") else { + return; + }; + let admin = Database::connect(&std::env::var("HPH_TEST_ADMIN_DATABASE_URL").unwrap()) + .await + .unwrap(); + admin.migrate().await.unwrap(); + let suffix = auth::random_token().unwrap(); + let suffix = &suffix[..12]; + let email = format!("owner-{suffix}@example.test"); + let company = format!("Workspace {suffix}"); + auth::bootstrap( + &admin, + email.clone(), + "correct horse battery staple".into(), + "Test Owner".into(), + company.clone(), + format!("workspace-{suffix}"), + ) + .await + .unwrap(); + let runtime = Database::connect(&runtime_url).await.unwrap(); + runtime.verify_runtime_role().await.unwrap(); + assert!(admin.verify_runtime_role().await.is_err()); + let state = WebState::new(runtime.clone(), "http://127.0.0.1:3000".into()) + .await + .unwrap(); + let app = router(state.clone()); + assert_eq!( + request(app.clone(), "/app", None, None, false).await.0, + StatusCode::SEE_OTHER + ); + assert_eq!( + request( + app.clone(), + "/auth/login", + Some(&[("email", &email), ("password", "wrong")]), + None, + false + ) + .await + .0, + StatusCode::FORBIDDEN + ); + let cookie = sign_in(app.clone(), &email).await; + let token = cookie.strip_prefix("hph_session=").unwrap(); + let mut session = auth::session(&runtime, token).await.unwrap(); + let companies = op::companies(&runtime, &session).await.unwrap(); + assert_eq!(companies.len(), 1); + let tenant = companies[0].0; + let fields = [ + ("company", tenant.to_string()), + ("csrf", session.csrf.clone()), + ]; + assert_eq!( + request( + app.clone(), + "/company/select", + Some(&[("company", &fields[0].1)]), + Some(&cookie), + true + ) + .await + .0, + StatusCode::FORBIDDEN + ); + let (status, _, body) = request( + app.clone(), + "/company/select", + Some(&[("company", &fields[0].1), ("csrf", &fields[1].1)]), + Some(&cookie), + true, + ) + .await; + assert_eq!(status, StatusCode::SEE_OTHER, "{body}"); + session = auth::session(&runtime, token).await.unwrap(); + let (_, _, html) = request(app.clone(), "/app", None, Some(&cookie), false).await; + assert!(html.contains(&company)); + assert!(html.contains("Test Owner")); + let key = op::new_id().unwrap(); + let (a, b) = tokio::join!( + op::punch(&runtime, &session, hph_core::PunchKind::In, key), + op::punch(&runtime, &session, hph_core::PunchKind::In, key) + ); + a.unwrap(); + b.unwrap(); + let data = op::snapshot(&runtime, &session).await.unwrap(); + assert_eq!(data.events.len(), 1); + assert!( + op::punch(&runtime, &session, hph_core::PunchKind::Out, key) + .await + .is_err() + ); + assert!( + op::punch( + &runtime, + &session, + hph_core::PunchKind::In, + op::new_id().unwrap() + ) + .await + .is_err() + ); + let event = data.events[0].id; + let at = chrono::Utc::now().timestamp() - 3600; + op::correct( + &runtime, + &session, + event, + at, + "Corrected forgotten start time", + ) + .await + .unwrap(); + assert!( + op::correct(&runtime, &session, event, at, "") + .await + .is_err() + ); + op::punch( + &runtime, + &session, + hph_core::PunchKind::Out, + op::new_id().unwrap(), + ) + .await + .unwrap(); + assert!( + op::correct( + &runtime, + &session, + event, + chrono::Utc::now().timestamp() + 100, + "Invalid future" + ) + .await + .is_err() + ); + let data = op::snapshot(&runtime, &session).await.unwrap(); + assert_eq!(data.events.len(), 2); + assert!( + data.audit + .iter() + .any(|r| r.0 == "attendance.corrected" && r.1.contains("Corrected forgotten")) + ); + // A new process/router reads the same data and existing session from PostgreSQL. + let app2 = router( + WebState::new( + Database::connect(&runtime_url).await.unwrap(), + "http://127.0.0.1:3000".into(), + ) + .await + .unwrap(), + ); + let (status, _, html) = request(app2, "/app?tab=attendance", None, Some(&cookie), false).await; + assert_eq!(status, StatusCode::OK); + assert!(html.contains("Clock out")); + assert!( + op::set_modules(&runtime, &session, vec!["reports".into()]) + .await + .is_err() + ); + op::set_modules(&runtime, &session, vec!["people".into(), "notes".into()]) + .await + .unwrap(); + assert!( + op::punch( + &runtime, + &session, + hph_core::PunchKind::In, + op::new_id().unwrap() + ) + .await + .is_err() + ); + op::add_note(&runtime, &session, "") + .await + .unwrap(); + let (_, _, html) = request(app.clone(), "/app?tab=notes", None, Some(&cookie), false).await; + assert!(html.contains("<script>")); + assert!(!html.contains("