Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(wecom): throttle binding-token minting to one link per user per minute (MUL-5880) (#6584)

Xichang(Seacen) Zhao72304b34cd2d
diff --git a/server/internal/integrations/wecom/binding.go b/server/internal/integrations/wecom/binding.go
index e7ed948085..1ce3ace285 100644
--- a/server/internal/integrations/wecom/binding.go
+++ b/server/internal/integrations/wecom/binding.go
@@ -35,6 +35,36 @@ import (
// longer.
const BindingTokenTTL = 15 * time.Minute
+// BindingTokenMintInterval is how often one platform user can be issued a new
+// binding link. Every message from an unbound user reaches the needs_binding
+// outcome, so without a floor here a user who types six lines writes six token
+// rows and receives six links, only the last of which they will click.
+//
+// This is a burst window, not a session-long one, and the distinction matters.
+// Suppressing a mint asserts that the link already sent is in the user's
+// hands, and nothing verifies that: the send returns as soon as the transport
+// accepts the frame and the socket acks asynchronously. If the first prompt is
+// lost, a long window turns that into a dead end — every message is answered
+// with "tap the link I sent you", pointing at something that never arrived,
+// and the user cannot link their account until the window passes.
+//
+// That covers the send we never hear back about, and equally the send we know
+// failed: the row is written before delivery is attempted, so a prompt the
+// transport refused outright (no live connection mid-reconnect or lease flip)
+// still suppresses the next minute of mints. Nothing here reacts to that
+// error — the window itself, not a delivery receipt, is what bounds the
+// damage, which is the other reason to keep it short.
+//
+// Sixty seconds does the job the throttle was written for: six lines typed in
+// one breath still write one row, at a cost of at most one row a minute for a
+// user who keeps going, against rows that expire in fifteen. The price of
+// being wrong is one more message, not ten minutes of a bot insisting it
+// already answered.
+//
+// It must stay comfortably inside BindingTokenTTL so a link a throttled user
+// is pointed back at still has real time left on it.
+const BindingTokenMintInterval = time.Minute
+
var (
// ErrBindingTokenInvalid: token unknown / already consumed / expired.
// One opaque error for all three avoids a replay timing oracle.
@@ -53,6 +83,14 @@ var (
type BindingToken struct {
Raw string
ExpiresAt time.Time
+
+ // Reused says the throttle suppressed the mint because a live link is
+ // already sitting in the user's chat. Raw is empty in that case and there
+ // is no way to recover it — the table only ever held the hash — so the
+ // caller must point the user back at the earlier message rather than
+ // building a URL. ExpiresAt carries the live token's expiry, not a fresh
+ // one's.
+ Reused bool
}
// RedeemedBindingToken is returned after a successful redemption.
@@ -62,32 +100,76 @@ type RedeemedBindingToken struct {
WecomUserID string
}
+// bindingMintQueries is the slice of generated queries the mint path uses.
+// Narrow on purpose: mint is the only part of the service that runs outside a
+// transaction, so it is the only part a unit test can drive with a fake.
+// *db.Queries satisfies it.
+type bindingMintQueries interface {
+ CreateChannelBindingToken(ctx context.Context, arg db.CreateChannelBindingTokenParams) (db.ChannelBindingToken, error)
+ FindLiveChannelBindingToken(ctx context.Context, arg db.FindLiveChannelBindingTokenParams) (db.ChannelBindingToken, error)
+}
+
// BindingTokenService mints and redeems WeCom binding tokens. Redemption is
// transactional: consuming the token and inserting the channel_user_binding
// row commit together, so a failed bind never burns a token.
type BindingTokenService struct {
- q *db.Queries
- tx engine.TxStarter
- now func() time.Time
+ q *db.Queries
+ mint bindingMintQueries
+ tx engine.TxStarter
+ now func() time.Time
}
// NewBindingTokenService constructs the service. tx (a *pgxpool.Pool) is
// needed for the transactional redeem path.
func NewBindingTokenService(q *db.Queries, tx engine.TxStarter) *BindingTokenService {
- return &BindingTokenService{q: q, tx: tx, now: time.Now}
+ return &BindingTokenService{q: q, mint: q, tx: tx, now: time.Now}
}
// Mint creates a single-use binding token for (installation, wecomUserID)
// and returns the raw secret + expiry. The raw value must be delivered over
// the aibot WebSocket (encrypted in transit by the platform) and never
// logged.
+//
+// Throttled: if this user already has a live, unconsumed token minted inside
+// BindingTokenMintInterval, no row is written and the result comes back with
+// Reused set and Raw empty — the raw secret was never stored, so there is
+// nothing to hand back. Callers point the user at the link already in their
+// chat instead. This is what keeps an unbound user's message stream from
+// writing a token row per message.
+//
+// Best-effort, not a guarantee: the lookup and the insert are two statements,
+// so two replies racing on the same user can both miss and both mint. In
+// practice they are serialised by a wide margin — the inbound read loop
+// dispatches one frame at a time and the second reply is a whole dispatch
+// behind — and losing the race costs one extra row and one extra link, both
+// private to that same user and both expiring on the usual TTL. Tightening it
+// further would mean holding a lock across the inbound hot path, which is not
+// worth it for a cosmetic throttle.
func (s *BindingTokenService) Mint(ctx context.Context, workspaceID, installationID pgtype.UUID, wecomUserID string) (BindingToken, error) {
+ if s.mint == nil {
+ return BindingToken{}, errors.New("wecom: BindingTokenService missing queries")
+ }
+ live, err := s.mint.FindLiveChannelBindingToken(ctx, db.FindLiveChannelBindingTokenParams{
+ InstallationID: installationID,
+ ChannelType: channelTypeWecom,
+ ChannelUserID: wecomUserID,
+ MintInterval: pgtype.Interval{Microseconds: BindingTokenMintInterval.Microseconds(), Valid: true},
+ })
+ switch {
+ case err == nil:
+ return BindingToken{ExpiresAt: live.ExpiresAt.Time, Reused: true}, nil
+ case errors.Is(err, pgx.ErrNoRows):
+ // Nothing live for this user — mint below.
+ default:
+ return BindingToken{}, fmt.Errorf("wecom: look up live token: %w", err)
+ }
+
raw, err := randomBindingToken(32)
if err != nil {
return BindingToken{}, fmt.Errorf("wecom: generate token: %w", err)
}
expiresAt := s.now().Add(BindingTokenTTL)
- if _, err := s.q.CreateChannelBindingToken(ctx, db.CreateChannelBindingTokenParams{
+ if _, err := s.mint.CreateChannelBindingToken(ctx, db.CreateChannelBindingTokenParams{
TokenHash: hashBindingToken(raw),
WorkspaceID: workspaceID,
InstallationID: installationID,
diff --git a/server/internal/integrations/wecom/binding_test.go b/server/internal/integrations/wecom/binding_test.go
new file mode 100644
index 0000000000..665b3ae66c
--- /dev/null
+++ b/server/internal/integrations/wecom/binding_test.go
@@ -0,0 +1,217 @@
+package wecom
+
+// binding_test.go — minting a binding token is a write, and it happened once
+// per inbound message from an unbound user. Someone who types six lines at a
+// bot they have not linked yet wrote six rows and got six links, only the
+// last of which they would ever click.
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func bindingUUID(b byte) pgtype.UUID { return pgtype.UUID{Bytes: [16]byte{b}, Valid: true} }
+
+// fakeMintQueries stands in for channel_binding_token, applying the same
+// predicates FindLiveChannelBindingToken does so the throttle is exercised
+// against the real filter rather than a stub that always answers.
+type fakeMintQueries struct {
+ rows []db.ChannelBindingToken
+ creates int
+ now func() time.Time
+}
+
+func (f *fakeMintQueries) CreateChannelBindingToken(_ context.Context, arg db.CreateChannelBindingTokenParams) (db.ChannelBindingToken, error) {
+ f.creates++
+ row := db.ChannelBindingToken{
+ TokenHash: arg.TokenHash,
+ WorkspaceID: arg.WorkspaceID,
+ InstallationID: arg.InstallationID,
+ ChannelType: arg.ChannelType,
+ ChannelUserID: arg.ChannelUserID,
+ ExpiresAt: arg.ExpiresAt,
+ CreatedAt: pgtype.Timestamptz{Time: f.now(), Valid: true},
+ }
+ f.rows = append(f.rows, row)
+ return row, nil
+}
+
+func (f *fakeMintQueries) FindLiveChannelBindingToken(_ context.Context, arg db.FindLiveChannelBindingTokenParams) (db.ChannelBindingToken, error) {
+ var best db.ChannelBindingToken
+ found := false
+ for _, r := range f.rows {
+ if r.InstallationID != arg.InstallationID || r.ChannelType != arg.ChannelType || r.ChannelUserID != arg.ChannelUserID {
+ continue
+ }
+ if r.ConsumedAt.Valid {
+ continue
+ }
+ if !r.ExpiresAt.Time.After(f.now()) {
+ continue
+ }
+ // The query derives its cutoff from now() on the database side, so
+ // the fake resolves the window against the same clock it stamps
+ // created_at with rather than against a caller-supplied timestamp.
+ cutoff := f.now().Add(-time.Duration(arg.MintInterval.Microseconds) * time.Microsecond)
+ if r.CreatedAt.Time.Before(cutoff) {
+ continue
+ }
+ if !found || r.CreatedAt.Time.After(best.CreatedAt.Time) {
+ best, found = r, true
+ }
+ }
+ if !found {
+ return db.ChannelBindingToken{}, pgx.ErrNoRows
+ }
+ return best, nil
+}
+
+func newThrottledService() (*BindingTokenService, *fakeMintQueries, *time.Time) {
+ clock := time.Now()
+ fake := &fakeMintQueries{now: func() time.Time { return clock }}
+ svc := &BindingTokenService{mint: fake, now: func() time.Time { return clock }}
+ return svc, fake, &clock
+}
+
+// TestMintReusesTheLinkAlreadySent: the second message inside the window must
+// not write another row. Fails on the pre-change Mint, which inserted every
+// time it was called.
+func TestMintReusesTheLinkAlreadySent(t *testing.T) {
+ svc, fake, _ := newThrottledService()
+ ws, inst := bindingUUID(1), bindingUUID(2)
+
+ first, err := svc.Mint(context.Background(), ws, inst, "T-alex")
+ if err != nil {
+ t.Fatalf("first mint: %v", err)
+ }
+ if first.Reused {
+ t.Fatal("the first mint cannot be a reuse")
+ }
+ if first.Raw == "" {
+ t.Fatal("the first mint must return a raw token")
+ }
+
+ for i := 0; i < 5; i++ {
+ again, err := svc.Mint(context.Background(), ws, inst, "T-alex")
+ if err != nil {
+ t.Fatalf("mint #%d: %v", i+2, err)
+ }
+ if !again.Reused {
+ t.Fatalf("mint #%d minted a second token inside the throttle window", i+2)
+ }
+ if again.Raw != "" {
+ t.Fatal("a reused token cannot hand back a raw secret it never stored")
+ }
+ if !again.ExpiresAt.Equal(first.ExpiresAt) {
+ t.Fatalf("reuse reported expiry %v, want the live token's %v", again.ExpiresAt, first.ExpiresAt)
+ }
+ }
+ if fake.creates != 1 {
+ t.Fatalf("six messages wrote %d token rows, want 1", fake.creates)
+ }
+}
+
+// TestMintIssuesAFreshLinkAfterTheWindow: the throttle must not lock a user
+// out — once the window passes they get a new link.
+func TestMintIssuesAFreshLinkAfterTheWindow(t *testing.T) {
+ svc, fake, clock := newThrottledService()
+ ws, inst := bindingUUID(1), bindingUUID(2)
+
+ if _, err := svc.Mint(context.Background(), ws, inst, "T-alex"); err != nil {
+ t.Fatalf("first mint: %v", err)
+ }
+ *clock = clock.Add(BindingTokenMintInterval + time.Second)
+
+ again, err := svc.Mint(context.Background(), ws, inst, "T-alex")
+ if err != nil {
+ t.Fatalf("second mint: %v", err)
+ }
+ if again.Reused || again.Raw == "" {
+ t.Fatal("past the throttle window the user must get a fresh link")
+ }
+ if fake.creates != 2 {
+ t.Fatalf("%d rows written, want 2", fake.creates)
+ }
+}
+
+// TestMintStillReusesPartWayThroughTheWindow pins the width of the window
+// itself. The two tests above only exercise its edges — same instant, and
+// past it — which a zero-length interval satisfies just as well, so neither
+// would notice if Mint stopped passing a real one. Halfway through, a zero
+// interval reads as expired and mints again.
+func TestMintStillReusesPartWayThroughTheWindow(t *testing.T) {
+ svc, fake, clock := newThrottledService()
+ ws, inst := bindingUUID(1), bindingUUID(2)
+
+ if _, err := svc.Mint(context.Background(), ws, inst, "T-alex"); err != nil {
+ t.Fatalf("first mint: %v", err)
+ }
+ *clock = clock.Add(BindingTokenMintInterval / 2)
+
+ again, err := svc.Mint(context.Background(), ws, inst, "T-alex")
+ if err != nil {
+ t.Fatalf("second mint: %v", err)
+ }
+ if !again.Reused {
+ t.Fatal("a link half a window old is still the one to point back at")
+ }
+ if fake.creates != 1 {
+ t.Fatalf("%d rows written, want 1", fake.creates)
+ }
+}
+
+// TestMintIsPerUser: one user's pending link must not silence another's.
+func TestMintIsPerUser(t *testing.T) {
+ svc, fake, _ := newThrottledService()
+ ws, inst := bindingUUID(1), bindingUUID(2)
+
+ if _, err := svc.Mint(context.Background(), ws, inst, "T-alex"); err != nil {
+ t.Fatalf("mint alex: %v", err)
+ }
+ dana, err := svc.Mint(context.Background(), ws, inst, "T-dana")
+ if err != nil {
+ t.Fatalf("mint dana: %v", err)
+ }
+ if dana.Reused || dana.Raw == "" {
+ t.Fatal("a second user must get their own link")
+ }
+ if fake.creates != 2 {
+ t.Fatalf("%d rows written, want 2", fake.creates)
+ }
+}
+
+// TestMintIgnoresAConsumedToken: they bound, then unbound and came back.
+func TestMintIgnoresAConsumedToken(t *testing.T) {
+ svc, fake, _ := newThrottledService()
+ ws, inst := bindingUUID(1), bindingUUID(2)
+
+ if _, err := svc.Mint(context.Background(), ws, inst, "T-alex"); err != nil {
+ t.Fatalf("first mint: %v", err)
+ }
+ fake.rows[0].ConsumedAt = pgtype.Timestamptz{Time: fake.now(), Valid: true}
+
+ again, err := svc.Mint(context.Background(), ws, inst, "T-alex")
+ if err != nil {
+ t.Fatalf("second mint: %v", err)
+ }
+ if again.Reused || again.Raw == "" {
+ t.Fatal("a consumed token must not suppress a new one")
+ }
+ if fake.creates != 2 {
+ t.Fatalf("%d rows written, want 2", fake.creates)
+ }
+}
+
+// TestMintThrottleWindowIsShorterThanTheTTL — a throttle at or past the TTL
+// would leave a user with no valid link and no way to get one.
+func TestMintThrottleWindowIsShorterThanTheTTL(t *testing.T) {
+ if BindingTokenMintInterval >= BindingTokenTTL {
+ t.Fatalf("throttle %v must stay inside the %v token TTL", BindingTokenMintInterval, BindingTokenTTL)
+ }
+}
diff --git a/server/internal/integrations/wecom/replier.go b/server/internal/integrations/wecom/replier.go
index 2fd3687289..75f2441374 100644
--- a/server/internal/integrations/wecom/replier.go
+++ b/server/internal/integrations/wecom/replier.go
@@ -145,8 +145,22 @@ func (r *OutboundReplier) sendBindingPrompt(ctx context.Context, inst engine.Res
if err != nil {
return fmt.Errorf("wecom: mint binding token: %w", err)
}
- bindURL := r.appURL + r.bindingPath + "?token=" + url.QueryEscape(token.Raw)
- text := "👋 请先绑定你的 Multica 账号,才能与我对话:\n" + bindURL + "\n(链接 15 分钟内有效)"
+ // The throttle suppressed the mint: a live link is already with this user.
+ // Only its hash was ever stored, so there is no URL to rebuild — point
+ // them at the message they already have. The throttle window is far
+ // shorter than the TTL, so that link still has most of its life left.
+ //
+ // This text is delivered by postPrivate below, which always lands in the
+ // 1:1 — the same conversation the earlier link is sitting in, whichever
+ // room triggered this. So it points up the current thread rather than
+ // telling the reader to go to a chat they are already reading. Only the
+ // group ack further down runs in the room, and it is the one that names
+ // the 1:1.
+ text := "👋 绑定链接刚才已经发给你了,就在上方,请直接点击完成绑定。"
+ if !token.Reused {
+ bindURL := r.appURL + r.bindingPath + "?token=" + url.QueryEscape(token.Raw)
+ text = "👋 请先绑定你的 Multica 账号,才能与我对话:\n" + bindURL + "\n(链接 15 分钟内有效)"
+ }
// A binding token is a bearer credential: binding.Redeem only checks that
// the redeemer belongs to the token's workspace, and the bind page redeems
// on load as whoever is signed in. Sending it to msg.Source.ChatID — which
diff --git a/server/internal/integrations/wecom/replier_test.go b/server/internal/integrations/wecom/replier_test.go
index f55e5a188a..47b3cab6cd 100644
--- a/server/internal/integrations/wecom/replier_test.go
+++ b/server/internal/integrations/wecom/replier_test.go
@@ -25,9 +25,17 @@ import (
)
// fakeBinder mints a fixed, recognizable raw token without touching a DB.
-type fakeBinder struct{ raw string }
+// With reused set it behaves like the throttle suppressing a mint: no raw
+// secret, only the live token's expiry.
+type fakeBinder struct {
+ raw string
+ reused bool
+}
func (f fakeBinder) Mint(context.Context, pgtype.UUID, pgtype.UUID, string) (BindingToken, error) {
+ if f.reused {
+ return BindingToken{ExpiresAt: time.Now().Add(14 * time.Minute), Reused: true}, nil
+ }
return BindingToken{Raw: f.raw, ExpiresAt: time.Now().Add(15 * time.Minute)}, nil
}
@@ -228,3 +236,68 @@ func TestSendBindingPrompt_P2PSendsOnlyPrivately(t *testing.T) {
t.Errorf("p2p token frame = %v, want USER_A at chat_type 1", body)
}
}
+
+// TestSendBindingPrompt_ThrottledSendsNoURL: when the throttle suppresses a
+// mint there is no raw secret to build a link from — the hash is all the table
+// ever held. Building the URL anyway yields "?token=" with nothing after it,
+// which is a dead link the user will tap and be refused by. The reply must
+// point them at the message they already have instead, and the room must
+// still get its answer.
+func TestSendBindingPrompt_ThrottledSendsNoURL(t *testing.T) {
+ t.Parallel()
+ const senderID = "SENDER_USERID"
+ const groupID = "GROUP_CHAT_ID"
+
+ reg := newSendersRegistry()
+ inst := engine.ResolvedInstallation{ID: mustTestUUID(t)}
+ conn := &recordingConn{}
+ reg.set(inst.ID, newWSSender(conn, nil))
+ r := NewOutboundReplier(OutboundReplierConfig{
+ Senders: reg,
+ AppURL: "https://multica.example",
+ })
+ r.binding = fakeBinder{reused: true}
+
+ msg := channel.InboundMessage{Source: channel.Source{
+ ChatID: groupID,
+ ChatType: channel.ChatTypeGroup,
+ SenderID: senderID,
+ }}
+ if err := r.sendBindingPrompt(context.Background(), inst, msg, engine.Result{Sender: senderID}); err != nil {
+ t.Fatalf("sendBindingPrompt: %v", err)
+ }
+
+ conn.mu.Lock()
+ frames := append([]frameEnvelope(nil), conn.frames...)
+ conn.mu.Unlock()
+ if len(frames) != 2 {
+ t.Fatalf("expected 2 frames (private notice + group ack), got %d", len(frames))
+ }
+
+ privateFrames := 0
+ for i := range frames {
+ var body map[string]any
+ if err := json.Unmarshal(frames[i].Body, &body); err != nil {
+ t.Fatalf("decode frame %d: %v", i, err)
+ }
+ content := ""
+ if md, ok := body["markdown"].(map[string]any); ok {
+ content, _ = md["content"].(string)
+ }
+ if strings.Contains(content, "token=") {
+ t.Errorf("a throttled prompt built a URL with no token in it: %q", content)
+ }
+ if strings.Contains(content, "https://multica.example") {
+ t.Errorf("a throttled prompt must not carry a bind link at all: %q", content)
+ }
+ if chatID, _ := body["chatid"].(string); chatID == senderID {
+ privateFrames++
+ if body["chat_type"] != float64(chatTypeSingleInt) {
+ t.Errorf("private frame chat_type = %v, want single (1)", body["chat_type"])
+ }
+ }
+ }
+ if privateFrames != 1 {
+ t.Errorf("expected exactly one privately-addressed frame, got %d", privateFrames)
+ }
+}
diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.go
index 7d50d48290..45f2850424 100644
--- a/server/pkg/db/generated/channel.sql.go
+++ b/server/pkg/db/generated/channel.sql.go
@@ -726,6 +726,66 @@ func (q *Queries) FindChannelBindingForMember(ctx context.Context, arg FindChann
return i, err
}
+const findLiveChannelBindingToken = `-- name: FindLiveChannelBindingToken :one
+SELECT token_hash, workspace_id, installation_id, channel_type, channel_user_id, expires_at, consumed_at, created_at FROM channel_binding_token
+WHERE installation_id = $1
+ AND channel_type = $2
+ AND channel_user_id = $3
+ AND consumed_at IS NULL
+ AND expires_at > now()
+ AND created_at >= now() - $4::interval
+ORDER BY created_at DESC
+LIMIT 1
+`
+
+type FindLiveChannelBindingTokenParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ChannelType string `json:"channel_type"`
+ ChannelUserID string `json:"channel_user_id"`
+ MintInterval pgtype.Interval `json:"mint_interval"`
+}
+
+// Mint guard: the newest token for this platform user that is still
+// unconsumed, unexpired, and recent enough that the link already sitting in
+// their chat is the one to point back at. Without it every message from an
+// unbound user mints another row, so a user who keeps typing at a bot they
+// have not linked yet writes one row per message. This narrows that to
+// roughly one row per window; it is not a hard guarantee, since the caller
+// runs this and the insert as two statements.
+//
+// `mint_interval` is the caller's throttle window (see
+// wecom.BindingTokenMintInterval). It is subtracted from now() rather than
+// passed in as an absolute cutoff so the whole window is measured on the
+// database clock: created_at is stamped by the column default, and comparing
+// it against an application-side timestamp would let clock skew between the
+// two stretch or shrink the window. The consumed_at / expires_at predicates
+// keep an already-redeemed or stale token from suppressing a mint the user
+// actually needs.
+//
+// idx_channel_binding_token_installation covers the installation_id prefix;
+// the rest is a filter over that installation's live tokens, which is a small
+// set because nothing here outlives the 15-minute TTL.
+func (q *Queries) FindLiveChannelBindingToken(ctx context.Context, arg FindLiveChannelBindingTokenParams) (ChannelBindingToken, error) {
+ row := q.db.QueryRow(ctx, findLiveChannelBindingToken,
+ arg.InstallationID,
+ arg.ChannelType,
+ arg.ChannelUserID,
+ arg.MintInterval,
+ )
+ var i ChannelBindingToken
+ err := row.Scan(
+ &i.TokenHash,
+ &i.WorkspaceID,
+ &i.InstallationID,
+ &i.ChannelType,
+ &i.ChannelUserID,
+ &i.ExpiresAt,
+ &i.ConsumedAt,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
const findReusableChannelUserBinding = `-- name: FindReusableChannelUserBinding :one
SELECT b.id, b.workspace_id, b.multica_user_id, b.installation_id, b.channel_type, b.channel_user_id, b.config, b.bound_at FROM channel_user_binding b
JOIN channel_installation ci ON ci.id = b.installation_id
diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sql
index 428178c994..e52b0470fa 100644
--- a/server/pkg/db/queries/channel.sql
+++ b/server/pkg/db/queries/channel.sql
@@ -641,6 +641,37 @@ INSERT INTO channel_binding_token (
)
RETURNING *;
+-- name: FindLiveChannelBindingToken :one
+-- Mint guard: the newest token for this platform user that is still
+-- unconsumed, unexpired, and recent enough that the link already sitting in
+-- their chat is the one to point back at. Without it every message from an
+-- unbound user mints another row, so a user who keeps typing at a bot they
+-- have not linked yet writes one row per message. This narrows that to
+-- roughly one row per window; it is not a hard guarantee, since the caller
+-- runs this and the insert as two statements.
+--
+-- `mint_interval` is the caller's throttle window (see
+-- wecom.BindingTokenMintInterval). It is subtracted from now() rather than
+-- passed in as an absolute cutoff so the whole window is measured on the
+-- database clock: created_at is stamped by the column default, and comparing
+-- it against an application-side timestamp would let clock skew between the
+-- two stretch or shrink the window. The consumed_at / expires_at predicates
+-- keep an already-redeemed or stale token from suppressing a mint the user
+-- actually needs.
+--
+-- idx_channel_binding_token_installation covers the installation_id prefix;
+-- the rest is a filter over that installation's live tokens, which is a small
+-- set because nothing here outlives the 15-minute TTL.
+SELECT * FROM channel_binding_token
+WHERE installation_id = $1
+ AND channel_type = $2
+ AND channel_user_id = $3
+ AND consumed_at IS NULL
+ AND expires_at > now()
+ AND created_at >= now() - sqlc.arg('mint_interval')::interval
+ORDER BY created_at DESC
+LIMIT 1;
+
-- name: ConsumeChannelBindingToken :one
-- Atomic redemption: returns the row only if the hash exists, is
-- unconsumed, and unexpired. Two simultaneous redemptions cannot both win.