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/README.md b/README.md index 8902c9f..6cd6c03 100644 --- a/README.md +++ b/README.md @@ -1,89 +1,81 @@ # HPH -**Work, in harmony.** A reusable foundation for modular business management software, with a Rust frontend and backend. +**Work, in harmony.** A modular business workspace built in Rust, and a personal project about learning by building. -HPH is currently a **runnable local demo**, not a system ready for real company data. The first working slice demonstrates the design, module composition and a server-validated time-tracking workflow. +HPH has two modes: an authenticated PostgreSQL workspace for local evaluation, and a separate in-memory Leptos demo. Company administrators choose their modules, appearance and timezone. Employees get their own account and attendance history. -## Stack +## What you can do -| Area | Choice | -| --- | --- | -| Interface | Leptos 0.8, server-side rendering and WebAssembly hydration | -| Server | Axum 0.8 + Tokio | -| Shared rules | Independent `hph-core` crate | -| Design | Responsive CSS with design tokens; sage and indigo themes, no remote fonts | -| Build | cargo-leptos 0.3.11, versioned Cargo.lock | -| Current persistence | PostgreSQL/SQLx infrastructure and repositories; the interface still uses demo memory | -| Next persistence step | Complete authentication and connect SQLx repositories to operational screens | +- Sign in, select a company and sign out with expiring server-side sessions. +- Create, edit and deactivate employees; assign employee or administrator roles. +- Record clock-ins, breaks and clock-outs. Changes survive application restarts. +- Review daily/monthly recorded time in the company timezone, including overnight shifts and daylight saving changes. +- Correct an event timestamp with a reason, retaining before/after values in append-only audit history. +- Customize company name, theme, accent color and a deployment-owned logo. +- Enable People, Attendance, Reports and Team notes independently, respecting dependencies. +- Use Team notes as a small, complete example when building your own module. -Application code is written in Rust. The browser also uses CSS and the small JavaScript loader generated by wasm-bindgen/Leptos: there is no separate React or TypeScript application to maintain. Node and npm are not required. English is the default language for the interface and repository documentation. +The operational interface is responsive, server-rendered Rust with standard HTML forms. It works without JavaScript. The original demo uses Leptos SSR and WebAssembly hydration. There is no separate React/TypeScript application and no Node requirement to run HPH. -## Run locally +## Run the persistent workspace -Prerequisites: Git and Rust installed through [rustup](https://rustup.rs). The `rust-toolchain.toml` file installs the required WebAssembly target and components. +You need Rust and Docker Compose. PostgreSQL runs locally; no cloud subscription is required. See [the complete setup guide](docs/WORKSPACE.md) for accounts, environment variables, upgrades and the restricted database role. ```bash git clone https://github.com/Stcant/HPH.git cd HPH -cargo install cargo-leptos --version 0.3.11 --locked -HPH_DEMO=true cargo leptos watch +# Set your own local database passwords; do not commit them. +export HPH_POSTGRES_PASSWORD='replace-with-a-local-owner-password' +export HPH_RUNTIME_PASSWORD='replace-with-a-different-runtime-password' +docker compose up -d ``` -In PowerShell, first set `$env:HPH_DEMO = "true"`, then run `cargo leptos watch`. +Follow [docs/WORKSPACE.md](docs/WORKSPACE.md) to bootstrap your first company and administrator, then run: -Open **http://127.0.0.1:3000**. The demo refuses to start without the explicit `HPH_DEMO=true` setting or on a non-loopback address. Do not expose it through a proxy, tunnel or public network: authentication is not available yet. PostgreSQL integration is optional and currently limited to connections, migrations and the health check; screens still use in-memory data. See [docs/DATABASE.md](docs/DATABASE.md). - -## Try the workflow - -1. From the dashboard, select **Clock in** for the demo profile, Elena Conti. -2. Open **Attendance** and select **Start break**, **End break**, then **Clock out**. Events reach the server and remain visible after refreshing the page. -3. Open **Your workspace**, enable **Reports** and inspect the recorded time for closed work intervals. Open intervals are excluded. -4. Try disabling **Time and attendance** while Reports is enabled: the server rejects the change because Reports depends on Attendance. Open work sessions also prevent Attendance from being disabled. -5. Disable Reports, close any open work sessions, then disable Attendance. The menu updates; enabling Attendance again restores access to the session's existing events. +```bash +# HPH_DATABASE_URL must use hph_runtime, never the migration owner. +cargo run --features ssr --locked +``` -All profiles are fictional. The demo's only actor is a fixed administrator selected by the server, not the browser. Module changes and events are shared between tabs using the same server instance and **are lost when the process restarts**. Other tabs do not update in real time: use the refresh button. +Open **http://127.0.0.1:3000**. Login and company selection lead to the persistent workspace. The server rejects superuser, BYPASSRLS and table-owner runtime connections. -## Customize the template +## Try the in-memory demo -Edit `hph.toml` and restart the server: +No database or account setup is required: -```toml -organization = "Your company" -theme = "sage" # sage | indigo -preset = "team" # essential | team | complete -# modules = ["people", "attendance"] # optional: overrides preset +```bash +cargo install cargo-leptos --version 0.3.11 --locked +HPH_DEMO=true cargo leptos watch ``` -The optional `modules` setting accepts the IDs `people`, `attendance` and `reports`. Modules must include their dependencies; HPH rejects invalid configurations at startup. When `modules` is omitted, the preset applies. Initial choices in `hph.toml` persist across restarts; changes made in the demo interface last only until the server restarts. +In PowerShell, set `$env:HPH_DEMO = "true"` first. Open **http://127.0.0.1:3000**. The demo requires loopback binding and uses fictional profiles. It must not be exposed through a public proxy or tunnel. Demo events and module changes are shared between browser tabs and reset when the server restarts. -| Preset | Modules | -| --- | --- | -| essential | People | -| team | People + Time and attendance | -| complete | People + Time and attendance + Reports | +`hph.toml` configures only this demo. Persistent companies are managed through the authenticated Workspace screen. -Modules are compiled Rust components. Company administrators can enable or disable them in the interface; adding a new feature requires code and a new build. This is not a marketplace of third-party plugins loaded at runtime. +## Modules and customization -Module configuration belongs to the company: each workspace is composed around its own processes. The demo keeps changes in memory; a PostgreSQL repository for company configuration exists, but it still needs to be connected to authenticated requests. +| Module | Dependency | Behavior | +| --- | --- | --- | +| People | None | Employee profiles, activation and roles | +| Time and attendance | People | Self-service clocking and administrator timestamp corrections | +| Reports | Attendance | Local daily/monthly totals from completed intervals | +| Team notes | People | Shared company noticeboard; operational mode only | -The foundation can be cloned or forked and customized. Reusable code does not automatically enable GitHub's **Template repository** setting. +Disabling a module hides and blocks its operations without deleting data. Attendance cannot be disabled while a work session is open. Module configuration is company-specific. Modules are compiled Rust code: adding a feature requires a build, while choosing existing modules requires only an administrator action. -## What works today +See [the module guide and Notes walkthrough](docs/MODULES.md). Company branding includes sage/indigo themes, a hex accent color and an optional local logo under `public/assets/`. English is the default language throughout the repository. + +## Stack -| Feature | Status | +| Area | Choice | | --- | --- | -| Responsive dashboard, screens and themes | Implemented; browser QA still pending | -| People directory | Read-only demo profiles | -| Modules and dependencies | Configuration enforced and verified on the server | -| Clock in / start break / end break / clock out | Sequence and timestamp validation on the server | -| Recorded-time summary | Closed intervals, excluding breaks, with second-level precision | -| Roles and company boundaries | Tested domain rules; no real authentication yet | -| PostgreSQL schema, module and membership repositories | Tested under RLS in CI; not connected to the screens | -| Multiple companies and real accounts in the application | Not implemented | -| Leave, shifts, corrections, audit and exports | Not implemented | -| Payroll, accounting and inventory | Outside the first version | - -Events use UTC timestamps displayed as `YYYY-MM-DD`. Summaries cover the demo session, not a contractual working day. There is no automatic calculation of overtime, accrued leave or payroll. +| Operational UI | Rust-generated HTML, standard forms, responsive CSS | +| Interactive demo | Leptos 0.8 SSR + WASM hydration | +| HTTP | Axum 0.8 + Tokio | +| Domain rules | Framework-independent `hph-core` crate | +| Persistence | PostgreSQL + SQLx, additive migrations and tenant RLS | +| Authentication | Argon2id password hashes, opaque hashed sessions, CSRF + Origin checks | +| Dates | UTC event storage, IANA company timezones via chrono-tz | ## Verification @@ -91,24 +83,35 @@ Events use UTC timestamps displayed as `YYYY-MM-DD`. Summaries cover the demo se cargo fmt --all --check cargo test --workspace --features ssr --locked cargo check --target wasm32-unknown-unknown --features hydrate --lib --locked -cargo leptos build ``` -Domain tests cover dependencies, permissions, foreign companies, duplicate clock-ins, reversed timestamps, breaks, disabling modules and data retention. HTTP tests exercise the real server functions through the Axum router and check SSR output. The PostgreSQL CI job applies RLS policies and tests SQLx pools, migrations, tenant context, module configuration and active membership lookup against a real PostgreSQL instance using a restricted runtime role. These are not browser tests and do not establish persistent business operations through the interface. +CI also runs migration/RLS tests and the real HTTP workflow against PostgreSQL using a non-owner runtime role. Browser checks cover desktop/mobile login, employee creation, clock/break flow, saved data, modules, notes, themes and logout. Node/Playwright are development-only tools for those browser checks. + +## Current boundaries + +This is an early portfolio application for local evaluation, not a production service certification. No public application deployment is included. + +- Company bootstrap is an operator CLI action. New employee accounts can be created by an administrator; email invitations, password recovery, MFA and OIDC are not implemented. +- Existing global accounts are never overwritten by company administrators. The CLI can add another company to an existing owner account only after verifying its password. +- Corrections currently change the timestamp of an existing event; adding/removing missed events and approval workflows are future work. +- Reports count completed intervals, excluding breaks and open intervals. No overtime, leave accrual, payroll or contractual rounding is applied. Display rounds down to whole minutes; event timestamps retain seconds. +- Reads currently load company history into memory; pagination and retention controls are needed before large installations. +- The audit UI shows the latest 50 changes; records remain in the database. Refresh other tabs to see changes. +- Production operation additionally requires deployment-specific TLS, backups, monitoring, account recovery and security review. -## Structure +Leave, shifts, documents, expenses and projects remain future modules. Payroll, accounting and inventory are outside this increment. The GitHub Template repository setting is unchanged; you can still clone or fork the project. -- `crates/hph-core/`: modules, roles, time-tracking rules, serialized contracts and tests. -- `src/app.rs`: Leptos components and screens. -- `src/api.rs`: server functions; the client does not supply the acting identity. -- `src/server.rs`: demo configuration and state, router and HTTP tests. -- `src/database.rs`: SQLx PostgreSQL pool, migrations, health check and tenant-scoped transactions. -- `src/module_repository.rs` and `src/membership_repository.rs`: company module configuration and active membership lookup. -- `style/main.css`: layout, tokens, themes and mobile styles. -- `docs/MODULES.md`: the module extension contract. -- `harness/PROJECT_MAP.md` and `harness/PROJECT_STATE.md`: architecture and project checkpoint. +## Code map -The next functional increment is **authentication and sessions**. The SQLx repository can already resolve an active membership for a selected company, but the screens do not use it yet. Until authentication, authorization and application persistence are integrated, HPH remains a local demo and must not host real company data. +- `crates/hph-core/`: module dependencies, permissions and time-tracking state machine. +- `src/auth.rs`: password hashing, login, session validation and CLI bootstrap. +- `src/operations.rs`: transactional company operations, permissions and date summaries. +- `src/workspace_web.rs`: authenticated HTTP routes, forms and request protections. +- `src/workspace_ui.rs`, `style/workspace.css`: operational screens and design. +- `src/workspace_tests.rs`, `scripts/browser-smoke.mjs`: database/HTTP and browser workflows. +- `src/app.rs`, `src/api.rs`, `src/server.rs`: separate Leptos demo. +- `src/database.rs`, `migrations/`: PostgreSQL infrastructure and schema. +- `harness/PROJECT_MAP.md`, `harness/PROJECT_STATE.md`: architecture and verification checkpoint. --- diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..6230c70 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,20 @@ +services: + postgres: + image: postgres:18 + environment: + POSTGRES_DB: hph + POSTGRES_USER: hph_owner + POSTGRES_PASSWORD: ${HPH_POSTGRES_PASSWORD:?Set HPH_POSTGRES_PASSWORD} + HPH_RUNTIME_PASSWORD: ${HPH_RUNTIME_PASSWORD:?Set HPH_RUNTIME_PASSWORD} + ports: + - "127.0.0.1:5432:5432" + volumes: + - hph-postgres:/var/lib/postgresql + - ./scripts/init-runtime.sh:/docker-entrypoint-initdb.d/10-runtime.sh:ro + healthcheck: + test: ["CMD-SHELL", "pg_isready -U hph_owner -d hph"] + interval: 5s + timeout: 3s + retries: 10 +volumes: + hph-postgres: 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/docs/DATABASE.md b/docs/DATABASE.md index ab059a9..b0df42d 100644 --- a/docs/DATABASE.md +++ b/docs/DATABASE.md @@ -1,36 +1,36 @@ -# PostgreSQL data model +# PostgreSQL persistence -Initial schema: `migrations/0001_company_data.sql`. It creates organizations, external user identities, people, company memberships, module configuration, and attendance events. +HPH's authenticated mode uses PostgreSQL for accounts, opaque session hashes, company memberships, people, module selection, attendance, audit and notes. The explicit Leptos demo remains in-memory. See [WORKSPACE.md](WORKSPACE.md) for runnable setup and migration commands. -## Tenant boundary +## Role separation -Organization-scoped tables enforce Row-Level Security (RLS) against `hph.tenant_id`. Each request touching company data must run in a transaction and set the verified user and selected organization with transaction-local settings: +Use `HPH_MIGRATION_DATABASE_URL` only for operator CLI commands (`--migrate`, `--bootstrap`). Use `HPH_DATABASE_URL` for the server's non-owner role with NOSUPERUSER NOBYPASSRLS. Operational startup verifies those restrictions. The local Compose init script grants table and sequence access for the restricted role through the migration owner's default privileges. -```sql -SELECT set_config('hph.user_id', $1, true); -SELECT set_config('hph.tenant_id', $2, true); -``` +Company tables use forced RLS. `Database::begin_tenant_transaction` sets `hph.user_id` and `hph.tenant_id` only for the current transaction, preventing pooled connection context leaks. RLS is a second boundary, not a replacement for membership and role checks. -The third argument must remain `true`, so both settings end with the transaction. The user ID must come from the authenticated server session; the selected organization must first be checked against an active membership. The database policies separate rows by tenant; the Rust service must also enforce active membership and role permissions before running an operation. +Authentication tables are application-private global state: users, credentials and sessions are not exposed as direct SQL or general-purpose HTTP endpoints. The application role can operate on them for authentication. A valid session provides the user ID; company operations never trust caller-supplied identity. -The production runtime role must not own these tables and must not have `BYPASSRLS`. Migrations should run with a separate owner role. Table owners normally bypass policies; `FORCE ROW LEVEL SECURITY` makes owners subject to policies, while superusers and `BYPASSRLS` roles always bypass them. CI runs the policy checks as a non-owner role without that attribute. +## Transactions and history -Composite foreign keys keep memberships and attendance events attached to a person in the same organization. An organization-scoped idempotency key prevents duplicate attendance events on request retries. +`operations::begin` first locks the selected organization and verifies active membership plus active employee state. Company operations use this shared lock order so mutations, revocations, module selection and attendance checks cannot race within a company. Reads take the same lock for consistent snapshots; this intentionally favors simple correctness over high concurrency in the initial template. -## Rust connection layer +Time entries retain UTC timestamps and a per-person idempotency key. State transitions use the shared core rules. Exact retries return the existing effect; reusing a key for a different event is rejected. Timestamp corrections must preserve chronological validity and cannot collide with an existing event timestamp. Audit writes share the business transaction. -The SSR server can open a bounded SQLx PostgreSQL pool with `HPH_DATABASE_URL`. If `HPH_MIGRATION_DATABASE_URL` is also set, startup applies migrations through that separate connection and then closes it. Use a migration owner for that URL and a runtime role without table ownership or `BYPASSRLS` for the runtime URL. +Audit records are append-only through a database trigger, even for runtime roles granted UPDATE/DELETE on tables. The service records event IDs, old/new timestamps and reasons for corrections. The UI shows the latest 50 audit records. Tenant deletion and retention/export workflows are not implemented; deleting audit rows indirectly is also rejected by the trigger. -Each database operation must start a transaction scoped to a previously verified user and organization through `Database::begin_tenant_transaction(user_id, tenant_id)`. Both RLS settings are transaction-local. The `/health` endpoint checks pool reachability when configured. +## Migrations -## Company module repository +- `0001_company_data.sql`: organizations, global identities, people, memberships, module flags, attendance and company RLS. +- `0002_workspace.sql`: active employees, branding, password credentials, expiring sessions, immutable audit and Notes. -`src/module_repository.rs` provides tenant-scoped reads and atomic writes for `hph_company_modules`. Reads require an active membership; writes additionally require an active admin membership. The repository validates module dependencies through `hph-core` and records all flags together in one transaction. It returns `None` when no company selection is stored so the caller can apply its configured preset. +Migrations preserve existing data. Operational startup does not apply migrations implicitly. Run the explicit migration CLI with the owner role and retain backups appropriate to your installation. -Its PostgreSQL CI integration test seeds fixtures through a separate admin connection, then exercises repository reads and writes through a non-owner runtime role without `BYPASSRLS`. +## Existing lower-level repositories -The SSR screens and server functions do not call this repository yet. The current application still uses its in-memory demo actor, whose IDs are not database UUIDs. Connect it only after authentication supplies verified user and organization UUIDs; do not adapt the synthetic demo identity into a production database identity. +`CompanyModuleRepository` and `MembershipRepository` remain tested building blocks. The operational service reuses the same database context and core contracts but performs membership, module and business checks together in its own transaction, avoiding nested independent transactions around writes. -## Current limit +## Verification -People, attendance, memberships, and module configuration in the screens are still in-memory demo state. Authentication, session verification, HTTP integration, and production authorization remain out of scope. SQLx repository behavior is exercised against PostgreSQL in CI. +CI applies the schema and SQL isolation cases, verifies the SQLx migrator and pool, then uses a restricted runtime role for repository and full HTTP workflow tests. The operational tests cover session selection, idempotent/concurrent requests, persistence across router restart, invalid dependencies, corrections, audit immutability, role denial, deactivation, RLS, logout and expiration. Browser checks run against this database and the real Rust server using synthetic accounts. + +Current reads load company event history in memory. Add pagination, retention and capacity testing before a large installation. The current checks do not constitute a deployment security assessment or backup recovery test. diff --git a/docs/MODULES.md b/docs/MODULES.md index d073048..3be2428 100644 --- a/docs/MODULES.md +++ b/docs/MODULES.md @@ -1,39 +1,42 @@ # Extending HPH -## Current contract +## Shared contract -Module composition is declared in `crates/hph-core/src/lib.rs`: `ModuleId`, `catalog()` and `ModuleSet`. This shared source is compiled for both the server and the browser. Do not maintain a second JavaScript catalog or a separate dependency engine in the UI. +`crates/hph-core/src/lib.rs` owns `ModuleId`, `catalog()` and `ModuleSet`. Dependencies are checked on the server. People has none, Attendance requires People, Reports requires Attendance, and Notes requires People. An invalid configuration leaves the previous selection intact. -Module selection is a company setting: HPH Core is always included, and each company enables the features that fit its processes. Modules remain compiled, versioned Rust code within the template; they are not third-party plugins loaded at runtime. The demo keeps the selection in memory; persistent application configuration must be associated with the authenticated organization. +Modules are compiled Rust features of the application, not untrusted runtime plugins. Each authenticated company persists its own selection. HPH Core includes sessions, membership checks, company settings and audit. Disabling a module hides and blocks its operations without deleting data; open sessions prevent Attendance from being disabled. -Core is always present. The current modules form a dependency chain: People → Attendance → Reports. A module's dependencies must be enabled before enabling it. Before disabling a dependency, disable the modules that use it. An invalid change must leave the previous state intact. +The explicit Leptos demo still uses `hph.toml` and in-memory settings. Notes belongs to the authenticated workspace and is not offered in the demo. -Disabling a module must stop its protected operations and hide the relevant screens **without deleting its data**. Open work sessions prevent Attendance from being disabled. +## A complete example: Team notes -## Customize a single company installation +| Layer | Existing implementation | Purpose | +| --- | --- | --- | +| Catalog | `ModuleId::Notes`, `catalog()` | Typed identity, description and People dependency | +| Schema | `migrations/0002_workspace.sql`, `hph_notes` | Company/author ownership, length constraint and tenant RLS | +| Service | `operations::add_note` | Active membership, enabled-module check, validation and audit in one transaction | +| Read | `operations::snapshot` | Company-scoped latest 50 notes, only if enabled | +| HTTP | `/notes/add` in `workspace_web.rs` | Same-origin POST, session/company CSRF, authenticated actor | +| Screen | `workspace_ui::notes` | Escaped user text, accessible form, empty collection and saved-state feedback | +| Selection | `operations::set_modules` | Persisted flags and atomic dependency validation | +| Checks | `workspace_tests.rs`, `browser-smoke.mjs` | Real database, tenant checks, enabled workflow and HTML escaping | -In `hph.toml`, set `modules` to an explicit list of IDs (`people`, `attendance`, `reports`). This optional list overrides `preset` and is validated at startup: missing dependencies or duplicate IDs cause the configuration to be rejected. A commented example is included in `hph.toml`. +Follow the flow from the route to service before copying code. Obtain identity from the session, never from a hidden user ID. `operations::begin` locks the company and rechecks membership/active employee state inside the transaction. Every mutation, including role changes and deactivation, follows the same locking order. Reuse that transaction for the module write and audit record. -This is persistent initial configuration for the company installation. Changes made from the demo screen remain temporary and reset on restart. Persisting runtime settings per organization requires connecting the PostgreSQL repository to authenticated requests. +Notes deliberately supports append-only messages without editing/deletion or notifications. It demonstrates the complete extension path without adding those unrelated workflows. -## Add a module +## Add your module -1. Add a typed identifier to `ModuleId` and a definition to `catalog()` with explicit dependencies. Do not introduce cycles. -2. Define domain rules and serialized types in the core or, as it grows, a dedicated crate. Keep Leptos, HTTP and database concerns out of pure domain rules. -3. Implement the server operation in `src/api.rs`. Obtain the actor from server context and verify membership, permissions and module activation before mutating state. A hidden button is not an access control. -4. Add the screen and navigation in `src/app.rs`. Reuse existing colors, components, empty states and errors. Keep interface text, accessibility labels, comments and documentation in English. -5. Define what happens to open operations when the module is disabled. Do not implicitly delete documents or events. -6. Test domain rules and the HTTP boundary: valid operations, denied permissions, foreign companies, disabled modules, invalid input and data retention. -7. Update presets and documentation only if the new module actually belongs to that preset. Do not present an unimplemented module as available. +1. Add a `ModuleId` and catalog definition with explicit, acyclic dependencies. Update mappings and company module persistence. If the SQL check constraint contains the module IDs, extend it through a **new** migration. +2. Define domain contracts in `hph-core` when they are independent of HTTP/database/UI. Document behavior and what must happen if the module is disabled during an open operation. +3. Add tenant-owned tables with constraints and RLS. Never alter an applied migration, seed real installations with demo records, or erase data on module disable. +4. Add a transaction-scoped service operation. Recheck active membership, role, module activation and input invariants before writes. Use server identity and timestamps where the workflow requires them. +5. Add the protected route and Rust-rendered view. Reuse existing design tokens, navigation and form helpers. Pass every dynamic value through HTML escaping. Keep prose, accessibility labels, errors, comments and documentation in English. +6. Test success, a foreign tenant, an employee without the required role, disabled-module calls, invalid input and retained data. Exercise PostgreSQL with a non-owner runtime role and include a browser path when new interaction is introduced. +7. Document the module's setup and actual limits. Update presets only if the module should really be included by default. -## Future example: leave +Modules and permissions solve different problems: a company may enable a feature while only some members have permission to mutate it. A hidden menu or disabled button is not authorization. -Dependency: People. Clarify these requirements before implementation: date ranges, company time zone, working calendar, approver, overlaps and corrections. A request belongs to a company and employee; approval requires a permission distinct from submission. Leave balances require explicit rules and must not be inferred from assumptions about employment contracts. +## Future leave module -## Demo boundary - -`DemoState` uses mutex-protected shared memory and a fixed actor. Domain-level tenant checks do not establish a secure multi-company service. Authentication, per-request membership verification and database isolation at the HTTP boundary still need to be integrated. - -PostgreSQL operations must use transactions for related changes, constraints to prevent incompatible work sessions, tenant-linked keys and isolation tests with at least two companies. Module activation is a company setting, while permissions belong to the user: both must be checked. - -Use versioned migrations to preserve configuration and data as the template evolves. Do not overwrite an existing installation with demo data. +People is the likely dependency. Specify date ranges, company timezone and working calendar, approvers, overlaps, corrections and balances before implementation. Do not infer contract, payroll or legal rules. This module is not implemented by the Notes example. diff --git a/docs/WORKSPACE.md b/docs/WORKSPACE.md new file mode 100644 index 0000000..51e2256 --- /dev/null +++ b/docs/WORKSPACE.md @@ -0,0 +1,81 @@ +# Run an authenticated company workspace + +## Local PostgreSQL + +The root `compose.yaml` starts PostgreSQL 18 on **127.0.0.1:5432** and preserves data in a named Docker volume. `scripts/init-runtime.sh` creates a restricted `hph_runtime` role and default grants for tables and sequences created by `hph_owner`. + +```bash +export HPH_POSTGRES_PASSWORD='replace-with-a-local-owner-password' +export HPH_RUNTIME_PASSWORD='replace-with-a-different-runtime-password' +docker compose up -d +``` + +Set connection URLs. Percent-encode reserved URL characters in passwords; the sample passwords above need no encoding. + +```bash +export HPH_MIGRATION_DATABASE_URL="postgres://hph_owner:${HPH_POSTGRES_PASSWORD}@127.0.0.1:5432/hph" +export HPH_DATABASE_URL="postgres://hph_runtime:${HPH_RUNTIME_PASSWORD}@127.0.0.1:5432/hph" +export HPH_ORIGIN='http://127.0.0.1:3000' +``` + +The two roles are intentionally separate. Normal web startup rejects a superuser, BYPASSRLS role or owner of an HPH table. The migration connection is used only by explicit CLI commands in operational mode. + +The init script runs only when PostgreSQL initializes a new volume. Changing environment variables later does not rotate existing database passwords. Preserve your volume; do not delete it to upgrade HPH. + +## First company and account + +```bash +export HPH_BOOTSTRAP_EMAIL='you@example.com' +export HPH_BOOTSTRAP_NAME='Your name' +export HPH_BOOTSTRAP_COMPANY='Your company' +export HPH_BOOTSTRAP_SLUG='your-company' +read -rsp 'Administrator password (12+ characters): ' HPH_BOOTSTRAP_PASSWORD; echo +export HPH_BOOTSTRAP_PASSWORD +cargo run --features ssr --locked -- --bootstrap +unset HPH_BOOTSTRAP_PASSWORD +cargo run --features ssr --locked +``` + +The bootstrap command applies pending migrations and creates the company, administrator profile and People/Attendance/Reports selection. It does not start the web server. Reusing a company slug is rejected, not treated as permission to overwrite data. + +Open **http://127.0.0.1:3000**, sign in and choose your company. Use precisely the hostname configured in `HPH_ORIGIN`; switching between localhost and 127.0.0.1 will cause mutation origin checks to reject the request. + +To add another company for the same administrator, run bootstrap with a new company name/slug and the existing account email/password. The password is verified; bootstrap never silently resets it. + +For PowerShell, use `$env:NAME = 'value'` instead of `export`. Supply passwords through your shell's secure-input workflow and clear the temporary bootstrap variable afterwards. + +## Everyday workflow + +1. Open **People**. Add a name, unique employee number, department and job title. Optionally set an email and initial password to create a login. Share credentials through your own secure channel; HPH sends no messages. +2. Employees sign in with that login, choose their company and clock in from Overview or Attendance. Employees can see only their own profile and time entries; administrators can review the company. +3. Start/end breaks and clock out. An open interval is not counted until closed. Retrying an identical request key creates one event only; invalid transitions are rejected. +4. Use **Reports** to select a month and optionally a day. Midnight and daylight saving boundaries follow the company's IANA timezone. +5. Administrators can expand **Correct time** on an existing event. Enter an ISO 8601 timestamp with offset, such as `2026-10-14T09:00:00+02:00`, and a reason. The corrected sequence must remain valid; future times and timestamp collisions are rejected. The event ID and original/replacement timestamps are stored in audit history. +6. Use **Workspace** for branding, modules and audit. Use **My account** to change your password; this revokes all your sessions. + +An administrator cannot deactivate or demote their own account. Open work sessions must be closed before deactivating a person or disabling Attendance. Deactivation preserves history and is enforced on the next company operation. Changing a profile's contact email does not change the login email. A company administrator cannot overwrite another existing account's credentials. + +## Appearance and modules + +Choose sage or indigo, a six-digit hex accent color and a local logo path. Put installation-owned images under `public/assets/`; for example `/assets/hph-mark.svg`. Remote image URLs, data URLs and path traversal are rejected. Logos are deployed files, not uploads. + +Team notes is a working optional module. Enable People + Team notes, open the note screen, and publish a company note. Disabling Notes keeps existing notes. The [module walkthrough](MODULES.md) traces its catalog, schema, service, route and screen. + +## Upgrades and request security + +```bash +cargo run --features ssr --locked -- --migrate +cargo run --features ssr --locked +``` + +Back up your database before schema upgrades. Versioned migrations are additive; never edit an applied migration. `--migrate` uses `HPH_MIGRATION_DATABASE_URL`, while web requests use only `HPH_DATABASE_URL`. + +Session cookies are HttpOnly, SameSite=Strict, and Secure for HTTPS origins. Tokens have 256 bits of entropy; only their SHA-256 hashes are stored. Sessions expire after eight hours. POST requests require an exact Origin match, and authenticated forms additionally carry a session/company-bound CSRF value. Switching companies invalidates forms opened for the previous company. + +Logins use Argon2id, generic credential errors, per-account lockouts, a bounded per-IP attempt window and a concurrency limit. Client IP comes from the direct connection; forwarded headers are not trusted. A reverse proxy therefore needs its own suitable login rate limit. + +HTTP development binding is loopback-only. For a future TLS proxy deployment, set an HTTPS `HPH_ORIGIN` and appropriate `HPH_BIND`; HPH does not terminate TLS itself. This setup has not been deployed publicly or certified for production use. + +## Test boundaries + +Ordinary `cargo test` runs unit/HTTP demo tests; PostgreSQL integration tests return early unless `HPH_TEST_DATABASE_URL` and `HPH_TEST_ADMIN_DATABASE_URL` are set. CI supplies an isolated database and restricted runtime role, then exercises the operational HTTP workflow. Its browser captures use synthetic accounts only. Browser dependencies are not runtime dependencies. diff --git a/harness/PROJECT_MAP.md b/harness/PROJECT_MAP.md index d26e1d9..077bed8 100644 --- a/harness/PROJECT_MAP.md +++ b/harness/PROJECT_MAP.md @@ -1,72 +1,61 @@ # HPH — Project map -## Confirmed requirements +## Product and constraints -- A personal business management project with time tracking and attendance, extensible to additional functions. -- A reusable template: each installation/company can select its own modules. -- Each company composes HPH around its processes; module selection belongs to the company and must become persistent in the application. -- After initially leaving technology choices open, the owner expressed a preference for Rust throughout. Adopted choice: a Rust frontend and backend. -- Visual quality and a carefully designed user experience are central requirements. -- English is the default language for the interface, accessibility labels, errors, comments and documentation (requested on 2026-10-13). Preserve proper names and stable identifiers. -- Public portfolio repository: https://github.com/Stcant/HPH, branch `main`. No application deployment requested. +A personal Rust business-management project and reusable company template. Time tracking and attendance are the first operational workflow. Companies select modules and customize their appearance. English is the default language for UI, accessibility, errors, comments and documentation. The public portfolio repository is `Stcant/HPH`; no public application deployment is included. -## Architectural decisions +## Architecture -| Area | Choice and rationale | +| Area | Choice and boundary | | --- | --- | -| Frontend | Leptos 0.8, SSR + WASM hydration: Rust components and contracts in one application | -| HTTP | Axum 0.8 + Tokio, using the official Leptos integration | -| Organization | Modular monolith: one deployment, independent rules in hph-core, no initial microservices | -| Modules | Typed catalog, declared dependencies and server-enforced activation; persistent per-company configuration still needs application integration | -| Configuration | hph.toml for company, theme, preset or explicit module list; demo runtime changes are temporary | -| Design | CSS tokens, sage and indigo themes, sidebar, cards, tables and responsive layout | -| Persistence | PostgreSQL schema and RLS policies tested in CI; SQLx pool, migrations, module and membership repositories. Screens still use in-memory state; the API awaits an authenticated identity | -| Identity | Rust contracts and a SQLx repository for active membership, role and person per tenant. Login, sessions and connecting the resolver to server functions remain to be implemented | -| Language | English interface and repository content; HTML language is en. UTC timestamps use an unambiguous YYYY-MM-DD display format | - -Tradeoff: Rust end to end shares types and expertise, but requires WASM builds and offers a smaller UI ecosystem than React. Leptos generates a JavaScript loader; application code remains Rust. Do not claim that the browser runs no JavaScript at all. - -## Implementation - -- `crates/hph-core/src/lib.rs`: catalog and dependencies, user identity and company membership, attendance state machine, closed-interval calculations and tests. -- `migrations/0001_company_data.sql`: multi-company PostgreSQL schema and RLS policies; `migrations/tests/tenant_isolation.sql` verifies visibility and cross-company writes. -- `src/database.rs`: SQLx pool, runtime migrator, health check and transactions with transaction-local RLS context. -- `src/module_repository.rs`: atomic company module reads/writes under RLS, active membership and admin role checks. Not connected to server functions until an authenticated session provides verified UUIDs. -- `src/membership_repository.rs`: resolves an actor from a persisted active membership in the selected tenant, given an identity and tenant selection validated by the authentication layer. -- `src/app.rs`: dashboard, demo directory, time tracking, reports, module configuration and shared components. -- `src/api.rs`: snapshot, configuration and time-entry server functions. The acting identity comes from server context. -- `src/server.rs`: configuration, in-memory demo state, Axum router and HTTP/SSR tests; optional PostgreSQL health check. -- `src/main.rs`: startup requires HPH_DEMO=true and a loopback address; runtime pool and separate migrator are optional environment settings. -- `style/main.css`: visual design, tokens and mobile styles; no remote fonts or assets required. -- `Cargo.lock`: resolved versions; `rust-toolchain.toml`: toolchain and target. -- `.github/workflows/ci.yml`: formatting, SSR tests, WASM check and PostgreSQL integration. - -## Modules - -Initial company configuration can use a preset or an explicit validated list in hph.toml; the UI can change the selection during the demo. Production runtime configuration must be persisted and authorized per organization. - -Core is always active. People contains read-only synthetic profiles. Attendance depends on People; Reports depends on Attendance. Disabling modules preserves events; open work sessions prevent Attendance from being disabled. Reports show closed work intervals in the session, excluding breaks. - -## Current boundaries - -This is a local demo with a synthetic administrator membership. Identity/membership contracts, RLS schema, module repository and persisted membership repository are covered by CI. Login, sessions and connecting repositories to server functions are not integrated. The tenant is modeled and tested in the domain, but this does not prove a secure multi-company service. Data and module changes reset on restart. Refreshing other tabs is manual. - -Supporting multiple companies requires verified membership, mandatory tenant scope on queries/mutations, migrations, constraints and database isolation tests. No real data before this phase is complete. - -Timestamps are UTC and server-generated; sequences are validated. Company calendars, display time zones, contract rules, rounding, corrections/audit and retry idempotency require dedicated application implementation. - -## Customization model - -HPH Core remains shared. Modules are versioned Rust features in the template, selectable by company administrators and enforced on the server. Disabling them hides and blocks their operations without deleting data. The demo applies the selection to one in-memory workspace. Persistent configuration must be associated with the organization. The deployment model—dedicated instance or multi-company service—remains open, so the tenant boundary must stay explicit from the start. - -## Product evolution - -First target operational workflow: authentication, a real employee directory, persistent time entries and manager oversight. Then leave requests and an attendance calendar. Shifts, documents, expenses, projects, customers, invoicing, inventory and integrations remain candidate modules. Payroll and accounting require separate specifications. +| Operational UI | Rust-generated HTML with accessible standard forms and CSS; works without browser JavaScript | +| Interactive demo | Existing Leptos 0.8 SSR + WASM hydration, explicitly enabled by HPH_DEMO=true on loopback | +| Server | Axum 0.8 + Tokio; separate routers prevent the demo's synthetic actor reaching persistent routes | +| Shape | Modular monolith with shared framework-independent rules in hph-core | +| Persistence | PostgreSQL + SQLx, versioned additive migrations, forced tenant RLS, restricted runtime role | +| Identity | Argon2id local accounts; 256-bit opaque sessions stored as hashes, 8-hour expiry, logout/password-change revocation | +| Request boundary | Exact Origin on POST; authenticated forms carry session/company-bound CSRF; HttpOnly/Strict cookies, Secure for HTTPS | +| Company operations | One scoped transaction and organization lock; fresh active membership/employee and role checks before work | +| Time | Server UTC timestamps; validated sequence and idempotency; IANA display/report timezone; split closed intervals at local midnight | +| Modules | Typed catalog and dependencies; company-persisted flags; disabling preserves data and blocks protected operations | +| Design | Responsive sidebar/cards/tables/forms; sage/indigo, company accent and local asset logo; system fonts | + +The operational UI intentionally starts with server-rendered forms so every protected operation has an explicit HTTP boundary and remains functional without hydration. It does not replace the interactive Leptos demo. A future interactive operational frontend can reuse the same service contracts. Rust application code requires no Node; Playwright's Node dependency is for browser QA only. + +## Files and contracts + +- `src/main.rs`: chooses explicit demo mode or authenticated operational mode; `--migrate` and `--bootstrap` are operator-only CLI paths. +- `src/auth.rs`: Argon2 hashing/verification, login lockout, session token generation/resolution, company/account bootstrap. Bootstrap verifies the password before adding a company to an existing account. +- `src/workspace_web.rs`: protected routes, same-origin/CSRF checks, cookie handling, bounded IP login attempts and hash concurrency, response headers. +- `src/operations.rs`: transaction-scoped company selection, employee edits, idempotent clocking, reasoned timestamp corrections, module/settings updates, Notes and local-calendar summaries. +- `src/workspace_ui.rs`, `style/workspace.css`: operational Rust views and layout. Escape all dynamic text/attributes. Local logos are deployment-owned assets under `/assets/`. +- `src/database.rs`: bounded SQLx pool, owner migrator, transaction-local tenant/user settings and runtime-role checks. +- `src/module_repository.rs`, `src/membership_repository.rs`: lower-level building blocks with restricted-role integration tests. The operational service performs related checks together in one transaction rather than composing separate repository transactions. +- `crates/hph-core/src/lib.rs`: typed module IDs/catalog/dependencies, membership/role contracts, attendance state transitions and closed-interval rules. +- `src/app.rs`, `src/api.rs`, `src/server.rs`: separate Leptos demo with synthetic identity and in-memory state. Notes is not offered in this mode. +- `migrations/0001_company_data.sql`: base company schema and RLS. `0002_workspace.sql`: active profiles, branding, credentials, sessions, immutable audit and Notes. +- `compose.yaml`, `scripts/init-runtime.sh`: local PostgreSQL and non-owner runtime-role setup. `hph.toml` configures the demo only. +- `src/workspace_tests.rs`: real operational HTTP/DB integration. `scripts/browser-smoke.mjs`: real server desktop/mobile flows and image captures. `.github/workflows/ci.yml`: Rust/SSR/WASM, PostgreSQL and browser gates. + +## Invariants + +- User identity comes from an unexpired server-side session, not form fields. Selecting a company requires active membership and active employee state. +- Every company operation rechecks membership inside its transaction. The organization lock serializes reads and writes, including deactivation and module changes. This is a deliberate initial consistency/throughput tradeoff. +- Employees see their own profiles/events and can clock only for themselves. Administrators manage company people, modules, appearance and corrections. Company notes are shared with active members when enabled. +- A person cannot be deactivated during an open shift. An administrator cannot deactivate/demote their own account. Editing a profile email does not alter global login credentials. +- Timestamp corrections require a reason, reject future/colliding/invalid-sequence times, and atomically record old/new values and actor in immutable audit. Event creation is idempotent per company/person/request key. +- Audit rows are append-only through a PostgreSQL trigger. The display shows the latest 50; deletion/retention is not implemented. +- Module dependencies are authoritative in hph-core. Attendance requires People; Reports requires Attendance; Notes requires People. Invalid changes preserve the previous selection. +- Existing applied migrations are immutable. Demo records are never inserted into an operational company by normal startup. + +## Remaining boundaries + +Accounts are locally managed. Email invitations, password recovery, OIDC/MFA, missed-event insertion/deletion, approval workflows and export are not implemented. Operator setup and credential delivery remain manual. The application has not been publicly deployed or certified for production. + +Reads load company event history in memory, and the shared company lock prioritizes correctness over throughput. Pagination, retention, concurrency/load testing, backup recovery, monitoring and deployment-specific security review are needed before a large installation. + +Reports exclude open intervals and breaks; they do not calculate payroll, overtime, contractual rounding or leave balances. Views display whole minutes while stored events retain seconds. Leave, shifts, documents, expenses and projects are future modules; payroll, accounting and inventory remain outside this increment. ## Reading order -- [Project state](PROJECT_STATE.md): evidence and next action. -- [Startup and limitations](../README.md). -- [Module contract](../docs/MODULES.md). - -Primary references consulted: https://book.leptos.dev/getting_started/index.html ; https://book.leptos.dev/ssr/21_cargo_leptos.html ; https://github.com/leptos-rs/start-axum ; https://docs.rs/axum/latest/axum/ ; https://www.postgresql.org/docs/current/ddl-rowsecurity.html . +[State and current evidence](PROJECT_STATE.md) → [README](../README.md) → [Workspace setup](../docs/WORKSPACE.md) → [Database](../docs/DATABASE.md) → [Module contract and Notes walkthrough](../docs/MODULES.md). diff --git a/harness/PROJECT_STATE.md b/harness/PROJECT_STATE.md index 2d06823..54a53d0 100644 --- a/harness/PROJECT_STATE.md +++ b/harness/PROJECT_STATE.md @@ -1,10 +1,28 @@ # HPH — Project state +## Active implementation — 2026-10-13 + +Status: implemented; verification in progress in PR #9 on `feat/company-workspace`, based on `d6ee299822a8e0efe1f543406a25d317e82afe95`. User authorized all proposed features and PR/merge work. A clean local Git checkout and Rust 1.94 toolchain are available. The stable 1.99 compiler fails with SIGBUS in this executor; CI runs stable successfully. PostgreSQL/browser integration runs in CI because local PostgreSQL installation is unavailable. + +| 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 | implemented | +| Persistent people and time entries | Admin create/edit/deactivate/roles; employee self-clock; idempotent writes; invalid sequences rejected; survives restart | implemented | +| Attendance and corrections | Company timezone; daily/monthly closed intervals split at midnight; reason and immutable audit; valid corrected sequence | implemented | +| Template customization | Company name, theme, accent and safe local logo; persisted module selection; working Notes module example | implemented | +| Browser/portfolio and documentation | Desktop/mobile workflow tests; real screenshot and GIF; English docs; configured CI; PR merge only after gates pass | implemented | + +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. + +Evidence: local Rust/SSR tests and WASM compilation passed with 1.94. CI run 38514914137 on d7960b3 passed formatting, SSR, WASM, migrations, restricted-role repository tests and operational HTTP/DB tests. Browser completed login, profiles, clocking and Notes but failed selecting the Theme label; explicit accessible name fixed in deb742e. Browser mobile and final captures remain pending. + +Next action: finish browser verification, inspect and save real images, review all security/requirements boundaries and merge PR #9 only after final CI passes. 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. -Current increment: English throughout the repository and interface, plus a recruiter Easter egg in the README. Status: **verified** in PR #8 on `chore/english-language`; merge follows the final checkpoint checks. Scope: interface and accessibility text, domain/server errors, English HTML language, unambiguous UTC date display, documentation and existing SSR assertions. Acceptance: English content across maintained files, a readable expandable README note, and passing formatting/SSR/WASM/PostgreSQL checks. No authentication or persistence behavior changes are included. +Previous increment: English throughout the repository and interface, plus a recruiter Easter egg in the README. Status: **verified**, merged in PR #8 (f54564b67fc2a116464ffc7264e32a43b7e05045). Scope: interface and accessibility text, domain/server errors, English HTML language, unambiguous UTC date display, documentation and existing SSR assertions. Acceptance: English content across maintained files, a readable expandable README note, and passing formatting/SSR/WASM/PostgreSQL checks. No authentication or persistence behavior changes are included. Previous completed increment: persisted membership SQLx repository, **verified** and integrated into `main` by PR #7, merge `812a5bb21b232039151dd375b4671d019588e284`. CI run [38466818515](https://github.com/Stcant/HPH/actions/runs/38466818515) passed both `checks` and `database`, including tenant-scoped lookup and rejection of missing or revoked memberships under RLS. PR #6 was integrated with merge `231762216f4582e5e7ffe0550497d975f7f153c6`; run [38465298093](https://github.com/Stcant/HPH/actions/runs/38465298093) passed on commit `85573ff444bebe43d7a09da848bd08a80608b601`. Post-merge CI [38467158574](https://github.com/Stcant/HPH/actions/runs/38467158574) passed on `1d58132cba643ba740804275056b6c22fca15050`, the base of this language change. The overall project remains in progress; authentication and browser QA are still missing. @@ -149,7 +167,7 @@ Leave, time off, shifts, employee CRUD, corrections/audit, application-level ide ## Next action -Merge PR #8 after the final checkpoint checks. The next functional increment remains provider-neutral authentication/sessions and connecting session context to repositories; do not use the demo actor for tenant-scoped SQL. Then implement people and attendance repositories. Run desktop/mobile browser QA when an executable build and browser environment are available. A local source snapshot is available, but Rust verification still runs through GitHub CI. +Use the active implementation checkpoint at the top of this file. Older limitations and verification records below refer to their historical increments. ## Files and reading order 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/scripts/init-runtime.sh b/scripts/init-runtime.sh new file mode 100644 index 0000000..a43014a --- /dev/null +++ b/scripts/init-runtime.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# Called by the PostgreSQL image only for a new data volume. +set -eu +psql --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" \ + --set=ON_ERROR_STOP=1 --set=runtime_password="$HPH_RUNTIME_PASSWORD" <<'SQL' +CREATE ROLE hph_runtime LOGIN PASSWORD :'runtime_password' NOSUPERUSER NOCREATEDB NOCREATEROLE NOBYPASSRLS; +GRANT CONNECT ON DATABASE hph TO hph_runtime; +GRANT USAGE ON SCHEMA public TO hph_runtime; +ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO hph_runtime; +ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT USAGE, SELECT ON SEQUENCES TO hph_runtime; +SQL diff --git a/src/app.rs b/src/app.rs index ce64010..d50ba33 100644 --- a/src/app.rs +++ b/src/app.rs @@ -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..2a57350 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,8 +8,52 @@ async fn main() -> Result<(), Box> { use leptos::prelude::*; use std::sync::Arc; + if std::env::args().any(|arg| arg == "--migrate") { + let db = Database::connect(&std::env::var("HPH_MIGRATION_DATABASE_URL")?).await?; + db.migrate().await?; + db.close().await; + println!("Migrations applied."); + return Ok(()); + } + 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..dc1def8 --- /dev/null +++ b/src/operations.rs @@ -0,0 +1,664 @@ +//! 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 a.action,u.display_name || ': ' || a.detail,to_char(a.created_at AT TIME ZONE 'UTC','YYYY-MM-DD HH24:MI:SS') FROM hph_audit a JOIN hph_users u ON u.id=a.actor_user_id WHERE a.organization_id=$1 ORDER BY a.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?; + let people: std::collections::HashSet<_> = all.iter().map(|event| event.person).collect(); + for person in people { + if sequence(&all, 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/server.rs b/src/server.rs index 53389a0..4b1ded7 100644 --- a/src/server.rs +++ b/src/server.rs @@ -30,6 +30,9 @@ impl DemoState { Some(enabled) => ModuleSet::from_enabled(enabled)?, None => ModuleSet::preset(&config.preset)?, }; + if modules.contains(ModuleId::Notes) { + return Err("Team notes requires the authenticated workspace.".into()); + } let people = [ ( "elena", @@ -97,7 +100,10 @@ impl DemoState { Snapshot { workspace: workspace.clone(), actor_id: self.actor.person_id.clone(), - catalog: catalog(), + catalog: catalog() + .into_iter() + .filter(|module| module.id != ModuleId::Notes) + .collect(), server_time: chrono::Utc::now() .format("%Y-%m-%d · %H:%M UTC") .to_string(), diff --git a/src/workspace_tests.rs b/src/workspace_tests.rs new file mode 100644 index 0000000..b384373 --- /dev/null +++ b/src/workspace_tests.rs @@ -0,0 +1,477 @@ +//! 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()); + assert!( + WebState::new(runtime.clone(), "http://example.test".into()) + .await + .is_err() + ); + let secure_state = WebState::new(runtime.clone(), "https://example.test".into()) + .await + .unwrap(); + assert!(super::cookie(&secure_state, "opaque", 28800).contains("; Secure")); + 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() + ); + assert!( + op::set_modules(&runtime, &session, vec!["people".into()]) + .await + .is_err() + ); + assert!( + op::add_note(&runtime, &session, "Disabled module") + .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")) + ); + assert!( + op::correct( + &runtime, + &session, + data.events[1].id, + at - 1, + "Reversed sequence" + ) + .await + .is_err() + ); + // 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("