import { beforeEach, describe, expect, it, vi } from "vitest"; import { SystemRole } from "@capakraken/shared"; import { createToolContext, executeTool, totpValidateMock, } from "./assistant-tools-user-self-service-mfa-test-helpers.js"; describe("assistant user self-service MFA tools - enable flow", () => { beforeEach(() => { vi.clearAllMocks(); totpValidateMock.mockReset(); }); it("generates a TOTP secret through the real user router path", async () => { const db = { user: { update: vi.fn().mockResolvedValue({}), }, }; const ctx = createToolContext(db, SystemRole.ADMIN); const result = await executeTool("generate_totp_secret", "{}", ctx); expect(db.user.update).toHaveBeenCalledWith({ where: { id: "user_1" }, data: { totpSecret: "MOCKSECRET" }, }); expect(JSON.parse(result.content)).toEqual({ success: true, secret: "MOCKSECRET", uri: "otpauth://mock", message: "Generated a new MFA TOTP secret.", }); expect(result.action).toEqual({ type: "invalidate", scope: ["user"], }); }); it("enables TOTP through the real user router path when the token is valid", async () => { totpValidateMock.mockReturnValue(0); const db = { user: { findUnique: vi.fn().mockResolvedValue({ id: "user_1", name: "Assistant User", email: "assistant@example.com", totpSecret: "MOCKSECRET", totpEnabled: false, }), update: vi.fn().mockResolvedValue({}), }, auditLog: { create: vi.fn().mockResolvedValue({ id: "audit_1" }), }, }; const ctx = createToolContext(db, SystemRole.ADMIN); const result = await executeTool( "verify_and_enable_totp", JSON.stringify({ token: "123456" }), ctx, ); expect(db.user.findUnique).toHaveBeenCalledWith({ where: { id: "user_1" }, select: { id: true, name: true, email: true, totpSecret: true, totpEnabled: true }, }); expect(db.user.update).toHaveBeenCalledWith({ where: { id: "user_1" }, data: { totpEnabled: true }, }); expect(db.auditLog.create).toHaveBeenCalledWith({ data: expect.objectContaining({ entityType: "User", entityId: "user_1", action: "UPDATE", userId: "user_1", source: "ui", entityName: "Assistant User (assistant@example.com)", summary: "Enabled TOTP MFA", }), }); expect(JSON.parse(result.content)).toEqual({ success: true, enabled: true, message: "Enabled MFA TOTP.", }); expect(result.action).toEqual({ type: "invalidate", scope: ["user"], }); }); });