convert wetty from submodule to normal directory

This commit is contained in:
douboer@gmail.com
2026-03-03 16:07:18 +08:00
parent 1db76701a6
commit 0d185d2b3c
131 changed files with 15543 additions and 1 deletions

1
wetty

Submodule wetty deleted from 0ec642a273

387
wetty/.all-contributorsrc Normal file
View File

@@ -0,0 +1,387 @@
{
"projectName": "WeTTy",
"projectOwner": "butlerx",
"repoType": "github",
"repoHost": "https://github.com",
"files": [
"README.md"
],
"imageSize": 100,
"commit": true,
"commitConvention": "eslint",
"contributors": [
{
"login": "butlerx",
"name": "Cian Butler",
"avatar_url": "https://avatars1.githubusercontent.com/u/867930?v=4",
"profile": "http://cianbutler.ie",
"contributions": [
"code",
"doc"
]
},
{
"login": "krishnasrinivas",
"name": "Krishna Srinivas",
"avatar_url": "https://avatars0.githubusercontent.com/u/634494?v=4",
"profile": "http://about.me/krishnasrinivas",
"contributions": [
"code"
]
},
{
"login": "acalatrava",
"name": "acalatrava",
"avatar_url": "https://avatars1.githubusercontent.com/u/8502129?v=4",
"profile": "https://github.com/acalatrava",
"contributions": [
"code"
]
},
{
"login": "Strubbl",
"name": "Strubbl",
"avatar_url": "https://avatars3.githubusercontent.com/u/97055?v=4",
"profile": "https://github.com/Strubbl",
"contributions": [
"code"
]
},
{
"login": "2sheds",
"name": "Oleg Kurapov",
"avatar_url": "https://avatars3.githubusercontent.com/u/16163?v=4",
"profile": "https://github.com/2sheds",
"contributions": [
"code"
]
},
{
"login": "rabchev",
"name": "Boyan Rabchev",
"avatar_url": "https://avatars0.githubusercontent.com/u/1876061?v=4",
"profile": "http://www.rabchev.com",
"contributions": [
"code"
]
},
{
"login": "nosemeocurrenada",
"name": "Jimmy",
"avatar_url": "https://avatars1.githubusercontent.com/u/3845708?v=4",
"profile": "https://github.com/nosemeocurrenada",
"contributions": [
"code"
]
},
{
"login": "lucamilanesio",
"name": "Luca Milanesio",
"avatar_url": "https://avatars3.githubusercontent.com/u/182893?v=4",
"profile": "http://www.gerritforge.com",
"contributions": [
"code"
]
},
{
"login": "antonyjim",
"name": "Anthony Jund",
"avatar_url": "https://avatars3.githubusercontent.com/u/39376331?v=4",
"profile": "http://anthonyjund.com",
"contributions": [
"code"
]
},
{
"login": "mirtouf",
"name": "mirtouf",
"avatar_url": "https://avatars3.githubusercontent.com/u/5165058?v=4",
"profile": "https://www.mirtouf.fr",
"contributions": [
"code"
]
},
{
"login": "CoRfr",
"name": "Bertrand Roussel",
"avatar_url": "https://avatars1.githubusercontent.com/u/556693?v=4",
"profile": "https://cor-net.org",
"contributions": [
"code"
]
},
{
"login": "benletchford",
"name": "Ben Letchford",
"avatar_url": "https://avatars0.githubusercontent.com/u/6703966?v=4",
"profile": "https://www.benl.com.au/",
"contributions": [
"code"
]
},
{
"login": "SouraDutta",
"name": "SouraDutta",
"avatar_url": "https://avatars0.githubusercontent.com/u/33066261?v=4",
"profile": "https://github.com/SouraDutta",
"contributions": [
"code"
]
},
{
"login": "koushikmln",
"name": "Koushik M.L.N",
"avatar_url": "https://avatars3.githubusercontent.com/u/8670988?v=4",
"profile": "https://github.com/koushikmln",
"contributions": [
"code"
]
},
{
"login": "imuli",
"name": "Imuli",
"avatar_url": "https://avatars3.githubusercontent.com/u/4085046?v=4",
"profile": "https://imu.li/",
"contributions": [
"code"
]
},
{
"login": "perpen",
"name": "perpen",
"avatar_url": "https://avatars2.githubusercontent.com/u/9963805?v=4",
"profile": "https://github.com/perpen",
"contributions": [
"code"
]
},
{
"login": "nathanleclaire",
"name": "Nathan LeClaire",
"avatar_url": "https://avatars3.githubusercontent.com/u/1476820?v=4",
"profile": "https://nathanleclaire.com",
"contributions": [
"code"
]
},
{
"login": "MiKr13",
"name": "Mihir Kumar",
"avatar_url": "https://avatars2.githubusercontent.com/u/34394719?v=4",
"profile": "https://github.com/MiKr13",
"contributions": [
"code"
]
},
{
"login": "cardil",
"name": "Chris Suszynski",
"avatar_url": "https://avatars0.githubusercontent.com/u/540893?v=4",
"profile": "http://redhat.com",
"contributions": [
"code"
]
},
{
"login": "fbartels",
"name": "Felix Bartels",
"avatar_url": "https://avatars1.githubusercontent.com/u/1257835?v=4",
"profile": "http://9wd.de",
"contributions": [
"code"
]
},
{
"login": "jarrettgilliam",
"name": "Jarrett Gilliam",
"avatar_url": "https://avatars3.githubusercontent.com/u/5099690?v=4",
"profile": "https://github.com/jarrettgilliam",
"contributions": [
"code"
]
},
{
"login": "harryleesan",
"name": "Harry Lee",
"avatar_url": "https://avatars0.githubusercontent.com/u/7056279?v=4",
"profile": "https://harrylee.me",
"contributions": [
"code"
]
},
{
"login": "inducer",
"name": "Andreas Klöckner",
"avatar_url": "https://avatars3.githubusercontent.com/u/352067?v=4",
"profile": "http://andreask.cs.illinois.edu",
"contributions": [
"code"
]
},
{
"login": "DenisKramer",
"name": "DenisKramer",
"avatar_url": "https://avatars1.githubusercontent.com/u/23534092?v=4",
"profile": "https://github.com/DenisKramer",
"contributions": [
"code"
]
},
{
"login": "vamship",
"name": "Vamshi K Ponnapalli",
"avatar_url": "https://avatars0.githubusercontent.com/u/7143376?v=4",
"profile": "https://github.com/vamship",
"contributions": [
"code"
]
},
{
"login": "tnguyen14",
"name": "Tri Nguyen",
"avatar_url": "https://avatars1.githubusercontent.com/u/1652595?v=4",
"profile": "https://tridnguyen.com",
"contributions": [
"doc"
]
},
{
"login": "pojntfx",
"name": "Felix Pojtinger",
"avatar_url": "https://avatars1.githubusercontent.com/u/28832235?v=4",
"profile": "https://felix.pojtinger.com/",
"contributions": [
"doc"
]
},
{
"login": "nealey",
"name": "Neale Pickett",
"avatar_url": "https://avatars3.githubusercontent.com/u/423780?v=4",
"profile": "https://nealey.github.io/",
"contributions": [
"code"
]
},
{
"login": "mtpiercey",
"name": "Matthew Piercey",
"avatar_url": "https://avatars3.githubusercontent.com/u/22581026?v=4",
"profile": "https://www.matthewpiercey.ml",
"contributions": [
"doc"
]
},
{
"login": "kholbekj",
"name": "Kasper Holbek Jensen",
"avatar_url": "https://avatars3.githubusercontent.com/u/2786571?v=4",
"profile": "https://github.com/kholbekj",
"contributions": [
"doc"
]
},
{
"login": "khanzf",
"name": "Farhan Khan",
"avatar_url": "https://avatars1.githubusercontent.com/u/10103765?v=4",
"profile": "https://mastodon.technology/@farhan",
"contributions": [
"code"
]
},
{
"login": "jurruh",
"name": "Jurre Vriesen",
"avatar_url": "https://avatars1.githubusercontent.com/u/7419259?v=4",
"profile": "https://www.jurrevriesen.nl",
"contributions": [
"code"
]
},
{
"login": "jamtur01",
"name": "James Turnbull",
"avatar_url": "https://avatars3.githubusercontent.com/u/4365?v=4",
"profile": "https://www.kartar.net/",
"contributions": [
"code"
]
},
{
"login": "deanshub",
"name": "Dean Shub",
"avatar_url": "https://avatars2.githubusercontent.com/u/2688676?v=4",
"profile": "https://github.com/deanshub",
"contributions": [
"code"
]
},
{
"login": "lozbrown",
"name": "lozbrown ",
"avatar_url": "https://avatars3.githubusercontent.com/u/9961593?v=4",
"profile": "https://github.com/lozbrown",
"contributions": [
"code",
"example"
]
},
{
"login": "sergeir82",
"name": "sergeir82",
"avatar_url": "https://avatars0.githubusercontent.com/u/5081149?v=4",
"profile": "https://github.com/sergeir82",
"contributions": [
"code"
]
},
{
"login": "kmlucy",
"name": "Kyle Lucy",
"avatar_url": "https://avatars1.githubusercontent.com/u/13952475?v=4",
"profile": "https://github.com/kmlucy",
"contributions": [
"code"
]
},
{
"login": "userdocs",
"name": "userdocs",
"avatar_url": "https://avatars1.githubusercontent.com/u/16525024?v=4",
"profile": "https://github.com/userdocs",
"contributions": [
"doc"
]
},
{
"login": "janoskk",
"name": "Janos Kasza",
"avatar_url": "https://avatars3.githubusercontent.com/u/1554533?v=4",
"profile": "https://logmein.com/",
"contributions": [
"code"
]
},
{
"login": "DefunctLizard",
"name": "Grant Handy",
"avatar_url": "https://avatars3.githubusercontent.com/u/45475651?v=4",
"profile": "https://grantshandy.xyz/",
"contributions": [
"doc"
]
},
{
"login": "LeszekBlazewski",
"name": "Leszek Błażewski",
"avatar_url": "https://avatars.githubusercontent.com/u/34927142?v=4",
"profile": "https://github.com/LeszekBlazewski",
"contributions": [
"code",
"platform"
]
}
],
"contributorsPerLine": 7
}

12
wetty/.dockerignore Normal file
View File

@@ -0,0 +1,12 @@
node_modules
.git
.gitignore
*.md
*.yml
*.png
**/*.conf
**/*.service
dist
build
docs
Dockerfile

95
wetty/.eslintrc.cjs Normal file
View File

@@ -0,0 +1,95 @@
module.exports = {
extends: ['airbnb-base', 'prettier', 'plugin:@typescript-eslint/recommended'],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint', 'prettier'],
ignorePatterns: ['dist'],
root: true,
env: {
node: true,
browser: true,
},
rules: {
'@typescript-eslint/no-unused-vars': [
'error',
{ varsIgnorePattern: '^_', argsIgnorePattern: '^_' },
],
'@typescript-eslint/no-use-before-define': ['error', { functions: false }],
'func-style': ['error', 'declaration', { allowArrowFunctions: true }],
'import/extensions': [
'error',
'ignorePackages',
{
ts: 'never',
js: 'ignorePackages',
mjs: 'ignorePackages',
jsx: 'never',
tsx: 'never',
},
],
'import/no-extraneous-dependencies': [
'error',
{ devDependencies: ['**/*.test.*', '**/*.spec.*', 'build.js'] },
],
'import/order': [
'error',
{
groups: [
'builtin',
'internal',
'external',
'parent',
'sibling',
'index',
'object',
'type',
],
pathGroups: [{ pattern: '@ev/**', group: 'internal' }],
distinctGroup: true,
alphabetize: { order: 'asc', caseInsensitive: false },
},
],
'import/prefer-default-export': 'off',
'import/prefer-default-export': 'off',
'linebreak-style': ['error', 'unix'],
'lines-between-class-members': [
'error',
'always',
{ exceptAfterSingleLine: true },
],
'no-param-reassign': ['error', { props: false }],
'no-use-before-define': ['error', { functions: false }],
},
settings: {
// Apply special parsing for TypeScript files
'import/parsers': { '@typescript-eslint/parser': ['.ts', '.tsx', '.d.ts'] },
'import/resolver': {
typescript: {
project: ['./tsconfig.browser.json', './tsconfig.node.json'],
},
node: { extensions: ['.mjs', '.js', '.json', '.ts', '.d.ts'] },
},
'import/extensions': ['.js', '.mjs', '.jsx', '.ts', '.tsx', '.d.ts'],
// Resolve type definition packages
'import/external-module-folders': ['node_modules', 'node_modules/@types'],
},
overrides: [
{ files: ['*.ts', '*.tsx'], rules: { 'import/no-unresolved': 'off' } },
{
files: ['*.js', '*.jsx'],
rules: {
'@typescript-eslint/no-var-requires': 'off',
'import/no-unresolved': 'off',
},
},
{
files: ['*.spec.*', '*.test.*'],
extends: ['plugin:mocha/recommended'],
plugins: ['mocha'],
rules: {
'import/no-extraneous-dependencies': ['off'],
'mocha/no-mocha-arrows': ['off'],
'no-unused-expressions': ['off'],
},
},
],
};

View File

@@ -0,0 +1,38 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.

View File

@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

21
wetty/.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,21 @@
---
version: 2
updates:
- package-ecosystem: npm
directory: '/'
schedule:
interval: weekly
commit-message:
prefix: '[NPM] '
- package-ecosystem: github-actions
directory: '/'
schedule:
interval: weekly
commit-message:
prefix: '[GH action] '
- package-ecosystem: docker
directory: '/containers'
schedule:
interval: weekly
commit-message:
prefix: '[docker] '

View File

@@ -0,0 +1,51 @@
---
name: Build & Test
on:
workflow_call:
inputs:
working-directory:
required: false
type: string
default: '.'
jobs:
build_and_test:
name: Build & Test
runs-on: ubuntu-latest
defaults:
run:
working-directory: ${{ inputs.working-directory }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 2
- uses: pnpm/action-setup@v2
with:
version: 8
- name: Setup env
uses: actions/setup-node@v3
with:
node-version: 22
cache: 'pnpm'
- name: Install dependencies
run: pnpm install
- name: ESLint checks
run: pnpm lint
- run: pnpm build
name: Compile Typescript
- run: pnpm test
name: Run tests
env:
CI: true
- uses: actions/cache@v3
id: restore-build
with:
path: ./*
key: ${{ github.sha }}

View File

@@ -0,0 +1,29 @@
---
name: Code Scanning - Action
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
- cron: '0 11 * * 1'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
security-events: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: javascript
- name: Autobuild
uses: github/codeql-action/autobuild@v2
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2

View File

@@ -0,0 +1,63 @@
---
name: Docker Workflow
on:
workflow_call:
inputs:
platforms:
required: true
type: string
push:
type: boolean
default: false
secrets:
DOCKERHUB_USERNAME:
DOCKERHUB_TOKEN:
jobs:
docker:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Docker meta
id: meta
uses: docker/metadata-action@v5
with:
images: |
wettyoss/wetty
ghcr.io/butlerx/wetty
flavor: |
latest=true
tags: |
type=schedule
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{major}}
type=sha
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Login to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
file: containers/wetty/Dockerfile
platforms: ${{ inputs.platforms }}
push: ${{ inputs.push }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=registry,ref=${{ steps.meta.outputs.tags }}
cache-to: type=inline

60
wetty/.github/workflows/publish.yml vendored Normal file
View File

@@ -0,0 +1,60 @@
---
name: Build and Publish
on:
push:
branches:
- main
jobs:
test:
name: Build & Test
uses: ./.github/workflows/build-and-test.workflow.yml
publish:
runs-on: ubuntu-latest
needs: test
permissions:
contents: write
packages: write
steps:
- name: Checkout
uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
with:
version: 8
- name: Setup env
uses: actions/setup-node@v3
with:
node-version: 22
cache: 'pnpm'
- uses: actions/cache@v3
id: restore-build
with:
path: ./*
key: ${{ github.sha }}
# Publish to NPM
- name: Publish if version has been updated
uses: pascalgn/npm-publish-action@1.3.9
with:
tag_name: 'v%s'
tag_message: 'v%s'
commit_pattern: "^Release (\\S+)"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_AUTH_TOKEN: ${{ secrets.npm_token }}
# Publish to Github PKG
- uses: actions/setup-node@v3
with:
node-version: 22
registry-url: 'https://npm.pkg.github.com'
- name: Publish to Github PKG if version has been updated
uses: pascalgn/npm-publish-action@1.3.9
with:
create_tag: false
commit_pattern: "^Release (\\S+)"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -0,0 +1,23 @@
---
name: Run tests
on:
pull_request:
jobs:
test:
name: Build & Test
uses: ./.github/workflows/build-and-test.workflow.yml
validate-docker:
name: Validate Docker Build
uses: ./.github/workflows/docker.workflow.yml
strategy:
matrix:
platform:
- linux/amd64
- linux/arm/v6
- linux/arm/v7
- linux/arm64
secrets: inherit
with:
platforms: ${{ matrix.platform }}
push: false

32
wetty/.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,32 @@
---
name: Create Release
on:
push:
tags:
- 'v*.*.*'
jobs:
release:
name: Create Release
runs-on: ubuntu-latest
steps:
- name: Create Release
uses: fregante/release-with-changelog@v3
with:
token: ${{ secrets.GITHUB_TOKEN }}
title: 'Release {tag}'
exclude: true
commit-template: '- {title} ← {hash}'
template: |
### Changelog
{commits}
{range}
docker:
name: Docker Publish Image
uses: ./.github/workflows/docker.workflow.yml
secrets: inherit
with:
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
push: true

22
wetty/.github/workflows/stale.yml vendored Normal file
View File

@@ -0,0 +1,22 @@
---
name: Mark stale issues and pull requests
on:
schedule:
- cron: '39 10 * * *'
jobs:
stale:
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/stale@v8
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: 'Stale issue message'
stale-pr-message: 'Stale pull request message'
stale-issue-label: 'no-issue-activity'
stale-pr-label: 'no-pr-activity'
days-before-close: 21
days-before-stale: 365

146
wetty/.gitignore vendored Normal file
View File

@@ -0,0 +1,146 @@
/build
# Created by https://www.toptal.com/developers/gitignore/api/node
# Edit at https://www.toptal.com/developers/gitignore?templates=node
### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
### Node Patch ###
# Serverless Webpack directories
.webpack/
# Optional stylelint cache
# SvelteKit build / generate output
.svelte-kit
# End of https://www.toptal.com/developers/gitignore/api/node

4
wetty/.husky/pre-commit Executable file
View File

@@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
pnpm exec lint-staged

9
wetty/.mocharc.json Normal file
View File

@@ -0,0 +1,9 @@
{
"extension": ["ts"],
"spec": ["src/**/*.spec.*"],
"node-option": [
"experimental-specifier-resolution=node",
"loader=ts-node/esm",
"no-warnings"
]
}

26
wetty/.npmignore Normal file
View File

@@ -0,0 +1,26 @@
lib-cov
*.seed
*.log
*.csv
*.dat
*.out
*.pid
*.gz
tmp
pids
logs
results
npm-debug.log
node_modules/*
.esm-cache
src
*.yml
Dockerfile
*.png
.dockerignore
.eslint*
.prettierrc.js
tsconfig
docs

16
wetty/.prettierrc.json Normal file
View File

@@ -0,0 +1,16 @@
{
"singleQuote": true,
"trailingComma": "all",
"proseWrap": "always",
"overrides": [
{
"files": [
"*.js",
"*.ts"
],
"options": {
"printWidth": 80
}
}
]
}

1
wetty/.yarnrc Normal file
View File

@@ -0,0 +1 @@
network-timeout 1000000

21
wetty/LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2014 Krishna Srinivas
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

212
wetty/README.md Normal file
View File

@@ -0,0 +1,212 @@
# WeTTY = Web + TTY.
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-41-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
[![Documentation](https://img.shields.io/badge/documentation-yes-brightgreen.svg)](https://github.com/butlerx/wetty/tree/main/docs)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/butlerx/wetty/blob/main/LICENSE)
> Terminal access in browser over http/https
![WeTTY](./docs/terminal.png?raw=true)
Terminal over HTTP and https. WeTTY is an alternative to ajaxterm and anyterm
but much better than them because WeTTY uses xterm.js which is a full fledged
implementation of terminal emulation written entirely in JavaScript. WeTTY uses
websockets rather than Ajax and hence better response time.
## Prerequisites
- node >=18
- make
- python
- build-essential
## Install
```sh
npm -g i wetty
```
## Usage
```sh
$ wetty --help
Options:
--help, -h Print help message [boolean]
--version Show version number [boolean]
--conf config file to load config from [string]
--ssl-key path to SSL key [string]
--ssl-cert path to SSL certificate [string]
--ssh-host ssh server host [string]
--ssh-port ssh server port [number]
--ssh-user ssh user [string]
--title window title [string]
--ssh-auth defaults to "password", you can use "publickey,password"
instead [string]
--ssh-pass ssh password [string]
--ssh-key path to an optional client private key (connection will be
password-less and insecure!) [string]
--ssh-config Specifies an alternative ssh configuration file. For further
details see "-F" option in ssh(1) [string]
--force-ssh Connecting through ssh even if running as root [boolean]
--known-hosts path to known hosts file [string]
--base, -b base path to wetty [string]
--port, -p wetty listen port [number]
--host wetty listen host [string]
--command, -c command to run in shell [string]
--allow-iframe Allow wetty to be embedded in an iframe, defaults to allowing
same origin [boolean]
```
Open your browser on `http://yourserver:3000/wetty` and you will prompted to
login. Or go to `http://yourserver:3000/wetty/ssh/<username>` to specify the
user beforehand.
If you run it as root it will launch `/bin/login` (where you can specify the
user name), else it will launch `ssh` and connect by default to `localhost`. The
SSH connection can be forced using the `--force-ssh` option.
If instead you wish to connect to a remote host you can specify the `--ssh-host`
option, the SSH port using the `--ssh-port` option and the SSH user using the
`--ssh-user` option.
Check out the [Flags docs](https://butlerx.github.io/wetty/flags) for a full
list of flags
### Docker container
To use WeTTY as a docker container, a docker image is available on
[docker hub](https://hub.docker.com/r/wettyoss/wetty). To run this image, use
```sh
docker run --rm -p 3000:3000 wettyoss/wetty --ssh-host=<YOUR-IP>
```
and you will be able to open a ssh session to the host given by `YOUR-IP` under
the URL [http://localhost:3000/wetty](http://localhost:3000/wetty).
It is recommended to drive WeTTY behind a reverse proxy to have HTTPS security
and possibly Lets Encrypt support. Popular containers to achieve this are
[nginx-proxy](https://github.com/nginx-proxy/nginx-proxy) and
[traefik](https://traefik.io/traefik/). For traefik there is an example
docker-compose file in the containers directory.
## FAQ
Check out the [docs](https://github.com/butlerx/wetty/tree/main/docs)
- [Running as daemon](https://butlerx.github.io/wetty/service)
- [HTTPS Support](https://butlerx.github.io/wetty/https)
- [Using NGINX](https://butlerx.github.io/wetty/nginx)
- [Using Apache](https://butlerx.github.io/wetty/apache)
- [Automatic Login](https://butlerx.github.io/wetty/auto-login)
- [Downloading Files](https://butlerx.github.io/wetty/downloading-files)
### What browsers are supported?
WeTTY supports all browsers that
[xterm.js supports](https://github.com/xtermjs/xterm.js#browser-support).
## Author
👤 **Cian Butler <butlerx@notthe.cloud>**
- Mastodon: [@butlerx@mastodon.ie](https://mastodon.ie/@butlerx)
- Github: [@butlerx](https://github.com/butlerx)
## Contributing ✨
Contributions, issues and feature requests are welcome!<br />Feel free to check
[issues page](https://github.com/butlerx/wetty/issues).
Please read the [development docs](https://butlerx.github.io/wetty/development)
for installing from source and running is dev node
Thanks goes to these wonderful people
([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tbody>
<tr>
<td align="center" valign="top" width="14.28%"><a href="http://cianbutler.ie"><img src="https://avatars1.githubusercontent.com/u/867930?v=4?s=100" width="100px;" alt="Cian Butler"/><br /><sub><b>Cian Butler</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=butlerx" title="Code">💻</a> <a href="https://github.com/butlerx/WeTTy/commits?author=butlerx" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="http://about.me/krishnasrinivas"><img src="https://avatars0.githubusercontent.com/u/634494?v=4?s=100" width="100px;" alt="Krishna Srinivas"/><br /><sub><b>Krishna Srinivas</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=krishnasrinivas" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/acalatrava"><img src="https://avatars1.githubusercontent.com/u/8502129?v=4?s=100" width="100px;" alt="acalatrava"/><br /><sub><b>acalatrava</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=acalatrava" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/Strubbl"><img src="https://avatars3.githubusercontent.com/u/97055?v=4?s=100" width="100px;" alt="Strubbl"/><br /><sub><b>Strubbl</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=Strubbl" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/2sheds"><img src="https://avatars3.githubusercontent.com/u/16163?v=4?s=100" width="100px;" alt="Oleg Kurapov"/><br /><sub><b>Oleg Kurapov</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=2sheds" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="http://www.rabchev.com"><img src="https://avatars0.githubusercontent.com/u/1876061?v=4?s=100" width="100px;" alt="Boyan Rabchev"/><br /><sub><b>Boyan Rabchev</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=rabchev" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/nosemeocurrenada"><img src="https://avatars1.githubusercontent.com/u/3845708?v=4?s=100" width="100px;" alt="Jimmy"/><br /><sub><b>Jimmy</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=nosemeocurrenada" title="Code">💻</a></td>
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="http://www.gerritforge.com"><img src="https://avatars3.githubusercontent.com/u/182893?v=4?s=100" width="100px;" alt="Luca Milanesio"/><br /><sub><b>Luca Milanesio</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=lucamilanesio" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="http://anthonyjund.com"><img src="https://avatars3.githubusercontent.com/u/39376331?v=4?s=100" width="100px;" alt="Anthony Jund"/><br /><sub><b>Anthony Jund</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=antonyjim" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://www.mirtouf.fr"><img src="https://avatars3.githubusercontent.com/u/5165058?v=4?s=100" width="100px;" alt="mirtouf"/><br /><sub><b>mirtouf</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=mirtouf" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://cor-net.org"><img src="https://avatars1.githubusercontent.com/u/556693?v=4?s=100" width="100px;" alt="Bertrand Roussel"/><br /><sub><b>Bertrand Roussel</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=CoRfr" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://www.benl.com.au/"><img src="https://avatars0.githubusercontent.com/u/6703966?v=4?s=100" width="100px;" alt="Ben Letchford"/><br /><sub><b>Ben Letchford</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=benletchford" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/SouraDutta"><img src="https://avatars0.githubusercontent.com/u/33066261?v=4?s=100" width="100px;" alt="SouraDutta"/><br /><sub><b>SouraDutta</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=SouraDutta" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/koushikmln"><img src="https://avatars3.githubusercontent.com/u/8670988?v=4?s=100" width="100px;" alt="Koushik M.L.N"/><br /><sub><b>Koushik M.L.N</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=koushikmln" title="Code">💻</a></td>
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://imu.li/"><img src="https://avatars3.githubusercontent.com/u/4085046?v=4?s=100" width="100px;" alt="Imuli"/><br /><sub><b>Imuli</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=imuli" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/perpen"><img src="https://avatars2.githubusercontent.com/u/9963805?v=4?s=100" width="100px;" alt="perpen"/><br /><sub><b>perpen</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=perpen" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://nathanleclaire.com"><img src="https://avatars3.githubusercontent.com/u/1476820?v=4?s=100" width="100px;" alt="Nathan LeClaire"/><br /><sub><b>Nathan LeClaire</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=nathanleclaire" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/MiKr13"><img src="https://avatars2.githubusercontent.com/u/34394719?v=4?s=100" width="100px;" alt="Mihir Kumar"/><br /><sub><b>Mihir Kumar</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=MiKr13" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="http://redhat.com"><img src="https://avatars0.githubusercontent.com/u/540893?v=4?s=100" width="100px;" alt="Chris Suszynski"/><br /><sub><b>Chris Suszynski</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=cardil" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="http://9wd.de"><img src="https://avatars1.githubusercontent.com/u/1257835?v=4?s=100" width="100px;" alt="Felix Bartels"/><br /><sub><b>Felix Bartels</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=fbartels" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/jarrettgilliam"><img src="https://avatars3.githubusercontent.com/u/5099690?v=4?s=100" width="100px;" alt="Jarrett Gilliam"/><br /><sub><b>Jarrett Gilliam</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=jarrettgilliam" title="Code">💻</a></td>
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://harrylee.me"><img src="https://avatars0.githubusercontent.com/u/7056279?v=4?s=100" width="100px;" alt="Harry Lee"/><br /><sub><b>Harry Lee</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=harryleesan" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="http://andreask.cs.illinois.edu"><img src="https://avatars3.githubusercontent.com/u/352067?v=4?s=100" width="100px;" alt="Andreas Klöckner"/><br /><sub><b>Andreas Klöckner</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=inducer" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/DenisKramer"><img src="https://avatars1.githubusercontent.com/u/23534092?v=4?s=100" width="100px;" alt="DenisKramer"/><br /><sub><b>DenisKramer</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=DenisKramer" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/vamship"><img src="https://avatars0.githubusercontent.com/u/7143376?v=4?s=100" width="100px;" alt="Vamshi K Ponnapalli"/><br /><sub><b>Vamshi K Ponnapalli</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=vamship" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://tridnguyen.com"><img src="https://avatars1.githubusercontent.com/u/1652595?v=4?s=100" width="100px;" alt="Tri Nguyen"/><br /><sub><b>Tri Nguyen</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=tnguyen14" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://felix.pojtinger.com/"><img src="https://avatars1.githubusercontent.com/u/28832235?v=4?s=100" width="100px;" alt="Felix Pojtinger"/><br /><sub><b>Felix Pojtinger</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=pojntfx" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://nealey.github.io/"><img src="https://avatars3.githubusercontent.com/u/423780?v=4?s=100" width="100px;" alt="Neale Pickett"/><br /><sub><b>Neale Pickett</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=nealey" title="Code">💻</a></td>
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://www.matthewpiercey.ml"><img src="https://avatars3.githubusercontent.com/u/22581026?v=4?s=100" width="100px;" alt="Matthew Piercey"/><br /><sub><b>Matthew Piercey</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=mtpiercey" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/kholbekj"><img src="https://avatars3.githubusercontent.com/u/2786571?v=4?s=100" width="100px;" alt="Kasper Holbek Jensen"/><br /><sub><b>Kasper Holbek Jensen</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=kholbekj" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://mastodon.technology/@farhan"><img src="https://avatars1.githubusercontent.com/u/10103765?v=4?s=100" width="100px;" alt="Farhan Khan"/><br /><sub><b>Farhan Khan</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=khanzf" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://www.jurrevriesen.nl"><img src="https://avatars1.githubusercontent.com/u/7419259?v=4?s=100" width="100px;" alt="Jurre Vriesen"/><br /><sub><b>Jurre Vriesen</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=jurruh" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://www.kartar.net/"><img src="https://avatars3.githubusercontent.com/u/4365?v=4?s=100" width="100px;" alt="James Turnbull"/><br /><sub><b>James Turnbull</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=jamtur01" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/deanshub"><img src="https://avatars2.githubusercontent.com/u/2688676?v=4?s=100" width="100px;" alt="Dean Shub"/><br /><sub><b>Dean Shub</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=deanshub" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/lozbrown"><img src="https://avatars3.githubusercontent.com/u/9961593?v=4?s=100" width="100px;" alt="lozbrown "/><br /><sub><b>lozbrown </b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=lozbrown" title="Code">💻</a> <a href="#example-lozbrown" title="Examples">💡</a></td>
</tr>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/sergeir82"><img src="https://avatars0.githubusercontent.com/u/5081149?v=4?s=100" width="100px;" alt="sergeir82"/><br /><sub><b>sergeir82</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=sergeir82" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/kmlucy"><img src="https://avatars1.githubusercontent.com/u/13952475?v=4?s=100" width="100px;" alt="Kyle Lucy"/><br /><sub><b>Kyle Lucy</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=kmlucy" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/userdocs"><img src="https://avatars1.githubusercontent.com/u/16525024?v=4?s=100" width="100px;" alt="userdocs"/><br /><sub><b>userdocs</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=userdocs" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://logmein.com/"><img src="https://avatars3.githubusercontent.com/u/1554533?v=4?s=100" width="100px;" alt="Janos Kasza"/><br /><sub><b>Janos Kasza</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=janoskk" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://grantshandy.xyz/"><img src="https://avatars3.githubusercontent.com/u/45475651?v=4?s=100" width="100px;" alt="Grant Handy"/><br /><sub><b>Grant Handy</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=DefunctLizard" title="Documentation">📖</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/LeszekBlazewski"><img src="https://avatars.githubusercontent.com/u/34927142?v=4?s=100" width="100px;" alt="Leszek Błażewski"/><br /><sub><b>Leszek Błażewski</b></sub></a><br /><a href="https://github.com/butlerx/WeTTy/commits?author=LeszekBlazewski" title="Code">💻</a> <a href="#platform-LeszekBlazewski" title="Packaging/porting to new platform">📦</a></td>
</tr>
</tbody>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the
[all-contributors](https://github.com/all-contributors/all-contributors)
specification. Contributions of any kind welcome!
## Show your support
Give a ⭐️ if this project helped you!
## 📝 License
Copyright © 2019
[Cian Butler <butlerx@notthe.cloud>](https://github.com/butlerx).<br /> This
project is [MIT](https://github.com/butlerx/wetty/blob/main/LICENSE) licensed.
---

87
wetty/build.js Normal file
View File

@@ -0,0 +1,87 @@
import {spawn} from 'node:child_process';
import * as esbuild from 'esbuild';
import {copy} from 'esbuild-plugin-copy';
import {sassPlugin} from 'esbuild-sass-plugin';
/** @param {string} prog
* @param {string[]} [args=[]]
* @returns {[ChildProcess, Promise<{ret: number, sig: NodeJS.Signals}>]}
*/
function cmd(prog, args=[]) {
const proc = spawn(prog, args, { cwd: import.meta.dirname, stdio: "inherit", env: process.env});
const done = new Promise((resolve, _reject) => {
proc.addListener('exit',(ret, sig)=>{
resolve({ret,sig});
})
});
return [proc, done];
}
/** @type import('esbuild').Plugin */
const typechecker = {
name: 'typechecker',
setup(build) {
build.onStart(async () => {
const [_tsc, tscDone] = cmd('pnpm', ['tsc', '-p', 'tsconfig.browser.json']);
const {ret} = await tscDone;
if (ret !== 0) {
return {warnings: [{text:`Type checking failed: tsc exited with code ${ret}`}]}
}
return {};
});
}
};
/** @param {boolean} watching
*/
async function buildClient(watching){
/** @type {esbuild.BuildOptions} */
const esConf = {
entryPoints: ['src/client/wetty.ts', 'src/client/dev.ts'],
outdir: 'build/client',
bundle: true,
platform: 'browser',
format: 'esm',
minify: !watching,
sourcemap: !watching,
plugins: [
typechecker,
sassPlugin({
embedded: true,
loadPaths: ['node_modules'],
style: watching ? 'expanded' : 'compressed',
}),
copy({
assets: [
{from: './src/assets/xterm_config/*', to: 'xterm_config'},
{from: './src/assets/favicon.ico', to: 'favicon.ico'},
],
watch: watching,
}),
],
logLevel: 'info',
};
if (watching) {
const buildCtx = await esbuild.context(esConf)
await buildCtx.watch();
} else {
esbuild.build(esConf);
}
}
/** @param {boolean} watching
*/
async function buildServer(watching) {
const tscArgs = ['tsc', '-p', 'tsconfig.node.json'];
if (watching) tscArgs.push('--watch','--preserveWatchOutput');
const [_tsc, tscDone] = cmd('pnpm', tscArgs);
if (!watching) await tscDone;
}
const watching = process.argv.includes('--watch');
await buildClient(watching);
await buildServer(watching);

28
wetty/conf/config.json5 Normal file
View File

@@ -0,0 +1,28 @@
{
ssh: {
// user: 'username', // default user to use when ssh-ing
host: 'localhost', // Server to ssh to
auth: 'password', // shh authentication, method. Defaults to "password", you can use "publickey,password" instead'
// pass: "password", // Password to use when sshing
// key: "", // path to an optional client private key, connection will be password-less and insecure!
port: 22, // Port to ssh to
knownHosts: '/dev/null', // ssh knownHosts file to use
// config: '/home/user/.wetty_ssh_config', // alternative ssh configuration file, see "-F" option in ssh(1)
},
server: {
base: '/wetty/', // URL base to serve resources from
port: 3000, // Port to listen on
host: '0.0.0.0', // address to listen on
title: 'WeTTY - The Web Terminal Emulator', // Page title
bypassHelmet: false, // Disable Helmet security checks
},
forceSSH: false, // Force sshing to local machine over login if running as root
command: 'login', // Command to run on server. Login will use ssh if connecting to different server
/*
ssl:{
key: 'ssl.key',
cert: 'ssl.cert',
}
*/
}

88
wetty/conf/nginx.template Normal file
View File

@@ -0,0 +1,88 @@
server {
listen ${NGINX_PORT};
listen [::]:${NGINX_PORT};
server_name ${NGINX_DOMAIN};
root /var/www/${NGINX_DOMAIN}/public;
# $uri, index.html
location / {
try_files $uri $uri/ /index.html;
}
# headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-UA-Compatible "IE=Edge" always;
add_header Cache-Control "no-transform" always;
# . files
location ~ /\. {
deny all;
}
# assets, media
location ~* \.(?:css(\.map)?|js(\.map)?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
expires 7d;
access_log off;
}
# svg, fonts
location ~* \.(?:svgz?|ttf|ttc|otf|eot|woff|woff2)$ {
add_header Access-Control-Allow-Origin "*";
expires 7d;
access_log off;
}
location ^~ /wetty {
proxy_pass http://${WETTY_HOST}:${WETTY_PORT};
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 43200000;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
# Authenticate user via other services (e.g., oauth2 end-points)
#
# Configuration :
# - Configure a 'auth_request' directive for this server block
# - Capture the authenticated username using 'auth_request_set'
# - Set the 'remote-user' request header accordingly
#
# Example (using lasso as authentication middleware):
#
# Add to server block:
# auth_request /lasso-validate
# auth_request_set $auth_user $upstream_http_x_lasso_user;
#
# Add to /wetty location block
# proxy_set_header remote-user $auth_user;
#
# And configure a '/lasso-validate' location. See this blog for further
# guidance: https://developer.okta.com/blog/2018/08/28/nginx-auth-request
}
# gzip
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json application/javascript application/xml+rss application/atom+xml image/svg+xml;
}
# subdomains redirect
server {
listen ${NGINX_PORT};
listen [::]:${NGINX_PORT};
server_name *.${NGINX_DOMAIN};
return 301 https://${NGINX_DOMAIN}$request_uri;
}
# set ft=conf

13
wetty/conf/wetty.conf Normal file
View File

@@ -0,0 +1,13 @@
# Upstart script
# /etc/init/wetty.conf
description "Web TTY"
author "Wetty"
start on started mountall
stop on shutdown
respawn
respawn limit 20 5
exec sudo -u root wetty -p 3000

21
wetty/conf/wetty.service Normal file
View File

@@ -0,0 +1,21 @@
# systemd unit file
#
# place in /etc/systemd/system
# systemctl enable wetty.service
# systemctl start wetty.service
[Unit]
Description=Wetty Web Terminal
After=network.target
[Service]
Type=simple
WorkingDirectory=$HOME/.config/yarn/global/node_modules/wetty/
ExecStart=/usr/bin/node . -p 3000 --host 127.0.0.1
TimeoutStopSec=20
KillMode=mixed
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target

View File

@@ -0,0 +1,35 @@
version: '2'
# Sample docker compose file to demonstrate the usage of wetty behind a reverse
# proxy, optionally with Let's Encrypt based SSL certificate
#
# For SSL support, uncomment the commented lines. Consult traefik documentation
# for features like automatic forward from HTTP to HTTPS etc.
services:
wetty:
image: wettyoss/wetty
command:
- --base=/
- --ssh-host=ssh.example.com
labels:
- "traefik.enable=true"
- "traefik.http.routers.wetty.rule=Host(`wetty.example.com`)"
# - "traefik.http.routers.wetty.tls.certResolver=default"
# - "traefik.http.routers.wetty.tls=true"
reverse-proxy:
image: traefik
command:
- --providers.docker
- --entryPoints.web.address=:80
# - --entryPoints.websecure.address=:443
# - --certificatesResolvers.default.acme.email=your-email@example.com
# - --certificatesResolvers.default.acme.storage=acme.json
# - --certificatesResolvers.default.acme.httpChallenge.entryPoint=web
ports:
- "80:80"
# - "443:443"
volumes:
- /var/run/docker.sock:/var/run/docker.sock

View File

@@ -0,0 +1,3 @@
FROM sickp/alpine-sshd:latest
RUN adduser -D -h /home/term -s /bin/sh term && \
( echo "term:term" | chpasswd )

View File

@@ -0,0 +1,37 @@
# ---------- Base image ----------
FROM node:20-alpine as base
RUN apk add -U build-base python3 py3-setuptools make g++ git
WORKDIR /usr/src/app
# Install pnpm globally
RUN npm install -g pnpm@latest
COPY . /usr/src/app
# ---------- Production dependencies ----------
FROM base AS prod-deps
RUN --mount=type=cache,id=pnpm,target=/root/.pnpm-store pnpm install --prod --frozen-lockfile --ignore-scripts
# Rebuild only the native modules we need
RUN cd node_modules/node-pty && npm run install && cd ../..
RUN cd node_modules/.pnpm/gc-stats@1.4.1/node_modules/gc-stats && npm run install
# ---------- Build stage ----------
FROM base AS build
RUN --mount=type=cache,id=pnpm,target=/root/.pnpm-store pnpm install --frozen-lockfile
RUN pnpm run build
# ---------- Final runtime image ----------
FROM base
LABEL maintainer="butlerx@notthe.cloud"
WORKDIR /usr/src/app
ENV NODE_ENV=production
COPY --from=prod-deps /usr/src/app/node_modules /usr/src/app/node_modules
COPY --from=build /usr/src/app/build /usr/src/app/build
COPY package.json /usr/src/app
RUN apk add -U coreutils openssh-client sshpass && \
mkdir -p ~/.ssh
EXPOSE 3000
CMD ["pnpm", "start"]

44
wetty/docker-compose.yml Normal file
View File

@@ -0,0 +1,44 @@
---
version: '3.5'
services:
wetty:
image: wettyoss/wetty
build:
context: .
dockerfile: containers/wetty/Dockerfile
entrypoint: pnpm run docker-compose-entrypoint
tty: true
working_dir: /usr/src/app
ports:
- '3000:3000'
environment:
SSHHOST: 'wetty-ssh'
SSHPORT: 22
NODE_ENV: 'development'
web:
image: nginx
volumes:
- ./conf/nginx.template:/etc/nginx/conf.d/wetty.template
ports:
- '80:80'
environment:
- NGINX_DOMAIN=wetty.com
- NGINX_PORT=80
- WETTY_HOST=wetty
- WETTY_PORT=3000
command: >-
/bin/bash -c "envsubst
'$${NGINX_DOMAIN},$${NGINX_PORT},$${WETTY_HOST},$${WETTY_PORT}' <
/etc/nginx/conf.d/wetty.template > /etc/nginx/conf.d/default.conf && nginx
-g 'daemon off;'"
wetty-ssh:
build:
context: .
dockerfile: containers/ssh/Dockerfile
image: wettyoss/wetty:ssh
networks:
default:
name: wetty

90
wetty/docs/API.md Normal file
View File

@@ -0,0 +1,90 @@
## WeTTY
Create WeTTY server
- [WeTTy](#module_WeTTy)
- [start](#module_WeTTy..start) ⇒ `Promise`
- [connection](#event_connection)
- [spawn](#event_spawn)
- [exit](#event_exit)
- [disconnect](#event_disconnect)
- [server](#event_server)
### WeTTy.start ⇒ `Promise`
Starts WeTTY Server
**Kind**: inner property of [`WeTTy`](#module_WeTTy)
**Returns**: `Promise` - Promise resolves once server is running
| Param | Type | Default | Description |
| :------------------------ | --------- | ------------- | ---------------------------------------------------------------------------------------------------------------------- |
| [ssh] | `Object` | | SSH settings |
| [ssh.user] | `string` | `"''"` | default user for ssh |
| [ssh.host] | `string` | `"localhost"` | machine to ssh too |
| [ssh.auth] | `string` | `"password"` | authtype to use |
| [ssh.port] | `number` | `22` | port to connect to over ssh |
| [ssh.pass] | `string` | | Optional param of a password to use for ssh |
| [ssh.key] | `string` | | path to an optional client private key (connection will be password-less and insecure!) |
| [ssh.config] | `string` | | Specifies an alternative ssh configuration file. For further details see "-F" option in ssh(1) |
| [serverConf] | `Object` | | Server settings |
| [serverConf.base] | `Object` | `'/wetty/'` | Server settings |
| [serverConf.port] | `number` | `3000` | Port to run server on |
| [serverConf.host] | `string` | `'0.0.0.0'` | Host address for server |
| [serverConf.title] | `string` | `'WeTTY'` | Title of the server |
| [serverConf.bypasshelmet] | `boolean` | `false` | if helmet should be disabled on the sever |
| [command] | `string` | `"''"` | The command to execute. If running as root and no host specified this will be login if a host is specified will be ssh |
| [forcessh] | `boolean` | `false` | Connecting through ssh even if running as root |
| [ssl] | `Object` | | SSL settings |
| [ssl.key] | `string` | | Path to ssl key |
| [ssl.cert] | `string` | | Path to ssl cert |
### "connection"
**Kind**: event emitted by [`WeTTy`](#module_WeTTy)
**Properties**
| Name | Type | Description |
| ---- | -------- | --------------------------- |
| msg | `string` | Message for logs |
| date | `Date` | date and time of connection |
### "spawn"
Terminal process spawned
**Kind**: event emitted by [`WeTTy`](#module_WeTTy)
**Properties**
| Name | Type | Description |
| ------- | -------- | -------------------------------------- |
| msg | `string` | Message containing pid info and status |
| pid | `number` | Pid of the terminal |
| address | `string` | address of connecting user |
### "exit"
Terminal process exits
**Kind**: event emitted by [`WeTTy`](#module_WeTTy)
**Properties**
| Name | Type | Description |
| ---- | -------- | -------------------------------------- |
| code | `number` | the exit code |
| msg | `string` | Message containing pid info and status |
### "disconnect"
**Kind**: event emitted by [`WeTTy`](#module_WeTTy)
### "server"
**Kind**: event emitted by [`WeTTy`](#module_WeTTy)
**Properties**
| Name | Type | Description |
| ---------- | -------- | ------------------------------- |
| msg | `string` | Message for logging |
| port | `number` | port sever is on |
| connection | `string` | connection type for web traffic |

39
wetty/docs/README.md Normal file
View File

@@ -0,0 +1,39 @@
# Docs
![WeTTY](./terminal.png?raw=true)
- [AtoZ](./atoz.md)
- [Running as daemon](./service.md)
- [HTTPS Support](./https.md)
- [Using NGINX](./nginx.md)
- [Using Apache](./apache.md)
- [Automatic Login](./auto-login.md)
- [Downloading Files](./downloading-files.md)
- [Development Docs](./development.md)
## API
For WeTTY options and event details please refer to the [api docs](./API.md)
### Getting started
WeTTY is event driven. To Spawn a new server call `wetty.start()` with no
arguments.
```javascript
import { start } from 'wetty';
start(/* server settings, see Options */)
.then((wetty) => {
console.log('server running');
wetty
.on('exit', ({ code, msg }) => {
console.log(`Exit with code: ${code} ${msg}`);
})
.on('spawn', (msg) => console.log(msg));
/* code you want to execute */
})
.catch((err) => {
console.error(err);
});
```

151
wetty/docs/apache.md Normal file
View File

@@ -0,0 +1,151 @@
## Run WeTTY behind nginx or apache
As said earlier you can use a proxy to add https to WeTTY.
**Note** that if your proxy is configured for https you should run WeTTY without
SSL
If your proxy uses a base path other than `/wetty`, specify the path with the
`--base` flag, or the `BASE` environment variable.
The following confs assume you want to serve WeTTY on the url
`example.com/wetty` and are running WeTTY with the default base and serving it
on the same server
Put the following configuration in apache's conf:
```apache
RewriteCond %{REQUEST_URI} ^/wetty/socket.io [NC]
RewriteCond %{QUERY_STRING} transport=websocket [NC]
RewriteRule /wetty/socket.io/(.*) ws://localhost:3000/wetty/socket.io/$1 [P,L]
<LocationMatch ^/wetty(.*)>
DirectorySlash On
Require all granted
ProxyPassMatch http://127.0.0.1:3000
ProxyPassReverse /wetty/
</LocationMatch>
```
## SAML2 integration to auth users
This conf is using apache2 (as for nginx, SAML2 integration is not available on
the community version, only pro).
Main idea is to propagate the SAML2 validated user identity into the
`remote-user` HTTP header. You need to have the user id returned within the
SAML2 NameID matching the username defined on the platform WeTTY is running.
E.g: You can ask the Idp to return a sAMAccountName within the SAML2Response
NameID, and provision beforehand those allowed users on the OS WeTTY is running
on.
### SAML2 Metadata generation
SAML2 metadata needs to be generated for this new service on the server and
exchanged with the Idp. We will use the script provided at
https://raw.githubusercontent.com/bitsensor/saml-proxy/master/mellon_create_metadata.sh
```
$ mellon_create_metadata.sh urn:https://foo.bar.tlz https://foo.bar.tld/mellon
```
Then we move the generated files over `/etc/apache2/saml2/foo.{xml,key,cert}`.
You need to put here additionally the metadata from your SAML2 provider, named
here `idp.xml` and exchange you foo.xml with it.
### Apache2 conf
```apache
<VirtualHost *:443>
ServerName foo.bar.tld
ServerAdmin admin@bar.tld
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/foo.pem
SSLCertificateKeyFile /etc/apache2/ssl/foo.key
RedirectMatch ^/$ /wetty/
ProxyPass "/wetty" "http://127.0.0.1:3000/wetty"
<Location / >
AuthType Mellon
MellonEnable info
# this propagates to apache2 (and thus to access log) the proper user id, and not
# the transient nameid that is taken by default
# it has no impact on the backend as we propagate identify via remote-user header there
MellonUser "NameID"
MellonEndpointPath /mellon/
MellonSPMetadataFile /etc/apache2/saml2/foo.xml
MellonSPPrivateKeyFile /etc/apache2/saml2/foo.key
MellonSPCertFile /etc/apache2/saml2/foo.cert
MellonIdPMetadataFile /etc/apache2/saml2/idp.xml
# the identity propagated to WeTTY (as HTTP header 'remote-user: xxxxx')
# is retrieved from SAMLResponse NameID attribute
RequestHeader set remote-user %{MELLON_NAMEID}e
</Location>
<Location /wetty>
AuthType Mellon
MellonEnable auth
Require valid-user
</Location>
# security hazard for switching between users, disabled if remote-user set as recent github commit
# but not yet published via npm, so we put here a double security belt
<Location /wetty/ssh/>
Deny from all
</Location>
</VirtualHost>
```
### Auto login
If you want to have a seamless login by trusting your IdP for authentication,
you can create password-less users on the WeTTY platform and have them trust an
SSH key used by the NodeJS, owned by the dedicated WeTTY OS user.
WeTTY instantiation with proper parameters, especially the SSH private key is
done via the following systemd service `/etc/systemd/system/wetty.service`:
```
[Unit]
Description=WeTTY Web Terminal
After=network.target
[Service]
User=wetty
Type=simple
WorkingDirectory=/home/wetty/.node_modules/wetty/
ExecStart=/usr/bin/node . -p 3000 --host 127.0.0.1 --ssh-key /home/wetty/.ssh/wetty --ssh-auth publickey --force-ssh --title "Foo bar terminal services"
TimeoutStopSec=20
KillMode=mixed
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
```
For your new users to be automatically trusting this SSH key when provisioning,
you may add the pubkey to `/etc/skel/.ssh/authorized_keys`.
### Security precautions
You probably don't want local users to impersonate each other, for that you need
to make sure that:
1. NodeJS is listening only to localhost: provided by `wetty.service`
2. **Only** the apache2 process can join the WeTTY port. Else local users will
be able to connect and forge a `remote-user` header: provided by
`iptables -A OUTPUT -o lo -p tcp --dport 3000 -m owner \! --uid-owner www-data -j DROP`
3. Validate your WeTTY version does not allow access to `/wetty/ssh/` else again
you will be able to impersonate anyone: provided by either:
1. WeTTY version 2.0.3 and beyond implements this by disabling this feature
in case of `remote-user` presence
2. apache2 conf as provided in previous section (containing the
`<Location /wetty/ssh/>`)

View File

@@ -0,0 +1,3 @@
:root {
--content-max-width: 100%;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 251 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 451 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,19 @@
{
"name": "",
"short_name": "",
"icons": [
{
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone"
}

678
wetty/docs/atoz.md Normal file
View File

@@ -0,0 +1,678 @@
# Introduction
This is an A to Z guide that will help you get WeTTY up and running on a Debian
based system. It covers the key configuration areas by using copy and paste
commands. This will help you install this application and get it securely up and
running with minimal system interference and reversible changes. It should also
provide enough information to allow you to understand and extend that
configuration for your personal requirements.
**Note:** Some of these configurations are optional, such as self signed SSL and
public key authentication. The purpose of the guide is to show you how to
correctly understand, configure, install and use these options should you wish
to use them but they are not required to use WeTTY in general.
## Required dependencies
`Node` - WeTTY requires node v20 or greater. We will install this locally for a
non root user later in the guide.
`python` - This should be installed by default but we will include it in our
`apt-get` command to be safe.
`build-essential` - We need this specifically for `node-gyp` to build packages
when using `npm` to install packages.
As the `root` or `sudo` user run these commands:
```bash
sudo apt update
sudo apt install -y build-essential curl python
```
If you have no root access and just want to check the dependencies are installed
you can use these commands:
```bash
dpkg -s python | grep Status:
dpkg -s build-essential | grep Status:
```
If the package is installed you will see this result:
```bash
Status: install ok installed
```
## Create a local user account
For this guide, unless specifically stated, you should not use a `root` account
to install and run WeTTY. Please use an existing local account or create one
now.
**Note:** Whichever user runs WeTTY should be the same user you wish to
authenticate with via `ssh` to keep this guide simple.
If you need to create a local user account you can run this command:
**Important note:** replace `username` with a user name of your choosing and
create a password when prompted
```bash
adduser --gecos "" username
```
Switch to your local user now and open an `ssh` session to continue with this
guide.
## Install node locally
To install and manage `node` as a local user we are going to use
[Node Version Manager](https://github.com/nvm-sh/nvm). This is an established
solution for installing and managing multiple versions of node without needing
`root` access. This will allow you to install and use multiple versions of
`node` at the same time.
This command will download and install `nvm` and reload our shell.
```bash
curl -sL https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash && source ~/.profile
```
This command will install the latest version of the v20 branch, which is the
minimum required version for WeTTY.
```bash
nvm install 20
```
You can now call `node` to check it works using this command.
```bash
node -v
```
Your result should look something like this.
```bash
v20.2.0
```
**Note:** There is an important consideration with the `nvm` method. `node` is
only in the local user's path through sourcing of the `~/.nvm/nvm.sh` which is
done when the user logs in and the shell sources the user's `.bashrc` file. So
for some applications who are not aware of this local shell environment `node`
will not be usable unless we provide a full path and `nvm` commands will also be
unavailable. The way we over come this issue for the needs of this guide is by
using this command substitution to provide the full path, where applicable:
```bash
$(source ~/.nvm/nvm.sh && nvm which 20)
```
**Why?** This command will always provide us with the path to the most current
version of `node 20` installed via `nvm` regardless of other versions of `node`
installed with `nvm`.
## Generate OpenSSL certificates
**Why?** So that later we can configure WeTTY to work with `https` and make sure
we interact with WeTTY over a secure connection at all times.
Make the required directory using this command:
```bash
mkdir -p ~/.ssl
```
Generate the self signed `openssl` certificates we will use to encrypt our web
traffic when using WeTTY using this command:
**Note:** we are using `ecdsa` using the `secp384r1` curve. Tested to be
compatible with Chrome and Firefox browsers.
```bash
openssl req -x509 -nodes -days 1095 -newkey ec:<(openssl ecparam -name secp384r1) -subj "/C=GB/ST=None/L=None/O=None/OU=None/CN=None" -out ~/.ssl/wetty.crt -keyout ~/.ssl/wetty.key
```
Now give these file and folders the correct permissions using these commands:
```bash
chmod 700 ~/.ssl
chmod 644 ~/.ssl/wetty.crt
chmod 600 ~/.ssl/wetty.key
```
This is all we need to do for now in regards to https.
## Generate the ssh key file
**Why?** So that later we can set up automatic login via `ssh`. Our instance
will authorize using this key file stored locally.
Make the required directory, if it does not exist, using this command:
```bash
mkdir -p ~/.ssh
```
Create the `ssh` private key using `ed25519` that we need to authorize our local
connection, using this command:
```bash
ssh-keygen -q -C "wetty-keyfile" -t ed25519 -N '' -f ~/.ssh/wetty 2>/dev/null <<< y >/dev/null
```
**Important Note:** You must add the public key to your `authorized_keys` file
in order to be able to log in using your `ssh` key file when accessing WeTTY via
a web browser.
Copy the key to our `~/.ssh/authorized_keys` file, using this command:
```bash
cat ~/.ssh/wetty.pub >> ~/.ssh/authorized_keys
```
Now give these file and folders the correct permissions, using these commands:
```bash
chmod 700 ~/.ssh
chmod 644 ~/.ssh/authorized_keys
chmod 600 ~/.ssh/wetty
```
**Optional:** A housekeeping command. If you need to remove all entries of the
WeTTY public key with the comment `wetty-keyfile` from the
`~/.ssh/authorized_keys` file use this command. Otherwise ignore this.
```bash
sed -r '/^ssh-ed25519(.*)wetty-keyfile$/d' -i ~/.ssh/authorized_keys
```
## Install WeTTY
**Note:** we are using `-g` for `npm` along with `--prefix ~/` so that the
application's symbolic link is installed to our `~/bin` directory and available
in our local user's `PATH`.
As your local user run these commands:
To make sure the local user's `~/bin` directory exists and is in the `PATH`
please run the following command.
```bash
mkdir -p ~/bin && source ~/.profile
```
Then use `npm` to install `wetty`.
```bash
npm -g i wetty --prefix ~/
```
Once successfully installed the application should be available in your local
user's `PATH`. To test the installation was successful please use this command:
```bash
wetty -h
```
## Accessing the web interface via our external IP
If you are using your external IP and not a domain to access WeTTY this step
needs to be done here because it is not easy to do in the next steps if WeTTY is
running in the terminal.
This command will generate the correct URL you need to visit after using the
start up commands in the following section.
```bash
echo https://$(curl -s4 icanhazip.com):3000
```
_Please make a note of this URL now._
## Running WeTTY
Now we have all the ground work done we can focus on our WeTTY server
configuration settings.
For example, the below command would provide a `https` instance with automatic
`ssh` authorization using our `wetty` private key on port `3000` accessible at
`https://IP:3000` .
**Important note:** This command will run in your current terminal session and
not in the background. The key combination of `CTRL` + `c` will exit the
application.
```bash
wetty --host 0.0.0.0 --port 3000 --title wetty --base / --ssh-key ~/.ssh/wetty --ssh-host localhost --ssh-user $(whoami) --ssh-port 22 --ssh-auth publickey --ssl-key ~/.ssl/wetty.key --ssl-cert ~/.ssl/wetty.crt
```
Since you may not need all these settings we will look through what each one
does below so that you can decide how to best configure your instance.
### Environment settings explained
Let's break it down so that we can understand what's being done and why.
```bash
--host 0.0.0.0 --port 3000 --title wetty --base /
```
`--host 0.0.0.0` - defines the interface we want to bind to. Using `0.0.0.0`
means that we bind to all available interfaces so using this setting just works.
When we use nginx we can change this to `--host 127.0.0.1` in order to prevent
generic port access to the application and force traffic through our nginx
reverse proxy URL.
`--port 3000` - defines the local listening port. You will use this port to
connect via the remotely accessible web server or when configuring a reverse
proxy through nginx.
`--title wetty` - an optional setting to set the window title for this `wetty`
session.
`--base /` - changes the default base URL setting from `/wetty/` to define the
remote URL. We use `--base /` to make `wetty` accessible on the URL format
`https://IP:3000` instead of `https://IP:3000/wetty` but we would change this
back if we use nginx to reverse proxy the application.
### SSH settings explained
These settings are all specific to `ssh` and will enable you to automatically
log into you `ssh` session for the selected user.
```bash
--ssh-key ~/.ssh/wetty --ssh-host localhost --ssh-user $(whoami) --ssh-port 22 --ssh-auth publickey
```
`--ssh-key ~/.ssh/wetty` - we are telling WeTTY to load our `ssh` key file that
we generated earlier.
`--ssh-host localhost` - optional setting telling WeTTY to connect the host
`localhost`
`--ssh-user $(whoami)` - defines our `ssh` username. In this case via the
command substitution of `whoami` which will not require your input of a
username.
`--ssh-port 22` - optional setting to set the `ssh` port we need to connect to.
`--ssh-auth publickey` defines the accepted authentication types. You do not
have to use the key file and you can instead require a password but setting this
to `--sshauth password`. You can specify both `--sshauth publickey,password`
`--ssh-config configfile` - (not used for this guide) alternative ssh
configuration file. From ssh(1):
> If a configuration file is given on the command line, the system-wide
> configuration file (/etc/ssh/ssh_config) will be ignored. The default for the
> per-user configuration file is ~/.ssh/config.
### SSL settings explained
These settings are specific to `openssl` to make WeTTY load https webserver so
that all data is transmitted over a secure connection.
```bash
--ssl-key ~/.ssl/wetty.key --ssl-cert ~/.ssl/wetty.crt
```
`--ssl-key ~/.ssl/wetty.key` - tells WeTTY to load our `openssl` generated key
file.
`--ssl-cert ~/.ssl/wetty.crt` - tells WeTTY to load our `openssl` generates
certificate file.
### Optional - load settings via a configuration file
As of WeTTY v2 there is official support for a configuration file used with the
flag `--conf` to specify the location of this file.
Create the directory where we will store this configuration file.
```bash
mkdir -p ~/.config/wetty
```
Use `nano` to open a file for editing.
```bash
nano ~/.config/wetty/config.json
```
Here is the template `config.json` you need to use.
**Note:** To be [validated json](https://codebeautify.org/jsonvalidator) the
below json example should have the `// ...` comments removed. With all comments
removed the example is valid json. They are in the example to help explain the
options and won't stop WeTTY from loading if you leave them in place. Lines you
do not need can be commented out but should be removed if you want the json to
pass validation.
```json
"ssh": {
"user": "username", // default user to use when ssh-ing
"host": "localhost", // Server to ssh to
"auth": "publickey,password", // shh authentication, method. Defaults to "password", you can use "publickey,password" instead'
"pass": "password", // Password to use when ssh-ing
"key": "/home/username/.ssh/wetty", // path to an optional client private key, connection will be password-less and insecure!
"port": 22, // Port to ssh to
"knownHosts": "/dev/null" // ssh knownHosts file to use
},
"server": {
"base": "/wetty/", // URL base to serve resources from
"port": 3000, // Port to listen on
"host": "0.0.0.0", // listen on all interfaces or can be 127.0.0.1 with nginx
"title": "WeTTY - The Web Terminal Emulator", // Page title
"bypassHelmet": false // Disable Helmet security checks
},
"forceSSH": false, // Force sshing to local machine over login if running as root
"command": "login", // Command to run on server. Login will use ssh if connecting to different server
"ssl": {
"key": "/home/username/.ssl/wetty.key",
"cert": "/home/username/.ssl/wetty.crt"
}
}
```
Press `ctrl` + `x` and then press `y` to save then press `enter` to confirm and
exit `nano`.
## System Environment Variables
**Note:** We will not be using this section to configure WeTTY. We are simply
documenting it.
There are some environment variables you can export that can be used by WeTTY to
configure an instance.
```bash
BASE
PORT
TITLE
SSHUSER
SSHHOST
SSHAUTH
SSHPASS
SSHKEY
SSHPORT
KNOWNHOSTS
FORCESSH
COMMAND
ALLOWIFRAME
```
These can be used in the following way
```bash
export PORT=3000
```
There are currently no environment settings for variables not listed above.
## Systemd service settings
We will use a local user `systemd` service file to manage the `wetty` service.
First, create the required directory, if it does not exist.
```bash
mkdir -p ~/.config/systemd/user
```
### Systemd service
Here is an example template of how to use service file with hardcoded values you
can set in the `wetty.service` file with all options enabled.
Use `nano` to open a file for editing.
```bash
nano ~/.config/systemd/user/wetty.service
```
Then copy and paste this code.
**Note:** This is an example service file based on all the options documented
and configured so far. You may not want all these option enabled so please
remove or modify the `ExecStart` command based on your needs.
```bash
[Unit]
Description=WeTTY
After=network-online.target
[Service]
Type=simple
ExecStart=/bin/bash -c "$$(source /home/$$(whoami)/.nvm/nvm.sh && nvm which 12) /home/$$(whoami)/bin/wetty --host 0.0.0.0 -p 3000 --title wetty --base / --ssh-key /home/$$(whoami)/.ssh/wetty --ssh-host localhost --ssh-user $$(whoami) --ssh-port 22 --ssh-auth publickey --ssl-key /home/$$(whoami)/.ssl/wetty.key --ssl-cert /home/$$(whoami)/.ssl/wetty.crt"
Restart=always
RestartSec=2
TimeoutStopSec=5
SyslogIdentifier=wetty
[Install]
WantedBy=default.target
```
Press `ctrl` + `x` and then press `y` to save then press `enter` to confirm and
exit `nano`.
### Optional - Systemd service with config file
Here is the example using our pseudo configuration file. All modifications to
the start up of `wetty` will be done by editing the `~/.config/Wetty/config`
file and then reloading the `wetty.service`.
Use `nano` to open the file for editing.
```bash
nano ~/.config/systemd/user/wetty.service
```
Then copy and paste this code.
**Note:** This `ExecStart` assumes the location of your `config.json` to be
`~/.config/wetty/config.json`. Please make sure you use the correct location for
this file.
```bash
[Unit]
Description=WeTTY
After=network-online.target
[Service]
Type=simple
ExecStart=/bin/bash -c "$$(source /home/$$(whoami)/.nvm/nvm.sh && nvm which 20) /home/$$(whoami)/bin/wetty --conf /home/$$(whoami)/.config/wetty/config.json"
Restart=always
RestartSec=2
TimeoutStopSec=5
SyslogIdentifier=wetty
[Install]
WantedBy=default.target
```
Press `ctrl` + `x` and then press `y` to save then press `enter` to confirm and
exit `nano`.
### Activating your service
Then you can enable and start your service.
```bash
systemctl --user enable --now wetty
```
### Managing your services
These commands will help you manage your service.
```bash
systemctl --user daemon-reload
systemctl --user status wetty
systemctl --user start wetty
systemctl --user stop wetty
systemctl --user restart wetty
systemctl --user disable --now wetty
systemctl --user enable --now wetty
```
## Nginx reverse proxy
If you want to use nginx as a reverse proxy here is the configuration file you
can use.
Please modify these specific environment settings:
**Why?** This will disable generic port access to the application and force
traffic via the nginx reverse proxy.
```bash
--host 127.0.0.1
```
**Why?** This change is so that our application does not attempt to load as the
web root of `/` for nginx.
```bash
--base /wetty/
```
Now you can use this nginx configuration file.
**Note:** we are using `https` with `https://127.0.0.1:3000/wetty;` because we
configured `wetty` to run via `https` using our self signed ssl certificates. If
you chose not to run WeTTY with a self signed certificate you should changes
this to `http://127.0.0.1:3000/wetty;`
Then copy and paste this into the `https` server block of your enable server
configuration file.
```nginx
location /wetty {
proxy_pass https://127.0.0.1:3000/wetty;
#
proxy_pass_request_headers on;
#
proxy_set_header Host $host;
#
proxy_http_version 1.1;
#
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Protocol $scheme;
proxy_set_header X-Forwarded-Host $http_host;
proxy_set_header X-NginX-Proxy true;
#
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;
proxy_read_timeout 43200000;
proxy_set_header X-Forwarded-Ssl on;
#
proxy_redirect off;
proxy_buffering off;
}
```
Press `ctrl` + `x` and then press `y` to save then press `enter` to confirm and
exit `nano`
Now you would need to reload nginx service using this command:
```bash
systemctl restart nginx
```
### Accessing the web interface via nginx
Visit the URL format `https://YourIPorDomain/wetty` and you can access WeTTY.
This command will generate the correct URL you need to visit it you are not
using a domain.
```bash
echo https://$(curl -s4 icanhazip.com)/wetty
```
## Protecting your instance of WeTTY
**Disclaimer:** It is not recommended by this guide that you run an instance of
WeTTY on your server with no access control in place.
If you chose to not use a password to login in you should protect your instance
behind either:
1:
[Nginx basic auth](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/)
2: [Authelia](https://github.com/authelia/authelia)
## Configuration reference
`wetty -h` configuration options for reference.
```bash
--help, -h Print help message [boolean]
--version Show version number [boolean]
--conf config file to load config from [string]
--ssl-key path to SSL key [string]
--ssl-cert path to SSL certificate [string]
--ssh-host ssh server host [string] [default: "localhost"]
--ssh-port ssh server port [number] [default: 22]
--ssh-user ssh user [string] [default: ""]
--title window title [string] [default: "WeTTY - The Web Terminal Emulator"]
--ssh-auth defaults to "password", you can use "publickey,password"
instead [string] [default: "password"]
--ssh-pass ssh password [string]
--ssh-key path to an optional client private key (connection will be
password-less and insecure!) [string]
--ssh-config Specifies an alternative ssh configuration file. For further
details see "-F" option in ssh(1) [string] [default: ""]
--force-ssh Connecting through ssh even if running as root [boolean] [default: false]
--known-hosts path to known hosts file [string]
--base, -b base path to wetty [string] [default: "/wetty/"]
--port, -p wetty listen port [number] [default: 3000]
--host wetty listen host [string] [default: "0.0.0.0"]
--command, -c command to run in shell [string] [default: "login"]
--allow-iframe Allow wetty to be embedded in an iframe, defaults to allowing
same origin [boolean] [default: false]
```
## Updating WeTTY
```bash
npm -g update wetty --prefix ~/
```
To update or downgrade to a specific version you use this command:
```bash
npm -g i wetty@2.7.0 --prefix ~/
```
Now restart your `wetty` service.
## Updating nvm
The proper way to update NVM is to use git. The `.nvm` directory is a git repo.
These commands will update NVM to the latest version of the script and load it
to your shell.
```bash
cd ~/.nvm
git fetch --tags
git checkout $(git describe --abbrev=0 --tags --match "v[0-9]*" $(git rev-list --tags --max-count=1))
source ~/.nvm/nvm.sh
```
## Updating node
You can use the same command you used to install it with `nvm`
```bash
nvm install 20
```

22
wetty/docs/auto-login.md Normal file
View File

@@ -0,0 +1,22 @@
# Auto Login
WeTTY Supports a form of auto login by passing a users password though url
params.
This is not a required feature and the security implications for passing the
password in the url will have to be considered by the user.
## Requirements
For auto-login feature you'll need sshpass installed
- `apt-get install sshpass` (debian eg. Ubuntu)
- `yum install sshpass` (red hat flavours eg. CentOs)
## Usage
You can also pass the ssh password as an optional query parameter to auto-login
the user like this (Only while running WeTTY as a non root account or when
specifying the ssh host):
`http://yourserver:3000/wetty/ssh/<username>?pass=<password>`

25
wetty/docs/development.md Normal file
View File

@@ -0,0 +1,25 @@
# Installation from Source
WeTTY can be installed from source or from npm.
To install from source run:
```bash
$ git clone https://github.com/butlerx/wetty.git
$ cd wetty
$ pnpm install
$ pnpm build
```
## Development Env
To run WeTTY in dev mode you can run `pnpm dev`.
WeTTY will then be served from `http://localhost:3000/wetty` on your machine.
The server will be using the [`conf/config.json5`](../conf/config.json5) config
file and be pointing at `localhost` on port `22` .
The Dev server will rebuild WeTTY when ever a file is edited and restart the
server with the new build. Any current ssh session in WeTTY will be killed and
the user logged out.

27
wetty/docs/docker.md Normal file
View File

@@ -0,0 +1,27 @@
# Dockerized Version
WeTTY can be run from a container to ssh to a remote host or the host system.
This is handy for quick deployments. Just modify `docker-compose.yml` for your
host and run:
```sh
$ docker-compose up -d
```
This will start 2 containers, one will be WeTTY container running ssh client the
other will be a container running ssh server.
Visit the appropriate URL in your browser
(`[localhost|$(boot2docker ip)]:PORT`).
The default username is `term` and the password is `term`, if you did not modify
`SSHHOST`
In the docker version all flags can be accessed as environment variables such as
`SSHHOST` or `SSHPORT`.
If you don't want to build the image yourself just remove the line `build; .`
If you wish to use the WeTTY container in prod just modify the WeTTY container
to have `SSHHOST` point to the server you want to ssh to and remove the ssh
server container.

View File

@@ -0,0 +1,44 @@
# File Downloading
WeTTY supports file downloads by printing terminal escape sequences between a
base64 encoded file. The name of the downloaded file can optionally be provided,
also base64 encoded, before the encoded file contents with a `:` separating them.
The terminal escape sequences used are `^[[5i` and `^[[4i` (VT100 for "enter
auto print" and "exit auto print" respectively -
https://vt100.net/docs/tp83/appendixc.html).
To take advantage add the following bash function to your `.bashrc`
```bash
function wetty-download() {
file=${1:-/dev/stdin}
nameprefix=""
if [[ -f "$file" ]]; then
nameprefix="$(basename "$file" | base64 -w 0):"
fi
if [[ -f "$file" || "$file" == "/dev/stdin" ]]; then
printf "\033[5i"$nameprefix$(cat "$file" | base64 -w 0)"\033[4i"
else
echo "$file does not appear to be a file"
fi
}
```
You are then able to download files via WeTTY!
```bash
wetty-download my-pdf-file.pdf
```
or you can still use the classic style:
```bash
$ cat my-pdf-file.pdf | wetty-download
```
WeTTY will then issue a popup like the following that links to a local file
blob: `Download ready: file-20191015233654.pdf`

38
wetty/docs/flags.md Normal file
View File

@@ -0,0 +1,38 @@
# Flags
WeTTY can be run with the `--help` flag to get a full list of flags.
## Server Port
WeTTY runs on port `3000` by default. You can change the default port by
starting with the `--port` or `-p` flag.
## SSH Host
If WeTTY is run as root while the host is set as the local machine it will use
the `login` binary rather than ssh. If no host is specified it will use
`localhost` as the ssh host.
If instead you wish to connect to a remote host you can specify the host with
the `--ssh-host` flag and pass the IP or DNS address of the host you want to
connect to.
## Default User
You can specify the default user used to ssh to a host using the `--ssh-user`.
This user can overwritten by going to
`http://yourserver:3000/wetty/ssh/<username>`. If this is left blank a user will
be prompted to enter their username when they connect.
## SSH Port
By default WeTTY will try to ssh to port `22`, if your host uses an alternative
ssh port this can be specified with the flag `--ssh-port`.
## WeTTY URL
If you'd prefer an HTTP base prefix other than `/wetty`, you can specify that
with `--base`.
**Do not set this to `/ssh/${something}`, as this will break username matching
code.**

21
wetty/docs/https.md Normal file
View File

@@ -0,0 +1,21 @@
# HTTPS
Always use HTTPS especially with a terminal to your server. You can add HTTPS by
either using WeTTY behind a proxy or directly.
See docs for [NGinX](./nginx.md) and [Apache](./apache.md) for running behind a
proxy.
To run WeTTY directly with SSL use both the `--ssl-key` and `--ssl-cert` flags
and pass them the path too your cert and key as follows:
```bash
wetty --ssl-key key.pem --ssl-cert cert.pem
```
If you don't have SSL certificates from a CA you can create a self signed
certificate using this command:
```bash
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 30000 -nodes
```

96
wetty/docs/index.html Normal file
View File

@@ -0,0 +1,96 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, minimum-scale=1.0, shrink-to-fit=no, viewport-fit=cover"
/>
<meta name="description" content="WeTTY" />
<title>WeTTY = Web + TTY</title>
<link
rel="apple-touch-icon"
sizes="180x180"
href="assets/img/apple-touch-icon.png"
/>
<link
rel="icon"
type="image/png"
sizes="32x32"
href="assets/img/favicon-32x32.png"
/>
<link
rel="icon"
type="image/png"
sizes="16x16"
href="assets/img/favicon-16x16.png"
/>
<link rel="manifest" href="assets/img/site.webmanifest" />
<!-- Theme -->
<!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/docsify-themeable/dist/css/theme-simple.css"> -->
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/docsify-themeable/dist/css/theme-simple.css"
/>
<link rel="stylesheet" href="assets/css/main.css" />
<script src="https://cdn.jsdelivr.net/npm/docsify-edit-on-github"></script>
</head>
<body>
<div id="app">Please wait...</div>
<script>
window.$docsify = {
// GENERAL
// -----------------------------------------------------------------
name: 'WeTTY = Web + TTY',
repo: 'https://github.com/butlerx/wetty',
homepage: 'README.md',
loadSidebar: true,
loadSidebar: 'sidebar.md',
auto2top: true,
executeScript: true,
mergeNavbar: true,
maxLevel: 3,
subMaxLevel: 3,
// PLUGINS
// -----------------------------------------------------------------
plugins: [
EditOnGithubPlugin.create(
'https://github.com/butlerx/wetty/tree/master/docs/',
),
],
search: {
noData: {
'/': 'No results!',
},
paths: 'auto',
placeholder: {
'/': 'Search',
},
},
tabs: {
persist: true, // default
sync: true, // default
theme: 'classic', // default
tabComments: true, // default
tabHeadings: true, // default
},
themeable: {
readyTransition: true, // default
responsiveTables: true, // default
},
};
</script>
<script src="https://cdn.jsdelivr.net/npm/docsify"></script>
<script src="https://cdn.jsdelivr.net/npm/docsify-tabs"></script>
<script src="https://cdn.jsdelivr.net/npm/docsify-copy-code"></script>
<script src="https://cdn.jsdelivr.net/npm/docsify-themeable"></script>
<script src="https://cdn.jsdelivr.net/npm/docsify/lib/plugins/search.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/docsify-prism"></script>
<script src="https://cdn.jsdelivr.net/npm/prismjs/plugins/autoloader/prism-autoloader.min.js"></script>
</body>
</html>

34
wetty/docs/nginx.md Normal file
View File

@@ -0,0 +1,34 @@
## Run WeTTY behind nginx
As said earlier you can use Nginx to add https to WeTTY.
**Note** that if your proxy is configured for https you should run WeTTY without
SSL
If you configure nginx to use a base path other than `/wetty`, then specify that
path with the `--base` flag, or the `BASE` environment variable.
The following confs assume you want to serve WeTTY on the url
`example.com/wetty` and are running WeTTY with the default base and serving it
on the same server
For a more detailed look see the
[nginx.conf](https://github.com/butlerx/wetty/blob/main/conf/nginx.template)
used for testing
Put the following configuration in your nginx conf:
```nginx
location ^~ /wetty {
proxy_pass http://127.0.0.1:3000/wetty;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 43200000;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
}
```

32
wetty/docs/service.md Normal file
View File

@@ -0,0 +1,32 @@
## Run WeTTY as a service daemon
WeTTY can be run as a daemon on your service init confs and systemd services are
bundled with the npm package to make this easier.
### init.d
```bash
$ npm -g i wetty
$ sudo cp ~/.node_modules/wetty/conf/wetty.conf /etc/init
$ sudo start wetty
```
### systemd
```bash
$ yarn global add wetty
$ cp ~/.node_modules/wetty/conf/wetty.service ~/.config/systemd/user/
$ systemctl --user enable wetty
$ systemctl --user start wetty
```
This will start WeTTY on port 3000. If you want to change the port or redirect
stdout/stderr you should change the last line in `wetty.conf` file, something
like this:
```systemd
exec sudo -u root wetty -p 80 >> /var/log/wetty.log 2>&1
```
Systemd requires an absolute path for a unit's WorkingDirectory, consequently
`$HOME` will need updating to an absolute path in the `wetty.service` file.

11
wetty/docs/sidebar.md Normal file
View File

@@ -0,0 +1,11 @@
- [Home](README.md)
- [Apache](apache.md)
- [API](API.md)
- [AtoZ](atoz.md)
- [auto-login](auto-login.md)
- [development](development.md)
- [downloading-files](downloading-files.md)
- [flags](flags.md)
- [https](https.md)
- [nginx](nginx.md)
- [service](service.md)

BIN
wetty/docs/terminal.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

52
wetty/index.html Normal file
View File

@@ -0,0 +1,52 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=no"
/>
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<title>WeTTY - Gateway Client</title>
</head>
<body>
<div id="overlay">
<div class="error">
<div id="msg"></div>
<input type="button" onclick="location.reload();" value="reconnect" />
</div>
</div>
<div id="options">
<a class="toggler" href="#" alt="Toggle options"
><i class="fas fa-cogs"></i
></a>
<iframe class="editor" src="/xterm_config/index.html"></iframe>
</div>
<div id="functions">
<a
class="toggler"
href="#"
alt="Toggle options"
onclick="window.toggleFunctions()"
><i class="fas fa-keyboard"></i
></a>
<div class="onscreen-buttons">
<a href="#" alt="Up" onclick="window.pressUP()"><div>Up</div></a>
<a href="#" alt="Down" onclick="window.pressDOWN()"><div>Down</div></a>
<a href="#" alt="Left" onclick="window.pressLEFT()"><div>Left</div></a>
<a href="#" alt="Right" onclick="window.pressRIGHT()"><div>Right</div></a>
<a href="#" alt="Esc" onclick="window.pressESC()"><div>Esc</div></a>
<a id="onscreen-ctrl" href="#" alt="Ctrl" onclick="window.toggleCTRL()"
><div>Ctrl</div></a
>
<a href="#" alt="Tab" onclick="window.pressTAB()"><div>Tab</div></a>
</div>
</div>
<div id="terminal"></div>
<script type="module" src="/src/client/wetty.ts"></script>
</body>
</html>

186
wetty/package.json Normal file
View File

@@ -0,0 +1,186 @@
{
"name": "wetty",
"version": "2.7.0",
"description": "WeTTY = Web + TTY. Terminal access in browser over http/https",
"homepage": "https://github.com/butlerx/wetty",
"license": "MIT",
"type": "module",
"bin": "./build/main.js",
"main": "./build/main.js",
"exports": "./build/server.js",
"files": [
"build/",
"conf/"
],
"scripts": {
"build": "node build.js",
"clean": "rm -rf build",
"contributor": "all-contributors",
"dev": "vite",
"dev:wetty": "NODE_ENV=development concurrently --kill-others --raw --success first \"pnpm build --watch\" \"nodemon -w build -i build/client -w conf/config.json5 --delay 200ms . -- --conf conf/config.json5\"",
"docker-compose-entrypoint": "ssh-keyscan -H wetty-ssh >> ~/.ssh/known_hosts; pnpm start",
"lint": "eslint src",
"lint:fix": "eslint --fix src",
"start": "NODE_ENV=production node .",
"test": "mocha",
"prepare": "husky install"
},
"repository": "git://github.com/butlerx/wetty.git",
"author": "Cian Butler <butlerx@notthe.cloud> (cianbutler.ie)",
"bugs": {
"url": "https://github.com/butlerx/wetty/issues"
},
"lint-staged": {
"*.{js,ts}": [
"eslint --fix"
],
"*.{json,scss,md}": [
"prettier --write"
]
},
"engines": {
"node": ">=18.0.0"
},
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^6.1.2",
"@fortawesome/free-solid-svg-icons": "^6.1.2",
"@xterm/xterm": "^5.2.0",
"@xterm/addon-fit": "^0.10.0",
"@xterm/addon-image": "^0.8.0",
"@xterm/addon-web-links": "^0.11.0",
"compression": "^1.7.4",
"etag": "^1.8.1",
"express": "^4.17.1",
"express-winston": "^4.0.5",
"file-type": "^12.3.0",
"find-up": "^5.0.0",
"fresh": "^0.5.2",
"fs-extra": "^9.0.1",
"gc-stats": "^1.4.0",
"helmet": "^4.1.0",
"json5": "^2.1.3",
"lodash": "^4.17.20",
"node-gyp": "^9.1.0",
"node-pty": "^0.10.0",
"parseurl": "^1.3.3",
"prom-client": "^14.0.1",
"response-time": "^2.3.2",
"sass": "^1.54.4",
"serve-static": "^1.15.0",
"socket.io": "^4.5.1",
"socket.io-client": "^4.5.1",
"toastify-js": "^1.9.1",
"url-value-parser": "^2.1.0",
"winston": "^3.3.3",
"yargs": "^17.7.2"
},
"devDependencies": {
"@snowpack/plugin-run-script": "^2.3.0",
"@types/chai": "^4.3.1",
"@types/compression": "^1.7.0",
"@types/etag": "^1.8.0",
"@types/express": "^4.17.8",
"@types/fresh": "^0.5.0",
"@types/fs-extra": "^9.0.1",
"@types/gc-stats": "^1",
"@types/helmet": "^0.0.48",
"@types/jsdom": "^12.2.4",
"@types/lodash": "^4.14.161",
"@types/mocha": "^9.1.1",
"@types/morgan": "^1.7.37",
"@types/node": "^20.2.6",
"@types/parseurl": "^1.3.1",
"@types/response-time": "^2",
"@types/serve-static": "^1.15.3",
"@types/sinon": "^10.0.13",
"@types/toastify-js": "^1.9.2",
"@types/yargs": "^17.0.24",
"@typescript-eslint/eslint-plugin": "^5.59.9",
"@typescript-eslint/parser": "^5.59.9",
"all-contributors-cli": "^6.17.2",
"chai": "^4.3.6",
"concurrently": "^8.2.2",
"esbuild": "^0.21.5",
"esbuild-plugin-copy": "^2.1.1",
"esbuild-sass-plugin": "^3.3.1",
"eslint": "^8.36.0",
"eslint-config-airbnb-base": "latest",
"eslint-config-prettier": "^8.6.0",
"eslint-import-resolver-typescript": "^3.4.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-mocha": "^10.1.0",
"eslint-plugin-prettier": "^4.2.1",
"git-authors-cli": "^1.0.42",
"husky": "^9.0.11",
"jsdom": "^16.5.0",
"lint-staged": "^13.2.2",
"mocha": "^10.0.0",
"nodemon": "^3.1.4",
"prettier": "^2.5.1",
"sinon": "^14.0.0",
"ts-node": "^10.9.1",
"typescript": "^5.1.3",
"vite": "^6.2.6"
},
"contributors": [
"butlerx <butlerx@notthe.cloud>",
"Krishna Srinivas <krishna.srinivas@gmail.com>",
"userdocs <16525024+userdocs@users.noreply.github.com>",
"Boyan Rabchev <boyan@rabchev.com>",
"Ben Letchford <ben_letchford@debortoli.com.au>",
"Antonio Calatrava <antonio@antoniocalatrava.com>",
"Strubbl <github@linux4tw.de>",
"Oleg Kurapov <ok@2sheds.ru>",
"Anthony Jund <antonyjund@gmail.com>",
"Kyle Lucy <kmlucy@gmail.com>",
"Luca Milanesio <luca.milanesio@gmail.com>",
"nosemeocurrenada <nosemeocurrenada93@gmail.com>",
"cbutler <cbutler@demonware.net>",
"Henri <henri.ducrocq@gmail.com>",
"Imuli <i@imu.li>",
"Janos Kasza <janos.kasza@logmein.com>",
"mirtouf <mirtouf@gmail.com>",
"Koushik M.L.N <mln02koushik@gmail.com>",
"Denis Kramer <d.kramer@soton.ac.uk>",
"Harrison Pace <harrison.pace@gmail.com>",
"Jarrett Gilliam <jarrettgilliam@gmail.com>",
"Nathan LeClaire <nathan.leclaire@docker.com>",
"SouraDutta <33066261+SouraDutta@users.noreply.github.com>",
"Aayush Garg-gamer1478 <74775129+gamer-12748@users.noreply.github.com>",
"Bertrand Roussel <broussel@sierrawireless.com>",
"Christian7573 <Christian7573@users.noreply.github.com>",
"Dean Shub <deanshub@gmail.com>",
"Dmytri Kleiner <dk@trick.ca>",
"Felix Bartels <felix@host-consultants.de>",
"Felix Pojtinger <felix@pojtinger.com>",
"Josua Frank <frank.josua@gmail.com>",
"Georgelemental <georgelemental@gmail.com>",
"Loz Brown <github@protazoa.com>",
"Grant Handy <grantshandy@gmail.com>",
"harryleesan <harry.lee.san.temp@gmail.com>",
"Andreas Kloeckner <inform@tiker.net>",
"James Turnbull <james@lovedthanlost.net>",
"Arturo R <jaquer@users.noreply.github.com>",
"Josh Samuelson <js@puppetlabs.com>",
"Jurre Vriesen <jurrevriesen@gmail.com>",
"Kevin <kevin@vnucleus.com>",
"Farhan Khan <khanzf@gmail.com>",
"Kasper Holbek Jensen <kholbekj@gmail.com>",
"Krzysztof Suszyński <krzysztof.suszynski@wavesoftware.pl>",
"justluk <lukegriffith@gmail.com>",
"Mathieu Geli <mathieu.geli@gmail.com>",
"Mihir Kumar <mihirpandey.13@gmail.com>",
"Neale Pickett <neale@woozle.org>",
"pablo-zarate <pablo.zarateg@gmail.com>",
"Matthew Piercey <piercey.matthew@gmail.com>",
"Alex Cline <rev.a.r.cline@gmail.com>",
"Robert <robert@n5qm.com>",
"Sergei Ratnikov <sergeir82@gmail.com>",
"Shimi <shimile@users.noreply.github.com>",
"Sven Fischer <sven@leiderfischer.de>",
"Taha <tahayasinerol@live.com>",
"Tri Nguyen <tri@tridnguyen.com>",
"Vamshi K Ponnapalli <vamship@users.noreply.github.com>"
],
"packageManager": "pnpm@9.4.0+sha512.f549b8a52c9d2b8536762f99c0722205efc5af913e77835dbccc3b0b0b2ca9e7dc8022b78062c17291c48e88749c70ce88eb5a74f1fa8c4bf5e18bb46c8bd83a"
}

7261
wetty/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

BIN
wetty/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

View File

@@ -0,0 +1,164 @@
function optionGenericGet() {
return this.el.querySelector('input').value;
}
function optionGenericSet(value) {
this.el.querySelector('input').value = value;
}
function optionEnumGet() {
return this.el.querySelector('select').value;
}
function optionEnumSet(value) {
this.el.querySelector('select').value = value;
}
function optionBoolGet() {
return this.el.querySelector('input').checked;
}
function optionBoolSet(value) {
this.el.querySelector('input').checked = value;
}
function optionNumberGet() {
let value = (this.float === true ? parseFloat : parseInt)(
this.el.querySelector('input').value,
);
if (Number.isNaN(value) || typeof value !== 'number') value = 0;
if (typeof this.min === 'number') value = Math.max(value, this.min);
if (typeof this.max === 'number') value = Math.min(value, this.max);
return value;
}
function optionNumberSet(value) {
this.el.querySelector('input').value = value;
}
const allOptions = [];
/* eslint-disable @typescript-eslint/no-unused-vars */
function inflateOptions(optionsSchema) {
const booleanOption = document.querySelector('#boolean_option.templ');
const enumOption = document.querySelector('#enum_option.templ');
const textOption = document.querySelector('#text_option.templ');
const numberOption = document.querySelector('#number_option.templ');
const colorOption = document.querySelector('#color_option.templ');
function copyOver({ children }) {
while (children.length > 0) document.body.append(children[0]);
}
optionsSchema.forEach(option => {
let el;
option.get = optionGenericGet.bind(option);
option.set = optionGenericSet.bind(option);
switch (option.type) {
case 'boolean':
el = booleanOption.cloneNode(true);
option.get = optionBoolGet.bind(option);
option.set = optionBoolSet.bind(option);
break;
case 'enum':
el = enumOption.cloneNode(true);
option.enum.forEach(varriant => {
const optionEl = document.createElement('option');
optionEl.innerText = varriant;
optionEl.value = varriant;
el.querySelector('select').appendChild(optionEl);
});
option.get = optionEnumGet.bind(option);
option.set = optionEnumSet.bind(option);
break;
case 'text':
el = textOption.cloneNode(true);
break;
case 'number':
el = numberOption.cloneNode(true);
if (option.float === true)
el.querySelector('input').setAttribute('step', '0.001');
option.get = optionNumberGet.bind(option);
option.set = optionNumberSet.bind(option);
if (typeof option.min === 'number')
el.querySelector('input').setAttribute('min', option.min.toString());
if (typeof option.max === 'number')
el.querySelector('input').setAttribute('max', option.max.toString());
break;
case 'color':
el = colorOption.cloneNode(true);
break;
default:
throw new Error(`Unknown option type ${option.type}`);
}
el.querySelector('.title').innerText = option.name;
el.querySelector('.desc').innerText = option.description;
[option.el] = el.children;
copyOver(el);
allOptions.push(option);
});
}
function getItem(json, path) {
const mypath = path[0];
if (path.length === 1) return json[mypath];
if (json[mypath] != null) return getItem(json[mypath], path.slice(1));
return null;
}
function setItem(json, path, item) {
const mypath = path[0];
if (path.length === 1) json[mypath] = item;
else {
if (json[mypath] == null) json[mypath] = {};
setItem(json[mypath], path.slice(1), item);
}
}
window.loadOptions = config => {
allOptions.forEach(option => {
let value = getItem(config, option.path);
if (option.nullable === true && option.type === 'text' && value == null)
value = null;
else if (
option.nullable === true &&
option.type === 'number' &&
value == null
)
value = -1;
else if (value == null) return;
if (option.json === true && option.type === 'text')
value = JSON.stringify(value);
option.set(value);
option.el.classList.remove('unbounded');
});
};
if (window.top === window)
// eslint-disable-next-line no-alert
alert(
'Error: Page is top level. This page is supposed to be accessed from inside WeTTY.',
);
function saveConfig() {
const newConfig = {};
allOptions.forEach(option => {
let newValue = option.get();
if (
option.nullable === true &&
((option.type === 'text' && newValue === '') ||
(option.type === 'number' && newValue < 0))
)
return;
if (option.json === true && option.type === 'text')
newValue = JSON.parse(newValue);
setItem(newConfig, option.path, newValue);
});
window.wetty_save_config(newConfig);
}
window.addEventListener('input', () => {
const els = document.querySelectorAll('input, select');
for (let i = 0; i < els.length; i += 1) {
els[i].addEventListener('input', saveConfig);
}
});

View File

@@ -0,0 +1,71 @@
<!DOCTYPE html>
<html>
<head>
<title>Wetty XTerm Configuration</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<header>
<h1>Configure</h1>
</header>
<div class="templ" id="boolean_option">
<div class="boolean_option unbounded">
<p>
<b class="title"></b><br />
<span class="desc"></span>
</p>
<input type="checkbox" />
</div>
</div>
<div class="templ" id="enum_option">
<div class="enum_option unbounded">
<p>
<b class="title"></b><br />
<span class="desc"></span>
</p>
<select></select>
</div>
</div>
<div class="templ" id="text_option">
<div class="text_option unbounded">
<p>
<b class="title"></b><br />
<span class="desc"></span>
</p>
<input type="text" />
</div>
<div class="error_reporting"></div>
</div>
<div class="templ" id="number_option">
<div class="number_option unbounded">
<p>
<b class="title"></b><br />
<span class="desc"></span>
</p>
<input type="number" size="10" />
</div>
<div class="error_reporting"></div>
</div>
<div class="templ" id="color_option">
<div class="color_option unbounded">
<p>
<b class="title"></b><br />
<span class="desc"></span>
</p>
<input type="color" />
</div>
</div>
<script src="./functionality.js"></script>
<h2>General Options</h2>
<script src="./xterm_general_options.js"></script>
<h2>Color Theme</h2>
<script src="./xterm_color_theme.js"></script>
<h2>Advanced XTerm Options</h2>
<script src="./xterm_advanced_options.js"></script>
<script src="./xterm_defaults.js"></script>
</body>
</html>

View File

@@ -0,0 +1,78 @@
html {
background-color: black;
}
html,
body {
overflow: hidden auto;
}
body {
display: flex;
flex-flow: column nowrap;
font-family: monospace;
font-size: 1rem;
color: white;
}
.templ {
display: none;
}
h2 {
text-align: center;
text-decoration: underline;
}
header {
display: flex;
flex-flow: row nowrap;
align-items: center;
}
header button {
padding: 0.5em;
font-size: 1em;
margin: 0.5em;
border-radius: 0.5em;
}
.boolean_option,
.number_option,
.color_option,
.enum_option,
.text_option {
display: grid;
grid-template-columns: 100fr min(30em, 50%);
grid-template-rows: auto;
align-items: center;
}
.boolean_option input,
.number_option input,
.color_option input,
.text_option input,
.enum_option select {
margin: 0 0.5em;
font-size: 1em;
background-color: hsl(0, 0%, 20%);
color: white;
border: 2px solid white;
}
.number_option input,
.text_option input,
.enum_option select {
padding: 0.4em;
}
.boolean_option input {
width: 2em;
height: 2em;
font-size: 0.75em;
justify-self: center;
}
.color_option input {
width: 100%;
height: 100%;
background-color: lightgray;
}
.unbounded .title::before {
content: 'UNBOUND OPTION ';
color: red;
font-weight: bold;
}

View File

@@ -0,0 +1,127 @@
window.inflateOptions([
{
type: 'boolean',
name: 'Allow Proposed XTerm APIs',
description:
'When set to false, any experimental/proposed APIs will throw errors.',
path: ['xterm', 'allowProposedApi'],
},
{
type: 'boolean',
name: 'Allow Transparent Background',
description: 'Whether the background is allowed to be a non-opaque color.',
path: ['xterm', 'allowTransparency'],
},
{
type: 'text',
name: 'Bell Sound URI',
description: 'URI for a custom bell character sound.',
path: ['xterm', 'bellSound'],
nullable: true,
},
{
type: 'enum',
name: 'Bell Style',
description: 'How the terminal will react to the bell character',
path: ['xterm', 'bellStyle'],
enum: ['none', 'sound'],
},
{
type: 'boolean',
name: 'Force End-Of-Line',
description:
'When enabled, any new-line characters (\\n) will be interpreted as carriage-return new-line. (\\r\\n) Typically this is done by the shell program.',
path: ['xterm', 'convertEol'],
},
{
type: 'boolean',
name: 'Disable Stdin',
description: 'Whether input should be disabled',
path: ['xterm', 'disableStdin'],
},
{
type: 'number',
name: 'Letter Spacing',
description: 'The spacing in whole pixels between characters.',
path: ['xterm', 'letterSpacing'],
},
{
type: 'number',
name: 'Line Height',
description:
'Line height, multiplied by the font size to get the height of terminal rows.',
path: ['xterm', 'lineHeight'],
float: true,
},
{
type: 'enum',
name: 'XTerm Log Level',
description: 'Log level for the XTerm library.',
path: ['xterm', 'logLevel'],
enum: ['debug', 'info', 'warn', 'error', 'off'],
},
{
type: 'boolean',
name: 'Macintosh Option Key as Meta Key',
description:
'When enabled, the Option key on Macs will be interpreted as the Meta key.',
path: ['xterm', 'macOptionIsMeta'],
},
{
type: 'boolean',
name: 'Macintosh Option Click Forces Selection',
description:
"Whether holding a modifier key will force normal selection behavior, regardless of whether the terminal is in mouse events mode. This will also prevent mouse events from being emitted by the terminal. For example, this allows you to use xterm.js' regular selection inside tmux with mouse mode enabled.",
path: ['xterm', 'macOptionClickForcesSelection'],
},
{
type: 'number',
name: 'Forced Contrast Ratio',
description:
'Miminum contrast ratio for terminal text. This will alter the foreground color dynamically to ensure the ratio is met. Goes from 1 (do nothing) to 21 (strict black and white).',
path: ['xterm', 'minimumContrastRatio'],
float: true,
},
{
type: 'enum',
name: 'Renderer Type',
description:
'The terminal renderer to use. Canvas is preferred, but a DOM renderer is also available. Note: Letter spacing and cursor blink do not work in the DOM renderer.',
path: ['xterm', 'rendererType'],
enum: ['canvas', 'dom'],
},
{
type: 'boolean',
name: 'Right Click Selects Words',
description: 'Whether to select the word under the cursor on right click.',
path: ['xterm', 'rightClickSelectsWord'],
},
{
type: 'boolean',
name: 'Screen Reader Support',
description:
'Whether screen reader support is enabled. When on this will expose supporting elements in the DOM to support NVDA on Windows and VoiceOver on macOS.',
path: ['xterm', 'screenReaderMode'],
},
{
type: 'number',
name: 'Tab Stop Width',
description: 'The size of tab stops in the terminal.',
path: ['xterm', 'tabStopWidth'],
},
{
type: 'boolean',
name: 'Windows Mode',
description:
"\"Whether 'Windows mode' is enabled. Because Windows backends winpty and conpty operate by doing line wrapping on their side, xterm.js does not have access to wrapped lines. When Windows mode is enabled the following changes will be in effect:\n- Reflow is disabled.\n- Lines are assumed to be wrapped if the last character of the line is not whitespace.",
path: ['xterm', 'windowsMode'],
},
{
type: 'text',
name: 'Word Separator',
description:
'All characters considered word separators. Used for double-click to select word logic. Encoded as JSON in this editor for editing convienience.',
path: ['xterm', 'wordSeparator'],
json: true,
},
]);

View File

@@ -0,0 +1,152 @@
const selectionColorOption = {
type: 'color',
name: 'Selection Color',
description: 'Background color for selected text. Can be transparent.',
path: ['xterm', 'theme', 'selection'],
};
const selectionColorOpacityOption = {
type: 'number',
name: 'Selection Color Opacity',
description:
'Opacity of the selection highlight. A value between 1 (fully opaque) and 0 (fully transparent).',
path: ['wettyVoid'],
float: true,
min: 0,
max: 1,
};
window.inflateOptions([
{
type: 'color',
name: 'Foreground Color',
description: 'The default foreground (text) color.',
path: ['xterm', 'theme', 'foreground'],
},
{
type: 'color',
name: 'Background Color',
description: 'The default background color.',
path: ['xterm', 'theme', 'background'],
},
{
type: 'color',
name: 'Cursor Color',
description: 'Color of the cursor.',
path: ['xterm', 'theme', 'cursor'],
},
{
type: 'color',
name: 'Block Cursor Accent Color',
description:
'The accent color of the cursor, used as the foreground color for block cursors.',
path: ['xterm', 'theme', 'cursorAccent'],
},
selectionColorOption,
selectionColorOpacityOption,
{
type: 'color',
name: 'Black',
description: 'Color for ANSI Black text.',
path: ['xterm', 'theme', 'black'],
},
{
type: 'color',
name: 'Red',
description: 'Color for ANSI Red text.',
path: ['xterm', 'theme', 'red'],
},
{
type: 'color',
name: 'Green',
description: 'Color for ANSI Green text.',
path: ['xterm', 'theme', 'green'],
},
{
type: 'color',
name: 'Yellow',
description: 'Color for ANSI Yellow text.',
path: ['xterm', 'theme', 'yellow'],
},
{
type: 'color',
name: 'Blue',
description: 'Color for ANSI Blue text.',
path: ['xterm', 'theme', 'blue'],
},
{
type: 'color',
name: 'Magenta',
description: 'Color for ANSI Magenta text.',
path: ['xterm', 'theme', 'magenta'],
},
{
type: 'color',
name: 'Cyan',
description: 'Color for ANSI Cyan text.',
path: ['xterm', 'theme', 'cyan'],
},
{
type: 'color',
name: 'White',
description: 'Color for ANSI White text.',
path: ['xterm', 'theme', 'white'],
},
{
type: 'color',
name: 'Bright Black',
description: 'Color for ANSI Bright Black text.',
path: ['xterm', 'theme', 'brightBlack'],
},
{
type: 'color',
name: 'Bright Red',
description: 'Color for ANSI Bright Red text.',
path: ['xterm', 'theme', 'brightRed'],
},
{
type: 'color',
name: 'Bright Green',
description: 'Color for ANSI Bright Green text.',
path: ['xterm', 'theme', 'brightGreen'],
},
{
type: 'color',
name: 'Bright Yellow',
description: 'Color for ANSI Bright Yellow text.',
path: ['xterm', 'theme', 'brightYellow'],
},
{
type: 'color',
name: 'Bright Blue',
description: 'Color for ANSI Bright Blue text.',
path: ['xterm', 'theme', 'brightBlue'],
},
{
type: 'color',
name: 'Bright Magenta',
description: 'Color for ANSI Bright Magenta text.',
path: ['xterm', 'theme', 'brightMagenta'],
},
{
type: 'color',
name: 'Bright White',
description: 'Color for ANSI Bright White text.',
path: ['xterm', 'theme', 'brightWhite'],
},
]);
selectionColorOption.get = function getInput() {
return (
this.el.querySelector('input').value +
Math.round(
selectionColorOpacityOption.el.querySelector('input').value * 255,
).toString(16)
);
};
selectionColorOption.set = function setInput(value) {
this.el.querySelector('input').value = value.substring(0, 7);
selectionColorOpacityOption.el.querySelector('input').value =
Math.round((parseInt(value.substring(7), 16) / 255) * 100) / 100;
};
selectionColorOpacityOption.get = () => 0;
selectionColorOpacityOption.set = () => 0;

View File

@@ -0,0 +1,70 @@
const DEFAULT_BELL_SOUND =
'data:audio/mp3;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjMyLjEwNAAAAAAAAAAAAAAA//tQxAADB8AhSmxhIIEVCSiJrDCQBTcu3UrAIwUdkRgQbFAZC1CQEwTJ9mjRvBA4UOLD8nKVOWfh+UlK3z/177OXrfOdKl7pyn3Xf//WreyTRUoAWgBgkOAGbZHBgG1OF6zM82DWbZaUmMBptgQhGjsyYqc9ae9XFz280948NMBWInljyzsNRFLPWdnZGWrddDsjK1unuSrVN9jJsK8KuQtQCtMBjCEtImISdNKJOopIpBFpNSMbIHCSRpRR5iakjTiyzLhchUUBwCgyKiweBv/7UsQbg8isVNoMPMjAAAA0gAAABEVFGmgqK////9bP/6XCykxBTUUzLjEwMKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq';
window.loadOptions({
wettyFitTerminal: true,
wettyVoid: 0,
xterm: {
cols: 80,
rows: 24,
cursorBlink: false,
cursorStyle: 'block',
cursorWidth: 1,
bellSound: DEFAULT_BELL_SOUND,
bellStyle: 'none',
drawBoldTextInBrightColors: true,
fastScrollModifier: 'alt',
fastScrollSensitivity: 5,
fontFamily: 'courier-new, courier, monospace',
fontSize: 15,
fontWeight: 'normal',
fontWeightBold: 'bold',
lineHeight: 1.0,
linkTooltipHoverDuration: 500,
letterSpacing: 0,
logLevel: 'info',
scrollback: 1000,
scrollSensitivity: 1,
screenReaderMode: false,
macOptionIsMeta: false,
macOptionClickForcesSelection: false,
minimumContrastRatio: 1,
disableStdin: false,
allowProposedApi: true,
allowTransparency: false,
tabStopWidth: 8,
rightClickSelectsWord: false,
rendererType: 'canvas',
windowOptions: {},
windowsMode: false,
wordSeparator: ' ()[]{}\',"`',
convertEol: false,
termName: 'xterm',
cancelEvents: false,
theme: {
foreground: '#ffffff',
background: '#000000',
cursor: '#ffffff',
cursorAccent: '#000000',
selection: '#FFFFFF4D',
black: '#2e3436',
red: '#cc0000',
green: '#4e9a06',
yellow: '#c4a000',
blue: '#3465a4',
magenta: '#75507b',
cyan: '#06989a',
white: '#d3d7cf',
brightBlack: '#555753',
brightRed: '#ef2929',
brightGreen: '#8ae234',
brightYellow: '#fce94f',
brightBlue: '#729fcf',
brightMagenta: '#ad7fa8',
brightCyan: '#34e2e2',
brightWhite: '#eeeeec',
},
},
});

View File

@@ -0,0 +1,136 @@
window.inflateOptions([
{
type: 'text',
name: 'Font Family',
description: 'The font family for terminal text.',
path: ['xterm', 'fontFamily'],
},
{
type: 'number',
name: 'Font Size',
description: 'The font size in CSS pixels for terminal text.',
path: ['xterm', 'fontSize'],
min: 4,
},
{
type: 'enum',
name: 'Regular Font Weight',
description: 'The font weight for non-bold text.',
path: ['xterm', 'fontWeight'],
enum: [
'normal',
'bold',
'100',
'200',
'300',
'400',
'500',
'600',
'700',
'800',
'900',
],
},
{
type: 'enum',
name: 'Bold Font Weight',
description: 'The font weight for bold text.',
path: ['xterm', 'fontWeightBold'],
enum: [
'normal',
'bold',
'100',
'200',
'300',
'400',
'500',
'600',
'700',
'800',
'900',
],
},
{
type: 'boolean',
name: 'Fit Terminal',
description:
'Automatically fits the terminal to the page, overriding terminal columns and rows.',
path: ['wettyFitTerminal'],
},
{
type: 'number',
name: 'Terminal Columns',
description:
'The number of columns in the terminal. Overridden by the Fit Terminal option.',
path: ['xterm', 'cols'],
nullable: true,
},
{
type: 'number',
name: 'Terminal Rows',
description:
'The number of rows in the terminal. Overridden by the Fit Terminal option.',
path: ['xterm', 'rows'],
nullable: true,
},
{
type: 'enum',
name: 'Cursor Style',
description: 'The style of the cursor',
path: ['xterm', 'cursorStyle'],
enum: ['block', 'underline', 'bar'],
},
{
type: 'boolean',
name: 'Blinking Cursor',
description: 'Whether the cursor blinks',
path: ['xterm', 'cursorBlink'],
},
{
type: 'number',
name: 'Bar Cursor Width',
description:
"The width of the cursor in CSS pixels. Only applies when Cursor Style is set to 'bar'.",
path: ['xterm', 'cursorWidth'],
},
{
type: 'boolean',
name: 'Draw Bold Text In Bright Colors',
description: 'Whether to draw bold text in bright colors',
path: ['xterm', 'drawBoldTextInBrightColors'],
},
{
type: 'number',
name: 'Scroll Sensitivity',
description: 'The scroll speed multiplier for regular scrolling.',
path: ['xterm', 'scrollSensitivity'],
float: true,
},
{
type: 'enum',
name: 'Fast Scroll Key',
description: 'The modifier key to hold to multiply scroll speed.',
path: ['xterm', 'fastScrollModifier'],
enum: ['none', 'alt', 'shift', 'ctrl'],
},
{
type: 'number',
name: 'Fast Scroll Multiplier',
description: 'The scroll speed multiplier used for fast scrolling.',
path: ['xterm', 'fastScrollSensitivity'],
float: true,
},
{
type: 'number',
name: 'Scrollback Rows',
description:
'The amount of scrollback rows, rows you can scroll up to after they leave the viewport, to keep.',
path: ['xterm', 'scrollback'],
},
{
type: 'number',
name: 'Tab Stop Width',
description: 'The size of tab stops in the terminal.',
path: ['xterm', 'tabStopWidth'],
},
]);

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

View File

@@ -0,0 +1,111 @@
@use './variables';
#options {
height: 16px;
position: absolute;
right: 1em;
top: 1em;
width: 16px;
z-index: 20;
.toggler {
color: variables.$lgrey;
display: inline-block;
font-size: 16px;
position: absolute;
right: 1em;
top: 0;
z-index: 20;
:hover {
color: variables.$white;
}
}
.editor {
background-color: rgba(0, 0, 0, 0.85);
border-color: rgba(255, 255, 255, 0.25);
border-radius: 0.3em;
color: #eee;
display: none;
font-size: 24px;
height: 100%;
padding: 0.5em;
position: relative;
right: 2em;
top: 1em;
width: 100%;
}
}
#options.opened {
height: max(min(300px, 75vh), 50vh);
width: max(min(500px, 75vw), 50vw);
.editor {
display: flex;
}
.error {
color: red;
}
}
#functions {
position: fixed;
right: 2em;
top: 6em;
z-index: 20;
> a {
padding: 10px;
position: absolute;
right: -10px;
top: -40px;
color: variables.$lgrey;
:hover {
color: variables.$white;
}
}
.onscreen-buttons {
display: none;
width: 200px;
height: 200px;
border: solid 2px rgba(255, 255, 255, 0.25);
border-radius: 0.3em;
background-color: rgba(0, 0, 0, 0.85);
> a {
bottom: 1em;
right: 2em;
text-decoration: none;
color: white;
> div {
padding: 5px;
outline: 2px solid white;
margin: 10px;
display: inline-block;
font-weight: bold;
border-radius: 10px;
}
}
}
.active {
display: block;
}
.onscreen-buttons > a:active {
> div {
background-color: rgba(255, 255, 255, 0.25);
}
}
#onscreen-ctrl.active {
display: inline-block;
> div {
background-color: lightgray;
}
}
}

View File

@@ -0,0 +1,28 @@
@use './variables';
#overlay {
background-color: variables.$grey;
display: none;
height: 100%;
position: absolute;
width: 100%;
z-index: 100;
.error {
display: flex;
flex-direction: column;
height: 100%;
justify-content: center;
width: 100%;
#msg {
align-self: center;
color: variables.$white;
}
input {
align-self: center;
margin: 16px;
}
}
}

View File

@@ -0,0 +1,25 @@
@use '@xterm/xterm/css/xterm.css';
@use 'toastify-js/src/toastify.css';
@use './variables';
@use './overlay';
@use './options';
@use './terminal';
html,
body {
background-color: variables.$black;
height: 100%;
margin: 0;
overflow: hidden;
.toastify {
border-radius: 0;
color: variables.$black;
}
}
.xterm {
.xterm-viewport {
overflow-y: hidden;
}
}

View File

@@ -0,0 +1,6 @@
#terminal {
display: flex;
height: 100%;
position: relative;
width: 100%;
}

View File

@@ -0,0 +1,4 @@
$black: #000;
$grey: rgba(0, 0, 0, 0.75);
$white: #fff;
$lgrey: #ccc;

View File

@@ -0,0 +1,164 @@
function optionGenericGet() {
return this.el.querySelector('input').value;
}
function optionGenericSet(value) {
this.el.querySelector('input').value = value;
}
function optionEnumGet() {
return this.el.querySelector('select').value;
}
function optionEnumSet(value) {
this.el.querySelector('select').value = value;
}
function optionBoolGet() {
return this.el.querySelector('input').checked;
}
function optionBoolSet(value) {
this.el.querySelector('input').checked = value;
}
function optionNumberGet() {
let value = (this.float === true ? parseFloat : parseInt)(
this.el.querySelector('input').value,
);
if (Number.isNaN(value) || typeof value !== 'number') value = 0;
if (typeof this.min === 'number') value = Math.max(value, this.min);
if (typeof this.max === 'number') value = Math.min(value, this.max);
return value;
}
function optionNumberSet(value) {
this.el.querySelector('input').value = value;
}
const allOptions = [];
/* eslint-disable @typescript-eslint/no-unused-vars */
function inflateOptions(optionsSchema) {
const booleanOption = document.querySelector('#boolean_option.templ');
const enumOption = document.querySelector('#enum_option.templ');
const textOption = document.querySelector('#text_option.templ');
const numberOption = document.querySelector('#number_option.templ');
const colorOption = document.querySelector('#color_option.templ');
function copyOver({ children }) {
while (children.length > 0) document.body.append(children[0]);
}
optionsSchema.forEach(option => {
let el;
option.get = optionGenericGet.bind(option);
option.set = optionGenericSet.bind(option);
switch (option.type) {
case 'boolean':
el = booleanOption.cloneNode(true);
option.get = optionBoolGet.bind(option);
option.set = optionBoolSet.bind(option);
break;
case 'enum':
el = enumOption.cloneNode(true);
option.enum.forEach(varriant => {
const optionEl = document.createElement('option');
optionEl.innerText = varriant;
optionEl.value = varriant;
el.querySelector('select').appendChild(optionEl);
});
option.get = optionEnumGet.bind(option);
option.set = optionEnumSet.bind(option);
break;
case 'text':
el = textOption.cloneNode(true);
break;
case 'number':
el = numberOption.cloneNode(true);
if (option.float === true)
el.querySelector('input').setAttribute('step', '0.001');
option.get = optionNumberGet.bind(option);
option.set = optionNumberSet.bind(option);
if (typeof option.min === 'number')
el.querySelector('input').setAttribute('min', option.min.toString());
if (typeof option.max === 'number')
el.querySelector('input').setAttribute('max', option.max.toString());
break;
case 'color':
el = colorOption.cloneNode(true);
break;
default:
throw new Error(`Unknown option type ${option.type}`);
}
el.querySelector('.title').innerText = option.name;
el.querySelector('.desc').innerText = option.description;
[option.el] = el.children;
copyOver(el);
allOptions.push(option);
});
}
function getItem(json, path) {
const mypath = path[0];
if (path.length === 1) return json[mypath];
if (json[mypath] != null) return getItem(json[mypath], path.slice(1));
return null;
}
function setItem(json, path, item) {
const mypath = path[0];
if (path.length === 1) json[mypath] = item;
else {
if (json[mypath] == null) json[mypath] = {};
setItem(json[mypath], path.slice(1), item);
}
}
window.loadOptions = config => {
allOptions.forEach(option => {
let value = getItem(config, option.path);
if (option.nullable === true && option.type === 'text' && value == null)
value = null;
else if (
option.nullable === true &&
option.type === 'number' &&
value == null
)
value = -1;
else if (value == null) return;
if (option.json === true && option.type === 'text')
value = JSON.stringify(value);
option.set(value);
option.el.classList.remove('unbounded');
});
};
if (window.top === window)
// eslint-disable-next-line no-alert
alert(
'Error: Page is top level. This page is supposed to be accessed from inside WeTTY.',
);
function saveConfig() {
const newConfig = {};
allOptions.forEach(option => {
let newValue = option.get();
if (
option.nullable === true &&
((option.type === 'text' && newValue === '') ||
(option.type === 'number' && newValue < 0))
)
return;
if (option.json === true && option.type === 'text')
newValue = JSON.parse(newValue);
setItem(newConfig, option.path, newValue);
});
window.wetty_save_config(newConfig);
}
window.addEventListener('input', () => {
const els = document.querySelectorAll('input, select');
for (let i = 0; i < els.length; i += 1) {
els[i].addEventListener('input', saveConfig);
}
});

View File

@@ -0,0 +1,71 @@
<!DOCTYPE html>
<html>
<head>
<title>Wetty XTerm Configuration</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<header>
<h1>Configure</h1>
</header>
<div class="templ" id="boolean_option">
<div class="boolean_option unbounded">
<p>
<b class="title"></b><br />
<span class="desc"></span>
</p>
<input type="checkbox" />
</div>
</div>
<div class="templ" id="enum_option">
<div class="enum_option unbounded">
<p>
<b class="title"></b><br />
<span class="desc"></span>
</p>
<select></select>
</div>
</div>
<div class="templ" id="text_option">
<div class="text_option unbounded">
<p>
<b class="title"></b><br />
<span class="desc"></span>
</p>
<input type="text" />
</div>
<div class="error_reporting"></div>
</div>
<div class="templ" id="number_option">
<div class="number_option unbounded">
<p>
<b class="title"></b><br />
<span class="desc"></span>
</p>
<input type="number" size="10" />
</div>
<div class="error_reporting"></div>
</div>
<div class="templ" id="color_option">
<div class="color_option unbounded">
<p>
<b class="title"></b><br />
<span class="desc"></span>
</p>
<input type="color" />
</div>
</div>
<script src="./functionality.js"></script>
<h2>General Options</h2>
<script src="./xterm_general_options.js"></script>
<h2>Color Theme</h2>
<script src="./xterm_color_theme.js"></script>
<h2>Advanced XTerm Options</h2>
<script src="./xterm_advanced_options.js"></script>
<script src="./xterm_defaults.js"></script>
</body>
</html>

View File

@@ -0,0 +1,78 @@
html {
background-color: black;
}
html,
body {
overflow: hidden auto;
}
body {
display: flex;
flex-flow: column nowrap;
font-family: monospace;
font-size: 1rem;
color: white;
}
.templ {
display: none;
}
h2 {
text-align: center;
text-decoration: underline;
}
header {
display: flex;
flex-flow: row nowrap;
align-items: center;
}
header button {
padding: 0.5em;
font-size: 1em;
margin: 0.5em;
border-radius: 0.5em;
}
.boolean_option,
.number_option,
.color_option,
.enum_option,
.text_option {
display: grid;
grid-template-columns: 100fr min(30em, 50%);
grid-template-rows: auto;
align-items: center;
}
.boolean_option input,
.number_option input,
.color_option input,
.text_option input,
.enum_option select {
margin: 0 0.5em;
font-size: 1em;
background-color: hsl(0, 0%, 20%);
color: white;
border: 2px solid white;
}
.number_option input,
.text_option input,
.enum_option select {
padding: 0.4em;
}
.boolean_option input {
width: 2em;
height: 2em;
font-size: 0.75em;
justify-self: center;
}
.color_option input {
width: 100%;
height: 100%;
background-color: lightgray;
}
.unbounded .title::before {
content: 'UNBOUND OPTION ';
color: red;
font-weight: bold;
}

View File

@@ -0,0 +1,127 @@
window.inflateOptions([
{
type: 'boolean',
name: 'Allow Proposed XTerm APIs',
description:
'When set to false, any experimental/proposed APIs will throw errors.',
path: ['xterm', 'allowProposedApi'],
},
{
type: 'boolean',
name: 'Allow Transparent Background',
description: 'Whether the background is allowed to be a non-opaque color.',
path: ['xterm', 'allowTransparency'],
},
{
type: 'text',
name: 'Bell Sound URI',
description: 'URI for a custom bell character sound.',
path: ['xterm', 'bellSound'],
nullable: true,
},
{
type: 'enum',
name: 'Bell Style',
description: 'How the terminal will react to the bell character',
path: ['xterm', 'bellStyle'],
enum: ['none', 'sound'],
},
{
type: 'boolean',
name: 'Force End-Of-Line',
description:
'When enabled, any new-line characters (\\n) will be interpreted as carriage-return new-line. (\\r\\n) Typically this is done by the shell program.',
path: ['xterm', 'convertEol'],
},
{
type: 'boolean',
name: 'Disable Stdin',
description: 'Whether input should be disabled',
path: ['xterm', 'disableStdin'],
},
{
type: 'number',
name: 'Letter Spacing',
description: 'The spacing in whole pixels between characters.',
path: ['xterm', 'letterSpacing'],
},
{
type: 'number',
name: 'Line Height',
description:
'Line height, multiplied by the font size to get the height of terminal rows.',
path: ['xterm', 'lineHeight'],
float: true,
},
{
type: 'enum',
name: 'XTerm Log Level',
description: 'Log level for the XTerm library.',
path: ['xterm', 'logLevel'],
enum: ['debug', 'info', 'warn', 'error', 'off'],
},
{
type: 'boolean',
name: 'Macintosh Option Key as Meta Key',
description:
'When enabled, the Option key on Macs will be interpreted as the Meta key.',
path: ['xterm', 'macOptionIsMeta'],
},
{
type: 'boolean',
name: 'Macintosh Option Click Forces Selection',
description:
"Whether holding a modifier key will force normal selection behavior, regardless of whether the terminal is in mouse events mode. This will also prevent mouse events from being emitted by the terminal. For example, this allows you to use xterm.js' regular selection inside tmux with mouse mode enabled.",
path: ['xterm', 'macOptionClickForcesSelection'],
},
{
type: 'number',
name: 'Forced Contrast Ratio',
description:
'Miminum contrast ratio for terminal text. This will alter the foreground color dynamically to ensure the ratio is met. Goes from 1 (do nothing) to 21 (strict black and white).',
path: ['xterm', 'minimumContrastRatio'],
float: true,
},
{
type: 'enum',
name: 'Renderer Type',
description:
'The terminal renderer to use. Canvas is preferred, but a DOM renderer is also available. Note: Letter spacing and cursor blink do not work in the DOM renderer.',
path: ['xterm', 'rendererType'],
enum: ['canvas', 'dom'],
},
{
type: 'boolean',
name: 'Right Click Selects Words',
description: 'Whether to select the word under the cursor on right click.',
path: ['xterm', 'rightClickSelectsWord'],
},
{
type: 'boolean',
name: 'Screen Reader Support',
description:
'Whether screen reader support is enabled. When on this will expose supporting elements in the DOM to support NVDA on Windows and VoiceOver on macOS.',
path: ['xterm', 'screenReaderMode'],
},
{
type: 'number',
name: 'Tab Stop Width',
description: 'The size of tab stops in the terminal.',
path: ['xterm', 'tabStopWidth'],
},
{
type: 'boolean',
name: 'Windows Mode',
description:
"\"Whether 'Windows mode' is enabled. Because Windows backends winpty and conpty operate by doing line wrapping on their side, xterm.js does not have access to wrapped lines. When Windows mode is enabled the following changes will be in effect:\n- Reflow is disabled.\n- Lines are assumed to be wrapped if the last character of the line is not whitespace.",
path: ['xterm', 'windowsMode'],
},
{
type: 'text',
name: 'Word Separator',
description:
'All characters considered word separators. Used for double-click to select word logic. Encoded as JSON in this editor for editing convienience.',
path: ['xterm', 'wordSeparator'],
json: true,
},
]);

View File

@@ -0,0 +1,152 @@
const selectionColorOption = {
type: 'color',
name: 'Selection Color',
description: 'Background color for selected text. Can be transparent.',
path: ['xterm', 'theme', 'selection'],
};
const selectionColorOpacityOption = {
type: 'number',
name: 'Selection Color Opacity',
description:
'Opacity of the selection highlight. A value between 1 (fully opaque) and 0 (fully transparent).',
path: ['wettyVoid'],
float: true,
min: 0,
max: 1,
};
window.inflateOptions([
{
type: 'color',
name: 'Foreground Color',
description: 'The default foreground (text) color.',
path: ['xterm', 'theme', 'foreground'],
},
{
type: 'color',
name: 'Background Color',
description: 'The default background color.',
path: ['xterm', 'theme', 'background'],
},
{
type: 'color',
name: 'Cursor Color',
description: 'Color of the cursor.',
path: ['xterm', 'theme', 'cursor'],
},
{
type: 'color',
name: 'Block Cursor Accent Color',
description:
'The accent color of the cursor, used as the foreground color for block cursors.',
path: ['xterm', 'theme', 'cursorAccent'],
},
selectionColorOption,
selectionColorOpacityOption,
{
type: 'color',
name: 'Black',
description: 'Color for ANSI Black text.',
path: ['xterm', 'theme', 'black'],
},
{
type: 'color',
name: 'Red',
description: 'Color for ANSI Red text.',
path: ['xterm', 'theme', 'red'],
},
{
type: 'color',
name: 'Green',
description: 'Color for ANSI Green text.',
path: ['xterm', 'theme', 'green'],
},
{
type: 'color',
name: 'Yellow',
description: 'Color for ANSI Yellow text.',
path: ['xterm', 'theme', 'yellow'],
},
{
type: 'color',
name: 'Blue',
description: 'Color for ANSI Blue text.',
path: ['xterm', 'theme', 'blue'],
},
{
type: 'color',
name: 'Magenta',
description: 'Color for ANSI Magenta text.',
path: ['xterm', 'theme', 'magenta'],
},
{
type: 'color',
name: 'Cyan',
description: 'Color for ANSI Cyan text.',
path: ['xterm', 'theme', 'cyan'],
},
{
type: 'color',
name: 'White',
description: 'Color for ANSI White text.',
path: ['xterm', 'theme', 'white'],
},
{
type: 'color',
name: 'Bright Black',
description: 'Color for ANSI Bright Black text.',
path: ['xterm', 'theme', 'brightBlack'],
},
{
type: 'color',
name: 'Bright Red',
description: 'Color for ANSI Bright Red text.',
path: ['xterm', 'theme', 'brightRed'],
},
{
type: 'color',
name: 'Bright Green',
description: 'Color for ANSI Bright Green text.',
path: ['xterm', 'theme', 'brightGreen'],
},
{
type: 'color',
name: 'Bright Yellow',
description: 'Color for ANSI Bright Yellow text.',
path: ['xterm', 'theme', 'brightYellow'],
},
{
type: 'color',
name: 'Bright Blue',
description: 'Color for ANSI Bright Blue text.',
path: ['xterm', 'theme', 'brightBlue'],
},
{
type: 'color',
name: 'Bright Magenta',
description: 'Color for ANSI Bright Magenta text.',
path: ['xterm', 'theme', 'brightMagenta'],
},
{
type: 'color',
name: 'Bright White',
description: 'Color for ANSI Bright White text.',
path: ['xterm', 'theme', 'brightWhite'],
},
]);
selectionColorOption.get = function getInput() {
return (
this.el.querySelector('input').value +
Math.round(
selectionColorOpacityOption.el.querySelector('input').value * 255,
).toString(16)
);
};
selectionColorOption.set = function setInput(value) {
this.el.querySelector('input').value = value.substring(0, 7);
selectionColorOpacityOption.el.querySelector('input').value =
Math.round((parseInt(value.substring(7), 16) / 255) * 100) / 100;
};
selectionColorOpacityOption.get = () => 0;
selectionColorOpacityOption.set = () => 0;

View File

@@ -0,0 +1,70 @@
const DEFAULT_BELL_SOUND =
'data:audio/mp3;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjMyLjEwNAAAAAAAAAAAAAAA//tQxAADB8AhSmxhIIEVCSiJrDCQBTcu3UrAIwUdkRgQbFAZC1CQEwTJ9mjRvBA4UOLD8nKVOWfh+UlK3z/177OXrfOdKl7pyn3Xf//WreyTRUoAWgBgkOAGbZHBgG1OF6zM82DWbZaUmMBptgQhGjsyYqc9ae9XFz280948NMBWInljyzsNRFLPWdnZGWrddDsjK1unuSrVN9jJsK8KuQtQCtMBjCEtImISdNKJOopIpBFpNSMbIHCSRpRR5iakjTiyzLhchUUBwCgyKiweBv/7UsQbg8isVNoMPMjAAAA0gAAABEVFGmgqK////9bP/6XCykxBTUUzLjEwMKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq';
window.loadOptions({
wettyFitTerminal: true,
wettyVoid: 0,
xterm: {
cols: 80,
rows: 24,
cursorBlink: false,
cursorStyle: 'block',
cursorWidth: 1,
bellSound: DEFAULT_BELL_SOUND,
bellStyle: 'none',
drawBoldTextInBrightColors: true,
fastScrollModifier: 'alt',
fastScrollSensitivity: 5,
fontFamily: 'courier-new, courier, monospace',
fontSize: 15,
fontWeight: 'normal',
fontWeightBold: 'bold',
lineHeight: 1.0,
linkTooltipHoverDuration: 500,
letterSpacing: 0,
logLevel: 'info',
scrollback: 1000,
scrollSensitivity: 1,
screenReaderMode: false,
macOptionIsMeta: false,
macOptionClickForcesSelection: false,
minimumContrastRatio: 1,
disableStdin: false,
allowProposedApi: true,
allowTransparency: false,
tabStopWidth: 8,
rightClickSelectsWord: false,
rendererType: 'canvas',
windowOptions: {},
windowsMode: false,
wordSeparator: ' ()[]{}\',"`',
convertEol: false,
termName: 'xterm',
cancelEvents: false,
theme: {
foreground: '#ffffff',
background: '#000000',
cursor: '#ffffff',
cursorAccent: '#000000',
selection: '#FFFFFF4D',
black: '#2e3436',
red: '#cc0000',
green: '#4e9a06',
yellow: '#c4a000',
blue: '#3465a4',
magenta: '#75507b',
cyan: '#06989a',
white: '#d3d7cf',
brightBlack: '#555753',
brightRed: '#ef2929',
brightGreen: '#8ae234',
brightYellow: '#fce94f',
brightBlue: '#729fcf',
brightMagenta: '#ad7fa8',
brightCyan: '#34e2e2',
brightWhite: '#eeeeec',
},
},
});

View File

@@ -0,0 +1,136 @@
window.inflateOptions([
{
type: 'text',
name: 'Font Family',
description: 'The font family for terminal text.',
path: ['xterm', 'fontFamily'],
},
{
type: 'number',
name: 'Font Size',
description: 'The font size in CSS pixels for terminal text.',
path: ['xterm', 'fontSize'],
min: 4,
},
{
type: 'enum',
name: 'Regular Font Weight',
description: 'The font weight for non-bold text.',
path: ['xterm', 'fontWeight'],
enum: [
'normal',
'bold',
'100',
'200',
'300',
'400',
'500',
'600',
'700',
'800',
'900',
],
},
{
type: 'enum',
name: 'Bold Font Weight',
description: 'The font weight for bold text.',
path: ['xterm', 'fontWeightBold'],
enum: [
'normal',
'bold',
'100',
'200',
'300',
'400',
'500',
'600',
'700',
'800',
'900',
],
},
{
type: 'boolean',
name: 'Fit Terminal',
description:
'Automatically fits the terminal to the page, overriding terminal columns and rows.',
path: ['wettyFitTerminal'],
},
{
type: 'number',
name: 'Terminal Columns',
description:
'The number of columns in the terminal. Overridden by the Fit Terminal option.',
path: ['xterm', 'cols'],
nullable: true,
},
{
type: 'number',
name: 'Terminal Rows',
description:
'The number of rows in the terminal. Overridden by the Fit Terminal option.',
path: ['xterm', 'rows'],
nullable: true,
},
{
type: 'enum',
name: 'Cursor Style',
description: 'The style of the cursor',
path: ['xterm', 'cursorStyle'],
enum: ['block', 'underline', 'bar'],
},
{
type: 'boolean',
name: 'Blinking Cursor',
description: 'Whether the cursor blinks',
path: ['xterm', 'cursorBlink'],
},
{
type: 'number',
name: 'Bar Cursor Width',
description:
"The width of the cursor in CSS pixels. Only applies when Cursor Style is set to 'bar'.",
path: ['xterm', 'cursorWidth'],
},
{
type: 'boolean',
name: 'Draw Bold Text In Bright Colors',
description: 'Whether to draw bold text in bright colors',
path: ['xterm', 'drawBoldTextInBrightColors'],
},
{
type: 'number',
name: 'Scroll Sensitivity',
description: 'The scroll speed multiplier for regular scrolling.',
path: ['xterm', 'scrollSensitivity'],
float: true,
},
{
type: 'enum',
name: 'Fast Scroll Key',
description: 'The modifier key to hold to multiply scroll speed.',
path: ['xterm', 'fastScrollModifier'],
enum: ['none', 'alt', 'shift', 'ctrl'],
},
{
type: 'number',
name: 'Fast Scroll Multiplier',
description: 'The scroll speed multiplier used for fast scrolling.',
path: ['xterm', 'fastScrollSensitivity'],
float: true,
},
{
type: 'number',
name: 'Scrollback Rows',
description:
'The amount of scrollback rows, rows you can scroll up to after they leave the viewport, to keep.',
path: ['xterm', 'scrollback'],
},
{
type: 'number',
name: 'Tab Stop Width',
description: 'The size of tab stops in the terminal.',
path: ['xterm', 'tabStopWidth'],
},
]);

16
wetty/src/buffer.ts Normal file
View File

@@ -0,0 +1,16 @@
import { createInterface } from 'readline';
ask('Enter your username');
function ask(question: string): Promise<string> {
const rlp = createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise(resolve => {
rlp.question(`${question}: `, answer => {
rlp.close();
resolve(answer);
});
});
}

5
wetty/src/client/dev.ts Normal file
View File

@@ -0,0 +1,5 @@
caches.keys().then(cacheNames => {
cacheNames.forEach(cacheName => {
caches.delete(cacheName);
});
});

72
wetty/src/client/wetty.ts Normal file
View File

@@ -0,0 +1,72 @@
import { dom, library } from '@fortawesome/fontawesome-svg-core';
import { faCogs, faKeyboard } from '@fortawesome/free-solid-svg-icons';
import _ from 'lodash';
import '../assets/scss/styles.scss';
import { disconnect } from './wetty/disconnect';
import { overlay } from './wetty/disconnect/elements';
import { verifyPrompt } from './wetty/disconnect/verify';
import { FileDownloader } from './wetty/download';
import { mobileKeyboard } from './wetty/mobile';
import { socket } from './wetty/socket';
import { terminal, Term } from './wetty/term';
// Setup for fontawesome
library.add(faCogs);
library.add(faKeyboard);
dom.watch();
function onResize(term: Term): () => void {
return function resize() {
term.resizeTerm();
};
}
const term = terminal(socket);
if (_.isUndefined(term)) {
disconnect('终端初始化失败:未找到 #terminal 容器');
} else {
window.addEventListener('beforeunload', verifyPrompt, false);
window.addEventListener('resize', onResize(term), false);
term.resizeTerm();
term.focus();
mobileKeyboard();
const fileDownloader = new FileDownloader();
socket
.on('connect', () => {
if (!_.isNull(overlay)) overlay.style.display = 'none';
})
.on('data', (data: string) => {
const remainingData = fileDownloader.buffer(data);
if (remainingData) {
term.write(remainingData);
}
})
.on('login', () => {
if (!_.isNull(overlay)) overlay.style.display = 'none';
term.writeln('');
term.resizeTerm();
term.focus();
})
.on('logout', disconnect)
.on('disconnect', disconnect)
.on('error', (err: string | null) => {
if (err) disconnect(err);
});
term.onData((data: string) => {
socket.emit('input', data);
});
term.onResize((size: { cols: number; rows: number }) => {
socket.emit('resize', size);
});
socket.connect().catch((error: unknown) => {
const message =
error instanceof Error ? error.message : '连接网关失败,请检查配置';
disconnect(message);
});
}

View File

@@ -0,0 +1,11 @@
import _ from 'lodash';
import { overlay } from './disconnect/elements';
import { verifyPrompt } from './disconnect/verify';
export function disconnect(reason: string): void {
if (_.isNull(overlay)) return;
overlay.style.display = 'block';
const msg = document.getElementById('msg');
if (!_.isUndefined(reason) && !_.isNull(msg)) msg.innerHTML = reason;
window.removeEventListener('beforeunload', verifyPrompt, false);
}

View File

@@ -0,0 +1,5 @@
export const overlay = document.getElementById('overlay');
export const terminal = document.getElementById('terminal');
export const editor = document.querySelector(
'#options .editor',
) as HTMLIFrameElement;

View File

@@ -0,0 +1,4 @@
export function verifyPrompt(e: { returnValue: string }): string {
e.returnValue = 'Are you sure?';
return e.returnValue;
}

View File

@@ -0,0 +1,236 @@
import { expect } from 'chai';
import 'mocha';
import { JSDOM } from 'jsdom';
import * as sinon from 'sinon';
import { FileDownloader } from './download';
const noop = (): void => {}; // eslint-disable-line @typescript-eslint/no-empty-function
describe('FileDownloader', () => {
const FILE_BEGIN = 'BEGIN';
const FILE_END = 'END';
let fileDownloader: FileDownloader;
beforeEach(() => {
const { window } = new JSDOM(`...`);
global.document = window.document;
fileDownloader = new FileDownloader(noop, FILE_BEGIN, FILE_END);
});
afterEach(() => {
sinon.restore();
});
it('should return data before file markers', () => {
const onCompleteFileCallbackStub = sinon.stub(
fileDownloader,
'onCompleteFileCallback',
);
expect(
fileDownloader.buffer(`DATA AT THE LEFT${FILE_BEGIN}FILE${FILE_END}`),
).to.equal('DATA AT THE LEFT');
expect(onCompleteFileCallbackStub.calledOnce).to.be.true;
expect(onCompleteFileCallbackStub.getCall(0).args[0]).to.equal('FILE');
});
it('should return data after file markers', () => {
const onCompleteFileCallbackStub = sinon.stub(
fileDownloader,
'onCompleteFileCallback',
);
expect(
fileDownloader.buffer(`${FILE_BEGIN}FILE${FILE_END}DATA AT THE RIGHT`),
).to.equal('DATA AT THE RIGHT');
expect(onCompleteFileCallbackStub.calledOnce).to.be.true;
expect(onCompleteFileCallbackStub.getCall(0).args[0]).to.equal('FILE');
});
it('should return data before and after file markers', () => {
const onCompleteFileCallbackStub = sinon.stub(
fileDownloader,
'onCompleteFileCallback',
);
expect(
fileDownloader.buffer(
`DATA AT THE LEFT${FILE_BEGIN}FILE${FILE_END}DATA AT THE RIGHT`,
),
).to.equal('DATA AT THE LEFTDATA AT THE RIGHT');
expect(onCompleteFileCallbackStub.calledOnce).to.be.true;
expect(onCompleteFileCallbackStub.getCall(0).args[0]).to.equal('FILE');
});
it('should return data before a beginning marker found', () => {
sinon.stub(fileDownloader, 'onCompleteFileCallback');
expect(fileDownloader.buffer(`DATA AT THE LEFT${FILE_BEGIN}FILE`)).to.equal(
'DATA AT THE LEFT',
);
});
it('should return data after an ending marker found', () => {
const onCompleteFileCallbackStub = sinon.stub(
fileDownloader,
'onCompleteFileCallback',
);
expect(fileDownloader.buffer(`${FILE_BEGIN}FI`)).to.equal('');
expect(fileDownloader.buffer(`LE${FILE_END}DATA AT THE RIGHT`)).to.equal(
'DATA AT THE RIGHT',
);
expect(onCompleteFileCallbackStub.calledOnce).to.be.true;
expect(onCompleteFileCallbackStub.getCall(0).args[0]).to.equal('FILE');
});
it('should buffer across incomplete file begin marker sequence on two calls', () => {
fileDownloader = new FileDownloader(noop, 'BEGIN', 'END');
const onCompleteFileCallbackStub = sinon.stub(
fileDownloader,
'onCompleteFileCallback',
);
expect(fileDownloader.buffer('BEG')).to.equal('');
expect(fileDownloader.buffer('INFILEEND')).to.equal('');
expect(onCompleteFileCallbackStub.calledOnce).to.be.true;
expect(onCompleteFileCallbackStub.getCall(0).args[0]).to.equal('FILE');
});
it('should buffer across incomplete file begin marker sequence on n calls', () => {
fileDownloader = new FileDownloader(noop, 'BEGIN', 'END');
const onCompleteFileCallbackStub = sinon.stub(
fileDownloader,
'onCompleteFileCallback',
);
expect(fileDownloader.buffer('B')).to.equal('');
expect(fileDownloader.buffer('E')).to.equal('');
expect(fileDownloader.buffer('G')).to.equal('');
expect(fileDownloader.buffer('I')).to.equal('');
expect(fileDownloader.buffer('NFILEEND')).to.equal('');
expect(onCompleteFileCallbackStub.calledOnce).to.be.true;
expect(onCompleteFileCallbackStub.getCall(0).args[0]).to.equal('FILE');
});
it('should buffer across incomplete file begin marker sequence with data on the left and right on multiple calls', () => {
fileDownloader = new FileDownloader(noop, 'BEGIN', 'END');
const onCompleteFileCallbackStub = sinon.stub(
fileDownloader,
'onCompleteFileCallback',
);
expect(fileDownloader.buffer('DATA AT THE LEFTB')).to.equal(
'DATA AT THE LEFT',
);
expect(fileDownloader.buffer('E')).to.equal('');
expect(fileDownloader.buffer('G')).to.equal('');
expect(fileDownloader.buffer('I')).to.equal('');
expect(fileDownloader.buffer('NFILEENDDATA AT THE RIGHT')).to.equal(
'DATA AT THE RIGHT',
);
expect(onCompleteFileCallbackStub.calledOnce).to.be.true;
expect(onCompleteFileCallbackStub.getCall(0).args[0]).to.equal('FILE');
});
it('should buffer across incomplete file begin marker sequence then handle false positive', () => {
fileDownloader = new FileDownloader(noop, 'BEGIN', 'END');
const onCompleteFileCallbackStub = sinon.stub(
fileDownloader,
'onCompleteFileCallback',
);
expect(fileDownloader.buffer('DATA AT THE LEFTB')).to.equal(
'DATA AT THE LEFT',
);
expect(fileDownloader.buffer('E')).to.equal('');
expect(fileDownloader.buffer('G')).to.equal('');
// This isn't part of the file_begin marker and should trigger the partial
// file begin marker to be returned with the normal data
expect(fileDownloader.buffer('ZDATA AT THE RIGHT')).to.equal(
'BEGZDATA AT THE RIGHT',
);
expect(onCompleteFileCallbackStub.called).to.be.false;
});
it('should buffer across incomplete file end marker sequence on two calls', () => {
fileDownloader = new FileDownloader(noop, 'BEGIN', 'END');
const mockFilePart1 = 'DATA AT THE LEFTBEGINFILEE';
const mockFilePart2 = 'NDDATA AT THE RIGHT';
const onCompleteFileCallbackStub = sinon.stub(
fileDownloader,
'onCompleteFileCallback',
);
expect(fileDownloader.buffer(mockFilePart1)).to.equal('DATA AT THE LEFT');
expect(fileDownloader.buffer(mockFilePart2)).to.equal('DATA AT THE RIGHT');
expect(onCompleteFileCallbackStub.calledOnce).to.be.true;
expect(onCompleteFileCallbackStub.getCall(0).args[0]).to.equal('FILE');
});
it('should buffer across incomplete file end and file begin marker sequence with data on the left and right on multiple calls', () => {
fileDownloader = new FileDownloader(noop, 'BEGIN', 'END');
const onCompleteFileCallbackStub = sinon.stub(
fileDownloader,
'onCompleteFileCallback',
);
expect(fileDownloader.buffer('DATA AT THE LEFTBE')).to.equal(
'DATA AT THE LEFT',
);
expect(fileDownloader.buffer('G')).to.equal('');
expect(fileDownloader.buffer('I')).to.equal('');
expect(fileDownloader.buffer('NFILEE')).to.equal('');
expect(fileDownloader.buffer('N')).to.equal('');
expect(fileDownloader.buffer('DDATA AT THE RIGHT')).to.equal(
'DATA AT THE RIGHT',
);
expect(onCompleteFileCallbackStub.calledOnce).to.be.true;
expect(onCompleteFileCallbackStub.getCall(0).args[0]).to.equal('FILE');
});
it('should be able to handle multiple files', () => {
fileDownloader = new FileDownloader(noop, 'BEGIN', 'END');
const onCompleteFileCallbackStub = sinon.stub(
fileDownloader,
'onCompleteFileCallback',
);
expect(
fileDownloader.buffer(
'DATA AT THE LEFT' +
'BEGIN' +
'FILE1' +
'END' +
'SECOND DATA' +
'BEGIN',
),
).to.equal('DATA AT THE LEFTSECOND DATA');
expect(onCompleteFileCallbackStub.calledOnce).to.be.true;
expect(onCompleteFileCallbackStub.getCall(0).args[0]).to.equal('FILE1');
expect(fileDownloader.buffer('FILE2')).to.equal('');
expect(fileDownloader.buffer('E')).to.equal('');
expect(fileDownloader.buffer('NDRIGHT')).to.equal('RIGHT');
expect(onCompleteFileCallbackStub.calledTwice).to.be.true;
expect(onCompleteFileCallbackStub.getCall(1).args[0]).to.equal('FILE2');
});
it('should be able to handle multiple files with an ending marker', () => {
fileDownloader = new FileDownloader(noop, 'BEGIN', 'END');
const onCompleteFileCallbackStub = sinon.stub(
fileDownloader,
'onCompleteFileCallback',
);
expect(fileDownloader.buffer('DATA AT THE LEFTBEGINFILE1EN')).to.equal(
'DATA AT THE LEFT',
);
expect(onCompleteFileCallbackStub.calledOnce).to.be.false;
expect(fileDownloader.buffer('DSECOND DATABEGINFILE2EN')).to.equal(
'SECOND DATA',
);
expect(onCompleteFileCallbackStub.calledOnce).to.be.true;
expect(onCompleteFileCallbackStub.getCall(0).args[0]).to.equal('FILE1');
expect(fileDownloader.buffer('D')).to.equal('');
expect(onCompleteFileCallbackStub.calledTwice).to.be.true;
expect(onCompleteFileCallbackStub.getCall(1).args[0]).to.equal('FILE2');
});
});

View File

@@ -0,0 +1,169 @@
import fileType from 'file-type';
import Toastify from 'toastify-js';
const DEFAULT_FILE_BEGIN = '\u001b[5i';
const DEFAULT_FILE_END = '\u001b[4i';
type OnCompleteFile = (bufferCharacters: string) => void;
function onCompleteFile(bufferCharacters: string): void {
let fileNameBase64;
let fileCharacters = bufferCharacters;
if (bufferCharacters.includes(":")) {
[fileNameBase64, fileCharacters] = bufferCharacters.split(":");
}
// Try to decode it as base64, if it fails we assume it's not base64
try {
fileCharacters = window.atob(fileCharacters);
} catch (err) {
// Assuming it's not base64...
}
const bytes = new Uint8Array(fileCharacters.length);
for (let i = 0; i < fileCharacters.length; i += 1) {
bytes[i] = fileCharacters.charCodeAt(i);
}
let mimeType = 'application/octet-stream';
let fileExt = '';
const typeData = fileType(bytes);
if (typeData) {
mimeType = typeData.mime;
fileExt = typeData.ext;
}
// Check if the buffer is ASCII
// Ref: https://stackoverflow.com/a/14313213
// eslint-disable-next-line no-control-regex
else if (/^[\x00-\xFF]*$/.test(fileCharacters)) {
mimeType = 'text/plain';
fileExt = 'txt';
}
let fileName;
try {
if (fileNameBase64 !== undefined) {
fileName = window.atob(fileNameBase64);
}
} catch (err) {
// Filename wasn't base64-encoded so let's ignore it
}
if (fileName === undefined) {
fileName = `file-${new Date()
.toISOString()
.split('.')[0]
.replace(/-/g, '')
.replace('T', '')
.replace(/:/g, '')}${fileExt ? `.${fileExt}` : ''}`;
}
const blob = new Blob([new Uint8Array(bytes.buffer)], {
type: mimeType,
});
const blobUrl = URL.createObjectURL(blob);
Toastify({
text: `Download ready: <a href="${blobUrl}" target="_blank" download="${fileName}">${fileName}</a>`,
duration: 10000,
newWindow: true,
gravity: 'bottom',
position: 'right',
backgroundColor: '#fff',
stopOnFocus: true,
escapeMarkup: false,
}).showToast();
}
export class FileDownloader {
fileBuffer: string[];
fileBegin: string;
fileEnd: string;
partialFileBegin: string;
onCompleteFileCallback: OnCompleteFile;
constructor(
onCompleteFileCallback: OnCompleteFile = onCompleteFile,
fileBegin: string = DEFAULT_FILE_BEGIN,
fileEnd: string = DEFAULT_FILE_END,
) {
this.fileBuffer = [];
this.fileBegin = fileBegin;
this.fileEnd = fileEnd;
this.partialFileBegin = '';
this.onCompleteFileCallback = onCompleteFileCallback;
}
bufferCharacter(character: string): string {
// If we are not currently buffering a file.
if (this.fileBuffer.length === 0) {
// If we are not currently expecting the rest of the fileBegin sequences.
if (this.partialFileBegin.length === 0) {
// If the character is the first character of fileBegin we know to start
// expecting the rest of the fileBegin sequence.
if (character === this.fileBegin[0]) {
this.partialFileBegin = character;
return '';
}
// Otherwise, we just return the character for printing to the terminal.
return character;
}
// We're currently in the state of buffering a beginner marker...
const nextExpectedCharacter =
this.fileBegin[this.partialFileBegin.length];
// If the next character *is* the next character in the fileBegin sequence.
if (character === nextExpectedCharacter) {
this.partialFileBegin += character;
// Do we now have the complete fileBegin sequence.
if (this.partialFileBegin === this.fileBegin) {
this.partialFileBegin = '';
this.fileBuffer = this.fileBuffer.concat(this.fileBegin.split(''));
return '';
}
// Otherwise, we just wait until the next character.
return '';
}
// If the next expected character wasn't found for the fileBegin sequence,
// we need to return all the data that was bufferd in the partialFileBegin
// back to the terminal.
const dataToReturn = this.partialFileBegin + character;
this.partialFileBegin = '';
return dataToReturn;
}
// If we are currently in the state of buffering a file.
this.fileBuffer.push(character);
// If we now have an entire fileEnd marker, we have a complete file!
if (
this.fileBuffer.length >= this.fileBegin.length + this.fileEnd.length &&
this.fileBuffer.slice(-this.fileEnd.length).join('') === this.fileEnd
) {
this.onCompleteFileCallback(
this.fileBuffer
.slice(
this.fileBegin.length,
this.fileBuffer.length - this.fileEnd.length,
)
.join(''),
);
this.fileBuffer = [];
}
return '';
}
buffer(data: string): string {
// This is a optimization to quickly return if we know for
// sure we don't need to loop over each character.
if (
this.fileBuffer.length === 0 &&
this.partialFileBegin.length === 0 &&
data.indexOf(this.fileBegin[0]) === -1
) {
return data;
}
return data.split('').map(this.bufferCharacter.bind(this)).join('');
}
}

View File

@@ -0,0 +1,24 @@
/**
* Flow control client side.
* For low impact on overall throughput simply commits every `ackBytes`
* (default 2^18).
*/
export class FlowControlClient {
public counter = 0;
public ackBytes = 262144;
constructor(ackBytes?: number) {
if (ackBytes) {
this.ackBytes = ackBytes;
}
}
public needsCommit(length: number): boolean {
this.counter += length;
if (this.counter >= this.ackBytes) {
this.counter -= this.ackBytes;
return true;
}
return false;
}
}

View File

@@ -0,0 +1,14 @@
import _ from 'lodash';
export function mobileKeyboard(): void {
const [screen] = Array.from(document.getElementsByClassName('xterm-screen'));
if (_.isNull(screen)) return;
screen.setAttribute('contenteditable', 'true');
screen.setAttribute('spellcheck', 'false');
screen.setAttribute('autocorrect', 'false');
screen.setAttribute('autocomplete', 'false');
screen.setAttribute('autocapitalize', 'false');
/*
term.scrollPort_.screen_.setAttribute('contenteditable', 'false');
*/
}

View File

@@ -0,0 +1,118 @@
export type GatewayAuthType = 'password' | 'privateKey' | 'certificate';
export interface TerminalServerConfig {
id: string;
name?: string;
host: string;
port: number;
username: string;
transportMode?: string;
authType: GatewayAuthType;
password?: string;
privateKey?: string;
passphrase?: string;
certificate?: string;
knownHostFingerprint?: string;
cols?: number;
rows?: number;
}
export interface TerminalRuntimeConfig {
gatewayUrl?: string;
gatewayToken?: string;
selectedServerId?: string;
servers: TerminalServerConfig[];
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function asString(value: unknown): string | undefined {
return typeof value === 'string' ? value : undefined;
}
function asNumber(value: unknown): number | undefined {
return typeof value === 'number' ? value : undefined;
}
function parseServer(input: unknown): TerminalServerConfig | undefined {
if (!isObject(input)) return undefined;
const id = asString(input.id);
const host = asString(input.host);
const username = asString(input.username);
const authType = asString(input.authType) as GatewayAuthType | undefined;
const port = asNumber(input.port);
if (!id || !host || !username || !authType || !port) return undefined;
if (!['password', 'privateKey', 'certificate'].includes(authType)) {
return undefined;
}
return {
id,
host,
port,
username,
authType,
name: asString(input.name),
transportMode: asString(input.transportMode),
password: asString(input.password),
privateKey: asString(input.privateKey),
passphrase: asString(input.passphrase),
certificate: asString(input.certificate),
knownHostFingerprint: asString(input.knownHostFingerprint),
cols: asNumber(input.cols),
rows: asNumber(input.rows),
};
}
/**
* 加载终端运行配置:
* 1) 统一从项目根目录 `terminal.config.json` 读取;
* 2) 使用 `no-store` 避免开发阶段被浏览器缓存;
* 3) 只返回通过最小字段校验的服务器条目,减少运行时协议错误。
*/
export async function loadRuntimeConfig(): Promise<TerminalRuntimeConfig> {
const response = await fetch('/terminal.config.json', {
cache: 'no-store',
});
if (!response.ok) {
throw new Error(`读取 terminal.config.json 失败: HTTP ${response.status}`);
}
const data = (await response.json()) as unknown;
if (!isObject(data)) {
throw new Error('terminal.config.json 格式错误: 顶层必须是对象');
}
const serversInput = Array.isArray(data.servers) ? data.servers : [];
const servers = serversInput
.map(parseServer)
.filter((item): item is TerminalServerConfig => Boolean(item));
if (servers.length === 0) {
throw new Error('terminal.config.json 格式错误: servers 不能为空');
}
return {
gatewayUrl: asString(data.gatewayUrl),
gatewayToken: asString(data.gatewayToken),
selectedServerId: asString(data.selectedServerId),
servers,
};
}
export function selectServer(
config: TerminalRuntimeConfig,
): TerminalServerConfig {
if (config.selectedServerId) {
const selected = config.servers.find(
(server) => server.id === config.selectedServerId,
);
if (selected) return selected;
}
return config.servers[0];
}

View File

@@ -0,0 +1,273 @@
import { loadRuntimeConfig, selectServer } from './runtimeConfig';
type SocketEvent =
| 'connect'
| 'login'
| 'data'
| 'logout'
| 'disconnect'
| 'error';
type EventPayloadMap = {
connect: [];
login: [];
data: [string];
logout: [string];
disconnect: [string];
error: [string];
};
type EventHandler<K extends SocketEvent> = (...args: EventPayloadMap[K]) => void;
type EmitEvent = 'input' | 'resize' | 'commit';
interface ResizePayload {
cols: number;
rows: number;
}
interface GatewayFrame {
type: string;
payload?: Record<string, unknown>;
}
interface GatewaySocketOptions {
cols: number;
rows: number;
}
export interface TermSocketLike {
emit(event: EmitEvent, payload: string | number | ResizePayload): void;
}
export class GatewaySocket {
private ws: WebSocket | null = null;
private options: GatewaySocketOptions = { cols: 80, rows: 24 };
private initialized = false;
private handlers = new Map<SocketEvent, Set<(...args: unknown[]) => void>>();
public on<K extends SocketEvent>(event: K, handler: EventHandler<K>): this {
if (!this.handlers.has(event)) {
this.handlers.set(event, new Set<(...args: unknown[]) => void>());
}
this.handlers.get(event)?.add(handler as (...args: unknown[]) => void);
return this;
}
public emit(
event: EmitEvent,
payload: string | number | ResizePayload,
): void {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
if (!this.initialized && event !== 'resize') return;
if (event === 'input' && typeof payload === 'string') {
this.sendFrame({
type: 'stdin',
payload: { data: payload, meta: { source: 'keyboard' } },
});
return;
}
if (
event === 'resize' &&
typeof payload === 'object' &&
payload !== null &&
typeof (payload as ResizePayload).cols === 'number' &&
typeof (payload as ResizePayload).rows === 'number'
) {
const size = payload as ResizePayload;
this.options = { cols: size.cols, rows: size.rows };
this.sendFrame({
type: 'resize',
payload: size as unknown as Record<string, unknown>,
});
}
}
public async connect(): Promise<void> {
try {
const runtime = await loadRuntimeConfig();
const selectedServer = selectServer(runtime);
this.options = {
cols: selectedServer.cols ?? 80,
rows: selectedServer.rows ?? 24,
};
const wsUrl = GatewaySocket.buildGatewayWsUrl(
runtime.gatewayUrl,
runtime.gatewayToken,
);
this.ws = new WebSocket(wsUrl);
this.ws.addEventListener('open', () => {
this.fire('connect');
this.sendFrame({
type: 'init',
payload: this.buildInitPayload(selectedServer),
});
});
this.ws.addEventListener('message', (event) => {
this.handleMessage(event.data);
});
this.ws.addEventListener('close', (event) => {
const reason = event.reason || `连接已关闭 (code=${event.code})`;
if (this.initialized) {
this.fire('logout', reason);
}
this.fire('disconnect', reason);
this.initialized = false;
this.ws = null;
});
this.ws.addEventListener('error', () => {
this.fire('error', '网关连接异常');
});
} catch (error) {
this.fire(
'error',
error instanceof Error ? error.message : '初始化网关连接失败',
);
}
}
private static buildGatewayWsUrl(
rawUrl: string | undefined,
token?: string,
): string {
const defaultProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const defaultUrl = `${defaultProtocol}//${window.location.hostname}:8787`;
const normalized = rawUrl && rawUrl.trim() ? rawUrl : defaultUrl;
const url = new URL(normalized);
if (url.protocol !== 'ws:' && url.protocol !== 'wss:') {
url.protocol = defaultProtocol;
}
url.pathname = '/ws/terminal';
if (token) {
url.searchParams.set('token', token);
}
return url.toString();
}
/**
* 构建 gateway init 帧:
* 1) 认证信息按 authType 映射到协议要求字段;
* 2) `clientSessionKey` 固定化,支持网关侧短时断线续接;
* 3) 初始窗口大小从配置注入,后续再由 xterm resize 覆盖。
*/
private buildInitPayload(
server: Awaited<ReturnType<typeof selectServer>>,
): Record<string, unknown> {
const clientSessionKey = `${server.id}:${server.username}@${server.host}:${server.port}`;
const payload: Record<string, unknown> = {
host: server.host,
port: server.port,
username: server.username,
clientSessionKey,
pty: {
cols: this.options.cols,
rows: this.options.rows,
},
};
if (server.knownHostFingerprint) {
payload.knownHostFingerprint = server.knownHostFingerprint;
}
if (server.authType === 'password') {
payload.credential = {
type: 'password',
password: server.password || '',
};
return payload;
}
if (server.authType === 'privateKey') {
payload.credential = {
type: 'privateKey',
privateKey: server.privateKey || '',
...server.passphrase ? { passphrase: server.passphrase } : {},
};
return payload;
}
payload.credential = {
type: 'certificate',
privateKey: server.privateKey || '',
certificate: server.certificate || '',
...server.passphrase ? { passphrase: server.passphrase } : {},
};
return payload;
}
private handleMessage(raw: string | Blob | ArrayBuffer): void {
let data = '';
if (typeof raw === 'string') {
data = raw;
} else if (raw instanceof ArrayBuffer) {
data = new TextDecoder().decode(raw);
} else {
return;
}
let frame: GatewayFrame;
try {
frame = JSON.parse(data) as GatewayFrame;
} catch {
return;
}
if (!frame || typeof frame.type !== 'string') return;
if (frame.type === 'stdout' || frame.type === 'stderr') {
const text = `${frame.payload?.data || ''}`;
if (text) this.fire('data', text);
return;
}
if (frame.type === 'error') {
const msg = `${frame.payload?.message || '网关返回错误'}`;
this.fire('error', msg);
return;
}
if (frame.type === 'control') {
const action = `${frame.payload?.action || ''}`;
if (action === 'ping') {
this.sendFrame({ type: 'control', payload: { action: 'pong' } });
return;
}
if (action === 'connected') {
if (!this.initialized) {
this.initialized = true;
this.fire('login');
}
return;
}
if (action === 'disconnect') {
const reason = `${frame.payload?.reason || '连接已断开'}`;
this.fire('logout', reason);
}
}
}
private sendFrame(frame: GatewayFrame): void {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
this.ws.send(JSON.stringify(frame));
}
private fire<K extends SocketEvent>(
event: K,
...args: EventPayloadMap[K]
): void {
this.handlers.get(event)?.forEach((handler) => {
handler(...args);
});
}
}
export const socket = new GatewaySocket();

View File

@@ -0,0 +1,236 @@
import { FitAddon } from '@xterm/addon-fit';
import { ImageAddon } from '@xterm/addon-image';
import { WebLinksAddon } from '@xterm/addon-web-links';
import { Terminal } from '@xterm/xterm';
import _ from 'lodash';
import { terminal as termElement } from './disconnect/elements';
import { configureTerm } from './term/confiruragtion';
import { loadOptions } from './term/load';
import type { TermSocketLike } from './socket';
import type { Options } from './term/options';
export class Term extends Terminal {
socket: TermSocketLike;
fitAddon: FitAddon;
loadOptions: () => Options;
constructor(socket: TermSocketLike) {
super({ allowProposedApi: true });
this.socket = socket;
this.fitAddon = new FitAddon();
this.loadAddon(this.fitAddon);
this.loadAddon(new WebLinksAddon());
this.loadAddon(new ImageAddon());
this.loadOptions = loadOptions;
}
resizeTerm(): void {
this.refresh(0, this.rows - 1);
if (this.shouldFitTerm) this.fitAddon.fit();
this.socket.emit('resize', { cols: this.cols, rows: this.rows });
}
get shouldFitTerm(): boolean {
return this.loadOptions().wettyFitTerminal ?? true;
}
}
const ctrlButton = document.getElementById('onscreen-ctrl');
let ctrlFlag = false; // This indicates whether the CTRL key is pressed or not
/**
* Toggles the state of the `ctrlFlag` variable and updates the visual state
* of the `ctrlButton` element accordingly. If `ctrlFlag` is set to `true`,
* the `active` class is added to the `ctrlButton`; otherwise, it is removed.
* After toggling, the terminal (`wetty_term`) is focused if it exists.
*/
const toggleCTRL = (): void => {
ctrlFlag = !ctrlFlag;
if (ctrlButton) {
if (ctrlFlag) {
ctrlButton.classList.add('active');
} else {
ctrlButton.classList.remove('active');
}
}
window.wetty_term?.focus();
}
/**
* Simulates a backspace key press by sending the backspace character
* (ASCII code 127) to the terminal. This function is intended to be used
* in conjunction with the `simulateCTRLAndKey` function to handle
* keyboard shortcuts.
*
*/
const simulateBackspace = (): void => {
window.wetty_term?.input('\x7F', true);
}
/**
* Simulates a CTRL + key press by sending the corresponding character
* (converted from the key's ASCII code) to the terminal. This function
* is intended to be used in conjunction with the `toggleCTRL` function
* to handle keyboard shortcuts.
*
* @param key - The key that was pressed, which will be converted to
* its corresponding character code.
*/
const simulateCTRLAndKey = (key: string): void => {
window.wetty_term?.input(`${String.fromCharCode(key.toUpperCase().charCodeAt(0) - 64)}`, false);
}
/**
* Handles the keydown event for the CTRL key. When the CTRL key is pressed,
* it sets the `ctrlFlag` variable to true and updates the visual state of
* the `ctrlButton` element. If the CTRL key is released, it sets `ctrlFlag`
* to false and updates the visual state of the `ctrlButton` element.
*
* @param e - The keyboard event object.
*/
document.addEventListener('keyup', (e) => {
if (ctrlFlag) {
// if key is a character
if (e.key.length === 1 && e.key.match(/^[a-zA-Z0-9]$/)) {
simulateCTRLAndKey(e.key);
// delayed backspace is needed to remove the character added to the terminal
// when CTRL + key is pressed.
// this is a workaround because e.preventDefault() cannot be used.
_.debounce(() => {
simulateBackspace();
}, 100)();
}
toggleCTRL();
}
});
/**
* Simulates pressing the ESC key by sending the ESC character (ASCII code 27)
* to the terminal. If the CTRL key is active, it toggles the CTRL state off.
* After sending the ESC character, the terminal is focused.
*/
const pressESC = (): void => {
if (ctrlFlag) {
toggleCTRL();
}
window.wetty_term?.input('\x1B', false);
window.wetty_term?.focus();
}
/**
* Simulates pressing the UP arrow key by sending the UP character (ASCII code 65)
* to the terminal. If the CTRL key is active, it toggles the CTRL state off.
* After sending the UP character, the terminal is focused.
*/
const pressUP = (): void => {
if (ctrlFlag) {
toggleCTRL();
}
window.wetty_term?.input('\x1B[A', false);
window.wetty_term?.focus();
}
/**
* Simulates pressing the DOWN arrow key by sending the DOWN character (ASCII code 66)
* to the terminal. If the CTRL key is active, it toggles the CTRL state off.
* After sending the DOWN character, the terminal is focused.
*/
const pressDOWN = (): void => {
if (ctrlFlag) {
toggleCTRL();
}
window.wetty_term?.input('\x1B[B', false);
window.wetty_term?.focus();
}
/**
* Simulates pressing the TAB key by sending the TAB character (ASCII code 9)
* to the terminal. If the CTRL key is active, it toggles the CTRL state off.
* After sending the TAB character, the terminal is focused.
*/
const pressTAB = (): void => {
if (ctrlFlag) {
toggleCTRL();
}
window.wetty_term?.input('\x09', false);
window.wetty_term?.focus();
}
/**
* Simulates pressing the LEFT arrow key by sending the LEFT character (ASCII code 68)
* to the terminal. If the CTRL key is active, it toggles the CTRL state off.
* After sending the LEFT character, the terminal is focused.
*/
const pressLEFT = (): void => {
if (ctrlFlag) {
toggleCTRL();
}
window.wetty_term?.input('\x1B[D', false);
window.wetty_term?.focus();
}
/**
* Simulates pressing the RIGHT arrow key by sending the RIGHT character (ASCII code 67)
* to the terminal. If the CTRL key is active, it toggles the CTRL state off.
* After sending the RIGHT character, the terminal is focused.
*/
const pressRIGHT = (): void => {
if (ctrlFlag) {
toggleCTRL();
}
window.wetty_term?.input('\x1B[C', false);
window.wetty_term?.focus();
}
/**
* Toggles the visibility of the onscreen buttons by adding or removing
* the 'active' class to the element with the ID 'onscreen-buttons'.
*/
const toggleFunctions = (): void => {
const element = document.querySelector('div#functions > div.onscreen-buttons')
if (element?.classList.contains('active')) {
element?.classList.remove('active');
} else {
element?.classList.add('active');
}
}
declare global {
interface Window {
wetty_term?: Term;
wetty_close_config?: () => void;
wetty_save_config?: (newConfig: Options) => void;
clipboardData: DataTransfer;
loadOptions: (conf: Options) => void;
toggleFunctions?: () => void;
toggleCTRL? : () => void;
pressESC?: () => void;
pressUP?: () => void;
pressDOWN?: () => void;
pressTAB?: () => void;
pressLEFT?: () => void;
pressRIGHT?: () => void;
}
}
export function terminal(socket: TermSocketLike): Term | undefined {
const term = new Term(socket);
if (_.isNull(termElement)) return undefined;
termElement.innerHTML = '';
term.open(termElement);
configureTerm(term);
window.onresize = function onResize() {
term.resizeTerm();
};
window.wetty_term = term;
window.toggleFunctions = toggleFunctions;
window.toggleCTRL = toggleCTRL;
window.pressESC = pressESC;
window.pressUP = pressUP;
window.pressDOWN = pressDOWN;
window.pressTAB = pressTAB;
window.pressLEFT = pressLEFT;
window.pressRIGHT = pressRIGHT;
return term;
}

View File

@@ -0,0 +1,77 @@
import { editor } from '../disconnect/elements';
import { copySelected, copyShortcut } from './confiruragtion/clipboard';
import { onInput } from './confiruragtion/editor';
import { loadOptions } from './load';
import type { Options } from './options';
import type { Term } from '../term';
export function configureTerm(term: Term): void {
const options = loadOptions();
try {
term.options = options.xterm;
} catch {
/* Do nothing */
}
const toggle = document.querySelector('#options .toggler');
const optionsElem = document.getElementById('options');
if (editor == null || toggle == null || optionsElem == null) {
throw new Error("Couldn't initialize configuration menu");
}
/**
* 将当前配置同步给 iframe 配置面板,并注入回调钩子。
* 返回值表示 iframe 是否已准备好接收配置loadOptions 已可调用)。
*/
const syncEditor = (): boolean => {
const editorWindow = editor.contentWindow;
if (!editorWindow || typeof editorWindow.loadOptions !== 'function') {
return false;
}
editorWindow.loadOptions(loadOptions());
editorWindow.wetty_close_config = () => {
optionsElem?.classList.toggle('opened');
};
editorWindow.wetty_save_config = (newConfig: Options) => {
onInput(term, newConfig);
};
return true;
};
function editorOnLoad() {
if (syncEditor()) return;
// 某些浏览器/开发模式下iframe 的脚本初始化会略晚于 load 事件。
setTimeout(() => {
syncEditor();
}, 50);
}
if (
(
editor.contentDocument ||
(editor.contentWindow?.document ?? {
readyState: '',
})
).readyState === 'complete'
) {
editorOnLoad();
}
editor.addEventListener('load', editorOnLoad);
toggle.addEventListener('click', e => {
syncEditor();
optionsElem.classList.toggle('opened');
e.preventDefault();
});
term.attachCustomKeyEventHandler(copyShortcut);
document.addEventListener(
'mouseup',
() => {
if (term.hasSelection()) copySelected(term.getSelection());
},
false,
);
}

View File

@@ -0,0 +1,40 @@
/**
Copy text selection to clipboard on double click or select
@param text - the selected text to copy
@returns boolean to indicate success or failure
*/
export function copySelected(text: string): boolean {
if (window.clipboardData?.setData) {
window.clipboardData.setData('Text', text);
return true;
}
if (
document.queryCommandSupported &&
document.queryCommandSupported('copy')
) {
const textarea = document.createElement('textarea');
textarea.textContent = text;
textarea.style.position = 'fixed';
document.body.appendChild(textarea);
textarea.select();
try {
document.execCommand('copy');
return true;
} catch (ex) {
return false;
} finally {
document.body.removeChild(textarea);
}
}
return false;
}
export function copyShortcut(e: KeyboardEvent): boolean {
// Ctrl + Shift + C
if (e.ctrlKey && e.shiftKey && e.keyCode === 67) {
e.preventDefault();
document.execCommand('copy');
return false;
}
return true;
}

View File

@@ -0,0 +1,23 @@
import { editor } from '../../disconnect/elements';
import type { Term } from '../../term';
import type { Options } from '../options';
export const onInput = (term: Term, updated: Options) => {
try {
const updatedConf = JSON.stringify(updated, null, 2);
if (localStorage.options === updatedConf) return;
term.options = updated.xterm;
if (
!updated.wettyFitTerminal &&
updated.xterm.cols != null &&
updated.xterm.rows != null
)
term.resize(updated.xterm.cols, updated.xterm.rows);
term.resizeTerm();
editor.classList.remove('error');
localStorage.options = updatedConf;
} catch (e) {
console.error('Configuration Error', e); // eslint-disable-line no-console
editor.classList.add('error');
}
};

View File

@@ -0,0 +1,25 @@
import _ from 'lodash';
import type { XTerm, Options } from './options';
export const defaultOptions: Options = {
xterm: { fontSize: 14 },
wettyVoid: 0,
wettyFitTerminal: true,
};
export function loadOptions(): Options {
try {
let options = _.isUndefined(localStorage.options)
? defaultOptions
: JSON.parse(localStorage.options);
// Convert old options to new options
if (!('xterm' in options)) {
const xterm = options;
options = defaultOptions;
options.xterm = xterm as unknown as XTerm;
}
return options;
} catch {
return defaultOptions;
}
}

View File

@@ -0,0 +1,11 @@
export type XTerm = {
cols?: number;
rows?: number;
fontSize: number;
} & Record<string, unknown>;
export interface Options {
xterm: XTerm;
wettyFitTerminal: boolean;
wettyVoid: number;
}

160
wetty/src/main.ts Normal file
View File

@@ -0,0 +1,160 @@
#!/usr/bin/env node
/**
* Create WeTTY server
* @module WeTTy
*
* This is the cli Interface for wetty.
*/
import { unlinkSync, existsSync, lstatSync } from 'fs';
import { createRequire } from 'module';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import { start } from './server.js';
import { loadConfigFile, mergeCliConf } from './shared/config.js';
import { setLevel, logger } from './shared/logger.js';
/* eslint-disable @typescript-eslint/no-var-requires */
const require = createRequire(import.meta.url);
const packageJson = require('../package.json');
const opts = yargs(hideBin(process.argv))
.scriptName(packageJson.name)
.version(packageJson.version)
.options('conf', {
type: 'string',
description: 'config file to load config from',
})
.option('ssl-key', {
type: 'string',
description: 'path to SSL key',
})
.option('ssl-cert', {
type: 'string',
description: 'path to SSL certificate',
})
.option('ssh-host', {
description: 'ssh server host',
type: 'string',
})
.option('ssh-port', {
description: 'ssh server port',
type: 'number',
})
.option('ssh-user', {
description: 'ssh user',
type: 'string',
})
.option('title', {
description: 'window title',
type: 'string',
})
.option('ssh-auth', {
description:
'defaults to "password", you can use "publickey,password" instead',
type: 'string',
})
.option('ssh-pass', {
description: 'ssh password',
type: 'string',
})
.option('ssh-key', {
demand: false,
description:
'path to an optional client private key (connection will be password-less and insecure!)',
type: 'string',
})
.option('ssh-config', {
description:
'Specifies an alternative ssh configuration file. For further details see "-F" option in ssh(1)',
type: 'string',
})
.option('force-ssh', {
description: 'Connecting through ssh even if running as root',
type: 'boolean',
})
.option('known-hosts', {
description: 'path to known hosts file',
type: 'string',
})
.option('base', {
alias: 'b',
description: 'base path to wetty',
type: 'string',
})
.option('port', {
alias: 'p',
description: 'wetty listen port',
type: 'number',
})
.option('host', {
description: 'wetty listen host',
type: 'string',
})
.option('socket', {
description: 'Make wetty listen on unix socket',
type: 'string',
})
.option('command', {
alias: 'c',
description: 'command to run in shell',
type: 'string',
})
.option('allow-iframe', {
description:
'Allow WeTTY to be embedded in an iframe, defaults to allowing same origin',
type: 'boolean',
})
.option('allow-remote-hosts', {
description:
'Allow WeTTY to use the `host` and `port` params in a url as ssh destination',
type: 'boolean',
})
.option('allow-remote-command', {
description:
'Allow WeTTY to use the `command` and `path` params in a url as command and working directory on ssh host',
type: 'boolean',
})
.option('log-level', {
description: 'set log level of wetty server',
type: 'string',
})
.option('help', {
alias: 'h',
type: 'boolean',
description: 'Print help message',
})
.conflicts('host', 'socket')
.conflicts('port', 'socket')
.boolean('allow_discovery')
.parseSync();
function cleanup() {
if (opts.socket) {
const socket = opts.socket.toString();
if (existsSync(socket) && lstatSync(socket).isSocket()) {
unlinkSync(socket);
}
}
}
function exit() {
process.exit(1);
}
if (!opts.help) {
process.on('SIGINT', exit);
process.on('exit', cleanup);
loadConfigFile(opts.conf)
.then((config) => mergeCliConf(opts, config))
.then((conf) => {
setLevel(conf.logLevel);
start(conf.ssh, conf.server, conf.command, conf.forceSSH, conf.ssl);
})
.catch((err: Error) => {
logger().error('error in server', { err });
process.exitCode = 1;
});
} else {
yargs.showHelp();
process.exitCode = 0;
}

88
wetty/src/server.ts Normal file
View File

@@ -0,0 +1,88 @@
/**
* Create WeTTY server
* @module WeTTy
*/
import express from 'express';
import gc from 'gc-stats';
import { Gauge, collectDefaultMetrics } from 'prom-client';
import { getCommand } from './server/command.js';
import { gcMetrics } from './server/metrics.js';
import { server } from './server/socketServer.js';
import { spawn } from './server/spawn.js';
import {
sshDefault,
serverDefault,
forceSSHDefault,
defaultCommand,
} from './shared/defaults.js';
import { logger as getLogger } from './shared/logger.js';
import type { SSH, SSL, Server } from './shared/interfaces.js';
import type { Express } from 'express';
import type SocketIO from 'socket.io';
export * from './shared/interfaces.js';
export { logger as getLogger } from './shared/logger.js';
const wettyConnections = new Gauge({
name: 'wetty_connections',
help: 'number of active socket connections to wetty',
});
/**
* Starts WeTTy Server
* @name startServer
* @returns Promise that resolves SocketIO server
*/
export const start = (
ssh: SSH = sshDefault,
serverConf: Server = serverDefault,
command: string = defaultCommand,
forcessh: boolean = forceSSHDefault,
ssl: SSL | undefined = undefined,
): Promise<SocketIO.Server> =>
decorateServerWithSsh(express(), ssh, serverConf, command, forcessh, ssl);
export async function decorateServerWithSsh(
app: Express,
ssh: SSH = sshDefault,
serverConf: Server = serverDefault,
command: string = defaultCommand,
forcessh: boolean = forceSSHDefault,
ssl: SSL | undefined = undefined,
): Promise<SocketIO.Server> {
const logger = getLogger();
if (ssh.key) {
logger.warn(`!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
! Password-less auth enabled using private key from ${ssh.key}.
! This is dangerous, anything that reaches the wetty server
! will be able to run remote operations without authentication.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!`);
}
collectDefaultMetrics();
gc().on('stats', gcMetrics);
const io = await server(app, serverConf, ssl);
/**
* Wetty server connected too
* @fires WeTTy#connnection
*/
io.on('connection', async (socket: SocketIO.Socket) => {
/**
* @event wetty#connection
* @name connection
*/
logger.info('Connection accepted.');
wettyConnections.inc();
try {
const args = await getCommand(socket, ssh, command, forcessh);
logger.debug('Command Generated', { cmd: args.join(' ') });
await spawn(socket, args);
} catch (error) {
logger.info('Disconnect signal sent', { err: error });
wettyConnections.dec();
}
});
return io;
}

View File

@@ -0,0 +1,70 @@
import process from 'node:process';
import url from 'url';
import _ from 'lodash';
import { address } from './command/address.js';
import { loginOptions } from './command/login.js';
import { sshOptions } from './command/ssh.js';
import type { SSH } from '../shared/interfaces';
import type { Socket } from 'socket.io';
const localhost = (host: string): boolean =>
!_.isUndefined(process.getuid) &&
process.getuid() === 0 &&
(host === 'localhost' || host === '0.0.0.0' || host === '127.0.0.1');
const urlArgs = (
referer: string | undefined,
{
allowRemoteCommand,
allowRemoteHosts,
}: {
allowRemoteCommand: boolean;
allowRemoteHosts: boolean;
},
): { [s: string]: string } =>
_.pick(
_.pickBy(url.parse(referer || '', true).query, _.isString),
['pass'],
allowRemoteCommand ? ['command', 'path'] : [],
allowRemoteHosts ? ['port', 'host'] : [],
);
export async function getCommand(
socket: Socket,
{
user,
host,
port,
auth,
pass,
key,
knownHosts,
config,
allowRemoteHosts,
allowRemoteCommand,
}: SSH,
command: string,
forcessh: boolean
): Promise<string[]> {
const {
request: { headers: { referer } },
client: { conn: { remoteAddress } },
} = socket;
if (!forcessh && localhost(host)) {
return loginOptions(command, remoteAddress);
}
const sshAddress = await address(socket, user, host);
const args = {
host: sshAddress,
port: `${port}`,
pass: pass || '',
command,
auth,
knownHosts,
config: config || '',
...urlArgs(referer, { allowRemoteHosts, allowRemoteCommand }),
};
return sshOptions(args, key);
}

View File

@@ -0,0 +1,32 @@
import _ from 'lodash';
import { Socket } from 'socket.io';
import { login } from '../login.js';
import { escapeShell } from '../shared/shell.js';
export async function address(
socket: Socket,
user: string,
host: string,
): Promise<string> {
// Check request-header for username
const { request: { headers: {
'remote-user': userFromHeader,
referer
} } } = socket;
let username: string | undefined;
if (!_.isUndefined(userFromHeader) && !Array.isArray(userFromHeader)) {
username = userFromHeader;
} else {
const userFromPathMatch = referer?.match('.+/ssh/([^/]+)$');
if (userFromPathMatch) {
// eslint-disable-next-line prefer-destructuring
username = userFromPathMatch[1].split('?')[0];
} else if (user) {
username = user;
} else {
username = await login(socket);
}
}
return `${escapeShell(username)}@${host}`;
}

Some files were not shown because too many files have changed in this diff Show More