mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
Three refusals still answered 401 with prose alone: the Bearer re-read on `/api/auth/me/sessions`, and the wrong-second-factor arm on both MFA step-up routes. The shared 401 description told clients the code is the field to branch on, so a client that took that advice landed in its default arm on all three — and on the MFA pair that is the difference between re-prompting for a digit and signing the user out over a typo. The sessions re-read is the same missing-credential fact the gate already names, so it reuses `auth.missing`. The MFA pair gets a code of its own, `auth.mfa.code_invalid`: none of the existing ones fit, because every other 401 code asks the client to discard something, and this one asks it to keep the session and try another code. The description narrows to match what is actually true. The generic gates name a reason; a route that checks a credential of its own — sign-in, the MFA challenge exchange, a password confirmation — still answers 401 with prose, and the text now says so instead of promising a field those responses do not carry.
151 lines
4.9 KiB
TypeScript
151 lines
4.9 KiB
TypeScript
/**
|
|
* GET /api/auth/me/sessions — list the user's active web sessions.
|
|
* DELETE /api/auth/me/sessions — "sign out everywhere": revoke every OTHER
|
|
* session (and native refresh tokens), keeping
|
|
* the caller's current session. Closes #64.
|
|
*
|
|
* v1.23 — the user-facing session/device-management surface. Distinct from
|
|
* `/api/auth/me/devices`, which lists APNs / Web-Push notification devices;
|
|
* this lists the authenticated `Session` rows (one per browser login). The list
|
|
* carries the masked IP + resolved coarse location + a coarse device label +
|
|
* the sliding `lastActiveAt` — never the full IP, never a credential. The
|
|
* caller's own row is flagged `isCurrent` so the UI can mark "this device".
|
|
*/
|
|
import { NextRequest } from "next/server";
|
|
import { headers } from "next/headers";
|
|
import {
|
|
apiHandler,
|
|
AUTH_ERROR_CODES,
|
|
HttpError,
|
|
requireAuth,
|
|
} from "@/lib/api-handler";
|
|
import { apiSuccess } from "@/lib/api-response";
|
|
import { annotate } from "@/lib/logging/context";
|
|
import { auditLog } from "@/lib/auth/audit";
|
|
import { getClientIp } from "@/lib/api-response";
|
|
import { prisma } from "@/lib/db";
|
|
import { hashToken } from "@/lib/auth/hmac";
|
|
import {
|
|
destroyOtherSessions,
|
|
sessionHandle,
|
|
type CurrentCredential,
|
|
} from "@/lib/auth/session";
|
|
import { lookupIpLocation } from "@/lib/geo";
|
|
import { coarseDeviceLabel, maskIp } from "@/lib/auth/device-fingerprint";
|
|
|
|
export const dynamic = "force-dynamic";
|
|
|
|
export interface SessionDTO {
|
|
id: string;
|
|
device: string;
|
|
ipMasked: string | null;
|
|
location: string | null;
|
|
lastActiveAt: string | null;
|
|
createdAt: string;
|
|
isCurrent: boolean;
|
|
}
|
|
|
|
export const GET = apiHandler(async () => {
|
|
const { user, session } = await requireAuth();
|
|
|
|
const sessions = await prisma.session.findMany({
|
|
where: { userId: user.id, expiresAt: { gt: new Date() } },
|
|
orderBy: { lastActiveAt: { sort: "desc", nulls: "last" } },
|
|
select: {
|
|
id: true,
|
|
ipAddress: true,
|
|
userAgent: true,
|
|
lastActiveAt: true,
|
|
createdAt: true,
|
|
},
|
|
});
|
|
|
|
// Resolve location once per distinct IP (the resolver caches internally, but
|
|
// de-duping keeps the await count to the number of unique networks).
|
|
const uniqueIps = Array.from(
|
|
new Set(
|
|
sessions.map((s) => s.ipAddress).filter((ip): ip is string => !!ip),
|
|
),
|
|
);
|
|
const locationByIp = new Map<string, string | null>();
|
|
await Promise.all(
|
|
uniqueIps.map(async (ip) => {
|
|
try {
|
|
locationByIp.set(ip, await lookupIpLocation(ip));
|
|
} catch {
|
|
locationByIp.set(ip, null);
|
|
}
|
|
}),
|
|
);
|
|
|
|
const result: SessionDTO[] = sessions.map((s) => ({
|
|
id: sessionHandle(s.id),
|
|
device: coarseDeviceLabel(s.userAgent),
|
|
ipMasked: maskIp(s.ipAddress),
|
|
location: s.ipAddress ? (locationByIp.get(s.ipAddress) ?? null) : null,
|
|
lastActiveAt: s.lastActiveAt ? s.lastActiveAt.toISOString() : null,
|
|
createdAt: s.createdAt.toISOString(),
|
|
isCurrent: s.id === session.id,
|
|
}));
|
|
|
|
annotate({
|
|
action: { name: "auth.session.list" },
|
|
meta: { session_count: result.length },
|
|
});
|
|
|
|
return apiSuccess({ sessions: result });
|
|
});
|
|
|
|
export const DELETE = apiHandler(async (request: NextRequest) => {
|
|
const auth = await requireAuth();
|
|
const { user } = auth;
|
|
|
|
// Name the caller by the transport it actually used. On the Bearer path
|
|
// `session.id` is the `ApiToken` row id, not a session id; handing that to
|
|
// the session-kind spared nothing, so the phone that pressed "sign out
|
|
// everywhere" was the one signed out at its next rotation, while the other
|
|
// devices kept their access tokens. The access-token kind spares the
|
|
// caller's own device login by its `accessTokenHash`.
|
|
const current: CurrentCredential =
|
|
auth.authMethod === "bearer"
|
|
? {
|
|
kind: "accessToken",
|
|
accessTokenHash: hashToken(await presentedBearerToken()),
|
|
}
|
|
: { kind: "session", sessionId: auth.session.id };
|
|
|
|
const { sessionsRevoked, accessTokensRevoked } = await destroyOtherSessions(
|
|
user.id,
|
|
current,
|
|
);
|
|
|
|
await auditLog("auth.session.revoke_others", {
|
|
userId: user.id,
|
|
ipAddress: getClientIp(request),
|
|
details: { sessionsRevoked, accessTokensRevoked },
|
|
});
|
|
|
|
annotate({
|
|
action: { name: "auth.session.revoke_others" },
|
|
meta: {
|
|
sessions_revoked: sessionsRevoked,
|
|
access_tokens_revoked: accessTokensRevoked,
|
|
},
|
|
});
|
|
|
|
return apiSuccess({ sessionsRevoked });
|
|
});
|
|
|
|
/**
|
|
* The raw Bearer token this request presented. `requireAuth` has already
|
|
* accepted it, so a missing header here is a programming error, not a client
|
|
* one; it is refused the same way rather than reasoned about.
|
|
*/
|
|
async function presentedBearerToken(): Promise<string> {
|
|
const authHeader = (await headers()).get("authorization");
|
|
if (!authHeader?.startsWith("Bearer ")) {
|
|
throw new HttpError(401, "Not authenticated", AUTH_ERROR_CODES.missing);
|
|
}
|
|
return authHeader.slice(7);
|
|
}
|