2025-07-07 05:52:11 +02:00
|
|
|
import {
|
|
|
|
|
Account as AccountSchema,
|
|
|
|
|
RolePermission,
|
|
|
|
|
zBoolean,
|
|
|
|
|
} from "@versia/client/schemas";
|
|
|
|
|
import { config } from "@versia-server/config";
|
|
|
|
|
import { ApiError } from "@versia-server/kit";
|
|
|
|
|
import { apiRoute, handleZodError } from "@versia-server/kit/api";
|
2025-08-21 00:45:58 +02:00
|
|
|
import { db, Media, User } from "@versia-server/kit/db";
|
2025-07-07 05:52:11 +02:00
|
|
|
import { searchManager } from "@versia-server/kit/search";
|
2025-08-21 00:45:58 +02:00
|
|
|
import {
|
|
|
|
|
AuthorizationCodes,
|
|
|
|
|
OpenIdAccounts,
|
|
|
|
|
Users,
|
|
|
|
|
} from "@versia-server/kit/tables";
|
2025-07-07 05:52:11 +02:00
|
|
|
import { randomUUIDv7 } from "bun";
|
|
|
|
|
import { and, eq, isNull, type SQL } from "drizzle-orm";
|
|
|
|
|
import { setCookie } from "hono/cookie";
|
2025-08-21 00:45:58 +02:00
|
|
|
import { sign } from "hono/jwt";
|
2025-07-07 05:52:11 +02:00
|
|
|
import { describeRoute, validator } from "hono-openapi";
|
2025-08-21 00:45:58 +02:00
|
|
|
import * as client from "openid-client";
|
2025-07-07 05:52:11 +02:00
|
|
|
import { z } from "zod/v4";
|
|
|
|
|
import { randomString } from "@/math.ts";
|
|
|
|
|
|
|
|
|
|
export default apiRoute((app) => {
|
|
|
|
|
app.get(
|
|
|
|
|
"/oauth/sso/:issuer/callback",
|
|
|
|
|
describeRoute({
|
|
|
|
|
summary: "SSO callback",
|
|
|
|
|
tags: ["OpenID"],
|
|
|
|
|
description:
|
|
|
|
|
"After the user has authenticated to an external OpenID provider, they are redirected here to complete the OAuth flow and get a code",
|
|
|
|
|
responses: {
|
|
|
|
|
302: {
|
|
|
|
|
description:
|
|
|
|
|
"Redirect to frontend's consent route, or redirect to login page with error",
|
|
|
|
|
},
|
2025-08-21 00:45:58 +02:00
|
|
|
422: ApiError.validationFailed().schema,
|
2025-07-07 05:52:11 +02:00
|
|
|
},
|
|
|
|
|
}),
|
|
|
|
|
validator(
|
|
|
|
|
"param",
|
|
|
|
|
z.object({
|
|
|
|
|
issuer: z.string(),
|
|
|
|
|
}),
|
|
|
|
|
handleZodError,
|
|
|
|
|
),
|
|
|
|
|
validator(
|
|
|
|
|
"query",
|
|
|
|
|
z.object({
|
|
|
|
|
flow: z.string(),
|
2025-08-21 00:45:58 +02:00
|
|
|
link: zBoolean.default(false),
|
2025-07-07 05:52:11 +02:00
|
|
|
user_id: z.uuid().optional(),
|
|
|
|
|
}),
|
|
|
|
|
handleZodError,
|
|
|
|
|
),
|
|
|
|
|
async (context) => {
|
2025-08-21 00:45:58 +02:00
|
|
|
const { issuer: issuerId } = context.req.valid("param");
|
2025-07-07 05:52:11 +02:00
|
|
|
const { flow: flowId, user_id, link } = context.req.valid("query");
|
|
|
|
|
|
|
|
|
|
const issuer = config.authentication.openid_providers.find(
|
2025-08-21 00:45:58 +02:00
|
|
|
(provider) => provider.id === issuerId,
|
2025-07-07 05:52:11 +02:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (!issuer) {
|
2025-08-21 00:45:58 +02:00
|
|
|
throw new ApiError(422, "Unknown or invalid issuer");
|
2025-07-07 05:52:11 +02:00
|
|
|
}
|
|
|
|
|
|
2025-08-21 00:45:58 +02:00
|
|
|
const flow = await db.query.OpenIdLoginFlows.findFirst({
|
|
|
|
|
where: (flow): SQL | undefined => eq(flow.id, flowId),
|
|
|
|
|
with: {
|
|
|
|
|
application: true,
|
|
|
|
|
},
|
|
|
|
|
});
|
2025-07-07 05:52:11 +02:00
|
|
|
|
2025-08-21 00:45:58 +02:00
|
|
|
const redirectWithMessage = (
|
|
|
|
|
parameters: Record<string, string | undefined>,
|
|
|
|
|
route = config.frontend.routes.login,
|
|
|
|
|
) => {
|
|
|
|
|
const searchParams = new URLSearchParams(
|
|
|
|
|
Object.entries(parameters).filter(
|
|
|
|
|
([_, value]) => value !== undefined,
|
|
|
|
|
) as [string, string][],
|
|
|
|
|
);
|
2025-07-07 05:52:11 +02:00
|
|
|
|
2025-08-21 00:45:58 +02:00
|
|
|
return context.redirect(`${route}?${searchParams.toString()}`);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if (!flow) {
|
|
|
|
|
return redirectWithMessage({
|
|
|
|
|
error: "invalid_request",
|
|
|
|
|
error_description: "Invalid flow",
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const oidcConfig = await client.discovery(
|
|
|
|
|
issuer.url,
|
|
|
|
|
issuer.client_id,
|
|
|
|
|
issuer.client_secret,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const tokens = await client.authorizationCodeGrant(
|
|
|
|
|
oidcConfig,
|
|
|
|
|
context.req.raw,
|
|
|
|
|
{
|
|
|
|
|
pkceCodeVerifier: flow.codeVerifier,
|
|
|
|
|
expectedState: flow.state ?? undefined,
|
|
|
|
|
idTokenExpected: true,
|
2025-07-07 05:52:11 +02:00
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
|
2025-08-21 00:45:58 +02:00
|
|
|
const claims = tokens.claims();
|
|
|
|
|
|
|
|
|
|
if (!claims) {
|
|
|
|
|
return redirectWithMessage({
|
|
|
|
|
error: "invalid_request",
|
|
|
|
|
error_description: "Missing or invalid ID token",
|
|
|
|
|
});
|
2025-07-07 05:52:11 +02:00
|
|
|
}
|
|
|
|
|
|
2025-08-21 00:45:58 +02:00
|
|
|
const userInfo = await client.fetchUserInfo(
|
|
|
|
|
oidcConfig,
|
|
|
|
|
tokens.access_token,
|
|
|
|
|
claims.sub,
|
2025-07-07 05:52:11 +02:00
|
|
|
);
|
|
|
|
|
|
2025-08-21 00:45:58 +02:00
|
|
|
const { sub, email, preferred_username, picture } = userInfo;
|
|
|
|
|
|
2025-07-07 05:52:11 +02:00
|
|
|
// If linking account
|
|
|
|
|
if (link && user_id) {
|
|
|
|
|
// Check if userId is equal to application.clientId
|
2025-08-21 00:45:58 +02:00
|
|
|
if (!flow.application?.id.startsWith(user_id)) {
|
|
|
|
|
return redirectWithMessage(
|
|
|
|
|
{
|
2025-07-07 05:52:11 +02:00
|
|
|
oidc_account_linking_error: "Account linking error",
|
2025-08-21 00:45:58 +02:00
|
|
|
oidc_account_linking_error_message: `User ID does not match application client ID (${user_id} != ${flow.application?.id})`,
|
|
|
|
|
},
|
|
|
|
|
config.frontend.routes.home,
|
2025-07-07 05:52:11 +02:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check if account is already linked
|
|
|
|
|
const account = await db.query.OpenIdAccounts.findFirst({
|
|
|
|
|
where: (account): SQL | undefined =>
|
|
|
|
|
and(
|
|
|
|
|
eq(account.serverId, sub),
|
|
|
|
|
eq(account.issuerId, issuer.id),
|
|
|
|
|
),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (account) {
|
2025-08-21 00:45:58 +02:00
|
|
|
return redirectWithMessage(
|
|
|
|
|
{
|
2025-07-07 05:52:11 +02:00
|
|
|
oidc_account_linking_error:
|
|
|
|
|
"Account already linked",
|
|
|
|
|
oidc_account_linking_error_message:
|
|
|
|
|
"This account has already been linked to this OpenID Connect provider.",
|
2025-08-21 00:45:58 +02:00
|
|
|
},
|
|
|
|
|
config.frontend.routes.home,
|
2025-07-07 05:52:11 +02:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Link the account
|
|
|
|
|
await db.insert(OpenIdAccounts).values({
|
|
|
|
|
id: randomUUIDv7(),
|
|
|
|
|
serverId: sub,
|
|
|
|
|
issuerId: issuer.id,
|
|
|
|
|
userId: user_id,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return context.redirect(
|
|
|
|
|
`${context.get("config").http.base_url}${
|
|
|
|
|
context.get("config").frontend.routes.home
|
|
|
|
|
}?${new URLSearchParams({
|
|
|
|
|
oidc_account_linked: "true",
|
|
|
|
|
})}`,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let userId = (
|
|
|
|
|
await db.query.OpenIdAccounts.findFirst({
|
|
|
|
|
where: (account): SQL | undefined =>
|
|
|
|
|
and(
|
|
|
|
|
eq(account.serverId, sub),
|
|
|
|
|
eq(account.issuerId, issuer.id),
|
|
|
|
|
),
|
|
|
|
|
})
|
|
|
|
|
)?.userId;
|
|
|
|
|
|
|
|
|
|
if (!userId) {
|
|
|
|
|
// Register new user
|
|
|
|
|
if (config.authentication.openid_registration) {
|
|
|
|
|
let username =
|
|
|
|
|
preferred_username ??
|
|
|
|
|
email?.split("@")[0] ??
|
|
|
|
|
randomString(8, "hex");
|
|
|
|
|
|
|
|
|
|
const usernameValidator =
|
|
|
|
|
AccountSchema.shape.username.refine(
|
|
|
|
|
async (value) =>
|
|
|
|
|
!(await User.fromSql(
|
|
|
|
|
and(
|
|
|
|
|
eq(Users.username, value),
|
|
|
|
|
isNull(Users.instanceId),
|
|
|
|
|
),
|
|
|
|
|
)),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
await usernameValidator.parseAsync(username);
|
|
|
|
|
} catch {
|
|
|
|
|
username = randomString(8, "hex");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const doesEmailExist = email
|
|
|
|
|
? !!(await User.fromSql(eq(Users.email, email)))
|
|
|
|
|
: false;
|
|
|
|
|
|
|
|
|
|
const avatar = picture
|
|
|
|
|
? await Media.fromUrl(new URL(picture))
|
|
|
|
|
: null;
|
|
|
|
|
|
|
|
|
|
// Create new user
|
|
|
|
|
const user = await User.register(username, {
|
|
|
|
|
email: doesEmailExist ? undefined : email,
|
|
|
|
|
avatar: avatar ?? undefined,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Add to search index
|
|
|
|
|
await searchManager.addUser(user);
|
|
|
|
|
|
|
|
|
|
// Link account
|
|
|
|
|
await db.insert(OpenIdAccounts).values({
|
|
|
|
|
id: randomUUIDv7(),
|
|
|
|
|
serverId: sub,
|
|
|
|
|
issuerId: issuer.id,
|
|
|
|
|
userId: user.id,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
userId = user.id;
|
|
|
|
|
} else {
|
2025-08-21 00:45:58 +02:00
|
|
|
return redirectWithMessage({
|
|
|
|
|
error: "invalid_request",
|
|
|
|
|
error_description: "No user found with that account",
|
|
|
|
|
});
|
2025-07-07 05:52:11 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const user = await User.fromId(userId);
|
|
|
|
|
|
|
|
|
|
if (!user) {
|
2025-08-21 00:45:58 +02:00
|
|
|
return redirectWithMessage({
|
|
|
|
|
error: "invalid_request",
|
|
|
|
|
error_description: "No user found with that account",
|
|
|
|
|
});
|
2025-07-07 05:52:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!user.hasPermission(RolePermission.OAuth)) {
|
2025-08-21 00:45:58 +02:00
|
|
|
return redirectWithMessage({
|
|
|
|
|
error: "invalid_request",
|
|
|
|
|
error_description: `User does not have the '${RolePermission.OAuth}' permission`,
|
|
|
|
|
});
|
2025-07-07 05:52:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!flow.application) {
|
|
|
|
|
throw new ApiError(500, "Application not found");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const code = randomString(32, "hex");
|
|
|
|
|
|
2025-08-21 00:45:58 +02:00
|
|
|
await db.insert(AuthorizationCodes).values({
|
|
|
|
|
clientId: flow.application.id,
|
2025-07-07 05:52:11 +02:00
|
|
|
code,
|
2025-08-21 00:45:58 +02:00
|
|
|
expiresAt: new Date(Date.now() + 60 * 1000).toISOString(), // 1 minute
|
|
|
|
|
redirectUri: flow.clientRedirectUri ?? undefined,
|
2025-07-07 05:52:11 +02:00
|
|
|
userId: user.id,
|
2025-08-21 00:45:58 +02:00
|
|
|
scopes: flow.clientScopes ?? [],
|
2025-07-07 05:52:11 +02:00
|
|
|
});
|
|
|
|
|
|
2025-08-21 00:45:58 +02:00
|
|
|
const jwt = await sign(
|
|
|
|
|
{
|
|
|
|
|
sub: user.id,
|
|
|
|
|
iss: new URL(context.get("config").http.base_url).origin,
|
|
|
|
|
aud: flow.application.id,
|
|
|
|
|
exp: Math.floor(Date.now() / 1000) + 60 * 60,
|
|
|
|
|
iat: Math.floor(Date.now() / 1000),
|
|
|
|
|
nbf: Math.floor(Date.now() / 1000),
|
|
|
|
|
},
|
|
|
|
|
config.authentication.keys.private,
|
|
|
|
|
);
|
2025-07-07 05:52:11 +02:00
|
|
|
|
|
|
|
|
// Redirect back to application
|
|
|
|
|
setCookie(context, "jwt", jwt, {
|
|
|
|
|
httpOnly: true,
|
|
|
|
|
secure: true,
|
|
|
|
|
sameSite: "strict",
|
|
|
|
|
path: "/",
|
|
|
|
|
// 2 weeks
|
|
|
|
|
maxAge: 60 * 60 * 24 * 14,
|
|
|
|
|
});
|
|
|
|
|
|
2025-08-21 00:45:58 +02:00
|
|
|
return redirectWithMessage(
|
|
|
|
|
{
|
|
|
|
|
redirect_uri: flow.clientRedirectUri ?? undefined,
|
|
|
|
|
code,
|
|
|
|
|
client_id: flow.application.id,
|
|
|
|
|
application: flow.application.name,
|
|
|
|
|
website: flow.application.website ?? "",
|
|
|
|
|
scope: flow.clientScopes?.join(" "),
|
|
|
|
|
state: flow.clientState ?? undefined,
|
|
|
|
|
},
|
|
|
|
|
config.frontend.routes.consent,
|
2025-07-07 05:52:11 +02:00
|
|
|
);
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
});
|