All files / app/web-ui web-server.ts

100% Statements 671/671
100% Branches 82/82
100% Functions 26/26
100% Lines 671/671

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 6711x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 1x 1x 133x 133x 133x 133x 133x 133x 133x 133x 133x 4x 4x 4x 2x 1x 1x 2x 2x 1x 1x 2x 4x 4x 4x 4x 133x 133x 133x 133x 133x 17x 133x 133x 133x 6x 133x 133x 133x 133x 133x 3x 3x 133x 133x 133x 1x 1x 133x 133x 133x 133x 133x 6x 6x 133x 133x 133x 133x 3x 3x 133x 133x 133x 133x 1x 1x 133x 133x 133x 133x 133x 29x 133x 133x 133x 133x 45x 45x 133x 133x 133x 133x 1x 133x 133x 133x 133x 133x 133x 133x 133x 133x 133x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 133x 133x 133x 133x 133x 133x 133x 133x 134x 134x 134x 134x 134x 134x 134x 134x 130x 134x 74x 74x 74x 56x 134x 50x 50x 50x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 134x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 134x 133x 133x 132x 132x 6x 6x 4x 6x 6x 4x 4x 4x 4x 126x 126x 132x 2x 2x 2x 2x 132x 133x 133x 134x 134x 134x 134x 134x 134x 134x 133x 133x 2x 2x 2x 2x 2x 2x 2x 2x 2x 133x 133x 2x 2x 2x 2x 2x 2x 2x 2x 133x 133x 2x 2x 2x 2x 2x 2x 2x 2x 133x 133x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 133x 133x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 133x 133x 133x 133x 133x 18x 18x 18x 18x 18x 18x 18x 18x 133x 133x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 133x 133x 133x 133x 133x 133x 10x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 10x 6x 6x 133x 133x 133x 133x 133x 133x 133x 6x 6x 2x 2x 4x 4x 4x 4x 4x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 133x 133x 133x 133x 133x 133x 133x 2x 2x 133x 133x 133x 133x 133x 133x 133x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 133x 133x 133x 133x 133x 133x 36x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 36x 28x 28x 133x 133x 133x 133x 133x 133x 133x 133x 16x 16x 6x 6x 10x 16x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 133x 133x 133x 133x 133x 133x 133x 133x 20x 20x 2x 2x 18x 18x 20x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 16x 16x 16x 16x 16x 20x 2x 20x 14x 14x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 133x 133x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 133x 133x 16x 16x 16x 16x 16x 16x 16x 16x 133x 133x 16x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 14x 14x 14x 14x 14x 14x 14x 14x 133x 133x 12x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 10x 10x 10x 10x 10x 10x 10x 10x 133x
import * as http from 'http';
import {jsonc} from 'jsonc';
import {MFAMethod} from '../../lib/icloud/mfa/mfa-method.js';
import {iCPSEventApp, iCPSEventCloud, iCPSEventMFA, iCPSEventRuntimeError, iCPSEventRuntimeWarning, iCPSEventSyncEngine, iCPSEventWebServer} from '../../lib/resources/events-types.js';
import {Resources} from '../../lib/resources/main.js';
import {WEB_SERVER_ERR} from '../error/error-codes.js';
import {iCPSError} from '../error/error.js';
import {TokenApp} from '../icloud-app.js';
import {faviconBase64, iconBase64} from './assets/icons.js';
import {manifest} from './assets/manifest.js';
import {serviceWorker} from './scripts/service-worker.js';
import {RequestMfaView} from './view/request-mfa-view.js';
import {StateView} from './view/state-view.js';
import {SubmitMfaView} from './view/submit-mfa-view.js';
import {State, StateTrigger, StateType} from './state.js';
import {NotificationPusher} from './notification-pusher.js';
import {URL} from 'url';
import {pEvent} from 'p-event';
 
type WebServerResponse = {
    code: number, 
    header: {
        "Content-Type": string, // eslint-disable-line
        "Content-Length"?: number, //eslint-disable-line
        Location?: string
    }, 
    body: any
}
 
type WebServerRoute = (url: URL, body?: string) => WebServerResponse
 
type WebServerSitemap = {
    POST: {
        [path: string]: WebServerRoute
    },
    GET: {
        [path: string]: WebServerRoute
    }
}
 
/**
 * This objects starts a server, that will listen to incoming MFA codes and other MFA related commands
 */
export class WebServer {
    /**
     * The server object
     */
    server: http.Server;
 
    /**
     * Holds the MFA method used for this server
     */
    mfaMethod: MFAMethod;
 
    /**
     * Provides notification capabilities to the server
     */
    notificationPusher: NotificationPusher = new NotificationPusher();
 
    /**
     * Keeps track of the state of the server
     */
    state: State = new State();
 
    /**
     * Routing table for this server
     */
    _sitemap: WebServerSitemap = {
        GET: {
            '/': this.handleRoot.bind(this),
            '/state': this.handleStateView.bind(this),
            '/submit-mfa': this.handleSubmitMFAView.bind(this),
            '/request-mfa': this.handleRequestMFAView.bind(this),
            '/service-worker.js': this.handleServiceWorker.bind(this),
            '/manifest.json': this.handleManifest.bind(this),
            '/icon.png': this.handleIcon.bind(this),
            '/favicon.ico': this.handleFavicon.bind(this),
            '/api/state': this.handleStateRequest.bind(this),
            '/api/vapid-public-key': this.handleVapidPublicKeyRequest.bind(this)
        },
        POST: {
            '/api/reauthenticate': this.handleReauthRequest.bind(this),
            '/api/mfa': this.handleMFACode.bind(this),
            '/api/resend_mfa': this.handleMFAResend.bind(this),
            '/api/sync': this.handleSyncRequest.bind(this),
            '/api/subscribe': this.handlePushSubscription.bind(this)
        }
    }
 
    /**
     * Creates the server object and starts the web server
     * @returns 
     */
    static async spawn(): Promise<WebServer> {
        return new WebServer().startServer();
    }
 
    /**
     * Creates the server object
     * @emits iCPSEventWebServer.ERROR - When an error associated to the server occurs - Provides iCPSError as argument
     */
    constructor() {
        Resources.logger(this).debug(`Preparing web server on port ${Resources.manager().webServerPort}`);
        this.server = http.createServer(this.handleRequest.bind(this));
        this.server.on(`error`, err => {
            let icpsErr = new iCPSError(WEB_SERVER_ERR.SERVER_ERR);
 
            if (Object.hasOwn(err, `code`)) {
                if ((err as any).code === `EADDRINUSE`) {
                    icpsErr = new iCPSError(WEB_SERVER_ERR.ADDR_IN_USE_ERR).addContext(`port`, Resources.manager().webServerPort);
                }
 
                if ((err as any).code === `EACCES`) {
                    icpsErr = new iCPSError(WEB_SERVER_ERR.INSUFFICIENT_PRIVILEGES).addContext(`port`, Resources.manager().webServerPort);
                }
            }
 
            icpsErr.addCause(err);
 
            Resources.emit(iCPSEventWebServer.ERROR, icpsErr);
        });
 
        // TRIGGERS
        // Scheduled as well as explicit sync trigger
        Resources.events(this).on(iCPSEventApp.SCHEDULED_START, () => {
            this.state.triggerSync(StateTrigger.SYNC);
        });
        // Manual Auth Trigger
        Resources.events(this).on(iCPSEventWebServer.REAUTH_REQUESTED, () => {
            this.state.triggerSync(StateTrigger.AUTH);
        });
 
        // SUCCESS
        // Scheduled execution done 
        Resources.events(this).on(iCPSEventApp.SCHEDULED_DONE, (nextSync: Date) => {
            this.state.updateState(StateType.READY, {nextSync: nextSync.getTime()});
            this.notificationPusher.sendNotifications(this.state);
        });
        // Reauth success
        Resources.events(this).on(iCPSEventApp.TOKEN, () => {
            this.state.updateState(StateType.READY);
            this.notificationPusher.sendNotifications(this.state);
        });
 
        // ERROR
        // Sync error
        Resources.events(this).on(iCPSEventRuntimeError.SCHEDULED_ERROR, (err: iCPSError) => {
            this.state.updateState(StateType.READY, {error: err});
            this.notificationPusher.sendNotifications(this.state);
        });
        
        // MFA not provided
        Resources.events(this).on(iCPSEventMFA.MFA_NOT_PROVIDED, () => {
            this.state.updateState(StateType.READY, {error: new iCPSError(WEB_SERVER_ERR.MFA_CODE_NOT_PROVIDED)});
            this.notificationPusher.sendNotifications(this.state);
        });
        
        // Runtime error during re-auth
        Resources.events(this).on(iCPSEventWebServer.REAUTH_ERROR, (err: iCPSError) => {
            this.state.updateState(StateType.READY, {error: err});
            this.notificationPusher.sendNotifications(this.state);
        });
 
        // LIFECYCLE
        // Sync started after authentication
        Resources.events(this).on(iCPSEventSyncEngine.START, () => {
            this.state.updateState(StateType.SYNC);
        });
 
        // MFA required
        Resources.events(this).on(iCPSEventCloud.MFA_REQUIRED, () => {
            this.state.updateState(StateType.MFA)
            this.notificationPusher.sendNotifications(this.state);
        });
 
        // Initial scheduled run
        Resources.events(this).on(iCPSEventApp.SCHEDULED, (timestamp: Date) => {
            this.state.updateState(StateType.READY, {nextSync: timestamp.getTime()});
        });
 
 
        // allow the process to exit, if this server is the only thing left running
        this.server.unref();
 
        // Default MFA request always goes to device
        this.mfaMethod = new MFAMethod();
    }
 
    /* c8 ignore start */
    // Never starting/stopping the server just to see logger messages
 
    /**
     * Closes this server
     */
    close(): Promise<void> {
        Resources.events(this).removeListeners();
        return new Promise<void>(resolve => {
            this.server.close(() => resolve());
        });
    }
 
    /**
     * Starts the server and listens for incoming requests to perform MFA actions
     */
    startServer(): Promise<WebServer> {
        return new Promise<WebServer>((resolve, reject) => {
            try {
                this.server.listen(Resources.manager().webServerPort, () => {
                    
 
                    // Updating the port to match the actual listening port
                    //Resources.manager().webServerPort = (this.server.address() as AddressInfo).port
 
                    Resources.emit(iCPSEventWebServer.STARTED, Resources.manager().webServerPort);
                    Resources.logger(this).info(`Exposing GET endpoints: ${jsonc.stringify(Object.keys(this._sitemap.GET))}`);
                    Resources.logger(this).info(`Exposing POST endpoints: ${jsonc.stringify(Object.keys(this._sitemap.POST))}`);
                    resolve(this);
                });
            } catch (err) {
                const icpsErr = new iCPSError(WEB_SERVER_ERR.STARTUP_FAILED).addCause(err);
                Resources.emit(iCPSEventWebServer.ERROR, icpsErr);
                reject(icpsErr);
            }
        });
    }
 
    /* c8 ignore stop */
 
    /**
     * Handles incoming http requests
     * @param req - The HTTP request object
     * @param res - The HTTP response object
     * @emits iCPSEventRuntimeWarning.WEB_SERVER_ERR - When the request method or endpoint of server could not be found - Provides iCPSError as argument
     */
    async handleRequest(req: http.IncomingMessage, res: http.ServerResponse) {
        try {
            const url = new URL(
                req.url.replace(new RegExp(`^${Resources.manager().webBasePath}`), ``), // Removing the web base path for request matching
                `http://localhost/` // Necessary, because the req.url is relative
            )
            Resources.logger(this).debug(`Received ${req.method} request for URL ${url.toString()}`)
 
            const body = await this.readBody(req)
 
            if (req.method === `GET` && url.pathname in this._sitemap.GET) {
                this.sendResponse(this._sitemap.GET[url.pathname](url, body), res)
                return;
            }
 
            if (req.method === `POST` && url.pathname in this._sitemap.POST) {
                this.sendResponse(this._sitemap.POST[url.pathname](url, body), res)
                return;
            }
 
            Resources.logger(this).warn(`Unknown request method: ${req.method} for ${req.url}`);
 
            Resources.emit(iCPSEventRuntimeWarning.WEB_SERVER_ERROR, new iCPSError(WEB_SERVER_ERR.BAD_REQUEST)
                .addMessage(`Unknown path: endpoint ${req.url}, method ${req.method}, pathname ${url.pathname}`)
                .addContext(`request`, req));
 
            this.sendResponse({
                code: 400,
                header: {
                    "Content-Type": `application/json`
                },
                body: {
                    message: `Method (${req.method}) not supported on endpoint ${req.url}`
                }
            }, res)
        } catch (err) {
            const error = new iCPSError(WEB_SERVER_ERR.UNKNOWN_ERR)
                .addCause(err)
                .addContext(`request`, req)
                .addContext(`responseWritten`, !res.writable)
            Resources.emit(iCPSEventRuntimeWarning.WEB_SERVER_ERROR, error);
 
            if (res.writable) {
                this.sendResponse({
                    code: 500,
                    header: {
                        "Content-Type": `application/json`
                    },
                    body: {
                        message: error.getDescription()
                    }
                }, res)
            }
        }
    }
 
    async readBody(req: http.IncomingMessage): Promise<string> {
        try {
            if(req.headers[`content-length`] && Number.parseInt(req.headers[`content-length`], 10) > 0) {
                let body = ``;
                req.on(`data`, chunk => {
                    body += chunk.toString();
                });
                await pEvent(req, `end`, {rejectionEvents: [`error`]})
 
                Resources.logger(this).debug(`Read body: ${body}`)
                return body;
            }
            Resources.logger(this).debug(`No body to read`)
            return ``;
        } catch (err) {
            throw new iCPSError(WEB_SERVER_ERR.UNABLE_TO_READ_BODY)
                .addCause(err)
                .addContext(`request`, req)
        }
    }
 
    sendResponse(response: WebServerResponse, res: http.ServerResponse) {
        res.writeHead(response.code, response.header)
            .end(
                typeof response.body === `string` || response.body instanceof Buffer
                    ? response.body
                    : jsonc.stringify(response.body)
            )
    }
 
    handleRoot(): WebServerResponse {
        return {
            code: 302,
            header: {
                "Content-Type": `text/plain`,
                Location: `/state`
            },
            body: ``
        }
    }
 
    handleServiceWorker(): WebServerResponse {
        return {
            code: 200,
            header: {
                "Content-Type": `application/javascript`
            },
            body: serviceWorker(Resources.manager().webBasePath)
        }
    }
 
    handleManifest(): WebServerResponse {
        return {
            code: 200,
            header: {
                'Content-Type': `application/json`
            },
            body: manifest(Resources.manager().webBasePath)
        }
    }
 
    handleIcon(): WebServerResponse {
        const iconBuffer = Buffer.from(iconBase64, `base64`);
        return {
            code: 200,
            header: {
                'Content-Type': `image/png`,
                'Content-Length': iconBuffer.length,
            },
            body: iconBuffer
        }
    }
 
    handleFavicon(): WebServerResponse {
        const faviconBuffer = Buffer.from(faviconBase64, `base64`);
        return {
            code: 200,
            header: {
                'Content-Type': `image/x-icon`,
                'Content-Length': faviconBuffer.length,
            },
            body: faviconBuffer
        }
    }
 
    /**
     * This function will handle the request send to the state endpoint
     */
    handleStateRequest(): WebServerResponse {
        return {
            code: 200,
            header: {
                "Content-Type": `application/json`
            },
            body: this.state.serialize()
        }
    }
 
    handleVapidPublicKeyRequest(): WebServerResponse {
        return {
            code: 200,
            header: {
                "Content-Type": `application/json`
            },
            body: {
                publicKey: Resources.manager().notificationVapidCredentials.publicKey
            }
        }
    }
 
    /**
     * This function will check if the server is currently expecting an MFA code
     * @returns - Undefined if the server is expecting an MFA code, otherwise a WebServerResponse object indicating the error
     */
    handleInProgress(): WebServerResponse | undefined {
        if (this.state.state !== StateType.READY) {
            Resources.emit(iCPSEventRuntimeWarning.WEB_SERVER_ERROR, new iCPSError(WEB_SERVER_ERR.SYNC_IN_PROGRESS));
            return {
                code: 412,
                header: {
                    "Content-Type": `application/json`
                },
                body: {
                    message: `Cannot perform action while sync is in progress`,
                }
            }
        } 
        return undefined;
    }
 
    /**
     * This function will handle the request send to the re-authentication endpoint
     * @emits iCPSEventWebServer.REAUTH_REQUESTED - When the request was received
     * @emits iCPSEventWebServer.REAUTH_ERROR - When there was an error
     */
    handleReauthRequest(): WebServerResponse {
        const check = this.handleInProgress();
        if (check) {
            return check;
        }
 
        Resources.emit(iCPSEventWebServer.REAUTH_REQUESTED);
 
        this.triggerReauth()
            .catch(err => {
                Resources.emit(iCPSEventWebServer.REAUTH_ERROR, iCPSError.toiCPSError(err));
            });
        
        return {
            code: 200,
            header: {
                "Content-Type": `application/json`
            },
            body: {
                message: `Reauthentication requested`
            }
        }
    }
 
    /**
     * This function will trigger the reauthentication process
     * @param app - An optional TokenApp instance to use for reauthentication. If not provided, a new instance will be created (structured for testing purposes)
     * @returns A promise that resolves when the reauthentication process is complete
     */
    triggerReauth(app: TokenApp = new TokenApp(true)): Promise<unknown> {
        return app.run()
    }
 
    /**
     * This function will handle the request send to the sync endpoint
     * @param res - The HTTP response object
     * @emits iCPSEventWebServer.SYNC_REQUESTED - When the sync was requested
     */
    handleSyncRequest(): WebServerResponse {
        const check = this.handleInProgress();
        if (check) {
            return check;
        }
        Resources.emit(iCPSEventWebServer.SYNC_REQUESTED); // Will run a manual trigger for the cron-job
        return {
            code: 200,
            header: {
                "Content-Type": `application/json`
            },
            body: {
                message: `Sync requested`
            }
        }
    }
 
    /**
     * This function will check if the server is currently expecting an MFA code
     * @returns - Undefined if the server is expecting an MFA code, otherwise a WebServerResponse object indicating the error
     */
    handleMFACheck(): WebServerResponse | undefined {
        if (this.state.state !== StateType.MFA) {
            Resources.emit(iCPSEventRuntimeWarning.WEB_SERVER_ERROR, new iCPSError(WEB_SERVER_ERR.NO_CODE_EXPECTED));
            return {
                code: 412,
                header: {
                    "Content-Type": `application/json`
                },
                body: {
                    message: `MFA code not expected at this time.`,
                }
            }
        } 
        return undefined;
    }
 
    /**
     * This function will handle requests send to the MFA code input endpoint
     * @param url - The parsed URL invoking this request
     * @emits iCPSEventRuntimeWarning.WEB_SERVER_ERR - When the parameters do not match the expected format
     * @emits iCPSEventMFA.MFA_RECEIVED - When the MFA code was received - Provides MFA method and MFA code as arguments
     */
    handleMFACode(url: URL): WebServerResponse {
        const check = this.handleMFACheck();
        if (check) {
            return check;
        }
 
        if (!url.search.match(/code=(\d{6})/)) {
            Resources.emit(iCPSEventRuntimeWarning.WEB_SERVER_ERROR, new iCPSError(WEB_SERVER_ERR.CODE_FORMAT)
                .addMessage(url.toString()));
            return {
                code: 400,
                header: {
                    "Content-Type": `application/json`
                },
                body: {
                    message: `Unexpected MFA code format! Expecting 6 digits`
                }
            }
        }
 
        const mfa: string = url.search.match(/code=(\d{6})/)[1]
 
        Resources.logger(this).debug(`Received MFA: ${mfa}`);
        Resources.emit(iCPSEventMFA.MFA_RECEIVED, this.mfaMethod, mfa);
        return {
            code: 200,
            header: {
                "Content-Type": `application/json`
            },
            body: {
                message: `Read MFA code: ${mfa}`
            }
        }
    }
 
    /**
     * This function will handle the request send to the MFA code resend endpoint
     * @param url - The parsed URL invoking this request
     * @emits iCPSEventRuntimeWarning.WEB_SERVER_ERR - When the MFA resend method is not as expected - Provides iCPSError as argument
     * @emits iCPSEventMFA.MFA_RESEND - When the MFA code resend was requested - Provides MFA method as argument
     */
    handleMFAResend(url: URL): WebServerResponse {
        const check = this.handleMFACheck();
        if (check) {
            return check;
        }
        
        const methodMatch = url.search.match(/method=(sms|voice|device)/);
        if (!methodMatch) {
            Resources.emit(iCPSEventRuntimeWarning.WEB_SERVER_ERROR, new iCPSError(WEB_SERVER_ERR.RESEND_METHOD_FORMAT)
                .addContext(`requestURL`, url));
            
            return {
                code: 400,
                header: {
                    "Content-Type": `application/json`
                },
                body: {
                    message: `Resend method does not match expected format`
                }
            }
        }
 
        const methodString = methodMatch[1];
 
        const phoneNumberIdMatch = url.search.match(/phoneNumberId=(\d+)/);
 
        if (phoneNumberIdMatch && methodString !== `device`) {
            this.mfaMethod.update(methodString, parseInt(phoneNumberIdMatch[1], 10));
        } else {
            this.mfaMethod.update(methodString);
        }
 
        Resources.emit(iCPSEventMFA.MFA_RESEND, this.mfaMethod);
 
        return {
            code: 200,
            header: {
                "Content-Type": `application/json`
            },
            body: {
                message: `Requesting MFA resend with method ${this.mfaMethod}`
            }
        }
    }
    
    handlePushSubscription(_url: URL, data?: string): WebServerResponse {
        try {
            const pushSubscriptionData = Resources.validator().validatePushSubscription(jsonc.parse(data));
            Resources.manager().addNotificationSubscription(pushSubscriptionData);
            return {
                code: 201,
                header: {
                    "Content-Type": `application/json`
                },
                body: {
                    message: `Push subscription added successfully`
                }
            }
        } catch (err) {
            Resources.logger(this).error(`Unable to register push subscription: ${err}`);
            return {
                code: 400,
                header: {
                    "Content-Type": `application/json`
                },
                body: {
                    message: `Unable to add push subscription`
                }
            }
        }
    }
 
    handleStateView(): WebServerResponse {
        return {
            code: 200,
            header: {
                "Content-Type": `text/html`
            },
            body: new StateView().asHtml()
        }
    }
 
    handleSubmitMFAView(): WebServerResponse {
        if (this.state.state !== StateType.MFA) {
            Resources.logger(this).warn(`Submit MFA view requested, but not waiting for it. Redirecting to state view.`);
            return {
                code: 302,
                header: {
                    "Content-Type": `text/plain`,
                    Location: `${Resources.manager().webBasePath}/state`
                },
                body: {}
            }
        }
        return {
            code: 200,
            header: {
                "Content-Type": `text/html`
            },
            body: new SubmitMfaView().asHtml()
        }
    }
 
    handleRequestMFAView(): WebServerResponse {
        if (this.state.state !== StateType.MFA) {
            Resources.logger(this).warn(`Request MFA view requested, but not waiting for it. Redirecting to state view.`);
            return {
                code: 302,
                header: {
                    "Content-Type": `text/plain`,
                    Location: `${Resources.manager().webBasePath}/state`
                },
                body: {}
            }
        }
        return {
            code: 200,
            header: {
                "Content-Type": `text/html`
            },
            body: new RequestMfaView().asHtml()
        }
    }
}