Files
keeporg/internal/server/pages.go
T
ReactorcoremeltdownandClaude Opus 5.5 4ffc434b1b Keep server data in an encrypted database, and harden every part
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>
2026-11-02 15:38:32 +01:00

317 lines
16 KiB
Go

package server
import (
"html/template"
"net/http"
)
// The pages: sign-in, the vault list, the administration pages in
// pagesadmin.go, and the three one-shot pages a browser is the right place
// for — approving a device, redeeming an invite and finishing an OIDC round
// trip. There is no JavaScript anywhere in them: every control is a form,
// which is what makes the whole interface work in a locked-down browser and
// keeps the security surface down to the CSRF token.
var pages = template.Must(template.New("layout").Parse(`
{{define "layout"}}<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{.Title}} &middot; KeepOrg</title>
<style>
:root{color-scheme:light dark;--fg:#1a1a1a;--bg:#fafafa;--card:#fff;--line:#d8d8d8;--accent:#2d6a4f}
@media(prefers-color-scheme:dark){:root{--fg:#e8e8e8;--bg:#161616;--card:#1f1f1f;--line:#3a3a3a;--accent:#74c69d}}
*{box-sizing:border-box}
body{margin:0;min-height:100vh;display:grid;grid-template-columns:minmax(0,1fr);place-items:center;
background:var(--bg);color:var(--fg);
font:16px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;padding:24px}
body.wide{place-items:start center}
main{width:100%;min-width:0;max-width:26rem;background:var(--card);border:1px solid var(--line);border-radius:12px;padding:28px}
body.wide main{max-width:54rem}
h1{font-size:1.25rem;margin:0 0 .25rem}
p.sub{margin:0 0 1.25rem;opacity:.7;font-size:.9rem}
label{display:block;font-size:.8rem;text-transform:uppercase;letter-spacing:.04em;opacity:.7;margin:.9rem 0 .25rem}
input{width:100%;padding:.6rem .7rem;font:inherit;color:var(--fg);background:transparent;
border:1px solid var(--line);border-radius:8px}
button,a.button{width:100%;margin-top:1.4rem;padding:.7rem;font:inherit;font-weight:600;color:#fff;
background:var(--accent);border:0;border-radius:8px;cursor:pointer}
a.button{display:block;box-sizing:border-box;text-align:center;text-decoration:none}
.err{margin:0 0 1rem;padding:.6rem .7rem;border-radius:8px;background:#f8d7da;color:#842029;font-size:.9rem}
.alt{display:block;margin-top:1rem;text-align:center;font-size:.9rem;color:var(--accent)}
code{font-size:1.1rem;letter-spacing:.08em}
details{margin-top:1.5rem;border-top:1px solid var(--line);padding-top:1rem}
summary{cursor:pointer;font-size:.9rem;font-weight:600}
details p.sub{margin:.6rem 0 0}
header{display:flex;align-items:baseline;justify-content:space-between;gap:1rem;flex-wrap:wrap}
header form{margin:0}
header button{width:auto;margin:0;padding:.35rem .7rem;font-size:.85rem;font-weight:500;
background:transparent;color:var(--accent);border:1px solid var(--line)}
table{width:100%;border-collapse:collapse;margin:.5rem 0 1.5rem;font-size:.9rem}
th{text-align:left;font-size:.75rem;text-transform:uppercase;letter-spacing:.04em;opacity:.6;
padding:.4rem .5rem;border-bottom:1px solid var(--line)}
td{padding:.5rem;border-bottom:1px solid var(--line);vertical-align:top}
td.name{font-weight:600}
.tag{display:inline-block;padding:.1rem .4rem;border:1px solid var(--line);border-radius:5px;
font-size:.75rem;opacity:.85}
.ok{margin:0 0 1rem;padding:.6rem .7rem;border-radius:8px;background:#d1e7dd;color:#0f5132;font-size:.9rem}
.note{margin:1rem 0 0;padding:.7rem .8rem;border-left:3px solid var(--accent);background:rgba(0,0,0,.03);
font-size:.85rem}
@media(prefers-color-scheme:dark){.note{background:rgba(255,255,255,.04)}
.ok{background:#15372a;color:#9ad8b8}.err{background:#3b1f23;color:#f2b8c0}}
select{width:100%;padding:.6rem .7rem;font:inherit;color:var(--fg);background:var(--card);
border:1px solid var(--line);border-radius:8px}
fieldset{border:1px solid var(--line);border-radius:10px;padding:1rem 1.2rem 1.4rem;margin:0}
legend{padding:0 .4rem;font-size:.8rem;text-transform:uppercase;letter-spacing:.04em;opacity:.7}
.empty{opacity:.7;font-size:.9rem;margin:.5rem 0 1.5rem}
nav{display:flex;gap:.25rem;flex-wrap:wrap;margin:0 0 1.25rem;padding-bottom:.75rem;
border-bottom:1px solid var(--line)}
nav a,nav .here{padding:.3rem .6rem;border-radius:7px;font-size:.9rem;text-decoration:none;color:var(--accent)}
nav .here{background:var(--accent);color:#fff;font-weight:600}
nav form.out{margin:0 0 0 auto}
nav button{width:auto;margin:0;padding:.3rem .6rem;font:inherit;font-size:.85rem;font-weight:500;
background:transparent;color:var(--accent);border:1px solid var(--line)}
a{color:var(--accent)}
td form{display:inline;margin:0}
td button{width:auto;margin:0 .25rem .25rem 0;padding:.3rem .5rem;font-size:.8rem;font-weight:500;
background:transparent;color:var(--accent);border:1px solid var(--line)}
td button.danger,a.danger{color:#b02a37}
button.destroy{background:#b02a37}
button.secondary{margin-top:.6rem;background:transparent;color:var(--accent);border:1px solid var(--line)}
@media(prefers-color-scheme:dark){td button.danger,a.danger{color:#f2b8c0}
button.destroy{background:#a3313c}}
.inline{display:flex;gap:.6rem;align-items:flex-end;flex-wrap:wrap;margin:0}
.inline>div{flex:1 1 9rem}
.inline label{margin-top:0}
.inline button{width:auto;margin:0;padding:.6rem 1.1rem}
input[readonly]{min-width:17rem;font-family:ui-monospace,SFMono-Regular,monospace;
font-size:.8rem;opacity:.85}
.scroll{max-width:100%;overflow-x:auto}
fieldset+fieldset{margin-top:1.5rem}
.gone{opacity:.55}
</style></head><body{{if .Wide}} class="wide"{{end}}><main>{{if .Nav}}<nav>{{range .Nav}}{{if .Current}}<span class="here">{{.Label}}</span>{{else}}<a href="{{.Href}}">{{.Label}}</a>{{end}}{{end}}<form class="out" method="post" action="/web/signout"><input type="hidden" name="csrf" value="{{.CSRF}}"><button type="submit">Sign out {{.User}}</button></form></nav>{{end}}{{template "body" .}}</main></body></html>{{end}}
`))
var deviceTmpl = template.Must(template.Must(pages.Clone()).Parse(`
{{define "body"}}<h1>Approve this device</h1>
<p class="sub">Sign in to let the client on your device sync your databases.</p>
{{if .Error}}<p class="err">{{.Error}}</p>{{end}}
<form method="post" action="/device">
<label for="code">Device code</label><input id="code" name="code" value="{{.Code}}" required autocapitalize="characters">
<label for="username">Username</label><input id="username" name="username" autocomplete="username" required>
<label for="password">Password</label><input id="password" name="password" type="password" autocomplete="current-password" required>
<label for="totp">One-time code <small>(if enabled)</small></label><input id="totp" name="totp" inputmode="numeric" autocomplete="one-time-code">
<button type="submit">Approve</button>
</form>
{{if .OIDC}}<a class="alt" href="/oidc/login?code={{.Code}}">Sign in with single sign-on &rarr;</a>{{end}}
{{end}}`))
var inviteTmpl = template.Must(template.Must(pages.Clone()).Parse(`
{{define "body"}}<h1>Create your account</h1>
<p class="sub">You were invited to a KeepOrg server.</p>
{{if .Error}}<p class="err">{{.Error}}</p>{{end}}
<form method="post" action="/invite/{{.Token}}">
<label for="username">Username</label><input id="username" name="username" autocomplete="username" required>
<label for="email">Email <small>(optional)</small></label><input id="email" name="email" type="email" autocomplete="email">
<label for="password">Password</label><input id="password" name="password" type="password" autocomplete="new-password" minlength="10" required>
<label for="password2">Repeat password</label><input id="password2" name="password2" type="password" autocomplete="new-password" minlength="10" required>
<button type="submit">Create account</button>
</form>
{{end}}`))
var signInTmpl = template.Must(template.Must(pages.Clone()).Parse(`
{{define "body"}}<h1>KeepOrg</h1>
<p class="sub">Sign in to create and manage your vaults.</p>
{{if .Error}}<p class="err">{{.Error}}</p>{{end}}
<form method="post" action="/web/signin">
<input type="hidden" name="pre" value="{{.Pre}}">
<label for="username">Username</label><input id="username" name="username" autocomplete="username" required autofocus>
<label for="password">Password</label><input id="password" name="password" type="password" autocomplete="current-password" required>
<label for="totp">One-time code <small>(if enabled)</small></label><input id="totp" name="totp" inputmode="numeric" autocomplete="one-time-code">
<button type="submit">Sign in</button>
</form>
{{if .OIDC}}<a class="alt" href="/oidc/login">Sign in with single sign-on &rarr;</a>{{end}}
{{end}}`))
var vaultsTmpl = template.Must(template.Must(pages.Clone()).Parse(`
{{define "body"}}
<h1>Your vaults</h1>
<p class="sub">The files your KeepOrg client keeps in sync.</p>
{{if .Error}}<p class="err">{{.Error}}</p>{{end}}
{{if .Notice}}<p class="ok">{{.Notice}}</p>{{end}}
{{if .Vaults}}
<div class="scroll"><table>
<thead><tr><th>Vault</th><th>Access</th><th>On conflict</th><th>Version</th><th>Last saved</th><th></th></tr></thead>
<tbody>
{{range .Vaults}}<tr>
<td class="name">{{.Name}}.kdbx</td>
<td>{{.Perm}}</td>
<td><span class="tag">{{.Strategy}}</span></td>
<td>{{.Version}}</td>
<td>{{.Updated}}{{if .By}}<br><small>by {{.By}}</small>{{end}}</td>
<td>{{if eq .Perm "admin"}}<a class="danger" href="/web/vaults/{{.ID}}/delete">Delete</a>{{end}}</td>
</tr>{{end}}
</tbody></table></div>
{{else}}
<p class="empty">No vaults yet. Create one below, then open it from the KeepOrg client
on your computer or phone.</p>
{{end}}
{{if .Groups}}
<fieldset><legend>Create a vault</legend>
<form method="post" action="/web/vaults">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<label for="name">Name</label>
<input id="name" name="name" required placeholder="Team Vault">
<label for="group">Owned by</label>
<select id="group" name="group" required>
{{range .Groups}}<option value="{{.ID}}">{{.Name}}</option>{{end}}
</select>
<label for="strategy">When two people save at once</label>
<select id="strategy" name="strategy">
<option value="merge">Merge both edits (the server holds the key)</option>
<option value="server-wins">Keep the server copy</option>
<option value="client-wins">Keep the newest save</option>
<option value="manual">Leave both copies for a human</option>
</select>
<label for="password">Vault password</label>
<input id="password" name="password" type="password" autocomplete="new-password" minlength="12" required>
<label for="password2">Repeat vault password</label>
<input id="password2" name="password2" type="password" autocomplete="new-password" minlength="12" required>
<button type="submit">Create vault</button>
</form>
<p class="note">This password encrypts the vault itself and is what everyone with
access types into KeePass. It is not your account password, and it cannot be
recovered: write it down before you continue.<br><br>
Merging requires the server to keep this password, so a merge vault can be read
by whoever controls the server. Any other setting keeps the key off the server.</p>
</fieldset>
{{else}}
<p class="empty">You do not administer a group yet, so there is nowhere to put a
vault. Ask an administrator to add you to one.</p>
{{end}}
<p class="note">Your password, two-factor authentication and signed-in devices
are on the <a href="/web/account">Account</a> page.</p>
{{end}}`))
var deleteVaultTmpl = template.Must(template.Must(pages.Clone()).Parse(`
{{define "body"}}
{{with .V}}
<h1>Delete {{.Name}}.kdbx?</h1>
<p class="sub">This cannot be undone. <a href="/web/vaults">Back to your vaults</a></p>
{{end}}
{{if .Error}}<p class="err">{{.Error}}</p>{{end}}
{{with .V}}
<div class="scroll"><table>
<tbody>
<tr><td class="name">Owned by</td><td>{{.Group}}</td></tr>
<tr><td class="name">Versions stored</td><td>{{.Version}}</td></tr>
<tr><td class="name">Last saved</td><td>{{.Updated}}</td></tr>
<tr><td class="name">Groups granted access</td><td>{{.Grants}}</td></tr>
</tbody></table></div>
<p class="note">Every stored version of this file is erased from the server,
along with the grants that point at it. Copies already in people's mirror
directories stay on their computers: the server stops tracking the vault, it
does not reach into anybody's home directory. If the vault is merged here,
the key the server holds goes with it.</p>
<fieldset><legend>Confirm it is you</legend>
<form method="post" action="/web/vaults/{{.ID}}/delete">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
{{if .NeedsName}}
<label for="confirm_name">Type the vault's name: <strong>{{.Name}}</strong></label>
<input id="confirm_name" name="confirm_name" required autocomplete="off" autofocus>
<p class="sub">You sign in through single sign-on, so there is no password here
to ask for.</p>
{{else}}
<label for="password">Your account password</label>
<input id="password" name="password" type="password" autocomplete="current-password" required autofocus>
{{if .NeedsTOTP}}
<label for="totp">One-time code</label>
<input id="totp" name="totp" inputmode="numeric" autocomplete="one-time-code" required>
{{end}}
<p class="sub">Not the vault's password — the one you signed in with.</p>
{{end}}
<button class="destroy" type="submit">Delete {{.Name}} permanently</button>
</form>
</fieldset>
{{end}}
{{end}}`))
var deviceConfirmTmpl = template.Must(template.Must(pages.Clone()).Parse(`
{{define "body"}}{{with .D}}<h1>Let a device in?</h1>
<p class="sub">A KeepOrg client asked to sign in as <b>{{.User}}</b>.</p>
<table><tbody>
<tr><th>Device</th><td class="name">{{if .Label}}{{.Label}}{{else}}unnamed{{end}}</td></tr>
<tr><th>Its code</th><td><code>{{.Code}}</code></td></tr>
<tr><th>Started</th><td>{{.Started}}</td></tr>
</tbody></table>
<p class="note">Approve only if you started this sign-in yourself, just now,
and your device shows the code above. Anyone who sent you a link to this page
gets your access if you approve.</p>
<form method="post" action="/oidc/approve">
<input type="hidden" name="nonce" value="{{.Nonce}}">
<button type="submit" name="decision" value="approve">Approve {{if .Label}}{{.Label}}{{else}}this device{{end}}</button>
<button class="secondary" type="submit" name="decision" value="deny">This was not me</button>
</form>{{end}}{{end}}`))
var doneTmpl = template.Must(template.Must(pages.Clone()).Parse(`
{{define "body"}}<h1>{{.Title}}</h1><p class="sub">{{.Message}}</p>
{{if .Return}}<p><a class="button" href="{{.Return}}">Return to KeepOrg</a></p>{{end}}{{end}}`))
func (s *Server) renderDevice(w http.ResponseWriter, code, errMsg string) {
render(w, deviceTmpl, map[string]any{
"Title": "Approve device", "Code": code, "Error": errMsg, "OIDC": s.oidc != nil,
})
}
func (s *Server) renderInvite(w http.ResponseWriter, token, errMsg string) {
render(w, inviteTmpl, map[string]any{"Title": "Create account", "Token": token, "Error": errMsg})
}
func (s *Server) renderSignIn(w http.ResponseWriter, r *http.Request, errMsg string) {
render(w, signInTmpl, map[string]any{
"Title": "Sign in", "Error": errMsg, "OIDC": s.oidc != nil,
"Pre": s.preSessionToken(w, r),
})
}
func (s *Server) renderVaults(w http.ResponseWriter, sess *webSession, errMsg, notice string) {
vaults, groups := s.vaultRows(sess.user)
d := s.shell(sess, "Vaults", "Vaults")
d["Vaults"], d["Groups"], d["Error"], d["Notice"] = vaults, groups, errMsg, notice
render(w, vaultsTmpl, d)
}
func (s *Server) renderDeleteVault(w http.ResponseWriter, sess *webSession, id, errMsg string) {
v := s.deleteVaultView(sess.user, id)
if v == nil {
s.renderVaults(w, sess, "There is no such vault, or you do not administer it.", "")
return
}
d := s.shell(sess, "Delete vault", "Vaults")
d["V"], d["Error"] = v, errMsg
render(w, deleteVaultTmpl, d)
}
func (s *Server) renderDone(w http.ResponseWriter, title, msg string) {
render(w, doneTmpl, map[string]any{"Title": title, "Message": msg})
}
// renderApproved ends a device approval. A client that gave a return URL
// gets a link back to itself; html/template would neutralise its custom
// scheme, which is why it is marked safe here, after validReturnURL.
func (s *Server) renderApproved(w http.ResponseWriter, returnURL string) {
d := map[string]any{"Title": "Device approved",
"Message": "You can close this page and return to the application."}
if returnURL != "" && validReturnURL(returnURL) {
d["Return"] = template.URL(returnURL)
}
render(w, doneTmpl, d)
}
func render(w http.ResponseWriter, t *template.Template, data map[string]any) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Referrer-Policy", "no-referrer")
_ = t.ExecuteTemplate(w, "layout", data)
}