oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package chat
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
9 "log/slog"
10 "mime"
11 "net/http"
12 "strconv"
13 "strings"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/equipo/personapi"
17 "amadan.net/oficina/equipo/internal/wire"
18 "github.com/go-chi/chi/v5"
19)
20
21// HTTP serves person API v1 conversation routes and the runner stream.
22type HTTP struct {
23 Store *Store
24 // Authenticate verifies a bearer or session cookie, the roster and the
25 // request origin. The chat routes below decide which of the two to accept.
26 Authenticate func(*http.Request) (personapi.PersonPrincipal, error)
27 // AuthenticateRunner verifies a runner bearer token.
28 AuthenticateRunner func(context.Context, string) (RunnerPrincipal, error)
29 // Failure writes the standard error for an authentication failure.
30 Failure func(http.ResponseWriter, *http.Request, error)
31 Logger *slog.Logger
32 // Old are the earlier person API's handlers by "METHOD /path": the
33 // thin task routes share three paths with them and hand over requests
34 // that are not for a thin task until the slice 7 sweep.
35 Old map[string]http.Handler
36 // OficinaConnect starts the person's consent to connect their Oficina
37 // apps, their browser coming back to returnTo after: the address to
38 // send it to. Nil when the instance has no oficina-connect.
39 OficinaConnect func(ctx context.Context, person, returnTo string) (string, error)
40 // OficinaFinish finishes the person's consent with the state and code
41 // connect's callback handed back: a status (connected, denied,
42 // expired, unavailable), or ErrForbidden when the consent was another
43 // person's.
44 OficinaFinish func(ctx context.Context, person, state, code string) (string, error)
45 // OficinaCatchUp settles an Oficina connect card left open for a
46 // person who is connected (a finish whose settlement failed), when
47 // Base reads the Assistant lane. Nil without oficina-connect.
48 OficinaCatchUp func(ctx context.Context, person string) error
49}
50
51// thinOr serves thin when it applies to the request, else the earlier
52// handler for the same route.
53func (h *HTTP) thinOr(route string, thin func(*http.Request) bool, next http.HandlerFunc) http.HandlerFunc {
54 return func(w http.ResponseWriter, r *http.Request) {
55 if old, ok := h.Old[route]; ok && !thin(r) {
56 old.ServeHTTP(w, r)
57 return
58 }
59 next(w, r)
60 }
61}
62
63// thinTask: thin task ids start "tk"; the old engine's are upper case.
64func thinTask(r *http.Request) bool { return strings.HasPrefix(chi.URLParam(r, "id"), "tk") }
65
66// thinQuestion: thin question ids start "q_"; the old engine's questions
67// keep their route until the slice 7 sweep.
68func thinQuestion(r *http.Request) bool { return strings.HasPrefix(chi.URLParam(r, "id"), "q_") }
69
70// deviceClient: the task list for a device bearer (native apps, the
71// headless suite) is the thin one; a browser session reads the old list.
72func deviceClient(r *http.Request) bool { return len(r.Header.Values("Authorization")) > 0 }
73
74// Mount adds the routes to the person API v1 router.
75func (h *HTTP) Mount(r chi.Router) {
76 r.Get("/messages", h.bearer(h.messages))
77 r.Post("/messages", h.bearer(h.send))
78 r.Post("/attachments", h.bearer(h.upload))
79 r.Delete("/attachments/{id}", h.bearer(h.deleteUpload))
80 r.Get("/attachments/{id}", h.bearer(h.attachment(false)))
81 r.Get("/attachments/{id}/preview", h.bearer(h.attachment(true)))
82 r.Get("/turns/{id}", h.bearer(h.turn))
83 r.Post("/turns/{id}/cancel", h.bearer(h.cancel))
84 r.Post("/turns/{id}/retry", h.bearer(h.retry))
85 r.Get("/snapshot", h.bearer(h.snapshot))
86 r.Get("/projects", h.bearer(h.projects))
87 r.Put("/projects/{id}/star", h.bearer(h.projectStar))
88 r.Put("/projects/{id}/details", h.bearer(h.projectDetails))
89 r.Delete("/projects/{id}/names", h.bearer(h.projectForgetName))
90 r.Post("/projects", h.bearer(h.addProject))
91 r.Delete("/projects/{id}", h.bearer(h.removeProject))
92 r.Get("/cards/{id}", h.thinOr("GET /cards/{id}", thinCard, h.bearer(h.card)))
93 r.Post("/cards/{id}/answer", h.bearer(h.answer))
94 r.Post("/cards/{id}/visibility", h.bearer(h.cardVisibility))
95 r.Post("/push-registrations", h.bearer(h.registerPush))
96 r.Post("/push-registrations/activities", h.bearer(h.registerActivity))
97 r.Get("/notebook", h.bearer(h.notebook))
98 r.Post("/notebook/reset", h.bearer(h.resetNotebook))
99 r.Delete("/notebook/corrections/{id}", h.bearer(h.removePlacementNote))
100 r.Get("/tasks", h.thinOr("GET /tasks", deviceClient, h.bearer(h.tasks)))
101 r.Get("/tasks/{id}", h.thinOr("GET /tasks/{id}", thinTask, h.bearer(h.task)))
102 r.Post("/tasks/{id}/cancel", h.thinOr("POST /tasks/{id}/cancel", thinTask, h.bearer(h.cancelTask)))
103 r.Post("/tasks/{id}/retry", h.bearer(h.retryTask))
104 r.Post("/tasks/{id}/move", h.bearer(h.moveTask))
105 r.Put("/tasks/{id}/priority", h.bearer(h.setPriority))
106 r.Post("/tasks/{id}/run-now", h.bearer(h.runNow))
107 r.Post("/tasks/{id}/kind", h.bearer(h.setKind))
108 r.Post("/tasks/{id}/round", h.bearer(h.roundTask))
109 r.Post("/tasks/{id}/recover", h.bearer(h.recoverTask))
110 r.Post("/tasks/{id}/duplicate", h.bearer(h.markDuplicate))
111 r.Post("/tasks/{id}/merge", h.bearer(h.mergeTask))
112 r.Post("/tasks/{id}/undo-merge", h.bearer(h.undoMerge))
113 r.Get("/projects/{id}/merge-policy", h.bearer(h.mergePolicy))
114 r.Put("/projects/{id}/merge-policy", h.bearer(h.setMergePolicy))
115 r.Post("/tasks/{id}/uncombine", h.bearer(h.uncombineTask))
116 r.Post("/tasks/{id}/thread", h.bearer(h.postThread))
117 r.Get("/tasks/{id}/files/{file}", h.bearer(h.taskFile))
118 r.Get("/tasks/{id}/changes/diff", h.bearer(h.changeDiff))
119 r.Get("/steps/{id}/log", h.bearer(h.stepLog))
120 r.Post("/tasks/{id}/questions", h.bearer(h.ask))
121 r.Get("/questions/{id}", h.thinOr("GET /questions/{id}", thinQuestion, h.bearer(h.question)))
122 r.Post("/questions/{id}/cancel", h.bearer(h.cancelQuestion))
123 r.Get("/needs-you", h.thinOr("GET /needs-you", deviceClient, h.bearer(h.needsYou)))
124 r.Get("/runners", h.thinOr("GET /runners", deviceClient, h.bearer(h.runners)))
125 r.Get("/connections", h.thinOr("GET /connections", deviceClient, h.bearer(h.connections)))
126 r.Post("/connections", h.bearer(h.connect))
127 r.Get("/connections/{id}", h.thinOr("GET /connections/{id}", thinConnection, h.bearer(h.connection)))
128 r.Post("/connections/{id}/cancel", h.bearer(h.cancelConnection))
129 r.Post("/connections/{id}/secret", h.bearer(h.secret))
130 r.Delete("/connections/{id}", h.thinOr("DELETE /connections/{id}", thinConnection, h.bearer(h.signOut)))
131 r.Post("/connections/{id}/forget", h.bearer(h.forget))
132 r.Post("/connections/{id}/check", h.bearer(h.checkConnection))
133 r.Post("/connections/{id}/model", h.bearer(h.chooseModel))
134 r.Put("/connections/{id}/budget", h.bearer(h.setBudget))
135 r.Put("/connections/{id}/models", h.bearer(h.setModels))
136 r.Post("/connections/{id}/resume", h.bearer(h.resumeSpend))
137 r.Get("/thinking", h.bearer(h.thinking))
138 r.Put("/thinking", h.bearer(h.setThinking))
139 r.Get("/connections/preference", h.bearer(h.preferences))
140 r.Put("/connections/preference", h.bearer(h.setPreferences))
141 r.Put("/time-zone", h.bearer(h.setZone))
142 // The team's data-defined specialists. The list shares its path with
143 // the earlier person API's, which a browser session still reads.
144 r.Get("/specialists", h.thinOr("GET /specialists", deviceClient, h.bearer(h.specialists)))
145 r.Post("/specialists/{id}/revoke", h.bearer(h.revokeSpecialist))
146 h.mountHousekeeping(r)
147 h.mountUsage(r)
148 r.Get("/events", h.events)
149 r.Route("/assistant", h.MountAssistant)
150}
151
152// thinConnection: thin connection ids start "cn_".
153func thinConnection(r *http.Request) bool { return strings.HasPrefix(chi.URLParam(r, "id"), "cn_") }
154
155func (h *HTTP) connections(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
156 out, err := h.Store.Connections(r.Context(), p.Address)
157 if err != nil {
158 h.fail(w, r, err)
159 return
160 }
161 writeJSON(w, 200, wire.ConnectionList{Items: out})
162}
163
164func (h *HTTP) connection(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
165 out, err := h.Store.Connection(r.Context(), p.Address, chi.URLParam(r, "id"))
166 if err != nil {
167 h.fail(w, r, err)
168 return
169 }
170 writeJSON(w, 200, out)
171}
172
173// connect is POST /api/v1/connections: 202 with the attempt connecting.
174func (h *HTTP) connect(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
175 var in wire.Connect
176 if err := readJSON(r, &in); err != nil {
177 h.fail(w, r, err)
178 return
179 }
180 out, err := h.Store.StartConnection(r.Context(), p.Address, in)
181 if err != nil {
182 h.fail(w, r, err)
183 return
184 }
185 writeJSON(w, http.StatusAccepted, out)
186}
187
188// signOut is DELETE /api/v1/connections/{id}: 202, signed out once the
189// runner reports it.
190func (h *HTTP) signOut(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
191 out, err := h.Store.SignOut(r.Context(), p.Address, chi.URLParam(r, "id"))
192 if err != nil {
193 h.fail(w, r, err)
194 return
195 }
196 writeJSON(w, http.StatusAccepted, out)
197}
198
199// checkConnection is POST /api/v1/connections/{id}/check: 202, the
200// runner checks it; the state follows in the stream.
201func (h *HTTP) checkConnection(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
202 if err := h.Store.CheckConnection(r.Context(), p.Address, chi.URLParam(r, "id")); err != nil {
203 h.fail(w, r, err)
204 return
205 }
206 w.WriteHeader(http.StatusAccepted)
207}
208
209// forget is POST /api/v1/connections/{id}/forget: a signed-out record,
210// or an attempt that ended, goes from the list (204).
211func (h *HTTP) forget(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
212 if err := h.Store.Forget(r.Context(), p.Address, chi.URLParam(r, "id")); err != nil {
213 h.fail(w, r, err)
214 return
215 }
216 w.WriteHeader(http.StatusNoContent)
217}
218
219// thinking is GET /api/v1/thinking: the person's thinking words.
220func (h *HTTP) thinking(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
221 out, err := h.Store.Thinking(r.Context(), p.Address)
222 if err != nil {
223 h.fail(w, r, err)
224 return
225 }
226 writeJSON(w, 200, out)
227}
228
229// setThinking is PUT /api/v1/thinking {set, revision}: 409 when the
230// revision moved.
231func (h *HTTP) setThinking(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
232 var in wire.ThinkingChoice
233 if err := readJSON(r, &in); err != nil {
234 h.fail(w, r, err)
235 return
236 }
237 out, err := h.Store.SetThinking(r.Context(), p.Address, in)
238 if err != nil {
239 h.fail(w, r, err)
240 return
241 }
242 writeJSON(w, 200, out)
243}
244
245func (h *HTTP) preferences(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
246 out, err := h.Store.Preference(r.Context(), p.Address)
247 if err != nil {
248 h.fail(w, r, err)
249 return
250 }
251 writeJSON(w, 200, out)
252}
253
254// setPreferences is PUT /api/v1/connections/preference {provider, revision}: 409
255// when the revision moved.
256func (h *HTTP) setPreferences(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
257 var in wire.Preferences
258 if err := readJSON(r, &in); err != nil {
259 h.fail(w, r, err)
260 return
261 }
262 out, err := h.Store.SetPreference(r.Context(), p.Address, in)
263 if err != nil {
264 h.fail(w, r, err)
265 return
266 }
267 writeJSON(w, 200, out)
268}
269
270// secret is POST /api/v1/connections/{id}/secret: a token attempt's
271// sealed secret (wire.Sealed), 202 with the attempt waiting for its
272// runner. The box is never echoed.
273func (h *HTTP) secret(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
274 var in wire.Sealed
275 if err := readJSON(r, &in); err != nil {
276 h.fail(w, r, err)
277 return
278 }
279 out, err := h.Store.SendSecret(r.Context(), p.Address, chi.URLParam(r, "id"), in)
280 if err != nil {
281 h.fail(w, r, err)
282 return
283 }
284 writeJSON(w, http.StatusAccepted, out)
285}
286
287// chooseModel is POST /api/v1/connections/{id}/model {model}: the
288// connecting card's pick, from the list the runner read.
289func (h *HTTP) chooseModel(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
290 var in wire.ChooseModel
291 if err := readJSON(r, &in); err != nil {
292 h.fail(w, r, err)
293 return
294 }
295 out, err := h.Store.ChooseModel(r.Context(), p.Address, chi.URLParam(r, "id"), in)
296 if err != nil {
297 h.fail(w, r, err)
298 return
299 }
300 writeJSON(w, http.StatusAccepted, out)
301}
302
303// setBudget is PUT /api/v1/connections/{id}/budget {day, month,
304// revision}: 202, applied when the runner confirms (budget_pending until
305// then); 409 when the revision moved.
306func (h *HTTP) setBudget(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
307 var in wire.SetBudget
308 if err := readJSON(r, &in); err != nil {
309 h.fail(w, r, err)
310 return
311 }
312 out, err := h.Store.SetBudget(r.Context(), p.Address, chi.URLParam(r, "id"), in)
313 if err != nil {
314 h.fail(w, r, err)
315 return
316 }
317 writeJSON(w, http.StatusAccepted, out)
318}
319
320// setModels is PUT /api/v1/connections/{id}/models {allowed, revision}
321// (connectors spec rev 3.3 §16.1): 202, applied when the runner
322// confirms (models_pending until then); 409 when the revision moved or
323// the runner is too old to change the set; 422 when a model cannot be
324// allowed or none is.
325func (h *HTTP) setModels(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
326 var in wire.SetModels
327 if err := readJSON(r, &in); err != nil {
328 h.fail(w, r, err)
329 return
330 }
331 out, err := h.Store.SetModels(r.Context(), p.Address, chi.URLParam(r, "id"), in)
332 if err != nil {
333 h.fail(w, r, err)
334 return
335 }
336 writeJSON(w, http.StatusAccepted, out)
337}
338
339// resumeSpend is POST /api/v1/connections/{id}/resume {pause_revision}:
340// 202; 409 when that pause is not the connection's now.
341func (h *HTTP) resumeSpend(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
342 var in wire.ResumeSpend
343 if err := readJSON(r, &in); err != nil {
344 h.fail(w, r, err)
345 return
346 }
347 if err := h.Store.ResumeSpend(r.Context(), p.Address, chi.URLParam(r, "id"), in); err != nil {
348 h.fail(w, r, err)
349 return
350 }
351 w.WriteHeader(http.StatusAccepted)
352}
353
354func (h *HTTP) cancelConnection(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
355 out, err := h.Store.CancelConnection(r.Context(), p.Address, chi.URLParam(r, "id"))
356 if err != nil {
357 h.fail(w, r, err)
358 return
359 }
360 writeJSON(w, 200, out)
361}
362
363type handler func(http.ResponseWriter, *http.Request, personapi.PersonPrincipal)
364
365// bearer admits device bearers only; web pages call the store server side.
366func (h *HTTP) bearer(next handler) http.HandlerFunc {
367 return func(w http.ResponseWriter, r *http.Request) {
368 w.Header().Set("Cache-Control", "no-store")
369 if len(r.Header.Values("Authorization")) == 0 {
370 personapi.WriteError(w, r, http.StatusUnauthorized, "unauthenticated", nil)
371 return
372 }
373 p, err := h.Authenticate(r)
374 if err != nil {
375 h.Failure(w, r, err)
376 return
377 }
378 next(w, r.WithContext(personapi.WithVerifiedPrincipal(r.Context(), p)), p)
379 }
380}
381
382func writeJSON(w http.ResponseWriter, status int, v any) {
383 w.Header().Set("Content-Type", "application/json")
384 w.WriteHeader(status)
385 _ = json.NewEncoder(w).Encode(v)
386}
387
388func (h *HTTP) fail(w http.ResponseWriter, r *http.Request, err error) {
389 switch {
390 case errors.Is(err, ErrInvalid):
391 personapi.WriteError(w, r, 422, "invalid_input", nil)
392 case errors.Is(err, ErrNotFound):
393 personapi.WriteError(w, r, 404, "not_found", nil)
394 case errors.Is(err, ErrConflict):
395 personapi.WriteError(w, r, 409, "idempotency_conflict", nil)
396 case errors.Is(err, ErrExpired):
397 personapi.WriteError(w, r, 410, "cursor_expired", nil)
398 case errors.Is(err, ErrNotAllowed):
399 personapi.WriteError(w, r, 422, "repo_not_allowed", nil)
400 case errors.Is(err, ErrForbidden):
401 personapi.WriteError(w, r, 403, "forbidden", nil)
402 case errors.Is(err, ErrAbilityOff):
403 personapi.WriteError(w, r, 403, "ability_off", nil)
404 case errors.Is(err, ErrBusy):
405 personapi.WriteError(w, r, 409, "coordinator_busy", nil)
406 case errors.Is(err, ErrTaskEnded):
407 personapi.WriteError(w, r, 409, "task_ended", nil)
408 case errors.Is(err, ErrTaskBusy):
409 personapi.WriteError(w, r, 409, "task_busy", nil)
410 case errors.Is(err, ErrNotRetryable):
411 personapi.WriteError(w, r, 409, "not_retryable", nil)
412 case errors.Is(err, ErrNotMergeable):
413 personapi.WriteError(w, r, 409, "not_mergeable", nil)
414 case errors.Is(err, ErrNotUndoable):
415 personapi.WriteError(w, r, 409, "not_undoable", nil)
416 case errors.Is(err, ErrMerging):
417 personapi.WriteError(w, r, 409, "task_merging", nil)
418 case errors.Is(err, ErrNotAskable):
419 personapi.WriteError(w, r, 409, "not_askable", nil)
420 case errors.Is(err, ErrRunnerOffline):
421 personapi.WriteError(w, r, 409, "runner_offline", nil)
422 case errors.Is(err, ErrConfirmation):
423 personapi.WriteError(w, r, 422, "confirmation_required", nil)
424 case errors.Is(err, ErrHoldBar):
425 personapi.WriteError(w, r, http.StatusConflict, "hold_bar", nil)
426 case errors.Is(err, ErrAlreadyReleased):
427 personapi.WriteError(w, r, http.StatusConflict, "already_running", nil)
428 case errors.Is(err, ErrOfferChanged):
429 personapi.WriteError(w, r, http.StatusConflict, "offer_changed", nil)
430 case errors.Is(err, ErrRunnerTooOld):
431 personapi.WriteError(w, r, 409, "runner_too_old", nil)
432 case errors.Is(err, ErrNoRunner):
433 personapi.WriteError(w, r, 409, "no_runner", nil)
434 case errors.Is(err, ErrAttachmentsUnavailable):
435 personapi.WriteError(w, r, 409, "attachments_unavailable", nil)
436 case errors.Is(err, ErrAttachmentSent):
437 personapi.WriteError(w, r, 409, "attachment_sent", nil)
438 case errors.Is(err, ErrModelsNotAllowed):
439 personapi.WriteError(w, r, 422, "models_not_allowed", nil)
440 case errors.Is(err, ErrActionConflict):
441 personapi.WriteError(w, r, 409, "not_undoable", nil)
442 case errors.Is(err, ErrRevision):
443 personapi.WriteError(w, r, 409, "revision_conflict", nil)
444 case errors.Is(err, ErrNotActive):
445 personapi.WriteError(w, r, 409, "not_active", nil)
446 case errors.Is(err, ErrAttachmentTooLarge):
447 personapi.WriteError(w, r, http.StatusRequestEntityTooLarge, "attachment_too_large", nil)
448 case errors.Is(err, ErrAttachmentType):
449 personapi.WriteError(w, r, http.StatusUnsupportedMediaType, "attachment_type", nil)
450 case errors.Is(err, ErrAttachmentHEIC):
451 personapi.WriteError(w, r, http.StatusUnsupportedMediaType, "attachment_heic", nil)
452 case errors.Is(err, ErrAttachmentPixels):
453 personapi.WriteError(w, r, http.StatusRequestEntityTooLarge, "attachment_pixels", nil)
454 case errors.Is(err, ErrAttachmentLimit):
455 personapi.WriteError(w, r, 409, "attachment_limit", nil)
456 default:
457 h.Failure(w, r, err)
458 }
459}
460
461func (h *HTTP) send(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
462 h.sendWith(w, r, p, h.Store.Send)
463}
464
465// sendWith is POST messages in a lane: 201 for a new message, 200 for
466// the same key and text again.
467func (h *HTTP) sendWith(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal, send func(context.Context, string, wire.SendMessage) (wire.Sent, bool, error)) {
468 media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
469 var in wire.SendMessage
470 if err == nil && media == "application/json" {
471 raw, e := io.ReadAll(io.LimitReader(r.Body, 2*wire.MaxMessageBytes+1))
472 if e != nil || len(raw) > 2*wire.MaxMessageBytes {
473 err = ErrInvalid
474 } else {
475 err = wire.Strict(raw, &in)
476 }
477 }
478 if err != nil || media != "application/json" {
479 h.fail(w, r, ErrInvalid)
480 return
481 }
482 out, created, err := send(r.Context(), p.Address, in)
483 if err != nil {
484 h.fail(w, r, err)
485 return
486 }
487 status := http.StatusOK
488 if created {
489 status = http.StatusCreated
490 }
491 writeJSON(w, status, out)
492}
493
494// readJSON strictly decodes a small JSON body.
495func readJSON(r *http.Request, v any) error {
496 media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
497 if err != nil || media != "application/json" {
498 return ErrInvalid
499 }
500 raw, err := io.ReadAll(io.LimitReader(r.Body, 2*wire.MaxMessageBytes+1))
501 if err != nil || len(raw) > 2*wire.MaxMessageBytes || wire.Strict(raw, v) != nil {
502 return ErrInvalid
503 }
504 return nil
505}
506
507func (h *HTTP) projects(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
508 out, err := h.Store.Projects(r.Context(), p.Address)
509 if err != nil {
510 h.fail(w, r, err)
511 return
512 }
513 writeJSON(w, 200, out)
514}
515
516func (h *HTTP) addProject(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
517 var in wire.AddProject
518 if err := readJSON(r, &in); err != nil {
519 h.fail(w, r, err)
520 return
521 }
522 out, created, err := h.Store.AddProject(r.Context(), p.Address, in.Repo)
523 if err != nil {
524 h.fail(w, r, err)
525 return
526 }
527 status := http.StatusOK
528 if created {
529 status = http.StatusCreated
530 }
531 writeJSON(w, status, out)
532}
533
534func (h *HTTP) removeProject(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
535 out, err := h.Store.RemoveProject(r.Context(), p.Address, chi.URLParam(r, "id"))
536 if err != nil {
537 h.fail(w, r, err)
538 return
539 }
540 writeJSON(w, 200, out)
541}
542
543func (h *HTTP) answer(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
544 var in wire.AnswerCard
545 if err := readJSON(r, &in); err != nil {
546 h.fail(w, r, err)
547 return
548 }
549 out, current, err := h.Store.AnswerDevice(r.Context(), p.Address, p.CredentialID, chi.URLParam(r, "id"), in)
550 if errors.Is(err, ErrCardConflict) {
551 // A card the person can still act on was only stale; one that is
552 // done (answered, changed, removed) is answered.
553 code := "card_answered"
554 switch current.State {
555 case wire.CardOpen, wire.CardAdded, wire.CardWorking, wire.CardCreated, wire.CardHomeSet, wire.CardHomeAsk:
556 code = "card_stale"
557 }
558 if errors.Is(err, ErrDirectionNote) {
559 // Build this needs the person's note saying which option
560 // (wire.ConflictDirectionNote, a literal for the copy scan).
561 code = "direction_note"
562 }
563 writeJSON(w, http.StatusConflict, wire.CardConflict{Code: code, CopyKey: "api." + code, RequestID: r.Header.Get("Idempotency-Key"), Card: current})
564 return
565 }
566 if err != nil {
567 h.fail(w, r, err)
568 return
569 }
570 writeJSON(w, 200, out)
571}
572
573func (h *HTTP) messages(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
574 h.messagesWith(w, r, p, h.Store.Messages)
575}
576
577// messagesWith is GET messages?before=&limit= in a lane.
578func (h *HTTP) messagesWith(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal, page func(context.Context, string, string, int) (wire.MessagePage, error)) {
579 limit := 50
580 if v := r.URL.Query().Get("limit"); v != "" {
581 n, err := strconv.Atoi(v)
582 if err != nil || n < 1 || n > 200 {
583 h.fail(w, r, ErrInvalid)
584 return
585 }
586 limit = n
587 }
588 out, err := page(r.Context(), p.Address, r.URL.Query().Get("before"), limit)
589 if err != nil {
590 h.fail(w, r, err)
591 return
592 }
593 writeJSON(w, 200, out)
594}
595
596func (h *HTTP) turn(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
597 out, err := h.Store.Turn(r.Context(), p.Address, chi.URLParam(r, "id"))
598 if err != nil {
599 h.fail(w, r, err)
600 return
601 }
602 writeJSON(w, 200, out)
603}
604
605func (h *HTTP) cancel(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
606 h.cancelWith(w, r, p, h.Store.Cancel)
607}
608
609// retry is POST /turns/{id}/retry (Try again): 202 with the turn that
610// answers the failed turn's messages again, the same turn when asked
611// again; 409 not_retryable when the turn cannot be tried again.
612func (h *HTTP) retry(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
613 out, err := h.Store.Retry(r.Context(), p.Address, chi.URLParam(r, "id"))
614 if err != nil {
615 h.fail(w, r, err)
616 return
617 }
618 writeJSON(w, http.StatusAccepted, out)
619}
620
621// cancelWith is POST turns/{id}/cancel in a lane: 202, or 409 turn_ended.
622func (h *HTTP) cancelWith(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal, cancel func(context.Context, string, string) (int64, wire.Turn, error)) {
623 attempt, current, err := cancel(r.Context(), p.Address, chi.URLParam(r, "id"))
624 if errors.Is(err, ErrTerminal) {
625 personapi.WriteError(w, r, 409, "turn_ended", &current.Revision)
626 return
627 }
628 if err != nil {
629 h.fail(w, r, err)
630 return
631 }
632 writeJSON(w, http.StatusAccepted, wire.CancelAccepted{Attempt: attempt})
633}
634
635func (h *HTTP) snapshot(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
636 out, err := h.Store.Snapshot(r.Context(), p.Address)
637 if err != nil {
638 h.fail(w, r, err)
639 return
640 }
641 writeJSON(w, 200, out)
642}
643
644// streamPoll covers writes made by another process during a deploy overlap.
645const streamPoll = time.Second
646
647// events is the person's Server-Sent Events stream. A browser EventSource
648// cannot send a bearer, so this route alone also takes the session cookie,
649// and only from a same-origin fetch.
650func (h *HTTP) events(w http.ResponseWriter, r *http.Request) {
651 w.Header().Set("Cache-Control", "no-store")
652 if len(r.Header.Values("Authorization")) == 0 && r.Header.Get("Sec-Fetch-Site") != "same-origin" {
653 personapi.WriteError(w, r, http.StatusForbidden, "forbidden", nil)
654 return
655 }
656 p, err := h.Authenticate(r)
657 if err != nil {
658 h.Failure(w, r, err)
659 return
660 }
661 h.stream(w, r, p, wire.LaneCoordinator, h.Store.Events)
662}
663
664// stream serves a lane's events as Server-Sent Events from the request's
665// cursor, rechecking the person before each batch and ping.
666func (h *HTTP) stream(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal, lane string, read func(context.Context, string, int64, int) ([]wire.Event, error)) {
667 ctx := personapi.WithVerifiedPrincipal(r.Context(), p)
668 if lane == wire.LaneCoordinator {
669 defer h.Store.Hub().Follow(p.Address)()
670 }
671 // Live-only events (a glance) come from the moment the stream opens.
672 live, stop := h.Store.Hub().Live(p.Address, lane)
673 defer stop()
674 after, err := h.cursor(ctx, r)
675 if err != nil {
676 h.fail(w, r, err)
677 return
678 }
679 // Check the cursor before committing to a 200.
680 first, err := read(ctx, p.Address, after, 200)
681 if err != nil {
682 h.fail(w, r, err)
683 return
684 }
685 rc := http.NewResponseController(w)
686 w.Header().Set("Content-Type", "text/event-stream")
687 w.Header().Set("X-Accel-Buffering", "no")
688 w.WriteHeader(http.StatusOK)
689 if _, err = io.WriteString(w, "retry: 2000\n: ok\n\n"); err != nil || rc.Flush() != nil {
690 return
691 }
692 ping := time.NewTicker(wire.PingInterval)
693 defer ping.Stop()
694 poll := time.NewTicker(streamPoll)
695 defer poll.Stop()
696 // writeLive sends one live-only event: no id line, so a client's
697 // cursor never moves to it.
698 writeLive := func(e wire.Event) bool {
699 if _, err := h.Authenticate(r); err != nil {
700 return false
701 }
702 _ = rc.SetWriteDeadline(time.Now().Add(30 * time.Second))
703 raw, _ := json.Marshal(e)
704 _, err := fmt.Fprintf(w, "event: %s\ndata: %s\n\n", e.Type, raw)
705 return err == nil && rc.Flush() == nil
706 }
707 batch := first
708 for {
709 wake := h.Store.Hub().Wait(p.Address)
710 // What went live before this batch was read goes before it: a
711 // glance before its turn's first delta.
712 for drained := false; !drained; {
713 select {
714 case e := <-live:
715 if !writeLive(e) {
716 return
717 }
718 default:
719 drained = true
720 }
721 }
722 if len(batch) > 0 {
723 // Roster removal or device revocation closes the stream here.
724 if _, err := h.Authenticate(r); err != nil {
725 return
726 }
727 _ = rc.SetWriteDeadline(time.Now().Add(30 * time.Second))
728 for _, e := range batch {
729 raw, _ := json.Marshal(e)
730 if _, err := fmt.Fprintf(w, "id: %d\nevent: %s\ndata: %s\n\n", e.Cursor, e.Type, raw); err != nil {
731 return
732 }
733 after = e.Cursor
734 }
735 if rc.Flush() != nil {
736 return
737 }
738 }
739 select {
740 case <-ctx.Done():
741 return
742 case <-h.Store.Hub().Closing():
743 return
744 case <-ping.C:
745 if _, err := h.Authenticate(r); err != nil {
746 return
747 }
748 _ = rc.SetWriteDeadline(time.Now().Add(30 * time.Second))
749 if _, err := io.WriteString(w, "event: ping\ndata: {\"type\":\"ping\"}\n\n"); err != nil || rc.Flush() != nil {
750 return
751 }
752 case e := <-live:
753 if !writeLive(e) {
754 return
755 }
756 case <-wake:
757 case <-poll.C:
758 }
759 batch, err = read(ctx, p.Address, after, 200)
760 if err != nil {
761 return
762 }
763 }
764}
765
766// cursor reads ?after=, which wins over Last-Event-ID. With neither, the
767// stream starts at the newest event.
768func (h *HTTP) cursor(ctx context.Context, r *http.Request) (int64, error) {
769 raw := r.URL.Query().Get("after")
770 if raw == "" {
771 raw = r.Header.Get("Last-Event-ID")
772 }
773 if raw == "" {
774 return h.Store.Cursor(ctx)
775 }
776 n, err := strconv.ParseInt(raw, 10, 64)
777 if err != nil || n < 0 {
778 return 0, ErrInvalid
779 }
780 return n, nil
781}
782
783func (h *HTTP) notebook(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
784 out, err := h.Store.Notebook(r.Context(), p.Address)
785 if err != nil {
786 h.fail(w, r, err)
787 return
788 }
789 writeJSON(w, 200, out)
790}
791
792func (h *HTTP) resetNotebook(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
793 out, err := h.Store.ResetCoordinator(r.Context(), p.Address)
794 if err != nil {
795 h.fail(w, r, err)
796 return
797 }
798 writeJSON(w, http.StatusAccepted, out)
799}
800
801func (h *HTTP) recoverTask(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
802 attempt, err := h.Store.RecoverTask(r.Context(), p.Address, chi.URLParam(r, "id"))
803 if err != nil {
804 h.fail(w, r, err)
805 return
806 }
807 writeJSON(w, 202, wire.TaskAccepted{Attempt: attempt})
808}
809
810func (h *HTTP) runners(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
811 out, err := h.Store.RunnerList(r.Context(), p.Address)
812 if err != nil {
813 h.fail(w, r, err)
814 return
815 }
816 writeJSON(w, 200, out)
817}
818
819func (h *HTTP) needsYou(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
820 out, err := h.Store.NeedsYou(r.Context(), p.Address)
821 if err != nil {
822 h.fail(w, r, err)
823 return
824 }
825 writeJSON(w, 200, out)
826}
827
828func (h *HTTP) tasks(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
829 out, err := h.Store.Tasks(r.Context(), p.Address)
830 if err != nil {
831 h.fail(w, r, err)
832 return
833 }
834 writeJSON(w, 200, out)
835}
836
837func (h *HTTP) task(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
838 out, err := h.Store.TaskDetail(r.Context(), p.Address, chi.URLParam(r, "id"))
839 if err != nil {
840 h.fail(w, r, err)
841 return
842 }
843 writeJSON(w, 200, out)
844}
845
846func (h *HTTP) cancelTask(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
847 attempt, err := h.Store.CancelTask(r.Context(), p.Address, chi.URLParam(r, "id"))
848 if err != nil {
849 h.fail(w, r, err)
850 return
851 }
852 writeJSON(w, http.StatusAccepted, wire.TaskAccepted{Attempt: attempt})
853}
854
855func (h *HTTP) retryTask(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
856 var bound *wire.RetryTask
857 if r.Body != nil && r.ContentLength != 0 {
858 var raw json.RawMessage
859 if err := readJSON(r, &raw); err != nil {
860 h.fail(w, r, err)
861 return
862 }
863 var fields map[string]json.RawMessage
864 if json.Unmarshal(raw, &fields) != nil || fields == nil {
865 h.fail(w, r, ErrInvalid)
866 return
867 }
868 // Existing native clients send an empty JSON object. Any supplied field
869 // opts into binding; a partial or unknown body never becomes legacy retry.
870 if len(fields) > 0 {
871 var input wire.RetryTask
872 if wire.Strict(raw, &input) != nil {
873 h.fail(w, r, ErrInvalid)
874 return
875 }
876 bound = &input
877 }
878 }
879 var attempt int64
880 var err error
881 if bound != nil {
882 attempt, err = h.Store.RetryTaskBound(r.Context(), p.Address, p.CredentialID, chi.URLParam(r, "id"), *bound)
883 } else {
884 attempt, err = h.Store.RetryTask(r.Context(), p.Address, chi.URLParam(r, "id"))
885 }
886 if err != nil {
887 h.fail(w, r, err)
888 return
889 }
890 writeJSON(w, http.StatusAccepted, wire.TaskAccepted{Attempt: attempt})
891}
892
893// setPriority is PUT /api/v1/tasks/{id}/priority {priority, by,
894// revision}: the task creator's own tap; 409 when the revision moved.
895func (h *HTTP) setPriority(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
896 var in wire.SetPriority
897 if err := readJSON(r, &in); err != nil {
898 h.fail(w, r, err)
899 return
900 }
901 out, err := h.Store.SetPriority(r.Context(), p.Address, chi.URLParam(r, "id"), in)
902 if err != nil {
903 h.fail(w, r, err)
904 return
905 }
906 writeJSON(w, 200, out)
907}
908
909// runNow is POST /api/v1/tasks/{id}/run-now {step, step_revision}: the
910// task creator's leave for the held step at that revision, 202 with the
911// release; 409 when the step is not held at that revision, the hold is a
912// spending bar, or the runner is too old.
913func (h *HTTP) runNow(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
914 var in wire.RunNow
915 if err := readJSON(r, &in); err != nil {
916 h.fail(w, r, err)
917 return
918 }
919 out, err := h.Store.RunNow(r.Context(), p.Address, chi.URLParam(r, "id"), in)
920 if err != nil {
921 h.fail(w, r, err)
922 return
923 }
924 writeJSON(w, http.StatusAccepted, out)
925}
926
927// roundTask is Try another round, after the automatic rounds.
928func (h *HTTP) roundTask(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
929 attempt, err := h.Store.RoundTask(r.Context(), p.Address, chi.URLParam(r, "id"))
930 if err != nil {
931 h.fail(w, r, err)
932 return
933 }
934 writeJSON(w, http.StatusAccepted, wire.TaskAccepted{Attempt: attempt})
935}
936
937// setKind is the creator's switch between a change and an exploration.
938func (h *HTTP) setKind(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
939 var in wire.SetKind
940 if err := readJSON(r, &in); err != nil {
941 h.fail(w, r, err)
942 return
943 }
944 out, err := h.Store.SetKind(r.Context(), p.Address, chi.URLParam(r, "id"), in)
945 if err != nil {
946 h.fail(w, r, err)
947 return
948 }
949 writeJSON(w, 200, out)
950}
951
952func (h *HTTP) markDuplicate(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
953 var in wire.MarkDuplicate
954 if err := readJSON(r, &in); err != nil {
955 h.fail(w, r, err)
956 return
957 }
958 out, err := h.Store.MarkDuplicate(r.Context(), p.Address, chi.URLParam(r, "id"), in)
959 if err != nil {
960 h.fail(w, r, err)
961 return
962 }
963 writeJSON(w, 200, out)
964}
965
966// uncombineTask is Undo on a task Equipo combined into another.
967func (h *HTTP) uncombineTask(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
968 out, err := h.Store.Uncombine(r.Context(), p.Address, chi.URLParam(r, "id"))
969 if err != nil {
970 h.fail(w, r, err)
971 return
972 }
973 writeJSON(w, 200, out)
974}
975
976// mergeTask is the creator's Merge on a task left at Ready to merge.
977func (h *HTTP) mergeTask(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
978 attempt, err := h.Store.MergeTask(r.Context(), p.Address, chi.URLParam(r, "id"))
979 if err != nil {
980 h.fail(w, r, err)
981 return
982 }
983 writeJSON(w, http.StatusAccepted, wire.TaskAccepted{Attempt: attempt})
984}
985
986// undoMerge is the creator's Undo of Equipo's own merge: an ordinary
987// revert task, returned.
988func (h *HTTP) undoMerge(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
989 var in wire.UndoMerge
990 if err := readJSON(r, &in); err != nil {
991 h.fail(w, r, err)
992 return
993 }
994 out, err := h.Store.UndoMerge(r.Context(), p.Address, chi.URLParam(r, "id"), in.Revision)
995 if err != nil {
996 h.fail(w, r, err)
997 return
998 }
999 writeJSON(w, http.StatusCreated, out)
1000}
1001
1002func (h *HTTP) specialists(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
1003 out, err := h.Store.Specialists(r.Context(), p.Address)
1004 if err != nil {
1005 h.fail(w, r, err)
1006 return
1007 }
1008 writeJSON(w, 200, out)
1009}
1010
1011func (h *HTTP) revokeSpecialist(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
1012 var in wire.RevokeSpecialist
1013 if err := readJSON(r, &in); err != nil {
1014 h.fail(w, r, err)
1015 return
1016 }
1017 out, err := h.Store.RevokeSpecialist(r.Context(), p.Address, chi.URLParam(r, "id"), in)
1018 if err != nil {
1019 h.fail(w, r, err)
1020 return
1021 }
1022 writeJSON(w, 200, out)
1023}
1024
1025func (h *HTTP) mergePolicy(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
1026 out, err := h.Store.MergePolicy(r.Context(), p.Address, chi.URLParam(r, "id"))
1027 if err != nil {
1028 h.fail(w, r, err)
1029 return
1030 }
1031 writeJSON(w, 200, out)
1032}
1033
1034func (h *HTTP) setMergePolicy(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
1035 var in wire.SetMergePolicy
1036 if err := readJSON(r, &in); err != nil {
1037 h.fail(w, r, err)
1038 return
1039 }
1040 out, err := h.Store.SetMergePolicy(r.Context(), p.Address, chi.URLParam(r, "id"), in)
1041 if err != nil {
1042 h.fail(w, r, err)
1043 return
1044 }
1045 writeJSON(w, 200, out)
1046}
1047
1048func (h *HTTP) postThread(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
1049 var in wire.PostThread
1050 if err := readJSON(r, &in); err != nil {
1051 h.fail(w, r, err)
1052 return
1053 }
1054 out, err := h.Store.PostThread(r.Context(), p.Address, chi.URLParam(r, "id"), in)
1055 if err != nil {
1056 h.fail(w, r, err)
1057 return
1058 }
1059 writeJSON(w, 200, out)
1060}
1061
1062func (h *HTTP) stepLog(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
1063 out, err := h.Store.StepLog(r.Context(), p.Address, chi.URLParam(r, "id"))
1064 if err != nil {
1065 h.fail(w, r, err)
1066 return
1067 }
1068 writeJSON(w, 200, out)
1069}
1070
1071func (h *HTTP) ask(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
1072 var in wire.AskQuestion
1073 if err := readJSON(r, &in); err != nil {
1074 h.fail(w, r, err)
1075 return
1076 }
1077 out, err := h.Store.Ask(r.Context(), p.Address, chi.URLParam(r, "id"), in)
1078 if err != nil {
1079 h.fail(w, r, err)
1080 return
1081 }
1082 writeJSON(w, http.StatusAccepted, out)
1083}
1084
1085func (h *HTTP) question(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
1086 out, err := h.Store.Question(r.Context(), p.Address, chi.URLParam(r, "id"))
1087 if err != nil {
1088 h.fail(w, r, err)
1089 return
1090 }
1091 writeJSON(w, 200, out)
1092}
1093
1094func (h *HTTP) cancelQuestion(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
1095 attempt, err := h.Store.CancelQuestion(r.Context(), p.Address, chi.URLParam(r, "id"))
1096 if errors.Is(err, ErrTerminal) {
1097 personapi.WriteError(w, r, http.StatusConflict, "question_ended", nil)
1098 return
1099 }
1100 if err != nil {
1101 h.fail(w, r, err)
1102 return
1103 }
1104 writeJSON(w, http.StatusAccepted, wire.TaskAccepted{Attempt: attempt})
1105}
1106
1107func (h *HTTP) moveTask(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
1108 var in wire.MoveTask
1109 if err := readJSON(r, &in); err != nil {
1110 h.fail(w, r, err)
1111 return
1112 }
1113 var err error
1114 if in.Abandon {
1115 err = h.Store.AbandonMove(r.Context(), p.Address, chi.URLParam(r, "id"), in.Revision)
1116 } else if in.NewProject {
1117 err = h.Store.RequestNewProjectMove(r.Context(), p.Address, chi.URLParam(r, "id"), in)
1118 } else {
1119 err = h.Store.MoveTask(r.Context(), p.Address, chi.URLParam(r, "id"), in)
1120 }
1121 if err != nil {
1122 h.fail(w, r, err)
1123 return
1124 }
1125 writeJSON(w, http.StatusAccepted, map[string]bool{"accepted": true})
1126}
1127
1128func (h *HTTP) removePlacementNote(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
1129 if err := h.Store.RemovePlacementNote(r.Context(), p.Address, chi.URLParam(r, "id")); err != nil {
1130 h.fail(w, r, err)
1131 return
1132 }
1133 w.WriteHeader(http.StatusNoContent)
1134}
1135
1136// Legacy cards use rand.Text identifiers (or native:/Coordinator aliases),
1137// never the thin store's c_ prefix. Dispatch is independent of visibility.
1138func thinCard(r *http.Request) bool { return strings.HasPrefix(chi.URLParam(r, "id"), "c_") }
1139func (h *HTTP) card(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
1140 out, err := h.Store.DeviceCard(r.Context(), p.Address, p.CredentialID, chi.URLParam(r, "id"))
1141 if err != nil {
1142 h.fail(w, r, err)
1143 return
1144 }
1145 w.Header().Set("ETag", fmt.Sprintf(`"%d"`, out.Revision))
1146 writeJSON(w, http.StatusOK, out)
1147}
1148