refactor(web): migrate to Bun and TypeScript with README screenshots
This commit is contained in:
parent
87372041dd
commit
d6a9745df0
28 changed files with 3152 additions and 386 deletions
1
.bun-version
Normal file
1
.bun-version
Normal file
|
|
@ -0,0 +1 @@
|
|||
1.4.4
|
||||
53
README.md
53
README.md
|
|
@ -3,7 +3,8 @@
|
|||
> Public project website and account frontend for VNOX Central.
|
||||
|
||||
[](LICENSE)
|
||||
[](https://nodejs.org/)
|
||||
[](https://bun.sh/)
|
||||
[](https://www.typescriptlang.org/)
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -11,7 +12,23 @@
|
|||
|
||||
A lightweight, self-hosted website for VNOX, a Rust voice and text communication platform. This is a separate repository from [VNOX Client](https://git.wihuk.pro/boba/VNOX-Client) and [VNOX Server](https://git.wihuk.pro/boba/VNOX-Server).
|
||||
|
||||
The site uses plain HTML, CSS and JavaScript modules. There are **no runtime or build dependencies**, third-party scripts, analytics or external fonts.
|
||||
The application is written in **TypeScript**, HTML and CSS. **Bun** installs dependencies, runs development previews and tests, formats source and bundles production assets. Strict types cover Hub responses, sessions, profiles, language keys and UI state; untrusted JSON is also validated at runtime.
|
||||
|
||||
Browsers execute JavaScript, so Bun compiles the TypeScript source into one static browser bundle. A frontend framework is unnecessary for the landing page and account flow. There are **no browser runtime dependencies**, third-party scripts, analytics or external fonts. Production serves static files through Nginx; neither Bun nor Node.js runs on the website server.
|
||||
|
||||
## Screenshots
|
||||
|
||||
Actual screenshots of [central.loki-code.dev](https://central.loki-code.dev), captured on 24 October 2026 in a fresh, anonymous browser context. No private account data or credentials appear in these images.
|
||||
|
||||
### Project page
|
||||
|
||||

|
||||
|
||||
### Central account
|
||||
|
||||

|
||||
|
||||
[Mobile screenshot](docs/screenshots/landing-mobile.png)
|
||||
|
||||
## Features
|
||||
|
||||
|
|
@ -25,32 +42,38 @@ The website does not implement identity verification itself. The Rust Hub exchan
|
|||
|
||||
## Development
|
||||
|
||||
Requires Node.js 22 or newer. No `npm install` is needed.
|
||||
Requires **Bun 1.4.4** or newer. The verified version is pinned in `packageManager` and `.bun-version`; development package versions and integrity hashes are committed in `bun.lock`.
|
||||
|
||||
```sh
|
||||
npm run dev # Local preview at http://127.0.0.1:4176
|
||||
npm test # Node tests: locale parity, API/security and preview routing
|
||||
npm run build # Copy public/ and src/ into dist/, normalize permissions
|
||||
npm run preview # Preview the built dist/ directory
|
||||
bun install --frozen-lockfile
|
||||
bun run dev # Local preview at http://127.0.0.1:4176
|
||||
bun run check # Strict TypeScript checking, without emitting files
|
||||
bun test # API, locale and Bun preview regression tests
|
||||
bun run build # Check types and create the static dist/ release
|
||||
bun run preview # Preview the built dist/ directory
|
||||
bun run format:check # Check formatting with Bun's built-in formatter
|
||||
bun run format # Format TypeScript, CSS, HTML and configuration
|
||||
```
|
||||
|
||||
Optional browser QA: `python3 tests/browser_qa.py` uses an existing local Playwright installation and Chromium against the running preview. It does not add a project dependency.
|
||||
No Node.js installation is required. TypeScript and Bun type definitions are development-only dependencies; the browser bundle contains only this application's code. See the [dependency audit](docs/dependencies.md) for checked versions and licenses.
|
||||
|
||||
Set `PORT=4180` to change the preview port. The preview intentionally returns HTTP 503 for API requests; it contains no fake backend or development credentials.
|
||||
Set `PORT=4180` to change the preview port. Reload the browser after editing source: the development preview compiles the current TypeScript when `/src/app.js` is requested. The preview intentionally returns HTTP 503 for API requests; it contains no fake backend or development credentials.
|
||||
|
||||
Optional browser QA: `python3 tests/browser_qa.py` uses an existing local Playwright installation and Chromium against the running preview. It does not add a JavaScript project dependency.
|
||||
|
||||
## Structure
|
||||
|
||||
```text
|
||||
public/ HTML entry point and self-hosted assets
|
||||
src/ Application, API helpers, RU/EN catalogs and styling
|
||||
scripts/ Dependency-free build and loopback preview
|
||||
tests/ Node regression tests
|
||||
docs/ Design direction and Nginx integration example
|
||||
src/ Typed application, API helpers, RU/EN catalogs and CSS
|
||||
scripts/ Bun browser bundling, static build and loopback preview
|
||||
tests/ Bun regression tests and optional browser QA
|
||||
docs/ Design, deployment notes and repository-hosted screenshots
|
||||
```
|
||||
|
||||
## Hub integration
|
||||
|
||||
Serve `dist/` at the same HTTPS origin as VNOX Hub. `/` and `/account` use `index.html`; preserve proxy routes `/v1/`, `/health`, `/ready` and `/version`. See [Nginx example](docs/nginx-static.conf).
|
||||
Serve `dist/` at the same HTTPS origin as VNOX Hub. `/` and `/account` use `index.html`; preserve proxy routes `/v1/`, `/health`, `/ready` and `/version`. See the [Nginx example](docs/nginx-static.conf).
|
||||
|
||||
| Endpoint | Frontend behaviour |
|
||||
| --- | --- |
|
||||
|
|
@ -63,7 +86,7 @@ The Hub sets Secure, HttpOnly cookies. Tokens are never stored in browser storag
|
|||
|
||||
## Contributing
|
||||
|
||||
Keep RU/EN catalog keys aligned, render profile values as text and retain keyboard navigation and reduced-motion support. Use descriptive Conventional Commits such as `fix(web): preserve account state when changing language`. Run tests and build before submitting a focused PR; include screenshots for visual changes. See [verification notes](docs/verification.md) for browser QA and current limits.
|
||||
Keep RU/EN catalog keys aligned, render profile values as text and retain keyboard navigation and reduced-motion support. Use descriptive Conventional Commits such as `fix(web): preserve account state when changing language`. Run type checks, tests, formatting checks and a production build before submitting a focused PR; include screenshots for visual changes. See [verification notes](docs/verification.md) for browser QA and current limits.
|
||||
|
||||
## License
|
||||
|
||||
|
|
|
|||
64
bun.lock
Normal file
64
bun.lock
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
{
|
||||
"lockfileVersion": 2,
|
||||
"configVersion": 1,
|
||||
"workspaces": {
|
||||
"": {
|
||||
"name": "vnox-web",
|
||||
"devDependencies": {
|
||||
"@types/bun": "1.4.4",
|
||||
"typescript": "7.0.2",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@types/bun": ["@types/bun@1.4.4", "", { "dependencies": { "bun-types": "1.4.4" } }, "sha512-9wkRDXUXK124pEnAutE6n/l18j+i9GC5IAHK8TmX/2nlySETmky0OU6yL5U8pW1AoKh++AN9auDCr647BfurjQ=="],
|
||||
|
||||
"@types/node": ["@types/node@26.6.5", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg=="],
|
||||
|
||||
"@typescript/typescript-aix-ppc64": ["@typescript/typescript-aix-ppc64@7.0.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="],
|
||||
|
||||
"@typescript/typescript-darwin-arm64": ["@typescript/typescript-darwin-arm64@7.0.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA=="],
|
||||
|
||||
"@typescript/typescript-darwin-x64": ["@typescript/typescript-darwin-x64@7.0.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA=="],
|
||||
|
||||
"@typescript/typescript-freebsd-arm64": ["@typescript/typescript-freebsd-arm64@7.0.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ=="],
|
||||
|
||||
"@typescript/typescript-freebsd-x64": ["@typescript/typescript-freebsd-x64@7.0.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw=="],
|
||||
|
||||
"@typescript/typescript-linux-arm": ["@typescript/typescript-linux-arm@7.0.2", "", { "os": "linux", "cpu": "arm" }, "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ=="],
|
||||
|
||||
"@typescript/typescript-linux-arm64": ["@typescript/typescript-linux-arm64@7.0.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ=="],
|
||||
|
||||
"@typescript/typescript-linux-loong64": ["@typescript/typescript-linux-loong64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ=="],
|
||||
|
||||
"@typescript/typescript-linux-mips64el": ["@typescript/typescript-linux-mips64el@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA=="],
|
||||
|
||||
"@typescript/typescript-linux-ppc64": ["@typescript/typescript-linux-ppc64@7.0.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA=="],
|
||||
|
||||
"@typescript/typescript-linux-riscv64": ["@typescript/typescript-linux-riscv64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ=="],
|
||||
|
||||
"@typescript/typescript-linux-s390x": ["@typescript/typescript-linux-s390x@7.0.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw=="],
|
||||
|
||||
"@typescript/typescript-linux-x64": ["@typescript/typescript-linux-x64@7.0.2", "", { "os": "linux", "cpu": "x64" }, "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A=="],
|
||||
|
||||
"@typescript/typescript-netbsd-arm64": ["@typescript/typescript-netbsd-arm64@7.0.2", "", { "os": "none", "cpu": "arm64" }, "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA=="],
|
||||
|
||||
"@typescript/typescript-netbsd-x64": ["@typescript/typescript-netbsd-x64@7.0.2", "", { "os": "none", "cpu": "x64" }, "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA=="],
|
||||
|
||||
"@typescript/typescript-openbsd-arm64": ["@typescript/typescript-openbsd-arm64@7.0.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ=="],
|
||||
|
||||
"@typescript/typescript-openbsd-x64": ["@typescript/typescript-openbsd-x64@7.0.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg=="],
|
||||
|
||||
"@typescript/typescript-sunos-x64": ["@typescript/typescript-sunos-x64@7.0.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g=="],
|
||||
|
||||
"@typescript/typescript-win32-arm64": ["@typescript/typescript-win32-arm64@7.0.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ=="],
|
||||
|
||||
"@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="],
|
||||
|
||||
"bun-types": ["bun-types@1.4.4", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ=="],
|
||||
|
||||
"typescript": ["typescript@7.0.2", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="],
|
||||
|
||||
"undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],
|
||||
}
|
||||
}
|
||||
42
docs/dependencies.md
Normal file
42
docs/dependencies.md
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
# Tool and dependency audit
|
||||
|
||||
Checked on 24 October 2026 against the official Bun and TypeScript releases and npm registry package metadata.
|
||||
|
||||
| Tool/package | Selected | Latest | License | Scope |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Bun | 1.4.4 | 1.4.4 | MIT | Development runtime, bundler, formatter and test runner |
|
||||
| `typescript` | 7.0.2 | 7.0.2 | Apache-2.0 | Strict project type checking and editor types |
|
||||
| `@types/bun` | 1.4.4 | 1.4.4 | MIT | Bun development API definitions |
|
||||
| `bun-types` | 1.4.4 | 1.4.4 | MIT | Transitive Bun definitions |
|
||||
| `@types/node` | 26.6.5 | 26.6.5 | MIT | Transitive definitions for compatible system APIs |
|
||||
| `@typescript/typescript-linux-x64` | 7.0.2 | 7.0.2 | Apache-2.0 | Native checker binary for the tested Linux x64 platform |
|
||||
| `undici-types` | 8.9.0 | 8.12.3 globally; 8.9.0 within the parent's allowed range | MIT | Transitive fetch definitions |
|
||||
|
||||
The latest `@types/node` constrains `undici-types` to `~8.9.0`. The lock uses the newest compatible version; no override bypasses that upstream constraint. Other optional TypeScript platform binaries in the lock are pinned to the same 7.0.2 release and are installed only on matching platforms. None of these packages is imported into browser code or required by Nginx in production.
|
||||
|
||||
Bun was verified using the official Linux x64 release archive, SHA-256 `bf8ccbfb2b0b80159e0f9a6d15c55317add8077534dbc6130a3edb52fccb395c`. Project verification used a task-local copy of Bun 1.4.4; it did not change the workstation's global runtime.
|
||||
|
||||
## Sources
|
||||
|
||||
- [Official Bun 1.4.4 release](https://github.com/oven-sh/bun/releases/tag/bun-v1.4.4)
|
||||
- [Official TypeScript 7.0.2 release](https://github.com/microsoft/TypeScript/releases/tag/v7.0.2)
|
||||
- [Bun TypeScript documentation](https://bun.sh/docs/runtime/typescript)
|
||||
- [Bun bundler documentation](https://bun.sh/docs/bundler)
|
||||
- [TypeScript package metadata](https://registry.npmjs.org/typescript/latest)
|
||||
- [Bun definitions metadata](https://registry.npmjs.org/@types/bun/latest)
|
||||
- [Node definitions metadata and Undici range](https://registry.npmjs.org/@types/node/latest)
|
||||
- [Undici definitions metadata](https://registry.npmjs.org/undici-types/latest)
|
||||
|
||||
## Reproduction
|
||||
|
||||
```sh
|
||||
bun install --frozen-lockfile
|
||||
bun outdated
|
||||
bun pm ls --all
|
||||
bun audit
|
||||
bun run check
|
||||
bun test
|
||||
bun run build
|
||||
```
|
||||
|
||||
The audit reported **no known vulnerabilities** across 25 checked lockfile packages. On Linux x64, six development packages were installed. `bun outdated` reported no outdated direct dependencies. The complete compatible resolution and integrity hashes are committed in `bun.lock`.
|
||||
9
docs/screenshots/README.md
Normal file
9
docs/screenshots/README.md
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
# Website screenshots
|
||||
|
||||
Captured on 24 October 2026 from `https://central.loki-code.dev` using a new anonymous Chromium context with Russian selected.
|
||||
|
||||
- `landing-desktop.png`: project landing page, 1440 × 1000.
|
||||
- `account-desktop.png`: anonymous account / GitHub sign-in, 1440 × 1000.
|
||||
- `landing-mobile.png`: landing page, 390 × 844.
|
||||
|
||||
No user logged in, no GitHub consent flow was started, and no private profiles, credentials or tokens are shown. These are actual website screenshots, not generated mockups. The labelled client illustration on the page remains illustrative; the native settings image embedded in the page is a real client screenshot.
|
||||
BIN
docs/screenshots/account-desktop.png
Normal file
BIN
docs/screenshots/account-desktop.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 77 KiB |
BIN
docs/screenshots/landing-desktop.png
Normal file
BIN
docs/screenshots/landing-desktop.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 113 KiB |
BIN
docs/screenshots/landing-mobile.png
Normal file
BIN
docs/screenshots/landing-mobile.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 55 KiB |
|
|
@ -1,13 +1,16 @@
|
|||
# Verification
|
||||
|
||||
Verified locally on 24 October 2026:
|
||||
Verified locally on 24 October 2026 using pinned Bun 1.4.4 and TypeScript 7.0.2:
|
||||
|
||||
- `npm test`: 7 Node tests passed, including exact catalog parity, authentication request options, malformed-session checks, avatar-origin validation and encoded preview-path traversal.
|
||||
- `npm run build`: static build completed; assets normalized to mode 0644, directories 0755.
|
||||
- `node --check src/app.js`: JavaScript syntax check passed.
|
||||
- `python3 tests/browser_qa.py`: passed with the workstation's existing Playwright and `/usr/bin/chromium`; no browser or dependency was installed by this project.
|
||||
- `bun install --frozen-lockfile`: committed resolution accepted without changes.
|
||||
- `bun run check`: strict TypeScript check passed for frontend, Bun scripts and tests.
|
||||
- `bun test`: 8 Bun tests passed, including catalog parity, authentication request options, malformed Hub/session checks, avatar-origin validation and encoded preview-path traversal.
|
||||
- `bun run build`: TypeScript browser bundle and static build completed; assets normalized to mode 0644, directories 0755. Source TypeScript and development dependencies are excluded from the release.
|
||||
- `bun run format:check`: Bun's built-in formatter passed.
|
||||
- `bun audit`: no known vulnerabilities across 25 checked lockfile packages; direct dependencies are current.
|
||||
- `python3 tests/browser_qa.py`: passed against both the Bun development preview and the minified production `dist/` preview with the workstation's existing Playwright and `/usr/bin/chromium`; no browser dependency was installed by this project.
|
||||
|
||||
The optional browser script requires the loopback preview from `npm run dev` or `npm run preview`. It replaces API responses with test fixtures and refuses non-loopback origins. It checks:
|
||||
The optional browser script requires the loopback preview from `bun run dev` or `bun run preview`. It replaces API responses with test fixtures and refuses non-loopback origins. It checks:
|
||||
|
||||
- Keyboard-operated illustration tabs and theme selection.
|
||||
- Runtime RU/EN changes and layouts at 320, 390, 768 and 1440 pixels, including account views.
|
||||
|
|
@ -16,7 +19,7 @@ The optional browser script requires the loopback preview from `npm run dev` or
|
|||
- CSRF-header/Origin/POST sign-out and expired-session handling.
|
||||
- Browser storage contains only the UI language; no account tokens are persisted.
|
||||
|
||||
Screenshots were visually inspected at `/tmp/vnox-web-qa/desktop-hero.png`, `mobile-full.png`, `account-login-mobile.png` and `account-profile-desktop.png`. Screenshot profile data is explicitly a browser fixture, absent from production assets.
|
||||
Local QA screenshots were visually inspected in `/tmp/vnox-web-qa/`. Any authenticated profile in those temporary images is explicitly a browser fixture. The repository-hosted [README screenshots](screenshots/README.md) were captured separately from the live production site using a fresh anonymous context and contain no test profile or private data.
|
||||
|
||||
## Limits
|
||||
|
||||
|
|
|
|||
20
package.json
20
package.json
|
|
@ -5,11 +5,21 @@
|
|||
"type": "module",
|
||||
"license": "GPL-3.0-only",
|
||||
"description": "VNOX public website and central account frontend",
|
||||
"engines": { "node": ">=22" },
|
||||
"scripts": {
|
||||
"dev": "node scripts/serve.mjs",
|
||||
"build": "node scripts/build.mjs",
|
||||
"preview": "node scripts/serve.mjs --dist",
|
||||
"test": "node --test"
|
||||
"dev": "bun scripts/serve.ts",
|
||||
"build": "bun run check && bun scripts/build.ts",
|
||||
"preview": "bun scripts/serve.ts --dist",
|
||||
"check": "bun x --bun --no-install tsc --noEmit",
|
||||
"test": "bun test",
|
||||
"format": "bun fmt src scripts tests public/index.html package.json tsconfig.json",
|
||||
"format:check": "bun fmt --check src scripts tests public/index.html package.json tsconfig.json"
|
||||
},
|
||||
"engines": {
|
||||
"bun": ">=1.4.4"
|
||||
},
|
||||
"packageManager": "bun@1.4.4",
|
||||
"devDependencies": {
|
||||
"@types/bun": "1.4.4",
|
||||
"typescript": "7.0.2"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,26 +1,75 @@
|
|||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="theme-color" content="#19191b">
|
||||
<meta name="description" content="VNOX — голос и чат для своих сообществ. Нативный клиент, собственный сервер и открытый код.">
|
||||
<title>VNOX — Своя связь</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/assets/vnox-mark.svg">
|
||||
<link rel="stylesheet" href="/src/styles.css">
|
||||
<script type="module" src="/src/app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#main" data-i18n="skip">Перейти к содержимому</a>
|
||||
<header class="site-header shell">
|
||||
<a class="brand" href="/" aria-label="VNOX"><img src="/assets/vnox-mark.svg" alt="" width="36" height="36"><span>VNOX</span></a>
|
||||
<nav aria-label="Основная навигация" data-i18n-aria="nav">
|
||||
<a href="/#project" data-i18n="navProject">Проект</a><a href="/#client" data-i18n="navClient">Клиент</a><a href="/#roadmap" data-i18n="navRoadmap">Дальше</a>
|
||||
</nav>
|
||||
<div class="header-actions"><div class="language-switch" role="group" aria-label="Язык" data-i18n-aria="language"><button type="button" data-language="ru" aria-pressed="true">RU</button><button type="button" data-language="en" aria-pressed="false">EN</button></div><a class="account-link" href="/account" data-i18n="account">Аккаунт</a></div>
|
||||
</header>
|
||||
<main id="main" tabindex="-1"></main>
|
||||
<footer class="site-footer shell"><a class="brand" href="/"><img src="/assets/vnox-mark.svg" alt="" width="28" height="28"><span>VNOX</span></a><p data-i18n="footer">Сделано для разговоров, которые хочется продолжать.</p><a href="https://www.gnu.org/licenses/gpl-3.0.html" target="_blank" rel="noopener noreferrer">GPLv3</a><a href="https://git.wihuk.pro/boba/VNOX-Server" target="_blank" rel="noopener noreferrer" data-i18n="source">Исходный код</a></footer>
|
||||
<noscript><div class="noscript">Для входа в VNOX Central включите JavaScript. / Enable JavaScript to sign in to VNOX Central.</div></noscript>
|
||||
</body>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#19191b" />
|
||||
<meta
|
||||
name="description"
|
||||
content="VNOX — голос и чат для своих сообществ. Нативный клиент, собственный сервер и открытый код."
|
||||
/>
|
||||
<title>VNOX — Своя связь</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/assets/vnox-mark.svg" />
|
||||
<link rel="stylesheet" href="/src/styles.css" />
|
||||
<script type="module" src="/src/app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#main" data-i18n="skip">Перейти к содержимому</a>
|
||||
<header class="site-header shell">
|
||||
<a class="brand" href="/" aria-label="VNOX"
|
||||
><img src="/assets/vnox-mark.svg" alt="" width="36" height="36" /><span
|
||||
>VNOX</span
|
||||
></a
|
||||
>
|
||||
<nav aria-label="Основная навигация" data-i18n-aria="nav">
|
||||
<a href="/#project" data-i18n="navProject">Проект</a
|
||||
><a href="/#client" data-i18n="navClient">Клиент</a
|
||||
><a href="/#roadmap" data-i18n="navRoadmap">Дальше</a>
|
||||
</nav>
|
||||
<div class="header-actions">
|
||||
<div
|
||||
class="language-switch"
|
||||
role="group"
|
||||
aria-label="Язык"
|
||||
data-i18n-aria="language"
|
||||
>
|
||||
<button type="button" data-language="ru" aria-pressed="true">
|
||||
RU</button
|
||||
><button type="button" data-language="en" aria-pressed="false">
|
||||
EN
|
||||
</button>
|
||||
</div>
|
||||
<a class="account-link" href="/account" data-i18n="account">Аккаунт</a>
|
||||
</div>
|
||||
</header>
|
||||
<main id="main" tabindex="-1"></main>
|
||||
<footer class="site-footer shell">
|
||||
<a class="brand" href="/"
|
||||
><img src="/assets/vnox-mark.svg" alt="" width="28" height="28" /><span
|
||||
>VNOX</span
|
||||
></a
|
||||
>
|
||||
<p data-i18n="footer">
|
||||
Сделано для разговоров, которые хочется продолжать.
|
||||
</p>
|
||||
<a
|
||||
href="https://www.gnu.org/licenses/gpl-3.0.html"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>GPLv3</a
|
||||
><a
|
||||
href="https://git.wihuk.pro/boba/VNOX-Server"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
data-i18n="source"
|
||||
>Исходный код</a
|
||||
>
|
||||
</footer>
|
||||
<noscript
|
||||
><div class="noscript">
|
||||
Для входа в VNOX Central включите JavaScript. / Enable JavaScript to
|
||||
sign in to VNOX Central.
|
||||
</div></noscript
|
||||
>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
18
scripts/browser.ts
Normal file
18
scripts/browser.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { fileURLToPath } from "node:url";
|
||||
|
||||
export async function browserBundle(minify = false): Promise<Blob> {
|
||||
const result = await Bun.build({
|
||||
entrypoints: [fileURLToPath(new URL("../src/app.ts", import.meta.url))],
|
||||
target: "browser",
|
||||
format: "esm",
|
||||
minify,
|
||||
sourcemap: "none",
|
||||
});
|
||||
if (!result.success || !result.outputs[0]) {
|
||||
throw new AggregateError(
|
||||
result.logs,
|
||||
"Browser TypeScript compilation failed",
|
||||
);
|
||||
}
|
||||
return result.outputs[0];
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
import { cp, mkdir, rm, chmod, readdir } from 'node:fs/promises';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
const root = fileURLToPath(new URL('../', import.meta.url));
|
||||
await rm(`${root}dist`, { recursive: true, force: true });
|
||||
await mkdir(`${root}dist`, { recursive: true });
|
||||
await cp(`${root}public`, `${root}dist`, { recursive: true });
|
||||
await cp(`${root}src`, `${root}dist/src`, { recursive: true });
|
||||
async function permissions(directory) {
|
||||
await chmod(directory, 0o755);
|
||||
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||
const path = `${directory}/${entry.name}`;
|
||||
if (entry.isDirectory()) await permissions(path);
|
||||
else await chmod(path, 0o644);
|
||||
}
|
||||
}
|
||||
await permissions(`${root}dist`);
|
||||
console.log('Built dependency-free static website in dist/');
|
||||
21
scripts/build.ts
Normal file
21
scripts/build.ts
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import { cp, mkdir, rm, chmod, readdir } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { browserBundle } from "./browser";
|
||||
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
await rm(`${root}dist`, { recursive: true, force: true });
|
||||
await mkdir(`${root}dist/src`, { recursive: true });
|
||||
await cp(`${root}public`, `${root}dist`, { recursive: true });
|
||||
await cp(`${root}src/styles.css`, `${root}dist/src/styles.css`);
|
||||
await Bun.write(`${root}dist/src/app.js`, await browserBundle(true));
|
||||
|
||||
async function permissions(directory: string): Promise<void> {
|
||||
await chmod(directory, 0o755);
|
||||
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||
const path = `${directory}/${entry.name}`;
|
||||
if (entry.isDirectory()) await permissions(path);
|
||||
else await chmod(path, 0o644);
|
||||
}
|
||||
}
|
||||
await permissions(`${root}dist`);
|
||||
console.log("Built TypeScript browser bundle and static website in dist/");
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
import { createServer } from 'node:http';
|
||||
import { readFile, stat } from 'node:fs/promises';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { extname, resolve, sep } from 'node:path';
|
||||
const root = fileURLToPath(new URL('../', import.meta.url));
|
||||
const production = process.argv.includes('--dist');
|
||||
const port = Number(process.env.PORT ?? 4176);
|
||||
const types = {'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.css':'text/css; charset=utf-8','.svg':'image/svg+xml','.png':'image/png','.json':'application/json'};
|
||||
const server = createServer(async (request,response) => {
|
||||
try {
|
||||
const path = decodeURIComponent(new URL(request.url,'http://localhost').pathname);
|
||||
if (request.method!=='GET' && request.method!=='HEAD') { response.writeHead(405);response.end();return; }
|
||||
if (path.startsWith('/v1/') || ['/health','/ready','/version'].includes(path)) {
|
||||
response.writeHead(503,{'content-type':'application/json','cache-control':'no-store'});
|
||||
response.end(JSON.stringify({error:'preview_has_no_backend'}));return;
|
||||
}
|
||||
const sourcePath = !production && path.startsWith('/src/');
|
||||
const base = production ? resolve(root,'dist') : sourcePath ? resolve(root,'src') : resolve(root,'public');
|
||||
let file = resolve(base, sourcePath ? path.slice('/src/'.length) : `.${path}`);
|
||||
if (path==='/' || path==='/account' || path==='/account/') file=resolve(base,'index.html');
|
||||
if (!file.startsWith(base+sep)) { response.writeHead(403);response.end();return; }
|
||||
const info=await stat(file);
|
||||
if (!info.isFile()) throw new Error('not_file');
|
||||
response.writeHead(200,{'content-type':types[extname(file)]??'application/octet-stream','cache-control':'no-store','x-content-type-options':'nosniff'});
|
||||
response.end(request.method==='HEAD'?undefined:await readFile(file));
|
||||
} catch { response.writeHead(404,{'content-type':'text/plain'});response.end('Not found'); }
|
||||
});
|
||||
server.listen(port,'127.0.0.1',()=>console.log(`VNOX Web: http://127.0.0.1:${port}`));
|
||||
for (const signal of ['SIGINT','SIGTERM']) process.on(signal,()=>server.close(()=>process.exit(0)));
|
||||
74
scripts/serve.ts
Normal file
74
scripts/serve.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import { stat } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { extname, resolve, sep } from "node:path";
|
||||
import { browserBundle } from "./browser";
|
||||
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const production = Bun.argv.includes("--dist");
|
||||
const port = Number(Bun.env.PORT ?? 4176);
|
||||
const types: Record<string, string> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".svg": "image/svg+xml",
|
||||
".png": "image/png",
|
||||
};
|
||||
const headers = {
|
||||
"cache-control": "no-store",
|
||||
"x-content-type-options": "nosniff",
|
||||
};
|
||||
|
||||
const server = Bun.serve({
|
||||
port,
|
||||
hostname: "127.0.0.1",
|
||||
async fetch(request): Promise<Response> {
|
||||
try {
|
||||
const path = decodeURIComponent(new URL(request.url).pathname);
|
||||
if (request.method !== "GET" && request.method !== "HEAD")
|
||||
return new Response(null, { status: 405 });
|
||||
if (path.split("/").includes(".."))
|
||||
return new Response(null, { status: 403 });
|
||||
if (
|
||||
path.startsWith("/v1/") ||
|
||||
["/health", "/ready", "/version"].includes(path)
|
||||
) {
|
||||
return Response.json(
|
||||
{ error: "preview_has_no_backend" },
|
||||
{ status: 503, headers },
|
||||
);
|
||||
}
|
||||
if (!production && path === "/src/app.js") {
|
||||
const bundle = await browserBundle();
|
||||
return new Response(request.method === "HEAD" ? null : bundle, {
|
||||
headers: { ...headers, "content-type": types[".js"]! },
|
||||
});
|
||||
}
|
||||
const sourceStyle = !production && path === "/src/styles.css";
|
||||
const base = production
|
||||
? resolve(root, "dist")
|
||||
: sourceStyle
|
||||
? resolve(root, "src")
|
||||
: resolve(root, "public");
|
||||
let file = resolve(base, sourceStyle ? "styles.css" : `.${path}`);
|
||||
if (path === "/" || path === "/account" || path === "/account/")
|
||||
file = resolve(base, "index.html");
|
||||
if (!file.startsWith(base + sep))
|
||||
return new Response(null, { status: 403 });
|
||||
if (!(await stat(file)).isFile())
|
||||
return new Response("Not found", { status: 404 });
|
||||
return new Response(request.method === "HEAD" ? null : Bun.file(file), {
|
||||
headers: {
|
||||
...headers,
|
||||
"content-type": types[extname(file)] ?? "application/octet-stream",
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404, headers });
|
||||
}
|
||||
},
|
||||
});
|
||||
console.log(`VNOX Web: http://127.0.0.1:${server.port}`);
|
||||
for (const signal of ["SIGINT", "SIGTERM"] as const)
|
||||
process.on(signal, () => {
|
||||
void server.stop(true).then(() => process.exit(0));
|
||||
});
|
||||
27
src/api.js
27
src/api.js
|
|
@ -1,27 +0,0 @@
|
|||
export class ApiError extends Error {
|
||||
constructor(status, code) { super(code); this.name = 'ApiError'; this.status = status; }
|
||||
}
|
||||
export async function request(path, { signal, method = 'GET', csrf, fetcher = fetch } = {}) {
|
||||
if (!path.startsWith('/v1/')) throw new TypeError('Only same-origin VNOX API paths are allowed');
|
||||
const response = await fetcher(path, {
|
||||
method, signal, credentials: 'same-origin', cache: 'no-store',
|
||||
headers: { Accept: 'application/json', ...(csrf ? { 'X-CSRF-Token': csrf } : {}) },
|
||||
});
|
||||
if (!response.ok) throw new ApiError(response.status, 'request_failed');
|
||||
if (response.status === 204) return null;
|
||||
return response.json();
|
||||
}
|
||||
export function isSession(value) {
|
||||
return value?.authenticated === false || (value?.authenticated === true
|
||||
&& typeof value.csrf_token === 'string' && value.csrf_token.length > 0
|
||||
&& typeof value.user?.user_id === 'string' && typeof value.user?.handle === 'string'
|
||||
&& typeof value.user?.display_name === 'string');
|
||||
}
|
||||
export function safeAvatar(value) {
|
||||
if (typeof value !== 'string') return null;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.protocol === 'https:' && url.hostname === 'avatars.githubusercontent.com'
|
||||
&& !url.username && !url.password && !url.port ? url.href : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
90
src/api.ts
Normal file
90
src/api.ts
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
export interface User {
|
||||
user_id: string;
|
||||
handle: string;
|
||||
display_name: string;
|
||||
avatar_url?: string | null;
|
||||
}
|
||||
export type Session =
|
||||
| { authenticated: false }
|
||||
| { authenticated: true; user: User; csrf_token: string };
|
||||
export interface HubInfo {
|
||||
capabilities: { github_auth: string };
|
||||
}
|
||||
export interface RequestOptions {
|
||||
signal?: AbortSignal;
|
||||
method?: "GET" | "POST";
|
||||
csrf?: string;
|
||||
fetcher?: (input: string, options: RequestInit) => Promise<Response>;
|
||||
}
|
||||
export class ApiError extends Error {
|
||||
readonly status: number;
|
||||
constructor(status: number, code: string) {
|
||||
super(code);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
export async function request(
|
||||
path: string,
|
||||
{ signal, method = "GET", csrf, fetcher = fetch }: RequestOptions = {},
|
||||
): Promise<unknown> {
|
||||
if (!path.startsWith("/v1/"))
|
||||
throw new TypeError("Only same-origin VNOX API paths are allowed");
|
||||
const response = await fetcher(path, {
|
||||
method,
|
||||
signal,
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
...(csrf ? { "X-CSRF-Token": csrf } : {}),
|
||||
},
|
||||
});
|
||||
if (!response.ok) throw new ApiError(response.status, "request_failed");
|
||||
if (response.status === 204) return null;
|
||||
return response.json();
|
||||
}
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
export function isSession(value: unknown): value is Session {
|
||||
if (!record(value)) return false;
|
||||
if (value.authenticated === false) return true;
|
||||
if (
|
||||
value.authenticated !== true ||
|
||||
typeof value.csrf_token !== "string" ||
|
||||
value.csrf_token.length === 0 ||
|
||||
!record(value.user)
|
||||
)
|
||||
return false;
|
||||
return (
|
||||
typeof value.user.user_id === "string" &&
|
||||
typeof value.user.handle === "string" &&
|
||||
typeof value.user.display_name === "string" &&
|
||||
(value.user.avatar_url === undefined ||
|
||||
value.user.avatar_url === null ||
|
||||
typeof value.user.avatar_url === "string")
|
||||
);
|
||||
}
|
||||
export function isInfo(value: unknown): value is HubInfo {
|
||||
return (
|
||||
record(value) &&
|
||||
record(value.capabilities) &&
|
||||
typeof value.capabilities.github_auth === "string"
|
||||
);
|
||||
}
|
||||
export function safeAvatar(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.protocol === "https:" &&
|
||||
url.hostname === "avatars.githubusercontent.com" &&
|
||||
!url.username &&
|
||||
!url.password &&
|
||||
!url.port
|
||||
? url.href
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
165
src/app.js
165
src/app.js
|
|
@ -1,165 +0,0 @@
|
|||
import { detectLanguage, translate } from './i18n.js';
|
||||
import { request, isSession, safeAvatar } from './api.js';
|
||||
|
||||
let savedLanguage;
|
||||
try { savedLanguage = localStorage.getItem('vnox-web-language'); } catch { /* Storage is optional. */ }
|
||||
let language = detectLanguage(savedLanguage, navigator.languages ?? [navigator.language]);
|
||||
const accountPage = /^\/account\/?$/.test(location.pathname);
|
||||
const main = document.querySelector('main');
|
||||
let activeTab = 'text';
|
||||
let activeTheme = 'dark';
|
||||
let controller;
|
||||
let currentSession;
|
||||
let githubEnabled = false;
|
||||
let sessionState = 'loading';
|
||||
let infoState = 'loading';
|
||||
let logoutState = 'idle';
|
||||
const t = key => translate(language, key);
|
||||
const icon = (name, size = 20) => {
|
||||
const paths = {
|
||||
github: '<path d="M9 19c-4 1-4-2-6-2m12 4v-3.4a3 3 0 0 0-.8-2.3c2.7-.3 5.5-1.3 5.5-6A4.7 4.7 0 0 0 18.4 6a4.4 4.4 0 0 0-.1-3.3s-1-.3-3.4 1.3a11.6 11.6 0 0 0-6.2 0C6.3 2.4 5.3 2.7 5.3 2.7A4.4 4.4 0 0 0 5.2 6 4.7 4.7 0 0 0 4 9.3c0 4.7 2.8 5.7 5.5 6a3 3 0 0 0-.8 2.3V21"/>',
|
||||
voice: '<path d="m11 5-5 4H3v6h3l5 4V5Z"/><path d="M15 8a6 6 0 0 1 0 8m3-11a10 10 0 0 1 0 14"/>',
|
||||
mic: '<rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10v2a7 7 0 0 0 14 0v-2M12 19v3m-4 0h8"/>',
|
||||
chat: '<path d="M21 11.5a8.4 8.4 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7a8.4 8.4 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.4 8.4 0 0 1 3.8-.9h.5a8.5 8.5 0 0 1 8 8v.5Z"/>',
|
||||
external: '<path d="M15 3h6v6m0-6L10 14"/><path d="M10 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-5"/>',
|
||||
check: '<path d="m5 12 4 4L19 6"/>',
|
||||
copy: '<rect x="8" y="8" width="13" height="13" rx="2"/><path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/>',
|
||||
back: '<path d="m12 19-7-7 7-7m-7 7h14"/>',
|
||||
};
|
||||
return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths[name] ?? paths.chat}</svg>`;
|
||||
};
|
||||
const tr = (key, tag = 'span', attrs = '') => `<${tag} data-i18n="${key}" ${attrs}>${t(key)}</${tag}>`;
|
||||
const external = (href, key) => `<a class="text-link" href="${href}" target="_blank" rel="noopener noreferrer">${tr(key)}${icon('external', 15)}</a>`;
|
||||
function landing() {
|
||||
main.innerHTML = `
|
||||
<section class="hero shell" aria-labelledby="hero-title">
|
||||
<div class="hero-copy"><p class="development">${tr('development')}</p>${tr('heroTitle', 'h1', 'id="hero-title"')}${tr('heroText', 'p', 'class="hero-description"')}
|
||||
<div class="hero-actions"><a class="button primary" href="/account">${tr('openCentral')}</a><a class="button quiet" href="#project">${tr('explore')}</a></div>${tr('earlyNote','p','class="small hero-note"')}</div>
|
||||
<div class="diagram-wrap"><div class="diagram-meta">${tr('diagramLabel')}<span class="diagram-dots" aria-hidden="true"><i></i><i></i><i></i></span></div>
|
||||
<div class="product-diagram" data-preview-theme="dark"><div class="diagram-sidebar"><img src="/assets/vnox-mark.svg" alt="" width="32" height="32"><div class="diagram-community">${tr('community')}</div><div class="diagram-channel selected"># ${tr('general')}</div><div class="diagram-channel"># ${tr('ideas')}</div><div class="diagram-voice">${icon('voice',16)}${tr('voiceRoom')}</div><div class="diagram-people"><span class="person-dot"></span>${tr('you')}<span class="person-dot second"></span>${tr('friend')}</div><div class="diagram-self"><span class="mini-avatar">V</span>${tr('you')}${icon('mic',15)}</div></div>
|
||||
<div class="diagram-main"><div class="diagram-header"># ${tr('general')}<span>${icon('chat',17)}</span></div><div id="diagram-content"></div><div class="diagram-call"><span class="connection-dot"></span>${tr('voiceConnected')}${icon('mic',16)}</div></div></div>
|
||||
<div class="diagram-tabs" role="tablist" aria-label="${t('preview')}" data-i18n-aria="preview"><button role="tab" aria-selected="true" aria-controls="diagram-content" id="tab-text" data-tab="text">${tr('textTab')}</button><button role="tab" aria-selected="false" aria-controls="diagram-content" id="tab-voice" data-tab="voice" tabindex="-1">${tr('voiceTab')}</button><button role="tab" aria-selected="false" aria-controls="diagram-content" id="tab-theme" data-tab="theme" tabindex="-1">${tr('themeTab')}</button></div>${tr('diagramNote','p','class="small diagram-note"')}
|
||||
</div>
|
||||
</section>
|
||||
<section class="project-section shell" id="project" aria-labelledby="project-title"><div class="section-intro">${tr('projectTitle','h2','id="project-title"')}${tr('projectText','p')}<div class="source-links">${external('https://git.wihuk.pro/boba/VNOX-Client','clientCode')}${external('https://git.wihuk.pro/boba/VNOX-Server','serverCode')}</div></div><div class="project-points"><article><div class="point-icon">${icon('chat',24)}</div><div>${tr('projectNative','h3')}${tr('projectNativeText','p')}</div></article><article><div class="point-icon">${icon('voice',24)}</div><div>${tr('projectServer','h3')}${tr('projectServerText','p')}</div></article><article><img src="/assets/vnox-mark.svg" alt="" width="40" height="40"><div>${tr('projectCentral','h3')}${tr('projectCentralText','p')}</div></article></div></section>
|
||||
<section class="client-section" id="client" aria-labelledby="client-title"><div class="shell"><div class="client-heading">${tr('clientTitle','h2','id="client-title"')}${tr('clientText','p')}</div><figure class="client-image"><img src="/assets/client-settings.png" width="1280" height="800" alt="${t('clientScreenshot')}" data-i18n-alt="clientScreenshot" loading="lazy">${tr('screenshotCaption','figcaption')}</figure><div class="client-details"><article>${tr('appearanceTitle','h3')}${tr('appearanceText','p')}</article><article>${tr('identityTitle','h3')}${tr('identityText','p')}</article></div></div></section>
|
||||
<section class="roadmap shell" id="roadmap" aria-labelledby="roadmap-title"><div class="roadmap-heading">${tr('roadmapTitle','h2','id="roadmap-title"')}${tr('roadmapText','p')}</div><div class="roadmap-columns"><article><h3><span class="connection-dot" aria-hidden="true"></span>${tr('available')}</h3><ul><li>${tr('availableOne')}</li><li>${tr('availableTwo')}</li><li>${tr('availableThree')}</li><li>${tr('availableFour')}</li><li>${tr('availableFive')}</li></ul></article><article><h3><span class="planned-dot" aria-hidden="true"></span>${tr('next')}</h3><ul><li>${tr('nextOne')}</li><li>${tr('nextTwo')}</li><li>${tr('nextThree')}</li></ul></article></div>${tr('downloadNote','p','class="release-note"')}</section>
|
||||
<section class="faq shell" aria-labelledby="faq-title">${tr('faqTitle','h2','id="faq-title"')}<div>${['Server','Central','Release'].map(key=>`<details><summary>${tr(`faq${key}`)}<span aria-hidden="true">+</span></summary>${tr(`faq${key}Answer`,'p')}</details>`).join('')}</div></section>
|
||||
<section class="status-section shell" aria-label="${t('statusNote')}" data-i18n-aria="statusNote"><div><span id="service-dot" class="status-dot"></span><p id="service-status" role="status">${t('statusLoading')}</p></div><a href="/account" class="text-link">${tr('openCentral')}${icon('external',15)}</a></section>`;
|
||||
renderDiagram();
|
||||
main.querySelectorAll('[data-tab]').forEach(button => {
|
||||
button.addEventListener('click', () => { activeTab = button.dataset.tab; renderDiagram(); });
|
||||
button.addEventListener('keydown', event => {
|
||||
const tabs = [...main.querySelectorAll('[data-tab]')];
|
||||
let index = tabs.indexOf(button);
|
||||
if (event.key === 'ArrowRight') index = (index + 1) % tabs.length;
|
||||
else if (event.key === 'ArrowLeft') index = (index + tabs.length - 1) % tabs.length;
|
||||
else if (event.key === 'Home') index = 0;
|
||||
else if (event.key === 'End') index = tabs.length - 1;
|
||||
else return;
|
||||
event.preventDefault(); activeTab = tabs[index].dataset.tab; renderDiagram(); tabs[index].focus();
|
||||
});
|
||||
});
|
||||
}
|
||||
function renderDiagram() {
|
||||
const content = document.querySelector('#diagram-content');
|
||||
if (!content) return;
|
||||
main.querySelectorAll('[data-tab]').forEach(button => {
|
||||
const active = button.dataset.tab === activeTab;
|
||||
button.setAttribute('aria-selected', String(active));button.tabIndex = active ? 0 : -1;
|
||||
});
|
||||
content.setAttribute('role','tabpanel');content.setAttribute('aria-labelledby', `tab-${activeTab}`);
|
||||
if (activeTab === 'text') content.innerHTML = `<div class="illustration-chat"><div class="message-heading"><span class="chat-avatar">V</span><div>${tr('community','strong')}<div class="message-lines" aria-hidden="true"><i></i><i></i></div></div></div>${tr('messageSample','p')}<div class="illustration-composer" aria-hidden="true"><span>+</span><i></i>${icon('chat',15)}</div>${tr('messageNote','p','class="diagram-caption"')}</div>`;
|
||||
if (activeTab === 'voice') content.innerHTML = `<div class="illustration-voice"><div class="voice-orbit"><span class="voice-avatar">V</span><div class="waveform" aria-hidden="true">${Array.from({length:11},()=>'<i></i>').join('')}</div><span class="voice-avatar friend-avatar">${icon('voice',30)}</span></div>${tr('voiceExplain','p')}<div class="voice-controls" aria-hidden="true"><span>${icon('mic')}</span><span>${icon('voice')}</span></div>${tr('voiceCaption','p','class="diagram-caption"')}</div>`;
|
||||
if (activeTab === 'theme') {
|
||||
content.innerHTML = `<div class="illustration-themes">${tr('themeCaption','h3')}<div class="theme-options" role="group" aria-label="${t('previewTheme')}" data-i18n-aria="previewTheme">${['light','dark','black','custom'].map(theme=>`<button class="theme-option ${theme}" data-theme="${theme}" aria-pressed="${activeTheme===theme}"><span class="theme-sample" aria-hidden="true"><i></i><i></i><i></i></span>${tr(theme)}</button>`).join('')}</div></div>`;
|
||||
content.querySelectorAll('[data-theme]').forEach(button => button.addEventListener('click',()=>{
|
||||
activeTheme = button.dataset.theme;
|
||||
document.querySelector('.product-diagram').dataset.previewTheme = activeTheme;
|
||||
content.querySelectorAll('[data-theme]').forEach(item=>item.setAttribute('aria-pressed',String(item===button)));
|
||||
}));
|
||||
}
|
||||
}
|
||||
function account() {
|
||||
main.innerHTML = `<section class="account-section shell"><a href="/" class="text-link back-link">${icon('back',17)}${tr('back')}</a><div class="account-layout"><div class="account-intro"><img class="account-mark" src="/assets/vnox-mark.svg" alt="" width="76" height="76">${tr('accountHeading','h1')}${tr('accountIntro','p')}<div class="account-explanation">${tr('accountStage','p')}</div></div><div id="account-content" class="account-panel" aria-live="polite"></div></div></section>`;
|
||||
renderAccount();
|
||||
}
|
||||
function renderAccount() {
|
||||
const panel = document.querySelector('#account-content');
|
||||
if (!panel) return;
|
||||
panel.replaceChildren();
|
||||
if (sessionState === 'loading') { panel.innerHTML = `<div class="account-loading"><span class="loading-ring" aria-hidden="true"></span>${tr('sessionLoading','p')}</div>`;return; }
|
||||
if (sessionState === 'error') {
|
||||
panel.innerHTML = `${tr('accountError','h2')}${tr('accountErrorText','p')}<button class="button primary" id="retry-session">${tr('retry')}</button>`;
|
||||
panel.querySelector('#retry-session').addEventListener('click',refresh);return;
|
||||
}
|
||||
if (currentSession?.authenticated) {
|
||||
panel.innerHTML = `<div class="profile-heading"><div class="profile-avatar" id="profile-avatar" aria-hidden="true">V</div><div>${tr('profileTitle','h2')}<p id="profile-name"></p></div></div>${tr('profileIntro','p')}<dl class="profile-fields"><div><dt>${tr('handle')}</dt><dd id="profile-handle"></dd></div><div><dt>${tr('userId')}</dt><dd id="profile-id"></dd></div><div><dt>${tr('provider')}</dt><dd>GitHub</dd></div></dl><div class="profile-actions"><button class="button secondary" id="copy-id">${icon('copy',17)}${tr('copy')}</button><button class="button quiet" id="logout" ${logoutState==='pending'?'disabled':''}>${tr(logoutState==='pending'?'loggingOut':'logout')}</button></div><p class="form-message" id="profile-message" role="status"></p>`;
|
||||
const user = currentSession.user;
|
||||
panel.querySelector('#profile-name').textContent = user.display_name || t('profileFallback');
|
||||
panel.querySelector('#profile-handle').textContent = user.handle;
|
||||
panel.querySelector('#profile-id').textContent = user.user_id;
|
||||
const avatar = safeAvatar(user.avatar_url);
|
||||
if (avatar) { const image = document.createElement('img');image.src=avatar;image.alt='';image.referrerPolicy='no-referrer';image.addEventListener('error',()=>image.remove(),{once:true});panel.querySelector('#profile-avatar').append(image); }
|
||||
panel.querySelector('#copy-id').addEventListener('click',async()=>{
|
||||
try { await navigator.clipboard.writeText(user.user_id); panel.querySelector('#profile-message').textContent=t('copied'); }
|
||||
catch { panel.querySelector('#profile-message').textContent=t('copyError'); }
|
||||
});
|
||||
panel.querySelector('#logout').addEventListener('click',logout);
|
||||
if (logoutState==='error') panel.querySelector('#profile-message').textContent=t('logoutError');
|
||||
return;
|
||||
}
|
||||
panel.innerHTML = `<div class="login-provider">${icon('github',33)}</div>${tr('loginTitle','h2')}${tr('loginText','p')}<a class="button primary github-login ${githubEnabled?'':'unavailable'}" ${githubEnabled?'href="/v1/auth/github/start"':'aria-disabled="true" tabindex="-1"'}>${icon('github',21)}${tr('loginButton')}</a><p id="login-availability" class="form-message" role="status"></p><button class="text-button" id="retry-info" ${infoState==='error'?'':'hidden'}>${tr('retry')}</button><div class="privacy-note">${icon('check',16)}${tr('privacy','p')}</div>`;
|
||||
panel.querySelector('#login-availability').textContent = infoState==='loading'?t('loginLoading'):infoState==='error'?t('loginUnavailable'):githubEnabled?'':t('loginDisabled');
|
||||
panel.querySelector('#retry-info').addEventListener('click',refresh);
|
||||
}
|
||||
async function logout() {
|
||||
if (!currentSession?.authenticated || logoutState==='pending') return;
|
||||
const csrf = currentSession.csrf_token;
|
||||
logoutState='pending';renderAccount();
|
||||
try {
|
||||
await request('/v1/auth/logout',{method:'POST',csrf,signal:AbortSignal.timeout(15000)});
|
||||
currentSession={authenticated:false};logoutState='idle';renderAccount();
|
||||
} catch(error) {
|
||||
if (error.status===401) { currentSession={authenticated:false};logoutState='idle';renderAccount(); }
|
||||
else { logoutState='error';renderAccount(); }
|
||||
}
|
||||
}
|
||||
function updateStatus() {
|
||||
const status = document.querySelector('#service-status');
|
||||
if (status) { status.textContent = t(infoState==='loading'?'statusLoading':infoState==='ready'?'statusReady':'statusUnavailable');document.querySelector('#service-dot').dataset.state=infoState; }
|
||||
}
|
||||
async function refresh() {
|
||||
controller?.abort();controller=new AbortController();
|
||||
const currentController = controller;
|
||||
const signal = AbortSignal.any([currentController.signal,AbortSignal.timeout(15000)]);
|
||||
infoState='loading';
|
||||
if (accountPage) { sessionState='loading';renderAccount(); } else updateStatus();
|
||||
const info = request('/v1/info',{signal}).then(value=>{
|
||||
if (controller !== currentController) return;
|
||||
if (typeof value?.capabilities?.github_auth !== 'string') throw new Error('invalid_info');
|
||||
githubEnabled=value.capabilities.github_auth==='enabled';infoState='ready';
|
||||
}).catch(()=>{if(!currentController.signal.aborted){githubEnabled=false;infoState='error';}}).finally(()=>{if(controller===currentController){updateStatus();if(accountPage)renderAccount();}});
|
||||
if (accountPage) {
|
||||
await Promise.allSettled([info,request('/v1/auth/session',{signal}).then(value=>{
|
||||
if (controller !== currentController) return;
|
||||
if (!isSession(value)) throw new Error('invalid_session');
|
||||
currentSession=value;sessionState='ready';
|
||||
}).catch(()=>{if(!currentController.signal.aborted)sessionState='error';}).finally(()=>{if(controller===currentController)renderAccount();})]);
|
||||
} else await info;
|
||||
}
|
||||
function setLanguage(next) {
|
||||
language=next;
|
||||
try { localStorage.setItem('vnox-web-language',next); } catch { /* No authentication data is persisted. */ }
|
||||
document.documentElement.lang=next;
|
||||
document.title=t(accountPage?'accountTitle':'title');
|
||||
document.querySelector('meta[name="description"]').content=t('description');
|
||||
document.querySelectorAll('[data-i18n]').forEach(element=>element.textContent=t(element.dataset.i18n));
|
||||
for(const [attribute,dataKey] of [['aria-label','i18nAria'],['alt','i18nAlt']]) document.querySelectorAll(`[data-${attribute==='alt'?'i18n-alt':'i18n-aria'}]`).forEach(element=>element.setAttribute(attribute,t(element.dataset[dataKey])));
|
||||
document.querySelectorAll('[data-language]').forEach(button=>button.setAttribute('aria-pressed',String(button.dataset.language===next)));
|
||||
if (accountPage) renderAccount();else {renderDiagram();updateStatus();}
|
||||
}
|
||||
if(accountPage) account();else landing();
|
||||
document.querySelectorAll('[data-language]').forEach(button=>button.addEventListener('click',()=>setLanguage(button.dataset.language)));
|
||||
setLanguage(language);refresh();
|
||||
window.addEventListener('pageshow',event=>{if(event.persisted)refresh();});
|
||||
338
src/app.ts
Normal file
338
src/app.ts
Normal file
|
|
@ -0,0 +1,338 @@
|
|||
import type { Language, MessageKey } from "./i18n";
|
||||
import type { Session } from "./api";
|
||||
import { detectLanguage, translate } from "./i18n";
|
||||
import { request, isSession, isInfo, safeAvatar, ApiError } from "./api";
|
||||
|
||||
let savedLanguage: string | null | undefined;
|
||||
try {
|
||||
savedLanguage = localStorage.getItem("vnox-web-language");
|
||||
} catch {
|
||||
/* Storage is optional. */
|
||||
}
|
||||
let language = detectLanguage(
|
||||
savedLanguage,
|
||||
navigator.languages ?? [navigator.language],
|
||||
);
|
||||
const accountPage = /^\/account\/?$/.test(location.pathname);
|
||||
function find<T extends Element = HTMLElement>(
|
||||
selector: string,
|
||||
root: ParentNode = document,
|
||||
): T {
|
||||
const element = root.querySelector<T>(selector);
|
||||
if (!element) throw new Error(`Missing required element: ${selector}`);
|
||||
return element;
|
||||
}
|
||||
const main = find("main");
|
||||
type Tab = "text" | "voice" | "theme";
|
||||
type Theme = "light" | "dark" | "black" | "custom";
|
||||
let activeTab: Tab = "text";
|
||||
let activeTheme: Theme = "dark";
|
||||
let controller: AbortController | undefined;
|
||||
let currentSession: Session | null = null;
|
||||
let githubEnabled = false;
|
||||
let sessionState: "loading" | "ready" | "error" = "loading";
|
||||
let infoState: "loading" | "ready" | "error" = "loading";
|
||||
let logoutState: "idle" | "pending" | "error" = "idle";
|
||||
const t = (key: MessageKey) => translate(language, key);
|
||||
const icon = (
|
||||
name:
|
||||
| "github"
|
||||
| "voice"
|
||||
| "mic"
|
||||
| "chat"
|
||||
| "external"
|
||||
| "check"
|
||||
| "copy"
|
||||
| "back",
|
||||
size = 20,
|
||||
) => {
|
||||
const paths = {
|
||||
github:
|
||||
'<path d="M9 19c-4 1-4-2-6-2m12 4v-3.4a3 3 0 0 0-.8-2.3c2.7-.3 5.5-1.3 5.5-6A4.7 4.7 0 0 0 18.4 6a4.4 4.4 0 0 0-.1-3.3s-1-.3-3.4 1.3a11.6 11.6 0 0 0-6.2 0C6.3 2.4 5.3 2.7 5.3 2.7A4.4 4.4 0 0 0 5.2 6 4.7 4.7 0 0 0 4 9.3c0 4.7 2.8 5.7 5.5 6a3 3 0 0 0-.8 2.3V21"/>',
|
||||
voice:
|
||||
'<path d="m11 5-5 4H3v6h3l5 4V5Z"/><path d="M15 8a6 6 0 0 1 0 8m3-11a10 10 0 0 1 0 14"/>',
|
||||
mic: '<rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10v2a7 7 0 0 0 14 0v-2M12 19v3m-4 0h8"/>',
|
||||
chat: '<path d="M21 11.5a8.4 8.4 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7a8.4 8.4 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.4 8.4 0 0 1 3.8-.9h.5a8.5 8.5 0 0 1 8 8v.5Z"/>',
|
||||
external:
|
||||
'<path d="M15 3h6v6m0-6L10 14"/><path d="M10 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-5"/>',
|
||||
check: '<path d="m5 12 4 4L19 6"/>',
|
||||
copy: '<rect x="8" y="8" width="13" height="13" rx="2"/><path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/>',
|
||||
back: '<path d="m12 19-7-7 7-7m-7 7h14"/>',
|
||||
};
|
||||
return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths[name] ?? paths.chat}</svg>`;
|
||||
};
|
||||
const tr = (key: MessageKey, tag = "span", attrs = "") =>
|
||||
`<${tag} data-i18n="${key}" ${attrs}>${t(key)}</${tag}>`;
|
||||
const external = (href: string, key: MessageKey) =>
|
||||
`<a class="text-link" href="${href}" target="_blank" rel="noopener noreferrer">${tr(key)}${icon("external", 15)}</a>`;
|
||||
function landing() {
|
||||
main.innerHTML = `
|
||||
<section class="hero shell" aria-labelledby="hero-title">
|
||||
<div class="hero-copy"><p class="development">${tr("development")}</p>${tr("heroTitle", "h1", 'id="hero-title"')}${tr("heroText", "p", 'class="hero-description"')}
|
||||
<div class="hero-actions"><a class="button primary" href="/account">${tr("openCentral")}</a><a class="button quiet" href="#project">${tr("explore")}</a></div>${tr("earlyNote", "p", 'class="small hero-note"')}</div>
|
||||
<div class="diagram-wrap"><div class="diagram-meta">${tr("diagramLabel")}<span class="diagram-dots" aria-hidden="true"><i></i><i></i><i></i></span></div>
|
||||
<div class="product-diagram" data-preview-theme="dark"><div class="diagram-sidebar"><img src="/assets/vnox-mark.svg" alt="" width="32" height="32"><div class="diagram-community">${tr("community")}</div><div class="diagram-channel selected"># ${tr("general")}</div><div class="diagram-channel"># ${tr("ideas")}</div><div class="diagram-voice">${icon("voice", 16)}${tr("voiceRoom")}</div><div class="diagram-people"><span class="person-dot"></span>${tr("you")}<span class="person-dot second"></span>${tr("friend")}</div><div class="diagram-self"><span class="mini-avatar">V</span>${tr("you")}${icon("mic", 15)}</div></div>
|
||||
<div class="diagram-main"><div class="diagram-header"># ${tr("general")}<span>${icon("chat", 17)}</span></div><div id="diagram-content"></div><div class="diagram-call"><span class="connection-dot"></span>${tr("voiceConnected")}${icon("mic", 16)}</div></div></div>
|
||||
<div class="diagram-tabs" role="tablist" aria-label="${t("preview")}" data-i18n-aria="preview"><button role="tab" aria-selected="true" aria-controls="diagram-content" id="tab-text" data-tab="text">${tr("textTab")}</button><button role="tab" aria-selected="false" aria-controls="diagram-content" id="tab-voice" data-tab="voice" tabindex="-1">${tr("voiceTab")}</button><button role="tab" aria-selected="false" aria-controls="diagram-content" id="tab-theme" data-tab="theme" tabindex="-1">${tr("themeTab")}</button></div>${tr("diagramNote", "p", 'class="small diagram-note"')}
|
||||
</div>
|
||||
</section>
|
||||
<section class="project-section shell" id="project" aria-labelledby="project-title"><div class="section-intro">${tr("projectTitle", "h2", 'id="project-title"')}${tr("projectText", "p")}<div class="source-links">${external("https://git.wihuk.pro/boba/VNOX-Client", "clientCode")}${external("https://git.wihuk.pro/boba/VNOX-Server", "serverCode")}</div></div><div class="project-points"><article><div class="point-icon">${icon("chat", 24)}</div><div>${tr("projectNative", "h3")}${tr("projectNativeText", "p")}</div></article><article><div class="point-icon">${icon("voice", 24)}</div><div>${tr("projectServer", "h3")}${tr("projectServerText", "p")}</div></article><article><img src="/assets/vnox-mark.svg" alt="" width="40" height="40"><div>${tr("projectCentral", "h3")}${tr("projectCentralText", "p")}</div></article></div></section>
|
||||
<section class="client-section" id="client" aria-labelledby="client-title"><div class="shell"><div class="client-heading">${tr("clientTitle", "h2", 'id="client-title"')}${tr("clientText", "p")}</div><figure class="client-image"><img src="/assets/client-settings.png" width="1280" height="800" alt="${t("clientScreenshot")}" data-i18n-alt="clientScreenshot" loading="lazy">${tr("screenshotCaption", "figcaption")}</figure><div class="client-details"><article>${tr("appearanceTitle", "h3")}${tr("appearanceText", "p")}</article><article>${tr("identityTitle", "h3")}${tr("identityText", "p")}</article></div></div></section>
|
||||
<section class="roadmap shell" id="roadmap" aria-labelledby="roadmap-title"><div class="roadmap-heading">${tr("roadmapTitle", "h2", 'id="roadmap-title"')}${tr("roadmapText", "p")}</div><div class="roadmap-columns"><article><h3><span class="connection-dot" aria-hidden="true"></span>${tr("available")}</h3><ul><li>${tr("availableOne")}</li><li>${tr("availableTwo")}</li><li>${tr("availableThree")}</li><li>${tr("availableFour")}</li><li>${tr("availableFive")}</li></ul></article><article><h3><span class="planned-dot" aria-hidden="true"></span>${tr("next")}</h3><ul><li>${tr("nextOne")}</li><li>${tr("nextTwo")}</li><li>${tr("nextThree")}</li></ul></article></div>${tr("downloadNote", "p", 'class="release-note"')}</section>
|
||||
<section class="faq shell" aria-labelledby="faq-title">${tr("faqTitle", "h2", 'id="faq-title"')}<div>${(["Server", "Central", "Release"] as const).map((key) => `<details><summary>${tr(`faq${key}`)}<span aria-hidden="true">+</span></summary>${tr(`faq${key}Answer`, "p")}</details>`).join("")}</div></section>
|
||||
<section class="status-section shell" aria-label="${t("statusNote")}" data-i18n-aria="statusNote"><div><span id="service-dot" class="status-dot"></span><p id="service-status" role="status">${t("statusLoading")}</p></div><a href="/account" class="text-link">${tr("openCentral")}${icon("external", 15)}</a></section>`;
|
||||
renderDiagram();
|
||||
main.querySelectorAll<HTMLElement>("[data-tab]").forEach((button) => {
|
||||
button.addEventListener("click", () => {
|
||||
activeTab = button.dataset.tab as Tab;
|
||||
renderDiagram();
|
||||
});
|
||||
button.addEventListener("keydown", (event) => {
|
||||
const tabs = [...main.querySelectorAll<HTMLElement>("[data-tab]")];
|
||||
let index = tabs.indexOf(button);
|
||||
if (event.key === "ArrowRight") index = (index + 1) % tabs.length;
|
||||
else if (event.key === "ArrowLeft")
|
||||
index = (index + tabs.length - 1) % tabs.length;
|
||||
else if (event.key === "Home") index = 0;
|
||||
else if (event.key === "End") index = tabs.length - 1;
|
||||
else return;
|
||||
event.preventDefault();
|
||||
activeTab = tabs[index]!.dataset.tab as Tab;
|
||||
renderDiagram();
|
||||
tabs[index]!.focus();
|
||||
});
|
||||
});
|
||||
}
|
||||
function renderDiagram() {
|
||||
const content = document.querySelector("#diagram-content");
|
||||
if (!content) return;
|
||||
main.querySelectorAll<HTMLElement>("[data-tab]").forEach((button) => {
|
||||
const active = button.dataset.tab === activeTab;
|
||||
button.setAttribute("aria-selected", String(active));
|
||||
button.tabIndex = active ? 0 : -1;
|
||||
});
|
||||
content.setAttribute("role", "tabpanel");
|
||||
content.setAttribute("aria-labelledby", `tab-${activeTab}`);
|
||||
if (activeTab === "text")
|
||||
content.innerHTML = `<div class="illustration-chat"><div class="message-heading"><span class="chat-avatar">V</span><div>${tr("community", "strong")}<div class="message-lines" aria-hidden="true"><i></i><i></i></div></div></div>${tr("messageSample", "p")}<div class="illustration-composer" aria-hidden="true"><span>+</span><i></i>${icon("chat", 15)}</div>${tr("messageNote", "p", 'class="diagram-caption"')}</div>`;
|
||||
if (activeTab === "voice")
|
||||
content.innerHTML = `<div class="illustration-voice"><div class="voice-orbit"><span class="voice-avatar">V</span><div class="waveform" aria-hidden="true">${Array.from({ length: 11 }, () => "<i></i>").join("")}</div><span class="voice-avatar friend-avatar">${icon("voice", 30)}</span></div>${tr("voiceExplain", "p")}<div class="voice-controls" aria-hidden="true"><span>${icon("mic")}</span><span>${icon("voice")}</span></div>${tr("voiceCaption", "p", 'class="diagram-caption"')}</div>`;
|
||||
if (activeTab === "theme") {
|
||||
content.innerHTML = `<div class="illustration-themes">${tr("themeCaption", "h3")}<div class="theme-options" role="group" aria-label="${t("previewTheme")}" data-i18n-aria="previewTheme">${(["light", "dark", "black", "custom"] as const).map((theme) => `<button class="theme-option ${theme}" data-theme="${theme}" aria-pressed="${activeTheme === theme}"><span class="theme-sample" aria-hidden="true"><i></i><i></i><i></i></span>${tr(theme)}</button>`).join("")}</div></div>`;
|
||||
content.querySelectorAll<HTMLElement>("[data-theme]").forEach((button) =>
|
||||
button.addEventListener("click", () => {
|
||||
activeTheme = button.dataset.theme as Theme;
|
||||
find(".product-diagram").dataset.previewTheme = activeTheme;
|
||||
content
|
||||
.querySelectorAll<HTMLElement>("[data-theme]")
|
||||
.forEach((item) =>
|
||||
item.setAttribute("aria-pressed", String(item === button)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
function account() {
|
||||
main.innerHTML = `<section class="account-section shell"><a href="/" class="text-link back-link">${icon("back", 17)}${tr("back")}</a><div class="account-layout"><div class="account-intro"><img class="account-mark" src="/assets/vnox-mark.svg" alt="" width="76" height="76">${tr("accountHeading", "h1")}${tr("accountIntro", "p")}<div class="account-explanation">${tr("accountStage", "p")}</div></div><div id="account-content" class="account-panel" aria-live="polite"></div></div></section>`;
|
||||
renderAccount();
|
||||
}
|
||||
function renderAccount() {
|
||||
const panel = document.querySelector("#account-content");
|
||||
if (!panel) return;
|
||||
panel.replaceChildren();
|
||||
if (sessionState === "loading") {
|
||||
panel.innerHTML = `<div class="account-loading"><span class="loading-ring" aria-hidden="true"></span>${tr("sessionLoading", "p")}</div>`;
|
||||
return;
|
||||
}
|
||||
if (sessionState === "error") {
|
||||
panel.innerHTML = `${tr("accountError", "h2")}${tr("accountErrorText", "p")}<button class="button primary" id="retry-session">${tr("retry")}</button>`;
|
||||
find("#retry-session", panel).addEventListener("click", refresh);
|
||||
return;
|
||||
}
|
||||
if (currentSession?.authenticated) {
|
||||
panel.innerHTML = `<div class="profile-heading"><div class="profile-avatar" id="profile-avatar" aria-hidden="true">V</div><div>${tr("profileTitle", "h2")}<p id="profile-name"></p></div></div>${tr("profileIntro", "p")}<dl class="profile-fields"><div><dt>${tr("handle")}</dt><dd id="profile-handle"></dd></div><div><dt>${tr("userId")}</dt><dd id="profile-id"></dd></div><div><dt>${tr("provider")}</dt><dd>GitHub</dd></div></dl><div class="profile-actions"><button class="button secondary" id="copy-id">${icon("copy", 17)}${tr("copy")}</button><button class="button quiet" id="logout" ${logoutState === "pending" ? "disabled" : ""}>${tr(logoutState === "pending" ? "loggingOut" : "logout")}</button></div><p class="form-message" id="profile-message" role="status"></p>`;
|
||||
const user = currentSession.user;
|
||||
find("#profile-name", panel).textContent =
|
||||
user.display_name || t("profileFallback");
|
||||
find("#profile-handle", panel).textContent = user.handle;
|
||||
find("#profile-id", panel).textContent = user.user_id;
|
||||
const avatar = safeAvatar(user.avatar_url);
|
||||
if (avatar) {
|
||||
const image = document.createElement("img");
|
||||
image.src = avatar;
|
||||
image.alt = "";
|
||||
image.referrerPolicy = "no-referrer";
|
||||
image.addEventListener("error", () => image.remove(), { once: true });
|
||||
find("#profile-avatar", panel).append(image);
|
||||
}
|
||||
find("#copy-id", panel).addEventListener("click", async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(user.user_id);
|
||||
find("#profile-message", panel).textContent = t("copied");
|
||||
} catch {
|
||||
find("#profile-message", panel).textContent = t("copyError");
|
||||
}
|
||||
});
|
||||
find("#logout", panel).addEventListener("click", logout);
|
||||
if (logoutState === "error")
|
||||
find("#profile-message", panel).textContent = t("logoutError");
|
||||
return;
|
||||
}
|
||||
panel.innerHTML = `<div class="login-provider">${icon("github", 33)}</div>${tr("loginTitle", "h2")}${tr("loginText", "p")}<a class="button primary github-login ${githubEnabled ? "" : "unavailable"}" ${githubEnabled ? 'href="/v1/auth/github/start"' : 'aria-disabled="true" tabindex="-1"'}>${icon("github", 21)}${tr("loginButton")}</a><p id="login-availability" class="form-message" role="status"></p><button class="text-button" id="retry-info" ${infoState === "error" ? "" : "hidden"}>${tr("retry")}</button><div class="privacy-note">${icon("check", 16)}${tr("privacy", "p")}</div>`;
|
||||
find("#login-availability", panel).textContent =
|
||||
infoState === "loading"
|
||||
? t("loginLoading")
|
||||
: infoState === "error"
|
||||
? t("loginUnavailable")
|
||||
: githubEnabled
|
||||
? ""
|
||||
: t("loginDisabled");
|
||||
find("#retry-info", panel).addEventListener("click", refresh);
|
||||
}
|
||||
async function logout() {
|
||||
if (!currentSession?.authenticated || logoutState === "pending") return;
|
||||
const csrf = currentSession.csrf_token;
|
||||
logoutState = "pending";
|
||||
renderAccount();
|
||||
try {
|
||||
await request("/v1/auth/logout", {
|
||||
method: "POST",
|
||||
csrf,
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
currentSession = { authenticated: false };
|
||||
logoutState = "idle";
|
||||
renderAccount();
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 401) {
|
||||
currentSession = { authenticated: false };
|
||||
logoutState = "idle";
|
||||
renderAccount();
|
||||
} else {
|
||||
logoutState = "error";
|
||||
renderAccount();
|
||||
}
|
||||
}
|
||||
}
|
||||
function updateStatus() {
|
||||
const status = document.querySelector("#service-status");
|
||||
if (status) {
|
||||
status.textContent = t(
|
||||
infoState === "loading"
|
||||
? "statusLoading"
|
||||
: infoState === "ready"
|
||||
? "statusReady"
|
||||
: "statusUnavailable",
|
||||
);
|
||||
find("#service-dot").dataset.state = infoState;
|
||||
}
|
||||
}
|
||||
async function refresh() {
|
||||
controller?.abort();
|
||||
controller = new AbortController();
|
||||
const currentController = controller;
|
||||
const signal = AbortSignal.any([
|
||||
currentController.signal,
|
||||
AbortSignal.timeout(15000),
|
||||
]);
|
||||
infoState = "loading";
|
||||
if (accountPage) {
|
||||
sessionState = "loading";
|
||||
renderAccount();
|
||||
} else updateStatus();
|
||||
const info = request("/v1/info", { signal })
|
||||
.then((value) => {
|
||||
if (controller !== currentController) return;
|
||||
if (!isInfo(value)) throw new Error("invalid_info");
|
||||
githubEnabled = value.capabilities.github_auth === "enabled";
|
||||
infoState = "ready";
|
||||
})
|
||||
.catch(() => {
|
||||
if (!currentController.signal.aborted) {
|
||||
githubEnabled = false;
|
||||
infoState = "error";
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (controller === currentController) {
|
||||
updateStatus();
|
||||
if (accountPage) renderAccount();
|
||||
}
|
||||
});
|
||||
if (accountPage) {
|
||||
await Promise.allSettled([
|
||||
info,
|
||||
request("/v1/auth/session", { signal })
|
||||
.then((value) => {
|
||||
if (controller !== currentController) return;
|
||||
if (!isSession(value)) throw new Error("invalid_session");
|
||||
currentSession = value;
|
||||
sessionState = "ready";
|
||||
})
|
||||
.catch(() => {
|
||||
if (!currentController.signal.aborted) sessionState = "error";
|
||||
})
|
||||
.finally(() => {
|
||||
if (controller === currentController) renderAccount();
|
||||
}),
|
||||
]);
|
||||
} else await info;
|
||||
}
|
||||
function setLanguage(next: Language) {
|
||||
language = next;
|
||||
try {
|
||||
localStorage.setItem("vnox-web-language", next);
|
||||
} catch {
|
||||
/* No authentication data is persisted. */
|
||||
}
|
||||
document.documentElement.lang = next;
|
||||
document.title = t(accountPage ? "accountTitle" : "title");
|
||||
find<HTMLMetaElement>('meta[name="description"]').content = t("description");
|
||||
document
|
||||
.querySelectorAll<HTMLElement>("[data-i18n]")
|
||||
.forEach(
|
||||
(element) =>
|
||||
(element.textContent = t(element.dataset.i18n as MessageKey)),
|
||||
);
|
||||
for (const [attribute, dataKey] of [
|
||||
["aria-label", "i18nAria"],
|
||||
["alt", "i18nAlt"],
|
||||
] as const)
|
||||
document
|
||||
.querySelectorAll<HTMLElement>(
|
||||
`[data-${attribute === "alt" ? "i18n-alt" : "i18n-aria"}]`,
|
||||
)
|
||||
.forEach((element) =>
|
||||
element.setAttribute(
|
||||
attribute,
|
||||
t(element.dataset[dataKey] as MessageKey),
|
||||
),
|
||||
);
|
||||
document
|
||||
.querySelectorAll<HTMLElement>("[data-language]")
|
||||
.forEach((button) =>
|
||||
button.setAttribute(
|
||||
"aria-pressed",
|
||||
String(button.dataset.language === next),
|
||||
),
|
||||
);
|
||||
if (accountPage) renderAccount();
|
||||
else {
|
||||
renderDiagram();
|
||||
updateStatus();
|
||||
}
|
||||
}
|
||||
if (accountPage) account();
|
||||
else landing();
|
||||
document
|
||||
.querySelectorAll<HTMLElement>("[data-language]")
|
||||
.forEach((button) =>
|
||||
button.addEventListener("click", () =>
|
||||
setLanguage(button.dataset.language as Language),
|
||||
),
|
||||
);
|
||||
setLanguage(language);
|
||||
refresh();
|
||||
window.addEventListener("pageshow", (event) => {
|
||||
if (event.persisted) refresh();
|
||||
});
|
||||
31
src/i18n.js
31
src/i18n.js
|
|
@ -1,31 +0,0 @@
|
|||
export const messages = {
|
||||
ru: {
|
||||
skip:'Перейти к содержимому', nav:'Основная навигация', navProject:'Проект', navClient:'Клиент', navRoadmap:'Дальше', language:'Язык', account:'Аккаунт', footer:'Сделано для разговоров, которые хочется продолжать.', source:'Исходный код',
|
||||
title:'VNOX — Своя связь', accountTitle:'Аккаунт — VNOX Central', description:'VNOX — голос и чат для своих сообществ. Нативный клиент, собственный сервер и открытый код.',
|
||||
development:'В открытой разработке', heroTitle:'Свои люди.\nСвоя связь.', heroText:'Место для вашего сообщества. Обсуждайте планы, оставайтесь в голосе и управляйте своим сервером сами.', openCentral:'Открыть Vnox Central', explore:'О проекте', earlyNote:'Ранняя версия. Разрабатываем открыто, без обещаний на вырост.',
|
||||
diagramLabel:'Схема общения', diagramNote:'Иллюстрация устройства клиента', textTab:'Текст', voiceTab:'Голос', themeTab:'Внешний вид', community:'Ваше сообщество', general:'общий', ideas:'идеи', voiceRoom:'Вечерний войс', voiceConnected:'Голос остаётся с вами', voiceExplain:'Переключайте текстовые каналы, не выходя из разговора.', you:'Вы', friend:'Друг', messageSample:'Общий чат для идей, ссылок и планов.', messageNote:'Чат и голос доступны в одном окне.', voiceCaption:'Отдельное управление микрофоном и звуком.', themeCaption:'Четыре варианта. Один ваш.', light:'Светлая', dark:'Тёмная', black:'Мега-тёмная', custom:'Своя', preview:'Предпросмотр', previewTheme:'Тема иллюстрации',
|
||||
projectTitle:'Одно приложение.\nВаш сервер.', projectText:'VNOX объединяет текст и голос в нативном клиенте. Сервер сообщества запускается одним приложением и остаётся под управлением его владельца.', projectNative:'Нативный клиент', projectNativeText:'Написан на Rust и Slint. Настройки звука, профиля и внешнего вида собраны в одном месте.', projectServer:'Сервер сообщества', projectServerText:'Текстовые каналы и голос в одном серверном приложении. Владелец выбирает, где его запускать.', projectCentral:'Vnox Central', projectCentralText:'Центральный сервис для аккаунта. Каталог серверов и друзья — следующие этапы разработки.', clientCode:'Код клиента', serverCode:'Код сервера',
|
||||
clientTitle:'Удобство начинается\nс простых вещей.', clientText:'Светлая, тёмная, мега-тёмная или собственная тема. Размер текста, звук и профиль — там, где их ожидаешь найти.', clientScreenshot:'Настройки внешнего вида нативного клиента VNOX: четыре темы и размер текста.', screenshotCaption:'Настоящий снимок нативного клиента. Интерфейс продолжает развиваться.', appearanceTitle:'Внешний вид — ваш', appearanceText:'Своя палитра через поддерживаемые CSS-переменные. Без загрузки внешних ресурсов.', identityTitle:'Профиль без суеты', identityText:'Выберите фотографию, настройте масштаб и положение в круглом предпросмотре.',
|
||||
roadmapTitle:'Сначала надёжная связь.\nПотом всё остальное.', roadmapText:'Проект ещё в разработке. Здесь разделены доступные части и то, над чем мы работаем.', available:'Уже в коде', next:'В работе и планах', availableOne:'Нативный клиент, каналы и голос', availableTwo:'Настройки, темы и редактор аватара', availableThree:'Центральный сервис и защищённое соединение', availableFour:'Веб-аккаунт GitHub и интерфейс RU / EN', availableFive:'Входящие и подписанные исходящие вебхуки на сервере', nextOne:'Управление вебхуками в клиенте', nextTwo:'Трансляция экрана с раздельным звуком', nextThree:'Друзья и поиск серверов', downloadNote:'Публичные сборки появятся после проверки совместимости клиента и сервера. Пока доступны исходники.',
|
||||
faqTitle:'До первого разговора', faqServer:'Нужен ли отдельный голосовой сервер?', faqServerAnswer:'Нет. Для сообщества планируется одно серверное приложение, которое включает чат и голос.', faqCentral:'Зачем нужен Vnox Central?', faqCentralAnswer:'Для общего аккаунта и будущих социальных функций. Само сообщество размещает свой сервер отдельно.', faqRelease:'Где скачать клиент?', faqReleaseAnswer:'Проверенного публичного релиза пока нет. Код клиента и сервера открыт; инструкции по сборке находятся в их репозиториях.',
|
||||
statusLoading:'Проверяем Vnox Central…', statusReady:'Vnox Central отвечает', statusUnavailable:'Не удалось связаться с Vnox Central', statusNote:'Состояние центрального сервиса', retry:'Повторить',
|
||||
back:'На главную', accountHeading:'Ваш Vnox Central.', accountIntro:'Один аккаунт для будущих сообществ. Начните с безопасного входа через GitHub.', loginTitle:'Продолжить с GitHub', loginText:'VNOX получает ваш публичный профиль GitHub. Доступ к репозиториям для входа не запрашивается.', loginButton:'Войти через GitHub', loginLoading:'Проверяем возможность входа…', loginDisabled:'Вход через GitHub пока не включён на сервере.', loginUnavailable:'Не удалось проверить доступность входа. Повторите попытку.', privacy:'Авторизация происходит на github.com. Пароль GitHub остаётся у GitHub.', accountStage:'Центральный аккаунт пока не привязывается к локальным ключам настольного клиента. Друзья, серверы и сообщения появятся позже.', sessionLoading:'Загружаем аккаунт…', profileTitle:'Вы на связи.', profileIntro:'Вход через GitHub выполнен. Это ваш центральный аккаунт VNOX.', handle:'Имя аккаунта', userId:'ID аккаунта', provider:'Способ входа', logout:'Выйти из аккаунта', loggingOut:'Выходим…', logoutError:'Не удалось выйти. Повторите попытку.', sessionExpired:'Сессия завершилась. Войдите снова.', profileFallback:'Пользователь VNOX', accountError:'Аккаунт сейчас недоступен', accountErrorText:'Не удалось загрузить сессию. Проверьте соединение и повторите попытку.', copy:'Скопировать ID', copied:'ID скопирован', copyError:'Не удалось скопировать ID. Выделите его вручную.',
|
||||
},
|
||||
en: {
|
||||
skip:'Skip to content', nav:'Main navigation', navProject:'Project', navClient:'Client', navRoadmap:'What’s next', language:'Language', account:'Account', footer:'Made for conversations you want to continue.', source:'Source code',
|
||||
title:'VNOX — Your own connection', accountTitle:'Account — VNOX Central', description:'VNOX brings voice and chat to your community. Native client, your own server, open source.',
|
||||
development:'In open development', heroTitle:'Your people.\nYour connection.', heroText:'A place for your community. Share your plans, stay in voice and run your server on your terms.', openCentral:'Open Vnox Central', explore:'Explore the project', earlyNote:'An early version, developed in the open.',
|
||||
diagramLabel:'How you stay connected', diagramNote:'An illustration of the client layout', textTab:'Text', voiceTab:'Voice', themeTab:'Appearance', community:'Your community', general:'general', ideas:'ideas', voiceRoom:'Evening voice', voiceConnected:'Voice stays with you', voiceExplain:'Browse text channels without leaving the conversation.', you:'You', friend:'Friend', messageSample:'A shared chat for ideas, links and plans.', messageNote:'Chat and voice, together in one window.', voiceCaption:'Separate controls for your microphone and sound.', themeCaption:'Four options. One that’s yours.', light:'Light', dark:'Dark', black:'Mega dark', custom:'Custom', preview:'Preview', previewTheme:'Illustration theme',
|
||||
projectTitle:'One application.\nYour own server.', projectText:'VNOX brings text and voice together in a native client. One server application runs your community, under its owner’s control.', projectNative:'Native client', projectNativeText:'Built with Rust and Slint. Audio, profile and appearance settings, all in one place.', projectServer:'Community server', projectServerText:'Text channels and voice in one server application. Its owner chooses where to run it.', projectCentral:'Vnox Central', projectCentralText:'The central service for your account. Server discovery and friends are the next stages.', clientCode:'Client source', serverCode:'Server source',
|
||||
clientTitle:'Comfort starts\nwith simple things.', clientText:'Light, dark, mega dark or your own theme. Text size, audio and your profile, right where you expect them.', clientScreenshot:'Appearance settings in the native VNOX client, with four themes and a text size slider.', screenshotCaption:'A real screenshot of the native client. The interface is still evolving.', appearanceTitle:'Make it yours', appearanceText:'Create your palette with supported CSS variables. No external resources are loaded.', identityTitle:'A profile without the fuss', identityText:'Choose a photo, then adjust its zoom and position inside a circular preview.',
|
||||
roadmapTitle:'Reliable conversation first.\nThe rest comes next.', roadmapText:'VNOX is still being developed. Here is what exists in the code and what we’re building next.', available:'Already in the code', next:'In progress and planned', availableOne:'Native client, channels and voice', availableTwo:'Settings, themes and avatar editor', availableThree:'Central service and HTTPS', availableFour:'GitHub web account and RU / EN interface', availableFive:'Incoming and signed outgoing server webhooks', nextOne:'Webhook management in the client', nextTwo:'Screen broadcasting with separate audio sources', nextThree:'Friends and server discovery', downloadNote:'Public builds will follow client and server compatibility checks. Source code is available now.',
|
||||
faqTitle:'Before the first conversation', faqServer:'Do I need a separate voice server?', faqServerAnswer:'No. A community is intended to run one server application with both chat and voice.', faqCentral:'What is Vnox Central for?', faqCentralAnswer:'Your shared account and future social features. Each community hosts its own server separately.', faqRelease:'Where can I download the client?', faqReleaseAnswer:'There is no verified public release yet. Client and server code is open, with build instructions in their repositories.',
|
||||
statusLoading:'Checking Vnox Central…', statusReady:'Vnox Central is responding', statusUnavailable:'Could not reach Vnox Central', statusNote:'Central service status', retry:'Try again',
|
||||
back:'Back to home', accountHeading:'Your Vnox Central.', accountIntro:'One account for future communities. Start with secure GitHub sign-in.', loginTitle:'Continue with GitHub', loginText:'VNOX receives your public GitHub profile. Signing in does not request access to your repositories.', loginButton:'Sign in with GitHub', loginLoading:'Checking sign-in availability…', loginDisabled:'GitHub sign-in is not enabled on the server yet.', loginUnavailable:'Could not check sign-in availability. Try again.', privacy:'You authorize on github.com. Your GitHub password stays with GitHub.', accountStage:'Your central account is not yet linked to the desktop client’s local keys. Friends, servers and messages will follow.', sessionLoading:'Loading your account…', profileTitle:'You’re connected.', profileIntro:'Signed in with GitHub. This is your central VNOX account.', handle:'Account handle', userId:'Account ID', provider:'Signed in with', logout:'Sign out', loggingOut:'Signing out…', logoutError:'Could not sign out. Try again.', sessionExpired:'Your session ended. Sign in again.', profileFallback:'VNOX user', accountError:'Your account is currently unavailable', accountErrorText:'Could not load your session. Check your connection and try again.', copy:'Copy account ID', copied:'Account ID copied', copyError:'Could not copy the ID. Select it manually.',
|
||||
},
|
||||
};
|
||||
export function detectLanguage(saved, languages = []) {
|
||||
if (saved === 'ru' || saved === 'en') return saved;
|
||||
return languages.some(value => /^ru(?:-|$)/i.test(value)) ? 'ru' : 'en';
|
||||
}
|
||||
export function translate(language, key) { return messages[language]?.[key] ?? messages.en[key] ?? key; }
|
||||
284
src/i18n.ts
Normal file
284
src/i18n.ts
Normal file
|
|
@ -0,0 +1,284 @@
|
|||
export const messages = {
|
||||
ru: {
|
||||
skip: "Перейти к содержимому",
|
||||
nav: "Основная навигация",
|
||||
navProject: "Проект",
|
||||
navClient: "Клиент",
|
||||
navRoadmap: "Дальше",
|
||||
language: "Язык",
|
||||
account: "Аккаунт",
|
||||
footer: "Сделано для разговоров, которые хочется продолжать.",
|
||||
source: "Исходный код",
|
||||
title: "VNOX — Своя связь",
|
||||
accountTitle: "Аккаунт — VNOX Central",
|
||||
description:
|
||||
"VNOX — голос и чат для своих сообществ. Нативный клиент, собственный сервер и открытый код.",
|
||||
development: "В открытой разработке",
|
||||
heroTitle: "Свои люди.\nСвоя связь.",
|
||||
heroText:
|
||||
"Место для вашего сообщества. Обсуждайте планы, оставайтесь в голосе и управляйте своим сервером сами.",
|
||||
openCentral: "Открыть Vnox Central",
|
||||
explore: "О проекте",
|
||||
earlyNote: "Ранняя версия. Разрабатываем открыто, без обещаний на вырост.",
|
||||
diagramLabel: "Схема общения",
|
||||
diagramNote: "Иллюстрация устройства клиента",
|
||||
textTab: "Текст",
|
||||
voiceTab: "Голос",
|
||||
themeTab: "Внешний вид",
|
||||
community: "Ваше сообщество",
|
||||
general: "общий",
|
||||
ideas: "идеи",
|
||||
voiceRoom: "Вечерний войс",
|
||||
voiceConnected: "Голос остаётся с вами",
|
||||
voiceExplain: "Переключайте текстовые каналы, не выходя из разговора.",
|
||||
you: "Вы",
|
||||
friend: "Друг",
|
||||
messageSample: "Общий чат для идей, ссылок и планов.",
|
||||
messageNote: "Чат и голос доступны в одном окне.",
|
||||
voiceCaption: "Отдельное управление микрофоном и звуком.",
|
||||
themeCaption: "Четыре варианта. Один ваш.",
|
||||
light: "Светлая",
|
||||
dark: "Тёмная",
|
||||
black: "Мега-тёмная",
|
||||
custom: "Своя",
|
||||
preview: "Предпросмотр",
|
||||
previewTheme: "Тема иллюстрации",
|
||||
projectTitle: "Одно приложение.\nВаш сервер.",
|
||||
projectText:
|
||||
"VNOX объединяет текст и голос в нативном клиенте. Сервер сообщества запускается одним приложением и остаётся под управлением его владельца.",
|
||||
projectNative: "Нативный клиент",
|
||||
projectNativeText:
|
||||
"Написан на Rust и Slint. Настройки звука, профиля и внешнего вида собраны в одном месте.",
|
||||
projectServer: "Сервер сообщества",
|
||||
projectServerText:
|
||||
"Текстовые каналы и голос в одном серверном приложении. Владелец выбирает, где его запускать.",
|
||||
projectCentral: "Vnox Central",
|
||||
projectCentralText:
|
||||
"Центральный сервис для аккаунта. Каталог серверов и друзья — следующие этапы разработки.",
|
||||
clientCode: "Код клиента",
|
||||
serverCode: "Код сервера",
|
||||
clientTitle: "Удобство начинается\nс простых вещей.",
|
||||
clientText:
|
||||
"Светлая, тёмная, мега-тёмная или собственная тема. Размер текста, звук и профиль — там, где их ожидаешь найти.",
|
||||
clientScreenshot:
|
||||
"Настройки внешнего вида нативного клиента VNOX: четыре темы и размер текста.",
|
||||
screenshotCaption:
|
||||
"Настоящий снимок нативного клиента. Интерфейс продолжает развиваться.",
|
||||
appearanceTitle: "Внешний вид — ваш",
|
||||
appearanceText:
|
||||
"Своя палитра через поддерживаемые CSS-переменные. Без загрузки внешних ресурсов.",
|
||||
identityTitle: "Профиль без суеты",
|
||||
identityText:
|
||||
"Выберите фотографию, настройте масштаб и положение в круглом предпросмотре.",
|
||||
roadmapTitle: "Сначала надёжная связь.\nПотом всё остальное.",
|
||||
roadmapText:
|
||||
"Проект ещё в разработке. Здесь разделены доступные части и то, над чем мы работаем.",
|
||||
available: "Уже в коде",
|
||||
next: "В работе и планах",
|
||||
availableOne: "Нативный клиент, каналы и голос",
|
||||
availableTwo: "Настройки, темы и редактор аватара",
|
||||
availableThree: "Центральный сервис и защищённое соединение",
|
||||
availableFour: "Веб-аккаунт GitHub и интерфейс RU / EN",
|
||||
availableFive: "Входящие и подписанные исходящие вебхуки на сервере",
|
||||
nextOne: "Управление вебхуками в клиенте",
|
||||
nextTwo: "Трансляция экрана с раздельным звуком",
|
||||
nextThree: "Друзья и поиск серверов",
|
||||
downloadNote:
|
||||
"Публичные сборки появятся после проверки совместимости клиента и сервера. Пока доступны исходники.",
|
||||
faqTitle: "До первого разговора",
|
||||
faqServer: "Нужен ли отдельный голосовой сервер?",
|
||||
faqServerAnswer:
|
||||
"Нет. Для сообщества планируется одно серверное приложение, которое включает чат и голос.",
|
||||
faqCentral: "Зачем нужен Vnox Central?",
|
||||
faqCentralAnswer:
|
||||
"Для общего аккаунта и будущих социальных функций. Само сообщество размещает свой сервер отдельно.",
|
||||
faqRelease: "Где скачать клиент?",
|
||||
faqReleaseAnswer:
|
||||
"Проверенного публичного релиза пока нет. Код клиента и сервера открыт; инструкции по сборке находятся в их репозиториях.",
|
||||
statusLoading: "Проверяем Vnox Central…",
|
||||
statusReady: "Vnox Central отвечает",
|
||||
statusUnavailable: "Не удалось связаться с Vnox Central",
|
||||
statusNote: "Состояние центрального сервиса",
|
||||
retry: "Повторить",
|
||||
back: "На главную",
|
||||
accountHeading: "Ваш Vnox Central.",
|
||||
accountIntro:
|
||||
"Один аккаунт для будущих сообществ. Начните с безопасного входа через GitHub.",
|
||||
loginTitle: "Продолжить с GitHub",
|
||||
loginText:
|
||||
"VNOX получает ваш публичный профиль GitHub. Доступ к репозиториям для входа не запрашивается.",
|
||||
loginButton: "Войти через GitHub",
|
||||
loginLoading: "Проверяем возможность входа…",
|
||||
loginDisabled: "Вход через GitHub пока не включён на сервере.",
|
||||
loginUnavailable:
|
||||
"Не удалось проверить доступность входа. Повторите попытку.",
|
||||
privacy:
|
||||
"Авторизация происходит на github.com. Пароль GitHub остаётся у GitHub.",
|
||||
accountStage:
|
||||
"Центральный аккаунт пока не привязывается к локальным ключам настольного клиента. Друзья, серверы и сообщения появятся позже.",
|
||||
sessionLoading: "Загружаем аккаунт…",
|
||||
profileTitle: "Вы на связи.",
|
||||
profileIntro:
|
||||
"Вход через GitHub выполнен. Это ваш центральный аккаунт VNOX.",
|
||||
handle: "Имя аккаунта",
|
||||
userId: "ID аккаунта",
|
||||
provider: "Способ входа",
|
||||
logout: "Выйти из аккаунта",
|
||||
loggingOut: "Выходим…",
|
||||
logoutError: "Не удалось выйти. Повторите попытку.",
|
||||
sessionExpired: "Сессия завершилась. Войдите снова.",
|
||||
profileFallback: "Пользователь VNOX",
|
||||
accountError: "Аккаунт сейчас недоступен",
|
||||
accountErrorText:
|
||||
"Не удалось загрузить сессию. Проверьте соединение и повторите попытку.",
|
||||
copy: "Скопировать ID",
|
||||
copied: "ID скопирован",
|
||||
copyError: "Не удалось скопировать ID. Выделите его вручную.",
|
||||
},
|
||||
en: {
|
||||
skip: "Skip to content",
|
||||
nav: "Main navigation",
|
||||
navProject: "Project",
|
||||
navClient: "Client",
|
||||
navRoadmap: "What’s next",
|
||||
language: "Language",
|
||||
account: "Account",
|
||||
footer: "Made for conversations you want to continue.",
|
||||
source: "Source code",
|
||||
title: "VNOX — Your own connection",
|
||||
accountTitle: "Account — VNOX Central",
|
||||
description:
|
||||
"VNOX brings voice and chat to your community. Native client, your own server, open source.",
|
||||
development: "In open development",
|
||||
heroTitle: "Your people.\nYour connection.",
|
||||
heroText:
|
||||
"A place for your community. Share your plans, stay in voice and run your server on your terms.",
|
||||
openCentral: "Open Vnox Central",
|
||||
explore: "Explore the project",
|
||||
earlyNote: "An early version, developed in the open.",
|
||||
diagramLabel: "How you stay connected",
|
||||
diagramNote: "An illustration of the client layout",
|
||||
textTab: "Text",
|
||||
voiceTab: "Voice",
|
||||
themeTab: "Appearance",
|
||||
community: "Your community",
|
||||
general: "general",
|
||||
ideas: "ideas",
|
||||
voiceRoom: "Evening voice",
|
||||
voiceConnected: "Voice stays with you",
|
||||
voiceExplain: "Browse text channels without leaving the conversation.",
|
||||
you: "You",
|
||||
friend: "Friend",
|
||||
messageSample: "A shared chat for ideas, links and plans.",
|
||||
messageNote: "Chat and voice, together in one window.",
|
||||
voiceCaption: "Separate controls for your microphone and sound.",
|
||||
themeCaption: "Four options. One that’s yours.",
|
||||
light: "Light",
|
||||
dark: "Dark",
|
||||
black: "Mega dark",
|
||||
custom: "Custom",
|
||||
preview: "Preview",
|
||||
previewTheme: "Illustration theme",
|
||||
projectTitle: "One application.\nYour own server.",
|
||||
projectText:
|
||||
"VNOX brings text and voice together in a native client. One server application runs your community, under its owner’s control.",
|
||||
projectNative: "Native client",
|
||||
projectNativeText:
|
||||
"Built with Rust and Slint. Audio, profile and appearance settings, all in one place.",
|
||||
projectServer: "Community server",
|
||||
projectServerText:
|
||||
"Text channels and voice in one server application. Its owner chooses where to run it.",
|
||||
projectCentral: "Vnox Central",
|
||||
projectCentralText:
|
||||
"The central service for your account. Server discovery and friends are the next stages.",
|
||||
clientCode: "Client source",
|
||||
serverCode: "Server source",
|
||||
clientTitle: "Comfort starts\nwith simple things.",
|
||||
clientText:
|
||||
"Light, dark, mega dark or your own theme. Text size, audio and your profile, right where you expect them.",
|
||||
clientScreenshot:
|
||||
"Appearance settings in the native VNOX client, with four themes and a text size slider.",
|
||||
screenshotCaption:
|
||||
"A real screenshot of the native client. The interface is still evolving.",
|
||||
appearanceTitle: "Make it yours",
|
||||
appearanceText:
|
||||
"Create your palette with supported CSS variables. No external resources are loaded.",
|
||||
identityTitle: "A profile without the fuss",
|
||||
identityText:
|
||||
"Choose a photo, then adjust its zoom and position inside a circular preview.",
|
||||
roadmapTitle: "Reliable conversation first.\nThe rest comes next.",
|
||||
roadmapText:
|
||||
"VNOX is still being developed. Here is what exists in the code and what we’re building next.",
|
||||
available: "Already in the code",
|
||||
next: "In progress and planned",
|
||||
availableOne: "Native client, channels and voice",
|
||||
availableTwo: "Settings, themes and avatar editor",
|
||||
availableThree: "Central service and HTTPS",
|
||||
availableFour: "GitHub web account and RU / EN interface",
|
||||
availableFive: "Incoming and signed outgoing server webhooks",
|
||||
nextOne: "Webhook management in the client",
|
||||
nextTwo: "Screen broadcasting with separate audio sources",
|
||||
nextThree: "Friends and server discovery",
|
||||
downloadNote:
|
||||
"Public builds will follow client and server compatibility checks. Source code is available now.",
|
||||
faqTitle: "Before the first conversation",
|
||||
faqServer: "Do I need a separate voice server?",
|
||||
faqServerAnswer:
|
||||
"No. A community is intended to run one server application with both chat and voice.",
|
||||
faqCentral: "What is Vnox Central for?",
|
||||
faqCentralAnswer:
|
||||
"Your shared account and future social features. Each community hosts its own server separately.",
|
||||
faqRelease: "Where can I download the client?",
|
||||
faqReleaseAnswer:
|
||||
"There is no verified public release yet. Client and server code is open, with build instructions in their repositories.",
|
||||
statusLoading: "Checking Vnox Central…",
|
||||
statusReady: "Vnox Central is responding",
|
||||
statusUnavailable: "Could not reach Vnox Central",
|
||||
statusNote: "Central service status",
|
||||
retry: "Try again",
|
||||
back: "Back to home",
|
||||
accountHeading: "Your Vnox Central.",
|
||||
accountIntro:
|
||||
"One account for future communities. Start with secure GitHub sign-in.",
|
||||
loginTitle: "Continue with GitHub",
|
||||
loginText:
|
||||
"VNOX receives your public GitHub profile. Signing in does not request access to your repositories.",
|
||||
loginButton: "Sign in with GitHub",
|
||||
loginLoading: "Checking sign-in availability…",
|
||||
loginDisabled: "GitHub sign-in is not enabled on the server yet.",
|
||||
loginUnavailable: "Could not check sign-in availability. Try again.",
|
||||
privacy:
|
||||
"You authorize on github.com. Your GitHub password stays with GitHub.",
|
||||
accountStage:
|
||||
"Your central account is not yet linked to the desktop client’s local keys. Friends, servers and messages will follow.",
|
||||
sessionLoading: "Loading your account…",
|
||||
profileTitle: "You’re connected.",
|
||||
profileIntro: "Signed in with GitHub. This is your central VNOX account.",
|
||||
handle: "Account handle",
|
||||
userId: "Account ID",
|
||||
provider: "Signed in with",
|
||||
logout: "Sign out",
|
||||
loggingOut: "Signing out…",
|
||||
logoutError: "Could not sign out. Try again.",
|
||||
sessionExpired: "Your session ended. Sign in again.",
|
||||
profileFallback: "VNOX user",
|
||||
accountError: "Your account is currently unavailable",
|
||||
accountErrorText:
|
||||
"Could not load your session. Check your connection and try again.",
|
||||
copy: "Copy account ID",
|
||||
copied: "Account ID copied",
|
||||
copyError: "Could not copy the ID. Select it manually.",
|
||||
},
|
||||
} as const;
|
||||
export type Language = keyof typeof messages;
|
||||
export type MessageKey = keyof typeof messages.en;
|
||||
export function detectLanguage(
|
||||
saved: unknown,
|
||||
languages: readonly string[] = [],
|
||||
): Language {
|
||||
if (saved === "ru" || saved === "en") return saved;
|
||||
return languages.some((value) => /^ru(?:-|$)/i.test(value)) ? "ru" : "en";
|
||||
}
|
||||
export function translate(language: Language, key: MessageKey): string {
|
||||
return messages[language]?.[key] ?? messages.en[key] ?? key;
|
||||
}
|
||||
1888
src/styles.css
1888
src/styles.css
File diff suppressed because one or more lines are too long
|
|
@ -1,43 +0,0 @@
|
|||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { request, isSession, safeAvatar, ApiError } from '../src/api.js';
|
||||
import { messages, detectLanguage } from '../src/i18n.js';
|
||||
|
||||
test('catalogs match and never silently fall back to a missing translation',()=>{
|
||||
assert.deepEqual(Object.keys(messages.ru).sort(),Object.keys(messages.en).sort());
|
||||
for (const catalog of Object.values(messages)) for (const value of Object.values(catalog)) assert.ok(typeof value==='string' && value.length>0);
|
||||
});
|
||||
test('language preference is bounded and follows the OS without storage',()=>{
|
||||
assert.equal(detectLanguage('en',['ru-RU']),'en');
|
||||
assert.equal(detectLanguage('bad',['ru-RU']),'ru');
|
||||
assert.equal(detectLanguage(undefined,['pl-PL']),'en');
|
||||
assert.equal(detectLanguage('RU',['en-US']),'en');
|
||||
});
|
||||
test('API keeps authentication on the same origin and sends CSRF only in header',async()=>{
|
||||
let observed;
|
||||
const result=await request('/v1/auth/logout',{method:'POST',csrf:'fixture-csrf',fetcher:async(path,options)=>{
|
||||
observed={path,options};return {ok:true,status:204};
|
||||
}});
|
||||
assert.equal(result,null);
|
||||
assert.equal(observed.path,'/v1/auth/logout');
|
||||
assert.equal(observed.options.credentials,'same-origin');
|
||||
assert.equal(observed.options.cache,'no-store');
|
||||
assert.equal(observed.options.headers['X-CSRF-Token'],'fixture-csrf');
|
||||
assert.equal(observed.options.method,'POST');
|
||||
await assert.rejects(request('https://evil.example/v1/auth/session'),TypeError);
|
||||
await assert.rejects(request('//evil.example/v1/auth/session'),TypeError);
|
||||
});
|
||||
test('API failures expose a generic code and preserve status for expired sessions',async()=>{
|
||||
await assert.rejects(request('/v1/auth/session',{fetcher:async()=>({ok:false,status:401})}),error=>error instanceof ApiError && error.status===401 && error.message==='request_failed');
|
||||
});
|
||||
test('session validation rejects malformed authenticated payloads',()=>{
|
||||
assert.ok(isSession({authenticated:false}));
|
||||
assert.ok(isSession({authenticated:true,csrf_token:'fixture',user:{user_id:'fixture',handle:'test',display_name:'Test'}}));
|
||||
assert.equal(isSession({authenticated:true,user:{}}),false);
|
||||
assert.equal(isSession({authenticated:'true'}),false);
|
||||
assert.equal(isSession({authenticated:true,csrf_token:'',user:{user_id:'fixture',handle:'test',display_name:'Test'}}),false);
|
||||
});
|
||||
test('avatars allow only uncredentialed HTTPS GitHub image origin',()=>{
|
||||
assert.equal(safeAvatar('https://avatars.githubusercontent.com/u/1?v=4'),'https://avatars.githubusercontent.com/u/1?v=4');
|
||||
for (const url of ['javascript:alert(1)','data:image/svg+xml,<svg/>','http://avatars.githubusercontent.com/u/1','https://avatars.githubusercontent.com.evil.example/u/1','https://evil@avatars.githubusercontent.com/u/1','https://avatars.githubusercontent.com:8443/u/1','https://evil.example/u/1',null]) assert.equal(safeAvatar(url),null);
|
||||
});
|
||||
107
tests/api.test.ts
Normal file
107
tests/api.test.ts
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
import { test } from "bun:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { request, isSession, isInfo, safeAvatar, ApiError } from "../src/api";
|
||||
import { messages, detectLanguage } from "../src/i18n";
|
||||
|
||||
test("catalogs match and never silently fall back to a missing translation", () => {
|
||||
assert.deepEqual(
|
||||
Object.keys(messages.ru).sort(),
|
||||
Object.keys(messages.en).sort(),
|
||||
);
|
||||
for (const catalog of Object.values(messages))
|
||||
for (const value of Object.values(catalog))
|
||||
assert.ok(typeof value === "string" && value.length > 0);
|
||||
});
|
||||
test("language preference is bounded and follows the OS without storage", () => {
|
||||
assert.equal(detectLanguage("en", ["ru-RU"]), "en");
|
||||
assert.equal(detectLanguage("bad", ["ru-RU"]), "ru");
|
||||
assert.equal(detectLanguage(undefined, ["pl-PL"]), "en");
|
||||
assert.equal(detectLanguage("RU", ["en-US"]), "en");
|
||||
});
|
||||
test("API keeps authentication on the same origin and sends CSRF only in header", async () => {
|
||||
let observed: { path: string; options: RequestInit } | undefined;
|
||||
const result = await request("/v1/auth/logout", {
|
||||
method: "POST",
|
||||
csrf: "fixture-csrf",
|
||||
fetcher: async (path, options) => {
|
||||
observed = { path, options };
|
||||
return new Response(null, { status: 204 });
|
||||
},
|
||||
});
|
||||
assert.equal(result, null);
|
||||
assert.ok(observed);
|
||||
assert.equal(observed.path, "/v1/auth/logout");
|
||||
assert.equal(observed.options.credentials, "same-origin");
|
||||
assert.equal(observed.options.cache, "no-store");
|
||||
assert.equal(
|
||||
new Headers(observed.options.headers).get("X-CSRF-Token"),
|
||||
"fixture-csrf",
|
||||
);
|
||||
assert.equal(observed.options.method, "POST");
|
||||
await assert.rejects(
|
||||
request("https://evil.example/v1/auth/session"),
|
||||
TypeError,
|
||||
);
|
||||
await assert.rejects(request("//evil.example/v1/auth/session"), TypeError);
|
||||
});
|
||||
test("API failures expose a generic code and preserve status for expired sessions", async () => {
|
||||
await assert.rejects(
|
||||
request("/v1/auth/session", {
|
||||
fetcher: async () => new Response(null, { status: 401 }),
|
||||
}),
|
||||
(error: unknown) =>
|
||||
error instanceof ApiError &&
|
||||
error.status === 401 &&
|
||||
error.message === "request_failed",
|
||||
);
|
||||
});
|
||||
test("session validation rejects malformed authenticated payloads", () => {
|
||||
assert.ok(isSession({ authenticated: false }));
|
||||
assert.ok(
|
||||
isSession({
|
||||
authenticated: true,
|
||||
csrf_token: "fixture",
|
||||
user: { user_id: "fixture", handle: "test", display_name: "Test" },
|
||||
}),
|
||||
);
|
||||
assert.equal(isSession({ authenticated: true, user: {} }), false);
|
||||
assert.equal(isSession({ authenticated: "true" }), false);
|
||||
assert.equal(
|
||||
isSession({
|
||||
authenticated: true,
|
||||
csrf_token: "",
|
||||
user: { user_id: "fixture", handle: "test", display_name: "Test" },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
});
|
||||
test("avatars allow only uncredentialed HTTPS GitHub image origin", () => {
|
||||
assert.equal(
|
||||
safeAvatar("https://avatars.githubusercontent.com/u/1?v=4"),
|
||||
"https://avatars.githubusercontent.com/u/1?v=4",
|
||||
);
|
||||
for (const url of [
|
||||
"javascript:alert(1)",
|
||||
"data:image/svg+xml,<svg/>",
|
||||
"http://avatars.githubusercontent.com/u/1",
|
||||
"https://avatars.githubusercontent.com.evil.example/u/1",
|
||||
"https://evil@avatars.githubusercontent.com/u/1",
|
||||
"https://avatars.githubusercontent.com:8443/u/1",
|
||||
"https://evil.example/u/1",
|
||||
null,
|
||||
])
|
||||
assert.equal(safeAvatar(url), null);
|
||||
});
|
||||
|
||||
test("Hub capabilities reject malformed JSON before enabling sign-in", () => {
|
||||
assert.ok(isInfo({ capabilities: { github_auth: "enabled" } }));
|
||||
for (const value of [
|
||||
null,
|
||||
false,
|
||||
{},
|
||||
{ capabilities: null },
|
||||
{ capabilities: { github_auth: true } },
|
||||
]) {
|
||||
assert.equal(isInfo(value), false);
|
||||
}
|
||||
});
|
||||
|
|
@ -1,16 +0,0 @@
|
|||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { once } from 'node:events';
|
||||
import http from 'node:http';
|
||||
function fetchRaw(port,path){return new Promise((resolve,reject)=>{http.get({host:'127.0.0.1',port,path},response=>{let body='';response.on('data',chunk=>body+=chunk);response.on('end',()=>resolve({status:response.statusCode,body}));}).on('error',reject);});}
|
||||
test('preview serves only public/source assets and blocks encoded traversal',async t=>{
|
||||
const port=24176;
|
||||
const process=spawn(globalThis.process.execPath,['scripts/serve.mjs'],{env:{...globalThis.process.env,PORT:String(port)},stdio:['ignore','pipe','pipe']});
|
||||
t.after(()=>process.kill('SIGTERM'));
|
||||
await Promise.race([once(process.stdout,'data'),once(process,'exit').then(()=>{throw new Error('preview failed to start');})]);
|
||||
for(const path of ['/','/account','/account/','/src/app.js','/assets/vnox-mark.png']) assert.equal((await fetchRaw(port,path)).status,200,path);
|
||||
for(const path of ['/src/%2e%2e%2fpackage.json','/src/%2e%2e%2f.env','/src/%2e%2e%2fLICENSE']) assert.equal((await fetchRaw(port,path)).status,403,path);
|
||||
assert.equal((await fetchRaw(port,'/package.json')).status,404);
|
||||
assert.equal((await fetchRaw(port,'/v1/auth/session')).status,503);
|
||||
});
|
||||
72
tests/server.test.ts
Normal file
72
tests/server.test.ts
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
import { test, expect } from "bun:test";
|
||||
import { spawn } from "node:child_process";
|
||||
import { once } from "node:events";
|
||||
import http from "node:http";
|
||||
|
||||
function fetchRaw(
|
||||
port: number,
|
||||
path: string,
|
||||
): Promise<{ status: number | undefined; body: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
http
|
||||
.get({ host: "127.0.0.1", port, path }, (response) => {
|
||||
let body = "";
|
||||
response.on("data", (chunk) => {
|
||||
body += chunk;
|
||||
});
|
||||
response.on("end", () =>
|
||||
resolve({ status: response.statusCode, body }),
|
||||
);
|
||||
})
|
||||
.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
test("Bun preview serves browser JavaScript and blocks private files/encoded traversal", async () => {
|
||||
const child = spawn(process.execPath, ["scripts/serve.ts"], {
|
||||
env: { ...process.env, PORT: "0" },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
try {
|
||||
const output = await Promise.race([
|
||||
once(child.stdout, "data").then(([value]) => String(value)),
|
||||
once(child, "exit").then(() => {
|
||||
throw new Error("Preview failed to start");
|
||||
}),
|
||||
]);
|
||||
const port = Number(output.match(/127\.0\.0\.1:(\d+)/)?.[1]);
|
||||
expect(port).toBeGreaterThan(0);
|
||||
for (const path of [
|
||||
"/",
|
||||
"/account",
|
||||
"/account/",
|
||||
"/src/app.js",
|
||||
"/src/styles.css",
|
||||
"/assets/vnox-mark.png",
|
||||
]) {
|
||||
expect((await fetchRaw(port, path)).status).toBe(200);
|
||||
}
|
||||
for (const path of [
|
||||
"/src/%2e%2e%2fpackage.json",
|
||||
"/src/%2e%2e%2f.env",
|
||||
"/src/%2e%2e%2fLICENSE",
|
||||
]) {
|
||||
expect((await fetchRaw(port, path)).status).toBe(403);
|
||||
}
|
||||
for (const path of [
|
||||
"/package.json",
|
||||
"/src/app.ts",
|
||||
"/src/api.ts",
|
||||
"/scripts/serve.ts",
|
||||
]) {
|
||||
expect((await fetchRaw(port, path)).status).toBe(404);
|
||||
}
|
||||
expect((await fetchRaw(port, "/v1/auth/session")).status).toBe(503);
|
||||
const javascript = await fetchRaw(port, "/src/app.js");
|
||||
expect(javascript.body).not.toContain("import type");
|
||||
expect(javascript.body).toContain("vnox-web-language");
|
||||
} finally {
|
||||
child.kill("SIGTERM");
|
||||
await once(child, "exit");
|
||||
}
|
||||
}, 15000);
|
||||
17
tsconfig.json
Normal file
17
tsconfig.json
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"types": ["bun"],
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noEmit": true,
|
||||
"isolatedModules": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "scripts/**/*.ts", "tests/**/*.ts"]
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue