mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 08:02:12 +00:00
Gate the public share view behind the passphrase
A protected share link no longer renders the record until the passphrase is verified. The public page checks the gate state first (without bumping access counters), and for a link with a passphrase hash it serves a gate island unless a valid, token-scoped unlock cookie is present. A legacy link with a null passphrase hash renders exactly as before. The unlock route verifies the submitted passphrase with a constant-time compare against the stored hash, is rate-limited by share-unlock token and IP before any compare, and on success sets a short-lived (30 min) httpOnly, SameSite=Strict, Secure cookie scoped to that one token's view path. Every failure class answers one blunt 401; no-store and the flat 404 for unknown links are preserved. The gate island auto-submits the #k= fragment (scrubbing it from history first) or prompts for input.
This commit is contained in:
1 parent
1aeb6f7957
commit
5783acacbb
9 files changed
+755
-24
No files matched your search
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* v1.18.7 — public passphrase-gate verifier (POST /api/c/{token}/unlock).
|
||||
*
|
||||
* Asserts the load-bearing properties:
|
||||
* - a correct passphrase sets a short-lived, token-scoped httpOnly cookie;
|
||||
* - a wrong passphrase is rejected with a blunt 401, no cookie set;
|
||||
* - an unknown / revoked / expired token (gate null) is the same blunt 401;
|
||||
* - a link with no passphrase set cannot be unlocked;
|
||||
* - the route is rate-limited BEFORE any compare.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
const TEST_HMAC_KEY = "test-hmac-key-at-least-32-chars-long-xxxxx";
|
||||
|
||||
const cookieSet = vi.fn();
|
||||
vi.mock("next/headers", () => ({
|
||||
headers: vi.fn(async () => ({ get: () => null })),
|
||||
cookies: vi.fn(async () => ({
|
||||
get: () => undefined,
|
||||
set: cookieSet,
|
||||
delete: () => {},
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {},
|
||||
}));
|
||||
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
|
||||
vi.mock("@/lib/clinician-share/resolve-share-token", () => ({
|
||||
resolveShareGateState: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/clinician-share/passphrase", () => ({
|
||||
verifyPassphrase: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/rate-limit", () => ({
|
||||
checkAuthSurfaceRateLimit: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
|
||||
vi.mock("@/lib/db-compat", () => ({
|
||||
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
import { POST } from "../route";
|
||||
import { resolveShareGateState } from "@/lib/clinician-share/resolve-share-token";
|
||||
import { verifyPassphrase } from "@/lib/clinician-share/passphrase";
|
||||
import { checkAuthSurfaceRateLimit } from "@/lib/rate-limit";
|
||||
|
||||
const TOKEN = `hls_${"a".repeat(48)}`;
|
||||
const TOKEN_HASH = "f".repeat(64);
|
||||
|
||||
function req(body: unknown): NextRequest {
|
||||
return new NextRequest(`http://localhost/api/c/${TOKEN}/unlock`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
function call() {
|
||||
return POST(req({ passphrase: "ABCD-EFGH-JKMN-PQRS" }), {
|
||||
params: Promise.resolve({ token: TOKEN }),
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.stubEnv("API_TOKEN_HMAC_KEY", TEST_HMAC_KEY);
|
||||
vi.mocked(checkAuthSurfaceRateLimit).mockResolvedValue({
|
||||
allowed: true,
|
||||
remaining: 9,
|
||||
resetAt: Date.now() + 60_000,
|
||||
ip: "1.2.3.4",
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/c/[token]/unlock", () => {
|
||||
it("sets a token-scoped httpOnly cookie on a correct passphrase", async () => {
|
||||
vi.mocked(resolveShareGateState).mockResolvedValue({
|
||||
tokenHash: TOKEN_HASH,
|
||||
passphraseHash: "deadbeef",
|
||||
});
|
||||
vi.mocked(verifyPassphrase).mockReturnValue(true);
|
||||
|
||||
const res = await call();
|
||||
expect(res.status).toBe(200);
|
||||
|
||||
expect(cookieSet).toHaveBeenCalledTimes(1);
|
||||
const [name, , opts] = cookieSet.mock.calls[0];
|
||||
expect(name).toContain("hls_unlock_");
|
||||
expect(opts.httpOnly).toBe(true);
|
||||
expect(opts.sameSite).toBe("strict");
|
||||
// Scoped to THIS token's view path only.
|
||||
expect(opts.path).toBe(`/c/${TOKEN}`);
|
||||
expect(opts.maxAge).toBeGreaterThan(0);
|
||||
expect(opts.maxAge).toBeLessThanOrEqual(30 * 60);
|
||||
});
|
||||
|
||||
it("rejects a wrong passphrase with a blunt 401, no cookie", async () => {
|
||||
vi.mocked(resolveShareGateState).mockResolvedValue({
|
||||
tokenHash: TOKEN_HASH,
|
||||
passphraseHash: "deadbeef",
|
||||
});
|
||||
vi.mocked(verifyPassphrase).mockReturnValue(false);
|
||||
|
||||
const res = await call();
|
||||
expect(res.status).toBe(401);
|
||||
expect(cookieSet).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an unknown / revoked / expired token (gate null) with 401", async () => {
|
||||
vi.mocked(resolveShareGateState).mockResolvedValue(null);
|
||||
|
||||
const res = await call();
|
||||
expect(res.status).toBe(401);
|
||||
expect(verifyPassphrase).not.toHaveBeenCalled();
|
||||
expect(cookieSet).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cannot unlock a link with no passphrase set", async () => {
|
||||
vi.mocked(resolveShareGateState).mockResolvedValue({
|
||||
tokenHash: TOKEN_HASH,
|
||||
passphraseHash: null,
|
||||
});
|
||||
// verifyPassphrase returns false for a null stored hash.
|
||||
vi.mocked(verifyPassphrase).mockReturnValue(false);
|
||||
|
||||
const res = await call();
|
||||
expect(res.status).toBe(401);
|
||||
expect(cookieSet).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("is rate-limited before any compare", async () => {
|
||||
vi.mocked(resolveShareGateState).mockResolvedValue({
|
||||
tokenHash: TOKEN_HASH,
|
||||
passphraseHash: "deadbeef",
|
||||
});
|
||||
vi.mocked(checkAuthSurfaceRateLimit).mockResolvedValue({
|
||||
allowed: false,
|
||||
remaining: 0,
|
||||
resetAt: Date.now() + 60_000,
|
||||
ip: "1.2.3.4",
|
||||
});
|
||||
|
||||
const res = await call();
|
||||
expect(res.status).toBe(429);
|
||||
expect(verifyPassphrase).not.toHaveBeenCalled();
|
||||
expect(cookieSet).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* v1.18.7 — POST /api/c/{token}/unlock — public passphrase gate verifier.
|
||||
*
|
||||
* The second factor for a passphrase-protected clinician share link. It is an
|
||||
* anonymous, no-session surface (like the `/c/<token>` view itself): the raw
|
||||
* path token plus the submitted passphrase are the only credentials. On a
|
||||
* correct passphrase it mints a SHORT-LIVED, httpOnly, SameSite=Strict, Secure
|
||||
* cookie SCOPED to this token's view path so the page renders the record; a
|
||||
* cookie minted for one token never unlocks another.
|
||||
*
|
||||
* Brute-force protection is mandatory here — the passphrase is the only thing
|
||||
* standing between a leaked URL and the record — so the route is rate-limited
|
||||
* by `share-unlock:<tokenHash>:<ip>` BEFORE any compare, using the
|
||||
* anonymous-surface limiter so a broken trust chain collapses to one tight
|
||||
* bucket rather than a free-for-all.
|
||||
*
|
||||
* Failure is blunt: a malformed token, an unknown/revoked/expired link, a link
|
||||
* with no passphrase set, or a wrong passphrase all answer the SAME flat error.
|
||||
* `no-store` is preserved end to end. Nothing here leaks why a request failed.
|
||||
*/
|
||||
import { cookies } from "next/headers";
|
||||
import { NextRequest } from "next/server";
|
||||
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import {
|
||||
apiError,
|
||||
apiSuccess,
|
||||
returnAllZodIssues,
|
||||
safeJson,
|
||||
} from "@/lib/api-response";
|
||||
import { checkAuthSurfaceRateLimit } from "@/lib/rate-limit";
|
||||
import { shouldEmitSecureCookie } from "@/lib/auth/secure-cookie";
|
||||
import { resolveShareGateState } from "@/lib/clinician-share/resolve-share-token";
|
||||
import { verifyPassphrase } from "@/lib/clinician-share/passphrase";
|
||||
import {
|
||||
mintUnlockValue,
|
||||
unlockCookieName,
|
||||
UNLOCK_TTL_SECONDS,
|
||||
} from "@/lib/clinician-share/unlock-cookie";
|
||||
import { unlockShareLinkSchema } from "@/lib/validations/clinician-share-link";
|
||||
|
||||
/** One blunt failure for every class — a probe distinguishes nothing. */
|
||||
function reject() {
|
||||
return apiError("Invalid passphrase", 401);
|
||||
}
|
||||
|
||||
export const POST = apiHandler(
|
||||
async (
|
||||
request: NextRequest,
|
||||
ctx: { params: Promise<{ token: string }> },
|
||||
) => {
|
||||
const { token } = await ctx.params;
|
||||
annotate({ action: { name: "share-link.unlock" } });
|
||||
|
||||
// Resolve the live-gate state first (no counter bump). A malformed /
|
||||
// unknown / revoked / expired token is `null` → the same blunt reject.
|
||||
const gate = await resolveShareGateState(token);
|
||||
|
||||
// Rate-limit BEFORE any compare. Key on the resolved tokenHash when we
|
||||
// have one (so the bucket is per-link), else a fixed sentinel so probing
|
||||
// unknown tokens still shares one tight bucket. The anonymous-surface
|
||||
// limiter collapses a broken trust chain to a single bucket.
|
||||
const rlKey = gate ? gate.tokenHash : "unknown";
|
||||
const rl = await checkAuthSurfaceRateLimit(
|
||||
request,
|
||||
`share-unlock:${rlKey}`,
|
||||
10,
|
||||
10 * 60 * 1000,
|
||||
);
|
||||
if (!rl.allowed) {
|
||||
return apiError("Too many attempts", 429);
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request, {
|
||||
maxBytes: 4 * 1024,
|
||||
});
|
||||
if (jsonError) return jsonError;
|
||||
|
||||
const parsed = unlockShareLinkSchema.safeParse(body);
|
||||
if (!parsed.success) return returnAllZodIssues(parsed.error);
|
||||
|
||||
// A token with no live gate, or one carrying no passphrase, cannot be
|
||||
// unlocked. `verifyPassphrase` is constant-time and returns false for a
|
||||
// null stored hash, so the two branches are indistinguishable in timing.
|
||||
if (!gate) return reject();
|
||||
if (!verifyPassphrase(parsed.data.passphrase, gate.passphraseHash)) {
|
||||
annotate({ meta: { unlock: "rejected" } });
|
||||
return reject();
|
||||
}
|
||||
|
||||
// Correct passphrase — mint the short-lived, token-scoped unlock cookie.
|
||||
const cookieStore = await cookies();
|
||||
cookieStore.set(unlockCookieName(gate.tokenHash), mintUnlockValue(gate.tokenHash), {
|
||||
httpOnly: true,
|
||||
secure: shouldEmitSecureCookie(),
|
||||
sameSite: "strict",
|
||||
// Scope to THIS token's view path only — the cookie unlocks nothing else.
|
||||
path: `/c/${token}`,
|
||||
maxAge: UNLOCK_TTL_SECONDS,
|
||||
});
|
||||
|
||||
annotate({ meta: { unlock: "granted" } });
|
||||
return apiSuccess({ unlocked: true });
|
||||
},
|
||||
);
|
||||
Reference in new issue
Block a user