package web import ( "context" "encoding/json" "errors" "net/http" "strconv" "strings" "sync" "time" "github.com/go-chi/chi/v5" "amadan.net/oficina/base/internal/equipo" "amadan.net/oficina/base/internal/store" ) // asker is "Ask Base anything": the chat with Equipo's Assistant, 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 // hosts holds a *memberConn per member id: their lock, held while // their connection changes or their host is registered (lockMember), // and their connection's generation (changeLink). hosts sync.Map // oficina holds a *sync.Mutex per member id, held while Ask is set up // with Oficina ID for them (askOficinaLock). oficina sync.Map // zone is the team's IANA time zone (BASE_TIMEZONE), which Equipo // writes the Assistant's times in unless the person has one of their // own; zones holds, per member id, where telling Equipo has got to // (zoneFor). zone string zoneMu sync.Mutex zones map[string]*zoneTold // uploads is the upload relay's slots (ask_files.go). uploads *uploads } // 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/attachments", a.askUpload) r.Post("/ask/attachments/discard", a.askDiscard) r.Delete("/ask/attachments/{id}", a.askDeleteAttachment) r.Get("/ask/attachments/{id}", a.askAttachment(false)) r.Head("/ask/attachments/{id}", a.askAttachment(false)) r.Get("/ask/attachments/{id}/preview", a.askAttachment(true)) r.Head("/ask/attachments/{id}/preview", a.askAttachment(true)) r.Post("/ask/turns/{id}/cancel", a.askCancel) r.Post("/ask/cards/{id}/answer", a.askAnswer) r.Post("/ask/cards/{id}/carry_on", a.askCarryOn) r.Post("/ask/connect", a.askConnectStart) r.Get("/ask/connect", a.askConnectPage) r.Post("/ask/connect/check", a.askConnectCheck) r.Post("/ask/disconnect", a.askDisconnect) r.Post("/ask/dock", a.askDock) r.Get("/ask/oficina/connect", a.askOficinaConnect) r.Get("/ask/oficina/done", a.askOficinaDone) r.Post(askOficinaPath, a.askOficina) } // askDock is POST /ask/dock: on a wide screen the X closes Ask Base, docked // beside Home (open=0), and the Base button or the field opens it again // (open=1), kept for the member on every device. Plain forms, so they work // without scripts; the script posts them by fetch and gets a 204. func (a *app) askDock(w http.ResponseWriter, r *http.Request) { me, _ := CurrentMember(r) var closed bool switch r.PostFormValue("open") { case "1": case "0": closed = true default: http.Error(w, "bad request", http.StatusBadRequest) return } if err := store.SetAskClosed(r.Context(), a.db, me.ID, closed); err != nil { a.logger.Error("ask: dock", "err", err) http.Error(w, "unavailable", http.StatusServiceUnavailable) return } if wantsJSON(r) { w.WriteHeader(http.StatusNoContent) return } http.Redirect(w, r, "/", http.StatusSeeOther) } // newAsker is the chat with the Equipo at origin, for the team at zone // (BASE_TIMEZONE), which Base tells Equipo for each member (zoneFor). func newAsker(origin, instanceKey, name string, zone *time.Location) *asker { a := &asker{client: equipo.New(origin), seal: equipo.NewSealer(instanceKey), label: "Base (" + name + ")", zones: map[string]*zoneTold{}, uploads: newUploads(uploadBounds)} a.client.FileTimeout = uploadBounds.Upstream if zone != nil { a.zone = zone.String() } return a } // 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; failed: Base could not keep the bearer it got; ready: a live bearer; reconnect: Equipo // refused the bearer or it expired; unavailable: Equipo did not answer. // Norunner and oldrunner are ready, but the person has no runner that can // answer the Assistant (none, or one too old): the conversation shows, // with a note saying so. const ( askConnect = "connect" askPending = "pending" askExpired = "expired" askRefused = "refused" askFailed = "failed" askReady = "ready" askReconnect = "reconnect" askUnavailable = "unavailable" askNoRunner = "norunner" askRunnerTooOld = "oldrunner" ) // chatting reports whether state shows the conversation. func chatting(state string) bool { return state == askReady || state == askNoRunner || state == askRunnerTooOld } // 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. A key set up with Oficina ID (Via // "oficina") has no secret, challenge or nonce; it keeps instead the // cookie of the Equipo session it ends with, which Base never sends // anywhere again and never signs out (signing out would end the key). type deviceSecrets struct { Seed []byte `json:"seed"` Secret string `json:"secret"` Challenge string `json:"challenge"` Nonce string `json:"nonce"` Token string `json:"token,omitempty"` Via string `json:"via,omitempty"` SessionName string `json:"session_name,omitempty"` SessionValue string `json:"session_value,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 bearer of the member's device // dev, and forgets the member's host token (Equipo no longer speaks for // them), unless the link has moved on to another device since. func (a *app) askLost(ctx context.Context, me store.Member, dev string) { defer a.lockMember(me.ID)() if err := store.LoseEquipoLink(context.WithoutCancel(ctx), a.db, me.ID, dev); 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 // Zone is Base's time zone, the IANA name, for the day a job started // on (startedText) when the script draws it. Zone string Messages []equipo.Message // Jobs are the job cards, each with the cards that belong to it; // Cards every other card shown. Jobs []jobView Cards []equipo.Card Turn *equipo.Turn Status string Key string Problem string // Text is what the person wrote and Equipo did not take, kept in the // field. Text string // Unread is a conversation Home did not read (its chat was closed, or // Equipo was slow to answer): drawn without saying it is empty, for // the panel's script to read. Unread bool // Notice is a line the chat says once (how connecting Oficina ended), // in the conversation after its newest line (NoticeAfter). Notice string // CanAttach says the person's runner can take files: the paperclip // shows (with scripts) only then. CanAttach bool // base is Base's own origin: the only place a connect-Oficina link may // go and keep its rel. base string // offerAt is the newest reply of the Assistant's, which ends with the // open connect cards' buttons (OffersAt); "" when there is none. offerAt string } // NoticeAfter is the id of the line the notice follows: the newest // message, "" when there is none. func (v askView) NoticeAfter() string { if len(v.Messages) == 0 { return "" } return v.Messages[len(v.Messages)-1].ID } // connectOffer is an open connect card as the chat draws it: a button, // going to Base's own connect page, at the end of the Assistant's newest // reply. The snapshot does not say which turn raised a card, so a fresh // read puts it after the newest reply; the panel's script does the same, // and holds one that comes while its turn's reply streams until it lands // (ask.js, offer). type connectOffer struct { ID string Revision int64 URL string } // offerOf is card c as a button: an open connect card with a link to // Base's own connect page (the rel CleanAt keeps for that alone). func offerOf(c equipo.Card) (connectOffer, bool) { if c.Kind != equipo.CardConnect || !c.Open() { return connectOffer{}, false } for _, l := range c.Links { if l.Rel == equipo.LinkOficinaConnect { return connectOffer{ID: c.ID, Revision: c.Revision, URL: l.URL}, true } } return connectOffer{}, false } func (v askView) offers() []connectOffer { var out []connectOffer for _, c := range v.Cards { if o, ok := offerOf(c); ok { out = append(out, o) } } return out } // OffersAt are the buttons that end message id: the open connect cards', // when id is the Assistant's newest reply. func (v askView) OffersAt(id string) []connectOffer { if id == "" || id != v.offerAt { return nil } return v.offers() } // LooseOffers are the buttons drawn on their own, at the end of the // conversation: with no reply of the Assistant's to end, all of them. func (v askView) LooseOffers() []connectOffer { if v.offerAt != "" { return nil } return v.offers() } // LooseCards are the cards drawn as cards of their own: every card but // the connect cards drawn as buttons. func (v askView) LooseCards() []equipo.Card { var out []equipo.Card for _, c := range v.Cards { if _, ok := offerOf(c); !ok { out = append(out, c) } } return out } // jobView is a job card as the chat draws it, a pill, with the cards that // belong to it (Card.Job): under the pill while they wait on the person, // in its view once they have ended. Cards carries them all, for the // panel's script to place. type jobView struct { equipo.Card Cards []equipo.Card `json:"cards"` } // OpenCards are the job's cards that wait on the person, drawn under its // pill. func (j jobView) OpenCards() []equipo.Card { var out []equipo.Card for _, c := range j.Cards { if c.Open() { out = append(out, c) } } return out } // EndedCards are the job's cards that have ended (answered, resolved), // listed in its view: each its question and how it ended. func (j jobView) EndedCards() []equipo.Card { var out []equipo.Card for _, c := range j.Cards { if !c.Open() { out = append(out, c) } } return out } // Go is where to see the job's work, for templates: its link beside the // pill, or nil. func (j jobView) Go() *equipo.Link { if l, ok := j.Card.Go(); ok { return &l } return nil } // Equipo is the job's own page in Equipo, for templates: the job view's // title links there (plan decision D3), or nil. func (j jobView) Equipo() *equipo.Link { if l, ok := j.Card.Equipo(); ok { return &l } return nil } // startedText says when a job started (plan decision D19): how long ago // in minutes or hours, then from a day on, the day in Base's time zone // loc (nil: at as given). A start a little in the future, a clock behind // Equipo's, is just now. ask.js has the twin (startedText), and moves it // on every minute. func startedText(at, now time.Time, loc *time.Location) string { switch d := now.Sub(at); { case d < time.Minute: return "Started just now" case d < 2*time.Minute: return "Started 1 minute ago" case d < time.Hour: return "Started " + strconv.Itoa(int(d/time.Minute)) + " minutes ago" case d < 2*time.Hour: return "Started 1 hour ago" case d < 24*time.Hour: return "Started " + strconv.Itoa(int(d/time.Hour)) + " hours ago" } if loc != nil { at = at.In(loc) } return "Started on " + at.Format("2 January") } // 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 || state == askFailed { return askConnect } return state } func (a *app) newAskView(state, next string) askView { v := askView{base: a.cfg.Origin, State: state, Next: next, Equipo: a.ask.client.Origin() + "/", Key: equipo.NewKey()} if a.cfg.Timezone != nil { v.Zone = a.cfg.Timezone.String() } return v } // turnStatus is the line under the conversation while a turn runs. A // team_update turn is quiet (plan decision D9): it has none. func turnStatus(t *equipo.Turn) string { switch { case t == nil || t.Kind == equipo.TurnTeamUpdate: return "" case t.State == equipo.TurnWaiting: return "Ask Base can't answer right now. It will as soon as it can." } return "Thinking…" } // failedFiles are the words for a turn that failed for its files, by // Equipo's reason (copy review 13, pending); ask.js has the same // (failedFiles). Any other failure keeps "That didn't get an answer. Try // again.", which only the panel's script says, as it happens. var failedFiles = map[string]string{ "attachment_unavailable": "A file didn’t arrive whole. Attach it again.", "runner_storage_full": "There’s no room left for these files. Try fewer or smaller ones.", "runner_too_old": "Files can’t be read right now. Send it again without them.", } // fill puts a snapshot in the view: the messages, the jobs in the // snapshot's order with the cards that belong to each under it, every // other card to show, and the newest turn that has not ended, of those the // person sees running (never a quiet team_update turn, plan decision D9). func (v *askView) fill(s equipo.Snapshot) { v.Messages = make([]equipo.Message, len(s.Messages)) for i, m := range s.Messages { v.Messages[i] = m.Clean() } v.CanAttach = s.CanAttach var shown []equipo.Card jobs := map[string]int{} for _, c := range s.Cards { p, ok := c.CleanAt(v.base) switch { case !ok || !p.Shown(): case p.Kind == equipo.CardConnect && !p.Open(): // Connected: a fresh read no longer offers it (the chat says // so once, oficinaNotes). case p.Kind == equipo.CardJob: if _, dup := jobs[p.ID]; !dup { jobs[p.ID] = len(v.Jobs) v.Jobs = append(v.Jobs, jobView{Card: p, Cards: []equipo.Card{}}) } default: shown = append(shown, p) } } for _, c := range shown { if i, ok := jobs[c.Job]; ok && c.Job != "" { v.Jobs[i].Cards = append(v.Jobs[i].Cards, c) } else { v.Cards = append(v.Cards, c) } } for i := len(s.Messages) - 1; i >= 0; i-- { if s.Messages[i].Role != "person" { v.offerAt = s.Messages[i].ID break } } for i := len(s.Turns) - 1; i >= 0; i-- { if equipo.InFlight(s.Turns[i].State) && s.Turns[i].Kind != equipo.TurnTeamUpdate { t := s.Turns[i] v.Turn = &t break } } v.Status = turnStatus(v.Turn) // With nothing running, the turn of the person's newest message, if it // failed for its files, unanswered, says so (the page without scripts, and the panel // as it reads the conversation afresh). if v.Turn == nil && len(s.Messages) > 0 && s.Messages[len(s.Messages)-1].Role == "person" { for _, t := range s.Turns { if t.ID == s.Messages[len(s.Messages)-1].TurnID && t.State == equipo.TurnFailed { v.Status = failedFiles[t.Reason] } } } } // askSnapshot reads the member's conversation into v, moving v.State to // reconnect or unavailable when Equipo refuses or does not answer, and to // norunner when the person has no runner that can answer. Once Equipo // has answered, it records who the bearer speaks for, and registers the // member's host if Equipo does not hold it yet. func (a *app) askSnapshot(r *http.Request, me store.Member, l store.EquipoLink, token string, v *askView) int64 { return a.askSnapshotWithin(r, me, l, token, v, 0) } // askSnapshotWithin is askSnapshot giving Equipo at most wait to answer // (0: the client's own limit). Past it, v stays as it was, marked Unread. func (a *app) askSnapshotWithin(r *http.Request, me store.Member, l store.EquipoLink, token string, v *askView, wait time.Duration) int64 { ctx := r.Context() if wait > 0 { var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, wait) defer cancel() } s, err := a.ask.client.Snapshot(ctx, token) switch { case err != nil && wait > 0 && errors.Is(ctx.Err(), context.DeadlineExceeded) && r.Context().Err() == nil: a.logger.Warn("ask: snapshot slow", "wait", wait) v.Unread = true return 0 case errors.Is(err, equipo.ErrUnauthenticated): a.askLost(r.Context(), me, l.DeviceID) v.State = askReconnect return 0 case err != nil: a.logger.Warn("ask: snapshot", "err", err) v.State = askUnavailable return 0 } v.fill(s) if !s.Available { v.State = askNoRunner } if s.Me.Address != "" && s.Me.Address != l.Person { if err := store.SetEquipoPerson(r.Context(), a.db, me.ID, l.DeviceID, s.Me.Address); err != nil { a.logger.Error("ask: equipo person", "err", err) } } a.hostFor(r.Context(), me, l.DeviceID, token, false) 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) l, 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, l, sec.Token, &v) } if r.URL.Query().Get("problem") != "" && v.State == askReady { v.Problem = "That didn't send. Try again." } w.Header().Set("Cache-Control", "no-store") a.render(w, r, "ask", askPage{Name: a.cfg.Name, Ask: v}) } // askRunnerPage answers a form Equipo refused for want of a runner (state // norunner or oldrunner): /ask as it is now, with that note, and the // person's text and its key kept in the field, so sending it again is // the same message. func (a *app) askRunnerPage(w http.ResponseWriter, r *http.Request, c askConn, state string) { l, _, _, err := a.askLink(r.Context(), c.me) if err != nil { a.logger.Error("ask: link", "err", err) http.Error(w, "unavailable", http.StatusServiceUnavailable) return } v := a.newAskView(askReady, "ask") a.askSnapshot(r, c.me, l, c.token, &v) if chatting(v.State) { v.State = state } v.Text, v.Key = r.PostFormValue("text"), askKey(r.PostFormValue("key")) w.Header().Set("Cache-Control", "no-store") if err := a.pages.PageTheme(w, http.StatusConflict, "ask", askPage{Name: a.cfg.Name, Ask: v}, themeOf(r)); err != nil { a.logger.Error("render", "page", "ask", "err", err) } } // 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) l, 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, l, sec.Token, &v) } // RenewAfter is when the native app should set Ask up again with a // fresh Oficina ID assertion: "" for a key from the code flow. for i, m := range v.Messages { v.Messages[i] = asDrawn(r, m) } renew := "" if at := renewAfter(l, sec); !at.IsZero() && state != askConnect { renew = at.Format(time.RFC3339) } out := struct { State string `json:"state"` Messages []equipo.Message `json:"messages"` Jobs []jobView `json:"jobs"` Cards []equipo.Card `json:"cards"` Turn *equipo.Turn `json:"turn"` Status string `json:"status"` Cursor int64 `json:"cursor"` RenewAfter string `json:"renew_after"` EquipoOrigin string `json:"equipo_origin"` // Disconnected: the member disconnected Ask, so no app sets it up // again by itself. Disconnected bool `json:"disconnected"` // CanAttach: the person's runner can take files, so the paperclip // may show. CanAttach bool `json:"can_attach"` }{v.State, append([]equipo.Message{}, v.Messages...), append([]jobView{}, v.Jobs...), append([]equipo.Card{}, v.Cards...), v.Turn, v.Status, cursor, renew, a.ask.client.Origin(), me.AskDisconnected, v.CanAttach && v.State == askReady} 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) }