5 Commits
13 changed files with 149 additions and 28 deletions
+10 -5
View File
@@ -1,20 +1,25 @@
# syntax=docker/dockerfile:1.7
# ---- Stage 1: build the web frontend ----
FROM node:20-alpine AS web-builder
# Build toolchains run natively on the BuildKit host. Without BUILDPLATFORM,
# the arm64 branch executes npm and the Go compiler through QEMU, which is much
# slower and makes npm ci appear to hang despite producing no progress output.
# ---- Stage 1: build the web frontend once on the native builder ----
FROM --platform=$BUILDPLATFORM node:20-alpine AS web-builder
WORKDIR /web
COPY web/package.json web/package-lock.json* ./
RUN npm ci
COPY web/ ./
RUN npm run build
# ---- Stage 2: build the Go binary ----
FROM golang:1.25-alpine AS go-builder
# ---- Stage 2: cross-compile the Go binary on the native builder ----
FROM --platform=$BUILDPLATFORM golang:1.25-alpine AS go-builder
RUN apk add --no-cache git
WORKDIR /src
ARG VERSION=0.1.0-dev
ARG BUILD_TIME=""
ARG TARGETOS
ARG TARGETARCH
COPY go.mod go.sum ./
RUN go mod download
@@ -23,7 +28,7 @@ COPY . .
# Overlay the freshly built frontend so go:embed web/dist picks it up.
COPY --from=web-builder /web/dist ./web/dist
RUN CGO_ENABLED=0 GOOS=linux go build \
RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build \
-trimpath \
-ldflags "-s -w -X vocat/internal/buildinfo.Version=${VERSION} -X vocat/internal/buildinfo.BuildTime=${BUILD_TIME}" \
-o /out/vocat \
+4
View File
@@ -248,6 +248,10 @@ func run(logger *slog.Logger, logs *loghub.Hub) error {
case <-signalContext.Done():
logger.Info("shutdown signal received")
}
// Long-lived SSE and polling handlers use this context. Stop them before
// http.Server.Shutdown so they do not consume the entire graceful-shutdown
// deadline while waiting for a stream that is intentionally still active.
cancelPolling()
shutdownContext, cancelShutdown := context.WithTimeout(
context.Background(),
+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 {
+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 {
+6 -3
View File
@@ -7,8 +7,8 @@
// Trust model: GitHub TLS guarantees the channel; the repository owner controls
// which assets are published; SHA256SUMS guards integrity. There is no GPG
// signature verification — an accepted trade-off for a closed-network testing
// tool. The web UI's check-update button remains an intentional no-op; only the
// CLI performs code replacement.
// tool. Both the CLI and authenticated web UI use this same verified replacement
// path.
package update
import (
@@ -232,7 +232,10 @@ func RestartService(logger *slog.Logger) error {
if _, err := exec.LookPath("systemctl"); err != nil {
return fmt.Errorf("systemctl not found in PATH")
}
cmd := exec.Command("systemctl", "restart", "vocat")
// Queue the restart and let systemctl exit before systemd stops this unit.
// A blocking restart command becomes part of vocat.service's own cgroup and
// waits for that same cgroup to terminate, creating a stop-timeout cycle.
cmd := exec.Command("systemctl", "restart", "--no-block", "vocat")
if out, err := cmd.CombinedOutput(); err != nil {
logger.Warn("systemctl restart failed", "error", err, "output", string(out))
return fmt.Errorf("systemctl restart vocat: %w", err)
+6 -2
View File
@@ -216,7 +216,9 @@ ExecStart=${BINARY_PATH}
Restart=on-failure
RestartSec=3s
TimeoutStartSec=30s
TimeoutStopSec=20s
# HTTP, VoWiFi, and modem cleanup have bounded shutdown contexts totalling up
# to 30 seconds. Leave a small margin before systemd resorts to SIGKILL.
TimeoutStopSec=40s
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_RAW
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW
@@ -229,7 +231,9 @@ ProtectKernelLogs=true
ProtectKernelModules=true
ProtectKernelTunables=true
ProtectControlGroups=true
ReadWritePaths=/opt/vocat/data
# The web/CLI self-updater verifies a release in this directory and atomically
# renames it over the running binary. Keep the rest of the host read-only.
ReadWritePaths=/opt/vocat/data /opt/vocat/bin
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK
RestrictRealtime=true
LockPersonality=true
+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]);