Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ulixee
GitHub Repository: ulixee/secret-agent
Path: blob/main/mitm-socket/lib/MitmSocketSession.ts
1030 views
1
import Log from '@secret-agent/commons/Logger';
2
import { IBoundLog } from '@secret-agent/interfaces/ILog';
3
import MitmSocket from '..';
4
import BaseIpcHandler, { IGoIpcOpts } from './BaseIpcHandler';
5
6
const { log } = Log(module);
7
8
export default class MitmSocketSession extends BaseIpcHandler {
9
protected logger: IBoundLog;
10
11
private readonly socketsById = new Map<number, MitmSocket>();
12
13
constructor(readonly sessionId: string, options: IGoIpcOpts) {
14
super({ ...options, mode: 'proxy' });
15
this.logger = log.createChild(module, { sessionId });
16
}
17
18
public async requestSocket(socket: MitmSocket): Promise<void> {
19
const id = socket.id;
20
this.socketsById.set(id, socket);
21
22
socket.once('close', () => this.socketsById.delete(id));
23
24
await this.waitForConnected;
25
26
try {
27
await this.sendIpcMessage({
28
id,
29
socketPath: socket.socketPath,
30
...socket.connectOpts,
31
});
32
} catch (error) {
33
if (this.isClosing) {
34
return null;
35
}
36
this.logger.info('MitmSocketSession.requestSocketError', {
37
error,
38
});
39
}
40
}
41
42
protected onMessage(rawMessage: string): void {
43
if (this.isClosing) return;
44
const message = JSON.parse(rawMessage);
45
if (this.options.debug) {
46
this.logger.info('MitmSocketSession.onMessage', {
47
...message,
48
});
49
}
50
if (message?.id) {
51
this.socketsById.get(message.id)?.onMessage(message);
52
}
53
}
54
55
protected beforeExit(): void {
56
for (const socket of this.socketsById.values()) {
57
socket.onExit();
58
}
59
this.socketsById.clear();
60
}
61
}
62
63