2021-05-06 00:09:29 +00:00
|
|
|
// Copyright 2021 Signal Messenger, LLC
|
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2021-10-26 19:15:33 +00:00
|
|
|
import type { IpcMainEvent } from 'electron';
|
|
|
|
import { ipcMain as ipc } from 'electron';
|
2021-05-06 00:09:29 +00:00
|
|
|
|
2022-09-15 00:31:37 +00:00
|
|
|
import * as log from '../logging/log';
|
2021-10-26 19:15:33 +00:00
|
|
|
import type { IPCRequest, IPCResponse, ChallengeResponse } from '../challenge';
|
2021-05-06 00:09:29 +00:00
|
|
|
|
|
|
|
export class ChallengeMainHandler {
|
|
|
|
private handlers: Array<(response: ChallengeResponse) => void> = [];
|
|
|
|
|
|
|
|
constructor() {
|
|
|
|
this.initialize();
|
|
|
|
}
|
|
|
|
|
|
|
|
public handleCaptcha(captcha: string): void {
|
|
|
|
const response: ChallengeResponse = { captcha };
|
|
|
|
|
|
|
|
const { handlers } = this;
|
|
|
|
this.handlers = [];
|
2022-09-15 00:31:37 +00:00
|
|
|
|
|
|
|
log.info(
|
|
|
|
'challengeMain.handleCaptcha: sending captcha response to ' +
|
|
|
|
`${handlers.length} handlers`,
|
|
|
|
response
|
|
|
|
);
|
2021-05-06 00:09:29 +00:00
|
|
|
for (const resolve of handlers) {
|
|
|
|
resolve(response);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private async onRequest(
|
|
|
|
event: IpcMainEvent,
|
|
|
|
request: IPCRequest
|
|
|
|
): Promise<void> {
|
2022-09-15 00:31:37 +00:00
|
|
|
const logId = `challengeMain.onRequest(${request.reason})`;
|
|
|
|
log.info(`${logId}: received challenge request, waiting for response`);
|
|
|
|
|
|
|
|
const start = Date.now();
|
2021-05-06 00:09:29 +00:00
|
|
|
|
|
|
|
const data = await new Promise<ChallengeResponse>(resolve => {
|
|
|
|
this.handlers.push(resolve);
|
|
|
|
});
|
|
|
|
|
2022-09-15 00:31:37 +00:00
|
|
|
const duration = Date.now() - start;
|
|
|
|
log.info(`${logId}: got response after ${duration}ms`);
|
2021-05-06 00:09:29 +00:00
|
|
|
|
|
|
|
const ipcResponse: IPCResponse = {
|
|
|
|
seq: request.seq,
|
|
|
|
data,
|
|
|
|
};
|
|
|
|
event.sender.send('challenge:response', ipcResponse);
|
|
|
|
}
|
|
|
|
|
|
|
|
private initialize(): void {
|
|
|
|
ipc.on('challenge:request', (event, request) => {
|
|
|
|
this.onRequest(event, request);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|