Feature: transfer a Go-managed host to the MFC master from the web console

A Go-managed host cannot receive the client upgrade that only the MFC master
can push. Transfer moves its main link there and brings it back after N days;
MFC has no reason to return it.

Transfer is not share: ASSIGN writes the target and drops the current
connection, so the old master sees the host go offline and the new master gets
a normal main link it can remote control and upgrade. While a transfer is live
the client refuses a second transfer and any share, so no host is handed to a
third master that expiry would orphan.

Server: admin-only `transfer_device` WS command, COMMAND_ASSIGN_MASTER +
SHARE_TYPE_YAMA_FOREVER as `host:port:days::transport\0`, byte-compatible with
the MFC dialog. The transport segment is always present (YAMA_TRANSFER_TRANSPORT,
default 0/TCP) because clients keep their current link when it is missing: a
WSS-managed host would otherwise retry WSS against the MFC master's raw TCP
port and never connect. The empty shine segment keeps the host's header
encryption. The button only renders when `device_list.transfer` is present,
which MFC never sends, so no MFC change is needed. devicehistory keeps
transfer_to/transfer_until for the card badge and drops the marker on expiry or
on a fresh login here.

Client: KernelManager.cpp writes the registry and disconnects; ClientDll.cpp
re-reads the registry at the top of every reconnect, so a mid-session transfer
lands on the next round. Expiry is checked before every connect attempt as well
as inside the heartbeat loop, so an unreachable target cannot pin the host to
an expired address until a restart; restoring rebuilds the link captured on
entry (address, header encryption, transport). linux/main.cpp applies the
transfer on the main loop and restores the captured endpoint at expiry; Android
does the same; macOS has neither share nor transfer.
This commit is contained in:
yuanyuanxiang committed 2026-11-20 12:23:08 +01:00
1 parent b466f568ab
commit 63c7cdf588
18 files changed
+1024 -177

No files matched your search

+6
View File
@@ -72,6 +72,7 @@ Web 应用能力 (Phase 3-7):
- **鼠标 / 键盘输入**: Win32 消息映射 (`WM_*` / `VK_*` / `MK_*`),MSG64 48 字节布局直传客户端
- **Web 终端**: xterm.js + Windows ConPTY / 旧 cmd 管道双模式;二进制 "TRM1" 帧分流;尺寸自适应;单设备单 viewer
- **用户与分组**: admin 可创建/删除 viewer 账号、配置 allowed_groups,users.json 原子写入
- **转移主机**: 把主机临时交给另一台 master(通常是 MFC 服务端)做客户端升级,到期由客户端自动连回本机;转移状态持久化并在设备卡片上倒计时显示。仅 Go 服务端下发 `device_list.transfer`,MFC 共用同一份页面但不会出现该入口
## 支持的命令
@@ -102,6 +103,7 @@ Web 应用能力 (Phase 3-7):
| `COMMAND_SHELL` | 40 | 请求开启 shell 子连接 |
| `CMD_TERMINAL_RESIZE` | 81 | PTY 尺寸 (cols / rows int16 LE) |
| `COMMAND_BYE` | 204 | 优雅断开屏幕 / 终端 |
| `COMMAND_ASSIGN_MASTER` | 207 | 转移主机:`host:port:days::transport` + `SHARE_TYPE_YAMA_FOREVER`(transport:0=TCP / 5=WS / 6=WSS),客户端到期自动连回本机 |
| `CMD_MASTERSETTING` | 215 | 主控配置 + HMAC 签名 (1000B) |
| `CMD_HEARTBEAT_ACK` | 216 | 心跳响应(携带 Authorized 字段) |
| `TOKEN_CONN_AUTH` | 246 | 子连接身份握手响应 (256B) |
@@ -172,6 +174,9 @@ VSCode F5 调试时由 `sync-web-assets` preLaunchTask 自动同步。
| `YAMA_WEB_TRUST_PROXY` | Set to `1` only when running behind a reverse proxy you control (caddy / nginx / cloudflare). Switches client-IP extraction to use the last entry of `X-Forwarded-For` instead of `RemoteAddr`, so per-IP login rate limit sees the real client. Direct-exposure deployments MUST leave this unset — otherwise attackers can spoof the header to evade rate limits. | `1` |
| `YAMA_AUDIT_LOG` | 安全审计日志路径(JSON lines)。默认 `logs/audit.log`;设为 `off` / `none` / `0` / `-` 关闭独立文件(审计记录仍会写入 `logs/server.log`)。审计记录带 `audit=true` 和稳定的 `event` 名,便于告警与检索。 | `/var/log/yama/audit.log` |
| `YAMA_SSO_JWT_SECRET` | **[SSO]** Shared HS256 secret for bridging the parent portal's `auth_token` JWT into a YAMA web session via `/sso`. Must equal the upstream portal's signing key (FMS: `SERVER_PRIVATE_KEY`). **Only `admin` portal users are auto-logged-in**; other roles still need YAMA's own web login. Unset → SSO disabled, `/sso` returns 401. | `<shared-secret>` |
| `YAMA_TRANSFER_TARGET` | **[转移主机]** 预填 Web UI「转移主机」弹窗的目标 `host:port`。仅作默认值,操作员仍可改填其它地址;留空则按钮照常可用、输入框为空。 | `mfc.example.com:6543` |
| `YAMA_TRANSFER_DAYS` | **[转移主机]** 预填的转移天数(到期后客户端自动连回本机),默认 `1`。取值 `(0, 365]`,弹窗输入框下限为 `0.5`;非正数或无法解析时忽略并沿用默认值。 | `2` |
| `YAMA_TRANSFER_TRANSPORT` | **[转移主机]** 转移后主机连接目标主控所用的传输方式:`0`=TCP(默认,MFC 主控直连端口)、`5`=WS、`6`=WSS。命令里始终携带该段——缺省时客户端会沿用当前链路的传输方式,WSS 主机转移到直连主控会一直连不上。 | `0` |
```bash
# Linux/macOS
@@ -347,6 +352,7 @@ Web 端与设备端的认证、授权、远程控制操作会额外写入**独
| `remote.clipboard.get` / `.set` | 剪贴板读取 / 写入(只记字节数,**不记内容**) |
| `remote.rdp_reset` | 远程 RDP 会话归位操作 |
| `admin.user.create` / `admin.user.delete` / `admin.device.delete` | 管理操作(`target` / `device_id` / `mode`) |
| `admin.device.transfer` | 转移主机(`device_id` / `target` / `days` / `until`);被拒时带 `ok:false` 与 `reason`(`invalid_target`、`already_transferred`、`offline`、`send_failed`),并以 `WARN` 级别记录 |
| `admin.audit.query` | 管理员在网页查询审计日志(记录筛选条件与命中数) |
| `device.online` / `device.offline` | 受控设备上线 / 下线 |
| `device.auth.success` / `.failure` / `.throttled` / `.heartbeat.success` | 设备 TCP 授权结果(**只记 passcode 长度,不记 passcode**) |
+35
View File
@@ -1375,6 +1375,38 @@ func main() {
} else {
log.Info("SSO disabled (YAMA_SSO_JWT_SECRET not set) — web login only")
}
// "Transfer host": the web UI hands a host over to another master (the MFC
// server) so that master can push a client upgrade to it; the host returns
// to this server on its own once the days run out. The target only
// pre-fills the dialog — the operator can still type another one, and an
// empty value keeps the feature available with an empty field.
transferTarget := strings.TrimSpace(os.Getenv("YAMA_TRANSFER_TARGET"))
transferDays := 1.0
if v := strings.TrimSpace(os.Getenv("YAMA_TRANSFER_DAYS")); v != "" {
if d, err := strconv.ParseFloat(v, 64); err == nil && d > 0 {
transferDays = d
} else {
log.Info("Ignoring YAMA_TRANSFER_DAYS=%q (want a positive number)", v)
}
}
// The link the transferred host uses to reach the target. It is always in
// the command: clients keep their current link when it is missing, so a
// WSS-managed host would try WSS against a plain-TCP master. Default TCP
// matches what an MFC master listens on.
transferTransport := protocol.TransferTransportTCP
if v := strings.TrimSpace(os.Getenv("YAMA_TRANSFER_TRANSPORT")); v != "" {
switch v {
case "0", "5", "6":
transferTransport, _ = strconv.Atoi(v)
default:
log.Info("Ignoring YAMA_TRANSFER_TRANSPORT=%q (want 0=TCP, 5=WS, 6=WSS)", v)
}
}
if transferTarget != "" {
log.Info("Host transfer dialog pre-filled with %s (%.1f days, transport=%d)",
transferTarget, transferDays, transferTransport)
}
webCfg := web.Config{
AllowedOrigins: allowedOrigins,
LoginIPLimit: wsauth.NewRateLimiter(10, time.Minute),
@@ -1384,6 +1416,9 @@ func main() {
BrandName: brandName,
SSO: ssoDetector,
DeviceACL: deviceACL,
TransferTarget: transferTarget,
TransferDays: transferDays,
TransferTransport: transferTransport,
}
// Start HTTP server for web UI. Hub gives it read-only access to the
+68
View File
@@ -58,6 +58,14 @@ type Record struct {
FirstSeen int64 `json:"first_seen"`
LastSeen int64 `json:"last_seen"`
// TransferTo / TransferUntil mark a host that was handed over to another
// master (COMMAND_ASSIGN_MASTER): target is "host:port", until is the unix
// second the client goes back to its original master on its own. The store
// only remembers it for display — it never acts on the deadline, and a
// login here clears it because that means the host is back.
TransferTo string `json:"transfer_to,omitempty"`
TransferUntil int64 `json:"transfer_until,omitempty"`
}
type fileShape struct {
@@ -165,6 +173,13 @@ func (s *Store) upsertAt(d hub.DeviceInfo, at time.Time) {
rec.IP = d.IP
rec.Screen = d.Screen
rec.LastSeen = now
// A login on this server means the host is here, not at the master it was
// handed to: either it came back early (the upgrade finished, or the target
// was unreachable) or the deadline passed while this server was down. In
// both cases the marker would label an online card as "transferred" and
// keep the operator from transferring it again until the deadline.
rec.TransferTo = ""
rec.TransferUntil = 0
s.online[d.ID] = true
s.pruneLocked()
@@ -244,6 +259,59 @@ func (s *Store) Offline(online map[string]struct{}) []hub.DeviceInfo {
return out
}
// SetTransfer marks id as handed over to target ("host:port") until the given
// unix second. Reports false when the device has no history record — only a
// device that logged in at least once can be transferred, and the marker has
// nowhere to live otherwise.
func (s *Store) SetTransfer(id, target string, until int64) bool {
if id == "" || target == "" || until <= 0 {
return false
}
s.mu.Lock()
defer s.mu.Unlock()
rec, ok := s.devices[id]
if !ok {
return false
}
rec.TransferTo = target
rec.TransferUntil = until
s.markDirtyLocked()
return true
}
// ClearTransfer forgets the handover marker and reports whether one was set.
func (s *Store) ClearTransfer(id string) bool {
s.mu.Lock()
defer s.mu.Unlock()
rec, ok := s.devices[id]
if !ok || rec.TransferUntil == 0 {
return false
}
rec.TransferTo = ""
rec.TransferUntil = 0
s.markDirtyLocked()
return true
}
// Transfer returns the current handover marker, dropping it once the deadline
// has passed: the client returns to its original master by itself, so an
// expired marker would only mislabel the card forever.
func (s *Store) Transfer(id string) (target string, until int64, ok bool) {
s.mu.Lock()
defer s.mu.Unlock()
rec, found := s.devices[id]
if !found || rec.TransferUntil == 0 {
return "", 0, false
}
if time.Now().Unix() >= rec.TransferUntil {
rec.TransferTo = ""
rec.TransferUntil = 0
s.markDirtyLocked()
return "", 0, false
}
return rec.TransferTo, rec.TransferUntil, true
}
// Remove deletes the persisted record for id and reports whether one existed.
// This is the web UI's explicit "delete" for an offline device: an offline
// record has no live agent to uninstall, so forgetting it is all "delete" can
@@ -261,3 +261,48 @@ func TestFlushLeavesNoTempFiles(t *testing.T) {
}
}
}
// A transfer marker is dropped once its deadline passes — the client is back on
// its original master by then, so keeping the label would be a lie — and also
// as soon as the device logs in here again, because that means it is back
// early (upgrade done, or the target was unreachable).
func TestTransferMarkerLifecycle(t *testing.T) {
path := filepath.Join(t.TempDir(), "devices.json")
s, err := Open(path, 1000, nil)
if err != nil {
t.Fatalf("Open: %v", err)
}
t.Cleanup(func() { _ = s.Close() })
h := hub.New()
h.Subscribe(s)
h.Register(&hub.Device{ID: "dev-1", Name: "PC-1"}, &connection.Context{RemoteAddr: "198.51.100.9:5000"})
if _, _, ok := s.Transfer("dev-1"); ok {
t.Fatal("fresh device already reports a transfer")
}
if !s.SetTransfer("dev-1", "mfc.example:6544", time.Now().Add(time.Hour).Unix()) {
t.Fatal("SetTransfer on a known device failed")
}
if target, _, ok := s.Transfer("dev-1"); !ok || target != "mfc.example:6544" {
t.Fatalf("marker not visible: %q/%v", target, ok)
}
// Expired marker is dropped on read.
if !s.SetTransfer("dev-1", "mfc.example:6544", time.Now().Add(-time.Second).Unix()) {
t.Fatal("SetTransfer with a past deadline failed")
}
if _, _, ok := s.Transfer("dev-1"); ok {
t.Fatal("expired transfer marker still reported")
}
// A login on this server means the host is back, so the marker goes away.
if !s.SetTransfer("dev-1", "mfc.example:6544", time.Now().Add(time.Hour).Unix()) {
t.Fatal("SetTransfer after expiry failed")
}
h.Unregister("dev-1")
h.Register(&hub.Device{ID: "dev-1", Name: "PC-1"}, &connection.Context{RemoteAddr: "198.51.100.9:5001"})
if target, until, ok := s.Transfer("dev-1"); ok {
t.Fatalf("marker survived a reconnect: %q/%d", target, until)
}
}
+41
View File
@@ -155,6 +155,21 @@ const (
CommandBye byte = 204 // COMMAND_BYE - disconnect
CommandHeartbeat byte = 216 // CMD_HEARTBEAT_ACK
// CommandAssignMaster moves a host to another master (COMMAND_ASSIGN_MASTER).
// Payload: [cmd][ShareTypeYamaForever]host:port:days[:shine[:transport]]\0
// The client stores the target plus a deadline and goes back to the master it
// captured at startup when the deadline passes — the Go server does not take
// part in the restore. See common/host_transfer.h.
CommandAssignMaster byte = 207
ShareTypeYamaForever byte = 100 // SHARE_TYPE_YAMA_FOREVER — "transfer", not "share"
// TransferTransport* are the clients' CONNECT_ADDRESS.protoType values
// (common/commands.h): PROTO_TCP=0, PROTO_WS=5, PROTO_WSS=6. They travel in
// the assign-master payload's transport segment.
TransferTransportTCP int = 0
TransferTransportWS int = 5
TransferTransportWSS int = 6
// Client -> Server tokens
TokenAuth byte = 100 // TOKEN_AUTH - authorization required
TokenHeartbeat byte = 101 // TOKEN_HEARTBEAT
@@ -705,3 +720,29 @@ func BuildValidation(days float64, admin string, port int, maxDepth uint16) []by
return data
}
// BuildAssignMasterPacket encodes a "transfer this host to another master"
// command, byte-compatible with the MFC server's assignFunction
// (server/2015Remote/2015RemoteDlg.cpp):
//
// [COMMAND_ASSIGN_MASTER][SHARE_TYPE_YAMA_FOREVER]host:port:days::transport\0
//
// The shine segment stays empty: the header-encryption variant is not
// something this server can know better than the host, and clients rotate it
// when a login is rejected (client/IOCPClient.h). The transport segment is
// always sent, because an absent segment does **not** mean "plain TCP" to the
// clients — they keep the link they run today (client/ClientDll.cpp
// ApplyAssignedMaster, common/host_endpoint.h ApplyEndpoint). A host that
// talks WSS to this server would then try WSS against the MFC master's raw TCP
// port and never connect. The caller picks the transport; TCP (0) matches what
// an MFC master listens on. days is formatted without trailing zeros so "0.5"
// survives the round trip.
func BuildAssignMasterPacket(host string, port int, days float64, transport int) []byte {
payload := host + ":" + strconv.Itoa(port) + ":" + strconv.FormatFloat(days, 'f', -1, 64) +
"::" + strconv.Itoa(transport)
pkt := make([]byte, 0, 2+len(payload)+1)
pkt = append(pkt, CommandAssignMaster, ShareTypeYamaForever)
pkt = append(pkt, payload...)
pkt = append(pkt, 0) // clients parse the payload as a C string
return pkt
}
+32
View File
@@ -103,3 +103,35 @@ func isCommandTokenName(name string) bool {
strings.HasPrefix(name, "Token") ||
strings.HasPrefix(name, "Cmd")
}
// The assign-master payload must stay byte-compatible with the MFC master's
// assignFunction, otherwise the client parses the wrong fields: days keeps
// fractions ("0.5" for a half-day handover) and the string is NUL-terminated
// because both clients read it as a C string. The shine segment is empty
// (clients then keep their header-encryption variant) while the transport
// segment is always present — without it the clients would keep the link they
// run today, which is exactly the WSS-vs-TCP mismatch that made the transfer
// unreachable.
func TestBuildAssignMasterPacket(t *testing.T) {
cases := []struct {
host string
port int
days float64
transport int
want string
}{
{"mfc.example", 6544, 1, TransferTransportTCP, "mfc.example:6544:1::0\x00"},
{"10.0.0.5", 6543, 0.5, TransferTransportTCP, "10.0.0.5:6543:0.5::0\x00"},
{"mfc.example", 6544, 2.25, TransferTransportWS, "mfc.example:6544:2.25::5\x00"},
{"mfc.example", 6544, 1, TransferTransportWSS, "mfc.example:6544:1::6\x00"},
}
for _, tc := range cases {
got := BuildAssignMasterPacket(tc.host, tc.port, tc.days, tc.transport)
if len(got) < 2 || got[0] != CommandAssignMaster || got[1] != ShareTypeYamaForever {
t.Fatalf("header = %v, want [%d %d]", got[:2], CommandAssignMaster, ShareTypeYamaForever)
}
if string(got[2:]) != tc.want {
t.Fatalf("payload = %q, want %q", got[2:], tc.want)
}
}
}
+7 -6
View File
@@ -32,12 +32,13 @@ const (
auditClipGet = "remote.clipboard.get"
auditRdpReset = "remote.rdp_reset"
auditUserCreate = "admin.user.create"
auditUserDelete = "admin.user.delete"
auditDeviceAdmin = "admin.device.delete"
auditDeviceBind = "admin.device.bind"
auditDeviceUnbind = "admin.device.unbind"
auditQuery = "admin.audit.query"
auditUserCreate = "admin.user.create"
auditUserDelete = "admin.user.delete"
auditDeviceAdmin = "admin.device.delete"
auditDeviceTransfer = "admin.device.transfer"
auditDeviceBind = "admin.device.bind"
auditDeviceUnbind = "admin.device.unbind"
auditQuery = "admin.audit.query"
)
// audit emits one audit record for a WebSocket client. Identity fields are
+22 -1
View File
@@ -40,6 +40,9 @@ type Server struct {
trustForwardedFor bool // honor X-Forwarded-For (behind trusted proxy only)
basePath string // web UI mount prefix (e.g. "/remoter"); "" = domain root
brandName string // white-label title; "" = "SimpleRemoter" (official branding)
transferTarget string // pre-filled "transfer host" target, "host:port"
transferDays float64 // pre-filled "transfer host" days
transferTransport int // link to the target: protocol.TransferTransport*
sso SSODetector // nil = SSO disabled
mcp mcpEndpoint // nil = no /mcp route
sweepDone chan struct{} // closes to stop the login-limiter sweeper
@@ -93,6 +96,20 @@ type Config struct {
// behaviour: every authenticated session sees every device). The shipped
// server always wires one; tests may omit it.
DeviceACL *DeviceACL
// TransferTarget ("host:port") and TransferDays pre-fill the web UI's
// "transfer host" dialog. Reporting them is also what tells the shared
// page that this backend implements COMMAND_ASSIGN_MASTER — the MFC server
// serves the same page but never reports it, so no transfer button appears
// where the command would be dropped. Empty target = the operator types
// the address; days <= 0 falls back to 1.
//
// TransferTransport is the link the transferred host must use to reach the
// target (protocol.TransferTransportTCP/WS/WSS; zero value = TCP, what an
// MFC master listens on). It is always sent to the client: leaving it out
// would make a host that currently talks WSS keep WSS against the target.
TransferTarget string
TransferDays float64
TransferTransport int
}
// New creates an HTTP server bound to the given port. port=0 disables the server.
@@ -121,6 +138,9 @@ func (s *Server) WithConfig(cfg Config) *Server {
s.brandName = resolveBrandName(cfg.BrandName, s.basePath)
s.sso = cfg.SSO
s.deviceACL = cfg.DeviceACL
s.transferTarget = cfg.TransferTarget
s.transferDays = cfg.TransferDays
s.transferTransport = cfg.TransferTransport
return s
}
@@ -145,7 +165,8 @@ func (s *Server) Start() error {
withOriginAllowlist(s.allowedOrigins).
withLoginRateLimiters(s.loginIPLimit, s.loginUserLimit).
withTrustForwardedFor(s.trustForwardedFor).
withDeviceACL(s.deviceACL)
withDeviceACL(s.deviceACL).
withTransferDefaults(s.transferTarget, s.transferDays, s.transferTransport)
mux := http.NewServeMux()
mux.HandleFunc("/", s.handleIndex)
+278
View File
@@ -0,0 +1,278 @@
package web
import (
"encoding/json"
"testing"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
)
// transferReply drains queued messages until the transfer result arrives. The
// handler also broadcasts devices_changed to every authenticated client, so
// the reply is not necessarily the first message on the channel.
func transferReply(t *testing.T, c *wsClient) map[string]any {
t.Helper()
for i := 0; i < 8; i++ {
select {
case m := <-c.send:
var out map[string]any
if err := json.Unmarshal(m.data, &out); err != nil {
t.Fatalf("decode reply: %v", err)
}
if out["cmd"] == "transfer_device_result" {
return out
}
default:
t.Fatal("no transfer_device_result reply")
}
}
t.Fatal("transfer_device_result not queued")
return nil
}
func TestTransferDeviceSendsAssignMaster(t *testing.T) {
wh, h, hist := deleteTestHub(t)
var sent []byte
h.SetSender(func(_ *connection.Context, data []byte) error {
sent = append([]byte(nil), data...)
return nil
})
h.Register(&hub.Device{ID: "live", Name: "Live"},
&connection.Context{RemoteAddr: "10.0.0.9:1000"})
c, tok := deleteTestClient(wh, "admin")
raw, _ := json.Marshal(map[string]any{
"token": tok, "id": "live", "host": "mfc.example", "port": 6544, "days": 2,
})
wh.handleTransferDevice(c, raw)
rep := transferReply(t, c)
if rep["ok"] != true {
t.Fatalf("reply = %+v, want ok", rep)
}
if rep["target"] != "mfc.example:6544" {
t.Fatalf("target = %v, want mfc.example:6544", rep["target"])
}
// Wire format must match the MFC master byte for byte: command, transfer
// type, then host:port:days::transport as a NUL-terminated string. The
// empty shine segment keeps the host's header-encryption variant; the
// transport segment must always be present (TCP unless configured), or a
// host that currently talks WSS would keep WSS against the target.
want := string([]byte{protocol.CommandAssignMaster, protocol.ShareTypeYamaForever}) +
"mfc.example:6544:2::0\x00"
if string(sent) != want {
t.Fatalf("sent = %q, want %q", sent, want)
}
// The marker is what the card renders as "transferred → …".
target, until, ok := hist.Transfer("live")
if !ok || target != "mfc.example:6544" || until <= 0 {
t.Fatalf("history marker = %q/%d/%v, want mfc.example:6544 with a deadline", target, until, ok)
}
}
// The configured transport must reach the device: the clients keep their
// current link when the segment is missing, so a WSS-managed host handed to a
// plain-TCP master would retry WSS forever.
func TestTransferDeviceSendsConfiguredTransport(t *testing.T) {
wh, h, _ := deleteTestHub(t)
wh.withTransferDefaults("mfc.example:6544", 2, protocol.TransferTransportWSS)
var sent []byte
h.SetSender(func(_ *connection.Context, data []byte) error {
sent = append([]byte(nil), data...)
return nil
})
h.Register(&hub.Device{ID: "live", Name: "Live"},
&connection.Context{RemoteAddr: "10.0.0.14:1000"})
c, tok := deleteTestClient(wh, "admin")
raw, _ := json.Marshal(map[string]any{
"token": tok, "id": "live", "host": "mfc.example", "port": 6544, "days": 1,
})
wh.handleTransferDevice(c, raw)
if rep := transferReply(t, c); rep["ok"] != true {
t.Fatalf("reply = %+v, want ok", rep)
}
want := string([]byte{protocol.CommandAssignMaster, protocol.ShareTypeYamaForever}) +
"mfc.example:6544:1::6\x00"
if string(sent) != want {
t.Fatalf("sent = %q, want %q", sent, want)
}
}
func TestTransferDeviceRequiresAdmin(t *testing.T) {
wh, h, hist := deleteTestHub(t)
sent := false
h.SetSender(func(_ *connection.Context, _ []byte) error {
sent = true
return nil
})
h.Register(&hub.Device{ID: "live", Name: "Live"},
&connection.Context{RemoteAddr: "10.0.0.10:1000"})
c, tok := deleteTestClient(wh, "viewer")
raw, _ := json.Marshal(map[string]any{
"token": tok, "id": "live", "host": "mfc.example", "port": 6544, "days": 1,
})
wh.handleTransferDevice(c, raw)
if rep := transferReply(t, c); rep["ok"] != false {
t.Fatalf("reply = %+v, want ok:false", rep)
}
if sent {
t.Fatal("viewer's transfer command reached the device")
}
if _, _, ok := hist.Transfer("live"); ok {
t.Fatal("viewer's transfer left a marker")
}
}
func TestTransferDeviceOffline(t *testing.T) {
wh, _, _ := deleteTestHub(t)
c, tok := deleteTestClient(wh, "admin")
raw, _ := json.Marshal(map[string]any{
"token": tok, "id": "never-seen", "host": "mfc.example", "port": 6544, "days": 1,
})
wh.handleTransferDevice(c, raw)
if rep := transferReply(t, c); rep["ok"] != false || rep["msg"] != "Host is offline" {
t.Fatalf("reply = %+v, want offline failure", rep)
}
}
func TestTransferDeviceRejectsBadTarget(t *testing.T) {
cases := []struct {
name string
in map[string]any
}{
{"empty host", map[string]any{"host": "", "port": 6544, "days": 1}},
{"colon in host", map[string]any{"host": "mfc:6544", "port": 6544, "days": 1}},
{"port zero", map[string]any{"host": "mfc.example", "port": 0, "days": 1}},
{"port too big", map[string]any{"host": "mfc.example", "port": 70000, "days": 1}},
{"zero days", map[string]any{"host": "mfc.example", "port": 6544, "days": 0}},
{"too many days", map[string]any{"host": "mfc.example", "port": 6544, "days": 400}},
{"no id", map[string]any{"id": "", "host": "mfc.example", "port": 6544, "days": 1}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
wh, h, _ := deleteTestHub(t)
sent := false
h.SetSender(func(_ *connection.Context, _ []byte) error {
sent = true
return nil
})
h.Register(&hub.Device{ID: "live", Name: "Live"},
&connection.Context{RemoteAddr: "10.0.0.11:1000"})
c, tok := deleteTestClient(wh, "admin")
args := map[string]any{"token": tok, "id": "live"}
for k, v := range tc.in {
args[k] = v
}
raw, _ := json.Marshal(args)
wh.handleTransferDevice(c, raw)
if rep := transferReply(t, c); rep["ok"] != false {
t.Fatalf("reply = %+v, want ok:false", rep)
}
if sent {
t.Fatal("invalid target still reached the device")
}
})
}
}
// A second assignment while the first one is live would be ignored by the
// Windows client ("Avoid assign again"), so the server must not report success
// for it.
func TestTransferDeviceRefusesSecondTransfer(t *testing.T) {
wh, h, hist := deleteTestHub(t)
sends := 0
h.SetSender(func(_ *connection.Context, _ []byte) error {
sends++
return nil
})
h.Register(&hub.Device{ID: "live", Name: "Live"},
&connection.Context{RemoteAddr: "10.0.0.12:1000"})
if !hist.SetTransfer("live", "mfc.example:6544", 1<<62) {
t.Fatal("SetTransfer on a live device failed")
}
c, tok := deleteTestClient(wh, "admin")
raw, _ := json.Marshal(map[string]any{
"token": tok, "id": "live", "host": "other.example", "port": 6544, "days": 1,
})
wh.handleTransferDevice(c, raw)
rep := transferReply(t, c)
if rep["ok"] != false {
t.Fatalf("reply = %+v, want ok:false", rep)
}
if sends != 0 {
t.Fatalf("device received %d commands, want 0", sends)
}
if target, _, _ := hist.Transfer("live"); target != "mfc.example:6544" {
t.Fatalf("marker overwritten to %q", target)
}
}
// The shared page decides whether to show the transfer button by the presence
// of the "transfer" object in device_list, and reads the card marker from
// transferTo/transferUntil. Both are part of the contract with index.html.
func TestDeviceListReportsTransferContract(t *testing.T) {
wh, h, hist := deleteTestHub(t)
wh.withTransferDefaults("mfc.example:6544", 2, protocol.TransferTransportTCP)
h.Register(&hub.Device{ID: "live", Name: "Live"},
&connection.Context{RemoteAddr: "10.0.0.13:1000"})
if !hist.SetTransfer("live", "mfc.example:6544", 4102444800) { // year 2100
t.Fatal("SetTransfer failed")
}
c, tok := deleteTestClient(wh, "admin")
raw, _ := json.Marshal(map[string]any{"token": tok})
wh.handleGetDevices(c, raw)
var out struct {
Cmd string `json:"cmd"`
Transfer *struct {
Target string `json:"target"`
Days float64 `json:"days"`
} `json:"transfer"`
Devices []struct {
ID string `json:"id"`
TransferTo string `json:"transferTo"`
TransferUntil int64 `json:"transferUntil"`
} `json:"devices"`
}
for i := 0; i < 8; i++ {
select {
case m := <-c.send:
if err := json.Unmarshal(m.data, &out); err != nil {
t.Fatalf("decode: %v", err)
}
default:
t.Fatal("no device_list reply")
}
if out.Cmd == "device_list" {
break
}
}
if out.Transfer == nil {
t.Fatal("device_list carries no transfer config — the page would hide the button")
}
if out.Transfer.Target != "mfc.example:6544" || out.Transfer.Days != 2 {
t.Fatalf("transfer config = %+v", *out.Transfer)
}
if len(out.Devices) != 1 {
t.Fatalf("devices = %d, want 1", len(out.Devices))
}
if d := out.Devices[0]; d.TransferTo != "mfc.example:6544" || d.TransferUntil == 0 {
t.Fatalf("device marker = %+v, want mfc.example:6544 with a deadline", d)
}
}
+26
View File
@@ -181,6 +181,16 @@ type wsHub struct {
loginIPLimit *wsauth.RateLimiter
loginUserLimit *wsauth.RateLimiter
trustForwardedFor bool // honor X-Forwarded-For (only when behind a trusted proxy)
// transferTarget / transferDays pre-fill the "transfer host" dialog and,
// by being reported to the browser, tell the shared page that this backend
// implements COMMAND_ASSIGN_MASTER at all (see withTransferDefaults).
// transferTransport is the link the transferred host uses to reach the
// target (protocol.TransferTransport*); it is sent in the command because
// the clients keep their current link when it is missing.
transferTarget string
transferDays float64
transferTransport int
}
func newWSHub(auth *wsauth.Authenticator, devices *hub.Hub, history *devicehistory.Store, log *logger.Logger) *wsHub {
@@ -227,6 +237,22 @@ func (h *wsHub) withDeviceACL(acl *DeviceACL) *wsHub {
return h
}
// withTransferDefaults installs the pre-filled target/days and the link type
// (protocol.TransferTransport*) for the web UI's "transfer host" dialog. An
// empty target still enables the feature: the operator types the address in
// the dialog. The front-end keys the button's visibility off this being
// reported at all, so the shared page shows no transfer button on the MFC
// server (which never reports it).
func (h *wsHub) withTransferDefaults(target string, days float64, transport int) *wsHub {
h.transferTarget = target
if days <= 0 {
days = 1 // one day is enough for an upgrade round-trip
}
h.transferDays = days
h.transferTransport = transport
return h
}
// isSuperAdmin reports whether this session is the built-in admin account
// (username "admin" + role admin). Other admin-role users — local accounts
// created in the user panel or portal admins bridged by SSO — are device-
+140 -1
View File
@@ -5,6 +5,7 @@ import (
"errors"
"math"
"sort"
"strconv"
"strings"
"time"
@@ -90,6 +91,8 @@ func (h *wsHub) dispatch(c *wsClient, cmd string, raw []byte) {
// Admin operations (Phase 7).
case "delete_device":
h.handleDeleteDevice(c, raw)
case "transfer_device":
h.handleTransferDevice(c, raw)
case "create_user":
h.handleCreateUser(c, raw)
case "delete_user":
@@ -790,6 +793,13 @@ func (h *wsHub) handleGetDevices(c *wsClient, raw []byte) {
"devices": h.listVisibleDevices(c),
"username": c.user,
"role": c.role,
// Presence of this object is what tells the shared page that this
// backend implements "transfer host" (the MFC server omits it), so the
// button never appears where the command would go nowhere.
"transfer": map[string]any{
"target": h.transferTarget,
"days": h.transferDays,
},
}))
}
@@ -799,6 +809,11 @@ func (h *wsHub) handleGetDevices(c *wsClient, raw []byte) {
type deviceListItem struct {
hub.DeviceInfo
Owner string `json:"owner,omitempty"`
// TransferTo / TransferUntil carry the "handed over to another master"
// marker so the card can say where the host went and how long it stays
// there. Absent for a host that was never transferred.
TransferTo string `json:"transferTo,omitempty"`
TransferUntil int64 `json:"transferUntil,omitempty"`
}
// listVisibleDevices applies the device ACL to the online + offline snapshot.
@@ -815,7 +830,13 @@ func (h *wsHub) listVisibleDevices(c *wsClient) []deviceListItem {
if h.acl != nil && c.isSuperAdmin() {
owner = h.acl.Owner(d.ID)
}
out = append(out, deviceListItem{DeviceInfo: d, Owner: owner})
item := deviceListItem{DeviceInfo: d, Owner: owner}
if h.history != nil {
if target, until, ok := h.history.Transfer(d.ID); ok {
item.TransferTo, item.TransferUntil = target, until
}
}
out = append(out, item)
}
return out
}
@@ -1314,6 +1335,124 @@ func (h *wsHub) handleDeleteDevice(c *wsClient, raw []byte) {
}))
}
// maxTransferDays bounds the dialog input. A handover that outlives a year is
// indistinguishable from "lost the host": the client would sit on the other
// master long after whatever upgrade it was sent there for.
const maxTransferDays = 365
// handleTransferDevice hands one online host over to another master
// (COMMAND_ASSIGN_MASTER + SHARE_TYPE_YAMA_FOREVER) — the path that lets a Go
// server's host be upgraded by the MFC master: only a master the host is
// actually online on can push a new client build to it.
//
// The deadline is the client's business. It stored the master it booted
// against and reconnects there when the days run out, so nothing here
// schedules a restore; the server only keeps a marker so the card can read
// "transferred → host:port, N left" instead of silently going offline.
//
// Admin-only: this moves a host off this master.
func (h *wsHub) handleTransferDevice(c *wsClient, raw []byte) {
const replyCmd = "transfer_device_result"
if !h.requireAdmin(c, raw, replyCmd) {
return
}
var in struct {
ID string `json:"id"`
Host string `json:"host"`
Port int `json:"port"`
Days float64 `json:"days"`
}
if err := json.Unmarshal(raw, &in); err != nil {
h.audit(c, true, auditDeviceTransfer, map[string]any{
"ok": false,
"reason": "bad_payload",
})
c.queue(mustJSON(map[string]any{
"cmd": replyCmd, "ok": false, "msg": "Invalid transfer payload",
}))
return
}
in.ID = strings.TrimSpace(in.ID)
in.Host = strings.TrimSpace(in.Host)
// A ':' in the host would shift every following payload field, and the
// whole packet has to stay inside the 260-byte buffer both clients parse
// (MFC's assignFunction uses bToken[_MAX_PATH]).
if in.ID == "" || in.Host == "" || strings.Contains(in.Host, ":") || len(in.Host) > 200 ||
in.Port <= 0 || in.Port > 65535 || in.Days <= 0 || in.Days > maxTransferDays {
h.audit(c, true, auditDeviceTransfer, map[string]any{
"device_id": in.ID,
"host": in.Host,
"port": in.Port,
"days": in.Days,
"ok": false,
"reason": "invalid_target",
})
c.queue(mustJSON(map[string]any{
"cmd": replyCmd, "ok": false,
"msg": "Invalid target address or days (1-365)",
}))
return
}
// The Windows client ignores a second assignment while the first one is
// still live ("Avoid assign again"), so accepting it here would report a
// success the host never acted on.
target := in.Host + ":" + strconv.Itoa(in.Port)
if h.history != nil {
if prev, until, active := h.history.Transfer(in.ID); active {
h.audit(c, true, auditDeviceTransfer, map[string]any{
"device_id": in.ID,
"target": prev,
"ok": false,
"reason": "already_transferred",
})
c.queue(mustJSON(map[string]any{
"cmd": replyCmd, "ok": false,
"msg": "Host is already transferred to " + prev + " until it expires",
"target": prev, "until": until,
}))
return
}
}
if err := h.devices.SendToDevice(in.ID, protocol.BuildAssignMasterPacket(in.Host, in.Port, in.Days, h.transferTransport)); err != nil {
reason := "send_failed"
if errors.Is(err, hub.ErrDeviceOffline) {
reason = "offline"
}
h.audit(c, true, auditDeviceTransfer, map[string]any{
"device_id": in.ID,
"target": target,
"ok": false,
"reason": reason,
"error": err.Error(),
})
c.queue(mustJSON(map[string]any{
"cmd": replyCmd, "ok": false, "msg": "Host is offline",
}))
return
}
until := time.Now().Add(time.Duration(in.Days * 24 * float64(time.Hour))).Unix()
if h.history != nil {
// Display-only: a device whose login event has not landed yet still got
// the command, so a missing record must not turn this into a failure.
h.history.SetTransfer(in.ID, target, until)
}
h.audit(c, false, auditDeviceTransfer, map[string]any{
"device_id": in.ID,
"target": target,
"days": in.Days,
"until": until,
"ok": true,
})
h.broadcastAuthenticated(`{"cmd":"devices_changed"}`)
c.queue(mustJSON(map[string]any{
"cmd": replyCmd, "ok": true, "id": in.ID, "target": target, "until": until,
}))
}
// handleDeleteUser removes an account and revokes any of its live sessions.
// Admin-only. The bootstrap "admin" account is rejected at the wsauth layer.
func (h *wsHub) handleDeleteUser(c *wsClient, raw []byte) {