Files
free-turn-proxy-orig/internal/client/vkauth/cache.go
T
samosvalishe 2167ba990b refactor(layout): переезд в cmd/, свернуть client/internal в internal/client
- server/main.go → cmd/vk-turn-server/main.go. Несёт остаточные правки сервера
  (drop параметра useBond, убрано поле startup-лога).
- client/internal/{browserprofile,captcha,dnsdial,namegen,vkauth} →
  internal/client/* (единая иерархия internal/; параллельное дерево
  client/internal/ убрано). Все Go import-пути обновлены.
- .github/workflows/{ci,release}.yml, Dockerfile, README.md — пути сборки
  переключены на ./cmd/vk-turn-client и ./cmd/vk-turn-server.
- README: убран устаревший пример "server -vless-bond" (флаг удалён ранее);
  добавлены рецепты сборки .so для Android arm64 + Linux arm64/amd64 под
  ручную упаковку для мобилок.
- internal/proxy/udp/udp.go, internal/config/config.go: обновлены устаревшие
  ссылки client/internal/* в doc-комментариях.
- notes/GLOSSARY.md (новый, ~20 терминов): фиксирует DTLS-как-обфускацию,
  wrap=AEAD-не-XOR, четыре значения "client", три значения "stream", пять
  ортогональных переключателей "mode", заметки по сборке libvkturn.so, iSH,
  хрупкость init globalBondRegistry и удаления флагов.

cmd/vk-turn-client/ намеренно оставлен вне этого коммита; сворачивается вместе
с извлечением ручной captcha в следующем коммите, т.к. переименование и правки
импортов manualcaptcha.* попадают в один файл.

Wire-форматы не тронуты. Поведение не изменено кроме уже закоммиченных
удалений CLI.
2026-05-19 17:20:26 +03:00

83 lines
1.9 KiB
Go

package vkauth
import (
"strings"
"sync"
"sync/atomic"
)
// StreamCredentialsCache holds the resolved TURN creds for a group of streams
// plus auth-error tracking for invalidation decisions.
type StreamCredentialsCache struct {
creds TurnCredentials
mutex sync.RWMutex
errorCount atomic.Int32
lastErrorTime atomic.Int64
}
// Store maps cache-id (streamID / streamsPerCache) -> StreamCredentialsCache.
type Store struct {
mu sync.RWMutex
caches map[int]*StreamCredentialsCache
streamsPerCache int
}
func NewStore(streamsPerCache int) *Store {
if streamsPerCache <= 0 {
streamsPerCache = DefaultStreamsPerCache
}
return &Store{
caches: make(map[int]*StreamCredentialsCache),
streamsPerCache: streamsPerCache,
}
}
func (s *Store) CacheID(streamID int) int {
return streamID / s.streamsPerCache
}
func (s *Store) Get(streamID int) *StreamCredentialsCache {
cacheID := s.CacheID(streamID)
s.mu.RLock()
cache, exists := s.caches[cacheID]
s.mu.RUnlock()
if exists {
return cache
}
s.mu.Lock()
defer s.mu.Unlock()
if cache, exists = s.caches[cacheID]; exists {
return cache
}
cache = &StreamCredentialsCache{}
s.caches[cacheID] = cache
return cache
}
// Invalidate clears the creds for the given stream's cache and resets error state.
func (c *StreamCredentialsCache) Invalidate() {
c.mutex.Lock()
c.creds = TurnCredentials{}
c.mutex.Unlock()
c.errorCount.Store(0)
c.lastErrorTime.Store(0)
}
// IsAuthError matches the historical heuristic used by the TURN client: a TURN
// allocate failure mentioning auth/401/stale-nonce should trigger cache invalidate.
func IsAuthError(err error) bool {
if err == nil {
return false
}
s := err.Error()
return strings.Contains(s, "401") ||
strings.Contains(s, "Unauthorized") ||
strings.Contains(s, "authentication") ||
strings.Contains(s, "invalid credential") ||
strings.Contains(s, "stale nonce")
}