Compare commits
2
Commits
752d0cf3af
...
e9818aaeda
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e9818aaeda | ||
|
|
c3ca3e1752 |
No files matched your search
@@ -0,0 +1,6 @@
|
||||
# Run bun run dev:setup to create .env.development with a random secret.
|
||||
TURN_SECRET=replace-with-a-random-secret
|
||||
TURN_HOST=127.0.0.1
|
||||
TURN_PORT=3478
|
||||
VITE_ICE_ENDPOINT=/api/ice-servers
|
||||
VITE_STUN_URL=stun:127.0.0.1:3478
|
||||
@@ -1,2 +1,5 @@
|
||||
node_modules
|
||||
dist
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
@@ -73,6 +73,11 @@ relay-only routing or hide your IP from the peer. A remote peer can independentl
|
||||
proxy their own traffic; the opt-in controls this app's configuration and the
|
||||
relay candidates it accepts, not arbitrary software run by the other person.
|
||||
|
||||
When a credential endpoint is configured (including the local development setup
|
||||
below), **Use the configured relay with temporary credentials** replaces manual
|
||||
credential entry. The app fetches fresh credentials for each new connection,
|
||||
only after TURN opt-in. Uncheck it to use a different relay manually.
|
||||
|
||||
TURN credentials stay in the current component's memory; the app does not persist
|
||||
them or include them in codes. The relay receives its authentication exchange and
|
||||
can observe addresses, timing and traffic volume, and may charge for bandwidth.
|
||||
@@ -117,9 +122,96 @@ not a substitute for trusting the host or a portable WebRTC egress filter.
|
||||
|
||||
## Development
|
||||
|
||||
### Local STUN/TURN environment (Linux)
|
||||
|
||||
Keep Vite on the host for hot reload; only coturn runs in Docker. Both bind to
|
||||
loopback, so use two browser tabs on this machine. No DNS, certificates, firewall
|
||||
changes or production services are needed. Nothing is enabled at boot, and the
|
||||
container has no automatic restart policy.
|
||||
|
||||
```sh
|
||||
# Start Docker only when needed (if it isn't already running).
|
||||
sudo systemctl start docker.service
|
||||
# If you just joined the docker group, log in again or run: newgrp docker
|
||||
bun install --frozen-lockfile
|
||||
bun run dev:setup # creates ignored .env.development, without overwriting it
|
||||
bun run turn:up
|
||||
bun run dev # open the printed localhost URL in two tabs
|
||||
```
|
||||
|
||||
Pick a file in the sender tab, choose Receive in the other, and check **Allow a
|
||||
TURN relay** in both tabs. Leave **Use the configured relay with temporary
|
||||
credentials** checked. Exchange codes and compare fingerprints as usual. Reset,
|
||||
failure or completion clears consent, so check it again for each connection.
|
||||
STUN defaults to the local server; TURN remains opt-in, with direct routes preferred.
|
||||
|
||||
```sh
|
||||
bun run test # protocol and temporary-credential unit tests
|
||||
bun run test:turn # real Chromium file transfer, forced TURN/UDP
|
||||
bun run test:turn --tcp # same test, TURN/TCP only
|
||||
bun run build
|
||||
bun run test:browser # direct-path browser regressions
|
||||
docker compose --env-file .env.development logs --tail=50 coturn
|
||||
```
|
||||
|
||||
The TURN checks start and stop their own Vite server and isolated browser profiles;
|
||||
coturn must already be running. They obtain real temporary credentials, force
|
||||
relay-only routing, assert selected relay candidates on both ends, verify exact
|
||||
received bytes and receipts, and exercise cancellation and reconnection. TCP here
|
||||
means browser-to-TURN transport; relay-to-peer traffic is UDP. These same-machine
|
||||
checks do not test Internet NATs or a remote server's firewall.
|
||||
|
||||
Stop Vite with Ctrl-C, then:
|
||||
|
||||
```sh
|
||||
bun run turn:down
|
||||
# Optional: stop Docker too, after finishing any other containers.
|
||||
sudo systemctl stop docker.service docker.socket containerd.service
|
||||
```
|
||||
|
||||
`.env.development` contains the private shared `TURN_SECRET`, server-side
|
||||
`TURN_HOST`/`TURN_PORT`, and public `VITE_ICE_ENDPOINT`/`VITE_STUN_URL` settings.
|
||||
See [.env.example](.env.example). The secret never enters the client bundle.
|
||||
Compose passes it directly to coturn; no config-file environment substitution is
|
||||
assumed. If changing the port, update both `TURN_PORT` and `VITE_STUN_URL`, then
|
||||
rerun `turn:up` and restart Vite. The image is pinned to a concrete release;
|
||||
loopback listeners and UDP relay ports 49160–49200 are defined in [compose.yaml](compose.yaml).
|
||||
Loopback peer access is explicitly allowed for these local tests.
|
||||
|
||||
The credential endpoint is **development-only**, implemented as Vite middleware.
|
||||
It isn't included in `dist/` or `vite preview`. Production builds ignore
|
||||
`.env.development` and retain the existing static/manual configuration. To reuse
|
||||
the client integration later, set `VITE_ICE_ENDPOINT` and `VITE_STUN_URL` when
|
||||
building and implement the same JSON endpoint behind your production access
|
||||
policy. [dev/ice-server.ts](dev/ice-server.ts) contains the HMAC issuance logic.
|
||||
There are no accounts or room sessions in this app to authorize production
|
||||
credential issuance automatically. Don't expose this development endpoint or
|
||||
reuse the loopback-permitting Compose configuration as a public relay.
|
||||
|
||||
Credentials expire after one hour; each new code exchange fetches fresh ones.
|
||||
Automatic renewal during long transfers is not implemented because this app
|
||||
uses manual signaling. Keep development transfers below that duration; expired
|
||||
or failed sessions need fresh codes.
|
||||
|
||||
Configuration references: [coturn Docker usage](https://github.com/coturn/coturn/blob/master/docker/coturn/README.md)
|
||||
and [coturn configuration](https://github.com/coturn/coturn/blob/master/examples/etc/turnserver.conf).
|
||||
|
||||
### Existing checks and static build
|
||||
|
||||
Use Bun for dependency installation and Node.js 22.18+ for the scripts and tests.
|
||||
All application code, Vue scripts, development middleware, and checks use strict
|
||||
TypeScript. `vue-tsc` checks both TypeScript and Vue templates, and runs before
|
||||
every production build. TypeScript stays on 5.9 until Vue's checker supports the
|
||||
TypeScript 7 compiler.
|
||||
|
||||
Vite 8 supplies VoidZero's Rolldown bundler and Oxc transforms. The only added
|
||||
development dependencies are TypeScript, `vue-tsc`, and Node types. Node runs
|
||||
the TypeScript tests directly; no separate test framework or TS loader is needed.
|
||||
|
||||
```sh
|
||||
bun install --frozen-lockfile
|
||||
bun run dev
|
||||
bun run typecheck
|
||||
bun run test
|
||||
bun run build
|
||||
bun run test:browser # local Chromium integration checks against dist/
|
||||
|
||||
@@ -8,8 +8,11 @@
|
||||
"vue": "^3.5.43",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22",
|
||||
"@vitejs/plugin-vue": "^6.0.9",
|
||||
"vite": "^7.3.7",
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^8",
|
||||
"vue-tsc": "^3.3.12",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -22,118 +25,52 @@
|
||||
|
||||
"@babel/types": ["@babel/types@7.29.8", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg=="],
|
||||
|
||||
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="],
|
||||
|
||||
"@esbuild/android-arm": ["@esbuild/android-arm@0.28.2", "", { "os": "android", "cpu": "arm" }, "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg=="],
|
||||
|
||||
"@esbuild/android-arm64": ["@esbuild/android-arm64@0.28.2", "", { "os": "android", "cpu": "arm64" }, "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A=="],
|
||||
|
||||
"@esbuild/android-x64": ["@esbuild/android-x64@0.28.2", "", { "os": "android", "cpu": "x64" }, "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q=="],
|
||||
|
||||
"@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.28.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw=="],
|
||||
|
||||
"@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.28.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw=="],
|
||||
|
||||
"@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.28.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw=="],
|
||||
|
||||
"@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.28.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg=="],
|
||||
|
||||
"@esbuild/linux-arm": ["@esbuild/linux-arm@0.28.2", "", { "os": "linux", "cpu": "arm" }, "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w=="],
|
||||
|
||||
"@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.28.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug=="],
|
||||
|
||||
"@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.28.2", "", { "os": "linux", "cpu": "ia32" }, "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ=="],
|
||||
|
||||
"@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ=="],
|
||||
|
||||
"@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA=="],
|
||||
|
||||
"@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.28.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ=="],
|
||||
|
||||
"@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.28.2", "", { "os": "linux", "cpu": "none" }, "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA=="],
|
||||
|
||||
"@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.28.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg=="],
|
||||
|
||||
"@esbuild/linux-x64": ["@esbuild/linux-x64@0.28.2", "", { "os": "linux", "cpu": "x64" }, "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ=="],
|
||||
|
||||
"@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.28.2", "", { "os": "none", "cpu": "arm64" }, "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw=="],
|
||||
|
||||
"@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.28.2", "", { "os": "none", "cpu": "x64" }, "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw=="],
|
||||
|
||||
"@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.28.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ=="],
|
||||
|
||||
"@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.28.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw=="],
|
||||
|
||||
"@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.28.2", "", { "os": "none", "cpu": "arm64" }, "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q=="],
|
||||
|
||||
"@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.28.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g=="],
|
||||
|
||||
"@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.28.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ=="],
|
||||
|
||||
"@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.28.2", "", { "os": "win32", "cpu": "ia32" }, "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA=="],
|
||||
|
||||
"@esbuild/win32-x64": ["@esbuild/win32-x64@0.28.2", "", { "os": "win32", "cpu": "x64" }, "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g=="],
|
||||
|
||||
"@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="],
|
||||
|
||||
"@napi-rs/lzma-linux-x64-gnu": ["@napi-rs/lzma-linux-x64-gnu@1.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ=="],
|
||||
"@oxc-project/types": ["@oxc-project/types@0.153.0", "", {}, "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw=="],
|
||||
|
||||
"@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.13", "", { "os": "android", "cpu": "arm" }, "sha512-Vu/NICrgdRvUOeaJZIyB2FP63s6fO/4ud5l8dXmxDx9yDyn+mN0y+gsvsVviSli+T361Aqo0h46EuMoobrwawA=="],
|
||||
|
||||
"@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.13", "", { "os": "android", "cpu": "arm64" }, "sha512-6LEoIrGy5vvCd2boNnv2soPSUZj/PRvhp8R/t9KlX+mIZxThIE/ZqxrGXxmuNX0FuvQFvLdZr7S4HrYpYBVhEQ=="],
|
||||
|
||||
"@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.13", "", { "os": "darwin", "cpu": "arm64" }, "sha512-CaJSRzlQ6Q+zkDMVA9OkVxBjVoPRCDEE3v0FSJ9kIQBgRjFApA3Si4ijhbNVUji7ZJt+PfO0e46qy4nPInHUPA=="],
|
||||
|
||||
"@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.2.13", "", { "os": "darwin", "cpu": "x64" }, "sha512-e4r340I5hxSzJkD3YJBxgzq/rJ3wwxwdLLb2FPt1Zpyem20nrQPT11DDEEkazwxaHumH8wpglsp/Ozgj/wT6mw=="],
|
||||
|
||||
"@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.2.13", "", { "os": "freebsd", "cpu": "x64" }, "sha512-hoBWDZ4/K/mJKVMbsgUd1jfpA2DiOrJ54mpegObU9TBHBBrtX4FLIXJJQRDPZ/2Dn91GvPob+Z2hwKJzf4E5SQ=="],
|
||||
|
||||
"@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.2.13", "", { "os": "linux", "cpu": "arm" }, "sha512-oF9fZu3vTWnTiVAkDFxU9PJLt1nh20K9RRpuHsR7ZnE2L7XookBbDBVLojCVSLGbvtSlxeUNnjAj6DbNsKyzbg=="],
|
||||
|
||||
"@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.2.13", "", { "os": "linux", "cpu": "arm64" }, "sha512-DTpb/+jMiqWMPgphn4ksW1zW+XLJ6dJJ9FMvnIk9I291LhCctMPhMYJrP5t9p6C9qa3KXadDdUEZHBaPh3kNxQ=="],
|
||||
|
||||
"@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.2.13", "", { "os": "linux", "cpu": "arm64" }, "sha512-xU+Kvv9N2A3SY35zFh1FWWNjxbadE/BKeqnkXe7vScU4GZsw757BlVmDLITZEq8DPpk6m7uoDYkK7P+x/uU5Ow=="],
|
||||
|
||||
"@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.2.13", "", { "os": "linux", "cpu": "ppc64" }, "sha512-XMk/hnhh25oQ756Lclb1Q11h4ll0xC0Esa5w4Vzp+mAE2S3AGJgeM0SonrIgY8fHhjarb6hcoTuwoFG0VVP2ig=="],
|
||||
|
||||
"@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.2.13", "", { "os": "linux", "cpu": "s390x" }, "sha512-U1BoTHYmlywE2n3HUWjzZ+8EQsKr+OwpxYuDWaubx42tUL8QSL7nOqRz/NVHanibbFP3M1Rxuprz/wNcbMKjqw=="],
|
||||
|
||||
"@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.2.13", "", { "os": "linux", "cpu": "x64" }, "sha512-J4cm80Pc6wEwV5AZ42o62sIQgDk+Y7R2s646jIwuvO+4V46QB58N4vVuMPWCBaNgursXLpmUWJV//WQAkPvHBQ=="],
|
||||
|
||||
"@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.2.13", "", { "os": "linux", "cpu": "x64" }, "sha512-W0euZS40U4V6JkmEnVCIX9mcsL6cbXQ4X8c2w+MMOIjFg68TXUW+u3RT+2e1t1pv9mg/EP3pDtK3POXdQ7Rxyw=="],
|
||||
|
||||
"@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.2.13", "", { "os": "none", "cpu": "arm64" }, "sha512-do/AF/4n9MRshia3a5aXoy8xM2c6mgfT6D7H/dY6my5z+hfCIR4ab7mk4IRj++nsEQpKy39kd0DQnDq+r692tw=="],
|
||||
|
||||
"@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.2.13", "", { "os": "win32", "cpu": "arm64" }, "sha512-6FtUf2cJZobutJdxnGYX8z0vtbgqU0b2v8vfBhkXb9wp2MppMFtkunE+IaOntyi01rkIQoPW2GHABtfzsC0BRQ=="],
|
||||
|
||||
"@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.13", "", { "os": "win32", "cpu": "x64" }, "sha512-UKhFaZTeTcbKrb3iU82m17jVcPEAoqDkCN5MBqgPyZSwp/cQmib21crTS0DdH7T1B7wZRWEI89YQAOJMet5yhg=="],
|
||||
|
||||
"@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],
|
||||
|
||||
"@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.64.3", "", { "os": "android", "cpu": "arm" }, "sha512-a31GFbL70GlGUGhn8goVjRLtdDG1urLCJFWLZ7JcxdHK9pPvCohLFtYLgJDdNbtrNZSrJl1u9bK05ISsSC2EpA=="],
|
||||
|
||||
"@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.64.3", "", { "os": "android", "cpu": "arm64" }, "sha512-IRv757RLiPGlNxAX5JXU0eiUlUPvKiwFRbkqLd+gywptLK4uSEg1qkl6en6r0cXMazSnWUWOBABv+QfuLV3n5Q=="],
|
||||
|
||||
"@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.64.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-UkzI35Fnz6+MJNATdnjnZ3TpdG/rXab8h7oDOD9R0zDVIFmuuYrvgUj8V8mh+A//+LR4TlEQo4ZW4RhyRtWv3A=="],
|
||||
|
||||
"@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.64.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-C3AyMtAnKQ/jSkZ0chIoWbPXRbFz8JnPLhl1ULecEhcaOGkT19xt7KmO8BulQxt9S/XideHRXvsVQUbGj4JCOg=="],
|
||||
|
||||
"@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.64.3", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-M8yAdBMyHh14JLeXDNGvEkljzuHdcoLBQ399O4Fp4nvX51lueuEY/5U2G9Ci0D6/bQlBp/3JLiBQH55STwwbwg=="],
|
||||
|
||||
"@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.64.3", "", { "os": "freebsd", "cpu": "x64" }, "sha512-WQjuOKGh2FN98ZK6i0uM6M6YqnPEds85p3oRkrxiEeTQo/p7RpuU8c9MwQ88LfgwVAzohumlzbQQSikz4Zw9rw=="],
|
||||
|
||||
"@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.64.3", "", { "os": "linux", "cpu": "arm" }, "sha512-5tDLZG5s9WyVKoEHgwos6FpKrgpotl61EYeHSLSVkQzMzTsaClwEr8mok9rm3y734zjiGInG4dfw/56ebWVvEQ=="],
|
||||
|
||||
"@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.64.3", "", { "os": "linux", "cpu": "arm" }, "sha512-Mh5KbLeplM2HX6lQI18jsxSsqvPW8d+Hyk8HtY6Zl93woMitRSCZ92rBEzq6v8bfZGlpyMgj4P/sKW4KCjhH3A=="],
|
||||
|
||||
"@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.64.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-QZrrwHnznTv6y4iiHtCqDN+ZsF4qNFQObMOLgPrbxhh9O5o4rgoUe5OnkqG/ceCObMrAjhQt+eQ6HSDzBFgVMw=="],
|
||||
|
||||
"@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.64.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-4vLehpXSwlkltnvk5ETB+Hz+d3xayZS3NamZ5Vq4bSo+IUoIALovEJF1YgWPMjHwN7R5o/R4BpP9h3q8EK1xAA=="],
|
||||
|
||||
"@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.64.3", "", { "os": "linux", "cpu": "none" }, "sha512-SEN7TTTOdXJKZmsWKOnQeVfgy3Dje/08ISXWwFhTggQ3SxjuIaChvmOB5ZDZqJNlBjaXrV6nAHraqEAvdLGqcw=="],
|
||||
|
||||
"@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.64.3", "", { "os": "linux", "cpu": "none" }, "sha512-1LDsQMRMCEdGF9Dih5qyh6fF1LK3NnA+pAtE2+9AgZwUdXyd19TOBVC9crSB63iZBHR4vOG7h8gN/LcUH3J7xw=="],
|
||||
|
||||
"@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.64.3", "", { "os": "linux", "cpu": "ppc64" }, "sha512-v3D2tAfRriqGOi+5Ac5CiYbBo2NXtLVxJlludTvUZRj502lVMFeVIuvvWbz4qCrotn3e3Uvpvh7FcMpG2QxxXQ=="],
|
||||
|
||||
"@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.64.3", "", { "os": "linux", "cpu": "ppc64" }, "sha512-db5q6dP189V2+JkMpsXBl8ym6bC0x8ydZ47fUJZ9YdM6T2OF5uqNzX9HaAZHRP/lqjA9bJeNwi0qw1/2/37dUA=="],
|
||||
|
||||
"@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.64.3", "", { "os": "linux", "cpu": "none" }, "sha512-nArAVDmrL5ix9UoipcKEsYJw4kMUQCIPYRWuYF2POOC7jd9rmN95d/48ewsYFC/OdtwEx6VYYWYxrp8FbMOU2Q=="],
|
||||
|
||||
"@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.64.3", "", { "os": "linux", "cpu": "none" }, "sha512-2dc7LElu7EVSvpQT8epNnBLa02wlqilNYqHN0FA/RaKqCr9U9ZFYQ0Eh4sfgSzLneLDuJsJRjcezR/l2UyYGXA=="],
|
||||
|
||||
"@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.64.3", "", { "os": "linux", "cpu": "s390x" }, "sha512-9PYq2IEzSwXcvQLERcT9LKXRzw8J05GFTbJHA2anJR2WmlRjA1esgXVYhanp+bmjKsDVoZeU2L7Z2pRClLcZTw=="],
|
||||
|
||||
"@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.64.3", "", { "os": "linux", "cpu": "x64" }, "sha512-vMh+mt0cw1BHldd8cqaU6A5s1W4EUKl6+8MRsv86mj954L4xyruKD7qPXMUI2icImadAZARK10h0onaGTLmCVg=="],
|
||||
|
||||
"@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.64.3", "", { "os": "linux", "cpu": "x64" }, "sha512-PpiKU+sWbqDGc0U0su8oXiyeyqm0UQjmaaPKHktX+DaLe6YKJwW2YVD0f2AXHdVvblZbRqpwRVClWP2F5HCqrQ=="],
|
||||
|
||||
"@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.64.3", "", { "os": "openbsd", "cpu": "x64" }, "sha512-/3enY/AmaIt8IS0fWjX4ztYVPBqkj49cQTy/hCryhBFaEzDfJwwEolq9sxvyWAM2qmsmVuPdeRg5JXSrmeqvJg=="],
|
||||
|
||||
"@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.64.3", "", { "os": "none", "cpu": "arm64" }, "sha512-zsEP/QDuet52hhwvi5T1VPg0/Tkms0m3zkVv7CPsznvhdO4pL4oJTMz26EJsiCe18OeLKPgpTu3XVO3C1eq3ew=="],
|
||||
|
||||
"@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.64.3", "", { "os": "win32", "cpu": "arm64" }, "sha512-4ESknW4Db+kqvazVOfsReYJaHxcIsOqcgwjKV2J1tG5Bn4RVf5ocTQKSGuq2HWBJcOLuyim8IWX8DuH6nKmELA=="],
|
||||
|
||||
"@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.64.3", "", { "os": "win32", "cpu": "ia32" }, "sha512-3B8VCQyIyv7FQxYYhb3HpR3bIpronR20txjMSffSoz/sm/DDs3/49CFpEueOsvq9qW9sWoI/6pi6mtciD9NXFg=="],
|
||||
|
||||
"@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.64.3", "", { "os": "win32", "cpu": "x64" }, "sha512-YOoDkKh2oQxOxRB5D9AR8sj3qpMShpmyTkjojiBjMGigz3caV7UvCnXWWUQC0TBmrZ5zuHe2pWl8S+cMfvXzRg=="],
|
||||
|
||||
"@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.64.3", "", { "os": "win32", "cpu": "x64" }, "sha512-qTv4bG+eKJKifzxNJevMUh8L6CjJrz9/Kn1IbP2F5bo0tBzNIR7HMg4vni6XmDzcKUl00lHHY+J5ZgjbGiujOQ=="],
|
||||
|
||||
"@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="],
|
||||
"@types/node": ["@types/node@22.20.5", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA=="],
|
||||
|
||||
"@vitejs/plugin-vue": ["@vitejs/plugin-vue@6.0.9", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0", "vue": "^3.2.25" } }, "sha512-rD/MORlhaZMlXWW0rEn4FB4wMinWC0z/D7Ye160S5+Rs1mC8ZDAdcDp4SjKfUhG5t8q1ktcPVw4xuTkPRlzrSA=="],
|
||||
|
||||
"@volar/language-core": ["@volar/language-core@2.4.28", "", { "dependencies": { "@volar/source-map": "2.4.28" } }, "sha512-w4qhIJ8ZSitgLAkVay6AbcnC7gP3glYM3fYwKV3srj8m494E3xtrCv6E+bWviiK/8hs6e6t1ij1s2Endql7vzQ=="],
|
||||
|
||||
"@volar/source-map": ["@volar/source-map@2.4.28", "", {}, "sha512-yX2BDBqJkRXfKw8my8VarTyjv48QwxdJtvRgUpNE5erCsgEUdI2DsLbpa+rOQVAJYshY99szEcRDmyHbF10ggQ=="],
|
||||
|
||||
"@volar/typescript": ["@volar/typescript@2.4.28", "", { "dependencies": { "@volar/language-core": "2.4.28", "path-browserify": "^1.0.1", "vscode-uri": "^3.0.8" } }, "sha512-Ja6yvWrbis2QtN4ClAKreeUZPVYMARDYZl9LMEv1iQ1QdepB6wn0jTRxA9MftYmYa4DQ4k/DaSZpFPUfxl8giw=="],
|
||||
|
||||
"@vue/compiler-core": ["@vue/compiler-core@3.5.43", "", { "dependencies": { "@babel/parser": "^7.29.8", "@vue/shared": "3.5.43", "entities": "^7.0.1", "estree-walker": "^2.0.2", "source-map-js": "^1.2.1" } }, "sha512-zdiLhnbe1QQqgDT8xZMpNmyqZ3qlI+/Q/FHQco57Kwl/b05HhCzN6eVGN9QU9rbga4CrS0H5SYY8VGHZCt/1Hg=="],
|
||||
|
||||
"@vue/compiler-dom": ["@vue/compiler-dom@3.5.43", "", { "dependencies": { "@vue/compiler-core": "3.5.43", "@vue/shared": "3.5.43" } }, "sha512-PEZoAk3NQmsn/ejMzSOCyTYqwGqczrWm70PuhBKjjv1+TCoQAaO/zOqNwjV+honlNstT5ILxtc+8r8UUfj+iEQ=="],
|
||||
@@ -142,6 +79,8 @@
|
||||
|
||||
"@vue/compiler-ssr": ["@vue/compiler-ssr@3.5.43", "", { "dependencies": { "@vue/compiler-dom": "3.5.43", "@vue/shared": "3.5.43" } }, "sha512-GF62orf7KiJX9RqrHNGrYBudsQGD0OhJ5nDs90O8UiDuS40+YMYomiXu6w6EuvtXuRDc3MSNis3EaaSKAVSWpg=="],
|
||||
|
||||
"@vue/language-core": ["@vue/language-core@3.3.12", "", { "dependencies": { "@volar/language-core": "2.4.28", "@vue/compiler-dom": "^3.5.0", "@vue/shared": "^3.5.0", "alien-signals": "^3.2.1", "muggle-string": "^0.4.1", "path-browserify": "^1.0.1", "picomatch": "^4.0.4" } }, "sha512-k7uIKR0n4CBidk233y7cac9osnDQ5WRidTl6nsrNvpZ3nf8cx9iJxRVsRzVsoPRHbowT/iKgGMTS9RGov3jeIA=="],
|
||||
|
||||
"@vue/reactivity": ["@vue/reactivity@3.5.43", "", { "dependencies": { "@vue/shared": "3.5.43" } }, "sha512-G/c9GyOZNI2jVaaS6OX1EF1SSFSv7H0ERqNTl4+DTFMlZmB5eVAB53aLQNam/7NL2NPtaDD7RdVrzf8uJzMuOA=="],
|
||||
|
||||
"@vue/runtime-core": ["@vue/runtime-core@3.5.43", "", { "dependencies": { "@vue/reactivity": "3.5.43", "@vue/shared": "3.5.43" } }, "sha512-hU6U6VnVhBGQDpvlnnDlIB8ZGJBiOcgk2lh/0InltHiz3D8oSkluvuvY+do1G2H3+udeKFsmaBlgVYP7gXQzEw=="],
|
||||
@@ -152,11 +91,13 @@
|
||||
|
||||
"@vue/shared": ["@vue/shared@3.5.43", "", {}, "sha512-uksS7YGMR5NZyr4JNq0Rp+QyLns0ueaz20KwzIPW9R0LH1Vnt4E+XUM29PNseEbf1www2gOuhuDi5AKOIXag9Q=="],
|
||||
|
||||
"alien-signals": ["alien-signals@3.2.1", "", {}, "sha512-I8FjmltrfnDFoZedi5CG8DghVYNhzb/Ijluz7tCSJH0xpd0484Kowhbb1XDYOxfJpU1p5wnM2X54dA+IfGyD1g=="],
|
||||
|
||||
"csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
|
||||
|
||||
"entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
|
||||
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
|
||||
|
||||
"esbuild": ["esbuild@0.28.2", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="],
|
||||
"entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
|
||||
|
||||
"estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="],
|
||||
|
||||
@@ -164,24 +105,60 @@
|
||||
|
||||
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"lightningcss": ["lightningcss@1.33.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="],
|
||||
|
||||
"lightningcss-android-arm64": ["lightningcss-android-arm64@1.33.0", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="],
|
||||
|
||||
"lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.33.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg=="],
|
||||
|
||||
"lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.33.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ=="],
|
||||
|
||||
"lightningcss-freebsd-x64": ["lightningcss-freebsd-x64@1.33.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg=="],
|
||||
|
||||
"lightningcss-linux-arm-gnueabihf": ["lightningcss-linux-arm-gnueabihf@1.33.0", "", { "os": "linux", "cpu": "arm" }, "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ=="],
|
||||
|
||||
"lightningcss-linux-arm64-gnu": ["lightningcss-linux-arm64-gnu@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg=="],
|
||||
|
||||
"lightningcss-linux-arm64-musl": ["lightningcss-linux-arm64-musl@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ=="],
|
||||
|
||||
"lightningcss-linux-x64-gnu": ["lightningcss-linux-x64-gnu@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg=="],
|
||||
|
||||
"lightningcss-linux-x64-musl": ["lightningcss-linux-x64-musl@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw=="],
|
||||
|
||||
"lightningcss-win32-arm64-msvc": ["lightningcss-win32-arm64-msvc@1.33.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA=="],
|
||||
|
||||
"lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.33.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="],
|
||||
|
||||
"magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
|
||||
|
||||
"muggle-string": ["muggle-string@0.4.1", "", {}, "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ=="],
|
||||
|
||||
"nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="],
|
||||
|
||||
"path-browserify": ["path-browserify@1.0.1", "", {}, "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="],
|
||||
|
||||
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
|
||||
|
||||
"picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="],
|
||||
|
||||
"postcss": ["postcss@8.5.29", "", { "dependencies": { "nanoid": "^3.3.19", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ=="],
|
||||
|
||||
"rollup": ["rollup@4.64.3", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@napi-rs/lzma-linux-x64-gnu": "1.5.1", "@rollup/rollup-android-arm-eabi": "4.64.3", "@rollup/rollup-android-arm64": "4.64.3", "@rollup/rollup-darwin-arm64": "4.64.3", "@rollup/rollup-darwin-x64": "4.64.3", "@rollup/rollup-freebsd-arm64": "4.64.3", "@rollup/rollup-freebsd-x64": "4.64.3", "@rollup/rollup-linux-arm-gnueabihf": "4.64.3", "@rollup/rollup-linux-arm-musleabihf": "4.64.3", "@rollup/rollup-linux-arm64-gnu": "4.64.3", "@rollup/rollup-linux-arm64-musl": "4.64.3", "@rollup/rollup-linux-loong64-gnu": "4.64.3", "@rollup/rollup-linux-loong64-musl": "4.64.3", "@rollup/rollup-linux-ppc64-gnu": "4.64.3", "@rollup/rollup-linux-ppc64-musl": "4.64.3", "@rollup/rollup-linux-riscv64-gnu": "4.64.3", "@rollup/rollup-linux-riscv64-musl": "4.64.3", "@rollup/rollup-linux-s390x-gnu": "4.64.3", "@rollup/rollup-linux-x64-gnu": "4.64.3", "@rollup/rollup-linux-x64-musl": "4.64.3", "@rollup/rollup-openbsd-x64": "4.64.3", "@rollup/rollup-openharmony-arm64": "4.64.3", "@rollup/rollup-win32-arm64-msvc": "4.64.3", "@rollup/rollup-win32-ia32-msvc": "4.64.3", "@rollup/rollup-win32-x64-gnu": "4.64.3", "@rollup/rollup-win32-x64-msvc": "4.64.3", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-iIMWbptLYsZdGTJMH8ngApXdsCatE6bCMv2eqGIfGE1++kwh7TCWBdWKK0FKC0yx++196vGK5VdagzRXSLMa8A=="],
|
||||
"rolldown": ["rolldown@1.2.13", "", { "dependencies": { "@oxc-project/types": "=0.153.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.13", "@rolldown/binding-android-arm64": "1.2.13", "@rolldown/binding-darwin-arm64": "1.2.13", "@rolldown/binding-darwin-x64": "1.2.13", "@rolldown/binding-freebsd-x64": "1.2.13", "@rolldown/binding-linux-arm-gnueabihf": "1.2.13", "@rolldown/binding-linux-arm64-gnu": "1.2.13", "@rolldown/binding-linux-arm64-musl": "1.2.13", "@rolldown/binding-linux-ppc64-gnu": "1.2.13", "@rolldown/binding-linux-s390x-gnu": "1.2.13", "@rolldown/binding-linux-x64-gnu": "1.2.13", "@rolldown/binding-linux-x64-musl": "1.2.13", "@rolldown/binding-openharmony-arm64": "1.2.13", "@rolldown/binding-win32-arm64-msvc": "1.2.13", "@rolldown/binding-win32-x64-msvc": "1.2.13" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-/5apOkwWxtACcQtZ5WlrAsKS4JwXVThQPJZ3RqIruRY9UG9M8e0VlXN068xum/JRKA4aIUoJ13ghe/kGCvidiQ=="],
|
||||
|
||||
"source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="],
|
||||
|
||||
"tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],
|
||||
|
||||
"vite": ["vite@7.3.7", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-AHEzTORMbi7/7aXp7w7KZ5+DCUdSeLsJz0grY8xHpc9DHdYb0vQu6DqJfm2tOw3gDExNgPgnJTXxM6syYFHaCA=="],
|
||||
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
|
||||
|
||||
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"vite": ["vite@8.3.4", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.29", "rolldown": "~1.2.12", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-IftLE8phJhdNRIGNEV4JCCvfNScoZQVfcXaN8TQropWGJtOHcu+iAB9pHcuGvmEb/kddw0LBe/jS8ztdC6xdiQ=="],
|
||||
|
||||
"vscode-uri": ["vscode-uri@3.2.0", "", {}, "sha512-m2gXo3bn0G1kT9InzMf07fTbqMbGtyckj3bH5ktLO+1Ssv+yiATZ4dhwaQv9UZWxJh6E9IFGnQyjgWVDWVBDrg=="],
|
||||
|
||||
"vue": ["vue@3.5.43", "", { "dependencies": { "@vue/compiler-dom": "3.5.43", "@vue/compiler-sfc": "3.5.43", "@vue/runtime-dom": "3.5.43", "@vue/server-renderer": "3.5.43", "@vue/shared": "3.5.43" }, "peerDependencies": { "typescript": "*" }, "optionalPeers": ["typescript"] }, "sha512-o5qZoksdnjIKvW1srZ3ab7pcDNYAerBjRe54D0LBLfRdCYFrSgBHVXokMas35czQc0//lmx4/tuY4ZNQ+Rf2Ng=="],
|
||||
|
||||
"vue-tsc": ["vue-tsc@3.3.12", "", { "dependencies": { "@volar/typescript": "2.4.28", "@vue/language-core": "3.3.12" }, "peerDependencies": { "typescript": ">=5.0.0" }, "bin": { "vue-tsc": "bin/vue-tsc.js" } }, "sha512-kbpaz18O9jPVkXVHD1BEjpUXM6WhXSu+62L1sGGr6Wbzd8GbvkBQWjoj3KZ/C0aq2MZllce7UdtWzwCIYsBMGA=="],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# Linux development only. No boot startup or automatic container restart.
|
||||
services:
|
||||
coturn:
|
||||
image: coturn/coturn:4.18.0-r0-alpine
|
||||
network_mode: host
|
||||
restart: "no"
|
||||
command:
|
||||
- -n
|
||||
- --listening-ip=127.0.0.1
|
||||
- --relay-ip=127.0.0.1
|
||||
- --listening-port=${TURN_PORT:-3478}
|
||||
- --realm=hellcon.local
|
||||
- --use-auth-secret
|
||||
- --static-auth-secret=${TURN_SECRET:?Run bun run dev:setup first}
|
||||
- --fingerprint
|
||||
- --min-port=49160
|
||||
- --max-port=49200
|
||||
- --no-tls
|
||||
# DTLS is opt-in in coturn 4.18; leave it disabled.
|
||||
- --no-tcp-relay
|
||||
- --no-multicast-peers
|
||||
# Needed for two browsers relaying to each other on this machine.
|
||||
- --allow-loopback-peers
|
||||
- --no-cli
|
||||
- --no-software-attribute
|
||||
- --log-file=stdout
|
||||
tmpfs:
|
||||
- /var/lib/coturn
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "5m"
|
||||
max-file: "2"
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { IncomingMessage } from 'node:http';
|
||||
import { createHmac, randomUUID } from 'node:crypto';
|
||||
|
||||
interface IceResponse {
|
||||
setHeader(name: string, value: string): unknown;
|
||||
writeHead(status: number, headers?: Record<string, string>): unknown;
|
||||
end(body?: string): unknown;
|
||||
}
|
||||
|
||||
// Shared by Vite and the browser integration checks. Never imported by the client.
|
||||
export function iceMiddleware(env: NodeJS.ProcessEnv) {
|
||||
const secret = env.TURN_SECRET;
|
||||
if (!secret) throw new Error('TURN_SECRET is required. Run bun run dev:setup first.');
|
||||
const host = env.TURN_HOST || '127.0.0.1';
|
||||
const port = env.TURN_PORT || '3478';
|
||||
return (req: Pick<IncomingMessage, 'url' | 'method' | 'headers'>, res: IceResponse, next: () => void) => {
|
||||
if (req.url?.split('?')[0] !== '/api/ice-servers') return next();
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
if (req.method !== 'GET') {
|
||||
res.writeHead(405, { Allow: 'GET' }); res.end(); return;
|
||||
}
|
||||
if (req.headers['sec-fetch-site'] === 'cross-site' ||
|
||||
(req.headers.origin && req.headers.origin !== `http://${req.headers.host}`)) {
|
||||
res.writeHead(403); res.end(); return;
|
||||
}
|
||||
const expiresAt = Math.floor(Date.now() / 1000) + 3600;
|
||||
const username = `${expiresAt}:${randomUUID()}`;
|
||||
const credential = createHmac('sha1', secret).update(username).digest('base64');
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
res.end(JSON.stringify({ expiresAt, iceServers: [
|
||||
{ urls: `stun:${host}:${port}` },
|
||||
{ urls: [`turn:${host}:${port}?transport=udp`, `turn:${host}:${port}?transport=tcp`], username, credential },
|
||||
] }));
|
||||
};
|
||||
}
|
||||
+1
-1
@@ -10,6 +10,6 @@
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
+16
-5
@@ -6,17 +6,28 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"dev:setup": "node scripts/dev-setup.ts",
|
||||
"turn:up": "docker compose --env-file .env.development up -d",
|
||||
"turn:down": "docker compose --env-file .env.development down",
|
||||
"test:turn": "node scripts/browser-check.ts --turn",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"preview": "vite preview",
|
||||
"test": "node --test",
|
||||
"test:browser": "node scripts/browser-check.mjs",
|
||||
"test:cross-browser": "node scripts/cross-browser-check.mjs"
|
||||
"test": "node --test tests/*.test.ts",
|
||||
"test:browser": "node scripts/browser-check.ts",
|
||||
"test:cross-browser": "node scripts/cross-browser-check.ts",
|
||||
"typecheck": "vue-tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"vue": "^3.5.43"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22",
|
||||
"@vitejs/plugin-vue": "^6.0.9",
|
||||
"vite": "^7.3.7"
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^8",
|
||||
"vue-tsc": "^3.3.12"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.18.0"
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
// Dependency-free Chromium integration check. Run after `bun run build`.
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { createServer } from 'node:http';
|
||||
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, extname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const provider = process.argv.includes('--default-network') ? 'google' : 'none';
|
||||
const profile = await mkdtemp(join(tmpdir(), 'hellcon-browser-'));
|
||||
const server = createServer(async (req, res) => {
|
||||
try {
|
||||
const pathname = new URL(req.url, 'http://localhost').pathname;
|
||||
const base = pathname.startsWith('/src/lib/') ? root : join(root, 'dist');
|
||||
const path = resolve(base, '.' + (pathname === '/' ? '/index.html' : pathname));
|
||||
if (!path.startsWith(base + '/')) throw new Error('Invalid path');
|
||||
const types = { '.js': 'text/javascript', '.css': 'text/css', '.html': 'text/html', '.png': 'image/png' };
|
||||
res.setHeader('Content-Type', types[extname(path)] || 'application/octet-stream');
|
||||
res.end(await readFile(path));
|
||||
} catch { res.statusCode = 404; res.end(); }
|
||||
});
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
const origin = `http://127.0.0.1:${server.address().port}`;
|
||||
const browser = spawn(process.env.CHROMIUM_PATH || '/usr/bin/chromium', [
|
||||
'--headless', '--no-sandbox', '--disable-gpu', '--disable-background-networking',
|
||||
'--no-first-run', '--no-default-browser-check', `--user-data-dir=${profile}`, '--remote-debugging-pipe', 'about:blank',
|
||||
], { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'] });
|
||||
let stderr = '', nextId = 0, buffer = '';
|
||||
const pending = new Map();
|
||||
const browserErrors = [];
|
||||
browser.stderr.on('data', data => { stderr += data; });
|
||||
browser.stdio[3].on('error', () => {}); browser.stdio[4].on('error', () => {});
|
||||
browser.stdio[4].on('data', data => {
|
||||
buffer += data;
|
||||
let end;
|
||||
while ((end = buffer.indexOf('\0')) !== -1) {
|
||||
const message = JSON.parse(buffer.slice(0, end)); buffer = buffer.slice(end + 1);
|
||||
if (message.id) { pending.get(message.id)?.(message); pending.delete(message.id); }
|
||||
if (message.method === 'Runtime.exceptionThrown') browserErrors.push(message.params.exceptionDetails);
|
||||
}
|
||||
});
|
||||
function call(method, params = {}, sessionId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = ++nextId;
|
||||
const timer = setTimeout(() => { pending.delete(id); reject(new Error(`Timed out: ${method}\n${stderr.slice(-1500)}`)); }, 45000);
|
||||
pending.set(id, message => { clearTimeout(timer); message.error ? reject(new Error(JSON.stringify(message.error))) : resolve(message.result); });
|
||||
browser.stdio[3].write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + '\0');
|
||||
});
|
||||
}
|
||||
async function evaluate(session, expression) {
|
||||
const result = await call('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, session);
|
||||
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
|
||||
return result.result.value;
|
||||
}
|
||||
async function wait(session, expression) {
|
||||
return evaluate(session, `(async () => { for (let n = 0; n < 1800; n++) { if (${expression}) return true; await new Promise(r => setTimeout(r, 20)); } throw new Error('UI condition timed out: ' + ${JSON.stringify(expression)} + '\\n' + document.body.innerText); })()`);
|
||||
}
|
||||
async function page() {
|
||||
const { targetId } = await call('Target.createTarget', { url: 'about:blank' });
|
||||
const { sessionId } = await call('Target.attachToTarget', { targetId, flatten: true });
|
||||
await call('Runtime.enable', {}, sessionId);
|
||||
await call('Page.enable', {}, sessionId);
|
||||
await call('Page.navigate', { url: origin }, sessionId);
|
||||
for (let n = 0; n < 100; n++) {
|
||||
try { if (await evaluate(sessionId, `location.origin === ${JSON.stringify(origin)} && document.readyState === 'complete'`)) break; }
|
||||
catch (err) { if (!err.message.includes('context')) throw err; }
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
}
|
||||
await wait(sessionId, "!!document.querySelector('#stun-provider')");
|
||||
return sessionId;
|
||||
}
|
||||
const click = (session, label) => evaluate(session, `(() => { const b = [...document.querySelectorAll('button')].find(b => b.textContent.trim() === ${JSON.stringify(label)}); if (!b || b.disabled) throw new Error('Unavailable button: ' + ${JSON.stringify(label)}); b.click(); })()`);
|
||||
const input = (session, selector, value) => evaluate(session, `(() => { const el = document.querySelector(${JSON.stringify(selector)}); el.value = ${JSON.stringify(value)}; el.dispatchEvent(new Event(el.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true })); })()`);
|
||||
async function connect(sender, receiver, size) {
|
||||
await evaluate(sender, `(() => { const input = document.querySelector('#file-input'); const files = new DataTransfer(); files.items.add(new File([new Uint8Array(${size}).fill(123)], 'browser-test.bin')); input.files = files.files; input.dispatchEvent(new Event('change', { bubbles: true })); })()`);
|
||||
await input(sender, '#stun-provider', provider);
|
||||
await input(receiver, '#stun-provider', provider);
|
||||
await click(sender, 'Create code'); await wait(sender, "!!document.querySelector('#output-code')");
|
||||
const offer = await evaluate(sender, "document.querySelector('#output-code').value");
|
||||
await input(receiver, '#offer-input', 'invalid-code!');
|
||||
await click(receiver, 'Accept & create answer');
|
||||
await wait(receiver, "!!document.querySelector('[role=alert]')");
|
||||
assert.equal(await evaluate(receiver, "document.querySelector('#offer-input').disabled"), false);
|
||||
await input(receiver, '#offer-input', offer); await click(receiver, 'Accept & create answer');
|
||||
await wait(receiver, "!!document.querySelector('#output-code')");
|
||||
const answer = await evaluate(receiver, "document.querySelector('#output-code').value");
|
||||
await input(sender, '#answer-input', 'invalid-answer!'); await click(sender, 'Connect');
|
||||
await wait(sender, "!!document.querySelector('[role=alert]')");
|
||||
assert.equal(await evaluate(sender, "document.querySelector('#output-code')?.value"), offer);
|
||||
assert.equal(await evaluate(sender, "document.querySelector('#answer-input').disabled"), false);
|
||||
await input(sender, '#answer-input', answer); await click(sender, 'Connect');
|
||||
await wait(sender, "!!document.querySelector('.fingerprint')");
|
||||
const sf = await evaluate(sender, "[...document.querySelectorAll('.fp-row code')].map(e => e.textContent)");
|
||||
const rf = await evaluate(receiver, "[...document.querySelectorAll('.fp-row code')].map(e => e.textContent)");
|
||||
assert.equal(sf[0], rf[1]); assert.equal(sf[1], rf[0]); assert.equal(sf[0].split(' ').length, 32);
|
||||
assert.equal(await evaluate(receiver, "!!document.querySelector('.incoming')"), false);
|
||||
await click(sender, 'Both fingerprints match — confirm');
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
assert.equal(await evaluate(receiver, "!!document.querySelector('.incoming')"), false);
|
||||
await click(receiver, 'Both fingerprints match — confirm');
|
||||
await wait(receiver, "!!document.querySelector('.incoming')");
|
||||
}
|
||||
try {
|
||||
const sender = await page(), receiver = await page();
|
||||
await click(receiver, 'Receive');
|
||||
assert.equal(await evaluate(sender, "document.querySelector('.checkbox input').checked"), false);
|
||||
await connect(sender, receiver, 2 * 1024 * 1024 + 7);
|
||||
await click(receiver, 'Receive in memory (up to 64 MiB)');
|
||||
await wait(sender, "document.querySelector('[role=status]').textContent.includes('confirmed the complete file')");
|
||||
const data = await evaluate(receiver, `(async () => { const response = await fetch(document.querySelector('a.download').href); const bytes = new Uint8Array(await response.arrayBuffer()); return { length: bytes.length, valid: bytes.every(b => b === 123) }; })()`);
|
||||
assert.deepEqual(data, { length: 2 * 1024 * 1024 + 7, valid: true });
|
||||
console.log('PASS: real two-page WebRTC flow; full fingerprints; no metadata before both confirmations; exact file and receipt.');
|
||||
console.log('PASS: invalid offers can be replaced; invalid answers can be corrected without losing the live offer.');
|
||||
await click(sender, 'Reset'); await click(receiver, 'Reset');
|
||||
assert.equal(await evaluate(sender, "document.querySelector('[role=status]').textContent"), 'Choose a file to start.');
|
||||
assert.equal(await evaluate(receiver, "document.querySelector('[role=status]').textContent"), 'Paste the sender’s connection code to start.');
|
||||
console.log('PASS: Reset restores the ready state on both sides.');
|
||||
await evaluate(receiver, `window.__aborted = false; window.showSaveFilePicker = async () => ({ createWritable: async () => ({ write() { return new Promise(resolve => { window.__releaseWrite = resolve; }); }, async close() {}, async abort() { window.__aborted = true; window.__releaseWrite?.(); } }) });`);
|
||||
await connect(sender, receiver, 2 * 1024 * 1024);
|
||||
await click(receiver, 'Choose destination & receive to disk');
|
||||
await wait(receiver, '!!window.__releaseWrite');
|
||||
await click(sender, 'Receive');
|
||||
await wait(receiver, 'window.__aborted === true');
|
||||
assert.equal(await evaluate(receiver, "!!document.querySelector('a.download')"), false);
|
||||
console.log('PASS: switching away from Send closes the connection and aborts the receiver’s pending disk write.');
|
||||
await click(sender, 'Send'); await click(receiver, 'Reset');
|
||||
await connect(sender, receiver, 2048);
|
||||
await click(receiver, 'Receive in memory (up to 64 MiB)');
|
||||
await wait(sender, "document.querySelector('[role=status]').textContent.includes('confirmed the complete file')");
|
||||
console.log('PASS: fresh code exchange after a failed transfer succeeds without reloading either page.');
|
||||
assert.deepEqual(browserErrors, []);
|
||||
} finally {
|
||||
browser.kill();
|
||||
await new Promise(resolve => { if (browser.exitCode !== null) resolve(); else browser.once('exit', resolve); });
|
||||
await new Promise(resolve => server.close(resolve));
|
||||
await rm(profile, { recursive: true, force: true, maxRetries: 3 });
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// Dependency-free Chromium integration check. Run after `bun run build`.
|
||||
import { Readable, Writable } from 'node:stream';
|
||||
import { installBrowserContext, forceRelay, relayCandidateTypes, simulateSlowDisk } from './browser-context.ts';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { createServer } from 'node:http';
|
||||
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, extname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const provider = process.argv.includes('--default-network') ? 'google' : 'none';
|
||||
const turn = process.argv.includes('--turn');
|
||||
const transport = process.argv.includes('--tcp') ? 'tcp' : 'udp';
|
||||
const vite = turn ? await (await import('vite')).createServer({ server: { middlewareMode: true }, appType: 'spa' }) : null;
|
||||
const profile = await mkdtemp(join(tmpdir(), 'hellcon-browser-'));
|
||||
const server = createServer(async (req, res) => {
|
||||
if (vite) return vite.middlewares(req, res);
|
||||
try {
|
||||
const pathname = new URL(req.url ?? '/', 'http://localhost').pathname;
|
||||
const base = join(root, 'dist');
|
||||
const path = resolve(base, '.' + (pathname === '/' ? '/index.html' : pathname));
|
||||
if (!path.startsWith(base + '/')) throw new Error('Invalid path');
|
||||
const types: Record<string, string> = { '.js': 'text/javascript', '.css': 'text/css', '.html': 'text/html', '.png': 'image/png' };
|
||||
res.setHeader('Content-Type', types[extname(path)] || 'application/octet-stream');
|
||||
res.end(await readFile(path));
|
||||
} catch { res.statusCode = 404; res.end(); }
|
||||
});
|
||||
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address !== 'string');
|
||||
const origin = `http://127.0.0.1:${address.port}`;
|
||||
const browser = spawn(process.env.CHROMIUM_PATH || '/usr/bin/chromium', [
|
||||
'--headless', '--no-sandbox', '--disable-gpu', '--disable-background-networking',
|
||||
'--no-first-run', '--no-default-browser-check', `--user-data-dir=${profile}`, '--remote-debugging-pipe', 'about:blank',
|
||||
], { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'] });
|
||||
interface ProtocolResults {
|
||||
'Target.createTarget': { targetId: string };
|
||||
'Target.attachToTarget': { sessionId: string };
|
||||
'Runtime.enable': object;
|
||||
'Page.enable': object;
|
||||
'Page.navigate': object;
|
||||
'Page.addScriptToEvaluateOnNewDocument': object;
|
||||
'Runtime.evaluate': { exceptionDetails?: unknown; result: { value?: unknown } };
|
||||
}
|
||||
interface ProtocolMessage {
|
||||
id?: number;
|
||||
method?: string;
|
||||
params?: { exceptionDetails?: unknown };
|
||||
error?: unknown;
|
||||
result?: unknown;
|
||||
}
|
||||
const pipeIn = browser.stdio[3], pipeOut = browser.stdio[4];
|
||||
assert.ok(pipeIn instanceof Writable && pipeOut instanceof Readable && browser.stderr);
|
||||
const commandPipe = pipeIn;
|
||||
let stderr = '', nextId = 0, buffer = '';
|
||||
const pending = new Map<number, (message: ProtocolMessage) => void>();
|
||||
const browserErrors: unknown[] = [];
|
||||
browser.stderr.on('data', data => { stderr += data; });
|
||||
pipeIn.on('error', () => {}); pipeOut.on('error', () => {});
|
||||
pipeOut.on('data', data => {
|
||||
buffer += data;
|
||||
let end;
|
||||
while ((end = buffer.indexOf('\0')) !== -1) {
|
||||
const message: ProtocolMessage = JSON.parse(buffer.slice(0, end)); buffer = buffer.slice(end + 1);
|
||||
if (message.id) { pending.get(message.id)?.(message); pending.delete(message.id); }
|
||||
if (message.method === 'Runtime.exceptionThrown') browserErrors.push(message.params?.exceptionDetails);
|
||||
}
|
||||
});
|
||||
function call<M extends keyof ProtocolResults>(method: M, params: Record<string, unknown> = {}, sessionId?: string): Promise<ProtocolResults[M]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = ++nextId;
|
||||
const timer = setTimeout(() => { pending.delete(id); reject(new Error(`Timed out: ${method}\n${stderr.slice(-1500)}`)); }, 45000);
|
||||
pending.set(id, message => { clearTimeout(timer); message.error ? reject(new Error(JSON.stringify(message.error))) : resolve(message.result as ProtocolResults[M]); });
|
||||
commandPipe.write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + '\0');
|
||||
});
|
||||
}
|
||||
async function evaluate<T, Args extends unknown[]>(session: string, fn: (...args: Args) => T, ...args: Args): Promise<Awaited<T>> {
|
||||
const expression = `(${fn.toString()})(...${JSON.stringify(args)})`;
|
||||
const result = await call('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, session);
|
||||
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
|
||||
// CDP returns the serialized result of this exact callback.
|
||||
return result.result.value as Awaited<T>;
|
||||
}
|
||||
async function wait(session: string, check: () => unknown) {
|
||||
const expression = `window.__hellcon.wait(${check.toString()})`;
|
||||
const result = await call('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, session);
|
||||
if (result.exceptionDetails) throw new Error(JSON.stringify(result.exceptionDetails));
|
||||
}
|
||||
async function page() {
|
||||
const { targetId } = await call('Target.createTarget', { url: 'about:blank' });
|
||||
const { sessionId } = await call('Target.attachToTarget', { targetId, flatten: true });
|
||||
await call('Runtime.enable', {}, sessionId);
|
||||
await call('Page.enable', {}, sessionId);
|
||||
await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${installBrowserContext.toString()})()` }, sessionId);
|
||||
if (turn) await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${forceRelay.toString()})(${JSON.stringify(transport)})` }, sessionId);
|
||||
await call('Page.navigate', { url: origin }, sessionId);
|
||||
for (let n = 0; n < 100; n++) {
|
||||
try { if (await evaluate(sessionId, (expected: string) => location.origin === expected && document.readyState === 'complete', origin)) break; }
|
||||
catch (err) { if (!(err instanceof Error) || !err.message.includes('context')) throw err; }
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
}
|
||||
await wait(sessionId, () => !!document.querySelector('#stun-provider'));
|
||||
return sessionId;
|
||||
}
|
||||
const click = (session: string, label: string) => evaluate(session, (label: string) => window.__hellcon.click(label), label);
|
||||
const input = (session: string, selector: string, value: string) => evaluate(session, (selector: string, value: string) => window.__hellcon.input(selector, value), selector, value);
|
||||
const enableTurn = (session: string) => evaluate(session, () => {
|
||||
const checkbox = window.__hellcon.element<HTMLInputElement>('.checkbox input');
|
||||
if (!checkbox.checked) checkbox.click();
|
||||
});
|
||||
async function connect(sender: string, receiver: string, size: number) {
|
||||
await evaluate(sender, (size: number) => window.__hellcon.chooseFile(size, 'browser-test.bin'), size);
|
||||
await input(sender, '#stun-provider', provider);
|
||||
await input(receiver, '#stun-provider', provider);
|
||||
if (turn) { await enableTurn(sender); await enableTurn(receiver); }
|
||||
await click(sender, 'Create code'); await wait(sender, () => !!document.querySelector('#output-code'));
|
||||
const offer = await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
|
||||
await input(receiver, '#offer-input', 'invalid-code!');
|
||||
await click(receiver, 'Accept & create answer');
|
||||
await wait(receiver, () => !!document.querySelector('[role=alert]'));
|
||||
assert.equal(await evaluate(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#offer-input').disabled), false);
|
||||
if (turn) await enableTurn(receiver);
|
||||
await input(receiver, '#offer-input', offer); await click(receiver, 'Accept & create answer');
|
||||
await wait(receiver, () => !!document.querySelector('#output-code'));
|
||||
const answer = await evaluate(receiver, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code').value);
|
||||
await input(sender, '#answer-input', 'invalid-answer!'); await click(sender, 'Connect');
|
||||
await wait(sender, () => !!document.querySelector('[role=alert]'));
|
||||
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#output-code')?.value), offer);
|
||||
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#answer-input').disabled), false);
|
||||
await input(sender, '#answer-input', answer); await click(sender, 'Connect');
|
||||
await wait(sender, () => !!document.querySelector('.fingerprint'));
|
||||
const sf = await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent));
|
||||
const rf = await evaluate(receiver, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent));
|
||||
assert.equal(sf[0], rf[1]); assert.equal(sf[1], rf[0]); assert.equal(sf[0]?.split(' ').length, 32);
|
||||
assert.equal(await evaluate(receiver, () => !!document.querySelector('.incoming')), false);
|
||||
await click(sender, 'Both fingerprints match — confirm');
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
assert.equal(await evaluate(receiver, () => !!document.querySelector('.incoming')), false);
|
||||
await click(receiver, 'Both fingerprints match — confirm');
|
||||
await wait(receiver, () => !!document.querySelector('.incoming'));
|
||||
if (turn) {
|
||||
for (const session of [sender, receiver]) {
|
||||
const types = await evaluate(session, relayCandidateTypes);
|
||||
assert.deepEqual(types, ['relay', 'relay'], 'Both ends must actually use relay candidates');
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
const sender = await page(), receiver = await page();
|
||||
await click(receiver, 'Receive');
|
||||
assert.equal(await evaluate(sender, () => window.__hellcon.element<HTMLInputElement>('.checkbox input').checked), false);
|
||||
await connect(sender, receiver, 2 * 1024 * 1024 + 7);
|
||||
await click(receiver, 'Receive in memory (up to 64 MiB)');
|
||||
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
|
||||
const data = await evaluate(receiver, async () => {
|
||||
const response = await fetch(window.__hellcon.element<HTMLAnchorElement>('a.download').href);
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
return { length: bytes.length, valid: bytes.every(b => b === 123) };
|
||||
});
|
||||
assert.deepEqual(data, { length: 2 * 1024 * 1024 + 7, valid: true });
|
||||
console.log('PASS: real two-page WebRTC flow; full fingerprints; no metadata before both confirmations; exact file and receipt.');
|
||||
console.log('PASS: invalid offers can be replaced; invalid answers can be corrected without losing the live offer.');
|
||||
await click(sender, 'Reset'); await click(receiver, 'Reset');
|
||||
assert.equal(await evaluate(sender, () => window.__hellcon.element('[role=status]').textContent), 'Choose a file to start.');
|
||||
assert.equal(await evaluate(receiver, () => window.__hellcon.element('[role=status]').textContent), 'Paste the sender’s connection code to start.');
|
||||
console.log('PASS: Reset restores the ready state on both sides.');
|
||||
await evaluate(receiver, simulateSlowDisk);
|
||||
await connect(sender, receiver, 2 * 1024 * 1024);
|
||||
await click(receiver, 'Choose destination & receive to disk');
|
||||
await wait(receiver, () => !!window.__hellcon.releaseWrite);
|
||||
await click(sender, 'Receive');
|
||||
await wait(receiver, () => window.__hellcon.aborted);
|
||||
assert.equal(await evaluate(receiver, () => !!document.querySelector('a.download')), false);
|
||||
console.log('PASS: switching away from Send closes the connection and aborts the receiver’s pending disk write.');
|
||||
await click(sender, 'Send'); await click(receiver, 'Reset');
|
||||
await connect(sender, receiver, 2048);
|
||||
await click(receiver, 'Receive in memory (up to 64 MiB)');
|
||||
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
|
||||
console.log('PASS: fresh code exchange after a failed transfer succeeds without reloading either page.');
|
||||
if (turn) console.log(`PASS: forced TURN over ${transport.toUpperCase()}, relay candidates at both ends, exact file bytes and receipt.`);
|
||||
assert.deepEqual(browserErrors, []);
|
||||
} finally {
|
||||
browser.kill();
|
||||
await new Promise<void>(resolve => { if (browser.exitCode !== null || browser.signalCode !== null) resolve(); else browser.once('exit', () => resolve()); });
|
||||
await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
||||
await vite?.close();
|
||||
await rm(profile, { recursive: true, force: true, maxRetries: 3 });
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// These functions are serialized into isolated browser pages by the checks.
|
||||
// Keep their dependencies inside the function or on window.__hellcon.
|
||||
export function installBrowserContext() {
|
||||
function element<E extends Element>(selector: string): E {
|
||||
const value = document.querySelector<E>(selector);
|
||||
if (!value) throw new Error(`Missing element: ${selector}`);
|
||||
return value;
|
||||
}
|
||||
const context = {
|
||||
element,
|
||||
peers: [] as RTCPeerConnection[],
|
||||
aborted: false,
|
||||
releaseWrite: undefined as (() => void) | undefined,
|
||||
click(label: string) {
|
||||
const button = [...document.querySelectorAll('button')].find(button => button.textContent?.trim() === label);
|
||||
if (!button || button.disabled) throw new Error(`Unavailable button: ${label}`);
|
||||
button.click();
|
||||
},
|
||||
input(selector: string, value: string) {
|
||||
const input = element<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(selector);
|
||||
input.value = value;
|
||||
input.dispatchEvent(new Event(input.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true }));
|
||||
},
|
||||
chooseFile(size: number, name: string) {
|
||||
const input = element<HTMLInputElement>('#file-input');
|
||||
const files = new DataTransfer();
|
||||
files.items.add(new File([new Uint8Array(size).fill(123)], name));
|
||||
input.files = files.files;
|
||||
input.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
},
|
||||
async wait<T>(check: () => T | Promise<T>): Promise<NonNullable<Awaited<T>>> {
|
||||
const deadline = Date.now() + 36000;
|
||||
while (Date.now() < deadline) {
|
||||
const value = await check();
|
||||
if (value) return value;
|
||||
await new Promise<void>(resolve => setTimeout(resolve, 20));
|
||||
}
|
||||
throw new Error('UI condition timed out: ' + document.body.innerText);
|
||||
},
|
||||
};
|
||||
window.__hellcon = context;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__hellcon: {
|
||||
element<E extends Element>(selector: string): E;
|
||||
peers: RTCPeerConnection[];
|
||||
aborted: boolean;
|
||||
releaseWrite?: () => void;
|
||||
click(label: string): void;
|
||||
input(selector: string, value: string): void;
|
||||
chooseFile(size: number, name: string): void;
|
||||
wait<T>(check: () => T | Promise<T>): Promise<NonNullable<Awaited<T>>>;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function forceRelay(transport: 'udp' | 'tcp') {
|
||||
const NativePC = window.RTCPeerConnection;
|
||||
window.RTCPeerConnection = class extends NativePC {
|
||||
constructor(config?: RTCConfiguration) {
|
||||
super({ ...config, iceTransportPolicy: 'relay' });
|
||||
window.__hellcon.peers.push(this);
|
||||
}
|
||||
override setConfiguration(config: RTCConfiguration) {
|
||||
const iceServers = (config.iceServers ?? []).filter(server => server.username).map(server => ({
|
||||
...server,
|
||||
urls: (Array.isArray(server.urls) ? server.urls : [server.urls]).filter(url => url.endsWith(`transport=${transport}`)),
|
||||
}));
|
||||
super.setConfiguration({ ...config, iceServers, iceTransportPolicy: 'relay' });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export async function relayCandidateTypes() {
|
||||
for (let attempt = 0; attempt < 50; attempt++) {
|
||||
const pc = window.__hellcon.peers.at(-1);
|
||||
if (!pc) throw new Error('No peer connection');
|
||||
const stats = await pc.getStats();
|
||||
const transport = [...stats.values()].find((entry: RTCStats) => entry.type === 'transport') as RTCTransportStats | undefined;
|
||||
const pair = transport?.selectedCandidatePairId ? stats.get(transport.selectedCandidatePairId) as RTCIceCandidatePairStats | undefined : undefined;
|
||||
if (pair) {
|
||||
const local = stats.get(pair.localCandidateId) as (RTCStats & { candidateType: RTCIceCandidateType }) | undefined;
|
||||
const remote = stats.get(pair.remoteCandidateId) as (RTCStats & { candidateType: RTCIceCandidateType }) | undefined;
|
||||
return [local?.candidateType, remote?.candidateType];
|
||||
}
|
||||
await new Promise<void>(resolve => setTimeout(resolve, 100));
|
||||
}
|
||||
throw new Error('No selected ICE candidate pair in WebRTC statistics');
|
||||
}
|
||||
|
||||
export function simulateSlowDisk() {
|
||||
window.__hellcon.aborted = false;
|
||||
// Only the methods used by the app are implemented by this browser test double.
|
||||
window.showSaveFilePicker = async () => ({
|
||||
createWritable: async () => ({
|
||||
write() { return new Promise<void>(resolve => { window.__hellcon.releaseWrite = resolve; }); },
|
||||
async close() {},
|
||||
async abort() { window.__hellcon.aborted = true; window.__hellcon.releaseWrite?.(); },
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
// Exercises the built Vue app in separate Brave and Firefox processes.
|
||||
import { createServer } from 'node:http';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { readFile, mkdtemp, rm } from 'node:fs/promises';
|
||||
import { dirname, extname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { tmpdir } from 'node:os';
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const state = {};
|
||||
const profiles = [];
|
||||
const children = [];
|
||||
const provider = process.argv.includes('--default-network') ? 'google' : 'none';
|
||||
const reversed = process.argv.includes('--reverse');
|
||||
const driver = `
|
||||
const role = new URL(location.href).searchParams.get('role');
|
||||
const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
const post = async (key, value) => fetch('/.test/' + key, {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(value)});
|
||||
const get = async key => (await fetch('/.test/' + key)).json();
|
||||
const wait = async fn => { const deadline=Date.now()+36000; while(Date.now()<deadline){ const value = await fn(); if(value) return value; const error=document.querySelector('[role=alert]'); if(error) throw new Error(error.textContent); await pause(20); } throw new Error('Timed out: '+document.querySelector('[role=status]')?.textContent); };
|
||||
const click = text => { const button=[...document.querySelectorAll('button')].find(b=>b.textContent.trim()===text); if(!button || button.disabled)throw new Error('Unavailable: '+text); button.click(); };
|
||||
const input = (selector,value) => { const el=document.querySelector(selector); el.value=value; el.dispatchEvent(new Event(el.tagName==='SELECT'?'change':'input',{bubbles:true})); };
|
||||
const stage = async text => post(role+'Stage', text);
|
||||
const peers=[]; const NativePC=window.RTCPeerConnection;
|
||||
window.RTCPeerConnection = class extends NativePC { constructor(...args){super(...args);peers.push(this);} };
|
||||
setInterval(()=>post(role+'Diagnostic',{status:document.querySelector('[role=status]')?.textContent,error:document.querySelector('[role=alert]')?.textContent,download:!!document.querySelector('a.download')}),2000);
|
||||
try {
|
||||
await wait(()=>document.querySelector('#stun-provider'));
|
||||
if(role==='receiver'){click('Receive');await pause(20);}
|
||||
if(role==='sender'){
|
||||
const files=new DataTransfer();files.items.add(new File([new Uint8Array(2*1024*1024+7).fill(123)],'cross-browser.bin'));
|
||||
const el=document.querySelector('#file-input');el.files=files.files;el.dispatchEvent(new Event('change',{bubbles:true}));await pause(20);
|
||||
}
|
||||
input('#stun-provider',${JSON.stringify(provider)});await pause(20);
|
||||
if(role==='sender'){
|
||||
await stage('creating offer'); click('Create code');await wait(()=>document.querySelector('#output-code'));
|
||||
await post('offer',document.querySelector('#output-code').value);
|
||||
await stage('waiting for answer'); const answer=await wait(()=>get('answer'));input('#answer-input',answer);await pause(20);click('Connect');
|
||||
}else{
|
||||
await stage('waiting for offer'); const offer=await wait(()=>get('offer'));input('#offer-input',offer);await pause(20);
|
||||
await stage('creating answer');click('Accept & create answer');await wait(()=>document.querySelector('#output-code'));
|
||||
await post('answer',document.querySelector('#output-code').value);
|
||||
}
|
||||
await stage('comparing fingerprints');await wait(()=>document.querySelector('.fingerprint'));
|
||||
const fps=[...document.querySelectorAll('.fp-row code')].map(el=>el.textContent);
|
||||
await post(role+'Fingerprints',fps);
|
||||
const other=await wait(()=>get((role==='sender'?'receiver':'sender')+'Fingerprints'));
|
||||
if(fps[0]!==other[1]||fps[1]!==other[0])throw new Error('Fingerprints do not match');
|
||||
click('Both fingerprints match — confirm');
|
||||
if(role==='receiver'){
|
||||
await stage('waiting for metadata');await wait(()=>document.querySelector('.incoming'));click('Receive in memory (up to 64 MiB)');
|
||||
await stage('receiving');await wait(()=>document.querySelector('a.download'));
|
||||
await wait(()=>get('senderResult'));
|
||||
await pause(250);
|
||||
if(!document.querySelector('a.download'))throw new Error('Download was revoked after sender shutdown');
|
||||
await stage('checking downloaded bytes');
|
||||
const bytes=new Uint8Array(await (await fetch(document.querySelector('a.download').href)).arrayBuffer());
|
||||
if(bytes.length!==2*1024*1024+7||!bytes.every(b=>b===123))throw new Error('File content mismatch');
|
||||
}else{
|
||||
await stage('waiting for receipt');await wait(()=>document.querySelector('[role=status]').textContent.includes('confirmed the complete file'));
|
||||
}
|
||||
await post(role+'Result',{ok:true});
|
||||
}catch(error){
|
||||
await post(role+'Result',{ok:false,error:error.message,peers:peers.map(pc=>({connection:pc.connectionState,gathering:pc.iceGatheringState,ice:pc.iceConnectionState,localFingerprints:pc.localDescription?.sdp.match(/^a=fingerprint:.*$/gm),remoteFingerprints:pc.remoteDescription?.sdp.match(/^a=fingerprint:.*$/gm)}))});
|
||||
}
|
||||
`;
|
||||
let finish;
|
||||
const result = new Promise(resolve => { finish = resolve; });
|
||||
const server = createServer(async (req,res) => {
|
||||
try {
|
||||
const pathname=new URL(req.url,'http://localhost').pathname;
|
||||
if(pathname==='/.test/driver.js'){res.setHeader('Content-Type','text/javascript');res.end(driver);return;}
|
||||
if(pathname.startsWith('/.test/')){
|
||||
const key=pathname.slice('/.test/'.length);
|
||||
if(req.method==='POST'){
|
||||
let body='';for await(const part of req){body+=part;if(body.length>262144)throw new Error('Too big');}
|
||||
const previous=state[key];
|
||||
state[key]=JSON.parse(body);
|
||||
if(key.endsWith('Stage'))console.log(key+': '+state[key]);
|
||||
if(key.endsWith('Diagnostic')&&JSON.stringify(previous)!==JSON.stringify(state[key]))console.log(key+': '+JSON.stringify(state[key]));
|
||||
if(key.endsWith('Result')){
|
||||
console.log(key+': '+JSON.stringify(state[key]));
|
||||
if(!state[key].ok||(state.senderResult&&state.receiverResult))finish();
|
||||
}
|
||||
}
|
||||
res.setHeader('Content-Type','application/json');res.end(JSON.stringify(state[key]??null));return;
|
||||
}
|
||||
const base=join(root,'dist');const path=resolve(base,'.'+(pathname==='/'?'/index.html':pathname));
|
||||
if(!path.startsWith(base+'/'))throw new Error('Invalid path');
|
||||
let body=await readFile(path);
|
||||
if(pathname==='/')body=body.toString().replace('</body>','<script type="module" src="/.test/driver.js"></script></body>');
|
||||
res.setHeader('Content-Type',({'.html':'text/html','.js':'text/javascript','.css':'text/css','.png':'image/png'})[extname(path)]||'application/octet-stream');res.end(body);
|
||||
}catch{res.statusCode=404;res.end();}
|
||||
});
|
||||
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
|
||||
const origin='http://127.0.0.1:'+server.address().port;
|
||||
let timer;
|
||||
try{
|
||||
for(const name of ['brave','firefox']){
|
||||
const profile=await mkdtemp(join(tmpdir(),'hellcon-'+name+'-'));profiles.push(profile);
|
||||
const role=(name==='brave')!==reversed?'sender':'receiver';
|
||||
const args=name==='brave'?['--headless','--no-sandbox','--disable-gpu','--no-first-run','--no-default-browser-check','--user-data-dir='+profile,origin+'/?role='+role]:['--headless','--no-remote','--profile',profile,origin+'/?role='+role];
|
||||
const child=spawn(process.env[name==='brave'?'BRAVE_PATH':'FIREFOX_PATH']||'/usr/bin/'+name,args,{stdio:['ignore','ignore','pipe']});children.push(child);
|
||||
let errors='';child.stderr.on('data',chunk=>{errors+=chunk;});
|
||||
child.on('error',err=>{console.error(name,err.message);finish();});
|
||||
child.on('exit',code=>{if(code){console.error(name+' exited: '+errors.slice(-1500));finish();}});
|
||||
}
|
||||
timer=setTimeout(()=>{console.error('Cross-browser check timed out.', JSON.stringify({sender:state.senderDiagnostic,receiver:state.receiverDiagnostic}));finish();},provider==='none'?15000:90000);
|
||||
await result;
|
||||
if(!state.senderResult?.ok||!state.receiverResult?.ok)process.exitCode=1;
|
||||
else console.log('PASS: '+(reversed?'Firefox → Brave':'Brave → Firefox')+' full UI transfer, fingerprint verification and exact file contents.');
|
||||
}finally{
|
||||
clearTimeout(timer);
|
||||
for(const child of children)child.kill();
|
||||
await Promise.all(children.map(child=>new Promise(resolve=>{if(child.exitCode!==null||child.signalCode!==null)resolve();else child.once('exit',resolve);})));
|
||||
server.closeAllConnections();await new Promise(resolve=>server.close(resolve));
|
||||
for(const profile of profiles)await rm(profile,{recursive:true,force:true,maxRetries:5,retryDelay:200});
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// Exercises the built Vue app in separate Brave and Firefox processes.
|
||||
import { installBrowserContext } from './browser-context.ts';
|
||||
import { crossBrowserDriver } from './cross-browser-driver.ts';
|
||||
import { isRecord } from '../src/lib/validation.ts';
|
||||
import { createServer } from 'node:http';
|
||||
import { spawn, type ChildProcess } from 'node:child_process';
|
||||
import { readFile, mkdtemp, rm } from 'node:fs/promises';
|
||||
import { dirname, extname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { tmpdir } from 'node:os';
|
||||
const types: Record<string, string> = {'.html':'text/html','.js':'text/javascript','.css':'text/css','.png':'image/png'};
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const state: Record<string, unknown> = {};
|
||||
const profiles: string[] = [];
|
||||
const children: ChildProcess[] = [];
|
||||
const provider = process.argv.includes('--default-network') ? 'google' : 'none';
|
||||
const reversed = process.argv.includes('--reverse');
|
||||
const driver = `(${installBrowserContext.toString()})(); (${crossBrowserDriver.toString()})(${JSON.stringify(provider)});`;
|
||||
let finish: () => void = () => {};
|
||||
const result = new Promise<void>(resolve => { finish = resolve; });
|
||||
const server = createServer(async (req,res) => {
|
||||
try {
|
||||
const pathname=new URL(req.url ?? '/','http://localhost').pathname;
|
||||
if(pathname==='/.test/driver.js'){res.setHeader('Content-Type','text/javascript');res.end(driver);return;}
|
||||
if(pathname.startsWith('/.test/')){
|
||||
const key=pathname.slice('/.test/'.length);
|
||||
if(req.method==='POST'){
|
||||
let body='';for await(const part of req){body+=part;if(body.length>262144)throw new Error('Too big');}
|
||||
const previous=state[key];
|
||||
state[key]=JSON.parse(body);
|
||||
if(key.endsWith('Stage'))console.log(key+': '+state[key]);
|
||||
if(key.endsWith('Diagnostic')&&JSON.stringify(previous)!==JSON.stringify(state[key]))console.log(key+': '+JSON.stringify(state[key]));
|
||||
if(key.endsWith('Result')){
|
||||
console.log(key+': '+JSON.stringify(state[key]));
|
||||
if(!isRecord(state[key]) || !state[key].ok ||(state.senderResult&&state.receiverResult))finish();
|
||||
}
|
||||
}
|
||||
res.setHeader('Content-Type','application/json');res.end(JSON.stringify(state[key]??null));return;
|
||||
}
|
||||
const base=join(root,'dist');const path=resolve(base,'.'+(pathname==='/'?'/index.html':pathname));
|
||||
if(!path.startsWith(base+'/'))throw new Error('Invalid path');
|
||||
let body: string | Buffer = await readFile(path);
|
||||
if(pathname==='/')body=body.toString().replace('</body>','<script type="module" src="/.test/driver.js"></script></body>');
|
||||
res.setHeader('Content-Type',types[extname(path)]||'application/octet-stream');res.end(body);
|
||||
}catch{res.statusCode=404;res.end();}
|
||||
});
|
||||
await new Promise<void>(resolve=>server.listen(0,'127.0.0.1',resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === 'string') throw new Error('Missing server address');
|
||||
const origin='http://127.0.0.1:'+address.port;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try{
|
||||
for(const name of ['brave','firefox']){
|
||||
const profile=await mkdtemp(join(tmpdir(),'hellcon-'+name+'-'));profiles.push(profile);
|
||||
const role=(name==='brave')!==reversed?'sender':'receiver';
|
||||
const args=name==='brave'?['--headless','--no-sandbox','--disable-gpu','--no-first-run','--no-default-browser-check','--user-data-dir='+profile,origin+'/?role='+role]:['--headless','--no-remote','--profile',profile,origin+'/?role='+role];
|
||||
const child=spawn(process.env[name==='brave'?'BRAVE_PATH':'FIREFOX_PATH']||'/usr/bin/'+name,args,{stdio:['ignore','ignore','pipe']});children.push(child);
|
||||
let errors='';child.stderr.on('data',chunk=>{errors+=chunk;});
|
||||
child.on('error',err=>{console.error(name,err.message);finish();});
|
||||
child.on('exit',code=>{if(code){console.error(name+' exited: '+errors.slice(-1500));finish();}});
|
||||
}
|
||||
timer=setTimeout(()=>{console.error('Cross-browser check timed out.', JSON.stringify({sender:state.senderDiagnostic,receiver:state.receiverDiagnostic}));finish();},provider==='none'?15000:90000);
|
||||
await result;
|
||||
if(!isRecord(state.senderResult) || !state.senderResult.ok || !isRecord(state.receiverResult) || !state.receiverResult.ok)process.exitCode=1;
|
||||
else console.log('PASS: '+(reversed?'Firefox → Brave':'Brave → Firefox')+' full UI transfer, fingerprint verification and exact file contents.');
|
||||
}finally{
|
||||
clearTimeout(timer);
|
||||
for(const child of children)child.kill();
|
||||
await Promise.all(children.map(child=>new Promise<void>(resolve=>{if(child.exitCode!==null||child.signalCode!==null)resolve();else child.once('exit', () => resolve());})));
|
||||
server.closeAllConnections();await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
||||
for(const profile of profiles)await rm(profile,{recursive:true,force:true,maxRetries:5,retryDelay:200});
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import type {} from './browser-context.ts';
|
||||
|
||||
interface Exchange {
|
||||
offer: string;
|
||||
answer: string;
|
||||
senderFingerprints: string[];
|
||||
receiverFingerprints: string[];
|
||||
senderResult: { ok: boolean };
|
||||
}
|
||||
|
||||
// Serialized by the runner; all runtime dependencies live in this function or window.
|
||||
export async function crossBrowserDriver(provider: string) {
|
||||
const role = new URL(location.href).searchParams.get('role');
|
||||
if (role !== 'sender' && role !== 'receiver') throw new Error('Invalid role');
|
||||
const { click, input, wait, element } = window.__hellcon;
|
||||
const pause = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));
|
||||
const post = async (key: string, value: unknown) => fetch('/.test/' + key, {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(value)});
|
||||
const get = async <K extends keyof Exchange>(key: K): Promise<Exchange[K] | null> => (await fetch('/.test/' + key)).json();
|
||||
const stage = async (text: string) => post(role+'Stage', text);
|
||||
const peers: RTCPeerConnection[] = []; const NativePC = window.RTCPeerConnection;
|
||||
window.RTCPeerConnection = class extends NativePC { constructor(config?: RTCConfiguration) { super(config); peers.push(this); } };
|
||||
setInterval(()=>post(role+'Diagnostic',{status:document.querySelector('[role=status]')?.textContent,error:document.querySelector('[role=alert]')?.textContent,download:!!document.querySelector('a.download')}),2000);
|
||||
try {
|
||||
await wait(()=>document.querySelector('#stun-provider'));
|
||||
if(role==='receiver'){click('Receive');await pause(20);}
|
||||
if(role==='sender'){
|
||||
window.__hellcon.chooseFile(2*1024*1024+7, 'cross-browser.bin'); await pause(20);
|
||||
}
|
||||
input('#stun-provider',provider);await pause(20);
|
||||
if(role==='sender'){
|
||||
await stage('creating offer'); click('Create code');await wait(()=>document.querySelector('#output-code'));
|
||||
await post('offer',element<HTMLTextAreaElement>('#output-code').value);
|
||||
await stage('waiting for answer'); const answer=await wait(()=>get('answer'));input('#answer-input',answer);await pause(20);click('Connect');
|
||||
}else{
|
||||
await stage('waiting for offer'); const offer=await wait(()=>get('offer'));input('#offer-input',offer);await pause(20);
|
||||
await stage('creating answer');click('Accept & create answer');await wait(()=>document.querySelector('#output-code'));
|
||||
await post('answer',element<HTMLTextAreaElement>('#output-code').value);
|
||||
}
|
||||
await stage('comparing fingerprints');await wait(()=>document.querySelector('.fingerprint'));
|
||||
const fps=[...document.querySelectorAll('.fp-row code')].map(el=>el.textContent);
|
||||
await post(role+'Fingerprints',fps);
|
||||
const other=await wait(()=>get(role === 'sender' ? 'receiverFingerprints' : 'senderFingerprints'));
|
||||
if(fps[0]!==other[1]||fps[1]!==other[0])throw new Error('Fingerprints do not match');
|
||||
click('Both fingerprints match — confirm');
|
||||
if(role==='receiver'){
|
||||
await stage('waiting for metadata');await wait(()=>document.querySelector('.incoming'));click('Receive in memory (up to 64 MiB)');
|
||||
await stage('receiving');await wait(()=>document.querySelector('a.download'));
|
||||
await wait(()=>get('senderResult'));
|
||||
await pause(250);
|
||||
if(!document.querySelector('a.download'))throw new Error('Download was revoked after sender shutdown');
|
||||
await stage('checking downloaded bytes');
|
||||
const bytes=new Uint8Array(await (await fetch(element<HTMLAnchorElement>('a.download').href)).arrayBuffer());
|
||||
if(bytes.length!==2*1024*1024+7||!bytes.every(b=>b===123))throw new Error('File content mismatch');
|
||||
}else{
|
||||
await stage('waiting for receipt');await wait(()=>element('[role=status]').textContent?.includes('confirmed the complete file'));
|
||||
}
|
||||
await post(role+'Result',{ok:true});
|
||||
}catch(error){
|
||||
await post(role+'Result',{ok:false,error:error instanceof Error ? error.message : String(error),peers:peers.map(pc=>({connection:pc.connectionState,gathering:pc.iceGatheringState,ice:pc.iceConnectionState,localFingerprints:pc.localDescription?.sdp.match(/^a=fingerprint:.*$/gm),remoteFingerprints:pc.remoteDescription?.sdp.match(/^a=fingerprint:.*$/gm)}))});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
|
||||
try {
|
||||
await writeFile(new URL('../.env.development', import.meta.url),
|
||||
`# Local development only; shared by Compose and Vite.\nTURN_SECRET=${randomBytes(32).toString('hex')}\nTURN_HOST=127.0.0.1\nTURN_PORT=3478\nVITE_ICE_ENDPOINT=/api/ice-servers\nVITE_STUN_URL=stun:127.0.0.1:3478\n`,
|
||||
{ flag: 'wx', mode: 0o600 });
|
||||
console.log('Created .env.development with a private development TURN secret.');
|
||||
} catch (error) {
|
||||
if (!(error instanceof Error) || !('code' in error) || error.code !== 'EEXIST') throw error;
|
||||
console.log('.env.development already exists; left unchanged. See .env.example for required settings.');
|
||||
}
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
<script setup>
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import SendPanel from './components/SendPanel.vue';
|
||||
import ReceivePanel from './components/ReceivePanel.vue';
|
||||
|
||||
const mode = ref('send');
|
||||
const mode = ref<'send' | 'receive'>('send');
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
<script setup>
|
||||
import { STUN_PROVIDERS } from '../lib/webrtc.js';
|
||||
const settings = defineModel({ required: true });
|
||||
defineProps({ disabled: Boolean });
|
||||
<script setup lang="ts">
|
||||
import type { NetworkSettings } from '../lib/webrtc.ts';
|
||||
import { STUN_PROVIDERS } from '../lib/webrtc.ts';
|
||||
const settings = defineModel<NetworkSettings>({ required: true });
|
||||
defineProps<{ disabled?: boolean }>();
|
||||
const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -17,9 +19,12 @@ defineProps({ disabled: Boolean });
|
||||
<label class="checkbox"><input type="checkbox" v-model="settings.allowTurn" /> Allow a TURN relay for this connection (opt-in)</label>
|
||||
<template v-if="settings.allowTurn">
|
||||
<p class="status">Both people must opt in. Your browser may contact this relay and route encrypted file traffic through it. The operator sees addresses, timing and traffic volume, and may charge for bandwidth. Use credentials you are authorized to use; they remain in this tab.</p>
|
||||
<label v-if="iceEndpoint" class="checkbox"><input type="checkbox" v-model="settings.managedTurn" /> Use the configured relay with temporary credentials</label>
|
||||
<template v-if="!iceEndpoint || !settings.managedTurn">
|
||||
<input v-model="settings.turnUrl" class="stun-input" aria-label="TURN address" placeholder="turns:relay.example:5349?transport=tcp" autocomplete="off" />
|
||||
<input v-model="settings.username" class="stun-input" aria-label="TURN username" placeholder="TURN username" autocomplete="off" />
|
||||
<input v-model="settings.credential" class="stun-input" type="password" aria-label="TURN password" placeholder="TURN password" autocomplete="off" />
|
||||
</template>
|
||||
</template>
|
||||
</fieldset>
|
||||
</template>
|
||||
@@ -1,4 +1,4 @@
|
||||
<script setup>
|
||||
<script setup lang="ts">
|
||||
import TransferPanel from './TransferPanel.vue';
|
||||
</script>
|
||||
<template><TransferPanel /></template>
|
||||
@@ -1,4 +1,4 @@
|
||||
<script setup>
|
||||
<script setup lang="ts">
|
||||
import TransferPanel from './TransferPanel.vue';
|
||||
</script>
|
||||
<template><TransferPanel sending /></template>
|
||||
@@ -1,27 +1,42 @@
|
||||
<script setup>
|
||||
<script setup lang="ts">
|
||||
import { asError } from '../lib/validation.ts';
|
||||
import type { Fingerprints, IceOptions, NetworkSettings as NetworkSettingsModel } from '../lib/webrtc.ts';
|
||||
import type { FileMetadata, TransferState, FileDestination } from '../lib/transfer.ts';
|
||||
import { computed, onBeforeUnmount, ref } from 'vue';
|
||||
import NetworkSettings from './NetworkSettings.vue';
|
||||
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.js';
|
||||
import { FILE_LIMIT, MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.js';
|
||||
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.ts';
|
||||
import { FILE_LIMIT, MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.ts';
|
||||
|
||||
const props = defineProps({ sending: Boolean });
|
||||
const file = ref(null);
|
||||
type Step = 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
|
||||
interface Session {
|
||||
pc: RTCPeerConnection;
|
||||
options: IceOptions;
|
||||
file: File | null;
|
||||
controller: AbortController;
|
||||
transfer: Transfer | null;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
const props = defineProps<{ sending?: boolean }>();
|
||||
const file = ref<File | null>(null);
|
||||
const inputCode = ref('');
|
||||
const outputCode = ref('');
|
||||
const step = ref('idle');
|
||||
const step = ref<Step>('idle');
|
||||
const error = ref('');
|
||||
const copied = ref(false);
|
||||
const fps = ref(null);
|
||||
const fps = ref<Fingerprints | null>(null);
|
||||
const verified = ref(false);
|
||||
const progress = ref(0);
|
||||
const incoming = ref(null);
|
||||
const incoming = ref<FileMetadata | null>(null);
|
||||
const downloadUrl = ref('');
|
||||
const choosing = ref(false);
|
||||
const dragover = ref(false);
|
||||
const settings = ref({ stunChoice: 'google', customStun: '', allowTurn: false, turnUrl: '', username: '', credential: '' });
|
||||
const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
|
||||
const defaultStun = import.meta.env.VITE_STUN_URL || '';
|
||||
const settings = ref<NetworkSettingsModel>({ stunChoice: defaultStun ? 'custom' : 'google', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' });
|
||||
const canSaveToDisk = typeof window.showSaveFilePicker === 'function';
|
||||
let active = null;
|
||||
let copyTimer;
|
||||
let active: Session | null = null;
|
||||
let copyTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const busy = computed(() => !['idle', 'closed', 'done'].includes(step.value));
|
||||
const status = computed(() => ({
|
||||
idle: props.sending ? 'Choose a file to start.' : 'Paste the sender’s connection code to start.',
|
||||
@@ -61,22 +76,23 @@ function reset(keepNetwork = false) {
|
||||
verified.value = copied.value = choosing.value = false;
|
||||
progress.value = 0; step.value = 'idle';
|
||||
}
|
||||
function fail(session, err) {
|
||||
function fail(session: Session, err: unknown) {
|
||||
if (active !== session) return;
|
||||
dispose(); revokeDownload();
|
||||
fps.value = incoming.value = null;
|
||||
outputCode.value = ''; verified.value = false;
|
||||
settings.value.allowTurn = false;
|
||||
error.value = err.message || 'Connection failed.'; step.value = 'closed';
|
||||
error.value = asError(err).message; step.value = 'closed';
|
||||
}
|
||||
function pickFiles(event) {
|
||||
const selected = event.target?.files?.[0] ?? event.dataTransfer?.files?.[0];
|
||||
function pickFiles(event: Event) {
|
||||
const selected = event.target instanceof HTMLInputElement ? event.target.files?.[0]
|
||||
: event instanceof DragEvent ? event.dataTransfer?.files[0] : undefined;
|
||||
if (!selected) return;
|
||||
reset();
|
||||
if (selected.size > FILE_LIMIT) { file.value = null; error.value = 'The maximum file size is 64 GiB.'; return; }
|
||||
file.value = selected;
|
||||
}
|
||||
function attach(session, channel) {
|
||||
function attach(session: Session, channel: RTCDataChannel) {
|
||||
if (active !== session) { channel.close(); return; }
|
||||
if (session.transfer || channel.label !== 'hellcon-v2' || !channel.ordered || channel.maxRetransmits !== null || channel.maxPacketLifeTime !== null) {
|
||||
channel.close(); fail(session, new Error('Unexpected data channel.')); return;
|
||||
@@ -109,8 +125,9 @@ function start() {
|
||||
stunUrl: chosen.stunChoice === 'custom' ? chosen.customStun.trim() || null : STUN_PROVIDERS.find(p => p.id === chosen.stunChoice)?.url ?? null,
|
||||
turnUrl: chosen.turnUrl.trim(),
|
||||
};
|
||||
const pc = createPeerConnection(options);
|
||||
const session = { pc, options, file: file.value, controller: new AbortController(), transfer: null };
|
||||
// Fetch managed credentials before gathering, while retaining normal cancellation.
|
||||
const pc = createPeerConnection(iceEndpoint && options.managedTurn ? { ...options, allowTurn: false } : options);
|
||||
const session: Session = { pc, options, file: file.value, controller: new AbortController(), transfer: null };
|
||||
active = session;
|
||||
session.timer = setTimeout(() => fail(session, new Error('Connection timed out. Start again with new codes.')), 5 * 60 * 1000);
|
||||
pc.ondatachannel = event => attach(session, event.channel);
|
||||
@@ -126,13 +143,16 @@ function start() {
|
||||
async function createCode() {
|
||||
const pasted = inputCode.value;
|
||||
reset(true); inputCode.value = props.sending ? '' : pasted; step.value = 'gathering';
|
||||
let session;
|
||||
let session: Session | undefined;
|
||||
try {
|
||||
if (props.sending) {
|
||||
if (!file.value) throw new Error('Choose a file first.');
|
||||
validateMetadata({ name: file.value.name, size: file.value.size, mime: file.value.type || '' });
|
||||
}
|
||||
session = start();
|
||||
const configured = await fetchTurnOptions(session.options, iceEndpoint, { signal: session.controller.signal });
|
||||
if (active !== session) return;
|
||||
session.pc.setConfiguration(iceConfiguration(configured));
|
||||
const options = { ...session.options, signal: session.controller.signal };
|
||||
if (props.sending) attach(session, session.pc.createDataChannel('hellcon-v2'));
|
||||
const code = props.sending ? await createOfferCode(session.pc, options) : await createAnswerCode(session.pc, pasted, options);
|
||||
@@ -142,7 +162,7 @@ async function createCode() {
|
||||
step.value = props.sending ? 'offer-ready' : 'answer-ready';
|
||||
} catch (err) {
|
||||
if (session) fail(session, err);
|
||||
else { settings.value.allowTurn = false; error.value = err.message; step.value = 'closed'; }
|
||||
else { settings.value.allowTurn = false; error.value = asError(err).message; step.value = 'closed'; }
|
||||
}
|
||||
}
|
||||
async function useAnswer() {
|
||||
@@ -159,7 +179,7 @@ async function useAnswer() {
|
||||
// A rejected answer does not consume a valid local offer. Let the user
|
||||
// correct a paste error instead of silently invalidating both peers' codes.
|
||||
if (session.pc.signalingState === 'have-local-offer') {
|
||||
error.value = `${err.message || 'Invalid answer.'} Correct the answer and connect again; your offer is still valid.`;
|
||||
error.value = `${asError(err, 'Invalid answer.').message} Correct the answer and connect again; your offer is still valid.`;
|
||||
step.value = 'offer-ready';
|
||||
} else fail(session, err);
|
||||
}
|
||||
@@ -173,13 +193,14 @@ function verify() {
|
||||
session.timer = setTimeout(() => { if (active === session && !session.transfer) fail(session, new Error('Connection timed out.')); }, 60000);
|
||||
session.transfer?.verify();
|
||||
}
|
||||
async function acceptFile(toDisk) {
|
||||
async function acceptFile(toDisk: boolean) {
|
||||
const session = active;
|
||||
if (!session?.transfer || choosing.value || step.value !== 'choose-storage') return;
|
||||
if (!session?.transfer || !incoming.value || choosing.value || step.value !== 'choose-storage') return;
|
||||
choosing.value = true; error.value = '';
|
||||
let writable;
|
||||
let writable: FileDestination | undefined;
|
||||
try {
|
||||
if (toDisk) {
|
||||
if (!window.showSaveFilePicker) throw new Error('Direct-to-disk saving is unavailable.');
|
||||
const handle = await window.showSaveFilePicker({ suggestedName: incoming.value.name });
|
||||
if (active !== session) return;
|
||||
writable = await handle.createWritable();
|
||||
@@ -188,7 +209,7 @@ async function acceptFile(toDisk) {
|
||||
session.transfer.accept(writable);
|
||||
} catch (err) {
|
||||
if (writable) await writable.abort().catch(() => {});
|
||||
if (active === session && err.name !== 'AbortError') error.value = err.message || 'Could not open the destination file.';
|
||||
if (active === session && asError(err).name !== 'AbortError') error.value = asError(err, 'Could not open the destination file.').message;
|
||||
} finally { if (active === session) choosing.value = false; }
|
||||
}
|
||||
async function copy() {
|
||||
@@ -200,11 +221,14 @@ async function copy() {
|
||||
copyTimer = setTimeout(() => { copied.value = false; }, 1500);
|
||||
} catch { if (active === session) error.value = 'Clipboard unavailable. Select and copy the code manually.'; }
|
||||
}
|
||||
function formatBytes(bytes) {
|
||||
function formatBytes(bytes: number) {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
const index = Math.min(3, Math.floor(Math.log(bytes) / Math.log(1024)));
|
||||
return `${(bytes / 1024 ** index).toFixed(1)} ${['B', 'KiB', 'MiB', 'GiB'][index]}`;
|
||||
}
|
||||
function selectCode(event: FocusEvent) {
|
||||
if (event.target instanceof HTMLTextAreaElement) event.target.select();
|
||||
}
|
||||
onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); });
|
||||
</script>
|
||||
|
||||
@@ -227,7 +251,7 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
|
||||
<button class="primary" :disabled="busy || (sending ? !file : !inputCode.trim())" @click="createCode">{{ sending ? 'Create code' : 'Accept & create answer' }}</button>
|
||||
<template v-if="outputCode">
|
||||
<label class="step" for="output-code">{{ sending ? 'Send this code to the receiver' : 'Send this answer to the sender' }}</label>
|
||||
<textarea id="output-code" :value="outputCode" readonly @focus="$event.target.select()" />
|
||||
<textarea id="output-code" :value="outputCode" readonly @focus="selectCode" />
|
||||
<button @click="copy">{{ copied ? 'Copied!' : 'Copy code' }}</button>
|
||||
</template>
|
||||
<template v-if="sending && outputCode">
|
||||
@@ -252,7 +276,7 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
|
||||
<div v-if="progress > 0 || step === 'done'" class="progress" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="Transfer progress"><div :style="{ width: progress + '%' }"></div></div>
|
||||
<p class="status" role="status">{{ status }}</p>
|
||||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||
<div v-if="downloadUrl" class="file-chip"><span>{{ incoming.name }}</span><a class="download" :href="downloadUrl" :download="incoming.name">Save file</a></div>
|
||||
<div v-if="downloadUrl && incoming" class="file-chip"><span>{{ incoming.name }}</span><a class="download" :href="downloadUrl" :download="incoming.name">Save file</a></div>
|
||||
<button v-if="step !== 'idle'" @click="reset()">{{ busy ? 'Cancel connection' : 'Reset' }}</button>
|
||||
<p class="status">Switching tabs cancels an active transfer. Keep this tab open until receipt is confirmed.</p>
|
||||
</div>
|
||||
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_ICE_ENDPOINT?: string;
|
||||
readonly VITE_STUN_URL?: string;
|
||||
}
|
||||
|
||||
interface Window {
|
||||
showSaveFilePicker?: (options?: { suggestedName?: string }) => Promise<{ createWritable(): Promise<import('./lib/transfer.ts').FileDestination> }>;
|
||||
}
|
||||
@@ -1,14 +1,45 @@
|
||||
import { CHUNK_SIZE, MAX_BUFFERED, waitForBufferDrain } from './webrtc.js';
|
||||
import { asError, isRecord } from './validation.ts';
|
||||
import type { BufferedChannel } from './webrtc.ts';
|
||||
import { CHUNK_SIZE, MAX_BUFFERED, waitForBufferDrain } from './webrtc.ts';
|
||||
|
||||
export interface FileMetadata { name: string; size: number; mime: string }
|
||||
export type TransferState = 'verification' | 'waiting-accept' | 'choose-storage' | 'sending' |
|
||||
'receiving' | 'saving' | 'awaiting-receipt' | 'done' | 'closed';
|
||||
export interface TransferResult { blob?: Blob | null; meta: FileMetadata }
|
||||
export interface FileDestination {
|
||||
write(data: ArrayBuffer): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
abort(): Promise<void>;
|
||||
}
|
||||
export interface TransferChannel extends BufferedChannel {
|
||||
binaryType: BinaryType;
|
||||
onopen: ((event: Event) => void) | null;
|
||||
onmessage: ((event: MessageEvent<unknown>) => void) | null;
|
||||
onclose: ((event: Event) => void) | null;
|
||||
onerror: ((event: RTCErrorEvent) => void) | null;
|
||||
send(data: string | ArrayBuffer): void;
|
||||
close(): void;
|
||||
}
|
||||
export interface TransferOptions {
|
||||
file?: File | null;
|
||||
onState?: (state: TransferState) => void;
|
||||
onMeta?: (meta: FileMetadata) => void;
|
||||
onProgress?: (bytes: number, size: number) => void;
|
||||
onComplete?: (result: TransferResult) => void;
|
||||
onError?: (error: Error) => void;
|
||||
timeout?: number;
|
||||
}
|
||||
type ControlType = 'ready' | 'meta' | 'accept' | 'ack' | 'end' | 'complete';
|
||||
|
||||
export const MEMORY_LIMIT = 64 * 1024 * 1024;
|
||||
export const FILE_LIMIT = 64 * 1024 * 1024 * 1024;
|
||||
const CONTROL_LIMIT = 2048;
|
||||
const WINDOW = MAX_BUFFERED;
|
||||
|
||||
export function validateMetadata(meta) {
|
||||
if (!meta || typeof meta.name !== 'string' || !meta.name.length || meta.name.length > 255 ||
|
||||
export function validateMetadata(meta: unknown): FileMetadata {
|
||||
if (!isRecord(meta) || typeof meta.name !== 'string' || !meta.name.length || meta.name.length > 255 ||
|
||||
/[\x00-\x1f\x7f/\\\u202a-\u202e\u2066-\u2069]/.test(meta.name) ||
|
||||
!Number.isSafeInteger(meta.size) || meta.size < 0 || meta.size > FILE_LIMIT ||
|
||||
typeof meta.size !== 'number' || !Number.isSafeInteger(meta.size) || meta.size < 0 || meta.size > FILE_LIMIT ||
|
||||
typeof meta.mime !== 'string' || meta.mime.length > 128 || /[^\x20-\x7e]/.test(meta.mime)) {
|
||||
throw new Error('Invalid file metadata or file exceeds the 64 GiB limit.');
|
||||
}
|
||||
@@ -17,8 +48,45 @@ export function validateMetadata(meta) {
|
||||
|
||||
// One ordered, reliable channel; bounded receive queue and acknowledged send window.
|
||||
export class Transfer {
|
||||
constructor(dc, { file = null, onState = () => {}, onMeta = () => {}, onProgress = () => {}, onComplete = () => {}, onError = () => {}, timeout = 60000 } = {}) {
|
||||
Object.assign(this, { dc, file, onState, onMeta, onProgress, onComplete, onError, timeout });
|
||||
readonly dc: TransferChannel;
|
||||
readonly file: File | null;
|
||||
readonly onState: NonNullable<TransferOptions['onState']>;
|
||||
readonly onMeta: NonNullable<TransferOptions['onMeta']>;
|
||||
readonly onProgress: NonNullable<TransferOptions['onProgress']>;
|
||||
readonly onComplete: NonNullable<TransferOptions['onComplete']>;
|
||||
readonly onError: NonNullable<TransferOptions['onError']>;
|
||||
readonly timeout: number;
|
||||
state: TransferState;
|
||||
verified: boolean;
|
||||
peerReady: boolean;
|
||||
readySent: boolean;
|
||||
closed: boolean;
|
||||
received: number;
|
||||
sent: number;
|
||||
acked: number;
|
||||
queued: number;
|
||||
messages: number;
|
||||
chunks: ArrayBuffer[];
|
||||
queue: Promise<void>;
|
||||
readonly controller: AbortController;
|
||||
private timer: ReturnType<typeof setTimeout> | undefined;
|
||||
private meta: FileMetadata | null = null;
|
||||
private writable: FileDestination | null = null;
|
||||
private wake: (() => void) | null = null;
|
||||
|
||||
private get metadata(): FileMetadata {
|
||||
if (!this.meta) throw new Error('Missing file metadata.');
|
||||
return this.meta;
|
||||
}
|
||||
constructor(dc: TransferChannel, { file = null, onState = () => {}, onMeta = () => {}, onProgress = () => {}, onComplete = () => {}, onError = () => {}, timeout = 60000 }: TransferOptions = {}) {
|
||||
this.dc = dc;
|
||||
this.file = file;
|
||||
this.onState = onState;
|
||||
this.onMeta = onMeta;
|
||||
this.onProgress = onProgress;
|
||||
this.onComplete = onComplete;
|
||||
this.onError = onError;
|
||||
this.timeout = timeout;
|
||||
this.state = 'verification';
|
||||
this.verified = false;
|
||||
this.peerReady = false;
|
||||
@@ -31,7 +99,7 @@ export class Transfer {
|
||||
dc.binaryType = 'arraybuffer';
|
||||
dc.onopen = () => this.guard(() => this.ready());
|
||||
dc.onmessage = e => this.enqueue(e.data);
|
||||
const transportEnded = message => {
|
||||
const transportEnded = (message: string) => {
|
||||
// Firefox can report an SCTP error when the sender closes its peer
|
||||
// connection after receiving our completion ACK. The saved file remains
|
||||
// valid; a transport shutdown must not revoke a completed download.
|
||||
@@ -42,13 +110,13 @@ export class Transfer {
|
||||
dc.onerror = () => transportEnded('Data channel failed.');
|
||||
this.touch(5 * 60 * 1000);
|
||||
}
|
||||
setState(state) { this.state = state; this.onState(state); }
|
||||
setState(state: TransferState) { this.state = state; this.onState(state); }
|
||||
touch(ms = this.timeout) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = setTimeout(() => this.fail(new Error('Transfer timed out. Start a new connection.')), ms);
|
||||
}
|
||||
guard(fn) { try { fn(); } catch (err) { this.fail(err); } }
|
||||
control(type, data = {}) {
|
||||
guard(fn: () => void) { try { fn(); } catch (err) { this.fail(err); } }
|
||||
control(type: ControlType, data: Partial<FileMetadata> & { bytes?: number } = {}) {
|
||||
if (this.closed || this.dc.readyState !== 'open') throw new Error('Connection is not open.');
|
||||
const text = JSON.stringify({ v: 2, type, ...data });
|
||||
if (text.length > CONTROL_LIMIT) throw new Error('Control message is too large.');
|
||||
@@ -65,11 +133,11 @@ export class Transfer {
|
||||
if (this.file && this.peerReady && this.state === 'verification') {
|
||||
this.meta = validateMetadata({ name: this.file.name, size: this.file.size, mime: this.file.type || '' });
|
||||
this.setState('waiting-accept');
|
||||
this.control('meta', this.meta);
|
||||
this.control('meta', this.metadata);
|
||||
this.touch(5 * 60 * 1000);
|
||||
}
|
||||
}
|
||||
enqueue(data) {
|
||||
enqueue(data: unknown) {
|
||||
if (this.closed) return;
|
||||
const binary = data instanceof ArrayBuffer;
|
||||
const size = binary ? data.byteLength : typeof data === 'string' ? data.length : Infinity;
|
||||
@@ -81,42 +149,43 @@ export class Transfer {
|
||||
if (!this.closed) await this.message(data);
|
||||
}).catch(err => this.fail(err)).finally(() => { this.queued -= size; this.messages--; });
|
||||
}
|
||||
async message(data) {
|
||||
async message(data: unknown) {
|
||||
if (data instanceof ArrayBuffer) {
|
||||
if (this.file || this.state !== 'receiving' || !data.byteLength || this.received + data.byteLength > this.meta.size) throw new Error('Unexpected or excess file data.');
|
||||
if (this.file || this.state !== 'receiving' || !data.byteLength || this.received + data.byteLength > this.metadata.size) throw new Error('Unexpected or excess file data.');
|
||||
// Bound per-chunk overhead as well as payload bytes: millions of tiny
|
||||
// ArrayBuffers would otherwise defeat the in-memory size limit.
|
||||
if (data.byteLength !== Math.min(CHUNK_SIZE, this.meta.size - this.received)) throw new Error('Invalid file chunk size.');
|
||||
if (data.byteLength !== Math.min(CHUNK_SIZE, this.metadata.size - this.received)) throw new Error('Invalid file chunk size.');
|
||||
if (this.writable) await this.writable.write(data);
|
||||
else this.chunks.push(data);
|
||||
if (this.closed) return;
|
||||
this.received += data.byteLength;
|
||||
this.control('ack', { bytes: this.received });
|
||||
this.onProgress(this.received, this.meta.size);
|
||||
this.onProgress(this.received, this.metadata.size);
|
||||
this.touch();
|
||||
return;
|
||||
}
|
||||
const msg = JSON.parse(data);
|
||||
if (!msg || msg.v !== 2 || typeof msg.type !== 'string') throw new Error('Unsupported transfer protocol.');
|
||||
if (typeof data !== 'string') throw new Error('Unsupported transfer message.');
|
||||
const msg: unknown = JSON.parse(data);
|
||||
if (!isRecord(msg) || msg.v !== 2 || typeof msg.type !== 'string') throw new Error('Unsupported transfer protocol.');
|
||||
if (msg.type === 'ready' && !this.peerReady && this.state === 'verification') {
|
||||
this.peerReady = true; this.ready(); return;
|
||||
}
|
||||
if (!this.verified || !this.peerReady || !this.readySent) throw new Error('File data arrived before verification.');
|
||||
if (msg.type === 'meta' && !this.file && this.state === 'verification') {
|
||||
this.meta = validateMetadata(msg);
|
||||
this.setState('choose-storage'); this.onMeta(this.meta); this.touch(5 * 60 * 1000); return;
|
||||
this.setState('choose-storage'); this.onMeta(this.metadata); this.touch(5 * 60 * 1000); return;
|
||||
}
|
||||
if (msg.type === 'accept' && this.file && this.state === 'waiting-accept') {
|
||||
this.setState('sending'); this.touch();
|
||||
void this.sendFile().catch(err => this.fail(err)); return;
|
||||
}
|
||||
if (msg.type === 'ack' && this.file && ['sending', 'awaiting-receipt'].includes(this.state)) {
|
||||
if (!Number.isSafeInteger(msg.bytes) || msg.bytes <= this.acked || msg.bytes > this.sent ||
|
||||
if (typeof msg.bytes !== 'number' || !Number.isSafeInteger(msg.bytes) || msg.bytes <= this.acked || msg.bytes > this.sent ||
|
||||
(msg.bytes !== this.file.size && msg.bytes % CHUNK_SIZE !== 0)) throw new Error('Invalid receipt count.');
|
||||
this.acked = msg.bytes; this.onProgress(this.acked, this.file.size); this.wake?.(); this.touch(); return;
|
||||
}
|
||||
if (msg.type === 'end' && !this.file && this.state === 'receiving') {
|
||||
if (this.received !== this.meta.size) throw new Error('Incomplete file.');
|
||||
if (this.received !== this.metadata.size) throw new Error('Incomplete file.');
|
||||
this.setState('saving');
|
||||
if (this.writable) await this.writable.close();
|
||||
if (this.closed) return;
|
||||
@@ -125,27 +194,29 @@ export class Transfer {
|
||||
this.chunks = [];
|
||||
this.control('complete', { bytes: this.received });
|
||||
this.setState('done'); clearTimeout(this.timer);
|
||||
this.onComplete({ blob, meta: this.meta }); return;
|
||||
this.onComplete({ blob, meta: this.metadata }); return;
|
||||
}
|
||||
if (msg.type === 'complete' && this.file && this.state === 'awaiting-receipt' && msg.bytes === this.file.size && this.acked === this.file.size) {
|
||||
this.setState('done'); clearTimeout(this.timer); this.onComplete({ meta: this.meta }); this.close(); return;
|
||||
this.setState('done'); clearTimeout(this.timer); this.onComplete({ meta: this.metadata }); this.close(); return;
|
||||
}
|
||||
throw new Error('Unexpected transfer message.');
|
||||
}
|
||||
accept(writable = null) {
|
||||
accept(writable: FileDestination | null = null) {
|
||||
if (this.closed || this.state !== 'choose-storage') throw new Error('File is no longer available.');
|
||||
if (!writable && this.meta.size > MEMORY_LIMIT) throw new Error('Files over 64 MiB require direct-to-disk saving.');
|
||||
if (!writable && this.metadata.size > MEMORY_LIMIT) throw new Error('Files over 64 MiB require direct-to-disk saving.');
|
||||
this.writable = writable;
|
||||
this.setState('receiving'); this.touch();
|
||||
this.guard(() => this.control('accept'));
|
||||
}
|
||||
async sendFile() {
|
||||
for (let offset = 0; offset < this.file.size; offset += CHUNK_SIZE) {
|
||||
if (this.sent - this.acked >= WINDOW) await new Promise(resolve => { this.wake = resolve; });
|
||||
const file = this.file;
|
||||
if (!file) throw new Error('No file selected.');
|
||||
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
|
||||
if (this.sent - this.acked >= WINDOW) await new Promise<void>(resolve => { this.wake = resolve; });
|
||||
this.wake = null;
|
||||
if (this.closed) return;
|
||||
if (this.dc.bufferedAmount > MAX_BUFFERED) await waitForBufferDrain(this.dc, { signal: this.controller.signal, timeout: this.timeout });
|
||||
const buffer = await this.file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
|
||||
const buffer = await file.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
|
||||
if (this.closed) return;
|
||||
this.sent += buffer.byteLength;
|
||||
this.dc.send(buffer);
|
||||
@@ -153,15 +224,16 @@ export class Transfer {
|
||||
if (this.closed) return;
|
||||
this.setState('awaiting-receipt'); this.control('end'); this.touch();
|
||||
}
|
||||
fail(err) {
|
||||
fail(err: unknown) {
|
||||
if (this.closed) return;
|
||||
this.close(); this.setState('closed'); this.onError(err);
|
||||
this.close(); this.setState('closed'); this.onError(asError(err));
|
||||
}
|
||||
close() {
|
||||
if (this.closed) return;
|
||||
this.closed = true; clearTimeout(this.timer); this.controller.abort(); this.wake?.(); this.wake = null;
|
||||
this.chunks = [];
|
||||
if (this.writable && this.state !== 'done') Promise.resolve().then(() => this.writable.abort()).catch(() => {});
|
||||
const writable = this.writable;
|
||||
if (writable && this.state !== 'done') Promise.resolve().then(() => writable.abort()).catch(() => {});
|
||||
this.dc.onmessage = this.dc.onopen = this.dc.onclose = this.dc.onerror = null;
|
||||
this.dc.close();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function isStringArray(value: unknown): value is string[] {
|
||||
return Array.isArray(value) && value.every((item: unknown) => typeof item === 'string');
|
||||
}
|
||||
|
||||
export function asError(value: unknown, fallback = 'Connection failed.'): Error {
|
||||
return value instanceof Error ? value : new Error(fallback);
|
||||
}
|
||||
@@ -1,3 +1,31 @@
|
||||
import { asError, isRecord, isStringArray } from './validation.ts';
|
||||
|
||||
export interface IceOptions {
|
||||
stunUrl?: string | null;
|
||||
allowTurn?: boolean;
|
||||
managedTurn?: boolean;
|
||||
turnUrl?: string | string[];
|
||||
username?: string;
|
||||
credential?: string;
|
||||
}
|
||||
|
||||
export interface NetworkSettings {
|
||||
stunChoice: 'google' | 'cloudflare' | 'none' | 'custom';
|
||||
customStun: string;
|
||||
allowTurn: boolean;
|
||||
managedTurn: boolean;
|
||||
turnUrl: string;
|
||||
username: string;
|
||||
credential: string;
|
||||
}
|
||||
|
||||
export interface WaitOptions { signal?: AbortSignal; timeout?: number }
|
||||
type SignalOptions = WaitOptions & Pick<IceOptions, 'allowTurn'>;
|
||||
export interface Fingerprints { local: string; remote: string }
|
||||
export type IcePeer = EventTarget & Pick<RTCPeerConnection, 'iceGatheringState' | 'connectionState'>;
|
||||
export type BufferedChannel = EventTarget & Pick<RTCDataChannel, 'readyState' | 'bufferedAmount' | 'bufferedAmountLowThreshold'>;
|
||||
type CredentialFetch = (url: string, init: RequestInit) => Promise<Pick<Response, 'ok' | 'json'>>;
|
||||
|
||||
// Manual signaling. Codes are encoded connection details, not encrypted secrets.
|
||||
export const CHUNK_SIZE = 16 * 1024;
|
||||
export const MAX_BUFFERED = 1024 * 1024;
|
||||
@@ -8,15 +36,16 @@ export const STUN_PROVIDERS = [
|
||||
{ id: 'none', label: 'None (direct connections only)', url: null },
|
||||
];
|
||||
|
||||
export function iceConfiguration({ stunUrl = null, allowTurn = false, turnUrl = '', username = '', credential = '' } = {}) {
|
||||
const iceServers = [];
|
||||
export function iceConfiguration({ stunUrl = null, allowTurn = false, turnUrl = '', username = '', credential = '' }: IceOptions = {}): { iceServers: RTCIceServer[] } {
|
||||
const iceServers: RTCIceServer[] = [];
|
||||
if (stunUrl) {
|
||||
if (!/^stuns?:[^\s/?#@]+$/i.test(stunUrl)) throw new Error('Enter a stun: or stuns: server address.');
|
||||
iceServers.push({ urls: stunUrl });
|
||||
}
|
||||
// Credentials and URLs are ignored unless this user explicitly opts in.
|
||||
if (allowTurn) {
|
||||
if (!/^turns?:[^\s/?#@]+(?:\?transport=(?:udp|tcp))?$/i.test(turnUrl) || !username || !credential) {
|
||||
const urls = Array.isArray(turnUrl) ? turnUrl : [turnUrl];
|
||||
if (!urls.length || !urls.every(url => typeof url === 'string' && /^turns?:[^\s/?#@]+(?:\?transport=(?:udp|tcp))?$/i.test(url)) || !username || !credential) {
|
||||
throw new Error('TURN opt-in requires a turn: or turns: address, username and password.');
|
||||
}
|
||||
iceServers.push({ urls: turnUrl, username, credential });
|
||||
@@ -24,20 +53,43 @@ export function iceConfiguration({ stunUrl = null, allowTurn = false, turnUrl =
|
||||
return { iceServers };
|
||||
}
|
||||
|
||||
export function createPeerConnection(options) {
|
||||
export async function fetchTurnOptions(options: IceOptions, endpoint: string, { signal, fetchImpl = fetch }: { signal?: AbortSignal; fetchImpl?: CredentialFetch } = {}): Promise<IceOptions> {
|
||||
if (!options.allowTurn || !options.managedTurn || !endpoint) return options;
|
||||
const response = await fetchImpl(endpoint, { credentials: 'same-origin', cache: 'no-store', signal });
|
||||
if (!response.ok) throw new Error('Could not obtain TURN credentials. Check the local dev server.');
|
||||
const data: unknown = await response.json();
|
||||
if (!isRecord(data) || typeof data.expiresAt !== 'number' || !Number.isFinite(data.expiresAt) ||
|
||||
data.expiresAt <= Date.now() / 1000 + 30 || !Array.isArray(data.iceServers)) {
|
||||
throw new Error('Missing or expired TURN credentials.');
|
||||
}
|
||||
const turn: unknown = data.iceServers.find((server: unknown) => {
|
||||
if (!isRecord(server)) return false;
|
||||
const urls: unknown[] = Array.isArray(server.urls) ? server.urls : [server.urls];
|
||||
return urls.length > 0 && urls.every(url => typeof url === 'string' && /^turns?:/i.test(url));
|
||||
});
|
||||
if (!isRecord(turn) || typeof turn.username !== 'string' || typeof turn.credential !== 'string' ||
|
||||
!(typeof turn.urls === 'string' || isStringArray(turn.urls))) {
|
||||
throw new Error('Missing or invalid TURN credentials.');
|
||||
}
|
||||
const result = { ...options, turnUrl: turn.urls, username: turn.username, credential: turn.credential };
|
||||
iceConfiguration(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function createPeerConnection(options: IceOptions) {
|
||||
return new RTCPeerConnection(iceConfiguration(options));
|
||||
}
|
||||
|
||||
export function waitForIceComplete(pc, { signal, timeout = 30000 } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let timer;
|
||||
export function waitForIceComplete(pc: IcePeer, { signal, timeout = 30000 }: WaitOptions = {}) {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
pc.removeEventListener('icegatheringstatechange', check);
|
||||
pc.removeEventListener('connectionstatechange', check);
|
||||
signal?.removeEventListener('abort', aborted);
|
||||
};
|
||||
const finish = (err) => { cleanup(); err ? reject(err) : resolve(); };
|
||||
const finish = (err?: Error) => { cleanup(); err ? reject(err) : resolve(); };
|
||||
const aborted = () => finish(new Error('Connection cancelled.'));
|
||||
const check = () => {
|
||||
if (signal?.aborted || pc.connectionState === 'closed') aborted();
|
||||
@@ -51,7 +103,7 @@ export function waitForIceComplete(pc, { signal, timeout = 30000 } = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
export function validateDescription(sdp, { allowTurn = false } = {}) {
|
||||
export function validateDescription(sdp: unknown, { allowTurn = false }: Pick<IceOptions, 'allowTurn'> = {}) {
|
||||
if (typeof sdp !== 'string' || sdp.length > MAX_SIGNAL_LENGTH || /[^\x09\x0A\x0D\x20-\x7E]/.test(sdp)) {
|
||||
throw new Error('Invalid connection description.');
|
||||
}
|
||||
@@ -71,55 +123,58 @@ export function validateDescription(sdp, { allowTurn = false } = {}) {
|
||||
return fingerprints[0].slice('a=fingerprint:sha-256 '.length).toUpperCase().replaceAll(':', ' ');
|
||||
}
|
||||
|
||||
export function getFingerprints(pc, options) {
|
||||
export function getFingerprints(pc: { localDescription: { sdp: string } | null; remoteDescription: { sdp: string } | null }, options?: Pick<IceOptions, 'allowTurn'>): Fingerprints {
|
||||
return {
|
||||
local: validateDescription(pc.localDescription?.sdp, options),
|
||||
remote: validateDescription(pc.remoteDescription?.sdp, options),
|
||||
};
|
||||
}
|
||||
|
||||
export function encodeSignal(sdp) {
|
||||
export function encodeSignal(sdp: string) {
|
||||
const code = btoa(JSON.stringify({ version: 2, sdp })).replace(/=+$/, '');
|
||||
if (code.length > MAX_SIGNAL_LENGTH) throw new Error('Connection code is too large. Reduce the configured network interfaces and try again.');
|
||||
return code;
|
||||
}
|
||||
|
||||
export function decodeSignal(text, options) {
|
||||
export function decodeSignal(text: unknown, options?: Pick<IceOptions, 'allowTurn'>): string {
|
||||
if (typeof text !== 'string' || text.length > MAX_SIGNAL_LENGTH) throw new Error('Connection code is too large.');
|
||||
try {
|
||||
const clean = text.trim().replace(/\s+/g, '');
|
||||
const data = JSON.parse(atob(clean));
|
||||
if (data?.version !== 2) throw new Error('Both people need the current HellCon version.');
|
||||
const data: unknown = JSON.parse(atob(clean));
|
||||
if (!isRecord(data) || data.version !== 2) throw new Error('Both people need the current HellCon version.');
|
||||
if (typeof data.sdp !== 'string') throw new Error('Invalid connection description.');
|
||||
validateDescription(data.sdp, options);
|
||||
return data.sdp;
|
||||
} catch (err) {
|
||||
if (err instanceof SyntaxError || err.name === 'InvalidCharacterError') throw new Error('Invalid connection code. Paste the complete code.');
|
||||
if (err instanceof SyntaxError || asError(err).name === 'InvalidCharacterError') throw new Error('Invalid connection code. Paste the complete code.');
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function createOfferCode(pc, options = {}) {
|
||||
export async function createOfferCode(pc: RTCPeerConnection, options: SignalOptions = {}) {
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
await waitForIceComplete(pc, options);
|
||||
if (!pc.localDescription) throw new Error('Missing local connection description.');
|
||||
validateDescription(pc.localDescription.sdp, options);
|
||||
return encodeSignal(pc.localDescription.sdp);
|
||||
}
|
||||
|
||||
export async function createAnswerCode(pc, text, options = {}) {
|
||||
export async function createAnswerCode(pc: RTCPeerConnection, text: string, options: SignalOptions = {}) {
|
||||
await pc.setRemoteDescription({ type: 'offer', sdp: decodeSignal(text, options) });
|
||||
await pc.setLocalDescription(await pc.createAnswer());
|
||||
await waitForIceComplete(pc, options);
|
||||
if (!pc.localDescription) throw new Error('Missing local connection description.');
|
||||
validateDescription(pc.localDescription.sdp, options);
|
||||
return encodeSignal(pc.localDescription.sdp);
|
||||
}
|
||||
|
||||
export function acceptAnswerCode(pc, text, options) {
|
||||
export function acceptAnswerCode(pc: RTCPeerConnection, text: string, options?: SignalOptions) {
|
||||
return pc.setRemoteDescription({ type: 'answer', sdp: decodeSignal(text, options) });
|
||||
}
|
||||
|
||||
export function waitForBufferDrain(dc, { signal, timeout = 60000 } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let timer;
|
||||
export function waitForBufferDrain(dc: BufferedChannel, { signal, timeout = 60000 }: WaitOptions = {}) {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
dc.removeEventListener('bufferedamountlow', check);
|
||||
@@ -127,7 +182,7 @@ export function waitForBufferDrain(dc, { signal, timeout = 60000 } = {}) {
|
||||
dc.removeEventListener('error', failed);
|
||||
signal?.removeEventListener('abort', failed);
|
||||
};
|
||||
const finish = err => { cleanup(); err ? reject(err) : resolve(); };
|
||||
const finish = (err?: Error) => { cleanup(); err ? reject(err) : resolve(); };
|
||||
const failed = () => finish(new Error('Transfer interrupted.'));
|
||||
const check = () => {
|
||||
if (signal?.aborted || dc.readyState !== 'open') failed();
|
||||
File renamed without changes.
@@ -0,0 +1,89 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHmac } from 'node:crypto';
|
||||
import { iceMiddleware } from '../dev/ice-server.ts';
|
||||
import { fetchTurnOptions } from '../src/lib/webrtc.ts';
|
||||
|
||||
interface Credentials {
|
||||
expiresAt: number;
|
||||
iceServers: [{ urls: string }, { urls: string[]; username: string; credential: string }];
|
||||
}
|
||||
interface ResponseResult {
|
||||
status: number;
|
||||
headers: Record<string, string>;
|
||||
body?: Credentials;
|
||||
next?: boolean;
|
||||
}
|
||||
function request(handler: ReturnType<typeof iceMiddleware>, { method = 'GET', url = '/api/ice-servers', headers = { host: '127.0.0.1:5173' } }: { method?: string; url?: string; headers?: Record<string, string> } = {}) {
|
||||
const result: ResponseResult = { status: 200, headers: {} };
|
||||
handler({ method, url, headers }, {
|
||||
setHeader(key, value) { result.headers[key] = value; },
|
||||
writeHead(status, headers) { result.status = status; Object.assign(result.headers, headers); },
|
||||
end(body) { result.body = body ? JSON.parse(body) : undefined; },
|
||||
}, () => { result.next = true; });
|
||||
return result;
|
||||
}
|
||||
|
||||
test('temporary credentials match coturn HMAC, expire in an hour and never expose the secret', () => {
|
||||
const secret = 'test-only-secret';
|
||||
const handler = iceMiddleware({ TURN_SECRET: secret });
|
||||
const first = request(handler), second = request(handler);
|
||||
assert.equal(first.headers['Cache-Control'], 'no-store');
|
||||
assert.ok(first.body); assert.ok(second.body);
|
||||
const { expiresAt, iceServers } = first.body;
|
||||
const turn = iceServers[1];
|
||||
assert.ok(Math.abs(expiresAt - Date.now() / 1000 - 3600) < 2);
|
||||
assert.ok(turn.username.startsWith(`${expiresAt}:`));
|
||||
assert.notEqual(turn.username, second.body.iceServers[1].username);
|
||||
assert.equal(turn.credential, createHmac('sha1', secret).update(turn.username).digest('base64'));
|
||||
assert.deepEqual(turn.urls, ['turn:127.0.0.1:3478?transport=udp', 'turn:127.0.0.1:3478?transport=tcp']);
|
||||
assert.ok(!JSON.stringify(first.body).includes(secret));
|
||||
});
|
||||
|
||||
test('development endpoint rejects cross-site issuance and unsupported methods', () => {
|
||||
assert.throws(() => iceMiddleware({}), /TURN_SECRET/);
|
||||
const handler = iceMiddleware({ TURN_SECRET: 'test' });
|
||||
assert.equal(request(handler, { method: 'POST' }).status, 405);
|
||||
assert.equal(request(handler, { headers: { 'sec-fetch-site': 'cross-site' } }).status, 403);
|
||||
assert.equal(request(handler, { headers: { host: 'localhost', origin: 'http://elsewhere' } }).status, 403);
|
||||
assert.equal(request(handler, { url: '/other' }).next, true);
|
||||
});
|
||||
|
||||
test('managed credentials require opt-in, refresh each connection, and fail closed', async () => {
|
||||
let calls = 0;
|
||||
const handler = iceMiddleware({ TURN_SECRET: 'test' });
|
||||
const fetchImpl = async () => { calls++; return { ok: true, json: async () => request(handler).body }; };
|
||||
await fetchTurnOptions({ managedTurn: true }, '/api/ice-servers', { fetchImpl });
|
||||
await fetchTurnOptions({ allowTurn: true, managedTurn: false }, '/api/ice-servers', { fetchImpl });
|
||||
assert.equal(calls, 0);
|
||||
const options = { allowTurn: true, managedTurn: true, stunUrl: null };
|
||||
const first = await fetchTurnOptions(options, '/api/ice-servers', { fetchImpl });
|
||||
const second = await fetchTurnOptions(options, '/api/ice-servers', { fetchImpl });
|
||||
assert.equal(calls, 2);
|
||||
assert.notEqual(first.username, second.username);
|
||||
assert.equal(first.stunUrl, null, 'User STUN choice must be preserved');
|
||||
await assert.rejects(fetchTurnOptions(options, '/api/ice-servers', { fetchImpl: async () => ({ ok: false, json: async () => null }) }), /Could not obtain/);
|
||||
await assert.rejects(fetchTurnOptions(options, '/api/ice-servers', { fetchImpl: async () => ({ ok: true, json: async () => ({ expiresAt: 1, iceServers: [] }) }) }), /expired/);
|
||||
const controller = new AbortController(); controller.abort();
|
||||
await assert.rejects(fetchTurnOptions(options, '/api/ice-servers', { signal: controller.signal, fetchImpl: async (_url, { signal }) => { signal?.throwIfAborted(); throw new Error('Expected abort'); } }), { name: 'AbortError' });
|
||||
});
|
||||
|
||||
test('managed credentials reject malformed response shapes and non-string credentials', async () => {
|
||||
const expiresAt = Date.now() / 1000 + 3600;
|
||||
const turn = { urls: 'turn:localhost:3478', username: 'user', credential: 'password' };
|
||||
for (const body of [
|
||||
null,
|
||||
[],
|
||||
{ expiresAt, iceServers: {} },
|
||||
{ expiresAt, iceServers: [null] },
|
||||
{ expiresAt, iceServers: [{ ...turn, urls: [null] }] },
|
||||
{ expiresAt, iceServers: [{ ...turn, urls: [] }] },
|
||||
{ expiresAt, iceServers: [{ ...turn, username: 123 }] },
|
||||
{ expiresAt, iceServers: [{ ...turn, credential: {} }] },
|
||||
{ expiresAt, iceServers: [{ ...turn, urls: 'turn:bad host' }] },
|
||||
]) {
|
||||
await assert.rejects(fetchTurnOptions({ allowTurn: true, managedTurn: true }, '/api/ice-servers', {
|
||||
fetchImpl: async () => ({ ok: true, json: async () => body }),
|
||||
}), /credentials|TURN opt-in/);
|
||||
}
|
||||
});
|
||||
@@ -1,45 +1,53 @@
|
||||
import test from 'node:test';
|
||||
import test, { type TestContext } from 'node:test';
|
||||
import type { TransferChannel, TransferOptions, TransferResult } from '../src/lib/transfer.ts';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Transfer, MEMORY_LIMIT, FILE_LIMIT, validateMetadata } from '../src/lib/transfer.js';
|
||||
import { CHUNK_SIZE, MAX_BUFFERED } from '../src/lib/webrtc.js';
|
||||
import { Transfer, MEMORY_LIMIT, FILE_LIMIT, validateMetadata } from '../src/lib/transfer.ts';
|
||||
import { CHUNK_SIZE, MAX_BUFFERED } from '../src/lib/webrtc.ts';
|
||||
|
||||
class Channel extends EventTarget {
|
||||
readyState = 'open';
|
||||
class Channel extends EventTarget implements TransferChannel {
|
||||
binaryType: BinaryType = 'arraybuffer';
|
||||
bufferedAmountLowThreshold = 0;
|
||||
peer: Channel | null = null;
|
||||
onopen: TransferChannel['onopen'] = null;
|
||||
onmessage: TransferChannel['onmessage'] = null;
|
||||
onclose: TransferChannel['onclose'] = null;
|
||||
onerror: (() => void) | null = null;
|
||||
readyState: RTCDataChannelState = 'open';
|
||||
bufferedAmount = 0;
|
||||
frames = [];
|
||||
send(data) {
|
||||
frames: (string | ArrayBuffer)[] = [];
|
||||
send(data: string | ArrayBuffer) {
|
||||
if (this.readyState !== 'open') throw new Error('closed');
|
||||
this.frames.push(data);
|
||||
queueMicrotask(() => this.peer?.onmessage?.({ data }));
|
||||
queueMicrotask(() => this.peer?.onmessage?.(new MessageEvent('message', { data })));
|
||||
}
|
||||
close() { this.readyState = 'closed'; this.dispatchEvent(new Event('close')); }
|
||||
}
|
||||
const tick = () => new Promise(resolve => setImmediate(resolve));
|
||||
async function until(check) {
|
||||
const tick = () => new Promise<void>(resolve => setImmediate(resolve));
|
||||
async function until(check: () => boolean) {
|
||||
for (let i = 0; i < 500; i++) { if (check()) return; await tick(); }
|
||||
assert.fail('Condition did not become true');
|
||||
}
|
||||
const message = (transfer, type, data = {}) => transfer.enqueue(JSON.stringify({ v: 2, type, ...data }));
|
||||
const message = (transfer: Transfer, type: string, data: Record<string, unknown> = {}) => transfer.enqueue(JSON.stringify({ v: 2, type, ...data }));
|
||||
const meta = (size = 1) => ({ name: 'example.txt', size, mime: 'text/plain' });
|
||||
function receiver(t, options = {}) {
|
||||
function receiver(t: TestContext, options: TransferOptions = {}) {
|
||||
const dc = new Channel();
|
||||
const errors = [];
|
||||
const errors: string[] = [];
|
||||
const r = new Transfer(dc, { onError: err => errors.push(err.message), ...options });
|
||||
t.after(() => r.close());
|
||||
return { r, dc, errors };
|
||||
}
|
||||
async function prepared(t, size = 1, options = {}) {
|
||||
async function prepared(t: TestContext, size = 1, options: TransferOptions = {}) {
|
||||
const result = receiver(t, options);
|
||||
result.r.verify(); message(result.r, 'ready'); message(result.r, 'meta', meta(size));
|
||||
await result.r.queue;
|
||||
assert.equal(result.r.state, 'choose-storage');
|
||||
return result;
|
||||
}
|
||||
function pair(t, size = CHUNK_SIZE * 80 + 3, receiverOptions = {}) {
|
||||
function pair(t: TestContext, size = CHUNK_SIZE * 80 + 3, receiverOptions: TransferOptions = {}) {
|
||||
const a = new Channel(), b = new Channel(); a.peer = b; b.peer = a;
|
||||
const source = new Uint8Array(size); source.fill(123);
|
||||
const file = new File([source], 'payload.bin');
|
||||
const errors = [];
|
||||
const errors: string[] = [];
|
||||
const sender = new Transfer(a, { file, onError: err => errors.push(err.message) });
|
||||
const receiver = new Transfer(b, { onError: err => errors.push(err.message), ...receiverOptions });
|
||||
t.after(() => { sender.close(); receiver.close(); });
|
||||
@@ -50,19 +58,20 @@ test('no filename or contents before both explicit verification confirmations',
|
||||
const { sender, receiver, a } = pair(t);
|
||||
await tick(); assert.equal(a.frames.length, 0);
|
||||
sender.verify(); await tick();
|
||||
assert.deepEqual(a.frames.map(JSON.parse).map(m => m.type), ['ready']);
|
||||
assert.deepEqual(a.frames.map(frame => { assert.equal(typeof frame, 'string'); return JSON.parse(frame as string); }).map(m => m.type), ['ready']);
|
||||
receiver.verify(); await until(() => receiver.state === 'choose-storage');
|
||||
assert.deepEqual(a.frames.map(JSON.parse).map(m => m.type), ['ready', 'meta']);
|
||||
assert.deepEqual(a.frames.map(frame => { assert.equal(typeof frame, 'string'); return JSON.parse(frame as string); }).map(m => m.type), ['ready', 'meta']);
|
||||
assert.equal(sender.sent, 0);
|
||||
});
|
||||
|
||||
test('verified, accepted memory transfer preserves bytes and requires receipt ACK', async t => {
|
||||
let result;
|
||||
let result: TransferResult | undefined;
|
||||
const { sender, receiver, source, errors } = pair(t, undefined, { onComplete: value => { result = value; } });
|
||||
sender.verify(); receiver.verify();
|
||||
await until(() => receiver.state === 'choose-storage'); receiver.accept();
|
||||
await until(() => sender.state === 'done');
|
||||
assert.deepEqual(errors, []);
|
||||
assert.ok(result?.blob);
|
||||
assert.deepEqual(new Uint8Array(await result.blob.arrayBuffer()), source);
|
||||
assert.equal(sender.acked, source.length);
|
||||
assert.equal(result.blob.type, 'application/octet-stream');
|
||||
@@ -76,20 +85,20 @@ test('empty file still requires acceptance and completion ACK', async t => {
|
||||
});
|
||||
|
||||
test('disk transfer waits for storage close before acknowledging completion', async t => {
|
||||
let release, saved = 0;
|
||||
let release: (() => void) | undefined, saved = 0;
|
||||
const { sender, receiver, source } = pair(t);
|
||||
sender.verify(); receiver.verify(); await until(() => receiver.state === 'choose-storage');
|
||||
receiver.accept({ async write(bytes) { saved += bytes.byteLength; }, close() { return new Promise(resolve => { release = resolve; }); }, async abort() {} });
|
||||
receiver.accept({ async write(bytes) { saved += bytes.byteLength; }, close() { return new Promise<void>(resolve => { release = resolve; }); }, async abort() {} });
|
||||
await until(() => receiver.state === 'saving');
|
||||
assert.equal(sender.state, 'awaiting-receipt'); assert.equal(saved, source.length);
|
||||
release(); await until(() => sender.state === 'done');
|
||||
assert.ok(release); release(); await until(() => sender.state === 'done');
|
||||
});
|
||||
|
||||
test('slow storage bounds the sender to its acknowledged window', async t => {
|
||||
let release;
|
||||
let release: (() => void) | undefined;
|
||||
const { sender, receiver } = pair(t);
|
||||
sender.verify(); receiver.verify(); await until(() => receiver.state === 'choose-storage');
|
||||
receiver.accept({ write() { return new Promise(resolve => { release = resolve; }); }, async close() {}, async abort() { release?.(); } });
|
||||
receiver.accept({ write() { return new Promise<void>(resolve => { release = resolve; }); }, async close() {}, async abort() { release?.(); } });
|
||||
await until(() => sender.sent === MAX_BUFFERED);
|
||||
await tick(); assert.equal(sender.acked, 0); assert.equal(sender.sent, MAX_BUFFERED);
|
||||
receiver.close(); sender.close(); release?.();
|
||||
@@ -132,20 +141,21 @@ test('completed files cannot be extended by later frames', async t => {
|
||||
});
|
||||
|
||||
test('post-completion transport errors preserve the received file (Firefox shutdown)', async t => {
|
||||
let result;
|
||||
let result: TransferResult | undefined;
|
||||
const { r, dc, errors } = await prepared(t, 1, { onComplete: value => { result = value; } });
|
||||
r.accept(); r.enqueue(Uint8Array.of(123).buffer); message(r, 'end'); await r.queue;
|
||||
assert.equal(r.state, 'done');
|
||||
dc.onerror(new Event('error'));
|
||||
dc.onerror?.();
|
||||
assert.equal(r.state, 'done'); assert.equal(r.closed, true);
|
||||
assert.deepEqual(errors, []);
|
||||
assert.ok(result?.blob);
|
||||
assert.deepEqual(new Uint8Array(await result.blob.arrayBuffer()), Uint8Array.of(123));
|
||||
});
|
||||
|
||||
test('transport errors before receipt completion remain fatal', async t => {
|
||||
const { r, dc, errors } = await prepared(t, 1);
|
||||
r.accept(); r.enqueue(new ArrayBuffer(1)); await r.queue;
|
||||
dc.onerror(new Event('error'));
|
||||
dc.onerror?.();
|
||||
assert.equal(r.state, 'closed'); assert.equal(r.chunks.length, 0);
|
||||
assert.deepEqual(errors, ['Data channel failed.']);
|
||||
});
|
||||
@@ -157,23 +167,24 @@ test('memory limit requires an explicit disk destination for larger files', asyn
|
||||
});
|
||||
|
||||
test('metadata rejects invalid sizes, misleading names and invalid types', () => {
|
||||
for (const size of [-1, 0.5, '10', NaN, Infinity, FILE_LIMIT + 1]) assert.throws(() => validateMetadata(meta(size)));
|
||||
for (const size of [-1, 0.5, '10', NaN, Infinity, FILE_LIMIT + 1]) assert.throws(() => validateMetadata({ ...meta(), size }));
|
||||
for (const name of ['', '../secret', 'a\\b', 'bad\u202efile.exe', 'a'.repeat(256)]) assert.throws(() => validateMetadata({ ...meta(), name }));
|
||||
assert.throws(() => validateMetadata({ ...meta(), mime: {} }));
|
||||
});
|
||||
|
||||
test('cancellation aborts pending disk writes and drops retained buffers', async t => {
|
||||
let aborted = false, release;
|
||||
let aborted = false;
|
||||
let release: (() => void) | undefined;
|
||||
const { r } = await prepared(t);
|
||||
r.accept({ write() { return new Promise(resolve => { release = resolve; }); }, async abort() { aborted = true; release?.(); } });
|
||||
r.accept({ write() { return new Promise<void>(resolve => { release = resolve; }); }, async close() {}, async abort() { aborted = true; release?.(); } });
|
||||
r.enqueue(new ArrayBuffer(1)); await tick(); r.close(); await r.queue;
|
||||
assert.equal(aborted, true); assert.equal(r.chunks.length, 0); assert.equal(r.received, 0);
|
||||
});
|
||||
|
||||
test('peer flooding exceeds bounded queue and aborts storage', async t => {
|
||||
let release;
|
||||
let release: (() => void) | undefined;
|
||||
const { r } = await prepared(t, MEMORY_LIMIT);
|
||||
r.accept({ write() { return new Promise(resolve => { release = resolve; }); }, async abort() { release?.(); } });
|
||||
r.accept({ write() { return new Promise<void>(resolve => { release = resolve; }); }, async close() {}, async abort() { release?.(); } });
|
||||
r.enqueue(new ArrayBuffer(CHUNK_SIZE)); await tick();
|
||||
for (let i = 0; i < 130; i++) r.enqueue(new ArrayBuffer(CHUNK_SIZE));
|
||||
assert.equal(r.closed, true); release?.(); await r.queue;
|
||||
@@ -181,15 +192,15 @@ test('peer flooding exceeds bounded queue and aborts storage', async t => {
|
||||
|
||||
test('stalled transfers time out rather than reporting completion', async t => {
|
||||
const { r, errors } = await prepared(t, 1, { timeout: 10 });
|
||||
r.accept(); await new Promise(resolve => setTimeout(resolve, 30));
|
||||
r.accept(); await new Promise<void>(resolve => setTimeout(resolve, 30));
|
||||
assert.equal(r.closed, true); assert.match(errors[0], /timed out/);
|
||||
});
|
||||
|
||||
test('storage failure never sends successful receipt', async t => {
|
||||
const { r, dc } = await prepared(t);
|
||||
r.accept({ async write() { throw new Error('Disk full'); }, async abort() {} });
|
||||
r.accept({ async write() { throw new Error('Disk full'); }, async close() {}, async abort() {} });
|
||||
r.enqueue(new ArrayBuffer(1)); message(r, 'end'); await r.queue;
|
||||
assert.equal(r.closed, true); assert.equal(dc.frames.some(frame => JSON.parse(frame).type === 'complete'), false);
|
||||
assert.equal(r.closed, true); assert.equal(dc.frames.some(frame => typeof frame === 'string' && JSON.parse(frame).type === 'complete'), false);
|
||||
});
|
||||
|
||||
test('tiny chunks cannot bypass the memory cap through per-chunk overhead', async t => {
|
||||
@@ -1,6 +1,6 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { iceConfiguration, validateDescription, getFingerprints, encodeSignal, decodeSignal, waitForIceComplete, waitForBufferDrain, MAX_SIGNAL_LENGTH, MAX_BUFFERED } from '../src/lib/webrtc.js';
|
||||
import { iceConfiguration, validateDescription, getFingerprints, encodeSignal, decodeSignal, waitForIceComplete, waitForBufferDrain, MAX_SIGNAL_LENGTH, MAX_BUFFERED } from '../src/lib/webrtc.ts';
|
||||
const fingerprint = Array.from({ length: 32 }, (_, i) => i.toString(16).padStart(2, '0')).join(':');
|
||||
const sdp = `v=0\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=fingerprint:sha-256 ${fingerprint}\r\n`;
|
||||
|
||||
@@ -36,7 +36,7 @@ test('signals round-trip but reject legacy, malformed and oversized codes', () =
|
||||
assert.throws(() => decodeSignal(btoa(JSON.stringify({ version: 1, sdp }))));
|
||||
});
|
||||
|
||||
class Peer extends EventTarget { iceGatheringState = 'gathering'; connectionState = 'new'; }
|
||||
class Peer extends EventTarget { iceGatheringState: RTCIceGatheringState = 'gathering'; connectionState: RTCPeerConnectionState = 'new'; }
|
||||
|
||||
test('ICE gathering waits for completion, rejects timeout, and supports cancellation', async () => {
|
||||
const pc = new Peer();
|
||||
@@ -49,7 +49,11 @@ test('ICE gathering waits for completion, rejects timeout, and supports cancella
|
||||
});
|
||||
|
||||
test('buffer wait resolves when already drained and rejects close or cancellation', async () => {
|
||||
const channel = new EventTarget(); channel.readyState = 'open'; channel.bufferedAmount = 0;
|
||||
const channel = new class extends EventTarget {
|
||||
readyState: RTCDataChannelState = 'open';
|
||||
bufferedAmount = 0;
|
||||
bufferedAmountLowThreshold = 0;
|
||||
}();
|
||||
await waitForBufferDrain(channel);
|
||||
channel.bufferedAmount = MAX_BUFFERED + 1;
|
||||
const wait = waitForBufferDrain(channel); channel.readyState = 'closed'; channel.dispatchEvent(new Event('close'));
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"types": ["node", "vite/client"],
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noEmit": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"isolatedModules": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.vue", "dev/**/*.ts", "scripts/**/*.ts", "tests/**/*.ts", "vite.config.ts"]
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
|
||||
// base './' so the built app can be served from any static path (or opened from a subdirectory)
|
||||
export default defineConfig({
|
||||
base: './',
|
||||
plugins: [vue()],
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { defineConfig, loadEnv } from 'vite';
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
import { iceMiddleware } from './dev/ice-server.ts';
|
||||
|
||||
// base './' so the built app can be served from any static path (or opened from a subdirectory)
|
||||
export default defineConfig(({ mode }) => {
|
||||
const env = { ...loadEnv(mode, process.cwd(), ''), ...process.env };
|
||||
return {
|
||||
base: './',
|
||||
server: { host: '127.0.0.1' },
|
||||
plugins: [vue(), {
|
||||
name: 'local-turn-credentials',
|
||||
configureServer(server) {
|
||||
if (env.VITE_ICE_ENDPOINT === '/api/ice-servers') server.middlewares.use(iceMiddleware(env));
|
||||
},
|
||||
}],
|
||||
};
|
||||
});
|
||||
Reference in new issue
Block a user