feat: 实现电脑端被控与控制界面
This commit is contained in:
@@ -0,0 +1,517 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/account"
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/engine"
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/idutil"
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/lockfile"
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/protocol"
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/shell"
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/store"
|
||||
nixmsg "git.asio.asia/nixevol/NixMsg/sdk/go"
|
||||
)
|
||||
|
||||
// App 是这台电脑唯一的连接和本机接口。
|
||||
type App struct {
|
||||
dir string
|
||||
st *store.Store
|
||||
eng *engine.Engine
|
||||
|
||||
mu sync.Mutex
|
||||
token string
|
||||
client *nixmsg.Client
|
||||
stop context.CancelFunc
|
||||
connState string
|
||||
connText string
|
||||
presence map[string]bool
|
||||
presenceOK bool
|
||||
deviceIDs []string
|
||||
serverLogs map[string][]protocol.Log
|
||||
}
|
||||
|
||||
func New(dir string) (*App, error) {
|
||||
st, err := store.New(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &App{
|
||||
dir: dir,
|
||||
st: st,
|
||||
eng: engine.New(st, shell.System{}),
|
||||
connText: "未连接",
|
||||
presence: map[string]bool{},
|
||||
serverLogs: map[string][]protocol.Log{},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Run 监听本机随机端口,并把地址写入锁文件。
|
||||
func (a *App) Run(ctx context.Context, lock *lockfile.File) error {
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
token := newToken()
|
||||
a.mu.Lock()
|
||||
a.token = token
|
||||
a.mu.Unlock()
|
||||
if err := lock.Publish(ln.Addr().String(), token, os.Getpid()); err != nil {
|
||||
_ = ln.Close()
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
a.mu.Lock()
|
||||
a.stop = cancel
|
||||
a.mu.Unlock()
|
||||
|
||||
srv := &http.Server{
|
||||
Handler: cors(a.routes()),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
}
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
sh, done := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer done()
|
||||
_ = srv.Shutdown(sh)
|
||||
a.closeClient()
|
||||
}()
|
||||
go a.autoConnect()
|
||||
err = srv.Serve(ln)
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *App) requestStop() {
|
||||
a.mu.Lock()
|
||||
stop := a.stop
|
||||
a.mu.Unlock()
|
||||
if stop != nil {
|
||||
stop()
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) autoConnect() {
|
||||
var url, id, session, pending string
|
||||
a.st.View(func(d *store.Data) {
|
||||
url, id, session, pending = d.NixURL, d.EndpointID, d.SessionToken, d.PendingSecret
|
||||
})
|
||||
if id == "" || url == "" {
|
||||
return
|
||||
}
|
||||
if session != "" {
|
||||
_ = a.connect(url, id, "", session)
|
||||
return
|
||||
}
|
||||
if pending != "" {
|
||||
_ = a.connect(url, id, pending, "")
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) connect(rawURL, id, password, session string) error {
|
||||
if !idutil.ValidEndpoint(id) {
|
||||
return engine.Error("端编号不正确")
|
||||
}
|
||||
_ = a.st.Update(func(d *store.Data) error {
|
||||
d.NixURL = rawURL
|
||||
d.EndpointID = id
|
||||
if password != "" {
|
||||
d.PendingSecret = password
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
c := nixmsg.New()
|
||||
c.OnSession(func(tok string) {
|
||||
if tok == "" {
|
||||
return
|
||||
}
|
||||
_ = a.st.Update(func(d *store.Data) error {
|
||||
d.SessionToken = tok
|
||||
d.PendingSecret = ""
|
||||
d.EndpointID = id
|
||||
d.NixURL = rawURL
|
||||
return nil
|
||||
})
|
||||
})
|
||||
c.OnMessage(func(msg nixmsg.Message) error { return a.onMessage(c, msg) })
|
||||
c.OnPresence(func(ev nixmsg.PresenceEvent) { a.onPresence(c, ev) })
|
||||
c.OnConnection(func(ev nixmsg.ConnectionEvent) { a.onConnection(c, ev) })
|
||||
|
||||
a.mu.Lock()
|
||||
old := a.client
|
||||
a.client = c
|
||||
a.connState = string(nixmsg.StateConnecting)
|
||||
a.connText = "正在连接"
|
||||
a.mu.Unlock()
|
||||
if old != nil {
|
||||
_ = old.Close()
|
||||
}
|
||||
|
||||
cred := nixmsg.Credential{Password: password}
|
||||
if session != "" {
|
||||
cred = nixmsg.Credential{SessionToken: session}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
|
||||
defer cancel()
|
||||
err := c.Connect(ctx, rawURL, id, cred, nixmsg.Options{ClientLabel: "tapremly/0.1"})
|
||||
if err != nil {
|
||||
a.noteAuth(err, session != "")
|
||||
a.mu.Lock()
|
||||
if a.client == c {
|
||||
a.client = nil
|
||||
a.connState = string(nixmsg.StateOffline)
|
||||
a.connText = publicErr(nixErr(err))
|
||||
}
|
||||
a.mu.Unlock()
|
||||
_ = c.Close()
|
||||
return nixErr(err)
|
||||
}
|
||||
go a.rewatch()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) noteAuth(err error, usedSession bool) {
|
||||
var api *nixmsg.APIError
|
||||
if !errors.As(err, &api) {
|
||||
return
|
||||
}
|
||||
switch api.Code {
|
||||
case nixmsg.CodeBadCredentials, nixmsg.CodeAuthFailed, nixmsg.CodePasswordReset, nixmsg.CodeSessionInvalid:
|
||||
_ = a.st.Update(func(d *store.Data) error {
|
||||
d.PendingSecret = ""
|
||||
if usedSession || api.Code == nixmsg.CodeSessionInvalid || api.Code == nixmsg.CodePasswordReset {
|
||||
d.SessionToken = ""
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) onConnection(c *nixmsg.Client, ev nixmsg.ConnectionEvent) {
|
||||
a.mu.Lock()
|
||||
if a.client != c {
|
||||
a.mu.Unlock()
|
||||
return
|
||||
}
|
||||
a.connState = string(ev.State)
|
||||
a.connText = connText(ev.State)
|
||||
a.mu.Unlock()
|
||||
if ev.State == nixmsg.StateAuthFailed {
|
||||
_ = a.st.Update(func(d *store.Data) error {
|
||||
d.SessionToken = ""
|
||||
d.PendingSecret = ""
|
||||
return nil
|
||||
})
|
||||
}
|
||||
if ev.State == nixmsg.StateOnline {
|
||||
go a.rewatch()
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) onPresence(c *nixmsg.Client, ev nixmsg.PresenceEvent) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.client != c {
|
||||
return
|
||||
}
|
||||
if a.presence == nil {
|
||||
a.presence = map[string]bool{}
|
||||
}
|
||||
a.presence[ev.ID] = ev.Online
|
||||
a.presenceOK = true
|
||||
}
|
||||
|
||||
func (a *App) onMessage(c *nixmsg.Client, msg nixmsg.Message) error {
|
||||
a.mu.Lock()
|
||||
cur := a.client
|
||||
a.mu.Unlock()
|
||||
if cur != c {
|
||||
return nil
|
||||
}
|
||||
outs, logs, err := a.eng.Accept(msg.From, msg.Body.Data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, o := range outs {
|
||||
_, _ = a.sendRaw(o.To, o.Body, engine.Delivery{}, false)
|
||||
}
|
||||
if len(logs) > 0 {
|
||||
go a.uploadLogs(logs)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) closeClient() {
|
||||
a.mu.Lock()
|
||||
c := a.client
|
||||
a.client = nil
|
||||
a.connState = string(nixmsg.StateOffline)
|
||||
a.connText = "未连接"
|
||||
a.presenceOK = false
|
||||
a.mu.Unlock()
|
||||
if c != nil {
|
||||
_ = c.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) sendRaw(to string, body []byte, opt engine.Delivery, pinID bool) (nixmsg.SendResult, error) {
|
||||
a.mu.Lock()
|
||||
c := a.client
|
||||
a.mu.Unlock()
|
||||
if c == nil {
|
||||
return nixmsg.SendResult{}, engine.Error("还没有连上")
|
||||
}
|
||||
so := nixmsg.SendOptions{ContentType: "application/json; charset=utf-8"}
|
||||
if opt.Keep {
|
||||
so.Keep = true
|
||||
so.TTL = opt.TTL
|
||||
}
|
||||
so.SendAt = opt.SendAt
|
||||
if pinID {
|
||||
var probe struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if json.Unmarshal(body, &probe) == nil && idutil.ValidMessage(probe.ID) {
|
||||
so.ID = probe.ID
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
|
||||
defer cancel()
|
||||
res, err := c.Send(ctx, nixmsg.Target{Kind: "endpoint", ID: to}, nixmsg.Body{
|
||||
Enc: "utf8",
|
||||
ContentType: "application/json; charset=utf-8",
|
||||
Data: string(body),
|
||||
}, so)
|
||||
if err != nil {
|
||||
return res, nixErr(err)
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (a *App) uploadLogs(items []protocol.Log) {
|
||||
var base, token, ep string
|
||||
a.st.View(func(d *store.Data) {
|
||||
base, token, ep = d.ServerURL, d.DeviceToken, d.EndpointID
|
||||
})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
_ = account.PutLogs(ctx, base, ep, token, items)
|
||||
}
|
||||
|
||||
func (a *App) rewatch() {
|
||||
a.mu.Lock()
|
||||
ids := append([]string(nil), a.deviceIDs...)
|
||||
c := a.client
|
||||
a.mu.Unlock()
|
||||
if c == nil || len(ids) == 0 {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
_ = c.WatchPresence(ctx, ids, false)
|
||||
items, err := c.Presence(ctx, ids)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.client != c {
|
||||
return
|
||||
}
|
||||
if a.presence == nil {
|
||||
a.presence = map[string]bool{}
|
||||
}
|
||||
for _, it := range items {
|
||||
a.presence[it.ID] = it.Online
|
||||
}
|
||||
a.presenceOK = true
|
||||
}
|
||||
|
||||
func (a *App) rememberDevices(list []account.Device) {
|
||||
ids := make([]string, 0, len(list))
|
||||
seen := map[string]bool{}
|
||||
for _, d := range list {
|
||||
if d.EndpointID == "" || seen[d.EndpointID] {
|
||||
continue
|
||||
}
|
||||
seen[d.EndpointID] = true
|
||||
ids = append(ids, d.EndpointID)
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.deviceIDs = ids
|
||||
a.mu.Unlock()
|
||||
go a.rewatch()
|
||||
}
|
||||
|
||||
func (a *App) limits() engine.Limits {
|
||||
a.mu.Lock()
|
||||
c := a.client
|
||||
a.mu.Unlock()
|
||||
if c == nil {
|
||||
return engine.Limits{}
|
||||
}
|
||||
lim := c.Limits()
|
||||
return engine.Limits{MaxTTL: lim.MaxTTLSeconds, MaxSchedule: lim.MaxScheduleSeconds}
|
||||
}
|
||||
|
||||
func (a *App) session() (*account.Session, error) {
|
||||
var base string
|
||||
var cookies []store.Cookie
|
||||
a.st.View(func(d *store.Data) {
|
||||
base = d.ServerURL
|
||||
cookies = append([]store.Cookie(nil), d.Cookies...)
|
||||
})
|
||||
return account.NewSession(base, cookies)
|
||||
}
|
||||
|
||||
func (a *App) pushPublished() {
|
||||
body, err := protocol.ShortcutsBody("", a.eng.Published())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
online := a.connState == string(nixmsg.StateOnline) && a.presenceOK
|
||||
presence := a.presence
|
||||
a.mu.Unlock()
|
||||
if !online {
|
||||
return
|
||||
}
|
||||
for _, id := range a.eng.TrustList() {
|
||||
if presence[id] {
|
||||
_, _ = a.sendRaw(id, body, engine.Delivery{}, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) refreshShortcuts(remote string) error {
|
||||
if !idutil.ValidEndpoint(remote) {
|
||||
return engine.Error("端编号不正确")
|
||||
}
|
||||
id := idutil.New()
|
||||
if err := a.eng.BeginShortcutSync(remote, id); err != nil {
|
||||
return err
|
||||
}
|
||||
body, err := protocol.ShortcutsGetBody(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := a.sendRaw(remote, body, engine.Delivery{}, false); err != nil {
|
||||
_ = a.eng.FinishShortcutSync(remote, id)
|
||||
return err
|
||||
}
|
||||
go func() {
|
||||
time.Sleep(8 * time.Second)
|
||||
_ = a.eng.FinishShortcutSync(remote, id)
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) refreshLogs(remote string) error {
|
||||
if !idutil.ValidEndpoint(remote) {
|
||||
return engine.Error("端编号不正确")
|
||||
}
|
||||
if sess, err := a.session(); err == nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
items, gerr := sess.GetLogs(ctx, remote)
|
||||
cancel()
|
||||
if gerr == nil {
|
||||
a.mu.Lock()
|
||||
a.serverLogs[remote] = items
|
||||
a.mu.Unlock()
|
||||
}
|
||||
}
|
||||
a.mu.Lock()
|
||||
online := a.connState == string(nixmsg.StateOnline) && a.presenceOK && a.presence[remote]
|
||||
a.mu.Unlock()
|
||||
if !online {
|
||||
return nil
|
||||
}
|
||||
id := idutil.New()
|
||||
if err := a.eng.BeginLogSync(remote, id); err != nil {
|
||||
return err
|
||||
}
|
||||
body, err := protocol.LogsGetBody(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := a.sendRaw(remote, body, engine.Delivery{}, false); err != nil {
|
||||
_ = a.eng.FinishLogSync(remote, id, "")
|
||||
return err
|
||||
}
|
||||
go func() {
|
||||
time.Sleep(8 * time.Second)
|
||||
_ = a.eng.FinishLogSync(remote, id, "")
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func connText(st nixmsg.ConnectionState) string {
|
||||
switch st {
|
||||
case nixmsg.StateOnline:
|
||||
return "在线"
|
||||
case nixmsg.StateConnecting, nixmsg.StateReconnecting:
|
||||
return "正在连接"
|
||||
case nixmsg.StateKicked:
|
||||
return "已在其他地方登录"
|
||||
case nixmsg.StateAuthFailed:
|
||||
return "登录失败"
|
||||
default:
|
||||
return "未连接"
|
||||
}
|
||||
}
|
||||
|
||||
func nixErr(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var api *nixmsg.APIError
|
||||
if errors.As(err, &api) {
|
||||
switch api.Code {
|
||||
case nixmsg.CodeBadCredentials, nixmsg.CodeAuthFailed, nixmsg.CodePasswordReset:
|
||||
return engine.Error("端编号或密码不正确")
|
||||
case nixmsg.CodeTakenOver, nixmsg.CodeKicked:
|
||||
return engine.Error("这个端已在其他地方登录")
|
||||
case nixmsg.CodeSessionInvalid:
|
||||
return engine.Error("登录已失效,请重新登录")
|
||||
default:
|
||||
return engine.Error("连不上")
|
||||
}
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return engine.Error("连不上")
|
||||
}
|
||||
return engine.Error("连不上")
|
||||
}
|
||||
|
||||
func publicErr(err error) string {
|
||||
var ee engine.Error
|
||||
if errors.As(err, &ee) {
|
||||
return ee.Error()
|
||||
}
|
||||
var ae account.Error
|
||||
if errors.As(err, &ae) {
|
||||
return ae.Error()
|
||||
}
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
return "没有成功"
|
||||
}
|
||||
|
||||
func newToken() string {
|
||||
var b [32]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
@@ -0,0 +1,880 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/account"
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/engine"
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/idutil"
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/protocol"
|
||||
"git.asio.asia/TapRemly/desktop/agent/internal/store"
|
||||
nixmsg "git.asio.asia/nixevol/NixMsg/sdk/go"
|
||||
)
|
||||
|
||||
func (a *App) routes() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /v1/status", a.authed(a.handleStatus))
|
||||
mux.HandleFunc("POST /v1/stop", a.authed(a.handleStop))
|
||||
mux.HandleFunc("PUT /v1/settings", a.authed(a.handlePutSettings))
|
||||
mux.HandleFunc("POST /v1/session", a.authed(a.handleLogin))
|
||||
mux.HandleFunc("POST /v1/session/reconnect", a.authed(a.handleReconnect))
|
||||
mux.HandleFunc("DELETE /v1/session", a.authed(a.handleLogout))
|
||||
mux.HandleFunc("POST /v1/account/login", a.authed(a.handleAccountLogin))
|
||||
mux.HandleFunc("DELETE /v1/account", a.authed(a.handleAccountLogout))
|
||||
mux.HandleFunc("GET /v1/devices", a.authed(a.handleDevices))
|
||||
mux.HandleFunc("POST /v1/devices", a.authed(a.handleAddDevice))
|
||||
mux.HandleFunc("PATCH /v1/devices/{id}", a.authed(a.handlePatchDevice))
|
||||
mux.HandleFunc("DELETE /v1/devices/{id}", a.authed(a.handleDeleteDevice))
|
||||
mux.HandleFunc("GET /v1/groups", a.authed(a.handleGroups))
|
||||
mux.HandleFunc("POST /v1/groups", a.authed(a.handleCreateGroup))
|
||||
mux.HandleFunc("PATCH /v1/groups/{id}", a.authed(a.handleRenameGroup))
|
||||
mux.HandleFunc("DELETE /v1/groups/{id}", a.authed(a.handleDeleteGroup))
|
||||
mux.HandleFunc("GET /v1/trust", a.authed(a.handleTrustList))
|
||||
mux.HandleFunc("POST /v1/trust", a.authed(a.handleTrustAdd))
|
||||
mux.HandleFunc("DELETE /v1/trust/{id}", a.authed(a.handleTrustRemove))
|
||||
mux.HandleFunc("GET /v1/shortcuts/local", a.authed(a.handleLocalList))
|
||||
mux.HandleFunc("POST /v1/shortcuts/local", a.authed(a.handleLocalSave))
|
||||
mux.HandleFunc("PATCH /v1/shortcuts/local/{id}", a.authed(a.handleLocalUpdate))
|
||||
mux.HandleFunc("DELETE /v1/shortcuts/local/{id}", a.authed(a.handleLocalDelete))
|
||||
mux.HandleFunc("POST /v1/shortcuts/copy", a.authed(a.handleCopy))
|
||||
mux.HandleFunc("GET /v1/shortcuts/remote", a.authed(a.handleRemoteList))
|
||||
mux.HandleFunc("POST /v1/shortcuts/remote/refresh", a.authed(a.handleRemoteRefresh))
|
||||
mux.HandleFunc("GET /v1/shortcuts/published", a.authed(a.handlePublishedList))
|
||||
mux.HandleFunc("POST /v1/shortcuts/published", a.authed(a.handlePublishedSave))
|
||||
mux.HandleFunc("PATCH /v1/shortcuts/published/{id}", a.authed(a.handlePublishedUpdate))
|
||||
mux.HandleFunc("DELETE /v1/shortcuts/published/{id}", a.authed(a.handlePublishedDelete))
|
||||
mux.HandleFunc("POST /v1/send", a.authed(a.handleSend))
|
||||
mux.HandleFunc("GET /v1/inbox", a.authed(a.handleInbox))
|
||||
mux.HandleFunc("POST /v1/inbox/read", a.authed(a.handleInboxRead))
|
||||
mux.HandleFunc("GET /v1/results", a.authed(a.handleResults))
|
||||
mux.HandleFunc("GET /v1/logs", a.authed(a.handleLocalLogs))
|
||||
mux.HandleFunc("GET /v1/logs/remote", a.authed(a.handleRemoteLogs))
|
||||
mux.HandleFunc("POST /v1/logs/fetch", a.authed(a.handleFetchLogs))
|
||||
return mux
|
||||
}
|
||||
|
||||
func (a *App) authed(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
h := r.Header.Get("Authorization")
|
||||
const prefix = "Bearer "
|
||||
a.mu.Lock()
|
||||
token := a.token
|
||||
a.mu.Unlock()
|
||||
if len(h) <= len(prefix) || h[:len(prefix)] != prefix || token == "" || subtleEqual(h[len(prefix):], token) != 1 {
|
||||
writeErr(w, http.StatusUnauthorized, "请先连接")
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func subtleEqual(a, b string) int {
|
||||
if len(a) != len(b) {
|
||||
return 0
|
||||
}
|
||||
var v byte
|
||||
for i := 0; i < len(a); i++ {
|
||||
v |= a[i] ^ b[i]
|
||||
}
|
||||
if v == 0 {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (a *App) handleStatus(w http.ResponseWriter, _ *http.Request) {
|
||||
var endpoint, server, nix, user, session string
|
||||
var hasToken bool
|
||||
a.st.View(func(d *store.Data) {
|
||||
endpoint, server, nix, user, session = d.EndpointID, d.ServerURL, d.NixURL, d.AccountUser, d.SessionToken
|
||||
hasToken = d.DeviceToken != ""
|
||||
})
|
||||
a.mu.Lock()
|
||||
state, text := a.connState, a.connText
|
||||
a.mu.Unlock()
|
||||
if text == "" {
|
||||
text = "未连接"
|
||||
}
|
||||
lim := a.limits()
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"running": true,
|
||||
"conn": state,
|
||||
"conn_text": text,
|
||||
"endpoint_id": endpoint,
|
||||
"logged_in": session != "",
|
||||
"server_url": server,
|
||||
"nixmsg_url": nix,
|
||||
"account_user": user,
|
||||
"has_device_token": hasToken,
|
||||
"max_ttl_seconds": limOr(lim.MaxTTL, 2592000),
|
||||
"max_schedule_seconds": limOr(lim.MaxSchedule, 31536000),
|
||||
})
|
||||
}
|
||||
|
||||
func limOr(v, def int64) int64 {
|
||||
if v > 0 {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func (a *App) handleStop(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
go func() {
|
||||
time.Sleep(80 * time.Millisecond)
|
||||
a.requestStop()
|
||||
}()
|
||||
}
|
||||
|
||||
func (a *App) handlePutSettings(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
ServerURL string `json:"server_url"`
|
||||
NixURL string `json:"nixmsg_url"`
|
||||
}
|
||||
if err := readJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "内容不正确")
|
||||
return
|
||||
}
|
||||
req.ServerURL = strings.TrimRight(strings.TrimSpace(req.ServerURL), "/")
|
||||
req.NixURL = strings.TrimSpace(req.NixURL)
|
||||
if !validServer(req.ServerURL) || !validNix(req.NixURL) {
|
||||
writeErr(w, http.StatusBadRequest, "地址不正确")
|
||||
return
|
||||
}
|
||||
if err := a.st.Update(func(d *store.Data) error {
|
||||
d.ServerURL = req.ServerURL
|
||||
d.NixURL = req.NixURL
|
||||
return nil
|
||||
}); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *App) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
EndpointID string `json:"endpoint_id"`
|
||||
Password string `json:"password"`
|
||||
NixURL string `json:"nixmsg_url"`
|
||||
}
|
||||
if err := readJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "内容不正确")
|
||||
return
|
||||
}
|
||||
req.EndpointID = strings.TrimSpace(req.EndpointID)
|
||||
req.NixURL = strings.TrimSpace(req.NixURL)
|
||||
if req.NixURL == "" {
|
||||
a.st.View(func(d *store.Data) { req.NixURL = d.NixURL })
|
||||
}
|
||||
if !validNix(req.NixURL) {
|
||||
writeErr(w, http.StatusBadRequest, "地址不正确")
|
||||
return
|
||||
}
|
||||
if err := a.connect(req.NixURL, req.EndpointID, req.Password, ""); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "endpoint_id": req.EndpointID})
|
||||
}
|
||||
|
||||
func (a *App) handleReconnect(w http.ResponseWriter, _ *http.Request) {
|
||||
var url, id, session, pending string
|
||||
a.st.View(func(d *store.Data) {
|
||||
url, id, session, pending = d.NixURL, d.EndpointID, d.SessionToken, d.PendingSecret
|
||||
})
|
||||
if id == "" {
|
||||
writeErr(w, http.StatusBadRequest, "请先登录")
|
||||
return
|
||||
}
|
||||
var err error
|
||||
switch {
|
||||
case session != "":
|
||||
err = a.connect(url, id, "", session)
|
||||
case pending != "":
|
||||
err = a.connect(url, id, pending, "")
|
||||
default:
|
||||
writeErr(w, http.StatusBadRequest, "请重新登录")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *App) handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||
a.mu.Lock()
|
||||
c := a.client
|
||||
a.mu.Unlock()
|
||||
if c != nil {
|
||||
ctx, cancel := contextTimeout(r)
|
||||
_ = c.Logout(ctx)
|
||||
cancel()
|
||||
}
|
||||
a.closeClient()
|
||||
_ = a.st.Update(func(d *store.Data) error {
|
||||
d.SessionToken = ""
|
||||
d.PendingSecret = ""
|
||||
return nil
|
||||
})
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *App) handleAccountLogin(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := readJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "内容不正确")
|
||||
return
|
||||
}
|
||||
req.Username = strings.TrimSpace(req.Username)
|
||||
if req.Username == "" || req.Password == "" {
|
||||
writeErr(w, http.StatusBadRequest, "请填写账号和密码")
|
||||
return
|
||||
}
|
||||
sess, err := a.session()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
ctx, cancel := contextTimeout(r)
|
||||
defer cancel()
|
||||
name, err := sess.Login(ctx, req.Username, req.Password)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
if err := a.st.Update(func(d *store.Data) error {
|
||||
d.AccountUser = name
|
||||
d.Cookies = sess.Cookies()
|
||||
return nil
|
||||
}); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"username": name})
|
||||
}
|
||||
|
||||
func (a *App) handleAccountLogout(w http.ResponseWriter, r *http.Request) {
|
||||
if sess, err := a.session(); err == nil {
|
||||
ctx, cancel := contextTimeout(r)
|
||||
_ = sess.Logout(ctx)
|
||||
cancel()
|
||||
}
|
||||
_ = a.st.Update(func(d *store.Data) error {
|
||||
d.AccountUser = ""
|
||||
d.Cookies = nil
|
||||
return nil
|
||||
})
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *App) handleDevices(w http.ResponseWriter, r *http.Request) {
|
||||
sess, err := a.accountSession()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusUnauthorized, publicErr(err))
|
||||
return
|
||||
}
|
||||
ctx, cancel := contextTimeout(r)
|
||||
defer cancel()
|
||||
list, err := sess.Devices(ctx)
|
||||
_ = a.st.Update(func(d *store.Data) error {
|
||||
d.Cookies = sess.Cookies()
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadGateway, publicErr(err))
|
||||
return
|
||||
}
|
||||
a.rememberDevices(list)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": a.decorate(list)})
|
||||
}
|
||||
|
||||
func (a *App) handleGroups(w http.ResponseWriter, r *http.Request) {
|
||||
sess, err := a.accountSession()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusUnauthorized, publicErr(err))
|
||||
return
|
||||
}
|
||||
ctx, cancel := contextTimeout(r)
|
||||
defer cancel()
|
||||
list, err := sess.Groups(ctx)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadGateway, publicErr(err))
|
||||
return
|
||||
}
|
||||
items := make([]map[string]string, 0, len(list))
|
||||
for _, g := range list {
|
||||
items = append(items, map[string]string{"id": g.ID, "name": g.Name})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||
}
|
||||
|
||||
func (a *App) handleCreateGroup(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := readJSON(r, &req); err != nil || !idutil.ValidName(req.Name) {
|
||||
writeErr(w, http.StatusBadRequest, "请填写名称")
|
||||
return
|
||||
}
|
||||
a.withAccount(w, r, func(ctx context.Context, sess *account.Session) error {
|
||||
return sess.CreateGroup(ctx, strings.TrimSpace(req.Name))
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) handleRenameGroup(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := readJSON(r, &req); err != nil || !idutil.ValidName(req.Name) {
|
||||
writeErr(w, http.StatusBadRequest, "请填写名称")
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
a.withAccount(w, r, func(ctx context.Context, sess *account.Session) error {
|
||||
return sess.RenameGroup(ctx, id, strings.TrimSpace(req.Name))
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) handleDeleteGroup(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
a.withAccount(w, r, func(ctx context.Context, sess *account.Session) error {
|
||||
return sess.DeleteGroup(ctx, id)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) handleAddDevice(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
EndpointID string `json:"endpoint_id"`
|
||||
}
|
||||
if err := readJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "内容不正确")
|
||||
return
|
||||
}
|
||||
req.Name = strings.TrimSpace(req.Name)
|
||||
req.EndpointID = strings.TrimSpace(req.EndpointID)
|
||||
if !idutil.ValidName(req.Name) {
|
||||
writeErr(w, http.StatusBadRequest, "请填写名称")
|
||||
return
|
||||
}
|
||||
if req.EndpointID != "" && !idutil.ValidEndpoint(req.EndpointID) {
|
||||
writeErr(w, http.StatusBadRequest, "端编号不正确")
|
||||
return
|
||||
}
|
||||
sess, err := a.accountSession()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusUnauthorized, publicErr(err))
|
||||
return
|
||||
}
|
||||
ctx, cancel := contextTimeout(r)
|
||||
defer cancel()
|
||||
prov, err := sess.AddDevice(ctx, req.Name, req.EndpointID)
|
||||
_ = a.st.Update(func(d *store.Data) error {
|
||||
d.Cookies = sess.Cookies()
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadGateway, publicErr(err))
|
||||
return
|
||||
}
|
||||
if prov.DeviceToken != "" && req.EndpointID == "" {
|
||||
_ = a.st.Update(func(d *store.Data) error {
|
||||
d.DeviceToken = prov.DeviceToken
|
||||
if prov.EndpointID != "" {
|
||||
d.EndpointID = prov.EndpointID
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
if prov.Password != "" && prov.EndpointID != "" {
|
||||
var nix string
|
||||
a.st.View(func(d *store.Data) { nix = d.NixURL })
|
||||
_ = a.connect(nix, prov.EndpointID, prov.Password, "")
|
||||
}
|
||||
id := prov.ID
|
||||
if id == "" {
|
||||
id = prov.EndpointID
|
||||
}
|
||||
name := prov.Name
|
||||
if name == "" {
|
||||
name = req.Name
|
||||
}
|
||||
ep := prov.EndpointID
|
||||
if ep == "" {
|
||||
ep = req.EndpointID
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"id": id, "name": name, "endpoint_id": ep})
|
||||
}
|
||||
|
||||
func (a *App) handlePatchDevice(w http.ResponseWriter, r *http.Request) {
|
||||
var raw map[string]json.RawMessage
|
||||
if err := readJSON(r, &raw); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "内容不正确")
|
||||
return
|
||||
}
|
||||
var name, groupID *string
|
||||
if b, ok := raw["name"]; ok {
|
||||
var s string
|
||||
if json.Unmarshal(b, &s) != nil || !idutil.ValidName(s) {
|
||||
writeErr(w, http.StatusBadRequest, "请填写名称")
|
||||
return
|
||||
}
|
||||
s = strings.TrimSpace(s)
|
||||
name = &s
|
||||
}
|
||||
if b, ok := raw["group_id"]; ok {
|
||||
var s string
|
||||
if json.Unmarshal(b, &s) != nil {
|
||||
writeErr(w, http.StatusBadRequest, "内容不正确")
|
||||
return
|
||||
}
|
||||
groupID = &s
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
a.withAccount(w, r, func(ctx context.Context, sess *account.Session) error {
|
||||
return sess.PatchDevice(ctx, id, name, groupID)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) handleDeleteDevice(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
a.withAccount(w, r, func(ctx context.Context, sess *account.Session) error {
|
||||
return sess.DeleteDevice(ctx, id)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) handleTrustList(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": a.eng.TrustList()})
|
||||
}
|
||||
|
||||
func (a *App) handleTrustAdd(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
EndpointID string `json:"endpoint_id"`
|
||||
}
|
||||
if err := readJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "内容不正确")
|
||||
return
|
||||
}
|
||||
if err := a.eng.TrustAdd(req.EndpointID); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *App) handleTrustRemove(w http.ResponseWriter, r *http.Request) {
|
||||
id, _ := url.PathUnescape(r.PathValue("id"))
|
||||
if err := a.eng.TrustRemove(id); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *App) handleLocalList(w http.ResponseWriter, r *http.Request) {
|
||||
remote := r.URL.Query().Get("remote")
|
||||
items := a.eng.ListLocal(remote)
|
||||
out := make([]map[string]any, 0, len(items))
|
||||
for _, it := range items {
|
||||
out = append(out, map[string]any{
|
||||
"id": it.ID, "name": it.Name, "shell": it.Shell, "confirm": it.Confirm, "remote_id": it.RemoteID,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": out})
|
||||
}
|
||||
|
||||
func (a *App) handleLocalSave(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
RemoteID string `json:"remote_id"`
|
||||
Name string `json:"name"`
|
||||
Shell string `json:"shell"`
|
||||
Confirm bool `json:"confirm"`
|
||||
}
|
||||
if err := readJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "内容不正确")
|
||||
return
|
||||
}
|
||||
item, err := a.eng.SaveLocal(req.RemoteID, req.Name, req.Shell, req.Confirm)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, item)
|
||||
}
|
||||
|
||||
func (a *App) handleLocalUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Shell string `json:"shell"`
|
||||
Confirm bool `json:"confirm"`
|
||||
}
|
||||
if err := readJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "内容不正确")
|
||||
return
|
||||
}
|
||||
if err := a.eng.UpdateLocal(r.PathValue("id"), req.Name, req.Shell, req.Confirm); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *App) handleLocalDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if err := a.eng.DeleteLocal(r.PathValue("id")); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *App) handleCopy(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
RemoteID string `json:"remote_id"`
|
||||
ShortcutID string `json:"shortcut_id"`
|
||||
FromRemote bool `json:"from_remote"`
|
||||
Targets []string `json:"targets"`
|
||||
}
|
||||
if err := readJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "内容不正确")
|
||||
return
|
||||
}
|
||||
created, err := a.eng.CopyTo(req.RemoteID, req.ShortcutID, req.FromRemote, req.Targets)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": created})
|
||||
}
|
||||
|
||||
func (a *App) handleRemoteList(w http.ResponseWriter, r *http.Request) {
|
||||
remote := r.URL.Query().Get("remote")
|
||||
c := a.eng.RemoteCache(remote)
|
||||
synced := ""
|
||||
if !c.SyncedAt.IsZero() {
|
||||
synced = c.SyncedAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"items": c.Items, "synced_at": synced, "syncing": c.Syncing,
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) handleRemoteRefresh(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Remote string `json:"remote"`
|
||||
}
|
||||
if err := readJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "内容不正确")
|
||||
return
|
||||
}
|
||||
if err := a.refreshShortcuts(req.Remote); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *App) handlePublishedList(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": a.eng.Published()})
|
||||
}
|
||||
|
||||
func (a *App) handlePublishedSave(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Shell string `json:"shell"`
|
||||
Confirm bool `json:"confirm"`
|
||||
}
|
||||
if err := readJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "内容不正确")
|
||||
return
|
||||
}
|
||||
item, err := a.eng.SavePublished(req.Name, req.Shell, req.Confirm)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
go a.pushPublished()
|
||||
writeJSON(w, http.StatusOK, item)
|
||||
}
|
||||
|
||||
func (a *App) handlePublishedUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Shell string `json:"shell"`
|
||||
Confirm bool `json:"confirm"`
|
||||
}
|
||||
if err := readJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "内容不正确")
|
||||
return
|
||||
}
|
||||
if err := a.eng.UpdatePublished(r.PathValue("id"), req.Name, req.Shell, req.Confirm); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
go a.pushPublished()
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *App) handlePublishedDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if err := a.eng.DeletePublished(r.PathValue("id")); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
go a.pushPublished()
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *App) handleSend(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Remote string `json:"remote"`
|
||||
Kind string `json:"kind"`
|
||||
Shell string `json:"shell"`
|
||||
Text string `json:"text"`
|
||||
ShortcutID string `json:"shortcut_id"`
|
||||
SendAtMs *int64 `json:"send_at_ms"`
|
||||
Keep bool `json:"keep"`
|
||||
TTLSeconds *int64 `json:"ttl_seconds"`
|
||||
}
|
||||
if err := readJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "内容不正确")
|
||||
return
|
||||
}
|
||||
opt := engine.Delivery{Keep: req.Keep}
|
||||
if req.Keep {
|
||||
opt.TTL = req.TTLSeconds
|
||||
}
|
||||
if req.SendAtMs != nil && *req.SendAtMs > 0 {
|
||||
t := time.UnixMilli(*req.SendAtMs)
|
||||
opt.SendAt = &t
|
||||
}
|
||||
lim := a.limits()
|
||||
var (
|
||||
id string
|
||||
body []byte
|
||||
err error
|
||||
)
|
||||
switch req.Kind {
|
||||
case "shell":
|
||||
id, body, err = a.eng.SendShell(req.Remote, req.Shell, opt, lim)
|
||||
case "text":
|
||||
id, body, err = a.eng.SendText(req.Remote, req.Text, opt, lim)
|
||||
case "remote":
|
||||
id, body, err = a.eng.SendRemoteShortcut(req.Remote, req.ShortcutID, opt, lim)
|
||||
case "local":
|
||||
remote, script, _, lerr := a.eng.LocalShell(req.ShortcutID)
|
||||
if lerr != nil {
|
||||
err = lerr
|
||||
break
|
||||
}
|
||||
id, body, err = a.eng.SendShell(remote, script, opt, lim)
|
||||
req.Remote = remote
|
||||
default:
|
||||
writeErr(w, http.StatusBadRequest, "内容不正确")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
if _, err := a.sendRaw(req.Remote, body, opt, true); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"id": id, "note": a.offlineNote(req.Remote, opt)})
|
||||
}
|
||||
|
||||
func (a *App) offlineNote(remote string, opt engine.Delivery) string {
|
||||
if opt.SendAt != nil && opt.SendAt.After(time.Now().Add(2*time.Second)) {
|
||||
return "到时再发送"
|
||||
}
|
||||
if opt.Keep {
|
||||
return ""
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.connState == string(nixmsg.StateOnline) && a.presenceOK && !a.presence[remote] {
|
||||
return "没有留下"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (a *App) handleInbox(w http.ResponseWriter, _ *http.Request) {
|
||||
items := a.eng.Inbox()
|
||||
out := make([]map[string]any, 0, len(items))
|
||||
for _, it := range items {
|
||||
out = append(out, map[string]any{
|
||||
"id": it.ID, "from": it.From, "text": it.Text, "at": it.At.UTC().Format(time.RFC3339), "read": it.Read,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": out})
|
||||
}
|
||||
|
||||
func (a *App) handleInboxRead(w http.ResponseWriter, _ *http.Request) {
|
||||
if err := a.eng.MarkInboxRead(); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *App) handleResults(w http.ResponseWriter, _ *http.Request) {
|
||||
items := a.eng.Results()
|
||||
out := make([]map[string]any, 0, len(items))
|
||||
for _, it := range items {
|
||||
out = append(out, map[string]any{
|
||||
"id": it.ID, "remote": it.Remote, "ok": it.OK, "error": it.Error, "duplicate": it.Duplicate,
|
||||
"at": it.At.UTC().Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": out})
|
||||
}
|
||||
|
||||
func (a *App) handleLocalLogs(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": a.eng.LocalLogs()})
|
||||
}
|
||||
|
||||
func (a *App) handleRemoteLogs(w http.ResponseWriter, r *http.Request) {
|
||||
remote := r.URL.Query().Get("remote")
|
||||
c := a.eng.RemoteLogs(remote)
|
||||
synced := ""
|
||||
if !c.SyncedAt.IsZero() {
|
||||
synced = c.SyncedAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
a.mu.Lock()
|
||||
server := append([]protocol.Log(nil), a.serverLogs[remote]...)
|
||||
a.mu.Unlock()
|
||||
if server == nil {
|
||||
server = []protocol.Log{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"items": c.Items, "synced_at": synced, "syncing": c.Syncing, "error": c.Error, "server_items": server,
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) handleFetchLogs(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Remote string `json:"remote"`
|
||||
}
|
||||
if err := readJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "内容不正确")
|
||||
return
|
||||
}
|
||||
if err := a.refreshLogs(req.Remote); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, publicErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *App) decorate(list []account.Device) []map[string]any {
|
||||
a.mu.Lock()
|
||||
connected := a.connState == string(nixmsg.StateOnline)
|
||||
ready := a.presenceOK
|
||||
presence := a.presence
|
||||
a.mu.Unlock()
|
||||
out := make([]map[string]any, 0, len(list))
|
||||
for _, d := range list {
|
||||
p := "unknown"
|
||||
if connected && ready {
|
||||
if presence[d.EndpointID] {
|
||||
p = "online"
|
||||
} else {
|
||||
p = "offline"
|
||||
}
|
||||
}
|
||||
out = append(out, map[string]any{
|
||||
"id": d.ID, "name": d.Name, "endpoint_id": d.EndpointID, "group_id": d.GroupID,
|
||||
"online": p == "online", "presence": p,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (a *App) accountSession() (*account.Session, error) {
|
||||
var user string
|
||||
a.st.View(func(d *store.Data) { user = d.AccountUser })
|
||||
if user == "" {
|
||||
return nil, engine.Error("请先登录账号")
|
||||
}
|
||||
return a.session()
|
||||
}
|
||||
|
||||
func (a *App) withAccount(w http.ResponseWriter, r *http.Request, fn func(ctx context.Context, sess *account.Session) error) {
|
||||
sess, err := a.accountSession()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusUnauthorized, publicErr(err))
|
||||
return
|
||||
}
|
||||
ctx, cancel := contextTimeout(r)
|
||||
defer cancel()
|
||||
err = fn(ctx, sess)
|
||||
_ = a.st.Update(func(d *store.Data) error {
|
||||
d.Cookies = sess.Cookies()
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadGateway, publicErr(err))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func contextTimeout(r *http.Request) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(r.Context(), 20*time.Second)
|
||||
}
|
||||
|
||||
func validServer(s string) bool {
|
||||
u, err := url.Parse(s)
|
||||
if err != nil || u.Host == "" {
|
||||
return false
|
||||
}
|
||||
return u.Scheme == "http" || u.Scheme == "https"
|
||||
}
|
||||
|
||||
func validNix(s string) bool {
|
||||
u, err := url.Parse(s)
|
||||
if err != nil || u.Host == "" {
|
||||
return false
|
||||
}
|
||||
return u.Scheme == "ws" || u.Scheme == "wss"
|
||||
}
|
||||
|
||||
func readJSON(r *http.Request, dst any) error {
|
||||
dec := json.NewDecoder(http.MaxBytesReader(nil, r.Body, 1<<20))
|
||||
return dec.Decode(dst)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, code int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(code)
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetEscapeHTML(false)
|
||||
_ = enc.Encode(v)
|
||||
}
|
||||
|
||||
func writeErr(w http.ResponseWriter, code int, msg string) {
|
||||
writeJSON(w, code, map[string]string{"error": msg})
|
||||
}
|
||||
|
||||
func cors(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHTTPTempShellDoesNotCreateShortcut(t *testing.T) {
|
||||
a, err := New(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a.token = "secret"
|
||||
srv := httptest.NewServer(a.routes())
|
||||
defer srv.Close()
|
||||
|
||||
res := do(t, srv.URL, "POST", "/v1/send", `{"remote":"peer-a","kind":"shell","shell":"echo hi"}`)
|
||||
if res.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("status %d", res.StatusCode)
|
||||
}
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
_ = res.Body.Close()
|
||||
if !strings.Contains(string(body), "还没有连上") {
|
||||
t.Fatalf("body %s", body)
|
||||
}
|
||||
|
||||
res = do(t, srv.URL, "GET", "/v1/shortcuts/local?remote=peer-a", "")
|
||||
raw, _ := io.ReadAll(res.Body)
|
||||
_ = res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
t.Fatalf("list %d %s", res.StatusCode, raw)
|
||||
}
|
||||
if !strings.Contains(string(raw), `"items":[]`) && !strings.Contains(string(raw), `"items": []`) {
|
||||
t.Fatalf("shortcut appeared: %s", raw)
|
||||
}
|
||||
|
||||
res = do(t, srv.URL, "POST", "/v1/shortcuts/local", `{"remote_id":"peer-a","name":"打招呼","shell":"echo hi","confirm":false}`)
|
||||
raw, _ = io.ReadAll(res.Body)
|
||||
_ = res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
t.Fatalf("save %d %s", res.StatusCode, raw)
|
||||
}
|
||||
res = do(t, srv.URL, "GET", "/v1/shortcuts/local?remote=peer-a", "")
|
||||
raw, _ = io.ReadAll(res.Body)
|
||||
_ = res.Body.Close()
|
||||
if !strings.Contains(string(raw), "打招呼") {
|
||||
t.Fatalf("saved item missing: %s", raw)
|
||||
}
|
||||
res = do(t, srv.URL, "GET", "/v1/shortcuts/local?remote=peer-b", "")
|
||||
raw, _ = io.ReadAll(res.Body)
|
||||
_ = res.Body.Close()
|
||||
if strings.Contains(string(raw), "打招呼") {
|
||||
t.Fatalf("leaked: %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func do(t *testing.T, base, method, path, body string) *http.Response {
|
||||
t.Helper()
|
||||
var rdr io.Reader
|
||||
if body != "" {
|
||||
rdr = strings.NewReader(body)
|
||||
}
|
||||
req, err := http.NewRequest(method, base+path, rdr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer secret")
|
||||
if body != "" {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return res
|
||||
}
|
||||
Reference in New Issue
Block a user