2024-05-06 09:16:33 +02:00
|
|
|
import { randomBytes } from "node:crypto";
|
2024-05-29 02:59:49 +02:00
|
|
|
import { applyConfig, handleZodError } from "@/api";
|
|
|
|
|
import { errorResponse, response } from "@/response";
|
2024-05-06 09:16:33 +02:00
|
|
|
import { zValidator } from "@hono/zod-validator";
|
|
|
|
|
import type { Hono } 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-05-29 02:59:49 +02:00
|
|
|
import { TokenType } from "~/database/entities/Token";
|
|
|
|
|
import { db } from "~/drizzle/db";
|
2024-06-08 06:57:29 +02:00
|
|
|
import { RolePermissions, Tokens } 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({
|
|
|
|
|
allowedMethods: ["GET"],
|
|
|
|
|
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(),
|
|
|
|
|
}),
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const returnError = (query: object, error: string, description: string) => {
|
|
|
|
|
const searchParams = new URLSearchParams();
|
|
|
|
|
|
|
|
|
|
// Add all data that is not undefined except email and password
|
|
|
|
|
for (const [key, value] of Object.entries(query)) {
|
|
|
|
|
if (key !== "email" && key !== "password" && value !== undefined)
|
|
|
|
|
searchParams.append(key, value);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
searchParams.append("error", error);
|
|
|
|
|
searchParams.append("error_description", description);
|
|
|
|
|
|
|
|
|
|
return response(null, 302, {
|
2024-05-17 06:05:06 +02:00
|
|
|
Location: `${config.frontend.routes.login}?${searchParams.toString()}`,
|
2024-05-06 09:16:33 +02:00
|
|
|
});
|
|
|
|
|
};
|
|
|
|
|
|
2024-05-17 03:49:59 +02:00
|
|
|
/**
|
|
|
|
|
* OAuth Callback endpoint
|
|
|
|
|
* After the user has authenticated to an external OpenID provider,
|
|
|
|
|
* they are redirected here to complete the OAuth flow and get a code
|
|
|
|
|
*/
|
2024-05-06 09:16:33 +02:00
|
|
|
export default (app: Hono) =>
|
|
|
|
|
app.on(
|
|
|
|
|
meta.allowedMethods,
|
|
|
|
|
meta.route,
|
|
|
|
|
zValidator("query", schemas.query, handleZodError),
|
|
|
|
|
zValidator("param", schemas.param, handleZodError),
|
|
|
|
|
async (context) => {
|
|
|
|
|
const currentUrl = new URL(context.req.url);
|
2024-06-11 04:11:42 +02:00
|
|
|
const redirectUrl = new URL(context.req.url);
|
2024-05-06 09:16:33 +02:00
|
|
|
|
2024-06-11 04:24:32 +02:00
|
|
|
// 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
|
|
|
// Remove state query parameter from URL
|
|
|
|
|
currentUrl.searchParams.delete("state");
|
2024-06-11 04:11:42 +02:00
|
|
|
redirectUrl.searchParams.delete("state");
|
2024-06-11 04:08:57 +02:00
|
|
|
// Remove issuer query parameter from URL (can cause redirect URI mismatches)
|
2024-06-11 04:11:42 +02:00
|
|
|
redirectUrl.searchParams.delete("iss");
|
2024-06-11 04:15:29 +02:00
|
|
|
redirectUrl.searchParams.delete("code");
|
2024-05-06 09:16:33 +02:00
|
|
|
const { issuer: issuerParam } = context.req.valid("param");
|
2024-05-13 06:34:35 +02:00
|
|
|
const { flow: flowId, user_id, link } = context.req.valid("query");
|
2024-05-06 09:16:33 +02:00
|
|
|
|
2024-05-17 03:49:59 +02:00
|
|
|
const manager = new OAuthManager(issuerParam);
|
2024-05-06 09:16:33 +02:00
|
|
|
|
2024-05-17 03:49:59 +02:00
|
|
|
const userInfo = await manager.automaticOidcFlow(
|
|
|
|
|
flowId,
|
2024-05-06 09:16:33 +02:00
|
|
|
currentUrl,
|
2024-06-11 04:11:42 +02:00
|
|
|
redirectUrl,
|
2024-05-17 03:49:59 +02:00
|
|
|
(error, message, app) =>
|
|
|
|
|
returnError(
|
|
|
|
|
{
|
|
|
|
|
...manager.processOAuth2Error(app),
|
|
|
|
|
},
|
|
|
|
|
error,
|
|
|
|
|
message,
|
|
|
|
|
),
|
2024-05-06 09:16:33 +02:00
|
|
|
);
|
|
|
|
|
|
2024-05-17 03:49:59 +02:00
|
|
|
if (userInfo instanceof Response) return userInfo;
|
2024-05-06 09:16:33 +02:00
|
|
|
|
2024-05-17 03:49:59 +02:00
|
|
|
const { sub } = userInfo.userInfo;
|
|
|
|
|
const flow = userInfo.flow;
|
2024-05-06 09:16:33 +02:00
|
|
|
|
2024-05-17 03:49:59 +02:00
|
|
|
// If linking account
|
2024-05-13 06:34:35 +02:00
|
|
|
if (link && user_id) {
|
2024-05-17 03:49:59 +02:00
|
|
|
return await manager.linkUser(user_id, userInfo);
|
2024-05-13 06:34:35 +02:00
|
|
|
}
|
|
|
|
|
|
2024-05-06 09:16:33 +02:00
|
|
|
const userId = (
|
|
|
|
|
await db.query.OpenIdAccounts.findFirst({
|
|
|
|
|
where: (account, { eq, and }) =>
|
|
|
|
|
and(
|
|
|
|
|
eq(account.serverId, sub),
|
2024-05-17 03:49:59 +02:00
|
|
|
eq(account.issuerId, manager.issuer.id),
|
2024-05-06 09:16:33 +02:00
|
|
|
),
|
|
|
|
|
})
|
|
|
|
|
)?.userId;
|
|
|
|
|
|
|
|
|
|
if (!userId) {
|
|
|
|
|
return returnError(
|
2024-05-13 06:01:51 +02:00
|
|
|
{
|
|
|
|
|
redirect_uri: flow.application?.redirectUri,
|
|
|
|
|
client_id: flow.application?.clientId,
|
|
|
|
|
response_type: "code",
|
|
|
|
|
scope: flow.application?.scopes,
|
|
|
|
|
},
|
2024-05-06 09:16:33 +02:00
|
|
|
"invalid_request",
|
|
|
|
|
"No user found with that account",
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const user = await User.fromId(userId);
|
|
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
|
return returnError(
|
2024-05-13 06:01:51 +02:00
|
|
|
{
|
|
|
|
|
redirect_uri: flow.application?.redirectUri,
|
|
|
|
|
client_id: flow.application?.clientId,
|
|
|
|
|
response_type: "code",
|
|
|
|
|
scope: flow.application?.scopes,
|
|
|
|
|
},
|
2024-05-06 09:16:33 +02:00
|
|
|
"invalid_request",
|
|
|
|
|
"No user found with that account",
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-08 06:57:29 +02:00
|
|
|
if (!user.hasPermission(RolePermissions.OAUTH)) {
|
|
|
|
|
return returnError(
|
|
|
|
|
{
|
|
|
|
|
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-05-06 09:16:33 +02:00
|
|
|
if (!flow.application)
|
2024-05-13 06:01:51 +02:00
|
|
|
return errorResponse("Application not found", 500);
|
2024-05-06 09:16:33 +02:00
|
|
|
|
|
|
|
|
const code = randomBytes(32).toString("hex");
|
|
|
|
|
|
|
|
|
|
await db.insert(Tokens).values({
|
|
|
|
|
accessToken: randomBytes(64).toString("base64url"),
|
|
|
|
|
code: code,
|
|
|
|
|
scope: flow.application.scopes,
|
|
|
|
|
tokenType: TokenType.BEARER,
|
|
|
|
|
userId: user.id,
|
|
|
|
|
applicationId: flow.application.id,
|
|
|
|
|
});
|
|
|
|
|
|
2024-05-13 06:01:51 +02:00
|
|
|
// Try and import the key
|
|
|
|
|
const privateKey = await crypto.subtle.importKey(
|
|
|
|
|
"pkcs8",
|
|
|
|
|
Buffer.from(config.oidc.jwt_key.split(";")[0], "base64"),
|
|
|
|
|
"Ed25519",
|
|
|
|
|
false,
|
|
|
|
|
["sign"],
|
2024-05-06 09:16:33 +02:00
|
|
|
);
|
2024-05-13 06:01:51 +02:00
|
|
|
|
|
|
|
|
// 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
|
|
|
|
|
return response(null, 302, {
|
|
|
|
|
Location: new URL(
|
2024-05-17 06:05:06 +02:00
|
|
|
`${config.frontend.routes.consent}?${new URLSearchParams({
|
2024-05-13 06:01:51 +02:00
|
|
|
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(),
|
|
|
|
|
// Set cookie with JWT
|
|
|
|
|
"Set-Cookie": `jwt=${jwt}; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=${
|
|
|
|
|
60 * 60
|
|
|
|
|
}`,
|
|
|
|
|
});
|
2024-05-06 09:16:33 +02:00
|
|
|
},
|
|
|
|
|
);
|