Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+32
@@ -0,0 +1,32 @@
|
||||
import type { LoaderFunctionArgs, MetaFunction } from "react-router";
|
||||
|
||||
import { useUiPreferences } from "~/components/app/UiPreferencesContext";
|
||||
import { UiPreferencesSettingsPage } from "~/components/screens/settings/UiPreferencesSettingsPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
};
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
return { title: `${t("settings.appearance.title")} | ${process.env.APP_NAME}` } satisfies LoaderData;
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function UiPreferencesSettingsRoute(): React.JSX.Element {
|
||||
const { preferences, setAutoCollapseSidebar, setVisualEffectsEnabled } = useUiPreferences();
|
||||
|
||||
return (
|
||||
<UiPreferencesSettingsPage
|
||||
preferences={preferences}
|
||||
actions={{
|
||||
onSetAutoCollapseSidebar: setAutoCollapseSidebar,
|
||||
onSetVisualEffectsEnabled: setVisualEffectsEnabled,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+383
@@ -0,0 +1,383 @@
|
||||
/**
|
||||
* Phase 10 Task #68 — DSGVO self-service privacy hub.
|
||||
*
|
||||
* Top-level settings page that lets a logged-in user manage their
|
||||
* Art. 15/17/20 rights:
|
||||
*
|
||||
* • POST { intent: "export" } — enqueues a personal-data export
|
||||
* (rate-limited to 1 per 7 days; the worker streams the bundle to
|
||||
* S3 and emails a signed download URL).
|
||||
*
|
||||
* • POST { intent: "delete" } — emails a short-lived confirmation
|
||||
* link. The confirmation route flips User.pendingDeletion +
|
||||
* scheduledDeletionAt so a hijacked session cannot schedule deletion
|
||||
* without inbox access.
|
||||
*
|
||||
* • POST { intent: "reactivate" } — cancels a pending deletion.
|
||||
*
|
||||
* Every action is audited with regulatoryScope=[gdpr],
|
||||
* dataSensitivity=pii, actorType=user, and a stable requestId so the
|
||||
* worker job can be correlated with the UI action.
|
||||
*/
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { redirect, useActionData, useLoaderData, useNavigate, useRevalidator } from "react-router";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
|
||||
import { getDbClient } from "@hivegrid/db/client.server";
|
||||
import { createGdprExportJob, GDPR_USER_SELF_EXPORT_LIMIT_PER_24H, listGdprExportJobs } from "@hivegrid/db/privacy-gdpr.server";
|
||||
import { buildPrivacyHubVM, type PrivacyHubSectionKey, type PrivacyHubVM } from "@hivegrid/view-models";
|
||||
|
||||
import { PrivacyHubPage } from "~/components/screens/privacy/PrivacyHubPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { DeletionTokenSecretMissingError, signDeletionToken } from "~/utils/dsgvo/deletionToken.server";
|
||||
import { enqueuePrivacyNotification } from "~/utils/privacy/privacyNotificationQueue.server";
|
||||
import { enqueueGdprExport } from "~/utils/privacy/gdprExportQueue.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import type { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
|
||||
|
||||
const DSGVO_GRACE_PERIOD_DAYS = Number(process.env.DSGVO_GRACE_PERIOD_DAYS ?? "30") || 30;
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
tenantSlug: string;
|
||||
vm: PrivacyHubVM;
|
||||
};
|
||||
|
||||
async function hasPermission(request: Request, permission: DefaultPermission, tenantId: string): Promise<boolean> {
|
||||
try {
|
||||
await verifyUserHasPermission(request, permission, tenantId);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof Response && ((error.status >= 300 && error.status < 400) || error.status === 403 || error.status === 404)) return false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
type ActionData =
|
||||
| { intent: "export"; ok: true; message: string }
|
||||
| { intent: "delete"; ok: true; emailSent: true; message: string }
|
||||
| { intent: "reactivate"; ok: true }
|
||||
| { ok: false; error: string };
|
||||
|
||||
const DELETION_CONFIRM_TOKEN_TTL_HOURS = Number(process.env.DSGVO_CONFIRM_TOKEN_TTL_HOURS ?? "24") || 24;
|
||||
|
||||
function buildConfirmationUrl(request: Request, tenantSlug: string, token: string): string {
|
||||
const origin = new URL(request.url).origin;
|
||||
// Encode tenantSlug for safety; token is base64url which is already URL-safe.
|
||||
return `${origin}/app/${encodeURIComponent(tenantSlug)}/settings/privacy/delete/confirm/${token}`;
|
||||
}
|
||||
|
||||
function getDeletionMailAppName(t: (key: string) => string): string {
|
||||
return process.env.APP_NAME?.trim() || t("settings.privacy.mail.deleteConfirm.defaultAppName");
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const userInfo = await getUserInfo(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
const db = getDbClient();
|
||||
const user = await db.user.findUnique({
|
||||
where: { id: userInfo.userId },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
pendingDeletion: true,
|
||||
scheduledDeletionAt: true,
|
||||
pseudonymized: true,
|
||||
},
|
||||
});
|
||||
if (!user) throw new Response(t("settings.privacy.errors.userNotFound"), { status: 404 });
|
||||
|
||||
const now = new Date();
|
||||
const [recentJobs, userSelfCountLast24h, canTenantExport, canTenantDeletion, canSubprocessors, canAvv, activeDeletion] = await Promise.all([
|
||||
listGdprExportJobs({ tenantId, requestedByUserId: user.id, take: 5 }),
|
||||
db.gdprExportJob.count({
|
||||
where: { tenantId, scope: "user_self", targetUserId: user.id, createdAt: { gte: new Date(now.getTime() - 24 * 60 * 60 * 1_000) } },
|
||||
}),
|
||||
hasPermission(request, "privacy.tenant_export", tenantId),
|
||||
hasPermission(request, "privacy.tenant_deletion", tenantId),
|
||||
hasPermission(request, "privacy.subprocessors.read", tenantId),
|
||||
hasPermission(request, "privacy.avv.read", tenantId),
|
||||
db.tenantDeletionRequest.findFirst({
|
||||
where: { tenantId, status: "pending" },
|
||||
select: { id: true, gracePeriodEndsAt: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
const vm = buildPrivacyHubVM({
|
||||
now: now.toISOString(),
|
||||
tenantSlug: params.tenant ?? "",
|
||||
graceDays: DSGVO_GRACE_PERIOD_DAYS,
|
||||
userEmail: user.email,
|
||||
userPendingDeletion: user.pendingDeletion,
|
||||
userScheduledDeletionAt: user.scheduledDeletionAt ? user.scheduledDeletionAt.toISOString() : null,
|
||||
recentJobs: recentJobs.map((job) => ({
|
||||
id: job.id,
|
||||
scope: job.scope,
|
||||
status: job.status,
|
||||
progressPercent: job.progressPercent,
|
||||
resultSizeBytes: job.resultSizeBytes,
|
||||
resultExpiresAt: job.resultExpiresAt ? job.resultExpiresAt.toISOString() : null,
|
||||
downloadCount: job.downloadCount,
|
||||
createdAt: job.createdAt.toISOString(),
|
||||
})),
|
||||
userSelfCountLast24h,
|
||||
userSelfLimitPer24h: GDPR_USER_SELF_EXPORT_LIMIT_PER_24H,
|
||||
permissions: {
|
||||
tenantExport: canTenantExport,
|
||||
tenantDeletion: canTenantDeletion,
|
||||
subprocessors: canSubprocessors,
|
||||
avv: canAvv,
|
||||
},
|
||||
activeTenantDeletion: activeDeletion ? { id: activeDeletion.id, gracePeriodEndsAt: activeDeletion.gracePeriodEndsAt.toISOString() } : null,
|
||||
});
|
||||
|
||||
const data: LoaderData = {
|
||||
title: `${t("settings.privacy.title")} | ${process.env.APP_NAME ?? t("app.navbar.settings")}`,
|
||||
tenantSlug: params.tenant ?? "",
|
||||
vm,
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "title" in data ? [{ title: data.title }] : []);
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
const form = await request.formData();
|
||||
const intent = String(form.get("intent") ?? "");
|
||||
const db = getDbClient();
|
||||
const requestId = randomUUID();
|
||||
|
||||
if (intent === "export") {
|
||||
const exportJob = await createGdprExportJob({
|
||||
tenantId,
|
||||
requestedByUserId: userInfo.userId,
|
||||
targetUserId: userInfo.userId,
|
||||
scope: "user_self",
|
||||
});
|
||||
const enqueueResult = await enqueueGdprExport({
|
||||
exportJobId: exportJob.id,
|
||||
tenantId,
|
||||
requestedByUserId: userInfo.userId,
|
||||
targetUserId: userInfo.userId,
|
||||
scope: "user_self",
|
||||
requestId,
|
||||
});
|
||||
await createAuditEvent({
|
||||
tenantId,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "user",
|
||||
action: "REQUEST_PERSONAL_DATA_EXPORT",
|
||||
targetType: "User",
|
||||
targetId: userInfo.userId,
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
metadata: { requestId, intent: "export", source: "self-service", gdprExportJobId: exportJob.id, enqueueResult },
|
||||
});
|
||||
const data: ActionData = {
|
||||
intent: "export",
|
||||
ok: true,
|
||||
message: t("settings.privacy.messages.exportRequested"),
|
||||
};
|
||||
return Response.json(data);
|
||||
}
|
||||
|
||||
if (intent === "delete") {
|
||||
const confirmation = String(form.get("confirmation") ?? "");
|
||||
if (confirmation !== "LÖSCHEN" && confirmation.toUpperCase() !== "DELETE") {
|
||||
const data: ActionData = {
|
||||
ok: false,
|
||||
error: t("settings.privacy.errors.confirmationMismatch"),
|
||||
};
|
||||
return Response.json(data, { status: 400 });
|
||||
}
|
||||
const user = await db.user.findUnique({ where: { id: userInfo.userId }, select: { email: true } });
|
||||
if (!user) {
|
||||
const data: ActionData = { ok: false, error: t("settings.privacy.errors.userNotFound") };
|
||||
return Response.json(data, { status: 404 });
|
||||
}
|
||||
|
||||
// Mint a short-lived signed token; do NOT mutate User.pendingDeletion yet.
|
||||
// The pendingDeletion flag is only flipped after the user clicks the
|
||||
// confirmation link emailed below — that protects against an attacker
|
||||
// who has hijacked a session but cannot read the user's inbox.
|
||||
let token: string;
|
||||
try {
|
||||
token = signDeletionToken({ userId: userInfo.userId, expiresInHours: DELETION_CONFIRM_TOKEN_TTL_HOURS });
|
||||
} catch (err) {
|
||||
if (err instanceof DeletionTokenSecretMissingError) {
|
||||
const data: ActionData = {
|
||||
ok: false,
|
||||
error: t("settings.privacy.errors.deletionTokenSecretMissing"),
|
||||
};
|
||||
return Response.json(data, { status: 500 });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const confirmUrl = buildConfirmationUrl(request, tenantSlug, token);
|
||||
const ttlHours = Math.min(Math.max(Math.floor(DELETION_CONFIRM_TOKEN_TTL_HOURS), 1), 72);
|
||||
const appName = getDeletionMailAppName(t);
|
||||
const mailSubject = t("settings.privacy.mail.deleteConfirm.subject", { appName });
|
||||
const mailBody = [
|
||||
t("settings.privacy.mail.deleteConfirm.intro", { appName }),
|
||||
"",
|
||||
t("settings.privacy.mail.deleteConfirm.instructions", { hours: ttlHours }),
|
||||
"",
|
||||
confirmUrl,
|
||||
"",
|
||||
t("settings.privacy.mail.deleteConfirm.gracePeriod", { days: DSGVO_GRACE_PERIOD_DAYS }),
|
||||
"",
|
||||
t("settings.privacy.mail.deleteConfirm.ignore", {
|
||||
requestId,
|
||||
}),
|
||||
].join("\n");
|
||||
|
||||
try {
|
||||
// AGENTS.md DoD C15 — the confirmation notice goes through the M011
|
||||
// notification queue on the locked "critical" category, so a preference
|
||||
// can never silence a one-time deletion link.
|
||||
const queued = await enqueuePrivacyNotification({
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
email: user.email,
|
||||
messageKey: "settings.privacy.notify.deleteConfirm",
|
||||
sourceKey: `privacy-user-deletion:${requestId}`,
|
||||
subject: mailSubject,
|
||||
text: mailBody,
|
||||
metadata: { source: "self-service", requestId, ttlHours },
|
||||
});
|
||||
if (!queued.enqueued) {
|
||||
// Fail loudly rather than telling the user a mail is on its way: the
|
||||
// link has a hard deadline and deletion can always be re-requested.
|
||||
throw new Error(`Privacy deletion confirmation could not be queued: ${queued.reason}`);
|
||||
}
|
||||
} catch (err) {
|
||||
// Audit the failure so the operator sees the problem but do NOT leak
|
||||
// detail to the end-user; deletion can always be re-requested.
|
||||
await createAuditEvent({
|
||||
tenantId,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "user",
|
||||
action: "REQUEST_USER_DELETION",
|
||||
targetType: "User",
|
||||
targetId: userInfo.userId,
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "failure",
|
||||
metadata: { requestId, intent: "delete", source: "self-service", phase: "send-confirmation-email", error: String(err) },
|
||||
});
|
||||
const data: ActionData = {
|
||||
ok: false,
|
||||
error: t("settings.privacy.errors.confirmationEmailFailed"),
|
||||
};
|
||||
return Response.json(data, { status: 502 });
|
||||
}
|
||||
|
||||
await createAuditEvent({
|
||||
tenantId,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "user",
|
||||
action: "REQUEST_USER_DELETION",
|
||||
targetType: "User",
|
||||
targetId: userInfo.userId,
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
metadata: { requestId, intent: "delete", source: "self-service", phase: "confirmation-email-sent" },
|
||||
});
|
||||
const successMessage = t("settings.privacy.messages.deleteConfirmationSent", { email: user.email, hours: ttlHours, days: DSGVO_GRACE_PERIOD_DAYS });
|
||||
const ok: ActionData = {
|
||||
intent: "delete",
|
||||
ok: true,
|
||||
emailSent: true,
|
||||
message: successMessage,
|
||||
};
|
||||
return Response.json(ok);
|
||||
}
|
||||
|
||||
if (intent === "reactivate") {
|
||||
await db.user.update({
|
||||
where: { id: userInfo.userId },
|
||||
data: {
|
||||
pendingDeletion: false,
|
||||
deletionRequestedAt: null,
|
||||
scheduledDeletionAt: null,
|
||||
deletionRequestId: null,
|
||||
},
|
||||
});
|
||||
await createAuditEvent({
|
||||
tenantId,
|
||||
actorId: userInfo.userId,
|
||||
actorType: "user",
|
||||
action: "CANCEL_USER_DELETION",
|
||||
targetType: "User",
|
||||
targetId: userInfo.userId,
|
||||
regulatoryScope: ["gdpr"],
|
||||
dataSensitivity: "pii",
|
||||
outcome: "success",
|
||||
metadata: { requestId, intent: "reactivate", source: "self-service" },
|
||||
});
|
||||
return redirect(`./privacy?toast=${encodeURIComponent("settings.privacy.toast.deletionCancelled")}`);
|
||||
}
|
||||
|
||||
const data: ActionData = { ok: false, error: t("settings.privacy.errors.unknownIntent", { intent }) };
|
||||
return Response.json(data, { status: 400 });
|
||||
};
|
||||
|
||||
const SECTION_PATHS: Record<PrivacyHubSectionKey, string> = {
|
||||
export: "settings/compliance/data-export",
|
||||
deletion: "settings/compliance/tenant-deletion",
|
||||
subprocessors: "settings/compliance/subprocessors",
|
||||
avv: "settings/compliance/avv",
|
||||
};
|
||||
|
||||
export default function PrivacySettingsRoute() {
|
||||
const { tenantSlug, vm } = useLoaderData<LoaderData>();
|
||||
const action = useActionData<ActionData>();
|
||||
const navigate = useNavigate();
|
||||
const revalidator = useRevalidator();
|
||||
const { csrf } = useRootData();
|
||||
|
||||
useEffect(() => {
|
||||
if (!action) return;
|
||||
if ("ok" in action && !action.ok) toast.error(action.error);
|
||||
else if ("message" in action && action.message) toast.success(action.message);
|
||||
}, [action]);
|
||||
|
||||
return (
|
||||
<PrivacyHubPage
|
||||
embedded
|
||||
vm={vm}
|
||||
csrf={csrf}
|
||||
actions={{
|
||||
onOpenSection(section) {
|
||||
void navigate(appPath({ tenantSlug, path: SECTION_PATHS[section] }));
|
||||
},
|
||||
onDownloadJob(jobId) {
|
||||
window.location.assign(appPath({ tenantSlug, path: `settings/privacy/export/${jobId}/download` }));
|
||||
},
|
||||
onRetry() {
|
||||
revalidator.revalidate();
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+431
@@ -0,0 +1,431 @@
|
||||
import { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import { ActionFunction, LoaderFunctionArgs, MetaFunction, redirect, useLoaderData } from "react-router";
|
||||
import { useActionData } from "react-router";
|
||||
import {
|
||||
activateUserTotpPendingSecret,
|
||||
disableUserTotp,
|
||||
getUserTotpStatus,
|
||||
setUserMfaRecoveryCodes,
|
||||
setUserTotpPendingSecret,
|
||||
updateUserPassword,
|
||||
updateUserProfile,
|
||||
type UserTotpStatus,
|
||||
} from "~/utils/db/users.db.server";
|
||||
import { commitSession, createUserSession, getUserInfo, getUserSession, storage, validateCSRFToken } from "~/utils/session.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { hashPassword, verifyPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { validatePassword as validatePolicyPassword } from "~/services/auth/password-policy.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { deleteUserWithItsTenants } from "~/utils/services/userService";
|
||||
import { avatarUploadFailure, removeStoredAvatar, storeAvatar } from "~/utils/integrations/avatarStorage.server";
|
||||
import { avatarProxyPath, isAvatarUpload } from "~/utils/app/avatarPaths";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { UserProfileUpdatedDto } from "~/modules/events/dtos/UserProfileUpdatedDto";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { UserPasswordUpdatedDto } from "~/modules/events/dtos/UserPasswordUpdatedDto";
|
||||
import MyProfileScreen from "~/modules/users/components/MyProfileScreen";
|
||||
import { PageIntro } from "~/components/screens/shared/PageShell";
|
||||
import { LanguageSettingsNotice } from "~/components/settings/LanguageSettingsNotice";
|
||||
import { toast } from "sonner";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { generateRecoveryCodes } from "~/utils/auth/mfa/recovery-codes.server";
|
||||
import { getFreshTotpPendingEnrollmentForUser, startTotpEnrollment, verifyTotpCode } from "~/services/auth/totp.server";
|
||||
import { checkMfaStepUpState, clearMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
|
||||
import { revokeAllUserSessionsForUser } from "~/services/auth/sessionStore.server";
|
||||
|
||||
type CurrentSessionMfaStepUp =
|
||||
| { present: false; verified: false; stale: false; reason: "missing" }
|
||||
| { present: true; verified: true; stale: false; method: string }
|
||||
| { present: true; verified: false; stale: boolean; reason: "malformed" | "wrong-user" | "stale" };
|
||||
|
||||
export type CurrentSessionSettings = {
|
||||
locale: string;
|
||||
lightOrDarkMode: string;
|
||||
theme: string | null;
|
||||
cookieConsentCount: number;
|
||||
impersonationActive: boolean;
|
||||
mfaStepUp: CurrentSessionMfaStepUp;
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
mfaStatus: UserTotpStatus | null;
|
||||
currentSession: CurrentSessionSettings;
|
||||
};
|
||||
|
||||
function getCurrentSessionMfaStepUp(stepUp: ReturnType<typeof checkMfaStepUpState>): CurrentSessionMfaStepUp {
|
||||
if (stepUp.verified) {
|
||||
return { present: true, verified: true, stale: false, method: stepUp.state.method };
|
||||
}
|
||||
if (stepUp.reason === "missing") {
|
||||
return { present: false, verified: false, stale: false, reason: "missing" };
|
||||
}
|
||||
return { present: true, verified: false, stale: stepUp.reason === "stale", reason: stepUp.reason };
|
||||
}
|
||||
|
||||
function getCurrentSessionSettings(
|
||||
userInfo: Awaited<ReturnType<typeof getUserInfo>>,
|
||||
session: Awaited<ReturnType<typeof getUserSession>>
|
||||
): CurrentSessionSettings {
|
||||
const stepUp = checkMfaStepUpState(session, userInfo.userId);
|
||||
const cookies = Array.isArray(userInfo.cookies) ? userInfo.cookies : [];
|
||||
return {
|
||||
locale: userInfo.lng,
|
||||
lightOrDarkMode: userInfo.lightOrDarkMode === "dark" ? "dark" : "light",
|
||||
theme: typeof userInfo.theme === "string" && userInfo.theme.length > 0 ? userInfo.theme : null,
|
||||
cookieConsentCount: cookies.filter((cookie) => cookie?.allowed).length,
|
||||
impersonationActive: Boolean(userInfo.impersonatingFromUserId),
|
||||
mfaStepUp: getCurrentSessionMfaStepUp(stepUp),
|
||||
};
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const session = await getUserSession(request);
|
||||
await getFreshTotpPendingEnrollmentForUser({ userId: userInfo.userId });
|
||||
const data: LoaderData = {
|
||||
title: `${t("settings.profile.profileTitle")} | ${process.env.APP_NAME}`,
|
||||
mfaStatus: await getUserTotpStatus(userInfo?.userId),
|
||||
currentSession: getCurrentSessionSettings(userInfo, session),
|
||||
};
|
||||
return data;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
success?: string;
|
||||
passwordSuccess?: string;
|
||||
error?: string;
|
||||
mfaError?: string;
|
||||
mfaStatus?: UserTotpStatus | null;
|
||||
otpauthUri?: string;
|
||||
recoveryCodes?: string[];
|
||||
currentSession?: CurrentSessionSettings;
|
||||
};
|
||||
|
||||
function mfaJson(
|
||||
body: { mfaStatus: UserTotpStatus | null; mfaError?: string; otpauthUri?: string; recoveryCodes?: string[]; success?: string },
|
||||
init?: ResponseInit
|
||||
) {
|
||||
return Response.json(body, init);
|
||||
}
|
||||
|
||||
function isSixDigitTotpCode(code: FormDataEntryValue | null): code is string {
|
||||
return typeof code === "string" && /^\d{6}$/.test(code);
|
||||
}
|
||||
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
await requireAuth({ request, params });
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
|
||||
const firstName = form.get("firstName")?.toString();
|
||||
const lastName = form.get("lastName")?.toString() ?? "";
|
||||
const avatar = form.get("avatar")?.toString() ?? "";
|
||||
|
||||
const passwordCurrent = form.get("passwordCurrent")?.toString();
|
||||
const passwordNew = form.get("passwordNew")?.toString();
|
||||
const passwordNewConfirm = form.get("passwordNewConfirm")?.toString();
|
||||
|
||||
if (typeof action !== "string") {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
|
||||
const user = await runWithRlsContext({ userId: userInfo.userId, tenantId }, () =>
|
||||
db.user.findUnique({
|
||||
where: { id: userInfo.userId },
|
||||
})
|
||||
);
|
||||
const tenant = await getTenant(tenantId);
|
||||
if (!user) {
|
||||
return Response.json({ error: t("settings.profile.errors.userNotFound") }, { status: 400 });
|
||||
}
|
||||
if (!tenant) {
|
||||
return Response.json({ error: t("settings.profile.errors.accountNotFound") }, { status: 400 });
|
||||
}
|
||||
switch (action) {
|
||||
case "startTotpEnrollment": {
|
||||
const mfaStatus = await getUserTotpStatus(user.id);
|
||||
if (typeof passwordCurrent !== "string") {
|
||||
return mfaJson({ mfaStatus, mfaError: t("settings.profile.errors.currentPasswordRequired") }, { status: 400 });
|
||||
}
|
||||
const isCorrectPassword = (await verifyPassword(passwordCurrent, user.passwordHash)).valid;
|
||||
if (!isCorrectPassword) {
|
||||
return mfaJson({ mfaStatus, mfaError: t("settings.profile.errors.invalidPassword") }, { status: 400 });
|
||||
}
|
||||
|
||||
const enrollment = startTotpEnrollment(user.email);
|
||||
const updatedMfaStatus = await EventsService.createUserEventWithMutation(
|
||||
{
|
||||
request,
|
||||
event: "user.mfa.totp.enrollment.started",
|
||||
userId: user.id,
|
||||
data: (status) => ({
|
||||
user: { id: user.id, email: user.email },
|
||||
mfaStatus: status,
|
||||
}),
|
||||
},
|
||||
async () => {
|
||||
await setUserTotpPendingSecret(user.id, enrollment.encryptedSecret);
|
||||
return getUserTotpStatus(user.id);
|
||||
}
|
||||
);
|
||||
return mfaJson({ success: t("settings.profile.mfa.enrollmentStarted"), mfaStatus: updatedMfaStatus, otpauthUri: enrollment.otpauthUri });
|
||||
}
|
||||
case "confirmTotpEnrollment": {
|
||||
const mfaStatus = await getUserTotpStatus(user.id);
|
||||
const code = form.get("code");
|
||||
if (!isSixDigitTotpCode(code)) {
|
||||
return mfaJson({ mfaStatus, mfaError: t("settings.profile.mfa.enterCode") }, { status: 400 });
|
||||
}
|
||||
const pending = await getFreshTotpPendingEnrollmentForUser({ userId: user.id });
|
||||
if (!pending) {
|
||||
return mfaJson({ mfaStatus, mfaError: t("settings.profile.mfa.noPendingEnrollment") }, { status: 400 });
|
||||
}
|
||||
const pendingSecret = pending.totpPendingSecretEncrypted;
|
||||
if (!verifyTotpCode(pendingSecret, code)) {
|
||||
return mfaJson({ mfaStatus, mfaError: t("settings.profile.mfa.invalidCode") }, { status: 400 });
|
||||
}
|
||||
const recoveryCodeGeneration = generateRecoveryCodes();
|
||||
const updatedMfaStatus = await EventsService.createUserEventWithMutation(
|
||||
{
|
||||
request,
|
||||
event: "user.mfa.totp.enabled",
|
||||
userId: user.id,
|
||||
data: (status) => ({
|
||||
user: { id: user.id, email: user.email },
|
||||
mfaStatus: status,
|
||||
recoveryCodes: {
|
||||
generatedCount: recoveryCodeGeneration.codes.length,
|
||||
remainingCount: recoveryCodeGeneration.entries.filter((entry) => !entry.usedAt).length,
|
||||
generatedAt: recoveryCodeGeneration.generatedAt,
|
||||
},
|
||||
}),
|
||||
},
|
||||
async () => {
|
||||
await activateUserTotpPendingSecret(user.id, pendingSecret);
|
||||
await setUserMfaRecoveryCodes(user.id, recoveryCodeGeneration.entries, recoveryCodeGeneration.generatedAt);
|
||||
return getUserTotpStatus(user.id);
|
||||
}
|
||||
);
|
||||
return mfaJson({ success: t("settings.profile.mfa.enabled"), mfaStatus: updatedMfaStatus, recoveryCodes: recoveryCodeGeneration.codes });
|
||||
}
|
||||
case "disableTotpEnrollment": {
|
||||
const mfaStatus = await getUserTotpStatus(user.id);
|
||||
if (typeof passwordCurrent !== "string") {
|
||||
return mfaJson({ mfaStatus, mfaError: t("settings.profile.errors.currentPasswordRequired") }, { status: 400 });
|
||||
}
|
||||
const isCorrectPassword = (await verifyPassword(passwordCurrent, user.passwordHash)).valid;
|
||||
if (!isCorrectPassword) {
|
||||
return mfaJson({ mfaStatus, mfaError: t("settings.profile.errors.invalidPassword") }, { status: 400 });
|
||||
}
|
||||
const updatedMfaStatus = await EventsService.createUserEventWithMutation(
|
||||
{
|
||||
request,
|
||||
event: "user.mfa.totp.disabled",
|
||||
userId: user.id,
|
||||
data: (status) => ({
|
||||
user: { id: user.id, email: user.email },
|
||||
mfaStatus: status,
|
||||
}),
|
||||
},
|
||||
async () => {
|
||||
await disableUserTotp(user.id);
|
||||
return getUserTotpStatus(user.id);
|
||||
}
|
||||
);
|
||||
return mfaJson({ success: t("settings.profile.mfa.disabled"), mfaStatus: updatedMfaStatus });
|
||||
}
|
||||
case "clearMfaStepUp": {
|
||||
const session = await getUserSession(request);
|
||||
clearMfaStepUpState(session);
|
||||
return Response.json(
|
||||
{ success: t("settings.profile.mfa.sessionCleared"), currentSession: getCurrentSessionSettings(userInfo, session) },
|
||||
{ headers: { "Set-Cookie": await commitSession(session) } }
|
||||
);
|
||||
}
|
||||
case "profile": {
|
||||
const fields = { action, firstName, lastName, avatar, passwordCurrent, passwordNew, passwordNewConfirm };
|
||||
const fieldErrors = {
|
||||
firstName: action === "profile" && (fields.firstName ?? "").length < 2 ? t("settings.profile.errors.firstNameRequired") : "",
|
||||
};
|
||||
if (Object.values(fieldErrors).some(Boolean)) {
|
||||
return Response.json({ error: t("shared.invalidForm"), fields: fieldErrors }, { status: 400 });
|
||||
}
|
||||
|
||||
if (typeof firstName !== "string" || typeof lastName !== "string") {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
|
||||
// Three states arrive in this field: freshly picked bytes (data: URI),
|
||||
// an empty string (remove), or the value the screen already rendered
|
||||
// (untouched). Only the first is an upload — pushing the rendered value
|
||||
// back through storeFile would try to scan the proxy path itself.
|
||||
let avatarUpdate: { avatar?: string } = {};
|
||||
try {
|
||||
if (isAvatarUpload(avatar)) {
|
||||
await storeAvatar({ request, userId: userInfo.userId, dataUri: avatar, auditContext: "tenant.profile.avatar" });
|
||||
avatarUpdate = { avatar: avatarProxyPath(userInfo.userId, Date.now().toString(36)) };
|
||||
} else if (avatar === "") {
|
||||
await removeStoredAvatar(user.avatar, userInfo.userId);
|
||||
avatarUpdate = { avatar: "" };
|
||||
}
|
||||
} catch (error) {
|
||||
const failure = avatarUploadFailure(error);
|
||||
if (!failure) {
|
||||
throw error;
|
||||
}
|
||||
return Response.json({ error: t(failure.key) }, { status: failure.status });
|
||||
}
|
||||
const profile = await EventsService.createUserEventWithMutation(
|
||||
{
|
||||
request,
|
||||
event: "user.profile.updated",
|
||||
userId: user.id,
|
||||
data: {
|
||||
email: user.email,
|
||||
new: { firstName, lastName },
|
||||
old: { firstName: user.firstName, lastName: user.lastName },
|
||||
userId: userInfo?.userId,
|
||||
} satisfies UserProfileUpdatedDto,
|
||||
},
|
||||
() => updateUserProfile({ firstName, lastName, ...avatarUpdate }, userInfo?.userId)
|
||||
);
|
||||
if (!profile) {
|
||||
return Response.json({ error: t("settings.profile.errors.profileUpdateFailed") }, { status: 400 });
|
||||
}
|
||||
return Response.json({
|
||||
success: t("shared.updated"),
|
||||
});
|
||||
}
|
||||
case "password": {
|
||||
if (typeof passwordCurrent !== "string" || typeof passwordNew !== "string" || typeof passwordNewConfirm !== "string") {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
|
||||
if (passwordNew !== passwordNewConfirm) {
|
||||
return Response.json({ error: t("account.shared.passwordMismatch") }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!user) return null;
|
||||
|
||||
const policyResult = await validatePolicyPassword(passwordNew, { email: user.email });
|
||||
if (!policyResult.valid) {
|
||||
const first = policyResult.errors[0];
|
||||
return Response.json(
|
||||
{
|
||||
error: first ? t(first.code, first.args ?? {}) : t("settings.profile.errors.passwordMinLength"),
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const isCorrectPassword = (await verifyPassword(passwordCurrent, user.passwordHash)).valid;
|
||||
if (!isCorrectPassword) {
|
||||
return Response.json({ error: t("settings.profile.errors.invalidPassword") }, { status: 400 });
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(passwordNew);
|
||||
await revokeAllUserSessionsForUser(user.id);
|
||||
await EventsService.createUserEventWithMutation(
|
||||
{
|
||||
request,
|
||||
event: "user.password.updated",
|
||||
userId: user.id,
|
||||
data: {
|
||||
user: { id: user.id, email: user.email },
|
||||
} satisfies UserPasswordUpdatedDto,
|
||||
},
|
||||
() => updateUserPassword({ passwordHash }, userInfo?.userId)
|
||||
);
|
||||
|
||||
const rotatedSession = await createUserSession({ ...userInfo, userId: user.id }, new URL(request.url).pathname, { request, rotate: true });
|
||||
const setCookie = rotatedSession.headers.get("Set-Cookie");
|
||||
return Response.json({ passwordSuccess: t("settings.profile.passwordUpdated") }, setCookie ? { headers: { "Set-Cookie": setCookie } } : undefined);
|
||||
}
|
||||
case "deleteAccount": {
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
if (typeof passwordCurrent !== "string" || passwordCurrent.length === 0) {
|
||||
return Response.json({ error: t("settings.profile.errors.currentPasswordRequired") }, { status: 400 });
|
||||
}
|
||||
const isCorrectPassword = (await verifyPassword(passwordCurrent, user.passwordHash)).valid;
|
||||
if (!isCorrectPassword) {
|
||||
return Response.json({ error: t("settings.profile.errors.invalidPassword") }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
await deleteUserWithItsTenants({
|
||||
actorUserId: user.id,
|
||||
targetUser: user,
|
||||
request,
|
||||
});
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(error);
|
||||
return Response.json(
|
||||
{
|
||||
error: t("shared.unexpectedError"),
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const session = await getUserSession(request);
|
||||
return redirect("/login", {
|
||||
headers: {
|
||||
"Set-Cookie": await storage.destroySession(session),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function ProfileRoute() {
|
||||
const { t } = useTranslation();
|
||||
const appData = useAppData();
|
||||
const loaderData = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
useEffect(() => {
|
||||
const successMessage = actionData?.success ?? actionData?.passwordSuccess;
|
||||
if (successMessage) {
|
||||
toast.success(successMessage);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<EditPageLayout className="pb-20" fullWidth>
|
||||
{/* AK-SET-01: the Mein-Konto hub owns the page header. */}
|
||||
<PageIntro uiId="ui.settings.profile.intro">{t("settings.profile.accountSettings.description")}</PageIntro>
|
||||
<MyProfileScreen
|
||||
user={appData.user}
|
||||
role={appData.currentRole}
|
||||
mfaStatus={actionData?.mfaStatus ?? loaderData.mfaStatus}
|
||||
otpauthUri={actionData?.otpauthUri}
|
||||
recoveryCodes={actionData?.recoveryCodes}
|
||||
mfaError={actionData?.mfaError}
|
||||
/>
|
||||
<div className="mt-6 w-full">
|
||||
<LanguageSettingsNotice />
|
||||
</div>
|
||||
</EditPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+327
@@ -0,0 +1,327 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { MemoryRouter } from "react-router";
|
||||
|
||||
vi.mock("@hivegrid/db/notifications.server", () => ({
|
||||
getUserNotificationPreferences: vi.fn(),
|
||||
upsertUserNotificationPreference: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/loaders.middleware", () => ({
|
||||
requireAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
getUserInfo: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/data/useRootData", () => ({
|
||||
useRootData: () => ({ csrf: "csrf-test-token" }),
|
||||
}));
|
||||
const routeTranslations: Record<string, string> = {
|
||||
"settings.notifications.heading": "Notification preferences",
|
||||
"settings.notifications.description": "Choose which workspace updates you receive in-app and by email. Preferences are scoped to your current workspace and user account.",
|
||||
"settings.notifications.saved": "Notification preference saved.",
|
||||
"settings.notifications.categories.default": "Default",
|
||||
"settings.notifications.categories.billing": "Billing",
|
||||
"settings.notifications.categories.team": "Team",
|
||||
"settings.notifications.modules.general": "General",
|
||||
"settings.notifications.modules.billing": "Billing module",
|
||||
"settings.notifications.modules.team": "Team module",
|
||||
"settings.notifications.master.heading": "Email master switch",
|
||||
"settings.notifications.master.description": "Turns off all email notifications at once.",
|
||||
"settings.notifications.master.disableAllEmails": "Disable all emails",
|
||||
"settings.notifications.master.save": "Save all",
|
||||
"settings.notifications.channels.inApp": "In-app",
|
||||
"settings.notifications.channels.email": "Email",
|
||||
"settings.notifications.errors.invalidPreferenceAction": "Invalid notification preference action.",
|
||||
"settings.notifications.errors.invalidPreferenceCategory": "Invalid notification preference category.",
|
||||
"settings.notifications.errors.invalidPreferenceChannel": "Invalid notification preference channel.",
|
||||
"shared.save": "Save",
|
||||
};
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({
|
||||
t: (key: string) => routeTranslations[key] ?? key,
|
||||
})),
|
||||
}));
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, options?: Record<string, string>) => {
|
||||
if (key === "settings.notifications.categoryDescription") {
|
||||
return `Manage ${options?.category ?? ""} workspace notifications.`;
|
||||
}
|
||||
return routeTranslations[key] ?? key;
|
||||
},
|
||||
}),
|
||||
}));
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
useActionData: () => routeActionData,
|
||||
useLoaderData: () => routeLoaderData,
|
||||
useFetcher: () => ({ submit: vi.fn(), data: routeActionData, state: "idle" }),
|
||||
};
|
||||
});
|
||||
|
||||
import { buildNotificationSettingsVM } from "@hivegrid/view-models";
|
||||
import { getUserNotificationPreferences, upsertUserNotificationPreference } from "@hivegrid/db/notifications.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import WorkspaceNotificationSettingsRoute, { action, loader } from "./notifications";
|
||||
|
||||
let routeLoaderData: unknown;
|
||||
let routeActionData: unknown;
|
||||
|
||||
const request = new Request("https://app.example.test/acme/settings/notifications");
|
||||
const params = { tenant: "acme" };
|
||||
|
||||
function routeArgs(customRequest: Request = request) {
|
||||
return { request: customRequest, params, context: {}, unstable_pattern: "app.$tenant/settings/notifications" };
|
||||
}
|
||||
|
||||
function postFormRequest(formData: FormData) {
|
||||
return new Request(request.url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(formData as unknown as Record<string, string>),
|
||||
});
|
||||
}
|
||||
|
||||
function preferenceForm(overrides?: Record<string, string>) {
|
||||
const form = new FormData();
|
||||
form.set("action", "update-preference");
|
||||
form.set("category", "billing");
|
||||
form.set("channel", "EMAIL");
|
||||
form.set("enabled", "on");
|
||||
Object.entries(overrides ?? {}).forEach(([key, value]) => form.set(key, value));
|
||||
return form;
|
||||
}
|
||||
|
||||
describe("workspace notification settings route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue("tenant_1");
|
||||
vi.mocked(getUserInfo).mockResolvedValue({ userId: "user_1" } as never);
|
||||
vi.mocked(getUserNotificationPreferences).mockResolvedValue([]);
|
||||
vi.mocked(upsertUserNotificationPreference).mockResolvedValue({ id: "pref_1" });
|
||||
routeLoaderData = {
|
||||
vm: buildNotificationSettingsVM([
|
||||
{ category: "billing", channel: "EMAIL", enabled: false },
|
||||
{ category: "team", channel: "IN_APP", enabled: false },
|
||||
]),
|
||||
};
|
||||
routeActionData = undefined;
|
||||
});
|
||||
|
||||
it("requires auth and loads notification preferences only for the current tenant and user", async () => {
|
||||
vi.mocked(getUserNotificationPreferences).mockResolvedValue([
|
||||
{ tenantId: "tenant_1", userId: "user_1", category: "billing", channel: "EMAIL", enabled: false },
|
||||
{ tenantId: "tenant_1", userId: "user_1", category: "team", channel: "IN_APP", enabled: false },
|
||||
{ tenantId: "tenant_1", userId: "user_1", category: "unknown", channel: "EMAIL", enabled: false },
|
||||
] as never);
|
||||
|
||||
const response = (await loader(routeArgs())) as Response;
|
||||
const body = await response.json();
|
||||
|
||||
expect(requireAuth).toHaveBeenCalledWith({ request, params });
|
||||
expect(getTenantIdFromUrl).toHaveBeenCalledWith(params);
|
||||
expect(getUserInfo).toHaveBeenCalledWith(request);
|
||||
expect(getUserNotificationPreferences).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1" });
|
||||
expect(body.vm.status).toBe("ready");
|
||||
const channels = Object.fromEntries(
|
||||
body.vm.data.groups.flatMap((group: { categories: { category: string; channels: Record<string, boolean> }[] }) =>
|
||||
group.categories.map((category) => [category.category, category.channels]),
|
||||
),
|
||||
);
|
||||
expect(channels).toEqual({
|
||||
default: { IN_APP: true, EMAIL: true },
|
||||
billing: { IN_APP: true, EMAIL: false },
|
||||
team: { IN_APP: false, EMAIL: true },
|
||||
// locked critical category: always-on, independent of stored preferences
|
||||
critical: { IN_APP: true, EMAIL: true },
|
||||
});
|
||||
expect(JSON.stringify(body)).not.toContain("unknown");
|
||||
});
|
||||
|
||||
it("shows category preferences using the same default fallback as the worker", async () => {
|
||||
vi.mocked(getUserNotificationPreferences).mockResolvedValue([{ tenantId: "tenant_1", userId: "user_1", category: "default", channel: "EMAIL", enabled: false }] as never);
|
||||
|
||||
const response = (await loader(routeArgs())) as Response;
|
||||
const body = await response.json();
|
||||
|
||||
expect(body.vm.data.allEmailsDisabled).toBe(true);
|
||||
const channels = Object.fromEntries(
|
||||
body.vm.data.groups.flatMap((group: { categories: { category: string; channels: Record<string, boolean> }[] }) =>
|
||||
group.categories.map((category) => [category.category, category.channels]),
|
||||
),
|
||||
);
|
||||
expect(channels).toEqual({
|
||||
default: { IN_APP: true, EMAIL: false },
|
||||
billing: { IN_APP: true, EMAIL: false },
|
||||
team: { IN_APP: true, EMAIL: false },
|
||||
// locked critical category stays on even with the default turned off
|
||||
critical: { IN_APP: true, EMAIL: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("returns bounded 400 JSON for an invalid category without calling upsert", async () => {
|
||||
const form = preferenceForm({ category: "security" });
|
||||
|
||||
const response = (await action(routeArgs(postFormRequest(form)))) as Response;
|
||||
const body = await response.json();
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body).toEqual({ error: "Invalid notification preference category." });
|
||||
expect(upsertUserNotificationPreference).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns bounded 400 JSON for an invalid notification action without calling upsert", async () => {
|
||||
const form = preferenceForm({ action: "delete-preference" });
|
||||
|
||||
const response = (await action(routeArgs(postFormRequest(form)))) as Response;
|
||||
const body = await response.json();
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body).toEqual({ error: "Invalid notification preference action." });
|
||||
expect(upsertUserNotificationPreference).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns bounded 400 JSON for an invalid channel without calling upsert", async () => {
|
||||
const form = preferenceForm({ channel: "SMS" });
|
||||
|
||||
const response = (await action(routeArgs(postFormRequest(form)))) as Response;
|
||||
const body = await response.json();
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body).toEqual({ error: "Invalid notification preference channel." });
|
||||
expect(upsertUserNotificationPreference).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("writes a valid preference update with tenant, user, normalized category, channel, and enabled state", async () => {
|
||||
const form = preferenceForm({ category: " Team ", channel: "in-app", enabled: "true" });
|
||||
|
||||
const response = (await action(routeArgs(postFormRequest(form)))) as Response;
|
||||
const body = await response.json();
|
||||
|
||||
expect(requireAuth).toHaveBeenCalledWith({ request: expect.any(Request), params });
|
||||
expect(getTenantIdFromUrl).toHaveBeenCalledWith(params);
|
||||
expect(getUserInfo).toHaveBeenCalledWith(expect.any(Request));
|
||||
expect(upsertUserNotificationPreference).toHaveBeenCalledWith({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
channel: "IN_APP",
|
||||
category: "team",
|
||||
enabled: true,
|
||||
});
|
||||
expect(body).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it("pins inheriting categories to their current state before a default-category toggle so they do not cascade", async () => {
|
||||
// team already has an explicit IN_APP row; billing still inherits default (true).
|
||||
vi.mocked(getUserNotificationPreferences).mockResolvedValue([
|
||||
{ tenantId: "tenant_1", userId: "user_1", category: "team", channel: "IN_APP", enabled: false },
|
||||
] as never);
|
||||
const form = preferenceForm({ category: "default", channel: "in-app", enabled: "false" });
|
||||
|
||||
const response = (await action(routeArgs(postFormRequest(form)))) as Response;
|
||||
const body = await response.json();
|
||||
|
||||
expect(body).toEqual({ ok: true });
|
||||
// billing gets pinned to its current effective value (true), team stays untouched.
|
||||
expect(upsertUserNotificationPreference).toHaveBeenCalledWith({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
channel: "IN_APP",
|
||||
category: "billing",
|
||||
enabled: true,
|
||||
});
|
||||
expect(upsertUserNotificationPreference).not.toHaveBeenCalledWith(expect.objectContaining({ category: "team" }));
|
||||
expect(upsertUserNotificationPreference).toHaveBeenCalledWith({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
channel: "IN_APP",
|
||||
category: "default",
|
||||
enabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("disables email for every registered category when the master switch is turned on", async () => {
|
||||
const form = new FormData();
|
||||
form.set("action", "set-email-master");
|
||||
form.set("disableAllEmails", "on");
|
||||
|
||||
const response = (await action(routeArgs(postFormRequest(form)))) as Response;
|
||||
const body = await response.json();
|
||||
|
||||
expect(body).toEqual({ ok: true });
|
||||
expect(upsertUserNotificationPreference).toHaveBeenCalledTimes(3);
|
||||
for (const category of ["default", "billing", "team"]) {
|
||||
expect(upsertUserNotificationPreference).toHaveBeenCalledWith({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
channel: "EMAIL",
|
||||
category,
|
||||
enabled: false,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("re-enables email for every registered category when the master switch is cleared", async () => {
|
||||
const form = new FormData();
|
||||
form.set("action", "set-email-master");
|
||||
|
||||
const response = (await action(routeArgs(postFormRequest(form)))) as Response;
|
||||
const body = await response.json();
|
||||
|
||||
expect(body).toEqual({ ok: true });
|
||||
expect(upsertUserNotificationPreference).toHaveBeenCalledTimes(3);
|
||||
expect(upsertUserNotificationPreference).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ channel: "EMAIL", category: "default", enabled: true }),
|
||||
);
|
||||
});
|
||||
|
||||
it("renders the email master switch alongside the per-category controls", () => {
|
||||
const { container } = render(
|
||||
<MemoryRouter>
|
||||
<WorkspaceNotificationSettingsRoute />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
expect(container.querySelector('[data-ui-id="ui.settings.notifications.master.email"]')).toBeInTheDocument();
|
||||
expect(screen.getAllByText("In-app")).toHaveLength(3);
|
||||
expect(screen.getAllByText("Email")).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("renders compact controls for default, billing, and team notification preferences", () => {
|
||||
const { container } = render(
|
||||
<MemoryRouter>
|
||||
<WorkspaceNotificationSettingsRoute />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
// AK-SET-01: the page heading now belongs to the Mein-Konto hub; this tab
|
||||
// renders its description and the preference groups.
|
||||
expect(screen.queryByText("Notification preferences")).not.toBeInTheDocument();
|
||||
expect(screen.getByText(routeTranslations["settings.notifications.description"])).toBeInTheDocument();
|
||||
expect(screen.getByText("Preferences are scoped to your current workspace and user account.", { exact: false })).toBeInTheDocument();
|
||||
expect(screen.getByText("Default")).toBeInTheDocument();
|
||||
expect(screen.getByText("Billing")).toBeInTheDocument();
|
||||
expect(screen.getByText("Team")).toBeInTheDocument();
|
||||
expect(screen.getAllByText("In-app")).toHaveLength(3);
|
||||
expect(screen.getAllByText("Email")).toHaveLength(3);
|
||||
|
||||
// Switch state mirrors the VM: billing EMAIL off, team IN_APP off.
|
||||
const billingEmail = container
|
||||
.querySelector('[data-ui-id="ui.settings.notifications.preference.billing.email"]')
|
||||
?.querySelector('[role="switch"]');
|
||||
const teamInApp = container
|
||||
.querySelector('[data-ui-id="ui.settings.notifications.preference.team.in_app"]')
|
||||
?.querySelector('[role="switch"]');
|
||||
expect(billingEmail).toHaveAttribute("aria-checked", "false");
|
||||
expect(teamInApp).toHaveAttribute("aria-checked", "false");
|
||||
});
|
||||
});
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
// AK-P3 — Notification-Settings route (`/app/:tenant/settings/notifications`).
|
||||
// The category registry + default-inheritance merge live in the pure
|
||||
// notification-settings VM (@hivegrid/view-models); the loader builds the VM
|
||||
// once and the route injects it plus fetcher-backed action callbacks into the
|
||||
// interim <NotificationSettingsPage /> screen (AD-28).
|
||||
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
|
||||
import { upsertUserNotificationPreference, getUserNotificationPreferences } from "@hivegrid/db/notifications.server";
|
||||
import {
|
||||
buildNotificationSettingsVM,
|
||||
isAllowedNotificationCategory,
|
||||
isAllowedNotificationChannel,
|
||||
resolveNotificationPreferenceStates,
|
||||
NOTIFICATION_SETTING_CATEGORIES,
|
||||
type NotificationPreferenceInput,
|
||||
type NotificationSettingsVM,
|
||||
} from "@hivegrid/view-models";
|
||||
import { NotificationSettingsPage } from "~/components/screens/notifications/NotificationSettingsPage";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
type LoaderData = {
|
||||
vm: NotificationSettingsVM;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
ok?: true;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
function getRequiredFormValue(formData: FormData, key: string): string | null {
|
||||
const value = formData.get(key);
|
||||
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalized = value.trim();
|
||||
return normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
function isCheckboxOn(formData: FormData, key: string): boolean {
|
||||
const value = formData.get(key);
|
||||
return value === "on" || value === "true";
|
||||
}
|
||||
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const records = (await getUserNotificationPreferences({ tenantId, userId: userInfo.userId })) as NotificationPreferenceInput[];
|
||||
|
||||
const data: LoaderData = { vm: buildNotificationSettingsVM(records) };
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const formData = await request.formData();
|
||||
const actionName = getRequiredFormValue(formData, "action");
|
||||
|
||||
// Master "turn all emails off" switch: write the EMAIL preference for every
|
||||
// known category so explicit per-category overrides cannot leak emails back in.
|
||||
if (actionName === "set-email-master") {
|
||||
const emailsEnabled = !isCheckboxOn(formData, "disableAllEmails");
|
||||
|
||||
for (const category of NOTIFICATION_SETTING_CATEGORIES) {
|
||||
await upsertUserNotificationPreference({
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
channel: "EMAIL",
|
||||
category,
|
||||
enabled: emailsEnabled,
|
||||
});
|
||||
}
|
||||
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
|
||||
if (actionName !== "update-preference") {
|
||||
return badRequest({ error: t("settings.notifications.errors.invalidPreferenceAction") });
|
||||
}
|
||||
|
||||
const category = getRequiredFormValue(formData, "category")?.toLowerCase() ?? "";
|
||||
const channel = getRequiredFormValue(formData, "channel")?.replace(/-/g, "_").toUpperCase() ?? "";
|
||||
|
||||
if (!isAllowedNotificationCategory(category)) {
|
||||
return badRequest({ error: t("settings.notifications.errors.invalidPreferenceCategory") });
|
||||
}
|
||||
|
||||
if (!isAllowedNotificationChannel(channel)) {
|
||||
return badRequest({ error: t("settings.notifications.errors.invalidPreferenceChannel") });
|
||||
}
|
||||
|
||||
// Categories without an explicit row inherit "default" (worker fallback).
|
||||
// Before changing "default", pin the other categories' current effective
|
||||
// state as explicit rows so their toggles do not cascade along.
|
||||
if (category === "default") {
|
||||
const records = (await getUserNotificationPreferences({ tenantId, userId: userInfo.userId })) as NotificationPreferenceInput[];
|
||||
const states = resolveNotificationPreferenceStates(records);
|
||||
for (const other of NOTIFICATION_SETTING_CATEGORIES) {
|
||||
if (other === "default") continue;
|
||||
const hasExplicit = records.some(
|
||||
(record) => record.category.trim().toLowerCase() === other && record.channel.trim().replace(/-/g, "_").toUpperCase() === channel
|
||||
);
|
||||
if (!hasExplicit) {
|
||||
await upsertUserNotificationPreference({
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
channel,
|
||||
category: other,
|
||||
enabled: states[other][channel],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await upsertUserNotificationPreference({
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
channel,
|
||||
category,
|
||||
enabled: isCheckboxOn(formData, "enabled"),
|
||||
});
|
||||
|
||||
return Response.json({ ok: true });
|
||||
};
|
||||
|
||||
export default function WorkspaceNotificationSettingsRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const rootData = useRootData();
|
||||
const fetcher = useFetcher<ActionData>();
|
||||
|
||||
const saveState = fetcher.data ? { ok: fetcher.data.ok === true, errorText: fetcher.data.error } : null;
|
||||
|
||||
function submit(form: Record<string, string>) {
|
||||
fetcher.submit({ ...form, ...(rootData.csrf ? { csrf: rootData.csrf } : {}) }, { method: "post" });
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="relative z-0 flex-1 pb-8">
|
||||
<NotificationSettingsPage
|
||||
embedded
|
||||
vm={data.vm}
|
||||
saveState={saveState}
|
||||
actions={{
|
||||
onTogglePreference: ({ category, channel, enabled }) =>
|
||||
submit({ action: "update-preference", category, channel, enabled: enabled ? "true" : "false" }),
|
||||
onSetEmailMaster: (disableAllEmails) => submit({ action: "set-email-master", ...(disableAllEmails ? { disableAllEmails: "true" } : {}) }),
|
||||
}}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
// @vitest-environment node
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
createAuditEvent: vi.fn(),
|
||||
db: {
|
||||
user: {
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
},
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
getTranslations: vi.fn(),
|
||||
getUserInfo: vi.fn(),
|
||||
requireAuth: vi.fn(),
|
||||
enqueuePrivacyNotification: vi.fn(),
|
||||
signDeletionToken: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({ createAuditEvent: (...args: unknown[]) => mocks.createAuditEvent(...args) }));
|
||||
vi.mock("@hivegrid/db/client.server", () => ({ getDbClient: () => mocks.db, getReadDbClient: () => mocks.db }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: (...args: unknown[]) => mocks.getTranslations(...args) }));
|
||||
vi.mock("~/utils/loaders.middleware", () => ({ requireAuth: (...args: unknown[]) => mocks.requireAuth(...args) }));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
getUserInfo: (...args: unknown[]) => mocks.getUserInfo(...args),
|
||||
validateCSRFToken: (...args: unknown[]) => mocks.validateCSRFToken(...args),
|
||||
}));
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: (...args: unknown[]) => mocks.getTenantIdFromUrl(...args) }));
|
||||
vi.mock("~/utils/dsgvo/deletionToken.server", () => ({
|
||||
DeletionTokenSecretMissingError: class DeletionTokenSecretMissingError extends Error {},
|
||||
signDeletionToken: (...args: unknown[]) => mocks.signDeletionToken(...args),
|
||||
}));
|
||||
vi.mock("~/utils/privacy/privacyNotificationQueue.server", () => ({
|
||||
PRIVACY_NOTIFICATION_CATEGORY: "critical",
|
||||
enqueuePrivacyNotification: (...args: unknown[]) => mocks.enqueuePrivacyNotification(...args),
|
||||
}));
|
||||
|
||||
import { action } from "./data";
|
||||
|
||||
const originalAppName = process.env.APP_NAME;
|
||||
|
||||
const translations: Record<string, string> = {
|
||||
"settings.privacy.mail.deleteConfirm.defaultAppName": "this application",
|
||||
"settings.privacy.mail.deleteConfirm.subject": "Confirm account deletion for {{appName}}",
|
||||
"settings.privacy.mail.deleteConfirm.intro": "We received a request to delete your account for {{appName}}.",
|
||||
"settings.privacy.mail.deleteConfirm.instructions": "To confirm, please click the link below within {{hours}} hours:",
|
||||
"settings.privacy.mail.deleteConfirm.gracePeriod": "After confirmation a {{days}}-day grace period begins.",
|
||||
"settings.privacy.mail.deleteConfirm.ignore": "If you did not request this, ignore this email. (Request id: {{requestId}})",
|
||||
"settings.privacy.messages.deleteConfirmationSent": "Sent to {{email}} for {{hours}} hours and {{days}} days.",
|
||||
};
|
||||
|
||||
function t(key: string, values: Record<string, unknown> = {}) {
|
||||
return Object.entries(values).reduce(
|
||||
(message, [name, value]) => message.replaceAll(`{{${name}}}`, String(value)),
|
||||
translations[key] ?? key
|
||||
);
|
||||
}
|
||||
|
||||
function createDeleteRequest() {
|
||||
return new Request("https://app.example.test/app/acme/settings/privacy", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams([
|
||||
["intent", "delete"],
|
||||
["confirmation", "DELETE"],
|
||||
["csrf", "csrf-token"],
|
||||
]),
|
||||
});
|
||||
}
|
||||
|
||||
async function callDeleteAction() {
|
||||
return action({
|
||||
request: createDeleteRequest(),
|
||||
params: { tenant: "acme" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/settings/privacy",
|
||||
} as ActionFunctionArgs) as Promise<Response>;
|
||||
}
|
||||
|
||||
describe("privacy deletion confirmation email", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
delete process.env.APP_NAME;
|
||||
mocks.createAuditEvent.mockResolvedValue(undefined);
|
||||
mocks.getTenantIdFromUrl.mockResolvedValue("tenant-1");
|
||||
mocks.getTranslations.mockResolvedValue({ t });
|
||||
mocks.getUserInfo.mockResolvedValue({ userId: "user-1" });
|
||||
mocks.requireAuth.mockResolvedValue(undefined);
|
||||
mocks.validateCSRFToken.mockResolvedValue(undefined);
|
||||
mocks.signDeletionToken.mockReturnValue("signed-delete-token");
|
||||
mocks.db.user.findUnique.mockResolvedValue({ email: "ada@example.test" });
|
||||
mocks.enqueuePrivacyNotification.mockResolvedValue({ enqueued: true, jobId: "job-1" });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalAppName === undefined) {
|
||||
delete process.env.APP_NAME;
|
||||
} else {
|
||||
process.env.APP_NAME = originalAppName;
|
||||
}
|
||||
});
|
||||
|
||||
it("uses a grammatical neutral app-name fallback in queued deletion emails", async () => {
|
||||
const response = await callDeleteAction();
|
||||
const data = await response.json();
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(data).toMatchObject({ intent: "delete", ok: true, emailSent: true });
|
||||
expect(mocks.enqueuePrivacyNotification).toHaveBeenCalledTimes(1);
|
||||
const queued = mocks.enqueuePrivacyNotification.mock.calls[0]?.[0] as { subject?: string; text?: string; sourceKey?: string };
|
||||
|
||||
expect(queued.subject).toBe("Confirm account deletion for this application");
|
||||
expect(queued.text).toContain("delete your account for this application");
|
||||
expect(`${queued.subject}\n${queued.text}`).not.toMatch(/your your|undefined/);
|
||||
});
|
||||
|
||||
it("reports a failure instead of claiming the confirmation link was sent", async () => {
|
||||
// The link carries a hard deadline, so an unavailable queue must surface as
|
||||
// an error rather than a success message the user cannot act on.
|
||||
mocks.enqueuePrivacyNotification.mockResolvedValue({ enqueued: false, reason: "queue-unavailable" });
|
||||
|
||||
const response = await callDeleteAction();
|
||||
const data = await response.json();
|
||||
|
||||
expect(response.status).toBe(502);
|
||||
expect(data).toMatchObject({ ok: false });
|
||||
expect(mocks.createAuditEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ outcome: "failure", metadata: expect.objectContaining({ phase: "send-confirmation-email" }) })
|
||||
);
|
||||
});
|
||||
});
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
// Guard test (#72 i18n-foundation): the tenant profile route MUST keep its
|
||||
// locale picker. The picker itself lives in
|
||||
// `apps/web/app/modules/users/components/UserProfileSettings.tsx`. The route
|
||||
// composes the component and passes `currentSession.locale` so the UI can
|
||||
// show the active language. If somebody refactors the picker out we want CI
|
||||
// to scream — switching language is a privacy/UX requirement we already
|
||||
// shipped, not an optional feature.
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const profilePath = path.join(__dirname, "index.tsx");
|
||||
const settingsPath = path.resolve(__dirname, "../../../../modules/users/components/UserProfileSettings.tsx");
|
||||
|
||||
describe("tenant profile locale picker", () => {
|
||||
test("profile route loader includes the active locale in currentSession", () => {
|
||||
const source = readFileSync(profilePath, "utf8");
|
||||
expect(source).toContain("currentSession: getCurrentSessionSettings");
|
||||
expect(source).toContain("locale: userInfo.lng");
|
||||
});
|
||||
|
||||
test("UserProfileSettings exposes a locale-picker InputSelect", () => {
|
||||
const source = readFileSync(settingsPath, "utf8");
|
||||
// The picker uses the runtime-enabled locale contract to render options and
|
||||
// submits the change to the root /preferences action via setLocale.
|
||||
expect(source).toContain("const { csrf, enabledLocales } = useRootData()");
|
||||
expect(source).toContain("selectableLocales.map");
|
||||
expect(source).toMatch(/changedLocale\(/);
|
||||
expect(source).toContain('"setLocale"');
|
||||
expect(source).toContain('"/preferences"');
|
||||
});
|
||||
});
|
||||
+583
@@ -0,0 +1,583 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({
|
||||
t: (key: string) =>
|
||||
({
|
||||
"shared.invalidForm": "Form not submitted correctly.",
|
||||
"shared.unexpectedError": "Unexpected error",
|
||||
"settings.profile.errors.firstNameRequired": "First name required",
|
||||
"settings.profile.errors.invalidPassword": "Invalid password.",
|
||||
"settings.profile.errors.passwordMinLength": "Passwords must have least 6 characters.",
|
||||
"settings.profile.errors.currentPasswordRequired": "Current password is required.",
|
||||
"settings.profile.errors.cannotDeleteAdmin": "Cannot delete an admin",
|
||||
"settings.profile.passwordUpdated": "Password updated",
|
||||
"settings.profile.mfa.enrollmentStarted": "Authenticator enrollment started",
|
||||
"settings.profile.mfa.enabled": "Authenticator enabled",
|
||||
"settings.profile.mfa.disabled": "Authenticator disabled",
|
||||
"settings.profile.mfa.enterCode": "Enter the 6-digit authenticator code.",
|
||||
"settings.profile.mfa.noPendingEnrollment": "No pending authenticator enrollment found.",
|
||||
"settings.profile.mfa.invalidCode": "Invalid authenticator code.",
|
||||
})[key] ?? key,
|
||||
})),
|
||||
}));
|
||||
vi.mock("~/utils/loaders.middleware", () => ({
|
||||
requireAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
createUserSession: vi.fn(),
|
||||
getUserInfo: vi.fn(),
|
||||
getUserSession: vi.fn(),
|
||||
storage: { destroySession: vi.fn() },
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
getTenant: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: {
|
||||
user: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
vi.mock("~/utils/db/users.db.server", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("~/utils/db/users.db.server")>();
|
||||
return {
|
||||
...actual,
|
||||
activateUserTotpPendingSecret: vi.fn(),
|
||||
disableUserTotp: vi.fn(),
|
||||
getUserTotpStatus: vi.fn(),
|
||||
setUserMfaRecoveryCodes: vi.fn(),
|
||||
setUserTotpPendingSecret: vi.fn(),
|
||||
updateUserPassword: vi.fn(),
|
||||
updateUserProfile: vi.fn(),
|
||||
};
|
||||
});
|
||||
vi.mock("~/services/auth/totp.server", () => ({
|
||||
getFreshTotpPendingEnrollmentForUser: vi.fn(),
|
||||
startTotpEnrollment: vi.fn(),
|
||||
verifyTotpCode: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/auth/mfa/recovery-codes.server", () => ({
|
||||
generateRecoveryCodes: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/modules/events/services/.server/EventsService", () => ({
|
||||
default: { createUserEventWithMutation: vi.fn(async (_args, mutation) => mutation()) },
|
||||
}));
|
||||
vi.mock("bcryptjs", () => ({
|
||||
default: { compare: vi.fn(), hash: vi.fn() },
|
||||
}));
|
||||
vi.mock("~/utils/auth/passwordHasher.server", () => ({
|
||||
hashPassword: vi.fn(async () => "new-hash"),
|
||||
verifyPassword: vi.fn(async () => ({ valid: true })),
|
||||
}));
|
||||
vi.mock("~/services/auth/password-policy.server", () => ({
|
||||
validatePassword: vi.fn(async () => ({ valid: true, errors: [] })),
|
||||
loadPasswordPolicy: vi.fn(() => ({
|
||||
minLength: 1,
|
||||
requireUpper: false,
|
||||
requireLower: false,
|
||||
requireDigit: false,
|
||||
requireSpecial: false,
|
||||
hibpCheck: false,
|
||||
hibpMaxOccurrences: 0,
|
||||
})),
|
||||
MIN_PASSWORD_LENGTH: 12,
|
||||
}));
|
||||
vi.mock("~/utils/integrations/storageService", () => ({
|
||||
storeFile: vi.fn(),
|
||||
deleteFile: vi.fn(),
|
||||
resolveStorageBucket: vi.fn(() => "hivegrid-media"),
|
||||
// The avatar write-path maps these onto Klartext messages instead of a 500.
|
||||
StorageScanRejectedError: class StorageScanRejectedError extends Error {},
|
||||
UploadContentReadError: class UploadContentReadError extends Error {},
|
||||
}));
|
||||
vi.mock("~/utils/services/userService", () => ({ deleteUserWithItsTenants: vi.fn() }));
|
||||
vi.mock("~/services/auth/sessionStore.server", () => ({ revokeAllUserSessionsForUser: vi.fn() }));
|
||||
|
||||
import { hashPassword, verifyPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { validatePassword as validatePolicyPassword } from "~/services/auth/password-policy.server";
|
||||
import EventsService from "~/modules/events/services/.server/EventsService";
|
||||
import { generateRecoveryCodes } from "~/utils/auth/mfa/recovery-codes.server";
|
||||
import { getFreshTotpPendingEnrollmentForUser, startTotpEnrollment, verifyTotpCode } from "~/services/auth/totp.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import {
|
||||
activateUserTotpPendingSecret,
|
||||
disableUserTotp,
|
||||
getUserTotpStatus,
|
||||
setUserMfaRecoveryCodes,
|
||||
setUserTotpPendingSecret,
|
||||
updateUserPassword,
|
||||
updateUserProfile,
|
||||
} from "~/utils/db/users.db.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { createUserSession, getUserInfo, getUserSession, storage } from "~/utils/session.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { storeFile } from "~/utils/integrations/storageService";
|
||||
import { deleteUserWithItsTenants } from "~/utils/services/userService";
|
||||
import { action, loader } from "./index";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { revokeAllUserSessionsForUser } from "~/services/auth/sessionStore.server";
|
||||
|
||||
const params = { tenant: "acme" };
|
||||
const user = {
|
||||
id: "user_1",
|
||||
email: "ada@example.com",
|
||||
passwordHash: "hashed-password",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
admin: null,
|
||||
};
|
||||
const tenant = { id: "tenant_1", slug: "acme" };
|
||||
const disabledStatus = { enabled: false, pending: false, enabledAt: null, pendingCreatedAt: null };
|
||||
const pendingStatus = { enabled: false, pending: true, enabledAt: null, pendingCreatedAt: new Date("2026-05-08T12:00:00.000Z") };
|
||||
const enabledStatus = { enabled: true, pending: false, enabledAt: new Date("2026-05-08T12:05:00.000Z"), pendingCreatedAt: null };
|
||||
const recoveryGeneratedAt = new Date("2026-05-08T12:05:01.000Z");
|
||||
const recoveryCodes = ["ABCD-EFGH-JKLM", "NPQR-STUV-WXYZ"];
|
||||
const recoveryEntries = recoveryCodes.map((code, index) => ({ hash: `hash-${index + 1}`, usedAt: null, createdAt: recoveryGeneratedAt }));
|
||||
|
||||
function postRequest(form: FormData) {
|
||||
return new Request("https://app.example.test/acme/settings/profile", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(form as unknown as Record<string, string>),
|
||||
});
|
||||
}
|
||||
|
||||
function formWithAction(actionName: string, values: Record<string, string> = {}) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", actionName);
|
||||
Object.entries(values).forEach(([key, value]) => form.set(key, value));
|
||||
return form;
|
||||
}
|
||||
|
||||
async function callAction(form: FormData) {
|
||||
return action({
|
||||
request: postRequest(form),
|
||||
params,
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/settings/profile",
|
||||
} as ActionFunctionArgs) as Promise<Response>;
|
||||
}
|
||||
|
||||
async function json(response: Response) {
|
||||
return response.json() as Promise<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
function expectNoSecretLeak(payload: unknown) {
|
||||
const serialized = JSON.stringify(payload);
|
||||
expect(serialized).not.toContain("RAWSECRET");
|
||||
expect(serialized).not.toContain("encrypted-secret");
|
||||
expect(serialized).not.toContain("encrypted-pending");
|
||||
expect(serialized).not.toContain("123456");
|
||||
expect(serialized).not.toContain("password-123");
|
||||
expect(serialized).not.toContain("totpSecretEncrypted");
|
||||
expect(serialized).not.toContain("secret");
|
||||
expect(serialized).not.toContain("ABCD-EFGH-JKLM");
|
||||
expect(serialized).not.toContain("NPQR-STUV-WXYZ");
|
||||
expect(serialized).not.toContain("hash-1");
|
||||
expect(serialized).not.toContain("hash-2");
|
||||
}
|
||||
|
||||
describe("profile MFA route actions", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(requireAuth).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue({ userId: user.id } as never);
|
||||
vi.mocked(createUserSession).mockResolvedValue(
|
||||
new Response(null, { status: 302, headers: { "Set-Cookie": "hivegrid_app_session=rotated; Path=/; HttpOnly" } }) as never
|
||||
);
|
||||
vi.mocked(getUserSession).mockResolvedValue({ id: "session_1", get: vi.fn(), set: vi.fn(), unset: vi.fn() } as never);
|
||||
vi.mocked(storage.destroySession).mockResolvedValue("hivegrid_session=; Max-Age=0; Path=/; HttpOnly" as never);
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue(tenant.id);
|
||||
vi.mocked(getTenant).mockResolvedValue(tenant as never);
|
||||
vi.mocked(db.user.findUnique).mockResolvedValue(user as never);
|
||||
vi.mocked(updateUserProfile).mockResolvedValue({ ...user, avatar: "stored-avatar" } as never);
|
||||
vi.mocked(updateUserPassword).mockResolvedValue({ ...user, passwordHash: "new-hash" } as never);
|
||||
vi.mocked(storeFile).mockResolvedValue("stored-avatar" as never);
|
||||
vi.mocked(deleteUserWithItsTenants).mockResolvedValue({ deletedTenants: [{ id: tenant.id, name: "Acme" }] } as never);
|
||||
vi.mocked(getUserTotpStatus).mockResolvedValue(disabledStatus);
|
||||
vi.mocked(verifyPassword).mockResolvedValue({ valid: true });
|
||||
vi.mocked(startTotpEnrollment).mockReturnValue({
|
||||
secret: "RAWSECRET",
|
||||
encryptedSecret: "encrypted-secret",
|
||||
otpauthUri: "otpauth://totp/HiveGrid:ada@example.com?secret=RAWSECRET&issuer=HiveGrid",
|
||||
qrValue: "otpauth://totp/HiveGrid:ada@example.com?secret=RAWSECRET&issuer=HiveGrid",
|
||||
});
|
||||
vi.mocked(verifyTotpCode).mockReturnValue(true);
|
||||
vi.mocked(getFreshTotpPendingEnrollmentForUser).mockResolvedValue({
|
||||
totpPendingSecretEncrypted: "encrypted-pending",
|
||||
totpPendingCreatedAt: pendingStatus.pendingCreatedAt,
|
||||
});
|
||||
vi.mocked(generateRecoveryCodes).mockReturnValue({
|
||||
codes: recoveryCodes,
|
||||
entries: recoveryEntries,
|
||||
generatedAt: recoveryGeneratedAt,
|
||||
});
|
||||
});
|
||||
|
||||
it("loader exposes only non-secret MFA status for the current user", async () => {
|
||||
const response = await loader({
|
||||
request: new Request("https://app.example.test/acme/settings/profile"),
|
||||
params,
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/settings/profile",
|
||||
} as LoaderFunctionArgs);
|
||||
|
||||
expect(requireAuth).toHaveBeenCalled();
|
||||
expect(getUserTotpStatus).toHaveBeenCalledWith(user.id);
|
||||
expect(response).toMatchObject({ mfaStatus: disabledStatus });
|
||||
expect(response).not.toHaveProperty("recoveryCodes");
|
||||
expectNoSecretLeak(response);
|
||||
});
|
||||
|
||||
it("starts TOTP enrollment after validating the current password", async () => {
|
||||
vi.mocked(getUserTotpStatus).mockResolvedValueOnce(disabledStatus).mockResolvedValueOnce(pendingStatus);
|
||||
|
||||
const response = await callAction(formWithAction("startTotpEnrollment", { passwordCurrent: "password-123" }));
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(verifyPassword).toHaveBeenCalledWith("password-123", user.passwordHash);
|
||||
expect(setUserTotpPendingSecret).toHaveBeenCalledWith(user.id, "encrypted-secret");
|
||||
expect(body).toEqual({
|
||||
success: "Authenticator enrollment started",
|
||||
mfaStatus: { ...pendingStatus, pendingCreatedAt: pendingStatus.pendingCreatedAt?.toISOString() },
|
||||
otpauthUri: expect.stringContaining("otpauth://"),
|
||||
});
|
||||
expect(JSON.stringify(body)).not.toContain("encrypted-secret");
|
||||
expectNoSecretLeak(vi.mocked(EventsService.createUserEventWithMutation).mock.calls);
|
||||
});
|
||||
|
||||
it("rejects start enrollment with a bad password without persisting pending state", async () => {
|
||||
vi.mocked(verifyPassword).mockResolvedValue({ valid: false });
|
||||
|
||||
const response = await callAction(formWithAction("startTotpEnrollment", { passwordCurrent: "password-123" }));
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body).toEqual({ mfaStatus: disabledStatus, mfaError: "Invalid password." });
|
||||
expect(setUserTotpPendingSecret).not.toHaveBeenCalled();
|
||||
expectNoSecretLeak(body);
|
||||
});
|
||||
|
||||
it("confirms pending TOTP enrollment and returns one-time recovery codes", async () => {
|
||||
vi.mocked(getUserTotpStatus).mockResolvedValueOnce(pendingStatus).mockResolvedValueOnce(enabledStatus);
|
||||
|
||||
const response = await callAction(formWithAction("confirmTotpEnrollment", { code: "123456", userId: "attacker" }));
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(verifyTotpCode).toHaveBeenCalledWith("encrypted-pending", "123456");
|
||||
expect(activateUserTotpPendingSecret).toHaveBeenCalledWith(user.id, "encrypted-pending");
|
||||
expect(generateRecoveryCodes).toHaveBeenCalledTimes(1);
|
||||
expect(setUserMfaRecoveryCodes).toHaveBeenCalledWith(user.id, recoveryEntries, recoveryGeneratedAt);
|
||||
expect(JSON.stringify(vi.mocked(activateUserTotpPendingSecret).mock.calls)).not.toContain("attacker");
|
||||
expect(body).toEqual({
|
||||
success: "Authenticator enabled",
|
||||
mfaStatus: { ...enabledStatus, enabledAt: enabledStatus.enabledAt?.toISOString() },
|
||||
recoveryCodes,
|
||||
});
|
||||
expect(JSON.stringify(body)).not.toContain("hash-1");
|
||||
expect(JSON.stringify(body)).not.toContain("hash-2");
|
||||
const enabledEvent = vi.mocked(EventsService.createUserEventWithMutation).mock.calls.at(-1)?.[0];
|
||||
const enabledEventData = typeof enabledEvent?.data === "function" ? enabledEvent.data(enabledStatus) : enabledEvent?.data;
|
||||
expect(enabledEventData).toMatchObject({
|
||||
recoveryCodes: { generatedCount: 2, remainingCount: 2, generatedAt: recoveryGeneratedAt },
|
||||
});
|
||||
expectNoSecretLeak(vi.mocked(EventsService.createUserEventWithMutation).mock.calls);
|
||||
});
|
||||
|
||||
it("rejects invalid or missing TOTP codes before verification", async () => {
|
||||
const response = await callAction(formWithAction("confirmTotpEnrollment", { code: "12ab56" }));
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body).toEqual({ mfaStatus: disabledStatus, mfaError: "Enter the 6-digit authenticator code." });
|
||||
expect(verifyTotpCode).not.toHaveBeenCalled();
|
||||
expect(generateRecoveryCodes).not.toHaveBeenCalled();
|
||||
expect(setUserMfaRecoveryCodes).not.toHaveBeenCalled();
|
||||
expectNoSecretLeak(body);
|
||||
});
|
||||
|
||||
it("rejects confirmation without a pending secret", async () => {
|
||||
vi.mocked(getFreshTotpPendingEnrollmentForUser).mockResolvedValue(null);
|
||||
|
||||
const response = await callAction(formWithAction("confirmTotpEnrollment", { code: "123456" }));
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body).toEqual({ mfaStatus: disabledStatus, mfaError: "No pending authenticator enrollment found." });
|
||||
expect(activateUserTotpPendingSecret).not.toHaveBeenCalled();
|
||||
expectNoSecretLeak(body);
|
||||
});
|
||||
|
||||
it("rejects an expired pending enrollment returned as discarded by the central TOTP service", async () => {
|
||||
vi.mocked(getFreshTotpPendingEnrollmentForUser).mockResolvedValueOnce(null);
|
||||
|
||||
const response = await callAction(formWithAction("confirmTotpEnrollment", { code: "123456" }));
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body).toEqual({ mfaStatus: disabledStatus, mfaError: "No pending authenticator enrollment found." });
|
||||
expect(verifyTotpCode).not.toHaveBeenCalled();
|
||||
expect(activateUserTotpPendingSecret).not.toHaveBeenCalled();
|
||||
expect(generateRecoveryCodes).not.toHaveBeenCalled();
|
||||
expect(setUserMfaRecoveryCodes).not.toHaveBeenCalled();
|
||||
expectNoSecretLeak(body);
|
||||
});
|
||||
|
||||
it("rejects invalid confirmation codes without activating pending state", async () => {
|
||||
vi.mocked(verifyTotpCode).mockReturnValue(false);
|
||||
|
||||
const response = await callAction(formWithAction("confirmTotpEnrollment", { code: "123456" }));
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body).toEqual({ mfaStatus: disabledStatus, mfaError: "Invalid authenticator code." });
|
||||
expect(activateUserTotpPendingSecret).not.toHaveBeenCalled();
|
||||
expect(generateRecoveryCodes).not.toHaveBeenCalled();
|
||||
expect(setUserMfaRecoveryCodes).not.toHaveBeenCalled();
|
||||
expectNoSecretLeak(body);
|
||||
});
|
||||
|
||||
it("disables TOTP only after validating the current password", async () => {
|
||||
vi.mocked(getUserTotpStatus).mockResolvedValueOnce(enabledStatus).mockResolvedValueOnce(disabledStatus);
|
||||
|
||||
const response = await callAction(formWithAction("disableTotpEnrollment", { passwordCurrent: "password-123" }));
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(verifyPassword).toHaveBeenCalledWith("password-123", user.passwordHash);
|
||||
expect(disableUserTotp).toHaveBeenCalledWith(user.id);
|
||||
expect(body).toEqual({ success: "Authenticator disabled", mfaStatus: disabledStatus });
|
||||
expectNoSecretLeak(body);
|
||||
expectNoSecretLeak(vi.mocked(EventsService.createUserEventWithMutation).mock.calls);
|
||||
});
|
||||
|
||||
it("rejects disabling without a password", async () => {
|
||||
const response = await callAction(formWithAction("disableTotpEnrollment"));
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body).toEqual({ mfaStatus: disabledStatus, mfaError: "Current password is required." });
|
||||
expect(disableUserTotp).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("propagates unauthenticated rejection before reading or mutating MFA state", async () => {
|
||||
const rejection = new Response(null, { status: 302, headers: { Location: "/login" } });
|
||||
vi.mocked(requireAuth).mockRejectedValueOnce(rejection as never);
|
||||
|
||||
await expect(callAction(formWithAction("startTotpEnrollment", { passwordCurrent: "password-123" }))).rejects.toBe(rejection);
|
||||
expect(getUserInfo).not.toHaveBeenCalled();
|
||||
expect(setUserTotpPendingSecret).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updates profile fields for the authenticated user and ignores tampered form user IDs", async () => {
|
||||
const response = await callAction(
|
||||
formWithAction("profile", {
|
||||
userId: "attacker",
|
||||
firstName: "Grace",
|
||||
lastName: "Hopper",
|
||||
avatar: "data:image/png;base64,avatar",
|
||||
passwordCurrent: "password-123",
|
||||
})
|
||||
);
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
// The bytes go into the configured private bucket under the user's own key —
|
||||
// never into the legacy per-purpose bucket, which does not exist.
|
||||
expect(storeFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
bucket: "hivegrid-media",
|
||||
content: "data:image/png;base64,avatar",
|
||||
id: `users/${user.id}/avatar`,
|
||||
scan: expect.objectContaining({ context: "avatar", filename: `${user.id}.avatar` }),
|
||||
})
|
||||
);
|
||||
// The persisted value is the auth-proxy path, not storeFile's return: the
|
||||
// bucket is private, so there is no public object URL to store.
|
||||
const [profileUpdate, updatedUserId] = vi.mocked(updateUserProfile).mock.calls.at(-1) ?? [];
|
||||
expect(updatedUserId).toBe(user.id);
|
||||
expect(profileUpdate).toMatchObject({ firstName: "Grace", lastName: "Hopper" });
|
||||
expect(profileUpdate?.avatar).toMatch(new RegExp(`^/avatars/${user.id}\\?v=`));
|
||||
expect(JSON.stringify(vi.mocked(updateUserProfile).mock.calls)).not.toContain("attacker");
|
||||
expect(body).toEqual({ success: "shared.updated" });
|
||||
expect(vi.mocked(EventsService.createUserEventWithMutation).mock.calls.at(-1)?.[0]).toMatchObject({
|
||||
event: "user.profile.updated",
|
||||
userId: user.id,
|
||||
data: {
|
||||
email: user.email,
|
||||
new: { firstName: "Grace", lastName: "Hopper" },
|
||||
old: { firstName: user.firstName, lastName: user.lastName },
|
||||
userId: user.id,
|
||||
},
|
||||
});
|
||||
expectNoSecretLeak(vi.mocked(EventsService.createUserEventWithMutation).mock.calls);
|
||||
});
|
||||
|
||||
it("rejects invalid profile payloads before updating the authenticated user", async () => {
|
||||
const response = await callAction(formWithAction("profile", { firstName: "A", lastName: "Hopper", userId: "attacker" }));
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body).toEqual({ error: "Form not submitted correctly.", fields: { firstName: "First name required" } });
|
||||
expect(updateUserProfile).not.toHaveBeenCalled();
|
||||
expect(EventsService.createUserEventWithMutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("changes password only after comparing the current password and hashes the submitted new password", async () => {
|
||||
// hashPassword mock is already set to return "new-hash" globally.
|
||||
|
||||
const response = await callAction(
|
||||
formWithAction("password", {
|
||||
userId: "attacker",
|
||||
passwordCurrent: "password-123",
|
||||
passwordNew: "new-password",
|
||||
passwordNewConfirm: "new-password",
|
||||
})
|
||||
);
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(verifyPassword).toHaveBeenCalledWith("password-123", user.passwordHash);
|
||||
expect(hashPassword).toHaveBeenCalledWith("new-password");
|
||||
expect(updateUserPassword).toHaveBeenCalledWith({ passwordHash: "new-hash" }, user.id);
|
||||
expect(revokeAllUserSessionsForUser).toHaveBeenCalledWith(user.id);
|
||||
expect(vi.mocked(revokeAllUserSessionsForUser).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(updateUserPassword).mock.invocationCallOrder[0]!);
|
||||
expect(createUserSession).toHaveBeenCalledWith(expect.objectContaining({ userId: user.id }), "/acme/settings/profile", {
|
||||
request: expect.any(Request),
|
||||
rotate: true,
|
||||
});
|
||||
expect(response.headers.get("Set-Cookie")).toContain("hivegrid_app_session=rotated");
|
||||
expect(JSON.stringify(vi.mocked(updateUserPassword).mock.calls)).not.toContain("attacker");
|
||||
expect(body).toEqual({ passwordSuccess: "Password updated" });
|
||||
expect(vi.mocked(EventsService.createUserEventWithMutation).mock.calls.at(-1)?.[0]).toMatchObject({
|
||||
event: "user.password.updated",
|
||||
userId: user.id,
|
||||
data: { user: { id: user.id, email: user.email } },
|
||||
});
|
||||
expectNoSecretLeak(vi.mocked(EventsService.createUserEventWithMutation).mock.calls);
|
||||
});
|
||||
|
||||
it("rejects bad current passwords before hashing or updating the password", async () => {
|
||||
vi.mocked(verifyPassword).mockResolvedValue({ valid: false });
|
||||
|
||||
const response = await callAction(
|
||||
formWithAction("password", { passwordCurrent: "password-123", passwordNew: "new-password", passwordNewConfirm: "new-password" })
|
||||
);
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body).toEqual({ error: "Invalid password." });
|
||||
expect(hashPassword).not.toHaveBeenCalled();
|
||||
expect(updateUserPassword).not.toHaveBeenCalled();
|
||||
expect(EventsService.createUserEventWithMutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects invalid password fields before comparing passwords", async () => {
|
||||
vi.mocked(validatePolicyPassword).mockResolvedValueOnce({
|
||||
valid: false,
|
||||
errors: [{ code: "auth.password.errors.tooShort", args: { minLength: 12 } }],
|
||||
});
|
||||
const response = await callAction(formWithAction("password", { passwordCurrent: "password-123", passwordNew: "short", passwordNewConfirm: "short" }));
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body).toEqual({ error: "auth.password.errors.tooShort" });
|
||||
expect(verifyPassword).not.toHaveBeenCalled();
|
||||
expect(updateUserPassword).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("deletes only the authenticated non-admin user and keeps deletion events redacted", async () => {
|
||||
const response = await callAction(formWithAction("deleteAccount", { userId: "attacker", passwordCurrent: "password-123" }));
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("Location")).toBe("/login");
|
||||
expect(getUserSession).toHaveBeenCalled();
|
||||
expect(storage.destroySession).toHaveBeenCalledWith(expect.objectContaining({ id: "session_1" }));
|
||||
expect(response.headers.get("Set-Cookie")).toContain("Max-Age=0");
|
||||
expect(deleteUserWithItsTenants).toHaveBeenCalledWith({
|
||||
actorUserId: user.id,
|
||||
targetUser: user,
|
||||
request: expect.any(Request),
|
||||
});
|
||||
expect(JSON.stringify(vi.mocked(deleteUserWithItsTenants).mock.calls)).not.toContain("attacker");
|
||||
expect(EventsService.createUserEventWithMutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects account deletion without the current password", async () => {
|
||||
const response = await callAction(formWithAction("deleteAccount"));
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body).toEqual({ error: "Current password is required." });
|
||||
expect(verifyPassword).not.toHaveBeenCalled();
|
||||
expect(deleteUserWithItsTenants).not.toHaveBeenCalled();
|
||||
expect(EventsService.createUserEventWithMutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects account deletion with an invalid current password", async () => {
|
||||
vi.mocked(verifyPassword).mockResolvedValue({ valid: false });
|
||||
|
||||
const response = await callAction(formWithAction("deleteAccount", { passwordCurrent: "password-123" }));
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body).toEqual({ error: "Invalid password." });
|
||||
expect(verifyPassword).toHaveBeenCalledWith("password-123", user.passwordHash);
|
||||
expect(deleteUserWithItsTenants).not.toHaveBeenCalled();
|
||||
expect(EventsService.createUserEventWithMutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns an error when the deletion service fails after password validation", async () => {
|
||||
vi.mocked(deleteUserWithItsTenants).mockRejectedValueOnce(new Error("delete failed") as never);
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
|
||||
const response = await callAction(formWithAction("deleteAccount", { passwordCurrent: "password-123" }));
|
||||
const body = await json(response);
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body).toEqual({ error: "Unexpected error" });
|
||||
expect(verifyPassword).toHaveBeenCalledWith("password-123", user.passwordHash);
|
||||
expect(EventsService.createUserEventWithMutation).not.toHaveBeenCalled();
|
||||
expect(storage.destroySession).not.toHaveBeenCalled();
|
||||
expect(consoleError).toHaveBeenCalledWith(expect.any(Error));
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
it("does not treat the removed legacy User admin projection as a platform identity", async () => {
|
||||
vi.mocked(db.user.findUnique).mockResolvedValueOnce({ ...user, admin: { id: "admin_1" } } as never);
|
||||
|
||||
const response = await callAction(formWithAction("deleteAccount", { userId: "attacker", passwordCurrent: "password-123" }));
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(response.headers.get("Location")).toBe("/login");
|
||||
expect(deleteUserWithItsTenants).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
actorUserId: user.id,
|
||||
targetUser: expect.objectContaining({ id: user.id }),
|
||||
})
|
||||
);
|
||||
expect(EventsService.createUserEventWithMutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("propagates unauthenticated rejection before profile, password, or delete mutations", async () => {
|
||||
const rejection = new Response(null, { status: 302, headers: { Location: "/login" } });
|
||||
vi.mocked(requireAuth).mockRejectedValueOnce(rejection as never);
|
||||
|
||||
await expect(callAction(formWithAction("profile", { firstName: "Grace", lastName: "Hopper" }))).rejects.toBe(rejection);
|
||||
expect(getUserInfo).not.toHaveBeenCalled();
|
||||
expect(updateUserProfile).not.toHaveBeenCalled();
|
||||
expect(updateUserPassword).not.toHaveBeenCalled();
|
||||
expect(deleteUserWithItsTenants).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({
|
||||
t: (key: string) =>
|
||||
({
|
||||
"settings.profile.mfa.sessionCleared": "Session MFA verification cleared",
|
||||
})[key] ?? key,
|
||||
})),
|
||||
}));
|
||||
vi.mock("~/utils/loaders.middleware", () => ({
|
||||
requireAuth: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
commitSession: vi.fn(),
|
||||
createUserSession: vi.fn(),
|
||||
getUserInfo: vi.fn(),
|
||||
getUserSession: vi.fn(),
|
||||
storage: { destroySession: vi.fn() },
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/services/auth/sessionStore.server", () => ({ revokeAllUserSessionsForUser: vi.fn() }));
|
||||
vi.mock("~/utils/auth/mfa/step-up.server", () => ({
|
||||
checkMfaStepUpState: vi.fn(),
|
||||
clearMfaStepUpState: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
getTenant: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: { user: { findUnique: vi.fn() } },
|
||||
}));
|
||||
vi.mock("~/utils/db/users.db.server", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("~/utils/db/users.db.server")>();
|
||||
return {
|
||||
...actual,
|
||||
activateUserTotpPendingSecret: vi.fn(),
|
||||
disableUserTotp: vi.fn(),
|
||||
getUserTotpPendingEnrollment: vi.fn(),
|
||||
getUserTotpStatus: vi.fn(),
|
||||
setUserMfaRecoveryCodes: vi.fn(),
|
||||
setUserTotpPendingSecret: vi.fn(),
|
||||
updateUserPassword: vi.fn(),
|
||||
updateUserProfile: vi.fn(),
|
||||
};
|
||||
});
|
||||
vi.mock("~/services/auth/totp.server", () => ({
|
||||
getFreshTotpPendingEnrollmentForUser: vi.fn(),
|
||||
startTotpEnrollment: vi.fn(),
|
||||
verifyTotpCode: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/auth/mfa/recovery-codes.server", () => ({
|
||||
generateRecoveryCodes: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/modules/events/services/.server/EventsService", () => ({
|
||||
default: { create: vi.fn() },
|
||||
}));
|
||||
vi.mock("bcryptjs", () => ({
|
||||
default: { compare: vi.fn(), hash: vi.fn() },
|
||||
}));
|
||||
vi.mock("~/utils/integrations/storageService", () => ({ storeFile: vi.fn() }));
|
||||
vi.mock("~/utils/services/userService", () => ({ deleteUserWithItsTenants: vi.fn() }));
|
||||
|
||||
import { checkMfaStepUpState, clearMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { getUserTotpStatus } from "~/utils/db/users.db.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { commitSession, getUserInfo, getUserSession, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getFreshTotpPendingEnrollmentForUser } from "~/services/auth/totp.server";
|
||||
import { action, loader } from "./index";
|
||||
|
||||
const params = { tenant: "acme" };
|
||||
const user = {
|
||||
id: "user_1",
|
||||
email: "ada@example.com",
|
||||
passwordHash: "hashed-password",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
admin: null,
|
||||
};
|
||||
const tenant = { id: "tenant_1", slug: "acme" };
|
||||
const disabledStatus = { enabled: false, pending: false, enabledAt: null, pendingCreatedAt: null };
|
||||
|
||||
type SessionMock = {
|
||||
get: ReturnType<typeof vi.fn>;
|
||||
set: ReturnType<typeof vi.fn>;
|
||||
unset: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
function sessionMock(): SessionMock {
|
||||
return { get: vi.fn(), set: vi.fn(), unset: vi.fn() };
|
||||
}
|
||||
|
||||
function postRequest(actionName: string) {
|
||||
return new Request("https://app.example.test/acme/settings/profile", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({ action: actionName, csrf: "csrf-secret" }),
|
||||
});
|
||||
}
|
||||
|
||||
async function callLoader() {
|
||||
return loader({
|
||||
request: new Request("https://app.example.test/acme/settings/profile"),
|
||||
params,
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/settings/profile",
|
||||
} as LoaderFunctionArgs);
|
||||
}
|
||||
|
||||
async function callAction(actionName: string) {
|
||||
return action({
|
||||
request: postRequest(actionName),
|
||||
params,
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/settings/profile",
|
||||
} as ActionFunctionArgs) as Promise<Response>;
|
||||
}
|
||||
|
||||
function expectNoSessionLeak(payload: unknown) {
|
||||
const serialized = JSON.stringify(payload);
|
||||
expect(serialized).not.toContain("hivegrid_session");
|
||||
expect(serialized).not.toContain("raw-cookie-value");
|
||||
expect(serialized).not.toContain("csrf-secret");
|
||||
expect(serialized).not.toContain("adminMfaStepUp");
|
||||
expect(serialized).not.toContain("redirectTo");
|
||||
expect(serialized).not.toContain("actor-user-1");
|
||||
expect(serialized).not.toContain("password");
|
||||
}
|
||||
|
||||
describe("profile current-session settings", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(requireAuth).mockResolvedValue(undefined as never);
|
||||
vi.mocked(getUserInfo).mockResolvedValue({
|
||||
userId: user.id,
|
||||
lng: "en",
|
||||
lightOrDarkMode: "dark",
|
||||
theme: "zinc",
|
||||
csrf: "csrf-secret",
|
||||
cookies: [
|
||||
{ category: "REQUIRED", allowed: true },
|
||||
{ category: "ANALYTICS", allowed: false },
|
||||
{ category: "FUNCTIONAL", allowed: true },
|
||||
],
|
||||
impersonatingFromUserId: "actor-user-1",
|
||||
impersonatingStartedAt: "2026-05-08T12:00:00.000Z",
|
||||
} as never);
|
||||
vi.mocked(getUserSession).mockResolvedValue(sessionMock() as never);
|
||||
vi.mocked(getTenantIdFromUrl).mockResolvedValue(tenant.id);
|
||||
vi.mocked(getTenant).mockResolvedValue(tenant as never);
|
||||
vi.mocked(db.user.findUnique).mockResolvedValue(user as never);
|
||||
vi.mocked(getUserTotpStatus).mockResolvedValue(disabledStatus);
|
||||
vi.mocked(getFreshTotpPendingEnrollmentForUser).mockResolvedValue(null);
|
||||
vi.mocked(checkMfaStepUpState).mockReturnValue({
|
||||
verified: true,
|
||||
state: { userId: user.id, method: "totp", verifiedAt: "2026-05-08T12:00:00.000Z", redirectTo: "/admin" },
|
||||
ageMs: 10_000,
|
||||
});
|
||||
vi.mocked(commitSession).mockResolvedValue("hivegrid_session=updated-cookie; Path=/; HttpOnly" as never);
|
||||
vi.mocked(validateCSRFToken).mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("loader exposes only redacted facts for the current cookie session", async () => {
|
||||
const response = await callLoader();
|
||||
|
||||
expect(requireAuth).toHaveBeenCalled();
|
||||
expect(getUserSession).toHaveBeenCalledWith(expect.any(Request));
|
||||
expect(checkMfaStepUpState).toHaveBeenCalledWith(expect.anything(), user.id);
|
||||
expect(response).toMatchObject({
|
||||
mfaStatus: disabledStatus,
|
||||
currentSession: {
|
||||
locale: "en",
|
||||
lightOrDarkMode: "dark",
|
||||
theme: "zinc",
|
||||
cookieConsentCount: 2,
|
||||
impersonationActive: true,
|
||||
mfaStepUp: { present: true, verified: true, stale: false, method: "totp" },
|
||||
},
|
||||
});
|
||||
expectNoSessionLeak(response);
|
||||
});
|
||||
|
||||
it("marks malformed or stale step-up state as unverified without exposing raw state", async () => {
|
||||
vi.mocked(checkMfaStepUpState).mockReturnValueOnce({ verified: false, reason: "stale" });
|
||||
|
||||
const response = await callLoader();
|
||||
|
||||
expect(response).toMatchObject({
|
||||
currentSession: {
|
||||
mfaStepUp: { present: true, verified: false, stale: true, reason: "stale" },
|
||||
},
|
||||
});
|
||||
expectNoSessionLeak(response);
|
||||
});
|
||||
|
||||
it("reports absent step-up state without showing a verified session", async () => {
|
||||
vi.mocked(checkMfaStepUpState).mockReturnValueOnce({ verified: false, reason: "missing" });
|
||||
|
||||
const response = await callLoader();
|
||||
|
||||
expect(response).toMatchObject({
|
||||
currentSession: {
|
||||
mfaStepUp: { present: false, verified: false, stale: false, reason: "missing" },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("clears only the current session MFA step-up state and commits an updated cookie", async () => {
|
||||
const session = sessionMock();
|
||||
vi.mocked(getUserSession).mockResolvedValue(session as never);
|
||||
vi.mocked(checkMfaStepUpState).mockReturnValueOnce({
|
||||
verified: true,
|
||||
state: { userId: user.id, method: "totp", verifiedAt: "2026-05-08T12:00:00.000Z" },
|
||||
ageMs: 1_000,
|
||||
});
|
||||
vi.mocked(db.user.findUnique).mockImplementationOnce(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({
|
||||
tenantId: tenant.id,
|
||||
userId: user.id,
|
||||
});
|
||||
return user as never;
|
||||
});
|
||||
|
||||
const response = await callAction("clearMfaStepUp");
|
||||
const body = await response.json();
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(validateCSRFToken).toHaveBeenCalledWith(expect.any(Request));
|
||||
expect(clearMfaStepUpState).toHaveBeenCalledWith(session);
|
||||
expect(commitSession).toHaveBeenCalledWith(session);
|
||||
expect(response.headers.get("Set-Cookie")).toBe("hivegrid_session=updated-cookie; Path=/; HttpOnly");
|
||||
expect(body).toMatchObject({ success: "Session MFA verification cleared", currentSession: { mfaStepUp: { present: true, verified: true } } });
|
||||
expectNoSessionLeak(body);
|
||||
});
|
||||
|
||||
it("propagates unauthenticated rejection before reading or mutating session state", async () => {
|
||||
const rejection = new Response(null, { status: 302, headers: { Location: "/login" } });
|
||||
vi.mocked(requireAuth).mockRejectedValueOnce(rejection as never);
|
||||
|
||||
await expect(callAction("clearMfaStepUp")).rejects.toBe(rejection);
|
||||
expect(getUserInfo).not.toHaveBeenCalled();
|
||||
expect(clearMfaStepUpState).not.toHaveBeenCalled();
|
||||
expect(commitSession).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
requireAuth: vi.fn(),
|
||||
getUserInfo: vi.fn(),
|
||||
getValidatedServerSession: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
listActiveUserSessions: vi.fn(),
|
||||
revokeUserSession: vi.fn(),
|
||||
revokeAllUserSessionsExcept: vi.fn(),
|
||||
markSessionTrusted: vi.fn(),
|
||||
listTrustedDevices: vi.fn(),
|
||||
revokeTrustedDevice: vi.fn(),
|
||||
revokeAllTrustedDevices: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/loaders.middleware", () => ({ requireAuth: (...a: unknown[]) => mocks.requireAuth(...a) }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })) }));
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
getUserInfo: (...a: unknown[]) => mocks.getUserInfo(...a),
|
||||
getValidatedServerSession: (...a: unknown[]) => mocks.getValidatedServerSession(...a),
|
||||
validateCSRFToken: (...a: unknown[]) => mocks.validateCSRFToken(...a),
|
||||
}));
|
||||
vi.mock("~/services/auth/sessionStore.server", () => ({
|
||||
listActiveUserSessions: (...a: unknown[]) => mocks.listActiveUserSessions(...a),
|
||||
revokeUserSession: (...a: unknown[]) => mocks.revokeUserSession(...a),
|
||||
revokeAllUserSessionsExcept: (...a: unknown[]) => mocks.revokeAllUserSessionsExcept(...a),
|
||||
markSessionTrusted: (...a: unknown[]) => mocks.markSessionTrusted(...a),
|
||||
}));
|
||||
vi.mock("~/utils/auth/mfa/trusted-device.server", () => ({
|
||||
listTrustedDevices: (...a: unknown[]) => mocks.listTrustedDevices(...a),
|
||||
revokeTrustedDevice: (...a: unknown[]) => mocks.revokeTrustedDevice(...a),
|
||||
revokeAllTrustedDevices: (...a: unknown[]) => mocks.revokeAllTrustedDevices(...a),
|
||||
}));
|
||||
|
||||
import { action, loader } from "./security";
|
||||
|
||||
const params = { tenant: "acme" };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.getUserInfo.mockResolvedValue({ userId: "u1", sessionToken: "tok-current", csrf: "csrf-1" });
|
||||
mocks.getValidatedServerSession.mockResolvedValue({ id: "s1" });
|
||||
mocks.listActiveUserSessions.mockResolvedValue([
|
||||
{ id: "s1", lastSeenAt: new Date(), ipAddress: "1.1.1.1", userAgent: "Firefox", deviceLabel: null, approxLocation: null, trustedAt: null },
|
||||
{ id: "s2", lastSeenAt: new Date(), ipAddress: "2.2.2.2", userAgent: "Safari", deviceLabel: null, approxLocation: null, trustedAt: null },
|
||||
]);
|
||||
mocks.listTrustedDevices.mockResolvedValue([{ id: "td1", deviceLabel: null, userAgent: "Firefox", approxLocation: "DE" }]);
|
||||
});
|
||||
|
||||
function postRequest(fields: Record<string, string>) {
|
||||
const body = new URLSearchParams(fields);
|
||||
return new Request("https://example.test/acme/settings/security", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
describe("security route loader", () => {
|
||||
it("builds a ready device-list VM and flags the current session", async () => {
|
||||
const data = await loader({ request: new Request("https://example.test/acme/settings/security"), params, context: {} } as never);
|
||||
expect(mocks.requireAuth).toHaveBeenCalled();
|
||||
expect(data.vm.status).toBe("ready");
|
||||
if (data.vm.status !== "ready") return;
|
||||
expect(data.vm.data.devices.find((d) => d.id === "s1")?.isCurrent).toBe(true);
|
||||
expect(data.vm.data.otherActiveCount).toBe(1);
|
||||
expect(data.csrf).toBe("csrf-1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("security route action", () => {
|
||||
it("revokes a single session by id", async () => {
|
||||
const res = await action({ request: postRequest({ csrf: "csrf-1", intent: "revoke", sessionId: "s2" }), params, context: {} } as never);
|
||||
expect(mocks.validateCSRFToken).toHaveBeenCalled();
|
||||
expect(mocks.revokeUserSession).toHaveBeenCalledWith({ userId: "u1", sessionId: "s2" });
|
||||
expect((res as Response).status).toBe(302);
|
||||
});
|
||||
|
||||
it("revokes all other sessions except the current one", async () => {
|
||||
await action({ request: postRequest({ csrf: "csrf-1", intent: "revoke-all" }), params, context: {} } as never);
|
||||
expect(mocks.revokeAllUserSessionsExcept).toHaveBeenCalledWith({ userId: "u1", sessionId: "s1" });
|
||||
});
|
||||
|
||||
it("marks a session trusted", async () => {
|
||||
await action({ request: postRequest({ csrf: "csrf-1", intent: "trust", sessionId: "s2" }), params, context: {} } as never);
|
||||
expect(mocks.markSessionTrusted).toHaveBeenCalledWith({ userId: "u1", sessionId: "s2" });
|
||||
});
|
||||
|
||||
it("forgets a single trusted device by id", async () => {
|
||||
await action({ request: postRequest({ csrf: "csrf-1", intent: "forget-device", deviceId: "td1" }), params, context: {} } as never);
|
||||
expect(mocks.revokeTrustedDevice).toHaveBeenCalledWith({ userId: "u1", deviceId: "td1" });
|
||||
});
|
||||
|
||||
it("forgets all trusted devices", async () => {
|
||||
await action({ request: postRequest({ csrf: "csrf-1", intent: "forget-all-devices" }), params, context: {} } as never);
|
||||
expect(mocks.revokeAllTrustedDevices).toHaveBeenCalledWith("u1");
|
||||
});
|
||||
});
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
import { redirect, useLoaderData, type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { buildSessionListVM, summarizeUserAgent, type SessionListVM } from "@hivegrid/view-models";
|
||||
import SecuritySessionsScreen from "~/modules/users/components/SecuritySessionsScreen";
|
||||
import { PageBody, PageIntro } from "~/components/screens/shared/PageShell";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getUserInfo, getValidatedServerSession, validateCSRFToken } from "~/utils/session.server";
|
||||
import {
|
||||
listActiveUserSessions,
|
||||
markSessionTrusted,
|
||||
revokeAllUserSessionsExcept,
|
||||
revokeUserSession,
|
||||
} from "~/services/auth/sessionStore.server";
|
||||
import { listTrustedDevices, revokeAllTrustedDevices, revokeTrustedDevice } from "~/utils/auth/mfa/trusted-device.server";
|
||||
|
||||
// R-P2a S4b + D1 — Settings > Sicherheit: Geräteliste + Revoke + "überall abmelden" + Trust-Device.
|
||||
// Der Loader baut das VM serverseitig (M013), die Inline-UI unten ist das minimale Swap-Ziel für
|
||||
// Davids D-P2-Subframe-Screen (über den ui-app-Adapter, M015) — VM und Action-Callbacks bleiben.
|
||||
// D1: zusätzlich die per Login-2FA als vertrauenswürdig markierten Geräte (TrustedDevice) — widerrufbar
|
||||
// einzeln / "alle vergessen" (DoD-Screen "Trust-Device-Revoke").
|
||||
|
||||
type TrustedDeviceVM = { id: string; label: string | null; approxLocation: string | null };
|
||||
type LoaderData = { title: string; csrf: string; vm: SessionListVM; trustedDevices: TrustedDeviceVM[] };
|
||||
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs): Promise<LoaderData> => {
|
||||
await requireAuth({ request, params });
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const sessions = await listActiveUserSessions(userInfo.userId);
|
||||
const current = await getValidatedServerSession(request, userInfo);
|
||||
const vm = buildSessionListVM({
|
||||
sessions: sessions.map((session) => ({
|
||||
id: session.id,
|
||||
lastSeenAt: session.lastSeenAt,
|
||||
userAgent: session.userAgent,
|
||||
deviceLabel: session.deviceLabel,
|
||||
approxLocation: session.approxLocation,
|
||||
trustedAt: session.trustedAt,
|
||||
})),
|
||||
currentSessionId: current?.id ?? null,
|
||||
nowMs: Date.now(),
|
||||
});
|
||||
const trustedDevices: TrustedDeviceVM[] = (await listTrustedDevices(userInfo.userId)).map((device) => ({
|
||||
id: device.id,
|
||||
label: device.deviceLabel ?? (device.userAgent ? summarizeUserAgent(device.userAgent) : null),
|
||||
approxLocation: device.approxLocation,
|
||||
}));
|
||||
return { title: `${t("settings.security.title")} | ${process.env.APP_NAME ?? "HiveGrid"}`, csrf: userInfo.csrf ?? "", vm, trustedDevices };
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
await requireAuth({ request, params });
|
||||
const form = await request.formData();
|
||||
await validateCSRFToken(request, { formData: form });
|
||||
const userInfo = await getUserInfo(request);
|
||||
const userId = userInfo.userId;
|
||||
if (!userId) {
|
||||
throw redirect("/login");
|
||||
}
|
||||
const current = await getValidatedServerSession(request, userInfo);
|
||||
const intent = form.get("intent");
|
||||
let messageKey = "settings.security.toast.updated";
|
||||
const sessionId = String(form.get("sessionId") ?? "");
|
||||
const deviceId = String(form.get("deviceId") ?? "");
|
||||
if (intent === "revoke" && sessionId) {
|
||||
await revokeUserSession({ userId, sessionId });
|
||||
messageKey = "settings.security.toast.sessionRevoked";
|
||||
} else if (intent === "revoke-all") {
|
||||
await revokeAllUserSessionsExcept({ userId, sessionId: current?.id ?? "" });
|
||||
messageKey = "settings.security.toast.otherSessionsRevoked";
|
||||
} else if (intent === "trust" && sessionId) {
|
||||
await markSessionTrusted({ userId, sessionId });
|
||||
messageKey = "settings.security.toast.sessionTrusted";
|
||||
} else if (intent === "forget-device" && deviceId) {
|
||||
await revokeTrustedDevice({ userId, deviceId });
|
||||
messageKey = "settings.security.toast.deviceForgotten";
|
||||
} else if (intent === "forget-all-devices") {
|
||||
await revokeAllTrustedDevices(userId);
|
||||
messageKey = "settings.security.toast.allDevicesForgotten";
|
||||
}
|
||||
return redirect(`${new URL(request.url).pathname}?toast=${encodeURIComponent(messageKey)}`);
|
||||
};
|
||||
|
||||
export default function SecurityRoute() {
|
||||
const { t } = useTranslation();
|
||||
const { csrf, vm, trustedDevices } = useLoaderData<typeof loader>();
|
||||
return (
|
||||
<>
|
||||
{/* AK-SET-01: the Mein-Konto hub owns the page header; PageBody supplies
|
||||
the same 24px page padding the other tabs use. */}
|
||||
<PageBody>
|
||||
<PageIntro uiId="ui.settings.security.intro">{t("settings.security.sessions.subtitle")}</PageIntro>
|
||||
<SecuritySessionsScreen vm={vm} trustedDevices={trustedDevices} csrf={csrf} />
|
||||
</PageBody>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user