Sign in to Base with a passkey
Members add a passkey from Settings and sign in with "Or use a passkey" on the sign-in page, through rastrillo/passkey's register and discover pairs. A passkey sign-in passes the same admission check as an emailed link. Both buttons ship hidden and are revealed only where the browser can run a ceremony, so with scripts off neither shows and email sign-in is unchanged. passkey.Schema joins BootSchema. internal/browsertest holds the real-browser suite (go test -tags browser), on rastrillo's harness with a virtual authenticator. New strings are listed in docs/copy-pending.md.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
16 files changed,
+599
−6
docs/copy-pending.md+16 −0go.mod+2 −0internal/browsertest/base_test.go+190 −0internal/browsertest/doc.go+8 −0internal/browsertest/passkey_test.go+111 −0internal/look/static/app.css+6 −0internal/look/static/passkey-add.js+56 −0internal/store/migrations.go+4 −2internal/web/app.go+24 −0internal/web/passkey.go+36 −0internal/web/settings.go+28 −2internal/web/signin.go+2 −0internal/web/templates/settings.html+4 −0internal/web/templates/signin.html+4 −1internal/webtest/passkey_test.go+107 −0internal/webtest/signin_test.go+1 −1
diff --git a/docs/copy-pending.md b/docs/copy-pending.md| index cab203f..cc22877 100644 |
| --- a/docs/copy-pending.md |
| +++ b/docs/copy-pending.md |
| @@ -131,3 +131,19 @@ Installed apps: the shared sign-in (`internal/consumer`), Scratchpad and Welcome |
| | internal/welcome/welcome.go | Page failed to render (500) | something went wrong | |
| "Signed in as {name}, {Base name}" on Scratchpad is the spec's own wording (5.8). When Base has no name for a person, their email stands in for {name}. |
| + |
| +Passkeys (sign-in page and Settings): |
| + |
| +| File | Context | Text | |
| +|---|---|---| |
| +| internal/web/templates/signin.html | Sign-in page, passkey button, shown only when the browser can use a passkey (from the mockup; the plan says "Use a passkey") | Or use a passkey | |
| +| internal/web/templates/signin.html | Passkey sign-in: the person closed the prompt, or has no passkey here (rastrillo's English) | No passkey was used. Try again, or use your email. | |
| +| internal/web/templates/signin.html | Passkey sign-in failed (rastrillo's English) | That didn't work. Try again, or use your email. | |
| +| internal/web/templates/settings.html | Settings label | Passkeys | |
| +| internal/web/templates/settings.html | Passkeys row, none yet | None yet | |
| +| internal/web/templates/settings.html | Passkeys row, how many | {n} added | |
| +| internal/web/templates/settings.html | Settings button, shown only when the browser can make a passkey | Add a passkey | |
| +| internal/web/templates/settings.html | After adding a passkey | Passkey added. Next time, sign in with it. | |
| +| internal/web/templates/settings.html | Adding a passkey: the person closed the prompt | No passkey was added. | |
| +| internal/web/templates/settings.html | Adding a passkey failed | That didn't work. Try again. | |
| +| internal/web/settings.go | Passkey list failed (503) | unavailable | |
diff --git a/go.mod b/go.mod| index f46c5b9..200a83f 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -4,6 +4,8 @@ go 1.26.0 |
| require ( |
| amadan.net/rastrillo/rastrillo v0.33.0 |
| + github.com/chromedp/cdproto v0.158.6 |
| + github.com/chromedp/chromedp v0.21.0 |
| github.com/go-chi/chi/v5 v5.3.2 |
| ) |
diff --git a/internal/browsertest/base_test.go b/internal/browsertest/base_test.go| new file mode 100644 |
| index 0000000..0ec92ea |
| --- /dev/null |
| +++ b/internal/browsertest/base_test.go |
| @@ -0,0 +1,190 @@ |
| +//go:build browser |
| + |
| +package browsertest |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "html" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "path/filepath" |
| + "regexp" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/chromedp/chromedp" |
| + |
| + "amadan.net/rastrillo/rastrillo" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/harness" |
| + _ "amadan.net/rastrillo/rastrillo/locales/en" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "amadan.net/rastrillo/rastrillo/pow" |
| + |
| + "amadan.net/carlos/base/internal/config" |
| + "amadan.net/carlos/base/internal/store" |
| + "amadan.net/carlos/base/internal/web" |
| +) |
| + |
| +const ( |
| + ownerAddress = "paul@acme.test" |
| + ownerName = "Paul Campbell" |
| + baseName = "Acme Ltd" |
| + // timelessFont is preloaded by every page. It is git-ignored and fetched |
| + // by make fonts, so on a machine without it the browser gets a 404 and |
| + // the page falls back to DM Sans, as designed. |
| + timelessFont = "/static/fonts/timeless/1.094/TimelessSansVF.woff2" |
| +) |
| + |
| +var quiet = slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + |
| +// mailbox keeps every message Base sends. |
| +type mailbox struct { |
| + mu sync.Mutex |
| + bodies []string |
| +} |
| + |
| +func (m *mailbox) Send(_ context.Context, _, _, body string) error { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + m.bodies = append(m.bodies, body) |
| + return nil |
| +} |
| + |
| +func (m *mailbox) count() int { m.mu.Lock(); defer m.mu.Unlock(); return len(m.bodies) } |
| + |
| +var linkRE = regexp.MustCompile(`https?://[^\s"<>]+/auth/verify\?[^\s"<>]+`) |
| + |
| +// lastLink is the sign-in link in the latest message. |
| +func (m *mailbox) lastLink(t *testing.T) string { |
| + t.Helper() |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + if len(m.bodies) == 0 { |
| + t.Fatal("Base sent no email") |
| + } |
| + body := html.UnescapeString(m.bodies[len(m.bodies)-1]) |
| + link := linkRE.FindString(body) |
| + if link == "" { |
| + t.Fatalf("no sign-in link in:\n%s", body) |
| + } |
| + return link |
| +} |
| + |
| +type noInstaller struct{} |
| + |
| +func (noInstaller) Install(context.Context, string) error { return nil } |
| +func (noInstaller) Uninstall(context.Context, string) error { return nil } |
| + |
| +// baseApp is one Base over its own database, with the owner seeded. |
| +type baseApp struct { |
| + cfg config.Config |
| + db *sql.DB |
| + mail *mailbox |
| + handler http.Handler // wrapped as production wraps it |
| +} |
| + |
| +// baseConfig is the configuration every test starts from. |
| +func baseConfig(origin string) config.Config { |
| + return config.Config{Origin: origin, Name: baseName, Owner: ownerAddress, InstanceKey: "browser-instance-key", |
| + AllowLoggedMail: true, Slug: "acme", AppsDomain: "test", Timezone: time.UTC} |
| +} |
| + |
| +// newBase builds Base as cmd/base/main.go does: BootSchema applied, the owner |
| +// bootstrapped, web.App wrapped by rastrillo's serving stack. |
| +func newBase(t *testing.T, cfg config.Config) *baseApp { |
| + t.Helper() |
| + d, err := db.Open(filepath.Join(t.TempDir(), "base.db"), quiet) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + ctx := context.Background() |
| + if _, err := migrate.Apply(ctx, d, store.BootSchema); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := store.Bootstrap(ctx, d.Writer(), cfg.Owner); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := d.Writer().Exec(`UPDATE members SET name = ?`, ownerName); err != nil { |
| + t.Fatal(err) |
| + } |
| + b := &baseApp{cfg: cfg, db: d.Writer(), mail: &mailbox{}} |
| + h, err := web.App(d, cfg, b.mail, noInstaller{}, quiet) |
| + if err != nil { |
| + t.Fatalf("web.App: %v", err) |
| + } |
| + b.handler = served(t, h) |
| + return b |
| +} |
| + |
| +// served wraps h in what rastrillo.Serve puts around an app in production |
| +// (cmd/base and appboot): the framework's endpoints, panic recovery and the |
| +// security headers, default CSP and Referrer-Policy included. Only the |
| +// listener differs. |
| +func served(t *testing.T, h http.Handler) http.Handler { |
| + t.Helper() |
| + mux := http.NewServeMux() |
| + mux.Handle("/", h) |
| + out, closeAll, err := rastrillo.Handler(rastrillo.Options{Mux: mux, Logger: quiet}) |
| + if err != nil { |
| + t.Fatalf("rastrillo.Handler: %v", err) |
| + } |
| + t.Cleanup(func() { closeAll() }) |
| + return out |
| +} |
| + |
| +// driveBudget bounds one drive: a wait for something that never comes fails |
| +// as itself instead of hanging the suite until go test's own timeout. |
| +const driveBudget = 30 * time.Second |
| + |
| +// drive runs steps under driveBudget and fails the test with what was on |
| +// screen, as the harness's own Run does. |
| +func drive(t *testing.T, rig *harness.Rig, steps ...chromedp.Action[chromedp.Void]) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(rig.Context(), driveBudget) |
| + defer cancel() |
| + if err := chromedp.Do(ctx, steps...); err != nil { |
| + here, _ := chromedp.Run(rig.Context(), chromedp.Location()) |
| + text, _ := chromedp.Run(rig.Context(), chromedp.Evaluate[string](`document.body ? document.body.innerText : ""`)) |
| + t.Fatalf("drive failed at %s: %v\non screen:\n%s", here, err, text) |
| + } |
| +} |
| + |
| +// newRig starts Chromium with the harness's watchers. The font every page |
| +// preloads may be missing on this machine; that 404 is expected. |
| +func newRig(t *testing.T, build func(origin string) http.Handler) *harness.Rig { |
| + t.Helper() |
| + rig := harness.New(t, build) |
| + rig.Allow(http.MethodGet, timelessFont, http.StatusNotFound) |
| + return rig |
| +} |
| + |
| +// signInByEmail signs the owner in at origin the way a person does: type the |
| +// address, press Continue, open the emailed link and press Sign in. It ends |
| +// on Home. |
| +func signInByEmail(t *testing.T, rig *harness.Rig, origin string, mail *mailbox) { |
| + t.Helper() |
| + address := `input[name="address"]` |
| + drive(t, rig, chromedp.Navigate(origin+"/signin"), chromedp.WaitVisible(chromedp.CSS(address))) |
| + rig.Screen(".card", "the sign-in page") |
| + drive(t, rig, |
| + chromedp.SendKeys(chromedp.CSS(address), ownerAddress), |
| + // Base refuses a sign-in form sent sooner than a person could read it. |
| + chromedp.Sleep(pow.DefaultMinAge+300*time.Millisecond), |
| + chromedp.Click(chromedp.CSS(`form[action="/auth/begin"] button[type="submit"]`)), |
| + chromedp.WaitVisible(chromedp.CSS(`form[action="/auth/forget"]`)), |
| + ) |
| + rig.Screen(".card", "Check your email") |
| + signIn := `form[action$="/auth/verify"] button[type="submit"]` |
| + drive(t, rig, chromedp.Navigate(mail.lastLink(t)), chromedp.WaitVisible(chromedp.CSS(signIn))) |
| + rig.Screen(".card", "the emailed link's page") |
| + drive(t, rig, chromedp.Click(chromedp.CSS(signIn)), chromedp.WaitVisible(chromedp.CSS(".hello"))) |
| + rig.Screen("main", "Home") |
| + if here := harness.Read(rig, chromedp.Location()); here != origin+"/" { |
| + t.Fatalf("signing in by email ended at %s", here) |
| + } |
| +} |
diff --git a/internal/browsertest/doc.go b/internal/browsertest/doc.go| new file mode 100644 |
| index 0000000..ecbd848 |
| --- /dev/null |
| +++ b/internal/browsertest/doc.go |
| @@ -0,0 +1,8 @@ |
| +// Package browsertest drives Base, and the apps it installs, in a real |
| +// Chromium through rastrillo's harness. Every test here is tagged browser: |
| +// |
| +// RASTRILLO_CHROME=/path/to/chrome go test -tags browser ./internal/browsertest/ |
| +// |
| +// This file is untagged so that a plain go build or go vet still sees a |
| +// package here. |
| +package browsertest |
diff --git a/internal/browsertest/passkey_test.go b/internal/browsertest/passkey_test.go| new file mode 100644 |
| index 0000000..57e0b20 |
| --- /dev/null |
| +++ b/internal/browsertest/passkey_test.go |
| @@ -0,0 +1,111 @@ |
| +//go:build browser |
| + |
| +package browsertest |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "testing" |
| + "time" |
| + |
| + "github.com/chromedp/cdproto/cdp" |
| + "github.com/chromedp/cdproto/emulation" |
| + "github.com/chromedp/chromedp" |
| + |
| + "amadan.net/rastrillo/rastrillo/harness" |
| +) |
| + |
| +// passkeyDoor is the sign-in page's passkey button; addPasskey is Settings'. |
| +const ( |
| + passkeyDoor = `[data-rst-passkey]` |
| + addPasskey = `[data-passkey-add]` |
| +) |
| + |
| +// newPasskeyBase serves Base on the rig's own origin, http://localhost:PORT: |
| +// the one origin a WebAuthn ceremony accepts without a certificate (an IP is |
| +// not a relying party ID, and Chromium refuses WebAuthn on a page with a |
| +// certificate error). |
| +func newPasskeyBase(t *testing.T) (*harness.Rig, *baseApp) { |
| + t.Helper() |
| + var b *baseApp |
| + rig := newRig(t, func(origin string) http.Handler { |
| + b = newBase(t, baseConfig(origin)) |
| + return b.handler |
| + }) |
| + return rig, b |
| +} |
| + |
| +// The owner signs in by email, adds a passkey from Settings, signs out, and |
| +// signs back in with the passkey alone: no second email is sent. |
| +func TestPasskeyRegisterThenSignIn(t *testing.T) { |
| + rig, b := newPasskeyBase(t) |
| + signInByEmail(t, rig, rig.Origin, b.mail) |
| + |
| + drive(t, rig, chromedp.Navigate(rig.Origin+"/settings"), chromedp.WaitVisible(chromedp.CSS(addPasskey))) |
| + rig.Screen(".sheet", "Settings") |
| + if got := harness.Evaluate[string](rig, `document.querySelector("#passkeys").textContent`); got != "None yet" { |
| + t.Fatalf("before adding one, Settings lists passkeys as %q", got) |
| + } |
| + drive(t, rig, chromedp.Click(chromedp.CSS(addPasskey)), chromedp.WaitVisible(chromedp.CSS(`#passkey-added`))) |
| + rig.Screen(".sheet", "Settings, passkey added") |
| + if got := harness.Evaluate[string](rig, `document.querySelector("#passkeys").textContent`); got != "1 added" { |
| + t.Fatalf("after adding one, Settings lists passkeys as %q", got) |
| + } |
| + |
| + drive(t, rig, chromedp.Click(chromedp.CSS(`form[action="/auth/signout"] button`)), chromedp.WaitVisible(chromedp.CSS(passkeyDoor))) |
| + rig.Screen(".card", "the sign-in page after signing out") |
| + if here := harness.Read(rig, chromedp.Location()); here != rig.Origin+"/signin" { |
| + t.Fatalf("signing out ended at %s", here) |
| + } |
| + mails := b.mail.count() |
| + |
| + drive(t, rig, chromedp.Click(chromedp.CSS(passkeyDoor)), chromedp.WaitVisible(chromedp.CSS(".hello"))) |
| + rig.Screen("main", "Home, signed in with a passkey") |
| + if here := harness.Read(rig, chromedp.Location()); here != rig.Origin+"/" { |
| + t.Fatalf("the passkey sign-in ended at %s", here) |
| + } |
| + if n := b.mail.count(); n != mails { |
| + t.Fatalf("the passkey sign-in sent %d emails", n-mails) |
| + } |
| + var method string |
| + if err := b.db.QueryRow(`SELECT method FROM sessions ORDER BY created_at DESC, rowid DESC LIMIT 1`).Scan(&method); err != nil { |
| + t.Fatal(err) |
| + } |
| + if method != "passkey" { |
| + t.Fatalf("the newest session was signed in by %q, want passkey", method) |
| + } |
| +} |
| + |
| +// With scripts off there is no passkey button anywhere, and email sign-in |
| +// still works. |
| +func TestPasskeyButtonsHiddenWithoutScripts(t *testing.T) { |
| + rig, b := newPasskeyBase(t) |
| + drive(t, rig, scriptsDisabled(true)) |
| + |
| + // Half a second is what scripts would need to reveal the button, so a |
| + // hidden one is the scripts' absence, not a read taken too soon. |
| + drive(t, rig, chromedp.Navigate(rig.Origin+"/signin"), chromedp.WaitVisible(chromedp.CSS(`input[name="address"]`)), |
| + chromedp.Sleep(500*time.Millisecond)) |
| + if harness.Evaluate[bool](rig, `document.querySelector("`+passkeyDoor+`").checkVisibility()`) { |
| + t.Fatal("with scripts off the sign-in page shows the passkey button") |
| + } |
| + |
| + signInByEmail(t, rig, rig.Origin, b.mail) |
| + |
| + drive(t, rig, chromedp.Navigate(rig.Origin+"/settings"), chromedp.WaitVisible(chromedp.CSS("#passkeys")), |
| + chromedp.Sleep(500*time.Millisecond)) |
| + rig.Screen(".sheet", "Settings, scripts off") |
| + if harness.Evaluate[bool](rig, `document.querySelector("`+addPasskey+`").checkVisibility()`) { |
| + t.Fatal("with scripts off Settings shows the add-a-passkey button") |
| + } |
| +} |
| + |
| +// scriptsDisabled switches the page's own scripts off or on. DevTools' |
| +// evaluations still run. |
| +func scriptsDisabled(off bool) chromedp.Action[chromedp.Void] { |
| + return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| + _, err := cdp.Call(ctx, target, emulation.SetScriptExecutionDisabled, |
| + emulation.SetScriptExecutionDisabledParams{Value: off}) |
| + return err |
| + }) |
| +} |
diff --git a/internal/look/static/app.css b/internal/look/static/app.css| index c3ae354..54f8a8e 100644 |
| --- a/internal/look/static/app.css |
| +++ b/internal/look/static/app.css |
| @@ -81,6 +81,12 @@ button, input { font: inherit; } |
| .signin .input, .signin .btn { width: 100%; } |
| .signin .input { margin-bottom: 10px; } |
| .alt { margin-top: 14px; font-size: 14px; color: var(--haze); text-align: center; } |
| +/* The passkey door is that line as a button: a full 44px control, quiet until pointed at. */ |
| +button.alt { display: block; width: 100%; height: 44px; margin-top: 2px; padding: 0; border: 0; background: none; cursor: pointer; } |
| +button.alt:hover { color: var(--frost); text-decoration: underline; text-underline-offset: 3px; } |
| +button.alt[aria-busy="true"] { cursor: progress; } |
| +.signin .passkey-msg { margin: 0; font-size: 14px; text-align: center; } |
| +.signin .passkey-msg:empty { display: none; } |
| /* Home */ |
| .home { padding: 18px 26px 28px; display: flex; flex-direction: column; } |
diff --git a/internal/look/static/passkey-add.js b/internal/look/static/passkey-add.js| new file mode 100644 |
| index 0000000..089d88c |
| --- /dev/null |
| +++ b/internal/look/static/passkey-add.js |
| @@ -0,0 +1,56 @@ |
| +// Adds a passkey from Settings. The button ships hidden and is shown only |
| +// where the browser can make a passkey, so with scripts off, or in a browser |
| +// without passkeys, Settings has no button that cannot work. |
| +// |
| +// The ceremony is rastrillo's webauthn.mjs; Base's /passkey/register pair |
| +// mints the challenge and stores the credential for the signed-in member. |
| + |
| +const btn = document.querySelector("[data-passkey-add]"); |
| + |
| +async function post(url, body) { |
| + const res = await fetch(url, { |
| + method: "POST", |
| + credentials: "same-origin", |
| + headers: { "Content-Type": "application/json" }, |
| + body: JSON.stringify(body), |
| + }); |
| + if (!res.ok) throw new Error("status " + res.status); |
| + return res.json(); |
| +} |
| + |
| +if (btn && window.PublicKeyCredential) { |
| + const msg = document.getElementById(btn.getAttribute("aria-describedby") || ""); |
| + import(btn.dataset.module).then((m) => { |
| + if (!m.available || !m.available()) return; |
| + btn.hidden = false; |
| + btn.addEventListener("click", async () => { |
| + // A second click while one ceremony runs would start another. |
| + if (btn.getAttribute("aria-busy") === "true") return; |
| + btn.setAttribute("aria-busy", "true"); |
| + if (msg) msg.textContent = ""; |
| + try { |
| + const begin = await post(btn.dataset.begin, {}); |
| + const made = await m.register({ |
| + challenge: begin.challenge, |
| + rpId: location.hostname, |
| + rpName: btn.dataset.rpName, |
| + userId: btn.dataset.userId, |
| + userName: btn.dataset.userName, |
| + }); |
| + const done = await post(btn.dataset.finish, { |
| + clientDataJSON: made.clientDataJSON, |
| + attestationObject: made.attestationObject, |
| + }); |
| + if (!done || done.ok !== true) throw new Error("not stored"); |
| + location.assign(btn.dataset.done); |
| + return; |
| + } catch (err) { |
| + // NotAllowedError is the browser's answer when the person closes the |
| + // prompt (or it times out): gentler words than a failure. |
| + const cancelled = err && err.name === "NotAllowedError"; |
| + if (msg) msg.textContent = cancelled ? btn.dataset.cancelled : btn.dataset.failed; |
| + } |
| + btn.removeAttribute("aria-busy"); |
| + }); |
| + }, () => {}); |
| +} |
diff --git a/internal/store/migrations.go b/internal/store/migrations.go| index 4f520e8..180fa3f 100644 |
| --- a/internal/store/migrations.go |
| +++ b/internal/store/migrations.go |
| @@ -6,6 +6,7 @@ import ( |
| "amadan.net/rastrillo/rastrillo/auth" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| + "amadan.net/rastrillo/rastrillo/passkey" |
| "amadan.net/rastrillo/rastrillo/pow" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| ) |
| @@ -16,5 +17,6 @@ var migrationFS embed.FS |
| // Schema holds only Base's own tables. |
| var Schema = migrate.MustFromFS(migrationFS, "base") |
| -// BootSchema adds the framework tables the sign-in flow needs. |
| -var BootSchema = migrate.Merge(sessions.Schema, auth.Schema, pow.Schema, Schema) |
| +// BootSchema adds the framework tables the sign-in flow needs: sessions, |
| +// email links, the sign-in form's proof and passkeys. |
| +var BootSchema = migrate.Merge(sessions.Schema, auth.Schema, pow.Schema, passkey.Schema, Schema) |
diff --git a/internal/web/app.go b/internal/web/app.go| index 5a9ec7a..7dcd0d5 100644 |
| --- a/internal/web/app.go |
| +++ b/internal/web/app.go |
| @@ -18,7 +18,10 @@ import ( |
| "amadan.net/rastrillo/rastrillo/csrf" |
| "amadan.net/rastrillo/rastrillo/db" |
| "amadan.net/rastrillo/rastrillo/mail" |
| + "amadan.net/rastrillo/rastrillo/passkey" |
| "amadan.net/rastrillo/rastrillo/pow" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + "amadan.net/rastrillo/rastrillo/webauthn" |
| "amadan.net/carlos/base/internal/config" |
| "amadan.net/carlos/base/internal/issuer" |
| @@ -42,6 +45,7 @@ type app struct { |
| inst Installer |
| logger *slog.Logger |
| auth *auth.Auth |
| + pk *passkey.Handlers |
| pages *look.Renderer |
| mailer mail.Sender |
| } |
| @@ -87,6 +91,20 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger |
| if err != nil { |
| return nil, err |
| } |
| + // Passkeys share auth's sessions: the same table and, built for the same |
| + // origin, the same cookie. A passkey signs a member in on its own, through |
| + // the same admission check as an emailed link. |
| + sess, err := sessions.New(sessions.Config{DB: d.Writer(), Origin: cfg.Origin, Logger: logger}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + a.pk, err = passkey.New(passkey.Config{ |
| + Sessions: sess, DB: d.Writer(), Origin: cfg.Origin, Logger: logger, |
| + Authorize: a.authorize, SignedInPath: "/", Remember: a.auth.RememberJar(), |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| // Without an assertion key there are no installs to hand off to. |
| var authorize http.Handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| @@ -109,6 +127,10 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger |
| r.Post("/auth/verify", a.auth.Verify) |
| r.Post("/auth/forget", a.auth.Forget) |
| r.Post("/auth/signout", a.auth.Signout) |
| + r.Get(webauthnModulePath, serveScript(webauthn.JS())) |
| + r.Get(passkeyDoorPath, serveScript(passkey.JS())) |
| + r.Post(passkeyDoor.BeginPath, a.pk.DiscoverBegin) |
| + r.Post(passkeyDoor.FinishPath, a.pk.DiscoverFinish) |
| r.Group(func(r chi.Router) { |
| r.Use(a.requireMember) |
| r.Get("/", a.home) |
| @@ -119,6 +141,8 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger |
| r.Get("/store/{app}/uninstall", a.uninstallPage) |
| r.Post("/store/{app}/uninstall", a.storeUninstall) |
| r.Get("/settings", a.settings) |
| + r.Post(registerBeginPath, a.pk.RegisterBegin) |
| + r.Post(registerFinishPath, a.pk.RegisterFinish) |
| r.Method(http.MethodGet, "/authorize", authorize) |
| }) |
| return r, nil |
diff --git a/internal/web/passkey.go b/internal/web/passkey.go| new file mode 100644 |
| index 0000000..8433814 |
| --- /dev/null |
| +++ b/internal/web/passkey.go |
| @@ -0,0 +1,36 @@ |
| +package web |
| + |
| +import ( |
| + "net/http" |
| + |
| + "amadan.net/rastrillo/rastrillo/auth" |
| +) |
| + |
| +// Where Base serves passkeys. The scripts are rastrillo's own: webauthn.mjs |
| +// runs the browser's half of a ceremony, and the door script reveals the |
| +// sign-in page's passkey button only where a ceremony can run. |
| +const ( |
| + webauthnModulePath = "/passkey/webauthn.mjs" |
| + passkeyDoorPath = "/passkey/signin.mjs" |
| + registerBeginPath = "/passkey/register/begin" |
| + registerFinishPath = "/passkey/register/finish" |
| +) |
| + |
| +// passkeyDoor is the sign-in page's passkey button: the discover pair, which |
| +// signs a member in with a passkey alone. |
| +var passkeyDoor = auth.PasskeyDoor{ |
| + BeginPath: "/passkey/discover/begin", |
| + FinishPath: "/passkey/discover/finish", |
| + ModuleURL: webauthnModulePath, |
| + ScriptURL: passkeyDoorPath, |
| +} |
| + |
| +// serveScript answers with one JavaScript module. Its URL carries no |
| +// fingerprint, so the browser checks for a newer copy each time. |
| +func serveScript(body []byte) http.HandlerFunc { |
| + return func(w http.ResponseWriter, _ *http.Request) { |
| + w.Header().Set("Content-Type", "text/javascript; charset=utf-8") |
| + w.Header().Set("Cache-Control", "no-cache") |
| + _, _ = w.Write(body) |
| + } |
| +} |
diff --git a/internal/web/settings.go b/internal/web/settings.go| index 00457ad..406ba09 100644 |
| --- a/internal/web/settings.go |
| +++ b/internal/web/settings.go |
| @@ -1,14 +1,40 @@ |
| package web |
| -import "net/http" |
| +import ( |
| + "encoding/base64" |
| + "net/http" |
| + |
| + "amadan.net/rastrillo/rastrillo/auth" |
| +) |
| type settingsPage struct { |
| Name string |
| Address string |
| + // Passkeys is how many passkeys sign this member in; PasskeyAdded says |
| + // the page follows adding one. |
| + Passkeys int |
| + PasskeyAdded bool |
| + // UserID is the WebAuthn user handle a new passkey stores: the member's |
| + // random id, never their address. |
| + UserID string |
| + ModuleURL, RegisterBegin, RegisterEnd string |
| } |
| func (a *app) settings(w http.ResponseWriter, r *http.Request) { |
| me, _ := CurrentMember(r) |
| + id, _ := auth.From(r) |
| + keys, err := a.pk.List(id.Address) |
| + if err != nil { |
| + a.logger.Error("settings: passkeys", "err", err) |
| + http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| + return |
| + } |
| w.Header().Set("Cache-Control", "no-store") |
| - a.render(w, "settings", settingsPage{Name: a.cfg.Name, Address: me.Email}) |
| + a.render(w, "settings", settingsPage{ |
| + Name: a.cfg.Name, Address: me.Email, |
| + Passkeys: len(keys), |
| + PasskeyAdded: len(keys) > 0 && r.URL.Query().Get("passkey") == "added", |
| + UserID: base64.RawURLEncoding.EncodeToString([]byte(me.ID)), |
| + ModuleURL: webauthnModulePath, RegisterBegin: registerBeginPath, RegisterEnd: registerFinishPath, |
| + }) |
| } |
diff --git a/internal/web/signin.go b/internal/web/signin.go| index 03b1144..704b378 100644 |
| --- a/internal/web/signin.go |
| +++ b/internal/web/signin.go |
| @@ -26,6 +26,8 @@ var problemText = map[auth.SigninProblem]string{ |
| func (a *app) signin(w http.ResponseWriter, r *http.Request) { |
| state := a.auth.SigninState(r) |
| + door := passkeyDoor |
| + state.Passkey = &door |
| a.auth.PrepareSigninResponse(w, state) |
| w.Header().Set("Cache-Control", "no-store") |
| a.render(w, "signin", signinPage{ |
diff --git a/internal/web/templates/settings.html b/internal/web/templates/settings.html| index 97b8fa0..f81df5a 100644 |
| --- a/internal/web/templates/settings.html |
| +++ b/internal/web/templates/settings.html |
| @@ -6,7 +6,11 @@ |
| <ul class="people"> |
| <li><div class="who">Base name<small>{{.Name}}</small></div></li> |
| <li><div class="who">Signed in as<small>{{.Address}}</small></div></li> |
| +<li><div class="who">Passkeys<small id="passkeys">{{if .Passkeys}}{{.Passkeys}} added{{else}}None yet{{end}}</small></div>{{/* Hidden until the script finds the browser can make a passkey, so with scripts off there is no dead button. */}}<button class="btn ghost" type="button" hidden data-passkey-add data-module="{{.ModuleURL}}" data-begin="{{.RegisterBegin}}" data-finish="{{.RegisterEnd}}" data-rp-name="{{.Name}}" data-user-id="{{.UserID}}" data-user-name="{{.Address}}" data-done="/settings?passkey=added" data-cancelled="No passkey was added." data-failed="That didn't work. Try again." aria-describedby="passkey-msg">Add a passkey</button></li> |
| </ul> |
| +{{if .PasskeyAdded}}<p class="status" role="status" id="passkey-added">Passkey added. Next time, sign in with it.</p> |
| +{{end}}<p class="status" id="passkey-msg" aria-live="polite"></p> |
| <form method="post" action="/auth/signout"><button class="btn ghost" type="submit">Sign out</button></form> |
| </div> |
| +<script type="module" src="{{asset "static/passkey-add.js"}}"></script> |
| </main>{{end}} |
diff --git a/internal/web/templates/signin.html b/internal/web/templates/signin.html| index 7e153af..54571e0 100644 |
| --- a/internal/web/templates/signin.html |
| +++ b/internal/web/templates/signin.html |
| @@ -19,5 +19,8 @@ |
| {{end}}<input class="input" type="email" name="address" value="{{$s.Address}}" autocomplete="email" required aria-label="Email address"> |
| <button class="btn" type="submit">{{if eq $s.Problem "keymail"}}Send me a link instead{{else}}Continue{{end}}</button> |
| </form> |
| -{{end}}</div> |
| +{{with $s.Passkey}}{{/* Hidden until rastrillo's door script finds the browser can run a passkey ceremony, so with scripts off there is no dead button. */}}<button class="alt" type="button" hidden data-rst-passkey data-rst-passkey-begin="{{.BeginPath}}" data-rst-passkey-finish="{{$s.PasskeyFinish}}" data-rst-passkey-module="{{.ModuleURL}}" data-rst-passkey-cancelled="No passkey was used. Try again, or use your email." data-rst-passkey-failed="That didn't work. Try again, or use your email." aria-describedby="passkey-msg">Or use a passkey</button> |
| +<p class="passkey-msg" id="passkey-msg" aria-live="polite"></p> |
| +<script type="module" src="{{.ScriptURL}}"></script> |
| +{{end}}{{end}}</div> |
| </main>{{end}} |
diff --git a/internal/webtest/passkey_test.go b/internal/webtest/passkey_test.go| new file mode 100644 |
| index 0000000..3de301f |
| --- /dev/null |
| +++ b/internal/webtest/passkey_test.go |
| @@ -0,0 +1,107 @@ |
| +package webtest |
| + |
| +import ( |
| + "net/http" |
| + "regexp" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// The browser suite (internal/browsertest) runs the ceremonies. These check |
| +// the wiring a browser cannot see break: what the pages ship before any |
| +// script runs, and who the endpoints answer. |
| + |
| +func TestSigninOffersAHiddenPasskeyButton(t *testing.T) { |
| + a := newApp(t) |
| + page := a.get("/signin") |
| + if page.Code != 200 { |
| + t.Fatalf("signin: %d", page.Code) |
| + } |
| + door := regexp.MustCompile(`<button[^>]*data-rst-passkey[^>]*>Or use a passkey</button>`).FindString(page.Body) |
| + if door == "" { |
| + t.Fatalf("no passkey button in:\n%s", page.Body) |
| + } |
| + for _, want := range []string{` hidden `, `data-rst-passkey-begin="/passkey/discover/begin"`, |
| + `data-rst-passkey-finish="/passkey/discover/finish"`, `data-rst-passkey-module="/passkey/webauthn.mjs"`} { |
| + if !strings.Contains(door, want) { |
| + t.Errorf("passkey button lacks %s: %s", want, door) |
| + } |
| + } |
| + if !strings.Contains(page.Body, `<script type="module" src="/passkey/signin.mjs"></script>`) { |
| + t.Error("the sign-in page does not load the passkey button's script") |
| + } |
| + // The email form is there whatever the scripts do. |
| + if !strings.Contains(page.Body, `action="/auth/begin"`) { |
| + t.Error("no email form beside the passkey button") |
| + } |
| +} |
| + |
| +func TestPasskeyButtonCarriesReturnTo(t *testing.T) { |
| + a := newApp(t) |
| + page := a.get("/signin?return_to=%2Fstore") |
| + if !strings.Contains(page.Body, `data-rst-passkey-finish="/passkey/discover/finish?return_to=%2Fstore"`) { |
| + t.Fatalf("the passkey finish URL does not carry return_to:\n%s", page.Body) |
| + } |
| +} |
| + |
| +func TestPasskeyScriptsServed(t *testing.T) { |
| + a := newApp(t) |
| + for _, path := range []string{"/passkey/webauthn.mjs", "/passkey/signin.mjs"} { |
| + r := a.get(path) |
| + if r.Code != 200 || !strings.HasPrefix(r.Header.Get("Content-Type"), "text/javascript") || !strings.Contains(r.Body, "export") { |
| + t.Errorf("%s: %d %q", path, r.Code, r.Header.Get("Content-Type")) |
| + } |
| + } |
| +} |
| + |
| +func TestSettingsOffersAHiddenAddPasskeyButton(t *testing.T) { |
| + a := newApp(t) |
| + a.signedInOwner() |
| + page := a.get("/settings") |
| + if page.Code != 200 { |
| + t.Fatalf("settings: %d", page.Code) |
| + } |
| + if !strings.Contains(page.Body, `<small id="passkeys">None yet</small>`) { |
| + t.Errorf("Settings does not say there are no passkeys:\n%s", page.Body) |
| + } |
| + btn := regexp.MustCompile(`<button[^>]*data-passkey-add[^>]*>Add a passkey</button>`).FindString(page.Body) |
| + if btn == "" || !strings.Contains(btn, ` hidden `) { |
| + t.Fatalf("no hidden add-a-passkey button in:\n%s", page.Body) |
| + } |
| + // The user handle is the member's random id, never the address. |
| + if strings.Contains(btn, `data-user-id="`+ownerAddress) || !regexp.MustCompile(`data-user-id="[A-Za-z0-9_-]+"`).MatchString(btn) { |
| + t.Errorf("bad user handle: %s", btn) |
| + } |
| + if !regexp.MustCompile(`<script type="module" src="/static/passkey-add\.[^"]*js"></script>`).MatchString(page.Body) { |
| + t.Errorf("Settings does not load the add-a-passkey script:\n%s", page.Body) |
| + } |
| + // A query alone does not claim a passkey was added. |
| + if strings.Contains(a.get("/settings?passkey=added").Body, "Passkey added") { |
| + t.Error("Settings says a passkey was added when there is none") |
| + } |
| +} |
| + |
| +// Registering needs a member's session; discovery is open, but only to the |
| +// page's own origin. |
| +func TestPasskeyEndpointsGuarded(t *testing.T) { |
| + a := newApp(t) |
| + jsonPost := func(path, origin string) Resp { |
| + req, _ := http.NewRequest(http.MethodPost, a.srv.URL+path, strings.NewReader("{}")) |
| + req.Header.Set("Content-Type", "application/json") |
| + req.Header.Set("Origin", origin) |
| + return a.do(req) |
| + } |
| + if r := jsonPost("/passkey/register/begin", testOrigin); r.Code != http.StatusForbidden { |
| + t.Errorf("register begin, signed out: %d", r.Code) |
| + } |
| + if r := jsonPost("/passkey/discover/begin", "https://evil.example"); r.Code != http.StatusForbidden { |
| + t.Errorf("discover begin, cross-origin: %d", r.Code) |
| + } |
| + if r := jsonPost("/passkey/discover/begin", testOrigin); r.Code != 200 || !strings.Contains(r.Body, `"challenge"`) { |
| + t.Errorf("discover begin: %d %s", r.Code, r.Body) |
| + } |
| + a.signedInOwner() |
| + if r := jsonPost("/passkey/register/begin", testOrigin); r.Code != 200 || !strings.Contains(r.Body, `"challenge"`) { |
| + t.Errorf("register begin, signed in: %d %s", r.Code, r.Body) |
| + } |
| +} |
diff --git a/internal/webtest/signin_test.go b/internal/webtest/signin_test.go| index 0436a9b..05987f5 100644 |
| --- a/internal/webtest/signin_test.go |
| +++ b/internal/webtest/signin_test.go |
| @@ -70,7 +70,7 @@ func TestSignOut(t *testing.T) { |
| func TestSigninPageServesItsStylesheet(t *testing.T) { |
| a := newApp(t) |
| page := a.get("/signin") |
| - if page.Code != 200 || !strings.Contains(page.Body, "Sign in to Acme") || strings.Contains(page.Body, "passkey") { |
| + if page.Code != 200 || !strings.Contains(page.Body, "Sign in to Acme") { |
| t.Fatalf("signin page: %d\n%s", page.Code, page.Body) |
| } |
| m := regexp.MustCompile(`href="(/static/app[^"]*\.css)"`).FindStringSubmatch(page.Body) |