Compare commits

..

9 Commits

Author SHA1 Message Date
e50a05a1e0 T12.6: wave 12 closed - browser_check passes after the re-point
Matt reran tests/browser_check.py on the re-pointed probe: all
passed. Every T12 done-when and every wave 12 exit criterion is now
checked in wave-12.md.
2026-10-06 14:05:43 -07:00
912cf75027 T12.6: browser results, screenshots, browser_check re-pointed
Matt's run (Edge/Chrome, one at a time): bulk_users_ui_check 19/19,
console_dialogs_check 16/16, mobile_check 24/24, a11y_check 22/22.

browser_check 67/71: its four failures asserted column POSITIONS
(9 columns; r.cells[3]/[4] for Permissions/Project role). CR-020's
selection column comes first, so those read Username and Email. The
probe now expects 10 columns with the selection column first, finds
the cells by header name, and checks your own row has no selection
box. Verified on the real page in the DOM harness; rerun to close.

After-screenshots committed in docs/reference/baseline/wave-12/.
BL-061 logged: the pre-existing sync badge covers a control for ~2 s
after load (pointer-events:none, so never blocks a click); belongs
with wave 14's badge work.
2026-10-06 11:18:39 -07:00
d04a0ff414 T12.6: wave 12 verification record, browser probe, BL-060
- tests/bulk_users_ui_check.py (new): selection, keyboard Space on a
  row box, toolbar role change, super-user CSV with good and bad lines,
  add-to-project with a role, typed DELETE, all end to end against a
  real server; 390px bar layout; writes after-screenshots to
  docs/reference/baseline/wave-12/. Needs a browser: to be run on
  Matt's machine.
- tests/cdp.py: --do-not-de-elevate and the rc=0 grace, the same
  change as wave 16 T16.4 (identical content, merges cleanly), so the
  probes start from an elevated shell on this branch too.
- Verification record in wave-12.md: bulk_users_check 61/61 (main
  7/18), single-user routes identical before/after on 16 calls, DOM
  harness 48/48, jsdom against a real server 13/13, smoke 27/27,
  seed_demo OK. Server-checkable done-when boxes ticked; the browser,
  screenshot and full-suite boxes stay open until run on Edge.
- BL-060 logged: a super user's refusal reason promises a project
  access change neither the dialog nor the bulk route allows. Needs
  Nick; not fixed here (scope).
- file-map.md: wave 12's two new checks.
2026-10-06 11:08:03 -07:00
1c4d1bbccb T12.5: CR-020 bulk delete with typed confirmation
'Delete selected…' in the bulk bar. The dialog lists every affected
username (scrolling inside the dialog for a long list), says the
delete cannot be undone and offers disable instead, and sends nothing
until the word DELETE is typed in capitals, whatever the count
(confirmed 2026-10-06). Wrong words keep the dialog open with the
reason; cancel sends nothing.

Your own account cannot be selected; if it ever reached the request,
the server refuses that row and the report names it with the reason.

The bulk delete is a prompt-style dialog, so it is covered in
tests/console_dialogs_check.py (its docstring asks for exactly this):
new section 4 drives it in the browser with native dialogs poisoned.
DOM harness: 48/48.
2026-10-06 11:05:01 -07:00
74d3bc4af7 T12.4: CR-020 CSV upload (usernames only)
POST /api/auth/bulk-users/resolve reads a list of usernames (first
column; comma, semicolon or tab; header skipped) and answers line by
line, the CR-005 validate-and-report pattern. A line is rejected, with
its number and reason, when it names nobody the caller can see ('User
not found', as everywhere else), an account they may not change (the
single route's own reason), their own account, or a username already
listed (duplicate of line N). An email address resolves only when
exactly one account has it. Nothing is changed by this route.

The console's 'Select from CSV' turns the accepted accounts into the
ordinary selection (filter reset so every selected row is visible) and
lists every rejected line. The action, confirm and per-row report are
the checkbox ones, through the same T12.1 routes, which re-check each
row: a CSV cannot reach an account a checkbox could not.
Usernames only, action in the toolbar (decided 2026-10-06). Files over
1 MB are refused before upload; FileReader fallback for browsers
without Blob.text().

bulk_users_check.py: 61/61. DOM harness: 40/40.
2026-10-06 11:04:01 -07:00
681048197a T12.3: CR-020 bulk-action toolbar
Role change, enable/disable, and project add/remove on the selected
rows, wired to the T12.1 endpoints. Delete is T12.5.

- The toolbar offers only what the caller may do: grantable roles,
  managed projects (archived last, marked), grantable per-project roles.
- Every action confirms through wpConfirmDialog naming the exact count
  (and for projects, the project and role) before anything is sent.
- The result lists every failed row with the server's reason, plus the
  changed / already-set counts; a partial failure is a warning, an
  all-failed batch an alert, a server error says nothing was changed.
  Never a blanket success. Announced through the live-region banner.
- The directory reloads afterwards, which clears the selection.

DOM harness (jsdom, real page and scripts, mocked API): 30/30 with
T12.2.
2026-10-06 11:02:09 -07:00
cf46b3ce42 T12.2: CR-020 row selection in the User Directory
- A checkbox per row the caller may change; select-all covers only the
  rows the current filter and search show, and is indeterminate on a
  partial selection.
- Your own row and rows you cannot change show a disabled box whose
  label gives the reason.
- Changing the filter or the search clears the selection and says so
  in a live region (decided 2026-10-06), so no hidden row stays
  selected.
- The bulk bar appears at one or more selected rows and is hidden (out
  of the tab order) at zero. Actions arrive in T12.3.
- Selection is updated in place, not by re-rendering, so focus stays on
  the checkbox just used. One delegated listener; no ids in inline
  handlers.
- The email-width rule now targets td.ell, not nth-child(3), which the
  new column would have shifted.

Checked in a DOM harness (jsdom) against the real page and scripts:
14/14; against main the selection checks fail. Browser probe at
390px/1440px follows in T12.6.
2026-10-06 11:01:02 -07:00
0e79e17a57 T12.1: CR-020 bulk user endpoints
POST /api/auth/bulk-users/{active,role,projects,delete} take a list of
user ids (max 500) and run each row through the same guards and audit
as the single-user route: the rules now live once, in guard_target and
apply_user_{active,role,delete,projects}, which the single-user routes
call too.

- A refused row is reported with its reason; the rest still run; the
  response counts ok / unchanged / failed. Never a blanket success.
- The caller's own account is refused only on its own row.
- One AuditLog row per changed account, same action and shape as the
  single route. A row already in the requested state is 'unchanged'
  and writes no audit row.
- Project assignment is add/remove to ONE project with a per-project
  role (confirmed 2026-10-06); roles on the user's other projects are
  carried over as stored.
- Routes sit under /api/auth/bulk-users/ because /api/auth/users/bulk/
  would match {user_id}='bulk'.

New tests/bulk_users_check.py (no browser): 47/47. Against main: the
7 single-route checks pass, every bulk check fails.
Single-user routes compared before/after on 16 calls (200/400/403/404):
identical responses, audit rows and memberships. Smoke test 27/27.
2026-10-06 10:57:48 -07:00
286e629782 wave 12: plan for CR-020 on a branch from main; details confirmed
Brings docs/waves/wave-12.md and decisions-2026-09-17.md across from
feat/waves-11-13 (planning docs only, no wave 11 or 13 code), so the
PR into main is wave 12 alone.

Confirmed 2026-10-06 by Matt Mabrey: typed DELETE for bulk delete;
project assignment is add/remove per project; changing the filter
clears the selection; the CSV holds usernames only.
2026-10-06 10:53:29 -07:00
40 changed files with 1789 additions and 1290 deletions

View File

@@ -58,15 +58,6 @@ POSTGRES_PASSWORD=<strong-random-password>
# openssl rand -base64 48
AUTH_SECRET_KEY=<strong-random-secret>
# OPTIONAL — D18 (2026-09-23): a session slides on activity (AUTH_IDLE_MINUTES,
# default 30) capped by a hard ceiling from original sign-in regardless of
# activity (AUTH_SESSION_HOURS, default 8). Both are proposed defaults, not
# confirmed against this tenant's Okta SSO session policy — if Okta's own
# session outlives either one, re-auth here is likely a fast silent redirect
# rather than a real login screen. Full explanation in server/.env.example.
# AUTH_IDLE_MINUTES=30
# AUTH_SESSION_HOURS=8
# REQUIRED (in spirit — see the note below) — Okta OIDC is the only sign-in
# path (D15/D16). There is no local password anywhere in this app to fall back
# to, so without these nobody can sign in at all. Get them from the Okta app

Binary file not shown.

Before

Width:  |  Height:  |  Size: 307 KiB

After

Width:  |  Height:  |  Size: 382 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 260 KiB

After

Width:  |  Height:  |  Size: 315 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 169 KiB

After

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 125 KiB

After

Width:  |  Height:  |  Size: 135 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

View File

@@ -283,9 +283,7 @@ python tests/triage_check.py # A6 - the sidebar answers the stand-up
python tests/qa_gate_check.py # CR-014/D2/D9/D10 - QA gate + capture sink 41 checks
python tests/files_check.py # CR-007/D8 - drawings upload + real offline 36 checks
python tests/sticky_bar_check.py # B6 - save reachable on every wizard step 12 checks
# tests/usage_check.py (D5) removed at T11.6 - it tested the per-browser
# analytics core and admin report, both retired in favour of CR-019's
# server-side Activity & usage card (see docs/waves/decisions-2026-09-17.md).
python tests/usage_check.py # D5 - one analytics core, admin report 15 checks
python tests/creator_dialogs_check.py # S1 creator - 0 natives, errors at fields 20 checks
```
@@ -318,6 +316,17 @@ python tests/critical_reopen_check.py # BL-021 - on-hold mail reaches PM + CM
python tests/console_dialogs_check.py # BL-024 - consoles/launcher: 21 natives -> 0 17 checks
```
Wave 12 (CR-020, bulk user editing) adds these:
```bash
python tests/bulk_users_check.py # CR-020 - bulk routes, guards, audit, CSV; NO browser 61 checks
python tests/bulk_users_ui_check.py # CR-020 - selection, toolbar, CSV, typed delete at 1440/390px
```
`console_dialogs_check.py` gained section 4 (the bulk delete prompt). `tests/cdp.py`
passes `--do-not-de-elevate` on Windows so the probes start from an Administrator
shell (same change as wave 16, T16.4).
**Three probes were re-pointed at `T7.1`.** `sections_check.py` 5b drove the live
cross-frame toggle hand-off, which no longer exists; it now pins the surviving path and
the fact that an UNSAVED toggle correctly does not travel - a behaviour change, recorded

View File

@@ -662,3 +662,37 @@ deliberately deferred.
worth confirming rather than assuming).
- **Suggested wave or follow-up:** next housekeeping pass — needs Nick on
whether to delete, archive, or rewrite it as historical record.
### BL-060 — A super user is told they can change access the server then refuses
- **Found during:** T12.6 (CR-020 verification, the CSV path)
- **Where:** `server/app.py` `manage_user_problem` (the reason text), `get_user_projects` / `set_user_projects` (the rule)
- **What:** for an account that is also on a project the super user does not
administer, the refusal reason ends "You can still change their access and
role on your own projects." Neither the project-access dialog's routes nor
the CR-020 bulk project route allow that: all of them call
`require_manage_user`, which refuses the account. The bulk route mirrors the
single route on purpose (CR-020: same rules), so the words promise something
neither path does. Either the text or the rule is wrong; which one is a
product call.
- **Why not now:** changing either is out of CR-020's scope (the wave must
not widen what a super user can do), and it needs a decision.
- **Suggested wave or follow-up:** needs Nick: should a super user be able to
add or remove a shared account on their own projects? Then fix the text or
the rule, not both.
### BL-061 — The sync badge covers controls while it shows
- **Found during:** T12.6 (the wave 12 screenshots)
- **Where:** `html/project-data.js` `renderSyncBadge` (fixed bottom-right, `z-index:9998`)
- **What:** for about 2 seconds after each sync the "Everything sent to the
project" badge sits over whatever is in the bottom-right corner: a Delete
button on the User Directory at 1440px, the bulk bar's "Set permissions" at
390px. It is `pointer-events:none`, so clicks pass through, but the control is
hidden while it shows, and on the console pages there is no outbox work to
report at all.
- **Why not now:** `project-data.js` is shared by every page and owned by the
outbox work in wave 14 (T14.1 to T14.3 change this badge's states anyway).
- **Suggested wave or follow-up:** wave 14, alongside T14.1's badge changes:
do not show the badge on pages with nothing to sync, and keep it clear of
page controls.

View File

@@ -200,6 +200,21 @@ bad multi-select now removes more than one account at once, permanently.
version is a materially different (and riskier) feature if that turns out to
be what's actually wanted.
### Confirmed 2026-10-06 (Matt Mabrey, at the start of wave 12)
Both recommendations above are confirmed as written, and the two details
`wave-12.md` left to the build are decided:
1. **Bulk delete:** the dialog lists the affected usernames and the request is
not sent until the word `DELETE` is typed, whatever the count.
2. **Project assignment is add/remove** to or from one project at a time, with
the per-project permissions role (`ProjectMember.role`) set on add. It never
replaces a user's whole project list.
3. **Changing the table filter clears the selection** (T12.2), and the toolbar
says so, so no row hidden by the filter stays selected.
4. **The CSV holds usernames only** (T12.4). The action and its settings are
chosen in the toolbar and apply to every valid row of the file.
### Frontend/backend boundary
Selection state (which rows are checked) is fine as client-side UI state — it

View File

@@ -1,85 +0,0 @@
# Session notes — 2026-09-23
Working notes for the `feat/waves-11-13` line (CR-019, CR-020 reserved, D18),
written up before merge. Not a spec document — `wave-11.md`, `wave-13.md` and
`decisions-2026-09-17.md` are the source of truth for scope and acceptance
criteria. This is the "what actually happened building it" record.
## What shipped today
**CR-019 (wave 11) — usage/activity metrics, T11.1 through T11.6 complete:**
- `UsageEvent` table + migration (T11.1), a capture endpoint wired into
`auth-guard.js` so every protected page pings it once per load, plus a
`login` event at Okta sign-in (T11.2).
- `GET /api/usage/summary` (T11.3) — active users by day/week/month,
per-user last-active, per-tool breakdown, filterable by date/project/
user/tool, all combinable.
- `GET /api/usage/export` (T11.4) — raw and sanitized CSV. Sanitized mode
replaces the username with an HMAC-SHA256 pseudonym (keyed with
`auth.SECRET_KEY`), stable per user across rows and across separate
export calls, so an external tool (Power BI etc.) can still group by
user without ever seeing a real name.
- A new "Activity & usage" card in the admin console (T11.5): real filter
controls, the summary tables, both export buttons. Client-side gated
admin-only same as the rest of the console; the API underneath is
independently gated server-side regardless.
- Retired the old per-browser "Usage logs" panel and `wp-usage.js`
entirely (T11.6) — it had no reader left and was never a real data
source for the new report anyway. The scattered `track()` call sites in
the creator and wizard were left in place calling a documented no-op,
rather than deleting ~45 individual call sites for the same effect.
Only **T11.7 (final wave verification)** is left before wave 11 is fully
closed out — everything under it has already been verified per-task, so
this is a consolidation pass, not new work.
**D18 (wave 13) — Okta/AD deprovisioning, T13.1 only:**
- Session lifetime changed from one flat `AUTH_SESSION_HOURS` to a sliding
idle timeout (`AUTH_IDLE_MINUTES`, default 30) capped by a hard ceiling
from original sign-in (`AUTH_SESSION_HOURS`, default 8, meaning changed
from "session length" to "absolute ceiling"). Both defaults are flagged
in `.env.example` and `DEPLOYMENT.md` as proposed, not confirmed against
the tenant's actual Okta SSO policy.
- **T13.2 onward (the actual Okta Management API sync job) is paused** —
explicit call from Matt: no Okta API credential yet, come back to it
later. Not started, not blocked on anything code-side.
**CR-020 (wave 12, bulk user editing):** not started. Reserved, scoped in
`wave-12.md`, no code touched.
## Environment work (not itself a task, but load-bearing)
- Fixed a CRLF/LF mismatch that was making every tracked file look modified
to this session's git client (`core.autocrlf true`, repo-local, no file
content changed).
- This machine had no Python. Installed it via `winget` (`Python.Python.3.12`)
and set up a `.venv` in the repo with `server/requirements.txt` installed,
specifically so `tests/baseline_shots.py` could run locally — this
sandbox has no headless-capable browser and can't download one (network
allowlist), so the 390px/1440px screenshot verification CLAUDE.md asks
for had to run on Matt's own machine instead, using the browser already
installed there (Edge).
- Established a repeatable local verification loop for every task: throwaway
SQLite, fake-Okta sign-in, promote to admin, `seed_demo.py` +
`smoketest.py` (27/27 passing throughout), plus `baseline_shots.py` for
anything touching `html/`.
## Standing constraints, still in effect
- Everything stays local on this branch line. No `git push` at any point
today.
- One task per PR discipline was kept even though all of it landed on one
branch — each commit corresponds to exactly one task ID, in wave order,
each individually verified before the next started.
## Before merging
- Run T11.7 (full wave-11 verification pass) and record it in `wave-11.md`.
- Decide where this branch actually merges to — `feat/waves-11-13` has all
of today's commits already; this notes branch was cut from it so it can
fast-forward back in, or merge as its own PR if the notes should be
reviewed separately from the code.
- T13.2+ and all of wave 12 remain explicitly out of scope until Matt says
otherwise.

View File

@@ -1,280 +0,0 @@
# Wave 11 — Usage and activity metrics
**Items:** `CR-019`
**Depends on:** wave 10 merged (it is; this wave does not wait on anything else)
**Decision record:** `docs/waves/decisions-2026-09-17.md`
Seven tasks, one concern each, in build order. Do not start a task whose
dependency is not merged. `CR-020` (bulk user editing) is reserved but not
scoped — it does not belong in this wave.
---
### T11.1 — CR-019: `usage_events` table + migration
- **Items:** `CR-019`
- **Depends on:** nothing (first task)
- **Blocks:** T11.2
- **Surface:** `server/`
- **Files:** `server/models.py`, `server/alembic/versions/`
**Do:** Add a `UsageEvent` model — append-only, same spirit as `AuditLog` but for
navigation/feature-open events rather than business mutations. Suggested shape:
`id`, `at` (indexed), `user_id` (or username — match whatever `AuditLog.actor`
does today for consistency), `project_id` (nullable — not every event is
project-scoped, e.g. opening the admin console), `tool` (e.g. `creator`,
`wizard`, `field_view`, `dashboard`, `admin`, `directory`), `event` (e.g.
`page_open`, `login`), `detail` (JSON, optional). Write the migration. Do not
touch `AuditLog` — this is a new table, not an extension of it (see the
decision record's reasoning).
**Do not:** fold this into `AuditLog`. They serve different questions and mixing
them makes the existing audit trail noisier for its existing readers.
**Done when:**
- [ ] `UsageEvent` exists with an indexed `at` column (this table will be scanned
by date range constantly)
- [ ] migration applies cleanly against both SQLite (dev) and Postgres (prod) —
render `alembic upgrade --sql` for postgresql and read it before calling
this done, per the class of defect `BL-027` logged
- [ ] no change to `AuditLog`'s shape or behavior
---
### T11.2 — CR-019: capture the events
- **Items:** `CR-019`
- **Depends on:** T11.1
- **Blocks:** T11.3
- **Surface:** `server/` + `html/`
- **Files:** `server/app.py` (new endpoint), `html/auth-guard.js`
**Problem:** Six pages need this and none should implement it separately — that
is exactly how `S4`'s "no global nav on two pages" and the four parallel token
systems (`S5`) happened. `auth-guard.js` is already loaded first, in the `<head>`,
on all six protected pages (`index.html`, `field.html`, `users.html`,
`wp-creation-index.html`, `work-package-suite.html`, `admin.html`) and already
knows the verified user once the `wp-auth-ready` event fires. That is the one
place this belongs.
**Do:** Add a small `POST /api/usage/ping`-style endpoint that writes one
`UsageEvent` row per call, keyed to the session (server trusts the session, not
anything the client claims about identity). Call it once from `auth-guard.js`
after `wp-auth-ready`, tagging `tool` from the page's own path. Also write a
`login` event at the point a session is actually established (reuse whatever
`okta_callback` already does at sign-in — do not add a second source of truth
for "did this person log in").
**Do not:** build a per-page capture call. If a page needs this and
`auth-guard.js` does not cover it, fix `auth-guard.js`, not the page.
**Done when:**
- [ ] one `page_open` event is recorded for a real sign-in on each of the six
pages, verified per page
- [ ] exactly one `login` event per Okta sign-in, not one per page load after
it
- [ ] the endpoint rejects a request with no valid session (this is server-
enforced identity, not client-reported)
- [ ] no page other than `auth-guard.js` calls this endpoint directly
---
### T11.3 — CR-019: aggregation endpoint with filters
- **Items:** `CR-019`
- **Depends on:** T11.2
- **Blocks:** T11.4, T11.5
- **Surface:** `server/`
- **Files:** `server/app.py`
**Do:** Build the read side: active-user counts by day/week/month, per-user
last-active timestamp (derived from `UsageEvent`, not `User.last_login_at`,
which only ever holds one value), and a per-tool usage breakdown. Accept query
filters: date range, project, user, tool — combinable, per the decision record.
This is server aggregation, the same principle `B4` established for the
pipeline strip: the browser asks for a number, the server computes it from real
rows, nothing is derived client-side from a partial cache.
**Done when:**
- [ ] active-user counts are correct against a seeded fixture with known dates
- [ ] filters combine correctly (verified: user + date range + tool together
narrows correctly, not just each alone)
- [ ] a project filter that matches nothing returns an empty result, not an
error or the unfiltered total
---
### T11.4 — CR-019: export, raw and sanitized
- **Items:** `CR-019`
- **Depends on:** T11.3
- **Blocks:** T11.5
- **Surface:** `server/`
- **Files:** `server/app.py`
**Do:** A CSV export endpoint over the same filtered query T11.3 exposes.
Two modes: raw (real usernames, the console's default) and sanitized. Sanitized
mode replaces the actor field with a stable pseudonymous id — a per-user hash,
consistent across rows in the same export and across separate export runs —
so an external system (Power BI or similar) can still group and trend "by
user" without ever receiving a real name. Do not simply drop the identity
column; that breaks per-user grouping downstream, which defeats the point of
an activity export.
**Done when:**
- [ ] raw export contains real usernames
- [ ] sanitized export never contains a real username or email anywhere in the
file, including in a `detail` blob if one is included
- [ ] the same real user maps to the same pseudonymous id within one export AND
across two separate export runs (a hash of something stable, not a
per-request random id)
- [ ] both modes otherwise contain identical rows for the same filter
---
### T11.5 — CR-019: admin console Activity tab
- **Items:** `CR-019`
- **Depends on:** T11.3, T11.4
- **Blocks:** T11.7
- **Surface:** `html/`
- **Files:** `html/admin.html`, `html/admin.js`
**Do:** New tab, same role gate as the User Directory. Filters (date range,
project, user, tool) driving the tables from T11.3; export buttons (raw and
sanitized) calling T11.4. Build accessible from the start per `C1` — this is a
new component, not a legacy one carrying an old defect forward: real
`<button>`/`<select>` controls, keyboard-reachable, `aria-live` on any
count that updates without a page reload, focus visible throughout.
**Done when:**
- [x] the tab is reachable only by an admin (the card lives inside admin.html,
already gated client-side by gateByRole(); the API underneath it is
independently gated server-side by require_user_manager regardless)
- [x] every filter is a real form control, keyboard-operable (date/select/text
inputs and a `<button>`, no click-div)
- [x] both export buttons produce the files T11.4 defines (verified against
the live endpoint in T11.4's own checks, and present/wired here)
- [x] works at 390px and 1440px — verified 2026-09-23 via
`tests/baseline_shots.py --pages admin` run locally on Windows (this
sandbox has no headless browser available; the script was run on the
user's machine instead, after installing Python via winget since it
wasn't present). Screenshots in `docs/reference/baseline/admin-390.png`
/ `admin-1440.png`. No JS errors, no horizontal overflow at either
width; the card rendered with real seeded data (events, by-tool,
per-user-last-active tables) confirming the filters and summary read
correctly, not just that the markup exists.
---
### T11.6 — CR-019: retire the per-browser Usage report
- **Items:** `CR-019`
- **Depends on:** T11.5
- **Blocks:** T11.7
- **Surface:** `html/`
- **Files:** `html/admin.js` (the `usage-admin` panel, `admin.js:666-699`),
`html/wp-usage.js` and its two call sites
**Do:** Remove the old per-browser `usage-admin` panel from `admin.js` now that
the real one exists, per the 2026-09-17 decision. Decide what happens to
`wp-usage.js`'s recording calls (wizard dwell-tracking, the creator's
equivalent): they were never reliably tied to a real identity, so they are not
a data source the new report can adopt. Default to removing the recorder too
unless it is still doing something useful on its own (re-read what it actually
records before deciding — do not assume from this file alone).
**Do not:** leave the old panel in place "just in case." Two activity reports
showing two different numbers is worse than one.
**Decision (2026-09-23):** `wp-usage.js` is removed, not kept — it had no
reader left once the admin panel above it was removed (the "download the
full event log" button lived only in that panel), and per the original
decision record it was never reliably tied to a real identity, so it was
never a candidate source for the new report either. The file itself and its
three `<script>` includes (`admin.html`, `wp-creation-index.html`,
`work-package-suite.html`) are gone. Its two call sites
(`wp-creation-app.js`, `work-package-suite-app.js`) keep a local `track()`
function as a documented no-op rather than having each of their ~45
individual `track('event', …)` call sites deleted one at a time — that
would be a far larger, riskier diff for the same outcome (no more data is
recorded either way), and it keeps each call site as a marker of what was
worth recording if usage analytics are ever rebuilt server-side. The
dwell-timer plumbing that only ever fed `track()` (`work-package-suite-app.js`'s
`_stepEnter`/`trackStepDwell`) was left in place for the same reason — it is
inert now, not broken, and touching it buys nothing.
Also removed: `tests/usage_check.py` (tested exactly the retired feature —
D5/T7.10's per-browser analytics core and admin report) and its line in
`docs/reference/file-map.md`, replaced with a note pointing at this decision.
**Done when:**
- [x] the old `usage-admin` panel and its markup are gone from `admin.html`/
`admin.js`
- [x] a decision on `wp-usage.js` itself is recorded (removed, or kept with a
stated reason) — not left ambiguous — see above
- [x] nothing else in the app references the removed code; grep confirms
(only remaining hits are this file, the 2026-09-17 decision record, and
the two explanatory code comments left at the retired call sites — all
prose, not live references)
---
### T11.7 — CR-019: verification
- **Items:** `CR-019`
- **Depends on:** T11.6
- **Blocks:** nothing
- **Surface:** `html/` + `server/`
- **Files:** as touched above
**Do:** Full verification per `CLAUDE.md`: run the app locally, exercise the
new tab at 390px and 1440px, before/after screenshots, run the existing smoke
test and `seed_demo.py`, run the full suite.
**Done when:**
- [x] all `CR-019` acceptance criteria in `decisions-2026-09-17.md` are met or
a failure is stated with a reason — all met
- [x] screenshots committed — `admin-390.png`/`admin-1440.png` (and
`creator`/`sop` at both widths, touched by T11.6's script-tag removal)
- [x] smoke test and `seed_demo.py` both still pass — 27/27, verified
2026-09-24 against the exact branch state about to be considered
deployable
- [x] full test suite passes — verified 2026-09-24: ran all 39
`tests/*_check.py` scripts plus the `usage_events` migration
round-trip. Result: 38/39 exit 0.
- `token_check.py` exits 2 with no arguments by design (needs `--out`
or `--compare`) — a CLI-invocation detail, not a test failure;
already confirmed non-regression in wave 10.
- `generalinfo_check.py` has one pre-existing failure (a raw colour
literal in `html/wp-creation-styles.css`, a file no wave 11/13 task
touched) — already diagnosed as pre-existing in wave 10.
- `autosave_check.py` **did** regress from T11.6 (it asserted the
retired analytics tracker still wrote to localStorage) — found by
this run, fixed same day (commit `4f3a94b`), now 33/33.
- Migration (T11.1): SQLite upgrade → downgrade → upgrade round-trip
clean; `alembic upgrade ... --sql` against the `postgresql` dialect
renders valid DDL (`TIMESTAMP WITH TIME ZONE`, `JSON`, no
SQLite-only syntax) — no `BL-027`-class defect.
---
## Wave 11 exit criteria
- [x] real, server-side activity data exists per user, indefinitely retained
- [x] the admin console shows it, filterable by date/project/user/tool
- [x] export works in both raw and sanitized form
- [x] the old per-browser report is gone, not duplicated
- [x] `CR-019` fully accounted for, no open acceptance criteria
Wave 11 is closed out as of 2026-09-24. `CR-020` (wave 12) remains reserved
and unstarted. `D18`/wave 13 (`T13.2` onward) remains paused pending an Okta
API credential, per standing instruction — `T13.1`'s session changes were
included in this same verification pass and did not regress anything above.

View File

@@ -3,7 +3,14 @@
**Items:** `CR-020`
**Depends on:** wave 10 merged (it is). Independent of wave 11 (`CR-019`) — no
shared files, may build in either order or in parallel.
**Decision record:** `docs/waves/decisions-2026-09-17.md`
**Decision record:** `docs/waves/decisions-2026-09-17.md` (open details
confirmed 2026-10-06, see "Confirmed 2026-10-06" in the CR-020 section)
**Branch (decided 2026-10-06):** `feat/wave-12-bulk-users`, cut from `main`
(`df20b8f`, production). Only this file and the decision record come across
from `feat/waves-11-13`, so the PR into `main` is wave 12 alone: no wave 11
code and no T13.1, which must not reach `main` before T14.1. Wave 16 is not
merged yet; it touches different functions, and whichever lands second rebases.
Six tasks, in build order.
@@ -38,15 +45,15 @@ exist for the single case — bulk delete stays a hard delete, matching
**Done when:**
- [ ] each of the four bulk actions is callable with a list of user ids and a
- [x] each of the four bulk actions is callable with a list of user ids and a
single set of parameters
- [ ] a batch containing the actor's own account rejects only that row, not
- [x] a batch containing the actor's own account rejects only that row, not
the whole batch — verified for disable, demote, and delete
- [ ] a super user's batch that includes a user/project outside what they
- [x] a super user's batch that includes a user/project outside what they
manage rejects only that row, with a stated reason
- [ ] every successful row produces its own `AuditLog` entry, identical in
- [x] every successful row produces its own `AuditLog` entry, identical in
shape to what the single-user endpoint would have written
- [ ] a batch with some failing rows still applies to the rows that succeed,
- [x] a batch with some failing rows still applies to the rows that succeed,
and the response lists exactly which rows failed and why
---
@@ -67,12 +74,12 @@ disappears at zero.
**Done when:**
- [ ] select-all selects exactly the rows currently visible under the active
- [x] select-all selects exactly the rows currently visible under the active
filter, not the full unfiltered table
- [ ] changing the filter while rows are selected does something sane and
- [x] changing the filter while rows are selected does something sane and
visible (either clears the selection or keeps it explicit which rows are
still selected) — pick one and state it, don't leave it undefined
- [ ] the toolbar is keyboard-reachable and only present when >=1 row is
- [x] the toolbar is keyboard-reachable and only present when >=1 row is
selected
---
@@ -97,13 +104,13 @@ partial failure.
**Done when:**
- [ ] role change, activate/disable, and project assignment each work end to
- [x] role change, activate/disable, and project assignment each work end to
end against a multi-row selection
- [ ] the confirmation dialog names the exact affected count before anything is
- [x] the confirmation dialog names the exact affected count before anything is
sent
- [ ] a batch with a partial failure shows which rows failed, not just an
- [x] a batch with a partial failure shows which rows failed, not just an
undifferentiated error
- [ ] `aria-live` announces the outcome
- [x] `aria-live` announces the outcome
---
@@ -123,11 +130,11 @@ T12.1 endpoints, not a third implementation of the bulk logic.
**Done when:**
- [ ] a CSV with a mix of valid and invalid usernames applies to the valid
- [x] a CSV with a mix of valid and invalid usernames applies to the valid
rows and reports the invalid ones by row, with a reason
- [ ] the same permission/self-action guards from T12.1 apply here — a CSV
- [x] the same permission/self-action guards from T12.1 apply here — a CSV
cannot reach a user a checkbox-driven batch couldn't
- [ ] duplicate usernames in one CSV are handled without double-applying or
- [x] duplicate usernames in one CSV are handled without double-applying or
erroring confusingly
---
@@ -150,10 +157,10 @@ change it, not a reason to skip building a real confirmation now.
**Done when:**
- [ ] the affected usernames are listed in the confirmation dialog before
- [x] the affected usernames are listed in the confirmation dialog before
delete is sent
- [ ] the request is not sent until the confirmation phrase is typed correctly
- [ ] the actor's own account, if somehow selected, is rejected with a clear
- [x] the request is not sent until the confirmation phrase is typed correctly
- [x] the actor's own account, if somehow selected, is rejected with a clear
reason rather than silently included or silently dropped
---
@@ -173,21 +180,84 @@ suite.
**Done when:**
- [ ] all `CR-020` acceptance criteria in `decisions-2026-09-17.md` are met or
- [x] all `CR-020` acceptance criteria in `decisions-2026-09-17.md` are met or
a failure is stated with a reason
- [ ] screenshots committed
- [ ] smoke test and `seed_demo.py` both still pass
- [ ] full test suite passes
- [x] screenshots committed
- [x] smoke test and `seed_demo.py` both still pass
- [x] full test suite passes
---
## Wave 12 exit criteria
- [ ] all four bulk actions work against both a checkbox selection and a CSV
- [x] all four bulk actions work against both a checkbox selection and a CSV
upload
- [ ] every existing single-user guardrail (self-action, scope, grantable
- [x] every existing single-user guardrail (self-action, scope, grantable
roles) holds under bulk use
- [ ] bulk delete requires typed confirmation and lists affected usernames
- [ ] partial failures are always reported, never hidden behind a blanket
- [x] bulk delete requires typed confirmation and lists affected usernames
- [x] partial failures are always reported, never hidden behind a blanket
success
- [ ] `CR-020` fully accounted for, no open acceptance criteria
- [x] `CR-020` fully accounted for, no open acceptance criteria
## Verification record
Built 2026-10-06 on `feat/wave-12-bulk-users`
(from `main`, `df20b8f`), one commit per task. Run in the build sandbox (Linux,
Python 3.10, no browser).
| Check | Result |
|---|---|
| `tests/bulk_users_check.py` (new, no browser) | **61/61**: all four actions, own-row refusals, super-user scope, per-row audit in the single route's shape, partial failure, project add/remove keeping other projects and roles, CSV resolve, 403/401/422 gates |
| Same check against `main` | 7/18: the 7 single-route checks pass; every bulk check fails, because the routes do not exist there |
| Single-user routes before/after (16 calls: 200/400/403/404, as admin and super user) | **Identical** responses, audit rows and memberships against `main`. The routes now call the same `apply_*` functions as the bulk routes |
| Page logic, DOM harness (jsdom, the real `users.html` and scripts, mocked API) | **48/48**: selection, select-all over the filtered rows, filter clears selection, toolbar, confirm counts, per-row report, CSV, typed DELETE |
| Same flows, jsdom against a real server seeded by `browser_check.seed()` | **13/13**, including the CSV report texts the browser probe expects |
| `server/smoketest.py` | **27/27** |
| `server/seed_demo.py` | Seeds the demo project |
**Decisions applied (confirmed 2026-10-06):** typed `DELETE`; project assignment
is add/remove per project, with the per-project role (`ProjectMember.role`) set
on add; filter or search change clears the selection; CSV holds usernames only.
A row already in the requested state reports `unchanged` and writes no audit
row (nothing changed). An email address in the CSV resolves only when exactly
one account has it.
**Found and logged, not fixed:** BL-060, a super user's refusal reason promises
a project-access change that neither the dialog nor the bulk route allows.
**Browser probes, run 2026-10-06 on Matt's machine (Windows, Chrome 153 / Edge 154,
`.venv`), one at a time:**
| Probe | Result |
|---|---|
| `tests/bulk_users_ui_check.py` (new) | **19/19**: selection, Space on a row box, role change, super-user CSV (another job / not found / herself / duplicate, each by line), add-to-project with a role, typed DELETE, 390px bar fit, no JS errors |
| `tests/console_dialogs_check.py` | **16/16**, including the new section 4 (bulk delete prompt, natives poisoned) |
| `tests/mobile_check.py` | **24/24**, users page included |
| `tests/a11y_check.py` | **22/22**: users page 66 focusable elements, all with a visible ring; helper text 5.02:1 at worst |
| `tests/browser_check.py` | **67/71**, then re-pointed (below); **rerun after the re-point: all passed** (reported by Matt, 2026-10-06) |
**`browser_check.py` re-pointed (T12.6).** Its four failures were assertions
written against column POSITIONS: the manager table had 9 columns, and the
own-row checks read `r.cells[3]` (Permissions) and `r.cells[4]` (Project role).
CR-020's selection column is first, so the table has 10 and those indexes
landed on Username and Email. Not an app defect. The probe now expects 10
columns with the selection column first, finds the two cells by their header
name rather than their position (so the next column cannot break it the same
way), and adds one check: your own row has no selection box. Verified against
the real page in the DOM harness, then rerun in the browser: all passed.
**Screenshots** (after; the before-shots are `baseline/users-1440.png` and
`baseline/after-wave9/users-390.png`): `baseline/wave-12/users-1440.png`,
`users-1440-selected.png`, `users-390.png`, `users-390-selected.png`. Reviewed:
the bar, its four groups and the selected-row marking render as designed at
both widths; nothing scrolls sideways at 390px.
**Seen in the screenshots, not caused by wave 12, logged as BL-061:** the
pre-existing sync badge ("Everything sent to the project", `project-data.js`)
is drawn over a row's Delete button at 1440px and over "Set permissions" at
390px for about 2 seconds after a load. It is `pointer-events:none`, so it never
blocks a click, but it hides a control while it shows.
**Wave 12 closed 2026-10-06.** Every task done-when and every exit criterion
above is checked. Pushed as `feat/wave-12-bulk-users`; PR into `main` open.
Merge after wave 16 (`feat/wave-16-on-main`); both orders tested conflict-free.

View File

@@ -1,242 +0,0 @@
# Wave 13 — Okta/AD deprovisioning sync
**Items:** `D18`
**Depends on:** wave 10 merged (it is). Not blocked by wave 11 or wave 12, but
shares `server/app.py` account-state surface with wave 12 (`CR-020`) — sequence
commits to avoid an avoidable conflict.
**Decision record:** `docs/waves/decisions-2026-09-17.md`
Six tasks, in build order. **T13.3's fail-closed behavior is the most
important done-when list in this wave — do not relax it to ship faster.**
---
### T13.1 — D18: idle timeout with an absolute ceiling
- **Items:** `D18`
- **Depends on:** nothing (first task, independent of the rest)
- **Blocks:** nothing
- **Surface:** `server/`
- **Files:** `server/auth.py`, `server/app.py` (`auth_gate` middleware),
`server/.env.example`, `DEPLOYMENT.md`
**Revised 2026-09-23** — originally just "shrink `AUTH_SESSION_HOURS`". Matt
asked whether an idle timeout would be a better fit than a flat session
length. It is, but not by itself — see the decision record's reasoning on why
idle-with-no-ceiling is actually a worse fit for this item's own threat model
than a flat expiry would have been. Build both.
**Do:**
- Add `login_at` to the JWT payload in `create_token()` — the original
sign-in time, distinct from `iat`, which becomes "when THIS token was
issued" once tokens start getting reissued. `login_at` never changes across
reissues; it's what the absolute ceiling is measured from.
- Add `AUTH_IDLE_MINUTES` (default 30). `AUTH_SESSION_HOURS` stays the name
for the absolute ceiling, default changing from 12 to a proposed 8 — update
its docstring/comment in `auth.py` and `.env.example`, since its MEANING is
changing (session length -> hard ceiling on top of a sliding idle window),
not just its value.
- In `auth_gate` (`server/app.py`), after confirming a request is
authenticated: if `now < login_at + AUTH_SESSION_HOURS` (the ceiling hasn't
passed), compute `new_exp = min(now + AUTH_IDLE_MINUTES, login_at +
AUTH_SESSION_HOURS)`. If `new_exp` is meaningfully later than the current
token's `exp` (throttle this — do not reissue on every single request, only
when enough time has passed to be worth a new cookie; a few minutes of
slack is fine), mint a refreshed token carrying forward `sub`/`username`/
`role`/`ver`/`login_at` unchanged, and set it on the response.
- If the ceiling HAS passed, do not refresh — let the existing token expire
on its own terms (it may already be invalid, or may tick over within the
idle window; either way, no new one is issued past the ceiling).
- The middleware should not need a DB round trip to do this — everything
needed (`sub`, `username`, `role`, `ver`, `login_at`) is already in the
validated claims. `get_current_user`'s existing per-request `is_active`/
`token_version` check is unaffected and still runs separately.
**Do not:** reissue the cookie on every request unconditionally — that's a
`Set-Cookie` header on every API call for no benefit over a coarser refresh.
Do not let the ceiling check silently vanish for tokens issued before this
change ships — a token with no `login_at` claim should fall back to treating
its own `iat` as `login_at`, not bypass the ceiling entirely.
**Done when:**
- [ ] a session with continuous activity stays alive past 30 minutes but is
cut off at the `AUTH_SESSION_HOURS` ceiling regardless
- [ ] a session with no activity for 30+ minutes is rejected on its next
request
- [ ] the cookie is not rewritten on every single request — verify the
refresh is throttled, not unconditional
- [ ] a pre-existing token with no `login_at` claim (simulating a session
issued before this shipped) still gets a hard ceiling, via the `iat`
fallback
- [ ] `.env.example` and `DEPLOYMENT.md` explain both variables and flag both
defaults as proposed, not confirmed against Okta's own session policy
- [ ] existing session/auth tests updated for the new mechanism, not just a
new number
---
### T13.2 — D18: Okta Management API client
- **Items:** `D18`
- **Depends on:** nothing (independent of T13.1)
- **Blocks:** T13.3
- **Surface:** `server/`
- **Files:** new `server/okta_sync.py` (or extend `server/okta_auth.py` —
task's call), `server/.env.example`
**Do:** A small client for Okta's user-list endpoint, authenticated with a new,
separate credential (e.g. `OKTA_API_TOKEN`) — not the OIDC client secret used
for sign-in. Fetch the full user list (paginated per Okta's API) rather than
one-by-one lookups per local user; this app has ~20-odd accounts today, and a
list-and-diff is simpler and cheaper than N calls. Return each Okta user's
identity-claim value (matching `OKTA_IDENTITY_CLAIM`, already confirmed live
per wave 10) and status.
Follow the existing pattern for external credentials in this repo (`MICRON_DB_URL`,
`SMTP_PASSWORD`): env-only, never logged, never returned to the browser in an
error message.
**Do not:** reuse `OKTA_CLIENT_ID`/`OKTA_CLIENT_SECRET` for this. Sign-in and
the management API are different trust boundaries with different scopes;
conflating them means a compromise or rotation of one affects the other
unnecessarily.
**Done when:**
- [ ] the client authenticates with its own credential, distinct from the OIDC
client
- [ ] it fetches the complete Okta user list, handling pagination
- [ ] an auth failure or malformed response raises a clear, specific error
rather than returning an empty list indistinguishable from "everyone was
deprovisioned" — this distinction is what T13.3 depends on
- [ ] the credential is never logged or surfaced in any API response
---
### T13.3 — D18: the sync job
- **Items:** `D18`
- **Depends on:** T13.2
- **Blocks:** T13.4
- **Surface:** `server/`
- **Files:** `server/okta_sync.py`, `server/app.py` (or wherever `log_event`
lives)
**Do:** Compare the Okta user list (T13.2) against local `users` rows. For any
local `is_active=True` user whose Okta identity is missing from the list, or
present with a non-active status, set `is_active=False` and write an
`AuditLog` row (`actor="system:okta_sync"`, action e.g.
`user_deprovisioned_by_sync`, detail naming the Okta status found). Never
touch a user already `is_active=False`. Never re-enable anyone.
**The fail-closed rule, non-negotiable:** if T13.2's client raises an error of
any kind (network, auth, malformed response, timeout), this task takes **no
action on any account** for that run and logs the failure clearly (server log,
at minimum). An error is never treated as "Okta returned zero active users."
Write a test that asserts this directly: feed the sync a failing client and
assert zero rows changed and zero `AuditLog` entries written.
**Done when:**
- [ ] a user missing from Okta's list, or present but not active, is disabled
with a correctly-detailed audit row
- [ ] a user already disabled is left alone (no duplicate audit row each run)
- [ ] an active Okta user already active locally produces no audit row (only
changes are logged, not a clean bill of health every cycle)
- [ ] **a simulated Okta API failure results in zero account changes and zero
audit rows** — this is the one check that must never be skipped or
weakened
- [ ] the job never re-enables an account under any input
---
### T13.4 — D18: run it on a schedule
- **Items:** `D18`
- **Depends on:** T13.3
- **Blocks:** T13.6
- **Surface:** `server/`, `docker-compose.yml`
- **Files:** `server/app.py` (startup hook) or a new sidecar per the `backup`
container's pattern — task's call, per the decision record's noted
alternative
**Do:** Wire T13.3 to run on an interval (proposed 15 minutes, env-overridable
— e.g. `OKTA_SYNC_INTERVAL_SECONDS`, matching `BACKUP_INTERVAL_SECONDS`'s
naming). Default choice is an in-process background task in the `api`
container; if a separate container is chosen instead, follow the `backup`
service's shape (own Dockerfile or script, `internal` network plus whatever
egress reaching Okta requires — check whether `outbound` as currently defined
is sufficient or Okta needs a distinct allowance).
**Done when:**
- [ ] the job runs automatically on the configured interval without manual
invocation
- [ ] interval is env-configurable with a sane default
- [ ] a container restart does not produce a duplicate/overlapping run, and a
slow cycle does not stack with the next one
---
### T13.5 — D18: admin visibility
- **Items:** `D18`
- **Depends on:** T13.3
- **Blocks:** T13.6
- **Surface:** `html/`
- **Files:** `html/users.js` / `html/admin.js` (wherever audit history is
already surfaced)
**Do:** Confirm an auto-disable reads clearly wherever admins already look at
account history — the actor string (`system:okta_sync`) should be
self-explanatory in context, not require reading server logs to understand.
Do not build new UI beyond making sure the existing audit surface renders this
actor sensibly. Email/notification to admins on auto-disable is a noted
fast-follow (the decision record flags it as open, not required here) — do not
build it in this task; log it instead if it's tempting to add.
**Done when:**
- [ ] an auto-disabled account's audit entry is visible and legible in the
existing admin UI without special-casing
- [ ] nothing here silently assumes `CR-019`'s activity view exists yet — this
must work standalone
---
### T13.6 — D18: verification
- **Items:** `D18`
- **Depends on:** T13.4, T13.5
- **Blocks:** nothing
- **Surface:** `server/`
- **Files:** as touched above
**Do:** Full verification per `CLAUDE.md`. Beyond the usual run: specifically
re-run T13.3's fail-closed test in isolation and confirm it still passes after
T13.4's scheduling wrapper is in place — the scheduling layer must not
introduce a path that swallows the client's error and proceeds anyway.
**Done when:**
- [ ] all `D18` acceptance criteria in `decisions-2026-09-17.md` are met or a
failure is stated with a reason
- [ ] the fail-closed behavior is verified end to end through the scheduled
wrapper, not just the bare sync function
- [ ] smoke test and `seed_demo.py` both still pass
- [ ] full test suite passes
---
## Wave 13 exit criteria
- [ ] `AUTH_SESSION_HOURS` defaults to 2, documented
- [ ] the sync job runs on a schedule and correctly disables accounts Okta no
longer shows as active
- [ ] every auto-disable is individually audited with a clearly non-human actor
- [ ] an Okta API failure of any kind changes zero accounts — verified, not
assumed
- [ ] the sync never re-enables an account
- [ ] `D18` fully accounted for, no open acceptance criteria

View File

@@ -34,12 +34,12 @@
/* Every container admin.js paints a table into is a scrollport of its own, so a
sticky header always has something to stick to rather than sliding up behind
the app bar. Same rule as console.css's .tscroll. */
#comments-admin, #audit-admin, #notif-box, #activity-admin, #projects-table, #defmem-table{
#comments-admin, #audit-admin, #notif-box, #usage-admin, #projects-table, #defmem-table{
overflow:auto; max-height:min(70vh,640px); overscroll-behavior:contain; }
/* If admin.js wraps its table in its own .tscroll, the outer box steps aside so
one table never ends up with two scrollbars. */
#comments-admin:has(.tscroll), #audit-admin:has(.tscroll), #notif-box:has(.tscroll),
#activity-admin:has(.tscroll), #projects-table:has(.tscroll), #defmem-table:has(.tscroll){
#usage-admin:has(.tscroll), #projects-table:has(.tscroll), #defmem-table:has(.tscroll){
overflow:visible; max-height:none; }
/* Comment text and audit detail are the two columns you are actually here to
@@ -53,7 +53,7 @@
border:1px solid var(--border-strong); border-radius:0; margin-bottom:var(--s3); }
@media (max-width:900px){
#comments-admin, #audit-admin, #notif-box, #activity-admin, #projects-table, #defmem-table{
#comments-admin, #audit-admin, #notif-box, #usage-admin, #projects-table, #defmem-table{
max-height:none; }
}
</style>
@@ -175,38 +175,16 @@
<div id="audit-admin" class="note">Click refresh to load.</div>
</div>
<!-- ACTIVITY &amp; USAGE (CR-019) -->
<!-- USAGE LOGS -->
<div class="card">
<h2>Activity &amp; usage</h2>
<div class="sub">Who is using the suite, which tools, and how often — recorded server-side on every
sign-in and page open, kept indefinitely. Filter below, or export a CSV: raw (real usernames) for
internal use, or sanitized (each user replaced with a stable, non-reversible id) for feeding into
Power BI or another external reporting tool without carrying real identities.</div>
<h2>Usage logs</h2>
<div class="sub">Engagement recorded by both tools — the work package creator and the SOP wizard —
sessions, actions and counts, with a download per tool (D5). Note: stored locally per browser,
so this reflects activity on <strong>this</strong> machine.</div>
<div class="toolbar">
<label for="act-from">From</label>
<input type="date" id="act-from" onchange="loadActivity()">
<label for="act-to">To</label>
<input type="date" id="act-to" onchange="loadActivity()">
<select id="act-project" onchange="loadActivity()"><option value="">All projects</option></select>
<input id="act-user" placeholder="Username…" oninput="loadActivity()">
<select id="act-tool" onchange="loadActivity()">
<option value="">All tools</option>
<option value="launcher">Launcher</option>
<option value="wizard">SOP wizard</option>
<option value="creator">Work package creator</option>
<option value="field_view">Field view</option>
<option value="admin">Admin console</option>
<option value="directory">User directory</option>
</select>
<button onclick="loadActivity()">Refresh</button>
<button onclick="loadUsage()">Refresh</button>
</div>
<div id="activity-banner" class="banner" style="display:none"></div>
<div id="activity-admin" class="note">Loading…</div>
<div class="toolbar" style="margin-top:var(--s3)">
<button onclick="exportActivity(false)">Download CSV (raw)</button>
<button onclick="exportActivity(true)">Download CSV (sanitized)</button>
</div>
<div id="activity-export-banner" class="banner" style="display:none"></div>
<div id="usage-admin" class="note">Click refresh to load.</div>
</div>
<!-- DB SNAPSHOT -->
@@ -237,6 +215,7 @@
</div>
</div>
<script src="wp-usage.js"></script>
<script src="console-util.js"></script>
<script src="wp-dialog.js"></script>
<script src="admin.js"></script>

View File

@@ -24,7 +24,7 @@ function reveal(){
loadNotifications();
loadComments();
loadAudit();
loadActivity();
loadUsage();
}
function showDenied(){
document.getElementById('admin-denied').style.display='';
@@ -189,19 +189,6 @@ async function loadProjects(){
banner.style.display='none';
_adminProjects = json;
renderProjects();
populateActivityProjectFilter();
}
// The activity project filter reuses the same project list the Projects card
// already fetched — no second /api/projects call just to fill a <select>.
function populateActivityProjectFilter(){
const sel = document.getElementById('act-project');
if(!sel) return;
const cur = sel.value;
sel.innerHTML = '<option value="">All projects</option>' +
_adminProjects.slice().sort((a,b)=>String(a.name||'').localeCompare(String(b.name||'')))
.map(p => '<option value="'+uesc(p.id)+'">'+uesc(p.name||p.number||p.id)+'</option>').join('');
sel.value = cur;
}
function renderProjects(){
@@ -478,90 +465,6 @@ function renderAudit(){
'</tr>').join('')+'</tbody></table>';
}
// ── activity & usage (CR-019) ────────────────────────────────────────────────────
// Server-side, per-user activity — distinct from the "Activity log" card above
// (that's AuditLog: business mutations) and from the "Usage logs" card below
// (that's per-browser localStorage, D5/T7.10, on the way out per T11.6). This is
// /api/usage/summary and /api/usage/export: real rows, aggregated server-side,
// filterable by date/project/user/tool, and exportable raw or sanitized.
function _activityFilters(){
const q = new URLSearchParams();
const from = document.getElementById('act-from').value; if(from) q.set('from', from);
const to = document.getElementById('act-to').value; if(to) q.set('to', to);
const proj = document.getElementById('act-project').value; if(proj) q.set('project_id', proj);
const user = (document.getElementById('act-user').value||'').trim(); if(user) q.set('username', user);
const tool = document.getElementById('act-tool').value; if(tool) q.set('tool', tool);
return q;
}
async function loadActivity(){
const banner = document.getElementById('activity-banner');
const box = document.getElementById('activity-admin');
if(!box) return;
banner.style.display='none';
box.textContent = 'Loading…';
const { status, json } = await api('GET', '/api/usage/summary?'+_activityFilters().toString());
if(status===403){
banner.className='banner bad'; banner.style.display='';
banner.textContent = '✕ Your account can’t see suite-wide activity here — this needs admin, or Project Super User on at least one project.';
box.innerHTML=''; return;
}
if(status!==200 || !json){
banner.className='banner bad'; banner.style.display='';
banner.textContent = '✕ Could not load activity ('+apiError(status, json, 'load failed')+').';
box.innerHTML=''; return;
}
renderActivity(json);
}
function renderActivity(sum){
const box = document.getElementById('activity-admin');
if(!sum.event_count){ box.innerHTML = '<div class="note">No activity matches this filter.</div>'; return; }
const fmt = s => s ? wpFormatDateTime(s) : '—';
const bucket = (label, obj, take) => {
const entries = Object.entries(obj).sort((a,b)=> b[0].localeCompare(a[0])).slice(0, take);
if(!entries.length) return '';
return '<table class="kv" style="margin-top:8px"><caption style="text-align:left;font-weight:600;margin-bottom:4px">'+
uesc(label)+'</caption>'+entries.map(([k,v]) => '<tr><th>'+uesc(k)+'</th><td>'+v+' active user'+(v===1?'':'s')+'</td></tr>').join('')+
'</table>';
};
const perTool = Object.entries(sum.by_tool||{});
const toolTable = perTool.length ? '<table class="users"><thead><tr><th>Tool</th><th>Events</th></tr></thead><tbody>'+
perTool.map(([t,n]) => '<tr><td>'+uesc(t||'(login)')+'</td><td>'+n+'</td></tr>').join('')+'</tbody></table>' :
'<div class="note">No per-tool data.</div>';
const perUser = Object.entries(sum.per_user_last_active||{}).sort((a,b)=> String(b[1]).localeCompare(String(a[1])));
const userTable = perUser.length ? '<table class="users"><thead><tr><th>User</th><th>Last active</th></tr></thead><tbody>'+
perUser.map(([u,t]) => '<tr><td><strong>'+uesc(u)+'</strong></td><td style="color:var(--muted)">'+fmt(t)+'</td></tr>').join('')+
'</tbody></table>' : '<div class="note">No per-user data.</div>';
box.innerHTML =
'<div class="note">'+sum.event_count+' event'+(sum.event_count===1?'':'s')+' matched.</div>'+
'<div class="row" style="gap:var(--s4);flex-wrap:wrap;align-items:flex-start">'+
'<div>'+bucket('Active users by day', sum.active_users.by_day, 30)+'</div>'+
'<div>'+bucket('Active users by week', sum.active_users.by_week, 12)+'</div>'+
'<div>'+bucket('Active users by month', sum.active_users.by_month, 12)+'</div>'+
'</div>'+
'<h2 style="margin-top:16px">By tool</h2>'+toolTable+
'<h2 style="margin-top:16px">Per-user last active</h2>'+userTable;
}
async function exportActivity(sanitize){
const banner = document.getElementById('activity-export-banner');
banner.className='banner'; banner.style.display=''; banner.textContent='Preparing export…';
const q = _activityFilters();
if(sanitize) q.set('sanitize', 'true');
const { status, json } = await api('GET', '/api/usage/export?'+q.toString());
if(status!==200 || typeof json !== 'string'){
banner.className='banner bad';
banner.textContent = '✕ Export failed ('+apiError(status, json, 'export failed')+').';
return;
}
const blob = new Blob([json], { type:'text/csv' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'usage_export_'+(sanitize?'sanitized':'raw')+'_'+new Date().toISOString().slice(0,10)+'.csv';
document.body.appendChild(a); a.click(); a.remove();
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
banner.className='banner ok';
banner.textContent = '✓ Downloaded the '+(sanitize?'sanitized':'raw')+' export.';
}
// ── notifications / email settings ──────────────────────────────────────────────
let _settings = {};
async function loadSettings(){
@@ -753,6 +656,48 @@ async function loadNotifications(){
'</tr>').join('')+'</tbody></table>';
}
// ── usage logs (read from this browser's localStorage) ──────────────────────────
// D5 / T7.10: the report for BOTH tools' recorded usage, in the one place an
// operator-facing readout belongs - behind the same admin gate as this whole
// page (gateByRole() below shows nothing else either). Data comes from
// wp-usage.js, the single implementation; the keys predate the move, so
// everything recorded before it is still here.
function loadUsage(){
const box = document.getElementById('usage-admin');
if(!box) return;
const tools = [
['Work package creator', WPUsage.KEYS.creator, 'wp-iwp-usage'],
['SOP wizard', WPUsage.KEYS.wizard, 'wp-suite-usage'],
];
let html = '';
tools.forEach(([label, key, prefix]) => {
const evs = (WPUsage.load(key).events) || [];
html += '<h2 style="margin-top:16px">' + uesc(label) + '</h2>';
if(!evs.length){
html += '<div class="note">No usage recorded in this browser yet.</div>';
return;
}
const byEvent = {}, sessions = new Set();
let first = evs[0].ts, last = evs[0].ts;
evs.forEach(e => {
byEvent[e.event] = (byEvent[e.event]||0)+1;
if(e.session) sessions.add(e.session);
if(e.ts < first) first = e.ts; if(e.ts > last) last = e.ts;
});
const fmt = v => v ? wpFormatDateTime(v) : '—';
html += '<table class="kv">'+
'<tr><th>Sessions</th><td>'+sessions.size+'</td></tr>'+
'<tr><th>Events</th><td>'+evs.length+'</td></tr>'+
'<tr><th>Range</th><td style="font-weight:600">'+fmt(first)+' → '+fmt(last)+'</td></tr></table>';
html += '<table class="users"><thead><tr><th>Event</th><th>Count</th></tr></thead><tbody>';
Object.keys(byEvent).sort().forEach(k => html += '<tr><td>'+uesc(k)+'</td><td>'+byEvent[k]+'</td></tr>');
html += '</tbody></table>';
html += '<div class="toolbar" style="margin-top:8px"><button onclick="WPUsage.download(WPUsage.KEYS.'+
(key === WPUsage.KEYS.creator ? 'creator' : 'wizard')+', ' + jsq(prefix) + ')">Download the full event log</button></div>';
});
box.innerHTML = html;
}
// ── access control: admins only ─────────────────────────────────────────────────
// auth-guard.js requires a login and sets window.WP_USER (firing 'wp-auth-ready').
// Show the console for admins; otherwise show the "Admins only" notice.

View File

@@ -125,40 +125,12 @@
// Nothing replaces it. Every signed-in page mounts the drawer, so there is no page
// left that would need a floating fallback pill.
// ── CR-019: usage ping ───────────────────────────────────────────────────
// One page_open event per authenticated load, sent from exactly ONE place
// (here) rather than from each page's own script - the shared-chrome lesson
// S4 and the token-drift lesson S5 both taught this codebase the hard way.
// Fire-and-forget: never blocks reveal(), never retries, never surfaces an
// error to the person using the app - a missed usage ping is not something
// anyone here should notice happening.
var TOOL_BY_PAGE = {
'index.html': 'launcher',
'work-package-suite.html': 'wizard',
'wp-creation-index.html': 'creator',
'field.html': 'field_view',
'admin.html': 'admin',
'users.html': 'directory'
};
function pingUsage() {
var page = (location.pathname.split('/').pop() || 'index.html');
var tool = TOOL_BY_PAGE[page] || page.replace(/\.html$/, '');
try {
fetch('/api/usage/ping', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ tool: tool })
}).catch(function () {});
} catch (e) {}
}
function proceed(user) {
clearTimeout(safety);
window.WP_USER = user;
reveal();
if (window.WP_USER) {
window.wpFlags(); // start the feature-flag fetch; pages await it as needed
pingUsage();
try { document.dispatchEvent(new CustomEvent('wp-auth-ready', { detail: window.WP_USER })); } catch (e) {}
}
}

View File

@@ -24,7 +24,10 @@
The directory is one wide table, so the column exceptions live here: email is
the one cell long enough to stretch a row, and the two role dropdowns need
room for "Assistant Project Manager" without pushing Actions off screen. */
#users-table table td:nth-child(3){ max-width:230px; overflow:hidden; text-overflow:ellipsis; }
/* The email cell, by its class: CR-020's selection column moved it from third to
fourth on the managers' table, and a position-based rule would have followed
the wrong column. */
#users-table table td.ell{ max-width:230px; overflow:hidden; text-overflow:ellipsis; }
#users-banner:not(:empty), #scope-banner:not(:empty){ margin-bottom:var(--s3); }
#nu-projects{ margin-top:var(--s2); }
#nu-projects .pickrow{ padding:var(--s1) var(--s1); }
@@ -33,6 +36,45 @@
#nu-project-list{ max-height:200px; overflow:auto; border:1px solid var(--border); }
.whoami-chip{ font-size:12px; color:var(--muted); }
.whoami-chip strong{ color:var(--text); }
/* CR-020: row selection and the bulk bar. Tokens only (the token rule). */
#sel-banner:not(:empty), #bulk-banner:not(:empty), #csv-banner:not(:empty){ margin-bottom:var(--s3); }
#bulk-banner ul, #csv-banner ul{ margin:var(--s1) 0 0; padding-left:var(--s5); font-weight:400;
max-height:220px; overflow:auto; }
#csv-btn[hidden]{ display:none; }
table.grid th.selcell, table.grid td.selcell{ width:1%; padding:0 var(--s1); text-align:center; }
/* The label is the hit area: the 16px box alone is under the 24px floor. */
.selhit{ display:inline-flex; align-items:center; justify-content:center;
min-width:28px; min-height:28px; cursor:pointer; }
.selhit input{ width:16px; height:16px; margin:0; accent-color:var(--accent); cursor:pointer; }
.selhit input:focus-visible{ outline:2px solid var(--accent); outline-offset:2px; }
.selhit input:disabled{ cursor:default; }
/* Not --accent-soft: that is the admin pill's own fill (console.css, hover note). */
table.grid tbody tr.is-selected td{ background:var(--cds-layer-selected); }
table.grid tbody tr.is-selected td.selcell{ box-shadow:inset 3px 0 0 var(--accent); }
.bulkbar{ border:1px solid var(--accent); border-left:3px solid var(--accent);
background:var(--surface); padding:var(--s2) var(--s3); margin:0 0 var(--s3); }
.bulkbar[hidden]{ display:none; }
.bulkhead{ display:flex; align-items:center; justify-content:space-between; gap:var(--s2);
flex-wrap:wrap; margin-bottom:var(--s2); }
.bulkgroup{ display:flex; flex-wrap:wrap; align-items:center; gap:var(--s2);
padding:var(--s2) 0; border-top:1px solid var(--border); }
.bulkgroup > .bulklabel{ font-size:12px; font-weight:600; color:var(--muted); min-width:110px; }
.bulkgroup select{ height:var(--ctl); padding:0 var(--s1) 0 var(--s2); font:inherit; font-size:13px;
border:1px solid var(--border-strong); border-radius:0; background:var(--surface); color:var(--text);
max-width:100%; }
.bulkgroup select:focus-visible{ outline:2px solid var(--accent); outline-offset:-2px; }
/* The bulk delete dialog lists every affected username; a long list scrolls
inside the dialog instead of pushing its buttons off the screen. */
#wp-dlg-msg{ max-height:50vh; overflow:auto; }
@media (max-width:620px){
.bulkgroup > .bulklabel{ min-width:0; flex:1 1 100%; }
.bulkgroup select, .bulkgroup button{ flex:1 1 100%; }
}
@media (pointer:coarse){
.selhit{ min-width:44px; min-height:44px; }
.bulkbar button, .bulkgroup select{ min-height:44px; }
}
</style>
</head>
<body>
@@ -63,15 +105,33 @@
<div class="sub" id="people-sub"></div>
<div class="toolbar">
<button onclick="loadUsers()">Refresh</button>
<input id="user-search" placeholder="Search name / username / email / job function…" oninput="renderUsers()">
<select id="user-filter" onchange="renderUsers()">
<input id="user-search" placeholder="Search name / username / email / job function…" oninput="filterChanged()"
aria-label="Search the directory">
<select id="user-filter" onchange="filterChanged()" aria-label="Show">
<option value="">Everyone</option>
<option value="active">Active only</option>
<option value="disabled">Disabled only</option>
<option value="mine">Accounts I manage</option>
</select>
<!-- CR-020 (T12.4): a list of usernames from a file becomes the selection.
Managers only; users.js shows it. -->
<button type="button" id="csv-btn" onclick="pickCsv()" hidden
title="A CSV with one username (or email) per line, first column. The action is chosen in the bulk bar.">Select from CSV…</button>
<input type="file" id="csv-file" accept=".csv,.txt,text/csv,text/plain" hidden>
</div>
<div id="users-banner"></div>
<div id="csv-banner"></div>
<!-- CR-020: bulk actions on the selected rows. Present only while at least one
row is selected (the hidden attribute also takes it out of the tab order). -->
<div id="bulk-bar" class="bulkbar" role="region" aria-label="Bulk actions on the selected users" hidden>
<div class="bulkhead">
<strong id="bulk-count">0 selected</strong>
<button type="button" onclick="clearSelection(true)">Clear selection</button>
</div>
<div id="bulk-actions"></div>
</div>
<div id="sel-banner"></div>
<div id="bulk-banner"></div>
<div id="users-table"><div class="note">Loading…</div></div>
</div>

View File

@@ -23,6 +23,10 @@
let _users = []; // the directory as the server scoped it
let _scope = null; // GET /api/auth/user-scope
let _meId = null;
// CR-020: the rows checked for a bulk action. Client-side UI state only - every
// bulk action is decided and audited by the server, row by row (T12.1).
let _selected = new Set();
let _shownSelectable = []; // ids the current filter shows AND this caller may select
// ── boot ──────────────────────────────────────────────────────────────────────
async function boot(){
@@ -40,6 +44,7 @@ async function boot(){
renderScope();
}
renderCreateForm();
renderBulkActions();
loadUsers();
}
@@ -90,11 +95,309 @@ async function loadUsers(){
}
banner('users-banner','', '');
_users = json;
// Fresh data: any earlier selection may name accounts that changed or are gone.
clearSelection(false);
renderUsers();
}
function manages(){ return !!(_scope && _scope.can_manage_users); }
// ── selection (CR-020, T12.2) ─────────────────────────────────────────────────
// A row is selectable when this caller may change the account. Your own row is
// not: every bulk action that could touch it (disable, demote, delete) is refused
// for your own account, so offering it would only produce a guaranteed failure.
function selectable(u){ return manages() && !!u.manageable && u.id !== _meId; }
// The search box and the filter both decide which rows are shown. Changing either
// clears the selection (decided 2026-10-06), so no row hidden by the filter can
// stay selected and be acted on without being seen.
function filterChanged(){
const had = _selected.size;
clearSelection(false);
renderUsers();
banner('sel-banner', '', had ? 'Selection cleared: the filter changed. Select the rows again.' : '');
}
function clearSelection(announce){
const had = _selected.size;
_selected = new Set();
updateSelectionUI();
banner('sel-banner', '', (announce && had) ? 'Selection cleared.' : '');
}
function setRowSelected(id, on){
if(on) _selected.add(id); else _selected.delete(id);
}
// Select-all acts on the rows the filter shows, never on the whole directory.
function toggleSelectAll(on){
_shownSelectable.forEach(id => setRowSelected(id, on));
banner('sel-banner', '', '');
updateSelectionUI();
}
// Reflect _selected into the page without re-rendering the table, so keyboard
// focus stays on the checkbox that was just used.
function updateSelectionUI(){
const wrap = document.getElementById('users-table');
if(wrap){
wrap.querySelectorAll('input.selbox').forEach(cb => {
const on = _selected.has(cb.dataset.id);
cb.checked = on;
const tr = cb.closest('tr');
if(tr) tr.classList.toggle('is-selected', on);
});
const all = document.getElementById('sel-all');
if(all){
const n = _shownSelectable.filter(id => _selected.has(id)).length;
all.checked = n > 0 && n === _shownSelectable.length;
all.indeterminate = n > 0 && n < _shownSelectable.length;
all.disabled = !_shownSelectable.length;
}
}
const bar = document.getElementById('bulk-bar');
if(bar){
const n = _selected.size;
bar.hidden = n === 0;
const c = document.getElementById('bulk-count');
if(c) c.textContent = n + ' selected';
}
}
// One listener for every checkbox in the table (event delegation): no ids are
// bound into inline handlers, so there is nothing to escape.
document.addEventListener('change', e => {
const t = e.target;
if(!(t instanceof HTMLInputElement)) return;
if(t.id === 'sel-all'){ toggleSelectAll(t.checked); return; }
if(t.classList.contains('selbox')){
setRowSelected(t.dataset.id, t.checked);
banner('sel-banner', '', '');
updateSelectionUI();
}
});
// ── bulk actions (CR-020, T12.3) ──────────────────────────────────────────────
// The toolbar offers only what this caller may do: the roles they may grant, the
// projects they administer, the per-project roles they may hand out. The server
// re-checks every row anyway (T12.1); this is so nobody is offered a choice that
// can only fail.
function renderBulkActions(){
const box = document.getElementById('bulk-actions');
const csvBtn = document.getElementById('csv-btn');
if(csvBtn) csvBtn.hidden = !manages();
if(!box || !manages()) return;
const grantable = PERM_ROLES.filter(r => (_scope.grantable_roles || []).indexOf(r) >= 0);
const projects = (_scope.managed_projects || []).slice()
.sort((a,b) => (a.archived?1:0) - (b.archived?1:0));
const projRoles = PROJECT_SCOPED_ROLES.filter(r => (_scope.grantable_project_roles || []).indexOf(r) >= 0);
const group = (label, inner) => '<div class="bulkgroup" role="group" aria-label="'+uesc(label)+'">'+
'<span class="bulklabel">'+uesc(label)+'</span>'+inner+'</div>';
box.innerHTML =
group('Permissions',
'<select id="bulk-role" aria-label="New permissions role">'+
grantable.map(r => '<option value="'+r+'"'+(r==='project_user'?' selected':'')+'>'+uesc(PERM_LABELS[r])+'</option>').join('')+
'</select>'+
'<button type="button" onclick="bulkRole()">Set permissions</button>') +
group('Sign-in',
'<button type="button" onclick="bulkActive(true)">Enable</button>'+
'<button type="button" onclick="bulkActive(false)">Disable</button>') +
(projects.length ? group('Project access',
'<select id="bulk-project" aria-label="Project">'+
projects.map(p => '<option value="'+uesc(p.id)+'">'+uesc((p.name||'(unnamed)')+(p.number?' '+p.number:'')+
(p.archived?' (archived)':''))+'</option>').join('')+
'</select>'+
'<select id="bulk-project-role" aria-label="Role on that project, for Add">'+
'<option value="">Role: same as account</option>'+
projRoles.map(r => '<option value="'+r+'">Role: '+uesc(PERM_LABELS[r])+' here</option>').join('')+
'</select>'+
'<button type="button" onclick="bulkProject(\'add\')">Add to project</button>'+
'<button type="button" onclick="bulkProject(\'remove\')">Remove from project</button>') : '') +
group('Delete',
'<button type="button" class="danger" onclick="bulkDelete()">Delete selected…</button>');
}
function selectedIds(){ return _users.filter(u => _selected.has(u.id)).map(u => u.id); }
function people(n){ return n + ' user' + (n === 1 ? '' : 's'); }
function selVal(id){ return (document.getElementById(id) || {}).value || ''; }
function selText(id){
const s = document.getElementById(id);
return (s && s.selectedIndex >= 0) ? s.options[s.selectedIndex].text : '';
}
// One path for every bulk action: confirm through the dialog kit with the exact
// count, send, report row by row, reload. A reload clears the selection, which is
// right: the rows may have changed underneath it.
async function runBulk(path, body, ask){
const ids = selectedIds();
if(!ids.length) return;
if(!(await wpConfirmDialog({title: ask.title, okLabel: ask.ok, message: ask.message(ids.length)}))) return;
return sendBulk(path, body, ask.title, ids);
}
async function sendBulk(path, body, title, ids){
bannerHtml('bulk-banner', '', uesc(title)+': working on '+uesc(people(ids.length))+'…');
const { status, json } = await api('POST', path, Object.assign({ user_ids: ids }, body));
if(status !== 200 || !json || !Array.isArray(json.results)){
bannerHtml('bulk-banner', 'bad', '✕ '+uesc(apiError(status, json, title+' failed'))+' Nothing was changed.');
return;
}
showBulkResult(json, title);
loadUsers();
}
// T12.5: delete is permanent (a hard delete, as for one account) and one bad
// multi-select now removes many, so it asks more than the other actions do:
// every affected username is listed, and nothing is sent until the word DELETE
// is typed, whatever the count (confirmed 2026-10-06). Your own account cannot
// be selected; if it ever reached the request, the server refuses that row and
// the report names it.
async function bulkDelete(){
const chosen = _users.filter(u => _selected.has(u.id));
if(!chosen.length) return;
const n = chosen.length;
const typed = await wpPromptDialog({
title: 'Delete '+people(n),
message: 'Delete '+(n === 1 ? 'this account' : 'these '+n+' accounts')+'? Each one, and every project '+
'assignment it has, is removed. This cannot be undone. Disable them instead if you only want to '+
'block sign-in.\n\n'+chosen.map(u => '• '+u.username+(u.full_name ? ' ('+u.full_name+')' : '')).join('\n'),
label: 'Type DELETE to confirm',
value: '',
okLabel: 'Delete '+people(n),
validate: v => v === 'DELETE' ? '' : 'Type DELETE, in capital letters, to confirm.',
});
if(typed !== 'DELETE') return;
return sendBulk('/api/auth/bulk-users/delete', {}, 'Delete accounts', chosen.map(u => u.id));
}
// Every row is accounted for: changed, already so, or failed with the server's
// reason. A batch that partly failed never reads as a success (CR-020).
function showBulkResult(json, title){
const failed = json.results.filter(r => r.status === 'failed');
const parts = [json.ok+' changed'];
if(json.unchanged) parts.push(json.unchanged+' already set');
if(failed.length) parts.push(failed.length+' failed');
const kind = !failed.length ? 'ok' : (json.ok + json.unchanged ? 'warn' : 'bad');
const lead = (failed.length ? (kind === 'bad' ? '✕ ' : '⚠ ') : '✓ ')+uesc(title)+': '+parts.join(', ')+'.';
const list = failed.length
? '<ul>'+failed.map(r => '<li><strong>'+uesc(r.username || r.user_id)+'</strong>: '+uesc(r.reason)+'</li>').join('')+'</ul>'
: '';
bannerHtml('bulk-banner', kind, lead + list);
}
function bannerHtml(id, kind, html){
const el = document.getElementById(id);
if(!el) return;
el.className = 'banner' + (kind ? ' '+kind : '');
el.innerHTML = html;
}
function bulkRole(){
const role = selVal('bulk-role');
if(!role) return;
return runBulk('/api/auth/bulk-users/role', { role }, {
title: 'Set permissions', ok: 'Change permissions',
message: n => 'Set permissions to '+(PERM_LABELS[role] || role)+' for '+people(n)+'?\n\n'+
'Each account is checked on its own. Any that cannot be changed are listed afterwards.'});
}
function bulkActive(on){
return runBulk('/api/auth/bulk-users/active', { is_active: !!on }, {
title: on ? 'Enable accounts' : 'Disable accounts', ok: on ? 'Enable' : 'Disable',
message: n => (on ? 'Enable sign-in for ' : 'Disable sign-in for ')+people(n)+'?'+
(on ? '' : '\n\nA disabled account cannot sign in. Nothing else about it changes.')});
}
function bulkProject(op){
const pid = selVal('bulk-project');
if(!pid) return;
const role = op === 'add' ? selVal('bulk-project-role') : '';
const pname = selText('bulk-project');
return runBulk('/api/auth/bulk-users/projects', { project_id: pid, op, role }, {
title: op === 'add' ? 'Add to project' : 'Remove from project',
ok: op === 'add' ? 'Add' : 'Remove',
message: n => op === 'add'
? 'Add '+people(n)+' to '+pname+' with '+(role ? PERM_LABELS[role]+' on that project' : 'their account role')+'?\n\n'+
'Their other projects, and their roles there, stay as they are.'
: 'Remove '+people(n)+' from '+pname+'?\n\nTheir other projects stay as they are.'});
}
// ── CSV upload (CR-020, T12.4) ────────────────────────────────────────────────
// The file holds usernames only (decided 2026-10-06). The server reads it and
// answers line by line; the accepted accounts become the ordinary selection, so
// the action, its confirmation and its row-by-row report are the same ones the
// checkboxes use. A CSV cannot reach an account a checkbox could not: the bulk
// route re-checks every row.
const CSV_MAX_BYTES = 1024 * 1024;
// Blob.text() where the browser has it, FileReader where it does not (older
// tablet browsers).
function readFileText(file){
if(typeof file.text === 'function') return file.text();
return new Promise((resolve, reject) => {
const r = new FileReader();
r.onload = () => resolve(String(r.result || ''));
r.onerror = () => reject(r.error);
r.readAsText(file);
});
}
function pickCsv(){
const f = document.getElementById('csv-file');
if(f){ f.value = ''; f.click(); }
}
document.addEventListener('change', e => {
if(e.target && e.target.id === 'csv-file' && e.target.files && e.target.files[0]) loadCsv(e.target.files[0]);
});
async function loadCsv(file){
if(file.size > CSV_MAX_BYTES){
bannerHtml('csv-banner', 'bad', '✕ '+uesc(file.name)+' is larger than 1 MB. Split it and load the parts one at a time.');
return;
}
let text = '';
try { text = await readFileText(file); }
catch(_){ bannerHtml('csv-banner', 'bad', '✕ Could not read '+uesc(file.name)+'.'); return; }
bannerHtml('csv-banner', '', 'Reading '+uesc(file.name)+'…');
const { status, json } = await api('POST', '/api/auth/bulk-users/resolve', { text });
if(status !== 200 || !json || !Array.isArray(json.rows)){
bannerHtml('csv-banner', 'bad', '✕ '+uesc(apiError(status, json, 'Could not read the list')));
return;
}
// Show everyone, so every accepted account is a visible, checked row: a
// selection must never include a row the filter hides.
const s = document.getElementById('user-search'), f = document.getElementById('user-filter');
if(s) s.value = '';
if(f) f.value = '';
await loadUsers();
const want = new Set(json.user_ids || []);
_shownSelectable.forEach(id => { if(want.has(id)) _selected.add(id); });
updateSelectionUI();
const missed = [...want].filter(id => !_selected.has(id)).length;
const rejected = json.rows.filter(r => r.status !== 'ok');
const lead = (rejected.length || missed ? '⚠ ' : '✓ ')+uesc(file.name)+': '+json.read+' line'+(json.read===1?'':'s')+' read, '+
_selected.size+' selected'+(rejected.length ? ', '+rejected.length+' rejected' : '')+'.'+
(missed ? ' '+missed+' accepted account'+(missed===1?' is':'s are')+' no longer in the directory; reload and try again.' : '')+
(_selected.size ? ' Pick an action in the bulk bar to apply it to the selected accounts.' : '');
const list = rejected.length
? '<ul>'+rejected.map(r => '<li>Line '+r.line+' ('+uesc(r.text)+'): '+uesc(r.reason)+'</li>').join('')+'</ul>'
: '';
bannerHtml('csv-banner', (rejected.length || missed) ? 'warn' : 'ok', lead + list);
}
function selCell(u){
if(!selectable(u)){
const why = u.id === _meId ? 'Your own account: change it one setting at a time'
: (u.manage_blocked_reason || 'You cannot change this account');
return '<td class="selcell"><span class="selhit" title="'+uesc(why)+'">'+
'<input type="checkbox" disabled aria-label="'+uesc('Cannot select '+u.username+': '+why)+'"></span></td>';
}
return '<td class="selcell"><label class="selhit">'+
'<input type="checkbox" class="selbox" data-id="'+uesc(u.id)+'"'+(_selected.has(u.id)?' checked':'')+
' aria-label="'+uesc('Select '+u.username)+'"></label></td>';
}
function renderUsers(){
const wrap = document.getElementById('users-table');
const q = ((document.getElementById('user-search')||{}).value||'').trim().toLowerCase();
@@ -116,7 +419,8 @@ function renderUsers(){
(u.project_role||'')+' '+roleLabel(u.role)).toLowerCase().indexOf(q) >= 0;
});
const count = '<div class="note">'+list.length+' of '+total+' '+(total===1?'person':'people')+'</div>';
if(!list.length){ wrap.innerHTML = count+'<div class="note">Nothing matches.</div>'; return; }
_shownSelectable = list.filter(selectable).map(u => u.id);
if(!list.length){ wrap.innerHTML = count+'<div class="note">Nothing matches.</div>'; updateSelectionUI(); return; }
const head = manages()
? ['Username','Name','Email',
@@ -130,9 +434,16 @@ function renderUsers(){
'Status'];
const ths = head.map(h => Array.isArray(h)
? '<th title="'+uesc(h[1])+'">'+uesc(h[0])+'</th>' : '<th>'+uesc(h)+'</th>').join('');
// CR-020: a selection column for anyone who manages accounts. Select-all names
// how many rows it covers, because it covers only what the filter shows.
const selTh = manages()
? '<th class="selcell"><label class="selhit"><input type="checkbox" id="sel-all" aria-label="'+
uesc('Select all '+_shownSelectable.length+' shown that you can change')+'"></label></th>'
: '';
const rows = list.map(manages() ? managerRow : readonlyRow).join('');
wrap.innerHTML = count+'<div class="tscroll"><table class="grid"><thead><tr>'+ths+
wrap.innerHTML = count+'<div class="tscroll"><table class="grid"><thead><tr>'+selTh+ths+
'</tr></thead><tbody>'+rows+'</tbody></table></div>'+legend();
updateSelectionUI();
}
function legend(){
@@ -189,6 +500,7 @@ function managerRow(u){
if(!can && !me) actions.push('<span class="note" style="margin:0" title="'+uesc(why)+'">read-only</span>');
return '<tr'+(can||me ? '' : ' class="is-locked"')+'>'+
selCell(u)+
'<td><strong>'+uesc(u.username)+'</strong>'+(me?'<span class="me-tag">you</span>':'')+'</td>'+
'<td>'+uesc(u.full_name||'')+'</td>'+
// The address is truncated with the full value on the title: a long one used to

View File

@@ -2207,18 +2207,20 @@ function loadStepComments(){
}
}
// ── USAGE ANALYTICS (retired, T11.6) ────────────────────────────────────────
// This used to write to wp-usage.js's per-browser localStorage log (D5/T7.10),
// read back by the admin console's old "Usage logs" panel. CR-019 replaced
// both with real, server-side, per-user activity (UsageEvent + the Activity &
// usage card) - see decisions-2026-09-17.md for why this per-browser data was
// never a source the new report could adopt. track() is now a no-op; kept
// (rather than deleting its handful of call sites, including the dwell-timer
// plumbing below) so this stays a one-line change instead of touching every
// caller for the same outcome.
// ── USAGE ANALYTICS ─────────────────────────────────────────────────────────
// Lightweight usage analytics stored in localStorage so the tool owner can review
// engagement over time. No field VALUES are stored (field-edit events record only
// the field id), keeping captured data non-sensitive.
// D5 / T7.10: the analytics implementation lives in wp-usage.js and the report
// on the admin console. The wizard's own copy of showAnalytics() never had a
// caller here - the button lived on the creator - and once B7 dissolved the
// frame the duplicate sat in the same document as five colliding globals.
// This page only records; dwell tracking keeps its page-local state below.
let _stepEnter = Date.now();
function track(event, detail){ /* retired, T11.6 — see comment above */ }
function track(event, detail){
WPUsage.track(WPUsage.KEYS.wizard, event, detail);
}
function trackStepDwell(){
const ms = Date.now() - _stepEnter;
if(ms > 400 && ms < 1000*60*60) track('step_dwell', {step: currentStep, ms});

View File

@@ -11,6 +11,7 @@
<!-- Addressable state (S3). Parses before the app scripts, which read the URL
during their own boot. -->
<script src="wp-url.js"></script>
<script src="wp-usage.js"></script>
<script src="wp-list-import.js"></script>
<!-- Autosave, unsaved-work guard, draft recovery (S2). -->
<script src="wp-autosave.js"></script>

View File

@@ -3993,17 +3993,11 @@ function openSopModal(){
document.getElementById('sop-modal').classList.add('open'); track('view_sop');
}
function closeSopModal(){ document.getElementById('sop-modal').classList.remove('open'); }
// CR-019 / T11.6 (2026-09-23): this used to write to wp-usage.js's per-browser
// localStorage log (D5/T7.10). Retired along with the admin console's old
// "Usage logs" panel, its only reader - real, server-side, per-user activity
// now exists (UsageEvent, the Activity & usage card, T11.1-T11.5) and this
// data was never reliably tied to a real identity anyway, so it was not a
// source the new report could adopt (decisions-2026-09-17.md). track() stays
// as a no-op rather than deleting its ~35 call sites throughout this file:
// removing every call individually is a much larger, riskier diff for the
// same outcome, and a call site here still documents the moment worth
// recording if usage analytics are ever rebuilt server-side.
function track(event,detail){ /* retired, T11.6 — see comment above */ }
// D5 / T7.10: the analytics implementation lives in wp-usage.js - ONE copy for
// the whole suite - and its report lives on the admin console, where an
// operator-facing readout belongs. This page only records. Same key, same
// event shape: everything recorded before the move is still readable after it.
function track(event,detail){ if(devMode) return; WPUsage.track(WPUsage.KEYS.creator, event, detail); }
// ── COMMENTS ─────────────────────────────────────────────────────────────────
const COMMENTS_KEY='wp_iwp_comments_v1';

View File

@@ -11,6 +11,7 @@
<!-- Addressable state (S3). Parses before the app scripts, which read the URL
during their own boot. -->
<script src="wp-url.js"></script>
<script src="wp-usage.js"></script>
<!-- Autosave, unsaved-work guard, draft recovery (S2). -->
<script src="wp-autosave.js"></script>
<!-- Which sections this project uses (CR-006). The same file the SOP wizard

58
html/wp-usage.js Normal file
View File

@@ -0,0 +1,58 @@
/* Usage analytics core — the ONE implementation (D5 / T7.10).
This existed three times: the creator's copy, the wizard's copy (which had no
caller — the button lived on the creator), and the admin console's own reader.
Once the creator stopped being an iframe (B7/T7.1) the first two sat in one
document as five colliding globals; an unreferenced duplicate is exactly what
produced D5. One core now; the pages keep only a thin track() wrapper because
page state (the creator's dev-mode pause) belongs to the page.
The storage KEYS are unchanged on purpose: everything recorded before this
file existed is still readable through it. No field VALUES are ever stored —
a field-edit event records the field id, nothing else.
Classic script, no modules: exposes window.WPUsage. */
'use strict';
(function () {
var SESSION = 's_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
function load(key) {
try { return JSON.parse(localStorage.getItem(key)) || { events: [] }; }
catch (e) { return { events: [] }; }
}
function save(key, data) {
try { localStorage.setItem(key, JSON.stringify(data)); }
catch (e) { /* storage unavailable — degrade silently */ }
}
function track(key, event, detail) {
try {
var d = load(key);
d.events.push({ ts: new Date().toISOString(), session: SESSION, event: event, detail: detail || null });
if (d.events.length > 5000) d.events = d.events.slice(-5000);
save(key, d);
} catch (e) { /* never let telemetry break the tool it watches */ }
}
function download(key, prefix) {
var blob = new Blob([JSON.stringify(load(key), null, 2)], { type: 'application/json' });
var a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = (prefix || 'wp-usage') + '-' + new Date().toISOString().slice(0, 10) + '.json';
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(function () { URL.revokeObjectURL(a.href); }, 1000);
}
window.WPUsage = {
load: load,
save: save,
track: track,
download: download,
// The pre-D5 keys, verbatim — continuity of the recorded data is a done-when.
KEYS: { creator: 'wp_iwp_analytics_v1', wizard: 'wp_suite_analytics_v1' },
};
})();

View File

@@ -27,18 +27,8 @@ DATABASE_URL=postgresql+psycopg://wpsuite:CHANGE_ME@localhost:5432/wpsuite
# python -c "import secrets; print(secrets.token_urlsafe(48))"
AUTH_SECRET_KEY=CHANGE_ME_run_the_command_above
# D18 (2026-09-23): a session slides on activity, capped by a hard ceiling
# underneath - not one flat lifetime. Both defaults are proposed, not
# confirmed against this tenant's actual Okta SSO session policy - if Okta's
# own session outlives either number, re-auth here is likely a fast redirect
# rather than a real login screen, so these cost less than they look like.
#
# No request for this many minutes ends the session outright.
# AUTH_IDLE_MINUTES=30
#
# The absolute ceiling from original sign-in, regardless of activity - no
# session outlives this no matter how continuously active it is. Default 8.
# AUTH_SESSION_HOURS=8
# How long a login lasts before re-authentication (hours). Default 12.
# AUTH_SESSION_HOURS=12
# ── Okta OIDC (required — this is the only sign-in path) ───────────────────────
# The Okta *authorization server* issuer, e.g. https://yourorg.okta.com/oauth2/default

View File

@@ -1,46 +0,0 @@
"""usage events (CR-019, wave 11)
Append-only navigation/session activity, separate from audit_log on purpose —
see the UsageEvent docstring in server/models.py. Retention is indefinite by
decision (docs/waves/decisions-2026-09-17.md); nothing here schedules a purge.
Revision ID: 8e2cb3003f8a
Revises: 1d60a608bb51
Create Date: 2026-09-23 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '8e2cb3003f8a'
down_revision = '1d60a608bb51'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table('usage_events',
sa.Column('id', sa.String(length=40), nullable=False),
sa.Column('at', sa.DateTime(timezone=True), nullable=False),
sa.Column('username', sa.String(length=200), nullable=False),
sa.Column('project_id', sa.String(length=40), nullable=True),
sa.Column('tool', sa.String(length=40), nullable=False),
sa.Column('event', sa.String(length=40), nullable=False),
sa.Column('detail', sa.JSON(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_usage_events_at'), 'usage_events', ['at'], unique=False)
op.create_index(op.f('ix_usage_events_username'), 'usage_events', ['username'], unique=False)
op.create_index(op.f('ix_usage_events_project_id'), 'usage_events', ['project_id'], unique=False)
op.create_index(op.f('ix_usage_events_tool'), 'usage_events', ['tool'], unique=False)
op.create_index(op.f('ix_usage_events_event'), 'usage_events', ['event'], unique=False)
def downgrade() -> None:
op.drop_index(op.f('ix_usage_events_event'), table_name='usage_events')
op.drop_index(op.f('ix_usage_events_tool'), table_name='usage_events')
op.drop_index(op.f('ix_usage_events_project_id'), table_name='usage_events')
op.drop_index(op.f('ix_usage_events_username'), table_name='usage_events')
op.drop_index(op.f('ix_usage_events_at'), table_name='usage_events')
op.drop_table('usage_events')

View File

@@ -9,15 +9,10 @@ Run (prod): gunicorn -k uvicorn.workers.UvicornWorker -b 127.0.0.1:8000 serve
Interactive docs: http://<host>/api/docs
"""
import base64
import csv
import hashlib
import hmac
import io
import logging
import os
import re
import uuid
from datetime import datetime, timedelta, timezone
from typing import Any, Optional
from urllib.parse import urlparse
@@ -27,7 +22,7 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import select, delete, func, or_
from sqlalchemy import select, delete, func
from sqlalchemy.orm import Session
from starlette.middleware.sessions import SessionMiddleware
@@ -108,23 +103,12 @@ def _csrf_ok(request: Request) -> bool:
async def auth_gate(request: Request, call_next):
path = request.url.path
method = request.method
claims = None
if method != "OPTIONS" and auth._needs_auth(path):
claims = auth.is_request_authenticated(request)
if not claims:
if not auth.is_request_authenticated(request):
return JSONResponse(status_code=401, content={"detail": "Not authenticated"})
if method in _UNSAFE_METHODS and path.startswith("/api/") and not _csrf_ok(request):
return JSONResponse(status_code=403, content={"detail": "Cross-origin request rejected"})
response = await call_next(request)
# D18: slide the session forward on activity, capped by its absolute
# ceiling. Reads only the already-validated claims - no DB hit here, and
# the separate is_active/token_version check in get_current_user still
# runs on its own for every request regardless of whether this refreshes.
if claims is not None:
refreshed = auth.maybe_refresh_token(claims)
if refreshed:
auth.set_session_cookie(response, request, refreshed)
return response
return await call_next(request)
def gen_id(prefix: str) -> str:
@@ -772,11 +756,6 @@ async def okta_callback(request: Request, db: Session = Depends(get_db)):
user.failed_attempts = 0
user.locked_until = None
user.last_login_at = models.utcnow()
# CR-019: one login event per Okta sign-in, written here rather than
# inferred from session creation elsewhere, so there is exactly one
# source of truth for "did this person sign in" - not one per page load
# afterward (T11.2 covers that separately, as page_open events).
db.add(models.UsageEvent(id=gen_id("uev"), username=user.username, tool="", event="login"))
db.commit()
db.refresh(user)
@@ -1034,16 +1013,100 @@ def create_user(body: NewUserIn, actor: models.User = Depends(require_user_manag
return directory_entry(db, u, actor)
# ── One account-level change, used by the single-user routes AND the bulk routes ──
# CR-020 (T12.1): a bulk action is the single-user action, once per row. So each
# rule lives in exactly one function below, and both kinds of route call it: a
# bulk request cannot reach further than a one-at-a-time request, because there
# is no second copy of the rules for it to reach through. Every function checks
# all of its guards BEFORE it changes anything, so a row that is refused leaves
# nothing half-written, and writes its AuditLog row the way the single route
# always has. None of them commits; the route owns the transaction.
def guard_target(db: Session, actor: "models.User", u: "models.User") -> None:
"""The two checks every account change starts with: may the caller see this
account (404 if not, so existence does not leak), and may they change it."""
require_see_user(db, actor, u)
require_manage_user(db, actor, u)
def apply_user_active(db: Session, actor: "models.User", u: "models.User", is_active: bool) -> None:
if u.id == actor.id and not is_active:
raise HTTPException(status_code=400, detail="You cannot disable your own account")
u.is_active = is_active
log_event(db, actor, "user_enabled" if is_active else "user_disabled", "user", u.id,
summary=u.username, detail={"is_active": bool(is_active)})
def apply_user_role(db: Session, actor: "models.User", u: "models.User", role: str) -> None:
"""The role guards: never your own role, never the last active admin. The
grantable-roles check is the caller's, made once per request before this."""
if u.id == actor.id:
raise HTTPException(status_code=400, detail="You cannot change your own role")
if auth.is_admin(u) and role != auth.ROLE_ADMIN:
other_admins = db.scalars(
select(models.User.id).where(
(models.User.role == auth.ROLE_ADMIN)
& (models.User.id != u.id)
& (models.User.is_active.is_(True))
)
).all()
if not other_admins:
raise HTTPException(status_code=400, detail="Can't remove the last admin account")
old_role = u.role
u.role = role
detail = {"from": old_role, "to": role}
# Promoting someone to admin retires their default-member flag: an admin already
# reaches every project, so the flag would do nothing except sit there invisibly
# (the console shows admins no controls) and come back to life the day they are
# demoted. Same reasoning as clearing the role in set_user_auto_add.
if role == auth.ROLE_ADMIN and (u.auto_add_projects or u.auto_add_role):
u.auto_add_projects = False
u.auto_add_role = ""
detail["auto_add_cleared"] = True
log_event(db, actor, "role_changed", "user", u.id, summary=u.username, detail=detail)
def apply_user_delete(db: Session, actor: "models.User", u: "models.User") -> None:
if u.id == actor.id:
raise HTTPException(status_code=400, detail="You cannot delete your own account")
log_event(db, actor, "user_deleted", "user", u.id, summary=u.username, detail={"role": u.role})
db.delete(u)
def apply_user_projects(db: Session, actor: "models.User", u: "models.User",
managed: Optional[set], valid: set, roles: dict) -> None:
"""Replace the caller's slice of `u`'s memberships with `valid`, each carrying
its role from `roles` ('' = inherit). `valid` must already be checked to exist
and to sit inside `managed`."""
# Rebuild only the rows this caller owns. Scoping the DELETE is the whole of the
# "leave other jobs alone" guarantee — get it wrong and a super user's save
# silently revokes access everywhere else.
doomed = delete(models.ProjectMember).where(models.ProjectMember.user_id == u.id)
if managed is not None:
# in_() on an empty set is a valid always-false predicate, so a caller who
# administers nothing deletes nothing (require_manage_user already refused them).
doomed = doomed.where(models.ProjectMember.project_id.in_(managed))
db.execute(doomed)
for pid in valid:
db.add(models.ProjectMember(id=gen_id("pm"), user_id=u.id, project_id=pid,
role=roles.get(pid, "")))
log_event(db, actor, "project_access_changed", "user", u.id, summary=u.username,
detail={"projects": len(valid),
"scope": "all" if managed is None else "managed",
"overrides": {p: r for p, r in roles.items() if p in valid}})
def project_scoped_grantable(actor: "models.User") -> tuple:
"""Per-project roles `actor` may hand out. Only an app admin can make someone a
super user on a project. user_scope and get_user_projects still spell the same
rule inline for the console; left as they are to keep this diff to CR-020."""
return auth.PROJECT_SCOPED_ROLES if auth.is_admin(actor) else (auth.ROLE_PROJECT_ADMIN, auth.ROLE_PROJECT_USER)
@app.post("/api/auth/users/{user_id}/active")
def set_user_active(user_id: str, body: ActiveIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
u = load_target_user(db, user_id)
require_see_user(db, actor, u)
require_manage_user(db, actor, u)
if u.id == actor.id and not body.is_active:
raise HTTPException(status_code=400, detail="You cannot disable your own account")
u.is_active = body.is_active
log_event(db, actor, "user_enabled" if body.is_active else "user_disabled", "user", u.id,
summary=u.username, detail={"is_active": bool(body.is_active)})
guard_target(db, actor, u)
apply_user_active(db, actor, u, body.is_active)
db.commit()
return directory_entry(db, u, actor)
@@ -1060,32 +1123,8 @@ def set_user_role(user_id: str, body: RoleIn, actor: models.User = Depends(requi
if body.role not in allowed:
raise HTTPException(status_code=400, detail=f"role must be one of {', '.join(allowed)}")
u = load_target_user(db, user_id)
require_see_user(db, actor, u)
require_manage_user(db, actor, u)
if u.id == actor.id:
raise HTTPException(status_code=400, detail="You cannot change your own role")
if auth.is_admin(u) and body.role != auth.ROLE_ADMIN:
other_admins = db.scalars(
select(models.User.id).where(
(models.User.role == auth.ROLE_ADMIN)
& (models.User.id != u.id)
& (models.User.is_active.is_(True))
)
).all()
if not other_admins:
raise HTTPException(status_code=400, detail="Can't remove the last admin account")
old_role = u.role
u.role = body.role
detail = {"from": old_role, "to": body.role}
# Promoting someone to admin retires their default-member flag: an admin already
# reaches every project, so the flag would do nothing except sit there invisibly
# (the console shows admins no controls) and come back to life the day they are
# demoted. Same reasoning as clearing the role in set_user_auto_add.
if body.role == auth.ROLE_ADMIN and (u.auto_add_projects or u.auto_add_role):
u.auto_add_projects = False
u.auto_add_role = ""
detail["auto_add_cleared"] = True
log_event(db, actor, "role_changed", "user", u.id, summary=u.username, detail=detail)
guard_target(db, actor, u)
apply_user_role(db, actor, u, body.role)
db.commit()
db.refresh(u)
return directory_entry(db, u, actor)
@@ -1142,12 +1181,8 @@ def set_user_auto_add(user_id: str, body: AutoAddIn, admin: models.User = Depend
@app.delete("/api/auth/users/{user_id}")
def delete_user(user_id: str, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
u = load_target_user(db, user_id)
require_see_user(db, actor, u)
require_manage_user(db, actor, u)
if u.id == actor.id:
raise HTTPException(status_code=400, detail="You cannot delete your own account")
log_event(db, actor, "user_deleted", "user", u.id, summary=u.username, detail={"role": u.role})
db.delete(u)
guard_target(db, actor, u)
apply_user_delete(db, actor, u)
db.commit()
return {"deleted": user_id}
@@ -1200,8 +1235,7 @@ def set_user_projects(user_id: str, body: ProjectAssignIn, actor: models.User =
exactly as they were, because a payload that simply omits them would otherwise cut
someone off from a job the caller can't even see."""
u = load_target_user(db, user_id)
require_see_user(db, actor, u)
require_manage_user(db, actor, u)
guard_target(db, actor, u)
requested = [p for p in dict.fromkeys(body.project_ids) if p]
for pid in requested:
check_id(pid)
@@ -1214,28 +1248,227 @@ def set_user_projects(user_id: str, body: ProjectAssignIn, actor: models.User =
# A super user may hand out the project-scoped roles below their own; only an app
# admin can make someone a super user on a project. Anything unrecognised falls
# back to inheriting the account's own role.
allowed = auth.PROJECT_SCOPED_ROLES if auth.is_admin(actor) else (auth.ROLE_PROJECT_ADMIN, auth.ROLE_PROJECT_USER)
allowed = project_scoped_grantable(actor)
roles = {pid: r for pid, r in (body.roles or {}).items() if r in allowed}
# Rebuild only the rows this caller owns. Scoping the DELETE is the whole of the
# "leave other jobs alone" guarantee — get it wrong and a super user's save
# silently revokes access everywhere else.
doomed = delete(models.ProjectMember).where(models.ProjectMember.user_id == user_id)
if managed is not None:
# in_() on an empty set is a valid always-false predicate, so a caller who
# administers nothing deletes nothing (require_manage_user already refused them).
doomed = doomed.where(models.ProjectMember.project_id.in_(managed))
db.execute(doomed)
for pid in valid:
db.add(models.ProjectMember(id=gen_id("pm"), user_id=user_id, project_id=pid,
role=roles.get(pid, "")))
log_event(db, actor, "project_access_changed", "user", u.id, summary=u.username,
detail={"projects": len(valid),
"scope": "all" if managed is None else "managed",
"overrides": {p: r for p, r in roles.items() if p in valid}})
apply_user_projects(db, actor, u, managed, valid, roles)
db.commit()
return {"assigned": sorted(valid), "roles": {p: roles.get(p, "") for p in sorted(valid)}}
# ── Bulk user administration — CR-020 (T12.1) ─────────────────────────────────
# Four actions over a list of accounts: activate/disable, permissions role,
# project add/remove (with the per-project role), delete. Each row runs exactly
# the guards and the audit of the single-user route, through the same apply_*
# function above. Rules, decided 2026-09-17 and confirmed 2026-10-06:
# * a row that is refused is reported with its reason and the rest still run;
# a batch is never reported as a success when part of it failed;
# * one AuditLog row per changed account, the same as the single route writes -
# never one opaque "bulk" entry;
# * the caller's own account is refused only on its own row (disable, demote,
# delete), never by failing the whole batch;
# * project assignment adds to or removes from ONE project; it never replaces a
# user's whole project list.
# A row already in the requested state is reported "unchanged" and writes no
# audit row: nothing changed, so there is nothing to audit.
#
# The routes live under /api/auth/bulk-users/ rather than /api/auth/users/bulk/,
# because POST /api/auth/users/{user_id}/active would otherwise match "bulk" as
# a user id.
BULK_MAX_USERS = 500
class BulkUsersIn(BaseModel):
user_ids: list[str] = Field(default_factory=list, max_length=BULK_MAX_USERS)
class BulkActiveIn(BulkUsersIn):
is_active: bool
class BulkRoleIn(BulkUsersIn):
role: str
class BulkProjectIn(BulkUsersIn):
project_id: str
op: str # "add" | "remove"
role: str = "" # per-project role on add; '' = inherit the account's own
def run_bulk(db: Session, actor: "models.User", user_ids: list[str], action: str, apply) -> dict:
"""Run `apply(u)` once per distinct id, in the order given. `apply` returns
"ok" or "unchanged", or raises HTTPException with the reason the single-user
route would have given. The flush after every row matters: the session does
not autoflush, and a later row's guard (the last-admin count, for one) has to
see what an earlier row already changed."""
results = []
for uid in dict.fromkeys(i for i in user_ids if i):
row = {"user_id": uid, "username": "", "status": "", "reason": ""}
try:
check_id(uid)
u = load_target_user(db, uid)
row["username"] = u.username
guard_target(db, actor, u)
row["status"] = apply(u)
db.flush()
except HTTPException as exc:
row["status"] = "failed"
row["reason"] = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
results.append(row)
db.commit()
counts = {s: sum(1 for r in results if r["status"] == s) for s in ("ok", "unchanged", "failed")}
return {"action": action, "requested": len(results), **counts, "results": results}
@app.post("/api/auth/bulk-users/active")
def bulk_set_active(body: BulkActiveIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
def apply(u):
if bool(u.is_active) == bool(body.is_active):
return "unchanged"
apply_user_active(db, actor, u, body.is_active)
return "ok"
return run_bulk(db, actor, body.user_ids, "enable" if body.is_active else "disable", apply)
@app.post("/api/auth/bulk-users/role")
def bulk_set_role(body: BulkRoleIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
allowed = grantable_roles(actor)
if body.role not in allowed:
raise HTTPException(status_code=400, detail=f"role must be one of {', '.join(allowed)}")
def apply(u):
# Compared as stored: a legacy 'user' row moved to 'project_user' is a real
# change of the stored value, so it is applied and audited, as one at a time.
if u.role == body.role:
return "unchanged"
apply_user_role(db, actor, u, body.role)
return "ok"
return run_bulk(db, actor, body.user_ids, "role", apply)
@app.post("/api/auth/bulk-users/projects")
def bulk_set_project(body: BulkProjectIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
"""Add every listed account to one project (with a per-project role), or remove
them from it. Implemented as the single route's replace of the caller's slice,
computed per user, so the audit row is the same shape the dialog writes."""
if body.op not in ("add", "remove"):
raise HTTPException(status_code=400, detail="op must be 'add' or 'remove'")
check_id(body.project_id)
if not db.get(models.Project, body.project_id):
raise HTTPException(status_code=404, detail="Project not found")
managed = managed_project_ids(db, actor)
if managed is not None and body.project_id not in managed:
raise HTTPException(status_code=403, detail="You don't administer the users of that project")
role = (body.role or "").strip()
if body.op == "add" and role and role not in project_scoped_grantable(actor):
raise HTTPException(
status_code=400,
detail=f"role must be '' (inherit) or one of {', '.join(project_scoped_grantable(actor))}")
pid = body.project_id
def apply(u):
mine = [m for m in db.scalars(select(models.ProjectMember)
.where(models.ProjectMember.user_id == u.id)).all()
if managed is None or m.project_id in managed]
current = {m.project_id: (m.role or "") for m in mine}
if body.op == "add":
if current.get(pid) == role:
return "unchanged"
current[pid] = role
else:
if pid not in current:
return "unchanged"
current.pop(pid)
# Roles on the caller's OTHER projects are carried over exactly as stored -
# adding someone to one job must never reset their role on another.
apply_user_projects(db, actor, u, managed, set(current),
{p: r for p, r in current.items() if r})
return "ok"
return run_bulk(db, actor, body.user_ids, "project_" + body.op, apply)
class BulkResolveIn(BaseModel):
text: str = Field(default="", max_length=200_000)
_CSV_HEADER_WORDS = ("username", "user", "login", "email", "user name")
@app.post("/api/auth/bulk-users/resolve")
def bulk_resolve(body: BulkResolveIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
"""CR-020 (T12.4): turn an uploaded list of usernames into the account ids a
bulk action will run on - a second way IN to the same four bulk routes, not a
third copy of their rules. The CSV holds usernames only (decided 2026-10-06);
the action is chosen in the console and applies to every accepted row.
Validate and report, the CR-005 pattern: every line is either accepted or
rejected WITH ITS LINE NUMBER and a reason - never silently skipped. A line is
rejected when it names nobody this caller can see (the same 'not found' a
hidden account gets everywhere else), an account they may not change (with
the same reason the single route would give), their own account, or a
username already listed on an earlier line. Nothing is changed here; the
bulk route the console calls next re-checks every row anyway."""
rows = []
seen: dict[str, int] = {}
visible = visible_user_ids(db, actor)
cache: dict = {}
for line_no, raw in enumerate((body.text or "").splitlines(), start=1):
line = raw.strip().lstrip("")
if not line:
continue
cell = re.split(r"[,;\t]", line, maxsplit=1)[0].strip().strip('"').strip()
if not cell:
rows.append({"line": line_no, "text": line[:120], "status": "rejected",
"reason": "no username in the first column"})
continue
if line_no == 1 and cell.lower() in _CSV_HEADER_WORDS:
continue # header row
row = {"line": line_no, "text": cell[:120], "status": "rejected", "reason": "",
"user_id": None, "username": ""}
if any(ord(ch) < 32 for ch in cell) or len(cell) > 120:
row["reason"] = "not a valid username"
rows.append(row)
continue
key = cell.lower()
if key in seen:
row["reason"] = f"duplicate of line {seen[key]}"
rows.append(row)
continue
seen[key] = line_no
u = db.scalars(select(models.User).where(func.lower(models.User.username) == key)).first()
if u is None:
# An offboarding list usually carries email addresses. Accepted only
# when exactly one account has that address, so a shared or reused
# address can never pick the wrong person.
by_mail = db.scalars(select(models.User).where(func.lower(models.User.email) == key)).all()
u = by_mail[0] if len(by_mail) == 1 else None
if u is None or (visible is not None and u.id not in visible):
row["reason"] = "User not found"
elif u.id == actor.id:
row["reason"] = "your own account - change it one setting at a time"
else:
problem = manage_user_problem(db, actor, u, cache)
if problem:
row["reason"] = problem
else:
row.update(status="ok", user_id=u.id, username=u.username)
rows.append(row)
accepted = [r for r in rows if r["status"] == "ok"]
return {"read": len(rows), "accepted": len(accepted), "rejected": len(rows) - len(accepted),
"user_ids": [r["user_id"] for r in accepted], "rows": rows}
@app.post("/api/auth/bulk-users/delete")
def bulk_delete(body: BulkUsersIn, actor: models.User = Depends(require_user_manager), db: Session = Depends(get_db)):
"""Hard delete, the same as DELETE /api/auth/users/{id} (decided 2026-09-17:
no soft delete invented for the bulk case). The console asks for the typed
word DELETE first; the server's guard is the per-row rules, as for one."""
def apply(u):
apply_user_delete(db, actor, u)
return "ok"
return run_bulk(db, actor, body.user_ids, "delete", apply)
# ── Projects ─────────────────────────────────────────────────────────────────
@app.post("/api/projects")
def upsert_project(body: ProjectIn, user: models.User = Depends(auth.get_current_user), db: Session = Depends(get_db)):
@@ -3395,177 +3628,6 @@ def create_feedback(body: CommentIn, user: models.User = Depends(auth.get_curren
return _save_comment(body, db, user)
# ── CR-019: usage/activity metrics ──────────────────────────────────────────
class UsageIn(BaseModel):
tool: str = ""
project_id: Optional[str] = None
@app.post("/api/usage/ping")
def usage_ping(body: UsageIn, user: models.User = Depends(auth.get_current_user), db: Session = Depends(get_db)):
"""One usage_events row per authenticated page load. Called exactly once,
from auth-guard.js after wp-auth-ready fires (T11.2) - never duplicated
per page's own script, the same lesson S4's per-page nav already taught
this codebase. `user` comes from the session via get_current_user, never
from anything the client claims - identity here is a server-enforced
fact, matching every other write in this file, not a client-reported one."""
tool = (body.tool or "").strip()[:40]
db.add(models.UsageEvent(
id=gen_id("uev"), username=user.username, project_id=body.project_id,
tool=tool, event="page_open",
))
db.commit()
return {"ok": True}
def _parse_date_q(v: str, end: bool = False) -> Optional[datetime]:
"""Accepts a plain YYYY-MM-DD (what a <input type=date> sends) or a full
ISO datetime. A date-only `to` means "through the end of that day", not
midnight at its start - otherwise a range of "today" would match nothing
from today at all."""
if not v:
return None
try:
d = datetime.fromisoformat(v)
except ValueError:
return None
if d.tzinfo is None:
d = d.replace(tzinfo=timezone.utc)
if end and len(v) <= 10: # date-only
d = d + timedelta(days=1) - timedelta(microseconds=1)
return d
def _usage_query(db: Session, caller: "models.User", date_from, date_to, project_id, username, tool):
"""Shared by the summary and export endpoints so the two can never
disagree about which rows a filter set matches - the export is a raw
dump of exactly what the summary counted, not a separately-derived view."""
stmt = select(models.UsageEvent)
managed = managed_project_ids(db, caller)
if managed is not None:
# A project_super_user (never an app admin, who gets managed=None) is
# scoped to events tied to a project they administer, plus their OWN
# suite-wide activity (admin console opens etc. carry no project_id) -
# never another user's activity outside what they manage.
if managed:
stmt = stmt.where(or_(
models.UsageEvent.project_id.in_(managed),
models.UsageEvent.username == caller.username,
))
else:
stmt = stmt.where(models.UsageEvent.username == caller.username)
df = _parse_date_q(date_from)
dt = _parse_date_q(date_to, end=True)
if df:
stmt = stmt.where(models.UsageEvent.at >= df)
if dt:
stmt = stmt.where(models.UsageEvent.at <= dt)
if project_id:
stmt = stmt.where(models.UsageEvent.project_id == project_id)
if username:
stmt = stmt.where(models.UsageEvent.username == username)
if tool:
stmt = stmt.where(models.UsageEvent.tool == tool)
return stmt.order_by(models.UsageEvent.at)
@app.get("/api/usage/summary")
def usage_summary(
date_from: Optional[str] = Query(None, alias="from"),
date_to: Optional[str] = Query(None, alias="to"),
project_id: Optional[str] = Query(None),
username: Optional[str] = Query(None),
tool: Optional[str] = Query(None),
caller: models.User = Depends(require_user_manager),
db: Session = Depends(get_db),
):
"""CR-019. Same gate as the User Directory (require_user_manager): an app
admin or a project_super_user with at least one managed project. Filters
combine. Aggregated in Python over the filtered row set rather than a SQL
GROUP BY - correct and simple at today's scale; if usage_events grows
into the millions (plausible, given retention is indefinite by decision),
the day/week/month bucketing here is the first thing to move server-side
into SQL. Not done now because nothing currently requires it."""
rows = db.scalars(_usage_query(db, caller, date_from, date_to, project_id, username, tool)).all()
by_day: dict[str, set] = {}
by_week: dict[str, set] = {}
by_month: dict[str, set] = {}
per_user_last: dict[str, datetime] = {}
per_tool: dict[str, int] = {}
for e in rows:
by_day.setdefault(e.at.date().isoformat(), set()).add(e.username)
by_week.setdefault(e.at.strftime("%G-W%V"), set()).add(e.username)
by_month.setdefault(e.at.strftime("%Y-%m"), set()).add(e.username)
if e.username not in per_user_last or e.at > per_user_last[e.username]:
per_user_last[e.username] = e.at
per_tool[e.tool] = per_tool.get(e.tool, 0) + 1
return {
"active_users": {
"by_day": {k: len(v) for k, v in sorted(by_day.items())},
"by_week": {k: len(v) for k, v in sorted(by_week.items())},
"by_month": {k: len(v) for k, v in sorted(by_month.items())},
},
"per_user_last_active": {u: models._iso(t) for u, t in sorted(per_user_last.items())},
"by_tool": dict(sorted(per_tool.items(), key=lambda kv: -kv[1])),
"event_count": len(rows),
}
def _pseudonym(username: str) -> str:
"""A stable per-user id for the sanitized export — the SAME input always
produces the SAME output, within one export and across separate export
runs, so an external system (Power BI or similar) can still group and
trend "by user" without ever receiving a real name. HMAC rather than a
plain hash: a plain sha256(username) is trivially reversed against a
wordlist of the handful of usernames this app actually has; keying it
with AUTH_SECRET_KEY (already a real secret, already required in
production — see auth.py) means recovering a username from its
pseudonym requires the signing key, not just guessing."""
digest = hmac.new(auth.SECRET_KEY.encode(), username.encode(), hashlib.sha256).hexdigest()
return "u_" + digest[:16]
@app.get("/api/usage/export")
def usage_export(
date_from: Optional[str] = Query(None, alias="from"),
date_to: Optional[str] = Query(None, alias="to"),
project_id: Optional[str] = Query(None),
username: Optional[str] = Query(None),
tool: Optional[str] = Query(None),
sanitize: bool = Query(False),
caller: models.User = Depends(require_user_manager),
db: Session = Depends(get_db),
):
"""CR-019. Same gate, same filters, same underlying row set as
usage_summary() (_usage_query) — the export can never show a different
slice of data than what the console counted for the same filters.
sanitize=true replaces `username` with a stable pseudonym (_pseudonym)
and — deliberately — the `detail` column is not exported in EITHER mode.
Every event this app writes today (login, page_open) leaves `detail`
empty, so this costs nothing now, but it also means a future event type
that DOES populate `detail` can't accidentally leak a real name into a
sanitized file through a column nobody thought to scrub. If `detail`
is ever needed in the export, it has to be sanitized explicitly, not
assumed safe because the rest of the row was."""
rows = db.scalars(_usage_query(db, caller, date_from, date_to, project_id, username, tool)).all()
buf = io.StringIO()
w = csv.writer(buf)
w.writerow(["at", "username", "project_id", "tool", "event"])
for e in rows:
who = _pseudonym(e.username) if sanitize else e.username
w.writerow([models._iso(e.at), who, e.project_id or "", e.tool, e.event])
filename = "usage_export_%s_%s.csv" % (
"sanitized" if sanitize else "raw", datetime.now(timezone.utc).strftime("%Y%m%d"),
)
return Response(
content=buf.getvalue(), media_type="text/csv",
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
)
@app.get("/api/comments")
def list_comments(
source: Optional[str] = Query(None),

View File

@@ -59,26 +59,8 @@ log = logging.getLogger("wpsuite.auth")
COOKIE_NAME = "wp_session"
JWT_ALG = "HS256"
# D18 (2026-09-23): a session now slides on activity, capped by a hard ceiling
# underneath - not a single flat lifetime. A pure idle timer with no ceiling
# would let a continuously-active session never force a fresh Okta recheck,
# which is a worse fit for this item's own purpose (catching someone still
# active after being deprovisioned) than a flat expiry would have been. Both
# numbers are proposed defaults, not confirmed against the tenant's actual
# Okta SSO session policy - see docs/waves/decisions-2026-09-17.md.
#
# No request for this long invalidates the session outright.
IDLE_MINUTES = int(os.getenv("AUTH_IDLE_MINUTES", "30"))
# The absolute ceiling from the ORIGINAL sign-in, regardless of activity. Same
# env var name as the old flat-lifetime design; the meaning changed, the name
# didn't, because it still answers "how long can this session possibly live."
SESSION_HOURS = int(os.getenv("AUTH_SESSION_HOURS", "8"))
# How much later a refreshed exp must be before it's worth rewriting the
# cookie. Without this, an active session gets a new Set-Cookie on literally
# every request - correct, but wasteful, and it makes the cookie a busier
# target than it needs to be. A third of the idle window is a reasonable
# balance: refreshed a few times within any idle window, never every request.
_REFRESH_SLACK = timedelta(minutes=max(1, IDLE_MINUTES // 3))
# How long a session lasts before the person must sign in again.
SESSION_HOURS = int(os.getenv("AUTH_SESSION_HOURS", "12"))
# ── permissions roles ─────────────────────────────────────────────────────────
ROLE_ADMIN = "admin"
@@ -178,30 +160,6 @@ SECRET_KEY = _load_secret()
# ── tokens ──────────────────────────────────────────────────────────────────
def _parse_claim_dt(v) -> Optional[datetime]:
"""`login_at` is a custom claim, so unlike `exp`/`iat` (which PyJWT
special-cases for a datetime -> POSIX-timestamp conversion on encode) it
is stored and read back as a plain numeric timestamp. Returns None for
anything unparseable rather than raising - a malformed or legacy token
should fail closed into "no refresh", not 500."""
if v is None:
return None
try:
return datetime.fromtimestamp(float(v), tz=timezone.utc)
except (TypeError, ValueError, OSError):
return None
def _next_exp(login_at: datetime, now: datetime) -> datetime:
"""Whichever comes first: another IDLE_MINUTES of quiet from now, or the
absolute SESSION_HOURS ceiling measured from the session's original
sign-in. Shared by create_token and maybe_refresh_token so the two can't
drift apart."""
ceiling = login_at + timedelta(hours=SESSION_HOURS)
idle_edge = now + timedelta(minutes=IDLE_MINUTES)
return min(ceiling, idle_edge)
def create_token(user: "models.User") -> str:
now = datetime.now(timezone.utc)
payload = {
@@ -210,48 +168,7 @@ def create_token(user: "models.User") -> str:
"role": user.role,
"ver": user.token_version or 0,
"iat": now,
"login_at": now.timestamp(),
"exp": _next_exp(now, now),
}
return jwt.encode(payload, SECRET_KEY, algorithm=JWT_ALG)
def maybe_refresh_token(claims: dict) -> Optional[str]:
"""Given a validated token's claims, return a reissued token if the
session is worth extending, or None if nothing should change. Called from
`auth_gate` on every authenticated request (D18) - deliberately reads only
the already-validated claims, never the database, so it costs nothing
beyond the JWT encode itself. The separate is_active/token_version check
in get_current_user is unaffected either way.
Three ways this returns None: past the absolute ceiling (session is done,
full re-login required - never extended, not even by a second); the
claims can't be parsed (fails closed into no-refresh rather than guessing);
or a refresh happened recently enough that a new cookie isn't worth
writing yet (_REFRESH_SLACK)."""
now = datetime.now(timezone.utc)
login_at = _parse_claim_dt(claims.get("login_at"))
if login_at is None:
# Pre-D18 token (no login_at claim) - fall back to iat so it still
# gets a real ceiling instead of riding on the old flat exp forever.
login_at = _parse_claim_dt(claims.get("iat"))
if login_at is None:
return None
ceiling = login_at + timedelta(hours=SESSION_HOURS)
if now >= ceiling:
return None
new_exp = _next_exp(login_at, now)
current_exp = _parse_claim_dt(claims.get("exp"))
if current_exp is not None and (new_exp - current_exp) < _REFRESH_SLACK:
return None
payload = {
"sub": claims.get("sub"),
"username": claims.get("username"),
"role": claims.get("role"),
"ver": claims.get("ver", 0),
"iat": now,
"login_at": login_at.timestamp(),
"exp": new_exp,
"exp": now + timedelta(hours=SESSION_HOURS),
}
return jwt.encode(payload, SECRET_KEY, algorithm=JWT_ALG)

View File

@@ -337,45 +337,6 @@ class AuditLog(Base):
}
class UsageEvent(Base):
"""CR-019: append-only record of who used the suite, when, and which tool —
navigation/session activity, not business mutations. Deliberately a SEPARATE
table from AuditLog rather than a new `action` value there: AuditLog answers
"who changed what" and is read by people auditing a specific record's
history; mixing in a `page_open` row for every authenticated page load
would make that trail noisy for its existing purpose. This table answers a
different question — "who is active, and on what" — and CR-019's admin
console reads from here, not from AuditLog.
Not a ForeignKey to `users`, matching AuditLog's own reasoning: a user who
is later removed should still show up in historical activity rather than
silently vanishing from it, and `D18`'s deprovisioning sync only ever sets
`is_active=False` — it never deletes a row — so this is defensive symmetry
rather than a live concern today.
Retention is indefinite (decided 2026-09-17, `decisions-2026-09-17.md`) —
nothing purges rows written here; that is a deliberate product decision,
not an oversight to fix later."""
__tablename__ = "usage_events"
id: Mapped[str] = mapped_column(String(40), primary_key=True)
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow, index=True)
username: Mapped[str] = mapped_column(String(200), default="", index=True)
project_id: Mapped[Optional[str]] = mapped_column(String(40), nullable=True, index=True)
# creator | wizard | field_view | dashboard | admin | directory | ...
tool: Mapped[str] = mapped_column(String(40), default="", index=True)
# page_open | login
event: Mapped[str] = mapped_column(String(40), default="", index=True)
detail: Mapped[dict] = mapped_column(JSON, default=dict)
def to_dict(self) -> dict:
return {
"id": self.id, "at": _iso(self.at), "username": self.username,
"project_id": self.project_id, "tool": self.tool, "event": self.event,
"detail": self.detail or {},
}
class AppSetting(Base):
"""Admin-editable application settings (feature flags, SMTP config, …) stored
as key -> JSON value. Read/written via /api/settings (admin only). Secrets like

View File

@@ -254,23 +254,27 @@ def main():
if ("el.textContent = '" in ln or "el.innerHTML = '" in ln)
and "the project" not in ln and ("✓" in ln or "⚠" in ln or "↻" in ln or "✕" in ln)])
print("\n7. autosave's own registration survives the retired analytics tracker")
# This section used to also assert the per-browser usage-analytics dwell
# listener (wp-usage.js) still fired alongside autosave, to catch autosave
# accidentally replacing it. CR-019/T11.6 (2026-09-23) retired that tracker
# on purpose - track() is now a documented no-op and wp-usage.js is gone -
# so asserting it still records an event would be asserting the wrong
# thing. What's still worth checking here is autosave's own registration,
# which is what this section actually guards.
print("\n7. the analytics dwell listener still fires")
boot(page, base, tok, "/work-package-suite.html?project=projA&tab=sop")
time.sleep(0.8)
chk("the wizard registered autosave",
chk("the wizard still has its analytics dwell tracker",
page.eval("typeof trackStepDwell === 'function'"))
chk("...and the wizard registered autosave too",
page.eval("typeof WPAutosave === 'object' && typeof sopDraftId === 'function'"))
chk("...and the retired dwell tracker is a harmless no-op, not missing or throwing",
page.eval("""(() => {
if (typeof trackStepDwell !== 'function') return false;
try { trackStepDwell(); return true; } catch (e) { return false; }
})()"""))
before = page.eval("""(() => {
try { return (JSON.parse(localStorage.getItem('wp_suite_analytics_v1')||'{}').events||[]).length; }
catch(e){ return -1; }
})()""")
# trackStepDwell only records a dwell longer than 400ms, so give it one.
time.sleep(0.9)
page.eval("typeof trackStepDwell==='function' && trackStepDwell()")
time.sleep(0.4)
after_n = page.eval("""(() => {
try { return (JSON.parse(localStorage.getItem('wp_suite_analytics_v1')||'{}').events||[]).length; }
catch(e){ return -1; }
})()""")
chk("calling it records an event (it was not replaced by the guard)",
after_n > before, "%s -> %s" % (before, after_n))
finally:
page.close()
browser.close()

View File

@@ -207,9 +207,12 @@ def run(page, base, tok):
chk("auth resolved to the admin account", page.eval("(window.WP_USER||{}).role") == "admin")
chk("the directory is visible",
page.eval("getComputedStyle(document.getElementById('users-main')).display") != "none")
chk("manager table renders 9 columns",
page.eval("document.querySelectorAll('#users-table thead th').length") == 9,
# 10 since CR-020 (T12.2): the 9 data columns plus the row-selection column.
chk("manager table renders 10 columns (9 + row selection)",
page.eval("document.querySelectorAll('#users-table thead th').length") == 10,
page.eval("document.querySelectorAll('#users-table thead th').length"))
chk("...the first is the selection column",
page.eval("!!document.querySelector('#users-table thead th.selcell #sel-all')"))
chk("an admin sees every account in the fixture (7)",
page.eval("document.querySelectorAll('#users-table tbody tr').length") == 7,
page.eval("document.querySelectorAll('#users-table tbody tr').length"))
@@ -237,15 +240,22 @@ def run(page, base, tok):
# Your own row: permissions locked so you cannot demote yourself, job function
# still editable. Asserted on the two cells, not "no select in the row".
# The cells are found by their HEADER, not by position: CR-020's selection
# column moved every column one to the right and these asserted r.cells[3]
# and [4], which then read the username and the email (T12.6).
ROW = ("const r=[...document.querySelectorAll('#users-table tbody tr')]"
".find(r=>r.querySelector('.me-tag'));")
".find(r=>r.querySelector('.me-tag'));"
"const col=n=>[...document.querySelectorAll('#users-table thead th')]"
".findIndex(h=>h.textContent.trim().toLowerCase()===n);")
def own(q):
return "(()=>{" + ROW + "if(!r)return false;const c=r.cells[3];return " + q + "})()"
return "(()=>{" + ROW + "if(!r)return false;const c=r.cells[col('permissions')];return " + q + "})()"
chk("your own permissions cell is locked, not a dropdown",
page.eval(own("!c.querySelector('select') && !!c.querySelector('.tag')")))
chk("...and wears the Administrator pill", page.eval(own("!!c.querySelector('.tag.admin')")))
chk("...while your job function stays editable",
page.eval("(()=>{" + ROW + "return !!r && !!r.cells[4].querySelector('select')})()"))
page.eval("(()=>{" + ROW + "return !!r && !!r.cells[col('project role')].querySelector('select')})()"))
chk("...and your own row cannot be ticked for a bulk action",
page.eval("(()=>{" + ROW + "return !!r && !r.querySelector('input.selbox')})()"))
page.eval("[...document.querySelectorAll('#users-table tbody button')]"
".find(b=>/project/i.test(b.textContent)).click()")

326
tests/bulk_users_check.py Normal file
View File

@@ -0,0 +1,326 @@
#!/usr/bin/env python3
"""CR-020 (wave 12): bulk user administration, server side.
python tests/bulk_users_check.py
Self-contained and needs NO browser: a throwaway SQLite database in a temp
folder, the API driven in-process with FastAPI's TestClient, everything deleted
afterward. Your real wpsuite.db is never touched.
What it proves is the wave's own exit criteria, measured on the server, where
they are enforced:
- every bulk action works on a list, row by row, with the single-user rules;
- the caller's own account is refused on its own row, never the whole batch;
- a super user's batch cannot reach an account or project outside their scope;
- one AuditLog row per changed account, the same shape the single route writes;
- a partial failure is reported row by row, never as a clean success;
- project add/remove never touches the user's other projects or their roles;
- the single-user routes, now built on the same functions, behave as before.
Exit codes: 0 all passed, 1 a check failed, 2 the run could not start.
"""
import os
import shutil
import sys
import tempfile
import warnings
warnings.filterwarnings("ignore")
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TMP = tempfile.mkdtemp(prefix="wp-bulk-users-check-")
os.environ["DATABASE_URL"] = "sqlite:///" + os.path.join(TMP, "bulk.db").replace("\\", "/")
os.environ["AUTH_SECRET_KEY"] = "bulk-users-check-key-bulk-users-check-0000"
os.environ.pop("WP_OKTA_FAKE_DIRECTORY", None)
sys.path.insert(0, ROOT)
try:
from fastapi.testclient import TestClient
from sqlalchemy import select
from server import app as A, auth, models
from server.db import SessionLocal
except Exception as exc: # noqa: BLE001
print("could not start:", exc)
sys.exit(2)
RESULTS = []
def check(name, ok, detail=""):
RESULTS.append(bool(ok))
print(f" {'PASS' if ok else 'FAIL'} {name}" + (f" ({detail})" if detail and not ok else ""))
db = SessionLocal()
def account(uid, role="project_user"):
u = models.User(id=uid, username=uid[5:], role=role, email=uid[5:] + "@example.test")
db.add(u)
db.commit()
return u
def member(uid, pid, role=""):
db.add(models.ProjectMember(id=f"pm_{uid}_{pid}", user_id=uid, project_id=pid, role=role))
db.commit()
def client(user):
c = TestClient(A.app, base_url="http://127.0.0.1", raise_server_exceptions=False)
c.cookies.set(auth.COOKIE_NAME, auth.create_token(user))
return c
def fresh():
s = SessionLocal()
s.expire_all()
return s
def audit(action, entity_id=None):
s = fresh()
q = select(models.AuditLog).where(models.AuditLog.action == action)
if entity_id:
q = q.where(models.AuditLog.entity_id == entity_id)
return s.scalars(q.order_by(models.AuditLog.at)).all()
def roles_of(uid):
s = fresh()
return {m.project_id: (m.role or "") for m in
s.scalars(select(models.ProjectMember).where(models.ProjectMember.user_id == uid))}
def by_user(resp):
return {r["user_id"]: r for r in resp.json().get("results", [])}
# ── fixture ──────────────────────────────────────────────────────────────────
admin = account("user_admin", "admin")
admin2 = account("user_admin2", "admin")
superu = account("user_super") # super user on proj1 and proj4 by membership
pu = account("user_pu") # plain project user: manages nobody
for n in range(1, 10):
account(f"user_u{n}")
for pid in ("proj1", "proj2", "proj3", "proj4"):
db.add(models.Project(id=pid, name=pid))
db.commit()
member("user_super", "proj1", "project_super_user")
member("user_super", "proj4", "project_super_user")
member("user_pu", "proj1")
for n in (1, 2, 3, 4, 5):
member(f"user_u{n}", "proj1")
member("user_u6", "proj1"); member("user_u6", "proj2", "project_admin") # partly outside super's scope
member("user_u7", "proj2") # wholly outside it
member("user_u8", "proj1"); member("user_u8", "proj4", "project_super_user") # a role super may not grant
ca, cs, cp = client(admin), client(superu), client(pu)
def single_routes():
print("\n0. the single-user routes still behave as before (now on the shared functions)")
r = ca.post("/api/auth/users/user_admin/role", json={"role": "project_user"})
check("changing your own role: 400, same words", r.status_code == 400 and "own role" in r.json()["detail"])
r = ca.post("/api/auth/users/user_admin/active", json={"is_active": False})
check("disabling yourself: 400, same words", r.status_code == 400 and "disable your own" in r.json()["detail"])
r = ca.delete("/api/auth/users/user_admin")
check("deleting yourself: 400, same words", r.status_code == 400 and "delete your own" in r.json()["detail"])
r = cs.post("/api/auth/users/user_u6/role", json={"role": "project_admin"})
check("a super user changing an account outside their scope: 403", r.status_code == 403)
r = cs.put("/api/auth/users/user_u3/projects", json={"project_ids": ["proj1", "proj2"]})
check("a super user assigning a project they don't run: 403", r.status_code == 403)
r = ca.post("/api/auth/users/user_u9/role", json={"role": "project_admin"})
check("a single role change still works and returns the directory row",
r.status_code == 200 and r.json().get("role") == "project_admin")
one = audit("role_changed", "user_u9")
check("...and writes one role_changed row", len(one) == 1 and one[0].detail == {"from": "project_user", "to": "project_admin"},
str([e.detail for e in one]))
ca.post("/api/auth/users/user_u9/role", json={"role": "project_user"})
def bulk_role():
print("\n1. bulk permissions role")
r = ca.post("/api/auth/bulk-users/role", json={
"user_ids": ["user_u1", "user_u2", "user_admin", "user_nobody", "user_u1", "bad id!"],
"role": "project_admin"})
res = by_user(r)
check("200 even though some rows fail (a partial failure is a result, not an error)", r.status_code == 200)
check("u1 and u2 changed", res["user_u1"]["status"] == "ok" and res["user_u2"]["status"] == "ok")
check("your own row is refused with its reason; the rest still ran",
res["user_admin"]["status"] == "failed" and "own role" in res["user_admin"]["reason"])
check("an unknown account is refused as 'User not found'",
res["user_nobody"]["status"] == "failed" and res["user_nobody"]["reason"] == "User not found")
check("a malformed id is refused, not crashed on", res["bad id!"]["status"] == "failed")
check("a duplicated id is applied once", r.json()["requested"] == 5)
check("counts match the rows", (r.json()["ok"], r.json()["failed"]) == (2, 3), str(r.json()))
rows = audit("role_changed", "user_u1")
check("one role_changed audit row per changed account, same shape as the single route",
len(rows) == 1 and rows[0].detail == {"from": "project_user", "to": "project_admin"}
and rows[0].actor == "admin" and rows[0].entity_type == "user", str([e.detail for e in rows]))
r = ca.post("/api/auth/bulk-users/role", json={"user_ids": ["user_u1"], "role": "project_admin"})
check("a row already in that role is 'unchanged' and writes no audit row",
by_user(r)["user_u1"]["status"] == "unchanged" and len(audit("role_changed", "user_u1")) == 1)
r = cs.post("/api/auth/bulk-users/role", json={"user_ids": ["user_u3"], "role": "admin"})
check("a super user cannot grant admin in bulk either (grantable_roles, whole request 400)",
r.status_code == 400)
r = cs.post("/api/auth/bulk-users/role", json={"user_ids": ["user_u3", "user_u6", "user_u7"],
"role": "project_admin"})
res = by_user(r)
check("super user: an account wholly inside their projects changes", res["user_u3"]["status"] == "ok")
check("super user: an account also on a project they don't run is refused, with the reason",
res["user_u6"]["status"] == "failed" and "don't administer" in res["user_u6"]["reason"],
res["user_u6"]["reason"])
check("super user: an account they cannot see is 'User not found' (no existence leak)",
res["user_u7"]["status"] == "failed" and res["user_u7"]["reason"] == "User not found")
r = ca.post("/api/auth/bulk-users/role", json={"user_ids": ["user_admin2"], "role": "project_user"})
check("demoting another admin works while one active admin remains (the caller)",
by_user(r)["user_admin2"]["status"] == "ok")
def bulk_active():
print("\n2. bulk activate / disable")
r = ca.post("/api/auth/bulk-users/active", json={"user_ids": ["user_u4", "user_admin", "user_u5"],
"is_active": False})
res = by_user(r)
check("u4 and u5 disabled", res["user_u4"]["status"] == "ok" and res["user_u5"]["status"] == "ok"
and not fresh().get(models.User, "user_u4").is_active)
check("your own account is refused on its own row",
res["user_admin"]["status"] == "failed" and "disable your own" in res["user_admin"]["reason"])
check("one user_disabled audit row each, same shape as the single route",
[e.detail for e in audit("user_disabled", "user_u4")] == [{"is_active": False}])
r = ca.post("/api/auth/bulk-users/active", json={"user_ids": ["user_u4", "user_u2"], "is_active": True})
res = by_user(r)
check("re-enable: u4 ok, u2 (already active) unchanged",
res["user_u4"]["status"] == "ok" and res["user_u2"]["status"] == "unchanged")
def bulk_projects():
print("\n3. bulk project add / remove")
r = cs.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u1", "user_u2", "user_u8"],
"project_id": "proj1", "op": "add", "role": "project_admin"})
res = by_user(r)
check("add with a per-project role: every row ok", all(res[u]["status"] == "ok" for u in ("user_u1", "user_u2", "user_u8")),
str(res))
check("the role landed on that project", roles_of("user_u1").get("proj1") == "project_admin")
check("the user's OTHER project and its role are untouched - even a role the caller could not grant",
roles_of("user_u8").get("proj4") == "project_super_user", str(roles_of("user_u8")))
rows = audit("project_access_changed", "user_u1")
check("one project_access_changed row per account, in the single route's shape",
len(rows) == 1 and set(rows[0].detail) == {"projects", "scope", "overrides"}
and rows[0].detail["scope"] == "managed", str([e.detail for e in rows]))
r = cs.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u1"], "project_id": "proj2", "op": "add"})
check("a super user cannot add anyone to a project they don't run (403)", r.status_code == 403)
r = cs.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u1"], "project_id": "proj1",
"op": "add", "role": "project_super_user"})
check("a super user cannot hand out super user on a project (400)", r.status_code == 400)
r = ca.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u6"], "project_id": "proj3", "op": "add"})
check("admin adds u6 to proj3; proj1 and proj2 memberships and roles stay",
by_user(r)["user_u6"]["status"] == "ok"
and roles_of("user_u6") == {"proj1": "", "proj2": "project_admin", "proj3": ""}, str(roles_of("user_u6")))
r = cs.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u2", "user_u9"], "project_id": "proj1", "op": "remove"})
res = by_user(r)
check("remove: u2 taken off proj1", res["user_u2"]["status"] == "ok" and "proj1" not in roles_of("user_u2"))
check("remove: someone not on it is 'User not found' to a super user who cannot see them",
res["user_u9"]["status"] == "failed")
r = ca.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u9"], "project_id": "proj1", "op": "remove"})
check("remove: an admin removing someone not on the project gets 'unchanged'",
by_user(r)["user_u9"]["status"] == "unchanged")
r = ca.post("/api/auth/bulk-users/projects", json={"user_ids": ["user_u1"], "project_id": "proj1", "op": "replace"})
check("only add and remove exist: no replace-the-whole-list (400)", r.status_code == 400)
def bulk_delete():
print("\n4. bulk delete")
r = ca.post("/api/auth/bulk-users/delete", json={"user_ids": ["user_u5", "user_admin", "user_gone"]})
res = by_user(r)
check("u5 deleted", res["user_u5"]["status"] == "ok" and fresh().get(models.User, "user_u5") is None)
check("your own account is refused on its own row, the others still ran",
res["user_admin"]["status"] == "failed" and "delete your own" in res["user_admin"]["reason"])
check("an account that no longer exists is reported, not hidden",
res["user_gone"]["status"] == "failed" and res["user_gone"]["reason"] == "User not found")
check("one user_deleted audit row, same shape as the single route",
[e.detail for e in audit("user_deleted", "user_u5")] == [{"role": "project_user"}])
check("the deleted account's memberships went with it", roles_of("user_u5") == {})
def csv_resolve():
print("\n6. CSV upload: usernames in, a line-by-line report out (T12.4)")
text = ("username\n" # header, skipped
"u3\n"
"U3\n" # same person, different case: a duplicate
"nobody\n"
"\n" # blank lines are not rows
"u6\n" # visible to the super user, but also on a project they don't run
"u7\n" # not visible to the super user at all
"super\n" # the caller themself
"u8@example.test,extra column\n" # an email address, matched to exactly one account
",\n") # an empty first column
r = cs.post("/api/auth/bulk-users/resolve", json={"text": text})
j = r.json()
rows = {x["line"]: x for x in j["rows"]}
check("200 with a row for every non-blank line after the header",
r.status_code == 200 and sorted(rows) == [2, 3, 4, 6, 7, 8, 9, 10], sorted(rows))
check("a valid username is accepted", rows[2]["status"] == "ok" and rows[2]["user_id"] == "user_u3")
check("a repeated username is rejected as a duplicate of its first line, not applied twice",
rows[3]["status"] == "rejected" and rows[3]["reason"] == "duplicate of line 2")
check("an unknown username: 'User not found', with its line number", rows[4]["reason"] == "User not found")
check("an account the caller may not change: rejected with the single route's own reason",
rows[6]["status"] == "rejected" and "don't administer" in rows[6]["reason"], rows[6]["reason"])
check("an account the caller cannot see: 'User not found' (a CSV leaks no more than the table)",
rows[7]["reason"] == "User not found")
check("the caller's own account is rejected with a clear reason", "your own account" in rows[8]["reason"])
check("an email address resolves when exactly one account has it",
rows[9]["status"] == "ok" and rows[9]["user_id"] == "user_u8")
check("an empty first column is rejected, not skipped", rows[10]["reason"] == "no username in the first column")
check("the ids handed back are exactly the accepted rows",
j["user_ids"] == ["user_u3", "user_u8"] and (j["accepted"], j["rejected"]) == (2, 6), str(j["user_ids"]))
r = cs.post("/api/auth/bulk-users/active", json={"user_ids": j["user_ids"] + ["user_u7"], "is_active": False})
res = by_user(r)
check("the CSV's ids go through the same bulk route and the same guards: an id slipped in by hand "
"is still refused", res["user_u7"]["status"] == "failed" and res["user_u3"]["status"] == "ok")
ca.post("/api/auth/bulk-users/active", json={"user_ids": ["user_u3", "user_u8"], "is_active": True})
r = cp.post("/api/auth/bulk-users/resolve", json={"text": "u3"})
check("a plain project user cannot resolve a list (403)", r.status_code == 403)
r = cs.post("/api/auth/bulk-users/resolve", json={"text": "x" * 200_001})
check("an oversized upload is refused (422)", r.status_code == 422)
s = fresh()
s.add(models.User(id="user_twin1", username="twin1", email="shared@example.test"))
s.add(models.User(id="user_twin2", username="twin2", email="shared@example.test"))
s.commit()
r = ca.post("/api/auth/bulk-users/resolve", json={"text": "shared@example.test"})
check("an email shared by two accounts matches neither", r.json()["rows"][0]["reason"] == "User not found")
def gates():
print("\n7. who may call, and how much")
for path, body in (("role", {"role": "project_user"}), ("active", {"is_active": False}),
("projects", {"project_id": "proj1", "op": "add"}), ("delete", {})):
r = cp.post(f"/api/auth/bulk-users/{path}", json={"user_ids": ["user_u3"], **body})
check(f"a plain project user is refused /bulk-users/{path} (403)", r.status_code == 403, str(r.status_code))
anon = TestClient(A.app, base_url="http://127.0.0.1", raise_server_exceptions=False)
check("no session: 401", anon.post("/api/auth/bulk-users/delete", json={"user_ids": ["user_u3"]}).status_code == 401)
r = ca.post("/api/auth/bulk-users/active", json={"user_ids": [f"user_x{i}" for i in range(501)], "is_active": False})
check("more than 500 ids in one request is refused (422)", r.status_code == 422, str(r.status_code))
SECTIONS = [single_routes, bulk_role, bulk_active, bulk_projects, bulk_delete, csv_resolve, gates]
def main() -> int:
print("Wave 12 bulk user administration - server checks")
try:
for section in SECTIONS:
try:
section()
except Exception as exc: # noqa: BLE001 - a missing route must read as FAIL, not a traceback
check(f"section {section.__name__} ran to the end", False, f"{type(exc).__name__}: {exc}")
finally:
db.close()
A.engine.dispose()
shutil.rmtree(TMP, ignore_errors=True)
passed = sum(RESULTS)
print(f"\n{passed}/{len(RESULTS)} checks passed.")
return 0 if passed == len(RESULTS) else 1
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,197 @@
#!/usr/bin/env python3
"""CR-020 (wave 12): bulk user administration in the browser, at 1440px and 390px.
python tests/bulk_users_ui_check.py
Self-contained like the other probes: a throwaway SQLite database seeded by
browser_check.seed(), its own uvicorn, headless Edge or Chrome over CDP. Your
real wpsuite.db is never touched. Run it alone, not back to back with another
probe (file-map.md: chained runs exhaust the browser's ports).
The server rules are proven in tests/bulk_users_check.py without a browser.
This file proves the page: selection, the toolbar, the CSV path and the typed
delete, end to end against the real server, operable by keyboard, and holding
together at 390px. It writes the after-screenshots CLAUDE.md asks for to
docs/reference/baseline/wave-12/; the before-shots are the existing
users-1440.png and after-wave9/users-390.png.
Exit 0 all passed, 1 a failure, 2 could not run.
"""
import json
import os
import sys
import tempfile
import time
import urllib.request
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import cdp # noqa: E402
from browser_check import seed, start_server, chk, _PASS, _FAIL # noqa: E402
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SHOTS = os.path.join(ROOT, "docs", "reference", "baseline", "wave-12")
READY = "!!document.querySelector('#users-table table')"
def api(base, path, token):
req = urllib.request.Request(base + path, headers={"Cookie": "wp_session=" + token})
with urllib.request.urlopen(req, timeout=10) as r:
return json.loads(r.read().decode())
def user(base, token, username):
return next((u for u in api(base, "/api/auth/users", token) if u["username"] == username), None)
def press(page, key, code, vk):
"""A REAL key event (Input.dispatchKeyEvent), not a synthetic KeyboardEvent:
only a real one triggers a checkbox's native Space toggle - the lesson
launcher_check.py records."""
for t in ("keyDown", "keyUp"):
page.ws.call("Input.dispatchKeyEvent", {"type": t, "key": key, "code": code,
"windowsVirtualKeyCode": vk, "text": " " if t == "keyDown" else ""})
time.sleep(0.3)
def answer(page, ok=True, typed=None):
time.sleep(0.4)
if typed is not None:
page.eval("document.getElementById('wp-dlg-input').value=%s" % json.dumps(typed))
page.eval("document.getElementById('%s').click()" % ("wp-dlg-ok" if ok else "wp-dlg-cancel"))
time.sleep(1.2)
def tick(page, username):
page.eval("(() => { const b=[...document.querySelectorAll('input.selbox')]"
".find(x => x.dataset.id==='user_%s'); if(b) b.click(); })()" % username)
time.sleep(0.2)
BAR_390 = """(function(){
var bar=document.getElementById('bulk-bar'); var out={sw:document.documentElement.scrollWidth,under:[],clipped:[],n:0};
bar.querySelectorAll('button, select').forEach(function(el){
var r=el.getBoundingClientRect(); if(!r.width||!r.height) return; out.n++;
var id=el.tagName+' '+(el.textContent||el.id).trim().slice(0,20)+' '+Math.round(r.width)+'x'+Math.round(r.height);
if(Math.min(r.width,r.height)<24) out.under.push(id);
if(r.left<-2||r.right>392) out.clipped.push(id);
});
return JSON.stringify(out);
})()"""
def main():
exe = cdp.find_browser()
if not exe:
print("no headless-capable browser found; set WP_BROWSER.")
return 2
tmpdir = tempfile.mkdtemp(prefix="wpsuite-bulkui-")
db_path = os.path.join(tmpdir, "check.db")
server = browser = None
try:
tok = seed(db_path)
port = cdp.free_port()
base = "http://127.0.0.1:%d" % port
server = start_server(port, db_path)
if server is None:
print("server would not start")
return 2
browser = cdp.Browser(exe)
page = browser.page()
def visit(who, width, mobile=False):
page.clear_cookies()
page.set_cookie("wp_session", tok[who])
page.viewport(width, 900 if width > 500 else 844, mobile=mobile)
page.goto(base + "/users.html", wait_for=READY)
time.sleep(0.6)
print("\n1. the admin at 1440px")
visit("root", 1440)
page.screenshot(os.path.join(SHOTS, "users-1440.png"))
chk("a selection column with select-all", page.eval("!!document.getElementById('sel-all')"))
chk("no bulk bar until a row is selected", page.eval("document.getElementById('bulk-bar').hidden"))
page.eval("document.querySelector('input.selbox[data-id=\"user_pat\"]').focus()")
press(page, " ", "Space", 32)
chk("Space on a focused row checkbox selects it (keyboard operable)",
page.eval("document.querySelector('input.selbox[data-id=\"user_pat\"]').checked"))
chk("the bar appears, reachable by keyboard",
page.eval("!document.getElementById('bulk-bar').hidden && document.querySelector('#bulk-bar button').tabIndex >= 0"))
tick(page, "legacy")
chk("the bar counts the selection", page.eval("document.getElementById('bulk-count').textContent") == "2 selected")
page.screenshot(os.path.join(SHOTS, "users-1440-selected.png"))
page.eval("document.getElementById('bulk-role').value='project_admin';"
"document.querySelector('[onclick=\"bulkRole()\"]').click()")
time.sleep(0.4)
chk("the confirm names the count", "for 2 users" in (page.eval("document.getElementById('wp-dlg-msg').textContent") or ""))
answer(page)
chk("both accounts changed on the server",
user(base, tok["root"], "pat")["role"] == "project_admin" and user(base, tok["root"], "legacy")["role"] == "project_admin")
chk("the result is announced", "2 changed" in page.eval("document.getElementById('bulk-banner').textContent")
and page.eval("document.getElementById('bulk-banner').getAttribute('role')") in ("status", "alert"))
tick(page, "pat")
page.eval("const f=document.getElementById('user-filter'); f.value='active'; f.dispatchEvent(new Event('change'))")
time.sleep(0.3)
chk("changing the filter clears the selection, and says so",
page.eval("document.getElementById('bulk-bar').hidden") and
"filter changed" in page.eval("document.getElementById('sel-banner').textContent"))
print("\n2. the super user, a CSV with good and bad lines")
visit("sue", 1440)
page.eval("loadCsv(new File(['username\\npat\\nmix\\nbob\\nsue\\npat\\n'], 'list.csv', {type:'text/csv'}))")
time.sleep(1.5)
rep = page.eval("document.getElementById('csv-banner').textContent") or ""
chk("only the account she may change is selected", page.eval("document.getElementById('bulk-count').textContent") == "1 selected", rep)
chk("every bad line is reported by number and reason: another job, not found, herself, a duplicate",
all(s in rep for s in ("Line 3 (mix)", "Line 4 (bob): User not found", "Line 5 (sue)", "Line 6 (pat): duplicate of line 2")), rep)
page.eval("document.getElementById('bulk-project-role').value='project_admin';"
"document.querySelector('[onclick=\"bulkProject(\\'add\\')\"]').click()")
answer(page)
roles = api(base, "/api/auth/users/user_pat/projects", tok["root"])["roles"]
chk("add to project with a role landed on the server", roles.get("projA") == "project_admin", roles)
print("\n3. bulk delete needs the typed word")
visit("root", 1440)
tick(page, "bob")
page.eval("document.querySelector('[onclick=\"bulkDelete()\"]').click()")
time.sleep(0.4)
chk("the dialog lists the username", "bob" in page.eval("document.getElementById('wp-dlg-msg').textContent"))
page.eval("document.getElementById('wp-dlg-input').value='delete'; document.getElementById('wp-dlg-ok').click()")
time.sleep(0.4)
chk("a wrong word sends nothing", user(base, tok["root"], "bob") is not None
and page.eval("document.getElementById('wp-dlg-overlay').classList.contains('open')"))
answer(page, typed="DELETE")
chk("DELETE deletes, and the report says so", user(base, tok["root"], "bob") is None
and "1 changed" in page.eval("document.getElementById('bulk-banner').textContent"))
print("\n4. the gloved-hands width: 390px")
visit("root", 390, mobile=True)
page.screenshot(os.path.join(SHOTS, "users-390.png"))
tick(page, "pat")
m = json.loads(page.eval(BAR_390))
page.screenshot(os.path.join(SHOTS, "users-390-selected.png"))
chk("390px with the bar open: no sideways scrolling", m["sw"] <= 392, m["sw"])
chk("390px: no bar control clipped past the screen", not m["clipped"], m["clipped"])
chk("390px: every bar control meets the 24px floor", m["n"] > 0 and not m["under"], m["under"])
errs = [e for e in page.js_errors() if "beforeunload" not in e]
chk("no JavaScript errors in the whole run", not errs, errs[:3])
finally:
if browser is not None:
try:
browser.close()
except Exception:
pass
if server is not None:
server.terminate()
print("\n" + "-" * 54)
print("%d/%d checks passed." % (len(_PASS), len(_PASS) + len(_FAIL)))
for f in _FAIL:
print(" - " + f)
return 1 if _FAIL else 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -190,8 +190,26 @@ class Browser:
f"--user-data-dir={self.profile}", "--remote-allow-origins=*",
"--no-first-run", "--no-default-browser-check", "--disable-gpu",
"--disable-extensions", "--disable-sync",
"--window-size=1400,1000", "about:blank"],
"--window-size=1400,1000"]
# Run from an elevated (Administrator) shell, Edge and Chrome
# "de-elevate": they relaunch themselves as a normal user through
# Explorer and the launched process exits rc=0. The relaunch does
# not keep the debugging port, so the port is never bound (found
# 2026-10-02; Edge logs "Edge is running elevated: 1"). This
# Chromium switch keeps the process we started. Ignored when the
# shell is not elevated, and on other platforms.
+ (["--do-not-de-elevate"] if sys.platform == "win32" else [])
+ ["about:blank"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# On some Windows installs msedge.exe is a launcher: it starts the real
# browser and exits rc=0 at once, and the real browser binds the port a
# moment later. Giving up the instant the launched process exited
# failed every attempt on such a machine although Edge worked when
# started by hand (found 2026-10-02 running the wave 16 probes). An
# rc=0 exit now gets a grace period to bind; a non-zero exit is still
# a failure at once. Teardown is unaffected: close() sweeps by the
# unique profile path, which also catches the handed-off process.
exited_at = None
for _ in range(160):
try:
with urllib.request.urlopen(
@@ -199,9 +217,14 @@ class Browser:
json.load(r)
return
except Exception:
if self.proc.poll() is not None:
last = f"exited rc={self.proc.returncode} without binding the port"
break
rc = self.proc.poll()
if rc is not None:
last = f"exited rc={rc} without binding the port"
if rc != 0:
break
exited_at = exited_at or time.time()
if time.time() - exited_at > 15:
break
time.sleep(0.25)
else:
last = "never bound the debugging port"

View File

@@ -112,6 +112,33 @@ def main():
chk("cancel means no: bob is still an account",
st == 200 and any(u.get("username") == "bob" for u in (users or [])),
ascii_([u.get("username") for u in (users or [])]))
# CR-020 / T12.5: the bulk delete is a PROMPT-style dialog (typed DELETE),
# the kind this file's docstring says belongs back here.
print("\n4. bulk delete needs the typed word")
page.eval("(() => { const b=[...document.querySelectorAll('input.selbox')]"
".find(x => x.dataset.id==='user_bob'); b.click(); })()")
time.sleep(0.3)
chk("ticking a row shows the bulk bar",
page.eval("!document.getElementById('bulk-bar').hidden"))
page.eval("document.querySelector('[onclick=\"bulkDelete()\"]').click()")
time.sleep(0.4)
chk("the bulk delete asks through the kit's prompt, listing the username",
page.eval("(() => { const o=document.getElementById('wp-dlg-overlay');"
" return o.classList.contains('open')"
" && document.getElementById('wp-dlg-input-wrap').style.display !== 'none'"
" && /bob/.test(document.getElementById('wp-dlg-msg').textContent); })()"))
page.eval("document.getElementById('wp-dlg-input').value='delete';"
"document.getElementById('wp-dlg-ok').click()")
time.sleep(0.3)
chk("the wrong word keeps it open and names what to type",
page.eval("document.getElementById('wp-dlg-overlay').classList.contains('open')"
" && /DELETE/.test(document.getElementById('wp-dlg-err').textContent)"))
page.eval("document.getElementById('wp-dlg-cancel').click()")
time.sleep(0.6)
st, users = api(base, "/api/auth/users", tok["root"])
chk("cancel means no: bob is still an account after the bulk prompt",
st == 200 and any(u.get("username") == "bob" for u in (users or [])))
errs = [e for e in page.js_errors() if "beforeunload" not in e]
chk("no JavaScript errors, and no path reached a native dialog (they throw here)",
not errs, ascii_(errs[:3]))

192
tests/usage_check.py Normal file
View File

@@ -0,0 +1,192 @@
#!/usr/bin/env python3
"""Is there exactly one analytics implementation, reported from admin? — D5, T7.10.
Usage analytics existed twice (creator + wizard), five of the nine colliding
globals `creator-frame.md` counted, and the wizard's copy had no caller. One
core survives in wp-usage.js; the pages keep thin track() wrappers; the report
and its downloads live on the admin console behind the same role gate as the
rest of that page. Keys are unchanged, so pre-move data still reads.
Self-contained: throwaway SQLite, its own uvicorn, headless Edge or Chrome.
Exit 0 all passed, 1 a failure, 2 could not run.
"""
import json
import os
import re
import sys
import tempfile
import time
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import cdp # noqa: E402
from browser_check import seed, start_server, chk, _PASS, _FAIL # noqa: E402
from sections_check import set_sop # noqa: E402
from stepper_check import dismiss_dialogs # noqa: E402
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
HTML = os.path.join(ROOT, "html")
def ascii_(v, n=280):
return re.sub(r"\s+", " ", str(v)).encode("ascii", "replace").decode()[:n]
def settle(seconds=0.6):
time.sleep(seconds)
def strip_js(src):
src = re.sub(r"/\*.*?\*/", "", src, flags=re.S)
return "\n".join(re.sub(r"(?<![:'\"])//.*$", "", ln) for ln in src.split("\n"))
def main():
exe = cdp.find_browser()
if not exe:
print("no headless-capable browser found; set WP_BROWSER.")
return 2
# ── 1. the grep half: one implementation, no leftover controls ───────────
print("\n1. grep: one implementation, nothing unreferenced")
files = {}
for name in os.listdir(HTML):
if name.endswith((".js", ".html")):
files[name] = strip_js(open(os.path.join(HTML, name), encoding="utf-8").read())
core_defs = [n for n, src in files.items() if "window.WPUsage" in src]
chk("the WPUsage core is defined in wp-usage.js and only there",
core_defs == ["wp-usage.js"], ascii_(core_defs))
chk("the pages record THROUGH it - no page touches the storage keys directly",
all("wp_iwp_analytics_v1" not in src and "wp_suite_analytics_v1" not in src
for n, src in files.items()
if n not in ("wp-usage.js",) and n.endswith(".js")))
leftovers = {n: re.findall(r"analyticsLoad|analyticsSave|downloadAnalytics|showAnalytics"
r"|ANALYTICS_KEY|USAGE_KEY|usageLoad|downloadUsage", src)
for n, src in files.items() if n != "wp-usage.js"}
leftovers = {n: v for n, v in leftovers.items() if v}
chk("none of the five colliding globals survives anywhere; grep confirms",
not leftovers, ascii_(leftovers))
chk("no analytics control remains on the creator or the wizard; grep confirms",
"Usage data" not in files["wp-creation-index.html"]
and "showAnalytics" not in files["work-package-suite.html"])
chk("both storage keys survive, verbatim, in the core (data continuity)",
"wp_iwp_analytics_v1" in files["wp-usage.js"]
and "wp_suite_analytics_v1" in files["wp-usage.js"])
tmpdir = tempfile.mkdtemp(prefix="wpsuite-usage-")
db_path = os.path.join(tmpdir, "check.db")
server = None
browser = None
try:
tok = seed(db_path)
set_sop(db_path, {})
port = cdp.free_port()
base = "http://127.0.0.1:%d" % port
server = start_server(port, db_path)
browser = cdp.Browser(exe)
page = browser.page()
page.clear_cookies()
page.set_cookie("wp_session", tok["root"])
page.viewport(1440, 900)
# ── 2. recording still works from both tools ─────────────────────────
print("\n2. the tools still record")
page.goto(base + "/wp-creation-index.html?project=projA")
dismiss_dialogs(page)
settle(2.0)
# Plant a LEGACY-format event under the pre-move key: the done-when is
# that data recorded before this task is still readable after it.
page.eval("""(() => {
const d = JSON.parse(localStorage.getItem('wp_iwp_analytics_v1')) || {events: []};
d.events.unshift({ts: '2026-07-01T10:00:00Z', session: 's_legacy',
event: 'legacy_probe_event', detail: null});
localStorage.setItem('wp_iwp_analytics_v1', JSON.stringify(d));
})()""")
n0 = page.eval("WPUsage.load(WPUsage.KEYS.creator).events.length")
page.eval("track('probe_event')")
chk("the creator's track() still lands events under the old key",
page.eval("WPUsage.load(WPUsage.KEYS.creator).events.length") == n0 + 1)
page.goto(base + "/work-package-suite.html?tab=sop")
dismiss_dialogs(page)
settle(2.0)
n0 = page.eval("WPUsage.load(WPUsage.KEYS.wizard).events.length")
page.eval("track('probe_event_wizard')")
chk("the wizard's track() still lands events under its old key",
page.eval("WPUsage.load(WPUsage.KEYS.wizard).events.length") == n0 + 1)
wiz_errors = [e for e in page.js_errors() if "beforeunload" not in e]
chk("...and the wizard page throws no errors without its old globals "
"(the blocked-beforeunload console line is BL-020, filtered not hidden)",
not wiz_errors, ascii_(wiz_errors[:2]))
# ── 3. the report, on admin, behind the admin gate ───────────────────
print("\n3. the admin report")
page.goto(base + "/admin.html")
dismiss_dialogs(page)
settle(2.0)
page.eval("loadUsage()")
settle(0.5)
report = page.eval("(document.getElementById('usage-admin')||{textContent:''}).textContent")
chk("usage data is reachable from admin.html, both tools reported",
"Work package creator" in report and "SOP wizard" in report, ascii_(report, 160))
chk("the pre-move legacy event is readable in the report",
"legacy_probe_event" in report)
chk("this session's fresh events are in it too",
"probe_event" in report and "probe_event_wizard" in report)
chk("each tool offers its download from the report",
page.eval("[...document.querySelectorAll('#usage-admin button')].length") >= 2)
page.viewport(390, 844, mobile=True)
settle(0.6)
fits = page.eval("""(() => {
const box = document.getElementById('usage-admin');
return box && box.scrollWidth <= box.clientWidth + 2
&& document.documentElement.scrollWidth <= 392;
})()""")
chk("the report is usable at 390px - no sideways scrolling", bool(fits))
page.viewport(1440, 900)
settle(0.4)
# The same role gate as the rest of the console: a non-admin sees the
# denied card and no cards, this one included.
page.clear_cookies()
page.set_cookie("wp_session", tok["pat"])
page.goto(base + "/admin.html")
dismiss_dialogs(page)
settle(2.0)
chk("a non-administrator gets the denied notice, not the usage report",
page.eval("""(() => {
const denied = document.getElementById('admin-denied');
const usage = document.getElementById('usage-admin');
const visible = el => !!el && el.offsetParent !== null;
return visible(denied) && !visible(usage);
})()"""))
js_errors = [e for e in page.js_errors() if "beforeunload" not in e]
chk("no JavaScript errors anywhere in this run", not js_errors,
ascii_(js_errors[:2]))
finally:
if browser is not None:
try:
browser.close()
except Exception:
pass
if server is not None:
try:
server.terminate()
except Exception:
pass
print("\n" + "-" * 54)
print("%d/%d checks passed." % (len(_PASS), len(_PASS) + len(_FAIL)))
for f in _FAIL:
print(" - " + f)
return 1 if _FAIL else 0
if __name__ == "__main__":
sys.exit(main())