2024-09-16 15:29:09 +02:00
|
|
|
import { apiRoute, applyConfig } from "@/api";
|
2024-06-13 07:38:26 +02:00
|
|
|
import { randomString } from "@/math";
|
2024-08-28 17:01:56 +02:00
|
|
|
import { setCookie } from "@hono/hono/cookie";
|
2024-09-16 15:29:09 +02:00
|
|
|
import { createRoute } from "@hono/zod-openapi";
|
2024-06-14 11:05:04 +02:00
|
|
|
import { and, eq, isNull } from "drizzle-orm";
|
2024-08-28 17:01:56 +02:00
|
|
|
import type { Context } from "hono";
|
2024-05-13 06:34:35 +02:00
|
|
|
import { SignJWT } from "jose";
|
2024-05-06 09:16:33 +02:00
|
|
|
import { z } from "zod";
|
2024-06-29 05:50:56 +02:00
|
|
|
import { TokenType } from "~/classes/functions/token";
|
2024-05-29 02:59:49 +02:00
|
|
|
import { db } from "~/drizzle/db";
|
2024-06-14 11:05:04 +02:00
|
|
|
import { RolePermissions, Tokens, Users } from "~/drizzle/schema";
|
2024-05-29 02:59:49 +02:00
|
|
|
import { config } from "~/packages/config-manager";
|
|
|
|
|
import { OAuthManager } from "~/packages/database-interface/oauth";
|
|
|
|
|
import { User } from "~/packages/database-interface/user";
|
2024-05-06 09:16:33 +02:00
|
|
|
|
|
|
|
|
export const meta = applyConfig({
|
|
|
|
|
auth: {
|
|
|
|
|
required: false,
|
|
|
|
|
},
|
|
|
|
|
ratelimits: {
|
|
|
|
|
duration: 60,
|
|
|
|
|
max: 20,
|
|
|
|
|
},
|
2024-05-17 03:49:59 +02:00
|
|
|
route: "/oauth/sso/:issuer/callback",
|
2024-05-06 09:16:33 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
export const schemas = {
|
|
|
|
|
query: z.object({
|
2024-05-17 03:49:59 +02:00
|
|
|
client_id: z.string().optional(),
|
2024-05-06 09:16:33 +02:00
|
|
|
flow: z.string(),
|
2024-05-13 06:34:35 +02:00
|
|
|
link: z
|
|
|
|
|
.string()
|
|
|
|
|
.transform((v) => ["true", "1", "on"].includes(v.toLowerCase()))
|
|
|
|
|
.optional(),
|
|
|
|
|
user_id: z.string().uuid().optional(),
|
2024-05-06 09:16:33 +02:00
|
|
|
}),
|
|
|
|
|
param: z.object({
|
|
|
|
|
issuer: z.string(),
|
|
|
|
|
}),
|
|
|
|
|
};
|
|
|
|
|
|
2024-09-16 15:29:09 +02:00
|
|
|
const route = createRoute({
|
|
|
|
|
method: "get",
|
|
|
|
|
path: "/oauth/sso/{issuer}/callback",
|
|
|
|
|
summary: "SSO callback",
|
|
|
|
|
description:
|
|
|
|
|
"After the user has authenticated to an external OpenID provider, they are redirected here to complete the OAuth flow and get a code",
|
|
|
|
|
request: {
|
|
|
|
|
query: schemas.query,
|
|
|
|
|
params: schemas.param,
|
|
|
|
|
},
|
|
|
|
|
responses: {
|
|
|
|
|
302: {
|
|
|
|
|
description:
|
|
|
|
|
"Redirect to frontend's consent route, or redirect to login page with error",
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
2024-08-28 17:01:56 +02:00
|
|
|
const returnError = (
|
|
|
|
|
context: Context,
|
|
|
|
|
query: object,
|
|
|
|
|
error: string,
|
|
|
|
|
description: string,
|
|
|
|
|
) => {
|
2024-05-06 09:16:33 +02:00
|
|
|
const searchParams = new URLSearchParams();
|
|
|
|
|
|
|
|
|
|
// Add all data that is not undefined except email and password
|
|
|
|
|
for (const [key, value] of Object.entries(query)) {
|
2024-06-13 04:26:43 +02:00
|
|
|
if (key !== "email" && key !== "password" && value !== undefined) {
|
2024-05-06 09:16:33 +02:00
|
|
|
searchParams.append(key, value);
|
2024-06-13 04:26:43 +02:00
|
|
|
}
|
2024-05-06 09:16:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
searchParams.append("error", error);
|
|
|
|
|
searchParams.append("error_description", description);
|
|
|
|
|
|
2024-08-28 17:01:56 +02:00
|
|
|
return context.redirect(
|
|
|
|
|
`${config.frontend.routes.login}?${searchParams.toString()}`,
|
|
|
|
|
);
|
2024-05-06 09:16:33 +02:00
|
|
|
};
|
|
|
|
|
|
2024-08-19 20:06:38 +02:00
|
|
|
export default apiRoute((app) =>
|
2024-09-16 15:29:09 +02:00
|
|
|
app.openapi(route, 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(config.http.base_url).protocol === "https:" &&
|
|
|
|
|
currentUrl.protocol === "http:"
|
|
|
|
|
) {
|
|
|
|
|
currentUrl.protocol = "https:";
|
|
|
|
|
redirectUrl.protocol = "https:";
|
|
|
|
|
}
|
2024-05-06 09:16:33 +02:00
|
|
|
|
2024-09-16 15:29:09 +02:00
|
|
|
// 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 manager = new OAuthManager(issuerParam);
|
|
|
|
|
|
|
|
|
|
const userInfo = await manager.automaticOidcFlow(
|
|
|
|
|
flowId,
|
|
|
|
|
currentUrl,
|
|
|
|
|
redirectUrl,
|
|
|
|
|
(error, message, app) =>
|
|
|
|
|
returnError(
|
|
|
|
|
context,
|
2024-10-03 13:51:19 +02:00
|
|
|
OAuthManager.processOAuth2Error(app),
|
2024-09-16 15:29:09 +02:00
|
|
|
error,
|
|
|
|
|
message,
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (userInfo instanceof Response) {
|
|
|
|
|
return userInfo;
|
|
|
|
|
}
|
2024-05-06 09:16:33 +02:00
|
|
|
|
2024-09-16 15:29:09 +02:00
|
|
|
const { sub, email, preferred_username, picture } = userInfo.userInfo;
|
|
|
|
|
const flow = userInfo.flow;
|
2024-05-06 09:16:33 +02:00
|
|
|
|
2024-09-16 15:29:09 +02:00
|
|
|
// If linking account
|
|
|
|
|
if (link && user_id) {
|
|
|
|
|
return await manager.linkUser(user_id, context, userInfo);
|
|
|
|
|
}
|
2024-05-13 06:34:35 +02:00
|
|
|
|
2024-09-16 15:29:09 +02:00
|
|
|
let userId = (
|
|
|
|
|
await db.query.OpenIdAccounts.findFirst({
|
|
|
|
|
where: (account, { eq, and }) =>
|
|
|
|
|
and(
|
|
|
|
|
eq(account.serverId, sub),
|
|
|
|
|
eq(account.issuerId, manager.issuer.id),
|
|
|
|
|
),
|
|
|
|
|
})
|
|
|
|
|
)?.userId;
|
|
|
|
|
|
|
|
|
|
if (!userId) {
|
|
|
|
|
// Register new user
|
|
|
|
|
if (config.signups.registration && config.oidc.allow_registration) {
|
|
|
|
|
let username =
|
|
|
|
|
preferred_username ??
|
|
|
|
|
email?.split("@")[0] ??
|
|
|
|
|
randomString(8, "hex");
|
|
|
|
|
|
|
|
|
|
const usernameValidator = z
|
|
|
|
|
.string()
|
|
|
|
|
.regex(/^[a-z0-9_]+$/)
|
|
|
|
|
.min(3)
|
|
|
|
|
.max(config.validation.max_username_size)
|
|
|
|
|
.refine(
|
|
|
|
|
(value) =>
|
|
|
|
|
!config.validation.username_blacklist.includes(
|
|
|
|
|
value,
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
.refine((value) =>
|
|
|
|
|
config.filters.username.some((filter) =>
|
|
|
|
|
value.match(filter),
|
2024-05-06 09:16:33 +02:00
|
|
|
),
|
2024-09-16 15:29:09 +02:00
|
|
|
)
|
|
|
|
|
.refine(
|
|
|
|
|
async (value) =>
|
|
|
|
|
!(await User.fromSql(
|
|
|
|
|
and(
|
|
|
|
|
eq(Users.username, value),
|
|
|
|
|
isNull(Users.instanceId),
|
2024-06-14 11:05:04 +02:00
|
|
|
),
|
2024-09-16 15:29:09 +02:00
|
|
|
)),
|
2024-06-14 11:05:04 +02:00
|
|
|
);
|
2024-09-16 15:29:09 +02:00
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
await usernameValidator.parseAsync(username);
|
|
|
|
|
} catch {
|
|
|
|
|
username = randomString(8, "hex");
|
2024-06-14 11:05:04 +02:00
|
|
|
}
|
2024-05-06 09:16:33 +02:00
|
|
|
|
2024-09-16 15:29:09 +02:00
|
|
|
const doesEmailExist = email
|
|
|
|
|
? !!(await User.fromSql(eq(Users.email, email)))
|
|
|
|
|
: false;
|
2024-05-06 09:16:33 +02:00
|
|
|
|
2024-09-16 15:29:09 +02:00
|
|
|
// Create new user
|
|
|
|
|
const user = await User.fromDataLocal({
|
|
|
|
|
email: doesEmailExist ? undefined : email,
|
|
|
|
|
username,
|
|
|
|
|
avatar: picture,
|
|
|
|
|
password: undefined,
|
|
|
|
|
});
|
2024-05-06 09:16:33 +02:00
|
|
|
|
2024-09-16 15:29:09 +02:00
|
|
|
// Link account
|
|
|
|
|
await manager.linkUserInDatabase(user.id, sub);
|
|
|
|
|
|
|
|
|
|
userId = user.id;
|
|
|
|
|
} else {
|
2024-06-08 06:57:29 +02:00
|
|
|
return returnError(
|
2024-08-28 17:01:56 +02:00
|
|
|
context,
|
2024-06-08 06:57:29 +02:00
|
|
|
{
|
|
|
|
|
redirect_uri: flow.application?.redirectUri,
|
|
|
|
|
client_id: flow.application?.clientId,
|
|
|
|
|
response_type: "code",
|
|
|
|
|
scope: flow.application?.scopes,
|
|
|
|
|
},
|
|
|
|
|
"invalid_request",
|
2024-09-16 15:29:09 +02:00
|
|
|
"No user found with that account",
|
2024-06-08 06:57:29 +02:00
|
|
|
);
|
|
|
|
|
}
|
2024-09-16 15:29:09 +02:00
|
|
|
}
|
2024-06-08 06:57:29 +02:00
|
|
|
|
2024-09-16 15:29:09 +02:00
|
|
|
const user = await User.fromId(userId);
|
|
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
|
return returnError(
|
|
|
|
|
context,
|
|
|
|
|
{
|
|
|
|
|
redirect_uri: flow.application?.redirectUri,
|
|
|
|
|
client_id: flow.application?.clientId,
|
|
|
|
|
response_type: "code",
|
|
|
|
|
scope: flow.application?.scopes,
|
|
|
|
|
},
|
|
|
|
|
"invalid_request",
|
|
|
|
|
"No user found with that account",
|
2024-05-06 09:16:33 +02:00
|
|
|
);
|
2024-09-16 15:29:09 +02:00
|
|
|
}
|
2024-05-13 06:01:51 +02:00
|
|
|
|
2024-09-16 15:29:09 +02:00
|
|
|
if (!user.hasPermission(RolePermissions.OAuth)) {
|
|
|
|
|
return returnError(
|
|
|
|
|
context,
|
|
|
|
|
{
|
|
|
|
|
redirect_uri: flow.application?.redirectUri,
|
|
|
|
|
client_id: flow.application?.clientId,
|
|
|
|
|
response_type: "code",
|
|
|
|
|
scope: flow.application?.scopes,
|
|
|
|
|
},
|
|
|
|
|
"invalid_request",
|
|
|
|
|
`User does not have the '${RolePermissions.OAuth}' permission`,
|
2024-08-28 17:01:56 +02:00
|
|
|
);
|
2024-09-16 15:29:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!flow.application) {
|
|
|
|
|
return context.json({ error: "Application not found" }, 500);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const code = randomString(32, "hex");
|
|
|
|
|
|
|
|
|
|
await db.insert(Tokens).values({
|
|
|
|
|
accessToken: randomString(64, "base64url"),
|
2024-10-03 13:41:58 +02:00
|
|
|
code,
|
2024-09-16 15:29:09 +02:00
|
|
|
scope: flow.application.scopes,
|
|
|
|
|
tokenType: TokenType.Bearer,
|
|
|
|
|
userId: user.id,
|
|
|
|
|
applicationId: flow.application.id,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Try and import the key
|
|
|
|
|
const privateKey = await crypto.subtle.importKey(
|
|
|
|
|
"pkcs8",
|
|
|
|
|
Buffer.from(config.oidc.keys?.private ?? "", "base64"),
|
|
|
|
|
"Ed25519",
|
|
|
|
|
false,
|
|
|
|
|
["sign"],
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// Generate JWT
|
|
|
|
|
const jwt = await new SignJWT({
|
|
|
|
|
sub: user.id,
|
|
|
|
|
iss: new URL(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(privateKey);
|
|
|
|
|
|
|
|
|
|
// Redirect back to application
|
|
|
|
|
setCookie(context, "jwt", jwt, {
|
|
|
|
|
httpOnly: true,
|
|
|
|
|
secure: true,
|
|
|
|
|
sameSite: "strict",
|
|
|
|
|
path: "/",
|
|
|
|
|
maxAge: 60 * 60,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return context.redirect(
|
|
|
|
|
new URL(
|
|
|
|
|
`${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()}`,
|
|
|
|
|
config.http.base_url,
|
|
|
|
|
).toString(),
|
|
|
|
|
);
|
|
|
|
|
}),
|
2024-08-19 20:06:38 +02:00
|
|
|
);
|