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

100% Statements 637/637
97.5% Branches 78/80
100% Functions 28/28
100% Lines 637/637

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 6371x 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 1x 1x 1x 1x 1x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 115x 115x 115x 115x 115x 115x 115x 115x 115x 3x 3x 3x 115x 115x 115x 52x 115x 115x 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 1x 1x 174x 174x 174x 174x 174x 174x 172x 172x 174x 136x 136x 136x 36x 174x 30x 30x 30x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 174x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 174x 1x 1x 173x 173x 3x 3x 2x 3x 3x 2x 2x 2x 2x 170x 173x 1x 1x 1x 1x 173x 1x 1x 174x 174x 174x 174x 174x 174x 174x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 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 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 3x 3x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 2x 2x 2x 2x 2x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 23x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 23x 19x 19x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 3x 3x 5x 5x 8x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 1x 1x 14x 14x 15x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 15x 6x 6x 6x 15x 7x 7x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 1x 1x 19x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 1x 1x 21x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 1x
import * as http from 'http';
import {jsonc} from 'jsonc';
import {MFAMethod} from '../../lib/icloud/mfa/mfa-method.js';
import {iCPSEventCloud, iCPSEventMFA, iCPSEventRuntimeWarning, 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 {PrometheusMetricsExporter} from '../event/prometheus-metrics-exporter.js';
import {LogLevel, StateType} from '../../lib/resources/state-manager.js';
import {NotificationPusher} from './notification-pusher.js';
import {URL} from 'url';
import {once} from 'events';
 
type WebServerResponse = {
    code: number,
    header: {
        "Content-Type": string,
        "Content-Length"?: number,
        Location?: string
    },
    body: any
}
 
type WebServerRoute = (url: URL, body?: string, headers?: http.IncomingHttpHeaders) => 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();
 
    /**
     * Provides the metrics for the /metrics endpoint - only set, if the prometheus metrics export is enabled
     */
    prometheusMetricsExporter?: PrometheusMetricsExporter;
 
    /**
     * 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/log': this.handleLogRequest.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(prometheusMetricsExporter?: PrometheusMetricsExporter): Promise<WebServer> {
        return new WebServer(prometheusMetricsExporter).startServer();
    }
 
    /**
     * Creates the server object
     * @param prometheusMetricsExporter - The exporter serving the /metrics endpoint - the endpoint is only exposed, if the exporter is provided and the prometheus metrics export is enabled
     * @emits iCPSEventWebServer.ERROR - When an error associated to the server occurs - Provides iCPSError as argument
     */
    constructor(prometheusMetricsExporter?: PrometheusMetricsExporter) {
        Resources.logger(this).debug(`Preparing web server on port ${Resources.manager().webServerPort}`);
        this.server = http.createServer(this.handleRequest.bind(this));
 
        // allow the process to exit, if this server is the only thing left running
        this.server.unref();
 
        this.mfaMethod = new MFAMethod();
 
        if (prometheusMetricsExporter && Resources.manager().exportPrometheusMetrics) {
            this.prometheusMetricsExporter = prometheusMetricsExporter;
            this._sitemap.GET[`/metrics`] = this.handleMetricsRequest.bind(this);
        }
 
        // Every new MFA flow starts with the code pushed to the trusted devices
        Resources.events(this).on(iCPSEventCloud.MFA_REQUIRED, () => {
            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) {
                reject(new iCPSError(WEB_SERVER_ERR.STARTUP_FAILED).addCause(err));
            }
        });
    }
 
    /* 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(`^${RegExp.escape(Resources.manager().webBasePath)}`), ``), // Removing the web base path for request matching (escaping, since it is user provided)
                `http://localhost/` // Necessary, because the req.url is relative
            )
            const body = await this.readBody(req)
            const headers = req.headers
 
            if (req.method === `GET` && url.pathname in this._sitemap.GET) {
                this.sendResponse(this._sitemap.GET[url.pathname](url, body, headers), res)
                return;
            }
 
            if (req.method === `POST` && url.pathname in this._sitemap.POST) {
                this.sendResponse(this._sitemap.POST[url.pathname](url, body, headers), 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 once(req, `end`) // Rejects if an 'error' event is emitted
 
                Resources.logger(this).debug(`Read body: ${body}`)
                return body;
            }
            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: `${Resources.manager().webBasePath}/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: Resources.state().serialize()
        }
    }
 
    handleLogRequest(url: URL): WebServerResponse {
        const logLevelMatch = url.search.match(/loglevel=(debug|info|warn|error)/);
        const logLevel = logLevelMatch?.[1] as LogLevel ?? `none`
 
        return {
            code: 200,
            header: {
                "Content-Type": `application/json`
            },
            body: Resources.state().serializeLog({level: logLevel})
        }
 
    }
 
    handleVapidPublicKeyRequest(): WebServerResponse {
        return {
            code: 200,
            header: {
                "Content-Type": `application/json`
            },
            body: {
                publicKey: Resources.manager().notificationVapidCredentials.publicKey
            }
        }
    }
 
    /**
     * This function will handle the request send to the metrics endpoint, negotiating the exposition format based on the Accept header
     * @param _url - The parsed URL invoking this request
     * @param _body - The request body
     * @param headers - The request headers
     */
    handleMetricsRequest(_url: URL, _body?: string, headers?: http.IncomingHttpHeaders): WebServerResponse {
        const exporter = this.prometheusMetricsExporter!;
        const {contentType, body} = exporter.render(exporter.negotiate(headers?.accept));
        return {
            code: 200,
            header: {
                "Content-Type": contentType
            },
            body
        }
    }
 
    /**
     * 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 (Resources.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()): 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 (Resources.state().state !== StateType.BLOCKED) {
            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;
        }
 
        const codeMatch = url.search.match(/code=(\d{6})/);
        if (!codeMatch) {
            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 = codeMatch[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`) {
            const phoneNumberId = parseInt(phoneNumberIdMatch[1], 10);
            const trustedPhoneNumber = Resources.state().trustedPhoneNumbers?.find(phoneNumber => phoneNumber.id === phoneNumberId);
            this.mfaMethod.update(methodString, phoneNumberId, trustedPhoneNumber?.nonFTEU);
        } 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 (Resources.state().state !== StateType.BLOCKED) {
            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 (Resources.state().state !== StateType.BLOCKED) {
            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()
        }
    }
}