mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 23:52:24 +00:00
feat(auth): add OIDC SSO login
Adds an OpenID Connect relying-party login path (PKCE authorization-code flow) against a single env-configured identity provider — additive to password/passkey login by default, with an operator opt-in (OIDC_ONLY, enforced server-side on every auth route) to disable them entirely. First-time sign-in auto-provisions or links an account by verified email. Closes an open redirect in the post-login `next` parameter (both the new OIDC path and the pre-existing password/passkey flow shared the same backslash-normalization bypass) by resolving the target through a real URL parse and comparing origins instead of a prefix check.
This commit is contained in:
1 parent
6712619495
commit
f815e4a83f
33 files changed
+2202
-95
No files matched your search
@@ -0,0 +1,43 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { sanitizeSameOriginPath } from "../url-safety";
|
||||
|
||||
const BASE = "https://healthlog.example.com/auth/login";
|
||||
|
||||
describe("sanitizeSameOriginPath", () => {
|
||||
it("passes through a plain same-origin path", () => {
|
||||
expect(sanitizeSameOriginPath("/dashboard", BASE)).toBe("/dashboard");
|
||||
});
|
||||
|
||||
it("defaults to / when next is null, undefined, or empty", () => {
|
||||
expect(sanitizeSameOriginPath(null, BASE)).toBe("/");
|
||||
expect(sanitizeSameOriginPath(undefined, BASE)).toBe("/");
|
||||
expect(sanitizeSameOriginPath("", BASE)).toBe("/");
|
||||
});
|
||||
|
||||
it("rejects a protocol-relative next (//host)", () => {
|
||||
expect(sanitizeSameOriginPath("//evil.com", BASE)).toBe("/");
|
||||
});
|
||||
|
||||
it("rejects an absolute next pointing at another origin", () => {
|
||||
expect(sanitizeSameOriginPath("https://evil.com/phish", BASE)).toBe("/");
|
||||
});
|
||||
|
||||
it("rejects the backslash-normalization bypass (/\\evil.com)", () => {
|
||||
// WHATWG URL parsing treats a leading backslash as a path separator for
|
||||
// special schemes, so a naive startsWith("/") && !startsWith("//")
|
||||
// check would accept this — Next.js's router.push() re-parses the
|
||||
// string the same way and hard-navigates to the resolved origin.
|
||||
expect(sanitizeSameOriginPath("/\\evil.com", BASE)).toBe("/");
|
||||
expect(sanitizeSameOriginPath("\\\\evil.com", BASE)).toBe("/");
|
||||
});
|
||||
|
||||
it("preserves a same-origin path's search and hash", () => {
|
||||
expect(sanitizeSameOriginPath("/settings?tab=security#top", BASE)).toBe(
|
||||
"/settings?tab=security#top",
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to / on an unparseable value", () => {
|
||||
expect(sanitizeSameOriginPath("https://", BASE)).toBe("/");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,408 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@/lib/safe-fetch", () => ({ safeFetch: vi.fn() }));
|
||||
vi.mock("jose", () => ({
|
||||
jwtVerify: vi.fn(),
|
||||
createRemoteJWKSet: vi.fn(() => ({ jwks: "fake" })),
|
||||
}));
|
||||
|
||||
import { safeFetch } from "@/lib/safe-fetch";
|
||||
import { jwtVerify as mockJwtVerify } from "jose";
|
||||
import {
|
||||
_resetOidcCacheForTests,
|
||||
buildAuthorizationUrl,
|
||||
deriveUniqueUsername,
|
||||
discoverOidcMetadata,
|
||||
exchangeCodeForTokens,
|
||||
fetchUserinfoEmail,
|
||||
getOidcConfig,
|
||||
getOidcRedirectUri,
|
||||
isOidcConfigured,
|
||||
isOidcOnly,
|
||||
sanitizeOidcNextPath,
|
||||
verifyIdToken,
|
||||
} from "../oidc";
|
||||
|
||||
const ENV_KEYS = [
|
||||
"OIDC_ISSUER_URL",
|
||||
"OIDC_CLIENT_ID",
|
||||
"OIDC_CLIENT_SECRET",
|
||||
"OIDC_SCOPES",
|
||||
"OIDC_BUTTON_LABEL",
|
||||
"OIDC_ONLY",
|
||||
"NEXT_PUBLIC_APP_URL",
|
||||
] as const;
|
||||
const ORIGINAL_ENV: Record<string, string | undefined> = {};
|
||||
|
||||
function jsonResponse(body: unknown, ok = true, status = 200): Response {
|
||||
return {
|
||||
ok,
|
||||
status,
|
||||
json: async () => body,
|
||||
} as unknown as Response;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
for (const key of ENV_KEYS) ORIGINAL_ENV[key] = process.env[key];
|
||||
vi.resetAllMocks();
|
||||
_resetOidcCacheForTests();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const key of ENV_KEYS) {
|
||||
if (ORIGINAL_ENV[key] === undefined) delete process.env[key];
|
||||
else process.env[key] = ORIGINAL_ENV[key];
|
||||
}
|
||||
});
|
||||
|
||||
function configureEnv() {
|
||||
process.env.OIDC_ISSUER_URL = "https://idp.example.com";
|
||||
process.env.OIDC_CLIENT_ID = "client-123";
|
||||
process.env.OIDC_CLIENT_SECRET = "secret-abc";
|
||||
process.env.NEXT_PUBLIC_APP_URL = "https://healthlog.example.com";
|
||||
}
|
||||
|
||||
describe("isOidcConfigured / getOidcConfig", () => {
|
||||
it("is unconfigured when any of the three vars is missing", () => {
|
||||
delete process.env.OIDC_ISSUER_URL;
|
||||
delete process.env.OIDC_CLIENT_ID;
|
||||
delete process.env.OIDC_CLIENT_SECRET;
|
||||
expect(isOidcConfigured()).toBe(false);
|
||||
expect(getOidcConfig()).toBeNull();
|
||||
|
||||
process.env.OIDC_ISSUER_URL = "https://idp.example.com";
|
||||
process.env.OIDC_CLIENT_ID = "client-123";
|
||||
// secret still missing
|
||||
expect(isOidcConfigured()).toBe(false);
|
||||
});
|
||||
|
||||
it("applies defaults for scopes and button label", () => {
|
||||
configureEnv();
|
||||
delete process.env.OIDC_SCOPES;
|
||||
delete process.env.OIDC_BUTTON_LABEL;
|
||||
const config = getOidcConfig();
|
||||
expect(config?.scopes).toBe("openid email profile");
|
||||
expect(config?.buttonLabel).toBe("Single Sign-On");
|
||||
// Trailing slash on the issuer is normalised away.
|
||||
process.env.OIDC_ISSUER_URL = "https://idp.example.com/";
|
||||
expect(getOidcConfig()?.issuerUrl).toBe("https://idp.example.com");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isOidcOnly", () => {
|
||||
it("only takes effect when the provider is fully configured", () => {
|
||||
delete process.env.OIDC_ISSUER_URL;
|
||||
process.env.OIDC_ONLY = "true";
|
||||
expect(isOidcOnly()).toBe(false);
|
||||
|
||||
configureEnv();
|
||||
process.env.OIDC_ONLY = "true";
|
||||
expect(isOidcOnly()).toBe(true);
|
||||
|
||||
process.env.OIDC_ONLY = "false";
|
||||
expect(isOidcOnly()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getOidcRedirectUri", () => {
|
||||
it("derives the callback URL from NEXT_PUBLIC_APP_URL", () => {
|
||||
configureEnv();
|
||||
expect(getOidcRedirectUri()).toBe(
|
||||
"https://healthlog.example.com/api/auth/oidc/callback",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sanitizeOidcNextPath", () => {
|
||||
const REQUEST_URL = "https://healthlog.example.com/api/auth/oidc/login";
|
||||
|
||||
it("passes through a plain same-origin path", () => {
|
||||
expect(sanitizeOidcNextPath("/dashboard", REQUEST_URL)).toBe("/dashboard");
|
||||
});
|
||||
|
||||
it("defaults to / when next is null or empty", () => {
|
||||
expect(sanitizeOidcNextPath(null, REQUEST_URL)).toBe("/");
|
||||
expect(sanitizeOidcNextPath("", REQUEST_URL)).toBe("/");
|
||||
});
|
||||
|
||||
it("rejects a protocol-relative next (//host)", () => {
|
||||
expect(sanitizeOidcNextPath("//evil.com", REQUEST_URL)).toBe("/");
|
||||
});
|
||||
|
||||
it("rejects an absolute next pointing at another origin", () => {
|
||||
expect(sanitizeOidcNextPath("https://evil.com/phish", REQUEST_URL)).toBe(
|
||||
"/",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects the backslash-normalization bypass (/\\evil.com)", () => {
|
||||
// WHATWG URL parsing treats a leading backslash as a path separator
|
||||
// for special schemes, so a naive startsWith("/") && !startsWith("//")
|
||||
// check would accept this — resolving through URL and comparing the
|
||||
// real origin closes that bypass.
|
||||
expect(sanitizeOidcNextPath("/\\evil.com", REQUEST_URL)).toBe("/");
|
||||
expect(sanitizeOidcNextPath("\\\\evil.com", REQUEST_URL)).toBe("/");
|
||||
});
|
||||
|
||||
it("preserves a same-origin path's search and hash", () => {
|
||||
expect(
|
||||
sanitizeOidcNextPath("/settings?tab=security#top", REQUEST_URL),
|
||||
).toBe("/settings?tab=security#top");
|
||||
});
|
||||
|
||||
it("falls back to / on an unparseable value", () => {
|
||||
expect(sanitizeOidcNextPath("https://", REQUEST_URL)).toBe("/");
|
||||
});
|
||||
});
|
||||
|
||||
const METADATA_DOC = {
|
||||
issuer: "https://idp.example.com",
|
||||
authorization_endpoint: "https://idp.example.com/authorize",
|
||||
token_endpoint: "https://idp.example.com/token",
|
||||
jwks_uri: "https://idp.example.com/jwks",
|
||||
userinfo_endpoint: "https://idp.example.com/userinfo",
|
||||
};
|
||||
|
||||
describe("discoverOidcMetadata", () => {
|
||||
beforeEach(() => configureEnv());
|
||||
|
||||
it("fetches and validates the discovery document", async () => {
|
||||
vi.mocked(safeFetch).mockResolvedValue(jsonResponse(METADATA_DOC));
|
||||
const config = getOidcConfig()!;
|
||||
const metadata = await discoverOidcMetadata(config);
|
||||
expect(metadata.token_endpoint).toBe(METADATA_DOC.token_endpoint);
|
||||
expect(safeFetch).toHaveBeenCalledWith(
|
||||
"https://idp.example.com/.well-known/openid-configuration",
|
||||
expect.objectContaining({ method: "GET" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("caches the result — a second call within the TTL does not refetch", async () => {
|
||||
vi.mocked(safeFetch).mockResolvedValue(jsonResponse(METADATA_DOC));
|
||||
const config = getOidcConfig()!;
|
||||
await discoverOidcMetadata(config);
|
||||
await discoverOidcMetadata(config);
|
||||
expect(safeFetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("rejects a discovery doc whose issuer does not match", async () => {
|
||||
vi.mocked(safeFetch).mockResolvedValue(
|
||||
jsonResponse({ ...METADATA_DOC, issuer: "https://evil.example.com" }),
|
||||
);
|
||||
const config = getOidcConfig()!;
|
||||
await expect(discoverOidcMetadata(config)).rejects.toThrow(
|
||||
/issuer mismatch/,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a discovery doc missing required fields", async () => {
|
||||
vi.mocked(safeFetch).mockResolvedValue(
|
||||
jsonResponse({ issuer: METADATA_DOC.issuer }),
|
||||
);
|
||||
const config = getOidcConfig()!;
|
||||
await expect(discoverOidcMetadata(config)).rejects.toThrow(
|
||||
/missing required fields/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAuthorizationUrl", () => {
|
||||
it("includes PKCE, state, nonce, and requested scopes", () => {
|
||||
configureEnv();
|
||||
const config = getOidcConfig()!;
|
||||
const url = new URL(
|
||||
buildAuthorizationUrl({
|
||||
metadata: METADATA_DOC,
|
||||
config,
|
||||
state: "state-1",
|
||||
nonce: "nonce-1",
|
||||
codeChallenge: "challenge-1",
|
||||
redirectUri: "https://healthlog.example.com/api/auth/oidc/callback",
|
||||
}),
|
||||
);
|
||||
expect(url.origin + url.pathname).toBe(METADATA_DOC.authorization_endpoint);
|
||||
expect(url.searchParams.get("response_type")).toBe("code");
|
||||
expect(url.searchParams.get("client_id")).toBe(config.clientId);
|
||||
expect(url.searchParams.get("state")).toBe("state-1");
|
||||
expect(url.searchParams.get("nonce")).toBe("nonce-1");
|
||||
expect(url.searchParams.get("code_challenge")).toBe("challenge-1");
|
||||
expect(url.searchParams.get("code_challenge_method")).toBe("S256");
|
||||
expect(url.searchParams.get("scope")).toBe(config.scopes);
|
||||
});
|
||||
});
|
||||
|
||||
describe("exchangeCodeForTokens", () => {
|
||||
beforeEach(() => configureEnv());
|
||||
|
||||
it("posts the authorization code + PKCE verifier and returns the token response", async () => {
|
||||
vi.mocked(safeFetch).mockResolvedValue(
|
||||
jsonResponse({ id_token: "id-token-value", access_token: "at-1" }),
|
||||
);
|
||||
const config = getOidcConfig()!;
|
||||
const tokens = await exchangeCodeForTokens({
|
||||
metadata: METADATA_DOC,
|
||||
config,
|
||||
code: "auth-code",
|
||||
codeVerifier: "verifier-1",
|
||||
redirectUri: "https://healthlog.example.com/api/auth/oidc/callback",
|
||||
});
|
||||
expect(tokens.id_token).toBe("id-token-value");
|
||||
const [url, init] = vi.mocked(safeFetch).mock.calls[0];
|
||||
expect(url).toBe(METADATA_DOC.token_endpoint);
|
||||
const body = (init as RequestInit).body as string;
|
||||
expect(body).toContain("grant_type=authorization_code");
|
||||
expect(body).toContain("code=auth-code");
|
||||
expect(body).toContain("code_verifier=verifier-1");
|
||||
});
|
||||
|
||||
it("throws on a non-OK response", async () => {
|
||||
vi.mocked(safeFetch).mockResolvedValue(jsonResponse({}, false, 400));
|
||||
const config = getOidcConfig()!;
|
||||
await expect(
|
||||
exchangeCodeForTokens({
|
||||
metadata: METADATA_DOC,
|
||||
config,
|
||||
code: "bad-code",
|
||||
codeVerifier: "verifier-1",
|
||||
redirectUri: "https://healthlog.example.com/api/auth/oidc/callback",
|
||||
}),
|
||||
).rejects.toThrow(/token exchange failed/);
|
||||
});
|
||||
|
||||
it("throws when the response is missing id_token", async () => {
|
||||
vi.mocked(safeFetch).mockResolvedValue(
|
||||
jsonResponse({ access_token: "at" }),
|
||||
);
|
||||
const config = getOidcConfig()!;
|
||||
await expect(
|
||||
exchangeCodeForTokens({
|
||||
metadata: METADATA_DOC,
|
||||
config,
|
||||
code: "code",
|
||||
codeVerifier: "verifier",
|
||||
redirectUri: "https://healthlog.example.com/api/auth/oidc/callback",
|
||||
}),
|
||||
).rejects.toThrow(/missing id_token/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("verifyIdToken", () => {
|
||||
beforeEach(() => configureEnv());
|
||||
|
||||
it("returns the identity claims on success", async () => {
|
||||
// Test payloads deliberately omit the full JWTVerifyResult shape.
|
||||
vi.mocked(mockJwtVerify).mockResolvedValue({
|
||||
payload: {
|
||||
sub: "user-sub-1",
|
||||
email: "person@example.com",
|
||||
email_verified: true,
|
||||
name: "Person",
|
||||
nonce: "nonce-1",
|
||||
},
|
||||
} as never);
|
||||
const config = getOidcConfig()!;
|
||||
const identity = await verifyIdToken({
|
||||
metadata: METADATA_DOC,
|
||||
config,
|
||||
idToken: "id-token",
|
||||
nonce: "nonce-1",
|
||||
});
|
||||
expect(identity).toEqual({
|
||||
sub: "user-sub-1",
|
||||
email: "person@example.com",
|
||||
emailVerified: true,
|
||||
name: "Person",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a nonce mismatch", async () => {
|
||||
vi.mocked(mockJwtVerify).mockResolvedValue({
|
||||
payload: { sub: "user-sub-1", nonce: "wrong-nonce" },
|
||||
} as never);
|
||||
const config = getOidcConfig()!;
|
||||
await expect(
|
||||
verifyIdToken({
|
||||
metadata: METADATA_DOC,
|
||||
config,
|
||||
idToken: "id-token",
|
||||
nonce: "nonce-1",
|
||||
}),
|
||||
).rejects.toThrow(/nonce mismatch/);
|
||||
});
|
||||
|
||||
it("rejects a token missing sub", async () => {
|
||||
vi.mocked(mockJwtVerify).mockResolvedValue({
|
||||
payload: { nonce: "nonce-1" },
|
||||
} as never);
|
||||
const config = getOidcConfig()!;
|
||||
await expect(
|
||||
verifyIdToken({
|
||||
metadata: METADATA_DOC,
|
||||
config,
|
||||
idToken: "id-token",
|
||||
nonce: "nonce-1",
|
||||
}),
|
||||
).rejects.toThrow(/missing sub claim/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fetchUserinfoEmail", () => {
|
||||
it("returns the userinfo email on success", async () => {
|
||||
vi.mocked(safeFetch).mockResolvedValue(
|
||||
jsonResponse({ email: "fallback@example.com", email_verified: true }),
|
||||
);
|
||||
const result = await fetchUserinfoEmail({
|
||||
metadata: METADATA_DOC,
|
||||
accessToken: "at-1",
|
||||
});
|
||||
expect(result).toEqual({
|
||||
email: "fallback@example.com",
|
||||
emailVerified: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("fails soft (null email) when the endpoint is missing or errors", async () => {
|
||||
const noEndpoint = await fetchUserinfoEmail({
|
||||
metadata: { ...METADATA_DOC, userinfo_endpoint: undefined },
|
||||
accessToken: "at-1",
|
||||
});
|
||||
expect(noEndpoint).toEqual({ email: null, emailVerified: undefined });
|
||||
|
||||
vi.mocked(safeFetch).mockRejectedValue(new Error("network down"));
|
||||
const onError = await fetchUserinfoEmail({
|
||||
metadata: METADATA_DOC,
|
||||
accessToken: "at-1",
|
||||
});
|
||||
expect(onError).toEqual({ email: null, emailVerified: undefined });
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveUniqueUsername", () => {
|
||||
it("sanitises the email local-part into a valid username", async () => {
|
||||
const exists = vi.fn().mockResolvedValue(false);
|
||||
const username = await deriveUniqueUsername(
|
||||
"j.doe+sso@example.com",
|
||||
exists,
|
||||
);
|
||||
expect(username).toMatch(/^[a-zA-Z0-9_-]+$/);
|
||||
expect(username.length).toBeGreaterThanOrEqual(3);
|
||||
expect(username.length).toBeLessThanOrEqual(30);
|
||||
});
|
||||
|
||||
it("appends a numeric suffix on collision", async () => {
|
||||
const exists = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValueOnce(false);
|
||||
const username = await deriveUniqueUsername("taken@example.com", exists);
|
||||
expect(username).toBe("taken2");
|
||||
expect(exists).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("pads a too-short local-part up to the 3-char minimum", async () => {
|
||||
const exists = vi.fn().mockResolvedValue(false);
|
||||
const username = await deriveUniqueUsername("a@example.com", exists);
|
||||
expect(username.length).toBeGreaterThanOrEqual(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* Shared between `/api/auth/oidc/login` (writer) and `/api/auth/oidc/callback`
|
||||
* (reader) — the encrypted, single-use blob carrying `{state, nonce,
|
||||
* codeVerifier, next}` across the browser round-trip to the IdP and back.
|
||||
*/
|
||||
export const OIDC_STATE_COOKIE = "oidc_auth_state";
|
||||
export const OIDC_STATE_TTL_MS = 10 * 60 * 1000;
|
||||
@@ -0,0 +1,353 @@
|
||||
/**
|
||||
* OpenID Connect (OIDC) relying-party login. A single, env-configured
|
||||
* provider (Authentik / Keycloak / Authelia / Google Workspace / etc.) — no
|
||||
* per-provider database table, matching the Polar/Oura/Strava "shared app
|
||||
* from env" convention. Discovery, PKCE, and token exchange are hand-rolled
|
||||
* over `safeFetch` (same convention as the Codex OAuth client and the MCP
|
||||
* OAuth server) rather than pulling in a full OAuth/OIDC framework; `jose`
|
||||
* is used only for JWKS fetch + ID-token signature/claims verification,
|
||||
* which is not worth hand-rolling.
|
||||
*/
|
||||
import { createRemoteJWKSet, jwtVerify } from "jose";
|
||||
import { safeFetch } from "@/lib/safe-fetch";
|
||||
import { sanitizeSameOriginPath } from "@/lib/url-safety";
|
||||
|
||||
export interface OidcConfig {
|
||||
issuerUrl: string;
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
scopes: string;
|
||||
buttonLabel: string;
|
||||
}
|
||||
|
||||
/** `||`, not `??`: the compose whitelist materialises an unset var as `""`. */
|
||||
function envOrEmpty(name: string): string {
|
||||
return process.env[name] || "";
|
||||
}
|
||||
|
||||
export function isOidcConfigured(): boolean {
|
||||
return Boolean(
|
||||
envOrEmpty("OIDC_ISSUER_URL") &&
|
||||
envOrEmpty("OIDC_CLIENT_ID") &&
|
||||
envOrEmpty("OIDC_CLIENT_SECRET"),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `OIDC_ONLY` only takes effect when the provider is actually fully
|
||||
* configured — a truthy flag with a half-set (or unset) provider group
|
||||
* must never lock every user out of the app, so it silently falls back to
|
||||
* "additive" rather than hiding password/passkey login.
|
||||
*
|
||||
* Enforced server-side on every password/passkey auth route (`/api/auth/
|
||||
* login`, `/api/auth/register`, `/api/auth/passkey/{login-options,
|
||||
* login-verify}`) — the login page hiding those buttons is not the
|
||||
* boundary. There is currently no OIDC-compatible login flow for the
|
||||
* native iOS client (it authenticates via password/passkey only, see
|
||||
* `src/lib/auth/native-client.ts`), so turning this on locks the iOS app
|
||||
* out of authentication entirely until a native SSO flow exists. Documented
|
||||
* in `.env.production.example`; check before recommending this to an
|
||||
* operator running the iOS app.
|
||||
*/
|
||||
export function isOidcOnly(): boolean {
|
||||
return isOidcConfigured() && envOrEmpty("OIDC_ONLY").toLowerCase() === "true";
|
||||
}
|
||||
|
||||
export function getOidcConfig(): OidcConfig | null {
|
||||
if (!isOidcConfigured()) return null;
|
||||
return {
|
||||
issuerUrl: envOrEmpty("OIDC_ISSUER_URL").replace(/\/+$/, ""),
|
||||
clientId: envOrEmpty("OIDC_CLIENT_ID"),
|
||||
clientSecret: envOrEmpty("OIDC_CLIENT_SECRET"),
|
||||
scopes: envOrEmpty("OIDC_SCOPES") || "openid email profile",
|
||||
buttonLabel: envOrEmpty("OIDC_BUTTON_LABEL") || "Single Sign-On",
|
||||
};
|
||||
}
|
||||
|
||||
export function getOidcRedirectUri(): string {
|
||||
return `${process.env.NEXT_PUBLIC_APP_URL}/api/auth/oidc/callback`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a caller-supplied post-login `next` path against the request's own
|
||||
* origin and only accept it if it stays there — see
|
||||
* `sanitizeSameOriginPath` for why a plain `startsWith` check isn't enough.
|
||||
*/
|
||||
export function sanitizeOidcNextPath(
|
||||
next: string | null,
|
||||
requestUrl: string,
|
||||
): string {
|
||||
return sanitizeSameOriginPath(next, requestUrl);
|
||||
}
|
||||
|
||||
export interface OidcMetadata {
|
||||
issuer: string;
|
||||
authorization_endpoint: string;
|
||||
token_endpoint: string;
|
||||
jwks_uri: string;
|
||||
userinfo_endpoint?: string;
|
||||
}
|
||||
|
||||
interface MetadataCacheEntry {
|
||||
metadata: OidcMetadata;
|
||||
fetchedAt: number;
|
||||
}
|
||||
|
||||
const METADATA_TTL_MS = 10 * 60 * 1000;
|
||||
let metadataCache: MetadataCacheEntry | null = null;
|
||||
let metadataInFlight: Promise<OidcMetadata> | null = null;
|
||||
let jwksCache: {
|
||||
issuerUrl: string;
|
||||
jwks: ReturnType<typeof createRemoteJWKSet>;
|
||||
} | null = null;
|
||||
|
||||
export function _resetOidcCacheForTests(): void {
|
||||
metadataCache = null;
|
||||
metadataInFlight = null;
|
||||
jwksCache = null;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch + validate the provider's `.well-known/openid-configuration`.
|
||||
* Module-level cached (10 min TTL) with in-flight de-dup so concurrent
|
||||
* logins don't stampede the discovery endpoint. The doc's own `issuer`
|
||||
* claim must match the configured issuer URL (RFC 8414 §3.3) — a
|
||||
* mismatch means the provider is misconfigured or something is spoofing
|
||||
* the discovery response.
|
||||
*/
|
||||
export async function discoverOidcMetadata(
|
||||
config: OidcConfig,
|
||||
): Promise<OidcMetadata> {
|
||||
const now = Date.now();
|
||||
if (metadataCache && now - metadataCache.fetchedAt < METADATA_TTL_MS) {
|
||||
return metadataCache.metadata;
|
||||
}
|
||||
if (metadataInFlight) return metadataInFlight;
|
||||
|
||||
metadataInFlight = (async () => {
|
||||
try {
|
||||
const res = await safeFetch(
|
||||
`${config.issuerUrl}/.well-known/openid-configuration`,
|
||||
{ method: "GET", headers: { Accept: "application/json" } },
|
||||
);
|
||||
if (!res.ok) {
|
||||
throw new Error(`discovery request failed: ${res.status}`);
|
||||
}
|
||||
const json: unknown = await res.json();
|
||||
if (
|
||||
!isRecord(json) ||
|
||||
typeof json.issuer !== "string" ||
|
||||
typeof json.authorization_endpoint !== "string" ||
|
||||
typeof json.token_endpoint !== "string" ||
|
||||
typeof json.jwks_uri !== "string"
|
||||
) {
|
||||
throw new Error("discovery document missing required fields");
|
||||
}
|
||||
if (json.issuer !== config.issuerUrl) {
|
||||
throw new Error(
|
||||
`discovery issuer mismatch: expected ${config.issuerUrl}, got ${json.issuer}`,
|
||||
);
|
||||
}
|
||||
const metadata: OidcMetadata = {
|
||||
issuer: json.issuer,
|
||||
authorization_endpoint: json.authorization_endpoint,
|
||||
token_endpoint: json.token_endpoint,
|
||||
jwks_uri: json.jwks_uri,
|
||||
userinfo_endpoint:
|
||||
typeof json.userinfo_endpoint === "string"
|
||||
? json.userinfo_endpoint
|
||||
: undefined,
|
||||
};
|
||||
metadataCache = { metadata, fetchedAt: Date.now() };
|
||||
return metadata;
|
||||
} finally {
|
||||
metadataInFlight = null;
|
||||
}
|
||||
})();
|
||||
|
||||
return metadataInFlight;
|
||||
}
|
||||
|
||||
function getJwks(metadata: OidcMetadata) {
|
||||
if (jwksCache && jwksCache.issuerUrl === metadata.issuer) {
|
||||
return jwksCache.jwks;
|
||||
}
|
||||
// `jose`'s own fetch to the trusted, discovery-supplied `jwks_uri` is a
|
||||
// deliberate, scoped exception to the safe-fetch-required convention —
|
||||
// the target host comes from the operator-configured issuer, never from
|
||||
// user input, and the ESLint rule only lints project source, not
|
||||
// library internals.
|
||||
const jwks = createRemoteJWKSet(new URL(metadata.jwks_uri));
|
||||
jwksCache = { issuerUrl: metadata.issuer, jwks };
|
||||
return jwks;
|
||||
}
|
||||
|
||||
export function buildAuthorizationUrl(params: {
|
||||
metadata: OidcMetadata;
|
||||
config: OidcConfig;
|
||||
state: string;
|
||||
nonce: string;
|
||||
codeChallenge: string;
|
||||
redirectUri: string;
|
||||
}): string {
|
||||
const url = new URL(params.metadata.authorization_endpoint);
|
||||
url.search = new URLSearchParams({
|
||||
response_type: "code",
|
||||
client_id: params.config.clientId,
|
||||
redirect_uri: params.redirectUri,
|
||||
scope: params.config.scopes,
|
||||
state: params.state,
|
||||
nonce: params.nonce,
|
||||
code_challenge: params.codeChallenge,
|
||||
code_challenge_method: "S256",
|
||||
}).toString();
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
interface OidcTokenResponse {
|
||||
id_token?: string;
|
||||
access_token?: string;
|
||||
token_type?: string;
|
||||
expires_in?: number;
|
||||
}
|
||||
|
||||
export async function exchangeCodeForTokens(params: {
|
||||
metadata: OidcMetadata;
|
||||
config: OidcConfig;
|
||||
code: string;
|
||||
codeVerifier: string;
|
||||
redirectUri: string;
|
||||
}): Promise<OidcTokenResponse> {
|
||||
const res = await safeFetch(params.metadata.token_endpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
Accept: "application/json",
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
grant_type: "authorization_code",
|
||||
code: params.code,
|
||||
redirect_uri: params.redirectUri,
|
||||
client_id: params.config.clientId,
|
||||
client_secret: params.config.clientSecret,
|
||||
code_verifier: params.codeVerifier,
|
||||
}).toString(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`token exchange failed: ${res.status}`);
|
||||
}
|
||||
const json: unknown = await res.json();
|
||||
if (!isRecord(json) || typeof json.id_token !== "string") {
|
||||
throw new Error("token response missing id_token");
|
||||
}
|
||||
return json as OidcTokenResponse;
|
||||
}
|
||||
|
||||
export interface OidcIdentity {
|
||||
sub: string;
|
||||
email: string | null;
|
||||
emailVerified: boolean | undefined;
|
||||
name: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify the ID token's signature (against the provider's live JWKS),
|
||||
* `iss`, `aud`, and `exp`, then confirm the `nonce` claim matches the one
|
||||
* minted at `/api/auth/oidc/login`. Signature verification matters even
|
||||
* though this token arrived over a direct back-channel HTTPS call to the
|
||||
* token endpoint (not a browser-relayed redirect) — it's still the
|
||||
* documented defense against a provider-side key-confusion attack.
|
||||
*/
|
||||
export async function verifyIdToken(params: {
|
||||
metadata: OidcMetadata;
|
||||
config: OidcConfig;
|
||||
idToken: string;
|
||||
nonce: string;
|
||||
}): Promise<OidcIdentity> {
|
||||
const jwks = getJwks(params.metadata);
|
||||
const { payload } = await jwtVerify(params.idToken, jwks, {
|
||||
issuer: params.metadata.issuer,
|
||||
audience: params.config.clientId,
|
||||
});
|
||||
|
||||
if (typeof payload.sub !== "string" || !payload.sub) {
|
||||
throw new Error("id token missing sub claim");
|
||||
}
|
||||
if (payload.nonce !== params.nonce) {
|
||||
throw new Error("id token nonce mismatch");
|
||||
}
|
||||
|
||||
return {
|
||||
sub: payload.sub,
|
||||
email: typeof payload.email === "string" ? payload.email : null,
|
||||
emailVerified:
|
||||
typeof payload.email_verified === "boolean"
|
||||
? payload.email_verified
|
||||
: undefined,
|
||||
name: typeof payload.name === "string" ? payload.name : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback for providers that omit `email` from the ID token's granted
|
||||
* scopes but expose it via userinfo. Best-effort: any failure here just
|
||||
* leaves the identity's email null and the caller rejects the login.
|
||||
*/
|
||||
export async function fetchUserinfoEmail(params: {
|
||||
metadata: OidcMetadata;
|
||||
accessToken: string;
|
||||
}): Promise<{ email: string | null; emailVerified: boolean | undefined }> {
|
||||
if (!params.metadata.userinfo_endpoint) {
|
||||
return { email: null, emailVerified: undefined };
|
||||
}
|
||||
try {
|
||||
const res = await safeFetch(params.metadata.userinfo_endpoint, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Bearer ${params.accessToken}`,
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
if (!res.ok) return { email: null, emailVerified: undefined };
|
||||
const json: unknown = await res.json();
|
||||
if (!isRecord(json)) return { email: null, emailVerified: undefined };
|
||||
return {
|
||||
email: typeof json.email === "string" ? json.email : null,
|
||||
emailVerified:
|
||||
typeof json.email_verified === "boolean"
|
||||
? json.email_verified
|
||||
: undefined,
|
||||
};
|
||||
} catch {
|
||||
return { email: null, emailVerified: undefined };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a `registerSchema`-valid username (`^[a-zA-Z0-9_-]+$`, 3-30 chars)
|
||||
* from an auto-provisioned SSO account's email local-part, de-duped via the
|
||||
* caller-supplied existence check. DB-free and pure so it's unit-testable
|
||||
* without a Prisma mock; the callback route supplies `exists` bound to
|
||||
* `prisma.user.findUnique`.
|
||||
*/
|
||||
export async function deriveUniqueUsername(
|
||||
email: string,
|
||||
exists: (candidate: string) => Promise<boolean>,
|
||||
): Promise<string> {
|
||||
const localPart = email.split("@")[0] ?? "user";
|
||||
let base = localPart.replace(/[^a-zA-Z0-9_-]/g, "");
|
||||
if (base.length < 3) base = `${base}user`.slice(0, 3).padEnd(3, "0");
|
||||
base = base.slice(0, 26); // leave room for a numeric suffix up to 30 chars
|
||||
|
||||
let candidate = base;
|
||||
let suffix = 0;
|
||||
while (await exists(candidate)) {
|
||||
suffix += 1;
|
||||
candidate = `${base}${suffix}`;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
@@ -14,6 +14,7 @@ export const authKeys = {
|
||||
*/
|
||||
authMe: () => ["auth", "me"] as const,
|
||||
authRegistrationStatus: () => ["auth", "registration-status"] as const,
|
||||
authOidcStatus: () => ["auth", "oidc", "status"] as const,
|
||||
/**
|
||||
* v1.4.40 W-RSC — Settings → AI surfaces and the targets editor
|
||||
* subscribe to the user-thresholds API. Centralise the key so a
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Isomorphic (client + server) — no `node:crypto`/`jose`/server-only imports,
|
||||
* so client components can pull this in without dragging server auth code
|
||||
* into the browser bundle.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Resolve a caller-supplied "redirect back to" path against a base URL and
|
||||
* only accept it if it stays on that origin. A plain `startsWith("/") &&
|
||||
* !startsWith("//")` string check is not enough — WHATWG URL parsing treats
|
||||
* a leading backslash as a path separator for special schemes, so a value
|
||||
* like `/\evil.com` passes that check but resolves off-origin (confirmed:
|
||||
* `router.push()` on such a value drives Next.js's client router into a
|
||||
* real cross-origin `location.assign()`, not just client-side History
|
||||
* state). Resolving through `new URL()` first and comparing the real
|
||||
* origin closes that class of bypass instead of pattern-matching the raw
|
||||
* string.
|
||||
*/
|
||||
export function sanitizeSameOriginPath(
|
||||
next: string | null | undefined,
|
||||
baseUrl: string,
|
||||
): string {
|
||||
if (!next) return "/";
|
||||
try {
|
||||
const resolved = new URL(next, baseUrl);
|
||||
const base = new URL(baseUrl);
|
||||
if (resolved.origin !== base.origin) return "/";
|
||||
return `${resolved.pathname}${resolved.search}${resolved.hash}`;
|
||||
} catch {
|
||||
return "/";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user