feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 MyGo contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+36
View File
@@ -0,0 +1,36 @@
# @mygo-plugins/websocket
A `WebSocket` for [MyGo](https://github.com/egoist/mygo) apps whose
connections Go makes, with the API of the browser's. Unlike the browser's,
it may send any header with the opening handshake, such as Authorization,
Cookie or Origin, and is not subject to the page's Content Security Policy.
Use the plugin in Go:
```go
import "github.com/egoist/mygo/plugins/websocket"
mygo.Use(websocket.Plugin) // or websocket.New(websocket.Options{...})
```
and connect in the frontend:
```ts
import { WebSocket } from "@mygo-plugins/websocket";
const ws = new WebSocket("wss://example.com/live", ["v1"], {
headers: { authorization: `Bearer ${token}` },
});
ws.onopen = () => ws.send("hello");
ws.onmessage = (e) => console.log(e.data);
ws.onclose = (e) => console.log(e.code, e.reason, e.wasClean);
```
Messages are sent in order, `bufferedAmount` counts the bytes Go has not
written yet, and received messages wait in Go while the page is behind, so a
fast server cannot fill the page's memory. Connections close (1001, going
away) when their page navigates away or its window closes. No extensions
(such as permessage-deflate) are negotiated.
[The documentation](https://github.com/egoist/mygo/blob/main/docs/plugins/websocket.md)
covers closing, failures and the options of the Go side.
+407
View File
@@ -0,0 +1,407 @@
package websocket
import (
"bufio"
"context"
"crypto/rand"
"crypto/sha1"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"slices"
"strings"
"sync"
"time"
"unicode/utf8"
)
// Opcodes (RFC 6455, section 5.2).
const (
opContinuation = 0x0
opText = 0x1
opBinary = 0x2
opClose = 0x8
opPing = 0x9
opPong = 0xa
)
// Close codes (RFC 6455, section 7.4.1).
const (
closeNormal = 1000
closeGoingAway = 1001
closeProtocolError = 1002
closeNoStatus = 1005
closeAbnormal = 1006
closeInvalidData = 1007
closeTooBig = 1009
)
// failure fails the connection with a close code (RFC 6455, section 7.1.7).
type failure struct {
code int
msg string
}
func (f *failure) Error() string { return f.msg }
func protocolError(format string, args ...any) error {
return &failure{closeProtocolError, fmt.Sprintf(format, args...)}
}
var errClosed = errors.New("websocket: connection closed")
// conn is a WebSocket connection, of a client unless server is set (tests).
type conn struct {
rwc io.ReadWriteCloser
br *bufio.Reader
server bool
max int64 // the most bytes a message may have
wmu sync.Mutex // writes
closeSent bool
// Messages the page sends are written in the order it sent them: next
// is the sequence number of the next one.
mu sync.Mutex
cond sync.Cond
next int64
done bool
once sync.Once
}
func newConn(rwc io.ReadWriteCloser, br *bufio.Reader, server bool, max int64) *conn {
if br == nil {
br = bufio.NewReader(rwc)
}
c := &conn{rwc: rwc, br: br, server: server, max: max, next: 1}
c.cond.L = &c.mu
return c
}
// acceptKey is the Sec-WebSocket-Accept of key.
func acceptKey(key string) string {
h := sha1.Sum([]byte(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))
return base64.StdEncoding.EncodeToString(h[:])
}
// dial opens a connection with the opening handshake, sent by client.
// It returns the connection and the subprotocol the server chose.
func dial(ctx context.Context, client *http.Client, rawURL string, protocols []string, headers [][2]string, allow func(*http.Request) bool, max int64) (*conn, string, error) {
u, err := url.Parse(rawURL)
if err != nil {
return nil, "", err
}
switch u.Scheme {
case "ws":
u.Scheme = "http"
case "wss":
u.Scheme = "https"
case "http", "https":
default:
return nil, "", fmt.Errorf("unsupported URL scheme %q", u.Scheme)
}
u.Fragment = ""
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return nil, "", err
}
for _, h := range headers {
if http.CanonicalHeaderKey(h[0]) == "Host" {
req.Host = h[1]
} else {
req.Header.Add(h[0], h[1])
}
}
var nonce [16]byte
rand.Read(nonce[:])
key := base64.StdEncoding.EncodeToString(nonce[:])
req.Header.Set("Upgrade", "websocket")
req.Header.Set("Connection", "Upgrade")
req.Header.Set("Sec-WebSocket-Key", key)
req.Header.Set("Sec-WebSocket-Version", "13")
req.Header.Del("Sec-WebSocket-Extensions")
if len(protocols) > 0 {
req.Header.Set("Sec-WebSocket-Protocol", strings.Join(protocols, ", "))
} else {
req.Header.Del("Sec-WebSocket-Protocol")
}
if allow != nil && !allow(req) {
return nil, "", fmt.Errorf("the app does not allow connections to %s", u.Redacted())
}
// The connection outlives the request: no timeout, and like browsers,
// no redirects.
c := *client
c.Timeout = 0
c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
res, err := c.Do(req)
if err != nil {
return nil, "", err
}
fail := func(format string, args ...any) (*conn, string, error) {
res.Body.Close()
return nil, "", fmt.Errorf(format, args...)
}
if res.StatusCode != http.StatusSwitchingProtocols {
return fail("the server answered the handshake with %s", res.Status)
}
if !strings.EqualFold(res.Header.Get("Upgrade"), "websocket") || !hasToken(res.Header.Get("Connection"), "upgrade") {
return fail("the server did not upgrade the connection to WebSocket")
}
if res.Header.Get("Sec-WebSocket-Accept") != acceptKey(key) {
return fail("the server answered with a wrong Sec-WebSocket-Accept")
}
protocol := res.Header.Get("Sec-WebSocket-Protocol")
if len(protocols) > 0 && protocol == "" {
return fail("the server did not select a requested subprotocol")
}
if protocol != "" && !slices.Contains(protocols, protocol) {
return fail("the server chose subprotocol %q, which was not requested", protocol)
}
if res.Header.Get("Sec-WebSocket-Extensions") != "" {
return fail("the server chose extensions, which were not requested")
}
rwc, ok := res.Body.(io.ReadWriteCloser)
if !ok {
return fail("the HTTP client cannot upgrade connections")
}
return newConn(rwc, nil, false, max), protocol, nil
}
func hasToken(header, token string) bool {
for t := range strings.SplitSeq(header, ",") {
if strings.EqualFold(strings.TrimSpace(t), token) {
return true
}
}
return false
}
// readFrame reads a frame.
func (c *conn) readFrame() (fin bool, op byte, payload []byte, err error) {
var h [8]byte
if _, err := io.ReadFull(c.br, h[:2]); err != nil {
return false, 0, nil, err
}
fin, op = h[0]&0x80 != 0, h[0]&0x0f
if h[0]&0x70 != 0 {
return false, 0, nil, protocolError("reserved bits set in a frame")
}
if masked := h[1]&0x80 != 0; masked != c.server {
return false, 0, nil, protocolError("wrong frame masking")
}
n := uint64(h[1] & 0x7f)
switch n {
case 126:
if _, err := io.ReadFull(c.br, h[:2]); err != nil {
return false, 0, nil, err
}
n = uint64(binary.BigEndian.Uint16(h[:2]))
case 127:
if _, err := io.ReadFull(c.br, h[:8]); err != nil {
return false, 0, nil, err
}
n = binary.BigEndian.Uint64(h[:8])
if n>>63 != 0 {
return false, 0, nil, protocolError("invalid frame length")
}
}
if op >= opClose && (!fin || n > 125) {
return false, 0, nil, protocolError("invalid control frame")
}
if n > uint64(c.max) {
return false, 0, nil, &failure{closeTooBig, fmt.Sprintf("message over %d bytes", c.max)}
}
var mask [4]byte
if c.server {
if _, err := io.ReadFull(c.br, mask[:]); err != nil {
return false, 0, nil, err
}
}
payload = make([]byte, n)
if _, err := io.ReadFull(c.br, payload); err != nil {
return false, 0, nil, err
}
if c.server {
for i := range payload {
payload[i] ^= mask[i%4]
}
}
return fin, op, payload, nil
}
// readMessage reads a text, binary or close message, answering pings.
func (c *conn) readMessage() (op byte, data []byte, err error) {
var msgOp byte
for {
fin, op, p, err := c.readFrame()
if err != nil {
return 0, nil, err
}
switch op {
case opPing:
if err := c.writeFrame(opPong, p); err != nil && err != errClosed {
return 0, nil, err
}
continue
case opPong:
continue
case opClose:
return opClose, p, nil
case opContinuation:
if msgOp == 0 {
return 0, nil, protocolError("unexpected continuation frame")
}
case opText, opBinary:
if msgOp != 0 {
return 0, nil, protocolError("new message before the last one ended")
}
msgOp = op
default:
return 0, nil, protocolError("unknown opcode %d", op)
}
if int64(len(data)+len(p)) > c.max {
return 0, nil, &failure{closeTooBig, fmt.Sprintf("message over %d bytes", c.max)}
}
data = append(data, p...)
if fin {
if msgOp == opText && !utf8.Valid(data) {
return 0, nil, &failure{closeInvalidData, "text message is not valid UTF-8"}
}
if data == nil {
data = []byte{}
}
return msgOp, data, nil
}
}
}
// writeFrame writes a whole message in one frame. Nothing is written after
// a close frame.
func (c *conn) writeFrame(op byte, p []byte) error {
c.wmu.Lock()
defer c.wmu.Unlock()
if c.closeSent {
return errClosed
}
if op == opClose {
c.closeSent = true
}
b := make([]byte, 0, 14+len(p))
b = append(b, 0x80|op)
var maskBit byte
if !c.server {
maskBit = 0x80
}
switch n := len(p); {
case n <= 125:
b = append(b, maskBit|byte(n))
case n <= 0xffff:
b = append(b, maskBit|126)
b = binary.BigEndian.AppendUint16(b, uint16(n))
default:
b = append(b, maskBit|127)
b = binary.BigEndian.AppendUint64(b, uint64(n))
}
if c.server {
b = append(b, p...)
} else {
var mask [4]byte
rand.Read(mask[:])
b = append(b, mask[:]...)
for i, x := range p {
b = append(b, x^mask[i%4])
}
}
_, err := c.rwc.Write(b)
return err
}
// writeClose sends a close frame, unless one was sent. A code of
// closeNoStatus sends none.
func (c *conn) writeClose(code int, reason string) error {
var p []byte
if code != closeNoStatus {
p = binary.BigEndian.AppendUint16(nil, uint16(code))
p = append(p, reason...)
}
return c.writeFrame(opClose, p)
}
// closing reports whether a close frame was sent.
func (c *conn) closing() bool {
c.wmu.Lock()
defer c.wmu.Unlock()
return c.closeSent
}
// parseClose returns the code and reason of a close frame's payload.
func parseClose(p []byte) (int, string, error) {
if len(p) == 0 {
return closeNoStatus, "", nil
}
if len(p) == 1 {
return 0, "", protocolError("invalid close frame")
}
code := int(binary.BigEndian.Uint16(p))
if !validCloseCode(code) {
return 0, "", protocolError("invalid close code %d", code)
}
if !utf8.Valid(p[2:]) {
return 0, "", &failure{closeInvalidData, "close reason is not valid UTF-8"}
}
return code, string(p[2:]), nil
}
// validCloseCode reports whether code may be sent in a close frame.
func validCloseCode(code int) bool {
switch {
case code >= 1000 && code <= 1003, code >= 1007 && code <= 1014:
return true
default:
return code >= 3000 && code <= 4999
}
}
// inTurn runs fn once the messages sent before the seq-th are written.
func (c *conn) inTurn(seq int64, fn func() error) error {
c.mu.Lock()
for c.next != seq && !c.done {
c.cond.Wait()
}
if c.done {
c.mu.Unlock()
return errClosed
}
c.mu.Unlock()
err := fn()
c.mu.Lock()
c.next++
c.mu.Unlock()
c.cond.Broadcast()
return err
}
// close starts the closing handshake: the connection is dropped if the
// server does not finish it in time.
func (c *conn) close(code int, reason string, timeout time.Duration) error {
err := c.writeClose(code, reason)
time.AfterFunc(timeout, c.terminate)
return err
}
// terminate drops the connection.
func (c *conn) terminate() {
c.once.Do(func() {
c.rwc.Close()
c.mu.Lock()
c.done = true
c.mu.Unlock()
c.cond.Broadcast()
})
}
+44
View File
@@ -0,0 +1,44 @@
package websocket
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestHandshakeRequiresRequestedSubprotocol(t *testing.T) {
for _, tc := range []struct {
name, header string
protocols []string
wantOpen bool
}{
{"missing", "", []string{"chat"}, false},
{"empty", "Sec-WebSocket-Protocol: \r\n", []string{"chat"}, false},
{"selected", "Sec-WebSocket-Protocol: chat\r\n", []string{"chat", "v2"}, true},
{"not requested", "", nil, true},
} {
t.Run(tc.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
nc, rw, err := http.NewResponseController(w).Hijack()
if err != nil {
t.Error(err)
return
}
defer nc.Close()
rw.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " + acceptKey(r.Header.Get("Sec-WebSocket-Key")) + "\r\n" + tc.header + "\r\n")
rw.Flush()
}))
defer srv.Close()
s := New(Options{}).Service.(*service)
events, _ := open(t, s, connectOptions{ID: "test", URL: srv.URL, Protocols: tc.protocols})
ev := next(t, events)
if tc.wantOpen {
if ev.Type != "open" {
t.Fatalf("handshake: %+v", ev)
}
} else if ev.Type != "close" || ev.Code != 1006 || ev.Clean || ev.Error == "" {
t.Fatalf("unacknowledged subprotocol should fail the handshake: %+v", ev)
}
})
}
}
+41
View File
@@ -0,0 +1,41 @@
{
"name": "@mygo-plugins/websocket",
"version": "0.10.0",
"description": "A WebSocket whose connections Go makes, for MyGo desktop apps",
"keywords": [
"mygo",
"desktop",
"webview",
"go",
"websocket"
],
"repository": {
"type": "git",
"url": "git+https://github.com/egoist/mygo.git",
"directory": "plugins/websocket"
},
"license": "MIT",
"type": "module",
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"types": "./dist/index.d.ts",
"files": [
"dist",
"README.md"
],
"scripts": {
"build": "bun run ../build.ts",
"test": "bun test"
},
"peerDependencies": {
"mygo-runtime": "^0.10.0"
},
"devDependencies": {
"mygo-runtime": "^0.10.0"
}
}
+164
View File
@@ -0,0 +1,164 @@
import { afterEach, expect, test } from "bun:test";
import { b64, fakeGo, tick, type GoCall } from "../../fake-go";
import { WebSocket } from "./index";
let go: ReturnType<typeof fakeGo> | undefined;
afterEach(() => go?.uninstall());
/** A server that echoes, as the Go side streams it. */
function echoServer() {
const sent: unknown[][] = [];
let conn: GoCall | undefined;
let finish: (() => void) | undefined;
go = fakeGo({
"plugin:websocket.Connect": (c) =>
new Promise<void>((resolve) => {
conn = c;
finish = resolve;
c.signal.addEventListener("abort", () => resolve());
c.send(1, { type: "open", protocol: "chat" });
}),
"plugin:websocket.Send": (c) => {
sent.push(c.args);
const m = c.args[2] as { type: string; text?: string; data?: string; code?: number };
if (m.type === "close") {
conn!.send(1, { type: "close", code: m.code, reason: "bye", clean: true });
finish!();
} else conn!.send(1, m.type === "text" ? { type: "text", text: m.text } : { type: "binary", data: m.data });
},
});
return { sent, server: () => conn! };
}
const next = (ws: WebSocket, type: string) => new Promise<any>((r) => ws.addEventListener(type, r, { once: true }));
test("opens, echoes and closes", async () => {
const { sent } = echoServer();
const ws = new WebSocket("https://example.com/live", ["chat"], { headers: { authorization: "Bearer t" } });
expect(ws.url).toBe("wss://example.com/live");
expect(ws.readyState).toBe(WebSocket.CONNECTING);
expect(() => ws.send("early")).toThrow("not open");
await next(ws, "open");
expect(ws.readyState).toBe(ws.OPEN);
expect(ws.protocol).toBe("chat");
const [connect] = go!.calls[0]![1] as [{ id: string; headers: [string, string][] }];
expect(connect.headers).toEqual([["authorization", "Bearer t"]]);
const got: unknown[] = [];
ws.onmessage = (e) => got.push(e.data);
ws.send("hello");
expect(ws.bufferedAmount).toBe(5);
ws.binaryType = "arraybuffer";
ws.send(new Uint8Array([1, 2, 3]));
while (got.length < 2 || ws.bufferedAmount > 0) await tick();
expect(got[0]).toBe("hello");
expect([...new Uint8Array(got[1] as ArrayBuffer)]).toEqual([1, 2, 3]);
// Messages carry their order.
expect(sent.map((s) => s[1])).toEqual([1, 2]);
expect(sent[0]![0]).toBe(connect.id);
const closed = next(ws, "close");
let errored = false;
ws.onerror = () => (errored = true);
ws.close(4001, "done");
expect(ws.readyState).toBe(WebSocket.CLOSING);
const e = await closed;
expect([e.code, e.reason, e.wasClean]).toEqual([4001, "bye", true]);
expect(ws.readyState).toBe(WebSocket.CLOSED);
expect(errored).toBe(false);
expect(sent[2]![2]).toEqual({ type: "close", code: 4001, reason: "done" });
});
test("receives blobs", async () => {
const { server } = echoServer();
const ws = new WebSocket("ws://example.com");
await next(ws, "open");
const msg = next(ws, "message");
server().send(1, { type: "binary", data: b64("blob") });
const e = await msg;
expect(e.data).toBeInstanceOf(Blob);
expect(await e.data.text()).toBe("blob");
});
test("fails", async () => {
go = fakeGo({
"plugin:websocket.Connect": (c) => c.send(1, { type: "close", code: 1006, error: "the server answered the handshake with 403 Forbidden" }),
});
const errors: string[] = [];
const log = console.error;
console.error = (m: string) => errors.push(m);
try {
const ws = new WebSocket("ws://example.com");
const order: string[] = [];
ws.onerror = () => order.push("error");
ws.onclose = (e) => order.push(`close ${e.code} ${e.wasClean}`);
await next(ws, "close");
expect(order).toEqual(["error", "close 1006 false"]);
expect(errors[0]).toContain("403 Forbidden");
} finally {
console.error = log;
}
});
test("closing while connecting stops the handshake", async () => {
let stopped = false;
go = fakeGo({
"plugin:websocket.Connect": (c) =>
new Promise<void>((r) =>
c.signal.addEventListener("abort", () => {
stopped = true;
r();
}),
),
});
const log = console.error;
console.error = () => {};
try {
const ws = new WebSocket("ws://example.com");
await tick();
ws.close();
const e = await next(ws, "close");
expect(e.code).toBe(1006);
expect(stopped).toBe(true);
} finally {
console.error = log;
}
});
test("validates", () => {
go = fakeGo({});
expect(() => new WebSocket("ftp://example.com")).toThrow("scheme");
expect(() => new WebSocket("ws://example.com/#x")).toThrow("fragment");
expect(() => new WebSocket("ws://example.com", ["a", "a"])).toThrow("duplicates");
const ws = new WebSocket("ws://example.com");
expect(() => ws.close(1001)).toThrow("Invalid close code");
expect(() => ws.close(1000, "x".repeat(124))).toThrow("123 bytes");
});
test("rejects invalid subprotocols before contacting Go", () => {
go = fakeGo({});
for (const protocol of ["", "chat room", "chat,other", "chat/1", "chat;v=1", "chat\n", "\tchat", "chát", "chat\u007f"]) {
for (const protocols of [protocol, ["valid", protocol]]) {
let thrown: unknown;
try {
new WebSocket("ws://example.com", protocols);
} catch (error) {
thrown = error;
}
expect(thrown).toBeInstanceOf(DOMException);
expect(thrown).toHaveProperty("name", "SyntaxError");
}
}
expect(go.calls).toHaveLength(0);
});
test("accepts HTTP token punctuation in subprotocols", async () => {
const { server } = echoServer();
const protocols = ["chat.v2", "!#$%&'*+-.^_`|~0123456789AZaz"];
const ws = new WebSocket("ws://example.com", protocols);
await next(ws, "open");
expect((server().args[0] as { protocols: string[] }).protocols).toEqual(protocols);
const closed = next(ws, "close");
ws.close();
await closed;
});
+338
View File
@@ -0,0 +1,338 @@
/**
* The WebSocket plugin of MyGo: a `WebSocket` whose connection Go makes,
* with the API of the browser's. Unlike the browser's, it may send any
* header with the opening handshake, such as Authorization or Cookie, and
* is not subject to the page's Content Security Policy. The Go side must
* use the plugin:
*
* ```go
* mygo.Use(websocket.Plugin) // github.com/egoist/mygo/plugins/websocket
* ```
*
* ```ts
* import { WebSocket } from "@mygo-plugins/websocket";
*
* const ws = new WebSocket("wss://example.com/live", [], {
* headers: { authorization: `Bearer ${token}` },
* });
* ws.onmessage = (e) => console.log(e.data);
* ```
*
* @module
*/
import { Channel, call, isCallError } from "mygo-runtime";
/** Options of a {@link WebSocket}, beyond the browser's. */
export interface WebSocketOptions {
/** Headers of the opening handshake, e.g. Authorization or Origin. */
headers?: HeadersInit;
}
/** What happens to the connection, from Go. */
interface GoEvent {
type: "open" | "text" | "binary" | "close";
protocol?: string;
text?: string;
/** Base64. */
data?: string;
code?: number;
reason?: string;
clean?: boolean;
error?: string;
}
/** A message for Go. */
type GoMessage =
| { type: "text"; text: string }
| { type: "binary"; data: string }
| { type: "close"; code: number; reason: string }
| { type: "skip" };
export interface WebSocketEventMap {
open: Event;
message: MessageEvent;
error: Event;
close: CloseEvent;
}
type Handler<E> = ((this: WebSocket, ev: E) => unknown) | null;
const CONNECTING = 0;
const OPEN = 1;
const CLOSING = 2;
const CLOSED = 3;
const encoder = new TextEncoder();
/**
* A WebSocket connection made by Go, with the API of the browser's
* `WebSocket`. The third argument sets headers of the opening handshake.
*/
export class WebSocket extends EventTarget {
static readonly CONNECTING = CONNECTING;
static readonly OPEN = OPEN;
static readonly CLOSING = CLOSING;
static readonly CLOSED = CLOSED;
declare readonly CONNECTING: 0;
declare readonly OPEN: 1;
declare readonly CLOSING: 2;
declare readonly CLOSED: 3;
/** The URL of the connection, with a ws: or wss: scheme. */
readonly url: string;
/** How binary messages arrive: as a `Blob`, or an `ArrayBuffer`. */
binaryType: BinaryType = "blob";
#id: string;
#state: number = CONNECTING;
#protocol = "";
#buffered = 0;
#seq = 0;
/** Why the connection failed, when the page failed it. */
#failed: string | undefined;
#events: Channel<GoEvent>;
#handlers = new Map<string, { fn: Handler<any> }>();
constructor(url: string | URL, protocols: string | string[] = [], options: WebSocketOptions = {}) {
super();
const base = typeof location !== "undefined" ? location.href : undefined;
let u: URL;
try {
u = new URL(url, base);
} catch {
throw new DOMException(`Invalid URL: ${url}`, "SyntaxError");
}
if (u.protocol === "http:") u.protocol = "ws:";
else if (u.protocol === "https:") u.protocol = "wss:";
if (u.protocol !== "ws:" && u.protocol !== "wss:") {
throw new DOMException(`The URL's scheme must be ws or wss, not ${u.protocol.slice(0, -1)}`, "SyntaxError");
}
if (u.hash) throw new DOMException("The URL contains a fragment", "SyntaxError");
const list = typeof protocols === "string" ? [protocols] : [...protocols];
if (new Set(list).size !== list.length) {
throw new DOMException("The subprotocols contain duplicates", "SyntaxError");
}
for (const protocol of list) {
// RFC 6455 subprotocols are nonempty HTTP tokens.
if (!protocol || /[^!#$%&'*+\-.^_`|~0-9A-Za-z]/.test(protocol)) {
throw new DOMException(`Invalid subprotocol: ${protocol}`, "SyntaxError");
}
}
this.url = u.href;
this.#id = globalThis.crypto?.randomUUID?.() ?? Math.random().toString(36).slice(2) + Date.now().toString(36);
this.#events = new Channel<GoEvent>((e) => this.#receive(e));
call("plugin:websocket.Connect", {
id: this.#id,
url: this.url,
protocols: list,
headers: [...new Headers(options.headers)],
}, this.#events).then(
() => this.#finish(1006, "", false, this.#failed ?? "connection lost"),
(err: unknown) => this.#finish(1006, "", false, this.#failed ?? failure(err)),
);
}
/** The state of the connection: CONNECTING, OPEN, CLOSING or CLOSED. */
get readyState(): number {
return this.#state;
}
/** The subprotocol the server chose, once open. */
get protocol(): string {
return this.#protocol;
}
/** The extensions in use: none. */
get extensions(): string {
return "";
}
/** Bytes sent with `send` that Go has not written yet. */
get bufferedAmount(): number {
return this.#buffered;
}
get onopen(): Handler<Event> {
return this.#handler("open");
}
set onopen(fn: Handler<Event>) {
this.#setHandler("open", fn);
}
get onmessage(): Handler<MessageEvent> {
return this.#handler("message");
}
set onmessage(fn: Handler<MessageEvent>) {
this.#setHandler("message", fn);
}
get onerror(): Handler<Event> {
return this.#handler("error");
}
set onerror(fn: Handler<Event>) {
this.#setHandler("error", fn);
}
get onclose(): Handler<CloseEvent> {
return this.#handler("close");
}
set onclose(fn: Handler<CloseEvent>) {
this.#setHandler("close", fn);
}
/** Sends a message: text, or binary data. Throws while connecting. */
send(data: string | ArrayBufferLike | ArrayBufferView | Blob): void {
if (this.#state === CONNECTING) throw new DOMException("The connection is not open yet", "InvalidStateError");
let size: number;
let message: GoMessage | Promise<GoMessage>;
if (typeof data === "string") {
const bytes = encoder.encode(data);
size = bytes.length;
message = { type: "text", text: data };
} else if (typeof Blob !== "undefined" && data instanceof Blob) {
size = data.size;
message = data.arrayBuffer().then(
(b): GoMessage => ({ type: "binary", data: toBase64(new Uint8Array(b)) }),
(): GoMessage => ({ type: "skip" }),
);
} else {
const bytes = ArrayBuffer.isView(data)
? new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
: new Uint8Array(data as ArrayBufferLike);
size = bytes.length;
message = { type: "binary", data: toBase64(bytes) };
}
this.#buffered += size;
if (this.#state !== OPEN) return; // discarded, as browsers do
const settle = () => (this.#buffered -= size);
this.#send(message).then(settle, settle);
}
/**
* Closes the connection with a code (1000, or 3000 to 4999) and a reason
* of at most 123 bytes.
*/
close(code?: number, reason?: string): void {
if (code !== undefined && code !== 1000 && !(code >= 3000 && code <= 4999)) {
throw new DOMException(`Invalid close code ${code}`, "InvalidAccessError");
}
const why = reason ?? "";
if (encoder.encode(why).length > 123) throw new DOMException("The close reason is over 123 bytes", "SyntaxError");
if (this.#state === CLOSING || this.#state === CLOSED) return;
if (this.#state === CONNECTING) {
this.#state = CLOSING;
this.#failed = "closed before the connection was established";
this.#events.close(); // stops the handshake
setTimeout(() => this.#finish(1006, "", false, this.#failed));
return;
}
this.#state = CLOSING;
this.#send({ type: "close", code: code ?? (why ? 1000 : 1005), reason: why }).catch(() => {});
}
#send(message: GoMessage | Promise<GoMessage>): Promise<void> {
const seq = ++this.#seq;
return Promise.resolve(message).then((m) => call<void>("plugin:websocket.Send", this.#id, seq, m));
}
#receive(e: GoEvent): void {
switch (e.type) {
case "open":
if (this.#state !== CONNECTING) return;
this.#state = OPEN;
this.#protocol = e.protocol ?? "";
this.dispatchEvent(new Event("open"));
return;
case "text":
case "binary": {
if (this.#state !== OPEN) return;
let data: unknown = e.text ?? "";
if (e.type === "binary") {
const bytes = fromBase64(e.data ?? "");
data = this.binaryType === "arraybuffer" ? bytes.buffer : new Blob([bytes as Uint8Array<ArrayBuffer>]);
}
this.dispatchEvent(new MessageEvent("message", { data, origin: new URL(this.url).origin }));
return;
}
case "close":
this.#finish(e.code ?? 1005, e.reason ?? "", e.clean ?? false, e.error);
}
}
#finish(code: number, reason: string, wasClean: boolean, error?: string): void {
if (this.#state === CLOSED) return;
this.#state = CLOSED;
this.#events.close();
if (error) {
console.error(`WebSocket connection to '${this.url}' failed: ${error}`);
this.dispatchEvent(new Event("error"));
}
this.dispatchEvent(closeEvent(code, reason, wasClean));
}
#handler(type: string): Handler<any> {
return this.#handlers.get(type)?.fn ?? null;
}
// An event handler is a listener added when it is first set, which calls
// whatever handler is set when the event fires.
#setHandler(type: string, fn: Handler<any>): void {
let entry = this.#handlers.get(type);
if (!entry) {
const e = (entry = { fn: null as Handler<any> });
this.#handlers.set(type, e);
this.addEventListener(type, (ev) => e.fn?.call(this, ev));
}
entry.fn = typeof fn === "function" ? fn : null;
}
}
for (const [name, value] of Object.entries({ CONNECTING, OPEN, CLOSING, CLOSED })) {
Object.defineProperty(WebSocket.prototype, name, { value, enumerable: true });
}
export interface WebSocket {
addEventListener<K extends keyof WebSocketEventMap>(
type: K,
listener: (this: WebSocket, ev: WebSocketEventMap[K]) => unknown,
options?: boolean | AddEventListenerOptions,
): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void;
removeEventListener<K extends keyof WebSocketEventMap>(
type: K,
listener: (this: WebSocket, ev: WebSocketEventMap[K]) => unknown,
options?: boolean | EventListenerOptions,
): void;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions): void;
}
export default WebSocket;
function closeEvent(code: number, reason: string, wasClean: boolean): CloseEvent {
if (typeof CloseEvent !== "undefined") return new CloseEvent("close", { code, reason, wasClean });
return Object.assign(new Event("close"), { code, reason, wasClean }) as CloseEvent;
}
/** Why the connection failed. */
function failure(err: unknown): string {
if (isCallError(err) && err.message.includes("plugin is not used")) {
return "the Go side does not use @mygo-plugins/websocket: call mygo.Use(websocket.Plugin) before App.Run";
}
return err instanceof Error ? err.message : String(err);
}
function toBase64(bytes: Uint8Array): string {
const native = (bytes as { toBase64?: () => string }).toBase64;
if (native) return native.call(bytes);
let s = "";
for (let i = 0; i < bytes.length; i += 0x8000) {
s += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000) as unknown as number[]);
}
return btoa(s);
}
function fromBase64(s: string): Uint8Array {
const native = (Uint8Array as { fromBase64?: (s: string) => Uint8Array }).fromBase64;
if (native) return native(s);
const bin = atob(s);
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return bytes;
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": { "outDir": "dist", "rootDir": "src" },
"include": ["src"],
"exclude": ["src/**/*.test.ts"]
}
+221
View File
@@ -0,0 +1,221 @@
// Package websocket is the WebSocket plugin of MyGo: pages open WebSocket
// connections from Go with the WebSocket class of its JavaScript package,
// @mygo-plugins/websocket, which has the API of the browser's. Unlike the
// browser's, it may send any header with the opening handshake, such as
// Authorization or Cookie, and is not subject to the page's Content
// Security Policy.
//
// mygo.Use(websocket.Plugin)
//
// and in the frontend:
//
// import { WebSocket } from "@mygo-plugins/websocket";
//
// const ws = new WebSocket("wss://example.com/live", [], {
// headers: { authorization: `Bearer ${token}` },
// });
// ws.onmessage = (e) => console.log(e.data);
//
// Connections close when their page navigates away or its window closes.
package websocket
import (
"context"
"errors"
"fmt"
"net/http"
"sync"
"time"
"github.com/egoist/mygo"
"github.com/egoist/mygo/netproxy"
)
// Options configure the plugin.
type Options struct {
// Client makes the opening handshakes; nil means a client of
// netproxy.Transport(), which follows the system's proxy settings.
// Its Timeout and CheckRedirect are ignored: connections last, and
// redirects fail them, as in browsers.
Client *http.Client
// Allow, when not nil, decides whether pages may open a connection
// with the handshake request; a connection it refuses fails.
Allow func(r *http.Request) bool
// MaxMessageSize is the most bytes a received message may have, 64 MiB
// when zero. A bigger message fails the connection.
MaxMessageSize int64
// CloseTimeout is how long a connection closed by the page waits for
// the server to finish the closing handshake, 5 seconds when zero.
CloseTimeout time.Duration
}
// Plugin is the plugin with the default options.
var Plugin = New(Options{})
// New returns the plugin with options.
func New(opts Options) mygo.Plugin {
if opts.Client == nil {
opts.Client = &http.Client{Transport: netproxy.Transport()}
}
if opts.MaxMessageSize <= 0 {
opts.MaxMessageSize = 64 << 20
}
if opts.CloseTimeout <= 0 {
opts.CloseTimeout = 5 * time.Second
}
return mygo.Plugin{Name: "websocket", Service: &service{opts: opts, conns: map[key]*conn{}}}
}
type service struct {
opts Options
mu sync.Mutex
conns map[key]*conn
}
// key identifies a connection: the page (a *mygo.Page) chooses ids for
// itself. A window may show several pages: those of its web views.
type key struct {
page any
id string
}
type connectOptions struct {
ID string `json:"id"`
URL string `json:"url"`
Protocols []string `json:"protocols"`
Headers [][2]string `json:"headers"`
}
// event is what happens to a connection, for the page.
type event struct {
Type string `json:"type"` // open, text, binary or close
Protocol string `json:"protocol,omitzero"`
Text string `json:"text,omitzero"`
Data []byte `json:"data,omitzero"`
Code int `json:"code,omitzero"`
Reason string `json:"reason,omitzero"`
Clean bool `json:"clean,omitzero"`
// Error tells why the connection failed.
Error string `json:"error,omitzero"`
}
// message is what the page sends.
type message struct {
Type string `json:"type"` // text, binary, close or skip
Text string `json:"text"`
Data []byte `json:"data"`
Code int `json:"code"`
Reason string `json:"reason"`
}
// Connect opens the connection and streams its events to the page until
// it closes.
func (s *service) Connect(ctx context.Context, opts connectOptions, events *mygo.Channel[event]) {
s.connect(ctx, mygo.CallerPage(ctx), opts, events.Send)
}
// Send sends the seq-th message of the page on the connection id, after
// those before it.
func (s *service) Send(ctx context.Context, id string, seq int64, m message) error {
return s.send(mygo.CallerPage(ctx), id, seq, m)
}
func (s *service) connect(ctx context.Context, page any, opts connectOptions, send func(event) error) {
k := key{page, opts.ID}
c, protocol, err := dial(ctx, s.opts.Client, opts.URL, opts.Protocols, opts.Headers, s.opts.Allow, s.opts.MaxMessageSize)
if err == nil {
s.mu.Lock()
if s.conns[k] != nil {
err = fmt.Errorf("connection %q is already open", opts.ID)
c.terminate()
} else {
s.conns[k] = c
}
s.mu.Unlock()
}
if err != nil {
send(event{Type: "close", Code: closeAbnormal, Error: err.Error()})
return
}
defer func() {
s.mu.Lock()
delete(s.conns, k)
s.mu.Unlock()
c.terminate()
}()
// The page going away closes the connection.
stop := context.AfterFunc(ctx, func() {
time.AfterFunc(time.Second, c.terminate)
c.writeClose(closeGoingAway, "")
c.terminate()
})
defer stop()
if send(event{Type: "open", Protocol: protocol}) != nil {
return
}
for {
op, data, err := c.readMessage()
if err != nil {
ev := event{Type: "close", Code: closeAbnormal}
if f, ok := errors.AsType[*failure](err); ok {
c.writeClose(f.code, "")
ev.Error = err.Error()
} else if !c.closing() {
// Not the server missing the closing handshake the page
// started.
ev.Error = err.Error()
}
send(ev)
return
}
switch op {
case opText:
err = send(event{Type: "text", Text: string(data)})
case opBinary:
err = send(event{Type: "binary", Data: data})
case opClose:
code, reason, perr := parseClose(data)
if perr != nil {
c.writeClose(perr.(*failure).code, "")
send(event{Type: "close", Code: closeAbnormal, Error: perr.Error()})
return
}
// Echo the code, unless the page closed first.
c.writeClose(code, "")
send(event{Type: "close", Code: code, Reason: reason, Clean: true})
return
}
if err != nil {
return // the page went away
}
}
}
func (s *service) send(page any, id string, seq int64, m message) error {
s.mu.Lock()
c := s.conns[key{page, id}]
s.mu.Unlock()
if c == nil {
return errClosed
}
return c.inTurn(seq, func() error {
switch m.Type {
case "text":
return c.writeFrame(opText, []byte(m.Text))
case "binary":
return c.writeFrame(opBinary, m.Data)
case "skip": // a message the page could not read
return nil
case "close":
if m.Code != closeNoStatus && m.Code != closeNormal && (m.Code < 3000 || m.Code > 4999) {
return fmt.Errorf("invalid close code %d", m.Code)
}
if len(m.Reason) > 123 {
return errors.New("close reason over 123 bytes")
}
return c.close(m.Code, m.Reason, s.opts.CloseTimeout)
}
return fmt.Errorf("unknown message type %q", m.Type)
})
}
+218
View File
@@ -0,0 +1,218 @@
package websocket
import (
"bufio"
"context"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/egoist/mygo/internal/wait"
)
// serverConn is the server's side of a hijacked connection.
type serverConn struct {
net.Conn
br *bufio.Reader
}
func (c serverConn) Read(p []byte) (int, error) { return c.br.Read(p) }
// testServer accepts connections and runs handle on the server's side.
func testServer(t *testing.T, handle func(r *http.Request, c *conn)) *httptest.Server {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/reject" || r.Header.Get("Sec-WebSocket-Version") != "13" || !strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {
http.Error(w, "not a WebSocket handshake", http.StatusBadRequest)
return
}
nc, brw, err := http.NewResponseController(w).Hijack()
if err != nil {
t.Error(err)
return
}
proto := ""
if p := r.Header.Get("Sec-WebSocket-Protocol"); p != "" {
proto = "Sec-WebSocket-Protocol: " + strings.Split(p, ",")[0] + "\r\n"
}
brw.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" +
"Sec-WebSocket-Accept: " + acceptKey(r.Header.Get("Sec-WebSocket-Key")) + "\r\n" + proto + "\r\n")
brw.Flush()
c := newConn(serverConn{nc, brw.Reader}, brw.Reader, true, 1<<20)
defer c.terminate()
handle(r, c)
}))
t.Cleanup(srv.Close)
return srv
}
// echo sends messages back; "close" makes it close the connection, "ping"
// pings, "split" sends a fragmented message.
func echo(r *http.Request, c *conn) {
for {
op, data, err := c.readMessage()
if err != nil {
return
}
switch {
case op == opClose:
code, _, _ := parseClose(data)
c.writeClose(code, "")
return
case string(data) == "close":
c.writeClose(4000, "bye")
case string(data) == "ping":
c.writeFrame(opPing, []byte("p"))
c.writeFrame(opText, []byte("pinged"))
case string(data) == "split":
c.rwc.Write([]byte{opText, 2, 'a', 'b'})
c.rwc.Write([]byte{0x80 | opContinuation, 1, 'c'})
case string(data) == "origin":
c.writeFrame(opText, []byte(r.Header.Get("Origin")))
default:
c.writeFrame(op, data)
}
}
}
// open connects the page of window 1 and returns its events.
func open(t *testing.T, s *service, opts connectOptions) (<-chan event, context.CancelFunc) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
events := make(chan event, 100)
go func() {
s.connect(ctx, 1, opts, func(e event) error {
if ctx.Err() != nil {
return ctx.Err()
}
events <- e
return nil
})
close(events)
}()
t.Cleanup(cancel)
return events, cancel
}
func next(t *testing.T, events <-chan event) event {
t.Helper()
select {
case e := <-events:
return e
case <-time.After(wait.Guard):
t.Fatal("no event")
return event{}
}
}
func TestWebSocket(t *testing.T) {
srv := testServer(t, echo)
url := "ws" + strings.TrimPrefix(srv.URL, "http")
s := New(Options{}).Service.(*service)
events, _ := open(t, s, connectOptions{ID: "a", URL: url, Protocols: []string{"chat", "v2"}, Headers: [][2]string{{"origin", "https://example.com"}}})
if e := next(t, events); e.Type != "open" || e.Protocol != "chat" {
t.Fatalf("open: %+v", e)
}
// Sent in the order of their sequence numbers, whatever the order of
// the calls.
errs := make(chan error, 3)
go func() { errs <- s.send(1, "a", 3, message{Type: "binary", Data: []byte{1, 2}}) }()
go func() { errs <- s.send(1, "a", 2, message{Type: "text", Text: "two"}) }()
time.Sleep(50 * time.Millisecond)
go func() { errs <- s.send(1, "a", 1, message{Type: "text", Text: "one"}) }()
for range 3 {
if err := <-errs; err != nil {
t.Fatal(err)
}
}
for _, want := range []string{"text:one", "text:two", "binary:\x01\x02"} {
e := next(t, events)
if got := e.Type + ":" + e.Text + string(e.Data); got != want {
t.Errorf("got %q, want %q", got, want)
}
}
for i, m := range []string{"ping", "split", "origin"} {
if err := s.send(1, "a", int64(4+i), message{Type: "text", Text: m}); err != nil {
t.Fatal(err)
}
}
for _, want := range []string{"pinged", "abc", "https://example.com"} {
if e := next(t, events); e.Text != want {
t.Errorf("got %+v, want %q", e, want)
}
}
// The page closes the connection.
if err := s.send(1, "a", 7, message{Type: "close", Code: 1000, Reason: "done"}); err != nil {
t.Fatal(err)
}
if e := next(t, events); e.Type != "close" || e.Code != 1000 || !e.Clean {
t.Errorf("close: %+v", e)
}
if err := s.send(1, "a", 8, message{Type: "text", Text: "late"}); err == nil {
t.Error("sent on a closed connection")
}
// The server closes it.
events, _ = open(t, s, connectOptions{ID: "b", URL: url})
next(t, events)
s.send(1, "b", 1, message{Type: "text", Text: "close"})
if e := next(t, events); e.Type != "close" || e.Code != 4000 || e.Reason != "bye" || !e.Clean {
t.Errorf("closed by the server: %+v", e)
}
// Failed handshakes.
events, _ = open(t, s, connectOptions{ID: "c", URL: srv.URL + "/reject", Headers: [][2]string{{"sec-websocket-version", "8"}}})
if e := next(t, events); e.Type != "close" || e.Code != 1006 || !strings.Contains(e.Error, "400") {
t.Errorf("rejected handshake: %+v", e)
}
deny := New(Options{Allow: func(*http.Request) bool { return false }}).Service.(*service)
events, _ = open(t, deny, connectOptions{ID: "d", URL: url})
if e := next(t, events); !strings.Contains(e.Error, "does not allow") {
t.Errorf("Allow: %+v", e)
}
}
func TestWebSocketPageGoesAway(t *testing.T) {
closed := make(chan int, 1)
srv := testServer(t, func(r *http.Request, c *conn) {
_, data, _ := c.readMessage()
code, _, _ := parseClose(data)
closed <- code
})
s := New(Options{}).Service.(*service)
events, cancel := open(t, s, connectOptions{ID: "a", URL: "ws" + strings.TrimPrefix(srv.URL, "http")})
next(t, events)
cancel()
select {
case code := <-closed:
if code != closeGoingAway {
t.Errorf("closed with %d", code)
}
case <-time.After(wait.Guard):
t.Fatal("the connection was not closed")
}
for range events {
}
s.mu.Lock()
defer s.mu.Unlock()
if len(s.conns) != 0 {
t.Errorf("connections left: %v", s.conns)
}
}
func TestWebSocketCloseTimeout(t *testing.T) {
srv := testServer(t, func(r *http.Request, c *conn) {
time.Sleep(2 * time.Second) // never answers the close
})
s := New(Options{CloseTimeout: 100 * time.Millisecond}).Service.(*service)
events, _ := open(t, s, connectOptions{ID: "a", URL: "ws" + strings.TrimPrefix(srv.URL, "http")})
next(t, events)
s.send(1, "a", 1, message{Type: "close", Code: 1000})
if e := next(t, events); e.Code != 1006 || e.Clean || e.Error != "" {
t.Errorf("close without an answer: %+v", e)
}
}