Compare commits

..

1 Commits

Author SHA1 Message Date
siujamo 442a1e2f9f refactor: move auth token to HttpOnly cookie, fix CORS and artefacts
Backend:
- Set JWT as HttpOnly cookie on login, add cookie fallback in auth middleware
- Add /auth/logout endpoint to clear cookie
- Fix CORS to echo origin with Allow-Credentials for withCredentials requests
- Make SPA static serving optional via SERVE_SPA config flag

Frontend:
- Remove manual token management; rely on HttpOnly cookie + withCredentials
- Simplify auth-slice to authenticated boolean flag
- Fix Artefact interface to match backend fields (sha256Hash, fileName, fileSize)
- Fix artefact upload endpoint and send version in FormData
- Use KiB/MiB for file size display
- Move Redux hooks from store/hooks to hooks/store
2026-07-07 15:57:26 +08:00
18 changed files with 307 additions and 209 deletions
+9
View File
@@ -63,3 +63,12 @@ BANDWIDTH_BPS=209715
# Default: 100
# Example: RATE_LIMIT_RPS=50 (stricter, for constrained environments)
RATE_LIMIT_RPS=100
# ── Web Admin Panel ───────────────────────────────────────
# Whether the Go server should serve the built SPA frontend from ./web/dist.
# Set to false when using Caddy, Nginx, or another reverse proxy to serve
# the frontend and proxy API requests to this server.
# Default: true
# Example: SERVE_SPA=false (frontend served by external web server)
SERVE_SPA=true
+25 -7
View File
@@ -2,6 +2,7 @@ package main
import (
"context"
"errors"
"log"
"net/http"
"os"
@@ -96,9 +97,16 @@ func main() {
r := gin.New()
r.Use(gin.Recovery())
// CORS
// CORS — withCredentials requires explicit origin, not wildcard
r.Use(func(c *gin.Context) {
origin := c.GetHeader("Origin")
if origin != "" {
c.Header("Access-Control-Allow-Origin", origin)
c.Header("Access-Control-Allow-Credentials", "true")
} else {
c.Header("Access-Control-Allow-Origin", "*")
}
c.Header("Vary", "Origin")
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization, Range")
if c.Request.Method == "OPTIONS" {
@@ -109,18 +117,21 @@ func main() {
})
// -- Public routes (daemon-facing) --
api := r.Group("/api/v1")
api := r.Group("/api")
{
api.POST("/devices/register", deviceHandler.Register)
api.POST("/devices/heartbeat", deviceHandler.Heartbeat)
api.GET("/devices/check-update", deviceHandler.CheckUpdate)
}
// -- Public auth routes --
api.POST("/auth/login", authHandler.Login)
// -- Authenticated admin routes --
admin := api.Group("")
admin.Use(middleware.AuthMiddleware(authSvc))
{
api.POST("/auth/login", authHandler.Login)
api.POST("/auth/logout", authHandler.Logout)
admin.GET("/devices", deviceHandler.List)
admin.GET("/devices/:deviceId", deviceHandler.Get)
@@ -156,8 +167,15 @@ func main() {
// -- Device status update --
api.POST("/deployments/:id/status", deploymentHandler.UpdateStatus)
// -- Static admin panel (served at root; API routes take precedence) --
r.StaticFS("/", http.Dir("./web/dist"))
// -- Static admin panel (SPA fallback) --
// Enable with SERVE_SPA=true (default). Set to false when using Caddy/Nginx as reverse proxy.
if cfg.ServeSPA {
r.Static("/assets", "./web/dist/assets")
r.GET("/favicon.ico", func(c *gin.Context) { c.File("./web/dist/favicon.ico") })
r.NoRoute(func(c *gin.Context) {
c.File("./web/dist/index.html")
})
}
// Graceful shutdown
srv := &http.Server{
@@ -166,9 +184,9 @@ func main() {
}
go func() {
log.Printf("[main] OTA Manifest Server listening on :%s", cfg.ServerPort)
log.Printf("[main] Pipely listening on port :%s", cfg.ServerPort)
log.Printf("[main] Max concurrent downloads: %d, bandwidth per stream: %d B/s", cfg.MaxConcurrent, cfg.BandwidthBPS)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("Server error: %v", err)
}
}()
+12 -1
View File
@@ -28,5 +28,16 @@ func (h *Handler) Login(c *gin.Context) {
return
}
c.JSON(http.StatusOK, resp)
// Set JWT as HttpOnly cookie so the frontend doesn't need to manage it.
// The browser sends it automatically on every request.
maxAge := h.svc.ExpiryHrs() * 3600
c.SetCookie("pipely_token", resp.Token, maxAge, "/", "", false, true)
c.JSON(http.StatusOK, gin.H{"message": "Login successful"})
}
func (h *Handler) Logout(c *gin.Context) {
// Clear the auth cookie by setting MaxAge=-1
c.SetCookie("pipely_token", "", -1, "/", "", false, true)
c.JSON(http.StatusOK, gin.H{"message": "Logged out"})
}
+4
View File
@@ -33,6 +33,10 @@ func NewService(db *gorm.DB, secret []byte, expiryHrs int) *Service {
}
}
func (s *Service) ExpiryHrs() int {
return int(s.expiry.Hours())
}
func (s *Service) Login(username, password string) (*model.LoginResponse, error) {
user, err := database.GetAdminUserByUsername(s.db, username)
if err != nil {
+11
View File
@@ -17,6 +17,7 @@ type Config struct {
MaxConcurrent int
BandwidthBPS int
RateLimitRPS int
ServeSPA bool
}
func Load() *Config {
@@ -34,6 +35,7 @@ func Load() *Config {
MaxConcurrent: envOrDefaultInt("MAX_CONCURRENT_DOWNLOADS", 50),
BandwidthBPS: envOrDefaultInt("BANDWIDTH_BPS", 10*1024*1024/50),
RateLimitRPS: envOrDefaultInt("RATE_LIMIT_RPS", 100),
ServeSPA: envOrDefaultBool("SERVE_SPA", true),
}
}
@@ -52,3 +54,12 @@ func envOrDefaultInt(key string, def int) int {
}
return def
}
func envOrDefaultBool(key string, def bool) bool {
if v := os.Getenv(key); v != "" {
if b, err := strconv.ParseBool(v); err == nil {
return b
}
}
return def
}
+22 -10
View File
@@ -10,19 +10,13 @@ import (
func AuthMiddleware(authSvc *auth.Service) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorisation header is missing"})
token := extractToken(c)
if token == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorisation token is missing"})
return
}
parts := strings.SplitN(authHeader, " ", 2)
if !(len(parts) == 2 && parts[0] == "Bearer") {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid authorisation format"})
return
}
user, err := authSvc.ValidateToken(parts[1])
user, err := authSvc.ValidateToken(token)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorised: " + err.Error()})
return
@@ -32,3 +26,21 @@ func AuthMiddleware(authSvc *auth.Service) gin.HandlerFunc {
c.Next()
}
}
func extractToken(c *gin.Context) string {
// First try the Authorization header
authHeader := c.GetHeader("Authorization")
if authHeader != "" {
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) == 2 && parts[0] == "Bearer" {
return parts[1]
}
}
// Fall back to the cookie set at login
if cookie, err := c.Cookie("pipely_token"); err == nil {
return cookie
}
return ""
}
+17
View File
@@ -0,0 +1,17 @@
# ─────────────────────────────────────────────────────────
# Pipely Web — Environment Variables
# ─────────────────────────────────────────────────────────
# Copy this file to .env and adjust values for your environment:
# cp .env.example .env
# ─────────────────────────────────────────────────────────
# ── API Server ───────────────────────────────────────────
# Base URL for the OTA Manifest Server API.
# Default: https://pipely.onixbyte.com/
# Development: http://localhost:8080
VITE_API_BASE_URL=http://localhost:5001/api
# Redux Persistent storage location
# Options: `local` (default), `session`
VITE_REDUX_STORAGE=local
+16 -8
View File
@@ -1,11 +1,13 @@
import WebClient from "@/shared/web-client"
export interface Artefact {
id: string
name: string
id: number
version: string
checksum: string
size: number
fileName: string
fileSize: number
sha256Hash: string
isDelta: boolean
deltaRef: string
createdAt: string
}
@@ -33,11 +35,17 @@ export async function getArtefacts(query?: ArtefactsQuery): Promise<ArtefactsRes
return data
}
export async function uploadArtefact(file: File): Promise<Artefact> {
const { data } = await WebClient.post<Artefact>("/artefacts/upload", file)
export async function uploadArtefact(version: string, file: File): Promise<Artefact> {
const form = new FormData()
form.append("version", version)
form.append("file", file)
const { data } = await WebClient.post<Artefact>("/artefacts", form, {
headers: { "Content-Type": "multipart/form-data" },
})
return data
}
export async function deleteArtefact(id: string): Promise<void> {
await WebClient.delete<void>(`/artefacts/${id}`)
export async function deleteArtefact(id: number): Promise<void> {
await WebClient.delete(`/artefacts/${id}`)
}
+4 -5
View File
@@ -5,11 +5,10 @@ export interface LoginRequest {
password: string
}
export interface LoginResponse {
token: string
export async function login(credentials: LoginRequest): Promise<void> {
await WebClient.post("/auth/login", credentials)
}
export async function login(credentials: LoginRequest): Promise<LoginResponse> {
const { data } = await WebClient.post<LoginResponse>("/auth/login", credentials)
return data
export async function logout(): Promise<void> {
await WebClient.post("/auth/logout")
}
+6 -4
View File
@@ -1,6 +1,5 @@
import { NavLink, useNavigate, Outlet } from "react-router-dom"
import { useDispatch } from "react-redux"
import { setToken } from "@/store/auth-slice"
import {
Drawer,
List,
@@ -21,6 +20,8 @@ import {
People,
Logout,
} from "@mui/icons-material"
import { logoutAction } from "@/store/auth-slice"
import { logout } from "@/api/auth"
const drawerWidth = 240
@@ -28,8 +29,9 @@ export default function Layout() {
const navigate = useNavigate()
const dispatch = useDispatch()
function handleLogout() {
dispatch(setToken(""))
async function handleLogout() {
dispatch(logoutAction())
await logout().catch(() => {})
navigate("/")
}
@@ -50,7 +52,7 @@ export default function Layout() {
}}>
<Toolbar>
<Typography variant="h6" noWrap component="div">
OTA Manager
Pipely
</Typography>
</Toolbar>
</AppBar>
+10 -10
View File
@@ -1,5 +1,4 @@
import { useEffect, useState, type MouseEvent } from "react"
import { getArtefacts, uploadArtefact, deleteArtefact, type Artefact } from "@/api/artefacts"
import {
Box,
Button,
@@ -24,6 +23,7 @@ import {
Pagination,
} from "@mui/material"
import { Upload, Delete, Archive } from "@mui/icons-material"
import { getArtefacts, uploadArtefact, deleteArtefact, type Artefact } from "@/api/artefacts"
const PAGE_SIZE = 20
@@ -34,7 +34,7 @@ export default function Artefacts() {
const [loading, setLoading] = useState(true)
const [dialogOpen, setDialogOpen] = useState(false)
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
const [deleteTarget, setDeleteTarget] = useState<{ id: string; version: string } | null>(null)
const [deleteTarget, setDeleteTarget] = useState<{ id: number; version: string } | null>(null)
const [uploading, setUploading] = useState(false)
const [version, setVersion] = useState("")
const [file, setFile] = useState<File | null>(null)
@@ -73,7 +73,7 @@ export default function Artefacts() {
setUploading(true)
try {
await uploadArtefact(file)
await uploadArtefact(version, file)
setVersion("")
setFile(null)
setDialogOpen(false)
@@ -90,7 +90,7 @@ export default function Artefacts() {
}
}
function handleDeleteClick(id: string, version: string) {
function handleDeleteClick(id: number, version: string) {
setDeleteTarget({ id, version })
setDeleteDialogOpen(true)
}
@@ -203,10 +203,10 @@ export default function Artefacts() {
<TableCell>
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
<Archive fontSize="small" color="action" />
{a.name}
{a.fileName}
</Box>
</TableCell>
<TableCell>{formatSize(a.size)}</TableCell>
<TableCell>{formatSize(a.fileSize)}</TableCell>
<TableCell>
<Box
component="span"
@@ -215,8 +215,8 @@ export default function Artefacts() {
fontSize: 12,
cursor: "help",
}}
title={a.checksum}>
{a.checksum.slice(0, 12)}...
title={a.sha256Hash}>
{a.sha256Hash.slice(0, 12)}...
</Box>
</TableCell>
<TableCell>{new Date(a.createdAt).toLocaleDateString()}</TableCell>
@@ -280,6 +280,6 @@ export default function Artefacts() {
function formatSize(bytes: number): string {
if (bytes < 1024) return bytes + " B"
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB"
return (bytes / (1024 * 1024)).toFixed(1) + " MB"
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KiB"
return (bytes / (1024 * 1024)).toFixed(1) + " MiB"
}
+1 -1
View File
@@ -45,7 +45,7 @@ export default function Deployments() {
const [loading, setLoading] = useState(true)
const [dialogOpen, setDialogOpen] = useState(false)
const [artefacts, setArtefacts] = useState<{ id: string; version: string }[]>([])
const [artefacts, setArtefacts] = useState<{ id: number; version: string }[]>([])
const [name, setName] = useState("")
const [artefactId, setArtefactId] = useState("")
const [targetGroups, setTargetGroups] = useState("")
+7 -4
View File
@@ -1,6 +1,8 @@
import { useState, type SubmitEvent } from "react"
import { useState } from "react"
import { useNavigate } from "react-router-dom"
import { useDispatch } from "react-redux"
import { login } from "@/api/auth"
import { loginAction } from "@/store/auth-slice"
import { Container, Paper, Box, TextField, Button, Typography, Alert } from "@mui/material"
export default function Login() {
@@ -9,15 +11,16 @@ export default function Login() {
const [error, setError] = useState("")
const [loading, setLoading] = useState(false)
const navigate = useNavigate()
const dispatch = useDispatch()
async function handleSubmit(e: SubmitEvent) {
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault()
setError("")
setLoading(true)
try {
const res = await login({ username, password })
console.log(res.token)
await login({ username, password })
dispatch(loginAction())
navigate("/dashboard")
} catch (err) {
setError(err instanceof Error ? err.message : "Login failed")
+1 -1
View File
@@ -4,7 +4,7 @@ import ErrorPage from "@/components/ErrorPage"
import Layout from "@/components/Layout"
import EmptyLayout from "@/components/EmptyLayout"
import { isAuthenticated } from "@/store/auth-slice"
import { useAppSelector } from "@/store"
import { useAppSelector } from "@/hooks/store"
function lazy<T extends { default: ComponentType<unknown> }>(importer: () => Promise<T>) {
return async () => {
+4 -1
View File
@@ -1,7 +1,10 @@
import axios from "axios"
import dayjs from "@/lib/dayjs"
export default axios.create({
const WebClient = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL,
timeout: dayjs.duration({ seconds: 10 }).asMilliseconds(),
withCredentials: true,
})
export default WebClient
+10 -7
View File
@@ -1,24 +1,27 @@
import { createSlice, type PayloadAction } from "@reduxjs/toolkit"
import { createSlice } from "@reduxjs/toolkit"
export interface AuthState {
token: string
authenticated: boolean
}
const initialState: AuthState = {
token: "",
authenticated: false,
}
const authSlice = createSlice({
name: "auth",
initialState,
reducers: {
setToken(state, action: PayloadAction<string>) {
state.token = action.payload
login(state) {
state.authenticated = true
},
logout(state) {
state.authenticated = false
},
},
})
export const { setToken } = authSlice.actions
export const { login: loginAction, logout: logoutAction } = authSlice.actions
export const authReducer = authSlice.reducer
export const isAuthenticated = (state: { auth: AuthState }) => state.auth.token !== ""
export const isAuthenticated = (state: { auth: AuthState }) => state.auth.authenticated
-2
View File
@@ -42,5 +42,3 @@ export default store
export type RootState = ReturnType<typeof rootReducer>
export type AppDispatch = typeof store.dispatch
export type AppStore = typeof store
export { useAppSelector, useAppDispatch } from "./hooks"