refactor: 🔥 Remove plugin functionality, move OpenID plugin to core

This commit is contained in:
Jesse Wierzbinski 2025-07-07 05:52:11 +02:00
parent 278bf960cb
commit b5e9e35427
No known key found for this signature in database
45 changed files with 1502 additions and 2304 deletions

View file

@ -97,30 +97,7 @@ export default apiRoute((app) =>
handleZodError,
),
async (context) => {
const oidcConfig = config.plugins?.config?.["@versia/openid"] as
| {
forced: boolean;
providers: {
id: string;
name: string;
icon: string;
}[];
keys: {
private: string;
public: string;
};
}
| undefined;
if (!oidcConfig) {
return returnError(
context,
"invalid_request",
"The OpenID Connect plugin is not enabled on this instance. Cannot process login request.",
);
}
if (oidcConfig?.forced) {
if (config.authentication.forced_openid) {
return returnError(
context,
"invalid_request",
@ -166,15 +143,6 @@ export default apiRoute((app) =>
);
}
// Try and import the key
const privateKey = await crypto.subtle.importKey(
"pkcs8",
Buffer.from(oidcConfig?.keys?.private ?? "", "base64"),
"Ed25519",
false,
["sign"],
);
// Generate JWT
const jwt = await new SignJWT({
sub: user.id,
@ -185,7 +153,7 @@ export default apiRoute((app) =>
nbf: Math.floor(Date.now() / 1000),
})
.setProtectedHeader({ alg: "EdDSA" })
.sign(privateKey);
.sign(config.authentication.keys.private);
const application = await Application.fromClientId(client_id);

View file

@ -0,0 +1,394 @@
import { afterAll, describe, expect, test } from "bun:test";
import { RolePermission } from "@versia/client/schemas";
import { config } from "@versia-server/config";
import { Application } from "@versia-server/kit/db";
import { fakeRequest, getTestUsers } from "@versia-server/tests";
import { randomUUIDv7 } from "bun";
import { SignJWT } from "jose";
import { randomString } from "@/math";
const { deleteUsers, tokens, users } = await getTestUsers(1);
const application = await Application.insert({
id: randomUUIDv7(),
clientId: "test-client-id",
redirectUri: "https://example.com/callback",
scopes: "openid profile email",
name: "Test Application",
secret: "test-secret",
});
afterAll(async () => {
await deleteUsers();
await application.delete();
});
describe("/oauth/authorize", () => {
test("should authorize and redirect with valid inputs", async () => {
const jwt = await new SignJWT({
sub: users[0].id,
iss: config.http.base_url.origin,
aud: application.data.clientId,
exp: Math.floor(Date.now() / 1000) + 60 * 60,
iat: Math.floor(Date.now() / 1000),
nbf: Math.floor(Date.now() / 1000),
})
.setProtectedHeader({ alg: "EdDSA" })
.sign(config.authentication.keys.private);
const response = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: `jwt=${jwt}`,
},
body: JSON.stringify({
client_id: application.data.clientId,
redirect_uri: application.data.redirectUri,
response_type: "code",
scope: application.data.scopes,
state: "test-state",
code_challenge: randomString(43),
code_challenge_method: "S256",
}),
});
expect(response.status).toBe(302);
const location = new URL(
response.headers.get("Location") ?? "",
config.http.base_url,
);
const params = new URLSearchParams(location.search);
expect(location.origin + location.pathname).toBe(
application.data.redirectUri,
);
expect(params.get("code")).toBeTruthy();
expect(params.get("state")).toBe("test-state");
});
test("should return error for invalid JWT", async () => {
const response = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: "jwt=invalid-jwt",
},
body: JSON.stringify({
client_id: application.data.clientId,
redirect_uri: application.data.redirectUri,
response_type: "code",
scope: application.data.scopes,
state: "test-state",
code_challenge: randomString(43),
code_challenge_method: "S256",
}),
});
expect(response.status).toBe(302);
const location = new URL(
response.headers.get("Location") ?? "",
config.http.base_url,
);
const params = new URLSearchParams(location.search);
expect(params.get("error")).toBe("invalid_request");
expect(params.get("error_description")).toBe(
"Invalid JWT: could not verify",
);
});
test("should return error for missing required fields in JWT", async () => {
const jwt = await new SignJWT({
sub: users[0].id,
iss: config.http.base_url.origin,
aud: application.data.clientId,
})
.setProtectedHeader({ alg: "EdDSA" })
.sign(config.authentication.keys.private);
const response = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: `jwt=${jwt}`,
},
body: JSON.stringify({
client_id: application.data.clientId,
redirect_uri: application.data.redirectUri,
response_type: "code",
scope: application.data.scopes,
state: "test-state",
code_challenge: randomString(43),
code_challenge_method: "S256",
}),
});
expect(response.status).toBe(302);
const location = new URL(
response.headers.get("Location") ?? "",
config.http.base_url,
);
const params = new URLSearchParams(location.search);
expect(params.get("error")).toBe("invalid_request");
expect(params.get("error_description")).toBe(
"Invalid JWT: missing required fields (aud, sub, exp, iss)",
);
});
test("should return error for user not found", async () => {
const jwt = await new SignJWT({
sub: "non-existent-user",
aud: application.data.clientId,
exp: Math.floor(Date.now() / 1000) + 60 * 60,
iss: config.http.base_url.origin,
iat: Math.floor(Date.now() / 1000),
nbf: Math.floor(Date.now() / 1000),
})
.setProtectedHeader({ alg: "EdDSA" })
.sign(config.authentication.keys.private);
const response = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: `jwt=${jwt}`,
},
body: JSON.stringify({
client_id: application.data.clientId,
redirect_uri: application.data.redirectUri,
response_type: "code",
scope: application.data.scopes,
state: "test-state",
code_challenge: randomString(43),
code_challenge_method: "S256",
}),
});
expect(response.status).toBe(302);
const location = new URL(
response.headers.get("Location") ?? "",
config.http.base_url,
);
const params = new URLSearchParams(location.search);
expect(params.get("error")).toBe("invalid_request");
expect(params.get("error_description")).toBe(
"Invalid JWT: sub is not a valid user ID",
);
const jwt2 = await new SignJWT({
sub: "23e42862-d5df-49a8-95b5-52d8c6a11aea",
aud: application.data.clientId,
exp: Math.floor(Date.now() / 1000) + 60 * 60,
iss: config.http.base_url.origin,
iat: Math.floor(Date.now() / 1000),
nbf: Math.floor(Date.now() / 1000),
})
.setProtectedHeader({ alg: "EdDSA" })
.sign(config.authentication.keys.private);
const response2 = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: `jwt=${jwt2}`,
},
body: JSON.stringify({
client_id: application.data.clientId,
redirect_uri: application.data.redirectUri,
response_type: "code",
scope: application.data.scopes,
state: "test-state",
code_challenge: randomString(43),
code_challenge_method: "S256",
}),
});
expect(response2.status).toBe(302);
const location2 = new URL(
response2.headers.get("Location") ?? "",
config.http.base_url,
);
const params2 = new URLSearchParams(location2.search);
expect(params2.get("error")).toBe("invalid_request");
expect(params2.get("error_description")).toBe(
"Invalid JWT, could not find associated user",
);
});
test("should return error for user missing required permissions", async () => {
const oldPermissions = config.permissions.default;
config.permissions.default = [];
const jwt = await new SignJWT({
sub: users[0].id,
iss: config.http.base_url.origin,
aud: application.data.clientId,
exp: Math.floor(Date.now() / 1000) + 60 * 60,
iat: Math.floor(Date.now() / 1000),
nbf: Math.floor(Date.now() / 1000),
})
.setProtectedHeader({ alg: "EdDSA" })
.sign(config.authentication.keys.private);
const response = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: `jwt=${jwt}`,
},
body: JSON.stringify({
client_id: application.data.clientId,
redirect_uri: application.data.redirectUri,
response_type: "code",
scope: application.data.scopes,
state: "test-state",
code_challenge: randomString(43),
code_challenge_method: "S256",
}),
});
expect(response.status).toBe(302);
const location = new URL(
response.headers.get("Location") ?? "",
config.http.base_url,
);
const params = new URLSearchParams(location.search);
expect(params.get("error")).toBe("unauthorized");
expect(params.get("error_description")).toBe(
`User missing required '${RolePermission.OAuth}' permission`,
);
config.permissions.default = oldPermissions;
});
test("should return error for invalid client_id", async () => {
const jwt = await new SignJWT({
sub: users[0].id,
aud: "invalid-client-id",
iss: config.http.base_url.origin,
exp: Math.floor(Date.now() / 1000) + 60 * 60,
iat: Math.floor(Date.now() / 1000),
nbf: Math.floor(Date.now() / 1000),
})
.setProtectedHeader({ alg: "EdDSA" })
.sign(config.authentication.keys.private);
const response = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: `jwt=${jwt}`,
},
body: JSON.stringify({
client_id: "invalid-client-id",
redirect_uri: application.data.redirectUri,
response_type: "code",
scope: application.data.scopes,
state: "test-state",
code_challenge: randomString(43),
code_challenge_method: "S256",
}),
});
expect(response.status).toBe(302);
const location = new URL(
response.headers.get("Location") ?? "",
config.http.base_url,
);
const params = new URLSearchParams(location.search);
expect(params.get("error")).toBe("invalid_request");
expect(params.get("error_description")).toBe(
"Invalid client_id: no associated API application found",
);
});
test("should return error for invalid redirect_uri", async () => {
const jwt = await new SignJWT({
sub: users[0].id,
iss: config.http.base_url.origin,
aud: application.data.clientId,
exp: Math.floor(Date.now() / 1000) + 60 * 60,
iat: Math.floor(Date.now() / 1000),
nbf: Math.floor(Date.now() / 1000),
})
.setProtectedHeader({ alg: "EdDSA" })
.sign(config.authentication.keys.private);
const response = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: `jwt=${jwt}`,
},
body: JSON.stringify({
client_id: application.data.clientId,
redirect_uri: "https://invalid.com/callback",
response_type: "code",
scope: application.data.scopes,
state: "test-state",
code_challenge: randomString(43),
code_challenge_method: "S256",
}),
});
expect(response.status).toBe(302);
const location = new URL(
response.headers.get("Location") ?? "",
config.http.base_url,
);
const params = new URLSearchParams(location.search);
expect(params.get("error")).toBe("invalid_request");
expect(params.get("error_description")).toBe(
"Invalid redirect_uri: does not match API application's redirect_uri",
);
});
test("should return error for invalid scope", async () => {
const jwt = await new SignJWT({
sub: users[0].id,
iss: config.http.base_url.origin,
aud: application.data.clientId,
exp: Math.floor(Date.now() / 1000) + 60 * 60,
iat: Math.floor(Date.now() / 1000),
nbf: Math.floor(Date.now() / 1000),
})
.setProtectedHeader({ alg: "EdDSA" })
.sign(config.authentication.keys.private);
const response = await fakeRequest("/oauth/authorize", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
Cookie: `jwt=${jwt}`,
},
body: JSON.stringify({
client_id: application.data.clientId,
redirect_uri: application.data.redirectUri,
response_type: "code",
scope: "invalid-scope",
state: "test-state",
code_challenge: randomString(43),
code_challenge_method: "S256",
}),
});
expect(response.status).toBe(302);
const location = new URL(
response.headers.get("Location") ?? "",
config.http.base_url,
);
const params = new URLSearchParams(location.search);
expect(params.get("error")).toBe("invalid_request");
expect(params.get("error_description")).toBe(
"Invalid scope: not a subset of the application's scopes",
);
});
});

View file

@ -0,0 +1,277 @@
import { RolePermission } from "@versia/client/schemas";
import { config } from "@versia-server/config";
import {
apiRoute,
auth,
handleZodError,
jsonOrForm,
} from "@versia-server/kit/api";
import { Application, Token, User } from "@versia-server/kit/db";
import { randomUUIDv7 } from "bun";
import { describeRoute, validator } from "hono-openapi";
import { type JWTPayload, jwtVerify, SignJWT } from "jose";
import { JOSEError } from "jose/errors";
import { z } from "zod/v4";
import { randomString } from "@/math";
import { errorRedirect, errors } from "../../../plugins/openid/errors.ts";
export default apiRoute((app) =>
app.post(
"/oauth/authorize",
describeRoute({
summary: "Main OpenID authorization endpoint",
tags: ["OpenID"],
responses: {
302: {
description: "Redirect to the application",
},
},
}),
auth({
auth: false,
}),
jsonOrForm(),
validator(
"query",
z.object({
prompt: z
.enum(["none", "login", "consent", "select_account"])
.optional()
.default("none"),
max_age: z.coerce
.number()
.int()
.optional()
.default(60 * 60 * 24 * 7),
}),
handleZodError,
),
validator(
"json",
z
.object({
scope: z.string().optional(),
redirect_uri: z
.url()
.optional()
.or(z.literal("urn:ietf:wg:oauth:2.0:oob")),
response_type: z.enum([
"code",
"token",
"none",
"id_token",
"code id_token",
"code token",
"token id_token",
"code token id_token",
]),
client_id: z.string(),
state: z.string().optional(),
code_challenge: z.string().optional(),
code_challenge_method: z.enum(["plain", "S256"]).optional(),
})
.refine(
// Check if redirect_uri is valid for code flow
(data) =>
data.response_type.includes("code")
? data.redirect_uri
: true,
"redirect_uri is required for code flow",
),
// Disable for Mastodon API compatibility
/* .refine(
// Check if code_challenge is valid for code flow
(data) =>
data.response_type.includes("code")
? data.code_challenge
: true,
"code_challenge is required for code flow",
), */
handleZodError,
),
validator(
"cookie",
z.object({
jwt: z.string(),
}),
handleZodError,
),
async (context) => {
const { scope, redirect_uri, client_id, state } =
context.req.valid("json");
const { jwt } = context.req.valid("cookie");
const errorSearchParams = new URLSearchParams(
context.req.valid("json"),
);
const result = await jwtVerify(
jwt,
config.authentication.keys.public,
{
algorithms: ["EdDSA"],
audience: client_id,
issuer: new URL(context.get("config").http.base_url).origin,
},
).catch((error) => {
if (error instanceof JOSEError) {
return null;
}
throw error;
});
if (!result) {
return errorRedirect(
context,
errors.InvalidJWT,
errorSearchParams,
);
}
const {
payload: { aud, sub, exp },
} = result;
if (!(aud && sub && exp)) {
return errorRedirect(
context,
errors.MissingJWTFields,
errorSearchParams,
);
}
if (!z.uuid().safeParse(sub).success) {
return errorRedirect(
context,
errors.InvalidSub,
errorSearchParams,
);
}
const user = await User.fromId(sub);
if (!user) {
return errorRedirect(
context,
errors.UserNotFound,
errorSearchParams,
);
}
if (!user.hasPermission(RolePermission.OAuth)) {
return errorRedirect(
context,
errors.MissingOauthPermission,
errorSearchParams,
);
}
const application = await Application.fromClientId(client_id);
if (!application) {
return errorRedirect(
context,
errors.MissingApplication,
errorSearchParams,
);
}
if (application.data.redirectUri !== redirect_uri) {
return errorRedirect(
context,
errors.InvalidRedirectUri,
errorSearchParams,
);
}
// Check that scopes are a subset of the application's scopes
if (
scope &&
!scope
.split(" ")
.every((s) => application.data.scopes.includes(s))
) {
return errorRedirect(
context,
errors.InvalidScope,
errorSearchParams,
);
}
const code = randomString(256, "base64url");
let payload: JWTPayload = {};
if (scope) {
if (scope.split(" ").includes("openid")) {
payload = {
...payload,
sub: user.id,
iss: new URL(context.get("config").http.base_url)
.origin,
aud: client_id,
exp: Math.floor(Date.now() / 1000) + 60 * 60,
iat: Math.floor(Date.now() / 1000),
nbf: Math.floor(Date.now() / 1000),
};
}
if (scope.split(" ").includes("profile")) {
payload = {
...payload,
name: user.data.displayName,
preferred_username: user.data.username,
picture: user.getAvatarUrl().href,
updated_at: new Date(user.data.updatedAt).toISOString(),
};
}
if (scope.split(" ").includes("email")) {
payload = {
...payload,
email: user.data.email,
// TODO: Add verification system
email_verified: true,
};
}
}
const idToken = await new SignJWT(payload)
.setProtectedHeader({ alg: "EdDSA" })
.sign(config.authentication.keys.private);
await Token.insert({
id: randomUUIDv7(),
accessToken: randomString(64, "base64url"),
code,
scope: scope ?? application.data.scopes,
tokenType: "Bearer",
applicationId: application.id,
redirectUri: redirect_uri ?? application.data.redirectUri,
expiresAt: new Date(
Date.now() + 60 * 60 * 24 * 14,
).toISOString(),
idToken: ["profile", "email", "openid"].some((s) =>
scope?.split(" ").includes(s),
)
? idToken
: null,
clientId: client_id,
userId: user.id,
});
const redirectUri =
redirect_uri === "urn:ietf:wg:oauth:2.0:oob"
? new URL(
"/oauth/code",
context.get("config").http.base_url,
)
: new URL(redirect_uri ?? application.data.redirectUri);
redirectUri.searchParams.append("code", code);
state && redirectUri.searchParams.append("state", state);
return context.redirect(redirectUri.toString());
},
),
);

View file

@ -0,0 +1,138 @@
import { afterAll, describe, expect, test } from "bun:test";
import { Application, Token } from "@versia-server/kit/db";
import { fakeRequest, getTestUsers } from "@versia-server/tests";
import { randomUUIDv7 } from "bun";
const { deleteUsers, users } = await getTestUsers(1);
const application = await Application.insert({
id: randomUUIDv7(),
clientId: "test-client-id",
redirectUri: "https://example.com/callback",
scopes: "openid profile email",
secret: "test-secret",
name: "Test Application",
});
const token = await Token.insert({
id: randomUUIDv7(),
code: "test-code",
redirectUri: application.data.redirectUri,
clientId: application.data.clientId,
accessToken: "test-access-token",
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
createdAt: new Date().toISOString(),
tokenType: "Bearer",
scope: application.data.scopes,
userId: users[0].id,
applicationId: application.id,
});
afterAll(async () => {
await deleteUsers();
await application.delete();
await token.delete();
});
describe("/oauth/revoke", () => {
test("should revoke token with valid inputs", async () => {
const response = await fakeRequest("/oauth/revoke", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
client_id: application.data.clientId,
client_secret: application.data.secret,
token: "test-access-token",
}),
});
expect(response.status).toBe(200);
const body = await response.json();
expect(body).toEqual({});
});
test("should return error for missing token", async () => {
const response = await fakeRequest("/oauth/revoke", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
client_id: application.data.clientId,
client_secret: application.data.secret,
}),
});
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe("unauthorized_client");
expect(body.error_description).toBe(
"You are not authorized to revoke this token",
);
});
test("should return error for invalid client credentials", async () => {
const response = await fakeRequest("/oauth/revoke", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
client_id: application.data.clientId,
client_secret: "invalid-secret",
token: "test-access-token",
}),
});
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe("unauthorized_client");
expect(body.error_description).toBe(
"You are not authorized to revoke this token",
);
});
test("should return error for token not found", async () => {
const response = await fakeRequest("/oauth/revoke", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
client_id: application.data.clientId,
client_secret: application.data.secret,
token: "invalid-token",
}),
});
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe("unauthorized_client");
expect(body.error_description).toBe(
"You are not authorized to revoke this token",
);
});
test("should return error for unauthorized client", async () => {
const response = await fakeRequest("/oauth/revoke", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
client_id: "unauthorized-client-id",
client_secret: application.data.secret,
token: "test-access-token",
}),
});
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe("unauthorized_client");
expect(body.error_description).toBe(
"You are not authorized to revoke this token",
);
});
});

View file

@ -0,0 +1,87 @@
import { apiRoute, handleZodError, jsonOrForm } from "@versia-server/kit/api";
import { db, Token } from "@versia-server/kit/db";
import { Tokens } from "@versia-server/kit/tables";
import { and, eq } from "drizzle-orm";
import { describeRoute, resolver, validator } from "hono-openapi";
import { z } from "zod/v4";
export default apiRoute((app) => {
app.post(
"/oauth/revoke",
describeRoute({
summary: "Revoke token",
tags: ["OpenID"],
responses: {
200: {
description: "Token deleted",
content: {
"application/json": {
schema: resolver(z.object({})),
},
},
},
401: {
description: "Authorization error",
content: {
"application/json": {
schema: resolver(
z.object({
error: z.string(),
error_description: z.string(),
}),
),
},
},
},
},
}),
jsonOrForm(),
validator(
"json",
z.object({
client_id: z.string(),
client_secret: z.string(),
token: z.string().optional(),
}),
handleZodError,
),
async (context) => {
const { client_id, client_secret, token } =
context.req.valid("json");
const foundToken = await Token.fromSql(
and(
eq(Tokens.accessToken, token ?? ""),
eq(Tokens.clientId, client_id),
),
);
if (!(foundToken && token)) {
return context.json(
{
error: "unauthorized_client",
error_description:
"You are not authorized to revoke this token",
},
401,
);
}
// Check if the client secret is correct
if (foundToken.data.application?.secret !== client_secret) {
return context.json(
{
error: "unauthorized_client",
error_description:
"You are not authorized to revoke this token",
},
401,
);
}
await db.delete(Tokens).where(eq(Tokens.accessToken, token));
return context.json({}, 200);
},
);
});

View file

@ -0,0 +1,130 @@
import { config } from "@versia-server/config";
import { apiRoute, handleZodError } from "@versia-server/kit/api";
import { Application, db } from "@versia-server/kit/db";
import { OpenIdLoginFlows } from "@versia-server/kit/tables";
import { randomUUIDv7 } from "bun";
import { describeRoute, validator } from "hono-openapi";
import {
calculatePKCECodeChallenge,
discoveryRequest,
generateRandomCodeVerifier,
processDiscoveryResponse,
} from "oauth4webapi";
import { z } from "zod/v4";
import { oauthRedirectUri } from "../../../plugins/openid/utils.ts";
export default apiRoute((app) => {
app.get(
"/oauth/sso",
describeRoute({
summary: "Initiate SSO login flow",
tags: ["OpenID"],
responses: {
302: {
description:
"Redirect to SSO login, or redirect to login page with error",
},
},
}),
validator(
"query",
z.object({
issuer: z.string(),
client_id: z.string().optional(),
redirect_uri: z.url().optional(),
scope: z.string().optional(),
response_type: z.enum(["code"]).optional(),
}),
handleZodError,
),
async (context) => {
// This is the Versia client's client_id, not the external OAuth provider's client_id
const { issuer: issuerId, client_id } = context.req.valid("query");
const errorSearchParams = new URLSearchParams(
context.req.valid("query"),
);
if (!client_id || client_id === "undefined") {
errorSearchParams.append("error", "invalid_request");
errorSearchParams.append(
"error_description",
"client_id is required",
);
return context.redirect(
`${context.get("config").frontend.routes.login}?${errorSearchParams.toString()}`,
);
}
const issuer = config.authentication.openid_providers.find(
(provider) => provider.id === issuerId,
);
if (!issuer) {
errorSearchParams.append("error", "invalid_request");
errorSearchParams.append(
"error_description",
"issuer is invalid",
);
return context.redirect(
`${context.get("config").frontend.routes.login}?${errorSearchParams.toString()}`,
);
}
const issuerUrl = new URL(issuer.url);
const authServer = await discoveryRequest(issuerUrl, {
algorithm: "oidc",
}).then((res) => processDiscoveryResponse(issuerUrl, res));
const codeVerifier = generateRandomCodeVerifier();
const application = await Application.fromClientId(client_id);
if (!application) {
errorSearchParams.append("error", "invalid_request");
errorSearchParams.append(
"error_description",
"client_id is invalid",
);
return context.redirect(
`${context.get("config").frontend.routes.login}?${errorSearchParams.toString()}`,
);
}
// Store into database
const newFlow = (
await db
.insert(OpenIdLoginFlows)
.values({
id: randomUUIDv7(),
codeVerifier,
applicationId: application.id,
issuerId,
})
.returning()
)[0];
const codeChallenge =
await calculatePKCECodeChallenge(codeVerifier);
return context.redirect(
`${authServer.authorization_endpoint}?${new URLSearchParams({
client_id: issuer.client_id,
redirect_uri: `${oauthRedirectUri(
context.get("config").http.base_url,
issuerId,
)}?flow=${newFlow.id}`,
response_type: "code",
scope: "openid profile email",
// PKCE
code_challenge_method: "S256",
code_challenge: codeChallenge,
}).toString()}`,
);
},
);
});

View file

@ -0,0 +1,341 @@
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";
import { db, Media, Token, User } from "@versia-server/kit/db";
import { searchManager } from "@versia-server/kit/search";
import { OpenIdAccounts, Users } from "@versia-server/kit/tables";
import { randomUUIDv7 } from "bun";
import { and, eq, isNull, type SQL } from "drizzle-orm";
import { setCookie } from "hono/cookie";
import { describeRoute, validator } from "hono-openapi";
import { SignJWT } from "jose";
import { z } from "zod/v4";
import { randomString } from "@/math.ts";
import { automaticOidcFlow } from "../../../../../plugins/openid/utils.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",
},
},
}),
validator(
"param",
z.object({
issuer: z.string(),
}),
handleZodError,
),
validator(
"query",
z.object({
client_id: z.string().optional(),
flow: z.string(),
link: zBoolean.optional(),
user_id: z.uuid().optional(),
}),
handleZodError,
),
async (context) => {
const currentUrl = new URL(context.req.url);
const redirectUrl = new URL(context.req.url);
// Correct some reverse proxies incorrectly setting the protocol as http, even if the original request was https
// Looking at you, Traefik
if (
new URL(context.get("config").http.base_url).protocol ===
"https:" &&
currentUrl.protocol === "http:"
) {
currentUrl.protocol = "https:";
redirectUrl.protocol = "https:";
}
// Remove state query parameter from URL
currentUrl.searchParams.delete("state");
redirectUrl.searchParams.delete("state");
// Remove issuer query parameter from URL (can cause redirect URI mismatches)
redirectUrl.searchParams.delete("iss");
redirectUrl.searchParams.delete("code");
const { issuer: issuerParam } = context.req.valid("param");
const { flow: flowId, user_id, link } = context.req.valid("query");
const issuer = config.authentication.openid_providers.find(
(provider) => provider.id === issuerParam,
);
if (!issuer) {
throw new ApiError(404, "Issuer not found");
}
const userInfo = await automaticOidcFlow(
issuer,
flowId,
currentUrl,
redirectUrl,
(error, message, flow) => {
const errorSearchParams = new URLSearchParams(
Object.entries({
redirect_uri: flow?.application?.redirectUri,
client_id: flow?.application?.clientId,
response_type: "code",
scope: flow?.application?.scopes,
}).filter(([_, value]) => value !== undefined) as [
string,
string,
][],
);
errorSearchParams.append("error", error);
errorSearchParams.append("error_description", message);
return context.redirect(
`${context.get("config").frontend.routes.login}?${errorSearchParams.toString()}`,
);
},
);
if (userInfo instanceof Response) {
return userInfo;
}
const { sub, email, preferred_username, picture } =
userInfo.userInfo;
const flow = userInfo.flow;
const errorSearchParams = new URLSearchParams(
Object.entries({
redirect_uri: flow.application?.redirectUri,
client_id: flow.application?.clientId,
response_type: "code",
scope: flow.application?.scopes,
}).filter(([_, value]) => value !== undefined) as [
string,
string,
][],
);
// If linking account
if (link && user_id) {
// Check if userId is equal to application.clientId
if (!flow.application?.clientId.startsWith(user_id)) {
return context.redirect(
`${context.get("config").http.base_url}${
context.get("config").frontend.routes.home
}?${new URLSearchParams({
oidc_account_linking_error: "Account linking error",
oidc_account_linking_error_message: `User ID does not match application client ID (${user_id} != ${flow.application?.clientId})`,
})}`,
);
}
// 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) {
return context.redirect(
`${context.get("config").http.base_url}${
context.get("config").frontend.routes.home
}?${new URLSearchParams({
oidc_account_linking_error:
"Account already linked",
oidc_account_linking_error_message:
"This account has already been linked to this OpenID Connect provider.",
})}`,
);
}
// 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 {
errorSearchParams.append("error", "invalid_request");
errorSearchParams.append(
"error_description",
"No user found with that account",
);
return context.redirect(
`${context.get("config").frontend.routes.login}?${errorSearchParams.toString()}`,
);
}
}
const user = await User.fromId(userId);
if (!user) {
errorSearchParams.append("error", "invalid_request");
errorSearchParams.append(
"error_description",
"No user found with that account",
);
return context.redirect(
`${context.get("config").frontend.routes.login}?${errorSearchParams.toString()}`,
);
}
if (!user.hasPermission(RolePermission.OAuth)) {
errorSearchParams.append("error", "invalid_request");
errorSearchParams.append(
"error_description",
`User does not have the '${RolePermission.OAuth}' permission`,
);
return context.redirect(
`${context.get("config").frontend.routes.login}?${errorSearchParams.toString()}`,
);
}
if (!flow.application) {
throw new ApiError(500, "Application not found");
}
const code = randomString(32, "hex");
await Token.insert({
id: randomUUIDv7(),
accessToken: randomString(64, "base64url"),
code,
scope: flow.application.scopes,
tokenType: "Bearer",
userId: user.id,
applicationId: flow.application.id,
});
// Generate JWT
const jwt = await new SignJWT({
sub: user.id,
iss: new URL(context.get("config").http.base_url).origin,
aud: flow.application.clientId,
exp: Math.floor(Date.now() / 1000) + 60 * 60,
iat: Math.floor(Date.now() / 1000),
nbf: Math.floor(Date.now() / 1000),
})
.setProtectedHeader({ alg: "EdDSA" })
.sign(config.authentication.keys.private);
// Redirect back to application
setCookie(context, "jwt", jwt, {
httpOnly: true,
secure: true,
sameSite: "strict",
path: "/",
// 2 weeks
maxAge: 60 * 60 * 24 * 14,
});
return context.redirect(
new URL(
`${context.get("config").frontend.routes.consent}?${new URLSearchParams(
{
redirect_uri: flow.application.redirectUri,
code,
client_id: flow.application.clientId,
application: flow.application.name,
website: flow.application.website ?? "",
scope: flow.application.scopes,
response_type: "code",
},
).toString()}`,
context.get("config").http.base_url,
).toString(),
);
},
);
});

View file

@ -0,0 +1,181 @@
import { afterAll, describe, expect, test } from "bun:test";
import { Application, Token } from "@versia-server/kit/db";
import { fakeRequest, getTestUsers } from "@versia-server/tests";
import { randomUUIDv7 } from "bun";
const { deleteUsers, users } = await getTestUsers(1);
const application = await Application.insert({
id: randomUUIDv7(),
clientId: "test-client-id",
redirectUri: "https://example.com/callback",
scopes: "openid profile email",
secret: "test-secret",
name: "Test Application",
});
const token = await Token.insert({
id: randomUUIDv7(),
code: "test-code",
redirectUri: application.data.redirectUri,
clientId: application.data.clientId,
accessToken: "test-access-token",
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
createdAt: new Date().toISOString(),
tokenType: "Bearer",
scope: application.data.scopes,
userId: users[0].id,
});
afterAll(async () => {
await deleteUsers();
await application.delete();
await token.delete();
});
describe("/oauth/token", () => {
test("should return token with valid inputs", async () => {
const response = await fakeRequest("/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "authorization_code",
code: "test-code",
redirect_uri: application.data.redirectUri,
client_id: application.data.clientId,
client_secret: application.data.secret,
}),
});
expect(response.status).toBe(200);
const body = await response.json();
expect(body.access_token).toBe("test-access-token");
expect(body.token_type).toBe("Bearer");
expect(body.expires_in).toBeGreaterThan(0);
});
test("should return error for missing code", async () => {
const response = await fakeRequest("/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "authorization_code",
redirect_uri: application.data.redirectUri,
client_id: application.data.clientId,
client_secret: application.data.secret,
}),
});
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe("invalid_request");
expect(body.error_description).toBe("Code is required");
});
test("should return error for missing redirect_uri", async () => {
const response = await fakeRequest("/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "authorization_code",
code: "test-code",
client_id: application.data.clientId,
client_secret: application.data.secret,
}),
});
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe("invalid_request");
expect(body.error_description).toBe("Redirect URI is required");
});
test("should return error for missing client_id", async () => {
const response = await fakeRequest("/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "authorization_code",
code: "test-code",
redirect_uri: application.data.redirectUri,
client_secret: application.data.secret,
}),
});
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe("invalid_request");
expect(body.error_description).toBe("Client ID is required");
});
test("should return error for invalid client credentials", async () => {
const response = await fakeRequest("/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "authorization_code",
code: "test-code",
redirect_uri: application.data.redirectUri,
client_id: application.data.clientId,
client_secret: "invalid-secret",
}),
});
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe("invalid_client");
expect(body.error_description).toBe("Invalid client credentials");
});
test("should return error for code not found", async () => {
const response = await fakeRequest("/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "authorization_code",
code: "invalid-code",
redirect_uri: application.data.redirectUri,
client_id: application.data.clientId,
client_secret: application.data.secret,
}),
});
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe("invalid_grant");
expect(body.error_description).toBe("Code not found");
});
test("should return error for unsupported grant type", async () => {
const response = await fakeRequest("/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "refresh_token",
code: "test-code",
redirect_uri: application.data.redirectUri,
client_id: application.data.clientId,
client_secret: application.data.secret,
}),
});
expect(response.status).toBe(401);
const body = await response.json();
expect(body.error).toBe("unsupported_grant_type");
expect(body.error_description).toBe("Unsupported grant type");
});
});

View file

@ -0,0 +1,190 @@
import { apiRoute, handleZodError, jsonOrForm } from "@versia-server/kit/api";
import { Application, Token } from "@versia-server/kit/db";
import { Tokens } from "@versia-server/kit/tables";
import { and, eq } from "drizzle-orm";
import { describeRoute, resolver, validator } from "hono-openapi";
import { z } from "zod/v4";
export default apiRoute((app) => {
app.post(
"/oauth/token",
describeRoute({
summary: "Get token",
tags: ["OpenID"],
responses: {
200: {
description: "Token",
content: {
"application/json": {
schema: resolver(
z.object({
access_token: z.string(),
token_type: z.string(),
expires_in: z
.number()
.optional()
.nullable(),
id_token: z.string().optional().nullable(),
refresh_token: z
.string()
.optional()
.nullable(),
scope: z.string().optional(),
created_at: z.number(),
}),
),
},
},
},
401: {
description: "Authorization error",
content: {
"application/json": {
schema: resolver(
z.object({
error: z.string(),
error_description: z.string(),
}),
),
},
},
},
},
}),
jsonOrForm(),
validator(
"json",
z.object({
code: z.string().optional(),
code_verifier: z.string().optional(),
grant_type: z
.enum([
"authorization_code",
"refresh_token",
"client_credentials",
"password",
"urn:ietf:params:oauth:grant-type:device_code",
"urn:ietf:params:oauth:grant-type:token-exchange",
"urn:ietf:params:oauth:grant-type:saml2-bearer",
"urn:openid:params:grant-type:ciba",
])
.default("authorization_code"),
client_id: z.string().optional(),
client_secret: z.string().optional(),
username: z.string().trim().optional(),
password: z.string().trim().optional(),
redirect_uri: z.url().optional(),
refresh_token: z.string().optional(),
scope: z.string().optional(),
assertion: z.string().optional(),
audience: z.string().optional(),
subject_token_type: z.string().optional(),
subject_token: z.string().optional(),
actor_token_type: z.string().optional(),
actor_token: z.string().optional(),
auth_req_id: z.string().optional(),
}),
handleZodError,
),
async (context) => {
const { grant_type, code, redirect_uri, client_id, client_secret } =
context.req.valid("json");
switch (grant_type) {
case "authorization_code": {
if (!code) {
return context.json(
{
error: "invalid_request",
error_description: "Code is required",
},
401,
);
}
if (!redirect_uri) {
return context.json(
{
error: "invalid_request",
error_description: "Redirect URI is required",
},
401,
);
}
if (!client_id) {
return context.json(
{
error: "invalid_request",
error_description: "Client ID is required",
},
401,
);
}
// Verify the client_secret
const client = await Application.fromClientId(client_id);
if (!client || client.data.secret !== client_secret) {
return context.json(
{
error: "invalid_client",
error_description: "Invalid client credentials",
},
401,
);
}
const token = await Token.fromSql(
and(
eq(Tokens.code, code),
eq(Tokens.redirectUri, decodeURI(redirect_uri)),
eq(Tokens.clientId, client_id),
),
);
if (!token) {
return context.json(
{
error: "invalid_grant",
error_description: "Code not found",
},
401,
);
}
// Invalidate the code
await token.update({ code: null });
return context.json(
{
...token.toApi(),
expires_in: token.data.expiresAt
? Math.floor(
(new Date(
token.data.expiresAt,
).getTime() -
Date.now()) /
1000,
)
: null,
id_token: token.data.idToken,
refresh_token: null,
},
200,
);
}
default:
}
return context.json(
{
error: "unsupported_grant_type",
error_description: "Unsupported grant type",
},
401,
);
},
);
});

View file

@ -48,17 +48,6 @@ export default apiRoute((app) =>
const knownDomainsCount = await Instance.getCount();
const oidcConfig = config.plugins?.config?.["@versia/openid"] as
| {
forced?: boolean;
providers?: {
id: string;
name: string;
icon?: string;
}[];
}
| undefined;
const content = await markdownToHtml(
config.instance.extended_description_path?.content ??
"This is a [Versia](https://versia.pub) server with the default extended description.",
@ -121,15 +110,15 @@ export default apiRoute((app) =>
},
version: "4.3.0-alpha.3+glitch",
versia_version: version,
// TODO: Put into plugin directly
sso: {
forced: oidcConfig?.forced ?? false,
providers:
oidcConfig?.providers?.map((p) => ({
forced: config.authentication.forced_openid,
providers: config.authentication.openid_providers.map(
(p) => ({
name: p.name,
icon: p.icon,
icon: p.icon?.href,
id: p.id,
})) ?? [],
}),
),
},
contact_account: (contactAccount as User)?.toApi(),
} satisfies z.infer<typeof InstanceV1Schema>);

View file

@ -0,0 +1,37 @@
import { afterAll, describe, expect, test } from "bun:test";
import { fakeRequest, getTestUsers } from "@versia-server/tests";
const { deleteUsers, tokens } = await getTestUsers(1);
afterAll(async () => {
await deleteUsers();
});
describe("/api/v1/sso/:id", () => {
test("should not find unknown issuer", async () => {
const response = await fakeRequest("/api/v1/sso/unknown", {
method: "GET",
headers: {
Authorization: `Bearer ${tokens[0].data.accessToken}`,
},
});
expect(response.status).toBe(404);
expect(await response.json()).toMatchObject({
error: "Issuer with ID unknown not found in instance's OpenID configuration",
});
const response2 = await fakeRequest("/api/v1/sso/unknown", {
method: "DELETE",
headers: {
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
},
});
expect(response2.status).toBe(404);
expect(await response2.json()).toMatchObject({
error: "Issuer with ID unknown not found in instance's OpenID configuration",
});
});
});

View file

@ -0,0 +1,147 @@
import { RolePermission } from "@versia/client/schemas";
import { config } from "@versia-server/config";
import { ApiError } from "@versia-server/kit";
import { apiRoute, auth, handleZodError } from "@versia-server/kit/api";
import { db } from "@versia-server/kit/db";
import { OpenIdAccounts } from "@versia-server/kit/tables";
import { and, eq, type SQL } from "drizzle-orm";
import { describeRoute, resolver, validator } from "hono-openapi";
import { z } from "zod/v4";
export default apiRoute((app) => {
app.get(
"/api/v1/sso/:id",
describeRoute({
summary: "Get linked account",
tags: ["SSO"],
responses: {
200: {
description: "Linked account",
content: {
"application/json": {
schema: resolver(
z.object({
id: z.string(),
name: z.string(),
icon: z.string().optional(),
}),
),
},
},
},
404: ApiError.accountNotFound().schema,
},
}),
auth({
auth: true,
permissions: [RolePermission.OAuth],
}),
validator("param", z.object({ id: z.string() }), handleZodError),
async (context) => {
const { id: issuerId } = context.req.valid("param");
const { user } = context.get("auth");
const issuer = config.authentication.openid_providers.find(
(provider) => provider.id === issuerId,
);
if (!issuer) {
return context.json(
{
error: `Issuer with ID ${issuerId} not found in instance's OpenID configuration`,
},
404,
);
}
const account = await db.query.OpenIdAccounts.findFirst({
where: (account): SQL | undefined =>
and(
eq(account.userId, user.id),
eq(account.issuerId, issuerId),
),
});
if (!account) {
throw new ApiError(
404,
"Account not found or is not linked to this issuer",
);
}
return context.json(
{
id: issuer.id,
name: issuer.name,
icon: issuer.icon?.proxied,
},
200,
);
},
);
app.delete(
"/api/v1/sso/:id",
describeRoute({
summary: "Unlink account",
tags: ["SSO"],
responses: {
204: {
description: "Account unlinked",
},
404: {
description: "Account not found",
content: {
"application/json": {
schema: resolver(ApiError.zodSchema),
},
},
},
},
}),
auth({
auth: true,
permissions: [RolePermission.OAuth],
}),
validator("param", z.object({ id: z.string() }), handleZodError),
async (context) => {
const { id: issuerId } = context.req.valid("param");
const { user } = context.get("auth");
// Check if issuer exists
const issuer = config.authentication.openid_providers.find(
(provider) => provider.id === issuerId,
);
if (!issuer) {
return context.json(
{
error: `Issuer with ID ${issuerId} not found in instance's OpenID configuration`,
},
404,
);
}
const account = await db.query.OpenIdAccounts.findFirst({
where: (account): SQL | undefined =>
and(
eq(account.userId, user.id),
eq(account.issuerId, issuerId),
),
});
if (!account) {
throw new ApiError(
404,
"Account not found or is not linked to this issuer",
);
}
await db
.delete(OpenIdAccounts)
.where(eq(OpenIdAccounts.id, account.id));
return context.body(null, 204);
},
);
});

View file

@ -0,0 +1,45 @@
import { afterAll, describe, expect, test } from "bun:test";
import { fakeRequest, getTestUsers } from "@versia-server/tests";
const { deleteUsers, tokens } = await getTestUsers(1);
afterAll(async () => {
await deleteUsers();
});
describe("/api/v1/sso", () => {
test("should return empty list", async () => {
const response = await fakeRequest("/api/v1/sso", {
method: "GET",
headers: {
Authorization: `Bearer ${tokens[0].data.accessToken}`,
},
});
expect(response.status).toBe(200);
expect(await response.json()).toMatchObject([]);
});
test("should return an error if provider doesn't exist", async () => {
const response = await fakeRequest("/api/v1/sso", {
method: "POST",
headers: {
Authorization: `Bearer ${tokens[0].data.accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
issuer: "unknown",
}),
});
expect(response.status).toBe(404);
expect(await response.json()).toMatchObject({
error: "Issuer with ID unknown not found in instance's OpenID configuration",
});
});
/*
Unfortunately, we cannot test actual linking, as it requires a valid OpenID provider
setup in config, which we don't have in tests
*/
});

View file

@ -0,0 +1,163 @@
import { RolePermission } from "@versia/client/schemas";
import { config } from "@versia-server/config";
import { ApiError } from "@versia-server/kit";
import { apiRoute, auth, handleZodError } from "@versia-server/kit/api";
import { Application, db } from "@versia-server/kit/db";
import { OpenIdLoginFlows } from "@versia-server/kit/tables";
import { randomUUIDv7 } from "bun";
import { describeRoute, resolver, validator } from "hono-openapi";
import {
calculatePKCECodeChallenge,
generateRandomCodeVerifier,
} from "oauth4webapi";
import { z } from "zod/v4";
import {
oauthDiscoveryRequest,
oauthRedirectUri,
} from "../../../../plugins/openid/utils.ts";
export default apiRoute((app) => {
app.get(
"/api/v1/sso",
describeRoute({
summary: "Get linked accounts",
tags: ["SSO"],
responses: {
200: {
description: "Linked accounts",
content: {
"application/json": {
schema: resolver(
z.array(
z.object({
id: z.string(),
name: z.string(),
icon: z.string().optional(),
}),
),
),
},
},
},
},
}),
auth({
auth: true,
permissions: [RolePermission.OAuth],
}),
async (context) => {
const { user } = context.get("auth");
const linkedAccounts = await user.getLinkedOidcAccounts(
config.authentication.openid_providers,
);
return context.json(
linkedAccounts.map((account) => ({
id: account.id,
name: account.name,
icon: account.icon,
})),
200,
);
},
);
app.post(
"/api/v1/sso",
describeRoute({
summary: "Link account",
tags: ["SSO"],
responses: {
302: {
description: "Redirect to OpenID provider",
},
404: {
description: "Issuer not found",
content: {
"application/json": {
schema: resolver(ApiError.zodSchema),
},
},
},
},
}),
auth({
auth: true,
permissions: [RolePermission.OAuth],
}),
validator("json", z.object({ issuer: z.string() }), handleZodError),
async (context) => {
const { user } = context.get("auth");
const { issuer: issuerId } = context.req.valid("json");
const issuer = config.authentication.openid_providers.find(
(provider) => provider.id === issuerId,
);
if (!issuer) {
return context.json(
{
error: `Issuer with ID ${issuerId} not found in instance's OpenID configuration`,
},
404,
);
}
const authServer = await oauthDiscoveryRequest(new URL(issuer.url));
const codeVerifier = generateRandomCodeVerifier();
const redirectUri = oauthRedirectUri(
context.get("config").http.base_url,
issuerId,
);
const application = await Application.insert({
id: randomUUIDv7(),
clientId:
user.id +
Buffer.from(
crypto.getRandomValues(new Uint8Array(32)),
).toString("base64"),
name: "Versia",
redirectUri: redirectUri.toString(),
scopes: "openid profile email",
secret: "",
});
// Store into database
const newFlow = (
await db
.insert(OpenIdLoginFlows)
.values({
id: randomUUIDv7(),
codeVerifier,
issuerId,
applicationId: application.id,
})
.returning()
)[0];
const codeChallenge =
await calculatePKCECodeChallenge(codeVerifier);
return context.redirect(
`${authServer.authorization_endpoint}?${new URLSearchParams({
client_id: issuer.client_id,
redirect_uri: `${redirectUri}?${new URLSearchParams({
flow: newFlow.id,
link: "true",
user_id: user.id,
})}`,
response_type: "code",
scope: "openid profile email",
// PKCE
code_challenge_method: "S256",
code_challenge: codeChallenge,
}).toString()}`,
);
},
);
});

View file

@ -39,17 +39,6 @@ export default apiRoute((app) =>
30 * 24 * 60 * 60 * 1000,
);
const oidcConfig = config.plugins?.config?.["@versia/openid"] as
| {
forced?: boolean;
providers?: {
id: string;
name: string;
icon?: string;
}[];
}
| undefined;
// TODO: fill in more values
return context.json({
domain: config.http.base_url.hostname,
@ -162,13 +151,14 @@ export default apiRoute((app) =>
hint: r.hint,
})),
sso: {
forced: oidcConfig?.forced ?? false,
providers:
oidcConfig?.providers?.map((p) => ({
forced: config.authentication.forced_openid,
providers: config.authentication.openid_providers.map(
(p) => ({
name: p.name,
icon: p.icon,
icon: p.icon?.href,
id: p.id,
})) ?? [],
}),
),
},
});
},