-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
loginScriptProcessing.ts
96 lines (85 loc) · 2.79 KB
/
loginScriptProcessing.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import deepClone from 'clone-deep'
import { Logger } from 'tabby-core'
import { SessionMiddleware } from '../api/middleware'
export interface LoginScript {
expect: string
send: string
isRegex?: boolean
optional?: boolean
}
export interface LoginScriptsOptions {
scripts?: LoginScript[]
}
export class LoginScriptProcessor extends SessionMiddleware {
private remainingScripts: LoginScript[] = []
private escapeSeqMap = {
a: '\x07',
b: '\x08',
e: '\x1b',
f: '\x0c',
n: '\x0a',
r: '\x0d',
t: '\x09',
v: '\x0b',
}
constructor (
private logger: Logger,
options: LoginScriptsOptions,
) {
super()
this.remainingScripts = deepClone(options.scripts ?? [])
for (const script of this.remainingScripts) {
if (!script.isRegex) {
script.expect = this.unescape(script.expect)
}
script.send = this.unescape(script.send)
}
}
feedFromSession (data: Buffer): void {
const dataString = data.toString()
for (const script of this.remainingScripts) {
if (!script.expect) {
continue
}
let match = false
if (script.isRegex) {
const re = new RegExp(script.expect, 'g')
match = re.test(dataString)
} else {
match = dataString.includes(script.expect)
}
if (match) {
this.logger.info('Executing script:', script)
this.outputToSession.next(Buffer.from(script.send + '\n'))
this.remainingScripts = this.remainingScripts.filter(x => x !== script)
} else {
if (script.optional) {
this.logger.debug('Skip optional script: ' + script.expect)
this.remainingScripts = this.remainingScripts.filter(x => x !== script)
} else {
break
}
}
}
super.feedFromSession(data)
}
executeUnconditionalScripts (): void {
for (const script of this.remainingScripts) {
if (!script.expect) {
this.logger.info('Executing script:', script.send)
this.outputToSession.next(Buffer.from(script.send + '\n'))
this.remainingScripts = this.remainingScripts.filter(x => x !== script)
} else {
break
}
}
}
unescape (line: string): string {
line = line.replace(/\\((x\d{2})|(u\d{4}))/g, (match, g) => {
return String.fromCharCode(parseInt(g.substr(1), 16))
})
return line.replace(/\\(.)/g, (match, g) => {
return this.escapeSeqMap[g] || g
})
}
}