From 2799e7d24c82e10dd157d0402f483efa6b93864c Mon Sep 17 00:00:00 2001 From: SandyTAP Date: Tue, 20 Oct 2026 12:04:24 +0300 Subject: [PATCH] feat(auth): add a phone-number format policy TELESRV_CHECK_NUMBER_FORMAT selects the login identity format gate. The default lenient policy keeps the structural country-code gate and adds a fallback for numbers the numbering plan cannot describe, so short and unassigned international ranges such as "+7 123" or "+1488" are usable login identities. A national number that omits its country calling code (a leading trunk zero) stays refused, and the stored identity is canonical on every later normalization pass. The strict policy additionally requires the number to sit in an assigned range of a real country calling code, so short and unassigned ranges are rejected. The reserved service number +42777 stays resolvable under both policies so auth recognizes it as a system account; SendCode, SignIn and SignUp refuse it before any code is issued. The policy is installed in both the server and the admin process before stores and RPC services are constructed, so a number written from the panel is judged by the same rules. --- .env.example | 6 ++ cmd/telesrv-admin/main.go | 4 + cmd/telesrv/main.go | 6 ++ docs/configuration.en.md | 1 + docs/configuration.zh-CN.md | 1 + internal/app/auth/phone_format_test.go | 51 +++++++++++ internal/config/config.go | 10 ++- internal/domain/account.go | 95 +++++++++++++++++++-- internal/domain/phone_format_policy_test.go | 68 +++++++++++++++ 9 files changed, 232 insertions(+), 10 deletions(-) create mode 100644 internal/app/auth/phone_format_test.go create mode 100644 internal/domain/phone_format_policy_test.go diff --git a/.env.example b/.env.example index 49975ee40..a85a1f643 100644 --- a/.env.example +++ b/.env.example @@ -13,6 +13,12 @@ TELESRV_DC=2 TELESRV_DEFAULT_COUNTRY_CODE=CN # Single-backend default: accept any client wire DC label during key exchange. TELESRV_STRICT_DC_CHECK=false +# Phone-number format policy. false (default): a login identity only needs a +# country calling code with a plausible length, and short or unassigned ranges +# such as "+7 123" or "+1488" stay usable. true: the number must sit in an +# assigned range of a real country calling code. The reserved service number +# +42777 never becomes a login identity in either mode. +TELESRV_CHECK_NUMBER_FORMAT=false # Where the panel-editable server identity lives: the name/description/icon and # the login-notification template overrides, all managed from Admin → Server # Settings (see internal/identity). Read every time a login notification is sent. diff --git a/cmd/telesrv-admin/main.go b/cmd/telesrv-admin/main.go index 3fa1dddd8..c36ac8fa6 100644 --- a/cmd/telesrv-admin/main.go +++ b/cmd/telesrv-admin/main.go @@ -19,6 +19,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "telesrv/internal/config" + "telesrv/internal/domain" "telesrv/internal/hoststats" ) @@ -133,6 +134,9 @@ func loadConfig() (uiConfig, error) { if err != nil { return uiConfig{}, fmt.Errorf("load config: %w", err) } + // 管理面板也能按手机号建号,必须与 telesrv 主进程使用同一套格式策略, + // 否则面板写入的号码主进程会当成非法号。 + domain.ConfigurePhoneFormatCheck(appCfg.CheckNumberFormat) adminAPIAddr := appCfg.AdminAPIAddr if strings.TrimSpace(adminAPIAddr) == "" { diff --git a/cmd/telesrv/main.go b/cmd/telesrv/main.go index 1d814fccd..ac355c7be 100644 --- a/cmd/telesrv/main.go +++ b/cmd/telesrv/main.go @@ -642,6 +642,12 @@ func run(logger *zap.Logger) error { if !domain.ConfigurePremiumBotUsername(cfg.PremiumBotUsername) { return fmt.Errorf("configure Premium bot username %q", cfg.PremiumBotUsername) } + // 手机号格式策略必须在 store / RPC service 构造前安装:login identity 的 + // 规范化结果会落进 users.phone,策略切换不能留下半规范化数据。 + domain.ConfigurePhoneFormatCheck(cfg.CheckNumberFormat) + logger.Info("手机号格式策略", + zap.Bool("check_number_format", cfg.CheckNumberFormat), + zap.Bool("strict", domain.PhoneFormatCheckEnabled())) // SCAM/FAKE 警告文案(空白 → domain 内置英文默认值):启动时写入一次, // getFullUser / channels.getFullChannel / 邀请预览的 About 投影都会读取。 domain.SetModerationProfileWarning(cfg.ScamProfileWarning, cfg.FakeProfileWarning) diff --git a/docs/configuration.en.md b/docs/configuration.en.md index a533dc2a2..eec9207be 100644 --- a/docs/configuration.en.md +++ b/docs/configuration.en.md @@ -39,6 +39,7 @@ About privacy hides the entire user About projection, including the warning. A u | `TELESRV_DC` | positive TL int32 / `2` | Canonical server DC ID used in server-originated configuration, media/DC metadata, and `channelFull.stats_dc`. It must be within `1..2147483647` or startup fails. It does not partition key-exchange state on the current single backend. | | `TELESRV_DEFAULT_COUNTRY_CODE` | ISO alpha-2 / `CN` | Country returned by `help.getNearestDc` for login-page preselection. Clients map `CN` to calling code `+86`, `US` to `+1`, and so on. Input is trimmed, uppercased, and validated as a country or autonomous area; malformed or unknown values fail startup. | | `TELESRV_STRICT_DC_CHECK` | bool / `false` | Default `false` accepts every wire int32 DC label for permanent and temporary key exchange. `true` requires permanent `dc_id == TELESRV_DC` and temporary `abs(dc_id) == TELESRV_DC`; it is only a diagnostic and does not provide multi-DC isolation. | +| `TELESRV_CHECK_NUMBER_FORMAT` | bool / `false` | Phone-number format policy for login identities. Default `false` keeps the lenient gate: the number needs a country calling code with a plausible length, and short or unassigned ranges such as `+7 123` or `+1488` remain usable login identities; a national number that omits its calling code (a leading trunk zero) is still refused. `true` additionally requires the number to sit in an assigned range of a real country calling code, so short and unassigned ranges are rejected. The reserved service number `+42777` never becomes a login identity in either mode. | | `TELESRV_WEBSOCKET_ENABLE` | bool / `true` | Enables MTProto-over-WebSocket demultiplexing on the MTProto listener. | | `TELESRV_WEBSOCKET_ALLOWED_ORIGINS` | list / `http://localhost:1234,http://127.0.0.1:1234` | Browser WebSocket origin allow-list. `*` is for temporary debugging only. | | `TELESRV_MTPROTO_MAX_CONNECTIONS` | int / `200000` | Global physical connection admission limit. Negative disables this gate. | diff --git a/docs/configuration.zh-CN.md b/docs/configuration.zh-CN.md index 28e0fb608..a13284fab 100644 --- a/docs/configuration.zh-CN.md +++ b/docs/configuration.zh-CN.md @@ -39,6 +39,7 @@ | `TELESRV_DC` | positive TL int32 / `2` | 服务端输出配置、媒体/DC 元数据和 `channelFull.stats_dc` 使用的规范 DC ID;必须在 `1..2147483647`,否则启动失败。当前单后端不会按它分区密钥交换状态。 | | `TELESRV_DEFAULT_COUNTRY_CODE` | ISO alpha-2 / `CN` | `help.getNearestDc` 返回的登录页默认国家。客户端把 `CN` 映射为国际区号 `+86`、`US` 映射为 `+1`。输入会 trim、转大写并校验为国家或自治地区;格式错误或未知值会让启动失败。 | | `TELESRV_STRICT_DC_CHECK` | bool / `false` | 默认 `false`,永久与临时密钥交换接受任意 wire int32 DC 标签。设为 `true` 时永久标签必须等于 `TELESRV_DC`、临时标签绝对值必须等于 `TELESRV_DC`;它仅是诊断开关,不提供多 DC 隔离。 | +| `TELESRV_CHECK_NUMBER_FORMAT` | bool / `false` | 登录手机号的格式策略。默认 `false` 走宽松门:国家码存在且长度符合该国号段计划即可,短号段与未分配号段(如 `+7 123`、`+1488`)同样可以作为登录身份;但省略国家码的本地号(前导 0)仍然拒绝。设为 `true` 时额外要求号段已被真实国家分配,短号段与未分配号段一律拒绝。保留服务号 `+42777` 在两种模式下都不能登录。 | | `TELESRV_WEBSOCKET_ENABLE` | bool / `true` | 在 MTProto 监听端口启用 MTProto-over-WebSocket 分流。 | | `TELESRV_WEBSOCKET_ALLOWED_ORIGINS` | list / `http://localhost:1234,http://127.0.0.1:1234` | 浏览器 WebSocket origin 白名单;`*` 只用于临时调试。 | | `TELESRV_MTPROTO_MAX_CONNECTIONS` | int / `200000` | 全局物理连接 admission 上限;负数关闭该门禁。 | diff --git a/internal/app/auth/phone_format_test.go b/internal/app/auth/phone_format_test.go new file mode 100644 index 000000000..64c1a4437 --- /dev/null +++ b/internal/app/auth/phone_format_test.go @@ -0,0 +1,51 @@ +package auth + +import ( + "context" + "errors" + "testing" + + "telesrv/internal/domain" + "telesrv/internal/store/memory" +) + +// The reserved service identity is not a login identity. Auth must recognize +// it before any code is issued, and the refusal must not enumerate the +// difference between a reserved number and a free one. +func TestReservedSystemPhoneCannotLogIn(t *testing.T) { + ctx := context.Background() + svc := NewService(memory.NewUserStore(), memory.NewAuthorizationStore(), memory.NewCodeStore(), nil, nil, "12345") + + if _, err := svc.SendCode(ctx, "+"+domain.OfficialSystemPhone); !errors.Is(err, ErrSystemUserLoginForbidden) { + t.Fatalf("SendCode(%q) error = %v, want ErrSystemUserLoginForbidden", domain.OfficialSystemPhone, err) + } + if _, err := svc.SendCode(ctx, domain.OfficialSystemPhone); !errors.Is(err, ErrSystemUserLoginForbidden) { + t.Fatalf("SendCode(%q) error = %v, want ErrSystemUserLoginForbidden", domain.OfficialSystemPhone, err) + } + if _, _, err := svc.SignUp(ctx, domain.Authorization{}, domain.OfficialSystemPhone, "hash", "Sys", "Tem"); !errors.Is(err, ErrSystemUserLoginForbidden) { + t.Fatalf("SignUp(%q) error = %v, want ErrSystemUserLoginForbidden", domain.OfficialSystemPhone, err) + } +} + +// The lenient phone format policy keeps short and unassigned international +// numbers usable: they are ordinary login identities from the client's point +// of view. +func TestLenientPhoneFormatAcceptsShortAndUnassignedNumbers(t *testing.T) { + ctx := context.Background() + svc := NewService(memory.NewUserStore(), memory.NewAuthorizationStore(), memory.NewCodeStore(), nil, nil, "12345") + + for _, phone := range []string{"+7 123", "+1488"} { + hash, err := svc.SendCode(ctx, phone) + if err != nil { + t.Fatalf("SendCode(%q): %v", phone, err) + } + verifyCodeForSignUp(t, svc, phone, hash, "12345") + u, _, err := svc.SignUp(ctx, domain.Authorization{}, phone, hash, "Short", "Number") + if err != nil { + t.Fatalf("SignUp(%q): %v", phone, err) + } + if u.Phone != domain.NormalizePhone(phone) { + t.Fatalf("user phone = %q, want %q", u.Phone, domain.NormalizePhone(phone)) + } + } +} diff --git a/internal/config/config.go b/internal/config/config.go index d2a419ffd..684c61cd6 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -48,6 +48,11 @@ type Config struct { // partitioning auth keys, sessions, or business state. See // mtprotoedge.Options.StrictDC for the optional strict behavior. StrictDCCheck bool + // CheckNumberFormat 开启严格的手机号格式校验:国家码必须真实存在, + // 且号段必须已分配。默认关闭——此时只要显式写成国际号(带 +)且位数在 + // 4-32 之间就接受,短号段(如 +7 123)和未分配号段(如 +1488)都能登录; + // 关闭时也依旧拒绝缺少国家码的本地号(如 09981679461)。 + CheckNumberFormat bool // MTProtoMaxConnections / PerIP 覆盖 raw Accept、codec sniff、握手到认证 session // 的完整物理连接生命周期;负数关闭对应 admission 上限。 MTProtoMaxConnections int @@ -977,6 +982,7 @@ func Load() (Config, error) { DC: envIntOr("TELESRV_DC", 2), DefaultCountryCode: countryCode, StrictDCCheck: envBoolOr("TELESRV_STRICT_DC_CHECK", false), + CheckNumberFormat: envBoolOr("TELESRV_CHECK_NUMBER_FORMAT", false), MTProtoMaxConnections: envIntOr("TELESRV_MTPROTO_MAX_CONNECTIONS", 200000), MTProtoMaxConnectionsPerIP: envIntOr("TELESRV_MTPROTO_MAX_CONNECTIONS_PER_IP", 4096), MTProtoMaxConcurrentHandshakes: envIntOr("TELESRV_MTPROTO_MAX_CONCURRENT_HANDSHAKES", 256), @@ -1316,8 +1322,8 @@ func Load() (Config, error) { VerificationNotifyBatch: envIntOr("TELESRV_VERIFICATION_NOTIFY_BATCH", 50), // Empty keeps the built-in English defaults: domain trims and falls // back when the stored text is blank (domain.SetModerationProfileWarning). - ScamProfileWarning: envOr("TELESRV_SCAM_WARNING", ""), - FakeProfileWarning: envOr("TELESRV_FAKE_WARNING", ""), + ScamProfileWarning: envOr("TELESRV_SCAM_WARNING", ""), + FakeProfileWarning: envOr("TELESRV_FAKE_WARNING", ""), BroadcastWorkerInterval: envDurationOr("TELESRV_BROADCAST_WORKER_INTERVAL", 3*time.Second), BroadcastWorkerLease: envDurationOr("TELESRV_BROADCAST_WORKER_LEASE", 30*time.Second), BroadcastMaterializeBatch: envIntOr("TELESRV_BROADCAST_MATERIALIZE_BATCH", 200), diff --git a/internal/domain/account.go b/internal/domain/account.go index e267a8b7f..3ceb17f9a 100644 --- a/internal/domain/account.go +++ b/internal/domain/account.go @@ -3,12 +3,43 @@ package domain import ( "errors" "strings" + "sync/atomic" "time" "unicode" "github.com/nyaruka/phonenumbers" ) +const ( + // MinLoginPhoneDigits is the shortest accepted login identity in the + // lenient format policy. It keeps short international numbers such as + // "+7 123" usable while staying above the empty and single-digit range. + MinLoginPhoneDigits = 4 + // MaxLoginPhoneDigits bounds a login identity. It matches the users.phone + // column width and stays inside E.164's 15-digit ceiling for every + // number the numbering plan can canonicalize. + MaxLoginPhoneDigits = 32 +) + +// phoneFormatCheck selects the strict phone-number format policy. The default +// is the lenient policy; ConfigurePhoneFormatCheck installs the deployment's +// choice before any store or RPC service is constructed. +var phoneFormatCheck atomic.Bool + +// ConfigurePhoneFormatCheck installs the deployment's phone-number format +// policy. Strict mode requires the number to sit in an assigned range of a +// real country calling code; the default lenient mode accepts any explicitly +// international number whose digits fit the length bounds. +func ConfigurePhoneFormatCheck(strict bool) { + phoneFormatCheck.Store(strict) +} + +// PhoneFormatCheckEnabled reports whether the strict phone-number format +// policy is installed. +func PhoneFormatCheckEnabled() bool { + return phoneFormatCheck.Load() +} + var ( ErrPasswordHashInvalid = errors.New("password hash invalid") ErrSRPIDInvalid = errors.New("srp id invalid") @@ -298,10 +329,21 @@ func PhoneDigits(phone string) string { // prefix. For example, both +98 0998 167 9461 and +98 998 167 9461 become // 989981679461, while Italy's significant leading zero in +39 02 ... is retained. // -// IsPossibleNumber is the structural gate rather than IsValidNumber. It keeps -// syntactically possible reserved/test ranges usable without accepting local -// numbers that omit their country calling code or numbers outside E.164's -// length/plan metadata. +// Two format policies exist: +// +// - The default (lenient) policy keeps IsPossibleNumber as the structural +// gate: a country calling code plus a length that matches that country's +// numbering plan is enough. A number the plan cannot describe is still +// accepted when it is short enough and carries no national trunk prefix, +// so ranges such as "+7 123" or "+1488" remain usable login identities. +// The digits are then stored verbatim. +// - The strict policy (ConfigurePhoneFormatCheck) additionally requires +// IsValidNumber, i.e. the number must sit in an assigned range of a real +// country calling code. Short and unassigned ranges are rejected. +// +// Neither policy accepts a national number that omits its country calling +// code: "09981679461" and "00989981679461" carry a leading trunk zero and +// are refused in both modes. func NormalizePhone(phone string) string { digits := PhoneDigits(phone) if digits == "" { @@ -323,14 +365,51 @@ func NormalizePhone(phone string) string { return digits } number, err := phonenumbers.Parse("+"+digits, phonenumbers.UNKNOWN_REGION) - if err != nil || !phonenumbers.IsPossibleNumber(number) { + if err == nil { + if phoneFormatCheck.Load() { + if !phonenumbers.IsValidNumber(number) { + return "" + } + canonical := strings.TrimPrefix(phonenumbers.Format(number, phonenumbers.E164), "+") + if canonical == "" || len(canonical) > MaxLoginPhoneDigits { + return "" + } + return canonical + } + if phonenumbers.IsPossibleNumber(number) { + canonical := strings.TrimPrefix(phonenumbers.Format(number, phonenumbers.E164), "+") + if canonical == "" || len(canonical) > MaxLoginPhoneDigits { + return "" + } + return canonical + } + // The numbering plan cannot describe these digits. The lenient policy + // still keeps an explicitly international number usable. + } else if phoneFormatCheck.Load() { + return "" + } + // The lenient policy accepts a number the plan cannot describe. The digits + // are stored verbatim, so the identity stays exactly what the caller + // typed and stays canonical on the next normalization pass. + if phoneFormatCheck.Load() { + return "" + } + if len(digits) < MinLoginPhoneDigits || len(digits) > MaxLoginPhoneDigits { + return "" + } + // A leading zero marks the national/trunk form of a number whose country + // calling code was omitted ("07400123456", "00989981679461"). Such a + // value is ambiguous between a national number and a calling code, so it + // never becomes a login identity. + if strings.HasPrefix(digits, "0") { return "" } - canonical := strings.TrimPrefix(phonenumbers.Format(number, phonenumbers.E164), "+") - if canonical == "" || len(canonical) > 15 { + // The +888 space has its own identity rule above: a number outside the + // 7-15 digit collectible range is not a login identity at all. + if strings.HasPrefix(digits, "888") { return "" } - return canonical + return digits } // ValidPhone reports whether phone is already in the persisted canonical form. diff --git a/internal/domain/phone_format_policy_test.go b/internal/domain/phone_format_policy_test.go new file mode 100644 index 000000000..9e77634e9 --- /dev/null +++ b/internal/domain/phone_format_policy_test.go @@ -0,0 +1,68 @@ +package domain + +import "testing" + +// The lenient policy is the default: an explicitly international number is a +// login identity even when the numbering plan cannot describe it. Short +// ranges and unassigned blocks stay usable, while a number without a country +// calling code is still refused. +func TestNormalizePhoneLenientPolicyAcceptsInternationalShortAndUnassigned(t *testing.T) { + for input, want := range map[string]string{ + "+7 123": "7123", + "+1488": "1488", + "+44 7400 123456": "447400123456", + "+222 12345678": "22212345678", + "+1 555 000 0001": "15550000001", + } { + if got := NormalizePhone(input); got != want { + t.Fatalf("NormalizePhone(%q) = %q, want %q", input, got, want) + } + } + // A national number that omits its country calling code stays refused in + // the lenient policy: the digits are ambiguous between a national number + // and a calling code. + for _, input := range []string{"09981679461", "00989981679461", "07400123456"} { + if got := NormalizePhone(input); got != "" { + t.Fatalf("NormalizePhone(%q) = %q, want empty", input, got) + } + } +} + +// The strict policy requires an assigned range of a real country calling code. +func TestNormalizePhoneStrictPolicyRequiresAssignedRange(t *testing.T) { + ConfigurePhoneFormatCheck(true) + t.Cleanup(func() { ConfigurePhoneFormatCheck(false) }) + for input, want := range map[string]string{ + "+44 7400 123456": "447400123456", + "+86 (188) 0000-0000": "8618800000000", + "+98 0998 167 9461": "989981679461", + } { + if got := NormalizePhone(input); got != want { + t.Fatalf("NormalizePhone(%q) = %q, want %q", input, got, want) + } + } + // Short ranges, unassigned blocks and unknown calling codes are refused. + for _, input := range []string{"+7 123", "+1488", "+222 12345678", "+1 555 000 0001", "+999 123456789", "09981679461"} { + if got := NormalizePhone(input); got != "" { + t.Fatalf("strict NormalizePhone(%q) = %q, want empty", input, got) + } + } +} + +// The reserved service identity stays resolvable under both policies so auth +// can recognize it as a system account instead of treating it as free. +func TestReservedSystemPhoneStaysResolvableUnderBothPolicies(t *testing.T) { + for _, strict := range []bool{false, true} { + ConfigurePhoneFormatCheck(strict) + if got := NormalizePhone(OfficialSystemPhone); got != OfficialSystemPhone { + t.Fatalf("strict=%v NormalizePhone(%q) = %q, want %q", strict, OfficialSystemPhone, got, OfficialSystemPhone) + } + if got := NormalizePhone("+42777"); got != OfficialSystemPhone { + t.Fatalf("strict=%v NormalizePhone(\"+42777\") = %q, want %q", strict, got, OfficialSystemPhone) + } + if _, ok := SystemUserByPhone(OfficialSystemPhone); !ok { + t.Fatalf("strict=%v SystemUserByPhone(%q) = false, want true", strict, OfficialSystemPhone) + } + } + ConfigurePhoneFormatCheck(false) +}