Manage people and the tenancy tree, from the web and the CLI

Nothing in the tree could be renamed, moved or removed, and an approved
person stayed in the project they were first put in — from the web or
the CLI. Now:

- /admin/users is the tree, each project opening onto its people and
  keys, with approve, move, suspend, reinstate and remove for people,
  revoke for keys, and add, rename, move and remove at every level,
  plus a search over every account. Forms post and get the page back,
  so it works with no script; htmx 2.0.11 (0BSD, embedded, checked
  against npm's integrity hash) swaps only the changed part, keeping
  open projects open.
- llmgw org tree/add/rename/move/remove, users move/delete, and
  keys list --all.
- Projects, teams and organizations are named by id, path
  (Acme/platform/gateway) or unique name; users by id or email. With a
  single project --project can be left out, instead of defaulting to
  "default", which a tree built from the web does not have.

Moving a person moves the keys they made; operator keys stay with the
project. Only empty things are removed, and never a project that had a
key, since usage history refers to it.

Also: keys init no longer reparents an existing team or project;
reinstating an account with no project is refused (a rejected signup
used to come back active and fail at its first key); rejecting a
signup removes it; keys limits --budget takes whole units like the
quotas page.

Checked in headless Chrome: a move from an open project updates the
page in place, keeps the project open, and the search still filters.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ilker ManapandClaude Opus 5.5 committed 2026-09-28 16:26:39 +02:00
1 parent 5141e4b138
commit 3104f4b706
21 files changed
+2081 -217

No files matched your search

+29 -8
View File
@@ -60,6 +60,26 @@ func (f *fakeAdmin) CreateProject(_ context.Context, teamID, name string) (strin
return "proj-1", f.err
}
func (f *fakeAdmin) Tree(context.Context) ([]store.TreeOrg, error) {
var out []store.TreeOrg
for _, o := range f.orgs {
out = append(out, store.TreeOrg{ID: o.ID, Name: o.Name})
}
return out, nil
}
func (f *fakeAdmin) RenameOrg(context.Context, string, string) error { return f.err }
func (f *fakeAdmin) RenameTeam(context.Context, string, string) error { return f.err }
func (f *fakeAdmin) RenameProject(context.Context, string, string) error { return f.err }
func (f *fakeAdmin) MoveTeam(context.Context, string, string) error { return f.err }
func (f *fakeAdmin) MoveProject(context.Context, string, string) error { return f.err }
func (f *fakeAdmin) DeleteOrg(context.Context, string) error { return f.err }
func (f *fakeAdmin) DeleteTeam(context.Context, string) error { return f.err }
func (f *fakeAdmin) DeleteProject(context.Context, string) error { return f.err }
func (f *fakeAdmin) MoveUser(context.Context, string, string) (int, error) { return 0, f.err }
func (f *fakeAdmin) DeleteUser(context.Context, string, time.Time) error { return f.err }
func (f *fakeAdmin) AllKeys(context.Context) ([]store.KeyRow, error) { return nil, nil }
func (f *fakeAdmin) RevokeKey(context.Context, string, time.Time) error { return f.err }
func tenancyPage(t *testing.T, s *fakeAdmin, admin bool) *http.ServeMux {
t.Helper()
a := fakeAccounts{user: store.User{ID: "u1", Email: "a@example.com", IsAdmin: admin}}
@@ -156,16 +176,17 @@ func TestThePageSaysWhatToDoWhenTheTreeIsEmpty(t *testing.T) {
}
}
func TestQuotasAreStillNotSettableFromTheBrowser(t *testing.T) {
func TestThisPageSetsNoQuotas(t *testing.T) {
body := mirrorGet(t, tenancyPage(t, &fakeAdmin{}, true), "/admin/users").Body.String()
// Making somewhere to put people is structural; raising what they may spend
// is financial. A stolen admin session should be able to do the first and
// not the second, and the page says so.
if !strings.Contains(body, "llmgw keys limits") {
t.Error("the page should still send quota changes to the shell")
}
// Quotas have their own page; this one arranges people. What stays off
// the web entirely is what would hand a stolen session more access.
if strings.Contains(body, `name="budget"`) {
t.Error("a budget field has appeared on the accounts page")
t.Error("a budget field has appeared on the people page")
}
for _, shell := range []string{"llmgw users promote", "reset-password", "llmgw keys create"} {
if !strings.Contains(body, shell) {
t.Errorf("the page should send %q to the shell", shell)
}
}
}
+256 -59
View File
@@ -3,7 +3,9 @@ package web
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"time"
"gitea.mynodes.xyz/ilker/llmgw/internal/store"
@@ -26,36 +28,77 @@ type AccountAdmin interface {
CreateOrg(ctx context.Context, name string) (string, error)
CreateTeam(ctx context.Context, orgID, name string) (string, error)
CreateProject(ctx context.Context, teamID, name string) (string, error)
// And keeping it in shape afterwards, which used to have no interface at
// all: nothing could be renamed, moved or removed, and an approved person
// stayed in the project they were first put in.
Tree(ctx context.Context) ([]store.TreeOrg, error)
RenameOrg(ctx context.Context, id, name string) error
RenameTeam(ctx context.Context, id, name string) error
RenameProject(ctx context.Context, id, name string) error
MoveTeam(ctx context.Context, teamID, orgID string) error
MoveProject(ctx context.Context, projectID, teamID string) error
DeleteOrg(ctx context.Context, id string) error
DeleteTeam(ctx context.Context, id string) error
DeleteProject(ctx context.Context, id string) error
MoveUser(ctx context.Context, userID, projectID string) (int, error)
DeleteUser(ctx context.Context, userID string, at time.Time) error
AllKeys(ctx context.Context) ([]store.KeyRow, error)
RevokeKey(ctx context.Context, id string, at time.Time) error
}
// userRow is an account as the page shows it: with where it is, not an id.
type userRow struct {
store.User
ProjectPath string
}
// keyRow is a key as the page shows it.
type keyRow struct {
store.KeyRow
State string
}
type adminUsersData struct {
Pending []store.User
Active []store.User
Accounts []userRow
Tree []store.TreeOrg
// People and Keys are keyed by project id.
People map[string][]userRow
Keys map[string][]keyRow
Projects []store.ProjectPath
Orgs []store.Org
Teams []store.TeamPath
Message string
Error string
CSRF string
Version string
Now string
// Open is the project whose section is shown expanded: the one just acted
// on, so the result of a change is in view without the reader hunting for
// it. Scripted pages keep every open section open; this is for the rest.
Open string
AdminID string
Message string
Error string
CSRF string
Version string
Now string
// HasMirror and HasQuotas keep the nav from offering a page that was never
// mounted.
HasMirror bool
HasQuotas bool
}
// RegisterAdminUsers mounts account administration under /admin/users.
// RegisterAdminUsers mounts account and tenancy administration under
// /admin/users.
//
// What is here and what is not is the whole design. Approving and suspending
// are the work an operator does constantly and should not need a terminal for.
// Making someone an admin, resetting a password and issuing keys on another
// person's behalf are not here: each of them turns a stolen admin session into
// more than it was — more access, or somebody else's account — and each is rare
// enough that a shell is no hardship.
// What is here and what is not is the whole design. Approving, suspending,
// moving people and keeping the tree in shape are the work an operator does
// constantly and should not need a terminal for. Making someone an admin,
// resetting a password and issuing keys on another person's behalf are not
// here: each of them turns a stolen admin session into more than it was —
// more access, or somebody else's account — and each is rare enough that a
// shell is no hardship. Revoking a key is here, because it only ever takes
// access away.
func (p *AccountPages) RegisterAdminUsers(mux *http.ServeMux, s AccountAdmin) {
mux.HandleFunc("GET /admin/users", p.adminOnly(func(w http.ResponseWriter, r *http.Request, admin store.User) {
p.renderUsers(w, r, s, "", "")
p.renderUsers(w, r, s, admin, "", "", r.URL.Query().Get("open"))
}))
mux.HandleFunc("POST /admin/users/{id}/approve", p.adminAction(s,
@@ -67,7 +110,7 @@ func (p *AccountPages) RegisterAdminUsers(mux *http.ServeMux, s AccountAdmin) {
if err := s.ApproveUser(ctx, id, project, admin.Email, time.Now()); err != nil {
return "", err
}
return "approved into " + project, nil
return "approved into " + projectPath(ctx, s, project), nil
}))
mux.HandleFunc("POST /admin/users/{id}/suspend", p.adminAction(s,
@@ -88,17 +131,47 @@ func (p *AccountPages) RegisterAdminUsers(mux *http.ServeMux, s AccountAdmin) {
return "suspended, and signed out everywhere", nil
}))
// The tenancy tree. Creating a container is not granting access: nobody can
// use one until an account is approved into it, which is the step above and
// already lives here. What is still not here is limits — raising a budget
// is a financial act, and a stolen session must not be able to perform one.
mux.HandleFunc("POST /admin/tenancy/org", p.tenancyAction(s,
func(ctx context.Context, r *http.Request) (string, error) {
id, err := s.CreateOrg(ctx, r.FormValue("name"))
mux.HandleFunc("POST /admin/users/{id}/reinstate", p.adminAction(s,
func(ctx context.Context, _ store.User, id string, _ *http.Request) (string, error) {
if err := s.SetUserState(ctx, id, store.UserActive); err != nil {
return "", err
}
return "reinstated", nil
}))
mux.HandleFunc("POST /admin/users/{id}/move", p.adminAction(s,
func(ctx context.Context, _ store.User, id string, r *http.Request) (string, error) {
project := r.FormValue("project")
if project == "" {
return "", errors.New("choose the project they go to")
}
moved, err := s.MoveUser(ctx, id, project)
if err != nil {
return "", err
}
return "organization " + r.FormValue("name") + " created as " + id, nil
return fmt.Sprintf("moved to %s, with %s", projectPath(ctx, s, project), plural(moved, "key", "keys")), nil
}))
mux.HandleFunc("POST /admin/users/{id}/delete", p.adminAction(s,
func(ctx context.Context, admin store.User, id string, _ *http.Request) (string, error) {
if id == admin.ID {
return "", errors.New("you cannot remove your own account")
}
if err := s.DeleteUser(ctx, id, time.Now()); err != nil {
return "", err
}
return "removed; their keys are revoked", nil
}))
// The tenancy tree. Creating a container is not granting access: nobody can
// use one until an account is approved into it.
mux.HandleFunc("POST /admin/tenancy/org", p.tenancyAction(s,
func(ctx context.Context, r *http.Request) (string, error) {
_, err := s.CreateOrg(ctx, r.FormValue("name"))
if err != nil {
return "", err
}
return "organization " + r.FormValue("name") + " created", nil
}))
mux.HandleFunc("POST /admin/tenancy/team", p.tenancyAction(s,
@@ -107,11 +180,11 @@ func (p *AccountPages) RegisterAdminUsers(mux *http.ServeMux, s AccountAdmin) {
if org == "" {
return "", errors.New("choose the organization this team belongs to")
}
id, err := s.CreateTeam(ctx, org, r.FormValue("name"))
_, err := s.CreateTeam(ctx, org, r.FormValue("name"))
if err != nil {
return "", err
}
return "team " + r.FormValue("name") + " created as " + id, nil
return "team " + r.FormValue("name") + " created", nil
}))
mux.HandleFunc("POST /admin/tenancy/project", p.tenancyAction(s,
@@ -124,16 +197,104 @@ func (p *AccountPages) RegisterAdminUsers(mux *http.ServeMux, s AccountAdmin) {
if err != nil {
return "", err
}
return "project " + r.FormValue("name") + " created as " + id, nil
r.Form.Set("open", id)
return "project " + r.FormValue("name") + " created", nil
}))
mux.HandleFunc("POST /admin/users/{id}/reinstate", p.adminAction(s,
func(ctx context.Context, _ store.User, id string, _ *http.Request) (string, error) {
if err := s.SetUserState(ctx, id, store.UserActive); err != nil {
mux.HandleFunc("POST /admin/tenancy/{kind}/{id}/rename", p.tenancyAction(s,
func(ctx context.Context, r *http.Request) (string, error) {
id, name := r.PathValue("id"), strings.TrimSpace(r.FormValue("name"))
var err error
switch r.PathValue("kind") {
case "org":
err = s.RenameOrg(ctx, id, name)
case "team":
err = s.RenameTeam(ctx, id, name)
case "project":
err = s.RenameProject(ctx, id, name)
default:
return "", errors.New("nothing of that kind")
}
if err != nil {
return "", err
}
return "reinstated", nil
return "renamed to " + name, nil
}))
mux.HandleFunc("POST /admin/tenancy/{kind}/{id}/move", p.tenancyAction(s,
func(ctx context.Context, r *http.Request) (string, error) {
id, to := r.PathValue("id"), r.FormValue("to")
if to == "" {
return "", errors.New("choose where it goes")
}
switch r.PathValue("kind") {
case "team":
if err := s.MoveTeam(ctx, id, to); err != nil {
return "", err
}
return "team moved", nil
case "project":
if err := s.MoveProject(ctx, id, to); err != nil {
return "", err
}
return "project moved to " + projectPath(ctx, s, id), nil
}
return "", errors.New("only a team or a project moves")
}))
mux.HandleFunc("POST /admin/tenancy/{kind}/{id}/delete", p.tenancyAction(s,
func(ctx context.Context, r *http.Request) (string, error) {
id := r.PathValue("id")
var err error
switch r.PathValue("kind") {
case "org":
err = s.DeleteOrg(ctx, id)
case "team":
err = s.DeleteTeam(ctx, id)
case "project":
err = s.DeleteProject(ctx, id)
default:
return "", errors.New("nothing of that kind")
}
if err != nil {
return "", err
}
r.Form.Del("open")
return "removed", nil
}))
mux.HandleFunc("POST /admin/keys/{id}/revoke", p.tenancyAction(s,
func(ctx context.Context, r *http.Request) (string, error) {
if err := s.RevokeKey(ctx, r.PathValue("id"), time.Now()); err != nil {
return "", err
}
return "key revoked; a running server stops accepting it when its cache expires", nil
}))
}
func projectPath(ctx context.Context, s AccountAdmin, id string) string {
all, err := s.AllProjects(ctx)
if err == nil {
for _, p := range all {
if p.ID == id {
return p.Path
}
}
}
return id
}
// plainError says what a store error means to the person who caused it.
func plainError(err error) error {
switch {
case errors.Is(err, store.ErrDuplicateName):
return errors.New("there is already one of those here")
case errors.Is(err, store.ErrNotEmpty):
return fmt.Errorf("not removed: %s", strings.TrimPrefix(err.Error(), store.ErrNotEmpty.Error()+": "))
case errors.Is(err, store.ErrNotFound):
return errors.New("that is no longer there; the page was out of date")
}
return err
}
// tenancyAction wraps a change to the tree: admin session, CSRF, audit, render.
@@ -153,15 +314,15 @@ func (p *AccountPages) tenancyAction(s AccountAdmin,
}
msg, err := do(r.Context(), r)
if err != nil {
if errors.Is(err, store.ErrDuplicateName) {
err = errors.New("there is already one of those here")
}
p.log.Warn("a tenancy change was refused", "admin", admin.Email, "err", err)
p.renderUsers(w, r, s, "", err.Error())
err = plainError(err)
p.log.Warn("a tenancy change was refused", "admin", admin.Email,
"path", r.URL.Path, "err", err)
p.renderUsers(w, r, s, admin, "", err.Error(), r.FormValue("open"))
return
}
p.log.Info("the tenancy tree was changed", "admin", admin.Email, "what", msg)
p.renderUsers(w, r, s, msg, "")
p.log.Info("the tenancy tree was changed", "admin", admin.Email,
"path", r.URL.Path, "what", msg)
p.renderUsers(w, r, s, admin, msg, "", r.FormValue("open"))
})
}
@@ -185,7 +346,8 @@ func (p *AccountPages) adminOnly(
}
}
// adminAction wraps a state change: admin session, CSRF, audit line, redirect.
// adminAction wraps a change to one account: admin session, CSRF, audit line,
// render.
func (p *AccountPages) adminAction(s AccountAdmin,
do func(ctx context.Context, admin store.User, id string, r *http.Request) (string, error),
) http.HandlerFunc {
@@ -204,51 +366,86 @@ func (p *AccountPages) adminAction(s AccountAdmin,
msg, err := do(r.Context(), admin, id, r)
if err != nil {
err = plainError(err)
// Logged at warn whether it worked or not: a refused administrative
// action is as worth knowing about as one that went through.
p.log.Warn("an administrative action was refused",
"admin", admin.Email, "subject", subject, "err", err)
p.renderUsers(w, r, s, "", err.Error())
p.renderUsers(w, r, s, admin, "", subject+": "+err.Error(), r.FormValue("open"))
return
}
p.log.Info("an account was changed",
"admin", admin.Email, "subject", subject, "what", msg)
p.renderUsers(w, r, s, subject+" "+msg, "")
p.renderUsers(w, r, s, admin, subject+" "+msg, "", r.FormValue("open"))
})
}
func (p *AccountPages) renderUsers(w http.ResponseWriter, r *http.Request,
s AccountAdmin, msg, errMsg string,
s AccountAdmin, admin store.User, msg, errMsg, open string,
) {
ctx := r.Context()
d := adminUsersData{
Message: msg, Error: errMsg,
Message: msg, Error: errMsg, Open: open, AdminID: admin.ID,
CSRF: csrfFor(r),
Version: p.version,
HasMirror: p.hasMirror,
HasQuotas: p.hasQuotas,
Now: time.Now().UTC().Format(time.RFC3339),
People: map[string][]userRow{},
Keys: map[string][]keyRow{},
}
all, err := s.Users(r.Context(), "")
if err != nil {
p.log.Error("could not list accounts", "err", err)
d.Error = "could not read the accounts"
}
for _, u := range all {
if u.State == store.UserPending {
d.Pending = append(d.Pending, u)
} else {
d.Active = append(d.Active, u)
var err error
logErr := func(what string, err error) {
if err != nil {
p.log.Error("could not read "+what, "err", err)
if d.Error == "" {
d.Error = "could not read " + what
}
}
}
if d.Projects, err = s.AllProjects(r.Context()); err != nil {
p.log.Error("could not list projects", "err", err)
d.Projects, err = s.AllProjects(ctx)
logErr("the projects", err)
paths := make(map[string]string, len(d.Projects))
for _, pp := range d.Projects {
paths[pp.ID] = pp.Path
}
if d.Orgs, err = s.AllOrgs(r.Context()); err != nil {
p.log.Error("could not list organizations", "err", err)
all, err := s.Users(ctx, "")
logErr("the accounts", err)
for _, u := range all {
if u.State == store.UserPending && u.ProjectID == "" {
d.Pending = append(d.Pending, u)
continue
}
row := userRow{User: u, ProjectPath: paths[u.ProjectID]}
d.Accounts = append(d.Accounts, row)
d.People[u.ProjectID] = append(d.People[u.ProjectID], row)
}
if d.Teams, err = s.AllTeams(r.Context()); err != nil {
p.log.Error("could not list teams", "err", err)
keys, err := s.AllKeys(ctx)
logErr("the keys", err)
now := time.Now()
for _, k := range keys {
d.Keys[k.ProjectID] = append(d.Keys[k.ProjectID], keyRow{KeyRow: k, State: keyState(k.Key, now)})
}
d.Tree, err = s.Tree(ctx)
logErr("the tree", err)
d.Orgs, err = s.AllOrgs(ctx)
logErr("the organizations", err)
d.Teams, err = s.AllTeams(ctx)
logErr("the teams", err)
render(w, "admin_users", d)
}
func keyState(k store.Key, now time.Time) string {
switch {
case !k.RevokedAt.IsZero():
return "revoked"
case !k.ExpiresAt.IsZero() && !now.Before(k.ExpiresAt):
return "expired"
default:
return "active"
}
}
+40
View File
@@ -317,3 +317,43 @@ tr.editing form { margin: .4rem 0; }
difference has to survive a glance. */
.chip.on { background: var(--accent); border-color: var(--accent); color: var(--bg);
font-weight: 600; }
/* People: the tenancy tree with its people and keys. Indented by level and
ruled on the left, so which team a project is in reads at a glance without
a table per level. */
.org { background: var(--card); border: 1px solid var(--line); border-radius: 8px;
padding: .9rem 1rem; margin: 0 0 1rem; }
.team { margin: .8rem 0 0 .4rem; padding-left: .9rem; border-left: 2px solid var(--line); }
.node-head { display: flex; align-items: center; gap: .4rem .9rem; flex-wrap: wrap; }
.node-name { font-weight: 600; }
.org > .node-head .node-name { font-size: 1.05rem; }
.node-meta { color: var(--muted); font-size: .82rem; font-weight: 400; }
details.edit { display: inline-block; font-size: .85rem; }
details.edit > summary { cursor: pointer; color: var(--accent); list-style: none;
text-decoration: underline; }
details.edit > summary::-webkit-details-marker { display: none; }
details.edit[open] > summary { color: var(--muted); }
details.edit form { display: flex; gap: .4rem; align-items: center; margin: .35rem 0; }
details.edit input[type=text] { width: 14rem; }
details.project { margin: .45rem 0; border: 1px solid var(--line); border-radius: 6px;
background: var(--bg); }
details.project > summary { cursor: pointer; padding: .45rem .7rem; display: flex;
gap: .8rem; align-items: baseline; }
details.project[open] > summary { border-bottom: 1px solid var(--line); }
.project-body { padding: .6rem .7rem .8rem; display: grid; gap: .7rem; }
table.compact { font-size: .83rem; }
table.compact th, table.compact td { padding: .35rem .55rem; }
form.add { display: flex; gap: .4rem; margin: .5rem 0 0; }
form.add input[type=text], details.edit input[type=text] { margin: 0; padding: .35rem .55rem; }
form.add input[type=text] { max-width: 18rem; }
form.add button, button.small { padding: .3rem .7rem; font-size: .82rem; }
form.org-add { margin: 0 0 1rem; }
td.actions { white-space: nowrap; }
td.actions form + form { margin-left: .6rem; }
.tag { font-size: .7rem; font-weight: 600; text-transform: uppercase; letter-spacing: .04em;
color: var(--accent); border: 1px solid var(--accent); border-radius: 4px;
padding: 0 .3rem; margin-left: .3rem; }
input.search { width: 100%; max-width: 26rem; margin: 0 0 .7rem; padding: .45rem .6rem;
font: inherit; border: 1px solid var(--line); border-radius: 6px;
background: var(--card); color: var(--fg); }
tr[hidden] { display: none; }
+1
View File
@@ -0,0 +1 @@
var htmx=function(){"use strict";const Y={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=pn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true,historyRestoreAsHxRequest:true,reportValidityOfForms:false},parseInterval:null,location:location,_:null,version:"2.0.11"};Y.onLoad=V;Y.process=Bt;Y.on=ye;Y.off=xe;Y.trigger=ae;Y.ajax=In;Y.find=a;Y.findAll=x;Y.closest=g;Y.remove=z;Y.addClass=w;Y.removeClass=S;Y.toggleClass=G;Y.takeClass=W;Y.swap=C;Y.defineExtension=zn;Y.removeExtension=Jn;Y.logAll=$;Y.logNone=_;Y.parseInterval=d;Y._=e;const n={addTriggerHandler:Et,bodyContains:ie,canAccessLocalStorage:U,findThisElement:we,filterValues:xn,swap:C,hasAttribute:s,getAttributeValue:f,getClosestAttributeValue:te,getClosestMatch:A,getExpressionVars:qn,getHeaders:yn,getInputValues:pn,getInternalData:re,getSwapSpecification:vn,getTriggerSpecs:lt,getTarget:Se,makeFragment:D,mergeObjects:se,makeSettleInfo:En,oobSwap:Te,querySelectorExt:ce,settleImmediately:Qt,shouldCancel:dt,triggerEvent:ae,triggerErrorEvent:ue,withExtensions:Vt};const he=["get","post","put","delete","patch"];const R=he.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function Q(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function f(e,t){return Q(e,t)||Q(e,"data-"+t)}function u(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ee(){return document}function q(e,t){return e.getRootNode?e.getRootNode({composed:t}):ee()}function A(e,t){while(e&&!t(e)){e=u(e)}return e||null}function o(e,t,n){const r=f(t,n);const o=f(t,"hx-disinherit");var i=f(t,"hx-inherit");if(e!==t){if(Y.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function te(t,n){let r=null;A(t,function(e){return!!(r=o(t,le(e),n))});if(r!=="unset"){return r}}function h(e,t){return e instanceof Element&&e.matches(t)}function N(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function I(e){if("parseHTMLUnsafe"in Document){return Document.parseHTMLUnsafe(e)}const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function r(e){const t=ee().createElement("script");oe(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Y.config.inlineScriptNonce){t.nonce=Y.config.inlineScriptNonce}return t}function i(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function k(e){if(!Y.config.allowScriptTags){e.querySelectorAll("script").forEach(e=>e.remove());return}Array.from(e.querySelectorAll("script")).forEach(e=>{if(i(e)){const t=r(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){T(e)}finally{e.remove()}}})}function D(e){e=e.replace(/<hx-([a-z]+)((?:\s[^>]*)?)>/gi,'<template hx type="$1"$2>').replace(/<\/hx-[a-z]+>/gi,"</template>");const t=e.replace(/<head(\s[^>]*)?>[\s\S]*?<\/head>/i,"");const n=N(t);let r;if(n==="html"){r=new DocumentFragment;const i=I(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=I(t);L(r,i.body);r.title=i.title}else{const i=I('<body><template class="internal-htmx-wrapper">'+t+"</template></body>");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){oLine truncated
+262 -92
View File
@@ -1,11 +1,16 @@
{{define "admin_users"}}<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Accounts · llmgw</title><link rel="stylesheet" href="/_static/base.css">
<title>People · llmgw</title><link rel="stylesheet" href="/_static/base.css">
{{/* Forms here post and get the whole page back, which works with no script at
all. htmx, when it loads, swaps only #people from that page instead of
reloading it, so an open project stays open and the page does not jump. */}}
<meta name="htmx-config" content='{"scrollIntoViewOnBoost":false,"defaultFocusScroll":false}'>
<script src="/_static/htmx-2.0.11.min.js" defer></script>
</head><body><div class="wrap">
<header>
<h1>Accounts</h1>
<p class="sub">{{len .Pending}} waiting for approval · {{len .Active}} active</p>
<h1>People</h1>
<p class="sub">{{len .Pending}} waiting for approval · {{len .Accounts}} accounts · {{len .Projects}} projects</p>
<nav><a href="/admin">cluster</a>
{{if .HasMirror}} <a href="/admin/mirror">mirror</a>
{{end}}{{if .HasQuotas}} <a href="/admin/quotas">quotas</a>
@@ -13,111 +18,276 @@
{{end}} <a href="/profile">your keys</a></nav>
</header>
{{if .Error}}<p class="error">{{.Error}}</p>{{end}}
{{if .Message}}<p class="ok">{{.Message}}</p>{{end}}
<div id="people" hx-boost="true" hx-target="#people" hx-select="#people"
hx-swap="outerHTML" hx-push-url="false">
{{if .Error}}<p class="error" role="alert">{{.Error}}</p>{{end}}
{{if .Message}}<p class="ok" role="status">{{.Message}}</p>{{end}}
<h2>Waiting for approval</h2>
{{if .Pending}}
<table><tr><th>Email</th><th>Name</th><th>Signed up</th><th>Project</th><th></th></tr>
<h2>Waiting for approval</h2>
<table><tr><th>Email</th><th>Name</th><th>Signed up</th><th>Put them in</th><th></th></tr>
{{range .Pending}}<tr>
<td>{{.Email}}</td><td>{{.Name}}</td><td>{{ago .CreatedAt}}</td>
<td colspan="2">
<td>
{{if $.Projects}}
<form method="post" action="/admin/users/{{.ID}}/approve" class="inline">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<select name="project">
<select name="project" aria-label="Project for {{.Email}}">
{{range $.Projects}}<option value="{{.ID}}">{{.Path}}</option>{{end}}
</select>
<button type="submit">Approve</button>
</form>
<form method="post" action="/admin/users/{{.ID}}/suspend" class="inline">
{{else}}<span class="note">Create a project first, below.</span>{{end}}
</td>
<td>
<form method="post" action="/admin/users/{{.ID}}/delete" class="inline"
hx-confirm="Reject and remove {{.Email}}?">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<button type="submit" class="link danger">Reject</button>
</form>
</td>
</tr>{{end}}</table>
{{else}}<p class="empty">Nobody is waiting.</p>{{end}}
<h2>Accounts</h2>
{{if .Active}}
<table><tr><th>Email</th><th>State</th><th>Admin</th><th>Project</th><th>Last login</th><th></th></tr>
{{range .Active}}<tr>
<td>{{.Email}}</td>
<td class="state state-{{.State}}">{{.State}}</td>
<td>{{if .IsAdmin}}yes{{else}}—{{end}}</td>
<td>{{or .ProjectID "—"}}</td>
<td>{{ago .LastLoginAt}}</td>
<td>
{{if eq (printf "%s" .State) "active"}}
<form method="post" action="/admin/users/{{.ID}}/suspend" class="inline">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<button type="submit" class="link danger">Suspend</button>
</form>
{{else}}
<form method="post" action="/admin/users/{{.ID}}/reinstate" class="inline">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<button type="submit" class="link">Reinstate</button>
</form>
{{end}}
</td>
</tr>{{end}}</table>
{{else}}<p class="empty">No accounts yet.</p>{{end}}
<h2>Organizations, teams and projects</h2>
<p class="note">Where an account lives. A person is approved into a project, a
project belongs to a team, and a team to an organization — and a quota can be
written on any of the three, so the shape here is the shape the bill takes.</p>
<div class="field-row">
<form method="post" action="/admin/tenancy/org">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<label>New organization
<input type="text" name="name" required placeholder="Scania"></label>
<button type="submit">Create</button>
</form>
<form method="post" action="/admin/tenancy/team">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<label>New team
<input type="text" name="name" required placeholder="platform"></label>
<label>in
<select name="org" required>
{{range .Orgs}}<option value="{{.ID}}">{{.Name}}</option>{{end}}
</select></label>
<button type="submit"{{if not .Orgs}} disabled{{end}}>Create</button>
</form>
<form method="post" action="/admin/tenancy/project">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<label>New project
<input type="text" name="name" required placeholder="gateway"></label>
<label>in
<select name="team" required>
{{range .Teams}}<option value="{{.ID}}">{{.OrgName}} / {{.Name}}</option>{{end}}
</select></label>
<button type="submit"{{if not .Teams}} disabled{{end}}>Create</button>
</form>
</div>
{{if not .Orgs}}
<p class="empty">No organizations yet. Create one, then a team in it, then a
project in the team — an account can only be approved into a project.</p>
{{else}}
{{/* One path column, not three: the store returns the chain already joined,
which is the string the approval chooser shows, and three headers over one
value line up with nothing. */}}
<table><tr><th>Organization / team / project</th><th>ID</th></tr>
{{range .Projects}}<tr><td>{{.Path}}</td><td><code>{{.ID}}</code></td></tr>{{end}}
{{if not .Projects}}<tr><td colspan="2" class="empty">No projects yet, so nobody can be approved.</td></tr>{{end}}
</table>
{{end}}
<p class="note">Four things are deliberately not here. Making someone an admin,
resetting a password, issuing keys on another
person's behalf and setting any quota all need a shell on the control plane — <code>llmgw users promote</code>,
<code>reset-password</code>, <code>llmgw keys</code>, <code>llmgw keys limits</code>.
A stolen admin session can approve, suspend and make somewhere to put people; it
cannot hand itself more access, take over an account, or raise what anybody is
allowed to spend.</p>
<h2>Organizations, teams and projects</h2>
<p class="note">A person is in a project, a project in a team, a team in an
organization{{if .HasQuotas}}, and <a href="/admin/quotas">quotas</a> can be set
on any of them{{end}}. Open a project to see its people and keys.</p>
{{if not .Tree}}
<p class="empty">No organizations yet. Create one, then a team in it, then a
project in the team — an account can only be approved into a project.</p>
{{end}}
{{range $org := .Tree}}
<section class="org">
<div class="node-head">
<strong class="node-name">{{$org.Name}}</strong>
<span class="node-meta">{{len $org.Teams}} team{{if ne (len $org.Teams) 1}}s{{end}}</span>
<details class="edit"><summary>rename</summary>
<form method="post" action="/admin/tenancy/org/{{$org.ID}}/rename">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<input type="text" name="name" value="{{$org.Name}}" required aria-label="New name">
<button type="submit">Save</button>
</form>
</details>
{{if not $org.Teams}}
<form method="post" action="/admin/tenancy/org/{{$org.ID}}/delete" class="inline"
hx-confirm="Remove the organization {{$org.Name}}?">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<button type="submit" class="link danger">remove</button>
</form>
{{end}}
</div>
{{range $team := $org.Teams}}
<div class="team">
<div class="node-head">
<span class="node-name">{{$team.Name}}</span>
<span class="node-meta">{{len $team.Projects}} project{{if ne (len $team.Projects) 1}}s{{end}}</span>
<details class="edit"><summary>rename</summary>
<form method="post" action="/admin/tenancy/team/{{$team.ID}}/rename">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<input type="text" name="name" value="{{$team.Name}}" required aria-label="New name">
<button type="submit">Save</button>
</form>
</details>
{{if gt (len $.Orgs) 1}}
<details class="edit"><summary>move</summary>
<form method="post" action="/admin/tenancy/team/{{$team.ID}}/move">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<select name="to" aria-label="Organization to move {{$team.Name}} to">
{{range $.Orgs}}{{if ne .ID $org.ID}}<option value="{{.ID}}">{{.Name}}</option>{{end}}{{end}}
</select>
<button type="submit">Move</button>
</form>
</details>
{{end}}
{{if not $team.Projects}}
<form method="post" action="/admin/tenancy/team/{{$team.ID}}/delete" class="inline"
hx-confirm="Remove the team {{$team.Name}}?">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<button type="submit" class="link danger">remove</button>
</form>
{{end}}
</div>
{{range $p := $team.Projects}}
<details class="project" id="p-{{$p.ID}}"{{if eq $.Open $p.ID}} open{{end}}>
<summary>
<span class="node-name">{{$p.Name}}</span>
<span class="node-meta">{{$p.Users}} {{if eq $p.Users 1}}person{{else}}people{{end}}
· {{$p.ActiveKeys}} key{{if ne $p.ActiveKeys 1}}s{{end}}{{if gt $p.Keys $p.ActiveKeys}} ({{sub $p.Keys $p.ActiveKeys}} revoked){{end}}</span>
</summary>
<div class="project-body">
<div class="node-head">
<details class="edit"><summary>rename</summary>
<form method="post" action="/admin/tenancy/project/{{$p.ID}}/rename">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<input type="hidden" name="open" value="{{$p.ID}}">
<input type="text" name="name" value="{{$p.Name}}" required aria-label="New name">
<button type="submit">Save</button>
</form>
</details>
{{if gt (len $.Teams) 1}}
<details class="edit"><summary>move to another team</summary>
<form method="post" action="/admin/tenancy/project/{{$p.ID}}/move">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<input type="hidden" name="open" value="{{$p.ID}}">
<select name="to" aria-label="Team to move {{$p.Name}} to">
{{range $.Teams}}{{if ne .ID $team.ID}}<option value="{{.ID}}">{{.OrgName}} / {{.Name}}</option>{{end}}{{end}}
</select>
<button type="submit">Move</button>
</form>
</details>
{{end}}
{{if and (eq $p.Users 0) (eq $p.Keys 0)}}
<form method="post" action="/admin/tenancy/project/{{$p.ID}}/delete" class="inline"
hx-confirm="Remove the project {{$p.Name}}?">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<button type="submit" class="link danger">remove</button>
</form>
{{else}}<span class="note">Removable once it has no people and never had a key.</span>{{end}}
</div>
{{with index $.People $p.ID}}
<table class="compact"><tr><th>Person</th><th>State</th><th>Last sign-in</th><th>Move to</th><th></th></tr>
{{range .}}{{template "user-row-actions" (dict "U" . "D" $ "Open" $p.ID)}}{{end}}
</table>
{{else}}<p class="empty">Nobody is in this project.</p>{{end}}
{{with index $.Keys $p.ID}}
<table class="compact"><tr><th>Key</th><th>Owner</th><th>State</th><th>Last used</th><th></th></tr>
{{range .}}<tr>
<td>{{.Name}} <code>{{.Prefix}}</code></td>
<td>{{or .OwnerEmail "issued by an operator"}}</td>
<td class="state state-{{.State}}">{{.State}}</td>
<td>{{ago .LastUsedAt}}</td>
<td>{{if eq .State "active"}}
<form method="post" action="/admin/keys/{{.ID}}/revoke" class="inline"
hx-confirm="Revoke the key {{.Name}}? Whatever uses it stops working.">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<input type="hidden" name="open" value="{{$p.ID}}">
<button type="submit" class="link danger">revoke</button>
</form>{{end}}</td>
</tr>{{end}}
</table>
{{end}}
</div>
</details>
{{end}}
<form method="post" action="/admin/tenancy/project" class="add">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<input type="hidden" name="team" value="{{$team.ID}}">
<input type="text" name="name" required placeholder="new project in {{$team.Name}}" aria-label="New project in {{$team.Name}}">
<button type="submit">Add</button>
</form>
</div>
{{end}}
<form method="post" action="/admin/tenancy/team" class="add team-add">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<input type="hidden" name="org" value="{{$org.ID}}">
<input type="text" name="name" required placeholder="new team in {{$org.Name}}" aria-label="New team in {{$org.Name}}">
<button type="submit">Add</button>
</form>
</section>
{{end}}
<form method="post" action="/admin/tenancy/org" class="add org-add">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<input type="text" name="name" required placeholder="new organization" aria-label="New organization">
<button type="submit">Add organization</button>
</form>
<h2 id="accounts">All accounts</h2>
{{if .Accounts}}
<table id="account-list"><tr><th>Person</th><th>State</th><th>Project</th><th>Last sign-in</th><th>Move to</th><th></th></tr>
{{range .Accounts}}{{template "user-row-actions" (dict "U" . "D" $ "Open" "" "Path" true)}}{{end}}
</table>
{{else}}<p class="empty">No accounts yet.</p>{{end}}
<p class="note">Not here on purpose: making someone an admin, resetting a password
and issuing a key for someone else. Each turns a stolen admin session into more
access than it had, so they need a shell on the control plane —
<code>llmgw users promote</code>, <code>llmgw users reset-password</code>,
<code>llmgw keys create</code>.</p>
</div>
<footer><span>llmgw {{.Version}}</span><span>{{.Now}}</span></footer>
</div></body></html>{{end}}
</div>
<script>
// Search the account list. Outside #people so what was typed survives a swap,
// and applied again after every swap.
(function () {
var box = document.createElement('input');
box.type = 'search'; box.placeholder = 'Find a person by email, name or project';
box.className = 'search'; box.setAttribute('aria-label', 'Find a person');
function apply() {
var q = box.value.trim().toLowerCase();
document.querySelectorAll('#account-list tr[data-q]').forEach(function (tr) {
tr.hidden = q !== '' && tr.dataset.q.indexOf(q) < 0;
});
}
box.addEventListener('input', apply);
function place() {
var h = document.getElementById('accounts');
if (h && box.parentNode !== h.parentNode) h.after(box);
apply();
}
place();
// Projects the reader had open stay open across a change.
var open = [];
document.addEventListener('htmx:beforeSwap', function () {
open = Array.prototype.map.call(document.querySelectorAll('details.project[open]'), function (d) { return d.id; });
});
document.addEventListener('htmx:afterSettle', function () {
open.forEach(function (id) { var d = document.getElementById(id); if (d) d.open = true; });
place();
});
})();
</script>
</body></html>{{end}}
{{define "user-row-actions"}}{{$u := .U}}{{$d := .D}}
<tr data-q="{{lower $u.Email}} {{lower $u.Name}} {{lower $u.ProjectPath}}">
<td>{{$u.Email}}{{if $u.IsAdmin}} <span class="tag">admin</span>{{end}}</td>
<td class="state state-{{$u.State}}">{{$u.State}}</td>
{{if .Path}}<td>{{or $u.ProjectPath "—"}}</td>{{end}}
<td>{{ago $u.LastLoginAt}}</td>
<td>
<form method="post" action="/admin/users/{{$u.ID}}/move" class="inline">
<input type="hidden" name="csrf" value="{{$d.CSRF}}">
<input type="hidden" name="open" value="{{.Open}}">
<select name="project" aria-label="Project for {{$u.Email}}">
{{range $d.Projects}}<option value="{{.ID}}"{{if eq .ID $u.ProjectID}} selected{{end}}>{{.Path}}</option>{{end}}
</select>
<button type="submit" class="small">Move</button>
</form>
</td>
<td class="actions">
{{if ne $u.ID $d.AdminID}}
{{if eq (printf "%s" $u.State) "active"}}
<form method="post" action="/admin/users/{{$u.ID}}/suspend" class="inline">
<input type="hidden" name="csrf" value="{{$d.CSRF}}">
<input type="hidden" name="open" value="{{.Open}}">
<button type="submit" class="link danger">suspend</button>
</form>
{{else}}
<form method="post" action="/admin/users/{{$u.ID}}/reinstate" class="inline">
<input type="hidden" name="csrf" value="{{$d.CSRF}}">
<input type="hidden" name="open" value="{{.Open}}">
<button type="submit" class="link">reinstate</button>
</form>
{{end}}
<form method="post" action="/admin/users/{{$u.ID}}/delete" class="inline"
hx-confirm="Remove {{$u.Email}} for good? Their keys are revoked.">
<input type="hidden" name="csrf" value="{{$d.CSRF}}">
<input type="hidden" name="open" value="{{.Open}}">
<button type="submit" class="link danger">remove</button>
</form>
{{else}}<span class="note">you</span>{{end}}
</td>
</tr>{{end}}
+2
View File
@@ -36,6 +36,8 @@ var files embed.FS
var staticFiles embed.FS
var funcs = template.FuncMap{
"lower": strings.ToLower,
"sub": func(a, b int) int { return a - b },
"join": func(v []string) string {
if len(v) == 0 {
return "—"