Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ Non-trivial logic must include one runnable check (unit test or minimal self-che
- The workspace and admin navigation end with the ky-ui account footer (`UserBlock`: `.ky-user-copy` with name and role, then `.ky-user-actions` holding `AppFrame`'s two `.ky-icon-button`s, the Settings menu's gear (`aria-current="page"` while Settings is open) and Sign out, each with `aria-label` and `title`; the words "Sign out" never show) and licence line (`web/src/components/LicenseFooter.tsx`); signed-out screens show the licence line under the card. It opens the shell About dialog (`ky-about`): name, "Developed by Busnes.app", MIT notice and `web/src/mit.txt`, a byte copy of `LICENSE.txt` (`LicenseFooter.test.tsx` fails when they differ). Signed in, the window shows the version from `GET /api/v1/auth/session` (`version`, `appversion.String()`); signed out it shows none, and the session route answers 401 (`TestAccountRoutesServeBothKinds`).
- The ky-ui app rail (`AppRail` in `web/src/components/AppNav.tsx`) heads the sidebar foot and the phone content foot of every `AppFrame`, so it shows only where the signed-in frame does (never on sign-in, password-change or locked screens). `AppFrame` fetches `GET /api/v1/suite/apps` once per mount; an empty list or a failed request renders no nav. Links are the server's hrefs exactly, same tab, `appMark(id)` images (data: URIs, allowed by `img-src` in `internal/web/embed.go`), and `kynotes` carries `aria-current="page"`. The server (`internal/httpapi/suite_routes.go`, `RequireAccount`) asks KyIdentity's suite directory (ky-primitives `suitedir`) with the effective SSO settings' client credentials and the session's SSO subject, only when the session's issuer is the configured one; password sessions, unconfigured SSO and errors answer `{"apps":[]}`, errors are logged without sub or secret, and successes are cached 60 s per account. Verify `TestSuiteApps*`, `AppRail.test.tsx` and `web/e2e/app-rail.e2e.ts`.
- State badges are the ky-ui `.ky-status` pill (a word and a dot, never colour alone, never the accent): the Users table status (Active success, Disabled neutral), Server health and readiness (OK success, Failed danger, Checking… neutral) and the page save status (Saved to server success, Needs attention danger, Unsaved changes, Syncing… and Saved locally neutral; `e2e/ui-council.e2e.ts`). There is no local pill CSS.
- `serviceStatus` reports a rejected health/readiness request as a failed probe independently, preserving the other result. Staff Refresh retries the probes; `api-status.test.ts` and `staff-console.e2e.ts` cover HTTP refusal, network failure and recovery.
- `web/src/ky-ui/` is generated from Busnes-app/ky-ui, pinned by `VERSION` file hashes. Change shared colors, navigation states, the shell (`shell.css`) and storage helpers upstream, then run its consumer sync with an explicit worktree map; do not hand-edit vendored files.
- Products own layout, routes, saved choice keys and named palettes. Busnes aliases consume shared tokens; mark primary navigation with `ky-nav-item` while preserving current-page semantics.
- `web/src/main.tsx` starts ky-ui's `watchForUpdate` (the update notice). The entry document is never served from a cache: the global `no-store` covers it (`TestEntryDocumentIsNeverServedFromCache`).
Expand Down Expand Up @@ -322,6 +323,19 @@ Non-trivial logic must include one runnable check (unit test or minimal self-che
loaders and multi startup remain refused; maintenance never mints local keys or recovers bytes.
Verify `TestStaffUserCommand*`, `TestStaffBootstrap*`, `TestReplicaMaintenance*`,
`TestReplicaAccept*`, existing bootstrap/user/golden tests and both backend race profiles.

- Staff surface preparation in recorded multi mode: `GET /admin/users` requires one `org`
query value and returns only that org's accounts/usage; `/admin/audit` defaults to platform
rows and accepts one org. `staff.read` is a platform audit naming the selected org, committed
before disclosure with an in-transaction `SessionRole` recheck. `/admin/orgs` is read-only
mirror/pool/usage metadata. User/team web mutations and team listing are absent in multi mode;
staff accounts remain host-managed and customer lifecycle remains KyIdentity's.
Multi user/session responses alone add `user.tenancy="multi"`; single responses keep their
exact shape. The web StaffConsole keeps one AppFrame navigation, native org/scope selectors,
read-only account/SSO views and scope-bound asynchronous results. SingleAdminConsole remains
the original surface. No UI choice grants access or changes the startup refusal.
Verify `TestStaff*`, N6, route classification, quota regressions, cross-org matrix and golden;
`staffAPI.test.ts` and `staff-console.e2e.ts` exercise parsing, scope changes and late responses.
- Native PostgreSQL restored-target preparation: `prepare-postgres-restore --confirm-restored`
reads `KYNOTES_DB_DSN` only from the environment, opens the exact existing schema without
migrating and refuses recorded single mode. Stop every replica before targeting a separately
Expand Down
17 changes: 17 additions & 0 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -1063,3 +1063,20 @@ only when both the store's server-owned fixed marker and recorded multi mode agr
account/org/erasure/revocation/replay fences remain under the writer lock. Single mode and
mutable stores retain the database configuration recheck. Signed tests cover fixed directory
signatures, logout replay/in-flight-login fencing, and refusal to bypass single-mode settings.

### Staff surface preparation

In multi mode the staff-only users read requires `?org=`, audit defaults to platform rows
and may select one org, and the new org listing exposes mirror and storage-pool metadata.
Each metadata read rechecks the administrator inside its writer transaction, builds the
response, commits a platform `staff.read` audit and only then publishes it. Missing/duplicate
org selection, missing orgs or failed audit disclose no directory data. User/team writes and
team listing are absent in multi mode. Existing single-mode handlers and answers remain.
User/account usage reuses the quota accounting function; org usage uses the pool counter.

Only multi-mode user/session metadata adds `tenancy: "multi"`. The browser selects the
staff console from that server-owned flag, within the existing Busnes AppFrame and native
controls. Org/scope choices send explicit query values, metadata is validated on receipt,
and asynchronous results retain their scope so a late reply cannot appear under another org.
Customer account and SSO controls are read-only; the original single console is retained.
Backend authorization remains authoritative. Multi startup still refuses this preparation.
11 changes: 11 additions & 0 deletions IMPLEMENTATION_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -2368,3 +2368,14 @@ only when both the store's server-owned fixed marker and recorded multi mode agr
account/org/erasure/revocation/replay fences remain under the writer lock. Single mode and
mutable stores retain the database configuration recheck. Signed tests cover fixed directory
signatures, logout replay/in-flight-login fencing, and refusal to bypass single-mode settings.

### Phase 6 staff surface preparation

Built read-only org/pool listing, org-scoped users/usage, platform-default/scoped audit reads
with fail-closed platform auditing and transactional staff recheck. Multi user/team web writes
are absent. StaffConsole uses the existing shell/native selectors and validates metadata;
server-owned multi user/session metadata selects it without changing single-mode answers.
Tests cover org selection, audit failure, revoked actors, customer mutation/content refusal,
usage agreement, response parsing and stale UI replies; run both backend races, the golden,
frontend checks/build/dist diff and browser fixtures. Startup remains refused. Host staff CLI,
replica config-accept maintenance and final hosted lifecycle acceptance remain separate work.
7 changes: 7 additions & 0 deletions docs/ASSURANCE-CASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,3 +231,10 @@ only when both the store's server-owned fixed marker and recorded multi mode agr
account/org/erasure/revocation/replay fences remain under the writer lock. Single mode and
mutable stores retain the database configuration recheck. Signed tests cover fixed directory
signatures, logout replay/in-flight-login fencing, and refusal to bypass single-mode settings.

Staff metadata preparation scopes users/audit reads to an explicit org and audits before
response publication. Tests recheck a concurrently revoked actor, refuse failed audits and
customer web mutations/content access, and compare logical usage. The staff browser performs
only read operations for accounts and SSO, validates returned metadata and suppresses stale
scope responses. Single-mode golden/UI regressions remain required; no hosted readiness is
claimed while startup is refused.
10 changes: 10 additions & 0 deletions docs/src/using.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,13 @@ Follow the ordered runbook: recover the capsule and deployment secrets, then fet
For native PostgreSQL recovery rehearsals, the [restore runbook](https://github.com/Busnes-app/KyNotes-server/blob/master/docs/RESTORE.md#prepare-a-native-postgresql-restored-target-tenancy-preparation)
explains the offline restored-target safety command. Hosted startup and backup transport
remain unavailable; preparing a target is not permission to serve it.


## Staff organization metadata (tenancy preparation)

Hosted startup remains unavailable in this release. The prepared staff console lists
organization status and storage-pool metadata. Select an organization under Users to inspect
its accounts and charged bytes, or select Platform/an organization under Audit log. Refresh
re-reads metadata. Customer accounts are managed in KyIdentity; staff metadata access never
opens notes, and there are no customer account, team or sign-in configuration write controls.
Standalone administrators keep the existing console and local account workflows.
15 changes: 15 additions & 0 deletions docs/superpowers/specs/2026-11-23-tenancy-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -1392,6 +1392,21 @@ Tests cover both schema-version refusals, explicit target/secret boundaries, ato
and rollback, and single-mode no-change. The command does not recover PG backup bytes, choose
open question 3's large-database transport or enable multi startup. Those remain prerequisites.

### Staff surface as built (startup still refused)

The prepared multi-mode admin surface requires one org for the users read, filters the audit
read to platform rows by default or one selected org, and lists org mirror/pool/usage metadata.
A writer transaction rechecks staff authority and commits the platform `staff.read` audit
before response publication. User/team web writes and team listing refuse multi mode.

Only multi-mode user/session metadata adds `user.tenancy="multi"`, selecting a read-only staff
console within the existing shell. Native org/audit selectors, wire validation and scope-bound
async state prevent stale replies appearing under a different org. Single-mode JSON and the
original administration UI remain unchanged. Backend role/isolation checks stay authoritative.
Tests cover both backends, logical usage, failed audit, revoked actors, missing/duplicate orgs,
customer mutation/content refusal, parsing and real-browser late replies. This does not enable
multi startup or complete the native backup/object/runtime prerequisites.

## Residual risks

- **One writer for every org.** N3 serialises all writes on PostgreSQL. A busy org delays the
Expand Down
35 changes: 21 additions & 14 deletions internal/httpapi/admin_routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ func recordAuditOutcome(db *sql.DB, actor, event, container, object, outcome, re
// ciphertext, request bodies, or raw process logs.
func AdminRoutes(mux RouteMux, db *sql.DB, ssoStore *sso.Store, cfg config.Config) {
viaProxy := forwardedFromProxy(cfg)
mux.Handle("POST /api/v1/admin/teams", auth.RequireStepUp(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
registerStaffOrgs(mux, db, cfg)
mux.Handle("POST /api/v1/admin/teams", singleModeOnly(db, auth.RequireStepUp(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if auth.CheckCSRF(r) != nil {
WriteError(w, r, 403, "csrf_failed", "csrf validation failed")
return
Expand Down Expand Up @@ -76,8 +77,8 @@ func AdminRoutes(mux RouteMux, db *sql.DB, ssoStore *sso.Store, cfg config.Confi
return
}
writeJSON(w, map[string]any{"id": teamID, "ownerUserId": in.OwnerUserID})
})))
mux.Handle("GET /api/v1/admin/teams", auth.RequireAdmin(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
}))))
mux.Handle("GET /api/v1/admin/teams", singleModeOnly(db, auth.RequireAdmin(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Administrator pages hold no team keys, so they get no name ciphertext either.
rows, err := db.Query(`SELECT c.id,c.owner_user_id,u.username,(SELECT COUNT(*) FROM memberships m WHERE m.container_id=c.id AND m.revoked_at=''),c.shared_generation>0,c.meta_version>0
FROM containers c JOIN users u ON u.id=c.owner_user_id WHERE c.kind='team' AND c.deleted_at='' ORDER BY c.id`)
Expand All @@ -102,8 +103,8 @@ func AdminRoutes(mux RouteMux, db *sql.DB, ssoStore *sso.Store, cfg config.Confi
return
}
writeJSON(w, out)
})))
mux.Handle("POST /api/v1/admin/teams/{id}/members", auth.RequireStepUp(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
}))))
mux.Handle("POST /api/v1/admin/teams/{id}/members", singleModeOnly(db, auth.RequireStepUp(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if auth.CheckCSRF(r) != nil {
WriteError(w, r, 403, "csrf_failed", "csrf validation failed")
return
Expand Down Expand Up @@ -145,8 +146,8 @@ func AdminRoutes(mux RouteMux, db *sql.DB, ssoStore *sso.Store, cfg config.Confi
return
}
w.WriteHeader(http.StatusNoContent)
})))
mux.Handle("DELETE /api/v1/admin/teams/{id}/members/{userID}", auth.RequireAdmin(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
}))))
mux.Handle("DELETE /api/v1/admin/teams/{id}/members/{userID}", singleModeOnly(db, auth.RequireAdmin(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if auth.CheckCSRF(r) != nil {
WriteError(w, r, 403, "csrf_failed", "csrf validation failed")
return
Expand All @@ -167,8 +168,8 @@ func AdminRoutes(mux RouteMux, db *sql.DB, ssoStore *sso.Store, cfg config.Confi
return
}
w.WriteHeader(http.StatusNoContent)
})))
mux.Handle("POST /api/v1/admin/users", auth.RequireStepUp(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
}))))
mux.Handle("POST /api/v1/admin/users", singleModeOnly(db, auth.RequireStepUp(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if auth.CheckCSRF(r) != nil {
WriteError(w, r, 403, "csrf_failed", "csrf validation failed")
return
Expand Down Expand Up @@ -196,7 +197,7 @@ func AdminRoutes(mux RouteMux, db *sql.DB, ssoStore *sso.Store, cfg config.Confi
s, _ := auth.SessionFromContext(r)
recordAuditOutcome(db, s.UserID, "admin.user.create", "", id, "success", "kind="+in.AccountKind, r.Header.Get("X-Request-Id"))
writeJSON(w, map[string]string{"id": id})
})))
}))))
mux.Handle("GET /api/v1/admin/settings", auth.RequireAdmin(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var theme string
if db.QueryRow(`SELECT value FROM server_settings WHERE key='default_theme'`).Scan(&theme) != nil {
Expand Down Expand Up @@ -224,6 +225,9 @@ func AdminRoutes(mux RouteMux, db *sql.DB, ssoStore *sso.Store, cfg config.Confi
w.WriteHeader(http.StatusNoContent)
})))
mux.Handle("GET /api/v1/admin/users", auth.RequireAdmin(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if serveStaffUsers(w, r, db) {
return
}
rows, err := db.Query(`SELECT id,username,role,account_kind,status,quota_bytes,created_at FROM users ORDER BY username`)
if err != nil {
WriteError(w, r, 500, "internal", "internal server error")
Expand All @@ -244,7 +248,7 @@ func AdminRoutes(mux RouteMux, db *sql.DB, ssoStore *sso.Store, cfg config.Confi
})))
// errActorRevoked: the acting administrator lost access after the request was authorized.
errActorRevoked := errors.New("acting administrator revoked")
mux.Handle("PATCH /api/v1/admin/users/{id}", auth.RequireStepUp(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mux.Handle("PATCH /api/v1/admin/users/{id}", singleModeOnly(db, auth.RequireStepUp(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if auth.CheckCSRF(r) != nil {
WriteError(w, r, 403, "csrf_failed", "csrf validation failed")
return
Expand Down Expand Up @@ -319,8 +323,8 @@ func AdminRoutes(mux RouteMux, db *sql.DB, ssoStore *sso.Store, cfg config.Confi
}
recordAudit(db, s.UserID, "admin.user.update", "", id, r.Header.Get("X-Request-Id"))
w.WriteHeader(http.StatusNoContent)
})))
mux.Handle("POST /api/v1/admin/users/{id}/password", auth.RequireStepUp(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
}))))
mux.Handle("POST /api/v1/admin/users/{id}/password", singleModeOnly(db, auth.RequireStepUp(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if auth.CheckCSRF(r) != nil {
WriteError(w, r, 403, "csrf_failed", "csrf validation failed")
return
Expand Down Expand Up @@ -362,8 +366,11 @@ func AdminRoutes(mux RouteMux, db *sql.DB, ssoStore *sso.Store, cfg config.Confi
}
recordAudit(db, s.UserID, "admin.user.password_reset", "", r.PathValue("id"), RequestID(r))
w.WriteHeader(http.StatusNoContent)
})))
}))))
mux.Handle("GET /api/v1/admin/audit", auth.RequireAdmin(db, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if serveStaffAudit(w, r, db) {
return
}
limit := 100
if value, err := strconv.Atoi(r.URL.Query().Get("limit")); err == nil && value > 0 && value < 501 {
limit = value
Expand Down
22 changes: 20 additions & 2 deletions internal/httpapi/auth_routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,11 @@ func AuthRoutes(mux RouteMux, db *sql.DB, cfg config.Config) {
if afterPasswordVerified != nil {
afterPasswordVerified()
}
tenancy, err := storage.TenancyOfContext(r.Context(), db)
if err != nil {
WriteError(w, r, 500, "internal", "session metadata unavailable")
return
}
// Bound to the verified hash: a password changed since then mints nothing and returns no identity.
var identity map[string]string
s, err := auth.MintPasswordSession(db, w, id, stored, cfg.Server.DevInsecureCookies, time.Now().UTC(), func(tx *sql.Tx) (err error) {
Expand All @@ -278,7 +283,11 @@ func AuthRoutes(mux RouteMux, db *sql.DB, cfg config.Config) {
return
}
recordAudit(db, id, "auth.login", "", "", RequestID(r))
out := map[string]any{"user": map[string]string{"id": id, "role": role, "accountKind": kind}, "passwordChangeRequired": known != 0, "expiresAt": s.ExpiresAt.UTC().Format(time.RFC3339), "hardExpiresAt": s.HardExpiresAt.UTC().Format(time.RFC3339)}
user := map[string]string{"id": id, "role": role, "accountKind": kind}
if tenancy.Multi() {
user["tenancy"] = "multi"
}
out := map[string]any{"user": user, "passwordChangeRequired": known != 0, "expiresAt": s.ExpiresAt.UTC().Format(time.RFC3339), "hardExpiresAt": s.HardExpiresAt.UTC().Format(time.RFC3339)}
if identity != nil {
out["identity"] = identity
}
Expand All @@ -297,9 +306,18 @@ func AuthRoutes(mux RouteMux, db *sql.DB, cfg config.Config) {
WriteError(w, r, 401, "unauthenticated", "session no longer active")
return
}
tenancy, err := storage.TenancyOfContext(r.Context(), db)
if err != nil {
WriteError(w, r, 500, "internal", "session metadata unavailable")
return
}
user := map[string]string{"id": s.UserID, "role": role, "username": username, "accountKind": s.AccountKind}
if tenancy.Multi() {
user["tenancy"] = "multi"
}
auth.RefreshCSRFCookie(w, r, cfg.Server.DevInsecureCookies)
// The About window's version badge: signed-in callers only.
writeJSON(w, map[string]any{"version": appversion.String(), "sso": s.SSOIssuer != "", "user": map[string]string{"id": s.UserID, "role": role, "username": username, "accountKind": s.AccountKind}, "passwordChangeRequired": s.PasswordChangeRequired, "expiresAt": s.ExpiresAt.UTC().Format(time.RFC3339), "hardExpiresAt": s.HardExpiresAt.UTC().Format(time.RFC3339)})
writeJSON(w, map[string]any{"version": appversion.String(), "sso": s.SSOIssuer != "", "user": user, "passwordChangeRequired": s.PasswordChangeRequired, "expiresAt": s.ExpiresAt.UTC().Format(time.RFC3339), "hardExpiresAt": s.HardExpiresAt.UTC().Format(time.RFC3339)})
}))
mux.Handle("GET /api/v1/auth/session", handleSession)
mux.Handle("GET /api/auth/session", handleSession)
Expand Down
Loading