| 1 | package calls |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "log/slog" |
| 9 | "strings" |
| 10 | "sync/atomic" |
| 11 | "time" |
| 12 | |
| 13 | "gorm.io/gorm" |
| 14 | "gorm.io/gorm/clause" |
| 15 | |
| 16 | "amadan.net/oficina/calls/internal/calls/seal" |
| 17 | ) |
| 18 | |
| 19 | // grantLife is ruling 4: a guest grant expires two hours after the |
| 20 | // meeting's start, or two hours after creation when there is no start. |
| 21 | const grantLife = 2 * time.Hour |
| 22 | |
| 23 | // pendingLife matches the pending-join cookie: fifteen minutes. |
| 24 | const pendingLife = 15 * time.Minute |
| 25 | |
| 26 | // clock is the store's time source. It is a value tests move (see |
| 27 | // TestHandle.SetClock) while request goroutines are reading it — a |
| 28 | // stream handler outlives the request that opened it — so the function |
| 29 | // lives behind an atomic rather than in a plain field. |
| 30 | type clock struct{ fn atomic.Value } |
| 31 | |
| 32 | func newClock(f func() time.Time) *clock { |
| 33 | c := &clock{} |
| 34 | c.set(f) |
| 35 | return c |
| 36 | } |
| 37 | |
| 38 | func (c *clock) set(f func() time.Time) { c.fn.Store(f) } |
| 39 | |
| 40 | func (c *clock) now() time.Time { return c.fn.Load().(func() time.Time)() } |
| 41 | |
| 42 | // store is every database access in the app. Sealing happens here and |
| 43 | // nowhere else, so a handler never holds a plaintext title it did not |
| 44 | // get from the store. |
| 45 | type store struct { |
| 46 | g *gorm.DB |
| 47 | sealer *seal.Sealer |
| 48 | clk *clock |
| 49 | logger *slog.Logger |
| 50 | // team is whether team mode is on: every person's write then runs |
| 51 | // inside the standing guard (team_guard.go). False, every write is |
| 52 | // what it always was. |
| 53 | team bool |
| 54 | } |
| 55 | |
| 56 | // now is the app's clock, the one a test can move. |
| 57 | func (s *store) now() time.Time { return s.clk.now() } |
| 58 | |
| 59 | func actorFor(p Person) string { return fmt.Sprintf("person:%d", p.ID) } |
| 60 | |
| 61 | // ensurePerson reads first and writes only when the read is empty: |
| 62 | // this runs on every signed-in request, and SQLite has one writer. |
| 63 | func (s *store) ensurePerson(ctx context.Context, address string) (Person, error) { |
| 64 | email := normalizeAddress(address) |
| 65 | if email == "" { |
| 66 | return Person{}, errors.New("calls: cannot map an empty address to a person") |
| 67 | } |
| 68 | var found Person |
| 69 | err := s.g.WithContext(ctx).Where("email = ?", email).Take(&found).Error |
| 70 | switch { |
| 71 | case err == nil: |
| 72 | return found, nil |
| 73 | case !errors.Is(err, gorm.ErrRecordNotFound): |
| 74 | return Person{}, fmt.Errorf("calls: load person: %w", err) |
| 75 | } |
| 76 | name := email |
| 77 | if at := strings.Index(email, "@"); at > 0 { |
| 78 | name = email[:at] |
| 79 | } |
| 80 | created := Person{Email: email, Name: name, CreatedAt: s.now().UTC()} |
| 81 | if res := s.g.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(&created); res.Error != nil { |
| 82 | return Person{}, fmt.Errorf("calls: create person: %w", res.Error) |
| 83 | } |
| 84 | if err := s.g.WithContext(ctx).Where("email = ?", email).Take(&found).Error; err != nil { |
| 85 | return Person{}, fmt.Errorf("calls: load person: %w", err) |
| 86 | } |
| 87 | return found, nil |
| 88 | } |
| 89 | |
| 90 | type meetingView struct { |
| 91 | Meeting |
| 92 | Title string |
| 93 | LinkPresent bool |
| 94 | CreatedByPrincipal string |
| 95 | ByAgent bool |
| 96 | } |
| 97 | |
| 98 | func (s *store) title(m Meeting) string { |
| 99 | t, err := s.sealer.OpenString(seal.PurposeMeetingTitle, m.TitleSealed) |
| 100 | if err != nil { |
| 101 | s.logger.Error("calls: open title", "meeting_id", m.ID, "err", err) |
| 102 | return "(title unreadable)" |
| 103 | } |
| 104 | return t |
| 105 | } |
| 106 | |
| 107 | // createMeeting creates the meeting and its first link in one |
| 108 | // transaction. The token is sealed for subsequent member sharing. |
| 109 | func (s *store) createMeeting(ctx context.Context, title string, startsAt *time.Time, actor string) (Meeting, string, error) { |
| 110 | return s.insertMeeting(ctx, title, false, "", startsAt, actor) |
| 111 | } |
| 112 | |
| 113 | // createCall is createMeeting for a meeting with no title of its own — |
| 114 | // the list's Start a call and the apps' Start meeting: the title is the |
| 115 | // one Calls wrote, and the meeting says so (Meeting.AutoTitle). |
| 116 | func (s *store) createCall(ctx context.Context, title autoTitle, actor string) (Meeting, string, error) { |
| 117 | return s.insertMeeting(ctx, title.Text, true, title.Zone, nil, actor) |
| 118 | } |
| 119 | |
| 120 | func (s *store) insertMeeting(ctx context.Context, title string, auto bool, zone string, startsAt *time.Time, actor string) (Meeting, string, error) { |
| 121 | sealed, err := s.sealer.SealString(seal.PurposeMeetingTitle, title) |
| 122 | if err != nil { |
| 123 | return Meeting{}, "", err |
| 124 | } |
| 125 | token, hash, err := newLinkToken() |
| 126 | if err != nil { |
| 127 | return Meeting{}, "", err |
| 128 | } |
| 129 | linkSealed, err := s.sealer.SealString(seal.PurposeMeetingLink, token) |
| 130 | if err != nil { |
| 131 | return Meeting{}, "", err |
| 132 | } |
| 133 | defaults, err := s.meetingDefaults(ctx) |
| 134 | if err != nil { |
| 135 | return Meeting{}, "", err |
| 136 | } |
| 137 | var m Meeting |
| 138 | err = s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 139 | return s.guard(ctx, func() error { |
| 140 | for attempt := 0; ; attempt++ { |
| 141 | sqid, err := newSqid() |
| 142 | if err != nil { |
| 143 | return err |
| 144 | } |
| 145 | m = Meeting{RequireSignin: defaults.RequireSignin, WaitingRoom: defaults.WaitingRoom, AutoTitle: auto, TitleZone: zone, Sqid: sqid, TitleSealed: sealed, StartsAt: startsAt, CreatedBy: actor, CreatedAt: s.now().UTC()} |
| 146 | res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&m) |
| 147 | if res.Error != nil { |
| 148 | return res.Error |
| 149 | } |
| 150 | if res.RowsAffected == 1 { |
| 151 | break |
| 152 | } |
| 153 | if attempt+1 >= maxSqidAttempts { |
| 154 | return errors.New("calls: could not mint a unique sqid") |
| 155 | } |
| 156 | } |
| 157 | return tx.Create(&MeetingLink{MeetingID: m.ID, TokenHash: hash, TokenSealed: linkSealed, CreatedBy: actor, CreatedAt: s.now().UTC()}).Error |
| 158 | }) |
| 159 | }) |
| 160 | if err != nil { |
| 161 | return Meeting{}, "", err |
| 162 | } |
| 163 | return m, token, nil |
| 164 | } |
| 165 | |
| 166 | func (s *store) listMeetings(ctx context.Context) ([]meetingView, error) { |
| 167 | var ms []Meeting |
| 168 | if err := s.g.WithContext(ctx).Order("ended_at IS NOT NULL, starts_at IS NULL, starts_at ASC, created_at DESC").Find(&ms).Error; err != nil { |
| 169 | return nil, err |
| 170 | } |
| 171 | // labels is shared across the whole list so a run of meetings from |
| 172 | // the same actor (one agent's usual shape) resolves creatorLabel |
| 173 | // once rather than once per row — the N+1 Task 3's report flagged |
| 174 | // for exactly this move. |
| 175 | labels := make(map[string]string, len(ms)) |
| 176 | out := make([]meetingView, 0, len(ms)) |
| 177 | for _, m := range ms { |
| 178 | v, err := s.meetingViewOfCached(ctx, m, labels) |
| 179 | if err != nil { |
| 180 | return nil, err |
| 181 | } |
| 182 | out = append(out, v) |
| 183 | } |
| 184 | return out, nil |
| 185 | } |
| 186 | |
| 187 | // meetingViewOf is one row as every reader wants it: the meeting, its |
| 188 | // title opened, whether a live link exists, and who made it — an |
| 189 | // agent's principal (§8.1's robot badge and operator name "on every |
| 190 | // write") or a person's display name, resolved through creatorLabel. |
| 191 | // Factored out of listMeetings so the drive surface's single-meeting |
| 192 | // read (§8.2) answers link_present from the same query the list does, |
| 193 | // rather than growing a second opinion about what "present" means. |
| 194 | func (s *store) meetingViewOf(ctx context.Context, m Meeting) (meetingView, error) { |
| 195 | return s.meetingViewOfCached(ctx, m, map[string]string{}) |
| 196 | } |
| 197 | |
| 198 | // meetingViewOfCached is meetingViewOf's body, taking a creator-label |
| 199 | // cache a caller can share across many rows. meetingViewOf itself |
| 200 | // passes a throwaway map, since a single row has nothing to share a |
| 201 | // cache with; listMeetings passes one map for the whole list. |
| 202 | func (s *store) meetingViewOfCached(ctx context.Context, m Meeting, labels map[string]string) (meetingView, error) { |
| 203 | var n int64 |
| 204 | if err := s.g.WithContext(ctx).Model(&MeetingLink{}). |
| 205 | Where("meeting_id = ? AND revoked_at IS NULL", m.ID).Count(&n).Error; err != nil { |
| 206 | return meetingView{}, err |
| 207 | } |
| 208 | by, ok := labels[m.CreatedBy] |
| 209 | if !ok { |
| 210 | by = s.creatorLabel(ctx, m.CreatedBy) |
| 211 | labels[m.CreatedBy] = by |
| 212 | } |
| 213 | return meetingView{ |
| 214 | Meeting: m, |
| 215 | Title: s.title(m), |
| 216 | LinkPresent: n > 0, |
| 217 | CreatedByPrincipal: by, |
| 218 | ByAgent: strings.HasPrefix(m.CreatedBy, "agent:") || strings.HasPrefix(m.CreatedBy, "connection:"), |
| 219 | }, nil |
| 220 | } |
| 221 | |
| 222 | func (s *store) meetingBySqid(ctx context.Context, sqid string) (Meeting, bool, error) { |
| 223 | var m Meeting |
| 224 | err := s.g.WithContext(ctx).Where("sqid = ?", sqid).Take(&m).Error |
| 225 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 226 | return Meeting{}, false, nil |
| 227 | } |
| 228 | return m, err == nil, err |
| 229 | } |
| 230 | |
| 231 | // personByID is the hub's half of standing: the tick and the entry |
| 232 | // checks hold a person id, not a request, so the row is read back here. |
| 233 | func (s *store) personByID(ctx context.Context, id int64) (Person, bool, error) { |
| 234 | var p Person |
| 235 | err := s.g.WithContext(ctx).Where("id = ?", id).Take(&p).Error |
| 236 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 237 | return Person{}, false, nil |
| 238 | } |
| 239 | return p, err == nil, err |
| 240 | } |
| 241 | |
| 242 | // liveLink answers one false for a token that never existed, one that |
| 243 | // was revoked, and one whose meeting has ended (spec §3.2's one 404). |
| 244 | func (s *store) liveLink(ctx context.Context, token string) (MeetingLink, Meeting, bool, error) { |
| 245 | if token == "" { |
| 246 | return MeetingLink{}, Meeting{}, false, nil |
| 247 | } |
| 248 | return s.liveLinkByHash(ctx, hashLinkToken(token)) |
| 249 | } |
| 250 | |
| 251 | func (s *store) liveLinkByHash(ctx context.Context, hash string) (MeetingLink, Meeting, bool, error) { |
| 252 | var l MeetingLink |
| 253 | err := s.g.WithContext(ctx).Where("token_hash = ?", hash).Take(&l).Error |
| 254 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 255 | return MeetingLink{}, Meeting{}, false, nil |
| 256 | } |
| 257 | if err != nil { |
| 258 | return MeetingLink{}, Meeting{}, false, err |
| 259 | } |
| 260 | return s.liveLinkRow(ctx, l) |
| 261 | } |
| 262 | |
| 263 | func (s *store) liveLinkByID(ctx context.Context, id int64) (MeetingLink, Meeting, bool, error) { |
| 264 | var l MeetingLink |
| 265 | err := s.g.WithContext(ctx).Where("id = ?", id).Take(&l).Error |
| 266 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 267 | return MeetingLink{}, Meeting{}, false, nil |
| 268 | } |
| 269 | if err != nil { |
| 270 | return MeetingLink{}, Meeting{}, false, err |
| 271 | } |
| 272 | return s.liveLinkRow(ctx, l) |
| 273 | } |
| 274 | |
| 275 | func (s *store) liveLinkRow(ctx context.Context, l MeetingLink) (MeetingLink, Meeting, bool, error) { |
| 276 | if l.RevokedAt != nil { |
| 277 | return MeetingLink{}, Meeting{}, false, nil |
| 278 | } |
| 279 | var m Meeting |
| 280 | if err := s.g.WithContext(ctx).Where("id = ?", l.MeetingID).Take(&m).Error; err != nil { |
| 281 | return MeetingLink{}, Meeting{}, false, err |
| 282 | } |
| 283 | if m.EndedAt != nil { |
| 284 | return MeetingLink{}, Meeting{}, false, nil |
| 285 | } |
| 286 | return l, m, true, nil |
| 287 | } |
| 288 | |
| 289 | // errMeetingEnded is replaceLink's answer when the meeting ended before |
| 290 | // the transaction reached it (review S5-2). A caller's own earlier read |
| 291 | // of ended_at is a snapshot, not a guarantee: the only read that can be |
| 292 | // trusted against a concurrent end is the one inside the write's own |
| 293 | // transaction, and this is that read's refusal. |
| 294 | var errMeetingEnded = errors.New("calls: the meeting has ended") |
| 295 | |
| 296 | // replaceLink revokes every live link for the meeting and mints one |
| 297 | // new one, in one transaction. The replacement is sealed for repeat sharing. |
| 298 | // |
| 299 | // The meeting's ended_at is re-read inside that transaction, matched in |
| 300 | // the same WHERE as the id: a meeting row is never deleted, so the one |
| 301 | // way the row fails to match is that it ended, and that is |
| 302 | // errMeetingEnded. Without it a replacement could read a running |
| 303 | // meeting, pause while another request ended it, and leave an |
| 304 | // unrevoked link on an ended meeting. |
| 305 | func (s *store) replaceLink(ctx context.Context, meetingID int64, actor string) (string, error) { |
| 306 | token, hash, err := newLinkToken() |
| 307 | if err != nil { |
| 308 | return "", err |
| 309 | } |
| 310 | sealed, err := s.sealer.SealString(seal.PurposeMeetingLink, token) |
| 311 | if err != nil { |
| 312 | return "", err |
| 313 | } |
| 314 | now := s.now().UTC() |
| 315 | err = s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 316 | return s.guard(ctx, func() error { |
| 317 | var m Meeting |
| 318 | if err := tx.Where("id = ? AND ended_at IS NULL", meetingID).Take(&m).Error; err != nil { |
| 319 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 320 | return errMeetingEnded |
| 321 | } |
| 322 | return err |
| 323 | } |
| 324 | if err := tx.Model(&MeetingLink{}).Where("meeting_id = ? AND revoked_at IS NULL", meetingID).Update("revoked_at", now).Error; err != nil { |
| 325 | return err |
| 326 | } |
| 327 | return tx.Create(&MeetingLink{MeetingID: meetingID, TokenHash: hash, TokenSealed: sealed, CreatedBy: actor, CreatedAt: now}).Error |
| 328 | }) |
| 329 | }) |
| 330 | if err != nil { |
| 331 | return "", err |
| 332 | } |
| 333 | return token, nil |
| 334 | } |
| 335 | |
| 336 | // shareLink is a member action. Older hash-only invitations cannot be opened; |
| 337 | // mint one recoverable invitation alongside them, then reuse it. Replacement |
| 338 | // and ending still revoke every live invitation in their own transactions. |
| 339 | func (s *store) shareLink(ctx context.Context, meetingID int64, actor string) (string, error) { |
| 340 | var token string |
| 341 | err := s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 342 | return s.guard(ctx, func() error { |
| 343 | var m Meeting |
| 344 | if err := tx.Where("id = ? AND ended_at IS NULL", meetingID).Take(&m).Error; err != nil { |
| 345 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 346 | return errMeetingEnded |
| 347 | } |
| 348 | return err |
| 349 | } |
| 350 | var link MeetingLink |
| 351 | err := tx.Where("meeting_id = ? AND revoked_at IS NULL AND token_sealed IS NOT NULL", meetingID).Order("id DESC").Take(&link).Error |
| 352 | if err == nil { |
| 353 | token, err = s.sealer.OpenString(seal.PurposeMeetingLink, link.TokenSealed) |
| 354 | if err != nil || token == "" || hashLinkToken(token) != link.TokenHash { |
| 355 | return errors.New("calls: cannot open invitation") |
| 356 | } |
| 357 | return nil |
| 358 | } |
| 359 | if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 360 | return err |
| 361 | } |
| 362 | var hash string |
| 363 | token, hash, err = newLinkToken() |
| 364 | if err != nil { |
| 365 | return err |
| 366 | } |
| 367 | sealed, err := s.sealer.SealString(seal.PurposeMeetingLink, token) |
| 368 | if err != nil { |
| 369 | return err |
| 370 | } |
| 371 | return tx.Create(&MeetingLink{MeetingID: meetingID, TokenHash: hash, TokenSealed: sealed, CreatedBy: actor, CreatedAt: s.now().UTC()}).Error |
| 372 | }) |
| 373 | }) |
| 374 | if err != nil { |
| 375 | // A token opened before a refusal at commit is not handed out: |
| 376 | // the guard said this person may not have it. |
| 377 | token = "" |
| 378 | } |
| 379 | return token, err |
| 380 | } |
| 381 | |
| 382 | // endMeeting sets ended_at and revokes every link, and reports whether |
| 383 | // this call is the one that ended the meeting. False means the |
| 384 | // conditional UPDATE matched no row — the meeting was already ended, |
| 385 | // by another request or an earlier one of this caller's — and nothing |
| 386 | // was written, so the links the winning end revoked stay revoked |
| 387 | // (review S5-2). Two racing ends therefore get one true and one false |
| 388 | // rather than two 200s. |
| 389 | func (s *store) endMeeting(ctx context.Context, meetingID int64, actor string) (bool, error) { |
| 390 | now := s.now().UTC() |
| 391 | ended := false |
| 392 | err := s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 393 | return s.guard(ctx, func() error { |
| 394 | ended = false |
| 395 | res := tx.Model(&Meeting{}).Where("id = ? AND ended_at IS NULL", meetingID). |
| 396 | Select("ended_at", "ended_by").Updates(map[string]any{"ended_at": now, "ended_by": actor}) |
| 397 | if res.Error != nil { |
| 398 | return res.Error |
| 399 | } |
| 400 | if res.RowsAffected == 0 { |
| 401 | return nil |
| 402 | } |
| 403 | ended = true |
| 404 | return tx.Model(&MeetingLink{}).Where("meeting_id = ? AND revoked_at IS NULL", meetingID).Update("revoked_at", now).Error |
| 405 | }) |
| 406 | }) |
| 407 | if err != nil { |
| 408 | return false, err |
| 409 | } |
| 410 | return ended, nil |
| 411 | } |
| 412 | |
| 413 | func (s *store) grantFor(ctx context.Context, meetingID, personID int64) (GuestGrant, bool, error) { |
| 414 | var g GuestGrant |
| 415 | err := s.g.WithContext(ctx).Where("meeting_id = ? AND person_id = ?", meetingID, personID).Take(&g).Error |
| 416 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 417 | return GuestGrant{}, false, nil |
| 418 | } |
| 419 | return g, err == nil, err |
| 420 | } |
| 421 | |
| 422 | // mintGrant is idempotent: following the link twice touches nothing. |
| 423 | func (s *store) mintGrant(ctx context.Context, m Meeting, personID int64) (GuestGrant, error) { |
| 424 | if g, ok, err := s.grantFor(ctx, m.ID, personID); err != nil || ok { |
| 425 | return g, err |
| 426 | } |
| 427 | now := s.now().UTC() |
| 428 | base := now |
| 429 | if m.StartsAt != nil { |
| 430 | base = m.StartsAt.UTC() |
| 431 | } |
| 432 | g := GuestGrant{MeetingID: m.ID, PersonID: personID, GrantedAt: now, ExpiresAt: base.Add(grantLife)} |
| 433 | if res := s.g.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).Create(&g); res.Error != nil { |
| 434 | return GuestGrant{}, res.Error |
| 435 | } |
| 436 | g, _, err := s.grantFor(ctx, m.ID, personID) |
| 437 | return g, err |
| 438 | } |
| 439 | |
| 440 | // mintGrantViaLink mints a grant for the link the browser actually |
| 441 | // followed, re-reading that link inside the grant's own transaction |
| 442 | // (review C1-3). followLink resolves the link and then mints; between |
| 443 | // those two steps a member can replace the link, and mintGrant on its |
| 444 | // own would never notice, because it is handed the meeting rather than |
| 445 | // the link. Standing checks the grant and not its origin, so such a |
| 446 | // grant would stay usable for its full two hours. |
| 447 | // |
| 448 | // It answers false — no error — when the link has been revoked or its |
| 449 | // meeting has ended, which the caller turns into the same 404 an unknown |
| 450 | // token gets (spec §3.2's one 404). |
| 451 | // |
| 452 | // SQLite's writer pool is one connection, so the transaction's read and |
| 453 | // its write cannot be interleaved with another transaction's. |
| 454 | func (s *store) mintGrantViaLink(ctx context.Context, linkID, personID int64) (GuestGrant, bool, error) { |
| 455 | var g GuestGrant |
| 456 | live := false |
| 457 | // In team mode the grant stands on the meeting's host, whose Access |
| 458 | // the caller carries on ctx (team_host.go): a link admits nobody new |
| 459 | // once its host has left the team. |
| 460 | err := s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 461 | return s.guard(ctx, func() error { |
| 462 | live = false |
| 463 | ts := &store{g: tx, sealer: s.sealer, clk: s.clk, logger: s.logger} |
| 464 | _, m, ok, err := ts.liveLinkByID(ctx, linkID) |
| 465 | if err != nil || !ok { |
| 466 | return err |
| 467 | } |
| 468 | if g, err = ts.mintGrant(ctx, m, personID); err != nil { |
| 469 | return err |
| 470 | } |
| 471 | live = true |
| 472 | return nil |
| 473 | }) |
| 474 | }) |
| 475 | if err != nil { |
| 476 | return GuestGrant{}, false, err |
| 477 | } |
| 478 | return g, live, nil |
| 479 | } |
| 480 | |
| 481 | func (s *store) fingerprint(address string) (string, error) { |
| 482 | return s.sealer.Fingerprint(seal.PurposePendingAddress, normalizeAddress(address)) |
| 483 | } |
| 484 | |
| 485 | func (s *store) writePending(ctx context.Context, address string, link MeetingLink) error { |
| 486 | fp, err := s.fingerprint(address) |
| 487 | if err != nil { |
| 488 | return err |
| 489 | } |
| 490 | now := s.now().UTC() |
| 491 | return s.g.WithContext(ctx).Create(&PendingJoin{ |
| 492 | MeetingID: link.MeetingID, LinkID: link.ID, AddressFingerprint: fp, |
| 493 | CreatedAt: now, ExpiresAt: now.Add(pendingLife), |
| 494 | }).Error |
| 495 | } |
| 496 | |
| 497 | // pendingLive is the Authorize half: does this address hold an |
| 498 | // unexpired pending row whose link is still live? |
| 499 | func (s *store) pendingLive(ctx context.Context, address string) (bool, error) { |
| 500 | p, ok, err := s.latestPending(ctx, address) |
| 501 | if err != nil || !ok { |
| 502 | return false, err |
| 503 | } |
| 504 | _, _, live, err := s.liveLinkByID(ctx, p.LinkID) |
| 505 | return live, err |
| 506 | } |
| 507 | |
| 508 | func (s *store) latestPending(ctx context.Context, address string) (PendingJoin, bool, error) { |
| 509 | fp, err := s.fingerprint(address) |
| 510 | if err != nil { |
| 511 | return PendingJoin{}, false, err |
| 512 | } |
| 513 | var p PendingJoin |
| 514 | err = s.g.WithContext(ctx).Where("address_fingerprint = ? AND expires_at > ?", fp, s.now().UTC()). |
| 515 | Order("created_at DESC, id DESC").Take(&p).Error |
| 516 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 517 | return PendingJoin{}, false, nil |
| 518 | } |
| 519 | return p, err == nil, err |
| 520 | } |
| 521 | |
| 522 | func (s *store) deletePending(ctx context.Context, address string) error { |
| 523 | fp, err := s.fingerprint(address) |
| 524 | if err != nil { |
| 525 | return err |
| 526 | } |
| 527 | return s.g.WithContext(ctx).Where("address_fingerprint = ?", fp).Delete(&PendingJoin{}).Error |
| 528 | } |
| 529 | |
| 530 | // consumePending re-checks the pending row's link and meeting as |
| 531 | // GET /j/{token} would, mints the grant for a non-member, and deletes |
| 532 | // every pending row for the address, all in one transaction. It returns |
| 533 | // the holding-screen path, or "" when the re-check failed. |
| 534 | // |
| 535 | // The row is re-selected inside the transaction and the caller's value |
| 536 | // is only trusted when it is still the newest unexpired one (review |
| 537 | // C1-4). latestPending runs before the transaction opens, so by the time |
| 538 | // we get here the row may have been consumed by a concurrent /continue, |
| 539 | // or superseded by a newer request from another browser. A stale value |
| 540 | // must not mint — and must not delete the row that superseded it, so a |
| 541 | // mismatch deletes nothing at all and the caller falls through to / or |
| 542 | // /welcome. Expiry needs no separate check: latestPending already |
| 543 | // excludes expired rows, and the sweeper removes them. |
| 544 | func (s *store) consumePending(ctx context.Context, p Person, pend PendingJoin, member bool) (string, error) { |
| 545 | dest := "" |
| 546 | err := s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 547 | consume := func() error { |
| 548 | dest = "" |
| 549 | ts := &store{g: tx, sealer: s.sealer, clk: s.clk, logger: s.logger} |
| 550 | current, ok, err := ts.latestPending(ctx, p.Email) |
| 551 | if err != nil || !ok || current.ID != pend.ID { |
| 552 | return err |
| 553 | } |
| 554 | if err := ts.deletePending(ctx, p.Email); err != nil { |
| 555 | return err |
| 556 | } |
| 557 | _, m, live, err := ts.liveLinkByID(ctx, current.LinkID) |
| 558 | if err != nil || !live { |
| 559 | return err |
| 560 | } |
| 561 | if !member { |
| 562 | if _, err := ts.mintGrant(ctx, m, p.ID); err != nil { |
| 563 | return err |
| 564 | } |
| 565 | } |
| 566 | dest = "/m/" + m.Sqid + "/join" |
| 567 | return nil |
| 568 | } |
| 569 | if member { |
| 570 | return consume() |
| 571 | } |
| 572 | // A guest's grant stands on the meeting's host, whose Access the |
| 573 | // caller carries on ctx in team mode (team_host.go). |
| 574 | return s.guard(ctx, consume) |
| 575 | }) |
| 576 | if err != nil { |
| 577 | dest = "" |
| 578 | } |
| 579 | return dest, err |
| 580 | } |
| 581 | |
| 582 | // sweepLimit bounds one sweep call to a page of rows, so a large |
| 583 | // backlog cannot hold SQLite's one write connection for an unbounded |
| 584 | // delete (review C2-3). The caller loops while the count it gets back |
| 585 | // is exactly this many. |
| 586 | const sweepLimit = 1000 |
| 587 | |
| 588 | // sweep deletes pending rows whose fifteen minutes are up, at most |
| 589 | // sweepLimit per call via a subselect on ids (a bare DELETE has no |
| 590 | // portable LIMIT). Reads already exclude expired rows; this is about |
| 591 | // not keeping a record past its life (review C1-7). It returns how many |
| 592 | // rows went. |
| 593 | func (s *store) sweep(ctx context.Context, now time.Time) (int64, error) { |
| 594 | res := s.g.WithContext(ctx).Where( |
| 595 | "id IN (SELECT id FROM pending_joins WHERE expires_at <= ? LIMIT ?)", |
| 596 | now.UTC(), sweepLimit, |
| 597 | ).Delete(&PendingJoin{}) |
| 598 | return res.RowsAffected, res.Error |
| 599 | } |
| 600 | |
| 601 | // nextExpiry answers the earliest expires_at across pending_joins, |
| 602 | // rastrillo's own auth_links, and rastrillo's own sessions, or the zero |
| 603 | // time when all three are empty. It is the platform wake-up input for |
| 604 | // cmd/calls/main.go's Options.NextDue (review C2-2). |
| 605 | // |
| 606 | // auth_links matters here too: a plain member sign-in writes no pending |
| 607 | // row at all (that table exists for the outsider/pending-join path, |
| 608 | // spec §3.2), only rastrillo's own magic-link row. If nextExpiry read |
| 609 | // pending_joins alone, an app that hibernated with nothing outstanding |
| 610 | // but one unclicked member link would never be woken to sweep it — the |
| 611 | // platform sees a zero NextDue and assumes there is nothing to do |
| 612 | // (round 2 follow-up, caught on re-review of 9e067e4). |
| 613 | // |
| 614 | // sessions is here for the same reason, one level further out: |
| 615 | // auth.Sweep cleans auth_links AND sessions in one call |
| 616 | // (auth/store.go:117 delegates to sessions.Sweep), so a session sitting |
| 617 | // alone with nothing else outstanding needs the same wake-up guarantee |
| 618 | // an unclicked link does (Codex round 3, C3-1). |
| 619 | func (s *store) nextExpiry(ctx context.Context) (time.Time, error) { |
| 620 | var p PendingJoin |
| 621 | err := s.g.WithContext(ctx).Order("expires_at ASC").Take(&p).Error |
| 622 | var pending time.Time |
| 623 | switch { |
| 624 | case errors.Is(err, gorm.ErrRecordNotFound): |
| 625 | // pending stays zero. |
| 626 | case err != nil: |
| 627 | return time.Time{}, err |
| 628 | default: |
| 629 | pending = p.ExpiresAt |
| 630 | } |
| 631 | |
| 632 | authLink, err := s.rastrilloTextExpiry(ctx, "auth_links") |
| 633 | if err != nil { |
| 634 | return time.Time{}, err |
| 635 | } |
| 636 | session, err := s.rastrilloTextExpiry(ctx, "sessions") |
| 637 | if err != nil { |
| 638 | return time.Time{}, err |
| 639 | } |
| 640 | |
| 641 | next := time.Time{} |
| 642 | for _, t := range []time.Time{pending, authLink, session} { |
| 643 | if t.IsZero() { |
| 644 | continue |
| 645 | } |
| 646 | if next.IsZero() || t.Before(next) { |
| 647 | next = t |
| 648 | } |
| 649 | } |
| 650 | return next, nil |
| 651 | } |
| 652 | |
| 653 | // rastrilloTextExpiry reads the earliest expires_at from one of |
| 654 | // rastrillo's own tables — auth_links or sessions, the only two callers |
| 655 | // pass, never anything caller-supplied. Both are rastrillo's tables, not |
| 656 | // store models: rastrillo writes to them over database/sql rather than |
| 657 | // gorm, storing expires_at as RFC3339 text via |
| 658 | // now.UTC().Format(time.RFC3339) (auth/store.go:83,152, |
| 659 | // sessions/sessions.go:157; see auth/migrations/0001_init.sql and |
| 660 | // sessions/migrations/0001_init.sql for the column). MIN() over that |
| 661 | // text column sorts correctly because every row is formatted the same |
| 662 | // fixed-width, UTC way, so lexicographic and chronological order agree. |
| 663 | // The zero time means no row; an empty table's MIN() is a SQL NULL, not |
| 664 | // an empty string, hence sql.NullString rather than a bare string. |
| 665 | func (s *store) rastrilloTextExpiry(ctx context.Context, table string) (time.Time, error) { |
| 666 | var raw sql.NullString |
| 667 | if err := s.g.WithContext(ctx).Raw("SELECT MIN(expires_at) FROM " + table).Row().Scan(&raw); err != nil { |
| 668 | return time.Time{}, err |
| 669 | } |
| 670 | if !raw.Valid || raw.String == "" { |
| 671 | return time.Time{}, nil |
| 672 | } |
| 673 | t, err := time.Parse(time.RFC3339, raw.String) |
| 674 | if err != nil { |
| 675 | return time.Time{}, fmt.Errorf("calls: parse %s.expires_at: %w", table, err) |
| 676 | } |
| 677 | return t, nil |
| 678 | } |
| 679 | |
| 680 | // Identity rows use AUTOINCREMENT and are never recycled for another person. |
| 681 | func (s *store) existingHomePerson(ctx context.Context, address string) (Person, error) { |
| 682 | var p Person |
| 683 | err := s.g.WithContext(ctx).Where("email = ?", normalizeAddress(address)).Take(&p).Error |
| 684 | return p, err |
| 685 | } |
| 686 | func (s *store) homePersonByID(ctx context.Context, q interface { |
| 687 | QueryRowContext(context.Context, string, ...any) *sql.Row |
| 688 | }, id int64) (Person, error) { |
| 689 | var p Person |
| 690 | err := q.QueryRowContext(ctx, "SELECT id, email, name FROM persons WHERE id = ?", id).Scan(&p.ID, &p.Email, &p.Name) |
| 691 | return p, err |
| 692 | } |
| 693 | |
| 694 | func (s *store) meetingDefaults(ctx context.Context) (MeetingDefaults, error) { |
| 695 | var d MeetingDefaults |
| 696 | err := s.g.WithContext(ctx).Where("id = ?", 1).Take(&d).Error |
| 697 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 698 | return MeetingDefaults{ID: 1}, nil |
| 699 | } |
| 700 | return d, err |
| 701 | } |
| 702 | func (s *store) saveMeetingDefaults(ctx context.Context, signin, waiting bool) error { |
| 703 | return s.guarded(ctx, func(g *gorm.DB) error { |
| 704 | return g.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "id"}}, DoUpdates: clause.AssignmentColumns([]string{"require_signin", "waiting_room"})}).Create(&MeetingDefaults{ID: 1, RequireSignin: signin, WaitingRoom: waiting}).Error |
| 705 | }) |
| 706 | } |
| 707 | |
| 708 | // Meetings are team-owned, as are the other meeting mutations in this store. |
| 709 | func (s *store) saveMeetingSettings(ctx context.Context, id int64, signin, waiting bool) error { |
| 710 | return s.guarded(ctx, func(g *gorm.DB) error { |
| 711 | return g.Model(&Meeting{}).Where("id = ? AND ended_at IS NULL", id).Select("RequireSignin", "WaitingRoom").Updates(map[string]any{"RequireSignin": signin, "WaitingRoom": waiting}).Error |
| 712 | }) |
| 713 | } |
| 714 | |
| 715 | // guestWithGrant is team mode's named guest: the anonymous person and |
| 716 | // their grant through the link, in one transaction inside the standing |
| 717 | // guard (the meeting host's, which the caller carries on ctx). False, with |
| 718 | // nothing written, when the link is no longer live. |
| 719 | func (s *store) guestWithGrant(ctx context.Context, name string, linkID int64) (Person, bool, error) { |
| 720 | var p Person |
| 721 | live := false |
| 722 | err := s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 723 | return s.guard(ctx, func() error { |
| 724 | live = false |
| 725 | ts := &store{g: tx, sealer: s.sealer, clk: s.clk, logger: s.logger} |
| 726 | _, m, ok, err := ts.liveLinkByID(ctx, linkID) |
| 727 | if err != nil || !ok { |
| 728 | return err |
| 729 | } |
| 730 | if p, err = ts.createGuest(ctx, name); err != nil { |
| 731 | return err |
| 732 | } |
| 733 | if _, err = ts.mintGrant(ctx, m, p.ID); err != nil { |
| 734 | return err |
| 735 | } |
| 736 | live = true |
| 737 | return nil |
| 738 | }) |
| 739 | }) |
| 740 | if err != nil || !live { |
| 741 | return Person{}, false, err |
| 742 | } |
| 743 | return p, true, nil |
| 744 | } |
| 745 | |
| 746 | func (s *store) createGuest(ctx context.Context, name string) (Person, error) { |
| 747 | p := Person{Email: "guest:" + nativeRandom(), Name: name, Anonymous: true, CreatedAt: s.now().UTC()} |
| 748 | err := s.g.WithContext(ctx).Create(&p).Error |
| 749 | return p, err |
| 750 | } |
| 751 | |
| 752 | // saveDeviceToken records where a person can be reached when the app is |
| 753 | // not running, and is an upsert on the token rather than on the person: |
| 754 | // Apple reissues a token to whoever installs the app next, so the same |
| 755 | // string arriving under a different person means the device changed |
| 756 | // hands and the old row is wrong. LastSeen moves on every registration, |
| 757 | // which is what lets a token that has gone quiet be swept later. |
| 758 | func (s *store) saveDeviceToken(ctx context.Context, personID int64, token, platform string) error { |
| 759 | now := s.now().UTC() |
| 760 | return s.guarded(ctx, func(g *gorm.DB) error { |
| 761 | return g.Clauses(clause.OnConflict{ |
| 762 | Columns: []clause.Column{{Name: "token"}}, |
| 763 | DoUpdates: clause.AssignmentColumns([]string{"person_id", "platform", "last_seen"}), |
| 764 | }).Create(&DeviceToken{ |
| 765 | PersonID: personID, Token: token, Platform: platform, CreatedAt: now, LastSeen: now, |
| 766 | }).Error |
| 767 | }) |
| 768 | } |
| 769 | |
| 770 | // deviceTokensFor answers every device a set of people can be reached |
| 771 | // on. Plural because one person has a Mac and a phone, and a knock is |
| 772 | // worth saying on both — whichever they are near. |
| 773 | func (s *store) deviceTokensFor(ctx context.Context, personIDs []int64) ([]DeviceToken, error) { |
| 774 | if len(personIDs) == 0 { |
| 775 | return nil, nil |
| 776 | } |
| 777 | var tokens []DeviceToken |
| 778 | err := s.g.WithContext(ctx).Where("person_id IN ?", personIDs).Find(&tokens).Error |
| 779 | return tokens, err |
| 780 | } |
| 781 | |
| 782 | // forgetDeviceToken deletes one token, which is the only correct answer |
| 783 | // to Apple reporting it unregistered. Deleting by token and not by |
| 784 | // person: the device is gone, the person is not. |
| 785 | func (s *store) forgetDeviceToken(ctx context.Context, token string) error { |
| 786 | return s.g.WithContext(ctx).Where("token = ?", token).Delete(&DeviceToken{}).Error |
| 787 | } |
| 788 | |
| 789 | // memberPersonIDs is everyone who may admit: the people whose address is |
| 790 | // on the team allowlist. A knock is theirs to answer, and nobody else's. |
| 791 | func (s *store) memberPersonIDs(ctx context.Context, allowed allowlist) ([]int64, error) { |
| 792 | var persons []Person |
| 793 | if err := s.g.WithContext(ctx).Where("email NOT LIKE ?", "guest:%").Find(&persons).Error; err != nil { |
| 794 | return nil, err |
| 795 | } |
| 796 | ids := make([]int64, 0, len(persons)) |
| 797 | for _, p := range persons { |
| 798 | if allowed.allows(p.Email) { |
| 799 | ids = append(ids, p.ID) |
| 800 | } |
| 801 | } |
| 802 | return ids, nil |
| 803 | } |
| 804 | |