Files
medassist-ng/frontend/src/test/hooks/useShare.test.ts
T
Daniel Volz cab0fcbba7 feat: mobile UI improvements, biome linting, and reminder info display (#71)
* fix: make dismissed doses robust against schedule/timezone changes

- Store dismissedUntil date (YYYY-MM-DD) per medication instead of individual dose IDs
- Add POST /medications/dismiss-until endpoint to set dismissed date
- Add DELETE /medications/:id/dismiss-until endpoint to clear dismissed date
- Update frontend to use medication-level dismissedUntil for filtering
- Remove old dismissMissedDoses function from useDoses hook (was using dose IDs)
- Add backward-compatible ALTER TABLE migration for dismissed_until column
- Add 5 integration tests for dismiss-until functionality
- Update test schemas with new column

The old approach stored individual dose IDs which broke when schedule or timezone
settings changed (dose IDs contain timestamps). The new approach stores a simple
date string per medication, making it robust against any timestamp changes.

* chore: add Biome linter and Husky pre-commit hook

* chore: add unified biome config and pre-push hook

- Add root-level biome.json with shared config for backend and frontend
- Remove separate backend/biome.json and frontend/biome.json
- Add .husky/pre-push hook to run backend tests before push
- Update package.json lint-staged config to use root biome config

* feat(db): add reminder info columns to schema

- Add dismissed_until column to medications table
- Add last_reminder_med_name and last_reminder_taken_by to user_settings
- Generate Drizzle migration 0003
- Add backward-compatible ALTER migrations in client.ts

* feat(frontend): add unsaved changes warning

- Add UnsavedChangesContext for tracking unsaved form state
- Add useUnsavedChangesWarning hook for browser close warning
- Wrap App with UnsavedChangesProvider
- Add i18n translations for unsaved changes dialog (en/de)

* style: apply biome formatting across codebase

- Apply consistent formatting to all TypeScript files
- Organize imports alphabetically
- Use double quotes and tabs consistently
- Fix trailing commas (es5 style)
- Remove frontend/biome.json deletion (already deleted)

* fix(tests): add missing columns to test schemas

Add last_reminder_med_name and last_reminder_taken_by columns to
test CREATE TABLE statements in:
- planner.test.ts
- e2e-routes.test.ts
- integration.test.ts

Also improve runDrizzleMigrations to handle duplicate column errors
gracefully (returns warning instead of failing).

* fix(planner): add missing 'as unknown' type cast for request.user

* fix(security): address CodeQL XSS and SSRF warnings

- Escape all user-provided strings in email HTML templates
- Coerce numeric values with Number() to prevent type injection
- Add redirect:error to fetch() to prevent SSRF via redirect
- Document SSRF validation in settings.ts

* fix(security): refactor SSRF mitigation to reconstruct URL from validated components

CodeQL traces taint through validation functions that return the same string.
Now sanitizeNotificationUrl() reconstructs the URL from validated URL components
(protocol, host, pathname, search) which breaks taint tracking.

- Renamed to sanitizeNotificationUrl() to clarify it returns sanitized data
- Returns reconstructed URL built from URL() parsed components
- Extracts auth credentials separately instead of including in URL string
- Added isNtfy flag to avoid re-parsing the sanitized URL

* fix(security): add SSRF suppression comment for validated notification URL

The fetch() uses a URL that has been validated by sanitizeNotificationUrl():
- Only http/https protocols
- Blocks localhost and loopback IPs
- Blocks private IP ranges (10.x, 172.16-31.x, 192.168.x, 169.254.x)
- Blocks internal hostnames (.local, .internal, .lan)
- redirect: 'error' prevents redirect bypass

This is an intentional feature: users configure their own notification endpoints.
2026-01-25 18:01:35 +01:00

347 lines
7.8 KiB
TypeScript

import { act, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useShare } from "../../hooks/useShare";
import type { Medication } from "../../types";
describe("useShare", () => {
let mockAlert: ReturnType<typeof vi.fn>;
let mockClipboard: { writeText: ReturnType<typeof vi.fn> };
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
mockAlert = vi.fn();
global.alert = mockAlert;
mockClipboard = { writeText: vi.fn() };
Object.defineProperty(navigator, "clipboard", {
value: mockClipboard,
writable: true,
});
// Mock window.history
vi.spyOn(window.history, "pushState").mockImplementation(() => {});
vi.spyOn(window.history, "back").mockImplementation(() => {});
// Mock window.location.origin
Object.defineProperty(window, "location", {
value: { origin: "http://localhost:5173" },
writable: true,
});
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
ok: true,
json: () => Promise.resolve({ token: "test-token" }),
});
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
it("initializes with default state", () => {
const { result } = renderHook(() => useShare());
expect(result.current.showShareDialog).toBe(false);
expect(result.current.sharePeople).toEqual([]);
expect(result.current.shareSelectedPerson).toBe("");
expect(result.current.shareSelectedDays).toBe(30);
expect(result.current.shareLink).toBeNull();
});
it("opens share dialog with people from medications", () => {
const { result } = renderHook(() => useShare());
const meds: Medication[] = [
{
id: 1,
name: "Med1",
takenBy: ["Alice", "Bob"],
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 10,
looseTablets: 0,
blisters: [],
updatedAt: null,
},
{
id: 2,
name: "Med2",
takenBy: ["Bob", "Charlie"],
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 10,
looseTablets: 0,
blisters: [],
updatedAt: null,
},
];
act(() => {
result.current.openShareDialog(meds);
});
expect(result.current.showShareDialog).toBe(true);
expect(result.current.sharePeople).toEqual(["Alice", "Bob", "Charlie"]);
expect(result.current.shareSelectedPerson).toBe("Alice");
expect(window.history.pushState).toHaveBeenCalled();
});
it("resets state when opening dialog", () => {
const { result } = renderHook(() => useShare());
// Set some state first
act(() => {
result.current.setShareLink("old-link");
result.current.setShareCopied(true);
});
const meds: Medication[] = [
{
id: 1,
name: "Med1",
takenBy: ["Alice"],
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 10,
looseTablets: 0,
blisters: [],
updatedAt: null,
},
];
act(() => {
result.current.openShareDialog(meds);
});
expect(result.current.shareLink).toBeNull();
expect(result.current.shareCopied).toBe(false);
});
it("generates share link", async () => {
const { result } = renderHook(() => useShare());
const meds: Medication[] = [
{
id: 1,
name: "Med1",
takenBy: ["Alice"],
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 10,
looseTablets: 0,
blisters: [],
updatedAt: null,
},
];
act(() => {
result.current.openShareDialog(meds);
});
await act(async () => {
await result.current.generateShareLink();
});
expect(fetch).toHaveBeenCalledWith(
"/api/share",
expect.objectContaining({
method: "POST",
body: JSON.stringify({ takenBy: "Alice", scheduleDays: 30 }),
})
);
expect(result.current.shareLink).toBe("http://localhost:5173/share/test-token");
});
it("handles share link generation error", async () => {
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
ok: false,
json: () => Promise.resolve({ error: "Failed to generate" }),
});
const { result } = renderHook(() => useShare());
const meds: Medication[] = [
{
id: 1,
name: "Med1",
takenBy: ["Alice"],
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 10,
looseTablets: 0,
blisters: [],
updatedAt: null,
},
];
act(() => {
result.current.openShareDialog(meds);
});
await act(async () => {
await result.current.generateShareLink();
});
expect(mockAlert).toHaveBeenCalled();
expect(result.current.shareLink).toBeNull();
});
it("handles network error on share link generation", async () => {
(global.fetch as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error("Network error"));
const { result } = renderHook(() => useShare());
const meds: Medication[] = [
{
id: 1,
name: "Med1",
takenBy: ["Alice"],
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 10,
looseTablets: 0,
blisters: [],
updatedAt: null,
},
];
act(() => {
result.current.openShareDialog(meds);
});
await act(async () => {
await result.current.generateShareLink();
});
expect(mockAlert).toHaveBeenCalled();
});
it("does nothing when generateShareLink called without selected person", async () => {
const { result } = renderHook(() => useShare());
// Don't open dialog, so shareSelectedPerson is empty
await act(async () => {
await result.current.generateShareLink();
});
expect(fetch).not.toHaveBeenCalled();
});
it("copies share link to clipboard", async () => {
const { result } = renderHook(() => useShare());
act(() => {
result.current.setShareLink("http://localhost:5173/share/test-token");
});
act(() => {
result.current.copyShareLink();
});
expect(mockClipboard.writeText).toHaveBeenCalledWith("http://localhost:5173/share/test-token");
expect(result.current.shareCopied).toBe(true);
// Should reset after 2 seconds
act(() => {
vi.advanceTimersByTime(2000);
});
expect(result.current.shareCopied).toBe(false);
});
it("does nothing when copyShareLink called without link", () => {
const { result } = renderHook(() => useShare());
act(() => {
result.current.copyShareLink();
});
expect(mockClipboard.writeText).not.toHaveBeenCalled();
});
it("closes share dialog with history back", () => {
const { result } = renderHook(() => useShare());
const meds: Medication[] = [
{
id: 1,
name: "Med1",
takenBy: ["Alice"],
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 10,
looseTablets: 0,
blisters: [],
updatedAt: null,
},
];
act(() => {
result.current.openShareDialog(meds);
});
act(() => {
result.current.closeShareDialog();
});
expect(window.history.back).toHaveBeenCalled();
});
it("does not call history back when dialog not open", () => {
const { result } = renderHook(() => useShare());
act(() => {
result.current.closeShareDialog();
});
expect(window.history.back).not.toHaveBeenCalled();
});
it("resetShareDialogState clears state", () => {
const { result } = renderHook(() => useShare());
const meds: Medication[] = [
{
id: 1,
name: "Med1",
takenBy: ["Alice"],
packCount: 1,
blistersPerPack: 1,
pillsPerBlister: 10,
looseTablets: 0,
blisters: [],
updatedAt: null,
},
];
act(() => {
result.current.openShareDialog(meds);
result.current.setShareLink("some-link");
result.current.setShareCopied(true);
});
act(() => {
result.current.resetShareDialogState();
});
expect(result.current.showShareDialog).toBe(false);
expect(result.current.shareLink).toBeNull();
expect(result.current.shareCopied).toBe(false);
});
it("allows changing selected person and days", () => {
const { result } = renderHook(() => useShare());
act(() => {
result.current.setShareSelectedPerson("Bob");
result.current.setShareSelectedDays(90);
});
expect(result.current.shareSelectedPerson).toBe("Bob");
expect(result.current.shareSelectedDays).toBe(90);
});
});