import { describe, expect, it } from 'vitest'; import { auth } from '#lib/server/auth.ts'; const { authRouteAllowed } = await import('#lib/server/auth-routes.ts'); type AdminPlugin = { endpoints?: Record; options?: { roles?: Record }; }; type RoleCheck = { authorize: (request: Record) => { success: boolean } }; /** * The plugin the app actually registered, so an upgrade that adds an endpoint or * changes a permission fails here rather than in production. */ function adminPlugin(): AdminPlugin { const plugin = (auth.options.plugins ?? []).find((entry) => entry.id === 'admin'); if (!plugin) throw new Error('the admin plugin is not registered'); return plugin as AdminPlugin; } function registeredPaths(): string[] { return Object.values(adminPlugin().endpoints ?? {}).flatMap((endpoint) => typeof endpoint.path === 'string' ? [endpoint.path] : [] ); } function adminRole(): RoleCheck { const role = adminPlugin().options?.roles?.admin; if (!role) throw new Error('the admin role is not configured'); return role; } describe('the admin plugin over HTTP', () => { it('is refused by the route gate on every path the plugin registers', () => { const paths = registeredPaths(); expect(paths.length).toBeGreaterThan(0); for (const path of paths) { expect(authRouteAllowed(`/api/auth${path}`, 'POST'), path).toBe(false); } }); it('is disabled inside better-auth, so a forwarding mistake cannot open it', () => { expect([...(auth.options.disabledPaths ?? [])].sort()).toEqual(registeredPaths().sort()); }); }); describe('the admin role', () => { it('refuses the powers no page asks for', () => { const refused: Record[] = [ { user: ['impersonate'] }, { user: ['impersonate-admins'] }, { user: ['delete'] }, { user: ['get'] }, { user: ['list'] }, { user: ['update'] }, { user: ['set-email'] }, { user: ['set-phone'] }, { session: ['list'] }, { session: ['delete'] } ]; for (const request of refused) { expect(adminRole().authorize(request).success, JSON.stringify(request)).toBe(false); } }); it('allows the five calls the instance console makes', () => { const granted: Record[] = [ { user: ['create'] }, { user: ['set-role'] }, { user: ['ban'] }, { user: ['set-password'] }, { session: ['revoke'] } ]; for (const request of granted) { expect(adminRole().authorize(request).success, JSON.stringify(request)).toBe(true); } }); });