| 1 | package slides |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "math" |
| 9 | "strconv" |
| 10 | |
| 11 | access "amadan.net/oficina/agent-access.git" |
| 12 | "amadan.net/oficina/home/connect/linkstore" |
| 13 | "amadan.net/oficina/home/handoff/seal" |
| 14 | "amadan.net/oficina/slides/internal/slides/core" |
| 15 | "amadan.net/oficina/slides/internal/slides/deck" |
| 16 | "github.com/google/uuid" |
| 17 | "gorm.io/gorm" |
| 18 | ) |
| 19 | |
| 20 | type slideAgentEdit struct { |
| 21 | Coordinate string `gorm:"primaryKey"` |
| 22 | Content string |
| 23 | DeckID int64 |
| 24 | Revision int64 |
| 25 | ResultSealed []byte |
| 26 | } |
| 27 | |
| 28 | func (slideAgentEdit) TableName() string { return "slides_agent_edits" } |
| 29 | |
| 30 | type slideAgentUpdate struct { |
| 31 | Team string `json:"team"` |
| 32 | Sqid string `json:"sqid"` |
| 33 | ExpectedRevision string `json:"expected_revision"` |
| 34 | ClientID string `json:"client_id"` |
| 35 | Ops []map[string]json.RawMessage `json:"ops"` |
| 36 | } |
| 37 | type slideAgentUpdated struct { |
| 38 | Sqid string `json:"sqid"` |
| 39 | Revision string `json:"revision"` |
| 40 | URL string `json:"url"` |
| 41 | IDs map[string]string `json:"ids"` |
| 42 | } |
| 43 | |
| 44 | func (a *slideAgent) editorInTx(ctx context.Context, tx *gorm.DB, p access.Principal, u User, sqid string, d *Deck) error { |
| 45 | state, ok := ctx.Value(slideAgentKey{}).(*slideAgentContext) |
| 46 | if !ok || state == nil || state.verify == nil { |
| 47 | return linkstore.ErrRefused |
| 48 | } |
| 49 | if err := state.verify(ctx); err != nil { |
| 50 | return err |
| 51 | } |
| 52 | person, err := a.app.home.ResolveOn(ctx, tx.Statement.ConnPool, p.Subject) |
| 53 | if err != nil { |
| 54 | return err |
| 55 | } |
| 56 | if person.ID != u.ID || person.Label != u.Email { |
| 57 | return linkstore.ErrRefused |
| 58 | } |
| 59 | var current User |
| 60 | if err = tx.First(¤t, person.ID).Error; err != nil { |
| 61 | return err |
| 62 | } |
| 63 | if current.Email != u.Email || a.app.team == nil && !a.app.allowed.allows(current.Email) { |
| 64 | return linkstore.ErrRefused |
| 65 | } |
| 66 | current.team = u.team |
| 67 | return a.visible(ctx, tx, current, "sqid=?", sqid, d) |
| 68 | } |
| 69 | |
| 70 | func (a *slideAgent) update(ctx context.Context, p access.Principal, u User, in slideAgentUpdate) (any, error) { |
| 71 | expected, err := strconv.ParseInt(in.ExpectedRevision, 10, 64) |
| 72 | if err != nil || expected < 0 || strconv.FormatInt(expected, 10) != in.ExpectedRevision { |
| 73 | return nil, access.Fail("invalid", "Use a canonical nonnegative decimal revision.") |
| 74 | } |
| 75 | id, err := uuid.Parse(in.ClientID) |
| 76 | if err != nil || id == uuid.Nil || id.String() != in.ClientID { |
| 77 | return nil, access.Fail("invalid", "Use a canonical nonzero client UUID.") |
| 78 | } |
| 79 | if len(in.Ops) < 1 || len(in.Ops) > 100 { |
| 80 | return nil, access.Fail("invalid", "Supply one to one hundred semantic operations.") |
| 81 | } |
| 82 | for _, op := range in.Ops { |
| 83 | if !slideAgentEditableOp(rawString(op, "op")) { |
| 84 | return nil, access.Fail("invalid", "Unsupported deck operation.") |
| 85 | } |
| 86 | } |
| 87 | // Decode numbers as Number, not float64. Marshal sorts object keys recursively |
| 88 | // and keeps ordered arrays, exact number spelling and absent versus null. |
| 89 | original, err := json.Marshal(in) |
| 90 | if err != nil { |
| 91 | return nil, slideAgentFailure(err) |
| 92 | } |
| 93 | var canonical any |
| 94 | decoder := json.NewDecoder(bytes.NewReader(original)) |
| 95 | decoder.UseNumber() |
| 96 | if err = decoder.Decode(&canonical); err != nil { |
| 97 | return nil, slideAgentFailure(err) |
| 98 | } |
| 99 | coordinate := a.digest("edit-coordinate", []string{"slides_update_deck", a.identityIssuer, a.issuer, a.team, p.Subject, p.Client, in.ClientID}) |
| 100 | content := a.digest("edit-content", canonical) |
| 101 | var initial Deck |
| 102 | if err = a.visible(ctx, a.app.db.G, u, "sqid=?", in.Sqid, &initial); err != nil { |
| 103 | return nil, slideAgentFailure(err) |
| 104 | } |
| 105 | sealer, err := seal.New(a.key, "oficina/slides/agent/v1") |
| 106 | if err != nil { |
| 107 | return nil, slideAgentFailure(err) |
| 108 | } |
| 109 | var result slideAgentUpdated |
| 110 | var d Deck |
| 111 | var h *core.Handle |
| 112 | fresh := false |
| 113 | defer func() { |
| 114 | if h != nil { |
| 115 | h.Close(context.WithoutCancel(ctx)) |
| 116 | } |
| 117 | }() |
| 118 | guard := a.app.deckGuard(ctx, u, initial) |
| 119 | err = a.app.db.G.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 120 | if e := a.bind(tx); e != nil { |
| 121 | return e |
| 122 | } |
| 123 | return guard.run(func() error { |
| 124 | if e := a.editorInTx(ctx, tx, p, u, in.Sqid, &d); e != nil { |
| 125 | return e |
| 126 | } |
| 127 | var receipt slideAgentEdit |
| 128 | e := tx.Where("coordinate=?", coordinate).Take(&receipt).Error |
| 129 | if e == nil { |
| 130 | if receipt.Content != content || receipt.DeckID != d.ID { |
| 131 | return access.Fail("conflict", "This client UUID already names a different edit.") |
| 132 | } |
| 133 | plain, e := sealer.Open("edit-result/"+coordinate, receipt.ResultSealed) |
| 134 | if e != nil { |
| 135 | return e |
| 136 | } |
| 137 | if e = json.Unmarshal(plain, &result); e != nil { |
| 138 | return e |
| 139 | } |
| 140 | if result.Sqid != in.Sqid || result.Revision != strconv.FormatInt(receipt.Revision, 10) || result.IDs == nil { |
| 141 | return access.Fail("unavailable", "The edit receipt is unavailable.") |
| 142 | } |
| 143 | return a.editorInTx(ctx, tx, p, u, in.Sqid, &d) |
| 144 | } |
| 145 | if !errors.Is(e, gorm.ErrRecordNotFound) { |
| 146 | return e |
| 147 | } |
| 148 | if d.Seq != expected { |
| 149 | return access.Fail("conflict", "This deck changed. Read it again before editing.") |
| 150 | } |
| 151 | if d.Seq == math.MaxInt64 { |
| 152 | return access.Fail("unavailable", "This deck's revision cannot advance.") |
| 153 | } |
| 154 | var view *deck.Deck |
| 155 | h, view, e = a.app.openDeckOn(ctx, tx, d) |
| 156 | if e != nil { |
| 157 | return e |
| 158 | } |
| 159 | var copied slideAgentUpdate |
| 160 | if e = json.Unmarshal(original, &copied); e != nil { |
| 161 | return e |
| 162 | } |
| 163 | ids, e := mintOpIDs(copied.Ops, view) |
| 164 | if e != nil { |
| 165 | return e |
| 166 | } |
| 167 | encoded, e := json.Marshal(copied.Ops) |
| 168 | if e != nil { |
| 169 | return e |
| 170 | } |
| 171 | actor, e := a.actor(tx, p, u) |
| 172 | if e != nil { |
| 173 | return e |
| 174 | } |
| 175 | if e = applyOpsOn(ctx, tx, h, &d, actor, encoded, metaRowUpdates(copied.Ops)); e != nil { |
| 176 | return e |
| 177 | } |
| 178 | if e = h.Check(ctx); e != nil { |
| 179 | return e |
| 180 | } |
| 181 | raw, e := h.JSON(ctx) |
| 182 | if e != nil { |
| 183 | return e |
| 184 | } |
| 185 | if _, e = deck.Parse(raw); e != nil { |
| 186 | return e |
| 187 | } |
| 188 | if _, e = slideAgentBounded(map[string]any{"sqid": d.Sqid, "revision": strconv.FormatInt(d.Seq+1, 10), "deck": json.RawMessage(raw)}); e != nil { |
| 189 | return e |
| 190 | } |
| 191 | result = slideAgentUpdated{Sqid: d.Sqid, Revision: strconv.FormatInt(d.Seq+1, 10), URL: a.app.cfg.Origin + "/d/" + d.Sqid, IDs: ids} |
| 192 | if _, e = slideAgentBounded(result); e != nil { |
| 193 | return e |
| 194 | } |
| 195 | encoded, e = json.Marshal(result) |
| 196 | if e != nil { |
| 197 | return e |
| 198 | } |
| 199 | ciphertext, e := sealer.Seal("edit-result/"+coordinate, encoded) |
| 200 | if e != nil { |
| 201 | return e |
| 202 | } |
| 203 | if e = tx.Create(&slideAgentEdit{Coordinate: coordinate, Content: content, DeckID: d.ID, Revision: d.Seq + 1, ResultSealed: ciphertext}).Error; e != nil { |
| 204 | return e |
| 205 | } |
| 206 | if e = a.editorInTx(ctx, tx, p, u, in.Sqid, &d); e != nil { |
| 207 | return e |
| 208 | } |
| 209 | fresh = true |
| 210 | return nil |
| 211 | }) |
| 212 | }) |
| 213 | if err != nil { |
| 214 | var rejected *core.RejectedError |
| 215 | if errors.As(err, &rejected) { |
| 216 | return nil, access.Fail("invalid", "The semantic operation batch was refused.") |
| 217 | } |
| 218 | if errors.Is(err, errDeckBusy) { |
| 219 | return nil, access.Fail("conflict", "This deck changed. Read it again before editing.") |
| 220 | } |
| 221 | return nil, slideAgentFailure(err) |
| 222 | } |
| 223 | if fresh { |
| 224 | a.app.live.PublishSeq(d.Sqid, d.Seq) |
| 225 | a.app.maybeSnapshot(ctx, d, h, d.Seq) |
| 226 | } |
| 227 | a.remember(ctx, d.ID) |
| 228 | return slideAgentBounded(result) |
| 229 | } |
| 230 | |