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,354 @@
import {
Account as AccountSchema,
RolePermission,
} from "@versia/client/schemas";
import { ApiError } from "@versia-server/kit";
import { 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 } from "hono-openapi";
import { validator } from "hono-openapi/zod";
import { SignJWT } from "jose";
import { z } from "zod";
import { randomString } from "@/math.ts";
import type { PluginType } from "../../index.ts";
import { automaticOidcFlow } from "../../utils.ts";
export default (plugin: PluginType): void => {
plugin.registerRoute("/oauth/sso/{issuer}/callback", (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",
},
},
}),
plugin.middleware,
validator(
"param",
z.object({
issuer: z.string(),
}),
handleZodError,
),
validator(
"query",
z.object({
client_id: z.string().optional(),
flow: z.string(),
link: z
.string()
.transform((v) =>
["true", "1", "on"].includes(v.toLowerCase()),
)
.optional(),
user_id: z.string().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 = context
.get("pluginConfig")
.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 (context.get("pluginConfig").allow_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(context.get("pluginConfig").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,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,92 @@
import { 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 } 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("/oauth/revoke", (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(),
plugin.middleware,
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,137 @@
import { 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 { validator } from "hono-openapi/zod";
import {
calculatePKCECodeChallenge,
discoveryRequest,
generateRandomCodeVerifier,
processDiscoveryResponse,
} from "oauth4webapi";
import { z } from "zod";
import type { PluginType } from "../../index.ts";
import { oauthRedirectUri } from "../../utils.ts";
export default (plugin: PluginType): void => {
plugin.registerRoute("/oauth/sso", (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",
},
},
}),
plugin.middleware,
validator(
"query",
z.object({
issuer: z.string(),
client_id: z.string().optional(),
redirect_uri: z.string().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 = context
.get("pluginConfig")
.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,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,206 @@
import { 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 } 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("/oauth/token", (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(),
plugin.middleware,
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.string().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,
);
},
);
});
};