All files / blong-gogo/src jwt.ts

78.52% Statements 117/149
90.9% Branches 10/11
66.66% Functions 2/3
78.52% Lines 117/149

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 1501x 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 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 17x 17x 14x 4x 4x 14x 10x 10x 17x 17x 10x 10x 10x 10x 10x 10x 10x 10x 8x 8x 8x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 10x 10x 10x 10x     10x 10x 10x                                                             10x 10x 1x 1x 1x 1x 1x  
import basic from '@fastify/basic-auth';
import bearer from '@fastify/bearer-auth';
import cookie from '@fastify/cookie';
import {type Errors} from '@feasibleone/blong/types';
import type {FastifyInstance, FastifyPluginOptions, FastifyReply, FastifyRequest} from 'fastify';
import fp from 'fastify-plugin';
import {LRUCache} from 'lru-cache';
 
import {type IGatewayCodec} from './GatewayCodec.ts';
 
declare module 'fastify' {
    interface FastifyRequest {
        auth: {
            credentials: {
                language?: unknown;
                mlek?: object | 'header';
                mlsk?: object | 'header';
                permissionMap?: Buffer;
                actorId?: string | number;
                sessionId?: string;
            };
        };
    }
    interface FastifyReply {
        unstate: (name: string) => this;
        state: (name: string, value: string, options: unknown) => this;
    }
}
 
export default fp<{
    cache: object | false;
    audience: string;
    verify: IGatewayCodec['verify'];
    errors: Errors<object>;
}>(
    async function jwtPlugin(
        fastify: FastifyInstance,
        {cache: cacheConfig, audience, verify, errors}: FastifyPluginOptions,
    ) {
        const cache =
            ![0, false, 'false'].includes(cacheConfig as string | number | boolean) &&
            new LRUCache({max: 1000, ...cacheConfig});
        await fastify.register(basic, {
            async validate(_username: string, _password: string, _req: unknown, _reply: unknown) {},
        });
        fastify.addHook(
            'preValidation',
            function (request: FastifyRequest, reply: FastifyReply, done: (err?: Error) => void) {
                const auth = request.routeOptions.config.auth;
                if (auth !== false && !request.originalUrl.startsWith('/documentation')) {
                    if (auth === 'login') {
                        request.auth = {credentials: {mlek: 'header', mlsk: 'header'}};
                        done();
                    } else {
                        return this?.verifyBearerAuth?.(request, reply, done);
                    }
                } else done();
            },
        );
        await fastify.register(bearer, {
            keys: new Set([]),
            addHook: false,
            auth: async (token, req) => {
                if (!token) throw errors['gateway.jwtMissingHeader']();
                const cachedCredentials = cache && cache.get(token);
                if (cachedCredentials) {
                    req.auth = {credentials: cachedCredentials};
                    return true;
                }
                const decoded = await verify(token, {audience});
                const {
                    // standard
                    exp,
                    aud, // eslint-disable-line @typescript-eslint/no-unused-vars
                    iss, // eslint-disable-line @typescript-eslint/no-unused-vars
                    iat, // eslint-disable-line @typescript-eslint/no-unused-vars
                    jti, // eslint-disable-line @typescript-eslint/no-unused-vars
                    nbf, // eslint-disable-line @typescript-eslint/no-unused-vars
                    sub: actorId,
                    // headers
                    typ, // eslint-disable-line @typescript-eslint/no-unused-vars
                    cty, // eslint-disable-line @typescript-eslint/no-unused-vars
                    alg, // eslint-disable-line @typescript-eslint/no-unused-vars
                    // custom
                    sig: mlsk,
                    enc: mlek,
                    ses: sessionId,
                    per = '',
                    // arbitrary
                    ...rest
                } = decoded;
                const credentials = {
                    mlek,
                    mlsk,
                    permissionMap: Buffer.from(per, 'base64'),
                    actorId,
                    sessionId,
                    ...rest,
                };
                if (cache) cache.set(token, credentials, {ttl: exp * 1000 - Date.now()});
                req.auth = {credentials};
                return true;
            },
        });
        await fastify.register(cookie, {});
        fastify.decorateRequest('auth');
        fastify.decorateReply('unstate', function (name: string) {
            return this.clearCookie(name);
        });
        (fastify.decorateReply as (name: string, fn: unknown) => void)(
            'state',
            function (this: FastifyReply, name: string, value: string, options: unknown) {
                const {
                    ttl: maxAge,
                    isSecure: secure,
                    isHttpOnly: httpOnly,
                    isSameSite: sameSite,
                    path,
                    domain,
                } = options as {
                    ttl?: number;
                    isSecure?: boolean;
                    isHttpOnly?: boolean;
                    isSameSite?: boolean;
                    path?: string;
                    domain?: string;
                };
                return this.setCookie(
                    name,
                    value,
                    Object.fromEntries(
                        Object.entries({
                            maxAge: maxAge && Math.floor(maxAge / 1000),
                            secure,
                            httpOnly,
                            sameSite,
                            path,
                            domain,
                        }).filter(([, value]) => value != null),
                    ),
                );
            },
        );
    },
    {
        fastify: '5.x',
        name: 'blong-jwt',
    },
);