Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,4 +1,4 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { action } from "./forgot-password";
import { getUserByEmail, updateUserVerifyToken } from "~/utils/db/users.db.server";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
@@ -6,6 +6,13 @@ import { queueTransactionalEmail } from "~/modules/emails/services/Transactional
import EmailTemplates from "~/modules/emails/utils/EmailTemplates";
import { issueMagicLink } from "~/services/auth/magic-link.server";
import { createPasswordResetVerifyToken, hashPasswordResetToken } from "~/services/auth/password-reset-token.server";
import { loadRequiredWebConfig } from "@hivegrid/config";
import {
AdminFallbackLoginRejected,
assertAdminFallbackLoginAllowedForIdentity,
} from "~/services/auth/admin-fallback.server";
import { writeAdminSsoAuditEvent } from "~/modules/admin-sso/audit.server";
import { checkAuthRateLimit } from "~/services/auth/auth-rate-limit.server";
const sendEmailMock = vi.fn();
@@ -34,10 +41,30 @@ vi.mock("~/utils/session.server", () => ({
validateCSRFToken: vi.fn(),
}));
vi.mock("~/services/auth/auth-rate-limit.server", () => ({
checkAuthRateLimit: vi.fn().mockResolvedValue({ allowed: true }),
}));
vi.mock("~/services/auth/magic-link.server", () => ({
issueMagicLink: vi.fn(),
}));
vi.mock("@hivegrid/config", () => ({
loadRequiredWebConfig: vi.fn(),
}));
vi.mock("~/services/auth/admin-fallback.server", async () => {
const actual = await vi.importActual<typeof import("~/services/auth/admin-fallback.server")>("~/services/auth/admin-fallback.server");
return {
...actual,
assertAdminFallbackLoginAllowedForIdentity: vi.fn(),
};
});
vi.mock("~/modules/admin-sso/audit.server", () => ({
writeAdminSsoAuditEvent: vi.fn(),
}));
vi.mock("~/services/auth/password-reset-token.server", async () => {
const actual = await vi.importActual<typeof import("~/services/auth/password-reset-token.server")>("~/services/auth/password-reset-token.server");
return {
@@ -52,6 +79,7 @@ vi.mock("~/modules/emails/utils/EmailTemplates", () => ({
parse: vi.fn(({ data }) => ({
subject: "Reset your password",
body: `<p>Reset at ${data.action_url}</p>`,
text: `Reset at ${data.action_url}`,
})),
},
},
@@ -86,6 +114,10 @@ const queueTransactionalEmailMock = vi.mocked(queueTransactionalEmail);
const passwordResetParseMock = vi.mocked(EmailTemplates.PASSWORD_RESET_EMAIL.parse);
const issueMagicLinkMock = vi.mocked(issueMagicLink);
const createPasswordResetVerifyTokenMock = vi.mocked(createPasswordResetVerifyToken);
const loadRequiredWebConfigMock = vi.mocked(loadRequiredWebConfig);
const assertAdminFallbackLoginAllowedForIdentityMock = vi.mocked(assertAdminFallbackLoginAllowedForIdentity);
const writeAdminSsoAuditEventMock = vi.mocked(writeAdminSsoAuditEvent);
const checkAuthRateLimitMock = vi.mocked(checkAuthRateLimit);
async function postForgotPassword(email?: string, mode?: "magic" | "reset") {
const form = new FormData();
@@ -115,6 +147,14 @@ async function readJson(response: unknown) {
describe("forgot password action", () => {
beforeEach(() => {
vi.clearAllMocks();
checkAuthRateLimitMock.mockResolvedValue({ allowed: true });
loadRequiredWebConfigMock.mockReturnValue({ magicLink: { enabled: true } } as ReturnType<typeof loadRequiredWebConfig>);
vi.spyOn(globalThis, "setTimeout").mockImplementation(((callback: TimerHandler) => {
if (typeof callback === "function") {
callback();
}
return 0;
}) as typeof setTimeout);
getAppConfigurationMock.mockResolvedValue({ appName: "Example" } as unknown as Awaited<ReturnType<typeof getAppConfiguration>>);
updateUserVerifyTokenMock.mockResolvedValue({ id: "user_1" } as Awaited<ReturnType<typeof updateUserVerifyToken>>);
queueTransactionalEmailMock.mockResolvedValue({ enqueued: true, jobId: "job_1" });
@@ -123,10 +163,15 @@ describe("forgot password action", () => {
createPasswordResetVerifyTokenMock.mockReturnValue("verify-token");
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
it("enqueues password reset email after updating the user token", async () => {
const response = await postForgotPassword("ada@example.com");
await expect(readJson(response)).resolves.toEqual({ success: "Email sent" });
await expect(readJson(response)).resolves.toEqual({ success: "account.reset.emailSent" });
expect(updateUserVerifyTokenMock).toHaveBeenCalledWith(
{
verifyToken: hashPasswordResetToken("verify-token"),
@@ -150,6 +195,7 @@ describe("forgot password action", () => {
alias: "password-reset",
subject: "Reset your password",
body: "<p>Reset at https://example.com/reset?e=ada%40example.com&t=verify-token</p>",
text: "Reset at https://example.com/reset?e=ada%40example.com&t=verify-token",
userId: "user_1",
data: {
name: "Ada",
@@ -164,7 +210,7 @@ describe("forgot password action", () => {
it("issues a login magic link when magic mode is requested", async () => {
const response = await postForgotPassword("Ada@Example.com ", "magic");
await expect(readJson(response)).resolves.toEqual({ success: "Email sent" });
await expect(readJson(response)).resolves.toEqual({ success: "account.reset.emailSent" });
expect(issueMagicLinkMock).toHaveBeenCalledWith({
request: expect.any(Request),
userId: "user_1",
@@ -178,6 +224,40 @@ describe("forgot password action", () => {
expect(sendEmailMock).not.toHaveBeenCalled();
});
it("does not resolve identities or issue links when magic-link auth is disabled", async () => {
loadRequiredWebConfigMock.mockReturnValue({ magicLink: { enabled: false } } as ReturnType<typeof loadRequiredWebConfig>);
const response = await postForgotPassword("admin@example.com", "magic");
await expect(readJson(response)).resolves.toEqual({ success: "account.reset.emailSent" });
expect(getUserByEmailMock).not.toHaveBeenCalled();
expect(issueMagicLinkMock).not.toHaveBeenCalled();
});
it("does not issue a link for a blocked AdminUser and keeps the generic response", async () => {
getUserByEmailMock.mockResolvedValue({
id: "admin_1",
email: "admin@example.com",
firstName: "Ada",
admin: { userId: "admin_1" },
} as never);
assertAdminFallbackLoginAllowedForIdentityMock.mockImplementationOnce(() => {
throw new AdminFallbackLoginRejected("email-not-allowlisted");
});
const response = await postForgotPassword("admin@example.com", "magic");
await expect(readJson(response)).resolves.toEqual({ success: "account.reset.emailSent" });
expect(issueMagicLinkMock).not.toHaveBeenCalled();
expect(writeAdminSsoAuditEventMock).toHaveBeenCalledWith(
expect.objectContaining({
action: "admin.login.fallback.failure",
actorAdminUserId: "admin_1",
meta: expect.objectContaining({ method: "magic-link", stage: "issue" }),
})
);
});
it("fails closed when the transactional email cannot be queued", async () => {
queueTransactionalEmailMock.mockRejectedValue(new Error("Redis connection required to enqueue transactional email."));
@@ -190,7 +270,7 @@ describe("forgot password action", () => {
const response = await postForgotPassword();
expect((response as Response).status).toBe(400);
await expect(readJson(response)).resolves.toEqual({ error: "Email required" });
await expect(readJson(response)).resolves.toEqual({ error: "account.reset.errors.emailRequired" });
expect(getUserByEmailMock).not.toHaveBeenCalled();
expect(updateUserVerifyTokenMock).not.toHaveBeenCalled();
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
@@ -198,17 +278,14 @@ describe("forgot password action", () => {
});
it("returns delayed success for unknown users without queueing", async () => {
vi.useFakeTimers();
getUserByEmailMock.mockResolvedValue(null);
const responsePromise = postForgotPassword("missing@example.com");
await vi.advanceTimersByTimeAsync(1500);
const response = await responsePromise;
const response = await postForgotPassword("missing@example.com");
await expect(readJson(response)).resolves.toEqual({ success: "Email sent" });
await expect(readJson(response)).resolves.toEqual({ success: "account.reset.emailSent" });
expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), expect.any(Number));
expect(updateUserVerifyTokenMock).not.toHaveBeenCalled();
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
expect(sendEmailMock).not.toHaveBeenCalled();
vi.useRealTimers();
});
});