package telegram
import (
"context"
"strings"
"sync/atomic"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"github.com/gotd/log"
"github.com/gotd/td/bin"
"github.com/gotd/td/tg"
"github.com/gotd/td/tgerr"
)
type AuthLostError struct {
Err error
Reason error
}
func (e *AuthLostError ) Error () string {
return "authorization lost: " + e .Err .Error()
}
func (e *AuthLostError ) Unwrap () []error {
if e .Reason == nil || e .Reason == e .Err {
return []error {e .Err }
}
return []error {e .Err , e .Reason }
}
func IsAuthLost (err error ) bool {
if tgerr .Is (err ,
"AUTH_KEY_UNREGISTERED" ,
"AUTH_KEY_INVALID" ,
"SESSION_REVOKED" ,
"SESSION_EXPIRED" ,
"USER_DEACTIVATED" ,
"USER_DEACTIVATED_BAN" ,
"AUTH_KEY_DUPLICATED" ,
) {
return true
}
rpcErr , ok := tgerr .As (err )
return ok && strings .HasPrefix (rpcErr .Type , authKeyDropPrefix )
}
type authState struct {
authorized atomic .Bool
loggedOut atomic .Bool
reported atomic .Bool
stopped atomic .Bool
done atomic .Pointer [chan struct {}]
}
func (c *Client ) waitAuthLost (ctx context .Context ) error {
done := c .auth .done .Load ()
if done == nil {
return nil
}
select {
case <- *done :
return nil
case <- ctx .Done ():
return ctx .Err ()
}
}
type queryWrapper interface {
GetQuery () bin .Object
}
func unwrapQuery (input bin .Encoder ) bin .Encoder {
for i := 0 ; i < 8 ; i ++ {
w , ok := input .(queryWrapper )
if !ok {
return input
}
q := w .GetQuery ()
if q == nil {
return input
}
input = q
}
return input
}
type authEffect int
const (
authNone authEffect = iota
authAuthorized
authLoggedOut
)
var noAuthRequests = map [string ]struct {}{
"account.getPassword" : {},
"account.deleteAccount" : {},
"account.sendVerifyEmailCode" : {},
"account.verifyEmail" : {},
}
func authEffectOf (input bin .Encoder , output bin .Decoder ) authEffect {
input = unwrapQuery (input )
switch input .(type ) {
case *tg .AuthLogOutRequest :
return authLoggedOut
case *tg .AuthSignInRequest ,
*tg .AuthSignUpRequest ,
*tg .AuthCheckPasswordRequest ,
*tg .AuthImportBotAuthorizationRequest ,
*tg .AuthImportAuthorizationRequest ,
*tg .AuthImportWebTokenAuthorizationRequest ,
*tg .AuthRecoverPasswordRequest ,
*tg .AuthImportLoginTokenRequest ,
*tg .AuthExportLoginTokenRequest :
if isAuthorization (output ) {
return authAuthorized
}
return authNone
}
named , ok := input .(interface { TypeName () string })
if !ok {
return authNone
}
name := named .TypeName ()
if _ , ok := noAuthRequests [name ]; ok {
return authNone
}
for _ , prefix := range []string {"auth." , "help." , "langpack." } {
if strings .HasPrefix (name , prefix ) {
return authNone
}
}
return authAuthorized
}
func isAuthorization (output bin .Decoder ) bool {
switch v := output .(type ) {
case *tg .AuthAuthorizationBox :
_ , ok := v .Authorization .(*tg .AuthAuthorization )
return ok
case *tg .AuthAuthorization :
return true
case *tg .AuthLoginTokenBox :
success , ok := v .LoginToken .(*tg .AuthLoginTokenSuccess )
if !ok {
return false
}
_, ok = success .Authorization .(*tg .AuthAuthorization )
return ok
case *tg .AuthLoginTokenSuccess :
_ , ok := v .Authorization .(*tg .AuthAuthorization )
return ok
default :
return false
}
}
func (c *Client ) observeAuth (input bin .Encoder , output bin .Decoder , err error ) {
if err == nil {
switch authEffectOf (input , output ) {
case authAuthorized :
c .markAuthorized ()
case authLoggedOut :
c .auth .authorized .Store (false )
}
return
}
c .observeRestriction (input , err )
if !IsAuthLost (err ) {
return
}
c .authLostDetected (err )
}
func (c *Client ) authLostDetected (err error ) {
if !c .auth .authorized .Load () || c .auth .loggedOut .Load () {
return
}
if c .ctx != nil && c .ctx .Err () != nil {
return
}
if !c .auth .reported .CompareAndSwap (false , true ) {
return
}
c .auth .authorized .Store (false )
reason := "unknown"
if rpcErr , ok := tgerr .As (err ); ok {
reason = rpcErr .Type
}
kind := AuthLostKindOf (err )
bg := context .Background ()
c .meters ().authLost .Add (bg , 1 , metric .WithAttributes (
attribute .String ("reason" , reason ),
attribute .String ("kind" , kind .String ()),
))
fields := []log .Attr {
log .String ("reason" , reason ),
log .String ("kind" , kind .String ()),
log .Bool ("callback" , c .onAuthLost != nil ),
}
switch kind {
case AuthLostBanned :
c .log .Error (bg , "Authorization lost: the account is banned by Telegram. " +
"If this is a mistake, log in from an official mobile app and follow " +
"its instructions to recover the account" , fields ...)
case AuthLostDeleted :
c .log .Error (bg , "Authorization lost: the account is deleted" , fields ...)
default :
c .log .Warn (bg , "Authorization lost" , fields ...)
}
if c .onAuthLost == nil {
return
}
done := make (chan struct {})
prev := c .auth .done .Swap (&done )
go func () {
defer close (done )
if prev != nil {
<-*prev
}
c .reportAuthLost (err )
}()
}
func (c *Client ) reportAuthLost (err error ) {
ctx := c .ctx
if ctx == nil {
ctx = context .Background ()
}
reason := c .onAuthLost (ctx , err )
if reason == nil {
c .auth .reported .Store (false )
return
}
c .auth .stopped .Store (true )
select {
case c .authLost <- &AuthLostError {Err : err , Reason : reason }:
default :
}
}
func (c *Client ) markAuthorized () {
if c .auth .authorized .Load () {
return
}
c .auth .authorized .Store (true )
c .auth .reported .Store (false )
c .auth .loggedOut .Store (false )
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .