Storage. The server keeps its data in SQLite (a file in the data directory, the default) or PostgreSQL (database, KEEPORG_DATABASE_URL or -database). Every row, the KDBX versions included, is sealed with AES-256-GCM under a key derived from the master key and named by an HMAC. The master key is required to start and a different one is refused. A data directory from 0.10 or earlier is imported on first start. Several servers may share one PostgreSQL database. Go goes to 1.26 for the pure-Go drivers (modernc.org/sqlite, jackc/pgx). Hardening, after an audit of the server, both clients and the deployment: - Single sign-on approves a device only after an explicit Approve in the browser that started it, bound by a cookie and PKCE; identities are never linked by username, by verified email only when allowed, never to admins. - Sign-in attempts are limited per address and per account, passwords are checked outside the store lock with uniform timing, one-time codes work once, and starting two-factor needs the password. - Merge vaults bound KDF parameters, payload size and XML shape, check pushes before storing them, and run at most two merges at once. A version is written in the same transaction as its metadata. - Tokens in URLs only on the event stream, which ends on revocation; CSP, frame-ancestors, no-store and HSTS; sign-in CSRF; 404 for databases without access; new trusted_proxies. - Clients open only the server's approval page, keep case-variant and retired file names apart, never overwrite a save made during a pull, require https except locally, send the stream token in a header, bound their reads and escape notifications and terminal output. - The .deb creates the master key, systemd is sandboxed further, nginx sets modern TLS and HSTS, and CI deploys from main only. Server 0.12.0, desktop 0.6.0, Android 0.4.0 (versionCode 4). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
375 lines
13 KiB
Go
375 lines
13 KiB
Go
package server
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"html/template"
|
|
"net/http"
|
|
"net/url"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"cc.tiredsysadmin.keeporg/internal/store"
|
|
"cc.tiredsysadmin.keeporg/internal/totp"
|
|
)
|
|
|
|
// The settings page at /web/account: who you are, how you sign in, and every
|
|
// device and browser signed in as you, each of which can be signed out from
|
|
// here. The rules are the functions in account.go, shared with the API.
|
|
|
|
// webAccount is what the settings page shows.
|
|
type webAccount struct {
|
|
Username string
|
|
Email string
|
|
ServerAdmin bool
|
|
Since string
|
|
Groups []webMembership
|
|
HasPassword bool
|
|
SSO string // the identity provider's host, when linked
|
|
TOTPOn bool
|
|
// TOTPKey and TOTPLink are set while an enrolment awaits its first code.
|
|
TOTPKey string
|
|
TOTPLink template.URL
|
|
Sessions []webSessionRow
|
|
// SSOLink starts linking single sign-on to this account, when the
|
|
// server has a provider and the account is not linked yet.
|
|
SSOLink string
|
|
}
|
|
|
|
type webMembership struct {
|
|
Name string
|
|
Role string
|
|
}
|
|
|
|
type webSessionRow struct {
|
|
ID string
|
|
Label string
|
|
Browser bool
|
|
Current bool
|
|
Created string
|
|
LastSeen string
|
|
Expires string
|
|
}
|
|
|
|
func (s *Server) accountView(sess *webSession) webAccount {
|
|
var v webAccount
|
|
s.st.Read(func(st *store.State) {
|
|
u := st.Users[sess.user.ID]
|
|
if u == nil {
|
|
return
|
|
}
|
|
v = webAccount{
|
|
Username: u.Username, Email: u.Email, ServerAdmin: u.ServerAdmin,
|
|
Since: u.CreatedAt.UTC().Format("2006-01-02"),
|
|
HasPassword: u.PassHash != "", TOTPOn: u.TOTPConfirmed,
|
|
}
|
|
if s.oidc != nil && u.OIDCSubject == "" && !u.Disabled {
|
|
v.SSOLink = "/oidc/login?link=1&csrf=" + url.QueryEscape(sess.csrf)
|
|
}
|
|
if u.OIDCIssuer != "" {
|
|
v.SSO = u.OIDCIssuer
|
|
if iss, err := url.Parse(u.OIDCIssuer); err == nil && iss.Host != "" {
|
|
v.SSO = iss.Host
|
|
}
|
|
}
|
|
if u.TOTPSecret != "" && !u.TOTPConfirmed {
|
|
v.TOTPKey = groupKey(u.TOTPSecret)
|
|
// The otpauth: scheme is what authenticator apps register for;
|
|
// html/template would neutralise it, and the URI is built here
|
|
// from our own values.
|
|
v.TOTPLink = template.URL(totp.URI("KeepOrg", u.Username, u.TOTPSecret))
|
|
}
|
|
for _, m := range st.Memberships {
|
|
if m.UserID != u.ID {
|
|
continue
|
|
}
|
|
if g := st.Groups[m.GroupID]; g != nil {
|
|
v.Groups = append(v.Groups, webMembership{Name: g.Name, Role: string(m.Role)})
|
|
}
|
|
}
|
|
sort.Slice(v.Groups, func(i, j int) bool { return v.Groups[i].Name < v.Groups[j].Name })
|
|
for _, sv := range sessionsOf(st, u.ID, sess.token) {
|
|
v.Sessions = append(v.Sessions, webSessionRow{
|
|
ID: sv.ID, Label: sv.Label, Browser: sv.Browser, Current: sv.Current,
|
|
Created: sv.CreatedAt.UTC().Format("2006-01-02 15:04 UTC"),
|
|
LastSeen: ago(sv.LastSeenAt),
|
|
Expires: sv.ExpiresAt.UTC().Format("2006-01-02"),
|
|
})
|
|
}
|
|
})
|
|
return v
|
|
}
|
|
|
|
// groupKey spaces a base32 secret in fours, for typing into an app by hand.
|
|
func groupKey(k string) string {
|
|
var b strings.Builder
|
|
for i, r := range k {
|
|
if i > 0 && i%4 == 0 {
|
|
b.WriteByte(' ')
|
|
}
|
|
b.WriteRune(r)
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
// ago says how long ago t was, coarsely.
|
|
func ago(t time.Time) string {
|
|
d := time.Since(t)
|
|
switch {
|
|
case d < 2*time.Minute:
|
|
return "just now"
|
|
case d < time.Hour:
|
|
return fmt.Sprintf("%d minutes ago", int(d.Minutes()))
|
|
case d < 2*time.Hour:
|
|
return "an hour ago"
|
|
case d < 24*time.Hour:
|
|
return fmt.Sprintf("%d hours ago", int(d.Hours()))
|
|
case d < 48*time.Hour:
|
|
return "yesterday"
|
|
case d < 30*24*time.Hour:
|
|
return fmt.Sprintf("%d days ago", int(d.Hours()/24))
|
|
}
|
|
return t.UTC().Format("2006-01-02")
|
|
}
|
|
|
|
func (s *Server) handleWebAccount(w http.ResponseWriter, r *http.Request, sess *webSession) {
|
|
s.renderAccount(w, sess, "", "")
|
|
}
|
|
|
|
// handleWebAccountAction applies one control of the settings page.
|
|
func (s *Server) handleWebAccountAction(w http.ResponseWriter, r *http.Request, sess *webSession) {
|
|
var notice string
|
|
// Changes that need the password and code are proven outside the
|
|
// store's lock, then applied inside it.
|
|
switch r.FormValue("action") {
|
|
case "password", "totp-begin", "totp-disable":
|
|
err := s.accountReconfirmed(r, sess, ¬ice)
|
|
s.finishAccountAction(w, r, sess, err, notice)
|
|
return
|
|
}
|
|
err := s.st.Update(func(st *store.State) error {
|
|
switch r.FormValue("action") {
|
|
case "revoke":
|
|
if err := revokeSession(st, sess.user.ID, r.FormValue("session")); err != nil {
|
|
return err
|
|
}
|
|
notice = "That device is signed out. It has to sign in again to sync."
|
|
case "revoke-others":
|
|
n := revokeOtherSessions(st, sess.user.ID, sess.token)
|
|
notice = fmt.Sprintf("Signed out %d other %s.", n, plural(n, "session", "sessions"))
|
|
case "totp-confirm":
|
|
if err := confirmTOTP(st, sess.user.ID, r.FormValue("code")); err != nil {
|
|
return err
|
|
}
|
|
notice = "Two-factor authentication is on. Signing in now asks for a one-time code."
|
|
case "totp-cancel":
|
|
cancelTOTP(st, sess.user.ID)
|
|
notice = "Setup cancelled. Nothing changed."
|
|
default:
|
|
return errBadAction
|
|
}
|
|
return nil
|
|
})
|
|
s.finishAccountAction(w, r, sess, err, notice)
|
|
}
|
|
|
|
// accountReconfirmed applies the settings changes that need the password,
|
|
// and the one-time code when one is on.
|
|
func (s *Server) accountReconfirmed(r *http.Request, sess *webSession, notice *string) error {
|
|
switch r.FormValue("action") {
|
|
case "password":
|
|
next := r.FormValue("new_password")
|
|
if next != r.FormValue("new_password2") {
|
|
return errors.New("the two new passwords do not match")
|
|
}
|
|
if err := s.changePassword(r, sess.user, r.FormValue("current_password"),
|
|
r.FormValue("totp"), next, sess.token); err != nil {
|
|
return err
|
|
}
|
|
*notice = "Password changed. Your other sessions were signed out."
|
|
case "totp-begin":
|
|
if err := s.reconfirm(r, sess.user, r.FormValue("password"), r.FormValue("totp"),
|
|
func(st *store.State, u *store.User) error { _, err := beginTOTP(st, u.ID); return err }); err != nil {
|
|
return err
|
|
}
|
|
*notice = "Add the key below to your authenticator app, then enter the code it shows."
|
|
case "totp-disable":
|
|
if err := s.reconfirm(r, sess.user, r.FormValue("password"), r.FormValue("totp"),
|
|
func(st *store.State, u *store.User) error { return disableTOTP(st, u.ID) }); err != nil {
|
|
return err
|
|
}
|
|
*notice = "Two-factor authentication is off."
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Server) finishAccountAction(w http.ResponseWriter, r *http.Request, sess *webSession, err error, notice string) {
|
|
if err != nil {
|
|
s.renderAccount(w, sess, accountError(err), "")
|
|
return
|
|
}
|
|
// Signing out one's own browser from the list ends this session too.
|
|
if s.webUser(r) == nil {
|
|
s.setWebCookie(w, "", -time.Second)
|
|
http.Redirect(w, r, "/web", http.StatusFound)
|
|
return
|
|
}
|
|
s.renderAccount(w, sess, "", notice)
|
|
}
|
|
|
|
func accountError(err error) string {
|
|
var throttled *errThrottled
|
|
switch {
|
|
case errors.As(err, &throttled):
|
|
return throttled.Error()
|
|
case errors.Is(err, errReauth), errors.Is(err, errTOTPRequired):
|
|
return "Confirm with your password and your current one-time code."
|
|
case errors.Is(err, errTOTPInvalid):
|
|
return "That one-time code was rejected. Check the clock on the device that shows it."
|
|
case errors.Is(err, errBadCredentials):
|
|
return "The password or the one-time code is wrong."
|
|
case errors.Is(err, errNoSuchSession):
|
|
return "That session is already signed out."
|
|
}
|
|
return humanError(err)
|
|
}
|
|
|
|
func plural(n int, one, many string) string {
|
|
if n == 1 {
|
|
return one
|
|
}
|
|
return many
|
|
}
|
|
|
|
func (s *Server) renderAccount(w http.ResponseWriter, sess *webSession, errMsg, notice string) {
|
|
d := s.shell(sess, "Account", "Account")
|
|
d["A"], d["Error"], d["Notice"] = s.accountView(sess), errMsg, notice
|
|
render(w, accountTmpl, d)
|
|
}
|
|
|
|
var accountTmpl = template.Must(template.Must(pages.Clone()).Parse(`
|
|
{{define "body"}}
|
|
<h1>Account</h1>
|
|
<p class="sub">How you sign in, and everywhere you are signed in.</p>
|
|
{{if .Error}}<p class="err">{{.Error}}</p>{{end}}
|
|
{{if .Notice}}<p class="ok">{{.Notice}}</p>{{end}}
|
|
{{with .A}}
|
|
<fieldset><legend>You</legend>
|
|
<table><tbody>
|
|
<tr><th>Username</th><td class="name">{{.Username}}</td></tr>
|
|
{{if .Email}}<tr><th>Email</th><td>{{.Email}}</td></tr>{{end}}
|
|
<tr><th>Signs in with</th><td>
|
|
{{if .HasPassword}}<span class="tag">password</span>{{end}}
|
|
{{if .TOTPOn}}<span class="tag">one-time code</span>{{end}}
|
|
{{if .SSO}}<span class="tag">single sign-on</span> <small>via {{.SSO}}</small>{{end}}
|
|
{{if .SSOLink}}<br><a href="{{.SSOLink}}">Link single sign-on to this account</a>{{end}}
|
|
</td></tr>
|
|
<tr><th>Role</th><td>{{if .ServerAdmin}}server administrator{{else}}member{{end}}</td></tr>
|
|
<tr><th>Groups</th><td>{{range $i, $g := .Groups}}{{if $i}}, {{end}}{{$g.Name}} <small>({{$g.Role}})</small>{{else}}none{{end}}</td></tr>
|
|
<tr><th>Member since</th><td>{{.Since}}</td></tr>
|
|
</tbody></table>
|
|
</fieldset>
|
|
|
|
<fieldset><legend>Signed-in devices</legend>
|
|
<p class="sub">Every browser and KeepOrg client signed in as you. Signing one out
|
|
stops it syncing at once; it has to sign in again.</p>
|
|
<div class="scroll"><table>
|
|
<thead><tr><th>Device</th><th>Last active</th><th>Signed in</th><th>Expires</th><th></th></tr></thead>
|
|
<tbody>
|
|
{{range .Sessions}}<tr>
|
|
<td class="name">{{if .Label}}{{.Label}}{{else}}unnamed{{end}}<br>
|
|
<span class="tag">{{if .Browser}}browser{{else}}app{{end}}</span>
|
|
{{if .Current}}<span class="tag">this browser</span>{{end}}</td>
|
|
<td>{{.LastSeen}}</td>
|
|
<td>{{.Created}}</td>
|
|
<td>{{.Expires}}</td>
|
|
<td>{{if not .Current}}<form method="post" action="/web/account">
|
|
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
|
<input type="hidden" name="action" value="revoke">
|
|
<input type="hidden" name="session" value="{{.ID}}">
|
|
<button class="danger" type="submit">Sign out</button>
|
|
</form>{{end}}</td>
|
|
</tr>{{end}}
|
|
</tbody></table></div>
|
|
{{if gt (len .Sessions) 1}}
|
|
<form method="post" action="/web/account">
|
|
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
|
<input type="hidden" name="action" value="revoke-others">
|
|
<button class="destroy" type="submit">Sign out every other device</button>
|
|
</form>
|
|
{{end}}
|
|
</fieldset>
|
|
|
|
{{if .HasPassword}}
|
|
<fieldset><legend>Two-factor authentication</legend>
|
|
{{if .TOTPOn}}
|
|
<p class="sub">On. Signing in with your password also asks for a one-time code
|
|
from your authenticator app.</p>
|
|
<form method="post" action="/web/account">
|
|
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
|
<div class="inline">
|
|
<div><label for="tf_password">Password</label>
|
|
<input id="tf_password" name="password" type="password" autocomplete="current-password" required></div>
|
|
<div><label for="tf_totp">Current one-time code</label>
|
|
<input id="tf_totp" name="totp" inputmode="numeric" autocomplete="one-time-code" required></div>
|
|
</div>
|
|
<div class="inline">
|
|
<button type="submit" name="action" value="totp-begin">Move to a new authenticator</button>
|
|
<button class="destroy" type="submit" name="action" value="totp-disable">Turn off</button>
|
|
</div>
|
|
</form>
|
|
{{else if .TOTPKey}}
|
|
<p class="sub">Add this key to an authenticator app such as Aegis, 2FAS or
|
|
Google Authenticator, then enter the six-digit code it shows.</p>
|
|
<p><code>{{.TOTPKey}}</code></p>
|
|
<p><a href="{{.TOTPLink}}">Open in an authenticator app on this device</a></p>
|
|
<form method="post" action="/web/account">
|
|
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
|
<input type="hidden" name="action" value="totp-confirm">
|
|
<label for="code">Code from the app</label>
|
|
<input id="code" name="code" inputmode="numeric" autocomplete="one-time-code" required>
|
|
<button type="submit">Turn on</button>
|
|
</form>
|
|
<form method="post" action="/web/account">
|
|
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
|
<input type="hidden" name="action" value="totp-cancel">
|
|
<button class="secondary" type="submit">Cancel</button>
|
|
</form>
|
|
{{else}}
|
|
<p class="sub">Off. With it on, a stolen password is not enough to sign in:
|
|
each sign-in also needs a code from an app on your phone.</p>
|
|
<form method="post" action="/web/account">
|
|
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
|
<input type="hidden" name="action" value="totp-begin">
|
|
<label for="tb_password">Your password</label>
|
|
<input id="tb_password" name="password" type="password" autocomplete="current-password" required>
|
|
<button type="submit">Set up two-factor authentication</button>
|
|
</form>
|
|
{{end}}
|
|
</fieldset>
|
|
|
|
<fieldset><legend>Password</legend>
|
|
<p class="sub">The password you sign in with, not any vault's password.
|
|
Changing it signs out your other devices.</p>
|
|
<form method="post" action="/web/account">
|
|
<input type="hidden" name="csrf" value="{{$.CSRF}}">
|
|
<input type="hidden" name="action" value="password">
|
|
<label for="current_password">Current password</label>
|
|
<input id="current_password" name="current_password" type="password" autocomplete="current-password" required>
|
|
{{if .TOTPOn}}<label for="cp_totp">One-time code</label>
|
|
<input id="cp_totp" name="totp" inputmode="numeric" autocomplete="one-time-code" required>{{end}}
|
|
<label for="new_password">New password</label>
|
|
<input id="new_password" name="new_password" type="password" autocomplete="new-password" minlength="10" required>
|
|
<label for="new_password2">Repeat new password</label>
|
|
<input id="new_password2" name="new_password2" type="password" autocomplete="new-password" minlength="10" required>
|
|
<button type="submit">Change password</button>
|
|
</form>
|
|
</fieldset>
|
|
{{else}}
|
|
<p class="note">You sign in through single sign-on{{if .SSO}} at {{.SSO}}{{end}},
|
|
so your password and second factor are managed there, not here.</p>
|
|
{{end}}
|
|
{{end}}
|
|
{{end}}`))
|