diff --git a/.github/workflows/public-site.yml b/.github/workflows/public-site.yml index ff9e601cc..f4868222f 100644 --- a/.github/workflows/public-site.yml +++ b/.github/workflows/public-site.yml @@ -188,6 +188,15 @@ jobs: run: | rustup toolchain install 1.99.1 --profile minimal --target wasm32-unknown-unknown python3 platform/tools/bootstrap_browser_runtime.py --fetch-rom + - name: Build the restricted workbench TLS transport + run: | + go_bundle=go1.27.4.darwin-arm64.tar.gz + go_stage="$RUNNER_TEMP/workbench-go" + mkdir -p "$go_stage" + curl --fail --location --retry 3 --max-time 180 "https://go.dev/dl/$go_bundle" --output "$go_stage/$go_bundle" + printf '%s %s\n' 91a44a2b8a716600ad94a4f143e156116620db8828086a6e3602291be9bd0bb4 "$go_stage/$go_bundle" | shasum -a 256 -c + tar -xzf "$go_stage/$go_bundle" -C "$go_stage" + python3 platform/tools/build_workbench_tls.py --go "$go_stage/go/bin/go" --output .work/browser-workbench-tls - name: Export reviewed browser assets id: export env: @@ -196,7 +205,7 @@ jobs: run: | python3 -m pip install pyfatfs==1.1.0 setuptools==80.10.2 python3 platform/tools/browser_docs_sd_fixture.py --output .work/browser-docs-sd - python3 platform/tools/build_public_site.py --output .work/public-site --base-path "$PUBLIC_BASE_PATH" --service-url "$PUBLIC_SERVICE_URL" --browser-runtime .work/browser-runtime --qemu-runtime .work/qemu-browser-runtime --qemu-c61-runtime .work/qemu-c61-runtime --littlefs-runtime .work/browser-littlefs --qemu-sd-media .work/browser-docs-sd + python3 platform/tools/build_public_site.py --output .work/public-site --base-path "$PUBLIC_BASE_PATH" --service-url "$PUBLIC_SERVICE_URL" --browser-runtime .work/browser-runtime --qemu-runtime .work/qemu-browser-runtime --qemu-c61-runtime .work/qemu-c61-runtime --littlefs-runtime .work/browser-littlefs --qemu-sd-media .work/browser-docs-sd --workbench-tls .work/browser-workbench-tls - uses: actions/setup-node@v4 with: node-version: "22" diff --git a/docs/code-map.md b/docs/code-map.md index c20737822..6027cc5a3 100644 --- a/docs/code-map.md +++ b/docs/code-map.md @@ -188,6 +188,7 @@ CLI、HTTP 或测试契约,而不是导入对方的内部实现细节。 | `platform/tools/generate_catalog.py` | 从源 catalog 生成设备 JSON/README | 发布与 CI | | `platform/tools/export_bundle.py` | 导出可移植设备/运行时资产包 | 部署 | | `platform/tools/build_public_site.py` | 显式白名单导出 Pages 静态资源、项目子路径、站点配置及纯视觉目录;不自动部署 | 公众入口与 URL/下载契约测试;架构边界见[浏览器调研](browser-runtime-feasibility.md) | +| `platform/tools/build_workbench_tls.py` | 构建浏览器 Workbench 隔离对端使用的 TLS WASM 和 Go 运行时许可 | `test_bootstrap_browser_runtime.py` 校验 Worker 模块来源,Pages 导出生成 TLS 资源摘要 | | `platform/tools/browser_docs_sd_fixture.py` | 从固定素材和 FAT 时间生成 CoreS3 Arduino WAV 原始 SD 种子及导出清单 | 完整种子与 WAV 摘要随生成校验,浏览器按固件摘要挂接 | | `platform/tools/bootstrap_browser_runtime.py` | 固定 esp32sim 源码与 lockfile 构建 WASM,校验 ROM 来源、许可和 SHA,生成可审计 runtime manifest | `test_bootstrap_browser_runtime.py`;构建产物仅存 ignored cache / 静态导出 | | `platform/tools/bootstrap_qemu_browser_runtime.py`、`scripts/qemu-wasm-build/` | 固定 C/QEMU、Emscripten 及依赖完整源码构建和对应源码归档;生产者路径映射、依赖策略与分发扫描,默认不打包 ROM/固件 | `test_bootstrap_qemu_browser_runtime.py`;[Pages 部署](pages-deployment.md) | diff --git a/docs/project-snapshot.md b/docs/project-snapshot.md index bdb3e13bf..34d8f5aaa 100644 --- a/docs/project-snapshot.md +++ b/docs/project-snapshot.md @@ -155,7 +155,7 @@ ## 代码与文档规模 -- `platform/tools`:`105` 个 Python 模块,`63268` 行;规模最大的模块如下。 +- `platform/tools`:`106` 个 Python 模块,`63353` 行;规模最大的模块如下。 | 模块 | 行数 | | --- | ---: | @@ -168,7 +168,7 @@ - `tests/`:`184` 个可执行 Python 测试文件,分布在 `85` 个目录;`253` 个 evidence JSON。 - `patches/`:`17` 个补丁组,`386` 个 patch 文件。 -- 文档:`762` 个 Markdown 页面;除本生成页外共 `84341` 行。 +- 文档:`762` 个 Markdown 页面;除本生成页外共 `84342` 行。 ## 文档与测试 diff --git a/platform/tests/test_bootstrap_browser_runtime.py b/platform/tests/test_bootstrap_browser_runtime.py index 072f72f0f..ad44dfa14 100644 --- a/platform/tests/test_bootstrap_browser_runtime.py +++ b/platform/tests/test_bootstrap_browser_runtime.py @@ -40,6 +40,7 @@ def test_worker_glue_is_exact_reviewed_source_and_has_only_local_imports(self): self.assertEqual(source["license"], "MIT") self.assertEqual(set(source["files"]), { "worker.js", "jit.mjs", "pacing.mjs", "experiments.mjs", "review-mqtt.mjs", "review-modbus-tcp.mjs", "LICENSE", + "https-app.mjs", "tls-worker-peer.mjs", }) for name, row in source["files"].items(): data = (directory / name).read_bytes() @@ -47,8 +48,9 @@ def test_worker_glue_is_exact_reviewed_source_and_has_only_local_imports(self): self.assertEqual(len(data), row["bytes"]) worker = (directory / "worker.js").read_text() self.assertIn("WebAssembly.instantiate", worker) - for code in (worker, (directory / "review-mqtt.mjs").read_text(), - (directory / "review-modbus-tcp.mjs").read_text()): + for name in ("worker.js", "review-mqtt.mjs", "review-modbus-tcp.mjs", + "https-app.mjs", "tls-worker-peer.mjs"): + code = (directory / name).read_text() self.assertNotIn("fetch(", code) self.assertNotIn("new WebSocket", code) diff --git a/platform/tests/test_public_qemu_entry.mjs b/platform/tests/test_public_qemu_entry.mjs index 079a59622..8462ed759 100644 --- a/platform/tests/test_public_qemu_entry.mjs +++ b/platform/tests/test_public_qemu_entry.mjs @@ -27,6 +27,8 @@ import * as instruments from '../web/public-instrument-examples.js'; import * as uartUnits from '../web/public-uart-unit-examples.js'; import * as nbiotExamples from '../web/public-nbiot-examples.js'; import * as mqttUnitExamples from '../web/public-mqtt-unit-examples.js'; +import * as espNow from '../web/public-espnow-example.js'; +import * as gatewayH2 from '../web/public-gateway-h2-examples.js'; import * as rui3Module from '../web/public-rui3-module-example.js'; import * as portAUnitExamples from '../web/public-port-a-examples.js'; import * as usbModuleExamples from '../web/public-usb-module-examples.js'; @@ -117,7 +119,7 @@ async function entry({search='',pageUrl=pageRoot,siteServiceUrl='',isolationErro throw new Error('Unexpected fetch '+url); }; const dependencies=Object.fromEntries(required.map(name=>[name,()=>{throw new Error(`Unexpected execution boundary ${name}`);} ])); - Object.assign(dependencies,config,firmware,demoFirmware,uiflowFirmware,cloudStatus,qemuProfiles,qemuFrame,qemuServo,qemuPeerPair,qemuUnitExamples,qrcodeModule,facesModule,envExamples,moduleLlm,miniScales,servos8,capGps,rui3Module,nbiotExamples,mqttUnitExamples,instruments,uartUnits,dofExamples,moduleRadios,gpioExamples,portAUnitExamples,usbModuleExamples,displayUnitExamples,driveModuleExamples,portBUnitExamples,serialSensorExamples,pwmUnitExamples,thermalExamples,cores3SensorExamples,fingerprint2,modbusRtu,networkFixtures,usbHidExamples,audioModule,{ + Object.assign(dependencies,config,firmware,demoFirmware,uiflowFirmware,cloudStatus,qemuProfiles,qemuFrame,qemuServo,qemuPeerPair,qemuUnitExamples,qrcodeModule,facesModule,envExamples,moduleLlm,miniScales,servos8,capGps,rui3Module,espNow,gatewayH2,nbiotExamples,mqttUnitExamples,instruments,uartUnits,dofExamples,moduleRadios,gpioExamples,portAUnitExamples,usbModuleExamples,displayUnitExamples,driveModuleExamples,portBUnitExamples,serialSensorExamples,pwmUnitExamples,thermalExamples,cores3SensorExamples,fingerprint2,modbusRtu,networkFixtures,usbHidExamples,audioModule,{ siteRoot:()=>new URL(pageUrl), ensurePublicIsolation:async()=>{events.push('isolation');if(isolationError)throw isolationError;return isolation;}, PublicMicroPythonRunner,deviceIdentityCapability,GNSS_EXAMPLE_ID,supportsQemuGnssWorkbench, diff --git a/platform/tools/bootstrap_browser_runtime.py b/platform/tools/bootstrap_browser_runtime.py index e820de468..15af1248a 100644 --- a/platform/tools/bootstrap_browser_runtime.py +++ b/platform/tools/bootstrap_browser_runtime.py @@ -21,7 +21,7 @@ ROOT = Path(__file__).resolve().parents[2] SOURCE_URL = "https://github.com/m5agent/esp32sim.git" -SOURCE_COMMIT = "d1c930adffaa8d94d03856eb0276df17da668002" +SOURCE_COMMIT = "c51955bc06e123b98a371208e12598a0152354ac" BOARD_PROFILES = json.loads((ROOT / "platform/web/esp32sim-browser-boards.json").read_text()) SOURCE_PROFILES = [ "m5stack-cores3", "m5stack-cores3+dual-kmeter", @@ -29,7 +29,9 @@ "m5stack-cores3+mini-scales", "m5stack-cores3+finger-unit", "m5stack-cores3+fingerprint2", "m5stack-cores3+8servos", "m5stack-cores3+rui3-module", "m5stack-cores3+hall-effect", "m5stack-cores3+dof6", "m5stack-cores3+dof9", "m5stack-cores3+dof10", "m5stack-cores3+bmm350", "m5stack-cores3+cc1101", "m5stack-cores3+lora868-sx1276", "m5stack-cores3+lora868-v12", "m5stack-cores3+lora1262", - "m5stack-cores3+usb-module-gpio", "m5stack-cores3+usb-module-mouse", + "m5stack-cores3+e220-433", "m5stack-cores3+espnow-echo", + "m5stack-cores3+usb-module-gpio", "m5stack-cores3+usb-module-mouse", "m5stack-cores3+lan-module", + "m5stack-cores3+gateway-h2-unit", "m5stack-cores3+gateway-h2-module", "m5stack-cores3+display-module", "m5stack-cores3+sim7020", "m5stack-cores3+sim7028", "m5stack-cores3+mqtt-unit", "m5stack-cores3+mqttpoe-unit", "m5stack-cores3+dc-motor-module", "m5stack-cores3+fan-module", diff --git a/platform/tools/build_public_site.py b/platform/tools/build_public_site.py index 6dc34ab9a..ffad4d8f3 100644 --- a/platform/tools/build_public_site.py +++ b/platform/tools/build_public_site.py @@ -408,7 +408,7 @@ def littlefs_runtime_files(directory: Path, *, require_sized_mount: bool = False return files -def build_site(root: Path, output: Path, *, base_path: str = "/", service_url: str = "", browser_runtime: Path | None = None, legacy_browser_runtime: Path | None = None, qemu_runtime: Path | None = None, qemu_c61_runtime: Path | None = None, littlefs_runtime: Path | None = None, allow_diagnostic_runtime: bool = False, qemu_candidate_profiles: tuple[str, ...] = (), qemu_sd_media: Path | None = None, qemu_cores3_audio: bool = False) -> dict: +def build_site(root: Path, output: Path, *, base_path: str = "/", service_url: str = "", browser_runtime: Path | None = None, legacy_browser_runtime: Path | None = None, qemu_runtime: Path | None = None, qemu_c61_runtime: Path | None = None, littlefs_runtime: Path | None = None, allow_diagnostic_runtime: bool = False, qemu_candidate_profiles: tuple[str, ...] = (), qemu_sd_media: Path | None = None, qemu_cores3_audio: bool = False, workbench_tls: Path | None = None) -> dict: root, output = root.resolve(), output.resolve() base_path = normalize_base_path(base_path) service_url = normalize_service_url(service_url) @@ -564,6 +564,23 @@ def build_site(root: Path, output: Path, *, base_path: str = "/", service_url: s destination = temporary / "platform/runtime/littlefs" / name destination.parent.mkdir(parents=True, exist_ok=True) destination.write_bytes(content) + if workbench_tls is not None: + if not esp32sim_present: + raise ValueError("workbench TLS requires the default esp32sim runtime") + destination = temporary / "platform/runtime/workbench-tls" + destination.mkdir(parents=True) + artifacts = {} + for filename, limit in (("wasm_exec.js", 65536), ("fixture.wasm", 12 * 1024 * 1024), + ("LICENSE.go", 16384)): + source = workbench_tls / filename + if source.is_symlink() or not 0 < source.stat().st_size <= limit: + raise ValueError("invalid workbench TLS runtime file") + content = source.read_bytes() + if filename == "fixture.wasm" and not content.startswith(b"\0asm\x01"): + raise ValueError("invalid workbench TLS module") + (destination / filename).write_bytes(content) + artifacts[filename] = {"bytes": len(content), "sha256": hashlib.sha256(content).hexdigest()} + (destination / "runtime.json").write_text(json.dumps({"schema_version": 1, "assets": artifacts}) + "\n") config = { "schema_version": 1, "service_url": service_url, "max_firmware_bytes": 64 * 1024 * 1024, @@ -572,6 +589,7 @@ def build_site(root: Path, output: Path, *, base_path: str = "/", service_url: s "browser_esp32sim_profiles": [profile for profiles in esp32sim_profiles.values() for profile in profiles], "browser_qemu_available": bool(qemu_runtime), "browser_esp32sim_workbench": bool(esp32sim_present and littlefs_runtime), + "browser_esp32sim_workbench_tls": workbench_tls is not None, "browser_runtime_build": esp32sim_build if esp32sim_present else runtime_manifest["build"]["kind"] if runtime_manifest else None, "browser_candidate_profiles": list(qemu_candidate_profiles), "publication_eligible": not bool(qemu_candidate_profiles or qemu_cores3_audio or esp32sim_diagnostic), @@ -637,6 +655,7 @@ def main() -> None: parser.add_argument("--base-path", default="/", help="/ for user Pages; /repository/ for project Pages") parser.add_argument("--service-url", default="", help="optional public HTTPS Device Service, without token") parser.add_argument("--browser-runtime", type=Path, help="directory from bootstrap_browser_runtime.py") + parser.add_argument("--workbench-tls", type=Path, help="optional reviewed local workbench TLS fixture runtime") parser.add_argument("--legacy-browser-runtime", type=Path, help="optional PaperS3/StopWatch bundle from bootstrap --legacy") parser.add_argument("--qemu-runtime", type=Path, help="directory from bootstrap_qemu_browser_runtime.py") parser.add_argument("--qemu-c61-runtime", type=Path, help="directory from the RISC-V C61 source build") @@ -649,7 +668,7 @@ def main() -> None: parser.add_argument("--qemu-candidate-profile", action="append", default=[], help="preview-only board candidate; never supplied by the Pages publication workflow") args = parser.parse_args() try: - manifest = build_site(ROOT, args.output, base_path=args.base_path, service_url=args.service_url, browser_runtime=args.browser_runtime, legacy_browser_runtime=args.legacy_browser_runtime, qemu_runtime=args.qemu_runtime, qemu_c61_runtime=args.qemu_c61_runtime, littlefs_runtime=args.littlefs_runtime, allow_diagnostic_runtime=args.allow_diagnostic_runtime, qemu_candidate_profiles=tuple(args.qemu_candidate_profile), qemu_sd_media=args.qemu_sd_media, qemu_cores3_audio=args.qemu_cores3_audio) + manifest = build_site(ROOT, args.output, base_path=args.base_path, service_url=args.service_url, browser_runtime=args.browser_runtime, legacy_browser_runtime=args.legacy_browser_runtime, qemu_runtime=args.qemu_runtime, qemu_c61_runtime=args.qemu_c61_runtime, littlefs_runtime=args.littlefs_runtime, allow_diagnostic_runtime=args.allow_diagnostic_runtime, qemu_candidate_profiles=tuple(args.qemu_candidate_profile), qemu_sd_media=args.qemu_sd_media, qemu_cores3_audio=args.qemu_cores3_audio, workbench_tls=args.workbench_tls) except (OSError, ValueError, KeyError) as error: parser.exit(1, f"public site export failed: {error}\n") print(json.dumps({"output": str(args.output), "assets": len(manifest["assets"]), "bytes": sum(row["bytes"] for row in manifest["assets"]), "base_path": manifest["base_path"], "published": False})) diff --git a/platform/tools/build_workbench_tls.py b/platform/tools/build_workbench_tls.py new file mode 100644 index 000000000..31f7f1c2b --- /dev/null +++ b/platform/tools/build_workbench_tls.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Build the restricted browser fixture's socket-free TLS transport.""" + +from __future__ import annotations + +import argparse +import os +from pathlib import Path +import shutil +import subprocess +import tempfile + + +GO_VERSION = "go1.27.4" +SOURCE = Path(__file__).resolve().parent / "workbench_tls/main.go" + + +def build(go: str, output: Path) -> None: + env = { + **os.environ, + "CGO_ENABLED": "0", + "GO111MODULE": "off", + "GOARCH": "wasm", + "GOENV": "off", + "GOFLAGS": "", + "GOOS": "js", + "GOPROXY": "off", + "GOSUMDB": "off", + "GOTOOLCHAIN": "local", + "GOWORK": "off", + } + env.pop("GOROOT", None) + version = subprocess.check_output([go, "version"], env=env, text=True).split() + if version[:3] != ["go", "version", GO_VERSION]: + raise ValueError(f"browser TLS fixture requires {GO_VERSION}") + toolchain = Path(subprocess.check_output([go, "env", "GOROOT"], env=env, text=True).strip()) + output = output.resolve() + output.parent.mkdir(parents=True, exist_ok=True) + if output.exists(): + raise FileExistsError(output) + with tempfile.TemporaryDirectory(dir=output.parent, prefix="workbench-tls-") as temp: + stage = Path(temp) / "runtime" + stage.mkdir() + subprocess.run( + [go, "build", "-trimpath", "-buildvcs=false", "-ldflags=-s -w -buildid=", + "-o", str(stage / "fixture.wasm"), str(SOURCE)], + env=env, + check=True, + ) + shutil.copyfile(toolchain / "lib/wasm/wasm_exec.js", stage / "wasm_exec.js") + shutil.copyfile(toolchain / "LICENSE", stage / "LICENSE.go") + stage.rename(output) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--go", default="go", help="the pinned Go toolchain executable") + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + build(args.go, args.output) + + +if __name__ == "__main__": + main() diff --git a/platform/tools/workbench_tls/main.go b/platform/tools/workbench_tls/main.go new file mode 100644 index 000000000..46b859422 --- /dev/null +++ b/platform/tools/workbench_tls/main.go @@ -0,0 +1,245 @@ +// SPDX-FileCopyrightText: 2026 m5agent contributors +// SPDX-License-Identifier: MIT + +// Terminates TLS for a browser workbench peer using in-memory pipes. +package main + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "math/big" + "net" + "regexp" + "syscall/js" + "time" +) + +const maxChunk = 32 * 1024 +const maxFlows = 2 + +type flow struct { + tcp, wire net.Conn + inbound chan []byte + replies chan []byte + onEvent js.Value + closed chan struct{} +} + +var hostPattern = regexp.MustCompile(`^[a-z0-9]([a-z0-9.-]{0,127}[a-z0-9])?$`) +var flows = map[int]*flow{} +var config *tls.Config + +func ephemeralCertificate(host string) (*tls.Config, []byte, error) { + caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return nil, nil, err + } + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return nil, nil, err + } + ca := &x509.Certificate{ + SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "Local fixture CA"}, + NotBefore: time.Unix(0, 0), NotAfter: time.Date(2090, 1, 1, 0, 0, 0, 0, time.UTC), + IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign, + } + caDer, err := x509.CreateCertificate(rand.Reader, ca, ca, &caKey.PublicKey, caKey) + if err != nil { + return nil, nil, err + } + leaf := &x509.Certificate{ + SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: host}, DNSNames: []string{host}, + NotBefore: ca.NotBefore, NotAfter: ca.NotAfter, BasicConstraintsValid: true, + KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + } + leafDer, err := x509.CreateCertificate(rand.Reader, leaf, ca, &key.PublicKey, caKey) + if err != nil { + return nil, nil, err + } + tlsConfig := &tls.Config{ + Certificates: []tls.Certificate{{Certificate: [][]byte{leafDer, caDer}, PrivateKey: key}}, + MinVersion: tls.VersionTLS12, SessionTicketsDisabled: true, + } + return tlsConfig, caDer, nil +} + +func jsBytes(data []byte) js.Value { + dst := js.Global().Get("Uint8Array").New(len(data)) + js.CopyBytesToJS(dst, data) + return dst +} + +func configure(_ js.Value, args []js.Value) any { + if len(args) != 1 || len(flows) != 0 || !hostPattern.MatchString(args[0].String()) { + return nil + } + cfg, ca, err := ephemeralCertificate(args[0].String()) + if err != nil { + return nil + } + config = cfg + return jsBytes(ca) +} + +func closeFlow(id int) { + item, ok := flows[id] + if !ok { + return + } + delete(flows, id) + close(item.closed) + _ = item.tcp.Close() + _ = item.wire.Close() +} + +func open(_ js.Value, args []js.Value) any { + if len(args) != 2 || config == nil || len(flows) >= maxFlows || + args[0].Type() != js.TypeNumber || args[1].Type() != js.TypeFunction { + return false + } + id := args[0].Int() + if id <= 0 || flows[id] != nil { + return false + } + tcp, wire := net.Pipe() + item := &flow{ + tcp: tcp, wire: wire, inbound: make(chan []byte, 8), replies: make(chan []byte, 4), + onEvent: args[1], closed: make(chan struct{}), + } + flows[id] = item + go item.receiveCiphertext() + go item.sendCiphertext() + go item.serve(id) + return true +} + +func (item *flow) receiveCiphertext() { + for { + select { + case data := <-item.inbound: + if _, err := item.wire.Write(data); err != nil { + return + } + case <-item.closed: + return + } + } +} + +func (item *flow) sendCiphertext() { + var data [maxChunk]byte + for { + n, err := item.wire.Read(data[:]) + if n > 0 { + item.onEvent.Invoke("ciphertext", jsBytes(data[:n])) + } + if err != nil { + return + } + } +} + +func (item *flow) serve(id int) { + defer closeFlow(id) + server := tls.Server(item.tcp, config) + if err := server.SetDeadline(time.Now().Add(15 * time.Second)); err != nil { + item.onEvent.Invoke("failed") + return + } + if err := server.Handshake(); err != nil { + item.onEvent.Invoke("failed") + return + } + if err := server.SetDeadline(time.Now().Add(90 * time.Second)); err != nil { + return + } + item.onEvent.Invoke("handshake", int(server.ConnectionState().Version)) + go func() { + for { + select { + case reply := <-item.replies: + if reply == nil { + _ = server.CloseWrite() + return + } + if _, err := server.Write(reply); err != nil { + return + } + case <-item.closed: + return + } + } + }() + var data [maxChunk]byte + for { + n, err := server.Read(data[:]) + if n > 0 { + item.onEvent.Invoke("plaintext", jsBytes(data[:n])) + } + if err != nil { + item.onEvent.Invoke("closed") + return + } + } +} + +func queue(args []js.Value, plaintext bool) bool { + if len(args) != 2 || args[0].Type() != js.TypeNumber || + !args[1].InstanceOf(js.Global().Get("Uint8Array")) { + return false + } + item := flows[args[0].Int()] + size := args[1].Get("byteLength").Int() + if item == nil || size == 0 || size > maxChunk { + return false + } + data := make([]byte, size) + js.CopyBytesToGo(data, args[1]) + queue := item.inbound + if plaintext { + queue = item.replies + } + select { + case queue <- data: + return true + default: + return false + } +} + +func finish(_ js.Value, args []js.Value) any { + if len(args) != 1 || args[0].Type() != js.TypeNumber { + return false + } + item := flows[args[0].Int()] + if item == nil { + return false + } + select { + case item.replies <- nil: + return true + default: + return false + } +} + +func main() { + global := js.Global() + global.Set("fixtureTlsConfigure", js.FuncOf(configure)) + global.Set("fixtureTlsOpen", js.FuncOf(open)) + global.Set("fixtureTlsFinish", js.FuncOf(finish)) + global.Set("fixtureTlsFeed", js.FuncOf(func(_ js.Value, args []js.Value) any { return queue(args, false) })) + global.Set("fixtureTlsReply", js.FuncOf(func(_ js.Value, args []js.Value) any { return queue(args, true) })) + global.Set("fixtureTlsClose", js.FuncOf(func(_ js.Value, args []js.Value) any { + if len(args) == 1 && args[0].Type() == js.TypeNumber { + closeFlow(args[0].Int()) + } + return nil + })) + global.Get("onFixtureTlsReady").Invoke() + select {} +} diff --git a/platform/web/index.html b/platform/web/index.html index 36fc722ad..5ad582fa8 100644 --- a/platform/web/index.html +++ b/platform/web/index.html @@ -212,6 +212,8 @@

8Servos 输出