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

65.3% Statements 271/415
51.92% Branches 27/52
85.71% Functions 18/21
65.3% Lines 271/415

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 4161x 1x 1x 1x 1x 1x 1x     12x 12x                   1x 364x 364x 364x 364x 364x 364x 364x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 448x 448x       448x 448x 448x 448x     448x 6x 6x 813x 813x 446x 446x     446x   446x 446x 446x 446x 446x 446x 446x 446x 813x 6x 6x 6x 6x 6x 6x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 88x 6x 83x 83x 83x 83x 83x 83x 83x 6x 6x           6x 6x 6x 6x 6x 6x 6x 6x 6x 360x 360x 360x 360x 360x 360x 360x 360x                                                                                                                                 360x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x             6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x               6x 6x 6x 6x 6x 6x 6x 6x 6x 360x 360x 360x 360x 360x 360x 360x 360x 360x 360x 360x 360x 360x 360x 358x 358x 358x 358x 360x 360x 360x 360x 360x 360x   360x 360x       360x 360x 360x 360x 360x 360x 360x 360x 360x 6x 364x 364x 364x 364x 364x 364x 364x 364x 364x 364x 364x 364x 364x 364x                                       364x 364x 364x 364x 364x 364x 364x 364x       364x 364x 364x 6x         6x 82x 82x 6x 82x 82x               82x 82x 82x 6x 6x 6x 1x 1x 6x 1x 1x 1x 1x 1x       1x 1x 1x 6x 6x 2x 2x 6x 2x 2x 6x 6x 6x 1x 1x 6x 1x 1x 1x 1x 1x 1x 1x 1x       6x 6x  
import {deriveStreamKey, readStream, streamInfoOf, streamSalt} from '@feasibleone/blong-mle';
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;
}

/** Whether an answer arrived as a stream rather than as one JSON body. */
function isStreamBody(body: unknown): boolean {
    return (
        typeof body === 'object' &&
        body !== null &&
        typeof (body as ReadableStream<Uint8Array>).getReader === 'function'
    );
}
 
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;
    /**
     * The pair a sealed stream is opened with, kept here because `receive` runs
     * outside `ready()`'s scope and the key agreement needs the private half
     * (`@@D-949`). It is the same pair every MLE message is signed and decrypted
     * with — nothing extra is generated for a stream.
     */
    let streamPair: {
        clientKey: {encrypt: Record<string, unknown>};
        serverKey: {encrypt: Record<string, unknown>};
    } | null = null;
 
    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() {
            /**
             * The pair is kept across a reload, which is what the write below has always assumed.
             *
             * A caller's session is opened with the pair it presented when it logged in — the realm
             * that answers the session hands those two public keys back — and every later call is
             * verified against the signing half of it. A reload that minted a new pair therefore
             * signed with a key the session had never seen, and the gateway answered
             * `Decryption failed` with `ERR_JWS_SIGNATURE_VERIFICATION_FAILED` underneath, on the
             * first call of every page that logs in by reloading (F-497). The value is written below
             * and was never read back, which is the shape of a half-finished feature rather than a
             * decision: keeping it is now deliberate — a private JWK in `localStorage` is readable by
             * any script on this origin, and the alternative is a session re-opened after every
             * reload, which needs the caller's keys to travel with the call instead (D-530).
             */
            let mleKey = null;
            if (isBrowser) {
                try {
                    mleKey = JSON.parse(window.localStorage.getItem('mle-jose') || 'null');
                } catch {
                    mleKey = 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;
                streamPair = {
                    clientKey: mleKey.clientKey as {encrypt: Record<string, unknown>},
                    serverKey: mleKey.serverKey as {encrypt: Record<string, unknown>},
                };
            }
        },
        async send(
            params: {
                $http?: {
                    url?: string;
                    method?: string;
                    headers?: Record<string, 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;
            }
            // The UI's active language rides with every call, so a read answers with
            // its labels and its record names in the language the reader is looking at.
            // It is read from the document — where `setLanguage` publishes it — rather
            // than from the token, because a switch must reach the server without a new
            // session (`D-635`).
            const language = isBrowser
                ? globalThis.document?.documentElement?.dataset['language']
                : undefined;
            if (language) {
                $http = $http || {};
                $http.headers = {...$http.headers, 'x-blong-language': language};
            }
            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,
        ) {
            // A sealed stream is the one answer this codec owns outright: its frames
            // are sealed under a key only the two key pairs in hand can agree, and
            // this is where both of them live (`@@D-949`). The body is not JSON, so
            // nothing below may try to decrypt it.
            if (isStreamBody(result.body)) {
                const streamed = {
                    headers: result.headers,
                    body: result.body as unknown as ReadableStream<Uint8Array>,
                };
                const salt = streamSalt(streamed);
                if (salt && streamPair) {
                    const method = String((($meta as {method?: string}) ?? {}).method ?? '');
                    const key = await deriveStreamKey({
                        privateJwk: streamPair.clientKey.encrypt,
                        peerPublicJwk: streamPair.serverKey.encrypt,
                        salt,
                        info: streamInfoOf(method),
                    });
                    return readStream(streamed, {key, info: streamInfoOf(method)});
                }
                // Unsealed: the codec beneath this one reads it, and there is
                // nothing here for a key to open.
                return super.receive(result, $meta);
            }
            await decrypt(result.body, 'error');
            await decrypt(result.body, 'result');
            // A capture with its own note: the body is a JSON document, and the sentence says which
            // half of the exchange it came from (`@@T-730`).
            const failed = Boolean(result.body?.error);
            this.capture?.json?.(
                {method: String((($meta as {method?: string}) ?? {}).method ?? 'mle.receive')},
                () => ({
                    label: failed ? 'mle.error' : 'mle.result',
                    value: failed ? result.body?.error : result.body?.result,
                }),
            );
            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) {
                // The base `receive` reads an error from the *decrypted* body and this hook
                // delegates to it, so the error has to be decrypted here: without this the
                // encrypted envelope is what a failed login throws, and the reason for the
                // failure is unreadable to the caller that has to act on it.
                await decrypt(result.body, '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) {
                await decrypt(result.body, '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) {
                await decrypt(result.body, 'error');
                return super.receive(result, $meta);
            }
            readToken(result.body.result as IToken);
            return super.receive(result, $meta);
        },
    };
});