diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a62345..9e4e77e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## [Unreleased] +- Export the Telegram Mini App launch and Stars checkout client contract, including validation of catalog and invoice replies. - Build with Ziran 7fbc8152 and Kryon 3627ea8a, the Kryon without raylib, together with Plot, Game2D, CSS and Apps. - The `native-crypto` artifact's Android and Windows runtimes generate their C with the toolchain's own `zi2c` under the device's target conditions, so an ARMv7 build no longer cross-compiles a code generator against glibc symbols bionic lacks; Android consumers also link liblog, which the runtime's diagnostics use. diff --git a/Makefile b/Makefile index fd79645..c4c334a 100644 --- a/Makefile +++ b/Makefile @@ -311,3 +311,15 @@ canvas-profile-host-test: canvas-profile-lifecycle-test .PHONY: password-test password-test: build/entity.zx build/ziran/libziran.a $(LIBOQS_LIBRARY) python3 scripts/password-test.py + +.PHONY: telegram-mini-app-test +telegram-mini-app-test: + mkdir -p build/telegram-mini-app-test + $(ZIRAN) build --project $(LOCK_FLAGS) --target=c --entry telegram_mini_app_test:main -o build/telegram-mini-app-test tests/telegram_mini_app_test.zi + $(CC) -std=c99 -O2 -I$(ZIRAN_ROOT)/include -Ibuild/telegram-mini-app-test $$(rg --files build/telegram-mini-app-test -g '*.c') -lm -o build/telegram-mini-app-test/test + build/telegram-mini-app-test/test + $(ZIRAN) bundle --project $(LOCK_FLAGS) --entry telegram_mini_app_test:main -o build/telegram-mini-app-test/test.zx tests/telegram_mini_app_test.zi + @result=$$($(ZIRAN) run build/telegram-mini-app-test/test.zx) && \ + printf 'Telegram Mini App VM fixture returned %s\n' "$$result" && test "$$result" = 0 + +test: telegram-mini-app-test diff --git a/README.md b/README.md index 0511f7b..b4d1390 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,11 @@ operation may still finish; these functions do not undo publications. fake-transport lifecycle tests, existing wire helper tests and a portable VM smoke test without accounts or network access. +## Telegram Mini Apps + +Use the [Telegram Mini App developer contract](docs/telegram-mini-app.md) for +issuer-verified launch parameters and Stars checkout in Entity hosts. + ## Standalone hosts and Dew The `entity/native_host` export opens the same profile bundle for native hosts. diff --git a/docs/telegram-mini-app.md b/docs/telegram-mini-app.md new file mode 100644 index 0000000..24802d4 --- /dev/null +++ b/docs/telegram-mini-app.md @@ -0,0 +1,186 @@ +# Telegram Mini Apps + +Entity’s `entity/telegram_mini_app` export defines the client contract for a +signed-in Entity host. The Telegram Mini App supplies its raw `WebApp.initData` +query string. The issuer verifies it for the configured app and bot, then +returns launch parameters safe to expose to application code. Entity continues +to use the existing account sign-in and wallet. [Telegram Mini Apps](https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app) + +The routes below require a compatible issuer. The client fixture exercises the +contract with synthetic replies. It makes no Telegram or issuer network calls. + +## Launch and catalog + +Send requests over HTTPS to the signed-in account’s configured, trusted wallet +issuer. Use the existing bearer session for an owner account. A hosted Mini App +uses `Authorization: Delegate ds1.` with the existing per-request +`X-Mesh-Delegate` proof. The owner separately approves the ability to read the +Dew balance and buy through Telegram. Its signed grant has `telegram_stars: true` +and appends `telegram-stars-purchases\n` (one LF) to the canonical grant message +after the existing scope lines. Continue signing the existing message for grants +that omit the flag. A Telegram-linked Lumi-only delegate can verify launch and +receives `stars_available: false`. The hosted capability covers its own invoice +and read-only balance routes. Keep raw `initData` and session credentials +in memory for the request. Exclude them from logs, telemetry, +URLs, and persisted browser state. The browser can use Telegram SDK presence for +layout. Use the issuer’s validated data for app routing and purchase availability. + +| Method and path | Request | Successful response | +| --- | --- | --- | +| `POST /api/v1/telegram/launch` | `{app_id, init_data}` | `{app_id, start_param?, chat_type?, stars_available}` | +| `GET /api/v1/tokens/purchases/telegram/catalog?app_id=APP` | No body | `{currency: "XTR", products: [{product_id, title, amount, units}]}` | +| `GET /api/v1/tokens/purchases/telegram/balance?app_id=APP` | No body | `{account_id, app_id, asset_id: "waozi:token", balance}` | + +`start_param` is an optional URL-safe token of up to 512 bytes from the verified +launch. Interpret it with an app-defined allowlist, for example to prefill an +invitation or navigate to a known screen. Require normal app confirmation for +side effects. `chat_type` is optional (`sender`, `private`, `group`, `supergroup`, +or `channel`). A valid launch may have neither optional field. The contract +exposes no Telegram user or chat ID. `initDataUnsafe`, browser query parameters +and `invoiceClosed` carry no account or purchase authority. + +Show Stars offers when `WebApp.openInvoice` is available, the issuer returns +`stars_available: true`, and the catalog has products. `amount` is a whole number +of Stars and `units` is the amount the issuer credits in wallet units. For Dew, +one Dew is 1,000,000 units. Display both from the catalog and render the title +as text. The issuer configures an explicit XTR price for each enabled canonical +pack. Telegram requires XTR for digital purchases in Mini Apps. [Telegram Stars payments](https://core.telegram.org/bots/payments-stars) + +## Invoice and settlement + +| Method and path | Request | Successful response | +| --- | --- | --- | +| `POST /api/v1/tokens/purchases/telegram/invoices` | `{app_id, product_id, request_id, init_data}` | `{invoice_id, invoice_url?, product_id, currency: "XTR", amount, units, status}` | +| `GET /api/v1/tokens/purchases/telegram/invoices/ID` | No body | Same invoice record, with `invoice_url` optional | +| `POST /api/v1/tokens/purchases/telegram/invoices/ID/cancel` | No body | Same record. HTTP 409 if checkout was approved and is pending. | + +Generate a fresh unpredictable `request_id` for each confirmed purchase and +retain it with the selected terms in that account’s purchase state. Retry an +uncertain response with the same ID and product. Keep IDs scoped to the owner +and app. On account or issuer change, discard pending UI replies, close the +purchase dialog and clear its catalog and launch data. Revalidate after sign-in. + +Launch verification uses the configured bot, checked freshness, and a +server-verified binding to the account. The issuer rejects duplicate decoded +fields and protects account binding against replay. The signed parameters remain +valid input for a purchase within the issuer’s freshness window. + +The issuer resolves the pack and price server-side and binds the quote to the +verified Telegram buyer, bot, app and signed-in Entity account. It creates the +invoice with Telegram’s `createInvoiceLink`, currency `XTR`, one price item and +an empty provider token. The opaque invoice payload identifies the stored quote. +The creation reply for a pending invoice includes its HTTPS `t.me` invoice link. +[Telegram Bot API](https://core.telegram.org/bots/api#createinvoicelink) + +The web bridge calls `WebApp.openInvoice(invoice_url, onClosed)` with the link +from a verified issuer response. Its callback reports `paid`, `pending`, +`cancelled`, or `failed`. Treat these as dialog states and refresh the invoice +status through the issuer. A dialog can close while the issuer still shows +`pending`. A distinct deliberate purchase uses a distinct `request_id`. +[Mini App events](https://core.telegram.org/bots/webapps#events-available-for-mini-apps) + +| Issuer status | UI behavior | +| --- | --- | +| `pending` | Await the payment result. A valid URL can open checkout. | +| `credited` | Reload the wallet balance. Owner sessions can reload the ledger. | +| `cancelled`, `failed`, `expired` | Show the issuer’s outcome. | +| `refunded` | Reload the wallet to reflect the verified reversal. | + +The issuer settles invoices using authenticated Telegram payment events or +transaction history. It checks Telegram’s webhook secret on incoming updates +and validates the bot, stored payload, buyer, currency and exact amount. Reply +to `pre_checkout_query` within ten seconds. A successful +payment commits the canonical wallet credit and a unique Telegram charge ID in +one transaction. Repeated deliveries return the existing result. A payment +that succeeds after the client has closed still settles. An unconfirmed invoice +can expire server-side without a grant. A verified refund reconciles the original +charge through the wallet’s reversal flow. For recovery, reconcile authenticated +transaction history through the same charge identity and settlement rules. Use +`refundStarPayment` with the stored buyer and charge ID for merchant-initiated +refunds. When the merchant bot also handles other updates, dispatch payments +through its existing webhook. [Webhook configuration](https://core.telegram.org/bots/api#setwebhook) · [Checkout and refund](https://core.telegram.org/bots/api#answerprecheckoutquery) · [Transaction history](https://core.telegram.org/bots/api#getstartransactions) + +## Ziran interface + +Import `entity/telegram_mini_app`. Use `TelegramLaunchPath` and +`TelegramStarsInvoicesPath` for the POST routes. The functions below implement +request construction and response validation. The host supplies authenticated +transport and checks that each response still belongs to the current account +and issuer. Parse only successful issuer responses. + +```zi +Telegram :: #import "entity/telegram_mini_app"; + +launch: Telegram.TelegramLaunchContext +catalog: Telegram.TelegramStarsCatalog +invoice: Telegram.TelegramStarsInvoice +body: Vec(u8) + +// Encode within the authenticated host, send, then clear its request buffer. +if Telegram.TelegramLaunchRequest(app_id, init_data, *body) { + // POST body to Telegram.TelegramLaunchPath. +} +if Telegram.TelegramReadLaunch(launch_reply, app_id, *launch) && launch.stars_available && + Telegram.TelegramReadStarsCatalog(catalog_reply, *catalog) && catalog.count > 0 { + // Show catalog.products[:catalog.count] and let the user confirm an offer. +} + +// Copy the confirmed product and retain it with the purchase request ID. +if Telegram.TelegramReadStarsInvoice(create_reply, *confirmed_product, "", *invoice) && + invoice.state == .Pending { + // Open the returned link through the Telegram bridge. +} +``` + +Use `TelegramStarsCatalogRequestPath` for the catalog and +`TelegramStarsInvoiceRequest` for creation. Use `TelegramStarsStatusRequestPath` +for refresh and `TelegramStarsCancelRequestPath` for explicit cancellation. +Give `TelegramReadStarsInvoice` the recorded invoice ID and +the same `TelegramStarsProduct` confirmed at creation. The parser rejects a +mismatched product, price, wallet quantity, currency or invoice ID. URL fields +are exposed only for pending invoices. `TelegramInvoiceClosedState` returns a +separate `TelegramInvoiceClosed` type for the browser callback. + +Use `TelegramStarsBalanceRequestPath` and `TelegramReadStarsBalance` to update +the wallet after settlement. Pass the expected account ID and app ID from the +current session. The parser checks both and the canonical Dew asset. The signed +balance can be negative after a refund of already-used Dew. + +Each reply is one JSON object of at most 16 KiB. The catalog may contain up to +32 products with distinct IDs. Each title can be up to 128 bytes. The SDK uses +ASCII letters, digits, underscores, hyphens and periods for IDs, with at most +64 bytes for app IDs and 128 bytes for product and request IDs. Invoice IDs use +32 lowercase hex digits and account IDs use 64. Use a random UUID or equivalent +for the request ID. Report offer quantities as JSON +integers in the positive JavaScript safe-integer range. + +## Issuer compatibility tests + +Run the issuer tests against a disposable wallet with signed test launch data +and a fake Telegram transport. Exercise the same JSON endpoints the host uses. + +| Fixture | Expected result | +| --- | --- | +| Fresh signed launch for the bound buyer and bot | The reply carries the expected app and only its safe launch fields. | +| Stale launch, duplicate decoded fields, bad signature or an unbound buyer | The issuer rejects the request without issuing purchase authority. | +| Matching purchase-only delegate, Lumi-only delegate or a different owner | Only the matching purchase delegate can purchase and read its own result and balance. General wallet mutations reject both delegates. | +| Repeated purchase request with the same ID | The same terms return the same invoice. A changed product conflicts. | +| Authenticated pre-checkout for a stored invoice | A matching buyer, amount, currency and payload can proceed. Wrong terms and unauthorized webhooks are rejected. | +| Closed or expired checkout with no successful payment | The wallet receives no grant. | +| Repeated successful payment from Telegram, including a concurrent retry | The owner receives one ledger credit. The repeat reports the same settlement. | +| Verified refund, including repeated receipt | The original credit is reversed once. | + +Return the validated `invoice_url` with a newly created pending invoice. A +status read may omit it while still pending. Send wallet units and Stars as +integers. Return an error when the owner, app or issuer authorization fails. + +Run `make -j1 telegram-mini-app-test` for the same request, launch, catalog and +invoice fixtures in C and the portable VM. The synthetic catalog contains a +fictional XTR amount. Deployment needs the bot and approved per-pack prices, +registered Mini App URL, webhook secret and enabled issuer configuration. +The merchant also needs a `/paysupport` response and customer support for +refunds. [Telegram merchant requirements](https://core.telegram.org/bots/payments-stars#going-live) + +A Telegram test account and test bot use the separate Bot API `/test/` path and +separate issuer state. The local fixtures emulate the provider and require no +Telegram account. [Telegram test environment](https://core.telegram.org/bots/webapps#using-bots-in-the-test-environment) diff --git a/src/telegram_mini_app.zi b/src/telegram_mini_app.zi new file mode 100644 index 0000000..f78b471 --- /dev/null +++ b/src/telegram_mini_app.zi @@ -0,0 +1,314 @@ +// Wire contract for an authenticated Entity host inside a Telegram Mini App. +// The wallet node verifies launch data and settles the payment. +#import "std/c_string" +#import "std/json_document" +#import "std/text_buffer" +#import "std/vec" + +TelegramLaunchPath :: "/api/v1/telegram/launch" +TelegramStarsCatalogPath :: "/api/v1/tokens/purchases/telegram/catalog" +TelegramStarsBalancePath :: "/api/v1/tokens/purchases/telegram/balance" +TelegramStarsInvoicesPath :: "/api/v1/tokens/purchases/telegram/invoices" +TelegramStarsCurrency :: "XTR" +TelegramStarsAsset :: "waozi:token" +TelegramInitDataMax :: 16384 +TelegramStarsProductsMax :: 32 + +TelegramLaunchContext :: struct { + start_param: [513]u8 + chat_type: [16]u8 + stars_available: bool +} + +TelegramStarsProduct :: struct { + product_id: [129]u8 + title: [129]u8 + amount: s64 + units: s64 +} + +TelegramStarsCatalog :: struct { + products: [TelegramStarsProductsMax]TelegramStarsProduct + count: s32 +} + +TelegramStarsState :: enum { + Unknown + Pending + Credited + Cancelled + Failed + Expired + Refunded +} + +TelegramStarsInvoice :: struct { + invoice_id: [129]u8 + invoice_url: [257]u8 + product_id: [129]u8 + amount: s64 + units: s64 + state: TelegramStarsState +} + +TelegramInvoiceClosed :: enum { + Unknown + Paid + Pending + Cancelled + Failed +} + +TelegramInvoiceClosedState :: (status: string) -> TelegramInvoiceClosed { + if status == "paid" { return .Paid } + if status == "pending" { return .Pending } + if status == "cancelled" { return .Cancelled } + if status == "failed" { return .Failed } + return .Unknown +} + +TelegramLaunchRequest :: (app_id: string, init_data: string, output: *Vec(u8)) -> bool { + return WriteRequest(app_id, init_data, "", "", output) +} + +TelegramStarsInvoiceRequest :: (app_id: string, product_id: string, request_id: string, + init_data: string, output: *Vec(u8)) -> bool { + VecClear(< bool { + return WritePath(TelegramStarsCatalogPath, "?app_id=", app_id, 1, 64, output) +} + +TelegramStarsBalanceRequestPath :: (app_id: string, output: *Vec(u8)) -> bool { + return WritePath(TelegramStarsBalancePath, "?app_id=", app_id, 1, 64, output) +} + +TelegramStarsStatusRequestPath :: (invoice_id: string, output: *Vec(u8)) -> bool { + VecClear(< bool { + if !TelegramStarsStatusRequestPath(invoice_id, output) || !BuilderAppend(< bool { + output.* = 0 + doc: JsonDocument + defer { ReleaseDocument(*doc) } + if !ReadObject(*doc, body) || !HexID(account_id, 64) || !ValidID(app_id, 1, 64) || + !JsonIs(*doc, JsonMember(*doc, doc.root, "account_id"), account_id) || + !JsonIs(*doc, JsonMember(*doc, doc.root, "app_id"), app_id) || + !JsonIs(*doc, JsonMember(*doc, doc.root, "asset_id"), TelegramStarsAsset) { return false } + balance, ok := JsonInteger(*doc, JsonMember(*doc, doc.root, "balance")) + if !ok || balance < -9007199254740991 || balance > 9007199254740991 { return false } + output.* = balance + return true +} + +TelegramReadLaunch :: (body: string, app_id: string, output: *TelegramLaunchContext) -> bool { + output.* = .{} + doc: JsonDocument + defer { ReleaseDocument(*doc) } + if !ReadObject(*doc, body) || !ValidID(app_id, 1, 64) || + !JsonIs(*doc, JsonMember(*doc, doc.root, "app_id"), app_id) { return false } + context: TelegramLaunchContext + if !ReadText(*doc, doc.root, "start_param", context.start_param[:], true) || + !ReadText(*doc, doc.root, "chat_type", context.chat_type[:], true) { return false } + start := TextUntilNul(context.start_param[:]) + if !URLToken(start, 0, 512) { return false } + chat := TextUntilNul(context.chat_type[:]) + if chat != "" && chat != "sender" && chat != "private" && chat != "group" && + chat != "supergroup" && chat != "channel" { return false } + available, ok := JsonBool(*doc, JsonMember(*doc, doc.root, "stars_available")) + if !ok { return false } + context.stars_available = available + output.* = context + return true +} + +TelegramReadStarsCatalog :: (body: string, output: *TelegramStarsCatalog) -> bool { + output.* = .{} + doc: JsonDocument + defer { ReleaseDocument(*doc) } + if !ReadObject(*doc, body) || !IsStars(*doc, doc.root) { return false } + array := JsonMember(*doc, doc.root, "products") + if JsonKindOf(*doc, array) != .Array || JsonCount(*doc, array) > TelegramStarsProductsMax { return false } + catalog: TelegramStarsCatalog + node := JsonFirst(*doc, array) + while node >= 0 { + product := *catalog.products[catalog.count] + if !UniqueObject(*doc, node) || !ReadProductID(*doc, node, product.product_id[:]) || + !ReadText(*doc, node, "title", product.title[:], false) || product.title[0] == 0 || + !ReadTerms(*doc, node, *product.amount, *product.units) { return false } + for index: cast(s32)0..catalog.count - 1 { + if TextUntilNul(catalog.products[index].product_id[:]) == TextUntilNul(product.product_id[:]) { return false } + } + catalog.count += 1 + node = JsonNext(*doc, node) + } + output.* = catalog + return true +} + +// Use an empty invoice_id only for the response to creating a new invoice. +// The expected product comes from the offer the user accepted. For later +// status reads the caller passes the same terms and the recorded invoice ID. +TelegramReadStarsInvoice :: (body: string, expected: *TelegramStarsProduct, + invoice_id: string, output: *TelegramStarsInvoice) -> bool { + output.* = .{} + doc: JsonDocument + defer { ReleaseDocument(*doc) } + if !ReadObject(*doc, body) || !IsStars(*doc, doc.root) { return false } + invoice: TelegramStarsInvoice + link_bytes: [257]u8 + if !ReadText(*doc, doc.root, "invoice_id", invoice.invoice_id[:], false) || + !ReadText(*doc, doc.root, "invoice_url", link_bytes[:], true) || + !ReadProductID(*doc, doc.root, invoice.product_id[:]) || + !ReadTerms(*doc, doc.root, *invoice.amount, *invoice.units) { return false } + id := TextUntilNul(invoice.invoice_id[:]) + link := TextUntilNul(link_bytes[:]) + if !HexID(id, 32) || (invoice_id != "" && id != invoice_id) || + TextUntilNul(invoice.product_id[:]) != TextUntilNul(expected.product_id[:]) || + invoice.amount != expected.amount || invoice.units != expected.units || + (link != "" && !TelegramInvoiceLinkValid(link)) { return false } + invoice.state = ReadState(*doc, JsonMember(*doc, doc.root, "status")) + if invoice.state == .Unknown || (invoice_id == "" && invoice.state == .Pending && link == "") { return false } + if invoice.state == .Pending { invoice.invoice_url = link_bytes } + output.* = invoice + return true +} + +TelegramInvoiceLinkValid :: (link: string) -> bool { + dollar := "https://t.me/$" + invoice := "https://t.me/invoice/" + if link.count > dollar.count && link[:dollar.count] == dollar { + return URLToken(link[dollar.count:], 1, 128) + } + if link.count > invoice.count && link[:invoice.count] == invoice { + return URLToken(link[invoice.count:], 1, 128) + } + return false +} + +#scope_file +HexID :: (value: string, length: s64) -> bool { + if value.count != length { return false } + for byte: value { + if !((byte >= #char "0" && byte <= #char "9") || (byte >= #char "a" && byte <= #char "f")) { return false } + } + return true +} + +URLToken :: (value: string, minimum: s64, maximum: s64, allow_dot: bool = false) -> bool { + if value.count < minimum || value.count > maximum { return false } + for byte: value { + if !((byte >= #char "a" && byte <= #char "z") || (byte >= #char "A" && byte <= #char "Z") || + (byte >= #char "0" && byte <= #char "9") || byte == #char "_" || byte == #char "-" || + (allow_dot && byte == #char ".")) { return false } + } + return true +} + +ValidID :: (value: string, minimum: s64, maximum: s64) -> bool { + return value != "." && value != ".." && URLToken(value, minimum, maximum, true) +} + +WriteRequest :: (app_id: string, init_data: string, product: string, request_id: string, output: *Vec(u8)) -> bool { + VecClear(< TelegramInitDataMax { return false } + for byte: init_data { + if byte < 32 || byte > 126 { return false } + } + if !BuilderAppend(< bool { + VecClear(< bool { + return body.count > 0 && body.count <= 16384 && JsonRead(doc, body) && UniqueObject(doc, doc.root) +} + +ReleaseDocument :: (doc: *JsonDocument) { + JsonReset(doc) + VecFree(doc.nodes) +} + +UniqueObject :: (doc: *JsonDocument, node: s32) -> bool { + if JsonKindOf(doc, node) != .Object || JsonCount(doc, node) > 32 { return false } + key: Vec(u8) + defer { VecFree(key) } + first := JsonFirst(doc, node) + while first >= 0 { + VecClear(key) + if !JsonKeyInto(doc, first, *key) || key.count == 0 || + JsonMember(doc, node, TextView(VecSlice(key, 0, key.count))) != first { return false } + first = JsonNext(doc, first) + } + return true +} + +ReadText :: (doc: *JsonDocument, object: s32, key: string, output: []u8, optional: bool) -> bool { + node := JsonMember(doc, object, key) + if optional && node < 0 { return true } + if JsonKindOf(doc, node) != .String { return false } + text: Vec(u8) + defer { VecFree(text) } + if !JsonStringInto(doc, node, *text) { return false } + for index: cast(s64)0..text.count - 1 { + if text[index] < 32 || text[index] == 127 { return false } + } + return CopyCString(TextView(VecSlice(text, 0, text.count)), output) +} + +ReadProductID :: (doc: *JsonDocument, node: s32, output: []u8) -> bool { + return ReadText(doc, node, "product_id", output, false) && ValidID(TextUntilNul(output), 1, 128) +} + +IsStars :: (doc: *JsonDocument, node: s32) -> bool { + return JsonIs(doc, JsonMember(doc, node, "currency"), TelegramStarsCurrency) +} + +ReadTerms :: (doc: *JsonDocument, node: s32, amount: *s64, units: *s64) -> bool { + count, count_ok := JsonInteger(doc, JsonMember(doc, node, "amount")) + quantity, quantity_ok := JsonInteger(doc, JsonMember(doc, node, "units")) + if !count_ok || !quantity_ok || count <= 0 || count > 9007199254740991 || + quantity <= 0 || quantity > 9007199254740991 { return false } + amount.* = count + units.* = quantity + return true +} + +ReadState :: (doc: *JsonDocument, node: s32) -> TelegramStarsState { + if JsonIs(doc, node, "pending") { return .Pending } + if JsonIs(doc, node, "credited") { return .Credited } + if JsonIs(doc, node, "cancelled") { return .Cancelled } + if JsonIs(doc, node, "failed") { return .Failed } + if JsonIs(doc, node, "expired") { return .Expired } + if JsonIs(doc, node, "refunded") { return .Refunded } + return .Unknown +} diff --git a/tests/telegram_mini_app_test.zi b/tests/telegram_mini_app_test.zi new file mode 100644 index 0000000..c3a2b8a --- /dev/null +++ b/tests/telegram_mini_app_test.zi @@ -0,0 +1,142 @@ +#import "Entity/telegram_mini_app" +#import "std/json_document" +#import "std/text_buffer" +#import "std/vec" + +// Synthetic wire fixtures. The price and link have no merchant binding. +Offer :: "{\"product_id\":\"dew_10\",\"title\":\"10 Dew\",\"amount\":23,\"units\":10000000}" +Launch :: "{\"app_id\":\"inbe\",\"start_param\":\"invite_ab-1\",\"chat_type\":\"private\",\"stars_available\":true}" +InvoiceID :: "a71c55c90123456789abcdef01234567" +InvoiceURL :: "https://t.me/$fake_invoice" +AccountID :: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789" + +PurchaseReply :: (id: string, product: string, currency: string, amount: string, + units: string, state: string, link: string) -> string { + data: Vec(u8) + BuilderPrint(*data, "{\"invoice_id\":\"%\",\"product_id\":\"%\",\"currency\":\"%\",\"amount\":%,\"units\":%,\"status\":\"%\",\"invoice_url\":\"%\"}", + id, product, currency, amount, units, state, link) + return BuilderFinish(data) +} + +FixtureCatalog :: (offers: string) -> string { + data: Vec(u8) + BuilderPrint(*data, "{\"currency\":\"XTR\",\"products\":[%]}", offers) + return BuilderFinish(data) +} + +CheckRequest :: () -> s32 { + scratch: Vec(u8) + init_data := "auth_date=123&user=%7B%22id%22%3A1%7D&start_param=next%2Bstep&hash=synthetic" + if !TelegramLaunchRequest("inbe", init_data, *scratch) { return 1 } + doc: JsonDocument + if !JsonRead(*doc, TextView(VecSlice(scratch, 0, scratch.count))) || JsonCount(*doc, doc.root) != 2 || + !JsonIs(*doc, JsonMember(*doc, doc.root, "app_id"), "inbe") || + !JsonIs(*doc, JsonMember(*doc, doc.root, "init_data"), init_data) { return 2 } + if !TelegramStarsInvoiceRequest("inbe", "dew_10", "purchase-123", init_data, *scratch) || + !JsonRead(*doc, TextView(VecSlice(scratch, 0, scratch.count))) || JsonCount(*doc, doc.root) != 4 || + !JsonIs(*doc, JsonMember(*doc, doc.root, "product_id"), "dew_10") || + !JsonIs(*doc, JsonMember(*doc, doc.root, "request_id"), "purchase-123") || + !JsonIs(*doc, JsonMember(*doc, doc.root, "init_data"), init_data) { return 3 } + if TelegramLaunchRequest("inbe", "", *scratch) || scratch.count != 0 || + TelegramLaunchRequest("inbe", "auth_date=123\r\n", *scratch) || + TelegramStarsInvoiceRequest("inbe", "dew_10", "xxx", init_data, *scratch) { return 4 } + if !TelegramStarsCatalogRequestPath("inbe", *scratch) || + TextView(VecSlice(scratch, 0, scratch.count)) != "/api/v1/tokens/purchases/telegram/catalog?app_id=inbe" || + TelegramStarsCatalogRequestPath("inbe&app_id=other", *scratch) || scratch.count != 0 { return 5 } + if !TelegramStarsStatusRequestPath(InvoiceID, *scratch) || + TextView(VecSlice(scratch, 0, scratch.count)) != "/api/v1/tokens/purchases/telegram/invoices/a71c55c90123456789abcdef01234567" || + TelegramStarsStatusRequestPath("id%2Fadmin", *scratch) || + TelegramStarsStatusRequestPath("../id", *scratch) { return 6 } + if !TelegramStarsCancelRequestPath(InvoiceID, *scratch) || + TextView(VecSlice(scratch, 0, scratch.count)) != "/api/v1/tokens/purchases/telegram/invoices/a71c55c90123456789abcdef01234567/cancel" || + TelegramStarsCancelRequestPath("a71c55c9", *scratch) || scratch.count != 0 || + !TelegramStarsBalanceRequestPath("inbe", *scratch) || + TextView(VecSlice(scratch, 0, scratch.count)) != "/api/v1/tokens/purchases/telegram/balance?app_id=inbe" { return 7 } + return 0 +} + +CheckLaunch :: () -> s32 { + launch: TelegramLaunchContext + if !TelegramReadLaunch(Launch, "inbe", *launch) || !launch.stars_available || + TextUntilNul(launch.start_param[:]) != "invite_ab-1" || TextUntilNul(launch.chat_type[:]) != "private" { return 11 } + if TelegramReadLaunch(Launch, "other", *launch) || launch.stars_available || launch.start_param[0] != 0 { return 12 } + if !TelegramReadLaunch("{\"app_id\":\"inbe\",\"stars_available\":false}", "inbe", *launch) || + launch.stars_available || launch.start_param[0] != 0 || launch.chat_type[0] != 0 { return 13 } + if TelegramReadLaunch("{\"app_id\":\"inbe\",\"stars_available\":false,\"stars_availabl\\u0065\":true}", "inbe", *launch) || + TelegramReadLaunch("{\"app_id\":\"inbe\",\"start_param\":\"https://invalid\",\"stars_available\":true}", "inbe", *launch) || + TelegramReadLaunch("{\"app_id\":\"inbe\",\"chat_type\":\"private\\u0000suffix\",\"stars_available\":true}", "inbe", *launch) || + TelegramReadLaunch("{\"app_id\":\"inbe\",\"stars_available\":\"true\"}", "inbe", *launch) { return 14 } + return 0 +} + +CheckPurchase :: () -> s32 { + catalog: TelegramStarsCatalog + if !TelegramReadStarsCatalog(FixtureCatalog(Offer), *catalog) || catalog.count != 1 || + TextUntilNul(catalog.products[0].title[:]) != "10 Dew" || catalog.products[0].amount != 23 || + catalog.products[0].units != 10000000 { return 21 } + expected := catalog.products[0] + duplicate: Vec(u8) + BuilderPrint(*duplicate, "%,%", Offer, Offer) + if TelegramReadStarsCatalog(FixtureCatalog(BuilderFinish(duplicate)), *catalog) || catalog.count != 0 || + !TelegramReadStarsCatalog(FixtureCatalog(""), *catalog) || catalog.count != 0 { return 22 } + if TelegramReadStarsCatalog("{\"currency\":\"USD\",\"products\":[]}", *catalog) || + TelegramReadStarsCatalog(FixtureCatalog("{\"product_id\":\"dew_10\",\"title\":\"10 Dew\",\"amount\":2.3e1,\"units\":10000000}"), *catalog) || + TelegramReadStarsCatalog(FixtureCatalog("{\"product_id\":\"dew_10\",\"title\":\"10 Dew\",\"amount\":23,\"units\":9007199254740992}"), *catalog) { return 23 } + + invoice: TelegramStarsInvoice + pending := PurchaseReply(InvoiceID, "dew_10", "XTR", "23", "10000000", "pending", InvoiceURL) + if !TelegramReadStarsInvoice(pending, *expected, "", *invoice) || invoice.state != .Pending || + TextUntilNul(invoice.invoice_id[:]) != InvoiceID || TextUntilNul(invoice.invoice_url[:]) != InvoiceURL { return 24 } + if TelegramReadStarsInvoice(pending, *expected, "different", *invoice) || invoice.state != .Unknown || + invoice.invoice_url[0] != 0 { return 25 } + pending_status := "{\"invoice_id\":\"a71c55c90123456789abcdef01234567\",\"product_id\":\"dew_10\",\"currency\":\"XTR\",\"amount\":23,\"units\":10000000,\"status\":\"pending\"}" + if !TelegramReadStarsInvoice(pending_status, *expected, InvoiceID, *invoice) || + invoice.state != .Pending || invoice.invoice_url[0] != 0 { return 30 } + if TelegramReadStarsInvoice(PurchaseReply(InvoiceID, "dew_100", "XTR", "23", "10000000", "credited", ""), *expected, InvoiceID, *invoice) || + TelegramReadStarsInvoice(PurchaseReply(InvoiceID, "dew_10", "USD", "23", "10000000", "credited", ""), *expected, InvoiceID, *invoice) || + TelegramReadStarsInvoice(PurchaseReply(InvoiceID, "dew_10", "XTR", "24", "10000000", "credited", ""), *expected, InvoiceID, *invoice) || + TelegramReadStarsInvoice(PurchaseReply(InvoiceID, "dew_10", "XTR", "23", "20000000", "credited", ""), *expected, InvoiceID, *invoice) { return 26 } + if TelegramReadStarsInvoice(PurchaseReply(InvoiceID, "dew_10", "XTR", "23", "10000000", "paid", ""), *expected, InvoiceID, *invoice) || + TelegramReadStarsInvoice(PurchaseReply(InvoiceID, "dew_10", "XTR", "23", "10000000", "pending", ""), *expected, "", *invoice) || + TelegramReadStarsInvoice(PurchaseReply(InvoiceID, "dew_10", "XTR", "23", "10000000", "pending", "https://t.me/$bad?redirect=x"), *expected, "", *invoice) || + TelegramInvoiceLinkValid("https://t.me@untrusted.example/$invoice") || + TelegramInvoiceLinkValid("https://t.me/invoice/x/y") || + !TelegramInvoiceLinkValid("https://t.me/invoice/sample-1_") { return 27 } + statuses: [5]string = .["credited", "cancelled", "failed", "expired", "refunded"] + states: [5]TelegramStarsState = .[.Credited, .Cancelled, .Failed, .Expired, .Refunded] + for status, index: statuses { + body := PurchaseReply(InvoiceID, "dew_10", "XTR", "23", "10000000", status, InvoiceURL) + if !TelegramReadStarsInvoice(body, *expected, InvoiceID, *invoice) || invoice.state != states[index] || + invoice.invoice_url[0] != 0 { return 28 } + } + if TelegramInvoiceClosedState("paid") != .Paid || TelegramInvoiceClosedState("pending") != .Pending || + TelegramInvoiceClosedState("cancelled") != .Cancelled || TelegramInvoiceClosedState("failed") != .Failed || + TelegramInvoiceClosedState("credited") != .Unknown { return 29 } + return 0 +} + +CheckBalance :: () -> s32 { + response: Vec(u8) + defer { VecFree(response) } + BuilderPrint(*response, "{\"account_id\":\"%\",\"app_id\":\"inbe\",\"asset_id\":\"waozi:token\",\"balance\":-10000000}", AccountID) + reply := TextView(VecSlice(response, 0, response.count)) + balance: s64 + if !TelegramReadStarsBalance(reply, AccountID, "inbe", *balance) || balance != -10000000 || + TelegramReadStarsBalance(reply, AccountID, "other", *balance) || balance != 0 || + TelegramReadStarsBalance(reply, "different-account", "inbe", *balance) { return 31 } + VecClear(response) + BuilderPrint(*response, "{\"account_id\":\"%\",\"app_id\":\"inbe\",\"asset_id\":\"other:asset\",\"balance\":150}", AccountID) + if TelegramReadStarsBalance(TextView(VecSlice(response, 0, response.count)), AccountID, "inbe", *balance) { return 32 } + return 0 +} + +#program_export +main :: () -> s32 { + status := CheckRequest() + if status != 0 { return status } + status = CheckLaunch() + if status != 0 { return status } + status = CheckPurchase() + if status != 0 { return status } + return CheckBalance() +} diff --git a/ziran.toml b/ziran.toml index 91c6487..4c06c0a 100644 --- a/ziran.toml +++ b/ziran.toml @@ -19,6 +19,7 @@ referral_model = "src/referral_model.zi" referral_native = "src/referral_native.zi" model = "src/model.zi" telegram_connection = "src/telegram_connection.zi" +telegram_mini_app = "src/telegram_mini_app.zi" profile_appearance = "src/profile_appearance.zi" dew_model = "src/dew_model.zi" dew_view = "src/dew_view.zi"