All files / blong-gogo/src busGateway.ts

23.84% Statements 67/281
50% Branches 1/2
20% Functions 1/5
23.84% Lines 67/281

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 2821x 1x 1x 1x 1x 1x   1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x   10x 10x             10x 10x                                                                                                                     10x 10x                                                                                                                                                                                                                                                                                                         10x  
// const request = (process.type === 'renderer') ? require('ut-browser-request') : require('request');
// const [httpPost] = [request.post].map(require('util').promisify);
import type {Errors, IMeta, ITypedError} from '@feasibleone/blong';
import ky from 'ky';
 
const decode = (result: unknown, method: string, unpack: boolean) =>
    unpack ? result : [result, {method, mtid: 'response'}];
 
export default ({
    serverInfo,
    mleClient,
    errors,
    get,
}: {
    serverInfo: (key: 'protocol' | 'port') => string;
    mleClient: {
        keys: {sign?: string; encrypt?: string};
        signEncrypt: (
            params: unknown,
            encryptKey: string,
            localKeys?: {mlsk: string; mlek: string},
        ) => Promise<unknown>;
        decryptVerify: (result: unknown, signKey: string) => Promise<unknown>;
    };
    errors: Errors<{
        'bus.jsonRpcHttp': unknown;
        'bus.jsonRpcEmpty': unknown;
    }>;
    get: (
        url: string,
        httpErrorType: (params?: unknown, $meta?: IMeta) => ITypedError,
        emptyErrorType: (params?: unknown, $meta?: IMeta) => ITypedError,
    ) => Promise<{
        sign: string;
        encrypt: string;
    }>;
}) => {
    const localCache: Record<
        string,
        {
            auth?: {
                access_token: string;
                refresh_token: string;
                expires_in: number;
                refresh_token_expires_in: number;
                sign?: string;
                encrypt?: string;
            };
            tokenInfo?: {
                tokenExpire: number;
                refreshTokenExpire: number;
            };
            remoteKeys?: {
                sign: string;
                encrypt: string;
            };
        }
    > = {};
    const localKeys =
        mleClient.keys.sign && mleClient.keys.encrypt
            ? {mlsk: mleClient.keys.sign, mlek: mleClient.keys.encrypt}
            : undefined;
 
    function tokenInfo(auth: {expires_in: number; refresh_token_expires_in: number}) {
        const now = Date.now() - 5000; // latency tolerance of 5 seconds
        return {
            tokenExpire: now + auth.expires_in * 1000,
            refreshTokenExpire: now + auth.refresh_token_expires_in * 1000,
        };
    }
 
    async function login(
        cache: (typeof localCache)[string],
        url: string,
        username?: string,
        password?: string,
        channel?: string,
    ) {
        const {sign, encrypt} = (localKeys && (cache.auth || cache.remoteKeys)) || {};
        if (sign && encrypt && localKeys) {
            const {result, error} = await ky
                .post<{result: unknown; error: unknown}>(`${url}/rpc/login/identity/exchange`, {
                    json: {
                        jsonrpc: '2.0',
                        method: 'login.identity.exchange',
                        id: 1,
                        params: await mleClient.signEncrypt(
                            {username, password, channel},
                            encrypt,
                            localKeys,
                        ),
                    },
                })
                .json();
            if (error) throw Object.assign(new Error(), await mleClient.decryptVerify(error, sign));
            else if (result)
                cache.auth = (await mleClient.decryptVerify(result, sign)) as {
                    access_token: string;
                    refresh_token: string;
                    expires_in: number;
                    refresh_token_expires_in: number;
                    sign?: string;
                    encrypt?: string;
                };
            else throw errors['bus.jsonRpcEmpty']();
        } else {
            const {result, error} = await ky
                .post<{result: unknown; error: unknown}>(`${url}/rpc/login/identity/check`, {
                    json: {
                        jsonrpc: '2.0',
                        method: 'login.identity.check',
                        id: 1,
                        params: {username, password, channel},
                    },
                })
                .json();
            if (error) throw Object.assign(new Error(), error);
            else if (result)
                cache.auth = result as {
                    access_token: string;
                    refresh_token: string;
                    expires_in: number;
                    refresh_token_expires_in: number;
                    sign?: string;
                    encrypt?: string;
                };
            else throw errors['bus.jsonRpcEmpty']();
        }
        cache.tokenInfo = tokenInfo(cache.auth);
    }
 
    return async function gateway({
        username,
        password,
        channel = 'web',
        protocol = serverInfo('protocol'),
        host: hostname = 'localhost',
        port = serverInfo('port'),
        url,
        auth,
        method,
    }: {
        username?: string;
        password?: string;
        channel?: string;
        protocol?: string;
        host?: string;
        port?: number | string;
        url?: string;
        tls?: boolean;
        auth?: {
            access_token: string;
            refresh_token: string;
            expires_in: number;
            refresh_token_expires_in: number;
            sign?: string;
            encrypt?: string;
        };
        encrypt?: boolean;
        method: string;
    }) {
        // don't put a default value for uri in arguments as it can be empty string or null
        if (url) {
            const parsed = new URL(url);
            hostname = parsed.hostname;
            port = parsed.port;
            protocol = parsed.protocol.split(':')[0];
            if (parsed.username) username = parsed.username;
            if (parsed.password) password = parsed.password;
        } else {
            protocol = protocol && protocol.split(':')[0];
            url = `${protocol}://${hostname}:${port}`;
        }

        const codec: {
            encode?: (params: unknown) => Promise<unknown> | unknown;
            decode?: (result: unknown, unpack: boolean) => Promise<unknown> | unknown;
            requestParams?: {
                protocol: string;
                hostname: string;
                port: number | string;
                path: string;
            };
        } = {
            requestParams: {
                protocol,
                hostname,
                port,
                path: `/rpc/${method.replace(/\./g, '/')}`,
            },
        };

        const cache = (localCache[url] = localCache[url] || {});

        if (localKeys && !cache.remoteKeys) {
            const body = await get(
                `${url}/rpc/login/.well-known/mle`,
                errors['bus.jsonRpcHttp'],
                errors['bus.jsonRpcEmpty'],
            );
            if (body.sign && body.encrypt) cache.remoteKeys = body;
        }

        if (auth) {
            cache.auth = auth;
            cache.tokenInfo = tokenInfo(auth);
        }

        if (!cache.auth && !(username && password)) {
            if (cache.remoteKeys) {
                const remoteKeys = cache.remoteKeys;
                codec.encode = async params => ({
                    params: await mleClient.signEncrypt(
                        params,
                        remoteKeys.encrypt,
                        localKeys,
                    ),
                    method,
                });
                codec.decode = async (result, unpack) =>
                    decode(
                        await mleClient.decryptVerify(result, remoteKeys.sign),
                        method,
                        unpack,
                    );
            } else {
                codec.encode = params => ({params, method});
                codec.decode = (result, unpack) => decode(result, method, unpack);
            }
            return codec;
        }

        if (!cache.auth) await login(cache, url, username, password, channel);

        const exp = Date.now();

        if (exp > cache.tokenInfo!.tokenExpire) {
            if (exp > cache.tokenInfo!.refreshTokenExpire) {
                await login(cache, url, username, password, channel);
            } else {
                const {body} = await ky
                    .post<{body: {expires_in: number; refresh_token_expires_in: number}}>(
                        `${url}/rpc/login/token`,
                        {
                            json: {
                                grant_type: 'refresh_token',
                                refresh_token: cache.auth!.refresh_token,
                            },
                        },
                    )
                    .json();
                Object.assign(cache.auth!, body);
                cache.tokenInfo = tokenInfo(body);
            }
        }

        const cachedAuth = cache.auth!;
        if (cachedAuth.sign && cachedAuth.encrypt) {
            codec.encode = async params => ({
                params: await mleClient.signEncrypt(params, cachedAuth.encrypt!),
                headers: {
                    authorization: 'Bearer ' + cachedAuth.access_token,
                },
                method,
            });
            codec.decode = async (result, unpack) =>
                decode(await mleClient.decryptVerify(result, cachedAuth.sign!), method, unpack);
        } else {
            codec.encode = params => ({
                params,
                headers: {
                    authorization: 'Bearer ' + cachedAuth.access_token,
                },
                method,
            });
            codec.decode = (result, unpack) => decode(result, method, unpack);
        }

        return codec;
    };
};