All files / src IceWarpApplication.ts

48.78% Statements 40/82
24.13% Branches 7/29
36.84% Functions 7/19
48.78% Lines 40/82

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 2322x   2x 2x 2x 2x 2x       2x 2x   2x 2x               2x 2x   2x   2x     2x 2x 2x   2x       4x                                                             2x 2x   2x 2x 1x   1x     2x 2x         2x       2x       2x 2x 2x 2x                                                                                                                                                                                                                         2x                       2x 2x   2x       2x 2x   2x        
import CoreFormsEnum from '@orchesty/nodejs-sdk/dist/lib/Application/Base/CoreFormsEnum';
import { ApplicationInstall } from '@orchesty/nodejs-sdk/dist/lib/Application/Database/ApplicationInstall';
import Field from '@orchesty/nodejs-sdk/dist/lib/Application/Model/Form/Field';
import FieldType from '@orchesty/nodejs-sdk/dist/lib/Application/Model/Form/FieldType';
import Form from '@orchesty/nodejs-sdk/dist/lib/Application/Model/Form/Form';
import FormStack from '@orchesty/nodejs-sdk/dist/lib/Application/Model/Form/FormStack';
import { ABasicApplication } from '@orchesty/nodejs-sdk/dist/lib/Authorization/Type/Basic/ABasicApplication';
import CacheService, { ICacheCallback } from '@orchesty/nodejs-sdk/dist/lib/Cache/CacheService';
import Redis from '@orchesty/nodejs-sdk/dist/lib/Storage/Redis/Redis';
import CurlSender from '@orchesty/nodejs-sdk/dist/lib/Transport/Curl/CurlSender';
import RequestDto from '@orchesty/nodejs-sdk/dist/lib/Transport/Curl/RequestDto';
import { HttpMethods } from '@orchesty/nodejs-sdk/dist/lib/Transport/HttpMethods';
import AProcessDto from '@orchesty/nodejs-sdk/dist/lib/Utils/AProcessDto';
import { decode } from '@orchesty/nodejs-sdk/dist/lib/Utils/Base64';
import { CommonHeaders, JSON_TYPE } from '@orchesty/nodejs-sdk/dist/lib/Utils/Headers';
 
/* eslint-disable prefer-named-capture-group */
/* eslint-disable no-unsafe-optional-chaining */
/* eslint-disable @typescript-eslint/no-shadow */
/* eslint-disable @typescript-eslint/prefer-nullish-coalescing */
/* eslint-disable @typescript-eslint/no-explicit-any */
 
const ACCESS_TOKEN = 'accessToken';
const REFRESH_TOKEN = 'refreshToken';
 
export const ICE_WARP_APPLICATION = 'ice-warp';
 
export default class IceWarpApplication extends ABasicApplication {
 
    public constructor(
        protected readonly cache: CacheService,
        protected readonly redis: Redis,
        protected readonly curl: CurlSender,
    ) {
        super();
    }
 
    public getName(): string {
        return ICE_WARP_APPLICATION;
    }
 
    public getPublicName(): string {
        return 'Ice Warp Application';
    }
 
    public getDescription(): string {
        return 'Ice Warp Application description';
    }
 
    public getFormStack(): FormStack {
        const form = new Form(CoreFormsEnum.AUTHORIZATION_FORM, 'Authorization settings');
        form.addField(new Field(FieldType.TEXT, ACCESS_TOKEN, 'Access token', undefined, true));
        form.addField(new Field(FieldType.TEXT, REFRESH_TOKEN, 'Refresh token', undefined, true));
 
        return new FormStack().addForm(form);
    }
 
    public isAuthorized(applicationInstall: ApplicationInstall): boolean {
        const authorizationForm = applicationInstall.getSettings()[CoreFormsEnum.AUTHORIZATION_FORM];
        return authorizationForm?.[ACCESS_TOKEN] && authorizationForm?.[REFRESH_TOKEN];
    }
 
    public async getRequestDto(
        dto: AProcessDto,
        applicationInstall: ApplicationInstall,
        method: HttpMethods,
        url?: string,
        data?: unknown,
    ): Promise<RequestDto> {
        const host = this.getHost(applicationInstall);
        const token = await this.getXoxpToken(dto, applicationInstall);
 
        let uri = `${host}${url ?? ''}`;
        if (uri.includes('?')) {
            uri = `${uri}&token=${token}`;
        } else {
            uri = `${uri}?token=${token}`;
        }
 
        const request = new RequestDto(uri, method, dto);
        request.setHeaders({
            [CommonHeaders.CONTENT_TYPE]: JSON_TYPE,
            [CommonHeaders.ACCEPT]: JSON_TYPE,
        });
 
        Iif (data) {
            request.setJsonBody(data);
        }
 
        return request;
    }
 
    protected async getXoxpToken(dto: AProcessDto, applicationInstall: ApplicationInstall): Promise<string> {
        const xoxpKey = this.xoxpIdKey(dto);
        const xoxpToken = await this.redis.get(xoxpKey);
        Eif (xoxpToken?.length) {
            return xoxpToken;
        }
 
        const accessKey = this.accessIdKey(dto);
        const accessToken = await this.redis.get(accessKey) ?? await this.getAccessToken(dto, applicationInstall);
 
        const request = new RequestDto(
            `${this.getHost(applicationInstall)}/icewarpapi/`,
            HttpMethods.POST,
            dto,
            `<iq uid="123456" type="set" format="xml"><query xmlns="admin:iq:rpc"><commandname>AuthenticateJWT</commandname><commandparams><token>${accessToken}</token></commandparams></query></iq>`,
            {
                'Content-Type': 'text/xml',
                Accept: 'text/xml',
            },
        );
        // eslint-disable-next-line
        const redis = this.redis;
        // eslint-disable-next-line
        const curl = this.curl;
        const sessionKey = this.sessionIdKey(dto);
 
        return this.cache.entryWithLock(
            this.xoxpIdKey(dto),
            this.xoxpIdLock(dto),
            request,
            async (resp): Promise<ICacheCallback<string>> => {
                const sessionId = [...resp.getBody()?.matchAll(/sid="(.+?)"/g)]?.[0]?.groups?.[1] || '';
 
                const requestXoxp = new RequestDto(
                    `${this.getHost(applicationInstall)}/icewarpapi/`,
                    HttpMethods.POST,
                    dto,
                    `<iq uid="123456" sid="${sessionId}" format="text/xml"><query xmlns="admin:iq:rpc"><commandname>AuthenticateTeamChatApi</commandname></query></iq>`,
                    {
                        'Content-Type': 'text/xml',
                        Accept: 'text/xml',
                    },
                );
 
                const expire = 23 * 60 * 60;
                const res = await curl.send(requestXoxp);
 
                const xoxp = [...res.getBody()?.matchAll(/<result>(.+?)<\/result>/g)]?.[0]?.groups?.[1] || '';
                await redis.set(sessionKey, xoxp, expire);
 
                return {
                    expire,
                    dataToStore: xoxp,
                };
            },
        );
    }
 
    protected async getAccessToken(dto: AProcessDto, applicationInstall: ApplicationInstall): Promise<string> {
        const accessKey = this.accessIdKey(dto);
        const accessToken = await this.redis.get(accessKey);
        if (accessToken?.length) {
            return accessToken;
        }
 
        const refreshKey = this.refreshIdKey(dto);
        const refreshToken = await this.redis.get(refreshKey) ?? applicationInstall.getSettings()?.[CoreFormsEnum.AUTHORIZATION_FORM]?.[REFRESH_TOKEN] ?? '';
 
        const request = new RequestDto(
            `${this.getHost(applicationInstall)}/icewarpapi/`,
            HttpMethods.POST,
            dto,
            `<iq uid="123456" type="set" format="xml"><query xmlns="admin:iq:rpc" ><commandname>RefreshJWTToken</commandname><commandparams><refreshtoken>${refreshToken}</refreshtoken></commandparams></query></iq>`,
            {
                'Content-Type': 'text/xml',
                Accept: 'text/xml',
            },
        );
        // eslint-disable-next-line
        const redis = this.redis;
 
        return this.cache.entryWithLock(
            this.accessIdKey(dto),
            this.accessIdLock(dto),
            request,
            async (resp): Promise<ICacheCallback<string>> => {
                const accessToken = [...resp.getBody()?.matchAll(/<accesstoken>(.+?)<\/accesstoken>/g)]?.[0]?.groups?.[1] || '';
                const refreshToken = [...resp.getBody()?.matchAll(/<refreshtoken>(.+?)<\/refreshtoken>/g)]?.[0]?.groups?.[1] || '';
 
                const tokenData = this.getTokenData(accessToken);
                await redis.set(refreshKey, refreshToken);
 
                return {
                    expire: Math.floor(((tokenData.exp * 1000) - (new Date().getTime())) * 0.001) - 60,
                    dataToStore: accessToken,
                };
            },
        );
    }
 
    protected sessionIdKey(dto: AProcessDto): string {
        return `icewarp-session-${dto.getUser()}`;
    }
 
    protected xoxpIdLock(dto: AProcessDto): string {
        return `icewarp-session-${dto.getUser()}-lock`;
    }
 
    protected accessIdKey(dto: AProcessDto): string {
        return `icewarp-access-${dto.getUser()}`;
    }
 
    protected xoxpIdKey(dto: AProcessDto): string {
        return `icewarp-xoxp-${dto.getUser()}`;
    }
 
    protected refreshIdKey(dto: AProcessDto): string {
        return `icewarp-refresh-${dto.getUser()}`;
    }
 
    protected accessIdLock(dto: AProcessDto): string {
        return `icewarp-access-${dto.getUser()}-lock`;
    }
 
    protected getHost(appInstall: ApplicationInstall): string {
        const authForm = appInstall.getSettings()[CoreFormsEnum.AUTHORIZATION_FORM];
        const tokenData = this.getTokenData(authForm[ACCESS_TOKEN]);
 
        return `https://${tokenData.iw_host}`;
    }
 
    private getTokenData(token: string): Record<string, any> {
        const part = token.split('.')?.[1] ?? '';
        const decoded = decode(part, 'base64');
 
        return JSON.parse(decoded || '{}');
    }
 
}