mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 07:42:23 +00:00
merge: integrate the v1.23 sessions and login-alert wave
This commit is contained in:
commit
4c4231838c
38 files changed
+2590
-23
No files matched your search
@@ -0,0 +1,117 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// Mirror require-fresh-mfa.test.ts mocking so the api-handler module loads
|
||||
// without a live DB / request scope.
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
session: { findUnique: vi.fn() },
|
||||
apiToken: { findUnique: vi.fn(), update: vi.fn() },
|
||||
user: { findUnique: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
vi.mock("@/lib/auth/hmac", () => ({ hashToken: vi.fn(() => "hash") }));
|
||||
vi.mock("@/lib/auth/audit", () => ({
|
||||
auditLog: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
||||
|
||||
const headersGet = vi.fn<(name: string) => string | null>();
|
||||
vi.mock("next/headers", () => ({
|
||||
headers: vi.fn(async () => ({ get: headersGet })),
|
||||
cookies: vi.fn(async () => ({
|
||||
get: () => undefined,
|
||||
set: () => {},
|
||||
delete: () => {},
|
||||
})),
|
||||
}));
|
||||
|
||||
import {
|
||||
requireFreshMfaIfEnrolled,
|
||||
StepUpRequiredError,
|
||||
HttpError,
|
||||
MFA_STEP_UP_MAX_AGE_SECONDS,
|
||||
} from "../api-handler";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { headers } from "next/headers";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
|
||||
const MFA_USER = {
|
||||
id: "user-1",
|
||||
role: "USER" as const,
|
||||
username: "u",
|
||||
totpConfirmedAt: new Date("2020-01-01"),
|
||||
};
|
||||
const PLAIN_USER = { ...MFA_USER, totpConfirmedAt: null };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
headersGet.mockReturnValue(null);
|
||||
// resetAllMocks wipes the inline mock factory implementation too; restore
|
||||
// the headers() wrapper so requireAuth's Bearer branch can read the header.
|
||||
vi.mocked(headers).mockImplementation(
|
||||
async () => ({ get: headersGet }) as never,
|
||||
);
|
||||
// resetAllMocks wipes the factory mockResolvedValue; auditLog is awaited
|
||||
// via `.catch(...)` in the Bearer path, so it must return a thenable.
|
||||
vi.mocked(auditLog).mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
function mockCookieSession(user: unknown) {
|
||||
vi.mocked(getSession).mockResolvedValue({
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 1e6) },
|
||||
user,
|
||||
} as never);
|
||||
}
|
||||
|
||||
describe("requireFreshMfaIfEnrolled", () => {
|
||||
it("passes a non-MFA user straight through without a freshness read", async () => {
|
||||
mockCookieSession(PLAIN_USER);
|
||||
const ctx = await requireFreshMfaIfEnrolled(MFA_STEP_UP_MAX_AGE_SECONDS);
|
||||
expect(ctx.user.id).toBe("user-1");
|
||||
expect(prisma.session.findUnique).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("passes an MFA user with a fresh verification", async () => {
|
||||
mockCookieSession(MFA_USER);
|
||||
vi.mocked(prisma.session.findUnique).mockResolvedValue({
|
||||
mfaVerifiedAt: new Date(Date.now() - 60_000),
|
||||
} as never);
|
||||
const ctx = await requireFreshMfaIfEnrolled(MFA_STEP_UP_MAX_AGE_SECONDS);
|
||||
expect(ctx.user.id).toBe("user-1");
|
||||
});
|
||||
|
||||
it("blocks an MFA user without a fresh verification", async () => {
|
||||
mockCookieSession(MFA_USER);
|
||||
vi.mocked(prisma.session.findUnique).mockResolvedValue({
|
||||
mfaVerifiedAt: null,
|
||||
} as never);
|
||||
await expect(
|
||||
requireFreshMfaIfEnrolled(MFA_STEP_UP_MAX_AGE_SECONDS),
|
||||
).rejects.toBeInstanceOf(StepUpRequiredError);
|
||||
});
|
||||
|
||||
it("a Bearer token can never satisfy step-up for an MFA-enrolled account", async () => {
|
||||
// requireAuth resolves the Bearer caller (no cookie), but the step-up read
|
||||
// is cookie-only — getSession returns null inside requireFreshMfa.
|
||||
vi.mocked(getSession).mockResolvedValue(null as never);
|
||||
headersGet.mockImplementation((n) =>
|
||||
n.toLowerCase() === "authorization" ? "Bearer hlk_xyz" : null,
|
||||
);
|
||||
vi.mocked(prisma.apiToken.findUnique).mockResolvedValue({
|
||||
id: "tok-1",
|
||||
userId: "user-1",
|
||||
permissions: ["*"],
|
||||
revoked: false,
|
||||
expiresAt: null,
|
||||
} as never);
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue(MFA_USER as never);
|
||||
vi.mocked(prisma.apiToken.update).mockResolvedValue({} as never);
|
||||
|
||||
await expect(
|
||||
requireFreshMfaIfEnrolled(MFA_STEP_UP_MAX_AGE_SECONDS),
|
||||
).rejects.toBeInstanceOf(HttpError);
|
||||
});
|
||||
});
|
||||
@@ -557,6 +557,34 @@ export async function requireFreshMfa(
|
||||
return { ...sessionData, mfaVerifiedAt: verifiedAt };
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.23 — conditional step-up for destructive account actions.
|
||||
*
|
||||
* Resolves the caller with the standard `requireAuth()` (cookie OR Bearer).
|
||||
* For an account WITHOUT a confirmed second factor the caller passes straight
|
||||
* through — a single-factor user is intentionally unaffected, so account
|
||||
* deletion / data reset keeps its existing typed-confirmation-only contract.
|
||||
* For an account WITH MFA active (`totpConfirmedAt` set) it additionally runs
|
||||
* `requireFreshMfa`, which is cookie-only by construction: an MFA-enrolled
|
||||
* account's Bearer transport carries no `mfaVerifiedAt` and therefore cannot
|
||||
* satisfy step-up, surfacing `StepUpRequiredError` (401,
|
||||
* `errorCode: "auth.stepup.required"`) so the UI launches a re-verification.
|
||||
*
|
||||
* Gating only the MFA-enrolled cohort keeps the boundary structural: a
|
||||
* hijacked live cookie session for an MFA user cannot nuke the record without
|
||||
* a fresh factor, while users who never opted into MFA are not forced through
|
||||
* a flow they have no way to complete.
|
||||
*/
|
||||
export async function requireFreshMfaIfEnrolled(
|
||||
maxAgeSeconds: number,
|
||||
): Promise<AuthContext> {
|
||||
const auth = await requireAuth();
|
||||
if (auth.user.totpConfirmedAt) {
|
||||
await requireFreshMfa(maxAgeSeconds);
|
||||
}
|
||||
return auth;
|
||||
}
|
||||
|
||||
/**
|
||||
* Report unhandled errors to GlitchTip (fire-and-forget).
|
||||
* Uses dynamic import to avoid circular dependencies and startup cost.
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
coarseDeviceLabel,
|
||||
normaliseUserAgent,
|
||||
coarseLocationSignal,
|
||||
computeDeviceHash,
|
||||
maskIp,
|
||||
} from "../device-fingerprint";
|
||||
|
||||
const FIREFOX_MAC =
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:120.0) Gecko/20100101 Firefox/120.0";
|
||||
const FIREFOX_MAC_MINOR =
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:121.0) Gecko/20100101 Firefox/121.0";
|
||||
const CHROME_WIN =
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36";
|
||||
|
||||
describe("coarseDeviceLabel", () => {
|
||||
it("reduces a UA to family + platform", () => {
|
||||
expect(coarseDeviceLabel(FIREFOX_MAC)).toBe("Firefox on macOS");
|
||||
expect(coarseDeviceLabel(CHROME_WIN)).toBe("Chrome on Windows");
|
||||
});
|
||||
it("handles a missing UA", () => {
|
||||
expect(coarseDeviceLabel(null)).toBe("Unknown device");
|
||||
expect(coarseDeviceLabel("")).toBe("Unknown device");
|
||||
});
|
||||
});
|
||||
|
||||
describe("coarseLocationSignal", () => {
|
||||
it("reduces a city string to its country token", () => {
|
||||
expect(coarseLocationSignal("Berlin, DE")).toBe("DE");
|
||||
});
|
||||
it("returns empty for no location", () => {
|
||||
expect(coarseLocationSignal(null)).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeDeviceHash", () => {
|
||||
it("is deterministic and a hex SHA-256 (no raw UA/IP leak)", () => {
|
||||
const h = computeDeviceHash({
|
||||
userId: "u1",
|
||||
userAgent: FIREFOX_MAC,
|
||||
coarseSignal: "DE",
|
||||
});
|
||||
expect(h).toMatch(/^[0-9a-f]{64}$/);
|
||||
// The hash must not embed the raw UA.
|
||||
expect(h).not.toContain("Firefox");
|
||||
expect(h).not.toContain("Mozilla");
|
||||
expect(
|
||||
computeDeviceHash({
|
||||
userId: "u1",
|
||||
userAgent: FIREFOX_MAC,
|
||||
coarseSignal: "DE",
|
||||
}),
|
||||
).toBe(h);
|
||||
});
|
||||
|
||||
it("is invariant to a minor browser-version bump (no false new-device)", () => {
|
||||
const a = computeDeviceHash({
|
||||
userId: "u1",
|
||||
userAgent: FIREFOX_MAC,
|
||||
coarseSignal: "DE",
|
||||
});
|
||||
const b = computeDeviceHash({
|
||||
userId: "u1",
|
||||
userAgent: FIREFOX_MAC_MINOR,
|
||||
coarseSignal: "DE",
|
||||
});
|
||||
expect(a).toBe(b);
|
||||
});
|
||||
|
||||
it("is salted per user — same browser, different account ⇒ different hash", () => {
|
||||
const a = computeDeviceHash({
|
||||
userId: "u1",
|
||||
userAgent: FIREFOX_MAC,
|
||||
coarseSignal: "DE",
|
||||
});
|
||||
const b = computeDeviceHash({
|
||||
userId: "u2",
|
||||
userAgent: FIREFOX_MAC,
|
||||
coarseSignal: "DE",
|
||||
});
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
|
||||
it("treats a different country as a new device", () => {
|
||||
const a = computeDeviceHash({
|
||||
userId: "u1",
|
||||
userAgent: FIREFOX_MAC,
|
||||
coarseSignal: "DE",
|
||||
});
|
||||
const b = computeDeviceHash({
|
||||
userId: "u1",
|
||||
userAgent: FIREFOX_MAC,
|
||||
coarseSignal: "US",
|
||||
});
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normaliseUserAgent", () => {
|
||||
it("matches the coarse label so the hash input is stable", () => {
|
||||
expect(normaliseUserAgent(FIREFOX_MAC)).toBe("Firefox on macOS");
|
||||
});
|
||||
});
|
||||
|
||||
describe("maskIp", () => {
|
||||
it("masks the host portion of an IPv4", () => {
|
||||
expect(maskIp("203.0.113.42")).toBe("203.0.x.x");
|
||||
});
|
||||
it("masks an IPv6 down to two hextets", () => {
|
||||
expect(maskIp("2001:db8:1234:5678::1")).toBe("2001:db8::");
|
||||
});
|
||||
it("returns null for a blank IP", () => {
|
||||
expect(maskIp(null)).toBeNull();
|
||||
expect(maskIp("")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
vi.mock("@/lib/safe-fetch", () => ({ safeFetch: vi.fn() }));
|
||||
vi.mock("@/lib/logging/context", () => ({ getEvent: () => null }));
|
||||
|
||||
import { checkPasswordBreach } from "../hibp";
|
||||
import { safeFetch } from "@/lib/safe-fetch";
|
||||
|
||||
const PASSWORD = "correct horse battery staple";
|
||||
const DIGEST = createHash("sha1")
|
||||
.update(PASSWORD, "utf8")
|
||||
.digest("hex")
|
||||
.toUpperCase();
|
||||
const PREFIX = DIGEST.slice(0, 5);
|
||||
const SUFFIX = DIGEST.slice(5);
|
||||
|
||||
function textResponse(body: string, ok = true): Response {
|
||||
return {
|
||||
ok,
|
||||
text: async () => body,
|
||||
} as unknown as Response;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
describe("checkPasswordBreach — k-anonymity", () => {
|
||||
it("sends ONLY the 5-char prefix and never the full hash or suffix", async () => {
|
||||
vi.mocked(safeFetch).mockResolvedValue(
|
||||
textResponse(`${SUFFIX}:42\nFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:9`),
|
||||
);
|
||||
|
||||
await checkPasswordBreach(PASSWORD);
|
||||
|
||||
const url = vi.mocked(safeFetch).mock.calls[0][0] as string;
|
||||
expect(url).toBe(`https://api.pwnedpasswords.com/range/${PREFIX}`);
|
||||
// The suffix and full digest must never leave the process.
|
||||
expect(url).not.toContain(SUFFIX);
|
||||
expect(url).not.toContain(DIGEST);
|
||||
// Only 5 hex chars after the range/ segment.
|
||||
const sent = url.split("/range/")[1];
|
||||
expect(sent).toHaveLength(5);
|
||||
expect(sent).toMatch(/^[0-9A-F]{5}$/);
|
||||
|
||||
// Add-Padding header is set so the response size doesn't leak the bucket.
|
||||
const init = vi.mocked(safeFetch).mock.calls[0][1] as RequestInit;
|
||||
expect((init.headers as Record<string, string>)["Add-Padding"]).toBe(
|
||||
"true",
|
||||
);
|
||||
// requirePublicHost is pinned.
|
||||
const opts = vi.mocked(safeFetch).mock.calls[0][2] as {
|
||||
requirePublicHost?: boolean;
|
||||
};
|
||||
expect(opts.requirePublicHost).toBe(true);
|
||||
});
|
||||
|
||||
it("flags a breached password from a matching suffix", async () => {
|
||||
vi.mocked(safeFetch).mockResolvedValue(textResponse(`${SUFFIX}:1337`));
|
||||
const res = await checkPasswordBreach(PASSWORD);
|
||||
expect(res).toEqual({ breached: true, count: 1337 });
|
||||
});
|
||||
|
||||
it("matches the suffix case-insensitively", async () => {
|
||||
vi.mocked(safeFetch).mockResolvedValue(
|
||||
textResponse(`${SUFFIX.toLowerCase()}:5`),
|
||||
);
|
||||
const res = await checkPasswordBreach(PASSWORD);
|
||||
expect(res?.breached).toBe(true);
|
||||
});
|
||||
|
||||
it("reports not-breached when the suffix is absent", async () => {
|
||||
vi.mocked(safeFetch).mockResolvedValue(
|
||||
textResponse("0000000000000000000000000000000000A:3"),
|
||||
);
|
||||
const res = await checkPasswordBreach(PASSWORD);
|
||||
expect(res).toEqual({ breached: false, count: 0 });
|
||||
});
|
||||
|
||||
it("fails open (null) on a non-200 response", async () => {
|
||||
vi.mocked(safeFetch).mockResolvedValue(textResponse("", false));
|
||||
expect(await checkPasswordBreach(PASSWORD)).toBeNull();
|
||||
});
|
||||
|
||||
it("fails open (null) when the request throws (HIBP down)", async () => {
|
||||
vi.mocked(safeFetch).mockRejectedValue(new Error("network"));
|
||||
expect(await checkPasswordBreach(PASSWORD)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
userKnownDevice: {
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
create: vi.fn(),
|
||||
},
|
||||
user: { findUnique: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/geo", () => ({
|
||||
lookupIpLocation: vi.fn(async () => "Berlin, DE"),
|
||||
lookupIpAsn: vi.fn(() => null),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/notifications/dispatcher", () => ({
|
||||
dispatchNotification: vi.fn().mockResolvedValue({ dispatched: true }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/audit", () => ({
|
||||
auditLog: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/i18n/server-translator", () => ({
|
||||
getServerTranslator: () => ({ t: (k: string) => k }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({ getEvent: () => null }));
|
||||
|
||||
import { recordSignInDevice } from "../login-alert";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { dispatchNotification } from "@/lib/notifications/dispatcher";
|
||||
|
||||
const UA =
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:120.0) Gecko/20100101 Firefox/120.0";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue({
|
||||
locale: "en",
|
||||
} as never);
|
||||
});
|
||||
|
||||
describe("recordSignInDevice — new-device dedupe", () => {
|
||||
it("first sighting records the device AND fires one alert", async () => {
|
||||
vi.mocked(prisma.userKnownDevice.findUnique).mockResolvedValue(null);
|
||||
vi.mocked(prisma.userKnownDevice.create).mockResolvedValue({} as never);
|
||||
|
||||
const res = await recordSignInDevice({
|
||||
userId: "u1",
|
||||
ip: "203.0.113.9",
|
||||
userAgent: UA,
|
||||
});
|
||||
|
||||
expect(res).toEqual({ known: false, alerted: true });
|
||||
expect(prisma.userKnownDevice.create).toHaveBeenCalledTimes(1);
|
||||
expect(dispatchNotification).toHaveBeenCalledTimes(1);
|
||||
const payload = vi.mocked(dispatchNotification).mock.calls[0][0];
|
||||
expect(payload.eventType).toBe("SECURITY_ALERT");
|
||||
expect(payload.userId).toBe("u1");
|
||||
});
|
||||
|
||||
it("second sighting of the same device is silent (no alert)", async () => {
|
||||
vi.mocked(prisma.userKnownDevice.findUnique).mockResolvedValue({
|
||||
id: "kd-1",
|
||||
} as never);
|
||||
vi.mocked(prisma.userKnownDevice.update).mockResolvedValue({} as never);
|
||||
|
||||
const res = await recordSignInDevice({
|
||||
userId: "u1",
|
||||
ip: "203.0.113.9",
|
||||
userAgent: UA,
|
||||
});
|
||||
|
||||
expect(res).toEqual({ known: true, alerted: false });
|
||||
expect(prisma.userKnownDevice.update).toHaveBeenCalledTimes(1);
|
||||
expect(prisma.userKnownDevice.create).not.toHaveBeenCalled();
|
||||
expect(dispatchNotification).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("records silently when alertOnNew is false (registration)", async () => {
|
||||
vi.mocked(prisma.userKnownDevice.findUnique).mockResolvedValue(null);
|
||||
vi.mocked(prisma.userKnownDevice.create).mockResolvedValue({} as never);
|
||||
|
||||
const res = await recordSignInDevice({
|
||||
userId: "u1",
|
||||
ip: "203.0.113.9",
|
||||
userAgent: UA,
|
||||
alertOnNew: false,
|
||||
});
|
||||
|
||||
expect(res).toEqual({ known: false, alerted: false });
|
||||
expect(prisma.userKnownDevice.create).toHaveBeenCalledTimes(1);
|
||||
expect(dispatchNotification).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("a unique-index race on create does not double-alert", async () => {
|
||||
vi.mocked(prisma.userKnownDevice.findUnique).mockResolvedValue(null);
|
||||
vi.mocked(prisma.userKnownDevice.create).mockRejectedValue(
|
||||
new Error("unique violation"),
|
||||
);
|
||||
|
||||
const res = await recordSignInDevice({
|
||||
userId: "u1",
|
||||
ip: "203.0.113.9",
|
||||
userAgent: UA,
|
||||
});
|
||||
|
||||
expect(res).toEqual({ known: true, alerted: false });
|
||||
expect(dispatchNotification).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("never persists the raw User-Agent — only the salted hash + coarse label", async () => {
|
||||
vi.mocked(prisma.userKnownDevice.findUnique).mockResolvedValue(null);
|
||||
vi.mocked(prisma.userKnownDevice.create).mockResolvedValue({} as never);
|
||||
|
||||
await recordSignInDevice({
|
||||
userId: "u1",
|
||||
ip: "203.0.113.9",
|
||||
userAgent: UA,
|
||||
});
|
||||
|
||||
const data = vi.mocked(prisma.userKnownDevice.create).mock.calls[0][0].data;
|
||||
expect(data.deviceHash).toMatch(/^[0-9a-f]{64}$/);
|
||||
expect(JSON.stringify(data)).not.toContain("Mozilla");
|
||||
expect(JSON.stringify(data)).not.toContain("203.0.113.9");
|
||||
// The coarse label is the family + platform descriptor.
|
||||
expect(data.label).toContain("Firefox on macOS");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
matchesSecurityActivity,
|
||||
securityActivityWhere,
|
||||
} from "../security-activity";
|
||||
|
||||
describe("matchesSecurityActivity", () => {
|
||||
it("includes every auth.* event", () => {
|
||||
for (const a of [
|
||||
"auth.login.password",
|
||||
"auth.login.failed",
|
||||
"auth.login.new_device",
|
||||
"auth.mfa.verify",
|
||||
"auth.password.change",
|
||||
"auth.session.revoke",
|
||||
"auth.session.revoke_others",
|
||||
"auth.token.autoissue.native",
|
||||
"auth.bearer.success",
|
||||
"auth.register",
|
||||
]) {
|
||||
expect(matchesSecurityActivity(a)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("includes export actions", () => {
|
||||
for (const a of [
|
||||
"export.download",
|
||||
"health-record.export",
|
||||
"user.export.full-backup",
|
||||
"user.export.measurements",
|
||||
]) {
|
||||
expect(matchesSecurityActivity(a)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("includes the erasure actions", () => {
|
||||
expect(matchesSecurityActivity("user.account.delete")).toBe(true);
|
||||
expect(matchesSecurityActivity("user.data.clear")).toBe(true);
|
||||
});
|
||||
|
||||
it("excludes unrelated audit actions", () => {
|
||||
for (const a of [
|
||||
"measurement.create",
|
||||
"medication.intake.bulk",
|
||||
"coach.budget.exceeded",
|
||||
"withings.sync.ok",
|
||||
"consent.ai.web",
|
||||
]) {
|
||||
expect(matchesSecurityActivity(a)).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("securityActivityWhere", () => {
|
||||
it("scopes by userId and mirrors the predicate clauses", () => {
|
||||
const where = securityActivityWhere("user-1");
|
||||
expect(where.userId).toBe("user-1");
|
||||
expect(where.OR).toEqual([
|
||||
{ action: { startsWith: "auth." } },
|
||||
{ action: { contains: "export" } },
|
||||
{ action: { in: ["user.account.delete", "user.data.clear"] } },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* v1.23 — coarse device fingerprinting shared by the active-session list and
|
||||
* the new-device sign-in alert.
|
||||
*
|
||||
* The fingerprint that backs login-alert dedupe is deliberately COARSE and
|
||||
* one-way: a SHA-256 over `userId | normalised-User-Agent | coarse-signal`.
|
||||
* The raw User-Agent and IP never leave this module into storage — only the
|
||||
* salted hash (userId-salted, so the same browser on two accounts hashes
|
||||
* differently) and a coarse human-readable label. A minor-version UA bump or a
|
||||
* differently-formatted IP must NOT mint a "new device", so the UA is reduced
|
||||
* to its family + platform and the geo signal to a country/ASN granularity.
|
||||
*/
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
/**
|
||||
* Reduce a User-Agent to a stable family + platform descriptor, e.g.
|
||||
* "Firefox on macOS". Minor versions, build numbers, and engine noise are
|
||||
* dropped so a routine browser update does not register as a new device.
|
||||
* Returns "Unknown device" when the UA is missing or unrecognised.
|
||||
*/
|
||||
export function coarseDeviceLabel(
|
||||
userAgent: string | null | undefined,
|
||||
): string {
|
||||
const ua = (userAgent ?? "").trim();
|
||||
if (!ua) return "Unknown device";
|
||||
|
||||
const browser = /\bEdg(?:e|A|iOS)?\//.test(ua)
|
||||
? "Edge"
|
||||
: /\bOPR\/|\bOpera\b/.test(ua)
|
||||
? "Opera"
|
||||
: /\bFirefox\//.test(ua)
|
||||
? "Firefox"
|
||||
: /\bChrome\//.test(ua) && !/\bChromium\//.test(ua)
|
||||
? "Chrome"
|
||||
: /\bChromium\//.test(ua)
|
||||
? "Chromium"
|
||||
: /\bSafari\//.test(ua) && /\bVersion\//.test(ua)
|
||||
? "Safari"
|
||||
: /HealthLog-iOS/i.test(ua)
|
||||
? "HealthLog iOS app"
|
||||
: null;
|
||||
|
||||
const platform = /\bWindows NT\b/.test(ua)
|
||||
? "Windows"
|
||||
: /\b(iPhone|iPad|iPod)\b/.test(ua)
|
||||
? "iOS"
|
||||
: /\bMac OS X\b|\bMacintosh\b/.test(ua)
|
||||
? "macOS"
|
||||
: /\bAndroid\b/.test(ua)
|
||||
? "Android"
|
||||
: /\bLinux\b/.test(ua)
|
||||
? "Linux"
|
||||
: null;
|
||||
|
||||
if (browser && platform) return `${browser} on ${platform}`;
|
||||
if (browser) return browser;
|
||||
if (platform) return platform;
|
||||
return "Unknown device";
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduce a User-Agent to the stable string fed into the dedupe hash. Uses the
|
||||
* coarse label so the hash is invariant to minor-version churn.
|
||||
*/
|
||||
export function normaliseUserAgent(
|
||||
userAgent: string | null | undefined,
|
||||
): string {
|
||||
return coarseDeviceLabel(userAgent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduce a resolved geo string to a coarse country-level signal, e.g.
|
||||
* "Berlin, DE" → "DE". Falls back to the whole string when there is no
|
||||
* trailing country token, and to "" when no location resolved. Kept coarse so
|
||||
* a user moving across a city/region does not register as a new device while a
|
||||
* cross-country sign-in still does.
|
||||
*/
|
||||
export function coarseLocationSignal(
|
||||
location: string | null | undefined,
|
||||
): string {
|
||||
const loc = (location ?? "").trim();
|
||||
if (!loc) return "";
|
||||
const parts = loc.split(",").map((p) => p.trim());
|
||||
return parts[parts.length - 1] || loc;
|
||||
}
|
||||
|
||||
/**
|
||||
* One-way, per-user device fingerprint. The userId is part of the digest so
|
||||
* the same browser on two accounts yields two unrelated hashes (no
|
||||
* cross-account correlation), and the raw inputs are never recoverable.
|
||||
*/
|
||||
export function computeDeviceHash(params: {
|
||||
userId: string;
|
||||
userAgent: string | null | undefined;
|
||||
coarseSignal: string;
|
||||
}): string {
|
||||
const material = `${params.userId}|${normaliseUserAgent(params.userAgent)}|${params.coarseSignal}`;
|
||||
return createHash("sha256").update(material).digest("hex");
|
||||
}
|
||||
|
||||
/**
|
||||
* Mask an IP for the user-facing security surfaces: keep enough to recognise
|
||||
* the network, drop the host. IPv4 → first two octets; IPv6 → first two
|
||||
* hextets. Returns null for a null/blank input.
|
||||
*/
|
||||
export function maskIp(ip: string | null | undefined): string | null {
|
||||
const raw = (ip ?? "").trim();
|
||||
if (!raw) return null;
|
||||
if (raw.includes(":")) {
|
||||
const groups = raw.split(":").filter((g) => g.length > 0);
|
||||
return `${groups.slice(0, 2).join(":")}::`;
|
||||
}
|
||||
const octets = raw.split(".");
|
||||
if (octets.length === 4) {
|
||||
return `${octets[0]}.${octets[1]}.x.x`;
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* v1.23 — HaveIBeenPwned password-breach check via the k-anonymity range API.
|
||||
*
|
||||
* Privacy contract (the whole point of k-anonymity): the password is SHA-1'd
|
||||
* locally and ONLY the first 5 hex characters of the uppercase digest leave the
|
||||
* server. The remaining 35-character suffix is matched against the response
|
||||
* locally; the full hash and the password itself never cross the network. The
|
||||
* request carries `Add-Padding: true` so the response size does not leak which
|
||||
* prefix bucket was queried.
|
||||
*
|
||||
* Resilience: any failure (egress disabled, HIBP down, timeout, non-200,
|
||||
* malformed body) returns `null` — "unknown". Callers treat `null` as
|
||||
* fail-open and never block on it; only a confirmed breach (`breached: true`)
|
||||
* is actionable. The check is therefore safe to run inline at password-set
|
||||
* time without making HIBP a hard dependency of account management.
|
||||
*/
|
||||
import { createHash } from "node:crypto";
|
||||
import { safeFetch } from "@/lib/safe-fetch";
|
||||
import { getEvent } from "@/lib/logging/context";
|
||||
|
||||
const HIBP_RANGE_URL = "https://api.pwnedpasswords.com/range/";
|
||||
|
||||
export interface BreachCheckResult {
|
||||
breached: boolean;
|
||||
/** Number of times the password appears in the corpus (0 when not found). */
|
||||
count: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the breach status of `password`, or `null` when the check could not
|
||||
* be completed (fail-open). Never throws.
|
||||
*/
|
||||
export async function checkPasswordBreach(
|
||||
password: string,
|
||||
): Promise<BreachCheckResult | null> {
|
||||
try {
|
||||
const digest = createHash("sha1")
|
||||
.update(password, "utf8")
|
||||
.digest("hex")
|
||||
.toUpperCase();
|
||||
const prefix = digest.slice(0, 5);
|
||||
const suffix = digest.slice(5);
|
||||
|
||||
const res = await safeFetch(
|
||||
`${HIBP_RANGE_URL}${prefix}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: { "Add-Padding": "true" },
|
||||
signal: AbortSignal.timeout(4000),
|
||||
},
|
||||
// The host is a fixed, app-controlled public endpoint, but pin the
|
||||
// public-host / DNS-rebinding guard anyway — it is a hard egress, and the
|
||||
// SSRF floor is cheap.
|
||||
{ requirePublicHost: true },
|
||||
);
|
||||
|
||||
if (!res.ok) return null;
|
||||
|
||||
const body = await res.text();
|
||||
// Each line: "<35-hex-suffix>:<count>". Compare case-insensitively.
|
||||
for (const line of body.split("\n")) {
|
||||
const sep = line.indexOf(":");
|
||||
if (sep < 0) continue;
|
||||
const lineSuffix = line.slice(0, sep).trim().toUpperCase();
|
||||
if (lineSuffix === suffix) {
|
||||
const count = parseInt(line.slice(sep + 1).trim(), 10);
|
||||
return { breached: true, count: Number.isFinite(count) ? count : 1 };
|
||||
}
|
||||
}
|
||||
return { breached: false, count: 0 };
|
||||
} catch (err) {
|
||||
getEvent()?.addWarning(
|
||||
`HIBP breach check unavailable (fail-open): ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* v1.23 — new-device / new-location sign-in alert.
|
||||
*
|
||||
* Called on every completed sign-in (password, MFA-verify, passkey). Computes
|
||||
* a coarse, one-way device fingerprint (see `device-fingerprint.ts`) and:
|
||||
* - first sighting of the fingerprint → record it AND fire one notification
|
||||
* through the dispatcher cascade (respecting the user's per-channel prefs),
|
||||
* - any later sighting → bump `lastSeenAt` only, stay silent (dedupe).
|
||||
*
|
||||
* The whole thing is best-effort and is invoked fire-and-forget from the login
|
||||
* paths: a failure here must never block or fail a sign-in. The raw IP/UA are
|
||||
* never persisted — only the salted hash + a coarse label (and the audit row,
|
||||
* which already records IP/geo for `auth.*` events).
|
||||
*/
|
||||
import { prisma } from "@/lib/db";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { lookupIpLocation, lookupIpAsn } from "@/lib/geo";
|
||||
import {
|
||||
coarseDeviceLabel,
|
||||
coarseLocationSignal,
|
||||
computeDeviceHash,
|
||||
} from "@/lib/auth/device-fingerprint";
|
||||
import { dispatchNotification } from "@/lib/notifications/dispatcher";
|
||||
import { getServerTranslator } from "@/lib/i18n/server-translator";
|
||||
import { defaultLocale, type Locale } from "@/lib/i18n/config";
|
||||
import { getEvent } from "@/lib/logging/context";
|
||||
|
||||
function isLocale(value: string | null | undefined): value is Locale {
|
||||
return (
|
||||
value === "de" ||
|
||||
value === "en" ||
|
||||
value === "fr" ||
|
||||
value === "es" ||
|
||||
value === "it" ||
|
||||
value === "pl"
|
||||
);
|
||||
}
|
||||
|
||||
export interface RecordSignInResult {
|
||||
known: boolean;
|
||||
alerted: boolean;
|
||||
}
|
||||
|
||||
export async function recordSignInDevice(params: {
|
||||
userId: string;
|
||||
ip: string | null;
|
||||
userAgent: string | null;
|
||||
/**
|
||||
* When false the device is recorded silently with no notification — used by
|
||||
* account registration, where the very first device should not trigger a
|
||||
* "new device" alert the moment the account is created.
|
||||
*/
|
||||
alertOnNew?: boolean;
|
||||
}): Promise<RecordSignInResult> {
|
||||
const { userId, ip, userAgent } = params;
|
||||
const alertOnNew = params.alertOnNew ?? true;
|
||||
|
||||
try {
|
||||
// Coarse geo signal — best-effort. The location resolver is online-first
|
||||
// with its own timeout; a miss falls back to the ASN number so a device
|
||||
// on the same network still dedupes even without a city.
|
||||
let location: string | null = null;
|
||||
try {
|
||||
location = await lookupIpLocation(ip);
|
||||
} catch {
|
||||
location = null;
|
||||
}
|
||||
const coarseSignal =
|
||||
coarseLocationSignal(location) || lookupIpAsn(ip)?.asn?.toString() || "";
|
||||
|
||||
const deviceHash = computeDeviceHash({ userId, userAgent, coarseSignal });
|
||||
const deviceLabel = coarseDeviceLabel(userAgent);
|
||||
const storedLabel = location ? `${deviceLabel} — ${location}` : deviceLabel;
|
||||
|
||||
const existing = await prisma.userKnownDevice.findUnique({
|
||||
where: { userId_deviceHash: { userId, deviceHash } },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
await prisma.userKnownDevice
|
||||
.update({
|
||||
where: { id: existing.id },
|
||||
data: { lastSeenAt: new Date() },
|
||||
})
|
||||
.catch(() => {});
|
||||
return { known: true, alerted: false };
|
||||
}
|
||||
|
||||
// First sighting. Insert; if a concurrent first-login races us to the
|
||||
// unique (userId, deviceHash) index, swallow it and treat as already known
|
||||
// so we never double-alert.
|
||||
try {
|
||||
await prisma.userKnownDevice.create({
|
||||
data: { userId, deviceHash, label: storedLabel },
|
||||
});
|
||||
} catch {
|
||||
return { known: true, alerted: false };
|
||||
}
|
||||
|
||||
if (!alertOnNew) return { known: false, alerted: false };
|
||||
|
||||
await auditLog("auth.login.new_device", {
|
||||
userId,
|
||||
ipAddress: ip,
|
||||
details: { device: deviceLabel },
|
||||
});
|
||||
|
||||
// Localise against the recipient's own locale, then fan out through the
|
||||
// dispatcher (which applies the user's per-channel SECURITY_ALERT prefs).
|
||||
let locale: Locale = defaultLocale;
|
||||
try {
|
||||
const row = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { locale: true },
|
||||
});
|
||||
if (isLocale(row?.locale)) locale = row.locale;
|
||||
} catch {
|
||||
locale = defaultLocale;
|
||||
}
|
||||
const { t } = getServerTranslator(locale);
|
||||
const locationText =
|
||||
location ?? t("notifications.security.unknownLocation");
|
||||
|
||||
await dispatchNotification({
|
||||
eventType: "SECURITY_ALERT",
|
||||
userId,
|
||||
title: t("notifications.security.newDeviceTitle"),
|
||||
message: t("notifications.security.newDeviceBody", {
|
||||
device: deviceLabel,
|
||||
location: locationText,
|
||||
}),
|
||||
urgent: true,
|
||||
});
|
||||
|
||||
return { known: false, alerted: true };
|
||||
} catch (err) {
|
||||
getEvent()?.addWarning(
|
||||
`recordSignInDevice failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
return { known: false, alerted: false };
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
isCookielessNativeCaller,
|
||||
} from "@/lib/auth/native-client";
|
||||
import { issueAccessAndRefresh } from "@/lib/auth/refresh-token";
|
||||
import { recordSignInDevice } from "@/lib/auth/login-alert";
|
||||
import type { User } from "@/generated/prisma/client";
|
||||
|
||||
export interface FinishLoginParams {
|
||||
@@ -54,6 +55,12 @@ export async function finishLogin(
|
||||
): Promise<Response> {
|
||||
const { user, request, ip, userAgent, source, mfaVerified } = params;
|
||||
|
||||
// v1.23 — new-device / new-location alert. Fire-and-forget: never let the
|
||||
// device ledger or the dispatcher add latency to — or fail — a sign-in. Runs
|
||||
// for every transport (web cookie + native bundle) since the factor checks
|
||||
// are already done by the time finishLogin is reached.
|
||||
void recordSignInDevice({ userId: user.id, ip, userAgent });
|
||||
|
||||
if (
|
||||
shouldIssueBearerToken(request.headers) ||
|
||||
isNativeClientRequest(request.headers)
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* v1.23 — security-activity feed. The SHARED read both the account-security
|
||||
* surface and the data-sovereignty privacy dashboard consume: a user-scoped,
|
||||
* read-only window onto the `AuditLog` rows that matter for account security —
|
||||
* logins, MFA events, password changes, token/session revocations, exports,
|
||||
* and deletions. No new storage: it reuses the existing
|
||||
* `@@index([userId, action, createdAt(sort: Desc)])`.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Whether an audit action belongs in the user-facing security-activity feed.
|
||||
* Pure so the contract can be unit-tested without a DB:
|
||||
* - every `auth.*` event (login, mfa, password, token, bearer, session,
|
||||
* register),
|
||||
* - every export action (`export.download`, `health-record.export`,
|
||||
* `user.export.*` — all contain "export"),
|
||||
* - the two erasure actions (`user.account.delete`, `user.data.clear`).
|
||||
*/
|
||||
export function matchesSecurityActivity(action: string): boolean {
|
||||
return (
|
||||
action.startsWith("auth.") ||
|
||||
action.includes("export") ||
|
||||
action === "user.account.delete" ||
|
||||
action === "user.data.clear"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prisma `where` mirror of `matchesSecurityActivity`, scoped to one user. Kept
|
||||
* alongside the predicate so the two never drift.
|
||||
*/
|
||||
export function securityActivityWhere(userId: string) {
|
||||
return {
|
||||
userId,
|
||||
OR: [
|
||||
{ action: { startsWith: "auth." } },
|
||||
{ action: { contains: "export" } },
|
||||
{ action: { in: ["user.account.delete", "user.data.clear"] } },
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -8,6 +8,12 @@ import { shouldEmitSecureCookie } from "@/lib/auth/secure-cookie";
|
||||
const SESSION_COOKIE = "healthlog_session";
|
||||
const SESSION_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
|
||||
|
||||
// v1.23 — throttle window for the user-facing active-session list's "last
|
||||
// seen" stamp. A write only happens when the prior stamp is older than this,
|
||||
// so the high-churn `getSession` path costs at most one extra UPDATE per
|
||||
// session per window rather than one per request.
|
||||
const LAST_ACTIVE_THROTTLE_MS = 5 * 60 * 1000; // 5 minutes
|
||||
|
||||
/**
|
||||
* v1.4.22 C4 — flag cookie mirroring the user's `onboardingCompletedAt`
|
||||
* status. Set to `"pending"` while the field is null and cleared once
|
||||
@@ -147,6 +153,22 @@ export async function getSession(): Promise<{
|
||||
});
|
||||
}
|
||||
|
||||
// v1.23 — sliding "last seen" stamp for the active-session list. Throttled
|
||||
// (only when the prior stamp is stale) and fire-and-forget so it never adds
|
||||
// latency or a failure mode to the request-resolution path.
|
||||
const lastActive = session.lastActiveAt;
|
||||
if (
|
||||
!lastActive ||
|
||||
lastActive.getTime() < Date.now() - LAST_ACTIVE_THROTTLE_MS
|
||||
) {
|
||||
void prisma.session
|
||||
.update({
|
||||
where: { id: session.id },
|
||||
data: { lastActiveAt: new Date() },
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
return {
|
||||
session: { id: session.id, expiresAt: session.expiresAt },
|
||||
user: session.user,
|
||||
@@ -191,3 +213,46 @@ export async function destroyAllSessions(userId: string): Promise<void> {
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.23 — "sign out everywhere" for the user-facing active-session surface
|
||||
* (issue #64). Distinct from `destroyAllSessions`: this keeps the caller's
|
||||
* CURRENT cookie session alive so clicking the button doesn't log the user out
|
||||
* of the device they pressed it on, and it does NOT revoke `ApiToken`s — those
|
||||
* are long-lived programmatic credentials the user manages separately under
|
||||
* /settings/api-tokens, not "sessions" in the device-list sense. It DOES revoke
|
||||
* every native-client `RefreshToken` (each is a device login) so a signed-in
|
||||
* phone/tablet is dropped too, matching the "everywhere" promise.
|
||||
*
|
||||
* Returns the number of OTHER web sessions removed so the surface can confirm.
|
||||
*/
|
||||
export async function destroyOtherSessions(
|
||||
userId: string,
|
||||
currentSessionId: string,
|
||||
): Promise<{ sessionsRevoked: number }> {
|
||||
const [deleted] = await prisma.$transaction([
|
||||
prisma.session.deleteMany({
|
||||
where: { userId, id: { not: currentSessionId } },
|
||||
}),
|
||||
prisma.refreshToken.updateMany({
|
||||
where: { userId, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
}),
|
||||
]);
|
||||
return { sessionsRevoked: deleted.count };
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.23 — revoke a single web session by id, scoped to the owning user so a
|
||||
* caller can never delete another user's session row. Returns whether a row
|
||||
* was actually removed (false → not found or not owned).
|
||||
*/
|
||||
export async function destroySessionById(
|
||||
userId: string,
|
||||
sessionId: string,
|
||||
): Promise<boolean> {
|
||||
const result = await prisma.session.deleteMany({
|
||||
where: { id: sessionId, userId },
|
||||
});
|
||||
return result.count > 0;
|
||||
}
|
||||
@@ -94,6 +94,13 @@ export const EVENT_TYPES = [
|
||||
// user-visible Telegram message on every dose would be noise). Routed
|
||||
// through the dedicated intake-sync sender, not the alert cascade.
|
||||
"MEDICATION_INTAKE_SYNC",
|
||||
// v1.23 — account-security alert (new-device / new-location sign-in). Fired
|
||||
// by the login completion path on the first sighting of a coarse device
|
||||
// fingerprint. ON by default at the channel layer: a sign-in the user did
|
||||
// not make is exactly the case they need to hear about, so silence-by-default
|
||||
// would defeat the feature. An explicit per-channel `NotificationPreference`
|
||||
// row still wins for a user who opts out.
|
||||
"SECURITY_ALERT",
|
||||
] as const;
|
||||
export type EventType = (typeof EVENT_TYPES)[number];
|
||||
|
||||
@@ -151,6 +158,10 @@ export const EVENT_DEFAULT_ENABLED: Record<EventType, boolean> = {
|
||||
// toggle: this is plumbing that keeps the user's own devices coherent,
|
||||
// not a notification the user chooses to receive.
|
||||
MEDICATION_INTAKE_SYNC: true,
|
||||
// v1.23 — ON by default; a new-device sign-in is a security event the user
|
||||
// needs surfaced. An explicit per-channel `NotificationPreference` row
|
||||
// (enabled=false) still suppresses it for a user who opts out.
|
||||
SECURITY_ALERT: true,
|
||||
};
|
||||
|
||||
export const CHANNEL_TYPE_LABELS: Record<ChannelType, string> = {
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
totpConfirmSchema,
|
||||
mfaDisableSchema,
|
||||
} from "@/lib/validations/mfa";
|
||||
import { dataEnvelope, stdResponses } from "./shared";
|
||||
import { dataEnvelope, stdResponses, errorEnvelope } from "./shared";
|
||||
|
||||
// ── Sub-schemas owned here (route-specific shapes) ───────────────────
|
||||
|
||||
@@ -129,6 +129,61 @@ const mfaToggleResponse = z
|
||||
.object({ enabled: z.boolean() })
|
||||
.meta({ id: "MfaToggleResponse" });
|
||||
|
||||
// ── v1.23 active sessions + security activity shapes ──────────────────
|
||||
|
||||
const sessionListResponse = z
|
||||
.object({
|
||||
sessions: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
device: z
|
||||
.string()
|
||||
.describe("Coarse device label derived from the User-Agent."),
|
||||
ipMasked: z
|
||||
.string()
|
||||
.nullable()
|
||||
.describe(
|
||||
"IP with the host portion masked — never the full address.",
|
||||
),
|
||||
location: z
|
||||
.string()
|
||||
.nullable()
|
||||
.describe("Resolved coarse location, when available."),
|
||||
lastActiveAt: z.iso.datetime({ offset: true }).nullable(),
|
||||
createdAt: z.iso.datetime({ offset: true }),
|
||||
isCurrent: z
|
||||
.boolean()
|
||||
.describe("True for the session making this request."),
|
||||
}),
|
||||
),
|
||||
})
|
||||
.meta({ id: "SessionListResponse" });
|
||||
|
||||
const signOutEverywhereResponse = z
|
||||
.object({
|
||||
sessionsRevoked: z
|
||||
.number()
|
||||
.int()
|
||||
.describe("Number of OTHER sessions removed (the current one is kept)."),
|
||||
})
|
||||
.meta({ id: "SignOutEverywhereResponse" });
|
||||
|
||||
const securityActivityResponse = z
|
||||
.object({
|
||||
events: z.array(
|
||||
z.object({
|
||||
action: z
|
||||
.string()
|
||||
.describe("Audit action name, e.g. auth.login.password."),
|
||||
createdAt: z.iso.datetime({ offset: true }),
|
||||
location: z.string().nullable(),
|
||||
ipMasked: z.string().nullable().describe("Host-masked IP."),
|
||||
carrier: z.string().nullable(),
|
||||
}),
|
||||
),
|
||||
})
|
||||
.meta({ id: "SecurityActivityResponse" });
|
||||
|
||||
export const authPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
"/api/auth/login": {
|
||||
post: {
|
||||
@@ -320,4 +375,91 @@ export const authPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/auth/me/sessions": {
|
||||
get: {
|
||||
tags: ["Auth"],
|
||||
summary: "List active web sessions",
|
||||
description:
|
||||
"v1.23 — the user-facing active-session list (issue #64). One row per browser login with a coarse device label, masked IP, resolved location, sliding last-active time, and the current-session marker. Distinct from /api/auth/me/devices (notification devices).",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "Active sessions for the caller.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(sessionListResponse, "SessionListEnvelope"),
|
||||
},
|
||||
},
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
delete: {
|
||||
tags: ["Auth"],
|
||||
summary: "Sign out everywhere else",
|
||||
description:
|
||||
"v1.23 — revokes every OTHER web session plus all native refresh tokens, keeping the caller's current session. API tokens are not touched (manage those under /settings/api-tokens).",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "Other sessions revoked.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
signOutEverywhereResponse,
|
||||
"SignOutEverywhereEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/auth/me/sessions/{id}": {
|
||||
delete: {
|
||||
tags: ["Auth"],
|
||||
summary: "Revoke a single web session",
|
||||
description:
|
||||
"v1.23 — revokes one session by id, scoped to the authenticated user (a foreign id returns 404, never another user's row).",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "Session revoked.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
z.object({ revoked: z.boolean() }),
|
||||
"SessionRevokeEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
"404": {
|
||||
description: "Session not found or not owned by the caller.",
|
||||
content: { "application/json": { schema: errorEnvelope } },
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
},
|
||||
"/api/auth/me/security-activity": {
|
||||
get: {
|
||||
tags: ["Auth"],
|
||||
summary: "List recent account-security activity",
|
||||
description:
|
||||
"v1.23 — the SHARED security-activity feed: the caller's recent auth + export + deletion audit events with timestamp, resolved location, and a host-masked IP. `limit` query param caps at 100 (default 50). Reuses the AuditLog store; no event detail bodies are surfaced.",
|
||||
responses: {
|
||||
"200": {
|
||||
description: "Recent security events for the caller.",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: dataEnvelope(
|
||||
securityActivityResponse,
|
||||
"SecurityActivityEnvelope",
|
||||
),
|
||||
},
|
||||
},
|
||||
},
|
||||
...stdResponses,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -33,6 +33,21 @@ export const authKeys = {
|
||||
|
||||
passkeys: () => ["passkeys"] as const,
|
||||
|
||||
/**
|
||||
* v1.23 — the user-facing active-session list behind
|
||||
* `GET /api/auth/me/sessions`. Revoking a single session or signing out
|
||||
* everywhere invalidates this key so the surface re-reads the live set.
|
||||
*/
|
||||
sessions: () => ["auth", "sessions"] as const,
|
||||
|
||||
/**
|
||||
* v1.23 — the shared security-activity feed behind
|
||||
* `GET /api/auth/me/security-activity` (logins, MFA, password change,
|
||||
* session revoke, exports, deletions). Consumed by the account-security
|
||||
* surface and the privacy dashboard.
|
||||
*/
|
||||
securityActivity: () => ["auth", "security-activity"] as const,
|
||||
|
||||
userAiProvider: () => ["user", "ai-provider"] as const,
|
||||
userProfile: () => ["user", "profile"] as const,
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user