native.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. // Package native controls a native WebView worker through private stdio pipes.
  2. package native
  3. import (
  4. "context"
  5. "encoding/json"
  6. "io"
  7. "os"
  8. "os/exec"
  9. "runtime"
  10. "sync"
  11. "time"
  12. "clusterflow.dev/cfbrowser/api"
  13. "clusterflow.dev/cfbrowser/internal/capture"
  14. "clusterflow.dev/cfbrowser/protocol"
  15. )
  16. type Driver struct {
  17. WorkerPath string
  18. Diagnostics io.Writer
  19. }
  20. func (*Driver) Probe(ctx context.Context) (api.Capabilities, error) {
  21. if err := ctx.Err(); err != nil {
  22. return api.Capabilities{}, err
  23. }
  24. features := map[string]api.Capability{}
  25. status := "unsupported"
  26. if nativeSupported() {
  27. status = "supported"
  28. }
  29. for _, n := range []string{"backgroundNavigation", "evalResult", "isolatedWorld", "domSnapshot", "openShadowDOM", "screenshotViewport"} {
  30. features[n] = api.Capability{Status: status, Reason: "native adapter implemented; worker startup verifies runtime availability"}
  31. }
  32. for _, n := range []string{"displayless", "trustedInput", "axSnapshot", "crossOriginFrames", "screenshotFullPage", "downloads", "fileUpload", "persistentProfile", "userHandoff", "proxy"} {
  33. features[n] = api.Capability{Status: "unsupported", Reason: "not implemented in native prototype"}
  34. }
  35. if runtime.GOOS == "windows" {
  36. features["trustedInput"] = api.Capability{Status: status, Reason: "WebView2 internal Input domain; select/check/scroll remain synthetic"}
  37. features["screenshotFullPage"] = api.Capability{Status: status, Reason: "bounded to 4096 x 4096 pixels and 4 MiB"}
  38. }
  39. features["syntheticInput"] = api.Capability{Status: status}
  40. features["networkPolicy"] = api.Capability{Status: "degraded", Reason: "top-level navigation validation only"}
  41. return api.Capabilities{Engine: nativeEngine(), Platform: runtime.GOOS + "/" + runtime.GOARCH, Features: features}, nil
  42. }
  43. type session struct {
  44. downloadDir string
  45. cmd *exec.Cmd
  46. stdin io.WriteCloser
  47. stdout io.ReadCloser
  48. client *protocol.Client
  49. done chan error
  50. once sync.Once
  51. }
  52. type enginePage struct {
  53. s *session
  54. id uint64
  55. once sync.Once
  56. }
  57. func (d *Driver) Open(ctx context.Context, o api.EngineOptions) (api.EngineSession, error) {
  58. if err := ctx.Err(); err != nil {
  59. return nil, err
  60. }
  61. if !nativeSupported() {
  62. return nil, api.Err("BROWSER_CAPABILITY_UNSUPPORTED", "native worker requires Linux or 64-bit Windows/macOS")
  63. }
  64. path, err := exec.LookPath(d.WorkerPath)
  65. if err != nil || d.WorkerPath == "" {
  66. return nil, api.Err("BROWSER_ENGINE_NOT_FOUND", "configure cfbrowser-worker path")
  67. }
  68. cmd := exec.Command(path)
  69. cmd.Stderr = d.Diagnostics
  70. configureCommand(cmd)
  71. if o.NoSandbox && runtime.GOOS == "linux" {
  72. cmd.Env = append(os.Environ(), "WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS=1")
  73. }
  74. stdin, err := cmd.StdinPipe()
  75. if err != nil {
  76. return nil, err
  77. }
  78. stdout, err := cmd.StdoutPipe()
  79. if err != nil {
  80. stdin.Close()
  81. return nil, err
  82. }
  83. if err = cmd.Start(); err != nil {
  84. stdin.Close()
  85. stdout.Close()
  86. return nil, err
  87. }
  88. s := &session{downloadDir: o.DownloadDir, cmd: cmd, stdin: stdin, stdout: stdout, done: make(chan error, 1)}
  89. s.client = protocol.NewClient(stdout, stdin)
  90. go func() { s.done <- cmd.Wait() }()
  91. var ok bool
  92. if err = s.client.Call(ctx, "configure", o, &ok); err != nil {
  93. _ = s.Close()
  94. return nil, err
  95. }
  96. if !ok {
  97. _ = s.Close()
  98. return nil, api.Err("BROWSER_RUNTIME_UNAVAILABLE", "worker rejected engine configuration")
  99. }
  100. var features struct {
  101. Version int `json:"featureVersion"`
  102. }
  103. err = s.client.Call(ctx, "session.features", nil, &features)
  104. if err != nil || features.Version != protocol.FeatureVersion {
  105. _ = s.Close()
  106. if ctx.Err() != nil {
  107. return nil, ctx.Err()
  108. }
  109. return nil, api.Err("BROWSER_WORKER_OUTDATED", "rebuild and package the native worker from the same cfbrowser source as the SDK")
  110. }
  111. return s, nil
  112. }
  113. func (s *session) NewPage(ctx context.Context) (api.EnginePage, error) {
  114. var id uint64
  115. err := s.client.Call(ctx, "page.new", nil, &id)
  116. if err != nil {
  117. return nil, err
  118. }
  119. return &enginePage{s: s, id: id}, nil
  120. }
  121. func (s *session) Downloads() []api.Download { return []api.Download{} }
  122. func (s *session) Close() error {
  123. s.once.Do(func() {
  124. s.stdin.Close()
  125. s.client.Close()
  126. select {
  127. case <-s.done:
  128. case <-time.After(2 * time.Second):
  129. _ = s.cmd.Process.Kill()
  130. <-s.done
  131. }
  132. s.stdout.Close()
  133. })
  134. return nil
  135. }
  136. func (p *enginePage) Navigate(ctx context.Context, url, op string) (string, error) {
  137. var out string
  138. err := p.s.client.Call(ctx, "page.navigate", map[string]any{"page": p.id, "url": url, "op": op}, &out)
  139. return out, err
  140. }
  141. func (p *enginePage) Evaluate(ctx context.Context, script string) (json.RawMessage, error) {
  142. var out json.RawMessage
  143. err := p.s.client.Call(ctx, "page.evaluate", map[string]any{"page": p.id, "script": script}, &out)
  144. return out, err
  145. }
  146. func (p *enginePage) Input(ctx context.Context, action, value string, x, y float64) error {
  147. return p.s.client.Call(ctx, "page.input", map[string]any{"page": p.id, "action": action, "value": value, "x": x, "y": y}, nil)
  148. }
  149. func (p *enginePage) Capture(ctx context.Context) ([]byte, error) { return p.capture(ctx, false) }
  150. func (p *enginePage) CaptureFullPage(ctx context.Context) ([]byte, error) {
  151. return p.capture(ctx, true)
  152. }
  153. func (p *enginePage) capture(ctx context.Context, full bool) ([]byte, error) {
  154. var name string
  155. if err := p.s.client.Call(ctx, "page.capture", map[string]any{"page": p.id, "fullPage": full}, &name); err != nil {
  156. return nil, err
  157. }
  158. return capture.Load(p.s.downloadDir, name)
  159. }
  160. func (p *enginePage) Close() error {
  161. var err error
  162. p.once.Do(func() {
  163. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  164. defer cancel()
  165. err = p.s.client.Call(ctx, "page.close", map[string]any{"page": p.id}, nil)
  166. })
  167. return err
  168. }
  169. func nativeSupported() bool {
  170. return runtime.GOOS == "linux" || (runtime.GOOS == "windows" || runtime.GOOS == "darwin") && (runtime.GOARCH == "amd64" || runtime.GOARCH == "arm64")
  171. }
  172. func nativeEngine() string {
  173. switch runtime.GOOS {
  174. case "windows":
  175. return "native-webview2"
  176. case "darwin":
  177. return "native-wkwebview"
  178. case "linux":
  179. return "native-webkitgtk"
  180. }
  181. return "native-unsupported"
  182. }