Validate jwt claims

This commit is contained in:
Zoe Roux 2025-03-25 10:26:56 +01:00
parent bcded031e2
commit 1f8652e06c
No known key found for this signature in database
2 changed files with 35 additions and 8 deletions

View File

@ -1,5 +1,6 @@
import Elysia, { t } from "elysia"; import Elysia, { getSchemaValidator, t } from "elysia";
import { createRemoteJWKSet, jwtVerify } from "jose"; import { createRemoteJWKSet, jwtVerify } from "jose";
import { KError } from "./models/error";
const jwtSecret = process.env.JWT_SECRET const jwtSecret = process.env.JWT_SECRET
? new TextEncoder().encode(process.env.JWT_SECRET) ? new TextEncoder().encode(process.env.JWT_SECRET)
@ -11,22 +12,34 @@ const jwks = createRemoteJWKSet(
), ),
); );
const Jwt = t.Object({
sub: t.String({ description: "User id" }),
username: t.String(),
sid: t.String({ description: "Session id" }),
});
const validator = getSchemaValidator(Jwt);
export const auth = new Elysia({ name: "auth" }) export const auth = new Elysia({ name: "auth" })
.guard({ .guard({
headers: t.Object({ // Those are not applied for now. See https://github.com/elysiajs/elysia/issues/1139
authorization: t.String({ pattern: "^Bearer .+$" }), detail: {
}), security: [{ bearer: ["read"] }, { api: ["read"] }],
},
response: {
401: { ...KError, description: "" },
403: { ...KError, description: "" },
},
}) })
.macro({ .macro({
permissions(perms: string[]) { permissions(perms: string[]) {
return { return {
beforeHandle: () => {}, resolve: async ({ headers: { authorization }, error }) => {
resolve: async ({ headers: { authorization } }) => {
const bearer = authorization?.slice(7); const bearer = authorization?.slice(7);
if (!bearer) return { jwt: false }; if (!bearer) return { jwt: false };
// @ts-expect-error ts can't understand that there's two overload idk why // @ts-expect-error ts can't understand that there's two overload idk why
const { payload: jwt } = await jwtVerify(bearer, jwtSecret ?? jwks); const { payload } = await jwtVerify(bearer, jwtSecret ?? jwks);
return { jwt }; // TODO: use perms
return { jwt: validator.Decode<typeof Jwt>(payload) };
}, },
}; };
}, },

View File

@ -55,6 +55,20 @@ app
description: "Routes about images: posters, thumbnails...", description: "Routes about images: posters, thumbnails...",
}, },
], ],
components: {
securitySchemes: {
bearer: {
type: "http",
scheme: "bearer",
bearerFormat: "opaque",
},
api: {
type: "apiKey",
in: "header",
name: "X-API-KEY",
},
},
},
}, },
}), }),
) )