| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "log/slog" |
| 7 | "net" |
| 8 | "net/http" |
| 9 | "net/url" |
| 10 | "slices" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/equipo/assist" |
| 15 | "amadan.net/oficina/equipo/internal/equipo/chat" |
| 16 | "amadan.net/oficina/equipo/internal/equipo/identity" |
| 17 | "amadan.net/oficina/equipo/internal/equipo/oficina" |
| 18 | "amadan.net/oficina/equipo/internal/wire" |
| 19 | "gorm.io/gorm" |
| 20 | "gorm.io/plugin/dbresolver" |
| 21 | ) |
| 22 | |
| 23 | // The Oficina apps, through oficina-connect (internal/equipo/oficina): |
| 24 | // the provider's name in the Assistant's registry, and the routes a |
| 25 | // person's browser takes to connect (the card's link, then connect's |
| 26 | // redirect back) and to disconnect. |
| 27 | const ( |
| 28 | oficinaProvider = chat.OficinaProvider |
| 29 | oficinaStartPath = "/oficina/connect/start" |
| 30 | oficinaCallbackPath = "/oficina/connect/callback" |
| 31 | oficinaDisconnectPath = "/oficina/connect/disconnect" |
| 32 | oficinaDonePath = "/oficina/connect/done" |
| 33 | ) |
| 34 | |
| 35 | // oficinaConnectionRecord is a person's connection to oficina-connect: |
| 36 | // their refresh token, sealed with the instance key (domain |
| 37 | // oficina.connect), replaced as connect rotates it. |
| 38 | type oficinaConnectionRecord struct { |
| 39 | Person string `gorm:"primaryKey"` |
| 40 | Refresh string |
| 41 | Revision int64 |
| 42 | CreatedAt time.Time |
| 43 | UpdatedAt time.Time |
| 44 | } |
| 45 | |
| 46 | func (oficinaConnectionRecord) TableName() string { return "oficina_connections" } |
| 47 | |
| 48 | // oficinaStore keeps connections in the instance's database. A save |
| 49 | // checks the roster in its transaction; each audit is a code, never a |
| 50 | // token. |
| 51 | type oficinaStore struct{ s *Store } |
| 52 | |
| 53 | func (o oficinaStore) Load(ctx context.Context, person string) (string, error) { |
| 54 | var sealed []string |
| 55 | err := o.s.db.G.WithContext(ctx).Clauses(dbresolver.Write).Model(&oficinaConnectionRecord{}).Where("person = ?", normalizeAddress(person)).Pluck("refresh", &sealed).Error |
| 56 | if err != nil || len(sealed) == 0 { |
| 57 | return "", storeError(err) |
| 58 | } |
| 59 | return sealed[0], nil |
| 60 | } |
| 61 | |
| 62 | func (o oficinaStore) Save(ctx context.Context, person, sealed, audit string) error { |
| 63 | person = normalizeAddress(person) |
| 64 | return o.tx(ctx, func(tx *gorm.DB) error { |
| 65 | if _, err := currentRunnerMember(tx, person); err != nil { |
| 66 | return err |
| 67 | } |
| 68 | var r oficinaConnectionRecord |
| 69 | if err := tx.Where("person = ?", person).Limit(1).Find(&r).Error; err != nil { |
| 70 | return err |
| 71 | } |
| 72 | now := time.Now().UTC() |
| 73 | if r.Person == "" { |
| 74 | r = oficinaConnectionRecord{Person: person, CreatedAt: now} |
| 75 | } |
| 76 | r.Refresh, r.Revision, r.UpdatedAt = sealed, r.Revision+1, now |
| 77 | if err := tx.Save(&r).Error; err != nil { |
| 78 | return err |
| 79 | } |
| 80 | if audit == "" { |
| 81 | return nil |
| 82 | } |
| 83 | return appendAudit(tx, Actor{Address: person}, audit, "") |
| 84 | }) |
| 85 | } |
| 86 | |
| 87 | // Delete forgets a connection, a removed member's too. |
| 88 | func (o oficinaStore) Delete(ctx context.Context, person, audit, detail string) error { |
| 89 | person = normalizeAddress(person) |
| 90 | return o.tx(ctx, func(tx *gorm.DB) error { |
| 91 | if err := tx.Where("person = ?", person).Delete(&oficinaConnectionRecord{}).Error; err != nil { |
| 92 | return err |
| 93 | } |
| 94 | return appendAudit(tx, Actor{Address: person}, audit, detail) |
| 95 | }) |
| 96 | } |
| 97 | |
| 98 | func (o oficinaStore) Audit(ctx context.Context, person, kind, detail string) error { |
| 99 | return o.tx(ctx, func(tx *gorm.DB) error { return appendAudit(tx, Actor{Address: person}, kind, detail) }) |
| 100 | } |
| 101 | |
| 102 | func (o oficinaStore) tx(ctx context.Context, fn func(*gorm.DB) error) error { |
| 103 | err := o.s.db.G.WithContext(ctx).Clauses(dbresolver.Write).Transaction(fn) |
| 104 | if err == nil || errors.Is(err, ErrForbidden) { |
| 105 | return err |
| 106 | } |
| 107 | return storeError(err) |
| 108 | } |
| 109 | |
| 110 | // oficinaSealer seals with the instance key, as device results and |
| 111 | // Base host tokens are (read when used: the key is set after the store). |
| 112 | type oficinaSealer struct{ s *Store } |
| 113 | |
| 114 | func (o oficinaSealer) Seal(domain string, v any) (string, error) { |
| 115 | return o.s.personDevices().Seal(domain, v) |
| 116 | } |
| 117 | |
| 118 | func (o oficinaSealer) Open(domain, raw string, v any) error { |
| 119 | return o.s.personDevices().Open(domain, raw, v) |
| 120 | } |
| 121 | |
| 122 | // oficinaLinkRel marks the connect card's link: Base resolves it |
| 123 | // through POST /api/v1/assistant/oficina/connect (baseConnectPath on the |
| 124 | // person's Base host); with no host registered it is the instance's own |
| 125 | // start, for a person who uses Equipo directly. |
| 126 | const ( |
| 127 | oficinaLinkRel = "oficina_connect" |
| 128 | baseConnectPath = "/ask/oficina/connect" |
| 129 | ) |
| 130 | |
| 131 | // oficinaResults are where a consent ended, as the callback reports it |
| 132 | // (oficina=<result> on the return address) and the page shows it. |
| 133 | var oficinaResults = map[string]string{"connected": "oficina.connect.connected", "denied": "oficina.connect.denied", "expired": "oficina.connect.expired", "unavailable": "oficina.connect.unavailable"} |
| 134 | |
| 135 | // oficinaLink is the connect card's one link for person. |
| 136 | func (s *Store) oficinaLink(ctx context.Context, person string) wire.CardLink { |
| 137 | link := wire.CardLink{Label: copyText("assistant.connect.oficina_link"), URL: s.chatOrigin + oficinaStartPath, Rel: oficinaLinkRel} |
| 138 | if origin, _, ok, err := s.Chat().Host(ctx, person); err == nil && ok { |
| 139 | link.URL = origin + baseConnectPath |
| 140 | } |
| 141 | return link |
| 142 | } |
| 143 | |
| 144 | // oficinaConnect starts person's consent for the person API: their |
| 145 | // browser comes back to returnTo, which must be on an allowed Base |
| 146 | // origin. |
| 147 | func (s *Store) oficinaConnect(ctx context.Context, person, returnTo string) (string, error) { |
| 148 | if !s.oficinaReturn(returnTo) { |
| 149 | return "", chat.ErrInvalid |
| 150 | } |
| 151 | dest, err := s.startOficina(ctx, normalizeAddress(person), returnTo) |
| 152 | if err != nil { |
| 153 | return "", connectRefusal(err) |
| 154 | } |
| 155 | return dest, nil |
| 156 | } |
| 157 | |
| 158 | // startOficina and finishOficina are the only ways a consent starts or |
| 159 | // finishes, from Base or from Equipo's own pages: each first checks the |
| 160 | // person may read their Oficina apps (spec 2026-11-26-assistant-abilities |
| 161 | // §6.1), refreshing their board when stale. Disconnect isn't checked. |
| 162 | func (s *Store) startOficina(ctx context.Context, person, returnTo string) (string, error) { |
| 163 | if err := s.Chat().Allowed(ctx, person, wire.AbilityAppsRead); err != nil { |
| 164 | return "", err |
| 165 | } |
| 166 | return s.oficina.Start(ctx, person, returnTo) |
| 167 | } |
| 168 | |
| 169 | func (s *Store) finishOficina(ctx context.Context, person, state, code string) error { |
| 170 | if err := s.Chat().Allowed(ctx, person, wire.AbilityAppsRead); err != nil { |
| 171 | return err |
| 172 | } |
| 173 | return s.oficina.Finish(ctx, person, state, code) |
| 174 | } |
| 175 | |
| 176 | // connectRefusal is a start or finish's error for the person API: |
| 177 | // chat.ErrAbilityOff when reading apps is off for the person, else |
| 178 | // unavailable. |
| 179 | func connectRefusal(err error) error { |
| 180 | if abilityOff(err) { |
| 181 | return chat.ErrAbilityOff |
| 182 | } |
| 183 | return chat.ErrUnavailable |
| 184 | } |
| 185 | |
| 186 | // abilityOff reports whether err is a refusal because an ability is off. |
| 187 | func abilityOff(err error) bool { |
| 188 | var r assist.Refusal |
| 189 | return errors.As(err, &r) && r.Code == wire.CodeAbilityOff |
| 190 | } |
| 191 | |
| 192 | // oficinaOffPage is Equipo's page saying reading apps is off for the |
| 193 | // person, and who can turn it on. |
| 194 | func (a *application) oficinaOffPage(w http.ResponseWriter, r *http.Request, person string) { |
| 195 | ask := "" |
| 196 | if out, err := a.store.Chat().OwnAbilities(r.Context(), person); err == nil { |
| 197 | ask = out.Ask |
| 198 | } |
| 199 | if ask == "" { |
| 200 | // No name to give: the reviewed "ask an owner" page. |
| 201 | ErrorPage(w, r, http.StatusForbidden, "") |
| 202 | return |
| 203 | } |
| 204 | data, err := a.page(r, "settings") |
| 205 | if err != nil { |
| 206 | a.failure(w, r, err) |
| 207 | return |
| 208 | } |
| 209 | data.Title, data.EmptyKey, data.EmptyArg = "oficina.connect.title", "oficina.connect.ability_off", ask |
| 210 | w.Header().Set("Cache-Control", "no-store") |
| 211 | renderStatus(w, http.StatusForbidden, "empty", data) |
| 212 | } |
| 213 | |
| 214 | // oficinaReturn: an absolute https address (http only on loopback), with |
| 215 | // no user or fragment, on an origin in EQUIPO_ASSISTANT_HOSTS. |
| 216 | func (s *Store) oficinaReturn(raw string) bool { |
| 217 | if raw == "" || len(raw) > 2048 || strings.ContainsAny(raw, " \t\r\n\\") { |
| 218 | return false |
| 219 | } |
| 220 | u, err := url.Parse(raw) |
| 221 | if err != nil || u.User != nil || u.Opaque != "" || u.Fragment != "" || u.Hostname() == "" { |
| 222 | return false |
| 223 | } |
| 224 | scheme, host := strings.ToLower(u.Scheme), strings.ToLower(u.Hostname()) |
| 225 | ip := net.ParseIP(host) |
| 226 | if scheme != "https" && (scheme != "http" || host != "localhost" && (ip == nil || !ip.IsLoopback())) { |
| 227 | return false |
| 228 | } |
| 229 | return slices.Contains(lowered(s.chatAssistantHosts), scheme+"://"+strings.ToLower(u.Host)) |
| 230 | } |
| 231 | |
| 232 | // oficinaStart sends the signed-in person to connect's consent page, for |
| 233 | // a person who connects from Equipo itself. |
| 234 | func (a *application) oficinaStart(w http.ResponseWriter, r *http.Request) { |
| 235 | id, ok := identity.From(r) |
| 236 | if !ok { |
| 237 | ErrorPage(w, r, http.StatusForbidden, "") |
| 238 | return |
| 239 | } |
| 240 | dest, err := a.store.startOficina(r.Context(), normalizeAddress(id.Address), "") |
| 241 | if abilityOff(err) { |
| 242 | a.oficinaOffPage(w, r, normalizeAddress(id.Address)) |
| 243 | return |
| 244 | } |
| 245 | if err != nil { |
| 246 | a.oficinaPage(w, r, http.StatusServiceUnavailable, oficinaResults["unavailable"]) |
| 247 | return |
| 248 | } |
| 249 | w.Header().Set("Cache-Control", "no-store") |
| 250 | w.Header().Set("Referrer-Policy", "no-referrer") |
| 251 | http.Redirect(w, r, dest, http.StatusSeeOther) |
| 252 | } |
| 253 | |
| 254 | // oficinaFinish finishes person's consent with the state and code the |
| 255 | // callback handed back (the person API, for Base): its status, or |
| 256 | // chat.ErrForbidden when the consent was another person's. |
| 257 | func (s *Store) oficinaFinish(ctx context.Context, person, state, code string) (string, error) { |
| 258 | if state == "" || code == "" || len(state) > 512 || len(code) > 512 { |
| 259 | return "", chat.ErrInvalid |
| 260 | } |
| 261 | err := s.finishOficina(ctx, normalizeAddress(person), state, code) |
| 262 | if abilityOff(err) { |
| 263 | return "", chat.ErrAbilityOff |
| 264 | } |
| 265 | return s.oficinaFinished(ctx, normalizeAddress(person), err) |
| 266 | } |
| 267 | |
| 268 | // oficinaFinished is a finished consent's status. Connected, the |
| 269 | // person's lists are read afresh and their connect card settled; a |
| 270 | // settlement that fails is caught up on their next read of the |
| 271 | // Assistant lane (oficinaCatchUp). |
| 272 | func (s *Store) oficinaFinished(ctx context.Context, person string, err error) (string, error) { |
| 273 | switch { |
| 274 | case errors.Is(err, oficina.ErrNotYours): |
| 275 | return "", chat.ErrForbidden |
| 276 | case errors.Is(err, oficina.ErrDenied): |
| 277 | return "denied", nil |
| 278 | case errors.Is(err, oficina.ErrExpired): |
| 279 | return "expired", nil |
| 280 | case err != nil: |
| 281 | return "unavailable", nil |
| 282 | } |
| 283 | s.assist.Forget(person) |
| 284 | if err := s.Chat().SettleConnectSince(ctx, person, oficinaProvider, oficinaConnected(person)); err != nil { |
| 285 | slog.Warn(copyOficinaCardFailed, "err", err) |
| 286 | } |
| 287 | return "connected", nil |
| 288 | } |
| 289 | |
| 290 | // oficinaCatchUp settles the person's Oficina connect card left open |
| 291 | // while they are connected: a finish saved the connection and then |
| 292 | // failed to settle it, and its state is used up. Settling queues the |
| 293 | // one resume turn, as the finish would have. The connection is read in |
| 294 | // the settling transaction, and only a card raised before it was saved |
| 295 | // settles. With no open card it is one read. |
| 296 | func (s *Store) oficinaCatchUp(ctx context.Context, person string) error { |
| 297 | person = normalizeAddress(person) |
| 298 | open, err := s.Chat().ConnectOpen(ctx, person, oficinaProvider) |
| 299 | if err != nil || !open { |
| 300 | return err |
| 301 | } |
| 302 | if s.oficinaPause != nil { |
| 303 | s.oficinaPause() |
| 304 | } |
| 305 | return s.Chat().SettleConnectSince(ctx, person, oficinaProvider, oficinaConnected(person)) |
| 306 | } |
| 307 | |
| 308 | // oficinaConnected reads person's connection in the settling |
| 309 | // transaction: when it was last saved, if they have one. |
| 310 | func oficinaConnected(person string) chat.Connected { |
| 311 | return func(tx *gorm.DB) (time.Time, bool, error) { |
| 312 | var r oficinaConnectionRecord |
| 313 | if err := tx.Where("person = ?", person).Limit(1).Find(&r).Error; err != nil || r.Person == "" || r.Refresh == "" { |
| 314 | return time.Time{}, false, err |
| 315 | } |
| 316 | return r.UpdatedAt, true, nil |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | // SetOficinaCatchUpPause runs pause inside oficinaCatchUp after it has |
| 321 | // looked and before it settles: tests interleave other work there. |
| 322 | func (s *Store) SetOficinaCatchUpPause(pause func()) { s.oficinaPause = pause } |
| 323 | |
| 324 | // oficinaCallback is connect's redirect back. It needs no session and |
| 325 | // finishes nothing: it checks the state (Peek) and hands the state and |
| 326 | // code on to where the consent started, for the person to finish with |
| 327 | // proof of who they are. For Base that is the return address it gave |
| 328 | // (oficina_state and oficina_code, or oficina=<result> when the consent |
| 329 | // failed), and Base finishes with the person's bearer; for a consent |
| 330 | // started in Equipo, the done page, which finishes with the session. A |
| 331 | // browser that brings back someone else's consent cannot finish it. A |
| 332 | // state never issued, used or unknown goes nowhere. |
| 333 | func (a *application) oficinaCallback(w http.ResponseWriter, r *http.Request) { |
| 334 | w.Header().Set("Cache-Control", "no-store") |
| 335 | // The code is in this address: never in a Referer. |
| 336 | w.Header().Set("Referrer-Policy", "no-referrer") |
| 337 | q := r.URL.Query() |
| 338 | res, err := a.store.oficina.Peek(r.Context(), q) |
| 339 | if res.Person == "" { |
| 340 | // Nobody's: plain words, not an Equipo page. |
| 341 | http.Error(w, copyText(oficinaResults["expired"]), http.StatusBadRequest) |
| 342 | return |
| 343 | } |
| 344 | add := url.Values{} |
| 345 | switch { |
| 346 | case errors.Is(err, oficina.ErrDenied): |
| 347 | add.Set("oficina", "denied") |
| 348 | case errors.Is(err, oficina.ErrExpired): |
| 349 | add.Set("oficina", "expired") |
| 350 | case err != nil: |
| 351 | add.Set("oficina", "unavailable") |
| 352 | default: |
| 353 | add.Set("oficina_state", q.Get("state")) |
| 354 | add.Set("oficina_code", q.Get("code")) |
| 355 | } |
| 356 | dest := res.ReturnTo |
| 357 | if dest == "" { |
| 358 | dest = oficinaDonePath |
| 359 | } |
| 360 | u, _ := url.Parse(dest) |
| 361 | v := u.Query() |
| 362 | for k := range add { |
| 363 | v.Set(k, add.Get(k)) |
| 364 | } |
| 365 | u.RawQuery = v.Encode() |
| 366 | http.Redirect(w, r, u.String(), http.StatusSeeOther) |
| 367 | } |
| 368 | |
| 369 | // oficinaDone is the Equipo page after a consent started in Equipo: it |
| 370 | // finishes it with the session's person, or shows how it failed. |
| 371 | func (a *application) oficinaDone(w http.ResponseWriter, r *http.Request) { |
| 372 | w.Header().Set("Cache-Control", "no-store") |
| 373 | w.Header().Set("Referrer-Policy", "no-referrer") |
| 374 | q := r.URL.Query() |
| 375 | result := q.Get("oficina") |
| 376 | if state := q.Get("oficina_state"); state != "" { |
| 377 | id, ok := identity.From(r) |
| 378 | if !ok { |
| 379 | ErrorPage(w, r, http.StatusForbidden, "") |
| 380 | return |
| 381 | } |
| 382 | person := normalizeAddress(id.Address) |
| 383 | finished := a.store.finishOficina(r.Context(), person, state, q.Get("oficina_code")) |
| 384 | if abilityOff(finished) { |
| 385 | a.oficinaOffPage(w, r, person) |
| 386 | return |
| 387 | } |
| 388 | var err error |
| 389 | if result, err = a.store.oficinaFinished(r.Context(), person, finished); err != nil { |
| 390 | ErrorPage(w, r, http.StatusForbidden, "") |
| 391 | return |
| 392 | } |
| 393 | } |
| 394 | key, ok := oficinaResults[result] |
| 395 | if !ok { |
| 396 | ErrorPage(w, r, http.StatusNotFound, "") |
| 397 | return |
| 398 | } |
| 399 | a.oficinaPage(w, r, http.StatusOK, key) |
| 400 | } |
| 401 | |
| 402 | // oficinaDisconnect revokes the signed-in person's connection at connect |
| 403 | // and forgets it. |
| 404 | func (a *application) oficinaDisconnect(w http.ResponseWriter, r *http.Request) { |
| 405 | id, ok := identity.From(r) |
| 406 | if !ok { |
| 407 | ErrorPage(w, r, http.StatusForbidden, "") |
| 408 | return |
| 409 | } |
| 410 | person := normalizeAddress(id.Address) |
| 411 | if err := a.store.oficina.Disconnect(r.Context(), person); err != nil { |
| 412 | a.oficinaPage(w, r, http.StatusServiceUnavailable, oficinaResults["unavailable"]) |
| 413 | return |
| 414 | } |
| 415 | a.store.assist.Forget(person) |
| 416 | a.oficinaPage(w, r, http.StatusOK, "oficina.connect.disconnected") |
| 417 | } |
| 418 | |
| 419 | // oficinaPage is a short page saying what happened, under the app's |
| 420 | // chrome. |
| 421 | func (a *application) oficinaPage(w http.ResponseWriter, r *http.Request, status int, key string) { |
| 422 | data, err := a.page(r, "settings") |
| 423 | if err != nil { |
| 424 | a.failure(w, r, err) |
| 425 | return |
| 426 | } |
| 427 | data.Title, data.EmptyKey = "oficina.connect.title", key |
| 428 | w.Header().Set("Cache-Control", "no-store") |
| 429 | renderStatus(w, status, "empty", data) |
| 430 | } |
| 431 | |