diff --git a/README.md b/README.md index 38a5112..cc802c4 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,37 @@ $ npx skills add https://github.com/gotd/cli --all $ npx skills add https://github.com/gotd/cli --skill tg ``` +## Inspect and invoke Telegram RPCs + +Use the schema compiled into `tg` for local discovery and invocation. + +```console +$ tg rpc list -o json +$ tg rpc describe messages.sendMedia -o json +$ tg rpc invoke --yes help.getConfig '{}' -o json +``` + +Pass `--schema-cache` to use Telegram Desktop's published TL schema at runtime. +The first request after a five-minute cache window checks for an update. A +valid cached schema remains available if that check fails. Newly published +methods use the same CLI commands when Telegram supports their layer. + +```console +$ tg rpc --schema-cache ~/.cache/tg/api.tl describe messages.getTranscriptionModels -o json +$ tg rpc --schema-cache ~/.cache/tg/api.tl invoke --yes messages.getTranscriptionModels '{"version":0}' -o json +``` + +Arguments use TL field names. Use `{"_":"inputPeerSelf"}` to select a concrete +constructor for an abstract field. Pass 64-bit integers as decimal strings +and byte fields as base64. Runtime mode calculates flags from supplied fields. +Omit false presence flags and flag words such as `flags`. + +Raw calls run with the existing user session and require `--yes` because +they may change Telegram account data. For a source build reusing a session +created by a release binary, use `tg devices` with the release binary to find +the current device's public app ID. Pass that ID as `--linked-app-id` in +runtime mode. Commands such as `tg upload` handle multi-step operations. + ## What you can do Run `tg --help` for the full, grouped command list, or `tg --help` for details. diff --git a/cmd/tg/app.go b/cmd/tg/app.go index 9a8529c..7241b6b 100644 --- a/cmd/tg/app.go +++ b/cmd/tg/app.go @@ -159,6 +159,10 @@ func (a *app) ensureActive() error { // skipConfig reports whether the command runs without a loaded config/session. func skipConfig(cmd *cobra.Command) bool { + switch cmd.CommandPath() { + case "tg " + cmdRPC + " describe", "tg " + cmdRPC + " " + cmdList: + return true + } for c := cmd; c != nil; c = c.Parent() { switch c.Name() { case "init", "docs", "completion", "help", @@ -171,8 +175,10 @@ func skipConfig(cmd *cobra.Command) bool { // runParams configures a client session for connect/run. type runParams struct { - auth authKind - updates bool + auth authKind + updates bool + layer int // Optional schema layer for runtime TL RPCs. + linkedAppID int // Public app ID of a pre-existing session for runtime TL RPCs. // authorize performs interactive authentication when the session is not yet // authorized. If nil, user sessions error with errNotAuthorized and bot // sessions authenticate with the configured token. @@ -191,6 +197,7 @@ func (a *app) optionsFor(st *accountState, rp runParams, d tg.UpdateDispatcher) Device: deviceConfig(), Middlewares: mw, SessionStorage: a.sessionStore(st.label, st.acc, rp.auth.String()), + Layer: rp.layer, } if rp.updates { opts.UpdateHandler = d @@ -214,14 +221,22 @@ func (a *app) connectWith( rp runParams, f func(ctx context.Context, client *telegram.Client, d tg.UpdateDispatcher) error, ) error { + if (rp.layer != 0 || rp.linkedAppID != 0) && + (rp.layer <= 0 || rp.auth != authUser || rp.updates || rp.authorize != nil) { + return errors.New("runtime schema connections require an existing user session without updates") + } var d tg.UpdateDispatcher if rp.updates { d = tg.NewUpdateDispatcher() } - appID, appHash, err := effectiveCreds(st.acc) - if err != nil { - return err + appID, appHash := rp.linkedAppID, "" + if appID == 0 { + var err error + appID, appHash, err = effectiveCreds(st.acc) + if err != nil { + return err + } } client := telegram.NewClient(appID, appHash, a.optionsFor(st, rp, d)) diff --git a/cmd/tg/chats.go b/cmd/tg/chats.go index 187142b..930e6f7 100644 --- a/cmd/tg/chats.go +++ b/cmd/tg/chats.go @@ -162,7 +162,7 @@ func (a *app) newChatsListCmd() *cobra.Command { ) cmd := &cobra.Command{ - Use: "list", + Use: cmdList, Short: "List dialogs with unread counts and flags", Long: `List dialogs (chats) newest-first, with unread counts, pinned/muted/archived flags and a last-message preview.`, diff --git a/cmd/tg/root.go b/cmd/tg/root.go index d214682..10a2db4 100644 --- a/cmd/tg/root.go +++ b/cmd/tg/root.go @@ -103,6 +103,7 @@ below apply to every command.`, a.newChatsCmd(), a.newHistoryCmd(), a.newSendCmd(), + a.newRPCCmd(), a.newReplyCmd(), a.newEditCmd(), a.newDeleteCmd(), diff --git a/cmd/tg/rpc.go b/cmd/tg/rpc.go new file mode 100644 index 0000000..18db5ef --- /dev/null +++ b/cmd/tg/rpc.go @@ -0,0 +1,405 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "reflect" + "sort" + "strconv" + "strings" + + "github.com/spf13/cobra" + + "github.com/gotd/cli/internal/runtimetl" + "github.com/gotd/td/bin" + "github.com/gotd/td/tdp" + "github.com/gotd/td/telegram" + "github.com/gotd/td/tg" +) + +type rpcCatalog struct { + names map[string]uint32 + constructors map[uint32]func() bin.Object + methods map[string]reflect.Method +} + +const cmdRPC = "rpc" + +func rpcKey(name string) string { + return strings.ToLower(strings.ReplaceAll(name, ".", "")) +} + +func telegramRPC() rpcCatalog { + client := reflect.TypeFor[*tg.Client]() + methods := make(map[string]reflect.Method, client.NumMethod()) + for i := range client.NumMethod() { + method := client.Method(i) + if method.Type.NumIn() >= 2 && method.Type.In(1) == reflect.TypeFor[context.Context]() && + method.Type.NumOut() == 2 && method.Type.Out(1) == reflect.TypeFor[error]() { + methods[rpcKey(method.Name)] = method + } + } + return rpcCatalog{tg.NamesMap(), tg.TypesConstructorMap(), methods} +} + +func (c rpcCatalog) object(name string) (bin.Object, error) { + id, ok := c.names[name] + if !ok || c.constructors[id] == nil { + return nil, fmt.Errorf("unknown Telegram schema name %q", name) + } + return c.constructors[id](), nil +} + +func (c rpcCatalog) list() []string { + names := make([]string, 0, len(c.methods)) + for name := range c.names { + if _, ok := c.methods[rpcKey(name)]; !ok { + continue + } + request, err := c.object(name) + if err != nil { + continue + } + if _, _, err := c.method(name, request); err == nil { + names = append(names, name) + } + } + sort.Strings(names) + return names +} + +func (c rpcCatalog) method(name string, request bin.Object) (reflect.Method, reflect.Value, error) { + method, ok := c.methods[rpcKey(name)] + if ok { + fields := request.(tdp.Object).TypeInfo().Fields + switch method.Type.NumIn() { + case 2: + if len(fields) == 0 { + return method, reflect.Value{}, nil + } + case 3: + value := reflect.ValueOf(request) + if method.Type.In(2) == value.Type() { + return method, value, nil + } + // gotd generates direct arguments for some single-field requests. + if len(fields) == 1 { + field := value.Elem().FieldByName(fields[0].Name) + if field.IsValid() && field.Type() == method.Type.In(2) { + return method, field, nil + } + } + } + } + return reflect.Method{}, reflect.Value{}, fmt.Errorf("%q has no callable Telegram RPC binding", name) +} + +type rpcField struct { + Name string `json:"name"` + Type string `json:"type"` + Optional bool `json:"optional"` +} + +type rpcDescription struct { + Name string `json:"name"` + ID uint32 `json:"id"` + Parameters []rpcField `json:"parameters"` + Result string `json:"result,omitempty"` +} + +func (c rpcCatalog) describe(name string) (rpcDescription, error) { + request, err := c.object(name) + if err != nil { + return rpcDescription{}, err + } + info := request.(tdp.Object).TypeInfo() + value := reflect.ValueOf(request).Elem() + result := rpcDescription{Name: name, ID: info.ID, Parameters: make([]rpcField, 0, len(info.Fields))} + for _, field := range info.Fields { + member := value.FieldByName(field.Name) + if member.IsValid() && field.SchemaName != "flags" && field.SchemaName != "flags2" { + result.Parameters = append(result.Parameters, rpcField{field.SchemaName, member.Type().String(), field.Null}) + } + } + if method, _, err := c.method(name, request); err == nil { + result.Result = method.Type.Out(0).String() + } + return result, nil +} + +func jsonObject(data json.RawMessage) (map[string]json.RawMessage, error) { + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil || fields == nil { + return nil, fmt.Errorf("expected a JSON object") + } + return fields, nil +} + +func (c rpcCatalog) decodeObject(data json.RawMessage, object bin.Object) error { + fields, err := jsonObject(data) + if err != nil { + return err + } + value := reflect.ValueOf(object) + for _, field := range object.(tdp.Object).TypeInfo().Fields { + if field.SchemaName == "flags" || field.SchemaName == "flags2" { + continue + } + argument, present := fields[field.SchemaName] + if !present { + if !field.Null { + return fmt.Errorf("missing Telegram argument %q", field.SchemaName) + } + continue + } + member := value.Elem().FieldByName(field.Name) + if err := c.decodeValue(argument, member); err != nil { + return fmt.Errorf("argument %q: %w", field.SchemaName, err) + } + if setter := value.MethodByName("Set" + field.Name); field.Null && setter.IsValid() { + setter.Call([]reflect.Value{member}) + } + delete(fields, field.SchemaName) + } + if len(fields) != 0 { + return fmt.Errorf("unrecognized Telegram arguments") + } + return nil +} + +func (c rpcCatalog) decodeUnion(data json.RawMessage, into reflect.Value) error { + fields, err := jsonObject(data) + if err != nil { + return err + } + var name string + if err := json.Unmarshal(fields["_"], &name); err != nil || name == "" { + return fmt.Errorf("expected a Telegram constructor name in the _ field") + } + object, err := c.object(name) + if err != nil { + return err + } + value := reflect.ValueOf(object) + if !value.Type().AssignableTo(into.Type()) { + return fmt.Errorf("constructor %q does not implement %s", name, into.Type()) + } + delete(fields, "_") + arguments, err := json.Marshal(fields) + if err != nil { + return err + } + if err := c.decodeObject(arguments, object); err != nil { + return err + } + into.Set(value) + return nil +} + +func (c rpcCatalog) decodeValue(data json.RawMessage, into reflect.Value) error { + data = bytes.TrimSpace(data) + if bytes.Equal(data, []byte("null")) { + return fmt.Errorf("omit optional arguments instead of passing null") + } + if !into.IsValid() || !into.CanSet() { + return fmt.Errorf("unsupported Telegram field") + } + switch into.Kind() { + case reflect.Interface: + return c.decodeUnion(data, into) + case reflect.Int, reflect.Int32: + // gotd uses Go int for TL int, which always has 32 wire bits. + var value int32 + if err := json.Unmarshal(data, &value); err != nil { + return err + } + into.SetInt(int64(value)) + return nil + case reflect.Int64, reflect.Uint64: + if bytes.HasPrefix(data, []byte(`"`)) { + return decodeWideInteger(data, into) + } + case reflect.Slice: + if into.Type().Elem().Kind() != reflect.Uint8 { + var items []json.RawMessage + if err := json.Unmarshal(data, &items); err != nil { + return err + } + result := reflect.MakeSlice(into.Type(), len(items), len(items)) + for i, entry := range items { + if err := c.decodeValue(entry, result.Index(i)); err != nil { + return fmt.Errorf("element %d: %w", i, err) + } + } + into.Set(result) + return nil + } + case reflect.Struct: + if object, ok := into.Addr().Interface().(bin.Object); ok { + return c.decodeObject(data, object) + } + case reflect.Pointer: + object := reflect.New(into.Type().Elem()) + if err := c.decodeValue(data, object.Elem()); err != nil { + return err + } + into.Set(object) + return nil + } + return json.Unmarshal(data, into.Addr().Interface()) +} + +func decodeWideInteger(data json.RawMessage, into reflect.Value) error { + var decimal string + if err := json.Unmarshal(data, &decimal); err != nil { + return err + } + if into.Kind() == reflect.Int64 { + value, err := strconv.ParseInt(decimal, 10, 64) + if err != nil { + return fmt.Errorf("invalid signed 64-bit decimal integer") + } + into.SetInt(value) + return nil + } + value, err := strconv.ParseUint(decimal, 10, 64) + if err != nil { + return fmt.Errorf("invalid unsigned 64-bit decimal integer") + } + into.SetUint(value) + return nil +} + +func (c rpcCatalog) invoke(ctx context.Context, api *tg.Client, name, params string) (any, error) { + request, err := c.object(name) + if err != nil { + return nil, err + } + method, argument, err := c.method(name, request) + if err != nil { + return nil, err + } + if err := c.decodeObject(json.RawMessage(params), request); err != nil { + return nil, err + } + arguments := []reflect.Value{reflect.ValueOf(api), reflect.ValueOf(ctx)} + if argument.IsValid() { + arguments = append(arguments, argument) + } + result := method.Func.Call(arguments) + if !result[1].IsNil() { + return nil, result[1].Interface().(error) + } + return result[0].Interface(), nil +} + +func (a *app) newRPCCmd() *cobra.Command { + root := &cobra.Command{ + Use: cmdRPC, + Short: "Inspect or invoke the Telegram RPC methods in the installed schema", + GroupID: groupMessaging, + } + var schemaCache string + root.PersistentFlags().StringVar(&schemaCache, "schema-cache", "", + "Automatically refresh and use this cache of the published Telegram Desktop API schema") + var linkedAppID int + root.PersistentFlags().IntVar(&linkedAppID, "linked-app-id", 0, + "Public app ID from 'tg devices' for an existing user session") + list := &cobra.Command{ + Use: cmdList, + Short: "List callable Telegram RPC methods in the installed schema", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + if schemaCache != "" { + schema, err := runtimetl.Refresh(cmd.Context(), schemaCache) + if err != nil { + return err + } + return a.printer.Emit(schema.Names()) + } + return a.printer.Emit(telegramRPC().list()) + }, + } + describe := &cobra.Command{ + Use: "describe ", + Short: "Describe a Telegram TL method or constructor", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + if schemaCache != "" { + schema, err := runtimetl.Refresh(cmd.Context(), schemaCache) + if err != nil { + return err + } + description, err := schema.Describe(args[0]) + if err != nil { + return err + } + return a.printer.Emit(description) + } + description, err := telegramRPC().describe(args[0]) + if err != nil { + return err + } + return a.printer.Emit(description) + }, + } + var confirmed bool + invoke := &cobra.Command{ + Use: "invoke ", + Short: "Execute a raw Telegram RPC as the current user", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + if !confirmed { + return fmt.Errorf("raw RPCs can change account data; pass --yes to proceed") + } + if linkedAppID < 0 || linkedAppID > 2147483647 || (linkedAppID != 0 && schemaCache == "") { + return fmt.Errorf("--linked-app-id requires a positive TL int and --schema-cache") + } + if schemaCache != "" { + return a.invokeRuntimeRPC(cmd.Context(), schemaCache, args[0], args[1], linkedAppID) + } + return a.run(cmd.Context(), runParams{auth: authUser}, func(ctx context.Context, api *tg.Client) error { + result, err := telegramRPC().invoke(ctx, api, args[0], args[1]) + if err != nil { + return err + } + return a.printer.Emit(result) + }) + }, + } + invoke.Flags().BoolVar(&confirmed, "yes", false, "Confirm execution of the raw RPC") + root.AddCommand(list, describe, invoke) + return root +} + +func (a *app) invokeRuntimeRPC(ctx context.Context, cache, name, params string, linkedAppID int) error { + schema, err := runtimetl.Refresh(ctx, cache) + if err != nil { + return err + } + call, err := schema.Prepare(name, json.RawMessage(params)) + if err != nil { + return err + } + if err := a.ensureActive(); err != nil { + return err + } + exists, err := a.sessionStore(a.active.label, a.active.acc, kindUser).Exists(ctx) + if err != nil { + return err + } + if !exists { + return errNotAuthorized + } + // The linked session already contains its authorization key. The public + // app ID is sufficient for initConnection, and this path never logs in. + return a.connect(ctx, runParams{auth: authUser, layer: schema.Layer, linkedAppID: linkedAppID}, + func(ctx context.Context, client *telegram.Client, _ tg.UpdateDispatcher) error { + if err := client.Invoke(ctx, call, call); err != nil { + return err + } + return a.printer.Emit(call.Response) + }) +} diff --git a/cmd/tg/rpc_test.go b/cmd/tg/rpc_test.go new file mode 100644 index 0000000..0538a55 --- /dev/null +++ b/cmd/tg/rpc_test.go @@ -0,0 +1,175 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "path/filepath" + "sort" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/gotd/td/bin" + "github.com/gotd/td/telegram" + "github.com/gotd/td/tg" +) + +func TestRuntimeRPCDisablesAutomaticAuthorizationAndUpdates(t *testing.T) { + for _, params := range []runParams{ + {layer: 234, auth: authBot}, + {layer: 234, updates: true}, + {layer: 234, authorize: func(context.Context, *telegram.Client, tg.UpdateDispatcher) error { + t.Fatal("runtime RPC attempted automatic authorization") + return nil + }}, + {linkedAppID: 12345}, + } { + require.ErrorContains(t, newApp().connectWith(t.Context(), nil, params, nil), + "runtime schema connections require an existing user session without updates") + } +} + +func TestRPCListWithoutConfig(t *testing.T) { + root := newRootCmd() + var output bytes.Buffer + root.SetOut(&output) + root.SetArgs([]string{"--config", filepath.Join(t.TempDir(), "missing.yaml"), + "--output", "json", "rpc", "list"}) + require.NoError(t, root.Execute()) + + var response struct { + Data []string `json:"data"` + } + require.NoError(t, json.Unmarshal(output.Bytes(), &response)) + require.True(t, sort.StringsAreSorted(response.Data)) + require.Contains(t, response.Data, "help.getConfig") + require.Contains(t, response.Data, "messages.sendMedia") + require.NotContains(t, response.Data, "inputPeerSelf") +} + +func TestRPCDescribe(t *testing.T) { + config, err := telegramRPC().describe("help.getConfig") + require.NoError(t, err) + require.Equal(t, uint32(tg.HelpGetConfigRequestTypeID), config.ID) + require.Empty(t, config.Parameters) + require.Equal(t, "*tg.Config", config.Result) + + send, err := telegramRPC().describe("messages.sendMedia") + require.NoError(t, err) + require.Contains(t, send.Parameters, rpcField{Name: "peer", Type: "tg.InputPeerClass"}) + require.Contains(t, send.Parameters, rpcField{Name: "silent", Type: "bool", Optional: true}) + require.NotEmpty(t, send.Result) +} + +func TestRPCDescribeWithoutConfig(t *testing.T) { + root := newRootCmd() + var output bytes.Buffer + root.SetOut(&output) + root.SetArgs([]string{"--config", filepath.Join(t.TempDir(), "missing.yaml"), + "--output", "json", "rpc", "describe", "messages.sendMedia"}) + require.NoError(t, root.Execute()) + + var response struct { + Data rpcDescription `json:"data"` + } + require.NoError(t, json.Unmarshal(output.Bytes(), &response)) + require.Equal(t, "messages.sendMedia", response.Data.Name) +} + +func TestRPCInvokeMediaWithSchemaNames(t *testing.T) { + var verified bool + api := newFuncAPI(t, func(input bin.Encoder) (bin.Encoder, error) { + request := input.(*tg.MessagesSendMediaRequest) + require.IsType(t, &tg.InputPeerSelf{}, request.Peer) + media := request.Media.(*tg.InputMediaUploadedDocument) + require.Equal(t, "audio/mpeg", media.MimeType) + require.Equal(t, "clip.mp3", media.File.(*tg.InputFile).Name) + require.Equal(t, int64(901234567890123456), request.RandomID) + require.Equal(t, "Test clip", request.Message) + verified = true + return &tg.UpdatesTooLong{}, nil + }) + result, err := telegramRPC().invoke(context.Background(), api, "messages.sendMedia", `{ + "peer":{"_":"inputPeerSelf"}, + "media":{"_":"inputMediaUploadedDocument", + "file":{"_":"inputFile","id":1,"parts":1,"name":"clip.mp3","md5_checksum":""}, + "mime_type":"audio/mpeg", + "attributes":[{"_":"documentAttributeFilename","file_name":"clip.mp3"}]}, + "message":"Test clip","random_id":901234567890123456 + }`) + require.NoError(t, err) + require.True(t, verified) + require.IsType(t, &tg.UpdatesTooLong{}, result) +} + +func TestRPCInvokeDirectArgument(t *testing.T) { + api := newFuncAPI(t, func(input bin.Encoder) (bin.Encoder, error) { + request := input.(*tg.UsersGetFullUserRequest) + require.IsType(t, &tg.InputUserSelf{}, request.ID) + return &tg.UsersUserFull{}, nil + }) + result, err := telegramRPC().invoke(context.Background(), api, "users.getFullUser", + `{"id":{"_":"inputUserSelf"}}`) + require.NoError(t, err) + require.IsType(t, &tg.UsersUserFull{}, result) +} + +func TestRPCInvokeWithExactWideIntegers(t *testing.T) { + api := newFuncAPI(t, func(input bin.Encoder) (bin.Encoder, error) { + request := input.(*tg.MessagesSendMessageRequest) + peer := request.Peer.(*tg.InputPeerChannel) + require.Equal(t, int64(9007199254740993), peer.ChannelID) + require.Equal(t, int64(-9223372036854775808), peer.AccessHash) + require.Equal(t, int64(9223372036854775807), request.RandomID) + return &tg.UpdatesTooLong{}, nil + }) + result, err := telegramRPC().invoke(context.Background(), api, "messages.sendMessage", `{ + "peer":{"_":"inputPeerChannel","channel_id":"9007199254740993","access_hash":"-9223372036854775808"}, + "message":"A test message", "random_id":"9223372036854775807" + }`) + require.NoError(t, err) + require.IsType(t, &tg.UpdatesTooLong{}, result) +} + +func TestRPCRejectsInvalidRequests(t *testing.T) { + api := newFuncAPI(t, func(_ bin.Encoder) (bin.Encoder, error) { + t.Fatal("invalid RPC reached the network") + return nil, nil + }) + for _, tc := range []struct { + method string + args string + }{ + {"bogus.method", "{}"}, + {"inputPeerSelf", "{}"}, + {"help.getConfig", `{"unexpected":1}`}, + {"messages.sendMedia", `{"peer":{"_":"inputFile"}}`}, + {"messages.sendMedia", `{"peer":null}`}, + {"messages.sendMessage", `{"peer":{"_":"inputPeerSelf"},"message":"test","random_id":"9223372036854775808"}`}, + {"users.getUsers", `{"id":[{"_":"inputUserSelf"},{"_":"inputPeerSelf"}]}`}, + } { + t.Run(tc.method+tc.args, func(t *testing.T) { + _, err := telegramRPC().invoke(context.Background(), api, tc.method, tc.args) + require.Error(t, err) + }) + } +} + +func TestRPCRejectsTLIntOverflow(t *testing.T) { + catalog := telegramRPC() + for _, tc := range []struct { + method string + args string + }{ + {"messages.getHistory", `{"peer":{"_":"inputPeerSelf"},"offset_id":4294967297, + "offset_date":0,"add_offset":0,"limit":1,"max_id":0,"min_id":0,"hash":0}`}, + {"messages.getMessagesViews", `{"peer":{"_":"inputPeerSelf"},"id":[4294967297],"increment":false}`}, + } { + t.Run(tc.method, func(t *testing.T) { + request, err := catalog.object(tc.method) + require.NoError(t, err) + require.ErrorContains(t, catalog.decodeObject([]byte(tc.args), request), "int32") + }) + } +} diff --git a/go.mod b/go.mod index b373b81..cba51c3 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( github.com/schollz/progressbar/v3 v3.19.1 github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.1.0 + github.com/stretchr/testify v1.12.1 go.uber.org/zap v1.28.0 golang.org/x/net v0.63.0 golang.org/x/sync v0.25.0 @@ -45,7 +46,6 @@ require ( github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/segmentio/asm v1.2.1 // indirect github.com/shopspring/decimal v1.4.0 // indirect - github.com/stretchr/testify v1.12.1 // indirect github.com/yuin/goldmark v1.8.5 // indirect go.opentelemetry.io/otel v1.47.0 // indirect go.opentelemetry.io/otel/metric v1.47.0 // indirect diff --git a/internal/runtimetl/codec.go b/internal/runtimetl/codec.go new file mode 100644 index 0000000..99712be --- /dev/null +++ b/internal/runtimetl/codec.go @@ -0,0 +1,294 @@ +package runtimetl + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "fmt" + "math" + "strconv" + "strings" + "unicode/utf8" + + "github.com/gotd/td/bin" +) + +const ( + maxDepth = 64 + maxVector = 16_384 + maxResponse = 2 << 20 +) + +// Call implements gotd's request encoder and response decoder for one TL method. +type Call struct { + schema *Schema + id uint32 + result string + request []byte + Response any +} + +func (s *Schema) Prepare(name string, arguments json.RawMessage) (*Call, error) { + method, ok := s.methods[name] + if !ok { + return nil, fmt.Errorf("unknown Telegram method %q", name) + } + var out bin.Buffer + result, err := s.writeObject(&out, method, arguments, 0) + if err != nil { + return nil, err + } + return &Call{schema: s, id: method.ID, request: out.Buf, result: result}, nil +} + +func (c *Call) TypeID() uint32 { return c.id } + +func (c *Call) Encode(out *bin.Buffer) error { + out.Put(c.request) + return nil +} + +func (c *Call) Decode(input *bin.Buffer) error { + if input.Len() > maxResponse { + return fmt.Errorf("cannot decode Telegram responses over 2 MiB") + } + decoded, err := c.schema.readValue(input, c.result, 0) + if err != nil { + return err + } + if input.Len() != 0 { + return fmt.Errorf("unexpected trailing TL response data") + } + c.Response = decoded + return nil +} + +func (s *Schema) writeObject(out *bin.Buffer, def Definition, arguments json.RawMessage, depth int) (string, error) { + var args map[string]json.RawMessage + if depth > maxDepth || json.Unmarshal(arguments, &args) != nil || args == nil { + return "", fmt.Errorf("expected a TL argument object") + } + flags := make(map[string]uint32) + for _, field := range def.Fields { + if _, present := args[field.Name]; present && field.flag != "" { + flags[field.flag] |= field.bit + } + } + out.PutID(def.ID) + result := def.Result + for _, field := range def.Fields { + if field.Type == "#" { + out.PutUint32(flags[field.Name]) + continue + } + if field.flag != "" && flags[field.flag]&field.bit == 0 { + continue + } + raw, present := args[field.Name] + if !present { + return "", fmt.Errorf("missing Telegram argument %q", field.Name) + } + delete(args, field.Name) + nested, err := s.writeValue(out, field.Type, raw, depth+1) + if err != nil { + return "", fmt.Errorf("%s: %w", field.Name, err) + } + if field.Type == tlQuery && result == "X" { + result = nested + } + } + if len(args) != 0 { + return "", fmt.Errorf("unrecognized Telegram arguments") + } + if result == "X" { + return "", fmt.Errorf("could not infer the nested RPC result type") + } + return result, nil +} + +func (s *Schema) writeValue(out *bin.Buffer, typ string, raw json.RawMessage, depth int) (string, error) { + if depth > maxDepth || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { + return "", fmt.Errorf("unexpected null or nesting limit") + } + if item, vector := vectorItem(typ); vector { + var list []json.RawMessage + if json.Unmarshal(raw, &list) != nil || len(list) > maxVector { + return "", fmt.Errorf("expected a TL vector") + } + out.PutVectorHeader(len(list)) + for _, value := range list { + if _, err := s.writeValue(out, item, value, depth+1); err != nil { + return "", err + } + } + return "", nil + } + switch typ { + case "int": + var value int32 + if err := json.Unmarshal(raw, &value); err != nil { + return "", fmt.Errorf("expected a 32-bit integer") + } + out.PutInt32(value) + case "long": + var decimal string + if json.Unmarshal(raw, &decimal) != nil { + decimal = string(raw) + } + value, err := strconv.ParseInt(decimal, 10, 64) + if err != nil { + return "", fmt.Errorf("expected a signed 64-bit decimal") + } + out.PutLong(value) + case "double": + var value float64 + if err := json.Unmarshal(raw, &value); err != nil { + return "", fmt.Errorf("expected a double") + } + out.PutDouble(value) + case "string": + var value string + if err := json.Unmarshal(raw, &value); err != nil { + return "", fmt.Errorf("expected a string") + } + out.PutString(value) + case tlBytes, tlInt128, tlInt256: + return "", writeBinary(out, typ, raw) + case tlBool, tlPresence: + var value bool + if json.Unmarshal(raw, &value) != nil || (typ == tlPresence && !value) { + return "", fmt.Errorf("expected a TL boolean (omit a false presence flag)") + } + if typ == tlBool { + out.PutBool(value) + } + default: + return s.writeNamedObject(out, typ, raw, depth) + } + return "", nil +} + +func writeBinary(out *bin.Buffer, typ string, raw json.RawMessage) error { + var encoded string + if json.Unmarshal(raw, &encoded) != nil { + return fmt.Errorf("expected a base64 string") + } + value, err := base64.StdEncoding.Strict().DecodeString(encoded) + if err != nil || (typ == tlInt128 && len(value) != 16) || (typ == tlInt256 && len(value) != 32) { + return fmt.Errorf("invalid TL bytes") + } + if typ == tlBytes { + out.PutBytes(value) + } else { + out.Put(value) + } + return nil +} + +func (s *Schema) writeNamedObject(out *bin.Buffer, typ string, raw json.RawMessage, depth int) (string, error) { + var fields map[string]json.RawMessage + if json.Unmarshal(raw, &fields) != nil { + return "", fmt.Errorf("expected a TL object") + } + var name string + if json.Unmarshal(fields["_"], &name) != nil || name == "" { + return "", fmt.Errorf("expected a TL name in the _ field") + } + delete(fields, "_") + def, ok := s.constructors[name] + if typ == tlQuery { + def, ok = s.methods[name] + } + if !ok || (typ != tlQuery && def.Result != typ) { + return "", fmt.Errorf("incompatible TL name %q for %s", name, typ) + } + args, err := json.Marshal(fields) + if err != nil { + return "", err + } + return s.writeObject(out, def, args, depth+1) +} + +func vectorItem(typ string) (string, bool) { + if strings.HasPrefix(typ, "Vector<") && strings.HasSuffix(typ, ">") { + return typ[7 : len(typ)-1], true + } + return "", false +} + +func (s *Schema) readValue(input *bin.Buffer, typ string, depth int) (any, error) { + if depth > maxDepth { + return nil, fmt.Errorf("cannot decode Telegram responses above the nesting limit") + } + if item, vector := vectorItem(typ); vector { + n, err := input.VectorHeader() + if err != nil || n < 0 || n > maxVector || n > input.Len()/4 { + return nil, fmt.Errorf("invalid TL vector response") + } + values := make([]any, n) + for i := range values { + values[i], err = s.readValue(input, item, depth+1) + if err != nil { + return nil, err + } + } + return values, nil + } + switch typ { + case "int": + return input.Int32() + case "long": + value, err := input.Long() + return strconv.FormatInt(value, 10), err + case "double": + value, err := input.Double() + if err == nil && (math.IsNaN(value) || math.IsInf(value, 0)) { + return nil, fmt.Errorf("nonfinite TL double") + } + return value, err + case "string": + value, err := input.String() + if err == nil && !utf8.ValidString(value) { + return nil, fmt.Errorf("invalid TL UTF-8") + } + return value, err + case tlBytes: + return input.Bytes() + case tlInt128: + data, err := input.Int128() + return data[:], err + case tlInt256: + data, err := input.Int256() + return data[:], err + case tlBool: + return input.Bool() + case tlPresence: + return true, nil + default: + return s.readObject(input, typ, depth) + } +} + +func (s *Schema) readObject(input *bin.Buffer, typ string, depth int) (any, error) { + id, err := input.ID() + if err != nil { + return nil, err + } + def, ok := s.ids[id] + if !ok || def.Result != typ || s.constructors[def.Name].ID != id { + return nil, fmt.Errorf("unexpected TL constructor 0x%08x for %s", id, typ) + } + fields := map[string]any{"_": def.Name} + flags := make(map[string]uint32) + for _, field := range def.Fields { + if field.Type == "#" { + flags[field.Name], err = input.Uint32() + } else if field.flag == "" || flags[field.flag]&field.bit != 0 { + fields[field.Name], err = s.readValue(input, field.Type, depth+1) + } + if err != nil { + return nil, fmt.Errorf("%s.%s: %w", def.Name, field.Name, err) + } + } + return fields, nil +} diff --git a/internal/runtimetl/refresh.go b/internal/runtimetl/refresh.go new file mode 100644 index 0000000..d4cd278 --- /dev/null +++ b/internal/runtimetl/refresh.go @@ -0,0 +1,114 @@ +package runtimetl + +import ( + "context" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "time" +) + +const ( + sourceURL = "https://raw.githubusercontent.com/telegramdesktop/tdesktop/dev/Telegram/SourceFiles/mtproto/scheme/api.tl" + maxSchema = 2 << 20 + refreshAfter = 5 * time.Minute +) + +func Refresh(ctx context.Context, path string) (*Schema, error) { + return refresh(ctx, path, time.Now(), func(ctx context.Context) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, sourceURL, http.NoBody) + if err != nil { + return nil, err + } + client := &http.Client{ + Timeout: 7 * time.Second, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("fetch Telegram Desktop schema: HTTP %d", resp.StatusCode) + } + return readBounded(resp.Body) + }) +} + +func refresh(ctx context.Context, path string, now time.Time, fetch func(context.Context) ([]byte, error)) (*Schema, error) { + previous, stamp := readCache(path) + if previous != nil && !stamp.After(now) && now.Sub(stamp) < refreshAfter { + return previous, nil + } + data, err := fetch(ctx) + var next *Schema + if err == nil { + next, err = Parse(data) + } + if latest, _ := readCache(path); latest != nil { + previous = latest + } + if err != nil || (previous != nil && previous.Layer > next.Layer) { + if previous == nil { + return nil, err + } + // A failed refresh starts a new retry window without replacing the cache. + _ = os.Chtimes(path, now, now) + return previous, nil + } + // The freshly fetched schema is usable even when the cache cannot be written. + _ = writeCache(path, data) + return next, nil +} + +func readBounded(reader io.Reader) ([]byte, error) { + data, err := io.ReadAll(io.LimitReader(reader, maxSchema+1)) + if err == nil && len(data) > maxSchema { + return nil, fmt.Errorf("cannot read Telegram schemas over 2 MiB") + } + return data, err +} + +func readCache(path string) (*Schema, time.Time) { + file, err := os.Open(filepath.Clean(path)) + if err != nil { + return nil, time.Time{} + } + defer func() { _ = file.Close() }() + info, err := file.Stat() + if err != nil || !info.Mode().IsRegular() || info.Size() > maxSchema { + return nil, time.Time{} + } + data, err := readBounded(file) + if err != nil { + return nil, time.Time{} + } + schema, err := Parse(data) + if err != nil { + return nil, time.Time{} + } + return schema, info.ModTime() +} + +func writeCache(path string, data []byte) error { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + file, err := os.CreateTemp(filepath.Dir(path), ".telegram-api-") + if err != nil { + return err + } + defer func() { _ = os.Remove(file.Name()) }() + _, writeErr := file.Write(data) + closeErr := file.Close() + if writeErr != nil { + return writeErr + } + if closeErr != nil { + return closeErr + } + return os.Rename(file.Name(), path) +} diff --git a/internal/runtimetl/runtime_test.go b/internal/runtimetl/runtime_test.go new file mode 100644 index 0000000..2a62c5b --- /dev/null +++ b/internal/runtimetl/runtime_test.go @@ -0,0 +1,147 @@ +package runtimetl + +import ( + "bytes" + "context" + "errors" + "math" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/gotd/td/bin" +) + +const published = `// LAYER 234 +item#123 data:long = Item; +result#456 flags:# yes:flags.1?true items:Vector text:flags.2?string = Result; +---functions--- +example.invoke#789 flags:# input:Item text:flags.2?string other:flags.2?int = Result; +invokeWithoutUpdates#bf9459b7 {X:Type} query:!X = X; +` + +func TestRuntimeRPCEncodingAndDecoding(t *testing.T) { + s, err := Parse([]byte(published)) + if err != nil { + t.Fatal(err) + } + call, err := s.Prepare("invokeWithoutUpdates", + []byte(`{"query":{"_":"example.invoke","input":{"_":"item","data":"9007199254740993"},"text":"hello","other":7}}`)) + if err != nil { + t.Fatal(err) + } + var wire, expected bin.Buffer + expected.PutID(0xbf9459b7) + expected.PutID(0x789) + expected.PutUint32(4) + expected.PutID(0x123) + expected.PutLong(9007199254740993) + expected.PutString("hello") + expected.PutInt32(7) + if err := call.Encode(&wire); err != nil || !bytes.Equal(wire.Buf, expected.Buf) { + t.Fatalf("wrong encoded request: %x", wire.Buf) + } + wire.Reset() + wire.PutID(0x456) + wire.PutUint32(2) + wire.PutVectorHeader(1) + wire.PutID(0x123) + wire.PutLong(math.MinInt64) + if err := call.Decode(&wire); err != nil { + t.Fatal(err) + } + decoded := call.Response.(map[string]any) + if decoded["yes"] != true || + decoded["items"].([]any)[0].(map[string]any)["data"] != "-9223372036854775808" { + t.Fatalf("unexpected result: %#v", decoded) + } + if _, err := s.Prepare("example.invoke", []byte(`{"input":{"_":"item","data":"1"},"text":"missing partner"}`)); err == nil || + !strings.Contains(err.Error(), `missing Telegram argument "other"`) { + t.Fatalf("expected missing flag partner error, got %v", err) + } + if _, err := s.Prepare("example.invoke", + []byte(`{"input":{"_":"example.invoke","input":{"_":"item","data":"1"}}}`)); err == nil || + !strings.Contains(err.Error(), `incompatible TL name "example.invoke" for Item`) { + t.Fatalf("expected incompatible constructor error, got %v", err) + } +} + +func TestDecodeFileChunkWithFraming(t *testing.T) { + s, err := Parse([]byte(`// LAYER 234 +file#abc data:bytes = File; +---functions--- +example.getFile#def = File; +`)) + if err != nil { + t.Fatal(err) + } + call, err := s.Prepare("example.getFile", []byte("{}")) + if err != nil { + t.Fatal(err) + } + chunk := bytes.Repeat([]byte{0x42}, 1<<20) + var wire bin.Buffer + wire.PutID(0xabc) + wire.PutBytes(chunk) + if err := call.Decode(&wire); err != nil { + t.Fatal(err) + } + decoded := call.Response.(map[string]any)["data"].([]byte) + if !bytes.Equal(decoded, chunk) { + t.Fatalf("file payload mismatch: decoded %d bytes", len(decoded)) + } +} + +func TestRefreshIntroducesMethodAndKeepsLastGoodSchema(t *testing.T) { + cache := filepath.Join(t.TempDir(), "telegram-api.tl") + now := time.Now() + current := published + fetch := func(context.Context) ([]byte, error) { return []byte(current), nil } + s, err := refresh(t.Context(), cache, now, fetch) + if err != nil || s.Layer != 234 { + t.Fatalf("initial refresh: %v", err) + } + current = strings.Replace(published, "234", "235", 1) + "example.future#abc = Bool;\n" + s, err = refresh(t.Context(), cache, now.Add(6*time.Minute), fetch) + if err != nil || s.Layer != 235 || !slices.Contains(s.Names(), "example.future") { + t.Fatalf("updating schema: %v", err) + } + if _, err := s.Prepare("example.future", []byte("{}")); err != nil { + t.Fatal(err) + } + for i, old := range []string{published, "unsupported schema"} { + current = old + s, err = refresh(t.Context(), cache, now.Add(time.Duration(12+i*6)*time.Minute), fetch) + if err != nil || s.Layer != 235 { + t.Fatalf("downgraded the last valid schema: %v", err) + } + } + s, err = refresh(t.Context(), cache, now.Add(24*time.Minute), + func(context.Context) ([]byte, error) { return nil, errors.New("offline") }) + if err != nil || s.Layer != 235 { + t.Fatalf("lost last valid schema when offline: %v", err) + } + st, err := os.Stat(cache) + if err != nil || st.Mode().Perm()&0o077 != 0 { + t.Fatalf("cache permissions: %v", err) + } + if _, err := refresh(t.Context(), cache, now.Add(25*time.Minute), + func(context.Context) ([]byte, error) { + t.Fatal("re-fetched within the failed refresh retry window") + return nil, nil + }); err != nil { + t.Fatal(err) + } +} + +func TestRefreshWithoutWritableCache(t *testing.T) { + path := t.TempDir() // A directory cannot be atomically replaced by the schema file. + s, err := refresh(t.Context(), path, time.Now(), + func(context.Context) ([]byte, error) { return []byte(published), nil }) + if err != nil || s.Layer != 234 { + t.Fatalf("fetched schema should work without a cache: %v", err) + } +} diff --git a/internal/runtimetl/schema.go b/internal/runtimetl/schema.go new file mode 100644 index 0000000..db51262 --- /dev/null +++ b/internal/runtimetl/schema.go @@ -0,0 +1,178 @@ +// Package runtimetl interprets the published Telegram Desktop API schema. +package runtimetl + +import ( + "bufio" + "bytes" + "fmt" + "math/bits" + "regexp" + "slices" + "strconv" + "strings" +) + +type Field struct { + Name string `json:"name"` + Type string `json:"type"` + flag string + bit uint32 +} + +type Definition struct { + Name string `json:"name"` + ID uint32 `json:"id"` + Fields []Field `json:"parameters"` + Result string `json:"result"` +} + +type Schema struct { + Layer int + methods map[string]Definition + constructors map[string]Definition + ids map[uint32]Definition +} + +const ( + tlQuery = "!X" + tlBytes = "bytes" + tlBool = "Bool" + tlPresence = "true" + tlInt128 = "int128" + tlInt256 = "int256" +) + +var ( + layerLine = regexp.MustCompile(`^// LAYER (\d+)$`) + tlName = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)?$`) +) + +func Parse(input []byte) (*Schema, error) { + s := &Schema{ + methods: map[string]Definition{}, constructors: map[string]Definition{}, + ids: map[uint32]Definition{}, + } + methods := false + lineNo := 0 + scan := bufio.NewScanner(bytes.NewReader(input)) + for scan.Scan() { + lineNo++ + line := strings.TrimSpace(scan.Text()) + if match := layerLine.FindStringSubmatch(line); match != nil { + layer, err := strconv.Atoi(match[1]) + if err != nil || layer <= 0 || s.Layer != 0 { + return nil, fmt.Errorf("invalid layer at line %d", lineNo) + } + s.Layer = layer + } + line, _, _ = strings.Cut(line, "//") + line = strings.TrimSpace(line) + switch line { + case "", "vector#1cb5c415 {t:Type} # [ t ] = Vector t;": + continue + case "---functions---": + methods = true + continue + case "---types---": + methods = false + continue + } + entry, err := parseDefinition(line) + if err != nil { + return nil, fmt.Errorf("schema line %d: %w", lineNo, err) + } + if _, exists := s.ids[entry.ID]; exists { + return nil, fmt.Errorf("duplicate TL ID at line %d", lineNo) + } + entries := s.constructors + if methods { + entries = s.methods + } + if _, exists := entries[entry.Name]; exists { + return nil, fmt.Errorf("duplicate TL name at line %d", lineNo) + } + entries[entry.Name] = entry + s.ids[entry.ID] = entry + } + if err := scan.Err(); err != nil { + return nil, err + } + if s.Layer == 0 || len(s.methods) == 0 || len(s.constructors) == 0 { + return nil, fmt.Errorf("incomplete Telegram API schema") + } + return s, nil +} + +func parseDefinition(line string) (Definition, error) { + left, right, ok := strings.Cut(line, "=") + head := strings.Fields(left) + result, end := strings.CutSuffix(strings.TrimSpace(right), ";") + if !ok || !end || len(head) == 0 || !validType(strings.TrimSpace(result)) { + return Definition{}, fmt.Errorf("invalid TL definition") + } + name, hexID, _ := strings.Cut(head[0], "#") + id, err := strconv.ParseUint(hexID, 16, 32) + if !tlName.MatchString(name) || err != nil { + return Definition{}, fmt.Errorf("invalid TL name or ID") + } + entry := Definition{Name: name, ID: uint32(id), Result: strings.TrimSpace(result), Fields: []Field{}} + seen := make(map[string]string, len(head)-1) + for _, token := range head[1:] { + if token == "{X:Type}" { + continue + } + key, typ, _ := strings.Cut(token, ":") + if _, duplicate := seen[key]; duplicate || !tlName.MatchString(key) || typ == "" { + return Definition{}, fmt.Errorf("invalid TL parameter") + } + field := Field{Name: key, Type: typ} + if mask, optional, found := strings.Cut(typ, "?"); found { + flag, bit, _ := strings.Cut(mask, ".") + value, err := strconv.ParseUint(bit, 10, 5) + if err != nil || seen[flag] != "#" { + return Definition{}, fmt.Errorf("invalid TL flag reference") + } + field.flag, field.bit, field.Type = flag, uint32(1)<") { + value = value[7 : len(value)-1] + } + return value == "#" || value == tlQuery || tlName.MatchString(value) +} + +func (s *Schema) Names() []string { + names := make([]string, 0, len(s.methods)) + for name := range s.methods { + names = append(names, name) + } + slices.Sort(names) + return names +} + +func (s *Schema) Describe(name string) (Definition, error) { + entry, ok := s.methods[name] + if !ok { + entry, ok = s.constructors[name] + } + if !ok { + return Definition{}, fmt.Errorf("unknown Telegram schema name %q", name) + } + entry.Fields = slices.Clone(entry.Fields) + for i := range entry.Fields { + field := &entry.Fields[i] + if field.flag != "" { + field.Type = fmt.Sprintf("%s.%d?%s", field.flag, bits.TrailingZeros32(field.bit), field.Type) + } + } + return entry, nil +}