diff --git a/CHANGELOG.md b/CHANGELOG.md index c63368e..dfa9bed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- Return linked Lumi replies to the exact originating private Telegram message, with a replay-safe delivery receipt. + - Relay private Lumi developer turns for the configured Mesh owner account. - Rename Daochi to Mesh at mesh.ziran-lang.org, preserving existing account keys, encrypted records and installed-client access. diff --git a/docs/lumi.md b/docs/lumi.md index d662a45..016b061 100644 --- a/docs/lumi.md +++ b/docs/lumi.md @@ -101,11 +101,15 @@ Lumi in Inner Breeze using a one-use link. Account signing keys stay in the app. for tasks, habits, diary entries, progress and feedback. `/app` and `/history` open Inner Breeze. App actions require the linked app to remain open and the corresponding sub-app to be installed. Feedback still asks for approval. -Telegram is input-only for the Lumi conversation. Incoming messages and their -Lumi responses remain in the app's full history and encrypted account sync. -App messages, responses and activity never mirror to the bot. The legacy -`POST /api/v1/lumi/telegram/messages` endpoint validates and acknowledges older -client uploads without any external delivery, including stale queued history. +Messages sent to the bot and their responses remain in the app's full history +and encrypted account sync. When the linked app handles a Telegram message, +it can attach its final answer to the authenticated `/api/v1/lumi/telegram/ack` +request as `reply` alongside the update ID and the claiming app client. Mesh +sends that answer once, as a direct reply to the original Telegram message. +App-originated conversations and activity stay in the app. The legacy +`POST /api/v1/lumi/telegram/messages` endpoint acknowledges history uploads +without external delivery. An unconfirmed delivery consumes the update to +prevent duplicate replies. Direct bot linking, help and explicit authorization acknowledgements remain. An hourly job inside the node deletes what Lumi no longer needs. When the app diff --git a/lumi_group.zi b/lumi_group.zi index e22d4c4..330bd59 100644 --- a/lumi_group.zi +++ b/lumi_group.zi @@ -106,7 +106,7 @@ Handle :: (service: chat.Chat, writer: http.ResponseWriter, request: *http.Reque unused transport.Typing(configuration.LumiBotToken, destination) content = chat.GroupReply(service, writer, request, input) } - delivered := transport.DeliverReply(configuration.LumiBotToken, destination, message, thread, content) + delivered := transport.DeliverReply(configuration.LumiBotToken, destination, message, thread, content, true) state := ifx delivered.message_id > 0 then "delivered" else "uncertain" if delivered.message_id == 0 { if delivered.error_code >= 400 && delivered.error_code < 500 { diff --git a/lumi_telegram.zi b/lumi_telegram.zi index 1440d80..6def723 100644 --- a/lumi_telegram.zi +++ b/lumi_telegram.zi @@ -1,5 +1,5 @@ -// Telegram is an authorized input transport for the app conversation. -// It queues app-owned actions; it never receives an account signing key. +// Telegram queues app-owned actions and receives replies to its own messages. +// Account signing keys stay in the app. #import "std/go_types" chat :: #import "chat"; entries :: #import "telegram_account_entry"; @@ -21,6 +21,7 @@ group :: #import "lumi_group"; strings :: #system_library "go:strings"; native_sql :: #system_library "go:database/sql"; Join :: (parts: []string, separator: string) -> string #foreign strings; +TrimSpace :: (value: string) -> string #foreign strings; RollbackAtReturn :: (transaction: *sql.Transaction) #go_defer #foreign native_sql "(*Tx).Rollback"; LinkResponse :: struct { @@ -65,6 +66,7 @@ LumiUpdate :: struct { kind: string #go_tag "json:\"kind\"" text: string #go_tag "json:\"text\"" choice: isize #go_tag "json:\"choice\"" + can_reply: bool #go_tag "json:\"can_reply,omitempty\"" } LumiPoll :: struct { linked: bool #go_tag "json:\"linked\"" @@ -74,6 +76,7 @@ LumiPoll :: struct { LumiReceipt :: struct { id: s64 #go_tag "json:\"id\"" client: string #go_tag "json:\"client\"" + reply: string #go_tag "json:\"reply\"" } LumiMessage :: struct { id: string #go_tag "json:\"id\"" @@ -107,6 +110,14 @@ EnsureSchema :: (database: *sql.Database, context: ctx.Context) -> bool { "ALTER TABLE server_lumi_updates ADD COLUMN done_at INTEGER NOT NULL DEFAULT 0") != null { return false } + if schema.AddColumn(database, context, "server_lumi_updates", "telegram_chat_id", + "ALTER TABLE server_lumi_updates ADD COLUMN telegram_chat_id INTEGER NOT NULL DEFAULT 0") != null || + schema.AddColumn(database, context, "server_lumi_updates", "telegram_message_id", + "ALTER TABLE server_lumi_updates ADD COLUMN telegram_message_id INTEGER NOT NULL DEFAULT 0") != null || + schema.AddColumn(database, context, "server_lumi_updates", "telegram_reply_id", + "ALTER TABLE server_lumi_updates ADD COLUMN telegram_reply_id INTEGER NOT NULL DEFAULT 0") != null { + return false + } // A delivered report is never copied to the owner again, even after its // copy is deleted. if schema.AddColumn(database, context, "server_app_feedback", "owner_delivered", @@ -228,6 +239,51 @@ ConsumeLink :: (database: *sql.Database, requestContext: ctx.Context, code: stri return result } +ReplyToUpdate :: (service: chat.Chat, writer: http.ResponseWriter, context: ctx.Context, + account: string, input: LumiReceipt, now: s64) { + arguments: [5]Any = .[account, input.id, input.client, now, 0] + destination: s64 + original: s64 + destinations: [2]Any = .[*destination, *original] + // Consume the exact app claim before contacting Telegram. A lost outbound + // response leaves an uncertain receipt and is never sent a second time. + row := sql.QueryRow(service.database, context, ClaimTelegramReply, arguments[0:4]) + scanned := sql.ScanRow(row, destinations[:]) + if scanned == sql.NoRows() { + delivered: s64 + delivery: [1]Any = .[*delivered] + row = sql.QueryRow(service.database, context, ReadTelegramReply, arguments[0:3]) + scanned = sql.ScanRow(row, delivery[:]) + if scanned == sql.NoRows() { + response.Error(writer, 409, "no matching Telegram message claim") + return + } + if scanned == null { + status: isize = ifx delivered > 0 then 200 else 202 + response.JSON(writer, status, true) + return + } + } + if scanned != null { + response.Error(writer, 503, "Telegram reply claim unavailable") + return + } + receipt := transport.DeliverReply(service.configuration.LumiBotToken, destination, original, 0, input.reply, false) + if receipt.message_id > 0 { + arguments[4] = receipt.message_id + saved := sql.Exec(service.database, ctx.Background(), + "UPDATE server_lumi_updates SET telegram_reply_id=?5 WHERE account_id=?1 AND id=?2 AND executor=?3 AND done_at=?4", arguments[:]) + if saved.error == null { + response.JSON(writer, 200, true) + return + } + print("Lumi private reply receipt could not be saved\n") + } else { + print("Lumi private reply delivery failed: http=% api=% reason=%\n", receipt.http_status, receipt.error_code, receipt.reason) + } + response.JSON(writer, 202, true) +} + Account :: (service: chat.Chat, writer: http.ResponseWriter, request: *http.Request, action: string) { user := auth.BearerUser(service.database, request, service.configuration.TokenSecret) if user.authentication.error != null || user.authentication.status != 0 { @@ -311,12 +367,18 @@ Account :: (service: chat.Chat, writer: http.ResponseWriter, request: *http.Requ return } if action == "ack" { - received := body.ReadJSON(writer, request, 256) + received := body.ReadJSON(writer, request, 32768) input: LumiReceipt - if received.error != null || json.Unmarshal(received.value, *input) != null || input.id == 0 || input.client.count != 64 { + if received.error != null || json.Unmarshal(received.value, *input) != null || + input.id == 0 || input.client.count != 64 || input.reply.count > 4096 || + (input.reply != "" && (input.id < 0 || TrimSpace(input.reply) == "")) { response.Error(writer, cast(isize)400, "invalid receipt") return } + if input.reply != "" { + ReplyToUpdate(service, writer, context, user.value, input, now) + return + } arguments[1] = input.id arguments[2] = input.client arguments[3] = now @@ -356,11 +418,12 @@ Account :: (service: chat.Chat, writer: http.ResponseWriter, request: *http.Requ result: LumiPoll result.linked = linked result.linked_at = linkedAt - updateDestinations: [4]Any = .[*result.update.id, *result.update.kind, *result.update.text, *result.update.choice] + updateDestinations: [5]Any = .[*result.update.id, *result.update.kind, *result.update.text, *result.update.choice, *result.update.can_reply] // Only the claiming app executes this update. Another signed-in device // gets its resulting conversation through encrypted sync. arguments[1] = client - row = sql.QueryRow(service.database, context, "UPDATE server_lumi_updates SET executor=?2 WHERE account_id=?1 AND done=0 AND id=(SELECT id FROM server_lumi_updates WHERE account_id=?1 AND done=0 ORDER BY id LIMIT 1) AND (executor='' OR executor=?2) RETURNING id,kind,text,choice", arguments[0:2]) + arguments[2] = destination + row = sql.QueryRow(service.database, context, "UPDATE server_lumi_updates SET executor=?2 WHERE account_id=?1 AND done=0 AND id=(SELECT id FROM server_lumi_updates WHERE account_id=?1 AND done=0 ORDER BY id LIMIT 1) AND (executor='' OR executor=?2) RETURNING id,kind,text,choice,(kind='message' AND telegram_chat_id=?3 AND telegram_chat_id>0 AND telegram_message_id>0)", arguments[0:3]) unused sql.ScanRow(row, updateDestinations[:]) response.JSON(writer, cast(isize)200, result) return @@ -409,10 +472,14 @@ Webhook :: (service: chat.Chat, entryService: entries.AccountEntries, writer: ht } received := body.ReadJSON(writer, request, 32768) update: TelegramUpdate - if received.error != null || json.Unmarshal(received.value, *update) != null || update.update_id <= 0 || !Schema(service, request) { + if received.error != null || json.Unmarshal(received.value, *update) != null || update.update_id <= 0 { response.Error(writer, cast(isize)400, "invalid update") return } + if !Schema(service, request) { + response.Error(writer, 503, "Telegram queue temporarily unavailable") + return + } message := update.message sender := message.from callback := update.callback_query @@ -442,6 +509,12 @@ Webhook :: (service: chat.Chat, entryService: entries.AccountEntries, writer: ht return } text := parsed.message + // Telegram also delivers non-text private updates, and retries any + // webhook response outside 2xx. Ignore unsupported messages once. + if callback.id == "" && (text.count == 0 || text.count >= 1024) { + response.JSON(writer, 200, true) + return + } if callback.id == "" && text.count == 44 && text[:12] == "/start auth_" { if !SendAccountMenu(service, entryService, request, sender.id, text[12:]) { unused transport.Deliver(service.configuration.LumiBotToken, sender.id, @@ -531,17 +604,10 @@ Webhook :: (service: chat.Chat, entryService: entries.AccountEntries, writer: ht choice = ifx callback.data[0] == cast(u8)89 then 1 else 2 unused transport.AnswerCallback(service.configuration.LumiBotToken, callback.id) } - if text.count == 0 || text.count >= 1024 { - response.Error(writer, cast(isize)400, "message too long") - return - } - arguments[0] = update.update_id - arguments[1] = account - arguments[2] = kind - arguments[3] = text - arguments[4] = choice + original := ifx kind == "message" then message.message_id else 0 + queued: [7]Any = .[update.update_id, account, kind, text, choice, sender.id, original] written := sql.Exec(service.database, context, - "INSERT OR IGNORE INTO server_lumi_updates(id,account_id,kind,text,choice) VALUES(?1,?2,?3,?4,?5)", arguments[:]) + "INSERT OR IGNORE INTO server_lumi_updates(id,account_id,kind,text,choice,telegram_chat_id,telegram_message_id) VALUES(?1,?2,?3,?4,?5,?6,?7)", queued[:]) if written.error != null { response.Error(writer, cast(isize)503, "app queue unavailable"); return } if kind == "message" { // Show at once that Lumi received the message; the app replies next. @@ -551,6 +617,21 @@ Webhook :: (service: chat.Chat, entryService: entries.AccountEntries, writer: ht } #scope_file +ClaimTelegramReply :: #string SQL +UPDATE server_lumi_updates SET done=1,done_at=?4,text='' +WHERE account_id=?1 AND id=?2 AND executor=?3 AND done=0 + AND kind='message' AND telegram_message_id>0 AND EXISTS( + SELECT 1 FROM server_lumi_telegram + WHERE account_id=?1 AND telegram_id=server_lumi_updates.telegram_chat_id) +RETURNING telegram_chat_id,telegram_message_id +SQL; +ReadTelegramReply :: #string SQL +SELECT telegram_reply_id FROM server_lumi_updates +WHERE account_id=?1 AND id=?2 AND executor=?3 AND done=1 + AND kind='message' AND telegram_message_id>0 AND EXISTS( + SELECT 1 FROM server_lumi_telegram + WHERE account_id=?1 AND telegram_id=server_lumi_updates.telegram_chat_id) +SQL; // An owner copy of a report holds the reporting account and report ID as JSON; // the CASE keeps other updates' plain text away from json_extract. ForgetReport :: "CREATE TRIGGER IF NOT EXISTS server_lumi_forget_report AFTER DELETE ON server_app_feedback BEGIN DELETE FROM server_lumi_updates WHERE kind='feedback' AND (CASE WHEN json_valid(text) THEN json_extract(text,'$.account_id') END)=OLD.account_id AND (CASE WHEN json_valid(text) THEN json_extract(text,'$.report_id') END)=OLD.id; END"; diff --git a/lumi_telegram_input_test.go b/lumi_telegram_input_test.go index a7427ca..b36f047 100644 --- a/lumi_telegram_input_test.go +++ b/lumi_telegram_input_test.go @@ -121,3 +121,95 @@ func TestLumiTelegramInputAPIDocumentation(t *testing.T) { t.Fatalf("Telegram paths differ: actual=%s expected=%s", a, b) } } + +func TestLumiTelegramRepliesOnlyToClaimedPrivateMessages(t *testing.T) { + server, store, _ := testServer(t) + server.Cfg.LumiBotToken = "direct-reply-fixture" + server.Cfg.LumiWebhookSecret = "direct-reply-webhook" + replies := make(chan TelegramReplySend, 8) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var reply TelegramReplySend + if strings.HasSuffix(r.URL.Path, "/sendMessage") && json.NewDecoder(r.Body).Decode(&reply) == nil && reply.ReplyParameters.MessageId > 0 { + replies <- reply + if reply.ReplyParameters.MessageId == 204 { + w.WriteHeader(http.StatusBadGateway) + return + } + } + _, _ = fmt.Fprint(w, `{"ok":true,"result":{"message_id":987}}`) + })) + defer upstream.Close() + previous := TelegramAPIBase + TelegramAPIBase = upstream.URL + t.Cleanup(func() { TelegramAPIBase = previous }) + handler := server.Routes() + account := newTestIdentity(t, handler, 0xc6) + other := newTestIdentity(t, handler, 0xc7) + client := strings.Repeat("a", 64) + otherClient := strings.Repeat("b", 64) + webhook := func(id int, text string) { + t.Helper() + if out := lumiWebhook(handler, server.Cfg.LumiWebhookSecret, id, "private", text); out.Code != 200 { + t.Fatalf("webhook %d: %d %s", id, out.Code, out.Body.String()) + } + } + ack := func(identity testIdentity, executor string, id, status int) { + t.Helper() + body := fmt.Sprintf(`{"id":%d,"client":%q,"reply":"A quiet morning 水"}`, id, executor) + out := lumiRequest(handler, identity, "POST", "/api/v1/lumi/telegram/ack", body) + if out.Code != status { + t.Fatalf("ack %d: status %d, want %d: %s", id, out.Code, status, out.Body.String()) + } + } + poll := func(id int64) { + t.Helper() + out := lumiRequest(handler, account, "GET", "/api/v1/lumi/telegram/updates?client="+client, "") + var result LumiPoll + if out.Code != 200 || json.Unmarshal(out.Body.Bytes(), &result) != nil || result.Update.ID != id { + t.Fatalf("poll %d: %d %s", id, out.Code, out.Body.String()) + } + } + webhook(201, "/start "+lumiLink(t, handler, account)) + webhook(205, "") + webhook(206, strings.Repeat("a", 1024)) + poll(0) + webhook(202, "What is mindful breathing?") + ack(account, client, 202, http.StatusConflict) + poll(202) + ack(other, client, 202, http.StatusConflict) + ack(account, otherClient, 202, http.StatusConflict) + ack(account, client, -1, http.StatusBadRequest) + ack(account, client, 202, http.StatusOK) + ack(account, client, 202, http.StatusOK) + webhook(202, "What is mindful breathing?") + poll(0) + select { + case reply := <-replies: + if reply.ChatId != 1234 || reply.Text != "A quiet morning 水" || reply.ReplyParameters.MessageId != 202 || reply.ReplyParameters.AllowSendingWithoutReply { + t.Fatalf("unexpected Telegram response: %+v", reply) + } + default: + t.Fatal("Telegram reply was not sent") + } + var receipt int64 + if err := store.Database.QueryRow("SELECT telegram_reply_id FROM server_lumi_updates WHERE id=202").Scan(&receipt); err != nil || receipt != 987 { + t.Fatalf("delivery receipt: %d %v", receipt, err) + } + webhook(204, "One more question") + poll(204) + ack(account, client, 204, http.StatusAccepted) + ack(account, client, 204, http.StatusAccepted) + select { + case reply := <-replies: + if reply.ReplyParameters.MessageId != 204 { + t.Fatalf("unexpected retry or misrouted delivery: %+v", reply) + } + default: + t.Fatal("uncertain delivery was never attempted") + } + select { + case reply := <-replies: + t.Fatalf("duplicate Telegram reply: %+v", reply) + default: + } +} diff --git a/telegram_paths.zi b/telegram_paths.zi index 64346e7..0d3c925 100644 --- a/telegram_paths.zi +++ b/telegram_paths.zi @@ -88,6 +88,7 @@ Document1 :: #string JSON_1 "/api/v1/lumi/telegram/ack": { "post": { "summary": "Acknowledge an action claimed by this app client", + "description": "An optional reply sends the final answer to the originating private Telegram message once. It requires the original account and claiming client. A 202 acknowledgement records that delivery could not be confirmed and prevents automatic replay.", "security": [ { "bearerAuth": [] @@ -95,7 +96,13 @@ Document1 :: #string JSON_1 ], "responses": { "200": { - "description": "Acknowledged" + "description": "Acknowledged. Any requested reply has a delivery receipt" + }, + "202": { + "description": "Acknowledged. Telegram delivery is unconfirmed" + }, + "409": { + "description": "No matching private Telegram message claim" }, "400": { "description": "Invalid receipt" @@ -109,7 +116,7 @@ Document1 :: #string JSON_1 "/api/v1/lumi/telegram/messages": { "post": { "summary": "Acknowledge a legacy Lumi conversation upload without sending to Telegram", - "description": "Telegram is input-only. Authenticated uploads from older apps drain silently, including stale history and previous uncertain deliveries. Conversation history remains in encrypted account sync. No Telegram text, actions or notifications are sent.", + "description": "Authenticated history uploads from older apps drain silently, including stale history and previous uncertain deliveries. Conversation history remains in encrypted account sync. No Telegram text, actions or notifications are sent.", "security": [ { "bearerAuth": [] diff --git a/telegram_transport.zi b/telegram_transport.zi index 1889bc2..241590f 100644 --- a/telegram_transport.zi +++ b/telegram_transport.zi @@ -70,10 +70,12 @@ ReplyAnswer :: struct { description: string #go_tag "json:\"description\"" } -DeliverReply :: (token: string, destination: s64, original: s64, thread: s64, content: string) -> MessageReceipt { +DeliverReply :: (token: string, destination: s64, original: s64, thread: s64, content: string, + allowSendingWithoutReply: bool) -> MessageReceipt { failed: MessageReceipt encoded := json.Marshal(TelegramReplySend.{chat_id = destination, text = content, - message_thread_id = thread, reply_parameters = ReplyParameters.{message_id = original, allow_sending_without_reply = true}}) + message_thread_id = thread, reply_parameters = ReplyParameters.{message_id = original, + allow_sending_without_reply = allowSendingWithoutReply}}) if encoded.error != null { return failed } diff --git a/testdata/telegram_paths.json b/testdata/telegram_paths.json index f064759..9f76d2b 100644 --- a/testdata/telegram_paths.json +++ b/testdata/telegram_paths.json @@ -74,6 +74,7 @@ "/api/v1/lumi/telegram/ack": { "post": { "summary": "Acknowledge an action claimed by this app client", + "description": "An optional reply sends the final answer to the originating private Telegram message once. It requires the original account and claiming client. A 202 acknowledgement records that delivery could not be confirmed and prevents automatic replay.", "security": [ { "bearerAuth": [] @@ -81,7 +82,13 @@ ], "responses": { "200": { - "description": "Acknowledged" + "description": "Acknowledged. Any requested reply has a delivery receipt" + }, + "202": { + "description": "Acknowledged. Telegram delivery is unconfirmed" + }, + "409": { + "description": "No matching private Telegram message claim" }, "400": { "description": "Invalid receipt" @@ -95,7 +102,7 @@ "/api/v1/lumi/telegram/messages": { "post": { "summary": "Acknowledge a legacy Lumi conversation upload without sending to Telegram", - "description": "Telegram is input-only. Authenticated uploads from older apps drain silently, including stale history and previous uncertain deliveries. Conversation history remains in encrypted account sync. No Telegram text, actions or notifications are sent.", + "description": "Authenticated history uploads from older apps drain silently, including stale history and previous uncertain deliveries. Conversation history remains in encrypted account sync. No Telegram text, actions or notifications are sent.", "security": [ { "bearerAuth": []