From ee35b278169414ee94c2b3cfd6b978e4ec78a6bd Mon Sep 17 00:00:00 2001 From: Lorena Jimenez Date: Thu, 26 Nov 2026 13:11:34 +0100 Subject: [PATCH] Manage accounts from a web admin page --- CHANGELOG.md | 1 + README.md | 8 + cmd/refract/account_api.go | 16 +- cmd/refract/account_api_test.go | 11 +- cmd/refract/admin_api.go | 210 ++++++++++++++++ cmd/refract/admin_api_test.go | 361 +++++++++++++++++++++++++++ cmd/refract/api.go | 29 +-- cmd/refract/hosts.go | 8 +- cmd/refract/login_api.go | 20 +- cmd/refract/main.go | 9 +- cmd/refract/routes.go | 40 ++- cmd/refract/routes_test.go | 22 +- cmd/refract/users_cmd.go | 76 +++--- internal/access/access.go | 15 ++ internal/projects/storage.go | 34 +++ internal/projects/trash.go | 34 +++ internal/store/store.go | 2 + internal/store/store_test.go | 25 ++ internal/usage/usage.go | 23 ++ internal/users/account_test.go | 67 ++++- internal/users/admin.go | 175 +++++++++++++ internal/users/password.go | 96 ++++---- internal/users/password_test.go | 20 +- internal/users/sessions.go | 30 ++- internal/users/tokens.go | 21 +- internal/users/users.go | 39 +-- web/e2e/admin.spec.ts | 29 +++ web/src/Admin.tsx | 378 +++++++++++++++++++++++++++++ web/src/App.tsx | 5 + web/src/Settings.tsx | 3 +- web/src/api.ts | 10 +- web/src/components/AccountMenu.tsx | 10 +- web/src/locales/es/admin.ts | 50 ++++ web/src/locales/es/index.ts | 2 + 34 files changed, 1709 insertions(+), 170 deletions(-) create mode 100644 cmd/refract/admin_api.go create mode 100644 cmd/refract/admin_api_test.go create mode 100644 internal/projects/storage.go create mode 100644 internal/users/admin.go create mode 100644 web/e2e/admin.spec.ts create mode 100644 web/src/Admin.tsx create mode 100644 web/src/locales/es/admin.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 09751e5..0493616 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Notable changes to Refract. The format follows [Keep a Changelog](https://keepac ### Added +- Administrators can create, rename, unlock and delete accounts, reset passwords, and end sessions from **Account administration**. The page also shows each account's model usage and project disk space. Run `refract users admin ` to grant the role or `refract users report [since]` for the same report as JSON. - Refract can read its encryption key, OpenID Connect client secret, SMTP URL and OpenAlex API key from files using the corresponding `REFRACT_*_FILE` variables. `refract users` and `refract local` also accept the encryption key from a file, and the systemd unit starts Refract directly with a systemd credential. - `REFRACT_OUTBOUND` (`any` by default, or `public`) chooses whether AI provider base URLs and git remotes may reach loopback and private networks. `public` does what `REFRACT_MODE=saas` did for outbound requests, and checks at startup that git is 2.37 or later. With `public`, provider requests and redirects must be https, and link-local git remotes are refused in every mode. `REFRACT_MODE=saas` no longer changes it. - Refract finds `tectonic`, `synctex`, `rg` and `git` in a bundled `libexec/refract` folder next to the executable (the executable's own folder on Windows) before the `PATH`, and runs them by absolute path; a bundled Git uses only its own helpers and templates. `REFRACT_TECTONIC_BIN`, `REFRACT_SYNCTEX_BIN`, `REFRACT_RG_BIN` and `REFRACT_GIT_BIN` override the lookup. The startup log shows where each was found, and the web app shows one notice when a tool is missing, saying what won't work, on whichever page opens first. On macOS and Linux a bundled tool in a folder that others can write, or that another user owns, is ignored. The same checks cover bundled Git's helpers and templates. diff --git a/README.md b/README.md index 775dd12..f06c90b 100644 --- a/README.md +++ b/README.md @@ -320,6 +320,12 @@ docker exec refract refract users list Accounts you add this way count as confirmed: you vouch for the address. People can see and end their own sessions in Settings → Account. To end all of someone's sessions for them (a lost laptop, say), run `refract users signout `. After too many failed sign-ins an account waits 15 minutes; `refract users unlock ` lets it in at once. To delete an account with its projects (those in the trash too), chats and connections, run `refract users remove `: it lists what would go, and deletes only when run again with `--yes`. With Cloudflare Access, also remove the person from your Access policy, or they get a new, empty account on their next visit. +Administrators can open **Account administration** from the account menu. They can create accounts, issue new passwords, change email addresses, end Refract sessions, clear lockouts and delete accounts. Changes are logged on the server. Changing an email address ends Refract sessions and invalidates existing account links. Passwords and Refract sessions apply to Refract's built-in sign-in. With Cloudflare Access, continue to manage access and sessions through Cloudflare. Without sign-in, account administration is available only when Refract itself listens on a loopback address. + +On a new installation, the first account created by the CLI or a trusted sign-in becomes an administrator if the account list is empty. An open sign-up never grants the role. After upgrading an existing installation, grant the role to the confirmed account you trust with `refract users admin ` on the server. + +Selecting an account shows its token usage this month and disk space per project, including Git history and projects in the trash. Generated build files are excluded from disk totals. For the same report as JSON, run `refract users report [since]`. Pass a Unix timestamp in seconds to choose when to start counting tokens. The default counts all recorded usage. + ### Sign in with OpenID Connect With `REFRACT_AUTH=builtin`, an OpenID Connect provider (Google, Microsoft Entra, Keycloak, Authentik, Authelia…) can add a **Continue with …** button next to the password form. @@ -614,6 +620,8 @@ refract users rename change an account's email, keeping its data refract users signout end all of an account's sessions refract users unlock clear an account's failed sign-ins and email limit (--all: every account and address) refract users remove delete an account and everything it owns, trash included (asks for --yes) +refract users admin grant administrator access to a confirmed account +refract users report [since] show model usage and project disk space as JSON refract users list list accounts refract version print the version ``` diff --git a/cmd/refract/account_api.go b/cmd/refract/account_api.go index de5b469..2147331 100644 --- a/cmd/refract/account_api.go +++ b/cmd/refract/account_api.go @@ -169,7 +169,7 @@ func (a *loginAPI) resetPassword(w http.ResponseWriter, r *http.Request) { case err != nil: httpError(w, err, http.StatusInternalServerError) default: - a.signIn(w, r, u.ID) + a.signIn(w, r, u) } } @@ -197,7 +197,7 @@ func (a *loginAPI) verifyEmail(w http.ResponseWriter, r *http.Request) { case u.ID == signedInAs: w.WriteHeader(http.StatusNoContent) default: - a.signIn(w, r, u.ID) + a.signIn(w, r, u) } } @@ -304,6 +304,9 @@ func (a *loginAPI) deleteAccount(w http.ResponseWriter, r *http.Request) { // Once started, deleting runs to the end even if the client goes away. n, err := a.users.Remove(context.WithoutCancel(r.Context()), u.ID, a.destroy) switch { + case err != nil && n > 0: + partialAccountRemoval(w, int64(n), err) + return case errors.Is(err, users.ErrOwnsProjects): httpError(w, errors.New("a project was created meanwhile: try again"), http.StatusConflict) return @@ -321,6 +324,15 @@ func (a *loginAPI) deleteAccount(w http.ResponseWriter, r *http.Request) { slog.Info("account deleted", "user", u.ID, "projects", n) } +func partialAccountRemoval(w http.ResponseWriter, removed int64, err error) { + slog.Warn("account removal stopped after deleting projects", "removed_projects", removed, "err", err) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusConflict) + json.NewEncoder(w).Encode(map[string]any{"error": map[string]any{ + "kind": "account_removal_partial", "message": "some projects were deleted before account removal stopped", "removed_projects": removed, + }}) +} + // thenAccount is the only value oidcStart takes for ?then=. func thenAccount(r *http.Request) bool { return r.URL.Query().Get("then") == "account" } diff --git a/cmd/refract/account_api_test.go b/cmd/refract/account_api_test.go index b5e0b23..52bda62 100644 --- a/cmd/refract/account_api_test.go +++ b/cmd/refract/account_api_test.go @@ -23,6 +23,7 @@ import ( "github.com/ponytojas/Refract/internal/mode" "github.com/ponytojas/Refract/internal/projects" "github.com/ponytojas/Refract/internal/store" + "github.com/ponytojas/Refract/internal/usage" "github.com/ponytojas/Refract/internal/users" ) @@ -63,7 +64,7 @@ func TestMain(m *testing.M) { func newAccountEnv(t *testing.T, o envOpts) *accountEnv { t.Helper() dir := t.TempDir() - db, err := store.Open(filepath.Join(dir, "t.db")) + db, err := store.Open(filepath.Join(dir, "refract.db")) if err != nil { t.Fatal(err) } @@ -71,7 +72,7 @@ func newAccountEnv(t *testing.T, o envOpts) *accountEnv { people := &users.Service{DB: db, Key: make([]byte, 32)} ps := &projects.Service{DB: db, Dir: filepath.Join(dir, "projects"), Limits: projects.DefaultLimits} e := &accountEnv{t: t, people: people, ps: ps, fake: &mail.Fake{}} - e.login = &loginAPI{users: people, mode: mode.SelfHost, signup: o.signup, destroy: destroyer(ps)} + e.login = &loginAPI{users: people, mode: mode.SelfHost, signup: o.signup, destroy: ps.DestroyOwnedProjects} if !o.noMail { e.login.public = "https://r.test" e.outbox = mail.NewOutbox(e.fake) @@ -80,6 +81,8 @@ func newAccountEnv(t *testing.T, o envOpts) *accountEnv { } app := http.NewServeMux() rt := &router{mux: app, acc: &access.Checker{DB: db}} + rec := &usage.Recorder{DB: db} + (&api{usage: rec, admin: &adminAPI{users: people, projects: ps, usage: rec}}).routes(rt) (&projectsAPI{svc: ps}).routes(rt) e.login.accountRoutes(rt) mux := http.NewServeMux() @@ -410,9 +413,9 @@ func TestDeleteAccountSurvivesDisconnect(t *testing.T) { reqCtx, cancel := context.WithCancel(as) defer cancel() inner := e.login.destroy - e.login.destroy = func(c context.Context, id string) error { + e.login.destroy = func(c context.Context, ids []string) (int, error) { cancel() // the client hangs up as the first project goes - return inner(c, id) + return inner(c, ids) } body, _ := json.Marshal(map[string]string{"password": "correct horse"}) r := httptest.NewRequest("POST", "/api/account/delete", bytes.NewReader(body)).WithContext(reqCtx) diff --git a/cmd/refract/admin_api.go b/cmd/refract/admin_api.go new file mode 100644 index 0000000..a8d136a --- /dev/null +++ b/cmd/refract/admin_api.go @@ -0,0 +1,210 @@ +package main + +import ( + "context" + "errors" + "log/slog" + "net/http" + "strconv" + "time" + + "github.com/ponytojas/Refract/internal/projects" + "github.com/ponytojas/Refract/internal/usage" + "github.com/ponytojas/Refract/internal/users" + "github.com/ponytojas/Refract/web" +) + +type adminAPI struct { + users *users.Service + projects *projects.Service + usage *usage.Recorder +} + +func (a *adminAPI) routes(rt *router) { + rt.admin("GET /admin", web.Handler().ServeHTTP) + rt.admin("GET /api/admin/accounts", a.accounts) + rt.admin("GET /api/admin/accounts/report", a.report) + rt.admin("POST /api/admin/accounts", a.manage) +} + +func (a *adminAPI) accounts(w http.ResponseWriter, r *http.Request) { + all, err := a.users.AdminAccounts(r.Context()) + if err != nil { + accessError(w, err) + return + } + writeJSON(w, all) +} + +type measuredProject struct { + ID string `json:"id"` + Name string `json:"name"` + Trashed bool `json:"trashed"` + Bytes int64 `json:"bytes"` +} + +type accountReport struct { + Models []usage.ModelTotals `json:"models"` + Projects []measuredProject `json:"projects"` +} + +func usageStart(raw string) (time.Time, error) { + since, err := strconv.ParseInt(raw, 10, 64) + if err != nil || since < 0 { + return time.Time{}, errors.New("since must be a Unix time in seconds") + } + return time.Unix(since, 0), nil +} + +// accountUsageAndStorage is shared by the web reports and the operator CLI. +func (a *adminAPI) accountUsageAndStorage(ctx context.Context, id string, since time.Time) (accountReport, error) { + owned, err := a.users.OwnedProjects(ctx, id) + if err != nil { + return accountReport{}, err + } + models, err := a.usage.Report(ctx, id, since) + if err != nil { + return accountReport{}, err + } + out := accountReport{Models: models, Projects: make([]measuredProject, 0, len(owned))} + for _, p := range owned { + size, err := a.projects.StorageBytes(ctx, p.ID) + if err != nil { + return accountReport{}, err + } + out.Projects = append(out.Projects, measuredProject{ID: p.ID, Name: p.Name, Trashed: p.Trashed, Bytes: size}) + } + return out, nil +} + +func (a *adminAPI) report(w http.ResponseWriter, r *http.Request) { + since, err := usageStart(r.URL.Query().Get("since")) + if err != nil { + httpError(w, err, http.StatusBadRequest) + return + } + id := r.URL.Query().Get("id") + if _, err := a.users.AccountByID(r.Context(), id); err != nil { + adminError(w, err) + return + } + out, err := a.accountUsageAndStorage(r.Context(), id, since) + if err != nil { + accessError(w, err) + return + } + writeJSON(w, out) +} + +type adminAction struct { + Action string `json:"action"` + ID string `json:"id"` + Email string `json:"email"` + Confirmed bool `json:"confirmed"` +} + +type adminResult struct { + Password string `json:"password,omitempty"` + Count int64 `json:"count,omitempty"` +} + +var ( + errAdminAction = errors.New("unknown account action") + errAdminConfirmation = errors.New("confirm this action first") + errAdminAddress = errors.New("enter a valid email address") +) + +func (a *adminAPI) manage(w http.ResponseWriter, r *http.Request) { + var in adminAction + if !decode(w, r, &in) { + return + } + switch in.Action { + case "add", "reset", "rename", "signout", "unlock", "unlock_all", "remove": + default: + adminError(w, errAdminAction) + return + } + out, target, err := a.apply(r.Context(), in) + partial := err != nil && in.Action == "remove" && out.Count > 0 + result := "success" + if err != nil { + result = "failed" + } + if partial { + result = "partial" + } + slog.Info("account administration", "actor", requestUser(r.Context()), "target", target, "action", in.Action, "result", result, "affected", out.Count) + if partial { + partialAccountRemoval(w, out.Count, err) + return + } + if err != nil { + adminError(w, err) + return + } + writeJSON(w, out) +} + +func (a *adminAPI) apply(ctx context.Context, in adminAction) (adminResult, string, error) { + var out adminResult + if in.Action == "add" || in.Action == "rename" { + if err := users.ValidateEmail(in.Email); err != nil { + return out, "", errAdminAddress + } + } + if in.Action == "add" { + u, password, err := a.users.ProvisionPassword(ctx, in.Email, true) + out.Password = password + return out, u.ID, err + } + if !in.Confirmed { + return out, "", errAdminConfirmation + } + if in.Action == "unlock_all" { + count, err := a.users.UnlockAll(ctx) + out.Count = count + return out, "", err + } + + acct, err := a.users.AccountByID(ctx, in.ID) + if err != nil { + return out, "", err + } + switch in.Action { + case "reset": + out.Password, err = a.users.ResetAccountPassword(ctx, acct.ID) + case "rename": + err = a.users.RenameAccount(ctx, acct.ID, in.Email) + case "signout": + out.Count, err = a.users.SignOutAccount(ctx, acct.ID) + case "unlock": + var cleared bool + cleared, err = a.users.Unlock(ctx, acct.Email) + if cleared { + out.Count = 1 + } + case "remove": + var deleted int + deleted, err = a.users.Remove(context.WithoutCancel(ctx), acct.ID, a.projects.DestroyOwnedProjects) + out.Count = int64(deleted) + } + return out, acct.ID, err +} + +func adminError(w http.ResponseWriter, err error) { + switch { + case errors.Is(err, users.ErrNoAccount): + httpError(w, err, http.StatusNotFound) + case errors.Is(err, errAdminConfirmation), errors.Is(err, errAdminAction): + httpError(w, err, http.StatusBadRequest) + case errors.Is(err, errAdminAddress): + kindError(w, http.StatusBadRequest, "admin_invalid_email", err) + case errors.Is(err, users.ErrAccountExists): + kindError(w, http.StatusConflict, "admin_account_exists", err) + case errors.Is(err, users.ErrOwnsProjects), errors.Is(err, projects.ErrTurnRunning): + kindError(w, http.StatusConflict, "admin_account_busy", errors.New("the account's projects are changing")) + default: + accessError(w, err) + } +} diff --git a/cmd/refract/admin_api_test.go b/cmd/refract/admin_api_test.go new file mode 100644 index 0000000..ed95451 --- /dev/null +++ b/cmd/refract/admin_api_test.go @@ -0,0 +1,361 @@ +package main + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "io" + "net" + "net/http" + "net/url" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + "github.com/ponytojas/Refract/internal/ai" + "github.com/ponytojas/Refract/internal/auth" + "github.com/ponytojas/Refract/internal/usage" + "github.com/ponytojas/Refract/internal/users" +) + +const adminAccountsPath = "/api/admin/accounts" + +func signInForAdminTest(e *accountEnv, email, password string) *browser { + b := e.browser() + b.expect(b.post("/api/auth/login", map[string]string{"email": email, "password": password}), http.StatusNoContent, "") + return b +} + +func TestAdminAccountActions(t *testing.T) { + e := newAccountEnv(t, envOpts{noMail: true}) + ctx := context.Background() + admin, err := e.people.SetPassword(ctx, "admin@example.com", "fixture admin password") + if err != nil { + t.Fatal(err) + } + operator := signInForAdminTest(e, admin.Email, "fixture admin password") + const email = "member@example.com" + add := adminAction{Action: "add", Email: email} + created := operator.post(adminAccountsPath, add) + var issued adminResult + if err := json.Unmarshal([]byte(created.Body), &issued); created.Status != http.StatusOK || err != nil || issued.Password == "" { + t.Fatalf("add account returned %d or failed to issue a password", created.Status) + } + acct, err := e.people.Lookup(ctx, email) + if err != nil || !acct.Verified { + t.Fatalf("account was not created and confirmed: %v", err) + } + member := signInForAdminTest(e, email, issued.Password) + for _, route := range []string{"/admin", adminAccountsPath, adminAccountsPath + "/report"} { + member.expect(member.do("GET", route, nil), http.StatusNotFound, "") + } + member.expect(member.post(adminAccountsPath, adminAction{Action: "remove", ID: admin.ID, Confirmed: true}), http.StatusNotFound, "") + operator.expect(operator.post(adminAccountsPath, add), http.StatusConflict, "admin_account_exists") + otherSession := signInForAdminTest(e, email, issued.Password) + + var accounts []users.AdminAccount + list := operator.do("GET", adminAccountsPath, nil) + if err := json.Unmarshal([]byte(list.Body), &accounts); list.Status != http.StatusOK || err != nil || len(accounts) != 2 || + !accounts[0].IsAdmin || accounts[1].IsAdmin { + t.Fatalf("unexpected account list: %d %+v, %v", list.Status, accounts, err) + } + for _, action := range []string{"reset", "remove", "signout", "unlock", "unlock_all", "rename"} { + operator.expect(operator.post(adminAccountsPath, adminAction{Action: action, ID: acct.ID, Email: email}), http.StatusBadRequest, "other") + } + + reset := operator.post(adminAccountsPath, adminAction{Action: "reset", ID: acct.ID, Confirmed: true}) + var replacement adminResult + if err := json.Unmarshal([]byte(reset.Body), &replacement); reset.Status != http.StatusOK || err != nil || + replacement.Password == "" || replacement.Password == issued.Password { + t.Fatalf("reset returned %d or failed to issue a different password", reset.Status) + } + member.expect(member.do("GET", "/api/account", nil), http.StatusUnauthorized, "login_required") + otherSession.expect(otherSession.do("GET", "/api/account", nil), http.StatusUnauthorized, "login_required") + if _, err := e.people.Login(ctx, email, issued.Password, ""); !errors.Is(err, users.ErrBadLogin) { + t.Fatalf("old password after reset: %v", err) + } + member = signInForAdminTest(e, email, replacement.Password) + + const renamed = "renamed@example.com" + operator.expect(operator.post(adminAccountsPath, adminAction{Action: "rename", ID: acct.ID, Email: renamed, Confirmed: true}), http.StatusOK, "") + if found, err := e.people.Lookup(ctx, renamed); err != nil || found.ID != acct.ID { + t.Fatalf("rename changed the account ID: %v", err) + } + member.expect(member.do("GET", "/api/account", nil), http.StatusUnauthorized, "login_required") + member = signInForAdminTest(e, renamed, replacement.Password) + operator.expect(operator.post(adminAccountsPath, adminAction{Action: "signout", ID: acct.ID, Confirmed: true}), http.StatusOK, "") + member.expect(member.do("GET", "/api/account", nil), http.StatusUnauthorized, "login_required") + + if _, err := e.people.DB.Exec(`INSERT INTO login_failures (key, count, since) VALUES (?, 10, ?), ('ip:192.0.2.1', 30, ?)`, + "email:"+renamed, time.Now().Unix(), time.Now().Unix()); err != nil { + t.Fatal(err) + } + operator.expect(operator.post(adminAccountsPath, adminAction{Action: "unlock", ID: acct.ID, Confirmed: true}), http.StatusOK, "") + var remaining int + if err := e.people.DB.QueryRow(`SELECT count(*) FROM login_failures WHERE key IN (?, 'ip:192.0.2.1')`, "email:"+renamed).Scan(&remaining); err != nil || remaining != 1 { + t.Fatalf("individual unlock left %d target failures, want the address only: %v", remaining, err) + } + operator.expect(operator.post(adminAccountsPath, adminAction{Action: "unlock_all", Confirmed: true}), http.StatusOK, "") + if err := e.people.DB.QueryRow(`SELECT count(*) FROM login_failures`).Scan(&remaining); err != nil || remaining != 0 { + t.Fatalf("global unlock left %d failures: %v", remaining, err) + } + + member = signInForAdminTest(e, renamed, replacement.Password) + owner := auth.WithUser(ctx, auth.User{ID: acct.ID, Email: renamed}) + p, err := e.ps.Create(owner, "Member's project") + if err != nil { + t.Fatal(err) + } + if err := e.ps.Trash(owner, p.ID); err != nil { + t.Fatal(err) + } + operator.expect(operator.post(adminAccountsPath, adminAction{Action: "remove", ID: acct.ID, Confirmed: true}), http.StatusOK, "") + if _, err := e.people.Lookup(ctx, renamed); !errors.Is(err, users.ErrNoAccount) { + t.Fatalf("deleted account still exists: %v", err) + } + if _, err := os.Stat(e.ps.Path(p.ID)); !errors.Is(err, os.ErrNotExist) { + t.Fatal("project in the trash survived account removal") + } + member.expect(member.do("GET", "/api/account", nil), http.StatusUnauthorized, "login_required") +} + +func TestAdminRemovePreflightsAndReportsPartialDeletion(t *testing.T) { + for _, partial := range []bool{false, true} { + name := "busy project leaves everything intact" + if partial { + name = "filesystem failure reports what was removed" + } + t.Run(name, func(t *testing.T) { + e := newAccountEnv(t, envOpts{noMail: true}) + ctx := context.Background() + admin, err := e.people.SetPassword(ctx, "admin@example.com", "fixture admin password") + if err != nil { + t.Fatal(err) + } + member, err := e.people.SetPassword(ctx, "member@example.com", "fixture member password") + if err != nil { + t.Fatal(err) + } + owner := auth.WithUser(ctx, member) + first, err := e.ps.Create(owner, "A first project") + if err != nil { + t.Fatal(err) + } + second, err := e.ps.Create(owner, "Z second project") + if err != nil { + t.Fatal(err) + } + if partial { + gone := filepath.Join(e.ps.Dir, ".purge-"+second.ID) + if err := os.Mkdir(gone, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(gone, "fixture"), []byte("blocked"), 0o600); err != nil { + t.Fatal(err) + } + } else { + e.ps.HoldTurns = func(id string) (func(), bool) { return func() {}, id != second.ID } + } + operator := signInForAdminTest(e, admin.Email, "fixture admin password") + res := operator.post(adminAccountsPath, adminAction{Action: "remove", ID: member.ID, Confirmed: true}) + if partial { + operator.expect(res, http.StatusConflict, "account_removal_partial") + var failure struct { + Error struct { + Removed int `json:"removed_projects"` + } + } + if err := json.Unmarshal([]byte(res.Body), &failure); err != nil || failure.Error.Removed != 1 { + t.Fatalf("response did not say that one project was deleted: %s (%v)", res.Body, err) + } + if _, err := e.ps.Get(ctx, first.ID); err == nil { + t.Fatal("reported partial deletion did not remove the first project") + } + } else { + operator.expect(res, http.StatusConflict, "admin_account_busy") + if _, err := e.ps.Get(ctx, first.ID); err != nil { + t.Fatalf("preflight deleted the first project: %v", err) + } + } + if _, err := e.ps.Get(ctx, second.ID); err != nil { + t.Fatalf("the second project was lost: %v", err) + } + if _, err := e.people.AccountByID(ctx, member.ID); err != nil { + t.Fatalf("the account was lost: %v", err) + } + }) + } +} + +type reportedListener struct { + net.Listener + addr net.Addr +} + +func (l reportedListener) Addr() net.Addr { return l.addr } + +func TestAdminWithoutAuthRequiresLoopbackListener(t *testing.T) { + t.Setenv("REFRACT_ALLOWED_HOSTS", "localhost") + for _, variable := range []string{"REFRACT_MODE", "REFRACT_PROFILE", "REFRACT_SANDBOX", "REFRACT_OUTBOUND"} { + t.Setenv(variable, "") + } + for _, tc := range []struct { + name string + ip net.IP + want int + }{{"loopback", net.IPv4(127, 0, 0, 1), http.StatusOK}, {"wildcard", net.IPv4zero, http.StatusNotFound}} { + t.Run(tc.name, func(t *testing.T) { + // The test itself always binds loopback. Only the address + // reported to the startup policy changes. + ln, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + addr := ln.Addr().(*net.TCPAddr) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + ready := make(chan struct{}) + done := make(chan error, 1) + data := t.TempDir() + go func() { + done <- run(ctx, runOptions{dataDir: data, key: make([]byte, 32), authKind: "none", + listen: func() (net.Listener, error) { + return reportedListener{ln, &net.TCPAddr{IP: tc.ip, Port: addr.Port}}, nil + }, + ready: func(context.Context, net.Addr) { close(ready) }, + }) + }() + select { + case <-ready: + case err := <-done: + t.Fatalf("server stopped before readiness: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("server did not start") + } + t.Cleanup(func() { + cancel() + select { + case err := <-done: + if err != nil { + t.Errorf("server shutdown: %v", err) + } + case <-time.After(5 * time.Second): + t.Error("server did not stop") + } + }) + client := &http.Client{Timeout: 5 * time.Second} + for _, path := range []string{"/api/me", adminAccountsPath} { + req, _ := http.NewRequest(http.MethodGet, "http://"+addr.String()+path, nil) + req.Header.Set("X-Refract", "1") + res, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + if path == "/api/me" { + var me struct { + IsAdmin bool `json:"is_admin"` + } + if err := json.NewDecoder(res.Body).Decode(&me); err != nil || me.IsAdmin != (tc.want == http.StatusOK) { + t.Errorf("/api/me: is_admin = %v (%v)", me.IsAdmin, err) + } + } else if res.StatusCode != tc.want { + t.Errorf("admin GET = %d, want %d", res.StatusCode, tc.want) + } + res.Body.Close() + } + }) + } +} + +func TestAdminReportMatchesCLIAndOwner(t *testing.T) { + e := newAccountEnv(t, envOpts{noMail: true}) + ctx := context.Background() + t.Setenv("REFRACT_DATA_DIR", filepath.Dir(e.ps.Dir)) + t.Setenv("REFRACT_SECRET_KEY", base64.StdEncoding.EncodeToString(e.people.Key)) + t.Setenv("REFRACT_SECRET_KEY_FILE", "") + create := func(email string) auth.User { + t.Helper() + u, err := e.people.SetPassword(ctx, email, "fixture report password") + if err != nil { + t.Fatal(err) + } + return u + } + admin, member := create("admin@example.com"), create("member@example.com") + operator := signInForAdminTest(e, admin.Email, "fixture report password") + ownerBrowser := signInForAdminTest(e, member.Email, "fixture report password") + owner := auth.WithUser(ctx, member) + p, err := e.ps.Create(owner, "Report project") + if err != nil { + t.Fatal(err) + } + initial, err := e.ps.StorageBytes(ctx, p.ID) + if err != nil || initial == 0 { + t.Fatalf("initial repository size = %d, %v", initial, err) + } + if err := e.ps.WriteFile(owner, p.ID, "main.tex", strings.NewReader("source")); err != nil { + t.Fatal(err) + } + build := filepath.Join(e.ps.Path(p.ID), ".refract") + if err := os.Mkdir(build, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(build, "generated.pdf"), []byte("ignored build output"), 0o600); err != nil { + t.Fatal(err) + } + recorder := &usage.Recorder{DB: e.people.DB, Now: func() time.Time { return time.Unix(100, 0) }} + for _, user := range []auth.User{member, admin} { + if err := recorder.Record(ctx, usage.Entry{UserID: user.ID, Kind: "quick", Model: user.Email, + Usage: ai.Usage{InputTokens: 12, CachedTokens: 2, OutputTokens: 5}}); err != nil { + t.Fatal(err) + } + } + r := operator.do("GET", adminAccountsPath+"/report?id="+url.QueryEscape(member.ID)+"&since=100", nil) + var webReport accountReport + if err := json.Unmarshal([]byte(r.Body), &webReport); r.Status != http.StatusOK || err != nil || + len(webReport.Projects) != 1 || webReport.Projects[0].ID != p.ID || webReport.Projects[0].Bytes != initial+6 { + t.Fatalf("unexpected report %d %+v, %v", r.Status, webReport, err) + } + own := ownerBrowser.do("GET", "/api/usage?since=100", nil) + var ownerReport accountReport + if err := json.Unmarshal([]byte(own.Body), &ownerReport); own.Status != http.StatusOK || err != nil || len(ownerReport.Models) != 1 || + !reflect.DeepEqual(ownerReport.Models, webReport.Models) || ownerReport.Models[0].Model != member.Email { + t.Fatalf("admin usage differs from account usage: %+v versus %+v (%v)", webReport.Models, ownerReport.Models, err) + } + var output bytes.Buffer + if err := runUsers([]string{"report", member.Email, "100"}, &output); err != nil { + t.Fatal(err) + } + var cli accountReport + if err := json.NewDecoder(&output).Decode(&cli); err != nil || !reflect.DeepEqual(webReport, cli) { + t.Fatalf("admin report differs from CLI: %+v versus %+v (%v)", webReport, cli, err) + } + if err := runUsers([]string{"admin", member.Email}, io.Discard); err != nil { + t.Fatal(err) + } + ownerBrowser.expect(ownerBrowser.do("GET", adminAccountsPath, nil), http.StatusOK, "") +} + +func TestOpenSignupDoesNotBootstrapAdmin(t *testing.T) { + e := newAccountEnv(t, envOpts{noMail: true}) + ctx := context.Background() + const email = "public@example.com" + link, err := e.people.SignUp(ctx, email, "fixture signup password", "en") + if err != nil { + t.Fatal(err) + } + if err := e.people.GrantAdmin(ctx, email); !errors.Is(err, users.ErrAdminEmail) { + t.Fatalf("unconfirmed admin grant: %v", err) + } + if err := e.people.MarkVerified(ctx, link.To.ID); err != nil { + t.Fatal(err) + } + member := signInForAdminTest(e, email, "fixture signup password") + member.expect(member.do("GET", adminAccountsPath, nil), http.StatusNotFound, "") +} diff --git a/cmd/refract/api.go b/cmd/refract/api.go index 5db8a16..03a9ea2 100644 --- a/cmd/refract/api.go +++ b/cmd/refract/api.go @@ -9,10 +9,7 @@ import ( "io" "log/slog" "net/http" - "slices" - "strconv" "sync" - "time" "github.com/ponytojas/Refract/internal/ai" "github.com/ponytojas/Refract/internal/assistant" @@ -39,6 +36,7 @@ type api struct { providers *providers.Store // users' API-key providers outbound *http.Client // for those providers (see providers.HTTPClient) usage *usage.Recorder // what each model call used; nil records nothing + admin *adminAPI users sync.Map // user id → *userAI } @@ -87,9 +85,12 @@ func (a *api) metered(kind string) func(context.Context) ai.Provider { func (a *api) missing() []string { return append([]string{}, a.missingTools...) } func (a *api) routes(rt *router) { + a.admin.routes(rt) rt.user("GET /api/me", func(w http.ResponseWriter, r *http.Request) { u, _ := auth.UserFrom(r.Context()) - writeJSON(w, map[string]any{"id": u.ID, "email": u.Email, "can_sign_out": a.canSignOut, "mode": a.mode, "missing_tools": a.missing()}) + isAdmin, _ := rt.isAdmin(r.Context()) + w.Header().Set("Cache-Control", "no-store") + writeJSON(w, map[string]any{"id": u.ID, "email": u.Email, "can_sign_out": a.canSignOut, "mode": a.mode, "missing_tools": a.missing(), "is_admin": isAdmin}) }) rt.user("GET /api/chatgpt/status", a.status) if a.mode.ChatGPT() { // elsewhere these fall through to a 404 @@ -109,30 +110,20 @@ func (a *api) routes(rt *router) { // usageSince is the signed-in account's token usage per model from ?since= // (Unix seconds; the client sends the start of its month), most used first. func (a *api) usageSince(w http.ResponseWriter, r *http.Request) { - since, err := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64) - if err != nil || since < 0 { - httpError(w, errors.New("since must be a Unix time in seconds"), http.StatusBadRequest) + since, err := usageStart(r.URL.Query().Get("since")) + if err != nil { + httpError(w, err, http.StatusBadRequest) return } - type model struct { - Model string `json:"model"` - usage.Totals - } - out := []model{} + out := []usage.ModelTotals{} if a.usage != nil { u, _ := auth.UserFrom(r.Context()) - totals, err := a.usage.Since(r.Context(), u.ID, time.Unix(since, 0)) + out, err = a.usage.Report(r.Context(), u.ID, since) if err != nil { httpError(w, err, http.StatusInternalServerError) return } - for m, t := range totals { - out = append(out, model{m, t}) - } } - slices.SortFunc(out, func(x, y model) int { - return cmp.Or(cmp.Compare(y.InputTokens+y.OutputTokens, x.InputTokens+x.OutputTokens), cmp.Compare(x.Model, y.Model)) - }) writeJSON(w, map[string]any{"models": out}) } diff --git a/cmd/refract/hosts.go b/cmd/refract/hosts.go index b7b4df7..bbaa15d 100644 --- a/cmd/refract/hosts.go +++ b/cmd/refract/hosts.go @@ -68,8 +68,7 @@ func newHostPolicy(publicURL, allowed string) (hostPolicy, error) { // the address actually bound, not by how REFRACT_ADDR spells it. authKind is // REFRACT_AUTH after authMode. warning, when not empty, is for the log. func (p *hostPolicy) forListener(addr net.Addr, authKind string) (warning string, err error) { - tcp, ok := addr.(*net.TCPAddr) - if p.configured || (ok && tcp.IP.IsLoopback()) { + if p.configured || loopbackListener(addr) { return "", nil } if authKind == "none" { @@ -79,6 +78,11 @@ func (p *hostPolicy) forListener(addr net.Addr, authKind string) (warning string return "Refract accepts requests for any host name because it listens on " + addr.String() + " without REFRACT_PUBLIC_URL or REFRACT_ALLOWED_HOSTS. Set one of them to the names people open Refract at, to protect against DNS rebinding.", nil } +func loopbackListener(addr net.Addr) bool { + tcp, ok := addr.(*net.TCPAddr) + return ok && tcp.IP.IsLoopback() +} + // parseAuthority reads a host with an optional port, as in a Host header or a // REFRACT_ALLOWED_HOSTS entry, and returns the normalized name without the // port. Brackets are only for IPv6 addresses; anything malformed is refused. diff --git a/cmd/refract/login_api.go b/cmd/refract/login_api.go index 6852efc..5fa45f3 100644 --- a/cmd/refract/login_api.go +++ b/cmd/refract/login_api.go @@ -21,11 +21,11 @@ type loginAPI struct { oidc *auth.OIDC // nil without OIDC allowed []string // emails and "@domains" OIDC may create accounts for; empty: existing users only - mode mode.Mode // REFRACT_MODE - signup bool // people may create their own account (open sign-up, and mail to confirm it) - public string // REFRACT_PUBLIC_URL, the base of links in emails; "" without - mail *mail.Outbox // nil when the server can't send email - destroy func(ctx context.Context, projectID string) error // deletes a project for good, for removing an account + mode mode.Mode // REFRACT_MODE + signup bool // people may create their own account (open sign-up, and mail to confirm it) + public string // REFRACT_PUBLIC_URL, the base of links in emails; "" without + mail *mail.Outbox // nil when the server can't send email + destroy func(context.Context, []string) (int, error) // deletes the account's projects } const oidcCookie = "refract_oidc" @@ -90,8 +90,8 @@ func (a *loginAPI) login(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) } -func (a *loginAPI) signIn(w http.ResponseWriter, r *http.Request, userID string) bool { - token, err := a.users.StartSession(r.Context(), userID, users.ClientOf(r)) +func (a *loginAPI) signIn(w http.ResponseWriter, r *http.Request, u auth.User) bool { + token, err := a.users.StartSessionFor(r.Context(), u, users.ClientOf(r)) if err != nil { httpError(w, err, http.StatusInternalServerError) return false @@ -168,7 +168,7 @@ func (a *loginAPI) oidcCallback(w http.ResponseWriter, r *http.Request) { fail("failed", err) return } - token, err := a.users.StartSession(r.Context(), u.ID, users.ClientOf(r)) + token, err := a.users.StartSessionFor(r.Context(), u, users.ClientOf(r)) if err != nil { fail("failed", err) return @@ -211,7 +211,7 @@ func (a *loginAPI) admitOIDC(ctx context.Context, email string, verified bool) ( if !verified { return auth.User{}, "unverified_email", nil } - if err := a.users.ConfirmByProvider(ctx, acct.ID); err != nil { + if err := a.users.ConfirmByProvider(ctx, auth.User{ID: acct.ID, Email: acct.Email}); err != nil { return auth.User{}, "", err } } @@ -236,7 +236,7 @@ func (a *loginAPI) changePassword(w http.ResponseWriter, r *http.Request) { httpError(w, err, http.StatusBadRequest) return } - a.signIn(w, r, u.ID) + a.signIn(w, r, u) } func kindError(w http.ResponseWriter, status int, kind string, err error) { diff --git a/cmd/refract/main.go b/cmd/refract/main.go index 2f62b54..ad0eca6 100644 --- a/cmd/refract/main.go +++ b/cmd/refract/main.go @@ -63,6 +63,10 @@ Usage: let an account (or everyone) sign in again after too many failed attempts refract users remove [--yes] delete an account with its projects, chats and connections + refract users admin + grant administrator access to a confirmed account + refract users report [since] + show model usage and project disk space as JSON refract users list list accounts refract version print the version ` @@ -289,6 +293,7 @@ func run(ctx context.Context, opts runOptions) error { svc: &projects.Service{DB: db, Dir: filepath.Join(dataDir, "projects"), Limits: projects.DefaultLimits, Key: key, PublicRemotes: publicOnly}, tmp: filepath.Join(dataDir, "tmp"), } + a.admin = &adminAPI{users: people, projects: pa.svc, usage: a.usage} fontResolver := fonts.NewResolver(filepath.Join(dataDir, "font-cache")) fontResolver.Offline = os.Getenv("REFRACT_FONT_DOWNLOADS") == "0" @@ -361,7 +366,7 @@ func run(ctx context.Context, opts runOptions) error { if login != nil { login.mode, login.public = deployment, base login.signup = signup && mailReady - login.destroy = destroyer(pa.svc) + login.destroy = pa.svc.DestroyOwnedProjects if mailReady { outbox = mail.NewOutbox(smtp) login.mail = outbox @@ -373,7 +378,7 @@ func run(ctx context.Context, opts runOptions) error { app := http.NewServeMux() // Every API route goes through the route table and its access check. - registerRoutes(&router{mux: app, acc: acc}, a, pa, ca, asa, ra, pp, login) + registerRoutes(&router{mux: app, acc: acc, disableAdmin: authKind == "none" && !loopbackListener(ln.Addr())}, a, pa, ca, asa, ra, pp, login) app.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) }) app.Handle("/", web.Handler()) diff --git a/cmd/refract/routes.go b/cmd/refract/routes.go index b5bfe3e..7d627e5 100644 --- a/cmd/refract/routes.go +++ b/cmd/refract/routes.go @@ -1,6 +1,7 @@ package main import ( + "context" "errors" "fmt" "log/slog" @@ -39,12 +40,14 @@ type route struct { Scope scope Min access.Role Needs []access.Need // what the account must have; checked after the role + Admin bool // this route is visible only to administrators } type router struct { - mux *http.ServeMux - acc *access.Checker - routes []route + mux *http.ServeMux + acc *access.Checker + routes []route + disableAdmin bool // no authenticated identity on a non-loopback listener // stub, in tests, replaces each handler before it is registered, so the // table can be walked through the real registration and guard. stub func(route) http.HandlerFunc @@ -54,6 +57,17 @@ func (rt *router) user(pattern string, h http.HandlerFunc, needs ...access.Need) rt.register(route{Pattern: pattern, Scope: scopeUser, Needs: needs}, h) } +func (rt *router) admin(pattern string, h http.HandlerFunc) { + rt.register(route{Pattern: pattern, Scope: scopeUser, Admin: true}, h) +} + +func (rt *router) isAdmin(ctx context.Context) (bool, error) { + if rt.disableAdmin { + return false, nil + } + return rt.acc.IsAdmin(ctx) +} + func (rt *router) project(pattern string, min access.Role, h http.HandlerFunc, needs ...access.Need) { rt.register(route{Pattern: pattern, Scope: scopeProject, Min: min, Needs: needs}, h) } @@ -110,6 +124,10 @@ func (r route) validate() error { if !ok || method == "" || !strings.HasPrefix(path, "/") { return fmt.Errorf("route %q: want \"METHOD /path\"", r.Pattern) } + adminPath := path == "/admin" || path == "/api/admin" || strings.HasPrefix(path, "/api/admin/") + if r.Admin != adminPath || r.Admin && r.Scope != scopeUser { + return fmt.Errorf("route %q must match the administrator scope", r.Pattern) + } wildcard := func(seg string) bool { return strings.HasPrefix(seg, "{") && seg != "{$}" } segs := strings.Split(strings.TrimPrefix(path, "/"), "/") if len(segs) >= 3 && segs[0] == "api" { @@ -144,13 +162,27 @@ func (rt *router) guard(r route, h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { ctx := req.Context() if _, err := access.UserFrom(ctx); err != nil { - if r.Scope == scopeUser { + if r.Admin { + http.NotFound(w, req) + } else if r.Scope == scopeUser { httpError(w, err, http.StatusForbidden) } else { accessError(w, access.ErrNotFound) } return } + if r.Admin { + ok, err := rt.isAdmin(ctx) + if err != nil { + accessError(w, err) + return + } + if !ok { + http.NotFound(w, req) + return + } + w.Header().Set("Cache-Control", "no-store") + } var project string var err error check := rt.acc.Require diff --git a/cmd/refract/routes_test.go b/cmd/refract/routes_test.go index f04e498..449fb25 100644 --- a/cmd/refract/routes_test.go +++ b/cmd/refract/routes_test.go @@ -38,9 +38,10 @@ func accessDB(t *testing.T) *access.Checker { t.Fatal(err) } t.Cleanup(func() { db.Close() }) - // ana and ben have verified emails, una has not. + // ana and ben have verified emails. For una, an administrator role alone + // is insufficient while their address remains unverified. for id, verified := range map[string]int{"ana": 1, "ben": 1, "una": 0} { - if _, err := db.Exec(`INSERT INTO users (id, email, created_at, email_verified_at) VALUES (?, ?, 1, ?)`, id, id+"@example.com", verified); err != nil { + if _, err := db.Exec(`INSERT INTO users (id, email, created_at, email_verified_at, is_admin) VALUES (?, ?, 1, ?, ?)`, id, id+"@example.com", verified, id != "ben"); err != nil { t.Fatal(err) } } @@ -127,11 +128,21 @@ func TestRouteTableAccess(t *testing.T) { {"owner", as("ana"), ana, reached, reached}, {"stranger", as("ben"), ana, http.StatusNotFound, reached}, {"owner of other ids", as("ana"), ben, http.StatusNotFound, reached}, + {"unconfirmed", as("una"), ana, http.StatusNotFound, reached}, {"empty user id", as(""), ana, http.StatusNotFound, http.StatusForbidden}, {"anonymous", context.Background(), ana, http.StatusNotFound, http.StatusForbidden}, } { + if tc.who == "unconfirmed" && !r.Admin { + continue // verified-email needs on other routes are covered below + } want := tc.wantUser - if scoped { + if r.Admin { + u, _ := auth.UserFrom(tc.ctx) + want = http.StatusNotFound + if u.ID == "ana" { + want = reached + } + } else if scoped { want = tc.want } if got := call(tc.ctx, tc.ids); got != want { @@ -252,6 +263,9 @@ func TestOwnerIsToldTheProjectIsTrashed(t *testing.T) { func TestRouteScopeIsValidated(t *testing.T) { for _, r := range []route{ + {Pattern: "GET /admin", Scope: scopeUser}, + {Pattern: "GET /api/admin/accounts", Scope: scopeUser}, + {Pattern: "GET /api/me", Scope: scopeUser, Admin: true}, {Pattern: "GET /api/projects/{id}/files", Scope: scopeUser}, {Pattern: "GET /api/chats/{chat}/turns", Scope: scopeProject, Min: access.Owner}, {Pattern: "GET /api/projects/{id}/files", Scope: scopeProject}, // no role @@ -436,7 +450,7 @@ func TestRouteNeeds(t *testing.T) { } } } - if r.Scope != scopeUser { + if r.Scope != scopeUser || r.Admin { continue } needs := slices.Contains(want, r.Pattern) diff --git a/cmd/refract/users_cmd.go b/cmd/refract/users_cmd.go index 0b95a47..7a7d68a 100644 --- a/cmd/refract/users_cmd.go +++ b/cmd/refract/users_cmd.go @@ -3,17 +3,17 @@ package main import ( "cmp" "context" - "crypto/rand" + "encoding/json" "errors" "fmt" "io" - "maps" "os" "path/filepath" "slices" "github.com/ponytojas/Refract/internal/projects" "github.com/ponytojas/Refract/internal/store" + "github.com/ponytojas/Refract/internal/usage" "github.com/ponytojas/Refract/internal/users" ) @@ -23,12 +23,14 @@ const usersUsage = `usage: refract users signout end all of an account's sessions refract users unlock | --all let an account (or everyone) sign in again after too many failed attempts refract users remove [--yes] delete an account and everything it owns + refract users admin grant administrator access to a confirmed account + refract users report [since] show model usage and project disk space as JSON refract users list list accounts` // runUsers manages accounts on the server's own database (same // REFRACT_DATA_DIR and encryption key as the server). func runUsers(args []string, out io.Writer) error { - arity := map[string][]int{"list": {1}, "add": {2}, "rename": {3}, "signout": {2}, "unlock": {2}, "remove": {2, 3}} + arity := map[string][]int{"list": {1}, "add": {2}, "rename": {3}, "signout": {2}, "unlock": {2}, "remove": {2, 3}, "admin": {2}, "report": {2, 3}} if len(args) == 0 || !slices.Contains(arity[args[0]], len(args)) || args[0] == "remove" && len(args) == 3 && args[2] != "--yes" { return errors.New(usersUsage) } @@ -47,19 +49,20 @@ func runUsers(args []string, out io.Writer) error { defer db.Close() svc := &users.Service{DB: db, Key: key} ctx := context.Background() + projectsDir := filepath.Join(dataDir, "projects") switch args[0] { case "list": - all, err := svc.List(ctx) + all, err := svc.AdminAccounts(ctx) if err != nil { return err } - for _, email := range slices.Sorted(maps.Keys(all)) { + for _, a := range all { state := "password" - if !all[email] { + if !a.HasPassword { state = "no password" } - fmt.Fprintf(out, "%s\t%s\n", email, state) + fmt.Fprintf(out, "%s\t%s\n", a.Email, state) } case "rename": if err := svc.Rename(ctx, args[1], args[2]); err != nil { @@ -67,10 +70,14 @@ func runUsers(args []string, out io.Writer) error { } fmt.Fprintf(out, "%s is now %s, with all its projects and settings.\n", args[1], args[2]) case "signout": - if exists, err := svc.Exists(ctx, args[1]); err != nil || !exists { - return cmp.Or(err, fmt.Errorf("there is no account %q", args[1])) + acct, err := svc.Lookup(ctx, args[1]) + if errors.Is(err, users.ErrNoAccount) { + return fmt.Errorf("there is no account %q", args[1]) } - n, err := svc.SignOut(ctx, args[1]) + if err != nil { + return err + } + n, err := svc.SignOutAccount(ctx, acct.ID) if err != nil { return err } @@ -94,18 +101,38 @@ func runUsers(args []string, out io.Writer) error { } fmt.Fprintf(out, "%s can sign in again.\n", args[1]) case "remove": - return removeUser(ctx, svc, filepath.Join(dataDir, "projects"), args[1], len(args) == 3, out) + return removeUser(ctx, svc, projectsDir, args[1], len(args) == 3, out) + case "admin": + if err := svc.GrantAdmin(ctx, args[1]); err != nil { + return err + } + fmt.Fprintf(out, "Granted administrator access to %s.\n", args[1]) + case "report": + acct, err := svc.Lookup(ctx, args[1]) + if err != nil { + return err + } + raw := "0" + if len(args) == 3 { + raw = args[2] + } + since, err := usageStart(raw) + if err != nil { + return err + } + a := &adminAPI{users: svc, projects: &projects.Service{Dir: projectsDir}, usage: &usage.Recorder{DB: db}} + report, err := a.accountUsageAndStorage(ctx, acct.ID, since) + if err != nil { + return err + } + return json.NewEncoder(out).Encode(report) case "add": // A generated password: nothing to type into a shell history or a // terminal without echo control (docker exec without -t). - pw := rand.Text() - u, err := svc.SetPassword(ctx, args[1], pw) + u, pw, err := svc.ProvisionPassword(ctx, args[1], false) if err != nil { return err } - if err := svc.MarkVerified(ctx, u.ID); err != nil { // the operator vouches for the address - return err - } fmt.Fprintf(out, "%s can sign in with this password (change it in Settings → Account):\n\n %s\n\n", u.Email, pw) } return nil @@ -136,21 +163,14 @@ func removeUser(ctx context.Context, svc *users.Service, projectsDir, email stri } return fmt.Errorf("nothing was deleted: run again with --yes to confirm") } - n, err := svc.Remove(ctx, acct.ID, destroyer(&projects.Service{DB: svc.DB, Dir: projectsDir})) + ps := &projects.Service{DB: svc.DB, Dir: projectsDir} + n, err := svc.Remove(ctx, acct.ID, ps.DestroyOwnedProjects) if err != nil { + if n > 0 { + fmt.Fprintf(out, "Deleted %d projects before removal stopped. The account remains.\n", n) + } return err } fmt.Fprintf(out, "Deleted %s and %d projects.\n", acct.Email, n) return nil } - -// destroyer deletes a project for good, live or trashed; a project already -// gone (the daily purge) counts as deleted. No user in the context: any project. -func destroyer(ps *projects.Service) func(context.Context, string) error { - return func(ctx context.Context, id string) error { - if err := ps.Destroy(ctx, id); err != nil && !errors.Is(err, projects.ErrNotFound) { - return err - } - return nil - } -} diff --git a/internal/access/access.go b/internal/access/access.go index 55c3ddb..f4954b2 100644 --- a/internal/access/access.go +++ b/internal/access/access.go @@ -52,6 +52,21 @@ type Checker struct { SkipVerified bool } +// IsAdmin reads the role on each request, including after a role is granted +// or the account is removed by the CLI while Refract is running. +func (c *Checker) IsAdmin(ctx context.Context) (bool, error) { + u, err := UserFrom(ctx) + if err != nil { + return false, nil + } + var admin bool + err = c.DB.QueryRowContext(ctx, `SELECT is_admin = 1 AND email_verified_at > 0 FROM users WHERE id = ?`, u.ID).Scan(&admin) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + return admin, err +} + // ProjectRole is the user's role on the project; None when there is no user, // no such project, or the project is in the trash. func (c *Checker) ProjectRole(ctx context.Context, projectID string) (Role, error) { diff --git a/internal/projects/storage.go b/internal/projects/storage.go new file mode 100644 index 0000000..6759f95 --- /dev/null +++ b/internal/projects/storage.go @@ -0,0 +1,34 @@ +package projects + +import ( + "context" + "io/fs" + "path/filepath" +) + +// StorageBytes measures regular files in a project, including Git history +// and excluding generated build data. It never follows symbolic links. +func (s *Service) StorageBytes(ctx context.Context, id string) (int64, error) { + defer lockRepo(id)() + var bytes int64 + err := filepath.WalkDir(s.Path(id), func(_ string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + if err := ctx.Err(); err != nil { + return err + } + if entry.IsDir() && entry.Name() == ".refract" { + return filepath.SkipDir + } + if entry.Type().IsRegular() { + info, err := entry.Info() + if err != nil { + return err + } + bytes += info.Size() + } + return nil + }) + return bytes, err +} diff --git a/internal/projects/trash.go b/internal/projects/trash.go index 001f1f3..29f30f7 100644 --- a/internal/projects/trash.go +++ b/internal/projects/trash.go @@ -4,9 +4,11 @@ import ( "context" "database/sql" "errors" + "fmt" "log/slog" "os" "path/filepath" + "slices" "strings" "time" @@ -95,6 +97,35 @@ func (s *Service) Destroy(ctx context.Context, id string) error { return s.purge(ctx, id, "1 = 1") } +// DestroyOwnedProjects reserves every project before deleting any. It returns +// the number deleted even if later filesystem or database work fails. +func (s *Service) DestroyOwnedProjects(ctx context.Context, ids []string) (int, error) { + ordered := slices.Clone(ids) + slices.Sort(ordered) + for _, id := range ordered { + defer lockRemote(id)() + } + for _, id := range ordered { + release, ok := s.holdTurns(id) + if !ok { + return 0, fmt.Errorf("reserving project %s: %w", id, ErrTurnRunning) + } + defer release() + } + var deleted int + for _, id := range ids { + err := s.purgeReserved(ctx, id, "1 = 1") + if errors.Is(err, ErrNotFound) { + continue // a concurrent purge finished before we acquired the locks + } + if err != nil { + return deleted, fmt.Errorf("deleting project %s: %w", id, err) + } + deleted++ + } + return deleted, nil +} + // PurgeExpired deletes the projects that have been in the trash for more than // TrashDays, and returns how many. One failure doesn't stop the rest. func (s *Service) PurgeExpired(ctx context.Context) (int, error) { @@ -170,7 +201,10 @@ func (s *Service) purge(ctx context.Context, id, cond string, args ...any) error return ErrTurnRunning } defer release() + return s.purgeReserved(ctx, id, cond, args...) +} +func (s *Service) purgeReserved(ctx context.Context, id, cond string, args ...any) error { gone := filepath.Join(s.Dir, purgePrefix+id) err := func() error { defer lockRepo(id)() diff --git a/internal/store/store.go b/internal/store/store.go index 69cc386..5b53034 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -123,6 +123,8 @@ var migrations = []string{ ALTER TABLE sessions ADD COLUMN user_agent TEXT NOT NULL DEFAULT ''; ALTER TABLE sessions ADD COLUMN ip TEXT NOT NULL DEFAULT ''; UPDATE sessions SET created_at = expires_at - 2592000, last_seen_at = CAST(strftime('%s', 'now') AS INTEGER)`, + // Existing accounts keep their privileges. The operator grants this role explicitly. + `ALTER TABLE users ADD COLUMN is_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_admin IN (0, 1))`, } // Open opens (creating if needed) the database at path and applies pending migrations. diff --git a/internal/store/store_test.go b/internal/store/store_test.go index 756bfbf..b4f472b 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -511,6 +511,31 @@ func TestAccountMigrationVerifiesExistingUsers(t *testing.T) { } } +func TestAdminMigrationDoesNotPromoteExistingAccounts(t *testing.T) { + idx := slices.IndexFunc(migrations, func(m string) bool { return strings.Contains(m, "ADD COLUMN is_admin") }) + if idx < 0 { + t.Fatal("no administrator migration") + } + path := filepath.Join(t.TempDir(), "refract.db") + old := at(t, path, idx) + _, err := old.Exec(`INSERT INTO users (id, email, created_at, email_verified_at) VALUES + ('unverified', 'unverified@example.com', 1, 0), ('first', 'first@example.com', 2, 4), + ('second', 'second@example.com', 2, 3), ('third', 'third@example.com', 3, 3)`) + old.Close() + if err != nil { + t.Fatal(err) + } + db, err := Open(path) + if err != nil { + t.Fatal(err) + } + defer db.Close() + var count int + if err := db.QueryRow(`SELECT count(*) FROM users WHERE is_admin = 1`).Scan(&count); err != nil || count != 0 { + t.Fatalf("administrators = %d, %v; want none", count, err) + } +} + func TestSessionMigrationDatesExistingSessions(t *testing.T) { idx := slices.IndexFunc(migrations, func(m string) bool { return strings.Contains(m, "sessions ADD COLUMN last_seen_at") }) if idx < 0 { diff --git a/internal/usage/usage.go b/internal/usage/usage.go index 377ba28..6b98e16 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -4,9 +4,11 @@ package usage import ( + "cmp" "context" "database/sql" "log/slog" + "slices" "time" "github.com/ponytojas/Refract/internal/ai" @@ -58,6 +60,27 @@ type Totals struct { ReasoningTokens int `json:"reasoning_tokens"` } +type ModelTotals struct { + Model string `json:"model"` + Totals +} + +// Report orders the account's totals by tokens used, most used first. +func (r *Recorder) Report(ctx context.Context, userID string, since time.Time) ([]ModelTotals, error) { + totals, err := r.Since(ctx, userID, since) + if err != nil { + return nil, err + } + out := make([]ModelTotals, 0, len(totals)) + for model, t := range totals { + out = append(out, ModelTotals{model, t}) + } + slices.SortFunc(out, func(x, y ModelTotals) int { + return cmp.Or(cmp.Compare(y.InputTokens+y.OutputTokens, x.InputTokens+x.OutputTokens), cmp.Compare(x.Model, y.Model)) + }) + return out, nil +} + // Since returns a user's totals per model for the calls made at or after since. func (r *Recorder) Since(ctx context.Context, userID string, since time.Time) (map[string]Totals, error) { rows, err := r.DB.QueryContext(ctx, `SELECT model, count(*), sum(input_tokens), sum(cached_tokens), sum(output_tokens), sum(reasoning_tokens) diff --git a/internal/users/account_test.go b/internal/users/account_test.go index f4cc315..0db08d2 100644 --- a/internal/users/account_test.go +++ b/internal/users/account_test.go @@ -8,6 +8,8 @@ import ( "sync/atomic" "testing" "time" + + "github.com/ponytojas/Refract/internal/auth" ) func countUsers(t *testing.T, s *Service) (n int) { @@ -188,7 +190,7 @@ func TestConfirmByProvider(t *testing.T) { s, ctx := newService(t), context.Background() l, _ := s.SignUp(ctx, "ana@example.com", "attacker pass", "en") tok, _ := s.NewSession(ctx, l.To.ID) - if err := s.ConfirmByProvider(ctx, l.To.ID); err != nil { + if err := s.ConfirmByProvider(ctx, auth.User{ID: l.To.ID, Email: l.To.Email}); err != nil { t.Fatal(err) } a, _ := s.Lookup(ctx, "ana@example.com") @@ -205,7 +207,7 @@ func TestConfirmByProvider(t *testing.T) { // A verified account keeps everything. u, _ := s.SetPassword(ctx, "ben@example.com", "correct horse") tok, _ = s.NewSession(ctx, u.ID) - if err := s.ConfirmByProvider(ctx, u.ID); err != nil { + if err := s.ConfirmByProvider(ctx, u); err != nil { t.Fatal(err) } if _, err := s.Session(ctx, tok); err != nil { @@ -216,6 +218,63 @@ func TestConfirmByProvider(t *testing.T) { } } +func TestRenameInvalidatesEmailProofs(t *testing.T) { + s, ctx := newService(t), context.Background() + start, err := s.SignUp(ctx, "old@example.com", "fixture account password", "en") + if err != nil { + t.Fatal(err) + } + recovery, ok, err := s.RequestReset(ctx, start.To.Email) + if err != nil || !ok { + t.Fatalf("request recovery link: %t %v", ok, err) + } + session, err := s.NewSession(ctx, start.To.ID) + if err != nil { + t.Fatal(err) + } + if err := s.RenameAccount(ctx, start.To.ID, "new@example.com"); err != nil { + t.Fatal(err) + } + for _, link := range []Link{start, recovery} { + if _, err := s.tokenAccount(ctx, link.Token, link.Purpose); !errors.Is(err, ErrBadToken) { + t.Errorf("old %s link wasn't revoked: %v", link.Purpose, err) + } + } + if _, err := s.Session(ctx, session); err == nil { + t.Error("previous session survived the email change") + } + if _, ok, err := s.link(ctx, start.To, Reset); err != nil || ok { + t.Errorf("issued a link using the pre-rename account: %t %v", ok, err) + } + oldIdentity := auth.User{ID: start.To.ID, Email: start.To.Email} + if _, err := s.StartSessionFor(ctx, oldIdentity, Client{}); !errors.Is(err, ErrBadLogin) { + t.Errorf("session for the previous address: %v", err) + } + if err := s.ConfirmByProvider(ctx, oldIdentity); !errors.Is(err, ErrNoAccount) { + t.Errorf("confirmation for the previous address: %v", err) + } + if _, ok, err := s.RequestReset(ctx, "new@example.com"); err != nil || !ok { + t.Errorf("recovery link for the new address: %t %v", ok, err) + } +} + +func TestEmailChangeWhileCheckingPasswordPreventsSession(t *testing.T) { + s, ctx := newService(t), context.Background() + u, err := s.SetPassword(ctx, "old@example.com", "fixture account password") + if err != nil { + t.Fatal(err) + } + testHookPasswordChecked = func(id string) { + if err := s.RenameAccount(ctx, id, "new@example.com"); err != nil { + t.Error(err) + } + } + defer func() { testHookPasswordChecked = nil }() + if _, token, err := s.SignIn(ctx, u.Email, "fixture account password", Client{}); !errors.Is(err, ErrBadLogin) || token != "" { + t.Error("the in-flight sign-in for the old address was not refused") + } +} + func TestAllowMail(t *testing.T) { s, ctx := newService(t), context.Background() s.SetPassword(ctx, "ana@example.com", "correct horse") @@ -269,7 +328,7 @@ func TestSignInAfterTakeoverGetsNoSession(t *testing.T) { t.Cleanup(func() { testHookPasswordChecked = nil }) testHookPasswordChecked = func(id string) { - if err := s.ConfirmByProvider(ctx, id); err != nil { + if err := s.ConfirmByProvider(ctx, auth.User{ID: id, Email: l.To.Email}); err != nil { t.Error(err) } } @@ -319,7 +378,7 @@ func TestConfirmByProviderWipesWhatTheSquatterAttached(t *testing.T) { switch how { case "provider": - if err := s.ConfirmByProvider(ctx, id); err != nil { + if err := s.ConfirmByProvider(ctx, auth.User{ID: id, Email: l.To.Email}); err != nil { t.Fatal(err) } case "reset": diff --git a/internal/users/admin.go b/internal/users/admin.go new file mode 100644 index 0000000..1d187c8 --- /dev/null +++ b/internal/users/admin.go @@ -0,0 +1,175 @@ +package users + +import ( + "cmp" + "context" + "crypto/rand" + "database/sql" + "errors" + "fmt" + + "github.com/ponytojas/Refract/internal/auth" +) + +var ( + ErrAccountExists = errors.New("an account already has this email address") + ErrAdminEmail = errors.New("confirm the account's email address before granting administrator access") +) + +type AdminAccount struct { + ID string `json:"id"` + Email string `json:"email"` + HasPassword bool `json:"has_password"` + Verified bool `json:"email_verified"` + IsAdmin bool `json:"is_admin"` +} + +func (s *Service) AdminAccounts(ctx context.Context) ([]AdminAccount, error) { + rows, err := s.DB.QueryContext(ctx, `SELECT id, email, password != '', email_verified_at > 0, is_admin FROM users ORDER BY email`) + if err != nil { + return nil, err + } + defer rows.Close() + out := []AdminAccount{} + for rows.Next() { + var a AdminAccount + if err := rows.Scan(&a.ID, &a.Email, &a.HasPassword, &a.Verified, &a.IsAdmin); err != nil { + return nil, err + } + out = append(out, a) + } + return out, rows.Err() +} + +// GrantAdmin is reserved for the operator command. +func (s *Service) GrantAdmin(ctx context.Context, email string) error { + acct, err := s.Lookup(ctx, email) + if err != nil { + return err + } + if !acct.Verified { + return ErrAdminEmail + } + res, err := s.DB.ExecContext(ctx, `UPDATE users SET is_admin = 1 WHERE id = ? AND email_verified_at > 0`, acct.ID) + if err != nil { + return err + } + if n, err := res.RowsAffected(); err != nil || n == 0 { + return cmp.Or(err, ErrNoAccount) + } + return nil +} + +// ProvisionPassword creates a trusted account or resets an existing password. +// With onlyNew, an existing address is refused without changing its password. +func (s *Service) ProvisionPassword(ctx context.Context, email string, onlyNew bool) (auth.User, string, error) { + email = normEmail(email) + if err := validEmail(email); err != nil { + return auth.User{}, "", err + } + return s.issuePassword(ctx, email, "", onlyNew) +} + +func (s *Service) ResetAccountPassword(ctx context.Context, id string) (string, error) { + if id == "" { + return "", ErrNoAccount + } + _, password, err := s.issuePassword(ctx, "", id, false) + return password, err +} + +func (s *Service) issuePassword(ctx context.Context, email, id string, onlyNew bool) (auth.User, string, error) { + password := rand.Text() + hash, err := hashPassword(password) + if err != nil { + return auth.User{}, "", err + } + tx, err := s.DB.BeginTx(ctx, nil) + if err != nil { + return auth.User{}, "", err + } + defer tx.Rollback() + u := auth.User{ID: id, Email: email} + if id != "" { + err = tx.QueryRowContext(ctx, `SELECT email FROM users WHERE id = ?`, id).Scan(&u.Email) + if errors.Is(err, sql.ErrNoRows) { + return auth.User{}, "", ErrNoAccount + } + } else { + err = tx.QueryRowContext(ctx, `SELECT id FROM users WHERE email = ?`, email).Scan(&u.ID) + if errors.Is(err, sql.ErrNoRows) { + u, err = s.createTrusted(ctx, tx, email) + } else if err == nil && onlyNew { + return auth.User{}, "", ErrAccountExists + } + } + if err != nil { + return auth.User{}, "", err + } + if err := putPassword(ctx, tx, u.ID, hash); err != nil { + return auth.User{}, "", err + } + if err := s.markVerified(ctx, tx, u.ID); err != nil { + return auth.User{}, "", err + } + if err := tx.Commit(); err != nil { + return auth.User{}, "", err + } + return u, password, nil +} + +// RenameAccount changes the address of a particular account and revokes its +// sessions and links issued for the prior address in the same transaction. +func (s *Service) RenameAccount(ctx context.Context, id, to string) error { + to = normEmail(to) + if err := validEmail(to); err != nil { + return err + } + tx, err := s.DB.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var one int + err = tx.QueryRowContext(ctx, `SELECT 1 FROM users WHERE email = ?`, to).Scan(&one) + if err == nil { + return ErrAccountExists + } + if !errors.Is(err, sql.ErrNoRows) { + return err + } + res, err := tx.ExecContext(ctx, `UPDATE users SET email = ? WHERE id = ?`, to, id) + if err != nil { + return err + } + if n, err := res.RowsAffected(); err != nil || n == 0 { + return cmp.Or(err, ErrNoAccount) + } + if _, err := tx.ExecContext(ctx, `DELETE FROM account_tokens WHERE user_id = ?`, id); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, `DELETE FROM sessions WHERE user_id = ?`, id); err != nil { + return err + } + return tx.Commit() +} + +func (s *Service) SignOutAccount(ctx context.Context, id string) (int64, error) { + res, err := s.DB.ExecContext(ctx, `DELETE FROM sessions WHERE user_id = ?`, id) + if err != nil { + return 0, err + } + return res.RowsAffected() +} + +// Rename keeps the same account and data when changing its sign-in address. +func (s *Service) Rename(ctx context.Context, from, to string) error { + acct, err := s.Lookup(ctx, from) + if errors.Is(err, ErrNoAccount) { + return fmt.Errorf("there is no account %q", from) + } + if err != nil { + return err + } + return s.RenameAccount(ctx, acct.ID, to) +} diff --git a/internal/users/password.go b/internal/users/password.go index 5a3152d..b92f26b 100644 --- a/internal/users/password.go +++ b/internal/users/password.go @@ -117,15 +117,31 @@ func (s *Service) SetPassword(ctx context.Context, email, pw string) (auth.User, if err != nil { return auth.User{}, err } - if _, err := s.DB.ExecContext(ctx, `UPDATE users SET password = ? WHERE id = ?`, h, u.ID); err != nil { - return auth.User{}, err + tx, err := s.DB.BeginTx(ctx, nil) + if err != nil { + return u, err } - if _, err = s.DB.ExecContext(ctx, `DELETE FROM sessions WHERE user_id = ?`, u.ID); err != nil { + defer tx.Rollback() + if err := putPassword(ctx, tx, u.ID, h); err != nil { return u, err } + return u, tx.Commit() +} + +func putPassword(ctx context.Context, tx *sql.Tx, id, hash string) error { + res, err := tx.ExecContext(ctx, `UPDATE users SET password = ? WHERE id = ?`, hash, id) + if err != nil { + return err + } + if n, err := res.RowsAffected(); err != nil || n == 0 { + return cmp.Or(err, ErrNoAccount) + } + if _, err := tx.ExecContext(ctx, `DELETE FROM sessions WHERE user_id = ?`, id); err != nil { + return err + } // A link to choose a password is no longer wanted once one was chosen. - _, err = s.DB.ExecContext(ctx, `DELETE FROM account_tokens WHERE user_id = ? AND purpose = ?`, u.ID, Reset) - return u, err + _, err = tx.ExecContext(ctx, `DELETE FROM account_tokens WHERE user_id = ? AND purpose = ?`, id, Reset) + return err } // validEmail checks an already normalized address. @@ -169,7 +185,7 @@ func (s *Service) SignIn(ctx context.Context, email, pw string, c Client) (auth. if testHookPasswordChecked != nil { testHookPasswordChecked(u.ID) } - token, ok, err := s.newSession(ctx, u.ID, stored, c) + token, ok, err := s.newSession(ctx, u, stored, c) if err != nil { return auth.User{}, "", err } @@ -358,11 +374,14 @@ func ClientIP(r *http.Request) string { // SignOut ends every session of a user. func (s *Service) SignOut(ctx context.Context, email string) (int64, error) { - res, err := s.DB.ExecContext(ctx, `DELETE FROM sessions WHERE user_id = (SELECT id FROM users WHERE email = ?)`, normEmail(email)) + acct, err := s.Lookup(ctx, email) + if errors.Is(err, ErrNoAccount) { + return 0, nil + } if err != nil { return 0, err } - return res.RowsAffected() + return s.SignOutAccount(ctx, acct.ID) } // ErrOwnsProjects is returned when an account can't be removed because it still has projects. @@ -445,11 +464,11 @@ func (s *Service) OwnedCount(ctx context.Context, userID string) (n int, err err } // Remove deletes an account and everything it owns, and returns how many -// projects went. destroy deletes one project for good, live or in the trash, -// files included. It stops at the first project it can't delete, leaving the -// account and the rest in place. Then it removes the account as Delete does, +// projects went. destroy reserves and deletes the projects, live or in the +// trash. If deletion fails part way, the account remains and the count says +// how many projects went. Then it removes the account as Delete does, // refusing with ErrOwnsProjects if a project appeared meanwhile. -func (s *Service) Remove(ctx context.Context, userID string, destroy func(ctx context.Context, projectID string) error) (int, error) { +func (s *Service) Remove(ctx context.Context, userID string, destroy func(context.Context, []string) (int, error)) (int, error) { acct, err := s.AccountByID(ctx, userID) if err != nil { return 0, err @@ -458,40 +477,23 @@ func (s *Service) Remove(ctx context.Context, userID string, destroy func(ctx co if err != nil { return 0, err } - for i, p := range owned { - if err := destroy(ctx, p.ID); err != nil { - return i, fmt.Errorf("deleting project %s (%s): %w", p.Name, p.ID, err) - } + ids := make([]string, 0, len(owned)) + for _, p := range owned { + ids = append(ids, p.ID) + } + deleted, err := destroy(ctx, ids) + if err != nil { + return deleted, err } tx, err := s.DB.BeginTx(ctx, nil) if err != nil { - return len(owned), err + return deleted, err } defer tx.Rollback() if err := deleteAccount(ctx, tx, userID, acct.Email); err != nil { - return len(owned), err - } - return len(owned), tx.Commit() -} - -// Rename changes a user's email, keeping everything they own. Moving from -// REFRACT_AUTH=none to a sign-in mode is "rename local you@example.com". -func (s *Service) Rename(ctx context.Context, from, to string) error { - from, to = normEmail(from), normEmail(to) - if !strings.Contains(to, "@") || strings.ContainsAny(to, " \t\r\n") { - return fmt.Errorf("%q is not an email address", to) - } - if taken, err := s.Exists(ctx, to); err != nil || taken { - return cmp.Or(err, fmt.Errorf("%s already has an account", to)) - } - res, err := s.DB.ExecContext(ctx, `UPDATE users SET email = ? WHERE email = ?`, to, from) - if err != nil { - return err - } - if n, _ := res.RowsAffected(); n == 0 { - return fmt.Errorf("there is no account %q", from) + return deleted, err } - return nil + return deleted, tx.Commit() } // Exists reports whether a user with this email exists. @@ -503,21 +505,15 @@ func (s *Service) Exists(ctx context.Context, email string) (bool, error) { // List returns every user's email, and whether they have a password. func (s *Service) List(ctx context.Context) (map[string]bool, error) { - rows, err := s.DB.QueryContext(ctx, `SELECT email, password != '' FROM users ORDER BY email`) + accounts, err := s.AdminAccounts(ctx) if err != nil { return nil, err } - defer rows.Close() - out := map[string]bool{} - for rows.Next() { - var email string - var has bool - if err := rows.Scan(&email, &has); err != nil { - return nil, err - } - out[email] = has + out := make(map[string]bool, len(accounts)) + for _, a := range accounts { + out[a.Email] = a.HasPassword } - return out, rows.Err() + return out, nil } // sessionID is what the database keeps: a leaked database holds no usable cookies. diff --git a/internal/users/password_test.go b/internal/users/password_test.go index 2c063f3..d5c5dd7 100644 --- a/internal/users/password_test.go +++ b/internal/users/password_test.go @@ -322,16 +322,20 @@ func TestRemove(t *testing.T) { } var destroyed []string - del := func(ctx context.Context, id string) error { - destroyed = append(destroyed, id) - if id == "p2" && len(destroyed) == 2 && failSecond { - return errors.New("busy") + del := func(ctx context.Context, ids []string) (int, error) { + for i, id := range ids { + destroyed = append(destroyed, id) + if id == "p2" && len(destroyed) == 2 && failSecond { + return i, errors.New("deleting p2: busy") + } + if _, err := s.DB.ExecContext(ctx, `DELETE FROM projects WHERE id = ?`, id); err != nil { + return i, err + } } - _, err := s.DB.ExecContext(ctx, `DELETE FROM projects WHERE id = ?`, id) - return err + return len(ids), nil } failSecond = true - if n, err := s.Remove(ctx, u.ID, del); err == nil || !strings.Contains(err.Error(), "Beta") || n != 1 { + if n, err := s.Remove(ctx, u.ID, del); err == nil || !strings.Contains(err.Error(), "p2") || n != 1 { t.Fatalf("a failing destroy: n=%d err=%v; want an error naming the project", n, err) } if _, err := s.Lookup(ctx, "ana@example.com"); err != nil { @@ -363,7 +367,7 @@ func TestRemove(t *testing.T) { // An account with no projects goes at once; a project that appears // between listing and deleting stops it. - if n, err := s.Remove(ctx, other.ID, func(context.Context, string) error { return nil }); !errors.Is(err, ErrOwnsProjects) || n != 1 { + if n, err := s.Remove(ctx, other.ID, func(context.Context, []string) (int, error) { return 0, nil }); !errors.Is(err, ErrOwnsProjects) || n != 0 { t.Errorf("a destroy that left the project: n=%d, %v", n, err) } s.DB.Exec(`DELETE FROM projects`) diff --git a/internal/users/sessions.go b/internal/users/sessions.go index 66841f1..efa9e04 100644 --- a/internal/users/sessions.go +++ b/internal/users/sessions.go @@ -69,28 +69,40 @@ func (s *Service) NewSession(ctx context.Context, userID string) (string, error) // StartSession signs a user in from a client and returns the cookie's token. func (s *Service) StartSession(ctx context.Context, userID string, c Client) (string, error) { - token, _, err := s.newSession(ctx, userID, "", c) + return s.StartSessionFor(ctx, auth.User{ID: userID}, c) +} + +// StartSessionFor checks that the address the caller authenticated is still +// the account's address. +func (s *Service) StartSessionFor(ctx context.Context, u auth.User, c Client) (string, error) { + token, ok, err := s.newSession(ctx, u, "", c) + if err == nil && !ok { + err = ErrBadLogin + } return token, err } -// newSession creates a session for userID. With a non-empty password hash it -// does so only if that is still the account's password, in the same -// statement, and reports ok=false otherwise. -func (s *Service) newSession(ctx context.Context, userID, password string, c Client) (token string, ok bool, err error) { +// newSession checks the account and any non-empty email and password hash +// in the same statement that inserts the session. +func (s *Service) newSession(ctx context.Context, u auth.User, password string, c Client) (token string, ok bool, err error) { b := make([]byte, 32) rand.Read(b) token = base64.RawURLEncoding.EncodeToString(b) now := s.now() s.DB.ExecContext(ctx, `DELETE FROM sessions WHERE expires_at < ? OR last_seen_at < ?`, now.Unix(), now.Add(-SessionIdle).Unix()) res, err := s.DB.ExecContext(ctx, `INSERT INTO sessions (id, user_id, expires_at, authenticated_at, created_at, last_seen_at, user_agent, ip) - SELECT ?, ?, ?, ?, ?, ?, ?, ? WHERE ? = '' OR EXISTS (SELECT 1 FROM users WHERE id = ? AND password = ?)`, - sessionID(token), userID, now.Add(SessionTTL).Unix(), now.Unix(), now.Unix(), now.Unix(), c.UserAgent, c.IP, - password, userID, password) + SELECT ?, id, ?, ?, ?, ?, ?, ? FROM users + WHERE id = ? AND (? = '' OR email = ?) AND (? = '' OR password = ?)`, + sessionID(token), now.Add(SessionTTL).Unix(), now.Unix(), now.Unix(), now.Unix(), c.UserAgent, c.IP, + u.ID, u.Email, u.Email, password, password) if err != nil { return "", false, err } n, err := res.RowsAffected() - return token, n == 1, err + if n != 1 || err != nil { + return "", false, err + } + return token, true, nil } // Session returns the user a session token belongs to, if the session is diff --git a/internal/users/tokens.go b/internal/users/tokens.go index c32539a..79a18f7 100644 --- a/internal/users/tokens.go +++ b/internal/users/tokens.go @@ -181,11 +181,21 @@ func (s *Service) link(ctx context.Context, a Account, p Purpose) (Link, bool, e return Link{}, false, err } defer tx.Rollback() + current, err := scanAccount(tx.QueryRowContext(ctx, accountColumns+` WHERE id = ? AND email = ?`, a.ID, a.Email)) + if errors.Is(err, ErrNoAccount) { + return Link{}, false, nil + } + if err != nil { + return Link{}, false, err + } + if p == Verify && current.Verified { + return Link{}, false, nil + } tok, err := s.issue(ctx, tx, a.ID, p) if err != nil { return Link{}, false, err } - return Link{To: a, Purpose: p, Token: tok}, true, tx.Commit() + return Link{To: current, Purpose: p, Token: tok}, true, tx.Commit() } // ResetPassword validates pw and the token (without using it), hashes pw, then @@ -269,16 +279,19 @@ func (s *Service) VerifyEmail(ctx context.Context, token, signedInAs, pw, ip str // an account that was never verified: someone may have signed up for an address // that isn't theirs, so everything that account holds goes (see clearUnverified) // and it becomes verified. No-op for a verified account. -func (s *Service) ConfirmByProvider(ctx context.Context, userID string) error { +func (s *Service) ConfirmByProvider(ctx context.Context, u auth.User) error { tx, err := s.DB.BeginTx(ctx, nil) if err != nil { return err } defer tx.Rollback() - if err := clearUnverified(ctx, tx, userID); err != nil { + if _, err := scanAccount(tx.QueryRowContext(ctx, accountColumns+` WHERE id = ? AND email = ?`, u.ID, u.Email)); err != nil { + return err + } + if err := clearUnverified(ctx, tx, u.ID); err != nil { return err } - if err := s.markVerified(ctx, tx, userID); err != nil { + if err := s.markVerified(ctx, tx, u.ID); err != nil { return err } return tx.Commit() diff --git a/internal/users/users.go b/internal/users/users.go index 5c658ec..5be1db8 100644 --- a/internal/users/users.go +++ b/internal/users/users.go @@ -65,21 +65,9 @@ func (s *Service) resolve(ctx context.Context, email string) (auth.User, string, defer tx.Rollback() err = tx.QueryRowContext(ctx, `SELECT id, lang FROM users WHERE email = ?`, email).Scan(&u.ID, &lang) if errors.Is(err, sql.ErrNoRows) { - var n int - if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM users`).Scan(&n); err != nil { - return auth.User{}, "", err - } - u.ID = newID() - at := s.now().Unix() - if _, err := tx.ExecContext(ctx, `INSERT INTO users (id, email, created_at, email_verified_at) VALUES (?, ?, ?, ?)`, u.ID, email, at, at); err != nil { - return auth.User{}, "", err - } - if n == 0 { - if err := s.adopt(ctx, tx, u.ID); err != nil { - return auth.User{}, "", err - } - } - } else if err != nil { + u, err = s.createTrusted(ctx, tx, email) + } + if err != nil { return auth.User{}, "", err } if err := tx.Commit(); err != nil { @@ -88,6 +76,27 @@ func (s *Service) resolve(ctx context.Context, email string) (auth.User, string, return u, lang, nil } +// Only the trusted creation path can bootstrap an administrator. An open +// self-sign-up uses its own insert and never grants this role. +func (s *Service) createTrusted(ctx context.Context, tx *sql.Tx, email string) (auth.User, error) { + var n int + if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM users`).Scan(&n); err != nil { + return auth.User{}, err + } + u := auth.User{ID: newID(), Email: email} + at := s.now().Unix() + if _, err := tx.ExecContext(ctx, `INSERT INTO users (id, email, created_at, email_verified_at, is_admin) + VALUES (?, ?, ?, ?, ?)`, u.ID, email, at, max(at, 1), n == 0); err != nil { + return auth.User{}, err + } + if n == 0 { + if err := s.adopt(ctx, tx, u.ID); err != nil { + return auth.User{}, err + } + } + return u, nil +} + func (s *Service) adopt(ctx context.Context, tx *sql.Tx, id string) error { if _, err := tx.ExecContext(ctx, `UPDATE projects SET owner = ? WHERE owner = ''`, id); err != nil { return err diff --git a/web/e2e/admin.spec.ts b/web/e2e/admin.spec.ts new file mode 100644 index 0000000..6720200 --- /dev/null +++ b/web/e2e/admin.spec.ts @@ -0,0 +1,29 @@ +import { expect, test } from '@playwright/test' + +test('an administrator can create and remove a member through the account page', async ({ page }) => { + await page.addInitScript(() => localStorage.setItem('refract-prefs', JSON.stringify({ language: 'en' }))) + await page.goto('/') + await page.getByRole('button', { name: 'Account menu', exact: true }).click() + await page.getByRole('menuitem', { name: 'Account administration', exact: true }).click() + await expect(page).toHaveURL(/\/admin$/) + await expect(page.getByRole('heading', { name: 'Account administration', level: 1 })).toBeVisible() + + const email = 'browser-admin-fixture@example.com' + await page.getByRole('button', { name: 'Add account', exact: true }).click() + const dialog = page.getByRole('alertdialog') + await dialog.getByLabel('Email', { exact: true }).fill(email) + await dialog.getByRole('button', { name: 'Add account', exact: true }).click() + await expect(dialog.getByRole('heading', { name: 'Generated password' })).toBeVisible() + await dialog.getByRole('button', { name: 'Done', exact: true }).click() + + const member = page.getByRole('button', { name: email, exact: true }) + await member.click() + await expect(page.getByRole('heading', { name: email, exact: true })).toBeVisible() + await expect(page.getByRole('heading', { name: 'Project disk space' })).toBeVisible() + await page.getByRole('button', { name: 'Delete account', exact: true }).click() + await dialog.getByRole('button', { name: 'Cancel', exact: true }).click() + await expect(member).toBeVisible() + await page.getByRole('button', { name: 'Delete account', exact: true }).click() + await dialog.getByRole('button', { name: 'Delete account', exact: true }).click() + await expect(member).toHaveCount(0) +}) diff --git a/web/src/Admin.tsx b/web/src/Admin.tsx new file mode 100644 index 0000000..c0a06ae --- /dev/null +++ b/web/src/Admin.tsx @@ -0,0 +1,378 @@ +import { useEffect, useState, type FormEvent } from 'react' +import { ArrowLeft, Loader2 } from 'lucide-react' +import { toast } from 'sonner' +import { api, errorText, RequestError, type ModelUsage } from '@/api' +import { useMe } from '@/components/AccountMenu' +import { Badge } from '@/components/ui/badge' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { + AlertDialog, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@/components/ui/alert-dialog' +import { lang, t } from '@/lib/i18n' +import { Link, pageReady, reloadTo } from '@/lib/router' +import { monthStart, totalTokens } from '@/lib/usage' + +const accountsURL = '/api/admin/accounts' + +type Account = { id: string; email: string; has_password: boolean; email_verified: boolean; is_admin: boolean } +type Report = { models: ModelUsage[]; projects: { id: string; name: string; trashed: boolean; bytes: number }[] } +type AccountAction = 'rename' | 'reset' | 'signout' | 'unlock' | 'remove' +type Action = + | { kind: AccountAction; account: Account } + | { kind: 'add'; account?: never } + | { kind: 'unlock_all'; account?: never } + +const accountActionLabels = { + rename: () => t('Change email'), + reset: () => t('Reset password'), + signout: () => t('Sign out everywhere'), + unlock: () => t('Clear lockout'), + remove: () => t('Delete account'), +} + +const actionDescriptions = { + rename: (email: string) => + t('Change the sign-in address for {email} and revoke their Refract sessions and email links.', { email }), + reset: (email: string) => t('Generate a new password for {email} and end all of their Refract sessions.', { email }), + signout: (email: string) => t('End all Refract sessions for {email}.', { email }), + unlock: (email: string) => t('Clear failed sign-in attempts for {email}.', { email }), + remove: (email: string) => + t('Permanently delete {email}, their projects, history, chats and connections.', { email }), +} + +export default function Admin() { + const me = useMe() + const [accounts, setAccounts] = useState(null) + const [loadError, setLoadError] = useState('') + const [version, setVersion] = useState(0) + const [selected, setSelected] = useState('') + const [action, setAction] = useState(null) + const account = accounts?.find((a) => a.id === selected) ?? accounts?.[0] + + useEffect(() => { + const controller = new AbortController() + api(accountsURL, { signal: controller.signal }) + .then((items) => { + setAccounts(items) + setLoadError('') + }) + .catch((error) => { + if (controller.signal.aborted) return + setAccounts(null) + setLoadError( + error instanceof RequestError && error.status === 404 ? t('Page not found') : t('Could not load accounts.'), + ) + }) + .finally(() => { + if (!controller.signal.aborted) pageReady() + }) + return () => controller.abort() + }, [version]) + + return ( +
+
+ +
+ {action && ( + setAction(null)} + refresh={() => setVersion((n) => n + 1)} + /> + )} +
+ ) +} + +function AccountReport({ id }: { id: string }) { + const [report, setReport] = useState(null) + const [failed, setFailed] = useState(false) + useEffect(() => { + const controller = new AbortController() + const query = new URLSearchParams({ id, since: String(monthStart(new Date())) }) + api(`${accountsURL}/report?${query}`, { signal: controller.signal }).then(setReport, () => { + if (!controller.signal.aborted) setFailed(true) + }) + return () => controller.abort() + }, [id]) + + if (!report) { + return ( +

+ {failed ? t('Could not load account usage and storage.') : t('Loading…')} +

+ ) + } + const number = new Intl.NumberFormat(lang) + return ( +
+
+

{t('Usage this month')}

+ {report.models.length ? ( +
+ {report.models.map((u) => ( +
+
{u.model}
+
+ {t('{count} tokens', { count: number.format(totalTokens(u)) })} +
+
+ ))} +
+ ) : ( +

{t('No AI requests this month.')}

+ )} +
+
+

{t('Project disk space')}

+ {report.projects.length ? ( +
+ {report.projects.map((p) => ( +
+
+ {p.name} + {p.trashed && ( + + {t('In the trash')} + + )} +
+
{t('{count} bytes', { count: number.format(p.bytes) })}
+
+ ))} +
+ ) : ( +

{t('This account has no projects.')}

+ )} +
+
+ ) +} + +function ActionDialog({ + action, + self, + close, + refresh, +}: { + action: Action + self: boolean + close: () => void + refresh: () => void +}) { + const [email, setEmail] = useState('') + const [busy, setBusy] = useState(false) + const [password, setPassword] = useState('') + const needsEmail = action.kind === 'rename' || action.kind === 'add' + const title = + action.kind === 'add' + ? t('Add account') + : action.kind === 'unlock_all' + ? t('Clear all lockouts') + : accountActionLabels[action.kind]() + const description = + action.kind === 'add' + ? t('Create an account and generate its first password.') + : action.kind === 'unlock_all' + ? t('Clear failed sign-in attempts for every account and network address.') + : actionDescriptions[action.kind](action.account.email) + + function done() { + setPassword('') + close() + if ( + self && + (action.kind === 'remove' || action.kind === 'signout' || action.kind === 'reset' || action.kind === 'rename') + ) { + void reloadTo('/') + return + } + refresh() + } + + async function copyPassword() { + try { + await navigator.clipboard.writeText(password) + toast.success(t('Password copied.')) + } catch { + toast.error(t('Could not copy the password. Select it to copy it manually.')) + } + } + + async function submit(event: FormEvent) { + event.preventDefault() + setBusy(true) + try { + const result = await api<{ password?: string }>(accountsURL, { + method: 'POST', + body: { action: action.kind, id: action.account?.id, email, confirmed: true }, + }) + if (result.password) { + setPassword(result.password) + } else { + toast.success(t('Account administration action completed.')) + done() + } + } catch (error) { + const kind = error instanceof RequestError ? error.error.kind : '' + if (kind === 'account_removal_partial') { + toast.error(errorText(error)) + close() + refresh() + return + } + const message = + kind === 'admin_account_exists' + ? t('An account already has this email address.') + : kind === 'admin_invalid_email' + ? t('Enter a valid email address.') + : kind === 'admin_account_busy' + ? t('The account’s projects are changing. Try again when they are ready.') + : t('Could not complete this action.') + toast.error(message) + } finally { + setBusy(false) + } + } + + return ( + { + if (!open && !busy) { + if (password) done() + else close() + } + }} + > + + {password ? ( + <> + + {t('Generated password')} + + {t('Copy this password before closing. Share it privately with the account holder.')} + + + e.currentTarget.select()} + /> + + + + + + ) : ( +
+ + {title} + {description} + + {needsEmail && ( + + )} + + {t('Cancel')} + + +
+ )} +
+
+ ) +} diff --git a/web/src/App.tsx b/web/src/App.tsx index 5922cf2..f0014a4 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -17,6 +17,7 @@ import { FolderOpen, Keyboard, Monitor, Moon, Settings, Sun } from 'lucide-react // on its own, so the project list (and sign-in) open quickly. const loadWorkspace = () => import('./Workspace') const Workspace = lazy(loadWorkspace) +const Admin = lazy(() => import('./Admin')) import { navigate, usePath } from '@/lib/router' export default function App() { @@ -123,6 +124,10 @@ export default function App() { + ) : path === '/admin' ? ( + + + ) : ( )} diff --git a/web/src/Settings.tsx b/web/src/Settings.tsx index c9c13df..cbb86d9 100644 --- a/web/src/Settings.tsx +++ b/web/src/Settings.tsx @@ -603,7 +603,8 @@ function DeleteGroup({ reloadTo('/?account_deleted=1') } catch (err) { toast.error(errorText(err)) - if (err instanceof RequestError && err.error.kind === 'reauth_required') reload() + if (err instanceof RequestError && ['reauth_required', 'account_removal_partial'].includes(err.error.kind)) + reload() setBusy(false) } } diff --git a/web/src/api.ts b/web/src/api.ts index 8485366..879dabc 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -1,11 +1,11 @@ -import { lang, t } from '@/lib/i18n' +import { lang, t, tn } from '@/lib/i18n' import { chatgptOffered } from '@/lib/mode' // Every /api call carries X-Refract (the server rejects requests without it: CSRF), // and the interface language, which the server uses for the emails it sends. const headers = { 'X-Refract': '1', 'X-Refract-Lang': lang } -export type ApiError = { kind: string; message: string; code?: string; param?: string } +export type ApiError = { kind: string; message: string; code?: string; param?: string; removed_projects?: number } export class RequestError extends Error { constructor( @@ -176,6 +176,12 @@ export function describe(e: ApiError): string { return t('This link has expired or was already used.') case 'password_required': return t('Enter your password to continue.') + case 'account_removal_partial': + return tn( + e.removed_projects ?? 0, + 'One project was permanently deleted before removal stopped. The account still exists.', + '{n} projects were permanently deleted before removal stopped. The account still exists.', + ) case 'reauth_required': return t('For your security, sign in again, then delete your account within 10 minutes.') case 'compile_busy': diff --git a/web/src/components/AccountMenu.tsx b/web/src/components/AccountMenu.tsx index 1f7da49..1b87dd5 100644 --- a/web/src/components/AccountMenu.tsx +++ b/web/src/components/AccountMenu.tsx @@ -9,6 +9,7 @@ import { Monitor, Moon, Settings, + Shield, Sun, } from 'lucide-react' import { @@ -31,7 +32,7 @@ import { lang, t } from '@/lib/i18n' import { allowanceLeft, compact, modelLabel, ownUsage, renewalDate, totalTokens } from '@/lib/usage' import { useMonthUsage } from './useMonthUsage' import { chatgptOffered } from '@/lib/mode' -import { reloadTo } from '@/lib/router' +import { Link, reloadTo } from '@/lib/router' const themes: { value: Theme; label: string; icon: typeof Sun }[] = [ { value: 'light', label: t('Light'), icon: Sun }, @@ -40,7 +41,7 @@ const themes: { value: Theme; label: string; icon: typeof Sun }[] = [ ] // Bottom-left account chip: ChatGPT identity, settings, theme. -type Me = { id: string; email: string; can_sign_out: boolean } +type Me = { id: string; email: string; can_sign_out: boolean; is_admin: boolean } let mePromise: Promise | null = null export function useMe() { const [me, setMe] = useState(null) @@ -115,6 +116,11 @@ export default function AccountMenu({ status, compact }: { status: ChatGPTStatus openSettings()}> {t('Settings')} + {me?.is_admin && ( + }> + {t('Account administration')} + + )} {status?.status.signed_in && ( }> {t('Manage ChatGPT usage')} diff --git a/web/src/locales/es/admin.ts b/web/src/locales/es/admin.ts new file mode 100644 index 0000000..2fa5f3c --- /dev/null +++ b/web/src/locales/es/admin.ts @@ -0,0 +1,50 @@ +export default { + 'Account administration': 'Administración de cuentas', + Accounts: 'Cuentas', + Administrator: 'Administrador', + 'Add account': 'Añadir cuenta', + 'Change email': 'Cambiar el correo', + 'Reset password': 'Restablecer contraseña', + 'Sign out everywhere': 'Cerrar todas las sesiones', + 'Clear lockout': 'Desbloquear cuenta', + 'Clear all lockouts': 'Quitar todos los bloqueos', + 'Password set': 'Con contraseña', + 'No password': 'Sin contraseña', + 'Page not found': 'Página no encontrada', + 'Could not load accounts.': 'No se pudieron cargar las cuentas.', + 'Could not load account usage and storage.': 'No se pudieron cargar el uso y el almacenamiento de la cuenta.', + 'Project disk space': 'Espacio en disco por proyecto', + 'In the trash': 'En la papelera', + '{count} tokens': '{count} tokens', + '{count} bytes': '{count} bytes', + 'This account has no projects.': 'Esta cuenta no tiene proyectos.', + 'Change the sign-in address for {email} and revoke their Refract sessions and email links.': + 'Cambia la dirección de inicio de sesión de {email} e invalida sus sesiones de Refract y enlaces enviados por correo.', + 'Generate a new password for {email} and end all of their Refract sessions.': + 'Genera una contraseña nueva para {email} y cierra todas sus sesiones de Refract.', + 'End all Refract sessions for {email}.': 'Cierra todas las sesiones de Refract de {email}.', + 'Clear failed sign-in attempts for {email}.': 'Borra los intentos de inicio de sesión fallidos de {email}.', + 'Permanently delete {email}, their projects, history, chats and connections.': + 'Elimina de forma permanente la cuenta de {email}, sus proyectos, historial, conversaciones y conexiones.', + 'Create an account and generate its first password.': 'Crea una cuenta y genera su primera contraseña.', + 'Clear failed sign-in attempts for every account and network address.': + 'Borra los intentos de inicio de sesión fallidos de todas las cuentas y direcciones de red.', + 'Account administration action completed.': 'La operación se completó.', + 'An account already has this email address.': 'Ya hay una cuenta con esta dirección de correo.', + 'Enter a valid email address.': 'Introduce una dirección de correo válida.', + 'The account’s projects are changing. Try again when they are ready.': + 'Los proyectos de la cuenta están cambiando. Inténtalo cuando estén listos.', + 'Could not complete this action.': 'No se pudo completar esta operación.', + 'One project was permanently deleted before removal stopped. The account still exists.': + 'Se eliminó un proyecto de forma permanente antes de que se interrumpiera el borrado. La cuenta sigue existiendo.', + '{n} projects were permanently deleted before removal stopped. The account still exists.': + 'Se eliminaron {n} proyectos de forma permanente antes de que se interrumpiera el borrado. La cuenta sigue existiendo.', + 'Generated password': 'Contraseña generada', + 'Copy this password before closing. Share it privately with the account holder.': + 'Copia esta contraseña antes de cerrar. Compártela en privado con la persona titular de la cuenta.', + 'Password copied.': 'Contraseña copiada.', + 'Could not copy the password. Select it to copy it manually.': + 'No se pudo copiar la contraseña. Selecciónala para copiarla manualmente.', + 'Copy password': 'Copiar contraseña', + Done: 'Listo', +} as Record diff --git a/web/src/locales/es/index.ts b/web/src/locales/es/index.ts index 9766a51..38d6f6c 100644 --- a/web/src/locales/es/index.ts +++ b/web/src/locales/es/index.ts @@ -7,6 +7,7 @@ import ui from './ui' import workspace from './workspace' import templates from './templates' import citations from './citations' +import admin from './admin' export default { ...ui, @@ -18,4 +19,5 @@ export default { ...completion, ...citations, ...templates, + ...admin, }