| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "net/http" |
| 10 | "net/url" |
| 11 | "regexp" |
| 12 | "slices" |
| 13 | "strconv" |
| 14 | "strings" |
| 15 | "time" |
| 16 | "unicode" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/equipo/assist" |
| 19 | "amadan.net/oficina/equipo/internal/websearch" |
| 20 | "amadan.net/oficina/equipo/internal/websource" |
| 21 | "amadan.net/oficina/equipo/internal/websource/guard" |
| 22 | "amadan.net/oficina/equipo/internal/wire" |
| 23 | ) |
| 24 | |
| 25 | // A lookup, step by step (spec 2026-11-26-assistant-abilities §4.2): the |
| 26 | // pack from the person's words; the addresses they typed, or a query |
| 27 | // step and a search; reads of the top results, picked by rank in this |
| 28 | // code; an answer step; the answer stored and shown under the reply, |
| 29 | // never handed back. Every search and read goes through the guarded |
| 30 | // client, paced per host and gated right before it is sent. |
| 31 | |
| 32 | // Lookup bounds. |
| 33 | const ( |
| 34 | lookupLimit = 40 * time.Second |
| 35 | lookupsPerTurn = 2 |
| 36 | lookupsPerDay = 100 |
| 37 | lookupReads = 3 |
| 38 | lookupTries = 6 |
| 39 | lookupPageText = 16 << 10 |
| 40 | lookupDenyFresh = 60 * time.Second |
| 41 | lookupDenyKeep = 10 * time.Minute |
| 42 | auditLookup = "assistant.lookup" |
| 43 | // lookupActivityKey is the activity line's copy while a lookup runs. |
| 44 | lookupActivityKey = "assistant.activity.lookup" |
| 45 | ) |
| 46 | |
| 47 | // What the Assistant gets back: fixed instance text, never page text or |
| 48 | // the answer (§4.2 step 8). Reviewed as code. |
| 49 | const ( |
| 50 | toolLookupShown = "Looked up and shown to the person under your reply, with its sources. You can't see it. Don't guess or repeat what it says. If they want something done with it, they'll tell you in their own words: ask for what you need, for example \"Want me to put a visit in your calendar? Tell me the day and time.\"" |
| 51 | toolLookupFailed = "The lookup didn't work. Tell the person in one line, for example \"I couldn't find that just now.\"" |
| 52 | toolNothingFound = "Nothing was found for that. Tell the person in one line, for example \"I couldn't find that just now.\"" |
| 53 | toolLookupLimit = "No more lookups can run for now. Tell the person in one line that you can't look that up just now." |
| 54 | toolLookupUnsupported = "A lookup can't run for this message. Tell the person in one line that you can't look that up here." |
| 55 | toolLookupInput = "web_lookup takes no input: it works from what the person asked." |
| 56 | ) |
| 57 | |
| 58 | var lookupTexts = map[string]string{wire.CodeLookupFailed: toolLookupFailed, wire.CodeNothingFound: toolNothingFound, wire.CodeLookupLimit: toolLookupLimit, wire.CodeLookupUnsupported: toolLookupUnsupported} |
| 59 | |
| 60 | // lookupQuery is one query and the backend that answered it. |
| 61 | type lookupQuery struct { |
| 62 | Q string `json:"q"` |
| 63 | Backend string `json:"backend"` |
| 64 | } |
| 65 | |
| 66 | // lookupRead is one page read, by its numbers only. |
| 67 | type lookupRead struct { |
| 68 | URL string `json:"url"` |
| 69 | FinalURL string `json:"final_url,omitempty"` |
| 70 | Status int `json:"status,omitempty"` |
| 71 | Bytes int `json:"bytes,omitempty"` |
| 72 | SHA256 string `json:"sha256,omitempty"` |
| 73 | Code string `json:"code,omitempty"` |
| 74 | } |
| 75 | |
| 76 | // lookupRun is one lookup's state while it runs. |
| 77 | type lookupRun struct { |
| 78 | s *Store |
| 79 | cfg *LookupConfig |
| 80 | call toolCallRecord |
| 81 | row lookupRecord |
| 82 | deny []string |
| 83 | // question is the person's message whole (the pack's may be cut): |
| 84 | // the addresses they typed come from it. |
| 85 | question string |
| 86 | queries []lookupQuery |
| 87 | reads []lookupRead |
| 88 | domains []string |
| 89 | } |
| 90 | |
| 91 | // webLookup runs the call's lookup and is the Assistant's result: the |
| 92 | // fixed shown result, or a code with fixed text. A delivery retry of the |
| 93 | // same call id answers as the first did. |
| 94 | func (s *Store) webLookup(ctx context.Context, call toolCallRecord) (json.RawMessage, error) { |
| 95 | if why := s.lookupUnsupported(ctx, call.Person); why != "" { |
| 96 | return nil, lookupFailure(wire.CodeLookupUnsupported) |
| 97 | } |
| 98 | if kind, err := s.turnKind(ctx, call); err != nil || kind != wire.TurnPerson { |
| 99 | return nil, lookupFailure(wire.CodeLookupUnsupported) |
| 100 | } |
| 101 | cfg := s.lookups.cfg.Load() |
| 102 | ctx, cancel := context.WithTimeout(ctx, lookupLimit) |
| 103 | defer cancel() |
| 104 | run := &lookupRun{s: s, cfg: cfg, call: call} |
| 105 | var pack wire.LookupPack |
| 106 | var replay *lookupRecord |
| 107 | err := s.tx(ctx, func(t *txn) error { |
| 108 | t.db = quietDB(t.db) |
| 109 | var prior lookupRecord |
| 110 | if err := t.db.Where("call_id = ? AND person = ?", call.CallID, call.Person).Limit(1).Find(&prior).Error; err != nil || prior.ID != "" { |
| 111 | replay = &prior |
| 112 | return err |
| 113 | } |
| 114 | var turn turnRecord |
| 115 | if err := t.db.Where("id = ? AND person = ?", call.TurnID, call.Person).First(&turn).Error; err != nil { |
| 116 | return err |
| 117 | } |
| 118 | // The cap is the whole turn's, whatever its attempts; the order |
| 119 | // is the attempt's (the reply shows its final attempt's). |
| 120 | var inTurn, inAttempt, today int64 |
| 121 | if err := t.db.Model(&lookupRecord{}).Where("turn_id = ?", call.TurnID).Count(&inTurn).Error; err != nil { |
| 122 | return err |
| 123 | } |
| 124 | if err := t.db.Model(&lookupRecord{}).Where("turn_id = ? AND attempt = ?", call.TurnID, call.Attempt).Count(&inAttempt).Error; err != nil { |
| 125 | return err |
| 126 | } |
| 127 | if err := t.db.Model(&lookupRecord{}).Where("person = ? AND created_at > ?", call.Person, t.now().Add(-24*time.Hour)).Count(&today).Error; err != nil { |
| 128 | return err |
| 129 | } |
| 130 | run.row = lookupRecord{ID: newID("lk"), Person: call.Person, TurnID: call.TurnID, Attempt: call.Attempt, Seq: inAttempt + 1, CallID: call.CallID, State: lookupRunning, CreatedAt: t.now()} |
| 131 | if inTurn >= lookupsPerTurn || today >= lookupsPerDay { |
| 132 | run.row.State, run.row.Code = lookupFailed, wire.CodeLookupLimit |
| 133 | return t.db.Create(&run.row).Error |
| 134 | } |
| 135 | var ok bool |
| 136 | var err error |
| 137 | if pack, ok, err = t.lookupPack(call.Person, turn, t.now()); err != nil { |
| 138 | return err |
| 139 | } |
| 140 | if !ok { |
| 141 | run.row.State, run.row.Code = lookupFailed, wire.CodeLookupUnsupported |
| 142 | return t.db.Create(&run.row).Error |
| 143 | } |
| 144 | mine, err := t.newestComposer(call.Person, turn.ID) |
| 145 | if err != nil { |
| 146 | return err |
| 147 | } |
| 148 | run.question = mine.Text |
| 149 | if err := t.db.Create(&run.row).Error; err != nil { |
| 150 | return err |
| 151 | } |
| 152 | // The reply's activity line while it runs. |
| 153 | a := wire.Activity{TurnID: turn.ID, Attempt: turn.Attempt, Kind: wire.ActivityTool, Tool: wire.ToolUse, Label: t.words(lookupActivityKey)} |
| 154 | return t.event(turn.Lane, turn.Person, wire.EventActivity, "turn", turn.ID, 0, turn.ID, "", turn.Attempt, a) |
| 155 | }) |
| 156 | if err != nil { |
| 157 | return nil, err |
| 158 | } |
| 159 | if replay != nil { |
| 160 | return lookupResult(*replay) |
| 161 | } |
| 162 | if run.row.State == lookupFailed { |
| 163 | return lookupResult(run.row) |
| 164 | } |
| 165 | answer, sources, code, err := run.do(ctx, pack) |
| 166 | var refusal assist.Refusal |
| 167 | if errors.As(err, &refusal) { |
| 168 | // The gate refused (web turned off meanwhile): nothing more was |
| 169 | // sent. The refusal is the Assistant's answer. |
| 170 | if err := run.finish(context.WithoutCancel(ctx), "", nil, refusal.Code); err != nil { |
| 171 | return nil, err |
| 172 | } |
| 173 | return nil, refusal |
| 174 | } |
| 175 | if err != nil { |
| 176 | code = wire.CodeLookupFailed |
| 177 | } |
| 178 | // Shown only once stored: a lookup whose outcome didn't commit is an |
| 179 | // error, not an answer the reply would lack. |
| 180 | if err := run.finish(context.WithoutCancel(ctx), answer, sources, code); err != nil { |
| 181 | return nil, err |
| 182 | } |
| 183 | return lookupResult(run.row) |
| 184 | } |
| 185 | |
| 186 | func lookupFailure(code string) error { |
| 187 | return assist.Refusal{Code: code, Message: lookupTexts[code]} |
| 188 | } |
| 189 | |
| 190 | // lookupResult is a stored lookup as the Assistant's result. |
| 191 | func lookupResult(r lookupRecord) (json.RawMessage, error) { |
| 192 | if r.State != lookupShown { |
| 193 | code := r.Code |
| 194 | if lookupTexts[code] == "" { |
| 195 | if code == "" || code == wire.CodeLookupShown { |
| 196 | code = wire.CodeLookupFailed |
| 197 | } else { |
| 198 | return nil, assist.Refusal{Code: code, Message: toolOpUnavailable} |
| 199 | } |
| 200 | } |
| 201 | return nil, lookupFailure(code) |
| 202 | } |
| 203 | var sources []wire.LookupSource |
| 204 | _ = json.Unmarshal([]byte(r.Sources), &sources) |
| 205 | out, _ := json.Marshal(map[string]any{"code": wire.CodeLookupShown, "sources": len(sources), "text": toolLookupShown}) |
| 206 | return out, nil |
| 207 | } |
| 208 | |
| 209 | // do runs steps 2 to 6: what to read, the reads, the answer. |
| 210 | func (r *lookupRun) do(ctx context.Context, pack wire.LookupPack) (answer string, sources []wire.LookupSource, code string, err error) { |
| 211 | deny, err := r.s.lookupDeny(ctx, r.call.Person) |
| 212 | if err != nil { |
| 213 | return "", nil, wire.CodeLookupFailed, nil |
| 214 | } |
| 215 | r.deny = append(slices.Clone(r.cfg.Deny), deny...) |
| 216 | var results []wire.SearchResult |
| 217 | var candidates []string |
| 218 | if typed := typedAddresses(r.question); len(typed) > 0 { |
| 219 | // The addresses the person typed, as typed: read, or refused by |
| 220 | // rule (recorded), never a search instead. |
| 221 | candidates = typed |
| 222 | } else { |
| 223 | q, err := r.s.lookupStep(ctx, r.call.Person, wire.LookupStep{Lookup: r.row.ID, Attempt: int(r.row.Attempt), Stage: wire.LookupStageQuery, Pack: pack}) |
| 224 | if err != nil || q.Code != "" || wire.ValidQueryResult(q) != nil { |
| 225 | return "", nil, wire.CodeLookupFailed, err |
| 226 | } |
| 227 | for _, query := range q.Queries { |
| 228 | if websource.LooksSecret(query) { |
| 229 | return "", nil, wire.CodeLookupFailed, nil |
| 230 | } |
| 231 | } |
| 232 | for _, query := range q.Queries { |
| 233 | got, backend, err := r.cfg.Search.Search(r.searchCtx(ctx), query, websearch.MaxResults, func(ctx context.Context, _ string) error { return assist.Gate(ctx, webLookupOp) }) |
| 234 | var refusal assist.Refusal |
| 235 | if errors.As(err, &refusal) { |
| 236 | return "", nil, "", refusal |
| 237 | } |
| 238 | var be *websearch.Error |
| 239 | if errors.As(err, &be) && be.Class == websearch.ClassLimit { |
| 240 | return "", nil, wire.CodeLookupLimit, nil |
| 241 | } |
| 242 | if err != nil { |
| 243 | continue |
| 244 | } |
| 245 | r.queries = append(r.queries, lookupQuery{Q: query, Backend: backend}) |
| 246 | for _, g := range got { |
| 247 | if !slices.ContainsFunc(results, func(x wire.SearchResult) bool { return x.URL == g.URL }) { |
| 248 | results = append(results, wire.SearchResult{Title: g.Title, URL: g.URL, Snippet: g.Snippet, Date: g.Date}) |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | if len(r.queries) == 0 { |
| 253 | return "", nil, wire.CodeLookupFailed, nil |
| 254 | } |
| 255 | if len(results) == 0 { |
| 256 | return "", nil, wire.CodeNothingFound, nil |
| 257 | } |
| 258 | results = results[:min(len(results), websearch.MaxResults)] |
| 259 | for _, res := range results { |
| 260 | candidates = append(candidates, res.URL) |
| 261 | } |
| 262 | } |
| 263 | var pages []wire.LookupPage |
| 264 | for i, u := range candidates { |
| 265 | if len(pages) == lookupReads || i == lookupTries { |
| 266 | break |
| 267 | } |
| 268 | page, err := r.read(ctx, u) |
| 269 | if err != nil { |
| 270 | return "", nil, "", err |
| 271 | } |
| 272 | if page != nil { |
| 273 | pages = append(pages, *page) |
| 274 | } |
| 275 | } |
| 276 | if len(pages) == 0 && len(results) == 0 { |
| 277 | return "", nil, wire.CodeNothingFound, nil |
| 278 | } |
| 279 | step, truncated := fitAnswerStep(wire.LookupStep{Person: r.call.Person, Lookup: r.row.ID, Attempt: int(r.row.Attempt), Stage: wire.LookupStageAnswer, Pack: pack, Results: results, Pages: pages, Truncated: true}) |
| 280 | step.Truncated = truncated |
| 281 | a, err := r.s.lookupStep(ctx, r.call.Person, step) |
| 282 | if err != nil || a.Code != "" || wire.ValidAnswerResult(a, len(results)) != nil { |
| 283 | return "", nil, wire.CodeLookupFailed, err |
| 284 | } |
| 285 | return a.Answer, lookupSources(pages, results, a.Used), wire.CodeLookupShown, nil |
| 286 | } |
| 287 | |
| 288 | // explicitAddr finds the addresses a person typed with a scheme, a port |
| 289 | // or an IP address: kept as typed, so the guarded client refuses what it |
| 290 | // must (scheme, port, IP literal, length) rather than the lookup reading |
| 291 | // something else. |
| 292 | var explicitAddr = regexp.MustCompile(`(?i)\b[a-z][a-z0-9+.-]{1,15}://[^\s<>"']+|\b(?:[a-z0-9-]+\.)+[a-z][a-z0-9-]*:\d{1,5}(?:/[^\s<>"']*)?|\b\d{1,3}(?:\.\d{1,3}){3}(?::\d{1,5})?(?:/[^\s<>"']*)?`) |
| 293 | |
| 294 | // typedAddresses are the addresses in the person's message, at most 3, |
| 295 | // in the order they were typed: those with a scheme, a port or an IP |
| 296 | // address as typed (https assumed when none), and the bare ones |
| 297 | // websource.Mentions finds, each address once. |
| 298 | func typedAddresses(text string) []string { |
| 299 | type hit struct { |
| 300 | at int |
| 301 | raw string |
| 302 | } |
| 303 | var hits []hit |
| 304 | var spans [][]int |
| 305 | for _, loc := range explicitAddr.FindAllStringIndex(text, -1) { |
| 306 | m := strings.TrimRight(text[loc[0]:loc[1]], ".,;:!?)]}'\"") |
| 307 | raw := m |
| 308 | if !strings.Contains(m, "://") { |
| 309 | raw = "https://" + m |
| 310 | } |
| 311 | hits, spans = append(hits, hit{loc[0], raw}), append(spans, loc) |
| 312 | } |
| 313 | inside := func(i int) bool { |
| 314 | return slices.ContainsFunc(spans, func(sp []int) bool { return i >= sp[0] && i < sp[1] }) |
| 315 | } |
| 316 | // A bare address with a query or fragment (Mentions stops before |
| 317 | // them), or too long for an address (Mentions leaves it out), is kept |
| 318 | // whole: read as typed, or refused, never shortened or searched. |
| 319 | for off := 0; off < len(text); { |
| 320 | i := strings.IndexFunc(text[off:], func(r rune) bool { return !unicode.IsSpace(r) }) |
| 321 | if i < 0 { |
| 322 | break |
| 323 | } |
| 324 | i += off |
| 325 | end := strings.IndexFunc(text[i:], unicode.IsSpace) |
| 326 | if end < 0 { |
| 327 | end = len(text) - i |
| 328 | } |
| 329 | tok := strings.TrimRight(text[i:i+end], ".,;:!)]}'\"") |
| 330 | off = i + end |
| 331 | cut := strings.IndexAny(tok, "/?#") |
| 332 | if cut <= 0 || inside(i) || strings.Contains(tok, "://") { |
| 333 | continue |
| 334 | } |
| 335 | host := tok[:cut] |
| 336 | if hostLike(host) && (len(tok) > guard.MaxURL || strings.ContainsAny(tok, "?#")) { |
| 337 | hits, spans = append(hits, hit{i, "https://" + tok}), append(spans, []int{i, i + len(tok)}) |
| 338 | } |
| 339 | } |
| 340 | lower := strings.ToLower(text) |
| 341 | used := map[int]bool{} |
| 342 | for _, u := range websource.Mentions(text) { |
| 343 | host := strings.ToLower(u.Host) |
| 344 | for off := 0; off < len(lower); { |
| 345 | i := strings.Index(lower[off:], host) |
| 346 | if i < 0 { |
| 347 | break |
| 348 | } |
| 349 | i += off |
| 350 | if !inside(i) && !used[i] { |
| 351 | used[i] = true |
| 352 | hits = append(hits, hit{i, u.String()}) |
| 353 | break |
| 354 | } |
| 355 | off = i + 1 |
| 356 | } |
| 357 | } |
| 358 | slices.SortStableFunc(hits, func(a, b hit) int { return a.at - b.at }) |
| 359 | var out []string |
| 360 | for _, h := range hits { |
| 361 | if !slices.Contains(out, h.raw) { |
| 362 | out = append(out, h.raw) |
| 363 | } |
| 364 | } |
| 365 | return out[:min(len(out), lookupReads)] |
| 366 | } |
| 367 | |
| 368 | // hostLike: host reads as a registered name (a dot, its last label with |
| 369 | // a letter), as an address the person typed would. |
| 370 | func hostLike(host string) bool { |
| 371 | dot := strings.LastIndexByte(host, '.') |
| 372 | return dot > 0 && dot < len(host)-1 && strings.IndexFunc(host[dot+1:], unicode.IsLetter) >= 0 && websource.CheckHost(strings.ToLower(host)) == nil |
| 373 | } |
| 374 | |
| 375 | // searchCtx carries the final check for each search request: the pace |
| 376 | // for the actual host, then the gate, right before it is sent. |
| 377 | func (r *lookupRun) searchCtx(ctx context.Context) context.Context { |
| 378 | return guard.WithBeforeHop(ctx, func(ctx context.Context, host string) error { |
| 379 | if err := r.s.lookups.pace.wait(ctx, host); err != nil { |
| 380 | return err |
| 381 | } |
| 382 | return assist.Gate(ctx, webLookupOp) |
| 383 | }) |
| 384 | } |
| 385 | |
| 386 | // read reads one page through the guarded client, every hop denied the |
| 387 | // lookup's hosts, paced and gated. A page that can't be read is skipped |
| 388 | // (nil), its rule noted; the gate refusing is the error. |
| 389 | func (r *lookupRun) read(ctx context.Context, raw string) (*wire.LookupPage, error) { |
| 390 | rd := lookupRead{URL: raw} |
| 391 | defer func() { r.reads = append(r.reads, rd) }() |
| 392 | u, err := url.Parse(raw) |
| 393 | if err != nil || len(raw) > guard.MaxURL { |
| 394 | rd.Code = guard.RuleURL |
| 395 | return nil, nil |
| 396 | } |
| 397 | if d := guard.Registrable(u.Hostname()); !slices.Contains(r.domains, d) { |
| 398 | r.domains = append(r.domains, d) |
| 399 | } |
| 400 | req, err := http.NewRequest(http.MethodGet, u.String(), nil) |
| 401 | if err != nil { |
| 402 | rd.Code = guard.RuleURL |
| 403 | return nil, nil |
| 404 | } |
| 405 | hctx := guard.WithBeforeHop(guard.WithDeny(ctx, r.deny), func(ctx context.Context, host string) error { |
| 406 | if err := r.s.lookups.pace.wait(ctx, host); err != nil { |
| 407 | return err |
| 408 | } |
| 409 | return assist.Gate(ctx, webLookupOp) |
| 410 | }) |
| 411 | res, err := r.cfg.Pages.Do(hctx, req) |
| 412 | if err != nil { |
| 413 | var refusal assist.Refusal |
| 414 | if errors.As(err, &refusal) { |
| 415 | rd.Code = refusal.Code |
| 416 | return nil, refusal |
| 417 | } |
| 418 | rd.Code = guard.RuleOf(err) |
| 419 | if rd.Code == "" { |
| 420 | rd.Code = guard.RuleUnavailable |
| 421 | } |
| 422 | return nil, nil |
| 423 | } |
| 424 | sum := sha256.Sum256(res.Body) |
| 425 | rd.FinalURL, rd.Status, rd.Bytes, rd.SHA256 = res.FinalURL, res.Status, len(res.Body), hex.EncodeToString(sum[:]) |
| 426 | if res.Status != http.StatusOK { |
| 427 | rd.Code = "status" |
| 428 | return nil, nil |
| 429 | } |
| 430 | base, err := websource.Parse(res.FinalURL) |
| 431 | if err != nil { |
| 432 | rd.Code = guard.RuleURL |
| 433 | return nil, nil |
| 434 | } |
| 435 | title, text := websource.Readable(res.Body, res.Type, base) |
| 436 | if strings.TrimSpace(text) == "" { |
| 437 | rd.Code = "unsupported_type" |
| 438 | return nil, nil |
| 439 | } |
| 440 | return &wire.LookupPage{URL: res.FinalURL, Title: title, Text: cutRunes(text, lookupPageText)}, nil |
| 441 | } |
| 442 | |
| 443 | // fitAnswerStep cuts the answer step to the runner's frame budget (§4.3): |
| 444 | // each page at most 16 KiB, then the lowest-ranked page's text first |
| 445 | // until the whole fits. truncated says it was cut. |
| 446 | func fitAnswerStep(s wire.LookupStep) (wire.LookupStep, bool) { |
| 447 | truncated := false |
| 448 | // Sized as sent: with the nonce the live channel adds (room kept). |
| 449 | limit := wire.MaxLookupStepBytes - lookupNonceRoom |
| 450 | size := func() int { raw, _ := json.Marshal(s); return len(raw) } |
| 451 | for i := len(s.Pages) - 1; i >= 0 && size() > limit; i-- { |
| 452 | over := size() - limit |
| 453 | text := s.Pages[i].Text |
| 454 | s.Pages[i].Text = cutRunes(text, len(text)-over-64) |
| 455 | truncated = true |
| 456 | } |
| 457 | for size() > limit && len(s.Results) > 0 { |
| 458 | s.Results = s.Results[:len(s.Results)-1] |
| 459 | truncated = true |
| 460 | } |
| 461 | for size() > limit && len(s.Pages) > 0 { |
| 462 | s.Pages = s.Pages[:len(s.Pages)-1] |
| 463 | truncated = true |
| 464 | } |
| 465 | return s, truncated |
| 466 | } |
| 467 | |
| 468 | // lookupNonceRoom is the room kept for the nonce the live channel adds. |
| 469 | const lookupNonceRoom = 128 |
| 470 | |
| 471 | // lookupSources are the pages read, or else the results the answer used: |
| 472 | // https only, at most 5. |
| 473 | func lookupSources(pages []wire.LookupPage, results []wire.SearchResult, used []int) []wire.LookupSource { |
| 474 | var out []wire.LookupSource |
| 475 | add := func(u, title string) { |
| 476 | if len(out) < wire.MaxLookupSources && strings.HasPrefix(u, "https://") && !slices.ContainsFunc(out, func(s wire.LookupSource) bool { return s.URL == u }) { |
| 477 | out = append(out, wire.LookupSource{URL: u, Title: cutRunes(strings.TrimSpace(title), 200)}) |
| 478 | } |
| 479 | } |
| 480 | for _, p := range pages { |
| 481 | add(p.URL, p.Title) |
| 482 | } |
| 483 | if len(out) == 0 { |
| 484 | for _, i := range used { |
| 485 | if i >= 0 && i < len(results) { |
| 486 | add(results[i].URL, results[i].Title) |
| 487 | } |
| 488 | } |
| 489 | } |
| 490 | return out |
| 491 | } |
| 492 | |
| 493 | // finish stores the lookup's outcome and audits it: the person, the |
| 494 | // numbers of queries and reads, the hosts' registrable domains, the code. |
| 495 | // Never a query, a path or the answer. |
| 496 | func (r *lookupRun) finish(ctx context.Context, answer string, sources []wire.LookupSource, code string) error { |
| 497 | queries, _ := json.Marshal(r.queries) |
| 498 | reads, _ := json.Marshal(r.reads) |
| 499 | src, _ := json.Marshal(sources) |
| 500 | r.row.Queries, r.row.Reads, r.row.Code = string(queries), string(reads), code |
| 501 | r.row.State = lookupFailed |
| 502 | if code == wire.CodeLookupShown && answer != "" && len(sources) > 0 { |
| 503 | r.row.State, r.row.Answer, r.row.Sources = lookupShown, answer, string(src) |
| 504 | } else if code == wire.CodeLookupShown { |
| 505 | r.row.Code = wire.CodeNothingFound |
| 506 | } |
| 507 | err := r.s.tx(ctx, func(t *txn) error { |
| 508 | t.db = quietDB(t.db) |
| 509 | if err := t.db.Model(&lookupRecord{}).Where("id = ?", r.row.ID).Select("state", "queries", "reads", "answer", "sources", "code").Updates(&r.row).Error; err != nil { |
| 510 | return err |
| 511 | } |
| 512 | if t.s.authority.Audit == nil { |
| 513 | return nil |
| 514 | } |
| 515 | return t.s.authority.Audit(t.db, r.call.Person, auditLookup, "queries="+strconv.Itoa(len(r.queries))+" reads="+strconv.Itoa(len(r.reads))+" domains="+strings.Join(r.domains, ",")+" code="+r.row.Code) |
| 516 | }) |
| 517 | if err != nil { |
| 518 | // Never the error itself: it may quote what was being written. |
| 519 | if l := r.s.logger.Load(); l != nil { |
| 520 | l.Warn("lookup not stored", "call", r.call.CallID) |
| 521 | } |
| 522 | r.row.State = lookupFailed |
| 523 | } |
| 524 | return err |
| 525 | } |
| 526 | |
| 527 | // lookupDeny is the person's own hosts no lookup may reach: the |
| 528 | // addresses of their Base's apps and Oficina apps (base_apps, read on a |
| 529 | // gate of its own), cached for 60 s and kept for at most 10 minutes. With |
| 530 | // none to be had, the lookup fails. |
| 531 | func (s *Store) lookupDeny(ctx context.Context, person string) ([]string, error) { |
| 532 | now := time.Now() |
| 533 | s.lookups.mu.Lock() |
| 534 | cached, ok := s.lookups.deny[person] |
| 535 | s.lookups.mu.Unlock() |
| 536 | if ok && now.Sub(cached.at) < lookupDenyFresh { |
| 537 | return cached.hosts, nil |
| 538 | } |
| 539 | hosts, err := s.baseAppOrigins(ctx, person) |
| 540 | if err != nil { |
| 541 | if ok && now.Sub(cached.at) < lookupDenyKeep { |
| 542 | return cached.hosts, nil |
| 543 | } |
| 544 | return nil, err |
| 545 | } |
| 546 | s.lookups.mu.Lock() |
| 547 | if s.lookups.deny == nil { |
| 548 | s.lookups.deny = map[string]denyEntry{} |
| 549 | } |
| 550 | s.lookups.deny[person] = denyEntry{hosts: hosts, at: now} |
| 551 | s.lookups.mu.Unlock() |
| 552 | return hosts, nil |
| 553 | } |
| 554 | |
| 555 | // baseAppOrigins are the hosts of the person's apps as their Base reports |
| 556 | // them (base_apps): an instance-owned read on its own gate. |
| 557 | func (s *Store) baseAppOrigins(ctx context.Context, person string) ([]string, error) { |
| 558 | ops := s.operations() |
| 559 | if ops == nil { |
| 560 | return nil, errors.New("lookup: no operations") |
| 561 | } |
| 562 | op, err := ops.Describe(ctx, person, "base_apps") |
| 563 | if err != nil { |
| 564 | return nil, err |
| 565 | } |
| 566 | raw, err := ops.Invoke(assist.WithGate(ctx, s.sendGate(ctx, person, op)), person, "base_apps", json.RawMessage(`{}`), "") |
| 567 | if err != nil { |
| 568 | return nil, err |
| 569 | } |
| 570 | // Both lists must be there (an empty one is fine) and every address |
| 571 | // readable: anything less is no list at all, and the lookup fails. |
| 572 | type app struct { |
| 573 | Address *string `json:"address"` |
| 574 | } |
| 575 | var apps struct { |
| 576 | Installed *[]app `json:"installed"` |
| 577 | Oficina *[]app `json:"oficina"` |
| 578 | } |
| 579 | if err := json.Unmarshal(raw, &apps); err != nil || apps.Installed == nil || apps.Oficina == nil { |
| 580 | return nil, errors.New("lookup: base_apps not understood") |
| 581 | } |
| 582 | hosts := []string{} |
| 583 | for _, a := range append(append([]app{}, *apps.Installed...), *apps.Oficina...) { |
| 584 | if a.Address == nil { |
| 585 | return nil, errors.New("lookup: base_apps not understood") |
| 586 | } |
| 587 | u, err := url.Parse(strings.TrimSpace(*a.Address)) |
| 588 | if err != nil || u.Hostname() == "" || u.Scheme != "https" && u.Scheme != "http" { |
| 589 | return nil, errors.New("lookup: base_apps not understood") |
| 590 | } |
| 591 | if h := strings.ToLower(u.Hostname()); !slices.Contains(hosts, h) { |
| 592 | hosts = append(hosts, h) |
| 593 | } |
| 594 | } |
| 595 | return hosts, nil |
| 596 | } |
| 597 | |