refactor(api): 🚚 Use api/ for API routes instead of server/api/

This commit is contained in:
Jesse Wierzbinski 2024-08-27 16:37:23 +02:00
parent dfc0bf4595
commit 3c1b330d4b
No known key found for this signature in database
143 changed files with 5 additions and 5 deletions

View file

@ -0,0 +1,333 @@
import { apiRoute, applyConfig, handleZodError, jsonOrForm } from "@/api";
import { randomString } from "@/math";
import { response } from "@/response";
import { sentry } from "@/sentry";
import { zValidator } from "@hono/zod-validator";
import { SignJWT, jwtVerify } from "jose";
import { z } from "zod";
import { TokenType } from "~/classes/functions/token";
import { db } from "~/drizzle/db";
import { RolePermissions, Tokens } from "~/drizzle/schema";
import { config } from "~/packages/config-manager";
import { User } from "~/packages/database-interface/user";
export const meta = applyConfig({
allowedMethods: ["POST"],
ratelimits: {
max: 4,
duration: 60,
},
route: "/oauth/authorize",
auth: {
required: false,
},
});
export const schemas = {
query: z.object({
prompt: z
.enum(["none", "login", "consent", "select_account"])
.optional()
.default("none"),
max_age: z.coerce
.number()
.int()
.optional()
.default(60 * 60 * 24 * 7),
}),
json: z.object({
scope: z.string().optional(),
redirect_uri: z
.string()
.url()
.optional()
.or(z.literal("urn:ietf:wg:oauth:2.0:oob")),
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(),
}),
};
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, {
Location: `${config.frontend.routes.login}?${searchParams.toString()}`,
});
};
export default apiRoute((app) =>
app.on(
meta.allowedMethods,
meta.route,
jsonOrForm(),
zValidator("query", schemas.query, handleZodError),
zValidator("json", schemas.json, handleZodError),
async (context) => {
const { scope, redirect_uri, response_type, client_id, state } =
context.req.valid("json");
const body = context.req.valid("json");
const cookie = context.req.header("Cookie");
if (!cookie) {
return returnError(
body,
"invalid_request",
"No cookies were sent with the request",
);
}
const jwt = cookie
.split(";")
.find((c) => c.trim().startsWith("jwt="))
?.split("=")[1];
if (!jwt) {
return returnError(
body,
"invalid_request",
"No jwt cookie was sent in the request",
);
}
// Try and import the key
const privateKey = await crypto.subtle.importKey(
"pkcs8",
Buffer.from(config.oidc.jwt_key.split(";")[0], "base64"),
"Ed25519",
true,
["sign"],
);
const publicKey = await crypto.subtle.importKey(
"spki",
Buffer.from(config.oidc.jwt_key.split(";")[1], "base64"),
"Ed25519",
true,
["verify"],
);
const result = await jwtVerify(jwt, publicKey, {
algorithms: ["EdDSA"],
issuer: new URL(config.http.base_url).origin,
audience: client_id,
}).catch((e) => {
console.error(e);
sentry?.captureException(e);
return null;
});
if (!result) {
return returnError(
body,
"invalid_request",
"Invalid JWT, could not verify",
);
}
const payload = result.payload;
if (!payload.sub) {
return returnError(body, "invalid_request", "Invalid sub");
}
if (!payload.aud) {
return returnError(body, "invalid_request", "Invalid aud");
}
if (!payload.exp) {
return returnError(body, "invalid_request", "Invalid exp");
}
// Check if the user is authenticated
const user = await User.fromId(payload.sub);
if (!user) {
return returnError(body, "invalid_request", "Invalid sub");
}
if (!user.hasPermission(RolePermissions.OAuth)) {
return returnError(
body,
"invalid_request",
`User is missing the ${RolePermissions.OAuth} permission`,
);
}
const responseTypes = response_type.split(" ");
const asksCode = responseTypes.includes("code");
const asksToken = responseTypes.includes("token");
const asksIdToken = responseTypes.includes("id_token");
if (!(asksCode || asksToken || asksIdToken)) {
return returnError(
body,
"invalid_request",
"Invalid response_type, must ask for code, token, or id_token",
);
}
if (asksCode && !redirect_uri) {
return returnError(
body,
"invalid_request",
"Redirect URI is required for code flow (can be urn:ietf:wg:oauth:2.0:oob)",
);
}
/* 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),
});
if (!application) {
return returnError(
body,
"invalid_client",
"Invalid client_id or client_secret",
);
}
if (application.redirectUri !== redirect_uri) {
return returnError(
body,
"invalid_request",
"Redirect URI does not match client_id",
);
}
// 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))
) {
return returnError(body, "invalid_scope", "Invalid scope");
}
// Generate tokens
const code = randomString(256, "base64url");
// Handle the requested scopes
let idTokenPayload = {};
const scopeIncludesOpenId = scope?.split(" ").includes("openid");
const scopeIncludesProfile = scope?.split(" ").includes("profile");
const scopeIncludesEmail = scope?.split(" ").includes("email");
if (scope) {
if (scopeIncludesOpenId) {
// 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,
name: user.data.displayName,
preferred_username: user.data.username,
picture: user.getAvatarUrl(config),
updated_at: new Date(user.data.updatedAt).toISOString(),
};
}
if (scopeIncludesEmail) {
// Include the user's email address
idTokenPayload = {
...idTokenPayload,
email: user.data.email,
// TODO: Add verification system
email_verified: true,
};
}
}
const idToken = await new SignJWT(idTokenPayload)
.setProtectedHeader({
alg: "EdDSA",
})
.sign(privateKey);
await db.insert(Tokens).values({
accessToken: randomString(64, "base64url"),
code: code,
scope: scope ?? application.scopes,
tokenType: TokenType.Bearer,
applicationId: application.id,
redirectUri: redirect_uri ?? application.redirectUri,
expiresAt: new Date(
Date.now() + 60 * 60 * 24 * 14,
).toISOString(),
idToken:
scopeIncludesOpenId ||
scopeIncludesEmail ||
scopeIncludesProfile
? idToken
: null,
clientId: client_id,
userId: user.id,
});
// Redirect to the client
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);
const searchParams = new URLSearchParams({
code: code,
});
if (state) {
searchParams.append("state", state);
}
redirectUri.search = searchParams.toString();
return response(null, 302, {
Location: redirectUri.toString(),
"Cache-Control": "no-store",
Pragma: "no-cache",
});
},
),
);

View file

@ -0,0 +1,291 @@
import { apiRoute, applyConfig, handleZodError } from "@/api";
import { randomString } from "@/math";
import { response } from "@/response";
import { zValidator } from "@hono/zod-validator";
import { and, eq, isNull } from "drizzle-orm";
import { SignJWT } from "jose";
import { z } from "zod";
import { TokenType } from "~/classes/functions/token";
import { db } from "~/drizzle/db";
import { RolePermissions, Tokens, Users } from "~/drizzle/schema";
import { config } from "~/packages/config-manager";
import { OAuthManager } from "~/packages/database-interface/oauth";
import { User } from "~/packages/database-interface/user";
export const meta = applyConfig({
allowedMethods: ["GET"],
auth: {
required: false,
},
ratelimits: {
duration: 60,
max: 20,
},
route: "/oauth/sso/:issuer/callback",
});
export const schemas = {
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(),
}),
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, {
Location: `${config.frontend.routes.login}?${searchParams.toString()}`,
});
};
/**
* 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
*/
export default apiRoute((app) =>
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);
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:";
}
// 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(
{
...manager.processOAuth2Error(app),
},
error,
message,
),
);
if (userInfo instanceof Response) {
return userInfo;
}
const { sub, email, preferred_username, picture } =
userInfo.userInfo;
const flow = userInfo.flow;
// If linking account
if (link && user_id) {
return await manager.linkUser(user_id, userInfo);
}
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),
),
)
.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;
// Create new user
const user = await User.fromDataLocal({
email: doesEmailExist ? undefined : email,
username,
avatar: picture,
password: undefined,
});
// Link account
await manager.linkUserInDatabase(user.id, sub);
userId = user.id;
} else {
return returnError(
{
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",
);
}
}
const user = await User.fromId(userId);
if (!user) {
return returnError(
{
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",
);
}
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`,
);
}
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"),
code: code,
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.jwt_key.split(";")[0], "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
return response(null, 302, {
Location: 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(),
// Set cookie with JWT
"Set-Cookie": `jwt=${jwt}; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=${
60 * 60
}`,
});
},
),
);

138
api/oauth/sso/index.ts Normal file
View file

@ -0,0 +1,138 @@
import { apiRoute, applyConfig, handleZodError } from "@/api";
import { oauthRedirectUri } from "@/constants";
import { redirect, response } from "@/response";
import { zValidator } from "@hono/zod-validator";
import {
calculatePKCECodeChallenge,
discoveryRequest,
generateRandomCodeVerifier,
processDiscoveryResponse,
} from "oauth4webapi";
import { z } from "zod";
import { db } from "~/drizzle/db";
import { OpenIdLoginFlows } from "~/drizzle/schema";
import { config } from "~/packages/config-manager";
export const meta = applyConfig({
allowedMethods: ["GET"],
auth: {
required: false,
},
ratelimits: {
duration: 60,
max: 20,
},
route: "/oauth/sso",
});
export const schemas = {
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(),
}),
};
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, {
Location: `${config.frontend.routes.login}?${searchParams.toString()}`,
});
};
export default apiRoute((app) =>
app.on(
meta.allowedMethods,
meta.route,
zValidator("query", schemas.query, 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 body = await context.req.query();
if (!client_id || client_id === "undefined") {
return returnError(
body,
"invalid_request",
"client_id is required",
);
}
const issuer = config.oidc.providers.find(
(provider) => provider.id === issuerId,
);
if (!issuer) {
return returnError(
body,
"invalid_request",
"issuer is invalid",
);
}
const issuerUrl = new URL(issuer.url);
const authServer = await discoveryRequest(issuerUrl, {
algorithm: "oidc",
}).then((res) => processDiscoveryResponse(issuerUrl, res));
const codeVerifier = generateRandomCodeVerifier();
const application = await db.query.Applications.findFirst({
where: (application, { eq }) =>
eq(application.clientId, client_id),
});
if (!application) {
return returnError(
body,
"invalid_request",
"client_id is invalid",
);
}
// Store into database
const newFlow = (
await db
.insert(OpenIdLoginFlows)
.values({
codeVerifier,
applicationId: application.id,
issuerId,
})
.returning()
)[0];
const codeChallenge =
await calculatePKCECodeChallenge(codeVerifier);
return redirect(
`${authServer.authorization_endpoint}?${new URLSearchParams({
client_id: issuer.client_id,
redirect_uri: `${oauthRedirectUri(issuerId)}?flow=${
newFlow.id
}`,
response_type: "code",
scope: "openid profile email",
// PKCE
code_challenge_method: "S256",
code_challenge: codeChallenge,
}).toString()}`,
302,
);
},
),
);

165
api/oauth/token/index.ts Normal file
View file

@ -0,0 +1,165 @@
import { apiRoute, applyConfig, handleZodError, jsonOrForm } from "@/api";
import { zValidator } from "@hono/zod-validator";
import { eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "~/drizzle/db";
import { Tokens } from "~/drizzle/schema";
export const meta = applyConfig({
allowedMethods: ["POST"],
auth: {
required: false,
},
ratelimits: {
duration: 60,
max: 10,
},
route: "/oauth/token",
});
export const schemas = {
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(),
}),
};
export default apiRoute((app) =>
app.on(
meta.allowedMethods,
meta.route,
jsonOrForm(),
zValidator("json", schemas.json, 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 db.query.Applications.findFirst({
where: (application, { eq }) =>
eq(application.clientId, client_id),
});
if (!client || client.secret !== client_secret) {
return context.json(
{
error: "invalid_client",
error_description: "Invalid client credentials",
},
401,
);
}
const token = await db.query.Tokens.findFirst({
where: (token, { eq, and }) =>
and(
eq(token.code, code),
eq(token.redirectUri, redirect_uri),
eq(token.clientId, client_id),
),
});
if (!token) {
return context.json(
{
error: "invalid_grant",
error_description: "Code not found",
},
401,
);
}
// Invalidate the code
await db
.update(Tokens)
.set({ code: null })
.where(eq(Tokens.id, token.id));
return context.json({
access_token: token.accessToken,
token_type: "Bearer",
expires_in: token.expiresAt
? Math.floor(
(new Date(token.expiresAt).getTime() -
Date.now()) /
1000,
)
: null,
id_token: token.idToken,
refresh_token: null,
scope: token.scope,
created_at: Math.floor(
new Date(token.createdAt).getTime() / 1000,
),
});
}
}
return context.json(
{
error: "unsupported_grant_type",
error_description: "Unsupported grant type",
},
401,
);
},
),
);