refactor: ♻️ Rewrite build system to fit the monorepo architecture
Some checks failed
Mirror to Codeberg / Mirror (push) Failing after 0s
Test Publish / build (client) (push) Failing after 1s
Test Publish / build (sdk) (push) Failing after 0s

This commit is contained in:
Jesse Wierzbinski 2025-07-04 06:29:43 +02:00
parent 7de4b573e3
commit 90b6399407
No known key found for this signature in database
217 changed files with 2143 additions and 1858 deletions

View file

@ -0,0 +1,38 @@
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();
});
// /api/v1/sso/:id
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,152 @@
import { RolePermission } from "@versia/client/schemas";
import { ApiError } from "@versia-server/kit";
import { 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 } from "hono-openapi";
import { resolver, validator } from "hono-openapi/zod";
import { z } from "zod";
import type { PluginType } from "../../../index.ts";
export default (plugin: PluginType): void => {
plugin.registerRoute("/api/v1/sso/:id", (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],
}),
plugin.middleware,
validator("param", z.object({ id: z.string() }), handleZodError),
async (context) => {
const { id: issuerId } = context.req.valid("param");
const { user } = context.get("auth");
const issuer = context
.get("pluginConfig")
.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],
}),
plugin.middleware,
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 = context
.get("pluginConfig")
.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,171 @@
import { RolePermission } from "@versia/client/schemas";
import { ApiError } from "@versia-server/kit";
import { 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 } from "hono-openapi";
import { resolver, validator } from "hono-openapi/zod";
import {
calculatePKCECodeChallenge,
generateRandomCodeVerifier,
} from "oauth4webapi";
import { z } from "zod";
import type { PluginType } from "../../index.ts";
import { oauthDiscoveryRequest, oauthRedirectUri } from "../../utils.ts";
export default (plugin: PluginType): void => {
plugin.registerRoute("/api/v1/sso", (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],
}),
plugin.middleware,
async (context) => {
const { user } = context.get("auth");
const linkedAccounts = await user.getLinkedOidcAccounts(
context.get("pluginConfig").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],
}),
plugin.middleware,
validator("json", z.object({ issuer: z.string() }), handleZodError),
async (context) => {
const { user } = context.get("auth");
const { issuer: issuerId } = context.req.valid("json");
const issuer = context
.get("pluginConfig")
.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()}`,
);
},
);
});
};