d7c0cf89d3
One theme (the PWA's dark palette) for dash/history/trace/notifications/ tools/passkey via static/ui.css; shared nav template with active-page highlight; tables wrapped in .scroll so they pan on phones; PWA nav no longer clips the RU/EN toggle; dash 'updated' timestamp fixed (selector matched nothing). AGENTS.md documents the local preview/screenshot recipe. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ASstMtsZWLSRcD1Tq8T68Q
208 lines
7.8 KiB
Go
208 lines
7.8 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/kami/maven/internal/auth"
|
|
"github.com/kami/maven/internal/ipc"
|
|
"github.com/kami/maven/internal/webauthn"
|
|
)
|
|
|
|
// assertIPC — satisfies the AssertStepUp caller shape. The only implementation
|
|
// is *ipc.Client; in-process CoreAPI adapters return ErrUnknownMethod.
|
|
type assertIPC interface {
|
|
AssertStepUp(ctx context.Context) error
|
|
}
|
|
|
|
// PasskeyHandle holds the WebAuthn relying party, a local in-memory credential
|
|
// store, and the IPC client used to assert step-up. It serves the four WebAuthn
|
|
// HTTP endpoints (register/begin, register/finish, assert/begin, assert/finish).
|
|
//
|
|
// Credentials are kept in-memory only (a single-user daemon restarts
|
|
// infrequently, and re-enrolling after restart is acceptable). A future
|
|
// version may persist them to disk.
|
|
type PasskeyHandle struct {
|
|
rp *webauthn.RP
|
|
assertFn assertIPC // *ipc.Client when connected; nil ⇒ no step-up IPC
|
|
store *credentialStore
|
|
session *webauthn.PasskeySession
|
|
}
|
|
|
|
type localCred struct {
|
|
PublicKey []byte
|
|
SignCount int64
|
|
}
|
|
|
|
func newPasskeyHandle(cfg webauthn.Config, core ipc.CoreAPI, storePath string, session *webauthn.PasskeySession) (*PasskeyHandle, error) {
|
|
var af assertIPC
|
|
if c, ok := core.(assertIPC); ok {
|
|
af = c
|
|
}
|
|
store, err := newCredentialStore(storePath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("credential store: %w", err)
|
|
}
|
|
return &PasskeyHandle{
|
|
rp: webauthn.NewRP(cfg),
|
|
assertFn: af,
|
|
store: store,
|
|
session: session,
|
|
}, nil
|
|
}
|
|
|
|
// Page serves the passkey enrollment + step-up UI. It's the only surface that
|
|
// can perform a WebAuthn gesture, so it's the gate the /tools enable depends
|
|
// on: assert here (bumps the daemon session to L3 for the assertion TTL), then
|
|
// enable a tool on /tools within that window.
|
|
func (h *PasskeyHandle) Page(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
w.Write([]byte(passkeyPageHTML))
|
|
}
|
|
|
|
const passkeyPageHTML = `<!doctype html><meta charset=utf-8>
|
|
<meta name=viewport content="width=device-width,initial-scale=1">
|
|
<title>maven · passkey</title>
|
|
<link rel=stylesheet href=/ui.css>
|
|
<style>button{padding:.5rem 1rem;margin:.3rem .3rem 0 0}
|
|
#msg{white-space:pre-wrap}</style>
|
|
<nav class=site>
|
|
<a href=/>voice</a> <a href=/dash>dash</a> <a href=/history>history</a>
|
|
<a href=/trace>trace</a> <a href=/notifications>notifications</a>
|
|
<a href=/tools>tools</a> <a href=/auth/passkey class=active>passkey</a>
|
|
</nav>
|
|
<h1>passkey</h1>
|
|
<p>Enroll a passkey once, then assert it to unlock destructive actions
|
|
(tool enable) for a few minutes.</p>
|
|
<button onclick=enroll()>enroll passkey</button>
|
|
<button onclick=assert()>assert (step-up)</button>
|
|
<a href=/tools><button>→ tools</button></a>
|
|
<div id=msg></div>
|
|
<script>
|
|
const b64u=b=>btoa(String.fromCharCode(...new Uint8Array(b))).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,'');
|
|
const ub64=s=>{s=s.replace(/-/g,'+').replace(/_/g,'/');const b=atob(s),a=new Uint8Array(b.length);for(let i=0;i<b.length;i++)a[i]=b.charCodeAt(i);return a;};
|
|
const say=(t,ok)=>{const m=document.getElementById('msg');m.textContent=t;m.className=ok?'msg msg-ok':'msg msg-err';};
|
|
async function enroll(){try{
|
|
const {challenge,options}=await (await fetch('/auth/webauthn/register/begin')).json();
|
|
options.challenge=ub64(options.challenge);
|
|
options.user.id=ub64(options.user.id);
|
|
const c=await navigator.credentials.create({publicKey:options});
|
|
const r=await fetch('/auth/webauthn/register/finish',{method:'POST',headers:{'content-type':'application/json'},
|
|
body:JSON.stringify({challenge,credential:{id:c.id,type:c.type,response:{
|
|
clientDataJSON:b64u(c.response.clientDataJSON),attestationObject:b64u(c.response.attestationObject)}}})});
|
|
say(r.ok?'enrolled ✓':'enroll failed: '+await r.text(),r.ok);
|
|
}catch(e){say('enroll error: '+e,false);}}
|
|
async function assert(){try{
|
|
const {challenge,options}=await (await fetch('/auth/webauthn/assert/begin')).json();
|
|
options.challenge=ub64(options.challenge);
|
|
const c=await navigator.credentials.get({publicKey:options});
|
|
const r=await fetch('/auth/webauthn/assert/finish',{method:'POST',headers:{'content-type':'application/json'},
|
|
body:JSON.stringify({challenge,credential:{id:c.id,type:c.type,response:{
|
|
clientDataJSON:b64u(c.response.clientDataJSON),authenticatorData:b64u(c.response.authenticatorData),
|
|
signature:b64u(c.response.signature)}}})});
|
|
say(r.ok?'stepped up ✓ — enable tools now':'assert failed: '+await r.text(),r.ok);
|
|
}catch(e){say('assert error: '+e,false);}}
|
|
</script>`
|
|
|
|
func (h *PasskeyHandle) RegisterBegin(w http.ResponseWriter, r *http.Request) {
|
|
opts, challenge, err := h.rp.CreationOptions([]byte("maven-user"), "maven user")
|
|
if err != nil {
|
|
log.Printf("webauthn: register begin: %v", err)
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]any{"challenge": challenge, "options": opts})
|
|
}
|
|
|
|
func (h *PasskeyHandle) RegisterFinish(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "POST only", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
var body struct {
|
|
Challenge string `json:"challenge"`
|
|
Credential map[string]any `json:"credential"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
|
http.Error(w, "bad request: "+err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
save := func(id string, publicKey []byte, _ []byte, _ string) error {
|
|
return h.store.Save(id, publicKey)
|
|
}
|
|
credID, err := h.rp.FinishRegistration(save, body.Challenge, body.Credential)
|
|
if err != nil {
|
|
log.Printf("webauthn: register finish: %v", err)
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
log.Printf("webauthn: registered credential %s", credID)
|
|
json.NewEncoder(w).Encode(map[string]string{"credential_id": credID})
|
|
}
|
|
|
|
func (h *PasskeyHandle) AssertBegin(w http.ResponseWriter, r *http.Request) {
|
|
opts, challenge, err := h.rp.AssertionOptions()
|
|
if err != nil {
|
|
log.Printf("webauthn: assert begin: %v", err)
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]any{"challenge": challenge, "options": opts})
|
|
}
|
|
|
|
func (h *PasskeyHandle) AssertFinish(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "POST only", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
var body struct {
|
|
Challenge string `json:"challenge"`
|
|
Credential map[string]any `json:"credential"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
|
http.Error(w, "bad request: "+err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
lookup := func(id string) ([]byte, int64, error) {
|
|
return h.store.Lookup(id)
|
|
}
|
|
update := func(id string, count int64) error {
|
|
return h.store.UpdateSignCount(id, count)
|
|
}
|
|
|
|
credID, err := h.rp.FinishAssertion(lookup, update, body.Challenge, body.Credential)
|
|
if err != nil {
|
|
log.Printf("webauthn: assert finish: %v", err)
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
// Assert step-up on the IPC (mavend) side so subsequent EnableTool calls
|
|
// see L3. Best-effort: if IPC fails (no -core or mavend unreachable), the
|
|
// user still sees success but the enable will fail with AuthStepUp.
|
|
if h.assertFn != nil {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
|
defer cancel()
|
|
if err := h.assertFn.AssertStepUp(ctx); err != nil {
|
|
log.Printf("webauthn: assert step-up: %v", err)
|
|
http.Error(w, "step-up assertion failed", http.StatusBadGateway)
|
|
return
|
|
}
|
|
}
|
|
|
|
// Assert the in-process session so the POST /tools handler sees step-up.
|
|
if h.session != nil {
|
|
h.session.Assert(r.Context(), auth.Scope{})
|
|
}
|
|
|
|
log.Printf("webauthn: asserted credential %s", credID)
|
|
json.NewEncoder(w).Encode(map[string]string{"credential_id": credID})
|
|
}
|