package app_test import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "strconv" "strings" "testing" "time" "github.com/noderunners/dlbot/internal/api" "github.com/noderunners/dlbot/internal/config" "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/tg/fakeserver" "github.com/noderunners/dlbot/internal/ytdlp/ytdlptest" ) // These tests drive the Mini App the way its front end does: plain HTTP // against the real API of a running core, with initData signed by the // bot token like Telegram signs it. func startApp(t *testing.T, fake *ytdlptest.Fake, mut func(*config.Config)) *moneyHarness { t.Helper() return startGroup(t, fake, func(c *config.Config) { c.MiniApp = true if mut != nil { mut(c) } }) } type appReply struct { Status int Body map[string]any Raw string } func (r appReply) str(key string) string { s, _ := r.Body[key].(string); return s } func (r appReply) num(key string) int64 { f, _ := r.Body[key].(float64) return int64(f) } func (r appReply) list(key string) []map[string]any { var out []map[string]any items, _ := r.Body[key].([]any) for _, it := range items { if m, ok := it.(map[string]any); ok { out = append(out, m) } } return out } func initDataFor(user int64) string { return api.SignInitData(fakeserver.Token, api.InitUser{ID: user, FirstName: "User", LanguageCode: "en"}, time.Now(), "") } // rawCall makes one request with the given Authorization header. func (h *moneyHarness) rawCall(auth, method, path string, body any) appReply { h.t.Helper() var rd io.Reader if body != nil { b, _ := json.Marshal(body) rd = bytes.NewReader(b) } req, err := http.NewRequest(method, h.cfg.PublicURL+"/app/api/"+path, rd) if err != nil { h.t.Fatal(err) } if auth != "" { req.Header.Set("Authorization", auth) } req.Header.Set("Accept-Language", "en-US,en;q=0.9") res, err := http.DefaultClient.Do(req) if err != nil { h.t.Fatalf("%s %s: %v", method, path, err) } defer res.Body.Close() raw, _ := io.ReadAll(res.Body) out := appReply{Status: res.StatusCode, Raw: string(raw)} _ = json.Unmarshal(raw, &out.Body) return out } // call makes a request as a Telegram user. func (h *moneyHarness) call(user int64, method, path string, body any) appReply { h.t.Helper() return h.rawCall("tma "+initDataFor(user), method, path, body) } // must is call, failing the test unless the answer is 200. func (h *moneyHarness) must(user int64, method, path string, body any) appReply { h.t.Helper() r := h.call(user, method, path, body) if r.Status != http.StatusOK { h.t.Fatalf("%s %s as %d: status %d, body %s", method, path, user, r.Status, r.Raw) } return r } // refused asserts that a call fails with the given status and error code. func (h *moneyHarness) refused(r appReply, status int, code string) { h.t.Helper() if r.Status != status || r.str("error") != code { h.t.Fatalf("status %d error %q, want %d %q (body %s)", r.Status, r.str("error"), status, code, r.Raw) } } // meetGroup makes the bot see a user in the test group, which is how it // learns that the group exists and who is in it. func (h *moneyHarness) meetGroup(users ...int64) { h.t.Helper() for _, u := range users { seq := h.srv.Seq() h.srv.PushMessage(group, u, "/queue") h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == group }) } } var appRoutes = []struct{ method, path string }{ {"GET", "me"}, {"PUT", "me"}, {"GET", "i18n"}, {"POST", "probe"}, {"POST", "download"}, {"GET", "queue"}, {"POST", "queue/x/cancel"}, {"POST", "queue/x/prioritize"}, {"GET", "history"}, {"POST", "history/x/resend"}, {"GET", "products"}, {"POST", "purchase"}, {"GET", "purchase/x"}, {"POST", "purchase/x/cancel"}, {"GET", "groups"}, {"GET", "groups/-1001234567890"}, {"PUT", "groups/-1001234567890/settings"}, {"GET", "groups/-1001234567890/usage"}, } // --- acceptance: initData is validated on every call ----------------------- func TestMiniAppRefusesCallsWithoutValidInitData(t *testing.T) { h := startApp(t, nil, nil) good := initDataFor(alice) forged := api.SignInitData("987654321:OTHERotherOTHERotherOTHERotherOTHER-01", api.InitUser{ID: alice, FirstName: "User"}, time.Now(), "") stale := api.SignInitData(fakeserver.Token, api.InitUser{ID: alice, FirstName: "User"}, time.Now().Add(-48*time.Hour), "") // The same signature, claiming to be somebody else. swapped := strings.Replace(good, "%22id%22%3A42", "%22id%22%3A43", 1) if swapped == good { t.Fatal("test setup: the user ID was not found in the init data") } bad := map[string]string{ "no header": "", "empty init data": "tma ", "wrong scheme": "Bearer " + good, "another bot's data": "tma " + forged, "two days old": "tma " + stale, "user swapped": "tma " + swapped, "garbage": "tma hash=zz&user=%7B%7D", } for _, rt := range appRoutes { for name, auth := range bad { r := h.rawCall(auth, rt.method, rt.path, map[string]any{}) if r.Status != http.StatusUnauthorized || r.str("error") != "unauthorized" { t.Errorf("%s %s with %s: status %d body %s", rt.method, rt.path, name, r.Status, r.Raw) } } } // The refusal is a sentence a person can read, from the catalog. if r := h.rawCall("", "GET", "me", nil); !strings.Contains(r.str("message"), "Open this page from Telegram") { t.Fatalf("refusal message = %q", r.str("message")) } // Nothing was created for the callers that were turned away. if _, err := h.app.Store.GetUser(context.Background(), alice); err == nil { t.Fatal("a refused call created a user") } me := h.must(alice, "GET", "me", nil) if me.num("id") != alice || me.str("lang") != "en" || me.str("dir") != "ltr" || me.str("source") != "free" { t.Fatalf("me = %s", me.Raw) } // A banned user is locked out of the app like out of the chat. if ok, err := h.app.Store.SetUserBanned(context.Background(), alice, true); err != nil || !ok { t.Fatal(ok, err) } h.refused(h.call(alice, "GET", "me", nil), http.StatusForbidden, "forbidden") } func TestMiniAppIsServedFromTheBinary(t *testing.T) { h := startApp(t, nil, nil) get := func(path string, hdr ...string) (*http.Response, string) { req, _ := http.NewRequest("GET", h.cfg.PublicURL+path, nil) for i := 0; i+1 < len(hdr); i += 2 { req.Header.Set(hdr[i], hdr[i+1]) } res, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } defer res.Body.Close() b, _ := io.ReadAll(res.Body) return res, string(b) } res, index := get("/app/") if res.StatusCode != 200 || !strings.Contains(index, "telegram-web-app.js") || !strings.Contains(index, `id="root"`) { t.Fatalf("/app/ = %d %q", res.StatusCode, index) } if !strings.HasPrefix(res.Header.Get("Content-Type"), "text/html") { t.Fatalf("content type = %q", res.Header.Get("Content-Type")) } if csp := res.Header.Get("Content-Security-Policy"); !strings.Contains(csp, "frame-ancestors") { t.Fatalf("no content security policy: %q", csp) } // Every script and style the page names is in the binary too. for _, part := range strings.Split(index, `"`) { if strings.HasPrefix(part, "/app/assets/") { if r, body := get(part); r.StatusCode != 200 || len(body) == 0 { t.Errorf("%s = %d, %d bytes", part, r.StatusCode, len(body)) } } } // A deep path is the app's business: it gets the same page. if r, body := get("/app/groups/123"); r.StatusCode != 200 || body != index { t.Fatalf("deep path = %d", r.StatusCode) } // A client that has the current build is told so. etag := res.Header.Get("ETag") if etag == "" { t.Fatal("no ETag") } if r, _ := get("/app/", "If-None-Match", etag); r.StatusCode != http.StatusNotModified { t.Fatalf("revalidation = %d, want 304", r.StatusCode) } } // --- acceptance: buy ------------------------------------------------------- func TestMiniAppBuyPass(t *testing.T) { h := startApp(t, nil, nil) products := h.must(alice, "GET", "products", nil) if products.Body["enabled"] != true || len(products.list("passes")) != 3 { t.Fatalf("products = %s", products.Raw) } seq := h.srv.Seq() // The amount sent with a pass is ignored: the price list is the core's. p := h.must(alice, "POST", "purchase", map[string]any{"target": "me", "product": "pass_week", "amount": 1}) inv, ok := h.ln.WaitInvoice(1, 5*time.Second) if !ok { t.Fatal("no invoice was created") } if inv.AmountSats != 3000 || p.num("amount") != 3000 || p.str("status") != "pending" { t.Fatalf("invoice %d sats, purchase %s", inv.AmountSats, p.Raw) } if p.str("bolt11") != inv.Bolt11 || !strings.HasPrefix(p.str("qr"), "data:image/png;base64,") { t.Fatalf("purchase lacks the invoice or its QR code: %.200s", p.Raw) } id := p.str("id") if st := h.must(alice, "GET", "purchase/"+id, nil); st.str("status") != "pending" { t.Fatalf("status before paying = %s", st.Raw) } // Somebody else cannot watch or cancel this purchase. h.refused(h.call(bob, "GET", "purchase/"+id, nil), http.StatusNotFound, "not_found") h.refused(h.call(bob, "POST", "purchase/"+id+"/cancel", nil), http.StatusNotFound, "not_found") h.pay(inv) // The app notices by asking: no webhook is needed for this to work. var st appReply deadline := time.Now().Add(5 * time.Second) for { st = h.must(alice, "GET", "purchase/"+id, nil) if st.str("status") == "paid" { break } if time.Now().After(deadline) { t.Fatalf("the purchase never became paid: %s", st.Raw) } time.Sleep(20 * time.Millisecond) } week := int64(7 * 24 * time.Hour / time.Millisecond) if until := st.num("pass_until"); until < db.NowMilli()+week-60_000 || until > db.NowMilli()+week+60_000 { t.Fatalf("pass_until = %d, want a week from now", until) } if st.Body["bolt11"] != nil { t.Fatal("a settled purchase still carries its invoice") } me := h.must(alice, "GET", "me", nil) if me.str("source") != "own_pass" || me.num("pass_until") != st.num("pass_until") { t.Fatalf("me after buying = %s", me.Raw) } // The chat gets a receipt as well. h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice && strings.Contains(c.Text(), "Paid") }) h.booksBalance() } func TestMiniAppPollingAloneSettlesAPurchase(t *testing.T) { // No webhook reaches the core here, and its own poller is an hour // away. The app's status calls are what settle the payment. h := startApp(t, nil, func(c *config.Config) { c.LNbits.WebhookSecret = "" }) p := h.must(alice, "POST", "purchase", map[string]any{"target": "me", "product": "credits", "amount": 500}) inv, ok := h.ln.WaitInvoice(1, 5*time.Second) if !ok || inv.AmountSats != 500 { t.Fatalf("invoice = %+v", inv) } h.pay(inv) st := h.must(alice, "GET", "purchase/"+p.str("id"), nil) if st.str("status") != "paid" || st.num("balance") != 500 { t.Fatalf("status after paying = %s", st.Raw) } // Asking again does not credit again. h.must(alice, "GET", "purchase/"+p.str("id"), nil) if got := h.balance(alice); got != 500 { t.Fatalf("balance = %d, want 500", got) } h.booksBalance() } func TestMiniAppRefusesWhatItDoesNotSell(t *testing.T) { h := startApp(t, nil, nil) for _, body := range []map[string]any{ {"target": "me", "product": "yacht"}, {"target": "me", "product": "one_off"}, // needs a download behind it {"target": "me", "product": "skip_queue"}, // needs a waiting job behind it {"target": "me", "product": "donation", "amount": 100}, // not sold in the app {"target": "me", "product": "credits", "amount": -5}, // not an amount {"target": "me", "product": "credits", "amount": 1 << 50}, // absurd {"target": "-1009999", "product": "pass_day"}, // a group the bot is not in } { if r := h.call(alice, "POST", "purchase", body); r.Status == http.StatusOK { t.Errorf("purchase %v was accepted: %s", body, r.Raw) } } h.refused(h.call(alice, "POST", "purchase", map[string]any{"target": "42", "product": "pass_day"}), http.StatusBadRequest, "bad_request") if n := len(h.ln.Invoices()); n != 0 { t.Fatalf("%d invoices were created for refused purchases", n) } } func TestMiniAppBuyCreditsForAGroup(t *testing.T) { h := startApp(t, nil, nil) h.meetGroup(bob) gid := strconv.FormatInt(group, 10) groups := h.must(bob, "GET", "groups", nil).list("groups") if len(groups) != 1 || groups[0]["id"] != gid { t.Fatalf("bob's groups = %v", groups) } p := h.must(bob, "POST", "purchase", map[string]any{"target": gid, "product": "credits", "amount": 1000}) inv, ok := h.ln.WaitInvoice(1, 5*time.Second) if !ok || inv.AmountSats != 1000 { t.Fatalf("invoice = %+v", inv) } h.pay(inv) deadline := time.Now().Add(5 * time.Second) for h.must(bob, "GET", "purchase/"+p.str("id"), nil).str("status") != "paid" { if time.Now().After(deadline) { t.Fatal("the group purchase never became paid") } time.Sleep(20 * time.Millisecond) } if got := h.groupWallet().Balance; got != 1000 { t.Fatalf("group balance = %d, want 1000", got) } if got := h.balance(bob); got != 0 { t.Fatalf("the buyer's own balance = %d, want 0", got) } detail := h.must(bob, "GET", "groups/"+gid, nil) if detail.num("balance") != 1000 { t.Fatalf("group detail = %s", detail.Raw) } h.booksBalance() } // --- acceptance: history resend -------------------------------------------- func TestMiniAppHistoryResend(t *testing.T) { h := startApp(t, &ytdlptest.Fake{FileSize: 3000}, nil) h.fetch(alice, link) items := h.must(alice, "GET", "history", nil).list("items") if len(items) != 1 || items[0]["title"] != "Test Video" || items[0]["profile"] != "best" { t.Fatalf("history = %v", items) } id, _ := items[0]["id"].(string) // History is personal. if got := h.must(bob, "GET", "history", nil).list("items"); len(got) != 0 { t.Fatalf("bob sees %d items of alice's history", len(got)) } h.refused(h.call(bob, "POST", "history/"+id+"/resend", nil), http.StatusNotFound, "not_found") seq := h.srv.Seq() h.must(alice, "POST", "history/"+id+"/resend", nil) again := h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice }) if again.Params["video"] == "" || len(again.Files) != 0 { t.Fatalf("the resend should reuse Telegram's copy: params %v, %d uploads", again.Params, len(again.Files)) } h.wait(seq, edits, func(c fakeserver.Call) bool { return c.ChatID() == alice && strings.Contains(c.Text(), "Done") }) // One real download happened, and both deliveries count as usage. if n := len(h.fake.Downloads()); n != 1 { t.Fatalf("%d downloads ran, want 1", n) } if u := h.usage(alice); u.Downloads != 2 { t.Fatalf("usage = %+v, want 2 downloads: a resend is a download", u) } if got := h.must(alice, "GET", "history", nil).list("items"); len(got) != 2 { t.Fatalf("history has %d items after the resend, want 2", len(got)) } } func TestMiniAppResendObeysTheDailyLimit(t *testing.T) { h := startApp(t, &ytdlptest.Fake{FileSize: 3000}, func(c *config.Config) { c.Limits.Free.DailyDownloads = 1 }) h.fetch(alice, link) id, _ := h.must(alice, "GET", "history", nil).list("items")[0]["id"].(string) seq := h.srv.Seq() r := h.call(alice, "POST", "history/"+id+"/resend", nil) h.refused(r, http.StatusUnprocessableEntity, "limit.daily_downloads") if r.Body["upgradable"] != true || r.str("message") == "" { t.Fatalf("refusal = %s", r.Raw) } h.never(seq, "sendVideo|sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice }) } // --- acceptance: download and queue cancel --------------------------------- func TestMiniAppDownloadAndCancel(t *testing.T) { block := make(chan struct{}) defer close(block) h := startApp(t, &ytdlptest.Fake{Block: block, FileSize: 3000}, nil) probe := h.must(alice, "POST", "probe", map[string]any{"url": link}) if probe.str("title") != "Test Video" || probe.num("duration") != 60 || len(probe.list("options")) < 2 { t.Fatalf("probe = %s", probe.Raw) } h.refused(h.call(alice, "POST", "probe", map[string]any{"url": "not a link"}), http.StatusUnprocessableEntity, "bad_link") h.refused(h.call(alice, "POST", "probe", map[string]any{"url": "http://127.0.0.1/x"}), http.StatusUnprocessableEntity, "bad_link") seq := h.srv.Seq() h.must(alice, "POST", "download", map[string]any{"url": probe.str("url"), "profile": "best"}) // The status lives in the chat, like for a download started there. status := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice }) h.waitJobs(db.JobRunning, 1) var jobs []map[string]any deadline := time.Now().Add(5 * time.Second) for { jobs = h.must(alice, "GET", "queue", nil).list("jobs") if len(jobs) == 1 && jobs[0]["status"] == "running" { break } if time.Now().After(deadline) { t.Fatalf("queue = %v", jobs) } time.Sleep(20 * time.Millisecond) } if jobs[0]["title"] != "Test Video" || jobs[0]["can_cancel"] != true || jobs[0]["can_prioritize"] != false { t.Fatalf("job = %v", jobs[0]) } id, _ := jobs[0]["id"].(string) // The queue is personal, and so is the right to cancel. if got := h.must(bob, "GET", "queue", nil).list("jobs"); len(got) != 0 { t.Fatalf("bob sees alice's queue: %v", got) } h.refused(h.call(bob, "POST", "queue/"+id+"/cancel", nil), http.StatusNotFound, "not_found") h.waitJobs(db.JobRunning, 1) seq = h.srv.Seq() h.must(alice, "POST", "queue/"+id+"/cancel", nil) h.wait(seq, edits, func(c fakeserver.Call) bool { return c.MessageID == status.MessageID && strings.Contains(c.Text(), "Cancelled") }) h.waitJobs(db.JobCancelled, 1) if got := h.must(alice, "GET", "queue", nil).list("jobs"); len(got) != 0 { t.Fatalf("queue after cancel = %v", got) } if u := h.usage(alice); u.Downloads != 0 { t.Fatalf("a cancelled download was counted: %+v", u) } h.never(seq, "sendVideo", nil) } func TestMiniAppCannotDownloadPastTheLimits(t *testing.T) { h := startApp(t, nil, nil) seq := h.srv.Seq() // The front end offers every format. The core still says no. r := h.call(alice, "POST", "download", map[string]any{"url": bigLink, "profile": "best"}) h.refused(r, http.StatusUnprocessableEntity, "limit.too_large") if r.Body["upgradable"] != true || !strings.Contains(r.str("message"), "MB") { t.Fatalf("refusal = %s", r.Raw) } h.never(seq, "sendMessage|sendVideo", func(c fakeserver.Call) bool { return c.ChatID() == alice }) if n := len(h.jobs(db.JobQueued)) + len(h.jobs(db.JobRunning)); n != 0 { t.Fatalf("%d jobs exist after a refusal", n) } h.refused(h.call(alice, "POST", "download", map[string]any{"url": link, "profile": "8k"}), http.StatusUnprocessableEntity, "bad_link") } func TestMiniAppPrioritize(t *testing.T) { block := make(chan struct{}) defer close(block) h := startApp(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) { c.Worker.Concurrency = 1 }) h.queued() // alice's job runs, bob's waits behind it jobs := h.must(bob, "GET", "queue", nil).list("jobs") if len(jobs) != 1 || jobs[0]["status"] != "queued" || jobs[0]["can_prioritize"] != true || jobs[0]["skip_price"] != float64(50) { t.Fatalf("bob's queue = %v", jobs) } if pos, _ := jobs[0]["position"].(float64); pos != 1 { t.Fatalf("position = %v, want 1", jobs[0]["position"]) } id, _ := jobs[0]["id"].(string) h.refused(h.call(alice, "POST", "queue/"+id+"/prioritize", nil), http.StatusNotFound, "not_found") // Without credits the answer is an invoice, and paying it promotes. r := h.must(bob, "POST", "queue/"+id+"/prioritize", nil) purchase, _ := r.Body["purchase"].(map[string]any) if r.Body["done"] != false || purchase == nil || purchase["amount"] != float64(50) || purchase["bolt11"] == "" { t.Fatalf("prioritize = %s", r.Raw) } inv, ok := h.ln.WaitInvoice(1, 5*time.Second) if !ok { t.Fatal("no invoice") } h.pay(inv) deadline := time.Now().Add(5 * time.Second) for { if q := h.jobs(db.JobQueued); len(q) == 1 && q[0].Lane == db.LanePaid { break } if time.Now().After(deadline) { t.Fatal("the job was not promoted after payment") } time.Sleep(20 * time.Millisecond) } if jobs = h.must(bob, "GET", "queue", nil).list("jobs"); len(jobs) != 1 || jobs[0]["can_prioritize"] != false { t.Fatalf("queue after promotion = %v", jobs) } h.booksBalance() } func TestMiniAppPrioritizeWithCredits(t *testing.T) { block := make(chan struct{}) defer close(block) h := startApp(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) { c.Worker.Concurrency = 1 }) h.grant(bob, 40) // not enough for a paid download, so bob queues as free h.queued() h.grant(bob, 20) // now 60 id, _ := h.must(bob, "GET", "queue", nil).list("jobs")[0]["id"].(string) r := h.must(bob, "POST", "queue/"+id+"/prioritize", nil) if r.Body["done"] != true || r.Body["purchase"] != nil { t.Fatalf("prioritize = %s", r.Raw) } if q := h.jobs(db.JobQueued); len(q) != 1 || q[0].Lane != db.LanePaid { t.Fatalf("the job was not promoted: %+v", q) } if got := h.balance(bob); got != 10 { t.Fatalf("balance = %d, want 10", got) } // A second press finds nothing left to promote and charges nothing. h.refused(h.call(bob, "POST", "queue/"+id+"/prioritize", nil), http.StatusUnprocessableEntity, "too_late") if got := h.balance(bob); got != 10 { t.Fatalf("balance after a second press = %d, want 10", got) } if n := len(h.ln.Invoices()); n != 0 { t.Fatalf("%d invoices, want none", n) } h.booksBalance() } // --- acceptance: group settings -------------------------------------------- func TestMiniAppGroupSettingsAreForAdmins(t *testing.T) { h := startApp(t, &ytdlptest.Fake{FileSize: 3000}, nil) h.meetGroup(alice, bob) gid := strconv.FormatInt(group, 10) path := "groups/" + gid // Alice is a member, not an admin: the group is not hers to manage. if got := h.must(alice, "GET", "groups", nil).list("groups"); len(got) != 0 { t.Fatalf("alice's groups = %v", got) } change := map[string]any{ "enabled": true, "auto_detect": true, "delete_commands": false, "who_can_use": "admins", "spend_rule": "capped", "spend_cap": 200, "daily_cap": 5000, "max_size_mb": 20, "max_duration": 600, "quality": "720", "lang": "en", "allowed": []string{}, "blocked": []string{"https://www.Example.ORG/some/page", "example.org"}, } h.refused(h.call(alice, "GET", path, nil), http.StatusForbidden, "forbidden") h.refused(h.call(alice, "GET", path+"/usage", nil), http.StatusForbidden, "forbidden") h.refused(h.call(alice, "PUT", path+"/settings", change), http.StatusForbidden, "forbidden") if st := h.settings(nil); st.WhoCanUse != db.UseEveryone || st.AutoDetect { t.Fatalf("a refused change was applied: %+v", st) } // A group that does not exist looks the same to everybody. h.refused(h.call(bob, "GET", "groups/-1009", nil), http.StatusNotFound, "not_found") before := h.must(bob, "GET", path, nil) settings, _ := before.Body["settings"].(map[string]any) if before.str("title") == "" || settings["who_can_use"] != "everyone" || settings["spend_rule"] != "admins" { t.Fatalf("group detail = %s", before.Raw) } saved := h.must(bob, "PUT", path+"/settings", change) settings, _ = saved.Body["settings"].(map[string]any) if fmt.Sprint(settings["blocked"]) != "[example.org]" { t.Fatalf("blocked sites were not cleaned: %v", settings["blocked"]) } st := h.settings(nil) if !st.AutoDetect || st.WhoCanUse != db.UseAdmins || st.SpendRule != db.SpendCapped || st.SpendCap != 200 || st.DailyCap != 5000 || st.MaxSizeMB != 20 || st.MaxDuration != 600 || st.Quality != "720" || st.Lang != "en" || st.Blocked != "example.org" { t.Fatalf("stored settings = %+v", st) } // The change is live in the chat: only admins may use the bot now. seq := h.srv.Seq() h.srv.PushMessage(group, alice, "/dl https://example.com/for-admins") h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == group && strings.Contains(c.Text(), "admins") }) h.never(seq, "sendPhoto", nil) // Nonsense is refused whole, and a cap above the tier is lowered to it. for field, value := range map[string]any{ "who_can_use": "root", "spend_rule": "everything", "spend_cap": -1, "daily_cap": -1, "max_size_mb": -3, "quality": "thumb", "lang": "tlh", "blocked": []string{"not a host!"}, } { bad := map[string]any{} for k, v := range change { bad[k] = v } bad[field] = value h.refused(h.call(bob, "PUT", path+"/settings", bad), http.StatusBadRequest, "bad_request") } if got := h.settings(nil); got.WhoCanUse != db.UseAdmins || got.MaxSizeMB != 20 { t.Fatalf("a refused change was applied: %+v", got) } change["max_size_mb"] = 999999 h.must(bob, "PUT", path+"/settings", change) if got := h.settings(nil).MaxSizeMB; got != h.cfg.Limits.Paid.MaxSizeMB { t.Fatalf("max size = %d MB, want the tier's %d", got, h.cfg.Limits.Paid.MaxSizeMB) } // An admin who is demoted loses access with the next check. h.srv.SetMember(group, bob, "member") h.app.Bot.Admins().Forget(group) h.refused(h.call(bob, "GET", path, nil), http.StatusForbidden, "forbidden") } func TestMiniAppGroupUsage(t *testing.T) { h := startApp(t, &ytdlptest.Fake{FileSize: 3000}, nil) h.groupFetch(alice, link) h.meetGroup(bob) usage := h.must(bob, "GET", "groups/"+strconv.FormatInt(group, 10)+"/usage", nil) members := usage.list("members") if usage.num("days") != 7 || len(members) != 1 || members[0]["downloads"] != float64(1) || members[0]["bytes"] != float64(3000) { t.Fatalf("usage = %s", usage.Raw) } } // --- preferences and texts ------------------------------------------------- func TestMiniAppPreferences(t *testing.T) { h := startApp(t, nil, nil) ctx := context.Background() h.must(alice, "PUT", "me", map[string]any{"quality": "720"}) if me := h.must(alice, "GET", "me", nil); me.str("quality") != "720" { t.Fatalf("me = %s", me.Raw) } // A default format has to be a video or audio format. h.refused(h.call(alice, "PUT", "me", map[string]any{"quality": "thumb"}), http.StatusBadRequest, "bad_request") h.refused(h.call(alice, "PUT", "me", map[string]any{"lang": "tlh"}), http.StatusBadRequest, "bad_request") h.must(alice, "PUT", "me", map[string]any{"quality": ""}) h.must(alice, "PUT", "me", map[string]any{"lang": "en"}) u, err := h.app.Store.GetUser(ctx, alice) if err != nil || u.LangOverride != "en" || u.Quality != "" { t.Fatalf("user = %+v, %v", u, err) } h.must(alice, "PUT", "me", map[string]any{"lang": "auto"}) if u, _ = h.app.Store.GetUser(ctx, alice); u.LangOverride != "" { t.Fatalf("language override = %q, want none", u.LangOverride) } me := h.must(alice, "GET", "me", nil) if !strings.HasSuffix(me.str("referral_link"), "?start=ref_42") || len(me.list("languages")) == 0 { t.Fatalf("me = %s", me.Raw) } } func TestMiniAppTextsComeFromTheCatalog(t *testing.T) { h := startApp(t, nil, nil) r := h.must(alice, "GET", "i18n", nil) msgs, _ := r.Body["messages"].(map[string]any) if r.str("lang") != "en" || r.str("dir") != "ltr" { t.Fatalf("i18n = %.200s", r.Raw) } if msgs["app.tab.home"] != "Home" || msgs["product.pass_week"] != "Week pass" { t.Fatalf("messages lack basic entries: %v, %v", msgs["app.tab.home"], msgs["product.pass_week"]) } // Placeholders arrive in the form the app fills in, plurals as forms. if msgs["app.pass_until"] != "Pass until {Until}" { t.Fatalf("placeholder form = %v", msgs["app.pass_until"]) } forms, _ := msgs["unit.sats"].(map[string]any) if forms["one"] != "{N} sat" || forms["other"] != "{N} sats" { t.Fatalf("plural forms = %v", msgs["unit.sats"]) } } // --- the way into the app from the chat ------------------------------------ func TestChatPointsToTheMiniApp(t *testing.T) { h := startApp(t, nil, nil) appURL := h.cfg.PublicURL + "/app/" // In private the button opens the app in place. seq := h.srv.Seq() h.srv.PushMessage(alice, alice, "/app") msg := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice }) if b := msg.Buttons(); len(b) != 1 || b[0].WebApp == nil || b[0].WebApp.URL != appURL { t.Fatalf("/app in private = %+v", msg.Buttons()) } // Telegram refuses web app buttons in groups, so there it is a link // to the bot's main Mini App. seq = h.srv.Seq() h.srv.PushMessage(group, alice, "/app") msg = h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == group }) if b := msg.Buttons(); len(b) != 1 || b[0].WebApp != nil || b[0].URL != "https://t.me/"+fakeserver.BotUsername+"?startapp" { t.Fatalf("/app in a group = %+v", msg.Buttons()) } // A refused download offers the shop inside the app as well. card := h.card(alice, alice, bigLink) seq = h.press(alice, alice, card, "dl:") offer := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice && len(c.Buttons()) > 0 }) var open *fakeserver.Button for _, b := range offer.Buttons() { if b.WebApp != nil { open = &b } } if open == nil || open.Text != "Open app" || open.WebApp.URL != appURL+"?page=buy" { t.Fatalf("the offer has no way into the app: %+v", offer.Buttons()) } } func TestChatHidesTheMiniAppWhenItIsOff(t *testing.T) { h := startGroup(t, nil, nil) // MINIAPP_ENABLED is not set seq := h.srv.Seq() h.srv.PushMessage(alice, alice, "/app") h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return strings.Contains(c.Text(), "not set up") && len(c.Buttons()) == 0 }) card := h.card(alice, alice, bigLink) seq = h.press(alice, alice, card, "dl:") offer := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == alice && len(c.Buttons()) > 0 }) for _, b := range offer.Buttons() { if b.WebApp != nil { t.Fatalf("a web app button without a Mini App: %+v", b) } } // The API is not there either. if r := h.call(alice, "GET", "me", nil); r.Status != http.StatusNotFound { t.Fatalf("the Mini App API answers with %d while the app is off", r.Status) } }