Files
buzz-sheet/lib/auth/sudloh.ts
T

165 lines
8.1 KiB
TypeScript

import "server-only";
import { createHash } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { getDb } from "@/db";
import { accounts, sessions, users } from "@/db/schema";
import { getRedisClient, redisCachePrefix } from "@/lib/redis/client";
import { HttpError } from "@/lib/security/http";
const CHECK_SECONDS = 300;
const ACCOUNT_SETTINGS_URL = "https://account.sudloh.com/account";
export { ACCOUNT_SETTINGS_URL };
type Endpoints = { issuer: string; userinfo_endpoint: string; introspection_endpoint: string };
type BoundToken = { token: string; accountId: string; expiresAt: string };
let discovery: { endpoints: Endpoints; until: number } | undefined;
async function endpoints(): Promise<Endpoints> {
if (discovery && discovery.until > Date.now()) return discovery.endpoints;
const issuer = (process.env.SUDLOH_OIDC_ISSUER || "https://account.sudloh.com/api/auth").replace(/\/$/, "");
const response = await fetch(`${issuer}/.well-known/openid-configuration`, {
cache: "no-store", signal: AbortSignal.timeout(5000),
});
if (!response.ok) throw new HttpError(503, "sudloh-unavailable");
const data: unknown = await response.json();
if (!data || typeof data !== "object" || !("issuer" in data) || data.issuer !== issuer ||
!("userinfo_endpoint" in data) || typeof data.userinfo_endpoint !== "string" ||
!("introspection_endpoint" in data) || typeof data.introspection_endpoint !== "string") {
throw new HttpError(503, "sudloh-discovery-invalid");
}
const result = data as Endpoints;
for (const url of [result.userinfo_endpoint, result.introspection_endpoint]) {
if (new URL(url).origin !== new URL(issuer).origin) throw new HttpError(503, "sudloh-discovery-invalid");
}
discovery = { endpoints: result, until: Date.now() + 10 * 60_000 };
return result;
}
async function userInfo(account: BoundToken) {
const response = await fetch((await endpoints()).userinfo_endpoint, {
headers: { Authorization: `Bearer ${account.token}` },
cache: "no-store", signal: AbortSignal.timeout(5000),
});
if (!response.ok) throw new HttpError(503, "sudloh-unavailable");
const data: unknown = await response.json();
if (!data || typeof data !== "object" ||
!("sub" in data) || data.sub !== account.accountId ||
!("name" in data) || typeof data.name !== "string" ||
!("email" in data) || typeof data.email !== "string" ||
!("email_verified" in data) || data.email_verified !== true ||
!("picture" in data) || typeof data.picture !== "string") {
throw new HttpError(503, "sudloh-profile-invalid");
}
return data as { sub: string; name: string; email: string; email_verified: true; picture: string };
}
async function introspect(account: BoundToken): Promise<boolean> {
const clientId = process.env.SUDLOH_OIDC_CLIENT_ID;
const clientSecret = process.env.SUDLOH_OIDC_CLIENT_SECRET;
if (!clientId || !clientSecret) throw new HttpError(503, "sudloh-not-configured");
const response = await fetch((await endpoints()).introspection_endpoint, {
method: "POST",
headers: {
Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString("base64")}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({ token: account.token, token_type_hint: "access_token" }),
cache: "no-store", signal: AbortSignal.timeout(5000),
});
if (!response.ok) throw new HttpError(503, "sudloh-unavailable");
const data: unknown = await response.json();
if (!data || typeof data !== "object" || !("active" in data) || typeof data.active !== "boolean") {
throw new HttpError(503, "sudloh-introspection-invalid");
}
if (!data.active) return false;
if (!("sub" in data) || data.sub !== account.accountId ||
!("exp" in data) || typeof data.exp !== "number" || data.exp <= Date.now() / 1000) return false;
return true;
}
function bindingKey(sessionId: string) {
return `${redisCachePrefix()}:sudloh:session:${sessionId}`;
}
async function updateProfile(userId: string, token: BoundToken): Promise<boolean> {
const profile = await userInfo(token);
const [current] = await getDb().select({ name: users.name, email: users.email,
emailVerified: users.emailVerified, image: users.image }).from(users).where(eq(users.id, userId)).limit(1);
if (!current) return false;
const email = profile.email.toLowerCase();
if (current.name !== profile.name || current.email !== email ||
!current.emailVerified || current.image !== profile.picture) {
try {
await getDb().update(users).set({ name: profile.name, email,
emailVerified: true, image: profile.picture }).where(eq(users.id, userId));
} catch (cause) {
const dbError = cause && typeof cause === "object" && "cause" in cause ? cause.cause : cause;
if (dbError && typeof dbError === "object" && "code" in dbError && dbError.code === "23505")
throw new HttpError(409, "sudloh-email-conflict");
throw cause;
}
}
return true;
}
export async function refreshLinkedSudlohProfile(userId: string): Promise<void> {
const [account] = await getDb().select().from(accounts).where(and(
eq(accounts.userId, userId), eq(accounts.providerId, "sudloh"),
)).limit(1);
if (!account?.accessToken || !account.accessTokenExpiresAt ||
account.accessTokenExpiresAt.getTime() <= Date.now()) throw new HttpError(401, "sudloh-sign-in-required");
const token: BoundToken = { token: account.accessToken, accountId: account.accountId,
expiresAt: account.accessTokenExpiresAt.toISOString() };
if (!await introspect(token)) throw new HttpError(401, "sudloh-sign-in-required");
if (!await updateProfile(userId, token)) throw new HttpError(401, "unauthorized");
}
export async function bindSudlohSession(userId: string, sessionId: string): Promise<void> {
const [account] = await getDb().select().from(accounts).where(and(
eq(accounts.userId, userId), eq(accounts.providerId, "sudloh"),
)).limit(1);
if (!account?.accessToken || !account.accessTokenExpiresAt) throw new HttpError(503, "sudloh-token-missing");
const seconds = Math.floor((account.accessTokenExpiresAt.getTime() - Date.now()) / 1000);
if (seconds <= 0) throw new HttpError(503, "sudloh-token-expired");
const bound: BoundToken = { token: account.accessToken, accountId: account.accountId,
expiresAt: account.accessTokenExpiresAt.toISOString() };
await (await getRedisClient()).set(bindingKey(sessionId), JSON.stringify(bound), "EX", seconds);
}
export async function validateSudlohSession(userId: string, sessionId: string, force = false): Promise<boolean> {
const [account] = await getDb().select({ id: accounts.id, accountId: accounts.accountId })
.from(accounts).where(and(eq(accounts.userId, userId), eq(accounts.providerId, "sudloh"))).limit(1);
const invalidate = async () => {
await getDb().delete(sessions).where(eq(sessions.id, sessionId));
return false;
};
if (!account) return invalidate();
const redis = await getRedisClient().catch(() => null);
if (!redis) throw new HttpError(503, "sudloh-check-unavailable");
const raw = await redis.get(bindingKey(sessionId)).catch(() => { throw new HttpError(503, "sudloh-check-unavailable"); });
if (!raw) return invalidate();
let bound: BoundToken;
try { bound = JSON.parse(raw) as BoundToken; }
catch { throw new HttpError(503, "sudloh-check-unavailable"); }
if (bound.accountId !== account.accountId || !bound.token ||
!Number.isFinite(Date.parse(bound.expiresAt)) || Date.parse(bound.expiresAt) <= Date.now()) return invalidate();
const digest = createHash("sha256").update(bound.token).digest("hex");
const key = `${redisCachePrefix()}:sudloh:active:${sessionId}:${digest}`;
if (!force && await redis.get(key).catch(() => null) === "1") return true;
try {
if (!await introspect(bound)) return invalidate();
if (!await updateProfile(userId, bound)) return invalidate();
const remaining = Math.floor((Date.parse(bound.expiresAt) - Date.now()) / 1000);
if (remaining > 0) await redis.set(key, "1", "EX", Math.min(CHECK_SECONDS, remaining)).catch(() => undefined);
return true;
} catch (cause) {
if (cause instanceof HttpError) throw cause;
throw new HttpError(503, "sudloh-unavailable");
}
}