All files / core/blong-gogo/src mle.ts

78.88% Statements 127/161
65.62% Branches 21/32
100% Functions 3/3
78.88% Lines 127/161

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 1621x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 15x 15x 15x 5x 15x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 3x 3x 3x 3x 3x                                     5x           5x 5x 15x 2x 2x 2x 2x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 11x 16x 16x 6x 6x 6x 16x 5x 5x   5x 5x 5x               5x 5x 5x 5x 5x 4x 4x 5x 5x 5x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 5x       5x 16x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x  
import type {FastifyInstance, FastifyRequest} from 'fastify';
import fp from 'fastify-plugin';
 
import jose from './jose.ts';
import isPublic from './public.ts';
 
export type IConfig = Parameters<typeof jose>[0] & {public: {sign: unknown; encrypt: unknown}};
 
export default fp<IConfig>(async function mlePlugin(fastify: FastifyInstance, config: IConfig) {
    const mle = await jose(config);
    if (config) {
        config.public.sign = mle.keys.sign;
        config.public.encrypt = mle.keys.encrypt;
    }
    fastify.addHook(
        'preValidation',
        async (request: FastifyRequest<{Body: {jsonrpc?: string}}>, reply) => {
            if (isPublic(request.originalUrl)) return;
            if (
                request.routeOptions.config.auth &&
                request.headers['content-type'] === 'application/json'
            ) {
                const [where, what]: [Record<string, unknown>, string] = (
                    request.body?.jsonrpc ? [request.body, 'params'] : [request, 'body']
                ) as [Record<string, unknown>, string];
                if (where[what] && request.routeOptions.config.mle !== false) {
                    // Check if the body looks MLE-encrypted (GeneralJWE with recipients, or CompactJWE string)
                    const isEncrypted =
                        typeof where[what] === 'string' ||
                        (typeof where[what] === 'object' &&
                            where[what] !== null &&
                            'recipients' in (where[what] as object));
                    if (!isEncrypted) return; // Plain JSON body — skip MLE
 
                    const credentials = request.auth?.credentials;
                    try {
                        if (credentials?.mlsk === 'header' && credentials?.mlek === 'header') {
                            const {
                                protectedHeader: {mlsk, mlek},
                                plaintext,
                            } = (await mle.decrypt(where[what] as string, {complete: true})) as {
                                plaintext: string | Uint8Array;
                                protectedHeader: {mlek?: {type: string}; mlsk?: {type: string}};
                            };
                            credentials.mlsk = mlsk;
                            credentials.mlek = mlek;
                            where[what] = await mle.verify(
                                plaintext,
                                mlsk as unknown as Parameters<typeof mle.verify>[1],
                            );
                        } else if (credentials?.mlsk) {
                            where[what] = await mle.decryptVerify(
                                where[what] as string,
                                credentials.mlsk as Parameters<typeof mle.decryptVerify>[1],
                            );
                        } else {
                            // No credentials (e.g. auth: 'login') — extract keys from JWE header
                            const {
                                protectedHeader: {mlsk, mlek},
                                plaintext,
                            } = (await mle.decrypt(where[what] as string, {complete: true})) as {
                                plaintext: string | Uint8Array;
                                protectedHeader: {mlek?: {type: string}; mlsk?: {type: string}};
                            };
                            // Store mlek on request so preSerialization can encrypt the response
                            (request as {mleKeys?: {mlsk: unknown; mlek: unknown}}).mleKeys = {
                                mlsk,
                                mlek,
                            };
                            where[what] = await mle.verify(
                                plaintext,
                                mlsk as unknown as Parameters<typeof mle.verify>[1],
                            );
                        }
                    } catch (error) {
                        reply.code(400);
                        const newError = new Error('Decryption failed');
                        newError.cause = error instanceof Error ? error : String(error);
                        throw newError;
                    }
                }
            }
        },
    );
    fastify.addHook(
        'preSerialization',
        async (
            request,
            reply,
            payload:
                | Error
                | {
                      id?: unknown;
                      jsonrpc?: unknown;
                      result?: Record<string, unknown>;
                      error?: Record<string, unknown>;
                      checkpoints?: unknown;
                  },
        ) => {
            if (isPublic(request.originalUrl)) return payload;
            if (payload instanceof Error) return payload;
            const mlek =
                request.auth?.credentials?.mlek ||
                (request as {mleKeys?: {mlek: unknown}}).mleKeys?.mlek;
            if (
                request.routeOptions.config.auth &&
                request.headers['content-type'] === 'application/json' &&
                payload &&
                mlek
            ) {
                const encrypt: (message: object) => unknown = message =>
                    request.routeOptions.config.mle === false
                        ? message
                        : mle.signEncrypt(message, mlek as {type: string});
                const where = payload.jsonrpc
                    ? payload
                    : {
                          result: payload,
                          id: undefined,
                          jsonrpc: undefined,
                          error: undefined,
                          checkpoints: undefined,
                      };
                let result,
                    error = undefined as string | undefined;
                const code = reply.statusCode.toString().slice(0, 1) + 'xx';
                if ('result' in where)
                    result = reply.serializeInput(
                        where.result as Record<string, unknown>,
                        code,
                    ) as string;
                if (payload.jsonrpc && 'error' in where)
                    error = reply.serializeInput(
                        payload.error as Record<string, unknown>,
                        code,
                    ) as string;
                reply.serializer(x => x);
                try {
                    return JSON.stringify({
                        id: where.id,
                        jsonrpc: where.jsonrpc,
                        result: result && (await encrypt(Buffer.from(result))),
                        error: error && (await encrypt(Buffer.from(error))),
                        checkpoints: where.checkpoints,
                    });
                } catch (error) {
                    reply.code(400);
                    throw error;
                }
            }
        },
    );
    fastify.route({
        method: 'GET',
        url: '/rpc/login/.well-known/mle',
        config: {auth: false},
        handler() {
            return config.public;
        },
    });
});