feat: [WIP] implement scp by bgo

This commit is contained in:
2026-06-12 14:12:11 +08:00
parent 3cd92945ac
commit 250ba269f5
5 changed files with 278 additions and 21 deletions
+17 -4
View File
@@ -340,12 +340,16 @@ func (a *App) runSaveRemotePipeline(pngBytes []byte) error {
"auth_method", cfg.SSH.AuthMethod, "png_size", len(pngBytes)) "auth_method", cfg.SSH.AuthMethod, "png_size", len(pngBytes))
// Select the uploader by auth method: Kerberos delegates to the system // Select the uploader by auth method: Kerberos delegates to the system
// ssh/scp binaries (reusing the kinit credential cache), while builtin // ssh/scp binaries (reusing the kinit credential cache), bgo delegates to
// uses the in-process Go SSH client. // the internal `bgo scp` client (under a PTY), while builtin uses the
// in-process Go SSH client.
var uploader application.SSHUploader var uploader application.SSHUploader
if cfg.SSH.IsKerberos() { switch {
case cfg.SSH.IsKerberos():
uploader = sshpkg.NewKerberosUploader(cfg.SSH) uploader = sshpkg.NewKerberosUploader(cfg.SSH)
} else { case cfg.SSH.IsBgo():
uploader = sshpkg.NewBgoUploader(cfg.SSH)
default:
uploader = sshpkg.NewUploader(cfg.SSH) uploader = sshpkg.NewUploader(cfg.SSH)
} }
@@ -467,6 +471,15 @@ func (a *App) TestSSHConnection(cfg domain.SSHConfig) error {
} }
return nil return nil
} }
// bgo manages its own auth; we can only confirm the binary is installed
// and resolvable (a real transfer would need a live remote + PTY).
if cfg.IsBgo() {
if err := sshpkg.TestBgoConnection(a.ctx, cfg); err != nil {
slog.Error("RPC TestSSHConnection (bgo) failed", "err", err)
return err
}
return nil
}
if err := sshpkg.TestConnection(a.ctx, cfg); err != nil { if err := sshpkg.TestConnection(a.ctx, cfg); err != nil {
slog.Error("RPC TestSSHConnection failed", "err", err) slog.Error("RPC TestSSHConnection failed", "err", err)
return err return err
+13
View File
@@ -289,6 +289,7 @@ onMounted(load)
<option value="password">Password</option> <option value="password">Password</option>
<option value="key">SSH-Key</option> <option value="key">SSH-Key</option>
<option value="kerberos">Kerberos</option> <option value="kerberos">Kerberos</option>
<option value="bgo">bgo</option>
</select> </select>
</label> </label>
<label class="field"> <label class="field">
@@ -350,6 +351,18 @@ onMounted(load)
keys. Make sure password-less login already works (e.g. via keys. Make sure password-less login already works (e.g. via
<code>ssh-copy-id</code>). <code>ssh-copy-id</code>).
</p> </p>
<p v-else-if="config.ssh.authMethod === 'bgo'" class="hint">
bgo mode delegates uploads to the internal <code>bgo scp</code> client,
which handles authentication itself. Install bgo and add it to your
<code>PATH</code> first see the
<a
href="https://bytedance.larkoffice.com/wiki/HpUCw7qRDiW66YkzKdwcXYrTnLf"
target="_blank"
rel="noopener"
>setup guide</a>.
Note: bgo cannot create remote directories, so screenshots are saved
flat into the remote home directory (the Remote path setting is ignored).
</p>
<p <p
v-else-if="config.ssh.authMethod === 'password' && !config.ssh.password" v-else-if="config.ssh.authMethod === 'password' && !config.ssh.password"
class="hint warn" class="hint warn"
+17
View File
@@ -69,6 +69,12 @@ func (s *CaptureAndSSHService) ExecuteWithBytes(ctx context.Context, pngBytes []
return fmt.Errorf("empty screenshot") return fmt.Errorf("empty screenshot")
} }
relPath := buildRemoteRelPath(s.Cfg.PathPrefix) relPath := buildRemoteRelPath(s.Cfg.PathPrefix)
// bgo cannot create remote directories, so it uploads flat into the
// remote $HOME with a timestamped filename rather than a date-grouped
// subdirectory tree (see BgoUploader for the rationale).
if s.Cfg.IsBgo() {
relPath = buildRemoteFlatName()
}
sshSvcLog().Info("save-remote pipeline start", sshSvcLog().Info("save-remote pipeline start",
"host", s.Cfg.Host, "user", s.Cfg.User, "port", s.Cfg.Port, "host", s.Cfg.Host, "user", s.Cfg.User, "port", s.Cfg.Port,
"size", len(pngBytes), "remote_path", relPath, "size", len(pngBytes), "remote_path", relPath,
@@ -128,6 +134,17 @@ func buildRemoteRelPath(prefix string) string {
) )
} }
// buildRemoteFlatName produces a flat, timestamped filename (no directory
// components) for destinations that cannot create remote directories, such
// as the bgo client. The file lands directly in the remote $HOME.
func buildRemoteFlatName() string {
now := time.Now()
return fmt.Sprintf("%s-%s.png",
now.Format("20060102-150405"),
randomSuffix(6),
)
}
func (s *CaptureAndSSHService) notifyFailure(reason string) { func (s *CaptureAndSSHService) notifyFailure(reason string) {
if s.Notifier != nil { if s.Notifier != nil {
s.Notifier.NotifyFailure(reason) s.Notifier.NotifyFailure(reason)
+31 -17
View File
@@ -10,12 +10,12 @@ package domain
// endpoint, etc.). // endpoint, etc.).
// //
// Field design notes: // Field design notes:
// - PathPrefix supports object name templating so users can group screenshots // - PathPrefix supports object name templating so users can group screenshots
// by date. // by date.
// - PublicURLBase is optional to support CDN-fronted buckets; otherwise the // - PublicURLBase is optional to support CDN-fronted buckets; otherwise the
// adapter falls back to "{Endpoint}/{Bucket}/{Key}" (path-style). // adapter falls back to "{Endpoint}/{Bucket}/{Key}" (path-style).
// - UsePathStyle defaults to true because many self-hosted MinIO / R2 // - UsePathStyle defaults to true because many self-hosted MinIO / R2
// deployments do not support virtual-hosted-style addressing. // deployments do not support virtual-hosted-style addressing.
type S3Config struct { type S3Config struct {
Endpoint string `json:"endpoint"` Endpoint string `json:"endpoint"`
Region string `json:"region"` Region string `json:"region"`
@@ -34,17 +34,22 @@ type S3Config struct {
// - Host / Port form the destination endpoint. Port defaults to 22 when 0. // - Host / Port form the destination endpoint. Port defaults to 22 when 0.
// - User is the SSH login name. // - User is the SSH login name.
// - AuthMethod selects how the connection authenticates: // - AuthMethod selects how the connection authenticates:
// "password" → password only, via the in-process Go SSH client. // "password" → password only, via the in-process Go SSH client.
// "key" → ssh-agent + ~/.ssh/id_* key files (no password), // "key" → ssh-agent + ~/.ssh/id_* key files (no password),
// via the in-process Go SSH client. // via the in-process Go SSH client.
// "kerberos" → delegate to the system /usr/bin/ssh binary so the // "kerberos" → delegate to the system /usr/bin/ssh binary so the
// existing Kerberos (GSSAPI) credential cache from // existing Kerberos (GSSAPI) credential cache from
// `kinit` is reused. Native GSSAPI is required here // `kinit` is reused. Native GSSAPI is required here
// because macOS stores tickets in an API: ccache // because macOS stores tickets in an API: ccache
// that pure-Go SSH libraries cannot read. // that pure-Go SSH libraries cannot read.
// "" / "builtin" → legacy combined behaviour (password → agent → key // "bgo" delegate to the internal `bgo scp` client which
// files) kept only for backward compatibility with // handles its own auth/credential management. bgo
// configs written before the method was split. // must run under a PTY and cannot create remote
// directories, so this mode uploads to the user's
// remote $HOME with a flat, timestamped filename.
// "" / "builtin" → legacy combined behaviour (password → agent → key
// files) kept only for backward compatibility with
// configs written before the method was split.
// - Password is optional; when empty the implementation falls back to the // - Password is optional; when empty the implementation falls back to the
// local SSH agent or ~/.ssh/id_* keys (i.e. the user is responsible for // local SSH agent or ~/.ssh/id_* keys (i.e. the user is responsible for
// having password-less access already configured on this machine). // having password-less access already configured on this machine).
@@ -85,6 +90,10 @@ const (
// SSHAuthKerberos delegates to the system ssh binary so an existing // SSHAuthKerberos delegates to the system ssh binary so an existing
// Kerberos credential cache (populated by `kinit`) is reused via GSSAPI. // Kerberos credential cache (populated by `kinit`) is reused via GSSAPI.
SSHAuthKerberos = "kerberos" SSHAuthKerberos = "kerberos"
// SSHAuthBgo delegates to the internal `bgo scp` client, which manages
// its own authentication. bgo requires a PTY and cannot create remote
// directories, so uploads land flat in the remote $HOME.
SSHAuthBgo = "bgo"
) )
// IsKerberos reports whether this config requests Kerberos/GSSAPI auth. // IsKerberos reports whether this config requests Kerberos/GSSAPI auth.
@@ -92,6 +101,11 @@ func (c SSHConfig) IsKerberos() bool {
return c.AuthMethod == SSHAuthKerberos return c.AuthMethod == SSHAuthKerberos
} }
// IsBgo reports whether this config requests the internal bgo client.
func (c SSHConfig) IsBgo() bool {
return c.AuthMethod == SSHAuthBgo
}
// AppConfig is the top-level on-disk configuration document. // AppConfig is the top-level on-disk configuration document.
// //
// We keep S3 / SSH nested so that adding more providers later (e.g. AliyunOSS, // We keep S3 / SSH nested so that adding more providers later (e.g. AliyunOSS,
+200
View File
@@ -0,0 +1,200 @@
// bgo_uploader.go — an SSHUploader implementation that delegates to the
// internal `bgo scp` client. bgo is ByteDance's internal credential/auth
// management tool; it wraps ssh/scp and handles login transparently once the
// user has configured it (see the Lark guide linked in the Settings UI).
//
// 设计理由 (为什么不能直接 exec bgo, 也不能复用 KerberosUploader):
// - bgo 强制要求在 PTY (伪终端) 下运行: 它会对 stdin/stdout 做终端 ioctl
// (resize pty). 没有 PTY 时直接 panic ("operation not supported by
// device"). 因此必须用系统 /usr/bin/script 为其分配一个伪终端:
// script -q /dev/null <bgo> scp <src> <user@host:dst>
// 这样既不引入额外的 PTY 依赖, 又满足 bgo 的运行约束.
// - bgo scp 不会自动创建远程目录, 且 bgo ssh 无法执行远程命令 (会 panic),
// 所以无法像 Kerberos 那样先 `mkdir -p`. 故 bgo 模式只能把文件平铺上传
// 到远端用户的 $HOME 根目录 (文件名内嵌时间戳保证唯一), 上层 service
// 负责生成扁平文件名.
// - bgo 自带鉴权, 不需要也不应传 GSSAPI / 密码 / 公钥相关的 ssh 选项.
package ssh
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/mmmy/snapgo/internal/domain"
)
// systemScriptPath is the absolute path to the macOS BSD `script` utility,
// which we use purely to allocate a PTY for bgo. Absolute path avoids PATH
// hijacking and the minimal PATH GUI apps inherit on macOS.
const systemScriptPath = "/usr/bin/script"
// bgoSearchPaths lists the locations we probe for the bgo binary when it is
// not already resolvable via $PATH. GUI apps on macOS launch with a minimal
// PATH that usually omits ~/.local/bin and Homebrew dirs, so we look there
// explicitly rather than failing with a confusing "command not found".
func bgoSearchPaths() []string {
home, _ := os.UserHomeDir()
return []string{
filepath.Join(home, ".local", "bin", "bgo"),
"/usr/local/bin/bgo",
"/opt/homebrew/bin/bgo",
"/opt/bin/bgo",
}
}
// BgoUploader satisfies application.SSHUploader by shelling out to `bgo scp`
// under a PTY allocated via the system `script` utility.
type BgoUploader struct {
cfg domain.SSHConfig
}
// NewBgoUploader returns an uploader that delegates to the bgo client.
func NewBgoUploader(cfg domain.SSHConfig) *BgoUploader {
return &BgoUploader{cfg: cfg}
}
// resolveBgoBinary locates the bgo executable, first via $PATH and then via
// the well-known install locations. Returns a clear error pointing the user
// to the setup guide when bgo cannot be found.
func resolveBgoBinary() (string, error) {
if p, err := exec.LookPath("bgo"); err == nil {
return p, nil
}
for _, candidate := range bgoSearchPaths() {
if info, err := os.Stat(candidate); err == nil && !info.IsDir() {
return candidate, nil
}
}
return "", fmt.Errorf("bgo executable not found — install bgo and add it to PATH (see the setup guide)")
}
// Upload writes data to a flat remote filename in the user's remote $HOME by
// staging it locally and invoking `bgo scp` once under a PTY.
//
// remoteRelPath is expected to be a flat filename (no directory components),
// because bgo cannot create remote directories. Any directory components are
// collapsed to the base name defensively.
func (u *BgoUploader) Upload(ctx context.Context, remoteRelPath string, data []byte, mode os.FileMode) error {
start := time.Now()
// Collapse to a flat filename: bgo scp cannot create remote directories.
name := path.Base(normaliseRemotePath(remoteRelPath))
if name == "" || name == "." || name == "/" {
return fmt.Errorf("ssh(bgo): remote filename is empty")
}
bgoBin, err := resolveBgoBinary()
if err != nil {
sshLog().Error("bgo uploader: binary not found", "err", err)
return err
}
sshLog().Info("bgo uploader start",
"host", u.cfg.Host, "user", u.cfg.User, "port", u.cfg.Port,
"remote_file", name, "size", len(data), "bgo", bgoBin)
// 1. Stage the payload to a local temp file for scp to read.
tmp, err := os.CreateTemp("", "snapgo-bgo-*.png")
if err != nil {
return fmt.Errorf("ssh(bgo): create temp: %w", err)
}
tmpPath := tmp.Name()
defer os.Remove(tmpPath)
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return fmt.Errorf("ssh(bgo): write temp: %w", err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("ssh(bgo): close temp: %w", err)
}
if err := os.Chmod(tmpPath, mode.Perm()); err != nil {
sshLog().Debug("bgo uploader chmod temp failed", "err", err)
}
// 2. bgo scp <tmp> <user@host:name> under a PTY (via `script`).
remoteTarget := fmt.Sprintf("%s@%s:%s", u.cfg.User, bracketHost(u.cfg.Host), name)
bgoArgs := u.bgoScpArgs(bgoBin, tmpPath, remoteTarget)
if err := u.runUnderPTY(ctx, bgoArgs); err != nil {
sshLog().Error("bgo uploader scp failed",
"remote_file", name, "elapsed", time.Since(start), "err", err)
return err
}
sshLog().Info("bgo uploader done",
"remote_file", name, "size", len(data), "total_elapsed", time.Since(start))
return nil
}
// bgoScpArgs builds the argument vector "bgo scp [-P port] <src> <dst>".
// bgo manages its own auth, so we pass no ssh -o options here.
func (u *BgoUploader) bgoScpArgs(bgoBin, src, dst string) []string {
args := []string{bgoBin, "scp"}
if u.cfg.Port > 0 && u.cfg.Port != 22 {
args = append(args, "-P", strconv.Itoa(u.cfg.Port))
}
args = append(args, src, dst)
return args
}
// runUnderPTY runs the given command vector under a PTY allocated by the
// system `script` utility, capturing combined output for diagnostics.
//
// macOS BSD script signature: `script -q <typescript-file> command [args...]`.
// We discard the typescript by writing to /dev/null.
func (u *BgoUploader) runUnderPTY(ctx context.Context, cmdVec []string) error {
args := append([]string{"-q", "/dev/null"}, cmdVec...)
cmd := exec.CommandContext(ctx, systemScriptPath, args...)
var combined bytes.Buffer
cmd.Stdout = &combined
cmd.Stderr = &combined
sshLog().Debug("bgo exec", "args", strings.Join(args, " "))
if err := cmd.Run(); err != nil {
msg := strings.TrimSpace(combined.String())
if msg == "" {
msg = err.Error()
}
return fmt.Errorf("bgo scp failed: %s", msg)
}
return nil
}
// bracketHost wraps a bare IPv6 literal in [] so the "user@host:path" target
// parses correctly (e.g. fdbd:dc03:8:379::130 → [fdbd:dc03:8:379::130]).
// IPv4 addresses and hostnames are returned unchanged. Already-bracketed
// inputs are left as-is.
func bracketHost(host string) string {
host = strings.TrimSpace(host)
if host == "" {
return host
}
if strings.HasPrefix(host, "[") {
return host
}
// An IPv6 literal contains multiple ':' separators; a hostname:port style
// is not expected here because the port lives in cfg.Port.
if strings.Count(host, ":") >= 2 {
return "[" + host + "]"
}
return host
}
// TestBgoConnection verifies that the bgo binary is resolvable. A real
// transfer test is intentionally avoided: bgo requires a PTY and a live
// remote, and bgo ssh cannot run a harmless remote probe command (it panics).
// Confirming bgo is installed and on PATH is the most useful signal we can
// give without performing an actual upload.
func TestBgoConnection(ctx context.Context, cfg domain.SSHConfig) error {
sshLog().Info("bgo test connection start", "host", cfg.Host, "user", cfg.User)
bin, err := resolveBgoBinary()
if err != nil {
return err
}
sshLog().Info("bgo test connection ok", "bgo", bin)
return nil
}