Cotton code
406 lines · 13.4 KB · GoRaw
package mainimport (	"context"	"crypto/rand"	"encoding/hex"	"encoding/json"	"errors"	"fmt"	"strings"	"time"	"go.mau.fi/whatsmeow"	"go.mau.fi/whatsmeow/store"	"go.mau.fi/whatsmeow/types"	"go.mau.fi/whatsmeow/types/events")// A pairing links a new number. WhatsApp offers a fresh QR every ~20 s (six of them, 160 s in// all); by phone number the helper asks once for the code the person types under Linked devices ›// Link with phone number. Since November 2026 WhatsApp may then ask the companion for a passkey// assertion before it links (whatsmeow's pair-passkey.go):////	PairPasskeyRequest      → pair_passkey { options }, status "passkey": the Mac asks the//	                          person's passkey for an assertion over those WebAuthn options//	passkey_response        → SendPasskeyResponse, status "passkey_sent"//	PairPasskeyConfirmation → pair_passkey_code { code, skip }, status "passkey_code": the person//	                          checks the code against the phone's; with skip the helper confirms//	passkey_confirm         → SendPasskeyConfirmation, status "passkey_confirmed"//	PairSuccess             → paired//// Once WhatsApp asks for the passkey the QR codes stop counting: the pairing waits passkeyWait// (whatsmeow keeps the handoff key that long) and then ends failed. A PairPasskeyError ends it// failed, saying why. A failed pairing is never started again by the helper.// The pairing's own clocks; tests shorten them.var (	qrFirstWait = 60 * time.Second	qrNextWait  = 20 * time.Second	passkeyWait = 5 * time.Minute	pairingCap  = 15 * time.Minute)// pairClient is what a pairing asks of its whatsmeow client; a fake stands in for it in tests.type pairClient interface {	PairPhone(ctx context.Context, phone string, showPushNotification bool, clientType whatsmeow.PairClientType, clientDisplayName string) (string, error)	SendPasskeyResponse(ctx context.Context, resp *types.WebAuthnResponse) error	SendPasskeyConfirmation(ctx context.Context) error	Disconnect()}type pairing struct {	cli    pairClient	ctx    context.Context	cancel context.CancelFunc	state  PairState	// failed ends the watcher from a command that WhatsApp refused.	failed chan string}// PairState is what `pair_status` answers: the Mac polls it while the person scans or types.type PairState struct {	Pairing string `json:"pairing"`	// starting, qr, code, passkey, passkey_sent, passkey_code, passkey_confirmed, paired, failed, cancelled	Status  string          `json:"status"`	QR      string          `json:"qr,omitempty"`	Code    string          `json:"code,omitempty"`	Passkey json.RawMessage `json:"passkey,omitempty"` // passkey: the WebAuthn request options, as WhatsApp sent them	Confirm string          `json:"confirm,omitempty"` // passkey_code: the code the phone shows too	Skip    bool            `json:"skip,omitempty"`    // passkey_code: WhatsApp needs no check; the helper confirmed	Account string          `json:"account,omitempty"`	Error   string          `json:"error,omitempty"`}func newPairingID() string {	b := make([]byte, 8)	_, _ = rand.Read(b)	return hex.EncodeToString(b)}// pairingEvent says whether a client event belongs to the pairing watcher.func pairingEvent(evt any) bool {	switch evt.(type) {	case *events.QR, *events.RotateADVSecret, *events.QRScannedWithoutMultidevice,		*events.PairPasskeyRequest, *events.PairPasskeyConfirmation, *events.PairPasskeyError,		*events.PairSuccess, *events.PairError, *events.ClientOutdated, *events.Disconnected,		*events.Connected, *events.ConnectFailure, *events.LoggedOut, *events.TemporaryBan:		return true	}	return false}// Pair starts linking a new number: pair_qr events for a QR without a phone, one pair_code for the// number with one.func (h *Hub) Pair(phone string) (string, error) {	device := h.container.NewDevice()	cli := h.newClient(device)	ctx, cancel := context.WithTimeout(context.Background(), pairingCap)	evs := make(chan any, 64)	handler := cli.AddEventHandler(func(evt any) {		if !pairingEvent(evt) {			return		}		select {		case evs <- evt:		default:			h.log.Errorf("pairing event dropped, the watcher is behind: %T", evt)		}	})	if err := cli.ConnectContext(ctx); err != nil {		cancel()		return "", err	}	id := newPairingID()	if !h.mu.TryLock() {		cancel()		cli.Disconnect()		return "", errors.New("busy")	}	h.pairings[id] = &pairing{cli: cli, ctx: ctx, cancel: cancel, state: PairState{Pairing: id, Status: "starting"}, failed: make(chan string, 1)}	h.mu.Unlock()	link := func() {		cli.RemoveEventHandler(handler)		h.linked(id, cli)	}	go h.watchPairing(ctx, id, cli, evs, phone, link)	return id, nil}// linked takes a number that just paired. The pairing client runs on the pairing's own context,// which ends the moment its watcher returns: whatsmeow reconnects after the 515 that follows a// pairing, keeps alive and handles frames on that same context, so a session kept on it went// quiet for good and WhatsApp logged the device out. The linked session is a fresh client over// the stored device, on the hub's own context, the way every session starts at launch.func (h *Hub) linked(id string, cli *whatsmeow.Client) {	account := accountOf(cli)	cli.Disconnect()	session := h.adopt(account, cli.Store)	h.setPair(id, func(s *PairState) { *s = PairState{Pairing: id, Status: "paired", Account: account} })	h.durable(&Event{Event: "paired", Pairing: id, Account: account, Name: cli.Store.PushName})	h.clearUnlinked()	if err := session.Connect(); err != nil {		h.setState(account, "disconnected", err.Error())	}}// adopt records a linked number's session as connecting, on a fresh client over// its stored device; the caller connects it. Never the client that paired it.func (h *Hub) adopt(account string, device *store.Device) *whatsmeow.Client {	cli := h.newClient(device)	h.mu.Lock()	h.sessions[account] = &session{cli: cli, state: "connecting"}	h.mu.Unlock()	return cli}func (h *Hub) setPair(id string, f func(*PairState)) {	h.mu.Lock()	defer h.mu.Unlock()	if p, ok := h.pairings[id]; ok {		f(&p.state)	}}// watchPairing walks one pairing from its first QR to paired or failed. link is called once,// on PairSuccess, and does everything a linked number needs.func (h *Hub) watchPairing(ctx context.Context, id string, cli pairClient, evs <-chan any, phone string, link func()) {	failed := make(chan string)	h.mu.Lock()	if p, ok := h.pairings[id]; ok {		failed = p.failed	}	h.mu.Unlock()	fail := func(detail string) {		h.setPair(id, func(s *PairState) { *s = PairState{Pairing: id, Status: "failed", Error: detail} })		h.transient(&Event{Event: "pair_failed", Pairing: id, Detail: detail})		cli.Disconnect()	}	defer func() {		h.mu.Lock()		if p, ok := h.pairings[id]; ok {			p.cancel()			if p.state.Status != "paired" && p.state.Status != "failed" {				p.state = PairState{Pairing: id, Status: "failed", Error: "the pairing ended"}			}			h.finished[id] = p.state			delete(h.pairings, id)		}		h.mu.Unlock()	}()	var codes []string // QR codes not yet shown	var current string	codeSent := false	var qrTimer, passkeyTimer <-chan time.Time	nextQR := func(wait time.Duration) {		current, codes = codes[0], codes[1:]		qrTimer = time.After(wait)		if phone == "" {			h.setPair(id, func(s *PairState) { s.Status, s.QR = "qr", current })			h.transient(&Event{Event: "pair_qr", Pairing: id, Code: current})		}	}	for {		select {		case <-ctx.Done():			if errors.Is(ctx.Err(), context.DeadlineExceeded) {				fail("the pairing took too long")			}			return		case detail := <-failed:			fail(detail)			return		case <-qrTimer:			if len(codes) == 0 {				fail("timeout")				return			}			nextQR(qrNextWait)		case <-passkeyTimer:			fail("WhatsApp's passkey request went unanswered")			return		case evt := <-evs:			switch e := evt.(type) {			case *events.QR:				if qrTimer != nil || passkeyTimer != nil || len(e.Codes) == 0 {					continue				}				codes = append([]string(nil), e.Codes...)				nextQR(qrFirstWait)				if phone != "" && !codeSent {					code, err := cli.PairPhone(ctx, phone, true, whatsmeow.PairClientChrome, "Chrome (Mac OS)")					if err != nil {						fail(err.Error())						return					}					codeSent = true					h.setPair(id, func(s *PairState) { s.Status, s.Code = "code", code })					h.transient(&Event{Event: "pair_code", Pairing: id, Code: code})				}			case *events.RotateADVSecret:				current = strings.Replace(current, e.OldSecret, e.NewSecret, 1)				for i := range codes {					codes[i] = strings.Replace(codes[i], e.OldSecret, e.NewSecret, 1)				}			case *events.PairPasskeyRequest:				options, err := json.Marshal(e.PublicKey)				if err != nil || e.PublicKey == nil {					fail("WhatsApp asked for a passkey without options")					return				}				// The QR codes no longer count: the person is answering WhatsApp's passkey.				qrTimer, codes = nil, nil				passkeyTimer = time.After(passkeyWait)				h.setPair(id, func(s *PairState) {					*s = PairState{Pairing: id, Status: "passkey", Passkey: options}				})				h.transient(&Event{Event: "pair_passkey", Pairing: id, Options: options})			case *events.PairPasskeyConfirmation:				if e.SkipHandoffUX {					// WhatsApp needs no check by the person: the helper confirms at once.					h.setPair(id, func(s *PairState) {						*s = PairState{Pairing: id, Status: "passkey_confirmed", Confirm: e.Code, Skip: true}					})					h.transient(&Event{Event: "pair_passkey_code", Pairing: id, Code: e.Code, Skip: true})					cctx, cancel := context.WithTimeout(ctx, 30*time.Second)					err := cli.SendPasskeyConfirmation(cctx)					cancel()					if err != nil {						fail("WhatsApp refused the passkey confirmation: " + err.Error())						return					}					continue				}				h.setPair(id, func(s *PairState) {					*s = PairState{Pairing: id, Status: "passkey_code", Confirm: e.Code}				})				h.transient(&Event{Event: "pair_passkey_code", Pairing: id, Code: e.Code})			case *events.PairPasskeyError:				fail("WhatsApp's passkey step failed: " + e.Error.Error())				return			case *events.PairSuccess:				link()				return			case *events.PairError:				fail(e.Error.Error())				return			case *events.QRScannedWithoutMultidevice:				fail("err-scanned-without-multidevice")				return			case *events.ClientOutdated:				fail("err-client-outdated")				return			case *events.Disconnected:				fail("timeout")				return			default:				fail("err-unexpected-state")				return			}		}	}}func (h *Hub) PairStatus(id string) (PairState, error) {	if !h.mu.TryLock() {		return PairState{}, errors.New("busy")	}	defer h.mu.Unlock()	if p, ok := h.pairings[id]; ok {		return p.state, nil	}	if st, ok := h.finished[id]; ok {		return st, nil	}	return PairState{}, fmt.Errorf("no pairing %s", id)}func (h *Hub) CancelPairing(id string) error {	if !h.mu.TryLock() {		return errors.New("busy")	}	p, ok := h.pairings[id]	if ok {		p.state = PairState{Pairing: id, Status: "cancelled"}		h.finished[id] = p.state		delete(h.pairings, id)	}	h.mu.Unlock()	if !ok {		return fmt.Errorf("no pairing %s", id)	}	p.cancel()	p.cli.Disconnect()	return nil}// advance moves a pairing from status `from` to `to` and answers its client, or says why not.func (h *Hub) advance(id, from, to string) (*pairing, error) {	if !h.mu.TryLock() {		return nil, errors.New("busy")	}	defer h.mu.Unlock()	p, ok := h.pairings[id]	if !ok {		return nil, fmt.Errorf("no pairing %s", id)	}	if p.state.Status != from {		return nil, fmt.Errorf("the pairing is %s, not waiting for this", p.state.Status)	}	p.state.Status = to	return p, nil}// refused ends a pairing whose answer WhatsApp would not take; its watcher says why.func (p *pairing) refused(detail string) {	select {	case p.failed <- detail:	default:	}}// PasskeyResponse hands WhatsApp the passkey's assertion, in the browser's JSON shape// (PublicKeyCredential.toJSON(): id, rawId, type, response.{clientDataJSON, authenticatorData,// signature, userHandle}, base64url). A malformed answer is refused and the pairing still waits;// one WhatsApp refuses ends the pairing.func (h *Hub) PasskeyResponse(id string, raw json.RawMessage) error {	var resp types.WebAuthnResponse	if err := json.Unmarshal(raw, &resp); err != nil {		return fmt.Errorf("the passkey answer is not a WebAuthn assertion: %w", err)	}	switch {	case resp.ID == "" || len(resp.RawID) == 0:		return errors.New("the passkey answer names no credential")	case resp.Type != "public-key":		return fmt.Errorf("the passkey answer is a %q, not a public-key credential", resp.Type)	case len(resp.Response.ClientDataJSON) == 0 || len(resp.Response.AuthenticatorData) == 0 || len(resp.Response.Signature) == 0:		return errors.New("the passkey answer carries no signed assertion")	}	p, err := h.advance(id, "passkey", "passkey_sent")	if err != nil {		return err	}	ctx, cancel := context.WithTimeout(p.ctx, 30*time.Second)	defer cancel()	if err := p.cli.SendPasskeyResponse(ctx, &resp); err != nil {		p.refused("WhatsApp refused the passkey: " + err.Error())		return err	}	return nil}// PasskeyConfirm tells WhatsApp the person saw the phone show the same code.func (h *Hub) PasskeyConfirm(id string) error {	p, err := h.advance(id, "passkey_code", "passkey_confirmed")	if err != nil {		return err	}	ctx, cancel := context.WithTimeout(p.ctx, 30*time.Second)	defer cancel()	if err := p.cli.SendPasskeyConfirmation(ctx); err != nil {		p.refused("WhatsApp refused the passkey confirmation: " + err.Error())		return err	}	return nil}