6 Commits
17 changed files with 498 additions and 50 deletions
+14 -6
View File
@@ -76,8 +76,8 @@ func (s *Server) handleCallAction(w http.ResponseWriter, r *http.Request, config
return true
}
duration = time.Duration(request.DurationSeconds) * time.Second
if duration < time.Second || duration > maxCallDuration {
writeError(w, http.StatusBadRequest, "invalid_duration", "duration_seconds must be between 1 and 600")
if duration < 0 || duration > maxCallDuration {
writeError(w, http.StatusBadRequest, "invalid_duration", "duration_seconds must be 0 (no automatic hang-up) or between 1 and 600")
return true
}
command = "ATD" + number + ";"
@@ -137,7 +137,9 @@ func (s *Server) handleCallAction(w http.ResponseWriter, r *http.Request, config
if call, ok := result.(vowifi.Call); ok {
callID = call.ID
}
go s.hangupVoWiFiAfter(config.ID, callID, duration)
if duration > 0 {
go s.hangupVoWiFiAfter(config.ID, callID, duration)
}
}
s.recordAudit(r.Context(), "admin", "call."+action, "device", config.ID, "success", transport)
writeJSON(w, http.StatusAccepted, map[string]any{"data": map[string]any{
@@ -158,7 +160,9 @@ func (s *Server) handleCallAction(w http.ResponseWriter, r *http.Request, config
return true
}
if action == "dial" {
go s.hangupAfter(config.ID, physicalID, duration)
if duration > 0 {
go s.hangupAfter(config.ID, physicalID, duration)
}
}
s.recordAudit(r.Context(), "admin", "call."+action, "device", config.ID, "success", transport)
writeJSON(w, http.StatusAccepted, map[string]any{
@@ -179,7 +183,7 @@ func resolveVoWiFiCallID(controller VoWiFiCallController, deviceID, id, required
return "", err
}
for _, call := range calls {
if requiredState == "" || call.State == requiredState {
if call.State != "ended" && call.State != "failed" && (requiredState == "" || call.State == requiredState) {
return call.ID, nil
}
}
@@ -203,7 +207,11 @@ func (s *Server) hangupVoWiFiAfter(deviceID, callID string, duration time.Durati
func (s *Server) callTransport(deviceID string) string {
if s.vowifi != nil {
if state, err := s.vowifi.State(deviceID); err == nil && state.Enabled {
// Enabled is only the desired card policy. Calls can use IMS only after
// registration has actually completed; otherwise keep using the modem's
// circuit-switched call path instead of routing into an unavailable IMS
// session.
if state, err := s.vowifi.State(deviceID); err == nil && state.IMSReady {
return "vowifi"
}
}
+43
View File
@@ -1,9 +1,11 @@
package server
import (
"context"
"testing"
"vocat/internal/modem"
"vocat/internal/vowifi"
)
func TestParseCLCC(t *testing.T) {
@@ -28,3 +30,44 @@ func TestValidDialNumber(t *testing.T) {
}
}
}
func TestCallTransportRequiresIMSReady(t *testing.T) {
controller := &fakeVoWiFiController{state: vowifi.State{Enabled: true}}
server := &Server{vowifi: controller}
if got := server.callTransport("ec20"); got != "cellular" {
t.Fatalf("callTransport before IMS registration = %q, want cellular", got)
}
controller.state.IMSReady = true
if got := server.callTransport("ec20"); got != "vowifi" {
t.Fatalf("callTransport with IMS ready = %q, want vowifi", got)
}
}
func TestResolveVoWiFiCallIDIgnoresTerminalCalls(t *testing.T) {
controller := &fakeCallController{calls: []vowifi.Call{
{ID: "failed", State: "failed"},
{ID: "active", State: "active"},
}}
got, err := resolveVoWiFiCallID(controller, "ec20", "", "")
if err != nil || got != "active" {
t.Fatalf("resolveVoWiFiCallID() = %q, %v; want active", got, err)
}
}
type fakeCallController struct {
calls []vowifi.Call
}
func (controller *fakeCallController) Calls(string) ([]vowifi.Call, error) {
return controller.calls, nil
}
func (*fakeCallController) DialCall(context.Context, string, string) (vowifi.Call, error) {
return vowifi.Call{}, nil
}
func (*fakeCallController) AnswerCall(context.Context, string, string) (vowifi.Call, error) {
return vowifi.Call{}, nil
}
func (*fakeCallController) HangupCall(context.Context, string, string) error { return nil }
+30 -1
View File
@@ -3,11 +3,13 @@ package server
import (
"context"
"encoding/json"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"vocat/internal/device"
"vocat/internal/modem"
@@ -354,7 +356,22 @@ func TestHandleUpdateCheckUsesTrustedRepository(t *testing.T) {
}
func TestHandleUpdateApplyInstallsFromTrustedRepository(t *testing.T) {
database, err := store.Open(context.Background(), ":memory:")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = database.Close() })
if err := database.SetAdmin(context.Background(), "admin", []byte("hash")); err != nil {
t.Fatal(err)
}
tokenHash := []byte("active-session")
if err := database.CreateSession(
context.Background(), 1, tokenHash, []byte("csrf"), time.Now().Add(time.Hour),
); err != nil {
t.Fatal(err)
}
server := &Server{
store: database,
logger: regionTestLogger(),
updateRepository: update.DefaultRepository,
updateApply: func(_ context.Context, _ *slog.Logger, options update.Options, restart bool) (update.CheckResult, error) {
@@ -370,9 +387,21 @@ func TestHandleUpdateApplyInstallsFromTrustedRepository(t *testing.T) {
t.Fatalf("status = %d, body = %s", recorder.Code, recorder.Body)
}
data := decodeData(t, recorder)
if data["applied"] != true || data["version"] != "9.9.9" {
if data["applied"] != true || data["version"] != "9.9.9" || data["reauthentication_required"] != true {
t.Fatalf("apply data = %#v", data)
}
if _, err := database.SessionByTokenHash(context.Background(), tokenHash); !errors.Is(err, store.ErrNotFound) {
t.Fatalf("session must be revoked after update, got %v", err)
}
expired := map[string]bool{}
for _, cookie := range recorder.Result().Cookies() {
if cookie.MaxAge < 0 {
expired[cookie.Name] = true
}
}
if !expired[sessionCookieName] || !expired[csrfCookieName] {
t.Fatalf("auth cookies were not expired: %#v", recorder.Result().Cookies())
}
}
func TestE911WebsheetFlow(t *testing.T) {
+14 -3
View File
@@ -421,11 +421,22 @@ func (s *Server) handleUpdateApply(w http.ResponseWriter, r *http.Request) {
})
return
}
// A binary update changes the trusted server code underneath every active
// browser/API session. Revoke every durable token before scheduling the
// restart and expire this client's cookies so all users must authenticate
// against the newly installed version.
if err := s.store.DeleteAllSessions(r.Context()); err != nil {
s.logger.Error("revoke sessions after update failed", "error", err)
writeError(w, http.StatusInternalServerError, "update_session_revocation_failed", "The update was installed, but active sessions could not be revoked; restart the service and sign in again.")
return
}
s.clearAuthCookies(w)
writeJSON(w, http.StatusOK, map[string]any{
"data": map[string]any{
"applied": true,
"version": result.Latest,
"message": "Update verified and installed; the service is restarting.",
"applied": true,
"version": result.Latest,
"reauthentication_required": true,
"message": "Update verified and installed; all sessions were revoked and the service is restarting.",
},
})
if flusher, ok := w.(http.Flusher); ok {
+4 -2
View File
@@ -21,6 +21,8 @@ import (
// USSD, and USB-net results are configurable for the feature endpoint tests.
type fakeDeviceController struct {
entry device.Device
atResponse modem.Response
atErr error
scanResult device.OperatorScanResult
scanErr error
ussdResult device.USSDResult
@@ -43,11 +45,11 @@ func (f fakeDeviceController) Refresh(context.Context, string) (device.Snapshot,
return device.Snapshot{}, nil
}
func (f fakeDeviceController) ExecuteAT(context.Context, string, string) (modem.Response, error) {
return modem.Response{}, nil
return f.atResponse, f.atErr
}
func (f fakeDeviceController) Reboot(context.Context, string) error { return nil }
func (f fakeDeviceController) USSD(context.Context, string, string) (device.USSDResult, error) {
return device.USSDResult{}, nil
return f.ussdResult, f.ussdErr
}
func (f fakeDeviceController) ContinueUSSD(context.Context, string, string) (device.USSDResult, error) {
return f.ussdResult, f.ussdErr
+20 -9
View File
@@ -260,8 +260,7 @@ func (s *Server) handleSession(w http.ResponseWriter, r *http.Request) {
}
session, csrfToken, err := s.auth.CSRFToken(r.Context(), sessionToken, existingCSRF)
if errors.Is(err, auth.ErrUnauthorized) {
s.clearAuthCookies(w)
writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required")
s.authenticationRequired(w, r)
return
}
if err != nil {
@@ -296,8 +295,7 @@ func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
if _, err := s.auth.ValidateCSRF(r.Context(), sessionToken, csrfToken); err != nil {
switch {
case errors.Is(err, auth.ErrUnauthorized):
s.clearAuthCookies(w)
writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required")
s.authenticationRequired(w, r)
case errors.Is(err, auth.ErrInvalidCSRF):
writeError(w, http.StatusForbidden, "invalid_csrf", "CSRF validation failed")
default:
@@ -346,8 +344,7 @@ func (s *Server) handleAPI(w http.ResponseWriter, r *http.Request) {
if _, err := s.auth.ValidateCSRF(r.Context(), sessionToken, csrfToken); err != nil {
switch {
case errors.Is(err, auth.ErrUnauthorized):
s.clearAuthCookies(w)
writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required")
s.authenticationRequired(w, r)
case errors.Is(err, auth.ErrInvalidCSRF):
writeError(w, http.StatusForbidden, "invalid_csrf", "CSRF validation failed")
default:
@@ -419,7 +416,7 @@ func (s *Server) decodeJSON(w http.ResponseWriter, r *http.Request, destination
func (s *Server) sessionToken(w http.ResponseWriter, r *http.Request) (string, bool) {
cookie, err := r.Cookie(sessionCookieName)
if err != nil || cookie.Value == "" {
writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required")
s.authenticationRequired(w, r)
return "", false
}
return cookie.Value, true
@@ -432,8 +429,7 @@ func (s *Server) requireAuthenticated(w http.ResponseWriter, r *http.Request) bo
}
if _, err := s.auth.Authenticate(r.Context(), sessionToken); err != nil {
if errors.Is(err, auth.ErrUnauthorized) {
s.clearAuthCookies(w)
writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required")
s.authenticationRequired(w, r)
} else {
s.logger.Error("request authentication failed", "error", err)
writeError(w, http.StatusInternalServerError, "internal_error", "an internal error occurred")
@@ -443,6 +439,21 @@ func (s *Server) requireAuthenticated(w http.ResponseWriter, r *http.Request) bo
return true
}
// authenticationRequired preserves JSON semantics for API clients while
// making a direct browser navigation land on the login screen instead of a
// raw {"error":...} document. Frontend fetches explicitly request JSON and
// are handled by the shared vocat:unauthorized event.
func (s *Server) authenticationRequired(w http.ResponseWriter, r *http.Request) {
s.clearAuthCookies(w)
w.Header().Set("Cache-Control", "no-store")
if (r.Method == http.MethodGet || r.Method == http.MethodHead) &&
strings.Contains(strings.ToLower(r.Header.Get("Accept")), "text/html") {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
writeError(w, http.StatusUnauthorized, "unauthorized", "authentication is required")
}
func (s *Server) validateDoubleSubmitCSRF(w http.ResponseWriter, r *http.Request) (string, bool) {
headerToken := r.Header.Get(csrfHeaderName)
cookie, err := r.Cookie(csrfCookieName)
+24
View File
@@ -241,6 +241,30 @@ func TestUnifiedAPIErrors(t *testing.T) {
}
}
func TestUnauthenticatedBrowserNavigationRedirectsToLogin(t *testing.T) {
app := newTestApplication(t)
client := *app.client
client.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
}
request, err := http.NewRequest(http.MethodGet, app.server.URL+"/api/devices", nil)
if err != nil {
t.Fatal(err)
}
request.Header.Set("Accept", "text/html,application/xhtml+xml")
response, err := client.Do(request)
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusSeeOther {
t.Fatalf("navigation status = %d", response.StatusCode)
}
if location := response.Header.Get("Location"); location != "/login" {
t.Fatalf("navigation location = %q", location)
}
}
func TestNewRequiresIndex(t *testing.T) {
database, err := store.Open(context.Background(), ":memory:")
if err != nil {
+167 -5
View File
@@ -11,6 +11,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"regexp"
"strconv"
"strings"
"sync"
@@ -30,6 +31,8 @@ const (
telegramMaxDialDuration = 10 * time.Minute
)
var telegramTokenInURLPattern = regexp.MustCompile(`bot[0-9]{5,20}:[A-Za-z0-9_-]{20,128}`)
type telegramRuntimeConfig struct {
Token string
ChatID string
@@ -146,6 +149,9 @@ func (bot *telegramBot) poll(ctx context.Context) {
updates, pollErr := bot.getUpdates(pollContext, config, offset, 5)
cancel()
if pollErr != nil {
if ctx.Err() != nil {
return
}
bot.warn("poll Telegram updates", pollErr)
if !waitTelegram(ctx, telegramPollInterval) {
return
@@ -186,6 +192,10 @@ func (bot *telegramBot) bootstrap(ctx context.Context, config telegramRuntimeCon
{"command": "call", "description": "限时拨号并自动挂断(需要确认)"},
{"command": "calls", "description": "查看当前通话"},
{"command": "hangup", "description": "挂断通话"},
{"command": "at", "description": "向指定设备发送安全 AT 指令"},
{"command": "ussd", "description": "向指定设备发送 USSD 指令"},
{"command": "ussd_reply", "description": "回复交互式 USSD 会话"},
{"command": "ussd_cancel", "description": "取消交互式 USSD 会话"},
{"command": "help", "description": "查看命令帮助"},
}
_ = bot.call(requestContext, config, "setMyCommands", map[string]any{"commands": commands}, nil)
@@ -274,6 +284,34 @@ func (bot *telegramBot) handleUpdate(ctx context.Context, config telegramRuntime
bot.executeSimpleCallAction(ctx, config, message.Chat.ID, message.From.ID, strings.TrimSpace(remainder), "hangup")
case "calls":
bot.executeSimpleCallAction(ctx, config, message.Chat.ID, message.From.ID, strings.TrimSpace(remainder), "status")
case "at":
parts := splitTelegramArguments(remainder, 2)
if len(parts) != 2 {
bot.sendText(ctx, config, message.Chat.ID, "用法:/at <设备ID> <AT指令>\n示例:/at EC20 AT+CSQ", nil)
return
}
bot.handleATCommand(ctx, config, message.Chat.ID, message.From.ID, parts[0], parts[1])
case "ussd":
parts := strings.Fields(remainder)
if len(parts) != 2 {
bot.sendText(ctx, config, message.Chat.ID, "用法:/ussd <设备ID> <USSD代码>\n示例:/ussd EC20 *100#", nil)
return
}
bot.handleUSSDCommand(ctx, config, message.Chat.ID, message.From.ID, parts[0], parts[1])
case "ussd_reply":
parts := splitTelegramArguments(remainder, 2)
if len(parts) != 2 {
bot.sendText(ctx, config, message.Chat.ID, "用法:/ussd_reply <会话ID> <回复内容>", nil)
return
}
bot.handleUSSDReply(ctx, config, message.Chat.ID, message.From.ID, parts[0], parts[1])
case "ussd_cancel":
sessionID := strings.TrimSpace(remainder)
if sessionID == "" || strings.ContainsAny(sessionID, " \t\r\n") {
bot.sendText(ctx, config, message.Chat.ID, "用法:/ussd_cancel <会话ID>", nil)
return
}
bot.handleUSSDCancel(ctx, config, message.Chat.ID, message.From.ID, sessionID)
default:
bot.sendText(ctx, config, message.Chat.ID, "未知命令。发送 /help 查看可用操作。", nil)
}
@@ -329,6 +367,10 @@ func (bot *telegramBot) sendHelp(ctx context.Context, config telegramRuntimeConf
"/calls <设备ID> — 查看模块当前通话",
"/answer <设备ID> — 接听蜂窝来电",
"/hangup <设备ID> — 立即挂断",
"/at <设备ID> <AT指令> — 执行经过安全校验的单行 AT 指令",
"/ussd <设备ID> <代码> — 发送 USSD 指令",
"/ussd_reply <会话ID> <内容> — 回复交互式 USSD 菜单",
"/ussd_cancel <会话ID> — 取消交互式 USSD 会话",
"",
"Bot 不提供 eSIM 下载、删除或改名,也不采集或转发通话音频。控制命令只接受设置中的 Admin ID。",
}, "\n")
@@ -653,6 +695,112 @@ func (bot *telegramBot) executeSimpleCallAction(ctx context.Context, config tele
bot.server.recordAudit(ctx, fmt.Sprintf("telegram:%d", adminID), "telegram.call."+action, "device", deviceID, outcome, "telegram")
}
func (bot *telegramBot) handleATCommand(ctx context.Context, config telegramRuntimeConfig, chatID, adminID int64, deviceID, command string) {
result, err := bot.executeATCommand(ctx, deviceID, command)
outcome := "success"
if err != nil {
outcome = "failure"
bot.sendText(ctx, config, chatID, "AT 指令执行失败:"+err.Error(), nil)
} else {
bot.sendText(ctx, config, chatID, result, nil)
}
bot.server.recordAudit(ctx, fmt.Sprintf("telegram:%d", adminID), "telegram.at.execute", "device", deviceID, outcome, "telegram")
}
func (bot *telegramBot) executeATCommand(ctx context.Context, deviceID, command string) (string, error) {
command = strings.TrimSpace(command)
if err := validateATCommand(command); err != nil {
return "", err
}
_, _, physicalID, err := bot.device(deviceID)
if err != nil {
return "", err
}
operationContext, cancel := context.WithTimeout(ctx, 60*time.Second)
defer cancel()
response, err := bot.server.devices.ExecuteAT(operationContext, physicalID, command)
if err != nil {
return "", err
}
return fmt.Sprintf("设备:%s\n> %s\n\n%s", deviceID, command, formatTelegramAT(response)), nil
}
func (bot *telegramBot) handleUSSDCommand(ctx context.Context, config telegramRuntimeConfig, chatID, adminID int64, deviceID, code string) {
result, err := bot.executeUSSDCommand(ctx, deviceID, code)
outcome := "success"
if err != nil {
outcome = "failure"
bot.sendText(ctx, config, chatID, "USSD 指令执行失败:"+err.Error(), nil)
} else {
bot.sendText(ctx, config, chatID, formatTelegramUSSD(deviceID, result), nil)
}
bot.server.recordAudit(ctx, fmt.Sprintf("telegram:%d", adminID), "telegram.ussd.start", "device", deviceID, outcome, "telegram")
}
func (bot *telegramBot) executeUSSDCommand(ctx context.Context, deviceID, code string) (device.USSDResult, error) {
_, _, physicalID, err := bot.device(deviceID)
if err != nil {
return device.USSDResult{}, err
}
operationContext, cancel := context.WithTimeout(ctx, 90*time.Second)
defer cancel()
return bot.server.devices.USSD(operationContext, physicalID, strings.TrimSpace(code))
}
func (bot *telegramBot) handleUSSDReply(ctx context.Context, config telegramRuntimeConfig, chatID, adminID int64, sessionID, input string) {
operationContext, cancel := context.WithTimeout(ctx, 90*time.Second)
result, err := bot.server.devices.ContinueUSSD(operationContext, strings.TrimSpace(sessionID), strings.TrimSpace(input))
cancel()
outcome := "success"
if err != nil {
outcome = "failure"
bot.sendText(ctx, config, chatID, "USSD 回复失败:"+err.Error(), nil)
} else {
bot.sendText(ctx, config, chatID, formatTelegramUSSD("", result), nil)
}
bot.server.recordAudit(ctx, fmt.Sprintf("telegram:%d", adminID), "telegram.ussd.reply", "ussd_session", "interactive", outcome, "telegram")
}
func (bot *telegramBot) handleUSSDCancel(ctx context.Context, config telegramRuntimeConfig, chatID, adminID int64, sessionID string) {
operationContext, cancel := context.WithTimeout(ctx, 30*time.Second)
err := bot.server.devices.CancelUSSD(operationContext, strings.TrimSpace(sessionID))
cancel()
outcome := "success"
if err != nil {
outcome = "failure"
bot.sendText(ctx, config, chatID, "取消 USSD 会话失败:"+err.Error(), nil)
} else {
bot.sendText(ctx, config, chatID, "USSD 会话已取消。", nil)
}
bot.server.recordAudit(ctx, fmt.Sprintf("telegram:%d", adminID), "telegram.ussd.cancel", "ussd_session", "interactive", outcome, "telegram")
}
func formatTelegramUSSD(deviceID string, result device.USSDResult) string {
lines := make([]string, 0, 7)
if strings.TrimSpace(deviceID) != "" {
lines = append(lines, "设备:"+strings.TrimSpace(deviceID))
}
if strings.TrimSpace(result.Code) != "" {
lines = append(lines, "USSD"+strings.TrimSpace(result.Code))
}
lines = append(lines, "状态:"+firstNonEmpty(strings.TrimSpace(result.Status), "final"))
if strings.TrimSpace(result.Text) != "" {
lines = append(lines, "\n"+strings.TrimSpace(result.Text))
} else if strings.TrimSpace(result.Raw) != "" {
lines = append(lines, "\n"+strings.TrimSpace(result.Raw))
} else {
lines = append(lines, "\n网络未返回文本内容。")
}
if result.Continueable && strings.TrimSpace(result.SessionID) != "" {
lines = append(lines,
"\n网络正在等待输入。",
"回复:/ussd_reply "+result.SessionID+" <内容>",
"取消:/ussd_cancel "+result.SessionID,
)
}
return strings.Join(lines, "\n")
}
func (bot *telegramBot) handleVoWiFi(ctx context.Context, config telegramRuntimeConfig, chatID, adminID int64, deviceID, operation string) {
stored, entry, _, err := bot.device(deviceID)
if err != nil {
@@ -828,7 +976,7 @@ func (bot *telegramBot) loadConfig(ctx context.Context) (telegramRuntimeConfig,
func (bot *telegramBot) call(ctx context.Context, config telegramRuntimeConfig, method string, payload any, result any) error {
base, err := validateTelegramAPIURL(ctx, config.BaseURL, config.Token, method)
if err != nil {
return err
return redactTelegramError(err, config.Token)
}
body, err := json.Marshal(payload)
if err != nil {
@@ -840,13 +988,13 @@ func (bot *telegramBot) call(ctx context.Context, config telegramRuntimeConfig,
}
request, err := http.NewRequestWithContext(ctx, http.MethodPost, base.String(), bytes.NewReader(body))
if err != nil {
return err
return redactTelegramError(err, config.Token)
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("User-Agent", "vocat-telegram-bot/1")
response, err := client.Do(request)
if err != nil {
return err
return redactTelegramError(err, config.Token)
}
defer response.Body.Close()
responseBody, err := io.ReadAll(io.LimitReader(response.Body, 2<<20))
@@ -900,7 +1048,7 @@ func (bot *telegramBot) warn(message string, err error) {
return
}
now := time.Now()
text := err.Error()
text := redactTelegramText(err.Error(), "")
bot.logMu.Lock()
if text == bot.lastLogText && now.Sub(bot.lastLogTime) < time.Minute {
bot.logMu.Unlock()
@@ -908,7 +1056,21 @@ func (bot *telegramBot) warn(message string, err error) {
}
bot.lastLogText, bot.lastLogTime = text, now
bot.logMu.Unlock()
bot.server.logger.Warn(message, "error", err)
bot.server.logger.Warn(message, "error", text)
}
func redactTelegramError(err error, token string) error {
if err == nil {
return nil
}
return errors.New(redactTelegramText(err.Error(), token))
}
func redactTelegramText(value, token string) string {
if strings.TrimSpace(token) != "" {
value = strings.ReplaceAll(value, token, "[REDACTED]")
}
return telegramTokenInURLPattern.ReplaceAllString(value, "bot[REDACTED]")
}
func parseTelegramCommand(text string) (string, string) {
+76
View File
@@ -1,11 +1,15 @@
package server
import (
"context"
"errors"
"strings"
"testing"
"time"
"vocat/internal/device"
"vocat/internal/modem"
"vocat/internal/store"
)
func TestTelegramAPIURLSupportsBaseAndTemplate(t *testing.T) {
@@ -105,3 +109,75 @@ func TestFormatTelegramATIncludesFinalResult(t *testing.T) {
t.Fatalf("formatTelegramAT(lines) = %q", got)
}
}
func TestTelegramExecutesGuardedATForConfiguredDevice(t *testing.T) {
database, err := store.Open(context.Background(), ":memory:")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = database.Close() })
if err := database.UpsertDevice(context.Background(), store.Device{ID: "EC20", Name: "EC20"}); err != nil {
t.Fatal(err)
}
bot := &telegramBot{server: &Server{
store: database,
devices: fakeDeviceController{
entry: device.Device{ID: "EC20", Discovered: true},
atResponse: modem.Response{Lines: []string{"+CSQ: 18,99"}, Final: "OK"},
},
}}
result, err := bot.executeATCommand(context.Background(), "EC20", "AT+CSQ")
if err != nil {
t.Fatal(err)
}
for _, expected := range []string{"设备:EC20", "> AT+CSQ", "+CSQ: 18,99", "OK"} {
if !strings.Contains(result, expected) {
t.Fatalf("AT result %q does not contain %q", result, expected)
}
}
if _, err := bot.executeATCommand(context.Background(), "EC20", "AT+CFUN=0"); err == nil {
t.Fatal("guarded AT command unexpectedly succeeded")
}
}
func TestTelegramExecutesInteractiveUSSDForConfiguredDevice(t *testing.T) {
database, err := store.Open(context.Background(), ":memory:")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = database.Close() })
if err := database.UpsertDevice(context.Background(), store.Device{ID: "EC20", Name: "EC20"}); err != nil {
t.Fatal(err)
}
bot := &telegramBot{server: &Server{
store: database,
devices: fakeDeviceController{
entry: device.Device{ID: "EC20", Discovered: true},
ussdResult: device.USSDResult{
Code: "*100#", Text: "1. Balance\n2. Bundles", Status: "awaiting_input",
SessionID: "0123456789abcdef", Continueable: true,
},
},
}}
result, err := bot.executeUSSDCommand(context.Background(), "EC20", "*100#")
if err != nil {
t.Fatal(err)
}
formatted := formatTelegramUSSD("EC20", result)
for _, expected := range []string{
"设备:EC20", "状态:awaiting_input", "1. Balance", "/ussd_reply 0123456789abcdef", "/ussd_cancel 0123456789abcdef",
} {
if !strings.Contains(formatted, expected) {
t.Fatalf("USSD result %q does not contain %q", formatted, expected)
}
}
}
func TestTelegramErrorsRedactBotTokens(t *testing.T) {
token := "1234567890:abcdefghijklmnopqrstuvwxyzABCDE"
err := errors.New(`Post "https://api.telegram.org/bot` + token + `/getUpdates": context canceled`)
redacted := redactTelegramError(err, token)
if strings.Contains(redacted.Error(), token) || !strings.Contains(redacted.Error(), "bot[REDACTED]") {
t.Fatalf("redacted error = %q", redacted)
}
}
+46 -12
View File
@@ -18,6 +18,8 @@ var (
ErrCallState = errors.New("ims: call is not in the required state")
)
const terminalCallRetention = 30 * time.Second
type imsCall struct {
public vowifi.Call
callID string
@@ -37,11 +39,14 @@ type imsCall struct {
func (session *Session) Calls() []vowifi.Call {
session.callMu.Lock()
defer session.callMu.Unlock()
now := time.Now().UTC()
calls := make([]vowifi.Call, 0, len(session.calls))
for _, call := range session.calls {
if call.public.State != "ended" && call.public.State != "failed" {
calls = append(calls, call.public)
for id, call := range session.calls {
if call.public.EndedAt != nil && now.Sub(*call.public.EndedAt) > terminalCallRetention {
delete(session.calls, id)
continue
}
calls = append(calls, call.public)
}
sort.Slice(calls, func(i, j int) bool { return calls[i].StartedAt.Before(calls[j].StartedAt) })
return calls
@@ -144,13 +149,14 @@ func (session *Session) watchOutgoingCall(call *imsCall, key sipTransactionKey)
case <-session.refreshContext.Done():
return
case <-timer.C:
session.setCallState(call.callID, "failed")
session.finishCall(call.callID, "failed", 0, "SIP INVITE transaction timed out")
return
case response := <-call.responses:
if response == nil {
continue
}
if response.StatusCode < 200 {
session.setCallDiagnostic(call.callID, response.StatusCode, response.Reason)
if response.StatusCode >= 180 {
session.setCallState(call.callID, "ringing")
}
@@ -170,7 +176,7 @@ func (session *Session) watchOutgoingCall(call *imsCall, key sipTransactionKey)
_ = session.sendACK(call)
session.setCallState(call.callID, "active")
} else {
session.setCallState(call.callID, "failed")
session.finishCall(call.callID, "failed", response.StatusCode, response.Reason)
}
return
}
@@ -223,18 +229,18 @@ func (session *Session) HangupCall(ctx context.Context, id string) error {
if err := respond(response); err != nil {
return err
}
session.setCallState(id, "ended")
session.finishCall(id, "ended", 0, "")
return nil
}
method := "BYE"
if direction == "outgoing" && (state == "dialing" || state == "ringing") {
method = "CANCEL"
}
if err := session.sendDialogRequest(ctx, call, method); err != nil {
return err
}
session.setCallState(id, "ended")
return nil
err := session.sendDialogRequest(ctx, call, method)
// A remote endpoint may already have removed the dialog and answer BYE with
// 481. The local call must still leave the active list after a hang-up.
session.finishCall(id, "ended", 0, "")
return err
}
func (session *Session) handleCallRequest(request *sipRequest, respond func([]byte) error) bool {
@@ -280,7 +286,7 @@ func (session *Session) handleCallRequest(request *sipRequest, respond func([]by
}
}
}
session.setCallState(callID, "ended")
session.finishCall(callID, "ended", 0, "")
return true
default:
return false
@@ -395,6 +401,34 @@ func (session *Session) setCallState(id, state string) {
session.callMu.Lock()
if call := session.calls[id]; call != nil {
call.public.State = state
if state != "ended" && state != "failed" {
call.public.EndedAt = nil
}
}
session.callMu.Unlock()
}
func (session *Session) setCallDiagnostic(id string, code int, reason string) {
session.callMu.Lock()
if call := session.calls[id]; call != nil {
call.public.SIPCode = code
call.public.Reason = safeSIPDiagnostic(reason)
}
session.callMu.Unlock()
}
func (session *Session) finishCall(id, state string, code int, reason string) {
now := time.Now().UTC()
session.callMu.Lock()
if call := session.calls[id]; call != nil {
call.public.State = state
if code != 0 {
call.public.SIPCode = code
}
if reason = safeSIPDiagnostic(reason); reason != "" {
call.public.Reason = reason
}
call.public.EndedAt = &now
}
session.callMu.Unlock()
}
+17 -2
View File
@@ -4,6 +4,8 @@ import (
"context"
"strings"
"testing"
"vocat/internal/vowifi"
)
func TestIncomingCallCanRingAndAnswerWithoutAudio(t *testing.T) {
@@ -60,8 +62,21 @@ func TestIncomingCallCanBeRejected(t *testing.T) {
if !strings.HasPrefix(string(response), "SIP/2.0 486 Busy Here") {
t.Fatalf("reject response = %q", response)
}
if len(session.Calls()) != 0 {
t.Fatal("ended call remained active")
calls := session.Calls()
if len(calls) != 1 || calls[0].State != "ended" || calls[0].EndedAt == nil {
t.Fatalf("terminal call status = %#v", calls)
}
}
func TestRejectedOutgoingCallRetainsSIPReason(t *testing.T) {
session := &Session{calls: make(map[string]*imsCall)}
call := &imsCall{public: vowifi.Call{ID: "rejected", State: "dialing"}}
session.calls[call.public.ID] = call
session.finishCall(call.public.ID, "failed", 484, "Address Incomplete\r\nignored")
calls := session.Calls()
if len(calls) != 1 || calls[0].State != "failed" || calls[0].SIPCode != 484 ||
calls[0].Reason != "Address Incomplete ignored" || calls[0].EndedAt == nil {
t.Fatalf("rejected call = %#v", calls)
}
}
+8 -5
View File
@@ -368,11 +368,14 @@ type SMSSender interface {
// Call describes one signalling-only IMS call. VoCat intentionally does not
// open, capture, or relay an RTP media stream for extension call tests.
type Call struct {
ID string `json:"id"`
Number string `json:"number"`
Direction string `json:"direction"`
State string `json:"state"`
StartedAt time.Time `json:"started_at"`
ID string `json:"id"`
Number string `json:"number"`
Direction string `json:"direction"`
State string `json:"state"`
StartedAt time.Time `json:"started_at"`
SIPCode int `json:"sip_code,omitempty"`
Reason string `json:"reason,omitempty"`
EndedAt *time.Time `json:"ended_at,omitempty"`
}
// CallController is an optional capability of an IMS session. Implementations
+2 -1
View File
@@ -45,7 +45,8 @@ function RequireAuth({ children }: { children: ReactElement }) {
const location = useLocation();
if (!ready) return <LoadingScreen />;
if (!isAuthenticated) {
return <Navigate to={`/login?redirect=${encodeURIComponent(location.pathname)}`} replace />;
const redirect = `${location.pathname}${location.search}${location.hash}`;
return <Navigate to={`/login?redirect=${encodeURIComponent(redirect)}`} replace />;
}
return children;
}
+17 -2
View File
@@ -9,6 +9,18 @@ import { tl } from "./lib/i18n";
const CSRF_KEY = "vocat.csrf";
// Authenticated pages and same-origin plugin frames share this signal. Clear
// the mutation token immediately so a revoked session cannot leave stale auth
// state behind in the browser.
export function notifyUnauthorized() {
try {
sessionStorage.removeItem(CSRF_KEY);
} catch {
/* ignore unavailable storage */
}
window.dispatchEvent(new Event("vocat:unauthorized"));
}
function isMutation(method: string) {
return !["GET", "HEAD", "OPTIONS"].includes(method.toUpperCase());
}
@@ -94,14 +106,17 @@ export async function api<T>(path: string, options: RequestOptions = {}): Promis
: JSON.stringify(snakeize(options.body)),
});
if (options.raw) return response as T;
if (options.raw) {
if (response.status === 401) notifyUnauthorized();
return response as T;
}
const contentType = response.headers.get("content-type") || "";
const payload = contentType.includes("application/json")
? await response.json()
: { message: await response.text() };
const normalized = camelize<Record<string, unknown>>(payload);
if (!response.ok) {
if (response.status === 401) window.dispatchEvent(new Event("vocat:unauthorized"));
if (response.status === 401) notifyUnauthorized();
const nested = normalized.error;
const detail = nested && typeof nested === "object"
? {
+2
View File
@@ -3,6 +3,7 @@ import { message } from "../ui";
import type { DeviceDetail, DeviceModem, ModemPnn } from "./types";
import { tl } from "../../lib/i18n";
import { lookupCarrier } from "../../lib/carrier";
import { notifyUnauthorized } from "../../api";
/* ---------------------------------------------------------------------------
* Lifecycle / status helpers (ported from the VoHive reference).
@@ -283,6 +284,7 @@ export async function readEventStream(
credentials: "include",
signal: handlers.signal,
});
if (response.status === 401) notifyUnauthorized();
if (!response.ok) throw new Error((await response.text()) || `HTTP ${response.status}`);
if (!response.body) throw new Error("No stream body");
+5 -2
View File
@@ -271,9 +271,12 @@ export default function SettingsPage() {
if (!confirmed) return;
setApplyingUpdate(true);
try {
const data = await api<{ message?: string }>("/system/update/apply", { method: "POST", body: {} });
const data = await api<{ message?: string; reauthenticationRequired?: boolean }>("/system/update/apply", { method: "POST", body: {} });
message.success(data?.message || t("正在更新..."));
window.setTimeout(() => window.location.reload(), 5000);
window.setTimeout(() => {
if (data?.reauthenticationRequired) window.location.replace("/login");
else window.location.reload();
}, 1500);
} catch (e) {
message.error(e instanceof Error ? e.message : t("应用更新失败"));
} finally {
+9
View File
@@ -62,6 +62,15 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
}, []);
useEffect(() => {
const unauthorized = () => {
setUser(null);
setReady(true);
};
window.addEventListener("vocat:unauthorized", unauthorized);
return () => window.removeEventListener("vocat:unauthorized", unauthorized);
}, []);
useEffect(() => {
void refresh();
}, [refresh]);