2024-08-19 20:06:38 +02:00
|
|
|
import { apiRoute, applyConfig, handleZodError, jsonOrForm } from "@/api";
|
2024-06-13 07:38:26 +02:00
|
|
|
import { randomString } from "@/math";
|
2024-05-29 02:59:49 +02:00
|
|
|
import { response } from "@/response";
|
2024-07-24 19:04:00 +02:00
|
|
|
import { sentry } from "@/sentry";
|
2024-05-06 09:16:33 +02:00
|
|
|
import { zValidator } from "@hono/zod-validator";
|
2024-04-18 11:04:07 +02:00
|
|
|
import { SignJWT, jwtVerify } from "jose";
|
2024-04-18 10:42:12 +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-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 { User } from "~/packages/database-interface/user";
|
2024-04-18 10:42:12 +02:00
|
|
|
|
|
|
|
|
export const meta = applyConfig({
|
|
|
|
|
allowedMethods: ["POST"],
|
|
|
|
|
ratelimits: {
|
|
|
|
|
max: 4,
|
|
|
|
|
duration: 60,
|
|
|
|
|
},
|
|
|
|
|
route: "/oauth/authorize",
|
|
|
|
|
auth: {
|
|
|
|
|
required: false,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
2024-05-06 09:16:33 +02:00
|
|
|
export const schemas = {
|
|
|
|
|
query: z.object({
|
|
|
|
|
prompt: z
|
|
|
|
|
.enum(["none", "login", "consent", "select_account"])
|
|
|
|
|
.optional()
|
|
|
|
|
.default("none"),
|
2024-05-06 10:19:42 +02:00
|
|
|
max_age: z.coerce
|
2024-05-06 09:16:33 +02:00
|
|
|
.number()
|
|
|
|
|
.int()
|
|
|
|
|
.optional()
|
|
|
|
|
.default(60 * 60 * 24 * 7),
|
2024-05-06 10:40:26 +02:00
|
|
|
}),
|
2024-07-11 12:56:28 +02:00
|
|
|
json: z.object({
|
2024-05-06 09:16:33 +02:00
|
|
|
scope: z.string().optional(),
|
2024-05-13 00:24:15 +02:00
|
|
|
redirect_uri: z
|
|
|
|
|
.string()
|
|
|
|
|
.url()
|
|
|
|
|
.optional()
|
|
|
|
|
.or(z.literal("urn:ietf:wg:oauth:2.0:oob")),
|
2024-05-06 09:16:33 +02:00
|
|
|
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(),
|
|
|
|
|
}),
|
|
|
|
|
};
|
2024-04-18 10:42:12 +02:00
|
|
|
|
2024-05-02 06:34:24 +02:00
|
|
|
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)) {
|
2024-06-13 04:26:43 +02:00
|
|
|
if (key !== "email" && key !== "password" && value !== undefined) {
|
2024-05-02 06:34:24 +02:00
|
|
|
searchParams.append(key, value);
|
2024-06-13 04:26:43 +02:00
|
|
|
}
|
2024-05-02 06:34:24 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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-04-18 10:42:12 +02:00
|
|
|
});
|
2024-05-02 06:34:24 +02:00
|
|
|
};
|
2024-04-18 10:42:12 +02:00
|
|
|
|
2024-08-19 20:06:38 +02:00
|
|
|
export default apiRoute((app) =>
|
2024-05-06 09:16:33 +02:00
|
|
|
app.on(
|
|
|
|
|
meta.allowedMethods,
|
|
|
|
|
meta.route,
|
2024-05-12 03:51:01 +02:00
|
|
|
jsonOrForm(),
|
2024-05-06 09:16:33 +02:00
|
|
|
zValidator("query", schemas.query, handleZodError),
|
2024-07-11 12:56:28 +02:00
|
|
|
zValidator("json", schemas.json, handleZodError),
|
2024-05-06 09:16:33 +02:00
|
|
|
async (context) => {
|
2024-05-29 03:14:24 +02:00
|
|
|
const { scope, redirect_uri, response_type, client_id, state } =
|
2024-07-11 12:56:28 +02:00
|
|
|
context.req.valid("json");
|
2024-05-06 10:40:26 +02:00
|
|
|
|
2024-07-11 12:56:28 +02:00
|
|
|
const body = context.req.valid("json");
|
2024-05-06 09:16:33 +02:00
|
|
|
|
|
|
|
|
const cookie = context.req.header("Cookie");
|
|
|
|
|
|
2024-06-13 04:26:43 +02:00
|
|
|
if (!cookie) {
|
2024-05-06 09:16:33 +02:00
|
|
|
return returnError(
|
|
|
|
|
body,
|
|
|
|
|
"invalid_request",
|
|
|
|
|
"No cookies were sent with the request",
|
|
|
|
|
);
|
2024-06-13 04:26:43 +02:00
|
|
|
}
|
2024-05-06 09:16:33 +02:00
|
|
|
|
|
|
|
|
const jwt = cookie
|
|
|
|
|
.split(";")
|
|
|
|
|
.find((c) => c.trim().startsWith("jwt="))
|
|
|
|
|
?.split("=")[1];
|
|
|
|
|
|
2024-06-13 04:26:43 +02:00
|
|
|
if (!jwt) {
|
2024-05-06 09:16:33 +02:00
|
|
|
return returnError(
|
|
|
|
|
body,
|
|
|
|
|
"invalid_request",
|
|
|
|
|
"No jwt cookie was sent in the request",
|
|
|
|
|
);
|
2024-06-13 04:26:43 +02:00
|
|
|
}
|
2024-05-06 09:16:33 +02:00
|
|
|
|
|
|
|
|
// Try and import the key
|
|
|
|
|
const privateKey = await crypto.subtle.importKey(
|
|
|
|
|
"pkcs8",
|
|
|
|
|
Buffer.from(config.oidc.jwt_key.split(";")[0], "base64"),
|
|
|
|
|
"Ed25519",
|
|
|
|
|
true,
|
|
|
|
|
["sign"],
|
2024-04-18 10:42:12 +02:00
|
|
|
);
|
|
|
|
|
|
2024-05-06 09:16:33 +02:00
|
|
|
const publicKey = await crypto.subtle.importKey(
|
|
|
|
|
"spki",
|
|
|
|
|
Buffer.from(config.oidc.jwt_key.split(";")[1], "base64"),
|
|
|
|
|
"Ed25519",
|
|
|
|
|
true,
|
|
|
|
|
["verify"],
|
2024-04-18 10:42:12 +02:00
|
|
|
);
|
|
|
|
|
|
2024-05-06 09:16:33 +02:00
|
|
|
const result = await jwtVerify(jwt, publicKey, {
|
|
|
|
|
algorithms: ["EdDSA"],
|
|
|
|
|
issuer: new URL(config.http.base_url).origin,
|
|
|
|
|
audience: client_id,
|
|
|
|
|
}).catch((e) => {
|
|
|
|
|
console.error(e);
|
2024-07-24 19:04:00 +02:00
|
|
|
sentry?.captureException(e);
|
2024-05-06 09:16:33 +02:00
|
|
|
return null;
|
|
|
|
|
});
|
|
|
|
|
|
2024-06-13 04:26:43 +02:00
|
|
|
if (!result) {
|
2024-05-06 09:16:33 +02:00
|
|
|
return returnError(
|
|
|
|
|
body,
|
|
|
|
|
"invalid_request",
|
|
|
|
|
"Invalid JWT, could not verify",
|
|
|
|
|
);
|
2024-06-13 04:26:43 +02:00
|
|
|
}
|
2024-05-06 09:16:33 +02:00
|
|
|
|
|
|
|
|
const payload = result.payload;
|
|
|
|
|
|
2024-06-13 04:26:43 +02:00
|
|
|
if (!payload.sub) {
|
2024-05-06 09:16:33 +02:00
|
|
|
return returnError(body, "invalid_request", "Invalid sub");
|
2024-06-13 04:26:43 +02:00
|
|
|
}
|
|
|
|
|
if (!payload.aud) {
|
2024-05-06 09:16:33 +02:00
|
|
|
return returnError(body, "invalid_request", "Invalid aud");
|
2024-06-13 04:26:43 +02:00
|
|
|
}
|
|
|
|
|
if (!payload.exp) {
|
2024-05-06 09:16:33 +02:00
|
|
|
return returnError(body, "invalid_request", "Invalid exp");
|
2024-06-13 04:26:43 +02:00
|
|
|
}
|
2024-05-06 09:16:33 +02:00
|
|
|
|
|
|
|
|
// Check if the user is authenticated
|
|
|
|
|
const user = await User.fromId(payload.sub);
|
|
|
|
|
|
2024-06-13 04:26:43 +02:00
|
|
|
if (!user) {
|
2024-05-06 09:16:33 +02:00
|
|
|
return returnError(body, "invalid_request", "Invalid sub");
|
2024-06-13 04:26:43 +02:00
|
|
|
}
|
2024-05-06 09:16:33 +02:00
|
|
|
|
2024-06-13 04:26:43 +02:00
|
|
|
if (!user.hasPermission(RolePermissions.OAuth)) {
|
2024-06-08 06:57:29 +02:00
|
|
|
return returnError(
|
|
|
|
|
body,
|
|
|
|
|
"invalid_request",
|
2024-06-13 04:26:43 +02:00
|
|
|
`User is missing the ${RolePermissions.OAuth} permission`,
|
2024-06-08 06:57:29 +02:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2024-05-06 09:16:33 +02:00
|
|
|
const responseTypes = response_type.split(" ");
|
|
|
|
|
|
|
|
|
|
const asksCode = responseTypes.includes("code");
|
|
|
|
|
const asksToken = responseTypes.includes("token");
|
|
|
|
|
const asksIdToken = responseTypes.includes("id_token");
|
|
|
|
|
|
2024-06-13 04:26:43 +02:00
|
|
|
if (!(asksCode || asksToken || asksIdToken)) {
|
2024-05-06 09:16:33 +02:00
|
|
|
return returnError(
|
|
|
|
|
body,
|
|
|
|
|
"invalid_request",
|
|
|
|
|
"Invalid response_type, must ask for code, token, or id_token",
|
|
|
|
|
);
|
2024-06-13 04:26:43 +02:00
|
|
|
}
|
2024-05-06 09:16:33 +02:00
|
|
|
|
2024-06-13 04:26:43 +02:00
|
|
|
if (asksCode && !redirect_uri) {
|
2024-05-06 09:16:33 +02:00
|
|
|
return returnError(
|
|
|
|
|
body,
|
|
|
|
|
"invalid_request",
|
2024-05-13 00:24:15 +02:00
|
|
|
"Redirect URI is required for code flow (can be urn:ietf:wg:oauth:2.0:oob)",
|
2024-05-06 09:16:33 +02:00
|
|
|
);
|
2024-06-13 04:26:43 +02:00
|
|
|
}
|
2024-05-06 09:16:33 +02:00
|
|
|
|
|
|
|
|
/* if (asksCode && !code_challenge)
|
|
|
|
|
return returnError(
|
|
|
|
|
"invalid_request",
|
|
|
|
|
"Code challenge is required for code flow",
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (asksCode && !code_challenge_method)
|
|
|
|
|
return returnError(
|
|
|
|
|
"invalid_request",
|
|
|
|
|
"Code challenge method is required for code flow",
|
|
|
|
|
); */
|
|
|
|
|
|
|
|
|
|
// Authenticate the user
|
|
|
|
|
const application = await db.query.Applications.findFirst({
|
|
|
|
|
where: (app, { eq }) => eq(app.clientId, client_id),
|
|
|
|
|
});
|
|
|
|
|
|
2024-06-13 04:26:43 +02:00
|
|
|
if (!application) {
|
2024-05-06 09:16:33 +02:00
|
|
|
return returnError(
|
|
|
|
|
body,
|
|
|
|
|
"invalid_client",
|
|
|
|
|
"Invalid client_id or client_secret",
|
|
|
|
|
);
|
2024-06-13 04:26:43 +02:00
|
|
|
}
|
2024-05-06 09:16:33 +02:00
|
|
|
|
2024-06-13 04:26:43 +02:00
|
|
|
if (application.redirectUri !== redirect_uri) {
|
2024-05-06 09:16:33 +02:00
|
|
|
return returnError(
|
|
|
|
|
body,
|
|
|
|
|
"invalid_request",
|
|
|
|
|
"Redirect URI does not match client_id",
|
|
|
|
|
);
|
2024-06-13 04:26:43 +02:00
|
|
|
}
|
2024-05-06 09:16:33 +02:00
|
|
|
|
|
|
|
|
// Validate scopes, they can either be equal or a subset of the application's scopes
|
|
|
|
|
const applicationScopes = application.scopes.split(" ");
|
|
|
|
|
|
|
|
|
|
if (
|
|
|
|
|
scope &&
|
|
|
|
|
!scope.split(" ").every((s) => applicationScopes.includes(s))
|
2024-06-13 04:26:43 +02:00
|
|
|
) {
|
2024-05-06 09:16:33 +02:00
|
|
|
return returnError(body, "invalid_scope", "Invalid scope");
|
2024-06-13 04:26:43 +02:00
|
|
|
}
|
2024-05-06 09:16:33 +02:00
|
|
|
|
|
|
|
|
// Generate tokens
|
2024-06-13 07:38:26 +02:00
|
|
|
const code = randomString(256, "base64url");
|
2024-05-06 09:16:33 +02:00
|
|
|
|
|
|
|
|
// Handle the requested scopes
|
|
|
|
|
let idTokenPayload = {};
|
2024-06-13 04:26:43 +02:00
|
|
|
const scopeIncludesOpenId = scope?.split(" ").includes("openid");
|
2024-05-06 09:16:33 +02:00
|
|
|
const scopeIncludesProfile = scope?.split(" ").includes("profile");
|
|
|
|
|
const scopeIncludesEmail = scope?.split(" ").includes("email");
|
|
|
|
|
if (scope) {
|
2024-06-13 04:26:43 +02:00
|
|
|
if (scopeIncludesOpenId) {
|
2024-05-06 09:16:33 +02:00
|
|
|
// Include the standard OpenID claims
|
|
|
|
|
idTokenPayload = {
|
|
|
|
|
...idTokenPayload,
|
|
|
|
|
sub: user.id,
|
|
|
|
|
aud: client_id,
|
|
|
|
|
iss: new URL(config.http.base_url).origin,
|
|
|
|
|
iat: Math.floor(Date.now() / 1000),
|
|
|
|
|
exp: Math.floor(Date.now() / 1000) + 60 * 60,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
if (scopeIncludesProfile) {
|
|
|
|
|
// Include the user's profile information
|
|
|
|
|
idTokenPayload = {
|
|
|
|
|
...idTokenPayload,
|
2024-06-13 02:45:07 +02:00
|
|
|
name: user.data.displayName,
|
|
|
|
|
preferred_username: user.data.username,
|
2024-05-06 09:16:33 +02:00
|
|
|
picture: user.getAvatarUrl(config),
|
2024-06-13 02:45:07 +02:00
|
|
|
updated_at: new Date(user.data.updatedAt).toISOString(),
|
2024-05-06 09:16:33 +02:00
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
if (scopeIncludesEmail) {
|
|
|
|
|
// Include the user's email address
|
|
|
|
|
idTokenPayload = {
|
|
|
|
|
...idTokenPayload,
|
2024-06-13 02:45:07 +02:00
|
|
|
email: user.data.email,
|
2024-05-06 09:16:33 +02:00
|
|
|
// TODO: Add verification system
|
|
|
|
|
email_verified: true,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-04-18 10:42:12 +02:00
|
|
|
|
2024-05-06 09:16:33 +02:00
|
|
|
const idToken = await new SignJWT(idTokenPayload)
|
|
|
|
|
.setProtectedHeader({
|
|
|
|
|
alg: "EdDSA",
|
|
|
|
|
})
|
|
|
|
|
.sign(privateKey);
|
|
|
|
|
|
|
|
|
|
await db.insert(Tokens).values({
|
2024-06-13 07:38:26 +02:00
|
|
|
accessToken: randomString(64, "base64url"),
|
2024-05-06 09:16:33 +02:00
|
|
|
code: code,
|
|
|
|
|
scope: scope ?? application.scopes,
|
2024-06-13 04:26:43 +02:00
|
|
|
tokenType: TokenType.Bearer,
|
2024-05-06 09:16:33 +02:00
|
|
|
applicationId: application.id,
|
|
|
|
|
redirectUri: redirect_uri ?? application.redirectUri,
|
|
|
|
|
expiresAt: new Date(
|
|
|
|
|
Date.now() + 60 * 60 * 24 * 14,
|
|
|
|
|
).toISOString(),
|
|
|
|
|
idToken:
|
2024-06-13 04:26:43 +02:00
|
|
|
scopeIncludesOpenId ||
|
2024-05-06 09:16:33 +02:00
|
|
|
scopeIncludesEmail ||
|
|
|
|
|
scopeIncludesProfile
|
|
|
|
|
? idToken
|
|
|
|
|
: null,
|
|
|
|
|
clientId: client_id,
|
|
|
|
|
userId: user.id,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Redirect to the client
|
2024-05-13 00:24:15 +02:00
|
|
|
const redirectUri =
|
|
|
|
|
redirect_uri === "urn:ietf:wg:oauth:2.0:oob"
|
|
|
|
|
? new URL("/oauth/code", config.http.base_url)
|
|
|
|
|
: new URL(redirect_uri ?? application.redirectUri);
|
2024-04-18 10:42:12 +02:00
|
|
|
|
2024-05-06 09:16:33 +02:00
|
|
|
const searchParams = new URLSearchParams({
|
|
|
|
|
code: code,
|
|
|
|
|
});
|
|
|
|
|
|
2024-06-13 04:26:43 +02:00
|
|
|
if (state) {
|
|
|
|
|
searchParams.append("state", state);
|
|
|
|
|
}
|
2024-05-13 00:24:15 +02:00
|
|
|
|
2024-06-08 02:08:27 +02:00
|
|
|
redirectUri.search = searchParams.toString();
|
|
|
|
|
|
2024-05-06 09:16:33 +02:00
|
|
|
return response(null, 302, {
|
2024-06-08 02:08:27 +02:00
|
|
|
Location: redirectUri.toString(),
|
2024-05-06 09:16:33 +02:00
|
|
|
"Cache-Control": "no-store",
|
|
|
|
|
Pragma: "no-cache",
|
|
|
|
|
});
|
|
|
|
|
},
|
2024-08-19 20:06:38 +02:00
|
|
|
),
|
|
|
|
|
);
|