All files / core/blong-gogo/src/codec/adapter/mle ready.ts

61% Statements 183/300
47.36% Branches 18/38
55% Functions 11/20
61% Lines 183/300

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 3011x 1x 1x 1x 1x 1x     2x 2x                           1x 1x 1x 1x 1x 1x 1x 6x 6x       6x 6x 6x 6x     6x 1x 1x 10x 10x 5x 5x     5x   5x 5x 5x 5x 5x 5x 5x 5x 10x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x                                                                                                                     4x 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 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 1x         1x 2x 2x 1x 2x 2x 2x 2x 2x 1x 1x 1x     1x           1x 1x     1x     1x 1x 1x     1x           1x 1x  
import {handler} from '@feasibleone/blong/types';
import {type Response} from 'got';
import {exportJWK, generateKeyPair} from 'jose';
import joseFactory from '../../../jose.ts';
 
const isBrowser: boolean = typeof window !== 'undefined' && typeof window.document !== 'undefined';

const key = async (alg: string, options?: object): Promise<object> => ({
    alg,
    ...(await exportJWK((await generateKeyPair(alg, options)).privateKey)),
});

interface IToken {
    access_token: string;
    expires_in: number;
    refresh_token?: string;
    refresh_token_expires_in?: number;
}

export default handler<{
    token: unknown;
    tokenExpire: number;
}>(({config: {token, tokenExpire}}) => {
    let jose: Awaited<ReturnType<typeof joseFactory>> | undefined,
        serverKey: {encrypt: unknown; sign: unknown},
        pending: Promise<{body?: unknown}> | null,
        refreshToken: string | null,
        refreshTokenExpire: number;
 
    const encrypt = (msg: unknown, protectedHeader?: object): unknown => {
        return jose
            ? globalThis.window &&
              msg &&
              (msg as Record<string, unknown>).formData instanceof globalThis.window.FormData
                ? msg
                : jose.signEncrypt(
                      msg as object,
                      serverKey.encrypt as Parameters<typeof jose.signEncrypt>[1],
                      protectedHeader,
                  )
            : msg;
    };
 
    const decrypt = async (object: object, property: string): Promise<void> => {
        const rec = object as Record<string, unknown>;
        if (rec?.[property] && typeof rec[property] !== 'string') {
            if (
                typeof window === 'object' &&
                'result' in rec &&
                rec.result instanceof window.Blob
            ) {
                rec[property] = rec.result;
            } else if (jose) {
                const decrypted = await jose.decryptVerify(
                    rec[property] as Parameters<typeof jose.decryptVerify>[0],
                    serverKey.sign as Parameters<typeof jose.decryptVerify>[1],
                );
                if (rec) rec[property] = decrypted;
            }
        }
    };
 
    // Public (auth: 'login') endpoints — pre-auth callers hold no blong token, so the MLE
    // request is encrypted with the handshake keys carried in the JWE protected header.
    // Shared by the loginTokenCreate / accessRegistrationAdd / loginTokenExchange /
    // loginTokenRefresh / loginTokenRestore request senders.
    const encryptPublic = async (
        params: {$http?: unknown} & Record<string, unknown>,
    ): Promise<{$http?: unknown} & Record<string, unknown>> => {
        if (!jose) return params;
        const {$http, ...rest} = params;
        const encrypted = (await encrypt(rest, {
            mlsk: jose.keys.sign,
            mlek: jose.keys.encrypt,
        })) as typeof params;
        if ($http && encrypted) encrypted.$http = $http;
        return encrypted;
    };
    function readToken(where: IToken): void {
        tokenExpire = Date.now() + where.expires_in * 1000 - 5000; // let it refresh 5 seconds earlier
        token = where.access_token;
        if (where.refresh_token) {
            refreshToken = where.refresh_token;
            refreshTokenExpire = Date.now() + where.refresh_token_expires_in! * 1000 + 5000; // give it extra 5 seconds validity
        }
    }
 
    function clearTokens(): void {
        token = null;
        tokenExpire = 0;
        refreshToken = null;
        refreshTokenExpire = 0;
    }
 
    /**
     * Redeem a refresh token at `login.token.refresh` (auth: 'login' — MLE
     * handshake keys, plain JSON-RPC response).  On success the new access +
     * refresh tokens are stored in memory.  On refusal (revoked / inactive /
     * expired session) the tokens are cleared so the next request surfaces a
     * clean 401 to the caller, which the UI turns into a login prompt.
     */
    async function refresh(this: {
        exec?(...params: unknown[]): Promise<unknown>;
        error?(error: unknown, $meta?: unknown): void;
    }, opts: {force?: boolean} = {}): Promise<void> {
        const now = Date.now();
        if (token && (opts.force || tokenExpire < now)) {
            if (refreshToken && refreshTokenExpire > now) {
                try {
                    pending =
                        pending ||
                        (async () => {
                            const params = await encryptPublic({refreshToken});
                            const result = (await this.exec!(
                                {
                                    path: '/rpc/login/token/refresh',
                                    method: 'POST',
                                    responseType: 'json',
                                    json: {
                                        jsonrpc: '2.0',
                                        id: 1,
                                        method: 'login.token.refresh',
                                        params,
                                    },
                                },
                                {},
                            )) as {
                                statusCode?: number;
                                body?: {result?: IToken; error?: {type?: string; message?: string; statusCode?: number}};
                            };
                            return result;
                        })();
                    const result = await pending!;
                    if (pending !== null) pending = null;
                    const {body, statusCode} = result as {
                        statusCode?: number;
                        body?: {result?: IToken; error?: {type?: string; message?: string; statusCode?: number}};
                    };
                    // The gateway MLE-encrypts the response with the handshake
                    // keys, so decrypt the result before reading the token.
                    await decrypt(body as object, 'result');
                    if (body?.error || (statusCode != null && statusCode >= 400)) {
                        clearTokens();
                        const error = new Error(
                            body?.error?.message || 'Token refresh failed',
                        ) as Error & {
                            type?: string;
                            statusCode?: number;
                            auth?: boolean;
                        };
                        error.type = body?.error?.type || 'rpc.refreshFailed';
                        error.statusCode = body?.error?.statusCode ?? statusCode ?? 401;
                        error.auth = true;
                        throw error;
                    }
                    readToken(body!.result as IToken);
                } catch (error) {
                    pending = null;
                    // Keep auth-classified failures as-is; otherwise drop tokens
                    // so the next request reports a clean 401.
                    if (!(error as {auth?: boolean}).auth) clearTokens();
                    throw error;
                }
            } else clearTokens();
        }
    }
 
    return {
        async ready() {
            let mleKey = null; // isBrowser && JSON.parse(window.localStorage.getItem('mle-jose') || 'null');
            if (!mleKey) {
                const {body: {sign, encrypt} = {}}: {body?: {sign?: unknown; encrypt?: unknown}} =
                    (await (this as {exec?(...params: unknown[]): Promise<unknown>}).exec!(
                        {
                            method: 'GET',
                            responseType: 'json',
                            path: '/rpc/login/.well-known/mle',
                        },
                        {},
                    )) as {body?: {sign?: unknown; encrypt?: unknown}};
                if (sign && encrypt) {
                    const signKey = await key('ES384', {crv: 'P-384', extractable: true});
                    const encryptKey = await key('ECDH-ES+A256KW', {
                        crv: 'P-384',
                        extractable: true,
                    });
                    mleKey = {
                        serverKey: {sign, encrypt},
                        clientKey: {
                            sign: signKey,
                            encrypt: encryptKey,
                        },
                    };
                    if (isBrowser) window.localStorage.setItem('mle-jose', JSON.stringify(mleKey));
                }
            }
            if (mleKey) {
                if (isBrowser && (!window.crypto || !window.crypto.subtle)) {
                    const errorMessage =
                        window.location.protocol === 'https:'
                            ? "Your browser doesn't support SubtleCrypto interface of the Web Crypto API"
                            : 'SubtleCrypto interface of the Web Crypto API is available only in secure contexts (HTTPS) ';
                    window.alert(errorMessage);
                    throw new Error(errorMessage);
                }
                jose = await joseFactory(mleKey.clientKey);
                serverKey = mleKey.serverKey;
            }
        },
        async send(
            params: {
                $http?: {
                    url?: string;
                    method?: string;
                    headers?: {authorization?: string};
                    path?: unknown;
                };
            },
            $meta: unknown,
        ) {
            let {$http, ...rest} = params; // eslint-disable-line prefer-const
            params = (await encrypt(params instanceof Array ? params : rest)) as typeof params;
            await refresh.call(this);
            if (token) {
                $http = $http || {};
                if (!$http.headers) $http.headers = {};
                $http.headers.authorization = 'Bearer ' + token;
            }
            if ($http && params) params.$http = $http;
            // An unexpected 401 is surfaced as-is: the automatic pre-send
            // `refresh()` above already renewed the token when it was close to
            // expiry, so a 401 here means the session is genuinely unusable
            // (e.g. revoked/closed server-side) — a forced renewal would only
            // add a failing round-trip.  The UI turns the 401 into a login
            // prompt.
            return super.send(params, $meta);
        },
        async receive(
            result: Response<{
                jsonrpc?: string;
                error?: object;
                result?: object;
                validation?: unknown;
                debug?: unknown;
            }>,
            $meta: unknown,
        ) {
            await decrypt(result.body, 'error');
            await decrypt(result.body, 'result');
            this.log?.debug?.(
                {...(result.body?.error || result.body?.result), $meta},
                result.body?.error ? 'Received error response' : 'Received successful response',
            );
            return super.receive(result, $meta);
        },
        async errorReceive(result: Response, $meta: unknown) {
            if (result.statusCode === 401) token = null;
            await decrypt(result.body as object, 'error');
            return super.receive(result, $meta);
        },
        async loginTokenCreateRequestSend(params: {$http?: unknown}, $meta: unknown) {
            return super.send(await encryptPublic(params), $meta);
        },
        async loginTokenCreateResponseReceive(result: Response<{result: unknown}>, $meta: unknown) {
            await decrypt(result.body, 'result');
            if ((result.body as {error?: unknown})?.error) return super.receive(result, $meta);
            readToken(result.body.result as IToken);
            return super.receive(result, $meta);
        },
        // Explicit token renewal (auth: 'login') — the same path the automatic
        // `refresh()` uses; feeds the new tokens into memory.
        async loginTokenRefreshRequestSend(params: {$http?: unknown}, $meta: unknown) {
            return super.send(await encryptPublic(params), $meta);
        },
        async loginTokenRefreshResponseReceive(result: Response<{result: unknown}>, $meta: unknown) {
            await decrypt(result.body, 'result');
            if ((result.body as {error?: unknown})?.error) return super.receive(result, $meta);
            readToken(result.body.result as IToken);
            return super.receive(result, $meta);
        },
        // Public (auth: 'login') endpoints — see encryptPublic.
        async accessRegistrationAddRequestSend(params: {$http?: unknown}, $meta: unknown) {
            return super.send(await encryptPublic(params), $meta);
        },
        async loginTokenExchangeRequestSend(params: {$http?: unknown}, $meta: unknown) {
            return super.send(await encryptPublic(params), $meta);
        },
        // Session restore (auth: 'login') — exchanges the path-scoped HttpOnly
        // cookie for fresh tokens; the response feeds the same readToken path.
        async loginTokenRestoreRequestSend(params: {$http?: unknown}, $meta: unknown) {
            return super.send(await encryptPublic(params), $meta);
        },
        async loginTokenRestoreResponseReceive(result: Response<{result: unknown}>, $meta: unknown) {
            await decrypt(result.body, 'result');
            if ((result.body as {error?: unknown})?.error) return super.receive(result, $meta);
            readToken(result.body.result as IToken);
            return super.receive(result, $meta);
        },
    };
});