Connect Oficina from the chat without leaving Base
A card link with rel oficina_connect opens Base's own /ask/oficina/connect in the same tab. Base asks Equipo for the consent address (https or the Equipo origin only, else it says it could not reach Oficina), sends the browser there, and finishes at /ask/oficina/done with the member's bearer. The outcome reaches Home's chat once, through a short-lived cookie. State and code are never logged; both routes answer no-store and no-referrer. Copy rows are pending in docs/copy-pending.md (Review 11).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+529
−4
docs/copy-pending.md+9 −0internal/equipo/chat.go+38 −1internal/equipo/equipotest/chat.go+71 −0internal/look/static/app.css+2 −2internal/look/static/ask.js+14 −0internal/web/ask.go+4 −0internal/web/ask_oficina.go+158 −0internal/web/home.go+1 −0internal/web/templates/partials/chat.html+2 −1internal/webtest/oficina_connect_test.go+230 −0
diff --git a/docs/copy-pending.md b/docs/copy-pending.md| index f149bc5..b543e44 100644 |
| --- a/docs/copy-pending.md |
| +++ b/docs/copy-pending.md |
| @@ -400,3 +400,12 @@ Review 10 (pending): Paul's live check of Settings. Settings is grouped into sec |
| | internal/web/templates/settings.html | APPROVED (Paul, 2026-11-14): Settings, the heading over the Ask Base row (shown only with the chat on; the row keeps its approved name, Ask Base) | Ask Base | |
| | internal/web/templates/settings.html | APPROVED (Paul, 2026-11-14): CHANGED, the row under the Ask Base heading, renamed so it doesn't repeat the heading | ~~Ask Base~~ → Connection | |
| | internal/web/templates/partials/crumb.html | APPROVED: the X at the top right of Settings, Store, People, Uninstall and /ask, a link Home; its accessible name reuses the chat's approved close | Close | |
| + |
| +Review 11 (pending): connecting Oficina from the chat. The person follows the Connect link on a card (its words come from the Assistant), signs in with Oficina, and lands back on Home with one line in the chat. The line is said once. Base never names Equipo in it. |
| + |
| +| File | Context | Text | |
| +|---|---|---| |
| +| ask_oficina.go, partials/chat.html | PENDING: the chat's line after Oficina was connected | Oficina connected. | |
| +| ask_oficina.go, partials/chat.html | PENDING: the line after the person refused, or stopped before finishing | Oficina wasn't connected. | |
| +| ask_oficina.go, partials/chat.html | PENDING: the line after the connect link had expired | That link expired. Try again. | |
| +| ask_oficina.go, partials/chat.html | PENDING: the line when Oficina, or the way to it, could not be reached | Couldn't reach Oficina. Try again later. | |
diff --git a/internal/equipo/chat.go b/internal/equipo/chat.go| index 8e4331a..9e85387 100644 |
| --- a/internal/equipo/chat.go |
| +++ b/internal/equipo/chat.go |
| @@ -103,6 +103,14 @@ const ( |
| // LinkEquipo is the rel of a job card's link to the job's page in Equipo. |
| const LinkEquipo = "equipo" |
| +// LinkOficinaConnect is the rel of a card's link that starts connecting the |
| +// person's Oficina account. It goes to Base itself (OficinaConnectPath), so |
| +// it opens in the same tab. |
| +const LinkOficinaConnect = "oficina_connect" |
| + |
| +// OficinaConnectPath is the path on Base a LinkOficinaConnect link has. |
| +const OficinaConnectPath = "/ask/oficina/connect" |
| + |
| // Clean is the card as Base passes it on: its own fields only, never-null |
| // options and links, and a link only if it is an http(s) URL (WebURL), |
| // with a rel only if it is LinkEquipo. A job card has no options, and is |
| @@ -136,7 +144,7 @@ func (c Card) Clean() (Card, bool) { |
| for _, l := range c.Links { |
| if u := WebURL(l.URL); u != "" { |
| link := Link{Label: l.Label, URL: u} |
| - if l.Rel == LinkEquipo { |
| + if l.Rel == LinkEquipo || l.Rel == LinkOficinaConnect && isConnectPath(u) { |
| link.Rel = l.Rel |
| } |
| out.Links = append(out.Links, link) |
| @@ -145,6 +153,13 @@ func (c Card) Clean() (Card, bool) { |
| return out, true |
| } |
| +// isConnectPath reports whether raw, a URL WebURL accepted, has the path |
| +// of Base's connect route and no more than that. |
| +func isConnectPath(raw string) bool { |
| + u, err := url.Parse(raw) |
| + return err == nil && u.Path == OficinaConnectPath && u.RawQuery == "" && u.Fragment == "" |
| +} |
| + |
| // validJob reports whether id is 1 to 128 of [A-Za-z0-9_-]. |
| func validJob(id string) bool { |
| if id == "" || len(id) > 128 { |
| @@ -320,3 +335,25 @@ func (b cancelOnClose) Close() error { |
| b.cancel() |
| return b.ReadCloser.Close() |
| } |
| + |
| +// OficinaConnect asks Equipo where the person consents to connecting their |
| +// Oficina account; they come back to returnTo. |
| +func (c *Client) OficinaConnect(ctx context.Context, token, returnTo string) (string, error) { |
| + var out struct { |
| + URL string `json:"url"` |
| + } |
| + in := map[string]string{"return_to": returnTo} |
| + _, err := c.call(ctx, http.MethodPost, assistant+"/oficina/connect", token, NewKey(), nil, in, &out) |
| + return out.URL, err |
| +} |
| + |
| +// OficinaFinish hands Equipo what the person came back with. The status is |
| +// connected, denied, expired or unavailable. |
| +func (c *Client) OficinaFinish(ctx context.Context, token, state, code string) (string, error) { |
| + var out struct { |
| + Status string `json:"status"` |
| + } |
| + in := map[string]string{"state": state, "code": code} |
| + _, err := c.call(ctx, http.MethodPost, assistant+"/oficina/connect/finish", token, NewKey(), nil, in, &out) |
| + return out.Status, err |
| +} |
diff --git a/internal/equipo/equipotest/chat.go b/internal/equipo/equipotest/chat.go| index 131cddc..2a9fbbd 100644 |
| --- a/internal/equipo/equipotest/chat.go |
| +++ b/internal/equipo/equipotest/chat.go |
| @@ -91,6 +91,12 @@ type chat struct { |
| // hostStatus and hostCode, when set, are what every PUT host gets. |
| hostStatus int |
| hostCode string |
| + // consent is the URL connect gives; finish is the status finish gives |
| + // (default connected); oficinaStatus and oficinaCode, when set, are what |
| + // both answer instead. |
| + consent, finish string |
| + oficinaStatus int |
| + oficinaCode string |
| } |
| func (c *chat) init() { |
| @@ -341,6 +347,10 @@ func (f *Fake) serveChat(w http.ResponseWriter, r *http.Request) { |
| f.cancel(w, r, strings.TrimSuffix(strings.TrimPrefix(p, "/turns/"), "/cancel")) |
| case r.Method == http.MethodPost && strings.HasPrefix(p, "/cards/") && strings.HasSuffix(p, "/answer"): |
| f.answer(w, r, strings.TrimSuffix(strings.TrimPrefix(p, "/cards/"), "/answer")) |
| + case r.Method == http.MethodPost && p == "/oficina/connect": |
| + f.oficinaConnect(w, r) |
| + case r.Method == http.MethodPost && p == "/oficina/connect/finish": |
| + f.oficinaFinish(w, r) |
| case r.Method == http.MethodGet && p == "/events": |
| f.stream(w, r) |
| default: |
| @@ -689,3 +699,64 @@ func (f *Fake) stream(w http.ResponseWriter, r *http.Request) { |
| } |
| } |
| } |
| + |
| +// OficinaConsent sets the consent URL connect answers with; FinishWith the |
| +// status finish answers with. FailOficina makes both answer status with code |
| +// (0 stops). |
| +func (f *Fake) OficinaConsent(url string) { f.cmu.Lock(); f.consent = url; f.cmu.Unlock() } |
| +func (f *Fake) FinishWith(status string) { f.cmu.Lock(); f.finish = status; f.cmu.Unlock() } |
| +func (f *Fake) FailOficina(status int, code string) { |
| + f.cmu.Lock() |
| + f.oficinaStatus, f.oficinaCode = status, code |
| + f.cmu.Unlock() |
| +} |
| + |
| +// OtherPersonsState is a state finish refuses with 403, as Equipo does for |
| +// a state that belongs to someone else. |
| +const OtherPersonsState = "someone-else" |
| + |
| +func (f *Fake) oficinaConnect(w http.ResponseWriter, r *http.Request) { |
| + var in struct { |
| + ReturnTo string `json:"return_to"` |
| + } |
| + f.cmu.Lock() |
| + status, code, consent := f.oficinaStatus, f.oficinaCode, f.consent |
| + f.cmu.Unlock() |
| + if strict(r, &in) != nil || in.ReturnTo == "" { |
| + writeError(w, r, 422, "invalid_input") |
| + return |
| + } |
| + if status != 0 { |
| + writeError(w, r, status, code) |
| + return |
| + } |
| + if consent == "" { |
| + consent = "https://oficina.example/consent?x=1" |
| + } |
| + writeJSON(w, 200, map[string]string{"url": consent}) |
| +} |
| + |
| +func (f *Fake) oficinaFinish(w http.ResponseWriter, r *http.Request) { |
| + var in struct { |
| + State string `json:"state"` |
| + Code string `json:"code"` |
| + } |
| + f.cmu.Lock() |
| + status, code, finish := f.oficinaStatus, f.oficinaCode, f.finish |
| + f.cmu.Unlock() |
| + if strict(r, &in) != nil || in.State == "" || in.Code == "" { |
| + writeError(w, r, 422, "invalid_input") |
| + return |
| + } |
| + switch { |
| + case in.State == OtherPersonsState: |
| + writeError(w, r, 403, "forbidden") |
| + case status != 0: |
| + writeError(w, r, status, code) |
| + default: |
| + if finish == "" { |
| + finish = "connected" |
| + } |
| + writeJSON(w, 200, map[string]string{"status": finish}) |
| + } |
| +} |
diff --git a/internal/look/static/app.css b/internal/look/static/app.css| index 667c21d..d231bfa 100644 |
| --- a/internal/look/static/app.css |
| +++ b/internal/look/static/app.css |
| @@ -663,7 +663,7 @@ aside.ask-panel { position: absolute; top: 16px; right: 16px; bottom: 16px; widt |
| .job-cards > .msg.card { position: relative; margin-left: 22px; max-width: 340px; } |
| .job-cards > .msg.card::before { content: ""; position: absolute; left: -10px; top: -6px; bottom: 50%; width: 8px; |
| border-left: 2px solid var(--pill-edge); border-bottom: 2px solid var(--pill-edge); border-bottom-left-radius: 10px; } |
| -.ask-empty, .ask-problem { margin: 0; padding: 0 20px 12px; color: var(--haze); font-size: 14px; } |
| +.ask-empty, .ask-problem, .ask-notice { 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; } |
| @@ -811,7 +811,7 @@ main { min-height: 100dvh; } |
| aside.ask-panel .ask-head h2 { font-size: 18px; } |
| aside.ask-panel .composer { padding: 8px 8px calc(8px + env(safe-area-inset-bottom)); } |
| aside.ask-panel .ask-foot { padding: 0 8px; } |
| - aside.ask-panel .ask-empty, aside.ask-panel .ask-problem { padding: 0 12px 12px; } |
| + aside.ask-panel .ask-empty, aside.ask-panel .ask-problem, aside.ask-panel .ask-notice { padding: 0 12px 12px; } |
| aside.ask-panel .thread { padding: 14px 12px; } |
| aside.ask-panel .msg { max-width: 92%; } |
| } |
diff --git a/internal/look/static/ask.js b/internal/look/static/ask.js| index ec12c3b..15457e5 100644 |
| --- a/internal/look/static/ask.js |
| +++ b/internal/look/static/ask.js |
| @@ -172,6 +172,15 @@ function start(root) { |
| return ""; |
| } |
| } |
| + // sameTab is whether href is Base's own connect-Oficina page. |
| + function sameTab(href) { |
| + try { |
| + const u = new URL(href); |
| + return u.origin === location.origin && u.pathname === "/ask/oficina/connect" && !u.search && !u.hash; |
| + } catch { |
| + return false; |
| + } |
| + } |
| function link(href, text) { |
| const a = document.createElement("a"); |
| a.href = href; |
| @@ -318,6 +327,11 @@ function start(root) { |
| const p = document.createElement("p"); |
| const a = link(safe, l.label || safe); |
| a.className = "card-link"; |
| + // Connecting Oficina is a page of Base's own: same tab. |
| + if (l.rel === "oficina_connect" && sameTab(safe)) { |
| + a.removeAttribute("target"); |
| + a.removeAttribute("rel"); |
| + } |
| p.append(a); |
| li.append(p); |
| } |
diff --git a/internal/web/ask.go b/internal/web/ask.go| index a13e667..cba514b 100644 |
| --- a/internal/web/ask.go |
| +++ b/internal/web/ask.go |
| @@ -42,6 +42,8 @@ func (a *app) askRoutes(r chi.Router) { |
| 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) |
| } |
| // askDock is POST /ask/dock: on a wide screen the X closes Ask Base, docked |
| @@ -184,6 +186,8 @@ type askView struct { |
| // 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). |
| + Notice string |
| } |
| // jobView is a job card as the chat draws it, a pill, with the cards that |
diff --git a/internal/web/ask_oficina.go b/internal/web/ask_oficina.go| new file mode 100644 |
| index 0000000..4ac35ec |
| --- /dev/null |
| +++ b/internal/web/ask_oficina.go |
| @@ -0,0 +1,158 @@ |
| +package web |
| + |
| +import ( |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + |
| + "amadan.net/carlos/base/internal/equipo" |
| + "amadan.net/carlos/base/internal/store" |
| +) |
| + |
| +// Connecting the person's Oficina account from the chat: a card link sends |
| +// them to /ask/oficina/connect, Base asks Equipo where to consent and sends |
| +// the browser there, and the browser returns to /ask/oficina/done, where |
| +// Base finishes it with the member's own bearer. The person never visits |
| +// Equipo. Neither route logs, stores or echoes the state or code. |
| + |
| +const oficinaDonePath = "/ask/oficina/done" |
| + |
| +// oficinaNote is the cookie that carries the outcome from /done to the next |
| +// Home, once. |
| +const oficinaNote = "oficina_note" |
| + |
| +// oficinaNotes are the outcomes the chat says, by the word they travel as. |
| +var oficinaNotes = map[string]string{ |
| + "connected": "Oficina connected.", |
| + "denied": "Oficina wasn't connected.", |
| + "expired": "That link expired. Try again.", |
| + "unavailable": "Couldn't reach Oficina. Try again later.", |
| +} |
| + |
| +// quiet marks a response as one no cache keeps and no Referer follows: its |
| +// URL may carry a code. |
| +func quiet(w http.ResponseWriter) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Referrer-Policy", "no-referrer") |
| +} |
| + |
| +// oficinaLink reports whether raw is somewhere Base may send the browser to |
| +// consent: an https address, or the Equipo origin, with a host and no user |
| +// info. |
| +func (a *app) oficinaLink(raw string) bool { |
| + u, err := url.Parse(raw) |
| + if err != nil || u.Host == "" || u.Hostname() == "" || u.User != nil || strings.HasPrefix(raw, "//") { |
| + return false |
| + } |
| + if u.Scheme == "https" { |
| + return true |
| + } |
| + eq, err := url.Parse(a.ask.client.Origin()) |
| + return err == nil && u.Scheme == eq.Scheme && u.Host == eq.Host |
| +} |
| + |
| +// oficinaBearer is the member's bearer, or says where to send them: the chat |
| +// is not connected, so /ask. |
| +func (a *app) oficinaBearer(w http.ResponseWriter, r *http.Request) (askConn, bool) { |
| + me, _ := CurrentMember(r) |
| + l, 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: |
| + http.Redirect(w, r, "/ask", http.StatusSeeOther) |
| + default: |
| + return askConn{me, l.DeviceID, sec.Token}, true |
| + } |
| + return askConn{}, false |
| +} |
| + |
| +// oficinaBack sends the member Home, with the outcome for the chat to say |
| +// ("" says nothing), and the chat open so they see it. |
| +func (a *app) oficinaBack(w http.ResponseWriter, r *http.Request, me store.Member, outcome string) { |
| + if _, ok := oficinaNotes[outcome]; ok { |
| + if me.AskClosed { |
| + if err := store.SetAskClosed(r.Context(), a.db, me.ID, false); err != nil { |
| + a.logger.Error("ask: dock", "err", err) |
| + } |
| + } |
| + http.SetCookie(w, &http.Cookie{Name: oficinaNote, Value: outcome, Path: "/", MaxAge: 120, |
| + HttpOnly: true, Secure: strings.HasPrefix(a.cfg.Origin, "https://"), SameSite: http.SameSiteLaxMode}) |
| + } |
| + http.Redirect(w, r, "/", http.StatusSeeOther) |
| +} |
| + |
| +// oficinaLost handles Equipo refusing the bearer: reconnect. |
| +func (a *app) oficinaFailed(w http.ResponseWriter, r *http.Request, c askConn, err error) { |
| + if errors.Is(err, equipo.ErrUnauthenticated) { |
| + a.askLost(r.Context(), c.me, c.device) |
| + http.Redirect(w, r, "/ask", http.StatusSeeOther) |
| + return |
| + } |
| + a.logger.Warn("ask: oficina", "err", err) |
| + a.oficinaBack(w, r, c.me, "unavailable") |
| +} |
| + |
| +// askOficinaConnect is GET /ask/oficina/connect: ask Equipo where to |
| +// consent, and go there. It only starts a flow for the signed-in member. |
| +func (a *app) askOficinaConnect(w http.ResponseWriter, r *http.Request) { |
| + quiet(w) |
| + c, ok := a.oficinaBearer(w, r) |
| + if !ok { |
| + return |
| + } |
| + to, err := a.ask.client.OficinaConnect(r.Context(), c.token, a.cfg.Origin+oficinaDonePath) |
| + if err != nil { |
| + a.oficinaFailed(w, r, c, err) |
| + return |
| + } |
| + if !a.oficinaLink(to) { |
| + a.logger.Warn("ask: oficina consent address refused") |
| + a.oficinaBack(w, r, c.me, "unavailable") |
| + return |
| + } |
| + http.Redirect(w, r, to, http.StatusSeeOther) |
| +} |
| + |
| +// askOficinaDone is GET /ask/oficina/done: the browser is back from |
| +// consent. With a state and code, finish with the member's bearer; with an |
| +// outcome Equipo already knows (denied, expired, unavailable), just say it. |
| +func (a *app) askOficinaDone(w http.ResponseWriter, r *http.Request) { |
| + quiet(w) |
| + c, ok := a.oficinaBearer(w, r) |
| + if !ok { |
| + return |
| + } |
| + q := r.URL.Query() |
| + state, code := q.Get("oficina_state"), q.Get("oficina_code") |
| + if state == "" || code == "" { |
| + outcome := q.Get("oficina") |
| + if outcome == "connected" { // only finishing connects |
| + outcome = "" |
| + } |
| + a.oficinaBack(w, r, c.me, outcome) |
| + return |
| + } |
| + status, err := a.ask.client.OficinaFinish(r.Context(), c.token, state, code) |
| + if err != nil { |
| + a.oficinaFailed(w, r, c, err) |
| + return |
| + } |
| + if _, known := oficinaNotes[status]; !known { |
| + status = "unavailable" |
| + } |
| + a.oficinaBack(w, r, c.me, status) |
| +} |
| + |
| +// takeOficinaNote is the outcome waiting for this member's Home, said once: |
| +// the cookie is cleared as it is read. |
| +func takeOficinaNote(w http.ResponseWriter, r *http.Request) string { |
| + ck, err := r.Cookie(oficinaNote) |
| + if err != nil { |
| + return "" |
| + } |
| + http.SetCookie(w, &http.Cookie{Name: oficinaNote, Value: "", Path: "/", MaxAge: -1, HttpOnly: true}) |
| + return oficinaNotes[ck.Value] |
| +} |
diff --git a/internal/web/home.go b/internal/web/home.go| index 4c9d793..bb793d4 100644 |
| --- a/internal/web/home.go |
| +++ b/internal/web/home.go |
| @@ -160,6 +160,7 @@ func (a *app) home(w http.ResponseWriter, r *http.Request) { |
| state = askUnavailable |
| } |
| v := a.newAskView(homeState(state), "home") |
| + v.Notice = takeOficinaNote(w, r) |
| // Docked open, the conversation is on Home from the first paint, |
| // if Equipo answers in time: Home never waits on it. Closed, it |
| // is not read; the panel's script reads it when the chat opens. |
diff --git a/internal/web/templates/partials/chat.html b/internal/web/templates/partials/chat.html| index 4b4decc..82407c3 100644 |
| --- a/internal/web/templates/partials/chat.html |
| +++ b/internal/web/templates/partials/chat.html |
| @@ -5,7 +5,7 @@ |
| {{template "ask-body" .}}</aside>{{end}} |
| {{/* A card, drawn from its fields alone: the question, a link per link, a button per option (its label, posting its value) while it is open, and the line saying how it ended. The panel's script draws the same (ask.js, addCard). */}} |
| {{define "ask-card"}}<li class="msg card card-{{.Kind}}" data-card="{{.ID}}" data-revision="{{.Revision}}"{{with .Job}} data-for="{{.}}"{{end}}><p>{{.Question}}</p> |
| -{{- range .Links}}<p><a class="card-link" href="{{.URL}}" target="_blank" rel="noopener">{{.Label}}</a></p>{{end}} |
| +{{- range .Links}}<p>{{if eq .Rel "oficina_connect"}}<a class="card-link" href="{{.URL}}">{{.Label}}</a>{{else}}<a class="card-link" href="{{.URL}}" target="_blank" rel="noopener">{{.Label}}</a>{{end}}</p>{{end}} |
| {{- if and .Open .Options}}<form class="choices" method="post" action="/ask/cards/{{.ID}}/answer"><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="key" value="{{newKey}}">{{range .Options}}<button class="btn ghost" type="submit" name="choice" value="{{.Value}}">{{.Label}}</button>{{end}}</form>{{end}} |
| {{- with .Result}}<p class="card-state">{{.}}</p>{{end}}</li>{{end}} |
| {{/* A job, a pill: its state's mark, the title and its status, and once there is something to see (ready, done) the link to it. The summary opens the job view (without scripts, in place). The cards that belong to the job hang under it while they wait on the person; once ended they are listed in its view. The panel's script draws the same (ask.js, addJob). */}} |
| @@ -47,6 +47,7 @@ |
| <button class="jump" type="button" hidden>Jump to latest</button></div> |
| <p class="ask-empty" data-empty{{if or .Messages .Jobs .Cards .Unread}} hidden{{end}}>Ask about your work, or ask Base to get something done.</p> |
| {{with .Problem}}<p class="ask-problem" role="alert">{{.}}</p>{{end}} |
| +{{with .Notice}}<p class="ask-notice" role="status">{{.}}</p>{{end}} |
| {{/* Without a runner that can answer, the conversation shows and says so; what the person wrote stays in the field. */}}<p class="ask-problem ask-runner" data-when="norunner"{{if not (.Shows "norunner")}} hidden{{end}} role="alert">Ask Base isn't set up for you yet. <a href="{{.Equipo}}" target="_blank" rel="noopener">Finish setting it up</a>, then try again.</p> |
| <p class="ask-problem ask-runner" data-when="oldrunner"{{if not (.Shows "oldrunner")}} hidden{{end}} role="alert">Ask Base needs an update first. <a href="{{.Equipo}}" target="_blank" rel="noopener">Update it</a>, then try again.</p> |
| <div class="ask-foot"> |
diff --git a/internal/webtest/oficina_connect_test.go b/internal/webtest/oficina_connect_test.go| new file mode 100644 |
| index 0000000..bd79328 |
| --- /dev/null |
| +++ b/internal/webtest/oficina_connect_test.go |
| @@ -0,0 +1,230 @@ |
| +package webtest |
| + |
| +import ( |
| + "database/sql" |
| + "time" |
| + |
| + "amadan.net/carlos/base/internal/config" |
| + "amadan.net/carlos/base/internal/web" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/carlos/base/internal/equipo" |
| + "amadan.net/carlos/base/internal/equipo/equipotest" |
| +) |
| + |
| +// Fake tokens are built at run time (R12), never written as literals. |
| +func fakeCode() string { return strings.Repeat("c", 3) + "-" + strings.Repeat("9", 8) } |
| +func fakeState() string { return strings.Repeat("s", 3) + "_" + strings.Repeat("7", 8) } |
| + |
| +func doneURL(state, code string) string { |
| + return "/ask/oficina/done?" + url.Values{"oficina_state": {state}, "oficina_code": {code}}.Encode() |
| +} |
| + |
| +func TestOficinaConnectStartsAndRedirects(t *testing.T) { |
| + a, f := newAskApp(t) |
| + token := a.connectEquipo(f) |
| + f.OficinaConsent("https://oficina.example/consent?x=1") |
| + r := a.get("/ask/oficina/connect") |
| + if r.Code != 303 || r.Location() != "https://oficina.example/consent?x=1" { |
| + t.Fatalf("connect: %d %q", r.Code, r.Location()) |
| + } |
| + if r.Header.Get("Cache-Control") != "no-store" || r.Header.Get("Referrer-Policy") != "no-referrer" { |
| + t.Errorf("headers: %v", r.Header) |
| + } |
| + calls := f.Calls("/api/v1/assistant/oficina/connect") |
| + if len(calls) != 1 || calls[0].Header.Get("Authorization") != "Bearer "+token || |
| + !strings.Contains(calls[0].Body, `"return_to":"`+testOrigin+`/ask/oficina/done"`) { |
| + t.Fatalf("calls: %+v", calls) |
| + } |
| +} |
| + |
| +func TestOficinaConnectNeverRedirectsAnywhereOdd(t *testing.T) { |
| + for _, bad := range []string{"http://evil.example/x", "javascript:alert(1)", "//evil.example/x", "/relative", "https://user:pw@evil.example/", "https:///nohost"} { |
| + a, f := newAskApp(t) |
| + a.connectEquipo(f) |
| + f.OficinaConsent(bad) |
| + r := a.get("/ask/oficina/connect") |
| + if r.Code == 303 && r.Location() == bad || r.Code != 303 || r.Location() != "/" { |
| + t.Errorf("%q: %d %q, want 303 to /", bad, r.Code, r.Location()) |
| + } |
| + if bad != "" && !strings.Contains(r.Header.Get("Set-Cookie"), "oficina_note=unavailable") { |
| + t.Errorf("%q: no unavailable note: %v", bad, r.Header) |
| + } |
| + } |
| +} |
| + |
| +func TestOficinaConnectAllowsEquipoOrigin(t *testing.T) { |
| + a, f := newAskApp(t) |
| + a.connectEquipo(f) |
| + f.OficinaConsent(f.URL + "/consent") |
| + if r := a.get("/ask/oficina/connect"); r.Code != 303 || r.Location() != f.URL+"/consent" { |
| + t.Fatalf("%d %q", r.Code, r.Location()) |
| + } |
| +} |
| + |
| +func TestOficinaConnectNeedsSignIn(t *testing.T) { |
| + 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 }) |
| + if r := a.get("/ask/oficina/connect"); r.Code != 303 || !strings.HasPrefix(r.Location(), "/signin") { |
| + t.Fatalf("signed out: %d %q", r.Code, r.Location()) |
| + } |
| + if r := a.get(doneURL(fakeState(), fakeCode())); r.Code != 303 || !strings.HasPrefix(r.Location(), "/signin") { |
| + t.Fatalf("done, signed out: %d %q", r.Code, r.Location()) |
| + } |
| +} |
| + |
| +func TestOficinaConnectNeedsTheChatConnected(t *testing.T) { |
| + a, f := newAskApp(t) // signed in, Equipo not connected |
| + if r := a.get("/ask/oficina/connect"); r.Code != 303 || r.Location() != "/ask" { |
| + t.Fatalf("connect: %d %q", r.Code, r.Location()) |
| + } |
| + if r := a.get(doneURL(fakeState(), fakeCode())); r.Code != 303 || r.Location() != "/ask" { |
| + t.Fatalf("done: %d %q", r.Code, r.Location()) |
| + } |
| + if n := len(f.Calls("/api/v1/assistant/oficina/connect")) + len(f.Calls("/api/v1/assistant/oficina/connect/finish")); n != 0 { |
| + t.Errorf("%d calls without a bearer", n) |
| + } |
| +} |
| + |
| +func TestOficinaConnectEquipoErrors(t *testing.T) { |
| + for _, c := range []struct { |
| + status int |
| + code string |
| + }{{422, "invalid_input"}, {503, "unavailable"}, {500, "internal"}} { |
| + a, f := newAskApp(t) |
| + a.connectEquipo(f) |
| + f.FailOficina(c.status, c.code) |
| + r := a.get("/ask/oficina/connect") |
| + if r.Code != 303 || r.Location() != "/" || !strings.Contains(r.Header.Get("Set-Cookie"), "oficina_note=unavailable") { |
| + t.Errorf("%d: %d %q %v", c.status, r.Code, r.Location(), r.Header) |
| + } |
| + } |
| + a, f := newAskApp(t) |
| + a.connectEquipo(f) |
| + f.FailOficina(401, "unauthenticated") |
| + if r := a.get("/ask/oficina/connect"); r.Code != 303 || r.Location() != "/ask" { |
| + t.Errorf("401: %d %q", r.Code, r.Location()) |
| + } |
| +} |
| + |
| +func TestOficinaDoneFinishesWithTheBearer(t *testing.T) { |
| + a, f := newAskApp(t) |
| + token := a.connectEquipo(f) |
| + st, code := fakeState(), fakeCode() |
| + r := a.get(doneURL(st, code)) |
| + if r.Code != 303 || r.Location() != "/" { |
| + t.Fatalf("done: %d %q", r.Code, r.Location()) |
| + } |
| + if r.Header.Get("Cache-Control") != "no-store" || r.Header.Get("Referrer-Policy") != "no-referrer" { |
| + t.Errorf("headers: %v", r.Header) |
| + } |
| + calls := f.Calls("/api/v1/assistant/oficina/connect/finish") |
| + if len(calls) != 1 || calls[0].Header.Get("Authorization") != "Bearer "+token || |
| + !strings.Contains(calls[0].Body, `"state":"`+st+`"`) || !strings.Contains(calls[0].Body, `"code":"`+code+`"`) { |
| + t.Fatalf("calls: %+v", calls) |
| + } |
| + // The outcome reaches the chat once, and nothing secret is logged. |
| + home := a.get("/") |
| + if !strings.Contains(home.Body, "Oficina connected.") { |
| + t.Fatalf("home lacks the note:\n%s", home.Body) |
| + } |
| + if again := a.get("/"); strings.Contains(again.Body, "Oficina connected.") { |
| + t.Errorf("the note showed twice") |
| + } |
| + for _, secret := range []string{st, code} { |
| + if strings.Contains(a.logs.String(), secret) { |
| + t.Errorf("a log carried the state or code") |
| + } |
| + } |
| +} |
| + |
| +func TestOficinaDoneOutcomes(t *testing.T) { |
| + for _, c := range []struct{ finish, want string }{ |
| + {"connected", "Oficina connected."}, |
| + {"denied", "Oficina wasn't connected."}, |
| + {"expired", "That link expired. Try again."}, |
| + {"unavailable", "Couldn't reach Oficina. Try again later."}, |
| + {"surprise", "Couldn't reach Oficina. Try again later."}, |
| + } { |
| + a, f := newAskApp(t) |
| + a.connectEquipo(f) |
| + f.FinishWith(c.finish) |
| + if r := a.get(doneURL(fakeState(), fakeCode())); r.Code != 303 || r.Location() != "/" { |
| + t.Fatalf("%s: %d %q", c.finish, r.Code, r.Location()) |
| + } |
| + if home := a.get("/"); !strings.Contains(strings.ReplaceAll(home.Body, "'", "'"), c.want) { |
| + t.Errorf("%s: home lacks %q", c.finish, c.want) |
| + } |
| + } |
| +} |
| + |
| +func TestOficinaDoneReturnedOutcomeWithoutCode(t *testing.T) { |
| + for param, want := range map[string]string{"denied": "Oficina wasn't connected.", "expired": "That link expired. Try again.", "unavailable": "Couldn't reach Oficina. Try again later."} { |
| + a, f := newAskApp(t) |
| + a.connectEquipo(f) |
| + if r := a.get("/ask/oficina/done?oficina=" + param); r.Code != 303 || r.Location() != "/" { |
| + t.Fatalf("%s: %d %q", param, r.Code, r.Location()) |
| + } |
| + if n := len(f.Calls("/api/v1/assistant/oficina/connect/finish")); n != 0 { |
| + t.Errorf("%s: finished with no code", param) |
| + } |
| + if home := a.get("/"); !strings.Contains(strings.ReplaceAll(home.Body, "'", "'"), want) { |
| + t.Errorf("%s: home lacks %q", param, want) |
| + } |
| + } |
| + // Only finishing connects: a bare "connected" says nothing. |
| + a, f := newAskApp(t) |
| + a.connectEquipo(f) |
| + if r := a.get("/ask/oficina/done?oficina=connected"); r.Code != 303 || r.Header.Get("Set-Cookie") != "" { |
| + t.Errorf("bare connected: %d %v", r.Code, r.Header) |
| + } |
| + // Anything else says nothing. |
| + a, f = newAskApp(t) |
| + a.connectEquipo(f) |
| + if r := a.get("/ask/oficina/done?oficina=<b>x</b>"); r.Code != 303 || r.Header.Get("Set-Cookie") != "" { |
| + t.Errorf("odd outcome: %d %v", r.Code, r.Header) |
| + } |
| +} |
| + |
| +func TestOficinaDoneAnotherPersonsState(t *testing.T) { |
| + a, f := newAskApp(t) |
| + a.connectEquipo(f) |
| + r := a.get(doneURL(equipotest.OtherPersonsState, fakeCode())) |
| + if r.Code != 303 || r.Location() != "/" { |
| + t.Fatalf("%d %q", r.Code, r.Location()) |
| + } |
| + if home := a.get("/"); strings.Contains(home.Body, "Oficina connected.") { |
| + t.Error("someone else's state read as connected") |
| + } |
| +} |
| + |
| +func TestOficinaDoneLostBearer(t *testing.T) { |
| + a, f := newAskApp(t) |
| + a.connectEquipo(f) |
| + f.FailOficina(401, "unauthenticated") |
| + if r := a.get(doneURL(fakeState(), fakeCode())); r.Code != 303 || r.Location() != "/ask" { |
| + t.Errorf("%d %q", r.Code, r.Location()) |
| + } |
| +} |
| + |
| +func TestOficinaConnectCardLinkKeepsItsRel(t *testing.T) { |
| + a, f := newAskApp(t) |
| + a.connectEquipo(f) |
| + good := equipo.Link{Label: "Connect", URL: testOrigin + "/ask/oficina/connect", Rel: "oficina_connect"} |
| + elsewhere := equipo.Link{Label: "Other", URL: "https://evil.example/x", Rel: "oficina_connect"} |
| + f.AskOutcome("Connect Oficina to go on.", nil, []equipo.Link{good, elsewhere}) |
| + body := a.get("/ask/state").Body |
| + if !strings.Contains(body, `"rel":"oficina_connect"`) || strings.Count(body, `"rel":"oficina_connect"`) != 1 { |
| + t.Fatalf("state: %s", body) |
| + } |
| + page := a.get("/ask").Body |
| + if !strings.Contains(page, `<a class="card-link" href="`+testOrigin+`/ask/oficina/connect">Connect</a>`) { |
| + t.Errorf("same-tab link missing:\n%s", page) |
| + } |
| + if !strings.Contains(page, `href="https://evil.example/x" target="_blank" rel="noopener"`) { |
| + t.Errorf("other link not opened in a new tab:\n%s", page) |
| + } |
| +} |