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 { KError } from "./models/error";
const jwtSecret = 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" })
.guard({
headers: t.Object({
authorization: t.String({ pattern: "^Bearer .+$" }),
}),
// Those are not applied for now. See https://github.com/elysiajs/elysia/issues/1139
detail: {
security: [{ bearer: ["read"] }, { api: ["read"] }],
},
response: {
401: { ...KError, description: "" },
403: { ...KError, description: "" },
},
})
.macro({
permissions(perms: string[]) {
return {
beforeHandle: () => {},
resolve: async ({ headers: { authorization } }) => {
resolve: async ({ headers: { authorization }, error }) => {
const bearer = authorization?.slice(7);
if (!bearer) return { jwt: false };
// @ts-expect-error ts can't understand that there's two overload idk why
const { payload: jwt } = await jwtVerify(bearer, jwtSecret ?? jwks);
return { jwt };
const { payload } = await jwtVerify(bearer, jwtSecret ?? jwks);
// TODO: use perms
return { jwt: validator.Decode<typeof Jwt>(payload) };
},
};
},

View File

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