oficina / base Public

Open Equipo's coordinator chat from "Ask Base anything"

With BASE_EQUIPO_ORIGIN set, the Ask field opens a glass panel sliding in
from the right over Home (a modal dialog; full screen on a phone; Escape
closes it and focus returns to the field). Without scripts the field is a
link to /ask, the same conversation as a page of plain forms.

Connect Equipo (Settings, or the panel) starts the device flow server
side and shows the code with a link to Equipo's approval page; the page
refreshes every five seconds and exchanges no more often than that. A 401
or an expired bearer shows Reconnect; Disconnect revokes the device.

Base relays every call with the member's bearer, which never reaches the
browser. /ask/events relays Equipo's SSE (message, turn, delta, activity
and card events only). With the chat off the field stays disabled, now
drawn as glass instead of a native bevel. New copy is under Review 5.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 10cb3a038474e5e400798708c954ab3e921951fc parent 12ffa62
20 files changed, +1,716 −7
  • README.md +5 −0
  • docs/copy-pending.md +51 −0
  • internal/browsertest/ask_test.go +123 −0
  • internal/look/look.go +12 −1
  • internal/look/look_test.go +22 −0
  • internal/look/static/app.css +55 −2
  • internal/look/static/ask.js +269 −0
  • internal/web/app.go +9 −1
  • internal/web/ask.go +255 −0
  • internal/web/ask_connect.go +188 −0
  • internal/web/ask_relay.go +232 −0
  • internal/web/home.go +11 −0
  • internal/web/settings.go +12 −0
  • internal/web/templates/ask.html +10 −0
  • internal/web/templates/ask_connect.html +17 −0
  • internal/web/templates/home.html +3 −1
  • internal/web/templates/partials/chat.html +33 −0
  • internal/web/templates/settings.html +2 −1
  • internal/webtest/ask_test.go +392 −0
  • internal/webtest/harness_test.go +15 −1
diff --git a/README.md b/README.md
index 69e0d8d..e955ce1 100644
--- a/README.md
+++ b/README.md
@@ -46,6 +46,11 @@ Everything is an environment variable. `BASE_ORIGIN`, `BASE_OWNER` and
across restarts: apps check sign-ins against its public half.
- `BASE_ALLOW_LOGGED_MAIL=1` prints sign-in links instead of sending them.
Local only; Base refuses it on a non-loopback origin.
+- `BASE_EQUIPO_ORIGIN` is the Equipo whose coordinator answers "Ask Base
+ anything", such as `https://equipo.example.com`. Without it the Ask field
+ stays off. Each person connects Equipo once, from Settings or the Ask
+ panel; Base keeps their Equipo key sealed with `BASE_INSTANCE_KEY`, so
+ changing that key disconnects everyone from Equipo.
To let your team sign in with Oficina ID, set all four of these. Without them
Base has only its own sign-in. With some but not all, it refuses to start.
diff --git a/docs/copy-pending.md b/docs/copy-pending.md
index ca14f3b..1421698 100644
--- a/docs/copy-pending.md
+++ b/docs/copy-pending.md
@@ -213,3 +213,54 @@ Reused as Calendar ships them, on the pages Base draws itself (internal/web/temp
| internal/web/oficina.go | Signed-out page, heading | You’re signed out |
| internal/web/oficina.go | Signed-out page, body | You’ve signed out of {Base name} on this device. |
| internal/web/oficina.go | Signed-out page, button (to /signin) | Sign in |
+
+Review 5 (pending): "Ask Base anything", the chat with Equipo's coordinator.
+
+| File | Context | Text |
+|---|---|---|
+| internal/web/templates/home.html | Home, the Ask field with the chat on (a link that opens the panel; "/" drawn after it) | Ask Base anything |
+| internal/web/templates/partials/chat.html | Panel and /ask page, heading | Ask Base |
+| internal/web/templates/partials/chat.html | Panel and /ask page, link to Equipo (new tab) | Open Equipo |
+| internal/web/templates/partials/chat.html | Panel, close button's accessible name | Close |
+| internal/web/templates/partials/chat.html | Not connected, body | Connect Equipo, and its coordinator answers you here. |
+| internal/web/templates/partials/chat.html | Not connected, button (also Settings and the connect page) | Connect Equipo |
+| internal/web/templates/partials/chat.html | Connecting started but not approved, body | You started connecting Equipo. Approve it there to start asking. |
+| internal/web/templates/partials/chat.html | Same, button (also Settings) | Finish connecting |
+| internal/web/templates/partials/chat.html | Equipo refused the bearer (401) or it expired, body (also the connect page) | Base's connection to Equipo expired or was removed. |
+| internal/web/templates/partials/chat.html | Same, button (also Settings and the connect page) | Reconnect Equipo |
+| internal/web/templates/partials/chat.html | Equipo did not answer | Equipo isn't answering. Try again in a minute. |
+| internal/web/templates/partials/chat.html | Conversation's accessible name | Conversation |
+| internal/web/templates/partials/chat.html | Empty conversation | Ask about your work, or ask Base to get something done. |
+| internal/web/ask.go | /ask after a relayed write failed (scripts off) | Equipo didn't get that. Try again. |
+| internal/look/static/ask.js | Panel, a send, answer or stop that failed | Equipo didn't get that. Try again. |
+| internal/web/ask.go, ask.js | Status line while a turn runs | Equipo is answering… |
+| internal/web/ask.go, ask.js | Status line while the turn waits (Equipo's reason no_connection) | Equipo can't answer right now. It will as soon as it can. |
+| internal/look/static/ask.js | Status line after a failed turn | That didn't get an answer. Try again. |
+| internal/web/templates/partials/chat.html | Stop button for a running turn | Stop |
+| internal/web/templates/partials/chat.html | Message field's label (visually hidden) | Message |
+| internal/web/templates/partials/chat.html | Message field's placeholder | Ask Base anything |
+| internal/web/templates/partials/chat.html | Send button | Send |
+| internal/web/templates/ask.html | /ask tab title | Ask Base · {Base name} |
+| internal/web/templates/ask.html | /ask crumb | Ask Base |
+| internal/web/templates/ask_connect.html | Connect page, tab title | Connect Equipo · {Base name} |
+| internal/web/templates/ask_connect.html | Connect page, heading | Connect Equipo |
+| internal/web/templates/ask_connect.html | Waiting for approval, body (the code below it) | In Equipo, check the request is from {device label}, then type this code: |
+| internal/web/templates/ask_connect.html | The code's accessible name | Your code |
+| internal/web/templates/ask_connect.html | Waiting for approval, button (Equipo's approval page, new tab) | Open Equipo |
+| internal/web/templates/ask_connect.html | Waiting for approval, note | This page checks every few seconds and moves on once you've approved it. |
+| internal/web/templates/ask_connect.html | Waiting for approval, button (checks now) | Check again |
+| internal/web/templates/ask_connect.html | Not connected, body | Connect Equipo, and its coordinator answers you in Base. |
+| internal/web/templates/ask_connect.html | Code expired, body | That code expired. Start again to get a new one. |
+| internal/web/templates/ask_connect.html | Equipo refused the exchange (403), body | Equipo didn't accept that request. Start again. |
+| internal/web/templates/ask_connect.html | Expired or refused, button | Start again |
+| internal/web/templates/ask_connect.html | Connect page, back button | Back |
+| internal/web/ask_connect.go | Equipo did not answer when starting | Equipo isn't answering. Try again in a minute. |
+| internal/web/ask_connect.go | Equipo did not answer while polling | Equipo isn't answering. Base will keep trying. |
+| internal/web/ask.go | Device label Equipo shows the person when approving (with Base's name) | Base ({Base name}) |
+| internal/web/templates/settings.html | Settings label | Equipo |
+| internal/web/templates/settings.html | Equipo row, values | Connected / Waiting for your approval in Equipo / Connection expired or removed / Not connected |
+| internal/web/templates/settings.html | Equipo row, buttons | Disconnect / Finish connecting / Reconnect Equipo / Connect Equipo |
+| internal/config/config.go | Start-up refusal (operator-facing log) | BASE_EQUIPO_ORIGIN {value} must be an https origin: a scheme and host only (http only on loopback) |
+| README.md | Settings: the BASE_EQUIPO_ORIGIN bullet (new lines only) | `BASE_EQUIPO_ORIGIN` is the Equipo whose coordinator answers "Ask Base anything", such as `https://equipo.example.com`. Without it the Ask field stays off. Each person connects Equipo once, from Settings or the Ask panel; Base keeps their Equipo key sealed with `BASE_INSTANCE_KEY`, so changing that key disconnects everyone from Equipo. |
+
+Activity lines in the status ("Adding a project…" and the like) are Equipo's own labels, shown as Equipo sends them.
diff --git a/internal/browsertest/ask_test.go b/internal/browsertest/ask_test.go
new file mode 100644
index 0000000..71061ba
--- /dev/null
+++ b/internal/browsertest/ask_test.go
@@ -0,0 +1,123 @@
+//go:build browser
+
+package browsertest
+
+import (
+ "context"
+ "net/http"
+ "os"
+ "path/filepath"
+ "regexp"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+
+ "amadan.net/rastrillo/rastrillo/harness"
+
+ "amadan.net/carlos/base/internal/equipo/equipotest"
+)
+
+// With the chat off, the Ask field is drawn as glass, not a native
+// disabled input with its bevel.
+func TestAskFieldOffIsGlass(t *testing.T) {
+ var b *baseApp
+ rig := newRig(t, func(origin string) http.Handler {
+ b = newBase(t, baseConfig(origin))
+ return b.handler
+ })
+ signInByEmail(t, rig, rig.Origin, b.mail)
+ style := harness.Evaluate[string](rig, `(() => { const s = getComputedStyle(document.querySelector("input.ask"));
+ return [s.borderTopStyle, s.borderTopWidth, s.boxShadow === "none" ? "flat" : "glass"].join(" ") })()`)
+ if style != "none 0px glass" {
+ t.Fatalf("the off Ask field is drawn %q, want %q", style, "none 0px glass")
+ }
+}
+
+// The owner connects Equipo from Settings, opens the panel from Home, asks
+// one thing and sees the coordinator's reply stream in; Escape closes the
+// panel and gives focus back to the field.
+func TestAskPanel(t *testing.T) {
+ f := equipotest.New(t)
+ f.Reply = func(string) string {
+ return "You can ask me to plan work, check on a project, or start a task. What would you like to do?"
+ }
+ var b *baseApp
+ rig := newRig(t, func(origin string) http.Handler {
+ cfg := baseConfig(origin)
+ cfg.EquipoOrigin = f.URL
+ b = newBase(t, cfg)
+ return b.handler
+ })
+ signInByEmail(t, rig, rig.Origin, b.mail)
+ drive(t, rig, chromedp.EmulateViewport(1280, 800))
+
+ // Connect: Settings, then the code page; approve in Equipo, check again.
+ connect := `form[action="/ask/connect"] button`
+ drive(t, rig, chromedp.Navigate(rig.Origin+"/settings"), chromedp.WaitVisible(chromedp.CSS(connect)),
+ chromedp.Click(chromedp.CSS(connect)), chromedp.WaitVisible(chromedp.CSS(`p.code`)))
+ rig.Screen(".card", "Connect Equipo, waiting for approval")
+ code := harness.Evaluate[string](rig, `document.querySelector("p.code").textContent`)
+ if !regexp.MustCompile(`^[A-Z0-9]{8}$`).MatchString(code) {
+ t.Fatalf("code %q", code)
+ }
+ if err := f.Approve(code); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := b.db.Exec(`UPDATE equipo_links SET polled_at = ?`, time.Now().Add(-time.Minute).UTC()); err != nil {
+ t.Fatal(err)
+ }
+ drive(t, rig, chromedp.Click(chromedp.CSS(`a[href^="/ask/connect"]`)),
+ chromedp.WaitVisible(chromedp.CSS(`form[action="/ask/disconnect"]`)))
+ rig.Screen(".sheet", "Settings, Equipo connected")
+
+ // Ask.
+ drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS(`a.ask`)),
+ chromedp.Click(chromedp.CSS(`a.ask`)), chromedp.WaitVisible(chromedp.CSS(`#ask-panel textarea`)))
+ if here := harness.Read(rig, chromedp.Location()); here != rig.Origin+"/" {
+ t.Fatalf("the field navigated to %s instead of opening the panel", here)
+ }
+ if got := harness.Evaluate[string](rig, `document.activeElement.id`); got != "ask-text" {
+ t.Errorf("focus is on %q, want the message field", got)
+ }
+ drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "What can I do"),
+ chromedp.Click(chromedp.CSS(`#ask-panel form.composer button`)),
+ chromedp.Poll[chromedp.Void](`[...document.querySelectorAll("#ask-panel .msg.coordinator")].some(m => m.textContent.includes("What would you like to do?") && !m.classList.contains("draft"))`,
+ chromedp.WithPollingTimeout(10*time.Second)))
+ rig.Screen("#ask-panel", "the panel with one question answered")
+ if got := harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .msg.person").length`); got != 1 {
+ t.Errorf("person messages shown: %d", got)
+ }
+ if n := len(f.Calls("/api/v1/messages")); n != 1 {
+ t.Errorf("messages sent to Equipo: %d", n)
+ }
+ if dir := os.Getenv("BASE_BROWSER_ARTIFACTS"); dir != "" {
+ var png []byte
+ drive(t, rig, chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
+ var err error
+ png, err = chromedp.FullScreenshot(100)(ctx, target)
+ return err
+ }))
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "7-ask-panel.png"), png, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ drive(t, rig, chromedp.KeyEvent("\u001b"),
+ chromedp.Poll[chromedp.Void](`!document.querySelector("#ask-panel").open`, chromedp.WithPollingTimeout(5*time.Second)))
+ if got := harness.Evaluate[string](rig, `document.activeElement.className`); got != "ask" {
+ t.Errorf("after Escape focus is on %q, want the Ask field", got)
+ }
+
+ // On a phone the panel is the whole screen.
+ drive(t, rig, chromedp.EmulateViewport(390, 844), chromedp.Click(chromedp.CSS(`a.ask`)),
+ chromedp.WaitVisible(chromedp.CSS(`#ask-panel textarea`)))
+ rig.Screen("#ask-panel", "the panel on a phone")
+ // Once it has slid in, it covers the screen.
+ whole := `(() => { const r = document.querySelector("#ask-panel").getBoundingClientRect();
+ return [r.left, r.top, r.width, r.height].map(Math.round).join(" ") === "0 0 390 844" })()`
+ drive(t, rig, chromedp.Poll[chromedp.Void](whole, chromedp.WithPollingTimeout(3*time.Second)))
+}
diff --git a/internal/look/look.go b/internal/look/look.go
index 33f5803..03aa1c0 100644
--- a/internal/look/look.go
+++ b/internal/look/look.go
@@ -64,12 +64,18 @@ type Renderer struct {
// NewRenderer parses every top-level *.html in pageFS as a page named after
// the file (without .html). A page defines the layout's "title" and "main"
-// blocks. funcs are extra template functions; "asset" is always provided.
+// blocks. Templates in partials/*.html are not pages: every page can use
+// what they define. funcs are extra template functions; "asset" is always
+// provided.
func NewRenderer(pageFS fs.FS, funcs template.FuncMap) (*Renderer, error) {
files, err := fs.Glob(pageFS, "*.html")
if err != nil {
return nil, err
}
+ partials, err := fs.Glob(pageFS, "partials/*.html")
+ if err != nil {
+ return nil, err
+ }
all := template.FuncMap{"asset": Assets.Path}
for k, v := range funcs {
all[k] = v
@@ -80,6 +86,11 @@ func NewRenderer(pageFS fs.FS, funcs template.FuncMap) (*Renderer, error) {
if err != nil {
return nil, err
}
+ if len(partials) > 0 {
+ if t, err = t.ParseFS(pageFS, partials...); err != nil {
+ return nil, fmt.Errorf("look: partials: %w", err)
+ }
+ }
if t, err = t.ParseFS(pageFS, f); err != nil {
return nil, fmt.Errorf("look: page %s: %w", f, err)
}
diff --git a/internal/look/look_test.go b/internal/look/look_test.go
index 5b74014..da7c56e 100644
--- a/internal/look/look_test.go
+++ b/internal/look/look_test.go
@@ -86,3 +86,25 @@ func TestPageUnknownNameErrors(t *testing.T) {
t.Fatal("want an error and no output")
}
}
+
+// Templates under partials/ are shared by every page and are not pages.
+func TestPartialsSharedByPages(t *testing.T) {
+ pages := fstest.MapFS{
+ "one.html": {Data: []byte(`{{define "main"}}<main>{{template "greet" .}}</main>{{end}}`)},
+ "two.html": {Data: []byte(`{{define "main"}}<main>2 {{template "greet" .}}</main>{{end}}`)},
+ "partials/bit.html": {Data: []byte(`{{define "greet"}}Hi {{.}}{{end}}`)},
+ }
+ r, err := look.NewRenderer(pages, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for page, want := range map[string]string{"one": "<main>Hi Ana</main>", "two": "<main>2 Hi Ana</main>"} {
+ rec := httptest.NewRecorder()
+ if err := r.Page(rec, page, "Ana"); err != nil || !strings.Contains(rec.Body.String(), want) {
+ t.Errorf("%s: %v\n%s", page, err, rec.Body.String())
+ }
+ }
+ if err := r.Page(httptest.NewRecorder(), "bit", nil); err == nil {
+ t.Error("a partial rendered as a page")
+ }
+}
diff --git a/internal/look/static/app.css b/internal/look/static/app.css
index 5704179..2463fc8 100644
--- a/internal/look/static/app.css
+++ b/internal/look/static/app.css
@@ -160,7 +160,8 @@ button.alt[aria-busy="true"] { cursor: progress; }
[hidden] { display: none !important; }
@media (prefers-reduced-motion: reduce) {
- .fog, .fog i, .light, .light::after, .app.new, .app.leaving, .installing { animation: none; }
+ .fog, .fog i, .light, .light::after, .app.new, .app.leaving, .installing, .msg.draft::after { animation: none; }
+ dialog.ask-panel { transition: none; }
.light { transform: skewX(-14deg); }
}
@@ -170,7 +171,59 @@ a.app, a.me { color: inherit; text-decoration: none; }
a.wordmark { color: inherit; text-decoration: none; min-height: 44px; border-radius: 8px; }
.notepad + form { margin-top: 16px; }
a.btn { display: inline-flex; align-items: center; text-decoration: none; }
-.ask:disabled { cursor: not-allowed; font: inherit; font-size: 14px; }
+/* The Ask field: glass whether it is the link to the chat or, with the chat
+ off, a disabled field (no native bevel, no greyed-out fill). */
+.ask { appearance: none; border: 0; min-height: 36px; align-items: center; font: inherit; font-size: 14px; }
+.ask::placeholder { color: var(--haze); opacity: 1; }
+.ask:disabled { cursor: not-allowed; color: var(--haze); opacity: 1; }
+a.ask { text-decoration: none; transition: background .2s, box-shadow .2s; }
+a.ask:hover { background: rgba(10,16,28,.4); box-shadow: inset 0 0 0 1px rgba(110,231,220,.45); }
+a.ask::after { content: "/"; color: var(--haze); opacity: .7; }
+.sr-only { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
+
+/* Ask Base: a sheet of dark glass that slides in from the right over Home
+ (full screen on a phone), and the same conversation on /ask. */
+dialog.ask-panel { position: fixed; inset: 12px 12px 12px auto; width: min(460px, calc(100vw - 24px)); height: auto;
+ max-width: none; max-height: none; margin: 0; padding: 0; border-radius: 18px; color: var(--frost);
+ background: linear-gradient(rgba(238,242,248,.07), rgba(238,242,248,.03)), rgba(14,17,42,.62);
+ flex-direction: column; overflow: hidden;
+ transition: transform .35s cubic-bezier(.2,.7,0,1), opacity .35s, overlay .35s allow-discrete, display .35s allow-discrete;
+ transform: translateX(32px); opacity: 0; }
+dialog.ask-panel[open] { display: flex; transform: none; opacity: 1; }
+@starting-style { dialog.ask-panel[open] { transform: translateX(32px); opacity: 0; } }
+dialog.ask-panel::backdrop { background: rgba(10,12,30,.38); }
+.ask-head { display: flex; align-items: center; gap: 8px; padding: 14px 14px 12px 20px; border-bottom: 1px solid rgba(238,242,248,.12); }
+.ask-head h2 { flex: 1; margin: 0; font-size: 20px; font-weight: 500; letter-spacing: -0.02em; font-variation-settings: "STYL" 0; }
+.ask-head .close { width: 44px; padding: 0; display: grid; place-items: center; }
+.ask-head .close svg { width: 18px; height: 18px; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; fill: none; }
+.ask-note { padding: 22px 20px; display: flex; flex-direction: column; gap: 14px; align-items: flex-start; }
+.ask-note p { margin: 0; color: var(--haze); }
+.ask-chat { flex: 1; min-height: 0; display: flex; flex-direction: column; }
+.thread { flex: 1; min-height: 0; overflow-y: auto; list-style: none; margin: 0; padding: 18px 16px; display: flex; flex-direction: column; gap: 10px; }
+.msg { max-width: 86%; padding: 10px 14px; border-radius: 14px; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 15px; line-height: 1.5; }
+.msg.person { align-self: flex-end; background: rgba(47,198,192,.24); box-shadow: inset 0 0 0 1px rgba(110,231,220,.35); border-bottom-right-radius: 4px; }
+.msg.coordinator { align-self: flex-start; background: rgba(238,242,248,.08); box-shadow: inset 0 0 0 1px rgba(238,242,248,.16); border-bottom-left-radius: 4px; }
+.msg.draft::after { content: ""; display: inline-block; width: 7px; height: 1em; margin-left: 3px; vertical-align: -2px; background: var(--signal); animation: caret 1s steps(2) infinite; }
+@keyframes caret { 50% { opacity: 0; } }
+.msg.card { align-self: stretch; max-width: none; background: rgba(139,92,246,.16); box-shadow: inset 0 0 0 1px rgba(139,92,246,.45); }
+.msg.card p { margin: 0 0 10px; }
+.choices { display: flex; flex-wrap: wrap; gap: 8px; }
+.ask-empty, .ask-problem { margin: 0; padding: 0 20px 12px; color: var(--haze); font-size: 14px; }
+.ask-foot { display: flex; align-items: center; gap: 10px; padding: 0 16px; }
+.ask-status { flex: 1; margin: 0; min-height: 1.5em; color: var(--haze); font-size: 14px; }
+.ask-status:empty { min-height: 0; }
+.composer { display: flex; gap: 8px; align-items: flex-end; padding: 10px 16px 16px; }
+.composer textarea.input { flex: 1; height: auto; min-height: 44px; max-height: 160px; padding: 11px 14px; resize: none; font: inherit; line-height: 20px; field-sizing: content; }
+.ask-page { display: flex; flex-direction: column; padding: 22px 0 0; }
+.ask-page .crumb { padding: 0 24px; }
+.ask-page .ask-head { padding-left: 24px; }
+.ask-page .thread { max-height: none; }
+.signin p.code { margin: 6px 0 18px; font-size: 32px; font-weight: 600; letter-spacing: .14em; text-align: center; color: var(--frost);
+ font-variant-numeric: tabular-nums; font-variation-settings: "STYL" 0; }
+@media (max-width: 600px) {
+ dialog.ask-panel { inset: 0; width: 100%; border-radius: 0; }
+ .msg { max-width: 92%; }
+}
/* Scratchpad's shared note: a field that grows past one control height. */
.notepad { display: flex; flex-direction: column; gap: 12px; align-items: flex-start; }
diff --git a/internal/look/static/ask.js b/internal/look/static/ask.js
new file mode 100644
index 0000000..5180661
--- /dev/null
+++ b/internal/look/static/ask.js
@@ -0,0 +1,269 @@
+// "Ask Base anything": the chat panel over Home (a <dialog>), and the /ask
+// page. Without this script the field is a link to /ask, whose forms post
+// and come back; with it, the same forms go by fetch and replies stream in
+// through /ask/events, which Base relays from Equipo. Text is only ever set
+// with textContent.
+
+const root = document.querySelector("[data-ask]");
+if (root) start(root);
+
+function start(root) {
+ const dialog = root.tagName === "DIALOG" ? root : null;
+ const opener = document.querySelector("[data-ask-open]");
+ const thread = root.querySelector(".thread");
+ const empty = root.querySelector("[data-empty]");
+ const status = root.querySelector(".ask-status");
+ const stop = root.querySelector("form.stop");
+ const composer = root.querySelector("form.composer");
+ const field = composer.querySelector("textarea");
+ let source = null;
+ let turn = null;
+ let retry = 0;
+
+ const json = { Accept: "application/json" };
+
+ function show(state) {
+ root.dataset.state = state;
+ for (const el of root.querySelectorAll("[data-when]")) {
+ el.hidden = !el.dataset.when.split(" ").includes(state);
+ }
+ }
+
+ function key() {
+ const b = crypto.getRandomValues(new Uint8Array(16));
+ return Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
+ }
+
+ function scroll() {
+ thread.scrollTop = thread.scrollHeight;
+ empty.hidden = thread.children.length > 0;
+ }
+
+ function item(attr, id) {
+ return id ? thread.querySelector(`[${attr}="${CSS.escape(id)}"]`) : null;
+ }
+
+ // A message, once: a coordinator's reply takes its streamed draft's place.
+ function addMessage(m) {
+ if (!m || item("data-id", m.id)) return;
+ const li = document.createElement("li");
+ li.className = "msg " + (m.role === "person" ? "person" : "coordinator");
+ li.dataset.id = m.id;
+ li.textContent = m.text;
+ const draft = m.role !== "person" && item("data-draft", m.turn_id);
+ if (draft) draft.replaceWith(li);
+ else thread.append(li);
+ scroll();
+ }
+
+ function delta(d) {
+ let li = item("data-draft", d.turn_id);
+ if (!li) {
+ li = document.createElement("li");
+ li.className = "msg coordinator draft";
+ li.dataset.draft = d.turn_id;
+ li.setAttribute("aria-busy", "true");
+ thread.append(li);
+ }
+ if (d.offset === li.textContent.length) li.textContent += d.text;
+ scroll();
+ }
+
+ function addCard(c) {
+ const old = item("data-card", c.id);
+ if (!(c.kind === "question" && c.state === "open")) {
+ if (old) old.remove();
+ scroll();
+ return;
+ }
+ if (old) return;
+ const li = document.createElement("li");
+ li.className = "msg card";
+ li.dataset.card = c.id;
+ const q = document.createElement("p");
+ q.textContent = c.question;
+ const form = document.createElement("form");
+ form.className = "choices";
+ form.method = "post";
+ form.action = `/ask/cards/${encodeURIComponent(c.id)}/answer`;
+ const rev = document.createElement("input");
+ rev.type = "hidden";
+ rev.name = "revision";
+ rev.value = String(c.revision);
+ form.append(rev);
+ for (const o of c.options || []) {
+ const b = document.createElement("button");
+ b.className = "btn ghost";
+ b.type = "submit";
+ b.name = "choice";
+ b.value = o;
+ b.textContent = o;
+ form.append(b);
+ }
+ li.append(q, form);
+ thread.append(li);
+ scroll();
+ }
+
+ const ended = (s) => s === "replied" || s === "failed" || s === "cancelled";
+
+ function setTurn(t, line) {
+ if (t && !ended(t.state)) {
+ turn = t;
+ stop.action = `/ask/turns/${encodeURIComponent(t.id)}/cancel`;
+ stop.hidden = false;
+ status.textContent = line || (t.state === "waiting"
+ ? "Equipo can't answer right now. It will as soon as it can."
+ : "Equipo is answering…");
+ return;
+ }
+ if (t && turn && t.id !== turn.id) return;
+ turn = null;
+ stop.hidden = true;
+ status.textContent = t && t.state === "failed" ? "That didn't get an answer. Try again." : "";
+ for (const d of thread.querySelectorAll("[data-draft]")) {
+ if (!t || d.dataset.draft === t.id) {
+ if (t && t.state === "cancelled") d.remove();
+ else d.removeAttribute("aria-busy");
+ }
+ }
+ }
+
+ function listen(cursor) {
+ quiet();
+ source = new EventSource(`/ask/events?after=${encodeURIComponent(cursor)}`);
+ const on = (type, fn) => source.addEventListener(type, (e) => {
+ retry = 0;
+ fn(JSON.parse(e.data));
+ });
+ on("message", (e) => addMessage(e.data));
+ on("delta", (e) => delta(e.data));
+ on("card", (e) => addCard(e.data));
+ on("turn", (e) => setTurn(e.data));
+ on("activity", (e) => {
+ if (turn && e.data.turn_id === turn.id && e.data.label) status.textContent = e.data.label;
+ });
+ on("state", (e) => {
+ quiet();
+ show(e.state);
+ });
+ source.onerror = () => {
+ if (source && source.readyState === EventSource.CLOSED) {
+ quiet();
+ retry = Math.min(retry + 1, 6);
+ setTimeout(() => { if (live()) load(); }, 2000 * retry);
+ }
+ };
+ }
+
+ function quiet() {
+ if (source) source.close();
+ source = null;
+ }
+
+ const live = () => !dialog || dialog.open;
+
+ async function load() {
+ let s;
+ try {
+ const res = await fetch("/ask/state", { headers: json });
+ if (!res.ok) throw new Error(res.status);
+ s = await res.json();
+ } catch {
+ show("unavailable");
+ return;
+ }
+ show(s.state);
+ if (s.state !== "ready" || !live()) return;
+ thread.replaceChildren();
+ s.messages.forEach(addMessage);
+ s.cards.forEach(addCard);
+ setTurn(s.turn, s.status);
+ scroll();
+ listen(s.cursor);
+ }
+
+ // post sends a form by fetch and returns its JSON, or null when it failed
+ // (and the panel says so).
+ async function post(form, extra) {
+ const body = new URLSearchParams(new FormData(form));
+ for (const [k, v] of Object.entries(extra || {})) body.set(k, v);
+ try {
+ const res = await fetch(form.action, { method: "POST", headers: json, body });
+ const out = await res.json();
+ if (res.ok) return out;
+ if (out.state && out.state !== "ready") show(out.state);
+ else if (res.status !== 409) status.textContent = "Equipo didn't get that. Try again.";
+ } catch {
+ status.textContent = "Equipo didn't get that. Try again.";
+ }
+ return null;
+ }
+
+ composer.addEventListener("submit", async (e) => {
+ e.preventDefault();
+ if (!field.value.trim()) return;
+ const sent = await post(composer, { key: key() });
+ if (!sent) return;
+ field.value = "";
+ addMessage(sent.message);
+ setTurn(sent.turn);
+ });
+ field.addEventListener("keydown", (e) => {
+ if (e.key === "Enter" && !e.shiftKey && !e.isComposing) {
+ e.preventDefault();
+ composer.requestSubmit();
+ }
+ });
+ stop.addEventListener("submit", (e) => {
+ e.preventDefault();
+ post(stop);
+ });
+ thread.addEventListener("submit", async (e) => {
+ e.preventDefault();
+ const form = e.target;
+ const choice = e.submitter && e.submitter.value;
+ if (!choice) return;
+ for (const b of form.querySelectorAll("button")) b.disabled = true;
+ const out = await post(form, { choice });
+ if (!out) {
+ for (const b of form.querySelectorAll("button")) b.disabled = false;
+ return;
+ }
+ addCard(out.card);
+ addMessage(out.message);
+ setTurn(out.turn);
+ });
+
+ if (!dialog) {
+ load();
+ return;
+ }
+
+ function open() {
+ if (dialog.open) return;
+ dialog.showModal();
+ load().then(() => {
+ const first = root.dataset.state === "ready" ? field : dialog.querySelector("[data-when]:not([hidden]) .btn");
+ if (first) first.focus();
+ });
+ field.focus();
+ }
+ opener.addEventListener("click", (e) => {
+ e.preventDefault();
+ open();
+ });
+ dialog.querySelector("[data-ask-close]").addEventListener("click", () => dialog.close());
+ // A click on the backdrop (outside the panel) closes it too.
+ dialog.addEventListener("click", (e) => {
+ if (e.target === dialog) dialog.close();
+ });
+ dialog.addEventListener("close", () => {
+ quiet();
+ opener.focus();
+ });
+ if (location.hash === "#ask") {
+ history.replaceState(null, "", location.pathname + location.search);
+ open();
+ }
+}
diff --git a/internal/web/app.go b/internal/web/app.go
index a141de1..75b4aef 100644
--- a/internal/web/app.go
+++ b/internal/web/app.go
@@ -31,7 +31,7 @@ import (
"amadan.net/carlos/base/internal/store"
)
-//go:embed templates/*.html
+//go:embed templates/*.html templates/partials/*.html
var templateFS embed.FS
// Installer installs and uninstalls catalogue apps for this Base;
@@ -55,6 +55,8 @@ type app struct {
mailer mail.Sender
// oficina is sign-in with Oficina ID, nil when cfg.Home is.
oficina *oficina
+ // ask is "Ask Base anything", nil when cfg.EquipoOrigin is empty.
+ ask *asker
}
// App builds Base's router. d is rastrillo's database handle (auth and
@@ -81,6 +83,9 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
return nil, err
}
a := &app{db: d.Writer(), cfg: cfg, inst: inst, logger: logger, pages: pages, mailer: mailer}
+ if cfg.EquipoOrigin != "" {
+ a.ask = newAsker(cfg.EquipoOrigin, cfg.InstanceKey, cfg.Name)
+ }
guard, err := pow.New(pow.Config{InstanceKey: cfg.InstanceKey, Nonces: pow.SQLNonces(d.Writer()), Difficulty: pow.NoProof, MinAge: pow.DefaultMinAge})
if err != nil {
return nil, err
@@ -190,6 +195,9 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
r.With(ownSignInOnly).Post(registerBeginPath, a.pk.RegisterBegin)
r.With(ownSignInOnly).Post(registerFinishPath, a.pk.RegisterFinish)
r.Method(http.MethodGet, "/authorize", authorize)
+ if a.ask != nil {
+ a.askRoutes(r)
+ }
})
return r, nil
}
diff --git a/internal/web/ask.go b/internal/web/ask.go
new file mode 100644
index 0000000..76c7e9c
--- /dev/null
+++ b/internal/web/ask.go
@@ -0,0 +1,255 @@
+package web
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+
+ "amadan.net/carlos/base/internal/equipo"
+ "amadan.net/carlos/base/internal/store"
+)
+
+// asker is "Ask Base anything": Equipo's coordinator chat, relayed server
+// to server with each member's own device bearer. Nil when
+// BASE_EQUIPO_ORIGIN is unset.
+type asker struct {
+ client *equipo.Client
+ seal equipo.Sealer
+ // label is the device name a member sees when approving Base in Equipo.
+ label string
+}
+
+// askRoutes mounts the chat, behind the member gate and Base's CSRF check.
+func (a *app) askRoutes(r chi.Router) {
+ r.Get("/ask", a.askPageView)
+ r.Get("/ask/state", a.askStateJSON)
+ r.Get("/ask/events", a.askEvents)
+ r.Post("/ask/messages", a.askSend)
+ r.Post("/ask/turns/{id}/cancel", a.askCancel)
+ r.Post("/ask/cards/{id}/answer", a.askAnswer)
+ r.Post("/ask/connect", a.askConnectStart)
+ r.Get("/ask/connect", a.askConnectPage)
+ r.Post("/ask/disconnect", a.askDisconnect)
+}
+
+func newAsker(origin, instanceKey, name string) *asker {
+ return &asker{client: equipo.New(origin), seal: equipo.NewSealer(instanceKey), label: "Base (" + name + ")"}
+}
+
+// The states of a member's chat. Connect: nothing connected; pending: a
+// sign-in code waits for approval in Equipo; expired and refused: that code
+// can no longer be approved; ready: a live bearer; reconnect: Equipo
+// refused the bearer or it expired; unavailable: Equipo did not answer.
+const (
+ askConnect = "connect"
+ askPending = "pending"
+ askExpired = "expired"
+ askRefused = "refused"
+ askReady = "ready"
+ askReconnect = "reconnect"
+ askUnavailable = "unavailable"
+)
+
+// deviceSecrets is what Base keeps sealed for a member's Equipo device:
+// the Ed25519 seed, the device secret, the challenge and the nonce it
+// proves with (kept, so a lost exchange answer can be asked for again),
+// and the bearer once it has one.
+type deviceSecrets struct {
+ Seed []byte `json:"seed"`
+ Secret string `json:"secret"`
+ Challenge string `json:"challenge"`
+ Nonce string `json:"nonce"`
+ Token string `json:"token,omitempty"`
+}
+
+func (a *app) sealSecrets(memberID string, s deviceSecrets) ([]byte, error) {
+ raw, err := json.Marshal(s)
+ if err != nil {
+ return nil, err
+ }
+ return a.ask.seal.Seal(memberID, raw)
+}
+
+// askLink reads the member's link and its secrets, and the state they put
+// the chat in, without calling Equipo. A link to another Equipo, or sealed
+// under another instance key, counts as none.
+func (a *app) askLink(ctx context.Context, me store.Member) (store.EquipoLink, deviceSecrets, string, error) {
+ var sec deviceSecrets
+ l, ok, err := store.EquipoLinkFor(ctx, a.db, me.ID)
+ if err != nil {
+ return l, sec, "", err
+ }
+ if !ok || l.Origin != a.ask.client.Origin() {
+ return store.EquipoLink{}, sec, askConnect, nil
+ }
+ raw, err := a.ask.seal.Open(me.ID, l.Sealed)
+ if err != nil || json.Unmarshal(raw, &sec) != nil {
+ return store.EquipoLink{}, deviceSecrets{}, askConnect, nil
+ }
+ live := time.Now().Before(l.ExpiresAt)
+ switch {
+ case l.State == store.EquipoPending && live:
+ return l, sec, askPending, nil
+ case l.State == store.EquipoPending:
+ return l, sec, askExpired, nil
+ case l.State == store.EquipoConnected && live && sec.Token != "":
+ return l, sec, askReady, nil
+ }
+ return l, sec, askReconnect, nil
+}
+
+// askLost records that Equipo refused the member's bearer.
+func (a *app) askLost(ctx context.Context, me store.Member) {
+ if err := store.SetEquipoLinkState(ctx, a.db, me.ID, store.EquipoLost); err != nil {
+ a.logger.Error("ask: mark lost", "err", err)
+ }
+}
+
+// askView is the chat as a page or the panel draws it.
+type askView struct {
+ State string
+ // Next is where connecting comes back to: home, settings or ask.
+ Next string
+ // Equipo is the "Open Equipo" link.
+ Equipo string
+ Messages []equipo.Message
+ Cards []equipo.Card
+ Turn *equipo.Turn
+ Status string
+ Key string
+ Problem string
+}
+
+// Shows reports whether the block for states (space-separated) shows now.
+func (v askView) Shows(states string) bool {
+ for _, s := range strings.Fields(states) {
+ if s == v.State {
+ return true
+ }
+ }
+ return false
+}
+
+// homeState is the state Home and Settings show, read without calling
+// Equipo: a code that can no longer be approved is as good as none.
+func homeState(state string) string {
+ if state == askExpired || state == askRefused {
+ return askConnect
+ }
+ return state
+}
+
+func (a *app) newAskView(state, next string) askView {
+ return askView{State: state, Next: next, Equipo: a.ask.client.Origin() + "/", Key: equipo.NewKey()}
+}
+
+// turnStatus is the line under the conversation while a turn runs.
+func turnStatus(t *equipo.Turn) string {
+ switch {
+ case t == nil:
+ return ""
+ case t.State == equipo.TurnWaiting:
+ return "Equipo can't answer right now. It will as soon as it can."
+ }
+ return "Equipo is answering…"
+}
+
+// fill puts a snapshot in the view: the messages, the open questions and
+// the newest turn that has not ended.
+func (v *askView) fill(s equipo.Snapshot) {
+ v.Messages = s.Messages
+ for _, c := range s.Cards {
+ if c.Open() {
+ v.Cards = append(v.Cards, c)
+ }
+ }
+ for i := len(s.Turns) - 1; i >= 0; i-- {
+ if equipo.InFlight(s.Turns[i].State) {
+ t := s.Turns[i]
+ v.Turn = &t
+ break
+ }
+ }
+ v.Status = turnStatus(v.Turn)
+}
+
+// askSnapshot reads the member's conversation into v, moving v.State to
+// reconnect or unavailable when Equipo refuses or does not answer.
+func (a *app) askSnapshot(r *http.Request, me store.Member, token string, v *askView) int64 {
+ s, err := a.ask.client.Snapshot(r.Context(), token)
+ switch {
+ case errors.Is(err, equipo.ErrUnauthenticated):
+ a.askLost(r.Context(), me)
+ v.State = askReconnect
+ case err != nil:
+ a.logger.Warn("ask: snapshot", "err", err)
+ v.State = askUnavailable
+ default:
+ v.fill(s)
+ }
+ return s.Cursor
+}
+
+type askPage struct {
+ Name string
+ Ask askView
+}
+
+// askPageView is GET /ask: the whole conversation as a page, which works
+// with scripts off.
+func (a *app) askPageView(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ _, sec, state, err := a.askLink(r.Context(), me)
+ if err != nil {
+ a.logger.Error("ask: link", "err", err)
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ return
+ }
+ v := a.newAskView(homeState(state), "ask")
+ if state == askReady {
+ a.askSnapshot(r, me, sec.Token, &v)
+ }
+ if r.URL.Query().Get("problem") != "" && v.State == askReady {
+ v.Problem = "Equipo didn't get that. Try again."
+ }
+ w.Header().Set("Cache-Control", "no-store")
+ a.render(w, "ask", askPage{Name: a.cfg.Name, Ask: v})
+}
+
+// askStateJSON is GET /ask/state: what the panel draws, and the cursor its
+// event stream starts after.
+func (a *app) askStateJSON(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ _, sec, state, err := a.askLink(r.Context(), me)
+ if err != nil {
+ a.logger.Error("ask: link", "err", err)
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ return
+ }
+ v := a.newAskView(homeState(state), "home")
+ var cursor int64
+ if state == askReady {
+ cursor = a.askSnapshot(r, me, sec.Token, &v)
+ }
+ out := struct {
+ State string `json:"state"`
+ Messages []equipo.Message `json:"messages"`
+ Cards []equipo.Card `json:"cards"`
+ Turn *equipo.Turn `json:"turn"`
+ Status string `json:"status"`
+ Cursor int64 `json:"cursor"`
+ }{v.State, append([]equipo.Message{}, v.Messages...), append([]equipo.Card{}, v.Cards...), v.Turn, v.Status, cursor}
+ writeJSON(w, http.StatusOK, out)
+}
+
+func writeJSON(w http.ResponseWriter, status int, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Cache-Control", "no-store")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(v)
+}
diff --git a/internal/web/ask_connect.go b/internal/web/ask_connect.go
new file mode 100644
index 0000000..a92fab4
--- /dev/null
+++ b/internal/web/ask_connect.go
@@ -0,0 +1,188 @@
+package web
+
+import (
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "errors"
+ "net/http"
+ "strings"
+ "time"
+
+ "amadan.net/carlos/base/internal/equipo"
+ "amadan.net/carlos/base/internal/store"
+)
+
+// askNext is where connecting Equipo comes back to; "home" opens the panel.
+var askNext = map[string]string{"home": "/#ask", "settings": "/settings", "ask": "/ask"}
+
+func nextOf(v string) string {
+ if _, ok := askNext[v]; ok {
+ return v
+ }
+ return "ask"
+}
+
+// pollEvery is Equipo's shortest interval between two exchange attempts.
+const pollEvery = 5 * time.Second
+
+type connectView struct {
+ Name, Label, State, Next string
+ Code, Verify, Back string
+ Problem string
+}
+
+// askConnectStart is POST /ask/connect: Connect Equipo (or Reconnect). Base
+// makes the member a device key pair, asks Equipo for a sign-in code and
+// shows it; the member approves it in Equipo.
+func (a *app) askConnectStart(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ next := nextOf(r.PostFormValue("next"))
+ ctx := r.Context()
+ if old, sec, state, err := a.askLink(ctx, me); err == nil && state == askReady {
+ a.revoke(ctx, old, sec)
+ }
+ pub, key, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ a.fail(w, err)
+ return
+ }
+ ch, err := a.ask.client.BeginDevice(ctx, pub, a.ask.label)
+ if err != nil {
+ a.logger.Warn("ask: begin device", "err", err)
+ a.renderConnect(w, r, http.StatusBadGateway, connectView{State: askConnect, Next: next,
+ Problem: "Equipo isn't answering. Try again in a minute."})
+ return
+ }
+ sealed, err := a.sealSecrets(me.ID, deviceSecrets{Seed: key.Seed(), Secret: ch.DeviceSecret,
+ Challenge: ch.Challenge, Nonce: rand.Text()})
+ if err != nil {
+ a.fail(w, err)
+ return
+ }
+ exp := ch.ExpiresAt
+ if exp.IsZero() {
+ exp = time.Now().Add(10 * time.Minute)
+ }
+ if err := store.SaveEquipoLink(ctx, a.db, store.EquipoLink{MemberID: me.ID, Origin: a.ask.client.Origin(),
+ State: store.EquipoPending, DeviceID: ch.ID, UserCode: ch.UserCode,
+ VerificationURI: a.verifyURI(ch), Sealed: sealed, ExpiresAt: exp}); err != nil {
+ a.fail(w, err)
+ return
+ }
+ http.Redirect(w, r, "/ask/connect?next="+next, http.StatusSeeOther)
+}
+
+// verifyURI is Equipo's approval page for ch, which must be on Equipo's
+// own origin: Base links to nothing else.
+func (a *app) verifyURI(ch equipo.Challenge) string {
+ if origin := a.ask.client.Origin(); strings.HasPrefix(ch.VerificationURI, origin+"/") {
+ return ch.VerificationURI
+ }
+ return a.ask.client.Origin() + "/auth/devices/" + ch.ID
+}
+
+// askConnectPage is GET /ask/connect: the code to approve while it waits,
+// finishing the exchange once the member has approved it. It refreshes
+// itself every five seconds, and asks Equipo no more often than that.
+func (a *app) askConnectPage(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ next := nextOf(r.URL.Query().Get("next"))
+ l, sec, state, err := a.askLink(r.Context(), me)
+ if err != nil {
+ a.fail(w, err)
+ return
+ }
+ v := connectView{State: state, Next: next}
+ if state == askPending {
+ if v.State, err = a.poll(r.Context(), me, l, sec); err != nil {
+ a.logger.Warn("ask: exchange", "err", err)
+ v.Problem = "Equipo isn't answering. Base will keep trying."
+ }
+ }
+ if v.State == askReady {
+ http.Redirect(w, r, askNext[next], http.StatusSeeOther)
+ return
+ }
+ v.Code, v.Verify = l.UserCode, l.VerificationURI
+ a.renderConnect(w, r, http.StatusOK, v)
+}
+
+// poll asks Equipo whether the member approved the code, and stores the
+// bearer if so. It does not ask within pollEvery of the last time.
+func (a *app) poll(ctx context.Context, me store.Member, l store.EquipoLink, sec deviceSecrets) (string, error) {
+ now := time.Now()
+ if l.PolledAt != nil && now.Sub(*l.PolledAt) < pollEvery {
+ return askPending, nil
+ }
+ if err := store.MarkEquipoPolled(ctx, a.db, me.ID, now); err != nil {
+ return askPending, err
+ }
+ ch := equipo.Challenge{ID: l.DeviceID, DeviceSecret: sec.Secret, Challenge: sec.Challenge}
+ proof, err := equipo.Prove(ed25519.NewKeyFromSeed(sec.Seed), ch, sec.Nonce)
+ if err != nil {
+ return askPending, err
+ }
+ cred, err := a.ask.client.Exchange(ctx, proof)
+ var e *equipo.Error
+ switch {
+ case errors.Is(err, equipo.ErrPending), errors.Is(err, equipo.ErrSlowDown):
+ return askPending, nil
+ case errors.Is(err, equipo.ErrExpired):
+ return askExpired, store.DeleteEquipoLink(ctx, a.db, me.ID)
+ case errors.As(err, &e) && e.Status == http.StatusForbidden:
+ return askRefused, store.DeleteEquipoLink(ctx, a.db, me.ID)
+ case err != nil:
+ return askPending, err
+ }
+ sec.Token = cred.Token
+ sealed, err := a.sealSecrets(me.ID, sec)
+ if err != nil {
+ return askPending, err
+ }
+ l.State, l.Sealed, l.ExpiresAt, l.Revision, l.UserCode = store.EquipoConnected, sealed, cred.ExpiresAt, cred.Revision, ""
+ if err := store.SaveEquipoLink(ctx, a.db, l); err != nil {
+ return askPending, err
+ }
+ return askReady, nil
+}
+
+// revoke revokes the member's device in Equipo, as itself. It is best
+// effort: the bearer is about to be forgotten either way.
+func (a *app) revoke(ctx context.Context, l store.EquipoLink, sec deviceSecrets) {
+ err := a.ask.client.RevokeDevice(ctx, sec.Token, l.DeviceID, l.Revision)
+ if err != nil && !errors.Is(err, equipo.ErrUnauthenticated) {
+ a.logger.Warn("ask: revoke device", "device", l.DeviceID, "err", err)
+ }
+}
+
+// askDisconnect is POST /ask/disconnect, from Settings.
+func (a *app) askDisconnect(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ l, sec, state, err := a.askLink(r.Context(), me)
+ if err != nil {
+ a.fail(w, err)
+ return
+ }
+ if state == askReady {
+ a.revoke(r.Context(), l, sec)
+ }
+ if err := store.DeleteEquipoLink(r.Context(), a.db, me.ID); err != nil {
+ a.fail(w, err)
+ return
+ }
+ http.Redirect(w, r, "/settings", http.StatusSeeOther)
+}
+
+func (a *app) renderConnect(w http.ResponseWriter, r *http.Request, status int, v connectView) {
+ v.Name, v.Label, v.Back = a.cfg.Name, a.ask.label, askNext[v.Next]
+ w.Header().Set("Cache-Control", "no-store")
+ if err := a.pages.PageStatus(w, status, "ask_connect", v); err != nil {
+ a.fail(w, err)
+ }
+}
+
+func (a *app) fail(w http.ResponseWriter, err error) {
+ a.logger.Error("ask", "err", err)
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+}
diff --git a/internal/web/ask_relay.go b/internal/web/ask_relay.go
new file mode 100644
index 0000000..87e21a9
--- /dev/null
+++ b/internal/web/ask_relay.go
@@ -0,0 +1,232 @@
+package web
+
+import (
+ "bufio"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+
+ "github.com/go-chi/chi/v5"
+
+ "amadan.net/carlos/base/internal/equipo"
+ "amadan.net/carlos/base/internal/store"
+)
+
+// maxAskForm bounds a chat form; Equipo takes 16 KiB of message text.
+const (
+ maxAskForm = 64 << 10
+ maxAskText = 16 << 10
+)
+
+// wantsJSON: the panel's script asks for JSON; a plain form gets a 303.
+func wantsJSON(r *http.Request) bool {
+ return strings.Contains(r.Header.Get("Accept"), "application/json")
+}
+
+// askBearer is the member's bearer for a relayed write. Without one it
+// answers for the caller: the panel hears the state, a form goes to /ask.
+func (a *app) askBearer(w http.ResponseWriter, r *http.Request) (store.Member, string, bool) {
+ me, _ := CurrentMember(r)
+ r.Body = http.MaxBytesReader(w, r.Body, maxAskForm)
+ if err := r.ParseForm(); err != nil {
+ http.Error(w, "bad request", http.StatusBadRequest)
+ return me, "", false
+ }
+ _, sec, state, err := a.askLink(r.Context(), me)
+ switch {
+ case err != nil:
+ a.logger.Error("ask: link", "err", err)
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ case state != askReady && wantsJSON(r):
+ writeJSON(w, http.StatusConflict, map[string]string{"state": homeState(state)})
+ case state != askReady:
+ http.Redirect(w, r, "/ask", http.StatusSeeOther)
+ default:
+ return me, sec.Token, true
+ }
+ return me, "", false
+}
+
+// askDone finishes a relayed write. A 401 from Equipo means the member must
+// reconnect; a 409 (a card already answered, a turn already ended) is
+// stale, and the conversation as it is now says so; anything else is a
+// problem to try again.
+func (a *app) askDone(w http.ResponseWriter, r *http.Request, me store.Member, err error, out any) {
+ var e *equipo.Error
+ status, state := http.StatusOK, askReady
+ switch {
+ case errors.Is(err, equipo.ErrUnauthenticated):
+ a.askLost(r.Context(), me)
+ status, state = http.StatusUnauthorized, askReconnect
+ case errors.As(err, &e) && e.Status == http.StatusConflict:
+ status = http.StatusConflict
+ case err != nil:
+ a.logger.Warn("ask: relay", "err", err)
+ status, state = http.StatusBadGateway, askUnavailable
+ }
+ if !wantsJSON(r) {
+ target := "/ask"
+ if status == http.StatusBadGateway {
+ target += "?problem=1"
+ }
+ http.Redirect(w, r, target, http.StatusSeeOther)
+ return
+ }
+ if err != nil {
+ writeJSON(w, status, map[string]string{"state": state})
+ return
+ }
+ writeJSON(w, status, out)
+}
+
+// askKey is the message key the form carries, so pressing Send twice
+// sends once; a missing or unusable one gets a fresh key.
+func askKey(k string) string {
+ if k == "" || len(k) > 128 || !utf8.ValidString(k) || strings.HasPrefix(k, "reply:") || strings.HasPrefix(k, "card:") {
+ return equipo.NewKey()
+ }
+ return k
+}
+
+// askSend is POST /ask/messages.
+func (a *app) askSend(w http.ResponseWriter, r *http.Request) {
+ me, token, ok := a.askBearer(w, r)
+ if !ok {
+ return
+ }
+ text := strings.TrimSpace(r.PostFormValue("text"))
+ if text == "" || len(text) > maxAskText {
+ if wantsJSON(r) {
+ writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"state": askReady})
+ } else {
+ http.Redirect(w, r, "/ask", http.StatusSeeOther)
+ }
+ return
+ }
+ sent, err := a.ask.client.Send(r.Context(), token, text, askKey(r.PostFormValue("key")))
+ a.askDone(w, r, me, err, sent)
+}
+
+// askCancel is POST /ask/turns/{id}/cancel: Stop.
+func (a *app) askCancel(w http.ResponseWriter, r *http.Request) {
+ me, token, ok := a.askBearer(w, r)
+ if !ok {
+ return
+ }
+ err := a.ask.client.Cancel(r.Context(), token, chi.URLParam(r, "id"), equipo.NewKey())
+ a.askDone(w, r, me, err, map[string]string{"state": askReady})
+}
+
+// askAnswer is POST /ask/cards/{id}/answer: one of a question's buttons.
+func (a *app) askAnswer(w http.ResponseWriter, r *http.Request) {
+ me, token, ok := a.askBearer(w, r)
+ if !ok {
+ return
+ }
+ rev, _ := strconv.ParseInt(r.PostFormValue("revision"), 10, 64)
+ out, err := a.ask.client.Answer(r.Context(), token, chi.URLParam(r, "id"), r.PostFormValue("choice"), rev, equipo.NewKey())
+ a.askDone(w, r, me, err, out)
+}
+
+// relayed are the event types the panel gets: the conversation's own.
+// Equipo's stream also carries runners, projects, tasks and the rest,
+// which Base keeps to Equipo.
+var relayed = map[string]bool{"message": true, "turn": true, "delta": true, "activity": true, "card": true}
+
+// askEvents is GET /ask/events: Equipo's event stream for the member,
+// relayed with their bearer. The cursor is Last-Event-ID when the browser
+// reconnects (it moves on with every event), else ?after=.
+func (a *app) askEvents(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ after := r.Header.Get("Last-Event-ID")
+ if after == "" {
+ after = r.URL.Query().Get("after")
+ }
+ if _, err := strconv.ParseUint(after, 10, 63); after != "" && err != nil {
+ http.Error(w, "bad request", http.StatusBadRequest)
+ return
+ }
+ _, sec, state, err := a.askLink(r.Context(), me)
+ if err != nil {
+ a.logger.Error("ask: link", "err", err)
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ return
+ }
+ if state != askReady {
+ endStream(w, homeState(state))
+ return
+ }
+ res, err := a.ask.client.Events(r.Context(), sec.Token, after)
+ if errors.Is(err, equipo.ErrUnauthenticated) {
+ a.askLost(r.Context(), me)
+ endStream(w, askReconnect)
+ return
+ }
+ if err != nil {
+ a.logger.Warn("ask: events", "err", err)
+ http.Error(w, "unavailable", http.StatusBadGateway)
+ return
+ }
+ defer res.Body.Close()
+ rc := http.NewResponseController(w)
+ streamHeaders(w)
+ if _, err := io.WriteString(w, "retry: 3000\n\n"); err != nil || rc.Flush() != nil {
+ return
+ }
+ relay(w, rc, res.Body)
+}
+
+func streamHeaders(w http.ResponseWriter) {
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("X-Accel-Buffering", "no")
+ w.WriteHeader(http.StatusOK)
+}
+
+// endStream answers a stream that cannot start with one "state" event
+// saying why, so the panel shows it instead of retrying.
+func endStream(w http.ResponseWriter, state string) {
+ streamHeaders(w)
+ fmt.Fprintf(w, "event: state\ndata: {\"state\":%q}\n\n", state)
+}
+
+// relay copies the events in relayed from upstream to w as they come,
+// with their ids, and turns Equipo's pings into comments that keep the
+// connection open.
+func relay(w io.Writer, rc *http.ResponseController, upstream io.Reader) {
+ sc := bufio.NewScanner(upstream)
+ sc.Buffer(make([]byte, 64<<10), 1<<20)
+ var block []string
+ typ := "message"
+ for sc.Scan() {
+ line := sc.Text()
+ if line != "" {
+ if t, ok := strings.CutPrefix(line, "event:"); ok {
+ typ = strings.TrimSpace(t)
+ }
+ if !strings.HasPrefix(line, ":") && !strings.HasPrefix(line, "retry:") {
+ block = append(block, line)
+ }
+ continue
+ }
+ out := ""
+ switch {
+ case len(block) == 0:
+ case relayed[typ]:
+ out = strings.Join(block, "\n") + "\n\n"
+ case typ == "ping":
+ out = ": ping\n\n"
+ }
+ block, typ = nil, "message"
+ if out == "" {
+ continue
+ }
+ if _, err := io.WriteString(w, out); err != nil || rc.Flush() != nil {
+ return
+ }
+ }
+}
diff --git a/internal/web/home.go b/internal/web/home.go
index 1fb562f..2297d5a 100644
--- a/internal/web/home.go
+++ b/internal/web/home.go
@@ -29,6 +29,8 @@ type homePage struct {
Lede string
Steps []step
Tiles []tile
+ // Ask is the chat panel, nil with the chat off.
+ Ask *askView
}
// Icons for the built-in tiles, in the mockup's style.
@@ -133,6 +135,15 @@ func (a *app) home(w http.ResponseWriter, r *http.Request) {
default:
page.Lede = "Two steps until " + a.cfg.Name + "'s Base is ready."
}
+ if a.ask != nil {
+ _, _, state, err := a.askLink(r.Context(), me)
+ if err != nil {
+ a.logger.Error("home: equipo link", "err", err)
+ state = askUnavailable
+ }
+ v := a.newAskView(homeState(state), "home")
+ page.Ask = &v
+ }
w.Header().Set("Cache-Control", "no-store")
a.render(w, "home", page)
}
diff --git a/internal/web/settings.go b/internal/web/settings.go
index cef5774..4ff0a70 100644
--- a/internal/web/settings.go
+++ b/internal/web/settings.go
@@ -25,6 +25,9 @@ type settingsPage struct {
// Oficina account. Connect offers to connect one: there is no link yet.
Oficina, Connect bool
ConnectLabel string
+ // Equipo is the member's Equipo connection (connect, pending, ready or
+ // reconnect), empty with the chat off.
+ Equipo string
}
func (a *app) settings(w http.ResponseWriter, r *http.Request) {
@@ -51,6 +54,15 @@ func (a *app) settings(w http.ResponseWriter, r *http.Request) {
UserID: base64.RawURLEncoding.EncodeToString([]byte(me.ID)),
ModuleURL: webauthnModulePath, RegisterBegin: registerBeginPath, RegisterEnd: registerFinishPath,
}
+ if a.ask != nil {
+ _, _, state, err := a.askLink(r.Context(), me)
+ if err != nil {
+ a.logger.Error("settings: equipo link", "err", err)
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ return
+ }
+ page.Equipo = homeState(state)
+ }
if a.oficina != nil {
page.Oficina = true
page.Connect = !a.oficina.linked(r.Context(), me)
diff --git a/internal/web/templates/ask.html b/internal/web/templates/ask.html
new file mode 100644
index 0000000..a2ce106
--- /dev/null
+++ b/internal/web/templates/ask.html
@@ -0,0 +1,10 @@
+{{define "title"}}Ask Base · {{.Name}}{{end}}
+{{define "head"}}{{if .Ask.Turn}}<noscript><meta http-equiv="refresh" content="5"></noscript>{{end}}{{end}}
+{{define "main"}}<main class="inner">
+<section class="sheet glass ask-page" data-ask data-state="{{.Ask.State}}">
+<div class="crumb"><a class="wordmark" href="/">base</a><span>Ask Base</span></div>
+{{template "ask-head" .Ask}}
+{{template "ask-body" .Ask}}
+</section>
+<script type="module" src="{{asset "static/ask.js"}}"></script>
+</main>{{end}}
diff --git a/internal/web/templates/ask_connect.html b/internal/web/templates/ask_connect.html
new file mode 100644
index 0000000..bc32b9c
--- /dev/null
+++ b/internal/web/templates/ask_connect.html
@@ -0,0 +1,17 @@
+{{define "title"}}Connect Equipo · {{.Name}}{{end}}
+{{define "head"}}{{if eq .State "pending"}}<meta http-equiv="refresh" content="5">{{end}}{{end}}
+{{define "main"}}<main class="signin">
+<div class="card glass">
+<div class="wordmark">base</div>
+<h2>Connect Equipo</h2>
+{{if eq .State "pending"}}<p>In Equipo, check the request is from {{.Label}}, then type this code:</p>
+<p class="code" aria-label="Your code">{{.Code}}</p>
+<a class="btn full" href="{{.Verify}}" target="_blank" rel="noopener">Open Equipo</a>
+<p class="alt">This page checks every few seconds and moves on once you've approved it.</p>
+<a class="btn ghost full" href="/ask/connect?next={{.Next}}">Check again</a>
+{{else}}<p>{{if eq .State "expired"}}That code expired. Start again to get a new one.{{else if eq .State "refused"}}Equipo didn't accept that request. Start again.{{else if eq .State "reconnect"}}Base's connection to Equipo expired or was removed.{{else}}Connect Equipo, and its coordinator answers you in Base.{{end}}</p>
+<form method="post" action="/ask/connect"><input type="hidden" name="next" value="{{.Next}}"><button class="btn full" type="submit">{{if eq .State "connect"}}Connect Equipo{{else if eq .State "reconnect"}}Reconnect Equipo{{else}}Start again{{end}}</button></form>
+<a class="btn ghost full" href="{{.Back}}">Back</a>
+{{end}}{{with .Problem}}<p class="status" role="alert">{{.}}</p>{{end}}
+</div>
+</main>{{end}}
diff --git a/internal/web/templates/home.html b/internal/web/templates/home.html
index 363f882..76ffc9b 100644
--- a/internal/web/templates/home.html
+++ b/internal/web/templates/home.html
@@ -3,7 +3,7 @@
<div class="topbar glass">
<div class="wordmark">base</div>
<div class="team">{{.Name}}</div>
-<input class="ask" type="text" disabled placeholder="Ask Base anything" title="Asking Base arrives in a later slice" aria-label="Ask Base anything">
+{{if .Ask}}<a class="ask" href="/ask" data-ask-open aria-haspopup="dialog" aria-controls="ask-panel">Ask Base anything</a>{{else}}<input class="ask" type="text" disabled placeholder="Ask Base anything" title="Asking Base arrives in a later slice" aria-label="Ask Base anything">{{end}}
<a class="me" href="/settings" aria-label="Settings">{{.Initials}}</a>
</div>
<h2 class="hello">{{.Greeting}}</h2>
@@ -14,4 +14,6 @@
<div class="dock">
{{range .Tiles}}<a class="app" href="{{.Href}}"><div class="tile glass t-{{.Tint}}">{{.Icon}}</div>{{.Name}}</a>
{{end}}</div>
+{{with .Ask}}{{template "ask-panel" .}}
+<script type="module" src="{{asset "static/ask.js"}}"></script>{{end}}
</main>{{end}}
diff --git a/internal/web/templates/partials/chat.html b/internal/web/templates/partials/chat.html
new file mode 100644
index 0000000..b682d43
--- /dev/null
+++ b/internal/web/templates/partials/chat.html
@@ -0,0 +1,33 @@
+{{/* The chat behind "Ask Base anything": the panel over Home, and /ask. Every state's block is drawn and the one for .State shows; the panel's script moves between them. */}}
+{{define "ask-head"}}<div class="ask-head"><h2 id="ask-title">Ask Base</h2><a class="btn ghost" href="{{.Equipo}}" target="_blank" rel="noopener">Open Equipo</a></div>{{end}}
+{{define "ask-panel"}}<dialog id="ask-panel" class="ask-panel glass" aria-labelledby="ask-title" data-ask data-state="{{.State}}">
+<div class="ask-head"><h2 id="ask-title">Ask Base</h2><a class="btn ghost" href="{{.Equipo}}" target="_blank" rel="noopener">Open Equipo</a><button class="btn ghost close" type="button" data-ask-close aria-label="Close"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg></button></div>
+{{template "ask-body" .}}</dialog>{{end}}
+{{define "ask-body"}}<div class="ask-note" data-when="connect"{{if not (.Shows "connect")}} hidden{{end}}>
+<p>Connect Equipo, and its coordinator answers you here.</p>
+<form method="post" action="/ask/connect"><input type="hidden" name="next" value="{{.Next}}"><button class="btn" type="submit">Connect Equipo</button></form>
+</div>
+<div class="ask-note" data-when="pending"{{if not (.Shows "pending")}} hidden{{end}}>
+<p>You started connecting Equipo. Approve it there to start asking.</p>
+<a class="btn" href="/ask/connect?next={{.Next}}">Finish connecting</a>
+</div>
+<div class="ask-note" data-when="reconnect"{{if not (.Shows "reconnect")}} hidden{{end}}>
+<p>Base's connection to Equipo expired or was removed.</p>
+<form method="post" action="/ask/connect"><input type="hidden" name="next" value="{{.Next}}"><button class="btn" type="submit">Reconnect Equipo</button></form>
+</div>
+<div class="ask-note" data-when="unavailable"{{if not (.Shows "unavailable")}} hidden{{end}}>
+<p>Equipo isn't answering. Try again in a minute.</p>
+</div>
+<div class="ask-chat" data-when="ready"{{if not (.Shows "ready")}} hidden{{end}}>
+<ol class="thread" role="log" aria-label="Conversation">
+{{range .Messages}}<li class="msg {{.Role}}" data-id="{{.ID}}">{{.Text}}</li>
+{{end}}{{range .Cards}}<li class="msg card" data-card="{{.ID}}"><p>{{.Question}}</p><form class="choices" method="post" action="/ask/cards/{{.ID}}/answer"><input type="hidden" name="revision" value="{{.Revision}}">{{range .Options}}<button class="btn ghost" type="submit" name="choice" value="{{.}}">{{.}}</button>{{end}}</form></li>
+{{end}}</ol>
+<p class="ask-empty" data-empty{{if or .Messages .Cards}} hidden{{end}}>Ask about your work, or ask Base to get something done.</p>
+{{with .Problem}}<p class="ask-problem" role="alert">{{.}}</p>{{end}}
+<div class="ask-foot">
+<p class="ask-status" role="status">{{.Status}}</p>
+<form class="stop" method="post" action="{{with .Turn}}/ask/turns/{{.ID}}/cancel{{else}}/ask{{end}}"{{if not .Turn}} hidden{{end}}><button class="btn ghost" type="submit">Stop</button></form>
+</div>
+<form class="composer" method="post" action="/ask/messages"><input type="hidden" name="key" value="{{.Key}}"><label class="sr-only" for="ask-text">Message</label><textarea class="input" id="ask-text" name="text" rows="1" required maxlength="16000" placeholder="Ask Base anything"></textarea><button class="btn" type="submit">Send</button></form>
+</div>{{end}}
diff --git a/internal/web/templates/settings.html b/internal/web/templates/settings.html
index 140c1fb..2d96f9c 100644
--- a/internal/web/templates/settings.html
+++ b/internal/web/templates/settings.html
@@ -7,7 +7,8 @@
<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>{{if .CanAddPasskey}}{{/* 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>{{end}}</li>
-{{if .Connect}}<li><div class="who">Oficina account<small>Not connected</small></div><a class="btn ghost" href="/account/home">{{.ConnectLabel}}</a></li>
+{{with .Equipo}}<li><div class="who">Equipo<small>{{if eq . "ready"}}Connected{{else if eq . "pending"}}Waiting for your approval in Equipo{{else if eq . "reconnect"}}Connection expired or removed{{else}}Not connected{{end}}</small></div>{{if eq . "ready"}}<form method="post" action="/ask/disconnect"><button class="btn ghost" type="submit">Disconnect</button></form>{{else if eq . "pending"}}<a class="btn ghost" href="/ask/connect?next=settings">Finish connecting</a>{{else}}<form method="post" action="/ask/connect"><input type="hidden" name="next" value="settings"><button class="btn ghost" type="submit">{{if eq . "reconnect"}}Reconnect Equipo{{else}}Connect Equipo{{end}}</button></form>{{end}}</li>
+{{end}}{{if .Connect}}<li><div class="who">Oficina account<small>Not connected</small></div><a class="btn ghost" href="/account/home">{{.ConnectLabel}}</a></li>
{{end}}</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>
diff --git a/internal/webtest/ask_test.go b/internal/webtest/ask_test.go
new file mode 100644
index 0000000..a22c794
--- /dev/null
+++ b/internal/webtest/ask_test.go
@@ -0,0 +1,392 @@
+package webtest
+
+import (
+ "bufio"
+ "context"
+ "database/sql"
+ "encoding/json"
+ "html"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/carlos/base/internal/config"
+ "amadan.net/carlos/base/internal/equipo/equipotest"
+ "amadan.net/carlos/base/internal/store"
+ "amadan.net/carlos/base/internal/web"
+)
+
+func strconv64(n int64) string { return strconv.FormatInt(n, 10) }
+
+// newAskApp is Base with "Ask Base anything" on, answered by a fake Equipo,
+// and the owner signed in.
+func newAskApp(t *testing.T) (*testApp, *equipotest.Fake) {
+ t.Helper()
+ f := equipotest.New(t)
+ a := newAppConfigured(t, func(*sql.DB, config.Config) web.Installer { return noInstaller{} }, time.UTC,
+ func(c *config.Config) { c.EquipoOrigin = f.URL })
+ a.signedInOwner()
+ return a, f
+}
+
+var codeRE = regexp.MustCompile(`<p class="code"[^>]*>([A-Z0-9]{8})</p>`)
+
+// ownerID is the bootstrapped owner's member id.
+func (a *testApp) ownerID() string {
+ a.t.Helper()
+ m, ok, err := store.MemberByEmail(context.Background(), a.DB, ownerAddress)
+ if err != nil || !ok {
+ a.t.Fatalf("owner: %v %v", ok, err)
+ }
+ return m.ID
+}
+
+// pollable makes Base's last look at Equipo old enough to look again.
+func (a *testApp) pollable() {
+ a.t.Helper()
+ if _, err := a.DB.Exec(`UPDATE equipo_links SET polled_at = ?`, time.Now().Add(-10*time.Second).UTC()); err != nil {
+ a.t.Fatal(err)
+ }
+}
+
+// connectEquipo connects the owner from Settings the way a person does:
+// Connect Equipo, approve the code in Equipo, come back. It returns the
+// bearer Equipo issued.
+func (a *testApp) connectEquipo(f *equipotest.Fake) string {
+ a.t.Helper()
+ r := a.post("/ask/connect", url.Values{"next": {"settings"}})
+ if r.Code != 303 || r.Location() != "/ask/connect?next=settings" {
+ a.t.Fatalf("connect: %d %q\n%s", r.Code, r.Location(), r.Body)
+ }
+ page := a.get(r.Location())
+ m := codeRE.FindStringSubmatch(page.Body)
+ if page.Code != 200 || m == nil {
+ a.t.Fatalf("pending page: %d\n%s", page.Code, page.Body)
+ }
+ if err := f.Approve(m[1]); err != nil {
+ a.t.Fatal(err)
+ }
+ a.pollable()
+ if r := a.get("/ask/connect?next=settings"); r.Code != 303 || r.Location() != "/settings" {
+ a.t.Fatalf("after approval: %d %q\n%s", r.Code, r.Location(), r.Body)
+ }
+ tokens := f.Tokens()
+ if len(tokens) != 1 {
+ a.t.Fatalf("tokens: %v", tokens)
+ }
+ return tokens[0]
+}
+
+// noLeak fails if any response so far carried token: body, header or cookie.
+func (a *testApp) noLeak(token string) {
+ a.t.Helper()
+ for _, r := range a.seen {
+ if strings.Contains(r.Body, token) {
+ a.t.Fatalf("a response body carried the bearer:\n%s", r.Body)
+ }
+ for k, vs := range r.Header {
+ for _, v := range vs {
+ if strings.Contains(v, token) {
+ a.t.Fatalf("header %s carried the bearer", k)
+ }
+ }
+ }
+ }
+}
+
+func TestAskOffWithoutEquipo(t *testing.T) {
+ a := newApp(t)
+ a.signedInOwner()
+ home := a.get("/").Body
+ if !strings.Contains(home, `<input class="ask" type="text" disabled`) || strings.Contains(home, `href="/ask"`) ||
+ strings.Contains(home, "<dialog") {
+ t.Errorf("chat is not off:\n%s", home)
+ }
+ if r := a.get("/ask"); r.Code != 404 {
+ t.Errorf("/ask: %d", r.Code)
+ }
+ if strings.Contains(a.get("/settings").Body, "Equipo") {
+ t.Error("Settings offers Equipo with the chat off")
+ }
+}
+
+func TestAskFieldOpensChat(t *testing.T) {
+ a, _ := newAskApp(t)
+ home := a.get("/").Body
+ for _, want := range []string{`<a class="ask" href="/ask"`, `<dialog id="ask-panel"`, `action="/ask/connect"`} {
+ if !strings.Contains(home, want) {
+ t.Errorf("Home lacks %q:\n%s", want, home)
+ }
+ }
+ settings := a.get("/settings").Body
+ for _, want := range []string{"Equipo<small>Not connected</small>", `action="/ask/connect"`, ">Connect Equipo</button>"} {
+ if !strings.Contains(settings, want) {
+ t.Errorf("Settings lacks %q:\n%s", want, settings)
+ }
+ }
+}
+
+func TestConnectEquipo(t *testing.T) {
+ a, f := newAskApp(t)
+ r := a.post("/ask/connect", url.Values{"next": {"settings"}})
+ if r.Code != 303 {
+ t.Fatalf("connect: %d\n%s", r.Code, r.Body)
+ }
+ begin := f.Calls("/api/v1/auth/devices")
+ if len(begin) != 1 || !strings.Contains(begin[0].Body, `"label":"Base (Acme)"`) {
+ t.Fatalf("begin: %+v", begin)
+ }
+ page := a.get(r.Location())
+ m := codeRE.FindStringSubmatch(page.Body)
+ if m == nil || f.Label(m[1]) != "Base (Acme)" {
+ t.Fatalf("no user code:\n%s", page.Body)
+ }
+ for _, want := range []string{f.URL + "/auth/devices/", `http-equiv="refresh" content="5"`, `href="/ask/connect?next=settings"`} {
+ if !strings.Contains(html.UnescapeString(page.Body), want) {
+ t.Errorf("pending page lacks %q:\n%s", want, page.Body)
+ }
+ }
+ // It asked once; a refresh inside Equipo's five seconds does not ask.
+ if n := len(f.Calls("/api/v1/auth/devices/exchange")); n != 1 {
+ t.Fatalf("exchanges after first look: %d", n)
+ }
+ a.get(r.Location())
+ if n := len(f.Calls("/api/v1/auth/devices/exchange")); n != 1 {
+ t.Fatalf("polled within five seconds: %d exchanges", n)
+ }
+ if err := f.Approve(m[1]); err != nil {
+ t.Fatal(err)
+ }
+ a.pollable()
+ if r := a.get(r.Location()); r.Code != 303 || r.Location() != "/settings" {
+ t.Fatalf("after approval: %d %q", r.Code, r.Location())
+ }
+ token := f.Tokens()[0]
+ l, ok, err := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID())
+ if !ok || err != nil || l.State != store.EquipoConnected || l.Revision != 3 || l.ExpiresAt.Before(time.Now().Add(29*24*time.Hour)) {
+ t.Fatalf("link: %+v %v %v", l, ok, err)
+ }
+ if strings.Contains(string(l.Sealed), token) || strings.Contains(string(l.Sealed), "equipo.person") {
+ t.Fatal("the bearer is stored in the clear")
+ }
+ settings := a.get("/settings").Body
+ if !strings.Contains(settings, "Equipo<small>Connected</small>") || !strings.Contains(settings, `action="/ask/disconnect"`) {
+ t.Errorf("Settings after connecting:\n%s", settings)
+ }
+ a.noLeak(token)
+}
+
+func TestConnectCodeExpires(t *testing.T) {
+ a, f := newAskApp(t)
+ r := a.post("/ask/connect", url.Values{"next": {"ask"}})
+ f.Expire()
+ page := a.get(r.Location())
+ if page.Code != 200 || !strings.Contains(page.Body, "That code expired.") || !strings.Contains(page.Body, `action="/ask/connect"`) {
+ t.Fatalf("expired: %d\n%s", page.Code, page.Body)
+ }
+}
+
+func TestAskSendRelaysWithBearer(t *testing.T) {
+ a, f := newAskApp(t)
+ token := a.connectEquipo(f)
+ page := a.get("/ask")
+ key := formFields(t, page.Body, "/ask/messages").Get("key")
+ if page.Code != 200 || key == "" {
+ t.Fatalf("/ask: %d key=%q\n%s", page.Code, key, page.Body)
+ }
+ r := a.post("/ask/messages", url.Values{"text": {"What can I do"}, "key": {key}})
+ if r.Code != 303 || r.Location() != "/ask" {
+ t.Fatalf("send: %d %q", r.Code, r.Location())
+ }
+ calls := f.Calls("/api/v1/messages")
+ if len(calls) != 1 {
+ t.Fatalf("sends: %d", len(calls))
+ }
+ h := calls[0].Header
+ if h.Get("Authorization") != "Bearer "+token || h.Get("Idempotency-Key") != key || h.Get("Cookie") != "" || h.Get("Origin") != "" {
+ t.Errorf("relayed headers: %v", h)
+ }
+ if !strings.Contains(calls[0].Body, `"idempotency_key":"`+key+`"`) {
+ t.Errorf("relayed body: %s", calls[0].Body)
+ }
+ // The same key again (a double press) sends nothing new.
+ a.post("/ask/messages", url.Values{"text": {"What can I do"}, "key": {key}})
+ var body string
+ for i := 0; i < 100; i++ {
+ if body = a.get("/ask").Body; strings.Contains(body, "Hello. What shall we work on?") {
+ break
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ if strings.Count(body, "What can I do") != 1 || !strings.Contains(body, "Hello. What shall we work on?") {
+ t.Fatalf("conversation:\n%s", body)
+ }
+ // Scripts on: the same route answers JSON.
+ req, _ := http.NewRequest(http.MethodPost, a.base+"/ask/messages", strings.NewReader(url.Values{"text": {"Build me a quick website"}, "key": {"k-json"}}.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Origin", a.origin)
+ req.Header.Set("Accept", "application/json")
+ res := a.do(req)
+ var sent struct {
+ Message struct{ Text string }
+ Turn struct{ ID, State string }
+ }
+ if res.Code != 200 || json.Unmarshal([]byte(res.Body), &sent) != nil || sent.Message.Text != "Build me a quick website" || sent.Turn.ID == "" {
+ t.Fatalf("JSON send: %d %s", res.Code, res.Body)
+ }
+ a.noLeak(token)
+}
+
+func TestAskRefusesCrossSitePost(t *testing.T) {
+ a, f := newAskApp(t)
+ a.connectEquipo(f)
+ if r := a.postFrom("https://evil.example", "/ask/messages", url.Values{"text": {"hi"}}); r.Code != 403 {
+ t.Fatalf("cross-site send: %d", r.Code)
+ }
+ if n := len(f.Calls("/api/v1/messages")); n != 0 {
+ t.Fatalf("relayed a cross-site send")
+ }
+}
+
+func TestAskScriptsOffCardAndCancel(t *testing.T) {
+ a, f := newAskApp(t)
+ a.connectEquipo(f)
+ id := f.AskQuestion("Which branch should I start from?", "main", "develop")
+ page := a.get("/ask").Body
+ action := "/ask/cards/" + id + "/answer"
+ fields := formFields(t, page, action)
+ if !strings.Contains(page, "Which branch should I start from?") || !strings.Contains(page, `name="choice" value="develop"`) {
+ t.Fatalf("card:\n%s", page)
+ }
+ fields.Set("choice", "main")
+ if r := a.post(action, fields); r.Code != 303 || r.Location() != "/ask" {
+ t.Fatalf("answer: %d", r.Code)
+ }
+ ans := f.Calls("/api/v1/cards/" + id + "/answer")
+ if len(ans) != 1 || ans[0].Body != `{"choice":"main","revision":1}`+"\n" && ans[0].Body != `{"choice":"main","revision":1}` {
+ t.Fatalf("answer relayed: %+v", ans)
+ }
+
+ f.Hold = true
+ a.post("/ask/messages", url.Values{"text": {"Can we fix a bug in Tito?"}})
+ page = a.get("/ask").Body
+ m := regexp.MustCompile(`action="(/ask/turns/([^/"]+)/cancel)"`).FindStringSubmatch(page)
+ if m == nil || !strings.Contains(page, `<noscript><meta http-equiv="refresh" content="5"></noscript>`) {
+ t.Fatalf("no stop button or refresh for a running turn:\n%s", page)
+ }
+ if r := a.post(m[1], nil); r.Code != 303 {
+ t.Fatalf("cancel: %d", r.Code)
+ }
+ if f.Turn(m[2]) != "cancelled" {
+ t.Fatalf("turn %s is %q", m[2], f.Turn(m[2]))
+ }
+}
+
+func TestAskNeedsReconnectAfter401(t *testing.T) {
+ a, f := newAskApp(t)
+ a.connectEquipo(f)
+ f.RevokeAll()
+ page := a.get("/ask").Body
+ if !strings.Contains(page, ">Reconnect Equipo</button>") {
+ t.Fatalf("no reconnect:\n%s", page)
+ }
+ l, _, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID())
+ if l.State != store.EquipoLost {
+ t.Fatalf("state %q", l.State)
+ }
+ if s := a.get("/settings").Body; !strings.Contains(s, ">Reconnect Equipo</button>") {
+ t.Errorf("Settings:\n%s", s)
+ }
+ var st struct{ State string }
+ if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || st.State != "reconnect" {
+ t.Errorf("state: %s", r.Body)
+ }
+}
+
+func TestAskExpiredBearerNeedsReconnect(t *testing.T) {
+ a, f := newAskApp(t)
+ a.connectEquipo(f)
+ if _, err := a.DB.Exec(`UPDATE equipo_links SET expires_at = ?`, time.Now().Add(-time.Minute).UTC()); err != nil {
+ t.Fatal(err)
+ }
+ before := len(f.Calls(""))
+ if page := a.get("/ask").Body; !strings.Contains(page, ">Reconnect Equipo</button>") {
+ t.Fatalf("no reconnect:\n%s", page)
+ }
+ if len(f.Calls("")) != before {
+ t.Error("Base used an expired bearer")
+ }
+}
+
+func TestDisconnectRevokesDevice(t *testing.T) {
+ a, f := newAskApp(t)
+ token := a.connectEquipo(f)
+ l, _, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID())
+ if r := a.post("/ask/disconnect", nil); r.Code != 303 || r.Location() != "/settings" {
+ t.Fatalf("disconnect: %d %q", r.Code, r.Location())
+ }
+ calls := f.Calls("/api/v1/auth/devices/" + l.DeviceID)
+ if len(calls) != 1 || calls[0].Method != http.MethodDelete || calls[0].Header.Get("If-Match") != `"3"` ||
+ calls[0].Header.Get("Authorization") != "Bearer "+token || !f.Revoked(l.DeviceID) {
+ t.Fatalf("revoke: %+v", calls)
+ }
+ if _, ok, _ := store.EquipoLinkFor(context.Background(), a.DB, a.ownerID()); ok {
+ t.Fatal("link kept")
+ }
+ if s := a.get("/settings").Body; !strings.Contains(s, "Equipo<small>Not connected</small>") {
+ t.Errorf("Settings:\n%s", s)
+ }
+}
+
+// The panel's stream: Equipo's chat events relayed, nothing else of Equipo.
+func TestAskEventsRelay(t *testing.T) {
+ a, f := newAskApp(t)
+ token := a.connectEquipo(f)
+ var st struct {
+ State string
+ Cursor int64
+ }
+ if r := a.get("/ask/state"); json.Unmarshal([]byte(r.Body), &st) != nil || st.State != "ready" {
+ t.Fatalf("state: %s", r.Body)
+ }
+ f.Emit("runner", map[string]any{"id": "R1", "online": false})
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ req, _ := http.NewRequestWithContext(ctx, http.MethodGet, a.base+"/ask/events?after="+strconv64(st.Cursor), nil)
+ res, err := a.client.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ if res.StatusCode != 200 || !strings.HasPrefix(res.Header.Get("Content-Type"), "text/event-stream") {
+ t.Fatalf("events: %d %s", res.StatusCode, res.Header.Get("Content-Type"))
+ }
+ a.post("/ask/messages", url.Values{"text": {"What can I do"}})
+ types := map[string]int{}
+ sc := bufio.NewScanner(res.Body)
+ var stream strings.Builder
+ for sc.Scan() {
+ line := sc.Text()
+ stream.WriteString(line + "\n")
+ if typ, ok := strings.CutPrefix(line, "event: "); ok {
+ types[typ]++
+ }
+ if strings.HasPrefix(line, "data: ") && strings.Contains(line, `"state":"replied"`) {
+ break
+ }
+ }
+ if types["runner"] != 0 || types["delta"] == 0 || types["message"] < 2 || types["turn"] == 0 {
+ t.Fatalf("relayed %v:\n%s", types, stream.String())
+ }
+ if strings.Contains(stream.String(), token) {
+ t.Fatal("the stream carried the bearer")
+ }
+ up := f.Calls("/api/v1/events")
+ if len(up) == 0 || up[0].Header.Get("Authorization") != "Bearer "+token || up[0].Query != "after="+strconv64(st.Cursor) {
+ t.Fatalf("upstream: %+v", up)
+ }
+}
diff --git a/internal/webtest/harness_test.go b/internal/webtest/harness_test.go
index 9a6903e..ca8c075 100644
--- a/internal/webtest/harness_test.go
+++ b/internal/webtest/harness_test.go
@@ -89,6 +89,9 @@ type testApp struct {
// post presents; localSignin is the page with the email form.
base, origin, localSignin string
home *oficina // set by newHomeApp
+ // seen is every response so far, for checks that a secret never
+ // reached the browser.
+ seen []Resp
}
// newApp builds the whole app per test over its own copy of the migrated
@@ -104,6 +107,12 @@ func newAppWith(t *testing.T, inst web.Installer, tz *time.Location) *testApp {
// newAppBuilt is newAppWith for an Installer that needs the app's database
// and configuration.
func newAppBuilt(t *testing.T, build func(*sql.DB, config.Config) web.Installer, tz *time.Location) *testApp {
+ t.Helper()
+ return newAppConfigured(t, build, tz, nil)
+}
+
+// newAppConfigured is newAppBuilt with a last say over the configuration.
+func newAppConfigured(t *testing.T, build func(*sql.DB, config.Config) web.Installer, tz *time.Location, tweak func(*config.Config)) *testApp {
t.Helper()
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
d, err := db.Open(schema.Path(t), logger)
@@ -116,6 +125,9 @@ func newAppBuilt(t *testing.T, build func(*sql.DB, config.Config) web.Installer,
}
cfg := config.Config{Origin: testOrigin, Name: "Acme", Owner: ownerAddress, InstanceKey: "test-instance-key", AllowLoggedMail: true,
Slug: "acme", AppsDomain: "bab.oncarlos.com", Timezone: tz}
+ if tweak != nil {
+ tweak(&cfg)
+ }
mailer := &capturingMailer{}
h, err := web.App(d, cfg, mailer, build(d.Writer(), cfg), logger)
if err != nil {
@@ -136,7 +148,9 @@ func (a *testApp) do(req *http.Request) Resp {
}
defer res.Body.Close()
b, _ := io.ReadAll(res.Body)
- return Resp{res.StatusCode, res.Header, string(b)}
+ out := Resp{res.StatusCode, res.Header, string(b)}
+ a.seen = append(a.seen, out)
+ return out
}
func (a *testApp) get(target string) Resp {