This commit is contained in:
Eugene Pankov
2021-06-14 23:00:05 +02:00
parent dc69574c07
commit e1425c6c80
32 changed files with 1502 additions and 422 deletions

21
src/app.module.ts Normal file
View File

@@ -0,0 +1,21 @@
import { NgModule } from '@angular/core';
import { NgbDropdownModule } from '@ng-bootstrap/ng-bootstrap'
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule, HttpClientXsrfModule } from '@angular/common/http'
import { AppComponent } from './components/app.component'
@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
HttpClientXsrfModule,
NgbDropdownModule,
],
declarations: [
AppComponent,
],
bootstrap: [AppComponent]
})
export class AppModule { }

1
src/assets/logo.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="Layer_1" x="0" y="0" version="1.1" viewBox="0 0 1024 1024" xml:space="preserve" style="enable-background:new 0 0 1024 1024"><style type="text/css">.st0{fill:url(#SVGID_1_)}.st1{opacity:.16;fill:url(#SVGID_2_)}.st2{fill:url(#SVGID_3_)}.st3{opacity:.16;fill:url(#SVGID_4_)}.st4{fill:url(#SVGID_5_)}.st5{opacity:.15;fill:url(#SVGID_6_)}.st6{fill:url(#SVGID_7_)}</style><g><linearGradient id="SVGID_1_" x1="260.967" x2="919.184" y1="871.181" y2="491.16" gradientUnits="userSpaceOnUse"><stop offset="0" style="stop-color:#669abd"/><stop offset="1" style="stop-color:#77dbdb"/></linearGradient><polygon points="297.54 934.52 882.6 596.72 882.61 427.82 297.54 765.65" class="st0"/><linearGradient id="SVGID_2_" x1="553.505" x2="626.647" y1="617.828" y2="744.513" gradientUnits="userSpaceOnUse"><stop offset=".559" style="stop-color:#000;stop-opacity:0"/><stop offset="1" style="stop-color:#000"/></linearGradient><polygon points="297.54 934.52 882.6 596.72 882.61 427.82 297.54 765.65" class="st1"/></g><g><linearGradient id="SVGID_3_" x1="114.663" x2="334.091" y1="744.528" y2="871.214" gradientUnits="userSpaceOnUse"><stop offset="0" style="stop-color:#6a8fad"/><stop offset="1" style="stop-color:#669abd"/></linearGradient><polygon points="151.23 681.18 151.22 850.09 297.54 934.52 297.54 765.65" class="st2"/><linearGradient id="SVGID_4_" x1="260.948" x2="187.806" y1="744.528" y2="871.213" gradientUnits="userSpaceOnUse"><stop offset=".559" style="stop-color:#000;stop-opacity:0"/><stop offset="1" style="stop-color:#000"/></linearGradient><polygon points="151.23 681.18 151.22 850.09 297.54 934.52 297.54 765.65" class="st3"/></g><g><linearGradient id="SVGID_5_" x1="114.663" x2="553.503" y1="237.793" y2="491.157" gradientUnits="userSpaceOnUse"><stop offset="0" style="stop-color:#6a8fad"/><stop offset="1" style="stop-color:#669abd"/></linearGradient><polygon points="151.23 174.45 151.21 343.36 443.79 512.27 590.08 427.81" class="st4"/><linearGradient id="SVGID_6_" x1="370.656" x2="297.509" y1="301.128" y2="427.822" gradientUnits="userSpaceOnUse"><stop offset=".559" style="stop-color:#000;stop-opacity:0"/><stop offset="1" style="stop-color:#000"/></linearGradient><polygon points="151.23 174.45 151.21 343.36 443.79 512.27 590.08 427.81" class="st5"/></g><linearGradient id="SVGID_7_" x1="78.091" x2="736.337" y1="554.498" y2="174.459" gradientUnits="userSpaceOnUse"><stop offset="0" style="stop-color:#ccecff"/><stop offset="1" style="stop-color:#9feced"/></linearGradient><polygon points="297.51 765.64 151.23 681.18 590.08 427.81 151.23 174.45 297.5 90 882.61 427.82" class="st6"/></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@@ -0,0 +1,15 @@
.sidebar
img.logo(src='{{_logo}}')
div(ngbDropdown)
button.btn.btn-secondary(ngbDropdownToggle) Cfg
//) !{require('../icons/download-solid.svg')}
div(ngbDropdownMenu)
a(
*ngFor='let config of configs',
ngbDropdownItem,
(click)='selectConfig(config)'
) Config modified at {{config.modified_at}}
.terminal([hidden]='!showApp')
iframe(#iframe)

View File

@@ -0,0 +1,34 @@
:host {
position: absolute;
left: 0;
top: 0;
width: 100vw;
height: 100vh;
overflow: hidden;
display: flex;
}
.sidebar {
width: 64px;
flex: none;
.logo {
width: 64px;
height: 64px;
}
}
.terminal {
flex: 1 1 0;
overflow: hidden;
position: relative;
}
iframe {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
border: none;
}

View File

@@ -0,0 +1,50 @@
import { Component, ElementRef, ViewChild } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { AppConnectorService } from '../services/appConnector.service'
@Component({
selector: 'app',
templateUrl: './app.component.pug',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
_logo = require('../assets/logo.svg')
showApp = false
configs: any[] = []
@ViewChild('iframe') iframe: ElementRef
constructor (
private appConnector: AppConnectorService,
private http: HttpClient,
) {
window.addEventListener('message', event => {
if (event.data === 'request-connector') {
this.iframe.nativeElement.contentWindow['__connector__'] = this.appConnector
this.iframe.nativeElement.contentWindow.postMessage('connector-ready', '*')
}
})
}
async ngAfterViewInit () {
this.configs = await this.http.get('/api/1/configs').toPromise()
this.selectConfig(this.configs[0])
}
unloadApp () {
this.showApp = false
this.iframe.nativeElement.src = 'about:blank'
}
loadApp () {
this.iframe.nativeElement.src = '/terminal'
this.showApp = true
}
selectConfig (config: any) {
this.appConnector.config = config
this.unloadApp()
setTimeout(() => {
this.loadApp()
})
}
}

9
src/index.pug Normal file
View File

@@ -0,0 +1,9 @@
doctype html
html
head
meta(name='viewport', content='initial-scale=1, minimal-ui, shrink-to-fit=no')
link(href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400", rel="stylesheet")
script(src='/build/index.js', defer)
title Terminus
body
app

15
src/index.ts Normal file
View File

@@ -0,0 +1,15 @@
import 'zone.js'
import 'core-js/proposals/reflect-metadata'
import 'core-js/features/array/flat'
import 'rxjs'
import { enableProdMode } from '@angular/core'
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'
import './styles.scss'
import { AppModule } from './app.module'
enableProdMode()
platformBrowserDynamic().bootstrapModule(AppModule)

202
src/polyfills.ts Normal file
View File

@@ -0,0 +1,202 @@
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
const MAX_ARGUMENTS_LENGTH = 0x1000
const base64 = require('base64-js')
function blitBuffer(src, dst, offset, length) {
let i
for (i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
export function utf8Write(string, offset, length) {
return blitBuffer(utf8ToBytes(string, this.length - offset), this, offset, length)
}
export function base64Slice(start, end) {
if (start === 0 && end === this.length) {
return base64.fromByteArray(this)
} else {
return base64.fromByteArray(this.slice(start, end))
}
}
function decodeCodePointsArray(codePoints) {
const len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
let res = ''
let i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
export function latin1Slice(start, end) {
let ret = ''
end = Math.min(this.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(this[i])
}
return ret
}
export function utf8Slice(this, start, end) {
end = Math.min(this.length, end)
const res = []
let i = start
while (i < end) {
const firstByte = this[i]
let codePoint = null
let bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1
if (i + bytesPerSequence <= end) {
let secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = this[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = this[i + 1]
thirdByte = this[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = this[i + 1]
thirdByte = this[i + 2]
fourthByte = this[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
function utf8ToBytes(string, units) {
units = units || Infinity
let codePoint
const length = string.length
let leadSurrogate = null
const bytes = []
for (let i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}

View File

@@ -0,0 +1,24 @@
import { Subject } from 'rxjs'
import { debounceTime } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http'
import { Injectable } from '@angular/core'
@Injectable({ providedIn: 'root' })
export class AppConnectorService {
config: any
private configUpdate = new Subject<string>()
constructor (private http: HttpClient) {
this.configUpdate.pipe(debounceTime(1000)).subscribe(content => {
this.http.patch(`/api/1/configs/${this.config.id}`, { content }).toPromise()
})
}
async loadConfig (): Promise<string> {
return this.config.content
}
async saveConfig (content: string): Promise<void> {
this.configUpdate.next(content)
}
}

9
src/styles.scss Normal file
View File

@@ -0,0 +1,9 @@
$font-family-sans-serif: "Source Sans Pro";
$border-radius-lg: 0;
$btn-border-width: 3px;
body {
overscroll-behavior: none;
}
@import "node_modules/bootstrap/scss/bootstrap";

0
src/terminal-styles.scss Normal file
View File

17
src/terminal.pug Normal file
View File

@@ -0,0 +1,17 @@
doctype html
html.terminus
head
meta(charset='UTF-8')
script(src='/build/terminal.js')
style#custom-css
style.
body { transition: 0.5s background; }
body
app-root(style='display: none')
.preload-logo
div
.terminus-logo
h1.terminus-title Terminus
sup α
.progress
.bar(style='width: 0%')

391
src/terminal.ts Normal file
View File

@@ -0,0 +1,391 @@
Object.assign(window, {
process: {
env: { XWEB: 1, LOGNAME: 'root' },
argv: ['terminus'],
platform: 'darwin',
on: () => null,
stdout: {},
stderr: {},
resourcesPath: 'resources',
version: '14.0.0',
nextTick: (f, ...args) => setTimeout(() => f(...args)),
// cwd: () => '/',
},
global: window,
})
import * as angularCoreModule from '@angular/core'
import * as angularCompilerModule from '@angular/compiler'
import * as angularCommonModule from '@angular/common'
import * as angularFormsModule from '@angular/forms'
import * as angularPlatformBrowserModule from '@angular/platform-browser'
import * as angularPlatformBrowserAnimationsModule from '@angular/platform-browser/animations'
import * as angularPlatformBrowserDynamicModule from '@angular/platform-browser-dynamic'
import * as angularAnimationsModule from '@angular/animations'
import * as ngBootstrapModule from '@ng-bootstrap/ng-bootstrap'
import * as ngxToastrModule from 'ngx-toastr'
import 'core-js/proposals/reflect-metadata'
import '@fortawesome/fontawesome-free/css/solid.css'
import '@fortawesome/fontawesome-free/css/brands.css'
import '@fortawesome/fontawesome-free/css/fontawesome.css'
import 'source-code-pro/source-code-pro.css'
import 'source-sans-pro/source-sans-pro.css'
import { Duplex } from 'stream-browserify'
import { Buffer } from 'buffer'
import './terminal-styles.scss'
import { base64Slice, latin1Slice, utf8Slice, utf8Write } from './polyfills'
export class Socket extends Duplex {
webSocket: WebSocket
initialBuffer: Buffer
constructor () {
console.warn('socket constr', arguments)
super({
allowHalfOpen: false,
})
this.initialBuffer = Buffer.from('')
}
connect () {
this.webSocket = new WebSocket(`ws://${location.host}/api/1/gateway/tcp`)
this.webSocket.onopen = event => {
this['emit']('connect')
this.webSocket.send(this.initialBuffer)
this.initialBuffer = Buffer.from('')
}
this.webSocket.onmessage = async event => {
this['emit']('data', Buffer.from(await event.data.arrayBuffer()))
}
}
setNoDelay () {
}
setTimeout () {
}
_read (size: number): void {
}
_write (chunk: Buffer, _encoding: string, callback: (error?: Error | null) => void): void {
if (!this.webSocket.readyState) {
this.initialBuffer = Buffer.concat([this.initialBuffer, chunk])
} else {
this.webSocket.send(chunk)
}
callback()
}
_destroy (error: Error|null, callback: (error: Error|null) => void): void {
console.warn('socket destroy', error)
callback(error)
}
}
async function start () {
class Logger {
constructor () {
for (let x of ['info', 'warn', 'error', 'log', 'debug']) {
this[x] = () => null
}
}
}
const mocks = {
fs: {
realpathSync: path => {
console.warn('mock realPathSync', path)
return path
},
existsSync: path => {
console.warn('mock existsSync', path)
return false
},
readdir: () => null,
stat: () => null,
mkdir: path => {
console.warn('mock mkdir', path)
},
mkdirSync: path => {
console.warn('mock mkdirSync', path)
},
writeFileSync: () => null,
readFileSync: (path) => {
return ''
},
readFile: (path, enc, cb) => {
console.warn('mock readFile', path)
cb('UNKNOWN', null)
},
// readdir: (path, cb) => {
// if (path === 'resources/builtin-plugins') {
// cb(null, [
// 'terminus-core',
// 'terminus-ssh',
// 'terminus-settings',
// 'terminus-terminal',
// ])
// } else {
// console.warn('mock readdir', path)
// cb(null, [])
// }
// },
constants: {},
},
'@electron/remote': {
app: {
getVersion: () => '1.0-web',
getPath: () => 'app-path',
getWindow: () => ({
reload: () => null,
setTrafficLightPosition: () => null,
}),
},
screen: {
on: () => null,
getAllDisplays: () => [],
getPrimaryDisplay: () => ({}),
getCursorScreenPoint: () => ({}),
getDisplayNearestPoint: () => null,
},
globalShortcut: {
unregisterAll: () => null,
register: () => null,
},
autoUpdater: {
on: () => null,
once: () => null,
setFeedURL: () => null,
checkForUpdates: () => null,
},
BrowserWindow: {
fromId: () => ({
setOpacity: () => null,
setProgressBar: () => null,
}),
},
getGlobal: () => window['process'],
},
electron: {
ipcRenderer: {
on: (e, c) => {
console.log('[ipc listen]', e)
},
once: (e, c) => {
console.log('[ipc listen once]', e)
},
send: msg => {
console.log('[ipc]', msg)
}
},
},
path: {
join: (...x) => x.join('/'),
basename: x => x,
dirname: x => x,
relative: (a, b) => b,
resolve: (a, b) => {
console.warn('mock path.resolve', a, b)
return b
}
},
buffer: {
Buffer,
},
crypto: {
...require('crypto-browserify'),
getHashes () {
return ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160']
},
timingSafeEqual (a, b) {
return a.equals(b)
},
},
events: require('events'),
readline: {
cursorTo: () => null,
clearLine: stream => stream.write('\r'),
},
zlib: {
...require('browserify-zlib'),
constants: require('browserify-zlib'),
},
'any-promise': Promise,
net: {
Socket,
},
tls: { },
module: {
globalPaths: [],
},
assert: require('assert'),
url: {
parse: () => null,
},
http: {
Agent: class {},
request: {},
},
https: {
Agent: class {},
request: {},
},
querystring: {},
tty: { isatty: () => false },
child_process: {},
winston: {
Logger,
transports: {
File: Object,
Console: Object,
}
},
'readable-stream': {},
os: {
platform: () => 'web',
homedir: () => '/home',
},
'mz/child_process': {
exec: (...x) => Promise.reject(),
},
'mz/fs': {
readFile: path => mocks.fs.readFileSync(path),
exists: path => mocks.fs.existsSync(path),
existsSync: path => mocks.fs.existsSync(path),
},
constants: require('constants-browserify'),
'hterm-umdjs': {
hterm: {
PreferenceManager: class { set () {} },
VT: {
ESC: {},
CSI: {},
OSC: {},
},
Terminal: class {},
Keyboard: class {},
},
lib: {
wc: {},
Storage: {
Memory: class {},
},
},
},
dns: {},
util: require('util/'),
keytar: {
getPassword: () => null,
},
}
;(mocks.assert as any).assertNotStrictEqual = () => true
;(mocks.assert as any).notStrictEqual = () => true
let builtins = {
'@angular/core': angularCoreModule,
'@angular/compiler': angularCompilerModule,
'@angular/common': angularCommonModule,
'@angular/forms': angularFormsModule,
'@angular/platform-browser': angularPlatformBrowserModule,
'@angular/platform-browser/animations': angularPlatformBrowserAnimationsModule,
'@angular/platform-browser-dynamic': angularPlatformBrowserDynamicModule,
'@angular/animations': angularAnimationsModule,
'@ng-bootstrap/ng-bootstrap': ngBootstrapModule,
'ngx-toastr': ngxToastrModule,
'deepmerge': require('deepmerge'),
'rxjs': require('rxjs'),
'rxjs/operators': require('rxjs/operators'),
'js-yaml': require('js-yaml'),
'zone.js/dist/zone.js': require('zone.js/dist/zone.js'),
}
Object.assign(window, {
require: (path) => {
if (mocks[path]) {
console.warn('requiring mock', path)
return mocks[path]
}
if (builtins[path]) {
return builtins[path]
}
console.error('requiring real module', path)
},
})
window['require'].main = {
paths: []
} as any
window['module'] = {
paths: []
} as any
window['require'].resolve = (path => null) as any
window['Buffer'] = mocks.buffer.Buffer
window['__dirname'] = '__dirname'
window['setImmediate'] = setTimeout as any
mocks.module['prototype'] = { require: window['require'] }
Buffer.prototype['latin1Slice'] = latin1Slice
Buffer.prototype['utf8Slice'] = utf8Slice
Buffer.prototype['base64Slice'] = base64Slice
Buffer.prototype['utf8Write'] = utf8Write
builtins['ssh2'] = require('ssh2')
builtins['ssh2/lib/protocol/constants'] = require('ssh2/lib/protocol/constants')
builtins['stream'] = require('stream-browserify')
async function loadPlugin (name, file = 'index.js') {
const url = `../app-dist/${name}/dist/${file}`
const e = document.createElement('script')
window['module'] = { exports: {} } as any
window['exports'] = window['module'].exports
await new Promise(resolve => {
e.onload = resolve
e.src = url
document.querySelector('head').appendChild(e)
})
return window['module'].exports
}
const pluginModules = []
for (const plugin of [
'terminus-core',
'terminus-settings',
'terminus-terminal',
'terminus-ssh',
'terminus-community-color-schemes',
'terminus-web',
]) {
console.log(`Loading ${plugin}`)
const mod = await loadPlugin(plugin)
builtins[`resources/builtin-plugins/${plugin}`] = builtins[plugin] = mod
pluginModules.push(mod)
}
await loadPlugin('app', 'preload.js')
await loadPlugin('app', 'bundle-web.js')
document.querySelector('app-root')['style'].display = 'flex'
await new Promise<void>(resolve => {
window.addEventListener('message', event => {
if (event.data === 'connector-ready') {
resolve()
}
})
window.parent.postMessage('request-connector', '*')
})
const config = window['__connector__'].loadConfig()
window['bootstrapTerminus'](pluginModules, { config })
}
start()