elysiajs / elysia

Ergonomic Framework for Humans
https://elysiajs.com
MIT License
10.64k stars 226 forks source link

Plugins not deduplicated when aot: true #842

Closed Scooter1337 closed 1 month ago

Scooter1337 commented 2 months ago

What version of Elysia is running?

1.1.16

What platform is your computer?

Darwin 24.0.0 arm64 arm

What steps can reproduce the bug?

export const requireAuthPlugin = () =>
  new Elysia({
    name: "requireAuth",
  })
    .onStart(async () => {
      console.log("🦊 Auth guard started");
    })
    .resolve(async function AuthGuard({ cookie: { auth_session }, request }) {
      console.log("Auth guard");
      if (!AuthHelpers.CSRFCheck(request)) {
        console.log("CSRF check failed");
        throw new Unauthorized("CSRF check failed");
      }

      if (!auth_session || !auth_session.value) {
        console.log("Session cookie not found");
        throw new Unauthorized("Session cookie not found");
      }

      const { session, user } = await lucia.validateSession(auth_session.value);
      if (!session || !user) {
        console.log("Invalid session");
        throw new Unauthorized("Invalid session");
      }

      if (session.fresh) {
        const sessionCookie = lucia.createSessionCookie(session.id);
        auth_session.set({
          domain: process.env.DOMAIN,
          value: sessionCookie.value,
          ...sessionCookie.attributes,
        });
      }
      return { session, user };
    });

What is the expected behavior?

Auth guard
GET [200] http://localhost:3000/settings/profile/me - timing disabled
Auth guard
GET [200] http://localhost:3000/settings/access_code - timing disabled

What do you see instead?

Auth guard
Auth guard
Auth guard
Auth guard
GET [200] http://localhost:3000/settings/profile/me - 5.19ms
GET [200] http://localhost:3000/settings/access_code - 7.63ms

Additional information

No response

Have you try removing the node_modules and bun.lockb and try again yet?

yes

EDIT

Going from:

const ProtectedControllers = new Elysia()
  .use(requireAuthPlugin)
  .use(companyController)
  .use(userSettingsController);

const UnprotectedControllers = new Elysia().use(authController);

export const Controllers = new Elysia()
  .use(UnprotectedControllers)
  .use(ProtectedControllers);

To:

const ProtectedControllers = new Elysia().use(requireAuthPlugin);

export const Controllers = new Elysia()
  .use(authController)
  .use(ProtectedControllers)
  .use(companyController)
  .use(userSettingsController);

Fixed it for some reason. Very odd!

Scooter1337 commented 1 month ago

For others having the same issue, my fix was actually calling the plugins' function.