diff --git a/buf.yaml b/buf.yaml index 54e1fdc4..ce8962f5 100644 --- a/buf.yaml +++ b/buf.yaml @@ -7,5 +7,13 @@ lint: # AWG_PREPARE_STATE_NONE is already in the API; renaming it would change the JSON the clients send and read. ENUM_ZERO_VALUE_SUFFIX: - proto/mistgate/admin/v1/node.proto + # The messages of the people's bot are shared between calls on purpose: every message type is code and descriptor in each Worker + # that serves the service (scripts/check-edge-sizes.sh). See the header of the file. + RPC_REQUEST_STANDARD_NAME: + - proto/mistgate/usernotify/v1/usernotify.proto + RPC_RESPONSE_STANDARD_NAME: + - proto/mistgate/usernotify/v1/usernotify.proto + RPC_REQUEST_RESPONSE_UNIQUE: + - proto/mistgate/usernotify/v1/usernotify.proto breaking: use: [FILE] diff --git a/cmd/mistgate-edge-admin/main_js.go b/cmd/mistgate-edge-admin/main_js.go index a4a0ad3f..15081e7e 100644 --- a/cmd/mistgate-edge-admin/main_js.go +++ b/cmd/mistgate-edge-admin/main_js.go @@ -7,6 +7,7 @@ import ( "github.com/mistgate/mistgate/edge/bridge" "github.com/mistgate/mistgate/internal/panel/app" "github.com/mistgate/mistgate/internal/panel/proposal/proposalrpc" + "github.com/mistgate/mistgate/internal/panel/telegram/usernotifyrpc" ) func main() { @@ -19,5 +20,6 @@ func main() { // buildAdmin is app.BuildAdmin with the ProposalService plugged in (app.Config.ProposalAPI). func buildAdmin(c app.Config) (*app.Panel, error) { c.ProposalAPI = proposalrpc.Handler + c.UserNotifyAPI = usernotifyrpc.Handler return app.BuildAdmin(c) } diff --git a/cmd/mistgate-edge/main_js.go b/cmd/mistgate-edge/main_js.go index ff947d46..2c07aefa 100644 --- a/cmd/mistgate-edge/main_js.go +++ b/cmd/mistgate-edge/main_js.go @@ -8,6 +8,7 @@ import ( "github.com/mistgate/mistgate/edge/bridge" "github.com/mistgate/mistgate/internal/panel/app" "github.com/mistgate/mistgate/internal/panel/proposal/proposalrpc" + "github.com/mistgate/mistgate/internal/panel/telegram/usernotifyrpc" ) func main() { @@ -21,5 +22,6 @@ func main() { // that the Workers that do not serve it never link it. func buildAll(c app.Config) (*app.Panel, error) { c.ProposalAPI = proposalrpc.Handler + c.UserNotifyAPI = usernotifyrpc.Handler return app.Build(c) } diff --git a/cmd/mistgate-edge/testdata/vps-oracle/main.go b/cmd/mistgate-edge/testdata/vps-oracle/main.go index 33d71806..c3c59c00 100644 --- a/cmd/mistgate-edge/testdata/vps-oracle/main.go +++ b/cmd/mistgate-edge/testdata/vps-oracle/main.go @@ -15,6 +15,7 @@ import ( "github.com/mistgate/mistgate/internal/panel/auth" "github.com/mistgate/mistgate/internal/panel/proposal/proposalrpc" "github.com/mistgate/mistgate/internal/panel/store" + "github.com/mistgate/mistgate/internal/panel/telegram/usernotifyrpc" "github.com/mistgate/mistgate/internal/panel/vault" ) @@ -49,7 +50,8 @@ func main() { built, err := app.Build(app.Config{ Store: st, Vault: vlt, Auth: authSvc, MasterKey: key, Clock: time.Now, Logger: log, Instance: in, Title: "Mistgate", DataDir: filepath.Join(filepath.Dir(os.Args[1]), "backup-unavailable"), - ProposalAPI: proposalrpc.Handler, + ProposalAPI: proposalrpc.Handler, + UserNotifyAPI: usernotifyrpc.Handler, }) if err != nil { fatal(err) diff --git a/cmd/mistgate/panel.go b/cmd/mistgate/panel.go index 53ec961f..d5954546 100644 --- a/cmd/mistgate/panel.go +++ b/cmd/mistgate/panel.go @@ -20,6 +20,7 @@ import ( nodeprovision "github.com/mistgate/mistgate/internal/panel/provision" "github.com/mistgate/mistgate/internal/panel/store" "github.com/mistgate/mistgate/internal/panel/telegram" + "github.com/mistgate/mistgate/internal/panel/telegram/usernotifyrpc" "github.com/mistgate/mistgate/internal/panel/update" "github.com/mistgate/mistgate/internal/panel/vault" "github.com/mistgate/mistgate/internal/panel/warp" @@ -78,7 +79,8 @@ func newPanel(st *store.Store, vlt *vault.Vault, authSvc *auth.Service, o panelO }, DecoyDir: o.decoyDir, PanelAddr: o.panelAddr, DataDir: o.dataDir, UpdateService: o.updateService, Title: o.title, HealthBlipWindow: healthBlipWindow, Ops: o.ops, - ProposalAPI: proposalrpc.Handler, + ProposalAPI: proposalrpc.Handler, + UserNotifyAPI: usernotifyrpc.Handler, }) if err != nil { return nil, err diff --git a/docs/en/reference/api.md b/docs/en/reference/api.md index b586c42a..6078d016 100644 --- a/docs/en/reference/api.md +++ b/docs/en/reference/api.md @@ -42,6 +42,7 @@ The API is defined in `proto/mistgate/admin/v1/`. Generated code is in the repos | `BackupService` | `backup.proto` | Encrypted panel backups | | `TrustTunnelService` | `trusttunnel.proto` | A person's TrustTunnel key and `tt://` links (package `mistgate.trusttunnel.v1`; the admin's write level, closed to API tokens and MCP) | | `TelegramService` | `telegram.proto` | The Telegram bot and each admin's chat (owner and signed-in admins only; closed to API tokens and MCP) | +| `UserNotifyService` | `usernotify.proto` (package `mistgate.usernotify.v1`) | The separate Telegram bot that tells users about their access, and each user's chats: link codes, mute, unlink, the chat limit (signed-in admins; the bot and the limit are the owner's, and setting or clearing the bot needs a step-up; closed to API tokens and MCP) | | `ApiTokenService`, `ApprovalService` | `integrations.proto` | API tokens and the owner's approvals | | `CheburcheckService`, `BsbordService` | `cheburcheck.proto`, `bsbord.proto` | The cheburcheck and bsbord sources of the [country check](../operations/reachability.md): settings, status and test, and for bsbord the unit list and the price check (owner only; changing or disconnecting a source, and the price check, need a step-up; closed to API tokens and MCP) | diff --git a/docs/ru/reference/api.md b/docs/ru/reference/api.md index 73f3232c..e282d6fb 100644 --- a/docs/ru/reference/api.md +++ b/docs/ru/reference/api.md @@ -42,6 +42,7 @@ API описан в `proto/mistgate/admin/v1/`. Сгенерированный | `BackupService` | `backup.proto` | Зашифрованные бэкапы панели | | `TrustTunnelService` | `trusttunnel.proto` | Ключ TrustTunnel человека и ссылки `tt://` (пакет `mistgate.trusttunnel.v1`; уровень записи админа, закрыт для токенов API и MCP) | | `TelegramService` | `telegram.proto` | Telegram-бот и чат каждого админа (только владелец и вошедшие админы; закрыт для токенов API и MCP) | +| `UserNotifyService` | `usernotify.proto` (пакет `mistgate.usernotify.v1`) | Отдельный Telegram-бот, который пишет людям об их доступе, и чаты каждого человека: коды привязки, отключение уведомлений, отвязка, лимит чатов (вошедшие админы; бот и лимит — только у владельца, смена и сброс бота требуют повторного подтверждения; закрыт для токенов API и MCP) | | `ApiTokenService`, `ApprovalService` | `integrations.proto` | API-токены и одобрения владельца | | `CheburcheckService`, `BsbordService` | `cheburcheck.proto`, `bsbord.proto` | Источники cheburcheck и bsbord [проверки из страны](../operations/reachability.md): настройки, статус и проверка, а у bsbord ещё список единиц и запрос цены (только владелец; изменение и отключение источника и запрос цены требуют повторного подтверждения; закрыт для токенов API и MCP) | diff --git a/docs/zh/reference/api.md b/docs/zh/reference/api.md index 1b5cb7fc..29f70e89 100644 --- a/docs/zh/reference/api.md +++ b/docs/zh/reference/api.md @@ -42,6 +42,7 @@ API 定义位于 `proto/mistgate/admin/v1/`。生成的代码也在仓库中:G | `BackupService` | `backup.proto` | 面板加密备份 | | `TrustTunnelService` | `trusttunnel.proto` | 用户的 TrustTunnel 密钥和 `tt://` 链接(包 `mistgate.trusttunnel.v1`;管理员写入级别,对 API 令牌和 MCP 关闭) | | `TelegramService` | `telegram.proto` | Telegram 机器人和各管理员的聊天(仅所有者和已登录的管理员可用;API 令牌和 MCP 无法访问) | +| `UserNotifyService` | `usernotify.proto`(包 `mistgate.usernotify.v1`) | 向用户通知其访问情况的独立 Telegram 机器人,以及每位用户的聊天:绑定码、静音、解绑、聊天上限(已登录的管理员可用;机器人及其上限仅所有者可设置,更换或清除机器人需要再次验证;API 令牌和 MCP 无法访问) | | `ApiTokenService`, `ApprovalService` | `integrations.proto` | API 令牌和所有者审批 | | `CheburcheckService`, `BsbordService` | `cheburcheck.proto`, `bsbord.proto` | [国家视角检测](../operations/reachability.md)的 cheburcheck 和 bsbord 来源:设置、状态和测试,bsbord 另有单元列表和价格查询(仅所有者;更改或断开来源以及价格查询需要再次验证;API 令牌和 MCP 无法访问) | diff --git a/edge/bridge/cron_js_test.go b/edge/bridge/cron_js_test.go index 7a499020..708eea06 100644 --- a/edge/bridge/cron_js_test.go +++ b/edge/bridge/cron_js_test.go @@ -19,6 +19,7 @@ import ( "github.com/mistgate/mistgate/internal/panel/health" "github.com/mistgate/mistgate/internal/panel/proposal/proposalrpc" "github.com/mistgate/mistgate/internal/panel/store" + "github.com/mistgate/mistgate/internal/panel/telegram/usernotifyrpc" "github.com/mistgate/mistgate/internal/panel/vault" ) @@ -99,6 +100,7 @@ func TestCronOpRunsEdgeTickAndReleasesFanout(t *testing.T) { RPOrigins: []string{"https://example.com"}, AgentSNI: "agent.example.com", SubPrefix: "/sub/", }, Remote: remote, AfterResponse: runner.Run, ProposalAPI: proposalrpc.Handler, + UserNotifyAPI: usernotifyrpc.Handler, }) if err != nil { t.Fatal(err) @@ -256,6 +258,7 @@ func TestCronConcurrentTicksShareOneCountryRound(t *testing.T) { RPOrigins: []string{"https://example.com"}, AgentSNI: "agent.example.com", SubPrefix: "/sub/", }, Remote: &cronTestRemote{}, AfterResponse: afterResponse, ProposalAPI: proposalrpc.Handler, + UserNotifyAPI: usernotifyrpc.Handler, }) if err != nil { t.Fatal(err) diff --git a/edge/bridge/proposals_js_test.go b/edge/bridge/proposals_js_test.go index 6aa30130..ce30561e 100644 --- a/edge/bridge/proposals_js_test.go +++ b/edge/bridge/proposals_js_test.go @@ -14,6 +14,7 @@ import ( "github.com/mistgate/mistgate/internal/panel/auth" "github.com/mistgate/mistgate/internal/panel/proposal/proposalrpc" "github.com/mistgate/mistgate/internal/panel/store" + "github.com/mistgate/mistgate/internal/panel/telegram/usernotifyrpc" "github.com/mistgate/mistgate/internal/panel/vault" ) @@ -51,6 +52,7 @@ func TestCronProposalsWorkCost(t *testing.T) { RPOrigins: []string{"https://example.com"}, AgentSNI: "agent.example.com", SubPrefix: "/sub/", }, Remote: &cronTestRemote{}, AfterResponse: runner.Run, ProposalAPI: proposalrpc.Handler, + UserNotifyAPI: usernotifyrpc.Handler, }) if err != nil { t.Fatal(err) diff --git a/edge/bridge/role_js_test.go b/edge/bridge/role_js_test.go index 66d4996f..b7ce4fdf 100644 --- a/edge/bridge/role_js_test.go +++ b/edge/bridge/role_js_test.go @@ -5,6 +5,7 @@ package bridge import ( "github.com/mistgate/mistgate/internal/panel/app" "github.com/mistgate/mistgate/internal/panel/proposal/proposalrpc" + "github.com/mistgate/mistgate/internal/panel/telegram/usernotifyrpc" ) // The tests run the role with every operation, as cmd/mistgate-edge does: the whole panel (with the ProposalService plugged in, @@ -13,6 +14,7 @@ import ( func init() { active = Role{Name: "all", Build: func(c app.Config) (*app.Panel, error) { c.ProposalAPI = proposalrpc.Handler + c.UserNotifyAPI = usernotifyrpc.Handler return app.Build(c) }, Auth: true, CreatesInstance: true} provisioner = sshProvisioner diff --git a/edge/bridge/silent_js_test.go b/edge/bridge/silent_js_test.go index 7318dc2b..16b00a85 100644 --- a/edge/bridge/silent_js_test.go +++ b/edge/bridge/silent_js_test.go @@ -19,6 +19,7 @@ import ( "github.com/mistgate/mistgate/internal/panel/proposal/proposalrpc" "github.com/mistgate/mistgate/internal/panel/protocols/builtin" "github.com/mistgate/mistgate/internal/panel/store" + "github.com/mistgate/mistgate/internal/panel/telegram/usernotifyrpc" "github.com/mistgate/mistgate/internal/panel/vault" ) @@ -62,6 +63,7 @@ func silentCalls(t *testing.T, detector bool, setup func(ctx context.Context, t RPOrigins: []string{"https://example.com"}, AgentSNI: "agent.example.com", SubPrefix: "/sub/", }, Remote: &cronTestRemote{}, AfterResponse: newEdgeTaskRunner().Run, ProposalAPI: proposalrpc.Handler, + UserNotifyAPI: usernotifyrpc.Handler, }) if err != nil { t.Fatal(err) diff --git a/gen/mistgate/usernotify/v1/usernotify.pb.go b/gen/mistgate/usernotify/v1/usernotify.pb.go new file mode 100644 index 00000000..fd0d9137 --- /dev/null +++ b/gen/mistgate/usernotify/v1/usernotify.pb.go @@ -0,0 +1,827 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.12 +// protoc (unknown) +// source: mistgate/usernotify/v1/usernotify.proto + +package usernotifyv1 + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type Empty struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Empty) Reset() { + *x = Empty{} + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Empty) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Empty) ProtoMessage() {} + +func (x *Empty) ProtoReflect() protoreflect.Message { + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Empty.ProtoReflect.Descriptor instead. +func (*Empty) Descriptor() ([]byte, []int) { + return file_mistgate_usernotify_v1_usernotify_proto_rawDescGZIP(), []int{0} +} + +// The state of the bot, for the settings card. +type UserBot struct { + state protoimpl.MessageState `protogen:"open.v1"` + Configured bool `protobuf:"varint,1,opt,name=configured,proto3" json:"configured,omitempty"` + // The bot's @username without the "@". + Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"` + // "" (no bot), "ok", "unauthorized" (Telegram refuses the token), "unreachable" (no answer), "conflict" (another program + // polls this bot) or "same_as_owner" (it is the owner's own bot, which the panel refuses to use). + State string `protobuf:"bytes,3,opt,name=state,proto3" json:"state,omitempty"` + // When the last message reached a chat; 0 = never. + LastSentUnix int64 `protobuf:"varint,4,opt,name=last_sent_unix,json=lastSentUnix,proto3" json:"last_sent_unix,omitempty"` + // People with at least one chat, and chats in all. + LinkedPeople int32 `protobuf:"varint,5,opt,name=linked_people,json=linkedPeople,proto3" json:"linked_people,omitempty"` + LinkedChats int32 `protobuf:"varint,6,opt,name=linked_chats,json=linkedChats,proto3" json:"linked_chats,omitempty"` + // The chat limit of everybody; chat_limit_default is what it is without a setting. + ChatLimit int32 `protobuf:"varint,7,opt,name=chat_limit,json=chatLimit,proto3" json:"chat_limit,omitempty"` + ChatLimitDefault int32 `protobuf:"varint,8,opt,name=chat_limit_default,json=chatLimitDefault,proto3" json:"chat_limit_default,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UserBot) Reset() { + *x = UserBot{} + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UserBot) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UserBot) ProtoMessage() {} + +func (x *UserBot) ProtoReflect() protoreflect.Message { + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UserBot.ProtoReflect.Descriptor instead. +func (*UserBot) Descriptor() ([]byte, []int) { + return file_mistgate_usernotify_v1_usernotify_proto_rawDescGZIP(), []int{1} +} + +func (x *UserBot) GetConfigured() bool { + if x != nil { + return x.Configured + } + return false +} + +func (x *UserBot) GetUsername() string { + if x != nil { + return x.Username + } + return "" +} + +func (x *UserBot) GetState() string { + if x != nil { + return x.State + } + return "" +} + +func (x *UserBot) GetLastSentUnix() int64 { + if x != nil { + return x.LastSentUnix + } + return 0 +} + +func (x *UserBot) GetLinkedPeople() int32 { + if x != nil { + return x.LinkedPeople + } + return 0 +} + +func (x *UserBot) GetLinkedChats() int32 { + if x != nil { + return x.LinkedChats + } + return 0 +} + +func (x *UserBot) GetChatLimit() int32 { + if x != nil { + return x.ChatLimit + } + return 0 +} + +func (x *UserBot) GetChatLimitDefault() int32 { + if x != nil { + return x.ChatLimitDefault + } + return 0 +} + +type SetUserBotRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The token from @BotFather. + Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SetUserBotRequest) Reset() { + *x = SetUserBotRequest{} + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SetUserBotRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SetUserBotRequest) ProtoMessage() {} + +func (x *SetUserBotRequest) ProtoReflect() protoreflect.Message { + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SetUserBotRequest.ProtoReflect.Descriptor instead. +func (*SetUserBotRequest) Descriptor() ([]byte, []int) { + return file_mistgate_usernotify_v1_usernotify_proto_rawDescGZIP(), []int{2} +} + +func (x *SetUserBotRequest) GetToken() string { + if x != nil { + return x.Token + } + return "" +} + +type SetUserBotResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Bot *UserBot `protobuf:"bytes,1,opt,name=bot,proto3" json:"bot,omitempty"` + // Chats dropped because the bot is another one than before (or none). + DroppedChats int32 `protobuf:"varint,2,opt,name=dropped_chats,json=droppedChats,proto3" json:"dropped_chats,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SetUserBotResponse) Reset() { + *x = SetUserBotResponse{} + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SetUserBotResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SetUserBotResponse) ProtoMessage() {} + +func (x *SetUserBotResponse) ProtoReflect() protoreflect.Message { + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SetUserBotResponse.ProtoReflect.Descriptor instead. +func (*SetUserBotResponse) Descriptor() ([]byte, []int) { + return file_mistgate_usernotify_v1_usernotify_proto_rawDescGZIP(), []int{3} +} + +func (x *SetUserBotResponse) GetBot() *UserBot { + if x != nil { + return x.Bot + } + return nil +} + +func (x *SetUserBotResponse) GetDroppedChats() int32 { + if x != nil { + return x.DroppedChats + } + return 0 +} + +type UserRef struct { + state protoimpl.MessageState `protogen:"open.v1"` + UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UserRef) Reset() { + *x = UserRef{} + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UserRef) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UserRef) ProtoMessage() {} + +func (x *UserRef) ProtoReflect() protoreflect.Message { + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[4] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UserRef.ProtoReflect.Descriptor instead. +func (*UserRef) Descriptor() ([]byte, []int) { + return file_mistgate_usernotify_v1_usernotify_proto_rawDescGZIP(), []int{4} +} + +func (x *UserRef) GetUserId() string { + if x != nil { + return x.UserId + } + return "" +} + +type UserTelegramLink struct { + state protoimpl.MessageState `protogen:"open.v1"` + // https://t.me/?start=; the code is in it and is shown nowhere else. + DeepLink string `protobuf:"bytes,1,opt,name=deep_link,json=deepLink,proto3" json:"deep_link,omitempty"` + ExpiresUnix int64 `protobuf:"varint,2,opt,name=expires_unix,json=expiresUnix,proto3" json:"expires_unix,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UserTelegramLink) Reset() { + *x = UserTelegramLink{} + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UserTelegramLink) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UserTelegramLink) ProtoMessage() {} + +func (x *UserTelegramLink) ProtoReflect() protoreflect.Message { + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[5] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UserTelegramLink.ProtoReflect.Descriptor instead. +func (*UserTelegramLink) Descriptor() ([]byte, []int) { + return file_mistgate_usernotify_v1_usernotify_proto_rawDescGZIP(), []int{5} +} + +func (x *UserTelegramLink) GetDeepLink() string { + if x != nil { + return x.DeepLink + } + return "" +} + +func (x *UserTelegramLink) GetExpiresUnix() int64 { + if x != nil { + return x.ExpiresUnix + } + return 0 +} + +// One chat of a person. The row id is what the other calls take; the Telegram chat id is never sent. +type UserTelegramChat struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + // ru, en, zh, tr or fa: the language of the messages to this chat. + Lang string `protobuf:"bytes,2,opt,name=lang,proto3" json:"lang,omitempty"` + // Announcements are off. + Muted bool `protobuf:"varint,3,opt,name=muted,proto3" json:"muted,omitempty"` + LinkedUnix int64 `protobuf:"varint,4,opt,name=linked_unix,json=linkedUnix,proto3" json:"linked_unix,omitempty"` + // When the last message reached the chat; 0 = never. + LastSentUnix int64 `protobuf:"varint,5,opt,name=last_sent_unix,json=lastSentUnix,proto3" json:"last_sent_unix,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UserTelegramChat) Reset() { + *x = UserTelegramChat{} + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UserTelegramChat) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UserTelegramChat) ProtoMessage() {} + +func (x *UserTelegramChat) ProtoReflect() protoreflect.Message { + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[6] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UserTelegramChat.ProtoReflect.Descriptor instead. +func (*UserTelegramChat) Descriptor() ([]byte, []int) { + return file_mistgate_usernotify_v1_usernotify_proto_rawDescGZIP(), []int{6} +} + +func (x *UserTelegramChat) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *UserTelegramChat) GetLang() string { + if x != nil { + return x.Lang + } + return "" +} + +func (x *UserTelegramChat) GetMuted() bool { + if x != nil { + return x.Muted + } + return false +} + +func (x *UserTelegramChat) GetLinkedUnix() int64 { + if x != nil { + return x.LinkedUnix + } + return 0 +} + +func (x *UserTelegramChat) GetLastSentUnix() int64 { + if x != nil { + return x.LastSentUnix + } + return 0 +} + +type ListUserTelegramChatsResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Chats []*UserTelegramChat `protobuf:"bytes,1,rep,name=chats,proto3" json:"chats,omitempty"` + // A link code is waiting (0 = none) and when it runs out. + PendingExpiresUnix int64 `protobuf:"varint,2,opt,name=pending_expires_unix,json=pendingExpiresUnix,proto3" json:"pending_expires_unix,omitempty"` + // The limit that applies to this person, and the person's own setting (0 = none; the global limit applies). + ChatLimit int32 `protobuf:"varint,3,opt,name=chat_limit,json=chatLimit,proto3" json:"chat_limit,omitempty"` + ChatLimitOverride int32 `protobuf:"varint,4,opt,name=chat_limit_override,json=chatLimitOverride,proto3" json:"chat_limit_override,omitempty"` + // Whether the bot is set at all, so the tab can say "no bot" without a second call. + BotConfigured bool `protobuf:"varint,5,opt,name=bot_configured,json=botConfigured,proto3" json:"bot_configured,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListUserTelegramChatsResponse) Reset() { + *x = ListUserTelegramChatsResponse{} + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListUserTelegramChatsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListUserTelegramChatsResponse) ProtoMessage() {} + +func (x *ListUserTelegramChatsResponse) ProtoReflect() protoreflect.Message { + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[7] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListUserTelegramChatsResponse.ProtoReflect.Descriptor instead. +func (*ListUserTelegramChatsResponse) Descriptor() ([]byte, []int) { + return file_mistgate_usernotify_v1_usernotify_proto_rawDescGZIP(), []int{7} +} + +func (x *ListUserTelegramChatsResponse) GetChats() []*UserTelegramChat { + if x != nil { + return x.Chats + } + return nil +} + +func (x *ListUserTelegramChatsResponse) GetPendingExpiresUnix() int64 { + if x != nil { + return x.PendingExpiresUnix + } + return 0 +} + +func (x *ListUserTelegramChatsResponse) GetChatLimit() int32 { + if x != nil { + return x.ChatLimit + } + return 0 +} + +func (x *ListUserTelegramChatsResponse) GetChatLimitOverride() int32 { + if x != nil { + return x.ChatLimitOverride + } + return 0 +} + +func (x *ListUserTelegramChatsResponse) GetBotConfigured() bool { + if x != nil { + return x.BotConfigured + } + return false +} + +type ChatRef struct { + state protoimpl.MessageState `protogen:"open.v1"` + UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` + ChatId string `protobuf:"bytes,2,opt,name=chat_id,json=chatId,proto3" json:"chat_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ChatRef) Reset() { + *x = ChatRef{} + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ChatRef) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ChatRef) ProtoMessage() {} + +func (x *ChatRef) ProtoReflect() protoreflect.Message { + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[8] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ChatRef.ProtoReflect.Descriptor instead. +func (*ChatRef) Descriptor() ([]byte, []int) { + return file_mistgate_usernotify_v1_usernotify_proto_rawDescGZIP(), []int{8} +} + +func (x *ChatRef) GetUserId() string { + if x != nil { + return x.UserId + } + return "" +} + +func (x *ChatRef) GetChatId() string { + if x != nil { + return x.ChatId + } + return "" +} + +type SetChatMutedRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` + ChatId string `protobuf:"bytes,2,opt,name=chat_id,json=chatId,proto3" json:"chat_id,omitempty"` + Muted bool `protobuf:"varint,3,opt,name=muted,proto3" json:"muted,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SetChatMutedRequest) Reset() { + *x = SetChatMutedRequest{} + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SetChatMutedRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SetChatMutedRequest) ProtoMessage() {} + +func (x *SetChatMutedRequest) ProtoReflect() protoreflect.Message { + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[9] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SetChatMutedRequest.ProtoReflect.Descriptor instead. +func (*SetChatMutedRequest) Descriptor() ([]byte, []int) { + return file_mistgate_usernotify_v1_usernotify_proto_rawDescGZIP(), []int{9} +} + +func (x *SetChatMutedRequest) GetUserId() string { + if x != nil { + return x.UserId + } + return "" +} + +func (x *SetChatMutedRequest) GetChatId() string { + if x != nil { + return x.ChatId + } + return "" +} + +func (x *SetChatMutedRequest) GetMuted() bool { + if x != nil { + return x.Muted + } + return false +} + +type SetChatLimitRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` + Limit int32 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SetChatLimitRequest) Reset() { + *x = SetChatLimitRequest{} + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SetChatLimitRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SetChatLimitRequest) ProtoMessage() {} + +func (x *SetChatLimitRequest) ProtoReflect() protoreflect.Message { + mi := &file_mistgate_usernotify_v1_usernotify_proto_msgTypes[10] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SetChatLimitRequest.ProtoReflect.Descriptor instead. +func (*SetChatLimitRequest) Descriptor() ([]byte, []int) { + return file_mistgate_usernotify_v1_usernotify_proto_rawDescGZIP(), []int{10} +} + +func (x *SetChatLimitRequest) GetUserId() string { + if x != nil { + return x.UserId + } + return "" +} + +func (x *SetChatLimitRequest) GetLimit() int32 { + if x != nil { + return x.Limit + } + return 0 +} + +var File_mistgate_usernotify_v1_usernotify_proto protoreflect.FileDescriptor + +const file_mistgate_usernotify_v1_usernotify_proto_rawDesc = "" + + "\n" + + "'mistgate/usernotify/v1/usernotify.proto\x12\x16mistgate.usernotify.v1\"\a\n" + + "\x05Empty\"\x9a\x02\n" + + "\aUserBot\x12\x1e\n" + + "\n" + + "configured\x18\x01 \x01(\bR\n" + + "configured\x12\x1a\n" + + "\busername\x18\x02 \x01(\tR\busername\x12\x14\n" + + "\x05state\x18\x03 \x01(\tR\x05state\x12(\n" + + "\x0elast_sent_unix\x18\x04 \x01(\x03B\x020\x02R\flastSentUnix\x12#\n" + + "\rlinked_people\x18\x05 \x01(\x05R\flinkedPeople\x12!\n" + + "\flinked_chats\x18\x06 \x01(\x05R\vlinkedChats\x12\x1d\n" + + "\n" + + "chat_limit\x18\a \x01(\x05R\tchatLimit\x12,\n" + + "\x12chat_limit_default\x18\b \x01(\x05R\x10chatLimitDefault\")\n" + + "\x11SetUserBotRequest\x12\x14\n" + + "\x05token\x18\x01 \x01(\tR\x05token\"l\n" + + "\x12SetUserBotResponse\x121\n" + + "\x03bot\x18\x01 \x01(\v2\x1f.mistgate.usernotify.v1.UserBotR\x03bot\x12#\n" + + "\rdropped_chats\x18\x02 \x01(\x05R\fdroppedChats\"\"\n" + + "\aUserRef\x12\x17\n" + + "\auser_id\x18\x01 \x01(\tR\x06userId\"V\n" + + "\x10UserTelegramLink\x12\x1b\n" + + "\tdeep_link\x18\x01 \x01(\tR\bdeepLink\x12%\n" + + "\fexpires_unix\x18\x02 \x01(\x03B\x020\x02R\vexpiresUnix\"\x9b\x01\n" + + "\x10UserTelegramChat\x12\x0e\n" + + "\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" + + "\x04lang\x18\x02 \x01(\tR\x04lang\x12\x14\n" + + "\x05muted\x18\x03 \x01(\bR\x05muted\x12#\n" + + "\vlinked_unix\x18\x04 \x01(\x03B\x020\x02R\n" + + "linkedUnix\x12(\n" + + "\x0elast_sent_unix\x18\x05 \x01(\x03B\x020\x02R\flastSentUnix\"\x8b\x02\n" + + "\x1dListUserTelegramChatsResponse\x12>\n" + + "\x05chats\x18\x01 \x03(\v2(.mistgate.usernotify.v1.UserTelegramChatR\x05chats\x124\n" + + "\x14pending_expires_unix\x18\x02 \x01(\x03B\x020\x02R\x12pendingExpiresUnix\x12\x1d\n" + + "\n" + + "chat_limit\x18\x03 \x01(\x05R\tchatLimit\x12.\n" + + "\x13chat_limit_override\x18\x04 \x01(\x05R\x11chatLimitOverride\x12%\n" + + "\x0ebot_configured\x18\x05 \x01(\bR\rbotConfigured\";\n" + + "\aChatRef\x12\x17\n" + + "\auser_id\x18\x01 \x01(\tR\x06userId\x12\x17\n" + + "\achat_id\x18\x02 \x01(\tR\x06chatId\"]\n" + + "\x13SetChatMutedRequest\x12\x17\n" + + "\auser_id\x18\x01 \x01(\tR\x06userId\x12\x17\n" + + "\achat_id\x18\x02 \x01(\tR\x06chatId\x12\x14\n" + + "\x05muted\x18\x03 \x01(\bR\x05muted\"D\n" + + "\x13SetChatLimitRequest\x12\x17\n" + + "\auser_id\x18\x01 \x01(\tR\x06userId\x12\x14\n" + + "\x05limit\x18\x02 \x01(\x05R\x05limit2\xfa\x06\n" + + "\x11UserNotifyService\x12L\n" + + "\n" + + "GetUserBot\x12\x1d.mistgate.usernotify.v1.Empty\x1a\x1f.mistgate.usernotify.v1.UserBot\x12c\n" + + "\n" + + "SetUserBot\x12).mistgate.usernotify.v1.SetUserBotRequest\x1a*.mistgate.usernotify.v1.SetUserBotResponse\x12Y\n" + + "\fClearUserBot\x12\x1d.mistgate.usernotify.v1.Empty\x1a*.mistgate.usernotify.v1.SetUserBotResponse\x12b\n" + + "\x15BeginUserTelegramLink\x12\x1f.mistgate.usernotify.v1.UserRef\x1a(.mistgate.usernotify.v1.UserTelegramLink\x12X\n" + + "\x16CancelUserTelegramLink\x12\x1f.mistgate.usernotify.v1.UserRef\x1a\x1d.mistgate.usernotify.v1.Empty\x12o\n" + + "\x15ListUserTelegramChats\x12\x1f.mistgate.usernotify.v1.UserRef\x1a5.mistgate.usernotify.v1.ListUserTelegramChatsResponse\x12X\n" + + "\x16UnlinkUserTelegramChat\x12\x1f.mistgate.usernotify.v1.ChatRef\x1a\x1d.mistgate.usernotify.v1.Empty\x12f\n" + + "\x18SetUserTelegramChatMuted\x12+.mistgate.usernotify.v1.SetChatMutedRequest\x1a\x1d.mistgate.usernotify.v1.Empty\x12f\n" + + "\x18SetUserTelegramChatLimit\x12+.mistgate.usernotify.v1.SetChatLimitRequest\x1a\x1d.mistgate.usernotify.v1.EmptyB\xed\x01\n" + + "\x1acom.mistgate.usernotify.v1B\x0fUsernotifyProtoP\x01ZDgithub.com/mistgate/mistgate/gen/mistgate/usernotify/v1;usernotifyv1\xa2\x02\x03MUX\xaa\x02\x16Mistgate.Usernotify.V1\xca\x02\x16Mistgate\\Usernotify\\V1\xe2\x02\"Mistgate\\Usernotify\\V1\\GPBMetadata\xea\x02\x18Mistgate::Usernotify::V1b\x06proto3" + +var ( + file_mistgate_usernotify_v1_usernotify_proto_rawDescOnce sync.Once + file_mistgate_usernotify_v1_usernotify_proto_rawDescData []byte +) + +func file_mistgate_usernotify_v1_usernotify_proto_rawDescGZIP() []byte { + file_mistgate_usernotify_v1_usernotify_proto_rawDescOnce.Do(func() { + file_mistgate_usernotify_v1_usernotify_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_mistgate_usernotify_v1_usernotify_proto_rawDesc), len(file_mistgate_usernotify_v1_usernotify_proto_rawDesc))) + }) + return file_mistgate_usernotify_v1_usernotify_proto_rawDescData +} + +var file_mistgate_usernotify_v1_usernotify_proto_msgTypes = make([]protoimpl.MessageInfo, 11) +var file_mistgate_usernotify_v1_usernotify_proto_goTypes = []any{ + (*Empty)(nil), // 0: mistgate.usernotify.v1.Empty + (*UserBot)(nil), // 1: mistgate.usernotify.v1.UserBot + (*SetUserBotRequest)(nil), // 2: mistgate.usernotify.v1.SetUserBotRequest + (*SetUserBotResponse)(nil), // 3: mistgate.usernotify.v1.SetUserBotResponse + (*UserRef)(nil), // 4: mistgate.usernotify.v1.UserRef + (*UserTelegramLink)(nil), // 5: mistgate.usernotify.v1.UserTelegramLink + (*UserTelegramChat)(nil), // 6: mistgate.usernotify.v1.UserTelegramChat + (*ListUserTelegramChatsResponse)(nil), // 7: mistgate.usernotify.v1.ListUserTelegramChatsResponse + (*ChatRef)(nil), // 8: mistgate.usernotify.v1.ChatRef + (*SetChatMutedRequest)(nil), // 9: mistgate.usernotify.v1.SetChatMutedRequest + (*SetChatLimitRequest)(nil), // 10: mistgate.usernotify.v1.SetChatLimitRequest +} +var file_mistgate_usernotify_v1_usernotify_proto_depIdxs = []int32{ + 1, // 0: mistgate.usernotify.v1.SetUserBotResponse.bot:type_name -> mistgate.usernotify.v1.UserBot + 6, // 1: mistgate.usernotify.v1.ListUserTelegramChatsResponse.chats:type_name -> mistgate.usernotify.v1.UserTelegramChat + 0, // 2: mistgate.usernotify.v1.UserNotifyService.GetUserBot:input_type -> mistgate.usernotify.v1.Empty + 2, // 3: mistgate.usernotify.v1.UserNotifyService.SetUserBot:input_type -> mistgate.usernotify.v1.SetUserBotRequest + 0, // 4: mistgate.usernotify.v1.UserNotifyService.ClearUserBot:input_type -> mistgate.usernotify.v1.Empty + 4, // 5: mistgate.usernotify.v1.UserNotifyService.BeginUserTelegramLink:input_type -> mistgate.usernotify.v1.UserRef + 4, // 6: mistgate.usernotify.v1.UserNotifyService.CancelUserTelegramLink:input_type -> mistgate.usernotify.v1.UserRef + 4, // 7: mistgate.usernotify.v1.UserNotifyService.ListUserTelegramChats:input_type -> mistgate.usernotify.v1.UserRef + 8, // 8: mistgate.usernotify.v1.UserNotifyService.UnlinkUserTelegramChat:input_type -> mistgate.usernotify.v1.ChatRef + 9, // 9: mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatMuted:input_type -> mistgate.usernotify.v1.SetChatMutedRequest + 10, // 10: mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatLimit:input_type -> mistgate.usernotify.v1.SetChatLimitRequest + 1, // 11: mistgate.usernotify.v1.UserNotifyService.GetUserBot:output_type -> mistgate.usernotify.v1.UserBot + 3, // 12: mistgate.usernotify.v1.UserNotifyService.SetUserBot:output_type -> mistgate.usernotify.v1.SetUserBotResponse + 3, // 13: mistgate.usernotify.v1.UserNotifyService.ClearUserBot:output_type -> mistgate.usernotify.v1.SetUserBotResponse + 5, // 14: mistgate.usernotify.v1.UserNotifyService.BeginUserTelegramLink:output_type -> mistgate.usernotify.v1.UserTelegramLink + 0, // 15: mistgate.usernotify.v1.UserNotifyService.CancelUserTelegramLink:output_type -> mistgate.usernotify.v1.Empty + 7, // 16: mistgate.usernotify.v1.UserNotifyService.ListUserTelegramChats:output_type -> mistgate.usernotify.v1.ListUserTelegramChatsResponse + 0, // 17: mistgate.usernotify.v1.UserNotifyService.UnlinkUserTelegramChat:output_type -> mistgate.usernotify.v1.Empty + 0, // 18: mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatMuted:output_type -> mistgate.usernotify.v1.Empty + 0, // 19: mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatLimit:output_type -> mistgate.usernotify.v1.Empty + 11, // [11:20] is the sub-list for method output_type + 2, // [2:11] is the sub-list for method input_type + 2, // [2:2] is the sub-list for extension type_name + 2, // [2:2] is the sub-list for extension extendee + 0, // [0:2] is the sub-list for field type_name +} + +func init() { file_mistgate_usernotify_v1_usernotify_proto_init() } +func file_mistgate_usernotify_v1_usernotify_proto_init() { + if File_mistgate_usernotify_v1_usernotify_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_mistgate_usernotify_v1_usernotify_proto_rawDesc), len(file_mistgate_usernotify_v1_usernotify_proto_rawDesc)), + NumEnums: 0, + NumMessages: 11, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_mistgate_usernotify_v1_usernotify_proto_goTypes, + DependencyIndexes: file_mistgate_usernotify_v1_usernotify_proto_depIdxs, + MessageInfos: file_mistgate_usernotify_v1_usernotify_proto_msgTypes, + }.Build() + File_mistgate_usernotify_v1_usernotify_proto = out.File + file_mistgate_usernotify_v1_usernotify_proto_goTypes = nil + file_mistgate_usernotify_v1_usernotify_proto_depIdxs = nil +} diff --git a/gen/mistgate/usernotify/v1/usernotifyv1connect/usernotify.connect.go b/gen/mistgate/usernotify/v1/usernotifyv1connect/usernotify.connect.go new file mode 100644 index 00000000..374afdf6 --- /dev/null +++ b/gen/mistgate/usernotify/v1/usernotifyv1connect/usernotify.connect.go @@ -0,0 +1,360 @@ +// Code generated by protoc-gen-connect-go. DO NOT EDIT. +// +// Source: mistgate/usernotify/v1/usernotify.proto + +package usernotifyv1connect + +import ( + connect "connectrpc.com/connect" + context "context" + errors "errors" + v1 "github.com/mistgate/mistgate/gen/mistgate/usernotify/v1" + http "net/http" + strings "strings" +) + +// This is a compile-time assertion to ensure that this generated file and the connect package are +// compatible. If you get a compiler error that this constant is not defined, this code was +// generated with a version of connect newer than the one compiled into your binary. You can fix the +// problem by either regenerating this code with an older version of connect or updating the connect +// version compiled into your binary. +const _ = connect.IsAtLeastVersion1_13_0 + +const ( + // UserNotifyServiceName is the fully-qualified name of the UserNotifyService service. + UserNotifyServiceName = "mistgate.usernotify.v1.UserNotifyService" +) + +// These constants are the fully-qualified names of the RPCs defined in this package. They're +// exposed at runtime as Spec.Procedure and as the final two segments of the HTTP route. +// +// Note that these are different from the fully-qualified method names used by +// google.golang.org/protobuf/reflect/protoreflect. To convert from these constants to +// reflection-formatted method names, remove the leading slash and convert the remaining slash to a +// period. +const ( + // UserNotifyServiceGetUserBotProcedure is the fully-qualified name of the UserNotifyService's + // GetUserBot RPC. + UserNotifyServiceGetUserBotProcedure = "/mistgate.usernotify.v1.UserNotifyService/GetUserBot" + // UserNotifyServiceSetUserBotProcedure is the fully-qualified name of the UserNotifyService's + // SetUserBot RPC. + UserNotifyServiceSetUserBotProcedure = "/mistgate.usernotify.v1.UserNotifyService/SetUserBot" + // UserNotifyServiceClearUserBotProcedure is the fully-qualified name of the UserNotifyService's + // ClearUserBot RPC. + UserNotifyServiceClearUserBotProcedure = "/mistgate.usernotify.v1.UserNotifyService/ClearUserBot" + // UserNotifyServiceBeginUserTelegramLinkProcedure is the fully-qualified name of the + // UserNotifyService's BeginUserTelegramLink RPC. + UserNotifyServiceBeginUserTelegramLinkProcedure = "/mistgate.usernotify.v1.UserNotifyService/BeginUserTelegramLink" + // UserNotifyServiceCancelUserTelegramLinkProcedure is the fully-qualified name of the + // UserNotifyService's CancelUserTelegramLink RPC. + UserNotifyServiceCancelUserTelegramLinkProcedure = "/mistgate.usernotify.v1.UserNotifyService/CancelUserTelegramLink" + // UserNotifyServiceListUserTelegramChatsProcedure is the fully-qualified name of the + // UserNotifyService's ListUserTelegramChats RPC. + UserNotifyServiceListUserTelegramChatsProcedure = "/mistgate.usernotify.v1.UserNotifyService/ListUserTelegramChats" + // UserNotifyServiceUnlinkUserTelegramChatProcedure is the fully-qualified name of the + // UserNotifyService's UnlinkUserTelegramChat RPC. + UserNotifyServiceUnlinkUserTelegramChatProcedure = "/mistgate.usernotify.v1.UserNotifyService/UnlinkUserTelegramChat" + // UserNotifyServiceSetUserTelegramChatMutedProcedure is the fully-qualified name of the + // UserNotifyService's SetUserTelegramChatMuted RPC. + UserNotifyServiceSetUserTelegramChatMutedProcedure = "/mistgate.usernotify.v1.UserNotifyService/SetUserTelegramChatMuted" + // UserNotifyServiceSetUserTelegramChatLimitProcedure is the fully-qualified name of the + // UserNotifyService's SetUserTelegramChatLimit RPC. + UserNotifyServiceSetUserTelegramChatLimitProcedure = "/mistgate.usernotify.v1.UserNotifyService/SetUserTelegramChatLimit" +) + +// UserNotifyServiceClient is a client for the mistgate.usernotify.v1.UserNotifyService service. +type UserNotifyServiceClient interface { + // The bot for the card: state, counts, the chat limit. No secrets, no chat ids. + GetUserBot(context.Context, *connect.Request[v1.Empty]) (*connect.Response[v1.UserBot], error) + // Sets the bot. Owner only; needs a step-up. Another bot than the stored one drops every chat. + SetUserBot(context.Context, *connect.Request[v1.SetUserBotRequest]) (*connect.Response[v1.SetUserBotResponse], error) + // Switches the bot off and forgets every chat, pending code and Telegram delivery. Owner only; needs a step-up. + ClearUserBot(context.Context, *connect.Request[v1.Empty]) (*connect.Response[v1.SetUserBotResponse], error) + // Hands out a link code for a person; a new one replaces the pending one. + BeginUserTelegramLink(context.Context, *connect.Request[v1.UserRef]) (*connect.Response[v1.UserTelegramLink], error) + // Withdraws the pending code of a person. Idempotent. + CancelUserTelegramLink(context.Context, *connect.Request[v1.UserRef]) (*connect.Response[v1.Empty], error) + // The chats of a person and the pending link, without chat ids. + ListUserTelegramChats(context.Context, *connect.Request[v1.UserRef]) (*connect.Response[v1.ListUserTelegramChatsResponse], error) + // Forgets one chat of a person. Idempotent. + UnlinkUserTelegramChat(context.Context, *connect.Request[v1.ChatRef]) (*connect.Response[v1.Empty], error) + // Switches the announcements of one chat off or on. + SetUserTelegramChatMuted(context.Context, *connect.Request[v1.SetChatMutedRequest]) (*connect.Response[v1.Empty], error) + // The chat limit: of everybody (user_id empty) or of one person, 1 to 10; 0 returns to the default. Owner only. + SetUserTelegramChatLimit(context.Context, *connect.Request[v1.SetChatLimitRequest]) (*connect.Response[v1.Empty], error) +} + +// NewUserNotifyServiceClient constructs a client for the mistgate.usernotify.v1.UserNotifyService +// service. By default, it uses the Connect protocol with the binary Protobuf Codec, asks for +// gzipped responses, and sends uncompressed requests. To use the gRPC or gRPC-Web protocols, supply +// the connect.WithGRPC() or connect.WithGRPCWeb() options. +// +// The URL supplied here should be the base URL for the Connect or gRPC server (for example, +// http://api.acme.com or https://acme.com/grpc). +func NewUserNotifyServiceClient(httpClient connect.HTTPClient, baseURL string, opts ...connect.ClientOption) UserNotifyServiceClient { + baseURL = strings.TrimRight(baseURL, "/") + userNotifyServiceMethods := v1.File_mistgate_usernotify_v1_usernotify_proto.Services().ByName("UserNotifyService").Methods() + return &userNotifyServiceClient{ + getUserBot: connect.NewClient[v1.Empty, v1.UserBot]( + httpClient, + baseURL+UserNotifyServiceGetUserBotProcedure, + connect.WithSchema(userNotifyServiceMethods.ByName("GetUserBot")), + connect.WithClientOptions(opts...), + ), + setUserBot: connect.NewClient[v1.SetUserBotRequest, v1.SetUserBotResponse]( + httpClient, + baseURL+UserNotifyServiceSetUserBotProcedure, + connect.WithSchema(userNotifyServiceMethods.ByName("SetUserBot")), + connect.WithClientOptions(opts...), + ), + clearUserBot: connect.NewClient[v1.Empty, v1.SetUserBotResponse]( + httpClient, + baseURL+UserNotifyServiceClearUserBotProcedure, + connect.WithSchema(userNotifyServiceMethods.ByName("ClearUserBot")), + connect.WithClientOptions(opts...), + ), + beginUserTelegramLink: connect.NewClient[v1.UserRef, v1.UserTelegramLink]( + httpClient, + baseURL+UserNotifyServiceBeginUserTelegramLinkProcedure, + connect.WithSchema(userNotifyServiceMethods.ByName("BeginUserTelegramLink")), + connect.WithClientOptions(opts...), + ), + cancelUserTelegramLink: connect.NewClient[v1.UserRef, v1.Empty]( + httpClient, + baseURL+UserNotifyServiceCancelUserTelegramLinkProcedure, + connect.WithSchema(userNotifyServiceMethods.ByName("CancelUserTelegramLink")), + connect.WithClientOptions(opts...), + ), + listUserTelegramChats: connect.NewClient[v1.UserRef, v1.ListUserTelegramChatsResponse]( + httpClient, + baseURL+UserNotifyServiceListUserTelegramChatsProcedure, + connect.WithSchema(userNotifyServiceMethods.ByName("ListUserTelegramChats")), + connect.WithClientOptions(opts...), + ), + unlinkUserTelegramChat: connect.NewClient[v1.ChatRef, v1.Empty]( + httpClient, + baseURL+UserNotifyServiceUnlinkUserTelegramChatProcedure, + connect.WithSchema(userNotifyServiceMethods.ByName("UnlinkUserTelegramChat")), + connect.WithClientOptions(opts...), + ), + setUserTelegramChatMuted: connect.NewClient[v1.SetChatMutedRequest, v1.Empty]( + httpClient, + baseURL+UserNotifyServiceSetUserTelegramChatMutedProcedure, + connect.WithSchema(userNotifyServiceMethods.ByName("SetUserTelegramChatMuted")), + connect.WithClientOptions(opts...), + ), + setUserTelegramChatLimit: connect.NewClient[v1.SetChatLimitRequest, v1.Empty]( + httpClient, + baseURL+UserNotifyServiceSetUserTelegramChatLimitProcedure, + connect.WithSchema(userNotifyServiceMethods.ByName("SetUserTelegramChatLimit")), + connect.WithClientOptions(opts...), + ), + } +} + +// userNotifyServiceClient implements UserNotifyServiceClient. +type userNotifyServiceClient struct { + getUserBot *connect.Client[v1.Empty, v1.UserBot] + setUserBot *connect.Client[v1.SetUserBotRequest, v1.SetUserBotResponse] + clearUserBot *connect.Client[v1.Empty, v1.SetUserBotResponse] + beginUserTelegramLink *connect.Client[v1.UserRef, v1.UserTelegramLink] + cancelUserTelegramLink *connect.Client[v1.UserRef, v1.Empty] + listUserTelegramChats *connect.Client[v1.UserRef, v1.ListUserTelegramChatsResponse] + unlinkUserTelegramChat *connect.Client[v1.ChatRef, v1.Empty] + setUserTelegramChatMuted *connect.Client[v1.SetChatMutedRequest, v1.Empty] + setUserTelegramChatLimit *connect.Client[v1.SetChatLimitRequest, v1.Empty] +} + +// GetUserBot calls mistgate.usernotify.v1.UserNotifyService.GetUserBot. +func (c *userNotifyServiceClient) GetUserBot(ctx context.Context, req *connect.Request[v1.Empty]) (*connect.Response[v1.UserBot], error) { + return c.getUserBot.CallUnary(ctx, req) +} + +// SetUserBot calls mistgate.usernotify.v1.UserNotifyService.SetUserBot. +func (c *userNotifyServiceClient) SetUserBot(ctx context.Context, req *connect.Request[v1.SetUserBotRequest]) (*connect.Response[v1.SetUserBotResponse], error) { + return c.setUserBot.CallUnary(ctx, req) +} + +// ClearUserBot calls mistgate.usernotify.v1.UserNotifyService.ClearUserBot. +func (c *userNotifyServiceClient) ClearUserBot(ctx context.Context, req *connect.Request[v1.Empty]) (*connect.Response[v1.SetUserBotResponse], error) { + return c.clearUserBot.CallUnary(ctx, req) +} + +// BeginUserTelegramLink calls mistgate.usernotify.v1.UserNotifyService.BeginUserTelegramLink. +func (c *userNotifyServiceClient) BeginUserTelegramLink(ctx context.Context, req *connect.Request[v1.UserRef]) (*connect.Response[v1.UserTelegramLink], error) { + return c.beginUserTelegramLink.CallUnary(ctx, req) +} + +// CancelUserTelegramLink calls mistgate.usernotify.v1.UserNotifyService.CancelUserTelegramLink. +func (c *userNotifyServiceClient) CancelUserTelegramLink(ctx context.Context, req *connect.Request[v1.UserRef]) (*connect.Response[v1.Empty], error) { + return c.cancelUserTelegramLink.CallUnary(ctx, req) +} + +// ListUserTelegramChats calls mistgate.usernotify.v1.UserNotifyService.ListUserTelegramChats. +func (c *userNotifyServiceClient) ListUserTelegramChats(ctx context.Context, req *connect.Request[v1.UserRef]) (*connect.Response[v1.ListUserTelegramChatsResponse], error) { + return c.listUserTelegramChats.CallUnary(ctx, req) +} + +// UnlinkUserTelegramChat calls mistgate.usernotify.v1.UserNotifyService.UnlinkUserTelegramChat. +func (c *userNotifyServiceClient) UnlinkUserTelegramChat(ctx context.Context, req *connect.Request[v1.ChatRef]) (*connect.Response[v1.Empty], error) { + return c.unlinkUserTelegramChat.CallUnary(ctx, req) +} + +// SetUserTelegramChatMuted calls mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatMuted. +func (c *userNotifyServiceClient) SetUserTelegramChatMuted(ctx context.Context, req *connect.Request[v1.SetChatMutedRequest]) (*connect.Response[v1.Empty], error) { + return c.setUserTelegramChatMuted.CallUnary(ctx, req) +} + +// SetUserTelegramChatLimit calls mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatLimit. +func (c *userNotifyServiceClient) SetUserTelegramChatLimit(ctx context.Context, req *connect.Request[v1.SetChatLimitRequest]) (*connect.Response[v1.Empty], error) { + return c.setUserTelegramChatLimit.CallUnary(ctx, req) +} + +// UserNotifyServiceHandler is an implementation of the mistgate.usernotify.v1.UserNotifyService +// service. +type UserNotifyServiceHandler interface { + // The bot for the card: state, counts, the chat limit. No secrets, no chat ids. + GetUserBot(context.Context, *connect.Request[v1.Empty]) (*connect.Response[v1.UserBot], error) + // Sets the bot. Owner only; needs a step-up. Another bot than the stored one drops every chat. + SetUserBot(context.Context, *connect.Request[v1.SetUserBotRequest]) (*connect.Response[v1.SetUserBotResponse], error) + // Switches the bot off and forgets every chat, pending code and Telegram delivery. Owner only; needs a step-up. + ClearUserBot(context.Context, *connect.Request[v1.Empty]) (*connect.Response[v1.SetUserBotResponse], error) + // Hands out a link code for a person; a new one replaces the pending one. + BeginUserTelegramLink(context.Context, *connect.Request[v1.UserRef]) (*connect.Response[v1.UserTelegramLink], error) + // Withdraws the pending code of a person. Idempotent. + CancelUserTelegramLink(context.Context, *connect.Request[v1.UserRef]) (*connect.Response[v1.Empty], error) + // The chats of a person and the pending link, without chat ids. + ListUserTelegramChats(context.Context, *connect.Request[v1.UserRef]) (*connect.Response[v1.ListUserTelegramChatsResponse], error) + // Forgets one chat of a person. Idempotent. + UnlinkUserTelegramChat(context.Context, *connect.Request[v1.ChatRef]) (*connect.Response[v1.Empty], error) + // Switches the announcements of one chat off or on. + SetUserTelegramChatMuted(context.Context, *connect.Request[v1.SetChatMutedRequest]) (*connect.Response[v1.Empty], error) + // The chat limit: of everybody (user_id empty) or of one person, 1 to 10; 0 returns to the default. Owner only. + SetUserTelegramChatLimit(context.Context, *connect.Request[v1.SetChatLimitRequest]) (*connect.Response[v1.Empty], error) +} + +// NewUserNotifyServiceHandler builds an HTTP handler from the service implementation. It returns +// the path on which to mount the handler and the handler itself. +// +// By default, handlers support the Connect, gRPC, and gRPC-Web protocols with the binary Protobuf +// and JSON codecs. They also support gzip compression. +func NewUserNotifyServiceHandler(svc UserNotifyServiceHandler, opts ...connect.HandlerOption) (string, http.Handler) { + userNotifyServiceMethods := v1.File_mistgate_usernotify_v1_usernotify_proto.Services().ByName("UserNotifyService").Methods() + userNotifyServiceGetUserBotHandler := connect.NewUnaryHandler( + UserNotifyServiceGetUserBotProcedure, + svc.GetUserBot, + connect.WithSchema(userNotifyServiceMethods.ByName("GetUserBot")), + connect.WithHandlerOptions(opts...), + ) + userNotifyServiceSetUserBotHandler := connect.NewUnaryHandler( + UserNotifyServiceSetUserBotProcedure, + svc.SetUserBot, + connect.WithSchema(userNotifyServiceMethods.ByName("SetUserBot")), + connect.WithHandlerOptions(opts...), + ) + userNotifyServiceClearUserBotHandler := connect.NewUnaryHandler( + UserNotifyServiceClearUserBotProcedure, + svc.ClearUserBot, + connect.WithSchema(userNotifyServiceMethods.ByName("ClearUserBot")), + connect.WithHandlerOptions(opts...), + ) + userNotifyServiceBeginUserTelegramLinkHandler := connect.NewUnaryHandler( + UserNotifyServiceBeginUserTelegramLinkProcedure, + svc.BeginUserTelegramLink, + connect.WithSchema(userNotifyServiceMethods.ByName("BeginUserTelegramLink")), + connect.WithHandlerOptions(opts...), + ) + userNotifyServiceCancelUserTelegramLinkHandler := connect.NewUnaryHandler( + UserNotifyServiceCancelUserTelegramLinkProcedure, + svc.CancelUserTelegramLink, + connect.WithSchema(userNotifyServiceMethods.ByName("CancelUserTelegramLink")), + connect.WithHandlerOptions(opts...), + ) + userNotifyServiceListUserTelegramChatsHandler := connect.NewUnaryHandler( + UserNotifyServiceListUserTelegramChatsProcedure, + svc.ListUserTelegramChats, + connect.WithSchema(userNotifyServiceMethods.ByName("ListUserTelegramChats")), + connect.WithHandlerOptions(opts...), + ) + userNotifyServiceUnlinkUserTelegramChatHandler := connect.NewUnaryHandler( + UserNotifyServiceUnlinkUserTelegramChatProcedure, + svc.UnlinkUserTelegramChat, + connect.WithSchema(userNotifyServiceMethods.ByName("UnlinkUserTelegramChat")), + connect.WithHandlerOptions(opts...), + ) + userNotifyServiceSetUserTelegramChatMutedHandler := connect.NewUnaryHandler( + UserNotifyServiceSetUserTelegramChatMutedProcedure, + svc.SetUserTelegramChatMuted, + connect.WithSchema(userNotifyServiceMethods.ByName("SetUserTelegramChatMuted")), + connect.WithHandlerOptions(opts...), + ) + userNotifyServiceSetUserTelegramChatLimitHandler := connect.NewUnaryHandler( + UserNotifyServiceSetUserTelegramChatLimitProcedure, + svc.SetUserTelegramChatLimit, + connect.WithSchema(userNotifyServiceMethods.ByName("SetUserTelegramChatLimit")), + connect.WithHandlerOptions(opts...), + ) + return "/mistgate.usernotify.v1.UserNotifyService/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case UserNotifyServiceGetUserBotProcedure: + userNotifyServiceGetUserBotHandler.ServeHTTP(w, r) + case UserNotifyServiceSetUserBotProcedure: + userNotifyServiceSetUserBotHandler.ServeHTTP(w, r) + case UserNotifyServiceClearUserBotProcedure: + userNotifyServiceClearUserBotHandler.ServeHTTP(w, r) + case UserNotifyServiceBeginUserTelegramLinkProcedure: + userNotifyServiceBeginUserTelegramLinkHandler.ServeHTTP(w, r) + case UserNotifyServiceCancelUserTelegramLinkProcedure: + userNotifyServiceCancelUserTelegramLinkHandler.ServeHTTP(w, r) + case UserNotifyServiceListUserTelegramChatsProcedure: + userNotifyServiceListUserTelegramChatsHandler.ServeHTTP(w, r) + case UserNotifyServiceUnlinkUserTelegramChatProcedure: + userNotifyServiceUnlinkUserTelegramChatHandler.ServeHTTP(w, r) + case UserNotifyServiceSetUserTelegramChatMutedProcedure: + userNotifyServiceSetUserTelegramChatMutedHandler.ServeHTTP(w, r) + case UserNotifyServiceSetUserTelegramChatLimitProcedure: + userNotifyServiceSetUserTelegramChatLimitHandler.ServeHTTP(w, r) + default: + http.NotFound(w, r) + } + }) +} + +// UnimplementedUserNotifyServiceHandler returns CodeUnimplemented from all methods. +type UnimplementedUserNotifyServiceHandler struct{} + +func (UnimplementedUserNotifyServiceHandler) GetUserBot(context.Context, *connect.Request[v1.Empty]) (*connect.Response[v1.UserBot], error) { + return nil, connect.NewError(connect.CodeUnimplemented, errors.New("mistgate.usernotify.v1.UserNotifyService.GetUserBot is not implemented")) +} + +func (UnimplementedUserNotifyServiceHandler) SetUserBot(context.Context, *connect.Request[v1.SetUserBotRequest]) (*connect.Response[v1.SetUserBotResponse], error) { + return nil, connect.NewError(connect.CodeUnimplemented, errors.New("mistgate.usernotify.v1.UserNotifyService.SetUserBot is not implemented")) +} + +func (UnimplementedUserNotifyServiceHandler) ClearUserBot(context.Context, *connect.Request[v1.Empty]) (*connect.Response[v1.SetUserBotResponse], error) { + return nil, connect.NewError(connect.CodeUnimplemented, errors.New("mistgate.usernotify.v1.UserNotifyService.ClearUserBot is not implemented")) +} + +func (UnimplementedUserNotifyServiceHandler) BeginUserTelegramLink(context.Context, *connect.Request[v1.UserRef]) (*connect.Response[v1.UserTelegramLink], error) { + return nil, connect.NewError(connect.CodeUnimplemented, errors.New("mistgate.usernotify.v1.UserNotifyService.BeginUserTelegramLink is not implemented")) +} + +func (UnimplementedUserNotifyServiceHandler) CancelUserTelegramLink(context.Context, *connect.Request[v1.UserRef]) (*connect.Response[v1.Empty], error) { + return nil, connect.NewError(connect.CodeUnimplemented, errors.New("mistgate.usernotify.v1.UserNotifyService.CancelUserTelegramLink is not implemented")) +} + +func (UnimplementedUserNotifyServiceHandler) ListUserTelegramChats(context.Context, *connect.Request[v1.UserRef]) (*connect.Response[v1.ListUserTelegramChatsResponse], error) { + return nil, connect.NewError(connect.CodeUnimplemented, errors.New("mistgate.usernotify.v1.UserNotifyService.ListUserTelegramChats is not implemented")) +} + +func (UnimplementedUserNotifyServiceHandler) UnlinkUserTelegramChat(context.Context, *connect.Request[v1.ChatRef]) (*connect.Response[v1.Empty], error) { + return nil, connect.NewError(connect.CodeUnimplemented, errors.New("mistgate.usernotify.v1.UserNotifyService.UnlinkUserTelegramChat is not implemented")) +} + +func (UnimplementedUserNotifyServiceHandler) SetUserTelegramChatMuted(context.Context, *connect.Request[v1.SetChatMutedRequest]) (*connect.Response[v1.Empty], error) { + return nil, connect.NewError(connect.CodeUnimplemented, errors.New("mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatMuted is not implemented")) +} + +func (UnimplementedUserNotifyServiceHandler) SetUserTelegramChatLimit(context.Context, *connect.Request[v1.SetChatLimitRequest]) (*connect.Response[v1.Empty], error) { + return nil, connect.NewError(connect.CodeUnimplemented, errors.New("mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatLimit is not implemented")) +} diff --git a/internal/panel/app/core_stars_test.go b/internal/panel/app/core_stars_test.go index e4c2fd48..784227a6 100644 --- a/internal/panel/app/core_stars_test.go +++ b/internal/panel/app/core_stars_test.go @@ -13,6 +13,7 @@ import ( "github.com/mistgate/mistgate/internal/panel/auth" "github.com/mistgate/mistgate/internal/panel/proposal/proposalrpc" "github.com/mistgate/mistgate/internal/panel/store" + "github.com/mistgate/mistgate/internal/panel/telegram/usernotifyrpc" "github.com/mistgate/mistgate/internal/panel/update" "github.com/mistgate/mistgate/internal/panel/vault" ) @@ -60,6 +61,7 @@ func TestRepoStarsBackgroundJobIsVPSOnly(t *testing.T) { DataDir: t.TempDir(), MasterKey: key, AfterResponse: func(work func()) { work() }, ProposalAPI: proposalrpc.Handler, + UserNotifyAPI: usernotifyrpc.Handler, } if tc.remote != nil { cfg.Remote = tc.remote diff --git a/internal/panel/app/edge_tick.go b/internal/panel/app/edge_tick.go index 7c12aad8..56350f1f 100644 --- a/internal/panel/app/edge_tick.go +++ b/internal/panel/app/edge_tick.go @@ -28,7 +28,7 @@ var edgeTickJobs = map[string]string{ "cheburcheck": "one due cheburcheck source and node per tick; off means no site request", "bsbord": "one previewed, capped mobile reachability request when a round is due; off means no site request", "provision": "wakes the Provisioner every tick while an install is queued, running or being cancelled", - "telegram": "polls pending chat codes, checks the release and agent watcher every fifth tick, and delivers queued messages", + "telegram": "polls pending chat codes (the admins' bot, and the bot of the people while a link code of a person is waiting), checks the release and agent watcher every fifth tick, and delivers queued messages", "updates": "advances the edge node rollout and scheduled update state machines", "proposals": "carries out the panel's accepted proposals (one read while none applies; the round lease is taken only when one does)", } @@ -156,9 +156,11 @@ func (p *Panel) EdgeTick(ctx context.Context, now time.Time) error { }) } if p.Telegram != nil { - // The link poll is last: it may long-poll for up to 25 s, and it must not delay what is already queued. - runFor("telegram link poll", 40*time.Second, func(ctx context.Context) error { - return p.Telegram.PollPendingLinkCode(ctx) + // The link polls are last: each may long-poll for up to 25 s, and they must not delay what is already queued. One read says + // whether the owner's bot (an admin's code) or the bot of the people (a person's code) has anything to hear; with nothing + // waiting neither calls Telegram. + runFor("telegram link poll", 90*time.Second, func(ctx context.Context) error { + return p.Telegram.PollPendingLinkCodes(ctx) }) } return errors.Join(errs...) diff --git a/internal/panel/app/edge_tick_test.go b/internal/panel/app/edge_tick_test.go index 300859fd..1ebaef88 100644 --- a/internal/panel/app/edge_tick_test.go +++ b/internal/panel/app/edge_tick_test.go @@ -24,6 +24,7 @@ import ( "github.com/mistgate/mistgate/internal/panel/proposal/proposalrpc" "github.com/mistgate/mistgate/internal/panel/store" "github.com/mistgate/mistgate/internal/panel/telegram" + "github.com/mistgate/mistgate/internal/panel/telegram/usernotifyrpc" "github.com/mistgate/mistgate/internal/panel/vault" "github.com/mistgate/mistgate/internal/release" ) @@ -125,6 +126,7 @@ func buildPanelOnWithVault(t *testing.T, st *store.Store, remote fleet.Remote, t DataDir: t.TempDir(), MasterKey: key, Remote: remote, AfterResponse: func(work func()) { work() }, ProposalAPI: proposalrpc.Handler, + UserNotifyAPI: usernotifyrpc.Handler, } if tweak != nil { tweak(&cfg) diff --git a/internal/panel/app/panel.go b/internal/panel/app/panel.go index fb78add3..262d0d90 100644 --- a/internal/panel/app/panel.go +++ b/internal/panel/app/panel.go @@ -168,6 +168,10 @@ type Config struct { // take it from here, so that the Workers that do not (link, public) never link it with its generated code. kick wakes the // executor after an accept. Build and BuildAdmin refuse a Config without it, so that no role can forget it. ProposalAPI func(st *store.Store, a *auth.Service, kick func()) (string, http.Handler) + // UserNotifyAPI is the UserNotifyService of the admin API (internal/panel/telegram/usernotifyrpc.Handler): the bot of the people and a + // person's Telegram chats. The roles that serve it take it from here, so that the Workers that do not (public, link, jobs, + // provision) never link its generated code and descriptors. Build and BuildAdmin refuse a Config without it. + UserNotifyAPI func(tg *telegram.Service) (string, http.Handler) } // Panel is the assembled panel: its public HTTP handler, VPS listener adapter and services. diff --git a/internal/panel/app/roles.go b/internal/panel/app/roles.go index 2dc74b1b..98f72cb2 100644 --- a/internal/panel/app/roles.go +++ b/internal/panel/app/roles.go @@ -36,6 +36,20 @@ import ( // a service that is silently absent from one edition. var errNoProposalAPI = errors.New("panel app: Config.ProposalAPI is required (proposalrpc.Handler)") +// errNoUserNotifyAPI is the same for Config.UserNotifyAPI. +var errNoUserNotifyAPI = errors.New("panel app: Config.UserNotifyAPI is required (usernotifyrpc.Handler)") + +// checkAPIs refuses a Config that lacks a service the roles with the admin API must serve. +func checkAPIs(c Config) error { + if c.ProposalAPI == nil { + return errNoProposalAPI + } + if c.UserNotifyAPI == nil { + return errNoUserNotifyAPI + } + return nil +} + // addProposals mounts the ProposalService behind the session. The executor wakes on an accept where there is one (Build); the // admin Worker has none, and the next cron tick of the jobs Worker takes the accepted proposal up. func (k *core) addProposals(cfg *httpserver.Config) { @@ -77,8 +91,8 @@ func surfaceOf(cfg httpserver.Config) Surface { // Build wires services into the HTTP handler shared by the VPS and edge editions: every role in one process. func Build(c Config) (*Panel, error) { - if c.ProposalAPI == nil { - return nil, errNoProposalAPI + if err := checkAPIs(c); err != nil { + return nil, err } k, err := wireCore(c) if err != nil { @@ -121,8 +135,8 @@ func Build(c Config) (*Panel, error) { // BuildAdmin is the admin Worker: Build without the public mounts, the agent link and the agent endpoint, which other // Workers serve (their prefixes are only checked), and with the install calls answered by the marker for the Provisioner. func BuildAdmin(c Config) (*Panel, error) { - if c.ProposalAPI == nil { - return nil, errNoProposalAPI + if err := checkAPIs(c); err != nil { + return nil, err } k, err := wireCore(c) if err != nil { @@ -301,6 +315,8 @@ func (k *core) adminConfig(parts subParts, prov *nodeprovision.Service, bkp *bac k.addDecoySite(&cfg) k.addWarpReach(&cfg) k.addProposals(&cfg) + path, handler := k.c.UserNotifyAPI(k.tg) + cfg.AdminHandlers = append(cfg.AdminHandlers, httpserver.AdminHandler{Path: path, Handler: handler}) return cfg } diff --git a/internal/panel/app/roles_test.go b/internal/panel/app/roles_test.go index a34e6bb4..6348cd24 100644 --- a/internal/panel/app/roles_test.go +++ b/internal/panel/app/roles_test.go @@ -26,6 +26,7 @@ import ( "github.com/mistgate/mistgate/internal/panel/proposal/proposalrpc" nodeprovision "github.com/mistgate/mistgate/internal/panel/provision" "github.com/mistgate/mistgate/internal/panel/store" + "github.com/mistgate/mistgate/internal/panel/telegram/usernotifyrpc" "github.com/mistgate/mistgate/internal/panel/vault" ) @@ -66,6 +67,7 @@ func roleConfig(t *testing.T, remote *edgeTickRemote) Config { AfterResponse: func(work func()) { work() }, SSHClient: nodeprovision.NewClient(), ProposalAPI: proposalrpc.Handler, + UserNotifyAPI: usernotifyrpc.Handler, } } @@ -158,6 +160,17 @@ func TestEdgeRolesCoverBuild(t *testing.T) { t.Errorf("role %s serves the ProposalService", name) } } + // The UserNotifyService is plugged in the same way (Config.UserNotifyAPI). + for name, p := range map[string]*Panel{"Build": r.whole, "admin": r.admin} { + if !slices.Contains(p.Surface.AdminAPI, "/mistgate.usernotify.v1.UserNotifyService/") { + t.Errorf("%s does not serve the UserNotifyService: %v", name, p.Surface.AdminAPI) + } + } + for name, p := range roles { + if name != "admin" && slices.Contains(p.Surface.AdminAPI, "/mistgate.usernotify.v1.UserNotifyService/") { + t.Errorf("role %s serves the UserNotifyService", name) + } + } if got := union(api, r.provision); len(got) != 1 || got[0] != "/mistgate.admin.v1.ProvisioningService/" { t.Errorf("the Provisioner serves %v, want the ProvisioningService alone", got) } @@ -266,9 +279,9 @@ func TestEdgeSubscriptionIsServedByThePublicRoleAlone(t *testing.T) { } } -// Build and BuildAdmin refuse a Config without the ProposalService (Config.ProposalAPI), so that no role can be built that -// lacks it; the roles that serve no admin API do not need it. -func TestProposalAPIIsRequired(t *testing.T) { +// Build and BuildAdmin refuse a Config without the ProposalService (Config.ProposalAPI) or the UserNotifyService +// (Config.UserNotifyAPI), so that no role can be built that lacks one; the roles that serve no admin API do not need it. +func TestAdminAPIsAreRequired(t *testing.T) { c := roleConfig(t, &edgeTickRemote{}) c.ProposalAPI = nil for name, build := range map[string]func(Config) (*Panel, error){"Build": Build, "BuildAdmin": BuildAdmin} { @@ -281,6 +294,14 @@ func TestProposalAPIIsRequired(t *testing.T) { t.Errorf("%s needs no ProposalAPI: %v", name, err) } } + c = roleConfig(t, &edgeTickRemote{}) + c.UserNotifyAPI = nil + for name, build := range map[string]func(Config) (*Panel, error){"Build": Build, "BuildAdmin": BuildAdmin} { + if _, err := build(c); err == nil || !strings.Contains(err.Error(), "UserNotifyAPI") { + t.Errorf("%s without UserNotifyAPI: %v", name, err) + } + } + c = roleConfig(t, &edgeTickRemote{}) public := c public.Auth = nil if _, err := BuildPublic(public); err != nil { diff --git a/internal/panel/auth/hardening_test.go b/internal/panel/auth/hardening_test.go index e121bb95..623977de 100644 --- a/internal/panel/auth/hardening_test.go +++ b/internal/panel/auth/hardening_test.go @@ -416,9 +416,10 @@ func TestEveryProcedureHasAPolicy(t *testing.T) { // policy_ownprobe.go), mistgate.tasks.v1 (TasksService, policy_tasks.go), mistgate.trusttunnel.v1 (TrustTunnelService, // policy_trusttunnel.go), mistgate.decoysite.v1 (DecoySiteService, policy_decoysite.go), mistgate.warpreach.v1 // (WarpReachService, policy_warpreach.go), and mistgate.subhost.v1 (SubscriptionHostService, policy_subhost.go) are - // VPS-only. mistgate.proposal.v1 (ProposalService, policy_proposal.go) is plugged in by the roles serving the admin API. + // VPS-only. mistgate.proposal.v1 (ProposalService, policy_proposal.go) and mistgate.usernotify.v1 (UserNotifyService, + // policy_usernotify.go) are plugged in by the roles serving the admin API. // Their procedures need a level too. - for _, pkg := range []protoreflect.FullName{"mistgate.admin.v1", "mistgate.probe.v1", "mistgate.ops.v1", "mistgate.tasks.v1", "mistgate.ownprobe.v1", "mistgate.trusttunnel.v1", "mistgate.decoysite.v1", "mistgate.warpreach.v1", "mistgate.subhost.v1", "mistgate.proposal.v1"} { + for _, pkg := range []protoreflect.FullName{"mistgate.admin.v1", "mistgate.probe.v1", "mistgate.ops.v1", "mistgate.tasks.v1", "mistgate.ownprobe.v1", "mistgate.trusttunnel.v1", "mistgate.decoysite.v1", "mistgate.warpreach.v1", "mistgate.subhost.v1", "mistgate.proposal.v1", "mistgate.usernotify.v1"} { protoregistry.GlobalFiles.RangeFilesByPackage(pkg, func(fd protoreflect.FileDescriptor) bool { for i := 0; i < fd.Services().Len(); i++ { svc := fd.Services().Get(i) diff --git a/internal/panel/auth/policy.go b/internal/panel/auth/policy.go index df414457..62b5428b 100644 --- a/internal/panel/auth/policy.go +++ b/internal/panel/auth/policy.go @@ -348,6 +348,17 @@ var procedureLevels = map[string]level{ adminv1connect.TelegramServiceUnlinkTelegramProcedure: levelRead, adminv1connect.TelegramServiceSetTelegramAlertsProcedure: levelRead, adminv1connect.TelegramServiceSendTelegramTestProcedure: levelRead, + // The bot of the people (notifications to users): the bot and the chat limit are the owner's, setting or clearing the bot also + // needs a step-up; handing out a link and managing a person's chats is what a helper does for a user; reading is for everybody. + UserNotifyGetBotProcedure: levelRead, + UserNotifySetBotProcedure: levelOwner, + UserNotifyClearBotProcedure: levelOwner, + UserNotifyBeginLinkProcedure: levelWrite, + UserNotifyCancelLinkProcedure: levelWrite, + UserNotifyListChatsProcedure: levelRead, + UserNotifyUnlinkChatProcedure: levelWrite, + UserNotifySetChatMutedProcedure: levelWrite, + UserNotifySetChatLimitProcedure: levelOwner, adminv1connect.UserServiceListUsersProcedure: levelRead, adminv1connect.UserServiceGetUserProcedure: levelRead, diff --git a/internal/panel/auth/policy_tokens.go b/internal/panel/auth/policy_tokens.go index 2f7f790a..7964c205 100644 --- a/internal/panel/auth/policy_tokens.go +++ b/internal/panel/auth/policy_tokens.go @@ -218,6 +218,8 @@ var stepUpProcedures = map[string]bool{ adminv1connect.BackupServiceDeleteKeptDataProcedure: true, adminv1connect.TelegramServiceSetTelegramBotProcedure: true, adminv1connect.TelegramServiceBeginTelegramLinkProcedure: true, + UserNotifySetBotProcedure: true, + UserNotifyClearBotProcedure: true, adminv1connect.GlobalpingServiceUpdateGlobalpingProcedure: true, adminv1connect.GlobalpingServiceDisconnectGlobalpingProcedure: true, adminv1connect.CheburcheckServiceUpdateCheburcheckProcedure: true, diff --git a/internal/panel/auth/policy_usernotify.go b/internal/panel/auth/policy_usernotify.go new file mode 100644 index 00000000..ddb01450 --- /dev/null +++ b/internal/panel/auth/policy_usernotify.go @@ -0,0 +1,21 @@ +package auth + +// The UserNotifyService (proto/mistgate/usernotify/v1: the bot of the people and a person's Telegram chats) is a package of its +// own, plugged in by the roles that serve the admin API (app.Config.UserNotifyAPI). Its procedures are named here by path, not by +// the generated constants, for the reason policy_proposal.go gives: auth is linked into every Worker, and the generated package +// must be linked only where the service is served. A test compares these literals with the generated names +// (policy_usernotify_test.go). The levels and step-ups are lines of the literal maps in policy.go and policy_tokens.go. +// +// The policy: the bot and the chat limit are the owner's (setting or clearing the bot also needs a step-up); handing out a link and +// managing a person's chats is what a helper does for a user; reading is for every admin. None is open to API tokens or MCP. +const ( + UserNotifyGetBotProcedure = "/mistgate.usernotify.v1.UserNotifyService/GetUserBot" + UserNotifySetBotProcedure = "/mistgate.usernotify.v1.UserNotifyService/SetUserBot" + UserNotifyClearBotProcedure = "/mistgate.usernotify.v1.UserNotifyService/ClearUserBot" + UserNotifyBeginLinkProcedure = "/mistgate.usernotify.v1.UserNotifyService/BeginUserTelegramLink" + UserNotifyCancelLinkProcedure = "/mistgate.usernotify.v1.UserNotifyService/CancelUserTelegramLink" + UserNotifyListChatsProcedure = "/mistgate.usernotify.v1.UserNotifyService/ListUserTelegramChats" + UserNotifyUnlinkChatProcedure = "/mistgate.usernotify.v1.UserNotifyService/UnlinkUserTelegramChat" + UserNotifySetChatMutedProcedure = "/mistgate.usernotify.v1.UserNotifyService/SetUserTelegramChatMuted" + UserNotifySetChatLimitProcedure = "/mistgate.usernotify.v1.UserNotifyService/SetUserTelegramChatLimit" +) diff --git a/internal/panel/auth/policy_usernotify_test.go b/internal/panel/auth/policy_usernotify_test.go new file mode 100644 index 00000000..b82fd32d --- /dev/null +++ b/internal/panel/auth/policy_usernotify_test.go @@ -0,0 +1,64 @@ +package auth + +import ( + "testing" + + "github.com/mistgate/mistgate/gen/mistgate/usernotify/v1/usernotifyv1connect" + "github.com/mistgate/mistgate/internal/panel/store" +) + +// policy_usernotify.go names the procedures by literal paths so that auth does not import the generated package; the literals must +// be the generated names. +func TestUserNotifyPolicyLiteralsAreTheGeneratedNames(t *testing.T) { + for literal, generated := range map[string]string{ + UserNotifyGetBotProcedure: usernotifyv1connect.UserNotifyServiceGetUserBotProcedure, + UserNotifySetBotProcedure: usernotifyv1connect.UserNotifyServiceSetUserBotProcedure, + UserNotifyClearBotProcedure: usernotifyv1connect.UserNotifyServiceClearUserBotProcedure, + UserNotifyBeginLinkProcedure: usernotifyv1connect.UserNotifyServiceBeginUserTelegramLinkProcedure, + UserNotifyCancelLinkProcedure: usernotifyv1connect.UserNotifyServiceCancelUserTelegramLinkProcedure, + UserNotifyListChatsProcedure: usernotifyv1connect.UserNotifyServiceListUserTelegramChatsProcedure, + UserNotifyUnlinkChatProcedure: usernotifyv1connect.UserNotifyServiceUnlinkUserTelegramChatProcedure, + UserNotifySetChatMutedProcedure: usernotifyv1connect.UserNotifyServiceSetUserTelegramChatMutedProcedure, + UserNotifySetChatLimitProcedure: usernotifyv1connect.UserNotifyServiceSetUserTelegramChatLimitProcedure, + } { + if literal != generated { + t.Errorf("policy names %q, the generated procedure is %q", literal, generated) + } + } +} + +// The bot and the chat limit are the owner's (the bot also needs a step-up); a helper hands out links and manages a person's chats; +// reading is for every admin. No token or MCP agent may call any of it. +func TestUserNotifyServicePolicy(t *testing.T) { + for _, tc := range []struct { + name string + path string + owner, helper, readon bool + stepUp bool + }{ + {"GetUserBot", UserNotifyGetBotProcedure, true, true, true, false}, + {"SetUserBot", UserNotifySetBotProcedure, true, false, false, true}, + {"ClearUserBot", UserNotifyClearBotProcedure, true, false, false, true}, + {"BeginUserTelegramLink", UserNotifyBeginLinkProcedure, true, true, false, false}, + {"CancelUserTelegramLink", UserNotifyCancelLinkProcedure, true, true, false, false}, + {"ListUserTelegramChats", UserNotifyListChatsProcedure, true, true, true, false}, + {"UnlinkUserTelegramChat", UserNotifyUnlinkChatProcedure, true, true, false, false}, + {"SetUserTelegramChatMuted", UserNotifySetChatMutedProcedure, true, true, false, false}, + {"SetUserTelegramChatLimit", UserNotifySetChatLimitProcedure, true, false, false, false}, + } { + if _, listed := procedureLevels[tc.path]; !listed { + t.Errorf("%s has no explicit level", tc.name) + } + for role, want := range map[string]bool{store.RoleOwner: tc.owner, store.RoleHelper: tc.helper, store.RoleReadonly: tc.readon} { + if got := roleAllows(role, levelOf(tc.path)); got != want { + t.Errorf("%s as %s: allowed = %v, want %v", tc.name, role, got, want) + } + } + if got := NeedsStepUp(tc.path); got != tc.stepUp { + t.Errorf("%s needs step-up = %v, want %v", tc.name, got, tc.stepUp) + } + if _, allowed := TokenAccess(tc.path); allowed { + t.Errorf("%s must stay closed to API tokens and MCP", tc.name) + } + } +} diff --git a/internal/panel/backup/validate_vault_golden_test.go b/internal/panel/backup/validate_vault_golden_test.go index b739fbe8..3564215f 100644 --- a/internal/panel/backup/validate_vault_golden_test.go +++ b/internal/panel/backup/validate_vault_golden_test.go @@ -20,6 +20,7 @@ import ( "os" "path/filepath" "strings" + "sync/atomic" "testing" "time" @@ -27,6 +28,8 @@ import ( "filippo.io/age" adminv1 "github.com/mistgate/mistgate/gen/mistgate/admin/v1" "github.com/mistgate/mistgate/gen/mistgate/admin/v1/adminv1connect" + usernotifyv1 "github.com/mistgate/mistgate/gen/mistgate/usernotify/v1" + "github.com/mistgate/mistgate/gen/mistgate/usernotify/v1/usernotifyv1connect" "github.com/mistgate/mistgate/internal/panel/app" "github.com/mistgate/mistgate/internal/panel/assistant" "github.com/mistgate/mistgate/internal/panel/auth" @@ -39,6 +42,7 @@ import ( "github.com/mistgate/mistgate/internal/panel/store" "github.com/mistgate/mistgate/internal/panel/tasks" "github.com/mistgate/mistgate/internal/panel/telegram" + "github.com/mistgate/mistgate/internal/panel/telegram/usernotifyrpc" "github.com/mistgate/mistgate/internal/panel/vault" ) @@ -72,6 +76,7 @@ func TestRestoreValidatesProductionSealedValues(t *testing.T) { RPOrigins: []string{"https://example.com"}, AgentSNI: "agent.example.com", SubPrefix: "/sub/", }, DataDir: dataDir, MasterKey: key, AfterResponse: func(work func()) { work() }, ProposalAPI: proposalrpc.Handler, + UserNotifyAPI: usernotifyrpc.Handler, }) if err != nil { t.Fatal(err) @@ -357,7 +362,27 @@ func TestRestoreValidatesProductionSealedValues(t *testing.T) { } })) t.Cleanup(tgAPI.Close) - tgService, err := telegram.New(telegram.Config{Store: st, Vault: vlt, StepUp: noStepUp, APIBase: tgAPI.URL, HTTPClient: tgAPI.Client()}) + // The bot of the people is another bot; a person links a chat with a one-time code that this fake Telegram hands back as the + // "/start " message the person would send. + var peopleCode atomic.Value + peopleCode.Store("") + peopleAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case strings.HasSuffix(r.URL.Path, "/getMe"): + _, _ = io.WriteString(w, "{\"ok\":true,\"result\":{\"id\":987654321,\"is_bot\":true,\"username\":\"golden_people_bot\"}}") + case strings.HasSuffix(r.URL.Path, "/deleteWebhook"): + _, _ = io.WriteString(w, "{\"ok\":true,\"result\":true}") + case strings.HasSuffix(r.URL.Path, "/getUpdates"): + _, _ = io.WriteString(w, "{\"ok\":true,\"result\":[{\"update_id\":1,\"message\":{\"chat\":{\"id\":4242,\"type\":\"private\"},\"text\":\"/start "+peopleCode.Load().(string)+"\"}}]}") + case strings.HasSuffix(r.URL.Path, "/sendMessage"): + _, _ = io.WriteString(w, "{\"ok\":true,\"result\":{\"message_id\":1}}") + default: + http.NotFound(w, r) + } + })) + t.Cleanup(peopleAPI.Close) + tgService, err := telegram.New(telegram.Config{Store: st, Vault: vlt, StepUp: noStepUp, APIBase: tgAPI.URL, UserAPIBase: peopleAPI.URL, HTTPClient: tgAPI.Client()}) if err != nil { t.Fatal(err) } @@ -367,6 +392,20 @@ func TestRestoreValidatesProductionSealedValues(t *testing.T) { if _, err := tgClient.SetTelegramBot(ctx, connect.NewRequest(&adminv1.SetTelegramBotRequest{Token: tgToken})); err != nil { t.Fatal(err) } + peoplePath, peopleHandler := usernotifyrpc.Handler(tgService) + peopleServer := serve(peoplePath, peopleHandler) + peopleClient := usernotifyv1connect.NewUserNotifyServiceClient(peopleServer.Client(), peopleServer.URL) + if _, err := peopleClient.SetUserBot(ctx, connect.NewRequest(&usernotifyv1.SetUserBotRequest{Token: "987654321:" + strings.Repeat("B", 35)})); err != nil { + t.Fatal(err) + } + link, err := peopleClient.BeginUserTelegramLink(ctx, connect.NewRequest(&usernotifyv1.UserRef{UserId: user.Msg.User.Id})) + if err != nil { + t.Fatal(err) + } + peopleCode.Store(link.Msg.DeepLink[strings.Index(link.Msg.DeepLink, "=")+1:]) + if err := tgService.PollPendingUserLink(ctx); err != nil { + t.Fatal(err) + } backupService, err := backup.New(backup.Config{Store: st, Vault: vlt, DataDir: dataDir, MasterKey: key, StepUp: noStepUp}) if err != nil { @@ -435,37 +474,39 @@ func TestRestoreValidatesProductionSealedValues(t *testing.T) { // Fail with the registry label if any expected production row was not created. for name, query := range map[string]string{ - "admin_password TOTP": "SELECT count(*) FROM admin_password WHERE length(totp_secret) > 0", - "panel CA": "SELECT count(*) FROM panel_ca WHERE length(key_enc) > 0", - "profile secrets": "SELECT count(*) FROM profile WHERE secrets_enc IS NOT NULL AND length(secrets_enc) > 0", - "user subscription token": "SELECT count(*) FROM user WHERE length(sub_token_enc) > 0", - "subscription link device": "SELECT count(*) FROM device WHERE kind = 'link'", - "AWG device": "SELECT count(*) FROM device WHERE kind = 'key'", - "device credentials": "SELECT count(*) FROM device_credential WHERE length(secret_enc) > 0", - "AWG inbound plugin state": "SELECT count(*) FROM inbound WHERE length(plugin_state_enc) > 0", - "retained AWG key": "SELECT count(*) FROM awg_retained_key WHERE length(state_enc) > 0", - "health probe credential": "SELECT count(*) FROM health_probe_cred WHERE length(secret_enc) > 0", - "node provisioning credentials": "SELECT count(*) FROM node_provision_job WHERE length(secret) > 0", - "node SSH password": "SELECT count(*) FROM node_server_access WHERE length(password) > 0", - "pending node SSH password": "SELECT count(*) FROM node_server_access WHERE pending_password IS NOT NULL AND length(pending_password) > 0", - "MCP plan owner secret": "SELECT count(*) FROM mcp_plan WHERE owner_secret IS NOT NULL AND length(owner_secret) > 0", - "Telegram bot token": "SELECT count(*) FROM telegram_bot WHERE length(token) > 0", - "pending auth ceremony TOTP": "SELECT count(*) FROM auth_ceremony WHERE length(totp_enc) > 0", - "panel SSH key": "SELECT count(*) FROM panel_ssh_key WHERE length(private_key) > 0", - "panel backup secret": "SELECT count(*) FROM panel_backup_settings WHERE length(secret_access_key) > 0", - "assistant provider key": "SELECT count(*) FROM assistant_provider WHERE length(key_enc) > 0", - "assistant conversation title": "SELECT count(*) FROM assistant_conversation WHERE length(title_enc) > 0", - "assistant conversation summary": "SELECT count(*) FROM assistant_conversation WHERE length(summary_enc) > 0", - "assistant message transcript": "SELECT count(*) FROM assistant_message WHERE length(body_enc) > 0", - "assistant plan confirmation": "SELECT count(*) FROM assistant_plan WHERE length(confirm_enc) > 0", - "assistant plan card": "SELECT count(*) FROM assistant_plan WHERE length(card_enc) > 0", - "assistant memory note": "SELECT count(*) FROM assistant_memory WHERE length(text_enc) > 0", - "scheduled task prompt": "SELECT count(*) FROM scheduled_task WHERE length(prompt_enc) > 0", - "assistant follow-up note": "SELECT count(*) FROM assistant_follow_up WHERE length(note_enc) > 0", - "Turnstile secret setting": "SELECT count(*) FROM setting WHERE k = 'turnstile_secret' AND length(v) > 0", - "Globalping token setting": "SELECT count(*) FROM setting WHERE k = 'globalping.token' AND length(v) > 0", - "Cheburcheck token setting": "SELECT count(*) FROM setting WHERE k = 'cheburcheck.token' AND length(v) > 0", - "Bsbord key setting": "SELECT count(*) FROM setting WHERE k = 'bsbord.key' AND length(v) > 0", + "admin_password TOTP": "SELECT count(*) FROM admin_password WHERE length(totp_secret) > 0", + "panel CA": "SELECT count(*) FROM panel_ca WHERE length(key_enc) > 0", + "profile secrets": "SELECT count(*) FROM profile WHERE secrets_enc IS NOT NULL AND length(secrets_enc) > 0", + "user subscription token": "SELECT count(*) FROM user WHERE length(sub_token_enc) > 0", + "subscription link device": "SELECT count(*) FROM device WHERE kind = 'link'", + "AWG device": "SELECT count(*) FROM device WHERE kind = 'key'", + "device credentials": "SELECT count(*) FROM device_credential WHERE length(secret_enc) > 0", + "AWG inbound plugin state": "SELECT count(*) FROM inbound WHERE length(plugin_state_enc) > 0", + "retained AWG key": "SELECT count(*) FROM awg_retained_key WHERE length(state_enc) > 0", + "health probe credential": "SELECT count(*) FROM health_probe_cred WHERE length(secret_enc) > 0", + "node provisioning credentials": "SELECT count(*) FROM node_provision_job WHERE length(secret) > 0", + "node SSH password": "SELECT count(*) FROM node_server_access WHERE length(password) > 0", + "pending node SSH password": "SELECT count(*) FROM node_server_access WHERE pending_password IS NOT NULL AND length(pending_password) > 0", + "MCP plan owner secret": "SELECT count(*) FROM mcp_plan WHERE owner_secret IS NOT NULL AND length(owner_secret) > 0", + "Telegram bot token": "SELECT count(*) FROM telegram_bot WHERE length(token) > 0", + "Telegram bot token of the people": "SELECT count(*) FROM user_telegram_bot WHERE length(token) > 0", + "Telegram chat of a person": "SELECT count(*) FROM user_telegram_chat WHERE length(chat_enc) > 0", + "pending auth ceremony TOTP": "SELECT count(*) FROM auth_ceremony WHERE length(totp_enc) > 0", + "panel SSH key": "SELECT count(*) FROM panel_ssh_key WHERE length(private_key) > 0", + "panel backup secret": "SELECT count(*) FROM panel_backup_settings WHERE length(secret_access_key) > 0", + "assistant provider key": "SELECT count(*) FROM assistant_provider WHERE length(key_enc) > 0", + "assistant conversation title": "SELECT count(*) FROM assistant_conversation WHERE length(title_enc) > 0", + "assistant conversation summary": "SELECT count(*) FROM assistant_conversation WHERE length(summary_enc) > 0", + "assistant message transcript": "SELECT count(*) FROM assistant_message WHERE length(body_enc) > 0", + "assistant plan confirmation": "SELECT count(*) FROM assistant_plan WHERE length(confirm_enc) > 0", + "assistant plan card": "SELECT count(*) FROM assistant_plan WHERE length(card_enc) > 0", + "assistant memory note": "SELECT count(*) FROM assistant_memory WHERE length(text_enc) > 0", + "scheduled task prompt": "SELECT count(*) FROM scheduled_task WHERE length(prompt_enc) > 0", + "assistant follow-up note": "SELECT count(*) FROM assistant_follow_up WHERE length(note_enc) > 0", + "Turnstile secret setting": "SELECT count(*) FROM setting WHERE k = 'turnstile_secret' AND length(v) > 0", + "Globalping token setting": "SELECT count(*) FROM setting WHERE k = 'globalping.token' AND length(v) > 0", + "Cheburcheck token setting": "SELECT count(*) FROM setting WHERE k = 'cheburcheck.token' AND length(v) > 0", + "Bsbord key setting": "SELECT count(*) FROM setting WHERE k = 'bsbord.key' AND length(v) > 0", } { var count int if err := st.R.QueryRowContext(ctx, query).Scan(&count); err != nil { diff --git a/internal/panel/store/user_telegram.go b/internal/panel/store/user_telegram.go index e6c12b72..ed02ef14 100644 --- a/internal/panel/store/user_telegram.go +++ b/internal/panel/store/user_telegram.go @@ -259,6 +259,14 @@ func (s *Store) HasPendingUserTelegramCode(ctx context.Context, now time.Time) ( return err == nil, err } +// PendingTelegramLinkCodes says in one read whether an admin's link code waits (the owner's bot) and whether a person's does (the +// bot of the people): what the edge tick asks before it long-polls either bot. +func (s *Store) PendingTelegramLinkCodes(ctx context.Context, now time.Time) (admin, people bool, err error) { + err = s.R.QueryRowContext(ctx, `SELECT EXISTS (SELECT 1 FROM telegram_link_code WHERE expires_at > ?), + EXISTS (SELECT 1 FROM user_telegram_code WHERE expires_at > ?)`, unix(now), unix(now)).Scan(&admin, &people) + return admin, people, err +} + // TakeUserTelegramCode atomically consumes a code before it expires and returns its person; ErrNotFound when the code is // unknown, spent or expired. DELETE ... RETURNING makes concurrent polls single use. func (s *Store) TakeUserTelegramCode(ctx context.Context, hash string, now time.Time) (string, error) { @@ -269,3 +277,32 @@ func (s *Store) TakeUserTelegramCode(ctx context.Context, hash string, now time. } return user, err } + +// UserTelegramStats counts the people with a chat, the chats, and says when the last message reached any of them (zero: never). +func (s *Store) UserTelegramStats(ctx context.Context) (people, chats int, lastSent time.Time, err error) { + var last int64 + err = s.R.QueryRowContext(ctx, `SELECT count(DISTINCT user_id), count(*), COALESCE(max(last_sent_at), 0) FROM user_telegram_chat`).Scan(&people, &chats, &last) + return people, chats, unixTime(last), err +} + +// UserExists says whether there is a person with this id. +func (s *Store) UserExists(ctx context.Context, user string) (bool, error) { + var ok bool + err := s.R.QueryRowContext(ctx, `SELECT EXISTS (SELECT 1 FROM user WHERE id = ?)`, user).Scan(&ok) + return ok, err +} + +// UserTelegramCodeExpiry is when the pending link code of a person runs out; ErrNotFound when there is none (or it has run out). +func (s *Store) UserTelegramCodeExpiry(ctx context.Context, user string, now time.Time) (time.Time, error) { + var exp int64 + err := s.R.QueryRowContext(ctx, `SELECT expires_at FROM user_telegram_code WHERE user_id = ? AND expires_at > ?`, user, unix(now)).Scan(&exp) + if errors.Is(err, sql.ErrNoRows) { + return time.Time{}, ErrNotFound + } + return fromUnix(exp), err +} + +// DeleteUserTelegramCode withdraws the pending link code of a person; it reports whether there was one. +func (s *Store) DeleteUserTelegramCode(ctx context.Context, user string) (bool, error) { + return s.deleteUserTelegramChat(ctx, `DELETE FROM user_telegram_code WHERE user_id = ?`, user) +} diff --git a/internal/panel/store/user_telegram_extra_test.go b/internal/panel/store/user_telegram_extra_test.go new file mode 100644 index 00000000..f39b7be8 --- /dev/null +++ b/internal/panel/store/user_telegram_extra_test.go @@ -0,0 +1,74 @@ +//go:build !js + +package store + +import ( + "context" + "errors" + "strings" + "testing" + "time" +) + +func TestUserTelegramStatsAndCodes(t *testing.T) { + ctx := context.Background() + s := openUserNotify(t, "usr_a", "usr_b") + if p, c, last, err := s.UserTelegramStats(ctx); err != nil || p != 0 || c != 0 || !last.IsZero() { + t.Fatalf("empty stats = %d %d %v %v", p, c, last, err) + } + if ok, _ := s.UserExists(ctx, "usr_a"); !ok { + t.Error("usr_a does not exist") + } + if ok, _ := s.UserExists(ctx, "usr_x"); ok { + t.Error("usr_x exists") + } + for i, u := range []string{"usr_a", "usr_a", "usr_b"} { + if err := s.LinkUserTelegramChat(ctx, u, []byte{byte(i)}, []byte("sealed"), "en", 3, userNotifyNow); err != nil { + t.Fatal(err) + } + } + chats, _ := s.UserTelegramChats(ctx, "usr_a") + if err := s.SetUserTelegramChatLastSent(ctx, "usr_a", chats[1].ID, userNotifyNow.Add(time.Hour)); err != nil { + t.Fatal(err) + } + if p, c, last, err := s.UserTelegramStats(ctx); err != nil || p != 2 || c != 3 || !last.Equal(userNotifyNow.Add(time.Hour)) { + t.Errorf("stats = %d %d %v %v", p, c, last, err) + } + + hash := strings.Repeat("a", 64) + if err := s.SetUserTelegramCode(ctx, hash, "usr_a", userNotifyNow.Add(time.Minute)); err != nil { + t.Fatal(err) + } + if exp, err := s.UserTelegramCodeExpiry(ctx, "usr_a", userNotifyNow); err != nil || !exp.Equal(userNotifyNow.Add(time.Minute)) { + t.Errorf("expiry = %v %v", exp, err) + } + if _, err := s.UserTelegramCodeExpiry(ctx, "usr_a", userNotifyNow.Add(time.Hour)); !errors.Is(err, ErrNotFound) { + t.Errorf("an expired code has an expiry: %v", err) + } + if _, err := s.UserTelegramCodeExpiry(ctx, "usr_b", userNotifyNow); !errors.Is(err, ErrNotFound) { + t.Errorf("a person with no code has an expiry: %v", err) + } + if ok, err := s.DeleteUserTelegramCode(ctx, "usr_a"); err != nil || !ok { + t.Errorf("delete = %v %v", ok, err) + } + if ok, err := s.DeleteUserTelegramCode(ctx, "usr_a"); err != nil || ok { + t.Errorf("second delete = %v %v", ok, err) + } +} + +func TestPendingTelegramLinkCodes(t *testing.T) { + ctx := context.Background() + s := openUserNotify(t, "usr_a") + if a, p, err := s.PendingTelegramLinkCodes(ctx, userNotifyNow); err != nil || a || p { + t.Fatalf("nothing waits: %v %v %v", a, p, err) + } + if err := s.SetUserTelegramCode(ctx, strings.Repeat("b", 64), "usr_a", userNotifyNow.Add(time.Minute)); err != nil { + t.Fatal(err) + } + if a, p, err := s.PendingTelegramLinkCodes(ctx, userNotifyNow); err != nil || a || !p { + t.Fatalf("a person's code waits: %v %v %v", a, p, err) + } + if a, p, err := s.PendingTelegramLinkCodes(ctx, userNotifyNow.Add(time.Hour)); err != nil || a || p { + t.Fatalf("it ran out: %v %v %v", a, p, err) + } +} diff --git a/internal/panel/telegram/client.go b/internal/panel/telegram/client.go index ea46f7a2..a27b9c9f 100644 --- a/internal/panel/telegram/client.go +++ b/internal/panel/telegram/client.go @@ -78,6 +78,11 @@ func (e *apiError) code() string { return "unreachable" } +// chatGone: the chat cannot be written to any more (the person blocked the bot or deleted the chat), so a link to it is worth nothing. +func (e *apiError) chatGone() bool { + return e != nil && (e.Status == http.StatusForbidden || (e.Status == http.StatusBadRequest && strings.Contains(strings.ToLower(e.Desc), "chat not found"))) +} + // errCode is code() for any error from this package. func errCode(err error) string { var ae *apiError @@ -151,9 +156,14 @@ type tgChat struct { Type string `json:"type"` } +type tgFrom struct { + LanguageCode string `json:"language_code"` +} + type tgMessage struct { - Chat tgChat `json:"chat"` - Text string `json:"text"` + Chat tgChat `json:"chat"` + From *tgFrom `json:"from"` + Text string `json:"text"` } type tgUpdate struct { diff --git a/internal/panel/telegram/rpc.go b/internal/panel/telegram/rpc.go index 29f26f6a..c35f9f99 100644 --- a/internal/panel/telegram/rpc.go +++ b/internal/panel/telegram/rpc.go @@ -136,6 +136,10 @@ func (r rpc) SetTelegramBot(ctx context.Context, req *connect.Request[adminv1.Se if !me.IsBot || me.Username == "" { return nil, fail(connect.CodeInvalidArgument, "token_invalid") } + // The bot of the people must be another one: both would take the same updates. + if ub, err := s.st.UserTelegramBot(ctx); err == nil && ub.BotID == me.ID { + return nil, fail(connect.CodeFailedPrecondition, "telegram_bot_is_users_bot") + } // Long polling and a webhook exclude each other; the panel takes no webhook, so one left on this bot is removed. if err := s.api.deleteWebhook(cctx, token); err != nil { s.log.Warn("telegram: deleteWebhook", "code", errCode(err)) diff --git a/internal/panel/telegram/service.go b/internal/panel/telegram/service.go index a21f9228..f920dc11 100644 --- a/internal/panel/telegram/service.go +++ b/internal/panel/telegram/service.go @@ -74,6 +74,7 @@ type Config struct { // Test seams. The zero value is production. APIBase string // https://api.telegram.org + UserAPIBase string // the same for the bot of the people; default APIBase HTTPClient *http.Client // default: a client with no timeout of its own (every call has its context's) Now func() time.Time Window time.Duration // how long a burst is gathered into one message; default 30 s @@ -93,6 +94,7 @@ type Service struct { st *store.Store vault *vault.Vault api *apiClient + uapi *apiClient // the bot of the people (user_bot.go); the same Bot API, another token cfg Config log *slog.Logger now func() time.Time @@ -110,6 +112,10 @@ type Service struct { pollFrom0 bool notify chan struct{} // an item was queued wake chan struct{} // the bot changed + + userPollStop context.CancelFunc // ends the poll of the people's bot in flight when that bot changes + userWake chan struct{} + chatKey []byte // the key of the chat MACs } // item is a line of news waiting for the next message: who gets it and how it reads in a language. @@ -169,10 +175,14 @@ func New(cfg Config) (*Service, error) { if cfg.RetryMax <= 0 { cfg.RetryMax = 6 } + if cfg.UserAPIBase == "" { + cfg.UserAPIBase = cfg.APIBase + } return &Service{ st: cfg.Store, vault: cfg.Vault, api: &apiClient{base: strings.TrimRight(cfg.APIBase, "/"), hc: cfg.HTTPClient}, cfg: cfg, log: cfg.Log, now: cfg.Now, + uapi: &apiClient{base: strings.TrimRight(cfg.UserAPIBase, "/"), hc: cfg.HTTPClient}, announcing: map[string]struct{}{}, open: map[string]time.Time{}, seenIP: map[string]time.Time{}, lastTest: map[string]time.Time{}, - notify: make(chan struct{}, 1), wake: make(chan struct{}, 1), + notify: make(chan struct{}, 1), wake: make(chan struct{}, 1), userWake: make(chan struct{}, 1), chatKey: cfg.Vault.Derive("user_telegram_chat_mac"), }, nil } @@ -192,7 +202,7 @@ func (s *Service) SetSources(src Sources) { // outlives it; the edge runs bounded methods from EdgeTick instead. func (s *Service) Run(ctx context.Context) { var wg sync.WaitGroup - for _, f := range []func(context.Context){s.pollLoop, s.sendLoop, s.watchLoop} { + for _, f := range []func(context.Context){s.pollLoop, s.sendLoop, s.watchLoop, s.userPollLoop} { wg.Add(1) go func() { defer wg.Done(); f(ctx) }() } @@ -334,12 +344,36 @@ func (s *Service) pollLoop(ctx context.Context) { // edge does not long-poll when there is no link code to hear. func (s *Service) PollPendingLinkCode(ctx context.Context) error { pending, err := s.st.HasPendingTelegramLinkCode(ctx, s.now()) - if err != nil { + if err != nil || !pending { return err } - if !pending { - return nil + return s.pollAdminLink(ctx) +} + +// PollPendingLinkCodes is the edge tick's whole Telegram poll step: one read says whether an admin's or a person's link code +// waits, and only a bot with a code waiting is polled, each within its own time budget. +func (s *Service) PollPendingLinkCodes(ctx context.Context) error { + admin, people, err := s.st.PendingTelegramLinkCodes(ctx, s.now()) + if err != nil || (!admin && !people) { + return err } + var errs []error + for _, step := range []struct { + wanted bool + poll func(context.Context) error + }{{admin, s.pollAdminLink}, {people, s.pollUserLink}} { + if !step.wanted { + continue + } + stepCtx, cancel := context.WithTimeout(ctx, 40*time.Second) + errs = append(errs, step.poll(stepCtx)) + cancel() + } + return errors.Join(errs...) +} + +// pollAdminLink is one bounded poll of the owner's bot, under the lease telegram-poll. +func (s *Service) pollAdminLink(ctx context.Context) error { holder := store.NewID("lease_") taken, err := s.st.TakeLease(ctx, "telegram-poll", holder, 45*time.Second, s.now()) if err != nil || !taken { diff --git a/internal/panel/telegram/user_admin.go b/internal/panel/telegram/user_admin.go new file mode 100644 index 00000000..a4c2c2b2 --- /dev/null +++ b/internal/panel/telegram/user_admin.go @@ -0,0 +1,328 @@ +package telegram + +import ( + "context" + "errors" + "strconv" + "strings" + "time" + + "connectrpc.com/connect" + + "github.com/mistgate/mistgate/internal/panel/auth" + "github.com/mistgate/mistgate/internal/panel/store" + "github.com/mistgate/mistgate/internal/panel/vault" +) + +// What the admin API does about the bot of the people and the chats of a person. The Connect service itself is +// usernotifyrpc (proto/mistgate/usernotify/v1), which only maps these to messages: this file imports no generated message, so +// the Workers that do not serve that service carry none of its descriptors. Levels are in auth/policy_usernotify.go; none of it +// is open to API tokens or MCP, and every method here refuses a token principal again on its own. Nothing returns the token or +// a Telegram chat id. + +var errUserNotFound = fail(connect.CodeNotFound, "user_not_found") + +// UserBotStatus is the card of the bot of the people. +type UserBotStatus struct { + Configured bool + Username string + State string // "", "ok", "unauthorized", "unreachable", "conflict" or "same_as_owner" + LastSent time.Time + People int // people with at least one chat + Chats int + ChatLimit int // of everybody + DefaultLimit int +} + +// UserChatInfo is one chat of a person, by its row id. +type UserChatInfo struct { + ID, Lang string + Muted bool + LinkedAt, LastSent time.Time +} + +// UserChats is a person's chats and what the tab of the person needs next to them. +type UserChats struct { + Chats []UserChatInfo + PendingExpires time.Time // zero: no code waits + Limit int // that applies to this person + LimitOverride int // the person's own, 0 = none + BotConfigured bool +} + +func (s *Service) userBotStatus(ctx context.Context) (UserBotStatus, error) { + global, _ := s.userChatLimits(ctx, "") + out := UserBotStatus{ChatLimit: global, DefaultLimit: store.DefaultUserTelegramChatLimit} + b, err := s.st.UserTelegramBot(ctx) + if errors.Is(err, store.ErrNotFound) { + return out, nil + } + if err != nil { + return out, err + } + out.Configured, out.Username, out.State = true, b.Username, userBotOK + switch { + case s.userBotIsOwners(ctx, b.BotID): + out.State = userBotSameAsOwner + case b.LastError != "": + out.State = b.LastError + } + people, chats, lastSent, err := s.st.UserTelegramStats(ctx) + if err != nil { + return out, err + } + out.People, out.Chats, out.LastSent = people, chats, lastSent + return out, nil +} + +func (s *Service) userBotCard(ctx context.Context) (UserBotStatus, error) { + card, err := s.userBotStatus(ctx) + if err != nil { + s.log.Error("telegram: people's bot status", "code", "user_telegram_status_failed", "err", err) + return card, errInternal + } + return card, nil +} + +// UserBot is the card of the bot, for any signed-in admin. +func (s *Service) UserBot(ctx context.Context) (UserBotStatus, error) { + if _, err := auth.SignedInSession(ctx); err != nil { + return UserBotStatus{}, err + } + return s.userBotCard(ctx) +} + +// SetUserBot sets the bot of the people: the owner, after a step-up. dropped is how many chats went with the old bot. +func (s *Service) SetUserBot(ctx context.Context, rawToken string) (card UserBotStatus, dropped int, err error) { + a, err := owner(ctx) + if err != nil { + return card, 0, err + } + if err := s.stepUp(ctx); err != nil { + return card, 0, err + } + token := vault.Redacted(strings.TrimSpace(rawToken)) + if !botTokenRe.MatchString(token.Reveal()) { + return card, 0, fail(connect.CodeInvalidArgument, "token_invalid") + } + cctx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + me, err := s.uapi.getMe(cctx, token) + if err != nil { + if errCode(err) == "unauthorized" { + return card, 0, fail(connect.CodeFailedPrecondition, "telegram_unauthorized") + } + return card, 0, fail(connect.CodeUnavailable, "telegram_unreachable") + } + if !me.IsBot || me.Username == "" { + return card, 0, fail(connect.CodeInvalidArgument, "token_invalid") + } + // The owner's own bot is for the owner: it would hear the people's chats and the people would hear the panel's alerts. + if s.userBotIsOwners(ctx, me.ID) { + return card, 0, fail(connect.CodeFailedPrecondition, "user_bot_same_as_owner") + } + // Long polling and a webhook exclude each other; the panel takes no webhook, so one left on this bot is removed. + if err := s.uapi.deleteWebhook(cctx, token); err != nil { + s.log.Warn("telegram: people's bot deleteWebhook", "code", errCode(err)) + } + dropped, err = s.st.SetUserTelegramBot(ctx, store.UserTelegramBot{Token: s.vault.Seal([]byte(token.Reveal()), userTokenRecordID), BotID: me.ID, Username: me.Username}, s.now()) + if err != nil { + s.log.Error("telegram: save people's bot", "code", "user_telegram_bot_save_failed", "err", err) + return card, 0, errInternal + } + s.auditCtx(ctx, a, "user_telegram_bot_set", map[string]any{"bot": me.Username, "dropped_chats": dropped}) + s.userBotChanged() + card, err = s.userBotCard(ctx) + return card, dropped, err +} + +// ClearUserBot switches the bot off and forgets every chat: the owner, after a step-up. +func (s *Service) ClearUserBot(ctx context.Context) (card UserBotStatus, dropped int, err error) { + a, err := owner(ctx) + if err != nil { + return card, 0, err + } + if err := s.stepUp(ctx); err != nil { + return card, 0, err + } + dropped, err = s.st.ClearUserTelegramBot(ctx) + if err != nil { + s.log.Error("telegram: clear people's bot", "code", "user_telegram_bot_clear_failed", "err", err) + return card, 0, errInternal + } + s.auditCtx(ctx, a, "user_telegram_bot_clear", map[string]any{"dropped_chats": dropped}) + s.userBotChanged() + card, err = s.userBotCard(ctx) + return card, dropped, err +} + +// userOrNotFound checks that the person exists. +func (s *Service) userOrNotFound(ctx context.Context, id string) error { + if id == "" { + return fail(connect.CodeInvalidArgument, "user_id_required") + } + ok, err := s.st.UserExists(ctx, id) + if err != nil { + s.log.Error("telegram: read user", "code", "user_telegram_user_read_failed", "err", err) + return errInternal + } + if !ok { + return errUserNotFound + } + return nil +} + +// BeginUserLink hands out the link of a person: the t.me address that holds a fresh one-time code, and when it runs out. +func (s *Service) BeginUserLink(ctx context.Context, user string) (link string, expires time.Time, err error) { + a, err := auth.SignedInSession(ctx) + if err != nil { + return "", expires, err + } + if err := s.userOrNotFound(ctx, user); err != nil { + return "", expires, err + } + b, err := s.st.UserTelegramBot(ctx) + if errors.Is(err, store.ErrNotFound) { + return "", expires, fail(connect.CodeFailedPrecondition, "user_bot_not_configured") + } + if err != nil { + s.log.Error("telegram: read people's bot", "code", "user_telegram_bot_read_failed", "err", err) + return "", expires, errInternal + } + n, err := s.st.CountUserTelegramChats(ctx, user) + if err != nil { + s.log.Error("telegram: count people's chats", "code", "user_telegram_chat_count_failed", "err", err) + return "", expires, errInternal + } + if n >= s.userChatLimit(ctx, user) { + return "", expires, fail(connect.CodeResourceExhausted, "user_chat_limit") + } + code, expires, err := s.newUserCode(ctx, user) + if err != nil { + s.log.Error("telegram: create people's link code", "code", "user_telegram_link_create_failed", "err", err) + return "", expires, errInternal + } + s.auditCtx(ctx, a, "user_telegram_link_begin", map[string]any{"user_id": user}) + return "https://t.me/" + b.Username + "?start=" + code, expires, nil +} + +// CancelUserLink withdraws the pending code of a person. +func (s *Service) CancelUserLink(ctx context.Context, user string) error { + a, err := auth.SignedInSession(ctx) + if err != nil { + return err + } + had, err := s.st.DeleteUserTelegramCode(ctx, user) + if err != nil { + s.log.Error("telegram: cancel people's link code", "code", "user_telegram_link_cancel_failed", "err", err) + return errInternal + } + if had { + s.auditCtx(ctx, a, "user_telegram_link_cancel", map[string]any{"user_id": user}) + } + return nil +} + +// UserChats lists a person's chats and the pending link. +func (s *Service) UserChats(ctx context.Context, user string) (UserChats, error) { + var out UserChats + if _, err := auth.SignedInSession(ctx); err != nil { + return out, err + } + if err := s.userOrNotFound(ctx, user); err != nil { + return out, err + } + chats, err := s.st.UserTelegramChats(ctx, user) + if err != nil { + s.log.Error("telegram: list people's chats", "code", "user_telegram_chat_list_failed", "err", err) + return out, errInternal + } + for _, c := range chats { + out.Chats = append(out.Chats, UserChatInfo{ID: c.ID, Lang: c.Lang, Muted: c.Muted, LinkedAt: c.LinkedAt, LastSent: c.LastSentAt}) + } + if exp, err := s.st.UserTelegramCodeExpiry(ctx, user, s.now()); err == nil { + out.PendingExpires = exp + } else if !errors.Is(err, store.ErrNotFound) { + s.log.Error("telegram: read people's link code", "code", "user_telegram_link_read_failed", "err", err) + return out, errInternal + } + global, own := s.userChatLimits(ctx, user) + out.Limit, out.LimitOverride = global, own + if own > 0 { + out.Limit = own + } + switch _, err := s.st.UserTelegramBot(ctx); { + case err == nil: + out.BotConfigured = true + case !errors.Is(err, store.ErrNotFound): + s.log.Error("telegram: read people's bot", "code", "user_telegram_bot_read_failed", "err", err) + return out, errInternal + } + return out, nil +} + +// UnlinkUserChat forgets one chat of a person. +func (s *Service) UnlinkUserChat(ctx context.Context, user, chat string) error { + a, err := auth.SignedInSession(ctx) + if err != nil { + return err + } + had, err := s.st.UnlinkUserTelegramChat(ctx, user, chat) + if err != nil { + s.log.Error("telegram: unlink people's chat", "code", "user_telegram_unlink_failed", "err", err) + return errInternal + } + if had { + s.auditCtx(ctx, a, "user_telegram_unlink", map[string]any{"user_id": user, "by": "admin"}) + } + return nil +} + +// MuteUserChat switches the announcements of one chat of a person. +func (s *Service) MuteUserChat(ctx context.Context, user, chat string, muted bool) error { + a, err := auth.SignedInSession(ctx) + if err != nil { + return err + } + switch err := s.st.SetUserTelegramChatMuted(ctx, user, chat, muted); { + case errors.Is(err, store.ErrNotFound): + return fail(connect.CodeNotFound, "chat_not_found") + case err != nil: + s.log.Error("telegram: mute people's chat", "code", "user_telegram_mute_failed", "err", err) + return errInternal + } + s.auditCtx(ctx, a, "user_telegram_mute", map[string]any{"user_id": user, "muted": muted}) + return nil +} + +// SetUserChatLimit sets the chat limit of everybody (user "") or of one person, 1 to 10; 0 returns it to the default. The owner's. +func (s *Service) SetUserChatLimit(ctx context.Context, user string, n int) error { + a, err := owner(ctx) + if err != nil { + return err + } + if n != 0 && (n < 1 || n > maxChatLimit) { + return fail(connect.CodeInvalidArgument, "limit_out_of_range") + } + if user != "" { + if err := s.userOrNotFound(ctx, user); err != nil { + return err + } + } + switch { + case user == "" && n == 0: + err = s.st.DeleteUserNotifySetting(ctx, userChatLimitKey) + case user == "": + err = s.st.SetUserNotifySetting(ctx, userChatLimitKey, strconv.Itoa(n)) + case n == 0: + err = s.st.DeleteUserNotifyOverride(ctx, user, userChatLimitKey) + default: + err = s.st.SetUserNotifyOverride(ctx, user, userChatLimitKey, strconv.Itoa(n)) + } + if err != nil { + s.log.Error("telegram: set people's chat limit", "code", "user_telegram_limit_failed", "err", err) + return errInternal + } + s.auditCtx(ctx, a, "user_telegram_chat_limit", map[string]any{"user_id": user, "limit": n}) + return nil +} diff --git a/internal/panel/telegram/user_bot.go b/internal/panel/telegram/user_bot.go new file mode 100644 index 00000000..9f8feb52 --- /dev/null +++ b/internal/panel/telegram/user_bot.go @@ -0,0 +1,388 @@ +package telegram + +import ( + "context" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/base32" + "encoding/hex" + "errors" + "strconv" + "strings" + "time" + + "github.com/mistgate/mistgate/internal/panel/store" + "github.com/mistgate/mistgate/internal/panel/vault" +) + +// The bot of the people: a second bot, never the owner's, through which the panel tells the people who use it about their term, +// their traffic and failures. This file is the half that listens: it hears "/start " (a person links a chat), /stop and +// /mute, and answers nobody else. Sending the notices is the outbox sender's job. The state of the bot (token, offset, last error) +// lives in user_telegram_bot, so every Worker and every process sees one card. +// +// Updates come by long polling only. The VPS polls for ever; the edge polls only while a link code is waiting, under the lease +// "user-telegram-poll" so that two isolates do not poll one bot (Telegram answers the second with 409). + +const ( + userTokenRecordID = "user_telegram_bot.token" + userLinkCodeTTL = 15 * time.Minute + userPollLease = "user-telegram-poll" + // userChatLimitKey is the key of the chat limit in user_notify_setting (everybody) and user_notify_override (one person). + userChatLimitKey = "telegram_chat_limit" + maxChatLimit = 10 +) + +// The state of the bot of the people, what GetUserBot says (and what user_telegram_bot.last_error holds, bar "ok"). +const ( + userBotOK = "ok" + userBotUnauthorized = "unauthorized" + userBotUnreachable = "unreachable" + userBotConflict = "conflict" + userBotSameAsOwner = "same_as_owner" + userBotNotConfigured = "" +) + +// chatMAC is the keyed MAC of a Telegram chat id: how a message from a chat finds its link without the id being stored in the clear. +func (s *Service) chatMAC(chat int64) []byte { + h := hmac.New(sha256.New, s.chatKey) + h.Write([]byte(strconv.FormatInt(chat, 10))) + return h.Sum(nil) +} + +// chatRecordID binds a sealed chat id to its chat: a blob cannot be moved to another row. +func chatRecordID(mac []byte) string { return "user_telegram_chat:" + hex.EncodeToString(mac) } + +// openChatID reads the Telegram chat id of a stored chat. +func (s *Service) openChatID(c store.UserTelegramChat) (int64, error) { + pt, err := s.vault.Open(c.ChatEnc, chatRecordID(c.ChatMAC)) + if err != nil { + return 0, err + } + return strconv.ParseInt(string(pt), 10, 64) +} + +// userToken is the token of the people's bot, opened from the vault for one use. +func (s *Service) userToken(b store.UserTelegramBot) (vault.Redacted, bool) { + pt, err := s.vault.Open(b.Token, userTokenRecordID) + if err != nil { + s.log.Error("telegram: the stored people's bot token cannot be opened", "code", "user_telegram_token_open_failed", "err", err) + return "", false + } + return vault.Redacted(pt), true +} + +// userBotIsOwners: the people's bot is the owner's own (the owner changed theirs to it after it was set here). Both would take the +// same updates, so neither is polled for the people. +func (s *Service) userBotIsOwners(ctx context.Context, botID int64) bool { + b, err := s.st.TelegramBot(ctx) + return err == nil && b.BotID == botID +} + +// userBotChanged ends the poll in flight and makes the loop look at the new bot at once. +func (s *Service) userBotChanged() { + s.mu.Lock() + stop := s.userPollStop + s.mu.Unlock() + if stop != nil { + stop() + } + select { + case s.userWake <- struct{}{}: + default: + } +} + +// ---- polling + +// userPollLoop is the VPS: one long poll after another until ctx ends. +func (s *Service) userPollLoop(ctx context.Context) { + backoff := time.Second + for ctx.Err() == nil { + ran, err := s.pollUserBot(ctx) + switch { + case ctx.Err() != nil: + return + case err != nil: + wait := backoff + var ae *apiError + if errors.As(err, &ae) && ae.RetryAfter > 0 { + wait = retryAfterWait(ae.RetryAfter) + } else { + backoff = min(backoff*2, 5*time.Minute) + } + s.log.Warn("telegram: people's bot getUpdates", "code", errCode(err), "retry_in", wait.String()) + s.wait(ctx, wait, s.userWake) + case !ran: + s.wait(ctx, 15*time.Second, s.userWake) + default: + backoff = time.Second + } + } +} + +// PollPendingUserLink is a bounded poll of the people's bot on its own. It asks D1 for a waiting link code first, so with none the +// edge makes no call to Telegram, and holds the lease while it polls. The edge tick uses PollPendingLinkCodes, which does the one +// read for both bots. +func (s *Service) PollPendingUserLink(ctx context.Context) error { + pending, err := s.st.HasPendingUserTelegramCode(ctx, s.now()) + if err != nil || !pending { + return err + } + return s.pollUserLink(ctx) +} + +// pollUserLink is one bounded poll of the people's bot, under the lease user-telegram-poll. +func (s *Service) pollUserLink(ctx context.Context) error { + holder := store.NewID("lease_") + taken, err := s.st.TakeLease(ctx, userPollLease, holder, 45*time.Second, s.now()) + if err != nil || !taken { + return err + } + defer func() { + if err := s.st.ReleaseLease(context.WithoutCancel(ctx), userPollLease, holder); err != nil && ctx.Err() == nil { + s.log.Warn("telegram: release people's poll lease", "code", "user_telegram_lease_release_failed", "err", err) + } + }() + _, err = s.pollUserBot(ctx) + return err +} + +// pollUserBot is one getUpdates of the people's bot and the handling of what it brought. ran says whether it asked Telegram at +// all (false: no bot, or a bot the owner uses too). A failure is stored as the card's error and returned. +func (s *Service) pollUserBot(ctx context.Context) (ran bool, err error) { + b, err := s.st.UserTelegramBot(ctx) + if errors.Is(err, store.ErrNotFound) { + return false, nil + } + if err != nil { + return false, err + } + if s.userBotIsOwners(ctx, b.BotID) { + s.saveUserPoll(ctx, b.Offset, userBotSameAsOwner, time.Time{}) + return false, nil + } + tok, ok := s.userToken(b) + if !ok { + return false, nil + } + pctx, cancel := context.WithTimeout(ctx, time.Duration(s.cfg.PollTimeout+15)*time.Second) + s.mu.Lock() + s.userPollStop = cancel + s.mu.Unlock() + ups, err := s.uapi.getUpdates(pctx, tok, b.Offset, s.cfg.PollTimeout) + cut := pctx.Err() // before cancel: set only when the poll was cut short + cancel() + s.mu.Lock() + s.userPollStop = nil + s.mu.Unlock() + if err != nil { + if ctx.Err() != nil { + return true, ctx.Err() + } + if cut != nil && !errors.Is(cut, context.DeadlineExceeded) { + return true, nil // the bot changed under the poll: start over with the new one + } + code := errCode(err) + s.saveUserPoll(ctx, b.Offset, code, time.Time{}) + return true, err + } + // Another isolate may have replaced the bot while this poll was in flight; its updates and its offset belong to the old one. + if cur, err := s.st.UserTelegramBot(ctx); err != nil || cur.BotID != b.BotID { + return true, err + } + offset := b.Offset + for _, u := range ups { + offset = max(offset, u.UpdateID+1) + if u.Message != nil { + s.handleUserMessage(ctx, tok, *u.Message) + } + } + s.saveUserPoll(ctx, offset, "", s.now()) + return true, nil +} + +func (s *Service) saveUserPoll(ctx context.Context, offset int64, code string, ok time.Time) { + if _, err := s.st.SaveUserTelegramBotPoll(ctx, offset, code, ok); err != nil && ctx.Err() == nil { + s.log.Warn("telegram: save people's bot poll", "code", "user_telegram_poll_store_failed", "err", err) + } +} + +// ---- what a person says to the bot + +// handleUserMessage answers a private chat. A chat that is not linked gets an answer only to "/start "; every other word from +// it, and everything from a group, gets none, so a stranger who finds the bot learns nothing from it. +func (s *Service) handleUserMessage(ctx context.Context, tok vault.Redacted, m tgMessage) { + if m.Chat.Type != "private" { + return + } + fields := strings.Fields(m.Text) + if len(fields) == 0 { + return + } + cmd, _, _ := strings.Cut(strings.ToLower(fields[0]), "@") + mac := s.chatMAC(m.Chat.ID) + chat, err := s.st.UserTelegramChatByMAC(ctx, mac) + linked := err == nil + if err != nil && !errors.Is(err, store.ErrNotFound) { + s.log.Warn("telegram: read people's chat", "code", "user_telegram_chat_read_failed", "err", err) + return + } + switch { + case cmd == "/start" && len(fields) >= 2: + s.linkUserChat(ctx, tok, m, mac, chat, linked, fields[1]) + case !linked: + return + case cmd == "/start": + s.userReply(ctx, tok, m.Chat.ID, mac, userWelcome.in(chat.Lang)) + case cmd == "/stop": + if ok, err := s.st.UnlinkUserTelegramChatByMAC(ctx, mac); err != nil { + s.log.Warn("telegram: unlink people's chat", "code", "user_telegram_unlink_failed", "err", err) + } else if ok { + s.auditAs(ctx, "user:"+chat.UserID, "user_telegram_unlink", map[string]any{"user_id": chat.UserID, "by": "chat"}, store.AuditBot) + s.userReply(ctx, tok, m.Chat.ID, nil, userStopped.in(chat.Lang)) + } + case cmd == "/mute" || cmd == "/unmute": + muted := cmd == "/mute" && !chat.Muted // /mute switches, /unmute only ever switches off + if err := s.st.SetUserTelegramChatMuted(ctx, chat.UserID, chat.ID, muted); err != nil { + if !errors.Is(err, store.ErrNotFound) { + s.log.Warn("telegram: mute people's chat", "code", "user_telegram_mute_failed", "err", err) + } + return + } + text := userUnmuted + if muted { + text = userMuted + } + s.userReply(ctx, tok, m.Chat.ID, mac, text.in(chat.Lang)) + } +} + +// linkUserChat takes the code of "/start " and links the chat to the person it was made for. A code that is not good, a chat +// that belongs to another person and a person with as many chats as the limit allows each get a short reason in the person's own +// language. A new link is told to the person's other chats, and written to the audit. +func (s *Service) linkUserChat(ctx context.Context, tok vault.Redacted, m tgMessage, mac []byte, chat store.UserTelegramChat, linked bool, code string) { + panelLang, _ := s.panel(ctx) + lang := userLang(langCode(m), string(panelLang)) + if linked { + lang = chat.Lang // an answer to a chat that is known follows its own language, not what the client says today + } + user, err := s.st.TakeUserTelegramCode(ctx, codeHash(code), s.now()) + switch { + case errors.Is(err, store.ErrNotFound): + s.userReply(ctx, tok, m.Chat.ID, mac, userBadCode.in(lang)) + return + case err != nil: + s.log.Warn("telegram: consume people's link code", "code", "user_telegram_link_consume_failed", "err", err) + return + } + if linked && chat.UserID == user { + s.userReply(ctx, tok, m.Chat.ID, mac, userWelcome.in(lang)) // the same chat linking again changes nothing and tells nobody + return + } + limit := s.userChatLimit(ctx, user) + before, err := s.st.UserTelegramChats(ctx, user) + if err != nil { + s.log.Warn("telegram: read people's chats", "code", "user_telegram_chat_read_failed", "err", err) + return + } + enc := s.vault.Seal([]byte(strconv.FormatInt(m.Chat.ID, 10)), chatRecordID(mac)) + switch err := s.st.LinkUserTelegramChat(ctx, user, mac, enc, lang, limit, s.now()); { + case errors.Is(err, store.ErrUserTelegramChatLimit): + s.userReply(ctx, tok, m.Chat.ID, mac, userLimitText(lang, limit)) + return + case errors.Is(err, store.ErrUserTelegramChatTaken): + s.userReply(ctx, tok, m.Chat.ID, mac, userTaken.in(lang)) + return + case errors.Is(err, store.ErrNotFound): // the person was deleted while the code waited + s.userReply(ctx, tok, m.Chat.ID, mac, userBadCode.in(lang)) + return + case err != nil: + s.log.Warn("telegram: link people's chat", "code", "user_telegram_link_failed", "err", err) + return + } + s.auditAs(ctx, "user:"+user, "user_telegram_link", map[string]any{"user_id": user, "chats": len(before) + 1}, store.AuditBot) + s.userReply(ctx, tok, m.Chat.ID, mac, userWelcome.in(lang)) + for _, c := range before { // the person's other chats hear of it, loudly: it may not have been the person + id, err := s.openChatID(c) + if err != nil { + s.log.Warn("telegram: open people's chat", "code", "user_telegram_chat_open_failed", "err", err) + continue + } + s.userReply(ctx, tok, id, c.ChatMAC, userNewChat.in(c.Lang)) + } +} + +func langCode(m tgMessage) string { + if m.From == nil { + return "" + } + return m.From.LanguageCode +} + +// userReply sends a plain message from the people's bot. A chat that cannot be written to any more (the person blocked the bot or +// deleted the chat) is forgotten; mac is nil for a chat that is forgotten already. +func (s *Service) userReply(ctx context.Context, tok vault.Redacted, chat int64, mac []byte, text string) { + sctx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + err := s.uapi.sendMessage(sctx, tok, chat, text) + if err == nil || ctx.Err() != nil { + return + } + var ae *apiError + if errors.As(err, &ae) && ae.chatGone() && mac != nil { + if _, err := s.st.UnlinkUserTelegramChatByMAC(ctx, mac); err != nil { + s.log.Warn("telegram: unlink people's chat", "code", "user_telegram_unlink_failed", "err", err) + } + return + } + s.log.Warn("telegram: people's reply", "code", errCode(err)) +} + +// ---- link codes and the chat limit + +// newUserCode makes the one-time code of a person (26 characters of base32: 130 bits, so 128 bits of entropy) that lives +// userLinkCodeTTL. A new code replaces the person's earlier one. Only its hash is stored. +func (s *Service) newUserCode(ctx context.Context, user string) (code string, expires time.Time, err error) { + var raw [16]byte + if _, err := rand.Read(raw[:]); err != nil { + return "", time.Time{}, err + } + code = strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(raw[:])) + expires = s.now().Add(userLinkCodeTTL) + if err := s.st.SetUserTelegramCode(ctx, codeHash(code), user, expires); err != nil { + return "", time.Time{}, err + } + return code, expires, nil +} + +// userChatLimits is the limit of everybody (the setting, or the default) and the person's own (0 when there is none). +func (s *Service) userChatLimits(ctx context.Context, user string) (global, own int) { + global = store.DefaultUserTelegramChatLimit + if all, err := s.st.UserNotifySettings(ctx); err == nil { + if n, ok := limitValue(all[userChatLimitKey]); ok { + global = n + } + } + if user != "" { + if ov, err := s.st.UserNotifyOverrides(ctx, user); err == nil { + own, _ = limitValue(ov[userChatLimitKey]) + } + } + return global, own +} + +// userChatLimit is how many chats a person may link. +func (s *Service) userChatLimit(ctx context.Context, user string) int { + global, own := s.userChatLimits(ctx, user) + if own > 0 { + return own + } + return global +} + +// limitValue reads a stored limit (a JSON number); ok is false for none or one out of range. +func limitValue(v string) (int, bool) { + n, err := strconv.Atoi(strings.TrimSpace(v)) + return n, err == nil && n >= 1 && n <= maxChatLimit +} diff --git a/internal/panel/telegram/user_bot_test.go b/internal/panel/telegram/user_bot_test.go new file mode 100644 index 00000000..0ccdbb16 --- /dev/null +++ b/internal/panel/telegram/user_bot_test.go @@ -0,0 +1,1052 @@ +package telegram + +import ( + "context" + "encoding/json" + "errors" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "connectrpc.com/connect" + + "github.com/mistgate/mistgate/internal/panel/store" +) + +// userEnv is an env with a second fake Telegram for the bot of the people, so the owner's bot and the people's can be told apart. +type userEnv struct { + *env + utg *fakeTG +} + +func newUserEnv(t *testing.T, opts ...option) *userEnv { + t.Helper() + utg := newFakeTG(t) + utg.username, utg.botID = "mist_people_bot", 987654321 + e := newEnv(t, append([]option{func(c *Config) { c.UserAPIBase = utg.srv.URL }}, opts...)...) + return &userEnv{env: e, utg: utg} +} + +// setUserBot stores the people's bot directly (the RPC path has its own test). +func (e *userEnv) setUserBot() { + e.t.Helper() + if _, err := e.st.SetUserTelegramBot(context.Background(), store.UserTelegramBot{ + Token: e.svc.vault.Seal([]byte(testToken), userTokenRecordID), BotID: e.utg.botID, Username: e.utg.username}, e.clk.now()); err != nil { + e.t.Fatal(err) + } +} + +func (e *userEnv) addUser(id string) { + e.t.Helper() + if _, err := e.st.W.Exec(`INSERT OR IGNORE INTO user_group (id, name, created_at) VALUES ('grp_a', 'a', 1)`); err != nil { + e.t.Fatal(err) + } + if _, err := e.st.W.Exec(`INSERT INTO user (id, name, group_id, period_start, sub_token_hash, sub_token_enc, created_at) VALUES (?, ?, 'grp_a', 1, ?, x'02', 1)`, + id, "name-"+id, []byte(id)); err != nil { + e.t.Fatal(err) + } +} + +// sayAs queues a message from a private chat with the language its Telegram client reports. +func (f *fakeTG) sayAs(chat int64, lang, text string) { + f.mu.Lock() + defer f.mu.Unlock() + f.nextID++ + f.updates = append(f.updates, tgUpdate{UpdateID: f.nextID, Message: &tgMessage{Chat: tgChat{ID: chat, Type: "private"}, From: &tgFrom{LanguageCode: lang}, Text: text}}) +} + +// poll runs one poll of the people's bot and fails the test on an error. +func (e *userEnv) poll() { + e.t.Helper() + if _, err := e.svc.pollUserBot(context.Background()); err != nil { + e.t.Fatalf("poll: %v", err) + } +} + +// code makes a link code for a person and returns it. +func (e *userEnv) code(user string) string { + e.t.Helper() + code, _, err := e.svc.newUserCode(context.Background(), user) + if err != nil { + e.t.Fatal(err) + } + return code +} + +// join links a chat the way a person does: sends "/start " and lets the bot hear it. +func (e *userEnv) join(user string, chat int64, lang string) { + e.t.Helper() + e.utg.sayAs(chat, lang, "/start "+e.code(user)) + e.poll() +} + +func (e *userEnv) chats(user string) []store.UserTelegramChat { + e.t.Helper() + c, err := e.st.UserTelegramChats(context.Background(), user) + if err != nil { + e.t.Fatal(err) + } + return c +} + +func (e *userEnv) userAudit() []string { + var out []string + for _, a := range e.auditActions() { + if strings.HasPrefix(a, "user_telegram") { + out = append(out, a) + } + } + return out +} + +func only(t *testing.T, got []string) string { + t.Helper() + if len(got) != 1 { + t.Fatalf("messages = %q, want exactly one", got) + } + return got[0] +} + +func TestUserLinkFlow(t *testing.T) { + e := newUserEnv(t) + e.setUserBot() + e.addUser("usr_a") + code := e.code("usr_a") + if len(code) != 26 { + t.Errorf("code %q has %d characters, want 26 (128 bits)", code, len(code)) + } + + e.utg.sayAs(500, "ru-RU", "/start "+code) + e.poll() + if got := only(t, e.utg.sentTo(500)); got != userWelcome.ru { + t.Errorf("welcome = %q", got) + } + chats := e.chats("usr_a") + if len(chats) != 1 || chats[0].Lang != "ru" || chats[0].Muted || !chats[0].LinkedAt.Equal(e.clk.now()) { + t.Fatalf("chats = %+v", chats) + } + if id, err := e.svc.openChatID(chats[0]); err != nil || id != 500 { + t.Errorf("sealed chat id = %d, %v", id, err) + } + if strings.Contains(string(chats[0].ChatEnc), "500") || strings.Contains(string(chats[0].ChatMAC), "500") { + t.Error("the chat id is stored in the clear") + } + if a := e.userAudit(); len(a) != 1 || !strings.HasPrefix(a[0], "user_telegram_link ") || strings.Contains(a[0], "500") { + t.Errorf("audit = %v", a) + } + if e.tg.total() != 0 { + t.Error("the owner's bot sent something") + } + + // the code is spent + e.utg.sayAs(501, "en", "/start "+code) + e.poll() + if got := only(t, e.utg.sentTo(501)); got != userBadCode.en { + t.Errorf("a spent code is answered %q", got) + } + if len(e.chats("usr_a")) != 1 { + t.Error("a spent code linked a chat") + } + + // the position in the updates is remembered by the bot's own row, and the card shows the poll worked + b, _ := e.st.UserTelegramBot(context.Background()) + if b.Offset == 0 || b.LastError != "" || b.LastOK.IsZero() { + t.Errorf("poll state = %+v", b) + } + last := b.Offset + e.poll() + e.utg.mu.Lock() + next := e.utg.offsets[len(e.utg.offsets)-1] + e.utg.mu.Unlock() + if next != last { + t.Errorf("the next poll asked from %d, the stored offset was %d", next, last) + } + if got := e.utg.sentTo(500); len(got) != 1 { + t.Errorf("an update was handled twice: %q", got) + } +} + +func TestUserLinkLanguages(t *testing.T) { + for _, tc := range []struct{ code, panel, want string }{ + {"ru", "en", "ru"}, {"RU", "en", "ru"}, {"zh-hans", "en", "zh"}, {"zh_CN", "en", "zh"}, {"tr", "ru", "tr"}, {"fa-IR", "en", "fa"}, + {"pt-BR", "ru", "ru"}, {"", "tr", "tr"}, {"de", "xx", "en"}, {"en-GB", "ru", "en"}, + } { + if got := userLang(tc.code, tc.panel); got != tc.want { + t.Errorf("userLang(%q, %q) = %q, want %q", tc.code, tc.panel, got, tc.want) + } + } + e := newUserEnv(t) + e.setUserBot() + e.addUser("usr_a") + e.utg.sayAs(1, "pt-BR", "/start "+e.code("usr_a")) // not a language of the panel: the panel's own, English here + e.poll() + if got := only(t, e.utg.sentTo(1)); got != userWelcome.en || e.chats("usr_a")[0].Lang != "en" { + t.Errorf("fallback: %q, %+v", got, e.chats("usr_a")) + } + // every text exists in all five languages, says no word of what the bot must not say, and holds no link + for name, tx := range map[string]userText{"welcome": userWelcome, "new": userNewChat, "bad": userBadCode, "taken": userTaken, "stopped": userStopped, "muted": userMuted, "unmuted": userUnmuted} { + for lang, s := range map[string]string{"ru": tx.ru, "en": tx.en, "zh": tx.zh, "tr": tx.tr, "fa": tx.fa} { + low := strings.ToLower(s) + if s == "" || strings.Contains(low, "vpn") || strings.Contains(low, "прокси") || strings.Contains(low, "обход") || strings.Contains(low, "http") || strings.ContainsAny(s, "<>&") { + t.Errorf("%s/%s: %q", name, lang, s) + } + } + } + if tx := userLimitText("fa", 3); !strings.Contains(tx, "3") || userLimitText("xx", 3) != userLimitText("en", 3) { + t.Errorf("limit text: %q", tx) + } +} + +func TestStrangersGetNoAnswer(t *testing.T) { + e := newUserEnv(t) + e.setUserBot() + e.addUser("usr_a") + e.join("usr_a", 10, "en") + before := e.utg.total() + for _, text := range []string{"hello", "/start", "/stop", "/mute", "/unmute", "/status", "/start@mist_people_bot", "give me the link"} { + e.utg.sayAs(99, "en", text) + } + // a group, even with a good code + code := e.code("usr_a") + e.utg.mu.Lock() + e.utg.nextID++ + e.utg.updates = append(e.utg.updates, tgUpdate{UpdateID: e.utg.nextID, Message: &tgMessage{Chat: tgChat{ID: -77, Type: "group"}, Text: "/start " + code}}) + e.utg.mu.Unlock() + e.poll() + if got := e.utg.total(); got != before { + t.Errorf("strangers got answers: %v", e.utg.sent[before:]) + } + if len(e.chats("usr_a")) != 1 { + t.Error("a group linked a chat") + } + // the group did not spend the code + e.utg.sayAs(11, "en", "/start "+code) + e.poll() + if len(e.chats("usr_a")) != 2 { + t.Error("the code was spent by a group") + } +} + +// An admin who writes to the bot of the people hears nothing, and the people's bot never writes to an admin's chat; the owner's +// own bot does not react to a person's chat either. +func TestAdminChatGetsNothingFromThePeoplesBot(t *testing.T) { + e := newUserEnv(t) + e.setUserBot() + e.setBot() + owner := e.addAdmin("adm_o", "Owner", store.RoleOwner) + e.link(owner, 80) + e.addUser("usr_a") + e.join("usr_a", 10, "en") + e.join("usr_a", 11, "ru") // a second chat is announced to the first, not to the admin + for _, text := range []string{"/start", "/mute", "/stop", "/unmute"} { + e.utg.sayAs(80, "en", text) + } + e.poll() + if got := e.utg.sentTo(80); len(got) != 0 { + t.Fatalf("the admin's chat got %q from the people's bot", got) + } + if e.tg.total() != 0 { + t.Errorf("the owner's bot sent %v", e.tg.sent) + } + // the owner's bot hears a person's code and does nothing with it + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + tok, _ := e.svc.token(ctx) + code := e.code("usr_a") + for _, text := range []string{"/start " + code, "/stop", "/mute"} { + e.svc.handleMessage(ctx, tok, tgMessage{Chat: tgChat{ID: 10, Type: "private"}, Text: text}) + } + if e.tg.total() != 0 || len(e.chats("usr_a")) != 2 { + t.Errorf("the owner's bot reacted to a person's chat: %v, %d chats", e.tg.sent, len(e.chats("usr_a"))) + } + if ok, _ := e.st.HasPendingUserTelegramCode(ctx, e.clk.now()); !ok { + t.Error("the owner's bot spent a person's code") + } +} + +func TestUserBotMustNotBeTheOwners(t *testing.T) { + e := newUserEnv(t) + owner := e.addAdmin("adm_o", "Owner", store.RoleOwner) + e.utg.botID = e.tg.botID // the same bot behind both tokens + e.setBot() + _, _, err := e.svc.SetUserBot(e.ctxAs(owner), testToken) + if connectCode(err) != connect.CodeFailedPrecondition || !strings.Contains(err.Error(), "user_bot_same_as_owner") { + t.Fatalf("SetUserBot with the owner's bot: %v", err) + } + if _, err := e.st.UserTelegramBot(context.Background()); !errors.Is(err, store.ErrNotFound) { + t.Errorf("a refused bot was stored: %v", err) + } + if e.utg.webhooks != 0 { + t.Error("the refused bot's webhook was deleted") + } + + // the other way round: the owner points theirs at the people's bot + e2 := newUserEnv(t) + o2 := e2.addAdmin("adm_o", "Owner", store.RoleOwner) + e2.setUserBot() + e2.tg.botID = e2.utg.botID + _, err = e2.rpcSetBot(o2, testToken, false) + if connectCode(err) != connect.CodeFailedPrecondition || !strings.Contains(err.Error(), "telegram_bot_is_users_bot") { + t.Fatalf("SetTelegramBot with the people's bot: %v", err) + } + if _, err := e2.st.TelegramBot(context.Background()); !errors.Is(err, store.ErrNotFound) { + t.Errorf("a refused owner bot was stored: %v", err) + } + + // and when it happens anyway (an old row), the people's bot is not polled and the card says so + e3 := newUserEnv(t) + e3.utg.botID = e3.tg.botID + e3.setBot() + e3.setUserBot() + if ran, err := e3.svc.pollUserBot(context.Background()); ran || err != nil { + t.Errorf("poll of a bot the owner uses: ran=%v err=%v", ran, err) + } + if e3.utg.count("getUpdates") != 0 { + t.Error("the people's bot was polled although it is the owner's") + } + card, err := e3.svc.userBotStatus(context.Background()) + if err != nil || card.State != userBotSameAsOwner { + t.Errorf("card = %+v, %v", card, err) + } +} + +// Several polls that hear the same code (in several isolates, from several chats) link exactly one chat. +func TestUserLinkCodeRace(t *testing.T) { + e := newUserEnv(t) + e.setUserBot() + e.addUser("usr_a") + other := func() *Service { + s, err := New(Config{Store: e.st, Vault: e.svc.vault, StepUp: e.svc.cfg.StepUp, APIBase: e.tg.srv.URL, UserAPIBase: e.utg.srv.URL, Now: e.clk.now}) + if err != nil { + t.Fatal(err) + } + return s + } + svcs := []*Service{e.svc, other(), other(), other()} + code := e.code("usr_a") + tok := testTokenRedacted() + start := make(chan struct{}) + var wg sync.WaitGroup + for i := range 8 { + wg.Add(1) + go func() { + defer wg.Done() + <-start + svcs[i%len(svcs)].handleUserMessage(context.Background(), tok, tgMessage{Chat: tgChat{ID: int64(900 + i), Type: "private"}, Text: "/start " + code}) + }() + } + close(start) + wg.Wait() + if n := len(e.chats("usr_a")); n != 1 { + t.Fatalf("%d chats linked by one code, want 1", n) + } + e.utg.mu.Lock() + var welcomes, refusals int + for _, m := range e.utg.sent { + switch m.Text { + case userWelcome.en: + welcomes++ + case userBadCode.en: + refusals++ + } + } + e.utg.mu.Unlock() + if welcomes != 1 || refusals != 7 { + t.Errorf("welcomes = %d, refusals = %d, want 1 and 7", welcomes, refusals) + } +} + +func TestUserChatLimit(t *testing.T) { + e := newUserEnv(t) + e.setUserBot() + e.addUser("usr_a") + e.addUser("usr_b") + for i := range 3 { + e.join("usr_a", int64(100+i), "en") + } + e.join("usr_a", 103, "ru") + if n := len(e.chats("usr_a")); n != 3 { + t.Fatalf("%d chats, want the default limit of 3", n) + } + if got := e.utg.sentTo(103); len(got) != 1 || got[0] != userLimitText("ru", 3) || !strings.Contains(got[0], "3") { + t.Errorf("the refusal = %q", got) + } + // the limit is the person's own, or everybody's, and 1 to 10 + if _, ok := limitValue("0"); ok { + t.Error("0 is a limit") + } + if _, ok := limitValue("11"); ok { + t.Error("11 is a limit") + } + owner := e.addAdmin("adm_o", "Owner", store.RoleOwner) + ctx := e.ctxAs(owner) + set := func(user string, n int) error { return e.svc.SetUserChatLimit(ctx, user, n) } + if err := set("", 4); err != nil { + t.Fatal(err) + } + e.join("usr_a", 103, "en") + if n := len(e.chats("usr_a")); n != 4 { + t.Errorf("after the limit of everybody went to 4: %d chats", n) + } + if err := set("usr_b", 1); err != nil { + t.Fatal(err) + } + e.join("usr_b", 200, "en") + e.join("usr_b", 201, "en") + if n := len(e.chats("usr_b")); n != 1 { + t.Errorf("a person with a limit of 1 has %d chats", n) + } + list, err := e.svc.UserChats(ctx, "usr_b") + if err != nil || list.Limit != 1 || list.LimitOverride != 1 { + t.Errorf("list = %+v, %v", list, err) + } + if err := set("usr_b", 0); err != nil { + t.Fatal(err) + } + if err := set("", 0); err != nil { + t.Fatal(err) + } + if got := e.svc.userChatLimit(context.Background(), "usr_b"); got != 3 { + t.Errorf("limit after both settings were removed = %d, want the default 3", got) + } + for _, bad := range []int{-1, 11} { + if err := set("", bad); connectCode(err) != connect.CodeInvalidArgument { + t.Errorf("limit %d: %v", bad, err) + } + } + if err := set("usr_missing", 2); connectCode(err) != connect.CodeNotFound { + t.Errorf("limit of a missing person: %v", err) + } + if err := set("", 2); err != nil { + t.Fatal(err) + } + // BeginUserTelegramLink refuses a person who is full already + _, _, err = e.svc.BeginUserLink(ctx, "usr_a") + if connectCode(err) != connect.CodeResourceExhausted { + t.Errorf("a link for a person who has 4 chats under a limit of 2: %v", err) + } +} + +func TestNewChatIsToldToTheOthers(t *testing.T) { + e := newUserEnv(t) + e.setUserBot() + e.addUser("usr_a") + e.addUser("usr_b") + e.join("usr_a", 301, "ru") + e.join("usr_b", 399, "en") + if got := e.utg.sentTo(301); len(got) != 1 { + t.Fatalf("the first chat heard %q", got) + } + e.join("usr_a", 302, "en") + e.join("usr_a", 303, "tr") + if got := e.utg.sentTo(301); len(got) != 3 || got[1] != userNewChat.ru || got[2] != userNewChat.ru { + t.Errorf("the first chat heard %q", got) + } + if got := e.utg.sentTo(302); len(got) != 2 || got[0] != userWelcome.en || got[1] != userNewChat.en { + t.Errorf("the second chat heard %q", got) + } + if got := e.utg.sentTo(303); len(got) != 1 || got[0] != userWelcome.tr { + t.Errorf("the newest chat heard %q", got) + } + if got := e.utg.sentTo(399); len(got) != 1 { + t.Errorf("another person's chat heard %q", got) + } + if a := e.userAudit(); len(a) != 4 { + t.Errorf("audit = %v", a) + } + + // the same chat linking again says welcome and tells nobody + e.join("usr_a", 302, "en") + if got := e.utg.sentTo(301); len(got) != 3 { + t.Errorf("a repeated link was announced: %q", got) + } + if n := len(e.chats("usr_a")); n != 3 { + t.Errorf("%d chats", n) + } + // a chat of another person is refused and told what to do + e.join("usr_b", 302, "en") + if got := e.utg.sentTo(302); got[len(got)-1] != userTaken.en { + t.Errorf("a chat that belongs to another person heard %q", got) + } + if n := len(e.chats("usr_b")); n != 1 { + t.Errorf("another person's chat was taken: %d", n) + } +} + +func TestStopAndMute(t *testing.T) { + e := newUserEnv(t) + e.setUserBot() + e.addUser("usr_a") + e.join("usr_a", 400, "en") + e.join("usr_a", 401, "ru") + muted := func(chat int64) bool { + c, err := e.st.UserTelegramChatByMAC(context.Background(), e.svc.chatMAC(chat)) + if err != nil { + e.t.Fatal(err) + } + return c.Muted + } + say := func(chat int64, text string) { + e.utg.sayAs(chat, "en", text) + e.poll() + } + last := func(chat int64) string { g := e.utg.sentTo(chat); return g[len(g)-1] } + + say(400, "/mute") + if !muted(400) || last(400) != userMuted.en || muted(401) { + t.Errorf("after /mute: %v %v %q", muted(400), muted(401), last(400)) + } + say(400, "/mute") // a switch + if muted(400) || last(400) != userUnmuted.en { + t.Errorf("after /mute twice: %v %q", muted(400), last(400)) + } + say(400, "/mute") + say(400, "/unmute") // the hidden synonym only switches off + say(400, "/unmute") + if muted(400) || last(400) != userUnmuted.en { + t.Errorf("after /unmute: %v %q", muted(400), last(400)) + } + say(400, "/MUTE@mist_people_bot") + if !muted(400) { + t.Error("a command with the bot's name or capitals was not heard") + } + say(400, "/start") // a linked chat that says /start is told the way things are + if last(400) != userWelcome.en { + t.Errorf("/start of a linked chat: %q", last(400)) + } + + say(401, "/stop") + if last(401) != userStopped.ru { + t.Errorf("/stop answer = %q", last(401)) + } + if n := len(e.chats("usr_a")); n != 1 { + t.Errorf("%d chats after /stop, want 1", n) + } + n := e.utg.total() + say(401, "/mute") + say(401, "/stop") + say(401, "hello") + if e.utg.total() != n { + t.Errorf("an unlinked chat was answered: %v", e.utg.sent[n:]) + } + if got := e.userAudit(); !strings.HasPrefix(got[0], "user_telegram_unlink ") || !strings.Contains(got[0], `"by":"chat"`) { // newest first + t.Errorf("audit = %v", got) + } +} + +// A chat that cannot be written to is forgotten: when the bot answers it (403, or 400 "chat not found") and when it tells it of a new chat. +func TestUserChatGoneIsUnlinked(t *testing.T) { + e := newUserEnv(t) + e.setUserBot() + e.addUser("usr_a") + e.join("usr_a", 500, "en") + e.join("usr_a", 501, "en") + + // the welcome of the next chat goes through; the news to the first two fails: 500 blocked the bot, 501 is gone + e.utg.mu.Lock() + e.utg.sendPlan = []planned{{}, {status: 403, desc: "Forbidden: bot was blocked by the user"}, {status: 400, desc: "Bad Request: chat not found"}} + e.utg.mu.Unlock() + e.join("usr_a", 502, "en") + chats := e.chats("usr_a") + if len(chats) != 1 { + t.Fatalf("chats = %d, want only the new one", len(chats)) + } + if id, _ := e.svc.openChatID(chats[0]); id != 502 { + t.Errorf("the chat left is %d", id) + } + + // a person who blocks the bot right after linking + e.utg.mu.Lock() + e.utg.sendPlan = []planned{{status: 403, desc: "Forbidden: bot was blocked by the user"}} + e.utg.mu.Unlock() + e.addUser("usr_b") + e.join("usr_b", 600, "en") + if n := len(e.chats("usr_b")); n != 0 { + t.Errorf("a chat that blocked the bot at once is still linked") + } + // any other failure keeps the chat + e.utg.mu.Lock() + e.utg.sendPlan = []planned{{status: 500, desc: "oops"}} + e.utg.mu.Unlock() + e.join("usr_b", 601, "en") + if n := len(e.chats("usr_b")); n != 1 { + t.Errorf("a failed answer unlinked the chat") + } +} + +func TestSetClearAndStateOfTheUserBot(t *testing.T) { + e := newUserEnv(t) + owner := e.addAdmin("adm_o", "Owner", store.RoleOwner) + helper := e.addAdmin("adm_h", "Helper", store.RoleHelper) + get := func() UserBotStatus { + b, err := e.svc.UserBot(e.ctxAs(helper)) + if err != nil { + t.Fatal(err) + } + if raw, _ := json.Marshal(b); strings.Contains(string(raw), "AAFake") { + t.Fatalf("the card carries the token: %s", raw) + } + return b + } + if b := get(); b.Configured || b.State != "" || b.ChatLimit != 3 || b.DefaultLimit != 3 { + t.Errorf("no bot: %+v", b) + } + + type botSet struct { + Bot UserBotStatus + DroppedChats int + } + set := func(a store.Admin, token string) (*botSet, error) { + b, dropped, err := e.svc.SetUserBot(e.ctxAs(a), token) + if err != nil { + return nil, err + } + return &botSet{b, dropped}, nil + } + for _, tc := range []struct { + name string + admin store.Admin + token string + want connect.Code + }{ + {"a helper", helper, testToken, connect.CodePermissionDenied}, + {"an API token", store.Admin{ID: "token:tok_1", Role: store.RoleOwner}, testToken, connect.CodePermissionDenied}, + {"a malformed token", owner, "nope", connect.CodeInvalidArgument}, + {"a token Telegram refuses", owner, "987654321:BBFakeFakeFakeFakeFakeFakeFakeFake_y", connect.CodeFailedPrecondition}, + } { + if _, err := set(tc.admin, tc.token); connectCode(err) != tc.want { + t.Errorf("%s: %v, want %v", tc.name, err, tc.want) + } + } + if _, err := e.st.UserTelegramBot(context.Background()); !errors.Is(err, store.ErrNotFound) { + t.Fatal("a refused call stored a bot") + } + deny := newUserEnv(t, func(c *Config) { + c.StepUp = func(context.Context) error { + return connect.NewError(connect.CodePermissionDenied, errors.New("step-up required")) + } + }) + o2 := deny.addAdmin("adm_o", "Owner", store.RoleOwner) + if _, _, err := deny.svc.SetUserBot(deny.ctxAs(o2), testToken); connectCode(err) != connect.CodePermissionDenied { + t.Errorf("SetUserBot without a step-up: %v", err) + } + if _, _, err := deny.svc.ClearUserBot(deny.ctxAs(o2)); connectCode(err) != connect.CodePermissionDenied { + t.Errorf("ClearUserBot without a step-up: %v", err) + } + + resp, err := set(owner, " "+testToken+" ") + if err != nil { + t.Fatal(err) + } + if b := resp.Bot; !b.Configured || b.Username != "mist_people_bot" || b.State != "ok" || resp.DroppedChats != 0 { + t.Errorf("after set: %+v", resp) + } + if e.utg.webhooks != 1 { + t.Errorf("deleteWebhook called %d times", e.utg.webhooks) + } + row, _ := e.st.UserTelegramBot(context.Background()) + if strings.Contains(string(row.Token), "AAFake") { + t.Error("the stored token is not sealed") + } + if pt, err := e.svc.vault.Open(row.Token, userTokenRecordID); err != nil || string(pt) != testToken { + t.Errorf("the stored token does not open: %v", err) + } + if _, err := e.svc.vault.Open(row.Token, tokenRecordID); err == nil { + t.Error("the people's token opens as the owner's") + } + for _, a := range e.userAudit() { + if strings.Contains(a, "AAFake") || strings.Contains(a, "123456789:") { + t.Errorf("audit holds the token: %s", a) + } + } + + // chats, a pending code and the counts on the card + e.addUser("usr_a") + e.addUser("usr_b") + e.join("usr_a", 1, "en") + e.join("usr_a", 2, "en") + e.join("usr_b", 3, "en") + e.code("usr_b") + if err := e.st.SetUserTelegramChatLastSent(context.Background(), "usr_a", e.chats("usr_a")[0].ID, e.clk.now().Add(time.Hour)); err != nil { + t.Fatal(err) + } + if b := get(); b.People != 2 || b.Chats != 3 || !b.LastSent.Equal(e.clk.now().Add(time.Hour)) || b.State != "ok" { + t.Errorf("card = %+v", b) + } + + // the same bot again keeps everything; another bot drops the chats + if resp, err := set(owner, testToken); err != nil || resp.DroppedChats != 0 || len(e.chats("usr_a")) != 2 { + t.Errorf("the same bot again: %+v, %v", resp, err) + } + e.utg.botID = 555555555 + if resp, err := set(owner, testToken); err != nil || resp.DroppedChats != 3 || len(e.chats("usr_a")) != 0 { + t.Errorf("another bot: %+v, %v", resp, err) + } + if ok, _ := e.st.HasPendingUserTelegramCode(context.Background(), e.clk.now()); ok { + t.Error("a pending code survived another bot") + } + + e.join("usr_a", 1, "en") + clearedBot, dropped, err := e.svc.ClearUserBot(e.ctxAs(owner)) + cleared := struct { + Bot UserBotStatus + Dropped int + }{clearedBot, dropped} + if err != nil || dropped != 1 || clearedBot.Configured || clearedBot.State != "" { + t.Errorf("clear: %+v, %v", cleared, err) + } + if _, err := e.st.UserTelegramBot(context.Background()); !errors.Is(err, store.ErrNotFound) || len(e.chats("usr_a")) != 0 { + t.Error("clear left the bot or a chat") + } + if a := e.userAudit(); !strings.HasPrefix(a[0], "user_telegram_bot_clear ") { + t.Errorf("audit = %v", a) + } +} + +func TestUserBotStateFollowsThePoll(t *testing.T) { + e := newUserEnv(t) + e.setUserBot() + state := func() string { + c, err := e.svc.userBotStatus(context.Background()) + if err != nil { + t.Fatal(err) + } + return c.State + } + if state() != "ok" { + t.Errorf("fresh bot: %q", state()) + } + for _, tc := range []struct { + plan planned + want string + }{ + {planned{status: 409, desc: "Conflict: terminated by other getUpdates request"}, "conflict"}, + {planned{status: 502, desc: "bad gateway"}, "unreachable"}, + {planned{status: 401, desc: "Unauthorized"}, "unauthorized"}, + } { + e.utg.mu.Lock() + e.utg.pollPlan = []planned{tc.plan} + e.utg.mu.Unlock() + if _, err := e.svc.pollUserBot(context.Background()); err == nil { + t.Errorf("%s: no error", tc.want) + } + if got := state(); got != tc.want { + t.Errorf("after %d: state %q, want %q", tc.plan.status, got, tc.want) + } + } + e.poll() // a good poll clears it + if state() != "ok" { + t.Errorf("after a good poll: %q", state()) + } + if b, _ := e.st.UserTelegramBot(context.Background()); b.LastOK.IsZero() { + t.Error("a good poll did not record its time") + } +} + +func TestUserLinkRPCs(t *testing.T) { + e := newUserEnv(t) + owner := e.addAdmin("adm_o", "Owner", store.RoleOwner) + e.addUser("usr_a") + ctx := e.ctxAs(owner) + type link struct { + DeepLink string + Expires time.Time + } + begin := func(user string) (*link, error) { + l, exp, err := e.svc.BeginUserLink(ctx, user) + if err != nil { + return nil, err + } + return &link{l, exp}, nil + } + list := func() UserChats { + c, err := e.svc.UserChats(ctx, "usr_a") + if err != nil { + t.Fatal(err) + } + return c + } + if _, err := begin("usr_a"); connectCode(err) != connect.CodeFailedPrecondition || !strings.Contains(err.Error(), "user_bot_not_configured") { + t.Errorf("without a bot: %v", err) + } + if l := list(); l.BotConfigured || len(l.Chats) != 0 || !l.PendingExpires.IsZero() || l.Limit != 3 { + t.Errorf("list without a bot: %+v", l) + } + e.setUserBot() + if _, err := begin("usr_none"); connectCode(err) != connect.CodeNotFound { + t.Errorf("a missing person: %v", err) + } + if _, err := begin(""); connectCode(err) != connect.CodeInvalidArgument { + t.Errorf("no person: %v", err) + } + if _, _, err := e.svc.BeginUserLink(e.ctxAs(store.Admin{ID: "token:t", Role: store.RoleOwner}), "usr_a"); connectCode(err) != connect.CodePermissionDenied { + t.Errorf("a token: %v", err) + } + + first, err := begin("usr_a") + if err != nil { + t.Fatal(err) + } + const prefix = "https://t.me/mist_people_bot?start=" + if !strings.HasPrefix(first.DeepLink, prefix) || len(strings.TrimPrefix(first.DeepLink, prefix)) != 26 || + !first.Expires.Equal(e.clk.now().Add(15*time.Minute)) { + t.Errorf("link = %+v", first) + } + if l := list(); !l.BotConfigured || !l.PendingExpires.Equal(first.Expires) { + t.Errorf("list with a code: %+v", l) + } + // a new code replaces the old one + second, _ := begin("usr_a") + codeOf := func(l *link) string { return strings.TrimPrefix(l.DeepLink, prefix) } + e.utg.sayAs(1, "en", "/start "+codeOf(first)) + e.poll() + if len(e.chats("usr_a")) != 0 || only(t, e.utg.sentTo(1)) != userBadCode.en { + t.Error("the replaced code still worked") + } + // a cancelled code is dead, cancelling twice is fine + for range 2 { + if err := e.svc.CancelUserLink(ctx, "usr_a"); err != nil { + t.Fatal(err) + } + } + e.utg.sayAs(2, "en", "/start "+codeOf(second)) + e.poll() + if l := list(); len(e.chats("usr_a")) != 0 || !l.PendingExpires.IsZero() { + t.Errorf("a cancelled code worked: %+v", l) + } + // an expired code is refused + third, _ := begin("usr_a") + e.clk.advance(16 * time.Minute) + e.utg.sayAs(3, "en", "/start "+codeOf(third)) + e.poll() + if len(e.chats("usr_a")) != 0 || !list().PendingExpires.IsZero() { + t.Error("an expired code worked") + } + + // chats: listed without a Telegram chat id, muted, unlinked + e.join("usr_a", 4242, "fa") + l := list() + if len(l.Chats) != 1 || l.Chats[0].Lang != "fa" || l.Chats[0].Muted || !l.Chats[0].LastSent.IsZero() { + t.Fatalf("list = %+v", l) + } + if raw, _ := json.Marshal(l); strings.Contains(string(raw), "4242") { + t.Errorf("the list carries the chat id: %s", raw) + } + id := l.Chats[0].ID + if err := e.svc.MuteUserChat(ctx, "usr_a", id, true); err != nil { + t.Fatal(err) + } + if !list().Chats[0].Muted { + t.Error("the chat was not muted") + } + if err := e.svc.MuteUserChat(ctx, "usr_a", "utc_none", true); connectCode(err) != connect.CodeNotFound { + t.Errorf("muting a missing chat: %v", err) + } + if err := e.svc.UnlinkUserChat(ctx, "usr_other", id); err != nil || len(list().Chats) != 1 { + t.Errorf("another person's unlink: %v", err) + } + for range 2 { + if err := e.svc.UnlinkUserChat(ctx, "usr_a", id); err != nil { + t.Fatal(err) + } + } + if len(list().Chats) != 0 { + t.Error("the chat was not unlinked") + } + n := 0 + for _, a := range e.userAudit() { + if strings.HasPrefix(a, "user_telegram_unlink ") { + n++ + } + } + if n != 1 { + t.Errorf("%d unlink audit rows for one unlink: %v", n, e.userAudit()) + } +} + +func TestUserCodeDiesWithThePerson(t *testing.T) { + e := newUserEnv(t) + e.setUserBot() + e.addUser("usr_a") + e.join("usr_a", 1, "en") + e.code("usr_a") + if _, err := e.st.W.Exec(`DELETE FROM user WHERE id = 'usr_a'`); err != nil { + t.Fatal(err) + } + if len(e.chats("usr_a")) != 0 { + t.Fatal("the chat outlived the person") + } + if ok, _ := e.st.HasPendingUserTelegramCode(context.Background(), e.clk.now()); ok { + t.Error("the code outlived the person") + } +} + +// The edge asks Telegram only while a person's code waits, and only one isolate at a time. +func TestEdgePollsThePeoplesBotOnlyForAPendingCode(t *testing.T) { + e := newUserEnv(t, func(c *Config) { c.Edge = true }) + e.setUserBot() + e.addUser("usr_a") + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := e.svc.PollPendingUserLink(ctx); err != nil || e.utg.count("getUpdates") != 0 { + t.Fatalf("no code: err=%v calls=%d", err, e.utg.count("getUpdates")) + } + e.utg.sayAs(7, "en", "/start "+e.code("usr_a")) + if err := e.svc.PollPendingUserLink(ctx); err != nil { + t.Fatal(err) + } + if e.utg.count("getUpdates") != 1 || len(e.chats("usr_a")) != 1 || only(t, e.utg.sentTo(7)) != userWelcome.en { + t.Errorf("polls = %d, chats = %d, answers = %q", e.utg.count("getUpdates"), len(e.chats("usr_a")), e.utg.sentTo(7)) + } + if e.tg.count("getUpdates") != 0 { + t.Error("the owner's bot was polled") + } + // the code is spent: the next tick is quiet again + if err := e.svc.PollPendingUserLink(ctx); err != nil || e.utg.count("getUpdates") != 1 { + t.Errorf("after the code was spent: err=%v calls=%d", err, e.utg.count("getUpdates")) + } + + // a held lease keeps a second isolate away from Telegram + e.code("usr_a") + if ok, err := e.st.TakeLease(ctx, userPollLease, "other-isolate", time.Minute, e.clk.now()); err != nil || !ok { + t.Fatal(err) + } + if err := e.svc.PollPendingUserLink(ctx); err != nil || e.utg.count("getUpdates") != 1 { + t.Errorf("with the lease held elsewhere: err=%v calls=%d", err, e.utg.count("getUpdates")) + } + // and the lease is let go after a poll + if err := e.st.ReleaseLease(ctx, userPollLease, "other-isolate"); err != nil { + t.Fatal(err) + } + if err := e.svc.PollPendingUserLink(ctx); err != nil || e.utg.count("getUpdates") != 2 { + t.Fatalf("poll: err=%v calls=%d", err, e.utg.count("getUpdates")) + } + if ok, err := e.st.TakeLease(ctx, userPollLease, "next", time.Minute, e.clk.now()); err != nil || !ok { + t.Errorf("the lease was not released: %v", err) + } + + // no bot: nothing happens + e.code("usr_a") + if _, err := e.st.ClearUserTelegramBot(ctx); err != nil { + t.Fatal(err) + } + if err := e.svc.PollPendingUserLink(ctx); err != nil { + t.Errorf("no bot: %v", err) + } +} + +// On the VPS the loop polls for ever and hears a code; a change of the bot makes it look again. +func TestUserPollLoopOnTheVPS(t *testing.T) { + e := newUserEnv(t) + e.setUserBot() + e.addUser("usr_a") + e.run() + e.utg.sayAs(5, "ru", "/start "+e.code("usr_a")) + waitFor(t, "the welcome", func() bool { return len(e.utg.sentTo(5)) == 1 }) + if got := e.utg.sentTo(5)[0]; got != userWelcome.ru { + t.Errorf("welcome = %q", got) + } + // the loop does not touch the owner's bot + if e.tg.count("getUpdates") != 0 { + t.Error("the owner's bot was polled with no owner bot set") + } + // the bot is cleared: the loop notices and waits; a new bot starts it again + if _, err := e.st.ClearUserTelegramBot(context.Background()); err != nil { + t.Fatal(err) + } + e.svc.userBotChanged() + e.addUser("usr_b") + e.setUserBot() + e.svc.userBotChanged() + e.utg.sayAs(6, "en", "/start "+e.code("usr_b")) + waitFor(t, "the welcome of the new bot", func() bool { return len(e.utg.sentTo(6)) == 1 }) +} + +// A failing poll backs off and is stored on the card; the loop survives a 401 and recovers. +func TestUserPollLoopBacksOffOnErrors(t *testing.T) { + var waits atomic.Int32 + e := newUserEnv(t, func(c *Config) { + c.Wait = func(ctx context.Context, d time.Duration, wake <-chan struct{}) bool { + waits.Add(1) + select { + case <-ctx.Done(): + return false + case <-time.After(5 * time.Millisecond): + return true + } + } + }) + e.setUserBot() + e.utg.mu.Lock() + e.utg.badToken = true + e.utg.mu.Unlock() + e.run() + waitFor(t, "the card to say the token is refused", func() bool { + c, err := e.svc.userBotStatus(context.Background()) + return err == nil && c.State == "unauthorized" + }) + if waits.Load() == 0 { + t.Error("the loop did not wait after a failure") + } + e.utg.mu.Lock() + e.utg.badToken = false + e.utg.mu.Unlock() + waitFor(t, "the card to recover", func() bool { + c, err := e.svc.userBotStatus(context.Background()) + return err == nil && c.State == "ok" + }) +} + +// What is stored about a failed poll is a code, never Telegram's words (they can hold the token). +func TestUserPollErrorIsACodeNotAMessage(t *testing.T) { + e := newUserEnv(t) + e.setUserBot() + e.utg.mu.Lock() + e.utg.pollPlan = []planned{{status: 502, desc: "bad gateway for bot" + testToken}} + e.utg.mu.Unlock() + _, err := e.svc.pollUserBot(context.Background()) + if err == nil || strings.Contains(err.Error(), "AAFake") { + t.Errorf("error = %v", err) + } + b, _ := e.st.UserTelegramBot(context.Background()) + if b.LastError != "unreachable" { + t.Errorf("the stored error is %q: a code, never a message", b.LastError) + } +} + +// The edge tick reads once whether a code waits for either bot and polls only the bot that has one. +func TestEdgePollsOnlyTheBotWithACodeWaiting(t *testing.T) { + e := newUserEnv(t, func(c *Config) { c.Edge = true }) + e.setUserBot() + e.setBot() + owner := e.addAdmin("adm_o", "Owner", store.RoleOwner) + e.addUser("usr_a") + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + polls := func() (admin, people int) { return e.tg.count("getUpdates"), e.utg.count("getUpdates") } + + if err := e.svc.PollPendingLinkCodes(ctx); err != nil { + t.Fatal(err) + } + if a, p := polls(); a != 0 || p != 0 { + t.Fatalf("nothing waits, polls = %d, %d", a, p) + } + e.code("usr_a") + if err := e.svc.PollPendingLinkCodes(ctx); err != nil { + t.Fatal(err) + } + if a, p := polls(); a != 0 || p != 1 { + t.Fatalf("a person's code waits, polls = %d, %d", a, p) + } + if _, _, err := e.svc.newCode(ctx, owner.ID); err != nil { + t.Fatal(err) + } + if err := e.svc.PollPendingLinkCodes(ctx); err != nil { + t.Fatal(err) + } + if a, p := polls(); a != 1 || p != 2 { + t.Fatalf("both wait, polls = %d, %d", a, p) + } +} diff --git a/internal/panel/telegram/user_texts.go b/internal/panel/telegram/user_texts.go new file mode 100644 index 00000000..1e1eeddc --- /dev/null +++ b/internal/panel/telegram/user_texts.go @@ -0,0 +1,111 @@ +package telegram + +import ( + "strconv" + "strings" +) + +// What the bot of the people says. Neutral words (access, device, service), no link and no question: the bot never sends a link +// and never asks for anything, and says so in its first message. Five languages like the panel; every key has all five. + +// userLanguages are the languages of the messages to a chat, the panel's own (instance.Languages). +var userLanguages = map[string]bool{"ru": true, "en": true, "zh": true, "tr": true, "fa": true} + +// userLang picks the language of a chat from Telegram's language_code ("ru", "pt-BR", "zh-hans" ...): the part before the dash when +// the panel speaks it, else fallback (the panel's language). +func userLang(code, fallback string) string { + for i := 0; i < len(code); i++ { + if code[i] == '-' || code[i] == '_' { + code = code[:i] + break + } + } + if code = strings.ToLower(code); userLanguages[code] { + return code + } + if userLanguages[fallback] { + return fallback + } + return "en" +} + +// userText is one message in the five languages; the language of a chat that is none of them gets English. +type userText struct{ ru, en, zh, tr, fa string } + +func (t userText) in(lang string) string { + switch lang { + case "ru": + return t.ru + case "zh": + return t.zh + case "tr": + return t.tr + case "fa": + return t.fa + } + return t.en +} + +var ( + userWelcome = userText{ + ru: "Готово, уведомления подключены. Этот бот никогда не присылает ссылок и ничего не спрашивает. /stop — отключить этот чат, /mute — без объявлений", + en: "Done, notifications are on. This bot never sends links and never asks you for anything. /stop turns off this chat, /mute turns off announcements", + zh: "已完成,通知已开启。本机器人从不发送链接,也不会向您索取任何信息。/stop 关闭此聊天,/mute 关闭公告", + tr: "Tamam, bildirimler açıldı. Bu bot hiçbir zaman bağlantı göndermez ve sizden hiçbir şey istemez. /stop bu sohbeti kapatır, /mute duyuruları kapatır", + fa: "انجام شد، اعلان‌ها روشن شد. این ربات هرگز پیوند نمی‌فرستد و هیچ چیزی از شما نمی‌خواهد. /stop این گفتگو را قطع می‌کند، /mute اطلاعیه‌ها را خاموش می‌کند", + } + userNewChat = userText{ + ru: "К этому доступу подключили ещё один Telegram. Если это были не вы, отключите его на своей странице", + en: "Another Telegram account was connected to this access. If it wasn’t you, disconnect it on your page", + zh: "有另一个 Telegram 账号连接到了此访问。如果不是您本人,请在您的页面上将其断开", + tr: "Bu erişime bir Telegram hesabı daha bağlandı. Siz yapmadıysanız, kendi sayfanızdan bağlantısını kesin", + fa: "یک تلگرام دیگر به این دسترسی متصل شد. اگر شما نبودید، آن را در صفحهٔ خودتان قطع کنید", + } + userBadCode = userText{ + ru: "Код не подошёл или устарел. Попросите новую ссылку у того, кто вас подключил", + en: "This code did not work or has expired. Ask the person who set it up for you for a new link", + zh: "该代码无效或已过期。请向为您开通的人索取新的链接", + tr: "Kod geçersiz ya da süresi dolmuş. Sizi bağlayan kişiden yeni bir bağlantı isteyin", + fa: "این کد معتبر نیست یا منقضی شده است. از کسی که شما را متصل کرده است پیوند تازه‌ای بخواهید", + } + userTaken = userText{ + ru: "Этот Telegram уже подключён к другому доступу. Отправьте /stop, чтобы отключить его, и запросите новую ссылку", + en: "This Telegram is already connected to another access. Send /stop to disconnect it, then ask for a new link", + zh: "此 Telegram 已连接到另一个访问。发送 /stop 将其断开,然后重新获取链接", + tr: "Bu Telegram zaten başka bir erişime bağlı. Bağlantıyı kesmek için /stop gönderin, sonra yeni bir bağlantı isteyin", + fa: "این تلگرام از قبل به دسترسی دیگری متصل است. برای قطع آن /stop را بفرستید و سپس پیوند تازه‌ای بخواهید", + } + userStopped = userText{ + ru: "Готово, этот чат отключён. Уведомления сюда больше не приходят", + en: "Done, this chat is disconnected. No more notifications will arrive here", + zh: "已完成,此聊天已断开。这里不会再收到通知", + tr: "Tamam, bu sohbetin bağlantısı kesildi. Buraya artık bildirim gelmeyecek", + fa: "انجام شد، این گفتگو قطع شد. دیگر اعلانی به اینجا نمی‌آید", + } + userMuted = userText{ + ru: "Объявления выключены, остальные уведомления приходят как раньше. Чтобы включить объявления снова, отправьте /mute ещё раз", + en: "Announcements are off, other notifications keep coming. Send /mute again to turn announcements back on", + zh: "公告已关闭,其他通知照常发送。再次发送 /mute 可重新开启公告", + tr: "Duyurular kapatıldı, diğer bildirimler eskisi gibi gelir. Duyuruları yeniden açmak için /mute komutunu tekrar gönderin", + fa: "اطلاعیه‌ها خاموش شد و اعلان‌های دیگر مثل قبل می‌آیند. برای روشن کردن دوباره اطلاعیه‌ها، /mute را دوباره بفرستید", + } + userUnmuted = userText{ + ru: "Объявления снова включены. /mute — выключить", + en: "Announcements are on again. /mute turns them off", + zh: "公告已重新开启。/mute 可关闭", + tr: "Duyurular yeniden açıldı. /mute ile kapatabilirsiniz", + fa: "اطلاعیه‌ها دوباره روشن شد. با /mute خاموش می‌شوند", + } +) + +// userLimitText says the person has as many chats as the limit allows. +func userLimitText(lang string, limit int) string { + n := strconv.Itoa(limit) + return userText{ + ru: "К этому доступу уже подключено максимум чатов: " + n + ". Отключите один из них на своей странице и запросите новую ссылку", + en: "The maximum number of chats is already connected to this access: " + n + ". Disconnect one on your page and ask for a new link", + zh: "此访问已连接到最大聊天数:" + n + "。请在您的页面上断开一个,然后重新获取链接", + tr: "Bu erişime bağlanabilecek en fazla sohbet sayısına ulaşıldı: " + n + ". Sayfanızdan birinin bağlantısını kesin ve yeni bir bağlantı isteyin", + fa: "تعداد گفتگوهای متصل به این دسترسی به حداکثر رسیده است: " + n + ". یکی را در صفحهٔ خودتان قطع کنید و پیوند تازه‌ای بخواهید", + }.in(lang) +} diff --git a/internal/panel/telegram/usernotifyrpc/service.go b/internal/panel/telegram/usernotifyrpc/service.go new file mode 100644 index 00000000..e5e90757 --- /dev/null +++ b/internal/panel/telegram/usernotifyrpc/service.go @@ -0,0 +1,114 @@ +// Package usernotifyrpc is the UserNotifyService (proto/mistgate/usernotify/v1): the bot of the people and their Telegram chats, +// for the admin. It only maps the messages to the proto-free calls of telegram.Service (user_admin.go), which does the work and +// checks who may call it. The roles that serve the admin API plug the handler in with app.Config.UserNotifyAPI; the Workers that +// do not (link, public, jobs, provision) never link it with its generated code and descriptors. +// +// Who may call what is the table of internal/panel/auth (policy_usernotify.go): none of it is open to API tokens or MCP. +package usernotifyrpc + +import ( + "context" + "net/http" + "time" + + "connectrpc.com/connect" + + usernotifyv1 "github.com/mistgate/mistgate/gen/mistgate/usernotify/v1" + "github.com/mistgate/mistgate/gen/mistgate/usernotify/v1/usernotifyv1connect" + "github.com/mistgate/mistgate/internal/panel/telegram" +) + +// Handler is app.Config.UserNotifyAPI: the UserNotifyService over tg. +func Handler(tg *telegram.Service) (string, http.Handler) { + return usernotifyv1connect.NewUserNotifyServiceHandler(rpc{tg}, connect.WithReadMaxBytes(16<<10)) +} + +type rpc struct{ tg *telegram.Service } + +func unix(t time.Time) int64 { + if t.IsZero() { + return 0 + } + return t.Unix() +} + +func card(b telegram.UserBotStatus) *usernotifyv1.UserBot { + return &usernotifyv1.UserBot{ + Configured: b.Configured, Username: b.Username, State: b.State, LastSentUnix: unix(b.LastSent), + LinkedPeople: int32(b.People), LinkedChats: int32(b.Chats), ChatLimit: int32(b.ChatLimit), ChatLimitDefault: int32(b.DefaultLimit), + } +} + +func (r rpc) GetUserBot(ctx context.Context, _ *connect.Request[usernotifyv1.Empty]) (*connect.Response[usernotifyv1.UserBot], error) { + b, err := r.tg.UserBot(ctx) + if err != nil { + return nil, err + } + return connect.NewResponse(card(b)), nil +} + +func (r rpc) SetUserBot(ctx context.Context, req *connect.Request[usernotifyv1.SetUserBotRequest]) (*connect.Response[usernotifyv1.SetUserBotResponse], error) { + b, dropped, err := r.tg.SetUserBot(ctx, req.Msg.Token) + if err != nil { + return nil, err + } + return connect.NewResponse(&usernotifyv1.SetUserBotResponse{Bot: card(b), DroppedChats: int32(dropped)}), nil +} + +func (r rpc) ClearUserBot(ctx context.Context, _ *connect.Request[usernotifyv1.Empty]) (*connect.Response[usernotifyv1.SetUserBotResponse], error) { + b, dropped, err := r.tg.ClearUserBot(ctx) + if err != nil { + return nil, err + } + return connect.NewResponse(&usernotifyv1.SetUserBotResponse{Bot: card(b), DroppedChats: int32(dropped)}), nil +} + +func (r rpc) BeginUserTelegramLink(ctx context.Context, req *connect.Request[usernotifyv1.UserRef]) (*connect.Response[usernotifyv1.UserTelegramLink], error) { + link, expires, err := r.tg.BeginUserLink(ctx, req.Msg.UserId) + if err != nil { + return nil, err + } + return connect.NewResponse(&usernotifyv1.UserTelegramLink{DeepLink: link, ExpiresUnix: expires.Unix()}), nil +} + +func (r rpc) CancelUserTelegramLink(ctx context.Context, req *connect.Request[usernotifyv1.UserRef]) (*connect.Response[usernotifyv1.Empty], error) { + if err := r.tg.CancelUserLink(ctx, req.Msg.UserId); err != nil { + return nil, err + } + return connect.NewResponse(&usernotifyv1.Empty{}), nil +} + +func (r rpc) ListUserTelegramChats(ctx context.Context, req *connect.Request[usernotifyv1.UserRef]) (*connect.Response[usernotifyv1.ListUserTelegramChatsResponse], error) { + c, err := r.tg.UserChats(ctx, req.Msg.UserId) + if err != nil { + return nil, err + } + out := &usernotifyv1.ListUserTelegramChatsResponse{ + PendingExpiresUnix: unix(c.PendingExpires), ChatLimit: int32(c.Limit), ChatLimitOverride: int32(c.LimitOverride), BotConfigured: c.BotConfigured, + } + for _, ch := range c.Chats { + out.Chats = append(out.Chats, &usernotifyv1.UserTelegramChat{Id: ch.ID, Lang: ch.Lang, Muted: ch.Muted, LinkedUnix: ch.LinkedAt.Unix(), LastSentUnix: unix(ch.LastSent)}) + } + return connect.NewResponse(out), nil +} + +func (r rpc) UnlinkUserTelegramChat(ctx context.Context, req *connect.Request[usernotifyv1.ChatRef]) (*connect.Response[usernotifyv1.Empty], error) { + if err := r.tg.UnlinkUserChat(ctx, req.Msg.UserId, req.Msg.ChatId); err != nil { + return nil, err + } + return connect.NewResponse(&usernotifyv1.Empty{}), nil +} + +func (r rpc) SetUserTelegramChatMuted(ctx context.Context, req *connect.Request[usernotifyv1.SetChatMutedRequest]) (*connect.Response[usernotifyv1.Empty], error) { + if err := r.tg.MuteUserChat(ctx, req.Msg.UserId, req.Msg.ChatId, req.Msg.Muted); err != nil { + return nil, err + } + return connect.NewResponse(&usernotifyv1.Empty{}), nil +} + +func (r rpc) SetUserTelegramChatLimit(ctx context.Context, req *connect.Request[usernotifyv1.SetChatLimitRequest]) (*connect.Response[usernotifyv1.Empty], error) { + if err := r.tg.SetUserChatLimit(ctx, req.Msg.UserId, int(req.Msg.Limit)); err != nil { + return nil, err + } + return connect.NewResponse(&usernotifyv1.Empty{}), nil +} diff --git a/proto/mistgate/usernotify/v1/usernotify.proto b/proto/mistgate/usernotify/v1/usernotify.proto new file mode 100644 index 00000000..5ba19899 --- /dev/null +++ b/proto/mistgate/usernotify/v1/usernotify.proto @@ -0,0 +1,122 @@ +syntax = "proto3"; + +package mistgate.usernotify.v1; + +// The bot of the people: the second Telegram bot of the panel, through which the panel tells the people who use it about their +// term, their traffic and failures. Conventions: admin/v1/common.proto. +// +// A separate package on purpose: only the admin API and the VPS panel serve this service (internal/panel/telegram/usernotifyrpc, +// plugged in through app.Config.UserNotifyAPI), and every other Worker would otherwise carry its generated code and descriptors +// for nothing (scripts/check-edge-sizes.sh). Its procedures are named by path in internal/panel/auth/policy_usernotify.go. +// The messages are shared on purpose too: each message type costs code in the Workers that link them. +// +// THE BOT. The owner makes a bot of its own with @BotFather (never the one of the alerts) and pastes its token here. The token +// is sealed in the panel vault and never comes back. A new or cleared bot drops every chat. LINKING. The owner or a helper hands +// out a one-time link for a person (a code of 128 bits, kept as a hash, 15 minutes, one per person); the person sends +// "/start " to the bot. Chat ids never leave the panel: a chat is named by its row id. +// +// WHO MAY CALL WHAT. SetUserBot, ClearUserBot and SetUserTelegramChatLimit are OWNER-ONLY (the first two need a step-up); the +// links and the chats of a person are the owner's and a helper's; reading is for every admin. None of it is open to API tokens +// or MCP. +// +// ERRORS. FAILED_PRECONDITION: "user_bot_not_configured", "user_bot_same_as_owner" (the token is the owner's own bot), +// "telegram_unauthorized" (Telegram refused the token). INVALID_ARGUMENT: "token_invalid", "user_id_required", +// "limit_out_of_range". NOT_FOUND: "user_not_found", "chat_not_found". RESOURCE_EXHAUSTED: "user_chat_limit". UNAVAILABLE: +// "telegram_unreachable". +service UserNotifyService { + // The bot for the card: state, counts, the chat limit. No secrets, no chat ids. + rpc GetUserBot(Empty) returns (UserBot); + // Sets the bot. Owner only; needs a step-up. Another bot than the stored one drops every chat. + rpc SetUserBot(SetUserBotRequest) returns (SetUserBotResponse); + // Switches the bot off and forgets every chat, pending code and Telegram delivery. Owner only; needs a step-up. + rpc ClearUserBot(Empty) returns (SetUserBotResponse); + // Hands out a link code for a person; a new one replaces the pending one. + rpc BeginUserTelegramLink(UserRef) returns (UserTelegramLink); + // Withdraws the pending code of a person. Idempotent. + rpc CancelUserTelegramLink(UserRef) returns (Empty); + // The chats of a person and the pending link, without chat ids. + rpc ListUserTelegramChats(UserRef) returns (ListUserTelegramChatsResponse); + // Forgets one chat of a person. Idempotent. + rpc UnlinkUserTelegramChat(ChatRef) returns (Empty); + // Switches the announcements of one chat off or on. + rpc SetUserTelegramChatMuted(SetChatMutedRequest) returns (Empty); + // The chat limit: of everybody (user_id empty) or of one person, 1 to 10; 0 returns to the default. Owner only. + rpc SetUserTelegramChatLimit(SetChatLimitRequest) returns (Empty); +} + +message Empty {} + +// The state of the bot, for the settings card. +message UserBot { + bool configured = 1; + // The bot's @username without the "@". + string username = 2; + // "" (no bot), "ok", "unauthorized" (Telegram refuses the token), "unreachable" (no answer), "conflict" (another program + // polls this bot) or "same_as_owner" (it is the owner's own bot, which the panel refuses to use). + string state = 3; + // When the last message reached a chat; 0 = never. + int64 last_sent_unix = 4 [jstype = JS_NUMBER]; + // People with at least one chat, and chats in all. + int32 linked_people = 5; + int32 linked_chats = 6; + // The chat limit of everybody; chat_limit_default is what it is without a setting. + int32 chat_limit = 7; + int32 chat_limit_default = 8; +} + +message SetUserBotRequest { + // The token from @BotFather. + string token = 1; +} +message SetUserBotResponse { + UserBot bot = 1; + // Chats dropped because the bot is another one than before (or none). + int32 dropped_chats = 2; +} + +message UserRef { string user_id = 1; } + +message UserTelegramLink { + // https://t.me/?start=; the code is in it and is shown nowhere else. + string deep_link = 1; + int64 expires_unix = 2 [jstype = JS_NUMBER]; +} + +// One chat of a person. The row id is what the other calls take; the Telegram chat id is never sent. +message UserTelegramChat { + string id = 1; + // ru, en, zh, tr or fa: the language of the messages to this chat. + string lang = 2; + // Announcements are off. + bool muted = 3; + int64 linked_unix = 4 [jstype = JS_NUMBER]; + // When the last message reached the chat; 0 = never. + int64 last_sent_unix = 5 [jstype = JS_NUMBER]; +} + +message ListUserTelegramChatsResponse { + repeated UserTelegramChat chats = 1; + // A link code is waiting (0 = none) and when it runs out. + int64 pending_expires_unix = 2 [jstype = JS_NUMBER]; + // The limit that applies to this person, and the person's own setting (0 = none; the global limit applies). + int32 chat_limit = 3; + int32 chat_limit_override = 4; + // Whether the bot is set at all, so the tab can say "no bot" without a second call. + bool bot_configured = 5; +} + +message ChatRef { + string user_id = 1; + string chat_id = 2; +} + +message SetChatMutedRequest { + string user_id = 1; + string chat_id = 2; + bool muted = 3; +} + +message SetChatLimitRequest { + string user_id = 1; + int32 limit = 2; +} diff --git a/web/src/gen/mistgate/usernotify/v1/usernotify_pb.ts b/web/src/gen/mistgate/usernotify/v1/usernotify_pb.ts new file mode 100644 index 00000000..4f0e5134 --- /dev/null +++ b/web/src/gen/mistgate/usernotify/v1/usernotify_pb.ts @@ -0,0 +1,454 @@ +// @generated by protoc-gen-es v2.16.0 with parameter "target=ts" +// @generated from file mistgate/usernotify/v1/usernotify.proto (package mistgate.usernotify.v1, syntax proto3) +/* eslint-disable */ + +import type { GenFile, GenMessage, GenService } from "@bufbuild/protobuf/codegenv2"; +import { fileDesc, messageDesc, serviceDesc } from "@bufbuild/protobuf/codegenv2"; +import type { Message } from "@bufbuild/protobuf"; + +/** + * Describes the file mistgate/usernotify/v1/usernotify.proto. + */ +export const file_mistgate_usernotify_v1_usernotify: GenFile = /*@__PURE__*/ + fileDesc("CidtaXN0Z2F0ZS91c2Vybm90aWZ5L3YxL3VzZXJub3RpZnkucHJvdG8SFm1pc3RnYXRlLnVzZXJub3RpZnkudjEiBwoFRW1wdHkitwEKB1VzZXJCb3QSEgoKY29uZmlndXJlZBgBIAEoCBIQCgh1c2VybmFtZRgCIAEoCRINCgVzdGF0ZRgDIAEoCRIaCg5sYXN0X3NlbnRfdW5peBgEIAEoA0ICMAISFQoNbGlua2VkX3Blb3BsZRgFIAEoBRIUCgxsaW5rZWRfY2hhdHMYBiABKAUSEgoKY2hhdF9saW1pdBgHIAEoBRIaChJjaGF0X2xpbWl0X2RlZmF1bHQYCCABKAUiIgoRU2V0VXNlckJvdFJlcXVlc3QSDQoFdG9rZW4YASABKAkiWQoSU2V0VXNlckJvdFJlc3BvbnNlEiwKA2JvdBgBIAEoCzIfLm1pc3RnYXRlLnVzZXJub3RpZnkudjEuVXNlckJvdBIVCg1kcm9wcGVkX2NoYXRzGAIgASgFIhoKB1VzZXJSZWYSDwoHdXNlcl9pZBgBIAEoCSI/ChBVc2VyVGVsZWdyYW1MaW5rEhEKCWRlZXBfbGluaxgBIAEoCRIYCgxleHBpcmVzX3VuaXgYAiABKANCAjACInAKEFVzZXJUZWxlZ3JhbUNoYXQSCgoCaWQYASABKAkSDAoEbGFuZxgCIAEoCRINCgVtdXRlZBgDIAEoCBIXCgtsaW5rZWRfdW5peBgEIAEoA0ICMAISGgoObGFzdF9zZW50X3VuaXgYBSABKANCAjACIsMBCh1MaXN0VXNlclRlbGVncmFtQ2hhdHNSZXNwb25zZRI3CgVjaGF0cxgBIAMoCzIoLm1pc3RnYXRlLnVzZXJub3RpZnkudjEuVXNlclRlbGVncmFtQ2hhdBIgChRwZW5kaW5nX2V4cGlyZXNfdW5peBgCIAEoA0ICMAISEgoKY2hhdF9saW1pdBgDIAEoBRIbChNjaGF0X2xpbWl0X292ZXJyaWRlGAQgASgFEhYKDmJvdF9jb25maWd1cmVkGAUgASgIIisKB0NoYXRSZWYSDwoHdXNlcl9pZBgBIAEoCRIPCgdjaGF0X2lkGAIgASgJIkYKE1NldENoYXRNdXRlZFJlcXVlc3QSDwoHdXNlcl9pZBgBIAEoCRIPCgdjaGF0X2lkGAIgASgJEg0KBW11dGVkGAMgASgIIjUKE1NldENoYXRMaW1pdFJlcXVlc3QSDwoHdXNlcl9pZBgBIAEoCRINCgVsaW1pdBgCIAEoBTL6BgoRVXNlck5vdGlmeVNlcnZpY2USTAoKR2V0VXNlckJvdBIdLm1pc3RnYXRlLnVzZXJub3RpZnkudjEuRW1wdHkaHy5taXN0Z2F0ZS51c2Vybm90aWZ5LnYxLlVzZXJCb3QSYwoKU2V0VXNlckJvdBIpLm1pc3RnYXRlLnVzZXJub3RpZnkudjEuU2V0VXNlckJvdFJlcXVlc3QaKi5taXN0Z2F0ZS51c2Vybm90aWZ5LnYxLlNldFVzZXJCb3RSZXNwb25zZRJZCgxDbGVhclVzZXJCb3QSHS5taXN0Z2F0ZS51c2Vybm90aWZ5LnYxLkVtcHR5GioubWlzdGdhdGUudXNlcm5vdGlmeS52MS5TZXRVc2VyQm90UmVzcG9uc2USYgoVQmVnaW5Vc2VyVGVsZWdyYW1MaW5rEh8ubWlzdGdhdGUudXNlcm5vdGlmeS52MS5Vc2VyUmVmGigubWlzdGdhdGUudXNlcm5vdGlmeS52MS5Vc2VyVGVsZWdyYW1MaW5rElgKFkNhbmNlbFVzZXJUZWxlZ3JhbUxpbmsSHy5taXN0Z2F0ZS51c2Vybm90aWZ5LnYxLlVzZXJSZWYaHS5taXN0Z2F0ZS51c2Vybm90aWZ5LnYxLkVtcHR5Em8KFUxpc3RVc2VyVGVsZWdyYW1DaGF0cxIfLm1pc3RnYXRlLnVzZXJub3RpZnkudjEuVXNlclJlZho1Lm1pc3RnYXRlLnVzZXJub3RpZnkudjEuTGlzdFVzZXJUZWxlZ3JhbUNoYXRzUmVzcG9uc2USWAoWVW5saW5rVXNlclRlbGVncmFtQ2hhdBIfLm1pc3RnYXRlLnVzZXJub3RpZnkudjEuQ2hhdFJlZhodLm1pc3RnYXRlLnVzZXJub3RpZnkudjEuRW1wdHkSZgoYU2V0VXNlclRlbGVncmFtQ2hhdE11dGVkEisubWlzdGdhdGUudXNlcm5vdGlmeS52MS5TZXRDaGF0TXV0ZWRSZXF1ZXN0Gh0ubWlzdGdhdGUudXNlcm5vdGlmeS52MS5FbXB0eRJmChhTZXRVc2VyVGVsZWdyYW1DaGF0TGltaXQSKy5taXN0Z2F0ZS51c2Vybm90aWZ5LnYxLlNldENoYXRMaW1pdFJlcXVlc3QaHS5taXN0Z2F0ZS51c2Vybm90aWZ5LnYxLkVtcHR5Qu0BChpjb20ubWlzdGdhdGUudXNlcm5vdGlmeS52MUIPVXNlcm5vdGlmeVByb3RvUAFaRGdpdGh1Yi5jb20vbWlzdGdhdGUvbWlzdGdhdGUvZ2VuL21pc3RnYXRlL3VzZXJub3RpZnkvdjE7dXNlcm5vdGlmeXYxogIDTVVYqgIWTWlzdGdhdGUuVXNlcm5vdGlmeS5WMcoCFk1pc3RnYXRlXFVzZXJub3RpZnlcVjHiAiJNaXN0Z2F0ZVxVc2Vybm90aWZ5XFYxXEdQQk1ldGFkYXRh6gIYTWlzdGdhdGU6OlVzZXJub3RpZnk6OlYxYgZwcm90bzM"); + +/** + * @generated from message mistgate.usernotify.v1.Empty + */ +export type Empty = Message<"mistgate.usernotify.v1.Empty"> & { +}; + +/** + * Describes the message mistgate.usernotify.v1.Empty. + * Use `create(EmptySchema)` to create a new message. + */ +export const EmptySchema: GenMessage = /*@__PURE__*/ + messageDesc(file_mistgate_usernotify_v1_usernotify, 0); + +/** + * The state of the bot, for the settings card. + * + * @generated from message mistgate.usernotify.v1.UserBot + */ +export type UserBot = Message<"mistgate.usernotify.v1.UserBot"> & { + /** + * @generated from field: bool configured = 1; + */ + configured: boolean; + + /** + * The bot's @username without the "@". + * + * @generated from field: string username = 2; + */ + username: string; + + /** + * "" (no bot), "ok", "unauthorized" (Telegram refuses the token), "unreachable" (no answer), "conflict" (another program + * polls this bot) or "same_as_owner" (it is the owner's own bot, which the panel refuses to use). + * + * @generated from field: string state = 3; + */ + state: string; + + /** + * When the last message reached a chat; 0 = never. + * + * @generated from field: int64 last_sent_unix = 4 [jstype = JS_NUMBER]; + */ + lastSentUnix: bigint; + + /** + * People with at least one chat, and chats in all. + * + * @generated from field: int32 linked_people = 5; + */ + linkedPeople: number; + + /** + * @generated from field: int32 linked_chats = 6; + */ + linkedChats: number; + + /** + * The chat limit of everybody; chat_limit_default is what it is without a setting. + * + * @generated from field: int32 chat_limit = 7; + */ + chatLimit: number; + + /** + * @generated from field: int32 chat_limit_default = 8; + */ + chatLimitDefault: number; +}; + +/** + * Describes the message mistgate.usernotify.v1.UserBot. + * Use `create(UserBotSchema)` to create a new message. + */ +export const UserBotSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_mistgate_usernotify_v1_usernotify, 1); + +/** + * @generated from message mistgate.usernotify.v1.SetUserBotRequest + */ +export type SetUserBotRequest = Message<"mistgate.usernotify.v1.SetUserBotRequest"> & { + /** + * The token from @BotFather. + * + * @generated from field: string token = 1; + */ + token: string; +}; + +/** + * Describes the message mistgate.usernotify.v1.SetUserBotRequest. + * Use `create(SetUserBotRequestSchema)` to create a new message. + */ +export const SetUserBotRequestSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_mistgate_usernotify_v1_usernotify, 2); + +/** + * @generated from message mistgate.usernotify.v1.SetUserBotResponse + */ +export type SetUserBotResponse = Message<"mistgate.usernotify.v1.SetUserBotResponse"> & { + /** + * @generated from field: mistgate.usernotify.v1.UserBot bot = 1; + */ + bot?: UserBot | undefined; + + /** + * Chats dropped because the bot is another one than before (or none). + * + * @generated from field: int32 dropped_chats = 2; + */ + droppedChats: number; +}; + +/** + * Describes the message mistgate.usernotify.v1.SetUserBotResponse. + * Use `create(SetUserBotResponseSchema)` to create a new message. + */ +export const SetUserBotResponseSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_mistgate_usernotify_v1_usernotify, 3); + +/** + * @generated from message mistgate.usernotify.v1.UserRef + */ +export type UserRef = Message<"mistgate.usernotify.v1.UserRef"> & { + /** + * @generated from field: string user_id = 1; + */ + userId: string; +}; + +/** + * Describes the message mistgate.usernotify.v1.UserRef. + * Use `create(UserRefSchema)` to create a new message. + */ +export const UserRefSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_mistgate_usernotify_v1_usernotify, 4); + +/** + * @generated from message mistgate.usernotify.v1.UserTelegramLink + */ +export type UserTelegramLink = Message<"mistgate.usernotify.v1.UserTelegramLink"> & { + /** + * https://t.me/?start=; the code is in it and is shown nowhere else. + * + * @generated from field: string deep_link = 1; + */ + deepLink: string; + + /** + * @generated from field: int64 expires_unix = 2 [jstype = JS_NUMBER]; + */ + expiresUnix: bigint; +}; + +/** + * Describes the message mistgate.usernotify.v1.UserTelegramLink. + * Use `create(UserTelegramLinkSchema)` to create a new message. + */ +export const UserTelegramLinkSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_mistgate_usernotify_v1_usernotify, 5); + +/** + * One chat of a person. The row id is what the other calls take; the Telegram chat id is never sent. + * + * @generated from message mistgate.usernotify.v1.UserTelegramChat + */ +export type UserTelegramChat = Message<"mistgate.usernotify.v1.UserTelegramChat"> & { + /** + * @generated from field: string id = 1; + */ + id: string; + + /** + * ru, en, zh, tr or fa: the language of the messages to this chat. + * + * @generated from field: string lang = 2; + */ + lang: string; + + /** + * Announcements are off. + * + * @generated from field: bool muted = 3; + */ + muted: boolean; + + /** + * @generated from field: int64 linked_unix = 4 [jstype = JS_NUMBER]; + */ + linkedUnix: bigint; + + /** + * When the last message reached the chat; 0 = never. + * + * @generated from field: int64 last_sent_unix = 5 [jstype = JS_NUMBER]; + */ + lastSentUnix: bigint; +}; + +/** + * Describes the message mistgate.usernotify.v1.UserTelegramChat. + * Use `create(UserTelegramChatSchema)` to create a new message. + */ +export const UserTelegramChatSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_mistgate_usernotify_v1_usernotify, 6); + +/** + * @generated from message mistgate.usernotify.v1.ListUserTelegramChatsResponse + */ +export type ListUserTelegramChatsResponse = Message<"mistgate.usernotify.v1.ListUserTelegramChatsResponse"> & { + /** + * @generated from field: repeated mistgate.usernotify.v1.UserTelegramChat chats = 1; + */ + chats: UserTelegramChat[]; + + /** + * A link code is waiting (0 = none) and when it runs out. + * + * @generated from field: int64 pending_expires_unix = 2 [jstype = JS_NUMBER]; + */ + pendingExpiresUnix: bigint; + + /** + * The limit that applies to this person, and the person's own setting (0 = none; the global limit applies). + * + * @generated from field: int32 chat_limit = 3; + */ + chatLimit: number; + + /** + * @generated from field: int32 chat_limit_override = 4; + */ + chatLimitOverride: number; + + /** + * Whether the bot is set at all, so the tab can say "no bot" without a second call. + * + * @generated from field: bool bot_configured = 5; + */ + botConfigured: boolean; +}; + +/** + * Describes the message mistgate.usernotify.v1.ListUserTelegramChatsResponse. + * Use `create(ListUserTelegramChatsResponseSchema)` to create a new message. + */ +export const ListUserTelegramChatsResponseSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_mistgate_usernotify_v1_usernotify, 7); + +/** + * @generated from message mistgate.usernotify.v1.ChatRef + */ +export type ChatRef = Message<"mistgate.usernotify.v1.ChatRef"> & { + /** + * @generated from field: string user_id = 1; + */ + userId: string; + + /** + * @generated from field: string chat_id = 2; + */ + chatId: string; +}; + +/** + * Describes the message mistgate.usernotify.v1.ChatRef. + * Use `create(ChatRefSchema)` to create a new message. + */ +export const ChatRefSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_mistgate_usernotify_v1_usernotify, 8); + +/** + * @generated from message mistgate.usernotify.v1.SetChatMutedRequest + */ +export type SetChatMutedRequest = Message<"mistgate.usernotify.v1.SetChatMutedRequest"> & { + /** + * @generated from field: string user_id = 1; + */ + userId: string; + + /** + * @generated from field: string chat_id = 2; + */ + chatId: string; + + /** + * @generated from field: bool muted = 3; + */ + muted: boolean; +}; + +/** + * Describes the message mistgate.usernotify.v1.SetChatMutedRequest. + * Use `create(SetChatMutedRequestSchema)` to create a new message. + */ +export const SetChatMutedRequestSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_mistgate_usernotify_v1_usernotify, 9); + +/** + * @generated from message mistgate.usernotify.v1.SetChatLimitRequest + */ +export type SetChatLimitRequest = Message<"mistgate.usernotify.v1.SetChatLimitRequest"> & { + /** + * @generated from field: string user_id = 1; + */ + userId: string; + + /** + * @generated from field: int32 limit = 2; + */ + limit: number; +}; + +/** + * Describes the message mistgate.usernotify.v1.SetChatLimitRequest. + * Use `create(SetChatLimitRequestSchema)` to create a new message. + */ +export const SetChatLimitRequestSchema: GenMessage = /*@__PURE__*/ + messageDesc(file_mistgate_usernotify_v1_usernotify, 10); + +/** + * The bot of the people: the second Telegram bot of the panel, through which the panel tells the people who use it about their + * term, their traffic and failures. Conventions: admin/v1/common.proto. + * + * A separate package on purpose: only the admin API and the VPS panel serve this service (internal/panel/telegram/usernotifyrpc, + * plugged in through app.Config.UserNotifyAPI), and every other Worker would otherwise carry its generated code and descriptors + * for nothing (scripts/check-edge-sizes.sh). Its procedures are named by path in internal/panel/auth/policy_usernotify.go. + * The messages are shared on purpose too: each message type costs code in the Workers that link them. + * + * THE BOT. The owner makes a bot of its own with @BotFather (never the one of the alerts) and pastes its token here. The token + * is sealed in the panel vault and never comes back. A new or cleared bot drops every chat. LINKING. The owner or a helper hands + * out a one-time link for a person (a code of 128 bits, kept as a hash, 15 minutes, one per person); the person sends + * "/start " to the bot. Chat ids never leave the panel: a chat is named by its row id. + * + * WHO MAY CALL WHAT. SetUserBot, ClearUserBot and SetUserTelegramChatLimit are OWNER-ONLY (the first two need a step-up); the + * links and the chats of a person are the owner's and a helper's; reading is for every admin. None of it is open to API tokens + * or MCP. + * + * ERRORS. FAILED_PRECONDITION: "user_bot_not_configured", "user_bot_same_as_owner" (the token is the owner's own bot), + * "telegram_unauthorized" (Telegram refused the token). INVALID_ARGUMENT: "token_invalid", "user_id_required", + * "limit_out_of_range". NOT_FOUND: "user_not_found", "chat_not_found". RESOURCE_EXHAUSTED: "user_chat_limit". UNAVAILABLE: + * "telegram_unreachable". + * + * @generated from service mistgate.usernotify.v1.UserNotifyService + */ +export const UserNotifyService: GenService<{ + /** + * The bot for the card: state, counts, the chat limit. No secrets, no chat ids. + * + * @generated from rpc mistgate.usernotify.v1.UserNotifyService.GetUserBot + */ + getUserBot: { + methodKind: "unary"; + input: typeof EmptySchema; + output: typeof UserBotSchema; + }, + /** + * Sets the bot. Owner only; needs a step-up. Another bot than the stored one drops every chat. + * + * @generated from rpc mistgate.usernotify.v1.UserNotifyService.SetUserBot + */ + setUserBot: { + methodKind: "unary"; + input: typeof SetUserBotRequestSchema; + output: typeof SetUserBotResponseSchema; + }, + /** + * Switches the bot off and forgets every chat, pending code and Telegram delivery. Owner only; needs a step-up. + * + * @generated from rpc mistgate.usernotify.v1.UserNotifyService.ClearUserBot + */ + clearUserBot: { + methodKind: "unary"; + input: typeof EmptySchema; + output: typeof SetUserBotResponseSchema; + }, + /** + * Hands out a link code for a person; a new one replaces the pending one. + * + * @generated from rpc mistgate.usernotify.v1.UserNotifyService.BeginUserTelegramLink + */ + beginUserTelegramLink: { + methodKind: "unary"; + input: typeof UserRefSchema; + output: typeof UserTelegramLinkSchema; + }, + /** + * Withdraws the pending code of a person. Idempotent. + * + * @generated from rpc mistgate.usernotify.v1.UserNotifyService.CancelUserTelegramLink + */ + cancelUserTelegramLink: { + methodKind: "unary"; + input: typeof UserRefSchema; + output: typeof EmptySchema; + }, + /** + * The chats of a person and the pending link, without chat ids. + * + * @generated from rpc mistgate.usernotify.v1.UserNotifyService.ListUserTelegramChats + */ + listUserTelegramChats: { + methodKind: "unary"; + input: typeof UserRefSchema; + output: typeof ListUserTelegramChatsResponseSchema; + }, + /** + * Forgets one chat of a person. Idempotent. + * + * @generated from rpc mistgate.usernotify.v1.UserNotifyService.UnlinkUserTelegramChat + */ + unlinkUserTelegramChat: { + methodKind: "unary"; + input: typeof ChatRefSchema; + output: typeof EmptySchema; + }, + /** + * Switches the announcements of one chat off or on. + * + * @generated from rpc mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatMuted + */ + setUserTelegramChatMuted: { + methodKind: "unary"; + input: typeof SetChatMutedRequestSchema; + output: typeof EmptySchema; + }, + /** + * The chat limit: of everybody (user_id empty) or of one person, 1 to 10; 0 returns to the default. Owner only. + * + * @generated from rpc mistgate.usernotify.v1.UserNotifyService.SetUserTelegramChatLimit + */ + setUserTelegramChatLimit: { + methodKind: "unary"; + input: typeof SetChatLimitRequestSchema; + output: typeof EmptySchema; + }, +}> = /*@__PURE__*/ + serviceDesc(file_mistgate_usernotify_v1_usernotify, 0); +