Phase 1: core bot

Link in, card, download, send, in private chats and groups.

- cmd/core with an embedded download worker
- Telegram front end on telego v1.13.0 (Bot API 10.4): link card with
  thumbnail and format buttons, one live status message, /dl /audio /thumb
  /info /queue /cancel, group support with requester-only buttons
- Database backed queue: paid and free lanes, leases with heartbeats, one
  automatic retry, cancel, queue position and wait estimate
- yt-dlp and ffprobe behind a Runner interface with classified, redacted
  errors mapped to friendly messages
- SQLite via modernc with goose migrations, portable schema
- Local file storage behind a Storage interface
- go-i18n with an English catalog, no literal text in handlers
- Free tier limits enforced before queueing and again on the real file
- Bot token and webhook secret are stripped from all log output
- Tests: URL parsing, job lifecycle, worker, yt-dlp wrapper, and end to end
  flows against a fake Bot API server; opt-in test with the real yt-dlp

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 07:33:32 +00:00
co-authored by Claude Fable 5.2
commit 3b361c17a1
63 changed files with 10715 additions and 0 deletions
+175
View File
@@ -0,0 +1,175 @@
// Package links finds, validates and redacts URLs in chat messages.
package links
import (
"errors"
"net"
"net/url"
"regexp"
"strings"
"unicode/utf16"
)
// Errors returned by Normalize.
var (
ErrNotURL = errors.New("links: not a url")
ErrScheme = errors.New("links: only http and https are allowed")
ErrPrivateHost = errors.New("links: host is local or private")
)
// Entity is the part of a Telegram message entity that matters here.
// Offset and Length are in UTF-16 code units, as Telegram sends them.
type Entity struct {
Type string
Offset int
Length int
URL string
}
var urlRe = regexp.MustCompile(`(?i)\bhttps?://[^\s<>"'` + "`" + `]+`)
// Extract returns the URLs found in a message, in order, without duplicates.
// Telegram entities are trusted first because they also catch links without
// a scheme (youtu.be/abc) and text links. A regular expression is the
// fallback for clients that send no entities.
func Extract(text string, entities []Entity) []string {
var out []string
seen := map[string]bool{}
add := func(raw string) {
u, err := Normalize(raw)
if err != nil || seen[u] {
return
}
seen[u] = true
out = append(out, u)
}
if len(entities) > 0 {
units := utf16.Encode([]rune(text))
for _, e := range entities {
switch e.Type {
case "text_link":
add(e.URL)
case "url":
if e.Offset < 0 || e.Length <= 0 || e.Offset+e.Length > len(units) {
continue
}
add(string(utf16.Decode(units[e.Offset : e.Offset+e.Length])))
}
}
}
if len(out) == 0 {
for _, m := range urlRe.FindAllString(text, -1) {
add(m)
}
}
return out
}
// Normalize validates a raw link and returns a cleaned form. It adds https
// when the scheme is missing, lowercases the host, drops the fragment and
// trailing punctuation, and rejects local or private hosts.
func Normalize(raw string) (string, error) {
raw = strings.TrimSpace(raw)
raw = strings.TrimRight(raw, ".,;:!?)]}>\"'")
if raw == "" {
return "", ErrNotURL
}
if !strings.Contains(raw, "://") {
if strings.ContainsAny(raw, " \t\n") || !strings.Contains(raw, ".") {
return "", ErrNotURL
}
raw = "https://" + raw
}
u, err := url.Parse(raw)
if err != nil {
return "", ErrNotURL
}
u.Scheme = strings.ToLower(u.Scheme)
if u.Scheme != "http" && u.Scheme != "https" {
return "", ErrScheme
}
host := strings.ToLower(u.Hostname())
if host == "" || !strings.Contains(host, ".") && net.ParseIP(host) == nil {
if host == "localhost" {
return "", ErrPrivateHost
}
return "", ErrNotURL
}
if isPrivateHost(host) {
return "", ErrPrivateHost
}
if port := u.Port(); port != "" {
u.Host = net.JoinHostPort(host, port)
} else if strings.Contains(host, ":") {
u.Host = "[" + host + "]"
} else {
u.Host = host
}
u.Fragment = ""
u.User = nil
return u.String(), nil
}
func isPrivateHost(host string) bool {
if host == "localhost" || strings.HasSuffix(host, ".localhost") ||
strings.HasSuffix(host, ".local") || strings.HasSuffix(host, ".internal") ||
strings.HasSuffix(host, ".lan") || strings.HasSuffix(host, ".home.arpa") {
return true
}
ip := net.ParseIP(host)
if ip == nil {
return false
}
return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() ||
ip.IsLinkLocalMulticast() || ip.IsMulticast() || ip.IsUnspecified()
}
// Site returns the host of a URL without a leading "www." or "m.", for use
// in allow lists, block lists and per-site metrics. It returns "" on error.
func Site(raw string) string {
u, err := url.Parse(raw)
if err != nil {
return ""
}
h := strings.ToLower(u.Hostname())
h = strings.TrimPrefix(h, "www.")
h = strings.TrimPrefix(h, "m.")
return h
}
// sensitiveParams are query keys whose values never reach the logs.
var sensitiveParams = []string{
"token", "key", "sig", "signature", "pass", "password", "pwd", "auth",
"secret", "session", "sid", "code", "credential", "jwt", "policy", "expires",
}
// Redact makes a URL safe for logs: it removes user info and blanks the
// values of query parameters that look like credentials.
func Redact(raw string) string {
u, err := url.Parse(raw)
if err != nil {
return "[unparseable url]"
}
u.User = nil
if u.RawQuery != "" {
q := u.Query()
for k := range q {
lk := strings.ToLower(k)
for _, s := range sensitiveParams {
if strings.Contains(lk, s) {
q.Set(k, "REDACTED")
break
}
}
}
u.RawQuery = q.Encode()
}
return u.String()
}
var anyURLRe = regexp.MustCompile(`(?i)\bhttps?://[^\s<>"'` + "`" + `]+`)
// RedactText redacts every URL inside free text such as tool error output.
func RedactText(s string) string {
return anyURLRe.ReplaceAllStringFunc(s, Redact)
}
+145
View File
@@ -0,0 +1,145 @@
package links
import (
"errors"
"reflect"
"strings"
"testing"
)
func TestNormalize(t *testing.T) {
tests := []struct {
name string
in string
want string
wantErr error
}{
{"plain https", "https://example.com/watch?v=1", "https://example.com/watch?v=1", nil},
{"http kept", "http://example.com/a", "http://example.com/a", nil},
{"no scheme", "youtu.be/abc123", "https://youtu.be/abc123", nil},
{"upper host", "HTTPS://Example.COM/Path", "https://example.com/Path", nil},
{"trailing punctuation", "https://example.com/a).", "https://example.com/a", nil},
{"fragment dropped", "https://example.com/a#t=10", "https://example.com/a", nil},
{"userinfo dropped", "https://user:pw@example.com/a", "https://example.com/a", nil},
{"port kept", "https://example.com:8443/a", "https://example.com:8443/a", nil},
{"spaces around", " https://example.com/a ", "https://example.com/a", nil},
{"public ip", "http://8.8.8.8/v.mp4", "http://8.8.8.8/v.mp4", nil},
{"empty", "", "", ErrNotURL},
{"word", "hello", "", ErrNotURL},
{"sentence", "hello there. friend", "", ErrNotURL},
{"ftp", "ftp://example.com/a", "", ErrScheme},
{"file", "file:///etc/passwd", "", ErrScheme},
{"javascript", "javascript://alert(1)", "", ErrScheme},
{"localhost", "http://localhost/a", "", ErrPrivateHost},
{"localhost port", "http://localhost:8080/a", "", ErrPrivateHost},
{"loopback", "http://127.0.0.1/a", "", ErrPrivateHost},
{"private 10", "http://10.1.2.3/a", "", ErrPrivateHost},
{"private 192", "http://192.168.1.1/a", "", ErrPrivateHost},
{"link local metadata", "http://169.254.169.254/latest/meta-data", "", ErrPrivateHost},
{"ipv6 loopback", "http://[::1]/a", "", ErrPrivateHost},
{"dot local", "http://printer.local/a", "", ErrPrivateHost},
{"dot internal", "http://db.internal/a", "", ErrPrivateHost},
{"unspecified", "http://0.0.0.0/a", "", ErrPrivateHost},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := Normalize(tc.in)
if !errors.Is(err, tc.wantErr) {
t.Fatalf("Normalize(%q) error = %v, want %v", tc.in, err, tc.wantErr)
}
if got != tc.want {
t.Fatalf("Normalize(%q) = %q, want %q", tc.in, got, tc.want)
}
})
}
}
func TestExtract(t *testing.T) {
tests := []struct {
name string
text string
entities []Entity
want []string
}{
{
name: "regex fallback",
text: "look https://example.com/a and http://example.org/b.",
want: []string{"https://example.com/a", "http://example.org/b"},
},
{
name: "url entity without scheme",
text: "/dl youtu.be/abc",
entities: []Entity{{Type: "bot_command", Offset: 0, Length: 3}, {Type: "url", Offset: 4, Length: 12}},
want: []string{"https://youtu.be/abc"},
},
{
name: "text link entity",
text: "click here",
entities: []Entity{{Type: "text_link", Offset: 6, Length: 4, URL: "https://example.com/v"}},
want: []string{"https://example.com/v"},
},
{
// The emoji is two UTF-16 units, so the entity offset is 3, not 2.
name: "utf16 offsets",
text: "\U0001F600 https://example.com/x",
entities: []Entity{{Type: "url", Offset: 3, Length: 21}},
want: []string{"https://example.com/x"},
},
{
name: "duplicates removed",
text: "https://example.com/a https://example.com/a",
want: []string{"https://example.com/a"},
},
{
name: "private hosts dropped",
text: "http://127.0.0.1/x https://example.com/ok",
want: []string{"https://example.com/ok"},
},
{
name: "bad entity range ignored, regex used",
text: "https://example.com/a",
entities: []Entity{{Type: "url", Offset: 50, Length: 10}},
want: []string{"https://example.com/a"},
},
{name: "none", text: "just words", want: nil},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := Extract(tc.text, tc.entities)
if !reflect.DeepEqual(got, tc.want) {
t.Fatalf("Extract() = %#v, want %#v", got, tc.want)
}
})
}
}
func TestSite(t *testing.T) {
tests := map[string]string{
"https://www.youtube.com/watch?v=1": "youtube.com",
"https://m.youtube.com/watch?v=1": "youtube.com",
"https://YouTu.be/x": "youtu.be",
"https://sub.example.com:8080/a": "sub.example.com",
"::bad::": "",
}
for in, want := range tests {
if got := Site(in); got != want {
t.Errorf("Site(%q) = %q, want %q", in, got, want)
}
}
}
func TestRedact(t *testing.T) {
got := Redact("https://bob:hunter2@example.com/v?id=7&token=abc&X-Signature=zzz")
for _, leak := range []string{"hunter2", "bob", "abc", "zzz"} {
if strings.Contains(got, leak) {
t.Fatalf("Redact leaked %q in %q", leak, got)
}
}
if !strings.Contains(got, "id=7") {
t.Fatalf("Redact dropped a harmless parameter: %q", got)
}
text := RedactText("ERROR: failed https://a.example/x?sig=SECRET1 then https://u:p@b.example/y")
if strings.Contains(text, "SECRET1") || strings.Contains(text, "u:p@") {
t.Fatalf("RedactText leaked: %q", text)
}
}