All files / blong-gogo/src mle.ts

85.92% Statements 116/135
72% Branches 18/25
100% Functions 3/3
85.92% Lines 116/135

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 1361x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 17x 17x 14x 17x 14x 14x 14x 14x 14x 14x       14x 14x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 14x 10x 10x 10x 10x 10x 14x           14x 14x 17x 1x 1x 1x 1x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 14x 14x 17x 14x 14x   14x 14x 14x 14x 14x 14x               14x 14x 14x 14x 14x 10x 10x 14x 14x 14x 4x 4x 14x 14x 14x 14x 14x 14x 14x 14x 4x 4x 14x       14x 17x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import type {FastifyInstance, FastifyRequest} from 'fastify';
import fp from 'fastify-plugin';
 
import jose from './jose.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 (
                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) {
                    const credentials = request.auth?.credentials;
                    if (!credentials) {
                        reply.code(401);
                        throw new Error('Missing authorization');
                    }
                    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 {
                            where[what] = await mle.decryptVerify(
                                where[what] as string,
                                credentials.mlsk as Parameters<typeof mle.decryptVerify>[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 (payload instanceof Error) return payload;
            if (
                request.routeOptions.config.auth &&
                request.headers['content-type'] === 'application/json' &&
                payload
            ) {
                const encrypt: (message: object) => unknown = message =>
                    request.routeOptions.config.mle === false
                        ? message
                        : mle.signEncrypt(
                              message,
                              request.auth?.credentials?.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;
        },
    });
});