carlos / platform Public

console: one front door; Keymail found from the address

Co-Authored-By: Claude <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 4f3ecc12a553a1a819c92d0116109d906397e02d parent e364f02
12 files changed, +795 −146
  • internal/console/authcli.go +9 −4
  • internal/console/claim_invariant_fixtures_test.go +1 −1
  • internal/console/claim_invariant_probes_nonapp_test.go +10 −4
  • internal/console/emailsignin.go +149 −0
  • internal/console/emailsignin_test.go +470 −0
  • internal/console/keymail_test.go +3 −0
  • internal/console/server.go +112 −44
  • internal/console/server_test.go +2 −80
  • internal/console/store.go +14 −0
  • internal/console/templates/check.html +14 −4
  • internal/console/templates/home.html +8 −7
  • internal/console/templates/layout.html +3 −2
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index c597c3e56..931c1ff5a 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -1383,9 +1383,10 @@ func (s *Server) renderCLI(w http.ResponseWriter, status int, name string, p cli
}
// handleCLIApprovePage is where the printed link lands. A signed-out visitor
-// goes to the front page to sign in and re-opens the link — the code is in
-// their terminal, so nothing is lost, and the console never carries a pending
-// approval through an authentication it has not finished.
+// gets the front page, asked to sign in, with next set back here (spec 8). A
+// code-shaped ?code= rides along in next only so it can be shown again for
+// comparison; the console never carries a pending approval through an
+// authentication it has not finished.
//
// IT DELIBERATELY DOES NOT ACT ON ?code=. Not to resolve it, not to look it
// up, and above all not to render an Approve button for it. A prefilled code
@@ -1400,7 +1401,11 @@ func (s *Server) renderCLI(w http.ResponseWriter, status int, name string, p cli
func (s *Server) handleCLIApprovePage(w http.ResponseWriter, r *http.Request) {
addr, raw, ok := s.session(r)
if !ok {
- http.Redirect(w, r, "/", http.StatusFound)
+ next := "/auth/cli"
+ if c := NormalizeUserCode(r.URL.Query().Get("code")); len(c) == userCodeLen+1 {
+ next += "?code=" + url.QueryEscape(c)
+ }
+ s.renderHome(w, homeForm{Next: next, Banner: copyText("home.cli_prompt")})
return
}
p := cliPage{page: page{Title: "Approve a terminal", Address: addr, CSRF: raw},
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 8919640e9..3caf30288 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -1216,7 +1216,7 @@ var claimFixtures = map[string]claimFixture{
// guarded cli_tokens write for the token's app. Person tokens (app '') are
// the same handler's other branch; service credentials are refused.
"route POST /auth/cli/tokens/revoke": {door: claimLegacyAppTokenRevokeDoor("/auth/cli/tokens/revoke")},
- "route POST /auth/continue": claimNonApp("continues sign-in: confirmations and sessions"),
+ "route POST /auth/continue": claimNonApp("starts sign-in: email challenges"),
"route POST /auth/signout": claimNonApp("ends the session"),
"route POST /fleet/store/{account}/{decision}": claimNonApp("operator entitlement decision for an account"),
"route POST /invite/{token}": claimNonApp("accepts an invitation: membership"),
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go
index 8e16fe554..d905e8458 100644
--- a/internal/console/claim_invariant_probes_nonapp_test.go
+++ b/internal/console/claim_invariant_probes_nonapp_test.go
@@ -143,15 +143,21 @@ func claimConfirmProbe() claimProbe {
}
func claimContinueProbe() claimProbe {
+ // An address Keymail's lookup does not know: the email door, which
+ // records a challenge and answers with the check page.
+ const addr = "probe@example.com"
return claimProbe{
+ setup: func(t *testing.T, cx *claimCase) {
+ cx.srv.consoleMail = &fakeConsoleMail{ready: true}
+ },
do: func(t *testing.T, cx *claimCase) claimReply {
- status, loc, body := postForm(t, newBrowser(t), cx.ts.URL+"/auth/continue", url.Values{"address": {claimFxOwner}})
+ status, loc, body := postForm(t, newBrowser(t), cx.ts.URL+"/auth/continue", url.Values{"address": {addr}})
return claimReply{Status: status, Loc: loc, Body: body}
},
- body: []string{"Check your Keymail"},
+ body: []string{esc(copyText("check.sent", "address", addr))},
effect: func(t *testing.T, cx *claimCase, r claimReply) string {
- if cx.sqlCount(t, `SELECT COUNT(*) FROM confirmations WHERE address = ?`, claimFxOwner) == 0 {
- return "no sign-in confirmation was recorded for " + claimFxOwner
+ if cx.sqlCount(t, `SELECT COUNT(*) FROM email_challenges WHERE address = ?`, addr) == 0 {
+ return "no sign-in challenge was recorded for " + addr
}
return ""
},
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go
index a6eecdd2a..814bd9276 100644
--- a/internal/console/emailsignin.go
+++ b/internal/console/emailsignin.go
@@ -1,8 +1,10 @@
package console
import (
+ "context"
"log"
"net/http"
+ netmail "net/mail"
"net/url"
"strings"
"time"
@@ -12,6 +14,153 @@ import (
// the auth cookie. (An email sign-in keeps its next on the challenge row.)
const nextCookie = "carlos_console_next"
+// challengeCookie names this browser's email challenge (its id), so a code
+// typed here finds it and a second request from here replaces it.
+const challengeCookie = "carlos_console_email"
+
+// Sign-in sends run off the request (spec 4.2): at most challengeSendSlots at
+// once, each with challengeSendTimeout to get a slot and finish.
+const (
+ challengeSendSlots = 4
+ challengeSendTimeout = 20 * time.Second
+)
+
+// signinView is the approved front-page and "Check your email" copy the
+// templates show; render fills it on every page.
+type signinView struct {
+ EmailLabel, EmailPlaceholder, EmailButton, Small, NoMail string
+ CheckTitle, CodeLabel, CodeButton, Nothing, AgainButton string
+}
+
+var approvedSigninView = signinView{
+ EmailLabel: copyText("home.email_label"),
+ EmailPlaceholder: copyText("home.email_placeholder"),
+ EmailButton: copyText("home.email_button"),
+ Small: copyText("home.small"),
+ NoMail: copyText("home.no_mail"),
+ CheckTitle: copyText("check.title"),
+ CodeLabel: copyText("check.code_label"),
+ CodeButton: copyText("check.code_button"),
+ Nothing: copyText("check.nothing"),
+ AgainButton: copyText("check.again_button"),
+}
+
+// sameOrigin reports whether a form POST came from this console's own pages:
+// an Origin header must name the configured origin's host; without one,
+// Sec-Fetch-Site must be same-origin or none; a request carrying neither (an
+// old browser, a script) passes, as every other form here does.
+func (s *Server) sameOrigin(r *http.Request) bool {
+ if o := r.Header.Get("Origin"); o != "" {
+ got, err := url.Parse(o)
+ if err != nil || got.Host == "" {
+ return false
+ }
+ want, err := url.Parse(s.cfg.Origin)
+ return err == nil && want.Host != "" && strings.EqualFold(got.Host, want.Host)
+ }
+ switch r.Header.Get("Sec-Fetch-Site") {
+ case "", "same-origin", "none":
+ return true
+ }
+ return false
+}
+
+// canonicalAddress is the one form of a typed address used everywhere after
+// the front door (spec 11): trimmed and lower-cased, and accepted only when it
+// is a bare address, so display-name and list forms are refused before any
+// challenge, rate-limit key or user row exists.
+func canonicalAddress(raw string) (string, bool) {
+ a := strings.ToLower(strings.TrimSpace(raw))
+ if !ValidAddress(a) {
+ return "", false
+ }
+ if parsed, err := netmail.ParseAddress(a); err != nil || parsed.Address != a {
+ return "", false
+ }
+ return a, true
+}
+
+// keymailAddress is discovery (spec 4.1): the configured Keymail host's own
+// addresses, or any address Keymail's public lookup says is a mailbox. Only
+// those public answers decide; any lookup failure means email.
+func (s *Server) keymailAddress(ctx context.Context, addr string) bool {
+ if s.km == nil {
+ return false
+ }
+ if h := s.km.Host(); h != "" && addr[strings.LastIndex(addr, "@")+1:] == h {
+ return true
+ }
+ ok, err := s.km.HasMailbox(ctx, addr)
+ if err != nil {
+ log.Printf("console: keymail lookup for %s: %v (sending email)", addr, err)
+ return false
+ }
+ return ok
+}
+
+// mailReady reports whether the console mailer can send now. No mailer is
+// not ready.
+func (s *Server) mailReady(ctx context.Context) bool {
+ return s.consoleMail != nil && s.consoleMail.Ready(ctx)
+}
+
+// sendChallengeAsync sends a sign-in or step-up message through the console
+// mailer on its own goroutine, so the page renders at once and send latency
+// is no oracle. A send that cannot get one of the challengeSendSlots within
+// its context is dropped; every failure is logged.
+func (s *Server) sendChallengeAsync(to, subject, body string) {
+ mailer := s.consoleMail
+ go func() {
+ defer func() {
+ if s.challengeSent != nil {
+ s.challengeSent <- struct{}{}
+ }
+ }()
+ ctx, cancel := context.WithTimeout(context.Background(), challengeSendTimeout)
+ defer cancel()
+ select {
+ case s.challengeSem <- struct{}{}:
+ defer func() { <-s.challengeSem }()
+ case <-ctx.Done():
+ log.Printf("console: sign-in email to %s dropped: no send slot free", to)
+ return
+ }
+ if mailer == nil {
+ log.Printf("console: sign-in email to %s dropped: no console mailer", to)
+ return
+ }
+ if err := mailer.Send(ctx, to, subject, body); err != nil {
+ log.Printf("console: sign-in email to %s: %v", to, err)
+ }
+ }()
+}
+
+// homeForm is what the front page's one form starts with.
+type homeForm struct {
+ Prefill, Next, Banner, Error string
+ NoMail bool
+}
+
+// renderHome renders the signed-out front page.
+func (s *Server) renderHome(w http.ResponseWriter, f homeForm) {
+ s.render(w, http.StatusOK, "home", page{
+ Title: "Sign in", Prefill: f.Prefill, Next: safeNext(f.Next),
+ Banner: f.Banner, Error: f.Error, NoMail: f.NoMail,
+ })
+}
+
+// renderCheck renders "Check your email" for addr. Every email-bound outcome
+// of the front door renders exactly this, so the page never says whether a
+// message was sent, throttled or refused.
+func (s *Server) renderCheck(w http.ResponseWriter, addr, next string) {
+ s.render(w, http.StatusOK, "check", page{
+ Title: copyText("check.title"),
+ CheckSent: copyText("check.sent", "address", addr),
+ Prefill: addr,
+ Next: safeNext(next),
+ })
+}
+
// safeNext returns raw when it is a local path and "" otherwise: it starts
// with "/", not "//", has no backslash, and parses with no scheme or host.
// Anything else is dropped silently and the usual landing applies.
diff --git a/internal/console/emailsignin_test.go b/internal/console/emailsignin_test.go
index f4ee364e7..ff42ed6c4 100644
--- a/internal/console/emailsignin_test.go
+++ b/internal/console/emailsignin_test.go
@@ -1,9 +1,12 @@
package console
import (
+ "io"
"net/http"
"net/http/httptest"
"net/url"
+ "regexp"
+ "strings"
"testing"
"time"
)
@@ -147,3 +150,470 @@ func TestFinishSigninEmailRecordsStepUp(t *testing.T) {
t.Fatalf("no personal account minted: %v, %v", accts, err)
}
}
+
+// ---- the front door (POST /auth/continue) -----------------------------------
+
+// newEmailFixture is the console fixture with a console mailer that reports
+// ready (or not) and a hook that signals each finished sign-in send.
+func newEmailFixture(t *testing.T, ready bool) (*consoleFixture, *fakeConsoleMail) {
+ t.Helper()
+ fx := newConsoleFixture(t)
+ m := &fakeConsoleMail{ready: ready}
+ fx.srv.consoleMail = m
+ fx.srv.challengeSent = make(chan struct{}, 16)
+ return fx, m
+}
+
+// lookupAnswers makes the fake Keymail's federation lookup answer status for
+// addr.
+func lookupAnswers(fx *consoleFixture, addr string, status int) {
+ fx.fk.mu.Lock()
+ defer fx.fk.mu.Unlock()
+ fx.fk.lookupStatus[addr] = status
+}
+
+func lookupCount(fx *consoleFixture) int {
+ fx.fk.mu.Lock()
+ defer fx.fk.mu.Unlock()
+ return fx.fk.lookups
+}
+
+// postContinue submits the front page's form from the console's own page
+// (Origin set, as a browser does on a POST).
+func postContinue(t *testing.T, fx *consoleFixture, c *http.Client, form url.Values) (status int, location, body string) {
+ t.Helper()
+ return postContinueFrom(t, fx, c, fx.ts.URL, form)
+}
+
+func postContinueFrom(t *testing.T, fx *consoleFixture, c *http.Client, origin string, form url.Values) (status int, location, body string) {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodPost, fx.ts.URL+"/auth/continue", strings.NewReader(form.Encode()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ if origin != "" {
+ req.Header.Set("Origin", origin)
+ }
+ res, err := c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ raw, err := io.ReadAll(res.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return res.StatusCode, res.Header.Get("Location"), string(raw)
+}
+
+// waitChallengeSent waits for n background sign-in sends to finish.
+func waitChallengeSent(t *testing.T, fx *consoleFixture, n int) {
+ t.Helper()
+ for i := 0; i < n; i++ {
+ select {
+ case <-fx.srv.challengeSent:
+ case <-time.After(10 * time.Second):
+ t.Fatalf("sign-in send %d of %d never finished", i+1, n)
+ }
+ }
+}
+
+func challengeRows(t *testing.T, fx *consoleFixture) int {
+ t.Helper()
+ var n int
+ if err := fx.st.db.QueryRow(`SELECT COUNT(*) FROM email_challenges`).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+func userRows(t *testing.T, fx *consoleFixture, addr string) int {
+ t.Helper()
+ var n int
+ if err := fx.st.db.QueryRow(`SELECT COUNT(*) FROM users WHERE address = ?`, addr).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+var (
+ signinCodeRe = regexp.MustCompile(`type this code on the page that's waiting: (\d{6})\b`)
+ signinLinkRe = regexp.MustCompile(`/auth/email/link\?t=([A-Za-z0-9_-]+)`)
+)
+
+// sentSignin is the one message the console mailer got, split into its
+// recipient, code and link token.
+func sentSignin(t *testing.T, m *fakeConsoleMail) (to, code, link string) {
+ t.Helper()
+ sent := m.sentCopy()
+ if len(sent) != 1 {
+ t.Fatalf("console mailer got %d messages, want 1: %q", len(sent), sent)
+ }
+ to, body, _ := strings.Cut(sent[0], "|")
+ cm := signinCodeRe.FindStringSubmatch(body)
+ lm := signinLinkRe.FindStringSubmatch(body)
+ if cm == nil || lm == nil {
+ t.Fatalf("sign-in email has no code or link:\n%s", body)
+ }
+ return to, cm[1], lm[1]
+}
+
+func TestContinueKeymailHostGoesToKeymail(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ addr := "bob@" + fx.srv.km.Host()
+
+ status, loc, _ := postContinue(t, fx, newBrowser(t), url.Values{"address": {addr}})
+ if status != http.StatusSeeOther || loc != "/auth/signin" {
+ t.Fatalf("continue = %d -> %q, want 303 -> /auth/signin", status, loc)
+ }
+ status, loc, _ = postContinue(t, fx, newBrowser(t), url.Values{"address": {addr}, "next": {"/auth/cli"}})
+ if want := "/auth/signin?next=" + url.QueryEscape("/auth/cli"); status != http.StatusSeeOther || loc != want {
+ t.Fatalf("continue with next = %d -> %q, want 303 -> %q", status, loc, want)
+ }
+ // An unsafe next is dropped, not carried to Keymail.
+ _, loc, _ = postContinue(t, fx, newBrowser(t), url.Values{"address": {addr}, "next": {"//evil.example"}})
+ if loc != "/auth/signin" {
+ t.Fatalf("continue with unsafe next -> %q, want /auth/signin", loc)
+ }
+ if n := lookupCount(fx); n != 0 {
+ t.Fatalf("the Keymail host's own address cost %d lookups, want 0", n)
+ }
+ if sent := m.sentCopy(); len(sent) != 0 || challengeRows(t, fx) != 0 {
+ t.Fatalf("a Keymail address got email: sent %q, %d challenges", sent, challengeRows(t, fx))
+ }
+}
+
+func TestContinueLookup200GoesToKeymail(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ lookupAnswers(fx, "bob@example.com", http.StatusOK)
+ status, loc, _ := postContinue(t, fx, newBrowser(t), url.Values{"address": {"bob@example.com"}})
+ if status != http.StatusSeeOther || loc != "/auth/signin" {
+ t.Fatalf("continue = %d -> %q, want 303 -> /auth/signin", status, loc)
+ }
+ if n := lookupCount(fx); n != 1 {
+ t.Fatalf("lookups = %d, want 1", n)
+ }
+ if sent := m.sentCopy(); len(sent) != 0 || challengeRows(t, fx) != 0 {
+ t.Fatalf("a Keymail-served domain got email: sent %q, %d challenges", sent, challengeRows(t, fx))
+ }
+}
+
+// checkEmailSent is the email outcome: the check page, one message to addr
+// with a code and a link, and a challenge for addr with next.
+func checkEmailSent(t *testing.T, fx *consoleFixture, m *fakeConsoleMail, c *http.Client, addr, next string, status int, body string) {
+ t.Helper()
+ if status != http.StatusOK || !strings.Contains(body, esc(copyText("check.sent", "address", addr))) {
+ t.Fatalf("continue = %d, want the check page for %s:\n%s", status, addr, body)
+ }
+ waitChallengeSent(t, fx, 1)
+ to, _, link := sentSignin(t, m)
+ if to != addr {
+ t.Fatalf("sign-in email went to %q, want %q", to, addr)
+ }
+ ch, ok := fx.st.PeekEmailLink(link, time.Now())
+ if !ok || ch.Address != addr || ch.Purpose != ChallengeSignIn || ch.Next != next {
+ t.Fatalf("challenge = %+v %v, want a sign-in for %s with next %q", ch, ok, addr, next)
+ }
+ if browserCookie(t, fx, c, challengeCookie) == "" {
+ t.Fatal("no challenge cookie set on the browser that asked")
+ }
+}
+
+func TestContinueLookup404SendsEmail(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ lookupAnswers(fx, "bob@example.com", http.StatusNotFound)
+ c := newBrowser(t)
+ status, _, body := postContinue(t, fx, c, url.Values{"address": {"bob@example.com"}, "next": {"/auth/cli"}})
+ checkEmailSent(t, fx, m, c, "bob@example.com", "/auth/cli", status, body)
+ sent := m.sentCopy()[0]
+ if !strings.Contains(sent, fx.ts.URL+"/auth/email/link?t=") {
+ t.Fatalf("link is not on the console's origin:\n%s", sent)
+ }
+}
+
+func TestContinueLookup500SendsEmailForForeignDomain(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ lookupAnswers(fx, "bob@example.com", http.StatusInternalServerError)
+ c := newBrowser(t)
+ status, _, body := postContinue(t, fx, c, url.Values{"address": {"bob@example.com"}})
+ checkEmailSent(t, fx, m, c, "bob@example.com", "", status, body)
+}
+
+// Review Focus 1: a stored grant is console state, and console state never
+// decides the door.
+func TestContinueGrantDoesNotDecide(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ now := time.Now()
+ if _, err := fx.st.EnsureUser("bob@example.com", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.SetGrantToken("bob@example.com", "grant-token", now); err != nil {
+ t.Fatal(err)
+ }
+ lookupAnswers(fx, "bob@example.com", http.StatusNotFound)
+ c := newBrowser(t)
+ status, _, body := postContinue(t, fx, c, url.Values{"address": {"bob@example.com"}})
+ checkEmailSent(t, fx, m, c, "bob@example.com", "", status, body)
+ fx.fk.mu.Lock()
+ defer fx.fk.mu.Unlock()
+ if len(fx.fk.sends) != 0 {
+ t.Fatalf("the stored grant was used to send %d Keymail messages", len(fx.fk.sends))
+ }
+}
+
+// Review Focus 3.
+func TestContinueNormalises(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ lookupAnswers(fx, "bob@example.com", http.StatusNotFound)
+ c := newBrowser(t)
+ status, _, body := postContinue(t, fx, c, url.Values{"address": {" Bob@Example.COM "}})
+ checkEmailSent(t, fx, m, c, "bob@example.com", "", status, body)
+
+ fx2, m2 := newEmailFixture(t, true)
+ for _, bad := range []string{"a<victim@example.com>", "a@x.com,b@y.com", "", "nobody"} {
+ status, _, body := postContinue(t, fx2, newBrowser(t), url.Values{"address": {bad}})
+ if status != http.StatusOK || !strings.Contains(body, esc(copyText("home.bad_address"))) {
+ t.Fatalf("continue %q = %d, want the front page with the bad-address error:\n%s", bad, status, body)
+ }
+ if !strings.Contains(body, `action="/auth/continue"`) {
+ t.Fatalf("continue %q: the error page has no form", bad)
+ }
+ }
+ if n := userRows(t, fx2, "victim@example.com"); n != 0 {
+ t.Fatal("a display-name address made a user row")
+ }
+ if n := challengeRows(t, fx2); n != 0 {
+ t.Fatalf("a refused address made %d challenges", n)
+ }
+ if n := lookupCount(fx2); n != 0 {
+ t.Fatalf("a refused address cost %d lookups", n)
+ }
+ if sent := m2.sentCopy(); len(sent) != 0 {
+ t.Fatalf("a refused address was mailed: %q", sent)
+ }
+}
+
+// The anti-oracle: a new address, a known user, a throttled repeat and a
+// refused submission all get the same page, byte for byte.
+func TestContinuePageIdentical(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ const addr = "bob@example.com"
+ lookupAnswers(fx, addr, http.StatusNotFound)
+ form := url.Values{"address": {addr}, "next": {"/auth/cli"}}
+
+ browsers := []*http.Client{newBrowser(t), newBrowser(t), newBrowser(t), newBrowser(t)}
+ _, _, fresh := postContinue(t, fx, browsers[0], form)
+ waitChallengeSent(t, fx, 1)
+
+ // Two minutes on, bob is a known user and may be sent another.
+ if _, err := fx.st.EnsureUser(addr, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ fx.srv.limits.mu.Lock()
+ fx.srv.limits.now = func() time.Time { return time.Now().Add(2 * time.Minute) }
+ fx.srv.limits.mu.Unlock()
+ _, _, known := postContinue(t, fx, browsers[1], form)
+ waitChallengeSent(t, fx, 1)
+
+ // At once again: the per-address gap refuses the send.
+ _, _, throttled := postContinue(t, fx, browsers[2], form)
+
+ // And an IP over its submission cap is refused before anything else.
+ for fx.srv.limits.submit("127.0.0.1") {
+ }
+ lookupsBefore := lookupCount(fx)
+ _, _, capped := postContinue(t, fx, browsers[3], form)
+
+ if fresh != known || fresh != throttled || fresh != capped {
+ t.Fatalf("pages differ:\nfresh:\n%s\nknown:\n%s\nthrottled:\n%s\ncapped:\n%s", fresh, known, throttled, capped)
+ }
+ if n := len(m.sentCopy()); n != 2 {
+ t.Fatalf("mailer got %d messages, want 2 (the throttled and capped ones send nothing)", n)
+ }
+ if n := challengeRows(t, fx); n != 2 {
+ t.Fatalf("%d challenges stored, want 2", n)
+ }
+ if lookupCount(fx) != lookupsBefore {
+ t.Fatal("a capped submission still asked Keymail")
+ }
+ // The headers match too: every outcome sets the challenge cookie.
+ for i, c := range browsers {
+ if browserCookie(t, fx, c, challengeCookie) == "" {
+ t.Errorf("outcome %d set no challenge cookie", i)
+ }
+ }
+ for _, want := range []string{
+ esc(copyText("check.title")), esc(copyText("check.code_label")), esc(copyText("check.code_button")),
+ esc(copyText("check.nothing")), esc(copyText("check.again_button")),
+ `action="/auth/email/code"`, `name="address" value="bob@example.com"`, `name="next" value="/auth/cli"`,
+ } {
+ if !strings.Contains(fresh, want) {
+ t.Errorf("check page is missing %q:\n%s", want, fresh)
+ }
+ }
+}
+
+// Spec 4.2, codex r3-1: with no working mailer an email-bound address is told
+// so, before any send limit, so the answer is the same throttled or not.
+func TestContinueNoMailer(t *testing.T) {
+ fx, m := newEmailFixture(t, false)
+ const addr = "bob@example.com"
+ lookupAnswers(fx, addr, http.StatusNotFound)
+ form := url.Values{"address": {addr}}
+ _, _, first := postContinue(t, fx, newBrowser(t), form)
+ if !strings.Contains(first, esc(copyText("home.no_mail"))) || !strings.Contains(first, `action="/auth/continue"`) {
+ t.Fatalf("no-mailer answer is not the front page with home.no_mail:\n%s", first)
+ }
+ // Spend bob's sign-in sends for the hour, as if he had been mailed.
+ fx.srv.limits.mu.Lock()
+ for i := 0; i < 5; i++ {
+ fx.srv.limits.addrSends.add(addr, time.Now())
+ }
+ fx.srv.limits.mu.Unlock()
+ for i := 2; i <= 6; i++ {
+ if _, _, body := postContinue(t, fx, newBrowser(t), form); body != first {
+ t.Fatalf("request %d differs from the first:\n%s\nvs\n%s", i, body, first)
+ }
+ }
+ if sent := m.sentCopy(); len(sent) != 0 || challengeRows(t, fx) != 0 {
+ t.Fatalf("no mailer, yet sent %q and stored %d challenges", sent, challengeRows(t, fx))
+ }
+ // A Keymail address still signs in.
+ lookupAnswers(fx, "kim@example.com", http.StatusOK)
+ if status, loc, _ := postContinue(t, fx, newBrowser(t), url.Values{"address": {"kim@example.com"}}); status != http.StatusSeeOther || loc != "/auth/signin" {
+ t.Fatalf("Keymail address with no mailer = %d -> %q", status, loc)
+ }
+}
+
+func TestContinueCrossSiteRefused(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ lookupAnswers(fx, "bob@example.com", http.StatusNotFound)
+ form := url.Values{"address": {"bob@example.com"}}
+ if status, _, _ := postContinueFrom(t, fx, newBrowser(t), "https://evil.example", form); status != http.StatusForbidden {
+ t.Fatalf("cross-site continue = %d, want 403", status)
+ }
+ if status, _, _ := postContinueFrom(t, fx, newBrowser(t), "null", form); status != http.StatusForbidden {
+ t.Fatalf("opaque-origin continue = %d, want 403", status)
+ }
+ // No Origin, but the browser says the request came from another site.
+ req, _ := http.NewRequest(http.MethodPost, fx.ts.URL+"/auth/continue", strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Sec-Fetch-Site", "cross-site")
+ res, err := newBrowser(t).Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ if res.StatusCode != http.StatusForbidden {
+ t.Fatalf("Sec-Fetch-Site cross-site continue = %d, want 403", res.StatusCode)
+ }
+ if n := lookupCount(fx); n != 0 || len(m.sentCopy()) != 0 || challengeRows(t, fx) != 0 {
+ t.Fatalf("a refused request still acted: %d lookups, %d sent, %d challenges", n, len(m.sentCopy()), challengeRows(t, fx))
+ }
+}
+
+func TestSameOrigin(t *testing.T) {
+ fx := newConsoleFixture(t)
+ for _, tc := range []struct {
+ origin, site string
+ want bool
+ }{
+ {"", "", true},
+ {fx.ts.URL, "", true},
+ {fx.ts.URL, "cross-site", true}, // Origin decides when present
+ {"https://evil.example", "same-origin", false},
+ {"null", "", false},
+ {"", "same-origin", true},
+ {"", "none", true},
+ {"", "same-site", false},
+ {"", "cross-site", false},
+ } {
+ r := httptest.NewRequest(http.MethodPost, "/auth/continue", nil)
+ if tc.origin != "" {
+ r.Header.Set("Origin", tc.origin)
+ }
+ if tc.site != "" {
+ r.Header.Set("Sec-Fetch-Site", tc.site)
+ }
+ if got := fx.srv.sameOrigin(r); got != tc.want {
+ t.Errorf("sameOrigin(Origin %q, Sec-Fetch-Site %q) = %v, want %v", tc.origin, tc.site, got, tc.want)
+ }
+ }
+}
+
+func TestInvitePageSignedOutPrefills(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ tok, err := fx.st.CreateInvite(OpsAccountID, "bob@example.com", "paul@keymail.dev", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ c := newBrowser(t)
+ status, _, body := get(t, c, fx.ts.URL+"/invite/"+tok)
+ next := "/invite/" + tok
+ for _, want := range []string{
+ esc(copyText("home.invite_prompt", "address", "bob@example.com")),
+ `value="bob@example.com"`,
+ `name="next" value="` + esc(next) + `"`,
+ } {
+ if status != http.StatusOK || !strings.Contains(body, want) {
+ t.Fatalf("signed-out invite page = %d, missing %q:\n%s", status, want, body)
+ }
+ }
+ // Reading the page did not use the invitation up.
+ if _, ok := fx.st.PendingInviteAddress(tok, time.Now()); !ok {
+ t.Fatal("the signed-out invite page consumed the invitation")
+ }
+ // The form carries next into the challenge.
+ lookupAnswers(fx, "bob@example.com", http.StatusNotFound)
+ status, _, body = postContinue(t, fx, c, url.Values{"address": {"bob@example.com"}, "next": {next}})
+ checkEmailSent(t, fx, m, c, "bob@example.com", next, status, body)
+
+ // An unknown invitation is the plain front page: no banner, no prefill.
+ status, _, body = get(t, newBrowser(t), fx.ts.URL+"/invite/no-such-invite")
+ if status != http.StatusOK || !strings.Contains(body, `action="/auth/continue"`) {
+ t.Fatalf("unknown invite signed out = %d:\n%s", status, body)
+ }
+ if strings.Contains(body, "to accept your invitation") || strings.Contains(body, `name="next"`) || strings.Contains(body, "bob@example.com") {
+ t.Fatalf("unknown invite page carries a banner, next or prefill:\n%s", body)
+ }
+}
+
+func TestCLIPageSignedOutBanner(t *testing.T) {
+ fx := newConsoleFixture(t)
+ status, _, body := get(t, newBrowser(t), fx.ts.URL+"/auth/cli")
+ if status != http.StatusOK || !strings.Contains(body, esc(copyText("home.cli_prompt"))) ||
+ !strings.Contains(body, `name="next" value="/auth/cli"`) || !strings.Contains(body, `action="/auth/continue"`) {
+ t.Fatalf("signed-out /auth/cli = %d:\n%s", status, body)
+ }
+ _, _, body = get(t, newBrowser(t), fx.ts.URL+"/auth/cli?code=wxyz4823")
+ if want := `name="next" value="` + esc("/auth/cli?code=WXYZ-4823") + `"`; !strings.Contains(body, want) {
+ t.Fatalf("signed-out /auth/cli?code= lost the code, missing %q:\n%s", want, body)
+ }
+ // A code that is not code-shaped is not carried.
+ _, _, body = get(t, newBrowser(t), fx.ts.URL+"/auth/cli?code="+url.QueryEscape(strings.Repeat("x", 500)))
+ if !strings.Contains(body, `name="next" value="/auth/cli"`) {
+ t.Fatalf("an odd code was carried into next:\n%s", body)
+ }
+}
+
+func TestHomeCarriesSafeNext(t *testing.T) {
+ fx := newConsoleFixture(t)
+ _, _, body := get(t, newBrowser(t), fx.ts.URL+"/?next="+url.QueryEscape("/auth/cli"))
+ if !strings.Contains(body, `name="next" value="/auth/cli"`) {
+ t.Fatalf("home dropped a safe next:\n%s", body)
+ }
+ _, _, body = get(t, newBrowser(t), fx.ts.URL+"/?next="+url.QueryEscape("//evil.example"))
+ if strings.Contains(body, `name="next"`) {
+ t.Fatalf("home carried an unsafe next:\n%s", body)
+ }
+ for _, want := range []string{esc(copyText("home.email_label")), esc(copyText("home.email_button")),
+ esc(copyText("home.small")), `placeholder="` + esc(copyText("home.email_placeholder")) + `"`} {
+ if !strings.Contains(body, want) {
+ t.Errorf("home is missing %q", want)
+ }
+ }
+ if strings.Contains(body, "Sign in with Keymail") || strings.Contains(body, `href="/auth/signin"`) {
+ t.Fatal("home still links the Keymail ceremony directly")
+ }
+}
diff --git a/internal/console/keymail_test.go b/internal/console/keymail_test.go
index 4cd409e62..efab8f993 100644
--- a/internal/console/keymail_test.go
+++ b/internal/console/keymail_test.go
@@ -77,6 +77,8 @@ type fakeKeymail struct {
// it hold the answer for that long (or until the caller gives up).
lookupStatus map[string]int
lookupStall map[string]time.Duration
+ // lookups counts every federation lookup the fake answered or was asked.
+ lookups int
// deliverStatus, when set, makes /api/federation/deliver answer that
// status (an ordinary post-lookup failure) before looking at the envelope.
deliverStatus int
@@ -220,6 +222,7 @@ func (f *fakeKeymail) handleRevoke(w http.ResponseWriter, r *http.Request) {
func (f *fakeKeymail) handleLookup(w http.ResponseWriter, r *http.Request) {
addr := r.URL.Query().Get("addr")
f.mu.Lock()
+ f.lookups++
stall, status := f.lookupStall[addr], f.lookupStatus[addr]
f.mu.Unlock()
if stall > 0 {
diff --git a/internal/console/server.go b/internal/console/server.go
index d0c0d724a..7e265d66b 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -954,9 +954,17 @@ type Server struct {
sendApp func(ctx context.Context, token, to, subject, body string) (string, error)
// Invite delivery (handleInvite): Keymail federation first, then the
// console's own email. Fields so tests can substitute and shrink them.
- sendFederated func(ctx context.Context, to, subject, body string) (string, error)
- consoleMail ConsoleMailer
- consoleNameCfg string
+ sendFederated func(ctx context.Context, to, subject, body string) (string, error)
+ consoleMail ConsoleMailer
+ consoleNameCfg string
+ // limits are email sign-in's rate limits (emailsignin_limits.go): in
+ // memory, one console process per deployment.
+ limits emailLimits
+ // challengeSem bounds the sign-in and step-up sends in flight
+ // (sendChallengeAsync). challengeSent, when non-nil, is signalled after
+ // each one finishes or is dropped. Tests only, as cliNotified.
+ challengeSem chan struct{}
+ challengeSent chan struct{}
inviteTimeout time.Duration
inviteKeymailShare time.Duration
// inviteRate is each account's invites created in the last hour
@@ -1353,6 +1361,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
storeWalks: newStoreWalkLocks(),
consoleMail: cfg.ConsoleMail,
consoleNameCfg: cfg.ConsoleName,
+ challengeSem: make(chan struct{}, challengeSendSlots),
inviteTimeout: 20 * time.Second,
inviteKeymailShare: 12 * time.Second,
// This process's identity in the relay writer lease. Random rather
@@ -1774,8 +1783,16 @@ type page struct {
ActiveTab string // app pages: "overview" | "releases" | "instances" | "activity" | "settings"
AppName string // app pages: the {app} segment, for the tab bar and eyebrow
- SubmittedAddr string // interstitial: the address the user typed
- KeymailURL string // interstitial: link to that address's keymail host
+ // The signed-out front page and "Check your email" (emailsignin.go).
+ // Prefill is the address the form starts with; Next the safe local path
+ // carried as a hidden field; Banner a note above the form (an invite, a
+ // terminal); NoMail shows home.no_mail; CheckSent is check.sent, filled;
+ // CodeError a refusal of a typed code. SigninCopy is the approved copy,
+ // set by render.
+ Prefill, Next, Banner string
+ NoMail bool
+ CheckSent, CodeError string
+ SigninCopy signinView
Msg string // generic message page body
@@ -2097,6 +2114,7 @@ func (s *Server) render(w http.ResponseWriter, status int, name string, p page)
p.StatusCopy = approvedStatusCopy
p.BrowserRestartCopy = approvedBrowserRestartCopy
p.MismatchCopy = approvedMismatchCopy
+ p.SigninCopy = approvedSigninView
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status)
if err := templates.ExecuteTemplate(w, name, p); err != nil {
@@ -2183,8 +2201,7 @@ func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) {
s.redirectToCurrentAccount(w, r, addr, http.StatusFound)
return
}
- p := page{Title: "Sign in"}
- s.render(w, http.StatusOK, "home", p)
+ s.renderHome(w, homeForm{Next: r.URL.Query().Get("next")})
}
// redirectToCurrentAccount sends a signed-in user to the account they were
@@ -2650,16 +2667,27 @@ func (s *Server) invitationGone(w http.ResponseWriter, r *http.Request) {
// top-level navigation (discussion #219, item 4). Links already sent keep
// working; they land on this page.
//
-// It requires a session as the invited address — the link lands in one
-// Keymail inbox and is worthless to anyone else. An address that has never
-// signed in does the OAuth ceremony first and comes back to the link.
+// It requires a session as the invited address: the link reaches one
+// address and is worthless to anyone else. Signed out, it is the front page
+// with the invited address filled in and next set back to this link, so
+// either sign-in door returns here (spec 8). An unknown or spent token gets
+// the plain front page.
func (s *Server) handleInvitePage(w http.ResponseWriter, r *http.Request) {
+ token := r.PathValue("token")
addr, raw, ok := s.session(r)
if !ok {
- http.Redirect(w, r, "/", http.StatusFound)
+ invited, found := s.store.PendingInviteAddress(token, time.Now())
+ if !found {
+ s.renderHome(w, homeForm{})
+ return
+ }
+ s.renderHome(w, homeForm{
+ Prefill: invited,
+ Next: "/invite/" + url.PathEscape(token),
+ Banner: copyText("home.invite_prompt", "address", invited),
+ })
return
}
- token := r.PathValue("token")
inv, err := s.store.PendingInviteFor(token, addr, time.Now())
if err != nil {
s.invitationGone(w, r)
@@ -2717,48 +2745,88 @@ func (s *Server) handleAcceptInvite(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/a/"+url.PathEscape(a.Sqid)+"/", http.StatusSeeOther)
}
-// handleContinue is the one button: empty address → the OAuth sign-up
-// ceremony; an address → a confirmation link into its Keymail Apps inbox.
-// The interstitial renders identically whether or not the address is known,
-// and whether or not the send succeeded — the console never confirms an
-// account's existence (anti-enumeration).
+// handleContinue is the front page's one form (spec 4): it finds the door
+// from the address alone. A Keymail address goes to Keymail's sign-in; any
+// other gets an emailed link and code. Every email-bound outcome renders the
+// same "Check your email" page, whether a message was sent, throttled or
+// refused, so the page reveals neither an account nor a rate limit.
func (s *Server) handleContinue(w http.ResponseWriter, r *http.Request) {
+ if !s.sameOrigin(r) {
+ s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
+ return
+ }
now := time.Now()
s.store.PurgeExpired(now) // housekeeping on the write path
- addr := strings.ToLower(strings.TrimSpace(r.FormValue("address")))
- if addr == "" {
- http.Redirect(w, r, "/auth/signin", http.StatusSeeOther)
+ typed := strings.TrimSpace(r.FormValue("address"))
+ next := safeNext(r.FormValue("next"))
+ addr, ok := canonicalAddress(typed)
+ if !ok {
+ s.renderHome(w, homeForm{Prefill: typed, Next: next, Error: copyText("home.bad_address")})
return
}
- if !ValidAddress(addr) {
- p := page{Title: "Sign in", Error: "That doesn't look like a keymail address — expected something like you@keymail.dev."}
- s.render(w, http.StatusOK, "home", p)
+ ip := s.clientIP(r)
+ if !s.limits.submit(ip) {
+ log.Printf("console: sign-in submissions from %s over the hourly cap", ip)
+ s.keepChallengeCookie(w, r)
+ s.renderCheck(w, addr, next)
return
}
- if tok, _ := s.store.GrantToken(addr); tok != "" {
- if raw, err := s.store.CreateConfirmation(addr, now); err == nil {
- link := s.cfg.Origin + "/auth/confirm?token=" + url.QueryEscape(raw)
- ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
- defer cancel()
- _, err := s.km.SendApp(ctx, tok, addr,
- "Sign in to the CARLOS platform console",
- "Someone (hopefully you) asked to sign in to the CARLOS platform console as "+addr+".\n\n"+
- "This link works once and expires in 15 minutes:\n\n"+link+"\n\n"+
- "If this wasn't you, ignore this message — nothing happens without the link.")
- if err != nil {
- // Best-effort by design: the interstitial shows regardless, so a
- // dead grant (401) or a keymail hiccup reveals nothing here. The
- // interstitial's OAuth fallback is the road back.
- log.Printf("console: confirmation send to %s: %v", addr, err)
- }
+ if s.keymailAddress(r.Context(), addr) {
+ target := "/auth/signin"
+ if next != "" {
+ target += "?next=" + url.QueryEscape(next)
}
+ http.Redirect(w, r, target, http.StatusSeeOther)
+ return
}
- p := page{
- Title: "Check your Keymail",
- SubmittedAddr: addr,
- KeymailURL: "https://" + addr[strings.LastIndex(addr, "@")+1:] + "/",
+ // Before the send limits (spec 4.2), so throttling stays invisible.
+ if !s.mailReady(r.Context()) {
+ s.renderHome(w, homeForm{Prefill: addr, Next: next, NoMail: true})
+ return
+ }
+ if !s.limits.signinSend(addr, ip) {
+ log.Printf("console: sign-in email to %s from %s over its limits; not sent", addr, ip)
+ s.keepChallengeCookie(w, r)
+ s.renderCheck(w, addr, next)
+ return
+ }
+ replace := ""
+ if c, err := r.Cookie(challengeCookie); err == nil {
+ replace = c.Value
+ }
+ id, link, code, err := s.store.CreateEmailChallenge(EmailChallenge{
+ Purpose: ChallengeSignIn, Address: addr, Next: next,
+ }, replace, now)
+ if err != nil {
+ log.Printf("console: sign-in challenge for %s: %v", addr, err)
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not start the sign-in flow. Please try again.")
+ return
+ }
+ s.setCookie(w, challengeCookie, id, int(ConfirmationTTL.Seconds()))
+ console := s.consoleName()
+ s.sendChallengeAsync(addr,
+ copyText("email.signin.subject", "console", console),
+ copyText("email.signin.body", "console", console, "address", addr,
+ "link", s.cfg.Origin+"/auth/email/link?t="+link, "code", code))
+ s.renderCheck(w, addr, next)
+}
+
+// keepChallengeCookie re-sets this browser's challenge cookie (or, with none,
+// a random stand-in that names nothing) when the front door sends nothing, so
+// the response carries the same Set-Cookie as one that sent. The earlier
+// challenge, if any, keeps working.
+func (s *Server) keepChallengeCookie(w http.ResponseWriter, r *http.Request) {
+ v := ""
+ if c, err := r.Cookie(challengeCookie); err == nil {
+ v = c.Value
+ }
+ if v == "" {
+ var err error
+ if v, err = randomToken(); err != nil {
+ return
+ }
}
- s.render(w, http.StatusOK, "check", p)
+ s.setCookie(w, challengeCookie, v, int(ConfirmationTTL.Seconds()))
}
// ValidAddress is the console's one shape check on a keymail address:
diff --git a/internal/console/server_test.go b/internal/console/server_test.go
index 9a0af8938..a323bf16f 100644
--- a/internal/console/server_test.go
+++ b/internal/console/server_test.go
@@ -13,7 +13,6 @@ import (
"net/url"
"os"
"path/filepath"
- "regexp"
"slices"
"strings"
"testing"
@@ -216,8 +215,8 @@ func TestConsoleE2E(t *testing.T) {
if status, loc, _ := get(t, c, fx.u("/")); status != http.StatusFound || loc != "/" {
t.Fatalf("signed-out /apps = %d -> %q, want 302 -> /", status, loc)
}
- if _, _, body := get(t, c, fx.ts.URL+"/"); !strings.Contains(body, "Sign in with Keymail") {
- t.Fatal("landing page is missing the sign-in button")
+ if _, _, body := get(t, c, fx.ts.URL+"/"); !strings.Contains(body, `action="/auth/continue"`) {
+ t.Fatal("landing page is missing the sign-in form")
}
signUp(t, fx, c, "code-1")
@@ -326,83 +325,6 @@ func TestHealthzCarriesTheBuild(t *testing.T) {
}
}
-var confirmLinkRe = regexp.MustCompile(`https?://[^\s"]+/auth/confirm\?token=[A-Za-z0-9_%.~-]+`)
-
-func TestReturningSignInViaConfirmationLink(t *testing.T) {
- fx := newConsoleFixture(t)
- signUp(t, fx, newBrowser(t), "code-1") // the one-time ceremony stores the grant
-
- // A fresh browser, no session: the console sends a confirmation link
- // into the Apps inbox using the stored grant.
- c := newBrowser(t)
- status, _, body := postForm(t, c, fx.ts.URL+"/auth/continue", url.Values{"address": {"paul@keymail.dev"}})
- if status != 200 || !strings.Contains(body, "Check your Keymail") {
- t.Fatalf("continue = %d %q", status, body)
- }
- fx.fk.mu.Lock()
- if len(fx.fk.sends) != 1 {
- fx.fk.mu.Unlock()
- t.Fatalf("keymail got %d sends, want 1", len(fx.fk.sends))
- }
- sent := fx.fk.sends[0]
- fx.fk.mu.Unlock()
- if sent.To != "paul@keymail.dev" || !strings.Contains(sent.Subject, "Sign in") {
- t.Fatalf("sent = %+v", sent)
- }
- link := confirmLinkRe.FindString(sent.Body)
- if link == "" {
- t.Fatalf("no confirmation link in sealed body: %q", sent.Body)
- }
-
- // The link mints a session — once. Landing prefers the readable segment:
- // the fixture's only account for paul is named "ops", slug-shaped and
- // unique for him, so preferredSeg picks the name over fx.sqid ("bab").
- if status, loc, _ := get(t, c, link); status != http.StatusSeeOther || loc != "/a/ops/" {
- t.Fatalf("confirm = %d -> %q, want 303 -> /a/ops/", status, loc)
- }
- _, _, body = get(t, c, fx.u("/"))
- if !strings.Contains(body, "kass") {
- t.Fatal("confirmed session doesn't see the user's apps")
- }
- if strings.Contains(body, "Account created") {
- t.Fatal("returning sign-in flashed the account-created banner")
- }
- if status, _, body := get(t, newBrowser(t), link); status != http.StatusGone || !strings.Contains(body, "already used") {
- t.Fatalf("reused link = %d %q, want 410", status, body)
- }
-}
-
-func TestContinueIndistinguishableAndOAuthFallback(t *testing.T) {
- fx := newConsoleFixture(t)
- signUp(t, fx, newBrowser(t), "code-1")
-
- normalize := func(body, addr string) string { return strings.ReplaceAll(body, addr, "ADDR") }
-
- sKnown, _, known := postForm(t, newBrowser(t), fx.ts.URL+"/auth/continue", url.Values{"address": {"paul@keymail.dev"}})
- sUnknown, _, unknown := postForm(t, newBrowser(t), fx.ts.URL+"/auth/continue", url.Values{"address": {"stranger@keymail.dev"}})
- if sKnown != sUnknown {
- t.Fatalf("status differs: known %d, unknown %d", sKnown, sUnknown)
- }
- if normalize(known, "paul@keymail.dev") != normalize(unknown, "stranger@keymail.dev") {
- t.Fatal("interstitial reveals whether an address is known")
- }
-
- // A revoked grant (send 401) must render the same interstitial — the
- // OAuth ceremony link on it is the road back, and it must always be there.
- fx.fk.mu.Lock()
- fx.fk.send401 = true
- fx.fk.mu.Unlock()
- sRevoked, _, revoked := postForm(t, newBrowser(t), fx.ts.URL+"/auth/continue", url.Values{"address": {"paul@keymail.dev"}})
- if sRevoked != sKnown || normalize(revoked, "paul@keymail.dev") != normalize(unknown, "stranger@keymail.dev") {
- t.Fatal("revoked-grant interstitial is distinguishable")
- }
- for _, body := range []string{known, unknown, revoked} {
- if !strings.Contains(body, `href="/auth/signin"`) {
- t.Fatal("interstitial is missing the OAuth fallback link")
- }
- }
-}
-
func TestSecondOAuthIsPlainSignIn(t *testing.T) {
fx := newConsoleFixture(t)
c1 := newBrowser(t)
diff --git a/internal/console/store.go b/internal/console/store.go
index 4b6680f3a..14ac7bc6a 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -1379,6 +1379,20 @@ FROM invites WHERE token = ?`, token).Scan(&i.Token, &i.AccountID, &i.Address, &
return &i, nil
}
+// PendingInviteAddress is the address an invite was sent to, read without
+// consuming it, and only while the invite is unaccepted and unexpired: the
+// signed-out invite page fills it into the sign-in form.
+func (s *Store) PendingInviteAddress(token string, now time.Time) (string, bool) {
+ var addr string
+ var expires, accepted int64
+ err := s.db.QueryRow(`SELECT address, expires_at, accepted_at FROM invites WHERE token = ?`,
+ token).Scan(&addr, &expires, &accepted)
+ if err != nil || accepted != 0 || now.Unix() > expires {
+ return "", false
+ }
+ return addr, true
+}
+
// AcceptInvite consumes an invite and creates the membership, in one
// transaction. Three gates, all inside it: the token must be unaccepted, the
// address must be the one it was addressed to (an invite is not a bearer
diff --git a/internal/console/templates/check.html b/internal/console/templates/check.html
index be30d57fa..08e856886 100644
--- a/internal/console/templates/check.html
+++ b/internal/console/templates/check.html
@@ -1,6 +1,16 @@
{{define "check"}}{{template "top" .}}
-<h1>Check your Keymail</h1>
-<p>If <strong>{{.SubmittedAddr}}</strong> has signed up here before, a single-use sign-in link is on its way to its <strong>Apps</strong> inbox. The link works once and expires in 15 minutes.</p>
-<p><a class="btn" href="{{.KeymailURL}}">Open Keymail</a></p>
-<p class="small">Nothing arriving, or first time here? <a href="/auth/signin">Approve the console in Keymail instead</a> — that works whether or not this address has been here before, and refreshes the console's permission if you had revoked it.</p>
+<h1>{{.SigninCopy.CheckTitle}}</h1>
+<p>{{.CheckSent}}</p>
+<form class="signin" method="post" action="/auth/email/code">
+ <label for="code">{{.SigninCopy.CodeLabel}}</label>
+ <input id="code" type="text" name="code" inputmode="numeric" autocomplete="one-time-code" required autofocus>
+ <button type="submit">{{.SigninCopy.CodeButton}}</button>
+</form>
+{{if .CodeError}}<p class="error">{{.CodeError}}</p>{{end}}
+<p class="small">{{.SigninCopy.Nothing}}</p>
+<form class="signin" method="post" action="/auth/continue">
+ <input type="hidden" name="address" value="{{.Prefill}}">
+ {{if .Next}}<input type="hidden" name="next" value="{{.Next}}">{{end}}
+ <button type="submit">{{.SigninCopy.AgainButton}}</button>
+</form>
{{template "bottom" .}}{{end}}
diff --git a/internal/console/templates/home.html b/internal/console/templates/home.html
index 56fc3ef42..7099f68e9 100644
--- a/internal/console/templates/home.html
+++ b/internal/console/templates/home.html
@@ -5,13 +5,14 @@
<p class="lede">Your apps, their live routes, and their release channels —
signed releases in, immutable bytes out.</p>
</div>
+{{if .Banner}}<p class="banner">{{.Banner}}</p>{{end}}
{{if .Error}}<p class="error">{{.Error}}</p>{{end}}
-<form class="signin" method="get" action="/auth/signin">
- <button type="submit">Sign in with Keymail</button>
+{{if .NoMail}}<p class="error">{{.SigninCopy.NoMail}}</p>{{end}}
+<form class="signin" method="post" action="/auth/continue">
+ <label for="address">{{.SigninCopy.EmailLabel}}</label>
+ <input id="address" type="email" name="address" value="{{.Prefill}}" placeholder="{{.SigninCopy.EmailPlaceholder}}" autocomplete="email" required autofocus>
+ {{if .Next}}<input type="hidden" name="next" value="{{.Next}}">{{end}}
+ <button type="submit">{{.SigninCopy.EmailButton}}</button>
</form>
-<p class="small">One button, whether it's your first time or your five-hundredth.
-First visits approve the console once in your Keymail — that single approval
-is the whole sign-up. After that, the same button is a one-click sign-in.
-No passwords, ever; revoke the console from Keymail's connected apps at any
-time.</p>
+<p class="small">{{.SigninCopy.Small}}</p>
{{template "bottom" .}}{{end}}
diff --git a/internal/console/templates/layout.html b/internal/console/templates/layout.html
index cd4ef06c9..172755dd3 100644
--- a/internal/console/templates/layout.html
+++ b/internal/console/templates/layout.html
@@ -44,7 +44,7 @@
should wrap inside the box rather than force the horizontal scrollbar
every other <pre> on this page gets for a shell command. */
.changelog { white-space: pre-wrap; }
- select, input[type=text], input[type=search] {
+ select, input[type=text], input[type=search], input[type=email] {
font: inherit; font-family: var(--sans); font-size: 0.9rem; color: var(--ink); background: var(--bg);
border: 1px solid var(--rule); border-radius: 0.4rem; padding: 0.3rem 0.5rem;
}
@@ -418,7 +418,8 @@
}
th, td { padding: 0.5rem 1rem 0.5rem 0; border-bottom: 1px solid var(--rule); }
form.signin { display: flex; gap: 0.6rem; flex-wrap: wrap; margin: 0 0 1rem; }
- form.signin input[type=text] { padding: 0.55rem 0.8rem; min-width: 16rem; }
+ form.signin input[type=text], form.signin input[type=email] { padding: 0.55rem 0.8rem; min-width: 16rem; }
+ form.signin label { flex-basis: 100%; font-weight: 600; }
button, .btn {
font-size: 0.95rem; font-weight: 600; background: var(--accent);
color: var(--bg); border: 0; border-radius: 0.4rem;