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 | 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 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 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 10x 2x 2x 2x 2x 2x 10x 10x 10x 10x 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, type ILocal} 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;
/** Allowed action methodIds — populated by the authorize handler. */
actions?: string[];
};
};
}
interface FastifyReply {
unstate: (name: string) => this;
state: (name: string, value: string, options: unknown) => this;
}
interface FastifyContextConfig {
methodName?: string;
}
}
export default fp<{
cache: object | false;
audience: string;
verify: IGatewayCodec['verify'];
errors: Errors<object>;
authorize?: string;
local?: ILocal;
methodId?: (name: string) => string;
methodParts?: (name: string) => string;
}>(
async function jwtPlugin(
fastify: FastifyInstance,
{
cache: cacheConfig,
audience,
verify,
errors,
authorize,
local,
methodId,
methodParts,
}: 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 permissionMap = Buffer.from(per, 'base64');
const credentials: Record<string, unknown> = {
mlek,
mlsk,
permissionMap,
actorId,
sessionId,
...rest,
};
// Call the authorize handler to resolve the list of allowed actions
if (authorize && local && methodId && methodParts) {
const handlerName = methodParts(authorize);
const reqName = `ports.${handlerName.split('.', 1)[0]}.request`;
const handler = local.get(reqName);
if (handler) {
const result = await handler.method(
{permissionMap},
{
method: handlerName,
mtid: 'request',
},
);
credentials.actions = Array.isArray(result) ? result[0] : result;
}
}
if (cache) cache.set(token, credentials, {ttl: exp * 1000 - Date.now()});
req.auth = {credentials: credentials as FastifyRequest['auth']['credentials']};
return true;
},
});
// Authorization hook: check the called method against allowed actions
if (authorize && local && methodId) {
fastify.addHook('preHandler', function (request, _reply, done) {
// Routes with auth: false or auth: 'login' don't go through bearer auth,
// so credentials have no actions. Skip the authorization check.
if (
!request.routeOptions.config.auth ||
request.routeOptions.config.auth === 'login'
) {
done();
return;
}
// The authorize handler itself must be accessible without authorization,
// otherwise we have a chicken-and-egg problem — you'd need authorization
// to call the handler that resolves authorization.
const methodName = request.routeOptions.config.methodName;
if (authorize && methodName && methodParts) {
const normalizedMethod = methodParts(authorize);
if (methodName === normalizedMethod) {
done();
return;
}
}
const credentials = request.auth?.credentials;
if (!credentials?.actions) {
done(new Error('Authorization denied: no actions resolved'));
return;
}
if (!methodName) {
done(); // no method configured — allow (backward compat)
return;
}
const requestedId = methodId(methodName);
if (credentials.actions.includes(requestedId)) {
done();
} else {
const error = new Error(
`Authorization denied: method "${methodName}" not allowed`,
) as Error & {statusCode: number};
error.statusCode = 403;
done(error);
}
});
}
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',
},
);
|