+// GetImage downloads a file through the authenticated file endpoint. Errors
+// never include its token or URL, and the body is limited before storage.
+func (b *TelegramAPI) GetImage(ctx context.Context, id string) (data []byte, err error) {
+ var file struct {
+ Path string `json:"file_path"`
+ Size int64 `json:"file_size"`
+ }
+
+ err = b.call(ctx, b.sendTimeout, "getFile", map[string]any{"file_id": id}, &file)
+ if err != nil {
+ return nil, fmt.Errorf("get image file: %w", err)
+ }
+
+ if file.Size > imageMaxBytes {
+ return nil, errImageSize
+ }
+
+ if file.Path == "" || path.Clean(file.Path) != file.Path || strings.HasPrefix(file.Path, "/") || strings.HasPrefix(file.Path, "../") || strings.ContainsAny(file.Path, "?%#\\") {
+ return nil, errors.New("invalid image file path")
+ }
+
+ ctx, cancel := context.WithTimeout(ctx, b.sendTimeout)
+ defer cancel()
+
+ request, err := http.NewRequestWithContext(ctx, http.MethodGet, b.base+"/file/bot"+b.token+"/"+file.Path, nil)
+ if err != nil {
+ return nil, fmt.Errorf("make image request: %s", b.redact(err))
+ }
+
+ response, err := b.http.Do(request)
+ if err != nil {
+ return nil, b.networkError("image download failed", err, b.sendTimeout)
+ }
+
+ defer func() {
+ closeErr := response.Body.Close()
+ if closeErr != nil {
+ err = errors.Join(err, b.networkError("close image download", closeErr, b.sendTimeout))
+ }
+ }()
+
+ if response.StatusCode != http.StatusOK {
+ return nil, &TelegramError{
+ Status: response.StatusCode,
+ Description: http.StatusText(response.StatusCode),
+ }
+ }
+
+ data, err = io.ReadAll(io.LimitReader(response.Body, imageMaxBytes+1))
+ if err != nil {
+ return nil, b.networkError("image cut off", err, b.sendTimeout)
+ }
+
+ if len(data) > imageMaxBytes {
+ return nil, errImageSize
+ }
+
+ return data, nil
+}
+