mirror of
https://github.com/versia-pub/server.git
synced 2025-12-06 08:28:19 +01:00
refactor(database): ♻️ Move Applications to our custom ORM
This commit is contained in:
parent
e8827bccfa
commit
9e96eca032
|
|
@ -1,31 +1,24 @@
|
||||||
import { afterAll, describe, expect, test } from "bun:test";
|
import { afterAll, describe, expect, test } from "bun:test";
|
||||||
import { randomString } from "@/math";
|
import { randomString } from "@/math";
|
||||||
import { eq } from "drizzle-orm";
|
|
||||||
import { db } from "~/drizzle/db";
|
|
||||||
import { Applications } from "~/drizzle/schema";
|
|
||||||
import { config } from "~/packages/config-manager";
|
import { config } from "~/packages/config-manager";
|
||||||
|
import { Application } from "~/packages/database-interface/application.ts";
|
||||||
import { fakeRequest, getTestUsers } from "~/tests/utils";
|
import { fakeRequest, getTestUsers } from "~/tests/utils";
|
||||||
import { meta } from "./index.ts";
|
import { meta } from "./index.ts";
|
||||||
|
|
||||||
const { users, deleteUsers, passwords } = await getTestUsers(1);
|
const { users, deleteUsers, passwords } = await getTestUsers(1);
|
||||||
|
|
||||||
// Create application
|
// Create application
|
||||||
const application = (
|
const application = await Application.insert({
|
||||||
await db
|
name: "Test Application",
|
||||||
.insert(Applications)
|
clientId: randomString(32, "hex"),
|
||||||
.values({
|
secret: "test",
|
||||||
name: "Test Application",
|
redirectUri: "https://example.com",
|
||||||
clientId: randomString(32, "hex"),
|
scopes: "read write",
|
||||||
secret: "test",
|
});
|
||||||
redirectUri: "https://example.com",
|
|
||||||
scopes: "read write",
|
|
||||||
})
|
|
||||||
.returning()
|
|
||||||
)[0];
|
|
||||||
|
|
||||||
afterAll(async () => {
|
afterAll(async () => {
|
||||||
await deleteUsers();
|
await deleteUsers();
|
||||||
await db.delete(Applications).where(eq(Applications.id, application.id));
|
await application.delete();
|
||||||
});
|
});
|
||||||
|
|
||||||
// /api/auth/login
|
// /api/auth/login
|
||||||
|
|
@ -37,7 +30,7 @@ describe(meta.route, () => {
|
||||||
formData.append("password", passwords[0]);
|
formData.append("password", passwords[0]);
|
||||||
|
|
||||||
const response = await fakeRequest(
|
const response = await fakeRequest(
|
||||||
`/api/auth/login?client_id=${application.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write`,
|
`/api/auth/login?client_id=${application.data.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write`,
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: formData,
|
body: formData,
|
||||||
|
|
@ -53,7 +46,7 @@ describe(meta.route, () => {
|
||||||
|
|
||||||
expect(locationHeader.pathname).toBe("/oauth/consent");
|
expect(locationHeader.pathname).toBe("/oauth/consent");
|
||||||
expect(locationHeader.searchParams.get("client_id")).toBe(
|
expect(locationHeader.searchParams.get("client_id")).toBe(
|
||||||
application.clientId,
|
application.data.clientId,
|
||||||
);
|
);
|
||||||
expect(locationHeader.searchParams.get("redirect_uri")).toBe(
|
expect(locationHeader.searchParams.get("redirect_uri")).toBe(
|
||||||
"https://example.com",
|
"https://example.com",
|
||||||
|
|
@ -71,7 +64,7 @@ describe(meta.route, () => {
|
||||||
formData.append("password", passwords[0]);
|
formData.append("password", passwords[0]);
|
||||||
|
|
||||||
const response = await fakeRequest(
|
const response = await fakeRequest(
|
||||||
`/api/auth/login?client_id=${application.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write`,
|
`/api/auth/login?client_id=${application.data.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write`,
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: formData,
|
body: formData,
|
||||||
|
|
@ -87,7 +80,7 @@ describe(meta.route, () => {
|
||||||
|
|
||||||
expect(locationHeader.pathname).toBe("/oauth/consent");
|
expect(locationHeader.pathname).toBe("/oauth/consent");
|
||||||
expect(locationHeader.searchParams.get("client_id")).toBe(
|
expect(locationHeader.searchParams.get("client_id")).toBe(
|
||||||
application.clientId,
|
application.data.clientId,
|
||||||
);
|
);
|
||||||
expect(locationHeader.searchParams.get("redirect_uri")).toBe(
|
expect(locationHeader.searchParams.get("redirect_uri")).toBe(
|
||||||
"https://example.com",
|
"https://example.com",
|
||||||
|
|
@ -105,7 +98,7 @@ describe(meta.route, () => {
|
||||||
formData.append("password", passwords[0]);
|
formData.append("password", passwords[0]);
|
||||||
|
|
||||||
const response = await fakeRequest(
|
const response = await fakeRequest(
|
||||||
`/api/auth/login?client_id=${application.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write&state=abc`,
|
`/api/auth/login?client_id=${application.data.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write&state=abc`,
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: formData,
|
body: formData,
|
||||||
|
|
@ -121,7 +114,7 @@ describe(meta.route, () => {
|
||||||
|
|
||||||
expect(locationHeader.pathname).toBe("/oauth/consent");
|
expect(locationHeader.pathname).toBe("/oauth/consent");
|
||||||
expect(locationHeader.searchParams.get("client_id")).toBe(
|
expect(locationHeader.searchParams.get("client_id")).toBe(
|
||||||
application.clientId,
|
application.data.clientId,
|
||||||
);
|
);
|
||||||
expect(locationHeader.searchParams.get("redirect_uri")).toBe(
|
expect(locationHeader.searchParams.get("redirect_uri")).toBe(
|
||||||
"https://example.com",
|
"https://example.com",
|
||||||
|
|
@ -142,7 +135,7 @@ describe(meta.route, () => {
|
||||||
formData.append("password", "password");
|
formData.append("password", "password");
|
||||||
|
|
||||||
const response = await fakeRequest(
|
const response = await fakeRequest(
|
||||||
`/api/auth/login?client_id=${application.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write`,
|
`/api/auth/login?client_id=${application.data.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write`,
|
||||||
|
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
|
@ -175,7 +168,7 @@ describe(meta.route, () => {
|
||||||
formData.append("password", "password");
|
formData.append("password", "password");
|
||||||
|
|
||||||
const response = await fakeRequest(
|
const response = await fakeRequest(
|
||||||
`/api/auth/login?client_id=${application.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write`,
|
`/api/auth/login?client_id=${application.data.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write`,
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: formData,
|
body: formData,
|
||||||
|
|
@ -207,7 +200,7 @@ describe(meta.route, () => {
|
||||||
formData.append("password", "password");
|
formData.append("password", "password");
|
||||||
|
|
||||||
const response = await fakeRequest(
|
const response = await fakeRequest(
|
||||||
`/api/auth/login?client_id=${application.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write`,
|
`/api/auth/login?client_id=${application.data.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write`,
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: formData,
|
body: formData,
|
||||||
|
|
|
||||||
|
|
@ -5,9 +5,9 @@ import { createRoute } from "@hono/zod-openapi";
|
||||||
import { eq, or } from "drizzle-orm";
|
import { eq, or } from "drizzle-orm";
|
||||||
import { SignJWT } from "jose";
|
import { SignJWT } from "jose";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { db } from "~/drizzle/db";
|
|
||||||
import { Users } from "~/drizzle/schema";
|
import { Users } from "~/drizzle/schema";
|
||||||
import { config } from "~/packages/config-manager";
|
import { config } from "~/packages/config-manager";
|
||||||
|
import { Application } from "~/packages/database-interface/application";
|
||||||
import { User } from "~/packages/database-interface/user";
|
import { User } from "~/packages/database-interface/user";
|
||||||
|
|
||||||
export const meta = applyConfig({
|
export const meta = applyConfig({
|
||||||
|
|
@ -197,20 +197,18 @@ export default apiRoute((app) =>
|
||||||
.setProtectedHeader({ alg: "EdDSA" })
|
.setProtectedHeader({ alg: "EdDSA" })
|
||||||
.sign(privateKey);
|
.sign(privateKey);
|
||||||
|
|
||||||
const application = await db.query.Applications.findFirst({
|
const application = await Application.fromClientId(client_id);
|
||||||
where: (app, { eq }) => eq(app.clientId, client_id),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!application) {
|
if (!application) {
|
||||||
return context.json({ error: "Invalid application" }, 400);
|
return context.json({ error: "Invalid application" }, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
const searchParams = new URLSearchParams({
|
const searchParams = new URLSearchParams({
|
||||||
application: application.name,
|
application: application.data.name,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (application.website) {
|
if (application.data.website) {
|
||||||
searchParams.append("website", application.website);
|
searchParams.append("website", application.data.website);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add all data that is not undefined except email and password
|
// Add all data that is not undefined except email and password
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,7 @@
|
||||||
import { afterAll, describe, expect, test } from "bun:test";
|
import { afterAll, describe, expect, test } from "bun:test";
|
||||||
import { randomString } from "@/math";
|
import { randomString } from "@/math";
|
||||||
import { eq } from "drizzle-orm";
|
|
||||||
import { db } from "~/drizzle/db";
|
|
||||||
import { Applications } from "~/drizzle/schema";
|
|
||||||
import { config } from "~/packages/config-manager";
|
import { config } from "~/packages/config-manager";
|
||||||
|
import { Application } from "~/packages/database-interface/application.ts";
|
||||||
import { fakeRequest, getTestUsers } from "~/tests/utils";
|
import { fakeRequest, getTestUsers } from "~/tests/utils";
|
||||||
import { meta } from "./index.ts";
|
import { meta } from "./index.ts";
|
||||||
|
|
||||||
|
|
@ -12,22 +10,17 @@ const token = randomString(32, "hex");
|
||||||
const newPassword = randomString(16, "hex");
|
const newPassword = randomString(16, "hex");
|
||||||
|
|
||||||
// Create application
|
// Create application
|
||||||
const application = (
|
const application = await Application.insert({
|
||||||
await db
|
name: "Test Application",
|
||||||
.insert(Applications)
|
clientId: randomString(32, "hex"),
|
||||||
.values({
|
secret: "test",
|
||||||
name: "Test Application",
|
redirectUri: "https://example.com",
|
||||||
clientId: randomString(32, "hex"),
|
scopes: "read write",
|
||||||
secret: "test",
|
});
|
||||||
redirectUri: "https://example.com",
|
|
||||||
scopes: "read write",
|
|
||||||
})
|
|
||||||
.returning()
|
|
||||||
)[0];
|
|
||||||
|
|
||||||
afterAll(async () => {
|
afterAll(async () => {
|
||||||
await deleteUsers();
|
await deleteUsers();
|
||||||
await db.delete(Applications).where(eq(Applications.id, application.id));
|
await application.delete();
|
||||||
});
|
});
|
||||||
|
|
||||||
// /api/auth/reset
|
// /api/auth/reset
|
||||||
|
|
@ -39,7 +32,7 @@ describe(meta.route, () => {
|
||||||
formData.append("password", passwords[0]);
|
formData.append("password", passwords[0]);
|
||||||
|
|
||||||
const response = await fakeRequest(
|
const response = await fakeRequest(
|
||||||
`/api/auth/login?client_id=${application.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write`,
|
`/api/auth/login?client_id=${application.data.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write`,
|
||||||
|
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
|
@ -62,7 +55,7 @@ describe(meta.route, () => {
|
||||||
formData.append("password", passwords[0]);
|
formData.append("password", passwords[0]);
|
||||||
|
|
||||||
const response = await fakeRequest(
|
const response = await fakeRequest(
|
||||||
`/api/auth/login?client_id=${application.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write`,
|
`/api/auth/login?client_id=${application.data.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write`,
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: formData,
|
body: formData,
|
||||||
|
|
@ -101,7 +94,7 @@ describe(meta.route, () => {
|
||||||
loginFormData.append("password", newPassword);
|
loginFormData.append("password", newPassword);
|
||||||
|
|
||||||
const loginResponse = await fakeRequest(
|
const loginResponse = await fakeRequest(
|
||||||
`/api/auth/login?client_id=${application.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write`,
|
`/api/auth/login?client_id=${application.data.clientId}&redirect_uri=https://example.com&response_type=code&scope=read+write`,
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: loginFormData,
|
body: loginFormData,
|
||||||
|
|
@ -117,7 +110,7 @@ describe(meta.route, () => {
|
||||||
|
|
||||||
expect(locationHeader.pathname).toBe("/oauth/consent");
|
expect(locationHeader.pathname).toBe("/oauth/consent");
|
||||||
expect(locationHeader.searchParams.get("client_id")).toBe(
|
expect(locationHeader.searchParams.get("client_id")).toBe(
|
||||||
application.clientId,
|
application.data.clientId,
|
||||||
);
|
);
|
||||||
expect(locationHeader.searchParams.get("redirect_uri")).toBe(
|
expect(locationHeader.searchParams.get("redirect_uri")).toBe(
|
||||||
"https://example.com",
|
"https://example.com",
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,8 @@ import { apiRoute, applyConfig, jsonOrForm } from "@/api";
|
||||||
import { randomString } from "@/math";
|
import { randomString } from "@/math";
|
||||||
import { createRoute } from "@hono/zod-openapi";
|
import { createRoute } from "@hono/zod-openapi";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { db } from "~/drizzle/db";
|
import { RolePermissions } from "~/drizzle/schema";
|
||||||
import { Applications, RolePermissions } from "~/drizzle/schema";
|
import { Application } from "~/packages/database-interface/application";
|
||||||
|
|
||||||
export const meta = applyConfig({
|
export const meta = applyConfig({
|
||||||
route: "/api/v1/apps",
|
route: "/api/v1/apps",
|
||||||
|
|
@ -81,29 +81,24 @@ export default apiRoute((app) =>
|
||||||
const { client_name, redirect_uris, scopes, website } =
|
const { client_name, redirect_uris, scopes, website } =
|
||||||
context.req.valid("json");
|
context.req.valid("json");
|
||||||
|
|
||||||
const app = (
|
const app = await Application.insert({
|
||||||
await db
|
name: client_name || "",
|
||||||
.insert(Applications)
|
redirectUri: decodeURI(redirect_uris) || "",
|
||||||
.values({
|
scopes: scopes || "read",
|
||||||
name: client_name || "",
|
website: website || null,
|
||||||
redirectUri: decodeURI(redirect_uris) || "",
|
clientId: randomString(32, "base64url"),
|
||||||
scopes: scopes || "read",
|
secret: randomString(64, "base64url"),
|
||||||
website: website || null,
|
});
|
||||||
clientId: randomString(32, "base64url"),
|
|
||||||
secret: randomString(64, "base64url"),
|
|
||||||
})
|
|
||||||
.returning()
|
|
||||||
)[0];
|
|
||||||
|
|
||||||
return context.json(
|
return context.json(
|
||||||
{
|
{
|
||||||
id: app.id,
|
id: app.id,
|
||||||
name: app.name,
|
name: app.data.name,
|
||||||
website: app.website,
|
website: app.data.website,
|
||||||
client_id: app.clientId,
|
client_id: app.data.clientId,
|
||||||
client_secret: app.secret,
|
client_secret: app.data.secret,
|
||||||
redirect_uri: app.redirectUri,
|
redirect_uri: app.data.redirectUri,
|
||||||
vapid_link: app.vapidKey,
|
vapid_link: app.data.vapidKey,
|
||||||
},
|
},
|
||||||
200,
|
200,
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { apiRoute, applyConfig, auth } from "@/api";
|
import { apiRoute, applyConfig, auth } from "@/api";
|
||||||
import { createRoute, z } from "@hono/zod-openapi";
|
import { createRoute } from "@hono/zod-openapi";
|
||||||
import { getFromToken } from "~/classes/functions/application";
|
|
||||||
import { RolePermissions } from "~/drizzle/schema";
|
import { RolePermissions } from "~/drizzle/schema";
|
||||||
|
import { Application } from "~/packages/database-interface/application";
|
||||||
import { ErrorSchema } from "~/types/api";
|
import { ErrorSchema } from "~/types/api";
|
||||||
|
|
||||||
export const meta = applyConfig({
|
export const meta = applyConfig({
|
||||||
|
|
@ -29,13 +29,7 @@ const route = createRoute({
|
||||||
description: "Application",
|
description: "Application",
|
||||||
content: {
|
content: {
|
||||||
"application/json": {
|
"application/json": {
|
||||||
schema: z.object({
|
schema: Application.schema,
|
||||||
name: z.string(),
|
|
||||||
website: z.string().nullable(),
|
|
||||||
vapid_key: z.string().nullable(),
|
|
||||||
redirect_uris: z.string(),
|
|
||||||
scopes: z.string(),
|
|
||||||
}),
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
@ -61,7 +55,7 @@ export default apiRoute((app) =>
|
||||||
return context.json({ error: "Unauthorized" }, 401);
|
return context.json({ error: "Unauthorized" }, 401);
|
||||||
}
|
}
|
||||||
|
|
||||||
const application = await getFromToken(token);
|
const application = await Application.getFromToken(token);
|
||||||
|
|
||||||
if (!application) {
|
if (!application) {
|
||||||
return context.json({ error: "Unauthorized" }, 401);
|
return context.json({ error: "Unauthorized" }, 401);
|
||||||
|
|
@ -69,11 +63,9 @@ export default apiRoute((app) =>
|
||||||
|
|
||||||
return context.json(
|
return context.json(
|
||||||
{
|
{
|
||||||
name: application.name,
|
...application.toApi(),
|
||||||
website: application.website,
|
redirect_uris: application.data.redirectUri,
|
||||||
vapid_key: application.vapidKey,
|
scopes: application.data.scopes,
|
||||||
redirect_uris: application.redirectUri,
|
|
||||||
scopes: application.scopes,
|
|
||||||
},
|
},
|
||||||
200,
|
200,
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -1,36 +0,0 @@
|
||||||
import type { Application as APIApplication } from "@versia/client/types";
|
|
||||||
import type { InferSelectModel } from "drizzle-orm";
|
|
||||||
import { db } from "~/drizzle/db";
|
|
||||||
import type { Applications } from "~/drizzle/schema";
|
|
||||||
|
|
||||||
export type Application = InferSelectModel<typeof Applications>;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieves the application associated with the given access token.
|
|
||||||
* @param token The access token to retrieve the application for.
|
|
||||||
* @returns The application associated with the given access token, or null if no such application exists.
|
|
||||||
*/
|
|
||||||
export const getFromToken = async (
|
|
||||||
token: string,
|
|
||||||
): Promise<Application | null> => {
|
|
||||||
const result = await db.query.Tokens.findFirst({
|
|
||||||
where: (tokens, { eq }) => eq(tokens.accessToken, token),
|
|
||||||
with: {
|
|
||||||
application: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return result?.application || null;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Converts this application to an API application.
|
|
||||||
* @returns The API application representation of this application.
|
|
||||||
*/
|
|
||||||
export const applicationToApi = (app: Application): APIApplication => {
|
|
||||||
return {
|
|
||||||
name: app.name,
|
|
||||||
website: app.website,
|
|
||||||
vapid_key: app.vapidKey,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
@ -32,9 +32,9 @@ import {
|
||||||
Users,
|
Users,
|
||||||
} from "~/drizzle/schema";
|
} from "~/drizzle/schema";
|
||||||
import { config } from "~/packages/config-manager/index.ts";
|
import { config } from "~/packages/config-manager/index.ts";
|
||||||
|
import type { ApplicationType } from "~/packages/database-interface/application.ts";
|
||||||
import type { EmojiWithInstance } from "~/packages/database-interface/emoji";
|
import type { EmojiWithInstance } from "~/packages/database-interface/emoji";
|
||||||
import { User } from "~/packages/database-interface/user";
|
import { User } from "~/packages/database-interface/user";
|
||||||
import type { Application } from "./application.ts";
|
|
||||||
import {
|
import {
|
||||||
type UserWithInstance,
|
type UserWithInstance,
|
||||||
type UserWithRelations,
|
type UserWithRelations,
|
||||||
|
|
@ -53,7 +53,7 @@ export type StatusWithRelations = Status & {
|
||||||
emojis: EmojiWithInstance[];
|
emojis: EmojiWithInstance[];
|
||||||
reply: Status | null;
|
reply: Status | null;
|
||||||
quote: Status | null;
|
quote: Status | null;
|
||||||
application: Application | null;
|
application: ApplicationType | null;
|
||||||
reblogCount: number;
|
reblogCount: number;
|
||||||
likeCount: number;
|
likeCount: number;
|
||||||
replyCount: number;
|
replyCount: number;
|
||||||
|
|
|
||||||
|
|
@ -12,9 +12,9 @@ import {
|
||||||
Tokens,
|
Tokens,
|
||||||
type Users,
|
type Users,
|
||||||
} from "~/drizzle/schema";
|
} from "~/drizzle/schema";
|
||||||
|
import type { ApplicationType } from "~/packages/database-interface/application.ts";
|
||||||
import type { EmojiWithInstance } from "~/packages/database-interface/emoji";
|
import type { EmojiWithInstance } from "~/packages/database-interface/emoji";
|
||||||
import { User } from "~/packages/database-interface/user";
|
import { User } from "~/packages/database-interface/user";
|
||||||
import type { Application } from "./application.ts";
|
|
||||||
import type { Token } from "./token.ts";
|
import type { Token } from "./token.ts";
|
||||||
|
|
||||||
export type UserType = InferSelectModel<typeof Users>;
|
export type UserType = InferSelectModel<typeof Users>;
|
||||||
|
|
@ -99,7 +99,7 @@ export const userExtrasTemplate = (name: string) => ({
|
||||||
export interface AuthData {
|
export interface AuthData {
|
||||||
user: User | null;
|
user: User | null;
|
||||||
token: string;
|
token: string;
|
||||||
application: Application | null;
|
application: ApplicationType | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getFromHeader = async (value: string): Promise<AuthData> => {
|
export const getFromHeader = async (value: string): Promise<AuthData> => {
|
||||||
|
|
@ -216,7 +216,7 @@ export const retrieveUserAndApplicationFromToken = async (
|
||||||
accessToken: string,
|
accessToken: string,
|
||||||
): Promise<{
|
): Promise<{
|
||||||
user: User | null;
|
user: User | null;
|
||||||
application: Application | null;
|
application: ApplicationType | null;
|
||||||
}> => {
|
}> => {
|
||||||
if (!accessToken) {
|
if (!accessToken) {
|
||||||
return { user: null, application: null };
|
return { user: null, application: null };
|
||||||
|
|
|
||||||
155
packages/database-interface/application.ts
Normal file
155
packages/database-interface/application.ts
Normal file
|
|
@ -0,0 +1,155 @@
|
||||||
|
import type { Application as APIApplication } from "@versia/client/types";
|
||||||
|
import {
|
||||||
|
type InferInsertModel,
|
||||||
|
type InferSelectModel,
|
||||||
|
type SQL,
|
||||||
|
desc,
|
||||||
|
eq,
|
||||||
|
inArray,
|
||||||
|
} from "drizzle-orm";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { db } from "~/drizzle/db";
|
||||||
|
import { Applications } from "~/drizzle/schema";
|
||||||
|
import { BaseInterface } from "./base.ts";
|
||||||
|
|
||||||
|
export type ApplicationType = InferSelectModel<typeof Applications>;
|
||||||
|
|
||||||
|
export class Application extends BaseInterface<typeof Applications> {
|
||||||
|
static schema: z.ZodType<APIApplication> = z.object({
|
||||||
|
name: z.string(),
|
||||||
|
website: z.string().url().optional().nullable(),
|
||||||
|
vapid_key: z.string().optional().nullable(),
|
||||||
|
redirect_uris: z.string().optional(),
|
||||||
|
scopes: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
async reload(): Promise<void> {
|
||||||
|
const reloaded = await Application.fromId(this.data.id);
|
||||||
|
|
||||||
|
if (!reloaded) {
|
||||||
|
throw new Error("Failed to reload application");
|
||||||
|
}
|
||||||
|
|
||||||
|
this.data = reloaded.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async fromId(id: string | null): Promise<Application | null> {
|
||||||
|
if (!id) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await Application.fromSql(eq(Applications.id, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async fromIds(ids: string[]): Promise<Application[]> {
|
||||||
|
return await Application.manyFromSql(inArray(Applications.id, ids));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async fromSql(
|
||||||
|
sql: SQL<unknown> | undefined,
|
||||||
|
orderBy: SQL<unknown> | undefined = desc(Applications.id),
|
||||||
|
): Promise<Application | null> {
|
||||||
|
const found = await db.query.Applications.findFirst({
|
||||||
|
where: sql,
|
||||||
|
orderBy,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!found) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return new Application(found);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async manyFromSql(
|
||||||
|
sql: SQL<unknown> | undefined,
|
||||||
|
orderBy: SQL<unknown> | undefined = desc(Applications.id),
|
||||||
|
limit?: number,
|
||||||
|
offset?: number,
|
||||||
|
extra?: Parameters<typeof db.query.Applications.findMany>[0],
|
||||||
|
): Promise<Application[]> {
|
||||||
|
const found = await db.query.Applications.findMany({
|
||||||
|
where: sql,
|
||||||
|
orderBy,
|
||||||
|
limit,
|
||||||
|
offset,
|
||||||
|
with: extra?.with,
|
||||||
|
});
|
||||||
|
|
||||||
|
return found.map((s) => new Application(s));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async getFromToken(
|
||||||
|
token: string,
|
||||||
|
): Promise<Application | null> {
|
||||||
|
const result = await db.query.Tokens.findFirst({
|
||||||
|
where: (tokens, { eq }) => eq(tokens.accessToken, token),
|
||||||
|
with: {
|
||||||
|
application: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return result?.application ? new Application(result.application) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static fromClientId(clientId: string): Promise<Application | null> {
|
||||||
|
return Application.fromSql(eq(Applications.clientId, clientId));
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(
|
||||||
|
newApplication: Partial<ApplicationType>,
|
||||||
|
): Promise<ApplicationType> {
|
||||||
|
await db
|
||||||
|
.update(Applications)
|
||||||
|
.set(newApplication)
|
||||||
|
.where(eq(Applications.id, this.id));
|
||||||
|
|
||||||
|
const updated = await Application.fromId(this.data.id);
|
||||||
|
|
||||||
|
if (!updated) {
|
||||||
|
throw new Error("Failed to update application");
|
||||||
|
}
|
||||||
|
|
||||||
|
this.data = updated.data;
|
||||||
|
return updated.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
save(): Promise<ApplicationType> {
|
||||||
|
return this.update(this.data);
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete(ids?: string[]): Promise<void> {
|
||||||
|
if (Array.isArray(ids)) {
|
||||||
|
await db.delete(Applications).where(inArray(Applications.id, ids));
|
||||||
|
} else {
|
||||||
|
await db.delete(Applications).where(eq(Applications.id, this.id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async insert(
|
||||||
|
data: InferInsertModel<typeof Applications>,
|
||||||
|
): Promise<Application> {
|
||||||
|
const inserted = (
|
||||||
|
await db.insert(Applications).values(data).returning()
|
||||||
|
)[0];
|
||||||
|
|
||||||
|
const application = await Application.fromId(inserted.id);
|
||||||
|
|
||||||
|
if (!application) {
|
||||||
|
throw new Error("Failed to insert application");
|
||||||
|
}
|
||||||
|
|
||||||
|
return application;
|
||||||
|
}
|
||||||
|
|
||||||
|
get id() {
|
||||||
|
return this.data.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public toApi(): APIApplication {
|
||||||
|
return {
|
||||||
|
name: this.data.name,
|
||||||
|
website: this.data.website,
|
||||||
|
vapid_key: this.data.vapidKey,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -27,10 +27,6 @@ import {
|
||||||
import { htmlToText } from "html-to-text";
|
import { htmlToText } from "html-to-text";
|
||||||
import { createRegExp, exactly, global } from "magic-regexp";
|
import { createRegExp, exactly, global } from "magic-regexp";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import {
|
|
||||||
type Application,
|
|
||||||
applicationToApi,
|
|
||||||
} from "~/classes/functions/application";
|
|
||||||
import {
|
import {
|
||||||
type StatusWithRelations,
|
type StatusWithRelations,
|
||||||
contentToHtml,
|
contentToHtml,
|
||||||
|
|
@ -47,6 +43,7 @@ import {
|
||||||
Users,
|
Users,
|
||||||
} from "~/drizzle/schema";
|
} from "~/drizzle/schema";
|
||||||
import { config } from "~/packages/config-manager";
|
import { config } from "~/packages/config-manager";
|
||||||
|
import { Application } from "./application.ts";
|
||||||
import { Attachment } from "./attachment.ts";
|
import { Attachment } from "./attachment.ts";
|
||||||
import { BaseInterface } from "./base.ts";
|
import { BaseInterface } from "./base.ts";
|
||||||
import { Emoji } from "./emoji.ts";
|
import { Emoji } from "./emoji.ts";
|
||||||
|
|
@ -904,7 +901,7 @@ export class Note extends BaseInterface<typeof Notes, StatusWithRelations> {
|
||||||
account: this.author.toApi(userFetching?.id === data.authorId),
|
account: this.author.toApi(userFetching?.id === data.authorId),
|
||||||
created_at: new Date(data.createdAt).toISOString(),
|
created_at: new Date(data.createdAt).toISOString(),
|
||||||
application: data.application
|
application: data.application
|
||||||
? applicationToApi(data.application)
|
? new Application(data.application).toApi()
|
||||||
: null,
|
: null,
|
||||||
card: null,
|
card: null,
|
||||||
content: replacedContent,
|
content: replacedContent,
|
||||||
|
|
|
||||||
|
|
@ -6,4 +6,5 @@ export { Emoji } from "~/packages/database-interface/emoji";
|
||||||
export { Instance } from "~/packages/database-interface/instance";
|
export { Instance } from "~/packages/database-interface/instance";
|
||||||
export { Note } from "~/packages/database-interface/note";
|
export { Note } from "~/packages/database-interface/note";
|
||||||
export { Timeline } from "~/packages/database-interface/timeline";
|
export { Timeline } from "~/packages/database-interface/timeline";
|
||||||
|
export { Application } from "~/packages/database-interface/application";
|
||||||
export { db } from "~/drizzle/db";
|
export { db } from "~/drizzle/db";
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,12 @@
|
||||||
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
import { afterAll, describe, expect, test } from "bun:test";
|
||||||
import { randomString } from "@/math";
|
import { randomString } from "@/math";
|
||||||
import { db } from "@versia/kit/db";
|
import { RolePermissions } from "@versia/kit/tables";
|
||||||
import { eq } from "@versia/kit/drizzle";
|
|
||||||
import { Applications, RolePermissions } from "@versia/kit/tables";
|
|
||||||
import { SignJWT } from "jose";
|
import { SignJWT } from "jose";
|
||||||
import { config } from "~/packages/config-manager";
|
import { config } from "~/packages/config-manager";
|
||||||
|
import { Application } from "~/packages/database-interface/application";
|
||||||
import { fakeRequest, getTestUsers } from "~/tests/utils";
|
import { fakeRequest, getTestUsers } from "~/tests/utils";
|
||||||
|
|
||||||
const { deleteUsers, tokens, users } = await getTestUsers(1);
|
const { deleteUsers, tokens, users } = await getTestUsers(1);
|
||||||
const clientId = "test-client-id";
|
|
||||||
const redirectUri = "https://example.com/callback";
|
|
||||||
const scope = "openid profile email";
|
|
||||||
const secret = "test-secret";
|
|
||||||
const privateKey = await crypto.subtle.importKey(
|
const privateKey = await crypto.subtle.importKey(
|
||||||
"pkcs8",
|
"pkcs8",
|
||||||
Buffer.from(
|
Buffer.from(
|
||||||
|
|
@ -23,19 +18,17 @@ const privateKey = await crypto.subtle.importKey(
|
||||||
["sign"],
|
["sign"],
|
||||||
);
|
);
|
||||||
|
|
||||||
beforeAll(async () => {
|
const application = await Application.insert({
|
||||||
await db.insert(Applications).values({
|
clientId: "test-client-id",
|
||||||
clientId,
|
redirectUri: "https://example.com/callback",
|
||||||
redirectUri,
|
scopes: "openid profile email",
|
||||||
scopes: scope,
|
name: "Test Application",
|
||||||
name: "Test Application",
|
secret: "test-secret",
|
||||||
secret,
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
afterAll(async () => {
|
afterAll(async () => {
|
||||||
await deleteUsers();
|
await deleteUsers();
|
||||||
await db.delete(Applications).where(eq(Applications.clientId, clientId));
|
await application.delete();
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("/oauth/authorize", () => {
|
describe("/oauth/authorize", () => {
|
||||||
|
|
@ -43,7 +36,7 @@ describe("/oauth/authorize", () => {
|
||||||
const jwt = await new SignJWT({
|
const jwt = await new SignJWT({
|
||||||
sub: users[0].id,
|
sub: users[0].id,
|
||||||
iss: new URL(config.http.base_url).origin,
|
iss: new URL(config.http.base_url).origin,
|
||||||
aud: clientId,
|
aud: application.data.clientId,
|
||||||
exp: Math.floor(Date.now() / 1000) + 60 * 60,
|
exp: Math.floor(Date.now() / 1000) + 60 * 60,
|
||||||
iat: Math.floor(Date.now() / 1000),
|
iat: Math.floor(Date.now() / 1000),
|
||||||
nbf: Math.floor(Date.now() / 1000),
|
nbf: Math.floor(Date.now() / 1000),
|
||||||
|
|
@ -59,10 +52,10 @@ describe("/oauth/authorize", () => {
|
||||||
Cookie: `jwt=${jwt}`,
|
Cookie: `jwt=${jwt}`,
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
redirect_uri: redirectUri,
|
redirect_uri: application.data.redirectUri,
|
||||||
response_type: "code",
|
response_type: "code",
|
||||||
scope,
|
scope: application.data.scopes,
|
||||||
state: "test-state",
|
state: "test-state",
|
||||||
code_challenge: randomString(43),
|
code_challenge: randomString(43),
|
||||||
code_challenge_method: "S256",
|
code_challenge_method: "S256",
|
||||||
|
|
@ -75,7 +68,9 @@ describe("/oauth/authorize", () => {
|
||||||
config.http.base_url,
|
config.http.base_url,
|
||||||
);
|
);
|
||||||
const params = new URLSearchParams(location.search);
|
const params = new URLSearchParams(location.search);
|
||||||
expect(location.origin + location.pathname).toBe(redirectUri);
|
expect(location.origin + location.pathname).toBe(
|
||||||
|
application.data.redirectUri,
|
||||||
|
);
|
||||||
expect(params.get("code")).toBeTruthy();
|
expect(params.get("code")).toBeTruthy();
|
||||||
expect(params.get("state")).toBe("test-state");
|
expect(params.get("state")).toBe("test-state");
|
||||||
});
|
});
|
||||||
|
|
@ -89,10 +84,10 @@ describe("/oauth/authorize", () => {
|
||||||
Cookie: "jwt=invalid-jwt",
|
Cookie: "jwt=invalid-jwt",
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
redirect_uri: redirectUri,
|
redirect_uri: application.data.redirectUri,
|
||||||
response_type: "code",
|
response_type: "code",
|
||||||
scope,
|
scope: application.data.scopes,
|
||||||
state: "test-state",
|
state: "test-state",
|
||||||
code_challenge: randomString(43),
|
code_challenge: randomString(43),
|
||||||
code_challenge_method: "S256",
|
code_challenge_method: "S256",
|
||||||
|
|
@ -115,7 +110,7 @@ describe("/oauth/authorize", () => {
|
||||||
const jwt = await new SignJWT({
|
const jwt = await new SignJWT({
|
||||||
sub: users[0].id,
|
sub: users[0].id,
|
||||||
iss: new URL(config.http.base_url).origin,
|
iss: new URL(config.http.base_url).origin,
|
||||||
aud: clientId,
|
aud: application.data.clientId,
|
||||||
})
|
})
|
||||||
.setProtectedHeader({ alg: "EdDSA" })
|
.setProtectedHeader({ alg: "EdDSA" })
|
||||||
.sign(privateKey);
|
.sign(privateKey);
|
||||||
|
|
@ -128,10 +123,10 @@ describe("/oauth/authorize", () => {
|
||||||
Cookie: `jwt=${jwt}`,
|
Cookie: `jwt=${jwt}`,
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
redirect_uri: redirectUri,
|
redirect_uri: application.data.redirectUri,
|
||||||
response_type: "code",
|
response_type: "code",
|
||||||
scope,
|
scope: application.data.scopes,
|
||||||
state: "test-state",
|
state: "test-state",
|
||||||
code_challenge: randomString(43),
|
code_challenge: randomString(43),
|
||||||
code_challenge_method: "S256",
|
code_challenge_method: "S256",
|
||||||
|
|
@ -153,7 +148,7 @@ describe("/oauth/authorize", () => {
|
||||||
test("should return error for user not found", async () => {
|
test("should return error for user not found", async () => {
|
||||||
const jwt = await new SignJWT({
|
const jwt = await new SignJWT({
|
||||||
sub: "non-existent-user",
|
sub: "non-existent-user",
|
||||||
aud: clientId,
|
aud: application.data.clientId,
|
||||||
exp: Math.floor(Date.now() / 1000) + 60 * 60,
|
exp: Math.floor(Date.now() / 1000) + 60 * 60,
|
||||||
iss: new URL(config.http.base_url).origin,
|
iss: new URL(config.http.base_url).origin,
|
||||||
iat: Math.floor(Date.now() / 1000),
|
iat: Math.floor(Date.now() / 1000),
|
||||||
|
|
@ -170,10 +165,10 @@ describe("/oauth/authorize", () => {
|
||||||
Cookie: `jwt=${jwt}`,
|
Cookie: `jwt=${jwt}`,
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
redirect_uri: redirectUri,
|
redirect_uri: application.data.redirectUri,
|
||||||
response_type: "code",
|
response_type: "code",
|
||||||
scope,
|
scope: application.data.scopes,
|
||||||
state: "test-state",
|
state: "test-state",
|
||||||
code_challenge: randomString(43),
|
code_challenge: randomString(43),
|
||||||
code_challenge_method: "S256",
|
code_challenge_method: "S256",
|
||||||
|
|
@ -193,7 +188,7 @@ describe("/oauth/authorize", () => {
|
||||||
|
|
||||||
const jwt2 = await new SignJWT({
|
const jwt2 = await new SignJWT({
|
||||||
sub: "23e42862-d5df-49a8-95b5-52d8c6a11aea",
|
sub: "23e42862-d5df-49a8-95b5-52d8c6a11aea",
|
||||||
aud: clientId,
|
aud: application.data.clientId,
|
||||||
exp: Math.floor(Date.now() / 1000) + 60 * 60,
|
exp: Math.floor(Date.now() / 1000) + 60 * 60,
|
||||||
iss: new URL(config.http.base_url).origin,
|
iss: new URL(config.http.base_url).origin,
|
||||||
iat: Math.floor(Date.now() / 1000),
|
iat: Math.floor(Date.now() / 1000),
|
||||||
|
|
@ -210,10 +205,10 @@ describe("/oauth/authorize", () => {
|
||||||
Cookie: `jwt=${jwt2}`,
|
Cookie: `jwt=${jwt2}`,
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
redirect_uri: redirectUri,
|
redirect_uri: application.data.redirectUri,
|
||||||
response_type: "code",
|
response_type: "code",
|
||||||
scope,
|
scope: application.data.scopes,
|
||||||
state: "test-state",
|
state: "test-state",
|
||||||
code_challenge: randomString(43),
|
code_challenge: randomString(43),
|
||||||
code_challenge_method: "S256",
|
code_challenge_method: "S256",
|
||||||
|
|
@ -239,7 +234,7 @@ describe("/oauth/authorize", () => {
|
||||||
const jwt = await new SignJWT({
|
const jwt = await new SignJWT({
|
||||||
sub: users[0].id,
|
sub: users[0].id,
|
||||||
iss: new URL(config.http.base_url).origin,
|
iss: new URL(config.http.base_url).origin,
|
||||||
aud: clientId,
|
aud: application.data.clientId,
|
||||||
exp: Math.floor(Date.now() / 1000) + 60 * 60,
|
exp: Math.floor(Date.now() / 1000) + 60 * 60,
|
||||||
iat: Math.floor(Date.now() / 1000),
|
iat: Math.floor(Date.now() / 1000),
|
||||||
nbf: Math.floor(Date.now() / 1000),
|
nbf: Math.floor(Date.now() / 1000),
|
||||||
|
|
@ -255,10 +250,10 @@ describe("/oauth/authorize", () => {
|
||||||
Cookie: `jwt=${jwt}`,
|
Cookie: `jwt=${jwt}`,
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
redirect_uri: redirectUri,
|
redirect_uri: application.data.redirectUri,
|
||||||
response_type: "code",
|
response_type: "code",
|
||||||
scope,
|
scope: application.data.scopes,
|
||||||
state: "test-state",
|
state: "test-state",
|
||||||
code_challenge: randomString(43),
|
code_challenge: randomString(43),
|
||||||
code_challenge_method: "S256",
|
code_challenge_method: "S256",
|
||||||
|
|
@ -300,9 +295,9 @@ describe("/oauth/authorize", () => {
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
client_id: "invalid-client-id",
|
client_id: "invalid-client-id",
|
||||||
redirect_uri: redirectUri,
|
redirect_uri: application.data.redirectUri,
|
||||||
response_type: "code",
|
response_type: "code",
|
||||||
scope,
|
scope: application.data.scopes,
|
||||||
state: "test-state",
|
state: "test-state",
|
||||||
code_challenge: randomString(43),
|
code_challenge: randomString(43),
|
||||||
code_challenge_method: "S256",
|
code_challenge_method: "S256",
|
||||||
|
|
@ -325,7 +320,7 @@ describe("/oauth/authorize", () => {
|
||||||
const jwt = await new SignJWT({
|
const jwt = await new SignJWT({
|
||||||
sub: users[0].id,
|
sub: users[0].id,
|
||||||
iss: new URL(config.http.base_url).origin,
|
iss: new URL(config.http.base_url).origin,
|
||||||
aud: clientId,
|
aud: application.data.clientId,
|
||||||
exp: Math.floor(Date.now() / 1000) + 60 * 60,
|
exp: Math.floor(Date.now() / 1000) + 60 * 60,
|
||||||
iat: Math.floor(Date.now() / 1000),
|
iat: Math.floor(Date.now() / 1000),
|
||||||
nbf: Math.floor(Date.now() / 1000),
|
nbf: Math.floor(Date.now() / 1000),
|
||||||
|
|
@ -341,10 +336,10 @@ describe("/oauth/authorize", () => {
|
||||||
Cookie: `jwt=${jwt}`,
|
Cookie: `jwt=${jwt}`,
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
redirect_uri: "https://invalid.com/callback",
|
redirect_uri: "https://invalid.com/callback",
|
||||||
response_type: "code",
|
response_type: "code",
|
||||||
scope,
|
scope: application.data.scopes,
|
||||||
state: "test-state",
|
state: "test-state",
|
||||||
code_challenge: randomString(43),
|
code_challenge: randomString(43),
|
||||||
code_challenge_method: "S256",
|
code_challenge_method: "S256",
|
||||||
|
|
@ -367,7 +362,7 @@ describe("/oauth/authorize", () => {
|
||||||
const jwt = await new SignJWT({
|
const jwt = await new SignJWT({
|
||||||
sub: users[0].id,
|
sub: users[0].id,
|
||||||
iss: new URL(config.http.base_url).origin,
|
iss: new URL(config.http.base_url).origin,
|
||||||
aud: clientId,
|
aud: application.data.clientId,
|
||||||
exp: Math.floor(Date.now() / 1000) + 60 * 60,
|
exp: Math.floor(Date.now() / 1000) + 60 * 60,
|
||||||
iat: Math.floor(Date.now() / 1000),
|
iat: Math.floor(Date.now() / 1000),
|
||||||
nbf: Math.floor(Date.now() / 1000),
|
nbf: Math.floor(Date.now() / 1000),
|
||||||
|
|
@ -383,8 +378,8 @@ describe("/oauth/authorize", () => {
|
||||||
Cookie: `jwt=${jwt}`,
|
Cookie: `jwt=${jwt}`,
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
redirect_uri: redirectUri,
|
redirect_uri: application.data.redirectUri,
|
||||||
response_type: "code",
|
response_type: "code",
|
||||||
scope: "invalid-scope",
|
scope: "invalid-scope",
|
||||||
state: "test-state",
|
state: "test-state",
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ import { type JWTPayload, SignJWT, jwtVerify } from "jose";
|
||||||
import { JOSEError } from "jose/errors";
|
import { JOSEError } from "jose/errors";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { TokenType } from "~/classes/functions/token";
|
import { TokenType } from "~/classes/functions/token";
|
||||||
|
import { Application } from "~/packages/database-interface/application.ts";
|
||||||
import { User } from "~/packages/database-interface/user";
|
import { User } from "~/packages/database-interface/user";
|
||||||
import type { PluginType } from "../index.ts";
|
import type { PluginType } from "../index.ts";
|
||||||
|
|
||||||
|
|
@ -197,9 +198,7 @@ export default (plugin: PluginType) =>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const application = await db.query.Applications.findFirst({
|
const application = await Application.fromClientId(client_id);
|
||||||
where: (app, { eq }) => eq(app.clientId, client_id),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!application) {
|
if (!application) {
|
||||||
errorSearchParams.append("error", "invalid_request");
|
errorSearchParams.append("error", "invalid_request");
|
||||||
|
|
@ -213,7 +212,7 @@ export default (plugin: PluginType) =>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (application.redirectUri !== redirect_uri) {
|
if (application.data.redirectUri !== redirect_uri) {
|
||||||
errorSearchParams.append("error", "invalid_request");
|
errorSearchParams.append("error", "invalid_request");
|
||||||
errorSearchParams.append(
|
errorSearchParams.append(
|
||||||
"error_description",
|
"error_description",
|
||||||
|
|
@ -230,7 +229,7 @@ export default (plugin: PluginType) =>
|
||||||
scope &&
|
scope &&
|
||||||
!scope
|
!scope
|
||||||
.split(" ")
|
.split(" ")
|
||||||
.every((s) => application.scopes.includes(s))
|
.every((s) => application.data.scopes.includes(s))
|
||||||
) {
|
) {
|
||||||
errorSearchParams.append("error", "invalid_scope");
|
errorSearchParams.append("error", "invalid_scope");
|
||||||
errorSearchParams.append(
|
errorSearchParams.append(
|
||||||
|
|
@ -288,10 +287,10 @@ export default (plugin: PluginType) =>
|
||||||
await db.insert(Tokens).values({
|
await db.insert(Tokens).values({
|
||||||
accessToken: randomString(64, "base64url"),
|
accessToken: randomString(64, "base64url"),
|
||||||
code,
|
code,
|
||||||
scope: scope ?? application.scopes,
|
scope: scope ?? application.data.scopes,
|
||||||
tokenType: TokenType.Bearer,
|
tokenType: TokenType.Bearer,
|
||||||
applicationId: application.id,
|
applicationId: application.id,
|
||||||
redirectUri: redirect_uri ?? application.redirectUri,
|
redirectUri: redirect_uri ?? application.data.redirectUri,
|
||||||
expiresAt: new Date(
|
expiresAt: new Date(
|
||||||
Date.now() + 60 * 60 * 24 * 14,
|
Date.now() + 60 * 60 * 24 * 14,
|
||||||
).toISOString(),
|
).toISOString(),
|
||||||
|
|
@ -310,7 +309,7 @@ export default (plugin: PluginType) =>
|
||||||
"/oauth/code",
|
"/oauth/code",
|
||||||
context.get("config").http.base_url,
|
context.get("config").http.base_url,
|
||||||
)
|
)
|
||||||
: new URL(redirect_uri ?? application.redirectUri);
|
: new URL(redirect_uri ?? application.data.redirectUri);
|
||||||
|
|
||||||
redirectUri.searchParams.append("code", code);
|
redirectUri.searchParams.append("code", code);
|
||||||
state && redirectUri.searchParams.append("state", state);
|
state && redirectUri.searchParams.append("state", state);
|
||||||
|
|
|
||||||
|
|
@ -1,26 +1,17 @@
|
||||||
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
import { afterAll, describe, expect, test } from "bun:test";
|
||||||
import { db } from "@versia/kit/db";
|
import { Application } from "~/packages/database-interface/application";
|
||||||
import { eq } from "drizzle-orm";
|
|
||||||
import { Applications } from "~/drizzle/schema";
|
|
||||||
import { fakeRequest } from "~/tests/utils";
|
import { fakeRequest } from "~/tests/utils";
|
||||||
|
|
||||||
const clientId = "test-client-id";
|
const application = await Application.insert({
|
||||||
const redirectUri = "https://example.com/callback";
|
clientId: "test-client-id",
|
||||||
const scope = "openid profile email";
|
redirectUri: "https://example.com/callback",
|
||||||
const secret = "test-secret";
|
scopes: "openid profile email",
|
||||||
|
secret: "test-secret",
|
||||||
beforeAll(async () => {
|
name: "Test Application",
|
||||||
await db.insert(Applications).values({
|
|
||||||
clientId,
|
|
||||||
redirectUri,
|
|
||||||
scopes: scope,
|
|
||||||
name: "Test Application",
|
|
||||||
secret,
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
afterAll(async () => {
|
afterAll(async () => {
|
||||||
await db.delete(Applications).where(eq(Applications.clientId, clientId));
|
await application.delete();
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("/.well-known/jwks", () => {
|
describe("/.well-known/jwks", () => {
|
||||||
|
|
|
||||||
|
|
@ -1,38 +1,30 @@
|
||||||
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
||||||
import { db } from "@versia/kit/db";
|
import { db } from "@versia/kit/db";
|
||||||
import { eq } from "@versia/kit/drizzle";
|
import { eq } from "@versia/kit/drizzle";
|
||||||
import { Applications, Tokens } from "@versia/kit/tables";
|
import { Tokens } from "@versia/kit/tables";
|
||||||
|
import { Application } from "~/packages/database-interface/application";
|
||||||
import { fakeRequest, getTestUsers } from "~/tests/utils";
|
import { fakeRequest, getTestUsers } from "~/tests/utils";
|
||||||
|
|
||||||
const { deleteUsers, users } = await getTestUsers(1);
|
const { deleteUsers, users } = await getTestUsers(1);
|
||||||
const clientId = "test-client-id";
|
|
||||||
const redirectUri = "https://example.com/callback";
|
const application = await Application.insert({
|
||||||
const scope = "openid profile email";
|
clientId: "test-client-id",
|
||||||
const secret = "test-secret";
|
redirectUri: "https://example.com/callback",
|
||||||
|
scopes: "openid profile email",
|
||||||
|
secret: "test-secret",
|
||||||
|
name: "Test Application",
|
||||||
|
});
|
||||||
|
|
||||||
beforeAll(async () => {
|
beforeAll(async () => {
|
||||||
const application = (
|
|
||||||
await db
|
|
||||||
.insert(Applications)
|
|
||||||
.values({
|
|
||||||
clientId,
|
|
||||||
redirectUri,
|
|
||||||
scopes: scope,
|
|
||||||
name: "Test Application",
|
|
||||||
secret,
|
|
||||||
})
|
|
||||||
.returning()
|
|
||||||
)[0];
|
|
||||||
|
|
||||||
await db.insert(Tokens).values({
|
await db.insert(Tokens).values({
|
||||||
code: "test-code",
|
code: "test-code",
|
||||||
redirectUri,
|
redirectUri: application.data.redirectUri,
|
||||||
clientId,
|
clientId: application.data.clientId,
|
||||||
accessToken: "test-access-token",
|
accessToken: "test-access-token",
|
||||||
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
|
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
tokenType: "Bearer",
|
tokenType: "Bearer",
|
||||||
scope,
|
scope: application.data.scopes,
|
||||||
userId: users[0].id,
|
userId: users[0].id,
|
||||||
applicationId: application.id,
|
applicationId: application.id,
|
||||||
});
|
});
|
||||||
|
|
@ -40,8 +32,10 @@ beforeAll(async () => {
|
||||||
|
|
||||||
afterAll(async () => {
|
afterAll(async () => {
|
||||||
await deleteUsers();
|
await deleteUsers();
|
||||||
await db.delete(Applications).where(eq(Applications.clientId, clientId));
|
await application.delete();
|
||||||
await db.delete(Tokens).where(eq(Tokens.clientId, clientId));
|
await db
|
||||||
|
.delete(Tokens)
|
||||||
|
.where(eq(Tokens.clientId, application.data.clientId));
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("/oauth/revoke", () => {
|
describe("/oauth/revoke", () => {
|
||||||
|
|
@ -52,8 +46,8 @@ describe("/oauth/revoke", () => {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
client_secret: secret,
|
client_secret: application.data.secret,
|
||||||
token: "test-access-token",
|
token: "test-access-token",
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
@ -70,8 +64,8 @@ describe("/oauth/revoke", () => {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
client_secret: secret,
|
client_secret: application.data.secret,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -90,7 +84,7 @@ describe("/oauth/revoke", () => {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
client_secret: "invalid-secret",
|
client_secret: "invalid-secret",
|
||||||
token: "test-access-token",
|
token: "test-access-token",
|
||||||
}),
|
}),
|
||||||
|
|
@ -111,8 +105,8 @@ describe("/oauth/revoke", () => {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
client_secret: secret,
|
client_secret: application.data.secret,
|
||||||
token: "invalid-token",
|
token: "invalid-token",
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
@ -133,7 +127,7 @@ describe("/oauth/revoke", () => {
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
client_id: "unauthorized-client-id",
|
client_id: "unauthorized-client-id",
|
||||||
client_secret: secret,
|
client_secret: application.data.secret,
|
||||||
token: "test-access-token",
|
token: "test-access-token",
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ import {
|
||||||
generateRandomCodeVerifier,
|
generateRandomCodeVerifier,
|
||||||
processDiscoveryResponse,
|
processDiscoveryResponse,
|
||||||
} from "oauth4webapi";
|
} from "oauth4webapi";
|
||||||
|
import { Application } from "~/packages/database-interface/application.ts";
|
||||||
import type { PluginType } from "../../index.ts";
|
import type { PluginType } from "../../index.ts";
|
||||||
import { oauthRedirectUri } from "../../utils.ts";
|
import { oauthRedirectUri } from "../../utils.ts";
|
||||||
|
|
||||||
|
|
@ -83,10 +84,7 @@ export default (plugin: PluginType) => {
|
||||||
|
|
||||||
const codeVerifier = generateRandomCodeVerifier();
|
const codeVerifier = generateRandomCodeVerifier();
|
||||||
|
|
||||||
const application = await db.query.Applications.findFirst({
|
const application = await Application.fromClientId(client_id);
|
||||||
where: (application, { eq }) =>
|
|
||||||
eq(application.clientId, client_id),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!application) {
|
if (!application) {
|
||||||
errorSearchParams.append("error", "invalid_request");
|
errorSearchParams.append("error", "invalid_request");
|
||||||
|
|
|
||||||
|
|
@ -1,41 +1,40 @@
|
||||||
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
||||||
import { db } from "@versia/kit/db";
|
import { db } from "@versia/kit/db";
|
||||||
import { eq } from "@versia/kit/drizzle";
|
import { eq } from "@versia/kit/drizzle";
|
||||||
import { Applications, Tokens } from "@versia/kit/tables";
|
import { Tokens } from "@versia/kit/tables";
|
||||||
|
import { Application } from "~/packages/database-interface/application";
|
||||||
import { fakeRequest, getTestUsers } from "~/tests/utils";
|
import { fakeRequest, getTestUsers } from "~/tests/utils";
|
||||||
|
|
||||||
const { deleteUsers, users } = await getTestUsers(1);
|
const { deleteUsers, users } = await getTestUsers(1);
|
||||||
const clientId = "test-client-id";
|
|
||||||
const redirectUri = "https://example.com/callback";
|
const application = await Application.insert({
|
||||||
const scope = "openid profile email";
|
clientId: "test-client-id",
|
||||||
const secret = "test-secret";
|
redirectUri: "https://example.com/callback",
|
||||||
|
scopes: "openid profile email",
|
||||||
|
secret: "test-secret",
|
||||||
|
name: "Test Application",
|
||||||
|
});
|
||||||
|
|
||||||
beforeAll(async () => {
|
beforeAll(async () => {
|
||||||
await db.insert(Applications).values({
|
|
||||||
clientId,
|
|
||||||
redirectUri,
|
|
||||||
scopes: scope,
|
|
||||||
name: "Test Application",
|
|
||||||
secret,
|
|
||||||
});
|
|
||||||
|
|
||||||
await db.insert(Tokens).values({
|
await db.insert(Tokens).values({
|
||||||
code: "test-code",
|
code: "test-code",
|
||||||
redirectUri,
|
redirectUri: application.data.redirectUri,
|
||||||
clientId,
|
clientId: application.data.clientId,
|
||||||
accessToken: "test-access-token",
|
accessToken: "test-access-token",
|
||||||
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
|
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
tokenType: "Bearer",
|
tokenType: "Bearer",
|
||||||
scope,
|
scope: application.data.scopes,
|
||||||
userId: users[0].id,
|
userId: users[0].id,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
afterAll(async () => {
|
afterAll(async () => {
|
||||||
await deleteUsers();
|
await deleteUsers();
|
||||||
await db.delete(Applications).where(eq(Applications.clientId, clientId));
|
await application.delete();
|
||||||
await db.delete(Tokens).where(eq(Tokens.clientId, clientId));
|
await db
|
||||||
|
.delete(Tokens)
|
||||||
|
.where(eq(Tokens.clientId, application.data.clientId));
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("/oauth/token", () => {
|
describe("/oauth/token", () => {
|
||||||
|
|
@ -48,9 +47,9 @@ describe("/oauth/token", () => {
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
grant_type: "authorization_code",
|
grant_type: "authorization_code",
|
||||||
code: "test-code",
|
code: "test-code",
|
||||||
redirect_uri: redirectUri,
|
redirect_uri: application.data.redirectUri,
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
client_secret: secret,
|
client_secret: application.data.secret,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -69,9 +68,9 @@ describe("/oauth/token", () => {
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
grant_type: "authorization_code",
|
grant_type: "authorization_code",
|
||||||
redirect_uri: redirectUri,
|
redirect_uri: application.data.redirectUri,
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
client_secret: secret,
|
client_secret: application.data.secret,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -90,8 +89,8 @@ describe("/oauth/token", () => {
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
grant_type: "authorization_code",
|
grant_type: "authorization_code",
|
||||||
code: "test-code",
|
code: "test-code",
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
client_secret: secret,
|
client_secret: application.data.secret,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -110,8 +109,8 @@ describe("/oauth/token", () => {
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
grant_type: "authorization_code",
|
grant_type: "authorization_code",
|
||||||
code: "test-code",
|
code: "test-code",
|
||||||
redirect_uri: redirectUri,
|
redirect_uri: application.data.redirectUri,
|
||||||
client_secret: secret,
|
client_secret: application.data.secret,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -130,8 +129,8 @@ describe("/oauth/token", () => {
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
grant_type: "authorization_code",
|
grant_type: "authorization_code",
|
||||||
code: "test-code",
|
code: "test-code",
|
||||||
redirect_uri: redirectUri,
|
redirect_uri: application.data.redirectUri,
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
client_secret: "invalid-secret",
|
client_secret: "invalid-secret",
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
@ -151,9 +150,9 @@ describe("/oauth/token", () => {
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
grant_type: "authorization_code",
|
grant_type: "authorization_code",
|
||||||
code: "invalid-code",
|
code: "invalid-code",
|
||||||
redirect_uri: redirectUri,
|
redirect_uri: application.data.redirectUri,
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
client_secret: secret,
|
client_secret: application.data.secret,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -172,9 +171,9 @@ describe("/oauth/token", () => {
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
grant_type: "refresh_token",
|
grant_type: "refresh_token",
|
||||||
code: "test-code",
|
code: "test-code",
|
||||||
redirect_uri: redirectUri,
|
redirect_uri: application.data.redirectUri,
|
||||||
client_id: clientId,
|
client_id: application.data.clientId,
|
||||||
client_secret: secret,
|
client_secret: application.data.secret,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ import { createRoute, z } from "@hono/zod-openapi";
|
||||||
import { db } from "@versia/kit/db";
|
import { db } from "@versia/kit/db";
|
||||||
import { eq } from "@versia/kit/drizzle";
|
import { eq } from "@versia/kit/drizzle";
|
||||||
import { Tokens } from "@versia/kit/tables";
|
import { Tokens } from "@versia/kit/tables";
|
||||||
|
import { Application } from "~/packages/database-interface/application.ts";
|
||||||
import type { PluginType } from "../../index.ts";
|
import type { PluginType } from "../../index.ts";
|
||||||
|
|
||||||
export const schemas = {
|
export const schemas = {
|
||||||
|
|
@ -140,12 +141,10 @@ export default (plugin: PluginType) => {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify the client_secret
|
// Verify the client_secret
|
||||||
const client = await db.query.Applications.findFirst({
|
const client =
|
||||||
where: (application, { eq }) =>
|
await Application.fromClientId(client_id);
|
||||||
eq(application.clientId, client_id),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!client || client.secret !== client_secret) {
|
if (!client || client.data.secret !== client_secret) {
|
||||||
return context.json(
|
return context.json(
|
||||||
{
|
{
|
||||||
error: "invalid_client",
|
error: "invalid_client",
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,7 @@
|
||||||
import { auth } from "@/api";
|
import { auth } from "@/api";
|
||||||
import { db } from "@versia/kit/db";
|
import { db } from "@versia/kit/db";
|
||||||
import {
|
import { Application } from "@versia/kit/db";
|
||||||
Applications,
|
import { OpenIdLoginFlows, RolePermissions } from "@versia/kit/tables";
|
||||||
OpenIdLoginFlows,
|
|
||||||
RolePermissions,
|
|
||||||
} from "@versia/kit/tables";
|
|
||||||
import {
|
import {
|
||||||
calculatePKCECodeChallenge,
|
calculatePKCECodeChallenge,
|
||||||
generateRandomCodeVerifier,
|
generateRandomCodeVerifier,
|
||||||
|
|
@ -169,22 +166,17 @@ export default (plugin: PluginType) => {
|
||||||
issuerId,
|
issuerId,
|
||||||
);
|
);
|
||||||
|
|
||||||
const application = (
|
const application = await Application.insert({
|
||||||
await db
|
clientId:
|
||||||
.insert(Applications)
|
user.id +
|
||||||
.values({
|
Buffer.from(
|
||||||
clientId:
|
crypto.getRandomValues(new Uint8Array(32)),
|
||||||
user.id +
|
).toString("base64"),
|
||||||
Buffer.from(
|
name: "Versia",
|
||||||
crypto.getRandomValues(new Uint8Array(32)),
|
redirectUri,
|
||||||
).toString("base64"),
|
scopes: "openid profile email",
|
||||||
name: "Versia",
|
secret: "",
|
||||||
redirectUri,
|
});
|
||||||
scopes: "openid profile email",
|
|
||||||
secret: "",
|
|
||||||
})
|
|
||||||
.returning()
|
|
||||||
)[0];
|
|
||||||
|
|
||||||
// Store into database
|
// Store into database
|
||||||
const newFlow = (
|
const newFlow = (
|
||||||
|
|
|
||||||
|
|
@ -1,135 +1,121 @@
|
||||||
import { describe, expect, it } from "bun:test";
|
import { describe, expect, it } from "bun:test";
|
||||||
import { checkIfOauthIsValid } from "@/oauth";
|
import { checkIfOauthIsValid } from "@/oauth";
|
||||||
import type { Application } from "~/classes/functions/application";
|
import {
|
||||||
|
Application,
|
||||||
|
type ApplicationType,
|
||||||
|
} from "~/packages/database-interface/application";
|
||||||
|
|
||||||
describe("checkIfOauthIsValid", () => {
|
describe("checkIfOauthIsValid", () => {
|
||||||
it("should return true when routeScopes and application.scopes are empty", () => {
|
it("should return true when routeScopes and application.scopes are empty", () => {
|
||||||
const application = { scopes: "" };
|
const application = new Application({ scopes: "" } as ApplicationType);
|
||||||
const routeScopes: string[] = [];
|
const routeScopes: string[] = [];
|
||||||
const result = checkIfOauthIsValid(
|
const result = checkIfOauthIsValid(application, routeScopes);
|
||||||
application as Application,
|
|
||||||
routeScopes,
|
|
||||||
);
|
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return true when routeScopes is empty and application.scopes contains write:* or write", () => {
|
it("should return true when routeScopes is empty and application.scopes contains write:* or write", () => {
|
||||||
const application = { scopes: "write:*" };
|
const application = new Application({
|
||||||
|
scopes: "write:*",
|
||||||
|
} as ApplicationType);
|
||||||
const routeScopes: string[] = [];
|
const routeScopes: string[] = [];
|
||||||
const result = checkIfOauthIsValid(
|
const result = checkIfOauthIsValid(application, routeScopes);
|
||||||
application as Application,
|
|
||||||
routeScopes,
|
|
||||||
);
|
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return true when routeScopes is empty and application.scopes contains read:* or read", () => {
|
it("should return true when routeScopes is empty and application.scopes contains read:* or read", () => {
|
||||||
const application = { scopes: "read:*" };
|
const application = new Application({
|
||||||
|
scopes: "read:*",
|
||||||
|
} as ApplicationType);
|
||||||
const routeScopes: string[] = [];
|
const routeScopes: string[] = [];
|
||||||
const result = checkIfOauthIsValid(
|
const result = checkIfOauthIsValid(application, routeScopes);
|
||||||
application as Application,
|
|
||||||
routeScopes,
|
|
||||||
);
|
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return true when routeScopes contains only write: permissions and application.scopes contains write:* or write", () => {
|
it("should return true when routeScopes contains only write: permissions and application.scopes contains write:* or write", () => {
|
||||||
const application = { scopes: "write:*" };
|
const application = new Application({
|
||||||
|
scopes: "write:*",
|
||||||
|
} as ApplicationType);
|
||||||
const routeScopes = ["write:users", "write:posts"];
|
const routeScopes = ["write:users", "write:posts"];
|
||||||
const result = checkIfOauthIsValid(
|
const result = checkIfOauthIsValid(application, routeScopes);
|
||||||
application as Application,
|
|
||||||
routeScopes,
|
|
||||||
);
|
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return true when routeScopes contains only read: permissions and application.scopes contains read:* or read", () => {
|
it("should return true when routeScopes contains only read: permissions and application.scopes contains read:* or read", () => {
|
||||||
const application = { scopes: "read:*" };
|
const application = new Application({
|
||||||
|
scopes: "read:*",
|
||||||
|
} as ApplicationType);
|
||||||
const routeScopes = ["read:users", "read:posts"];
|
const routeScopes = ["read:users", "read:posts"];
|
||||||
const result = checkIfOauthIsValid(
|
const result = checkIfOauthIsValid(application, routeScopes);
|
||||||
application as Application,
|
|
||||||
routeScopes,
|
|
||||||
);
|
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return true when routeScopes contains both write: and read: permissions and application.scopes contains write:* or write and read:* or read", () => {
|
it("should return true when routeScopes contains both write: and read: permissions and application.scopes contains write:* or write and read:* or read", () => {
|
||||||
const application = { scopes: "write:* read:*" };
|
const application = new Application({
|
||||||
|
scopes: "write:* read:*",
|
||||||
|
} as ApplicationType);
|
||||||
const routeScopes = ["write:users", "read:posts"];
|
const routeScopes = ["write:users", "read:posts"];
|
||||||
const result = checkIfOauthIsValid(
|
const result = checkIfOauthIsValid(application, routeScopes);
|
||||||
application as Application,
|
|
||||||
routeScopes,
|
|
||||||
);
|
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return false when routeScopes contains write: permissions but application.scopes does not contain write:* or write", () => {
|
it("should return false when routeScopes contains write: permissions but application.scopes does not contain write:* or write", () => {
|
||||||
const application = { scopes: "read:*" };
|
const application = new Application({
|
||||||
|
scopes: "read:*",
|
||||||
|
} as ApplicationType);
|
||||||
const routeScopes = ["write:users", "write:posts"];
|
const routeScopes = ["write:users", "write:posts"];
|
||||||
const result = checkIfOauthIsValid(
|
const result = checkIfOauthIsValid(application, routeScopes);
|
||||||
application as Application,
|
|
||||||
routeScopes,
|
|
||||||
);
|
|
||||||
expect(result).toBe(false);
|
expect(result).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return false when routeScopes contains read: permissions but application.scopes does not contain read:* or read", () => {
|
it("should return false when routeScopes contains read: permissions but application.scopes does not contain read:* or read", () => {
|
||||||
const application = { scopes: "write:*" };
|
const application = new Application({
|
||||||
|
scopes: "write:*",
|
||||||
|
} as ApplicationType);
|
||||||
const routeScopes = ["read:users", "read:posts"];
|
const routeScopes = ["read:users", "read:posts"];
|
||||||
const result = checkIfOauthIsValid(
|
const result = checkIfOauthIsValid(application, routeScopes);
|
||||||
application as Application,
|
|
||||||
routeScopes,
|
|
||||||
);
|
|
||||||
expect(result).toBe(false);
|
expect(result).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return false when routeScopes contains both write: and read: permissions but application.scopes does not contain write:* or write and read:* or read", () => {
|
it("should return false when routeScopes contains both write: and read: permissions but application.scopes does not contain write:* or write and read:* or read", () => {
|
||||||
const application = { scopes: "" };
|
const application = new Application({ scopes: "" } as ApplicationType);
|
||||||
const routeScopes = ["write:users", "read:posts"];
|
const routeScopes = ["write:users", "read:posts"];
|
||||||
const result = checkIfOauthIsValid(
|
const result = checkIfOauthIsValid(application, routeScopes);
|
||||||
application as Application,
|
|
||||||
routeScopes,
|
|
||||||
);
|
|
||||||
expect(result).toBe(false);
|
expect(result).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return true when routeScopes contains a mix of valid and invalid permissions and application.scopes contains all the required permissions", () => {
|
it("should return true when routeScopes contains a mix of valid and invalid permissions and application.scopes contains all the required permissions", () => {
|
||||||
const application = { scopes: "write:* read:*" };
|
const application = new Application({
|
||||||
|
scopes: "write:* read:*",
|
||||||
|
} as ApplicationType);
|
||||||
const routeScopes = ["write:users", "invalid:permission", "read:posts"];
|
const routeScopes = ["write:users", "invalid:permission", "read:posts"];
|
||||||
const result = checkIfOauthIsValid(
|
const result = checkIfOauthIsValid(application, routeScopes);
|
||||||
application as Application,
|
|
||||||
routeScopes,
|
|
||||||
);
|
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return false when routeScopes contains a mix of valid and invalid permissions but application.scopes does not contain all the required permissions", () => {
|
it("should return false when routeScopes contains a mix of valid and invalid permissions but application.scopes does not contain all the required permissions", () => {
|
||||||
const application = { scopes: "write:*" };
|
const application = new Application({
|
||||||
|
scopes: "write:*",
|
||||||
|
} as ApplicationType);
|
||||||
const routeScopes = ["write:users", "invalid:permission", "read:posts"];
|
const routeScopes = ["write:users", "invalid:permission", "read:posts"];
|
||||||
const result = checkIfOauthIsValid(
|
const result = checkIfOauthIsValid(application, routeScopes);
|
||||||
application as Application,
|
|
||||||
routeScopes,
|
|
||||||
);
|
|
||||||
expect(result).toBe(false);
|
expect(result).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return true when routeScopes contains a mix of valid write and read permissions and application.scopes contains all the required permissions", () => {
|
it("should return true when routeScopes contains a mix of valid write and read permissions and application.scopes contains all the required permissions", () => {
|
||||||
const application = { scopes: "write:* read:posts" };
|
const application = new Application({
|
||||||
|
scopes: "write:* read:posts",
|
||||||
|
} as ApplicationType);
|
||||||
const routeScopes = ["write:users", "read:posts"];
|
const routeScopes = ["write:users", "read:posts"];
|
||||||
const result = checkIfOauthIsValid(
|
const result = checkIfOauthIsValid(application, routeScopes);
|
||||||
application as Application,
|
|
||||||
routeScopes,
|
|
||||||
);
|
|
||||||
expect(result).toBe(true);
|
expect(result).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should return false when routeScopes contains a mix of valid write and read permissions but application.scopes does not contain all the required permissions", () => {
|
it("should return false when routeScopes contains a mix of valid write and read permissions but application.scopes does not contain all the required permissions", () => {
|
||||||
const application = { scopes: "write:*" };
|
const application = new Application({
|
||||||
|
scopes: "write:*",
|
||||||
|
} as ApplicationType);
|
||||||
const routeScopes = ["write:users", "read:posts"];
|
const routeScopes = ["write:users", "read:posts"];
|
||||||
const result = checkIfOauthIsValid(
|
const result = checkIfOauthIsValid(application, routeScopes);
|
||||||
application as Application,
|
|
||||||
routeScopes,
|
|
||||||
);
|
|
||||||
expect(result).toBe(false);
|
expect(result).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -13,9 +13,9 @@ import type {
|
||||||
} from "@versia/federation/types";
|
} from "@versia/federation/types";
|
||||||
import type { SocketAddress } from "bun";
|
import type { SocketAddress } from "bun";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import type { Application } from "~/classes/functions/application";
|
|
||||||
import type { RolePermissions } from "~/drizzle/schema";
|
import type { RolePermissions } from "~/drizzle/schema";
|
||||||
import type { Config } from "~/packages/config-manager";
|
import type { Config } from "~/packages/config-manager";
|
||||||
|
import type { Application } from "~/packages/database-interface/application";
|
||||||
import type { User as DatabaseUser } from "~/packages/database-interface/user";
|
import type { User as DatabaseUser } from "~/packages/database-interface/user";
|
||||||
|
|
||||||
export type HttpVerb = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS";
|
export type HttpVerb = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS";
|
||||||
|
|
|
||||||
|
|
@ -22,11 +22,11 @@ import {
|
||||||
import { parse } from "qs";
|
import { parse } from "qs";
|
||||||
import type { z } from "zod";
|
import type { z } from "zod";
|
||||||
import { fromZodError } from "zod-validation-error";
|
import { fromZodError } from "zod-validation-error";
|
||||||
import type { Application } from "~/classes/functions/application";
|
|
||||||
import { type AuthData, getFromHeader } from "~/classes/functions/user";
|
import { type AuthData, getFromHeader } from "~/classes/functions/user";
|
||||||
import { db } from "~/drizzle/db";
|
import { db } from "~/drizzle/db";
|
||||||
import { Challenges } from "~/drizzle/schema";
|
import { Challenges } from "~/drizzle/schema";
|
||||||
import { config } from "~/packages/config-manager/index.ts";
|
import { config } from "~/packages/config-manager/index.ts";
|
||||||
|
import { Application } from "~/packages/database-interface/application";
|
||||||
import type { User } from "~/packages/database-interface/user";
|
import type { User } from "~/packages/database-interface/user";
|
||||||
import type { ApiRouteMetadata, HonoEnv, HttpVerb } from "~/types/api";
|
import type { ApiRouteMetadata, HonoEnv, HttpVerb } from "~/types/api";
|
||||||
|
|
||||||
|
|
@ -185,7 +185,9 @@ const checkRouteNeedsAuth = (
|
||||||
return {
|
return {
|
||||||
user: auth.user as User,
|
user: auth.user as User,
|
||||||
token: auth.token as string,
|
token: auth.token as string,
|
||||||
application: auth.application as Application | null,
|
application: auth.application
|
||||||
|
? new Application(auth.application)
|
||||||
|
: null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import type { Application } from "~/classes/functions/application";
|
import type { Application } from "~/packages/database-interface/application";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if an OAuth application is valid for a route
|
* Check if an OAuth application is valid for a route
|
||||||
|
|
@ -15,12 +15,12 @@ export const checkIfOauthIsValid = (
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasAllWriteScopes =
|
const hasAllWriteScopes =
|
||||||
application.scopes.split(" ").includes("write:*") ||
|
application.data.scopes.split(" ").includes("write:*") ||
|
||||||
application.scopes.split(" ").includes("write");
|
application.data.scopes.split(" ").includes("write");
|
||||||
|
|
||||||
const hasAllReadScopes =
|
const hasAllReadScopes =
|
||||||
application.scopes.split(" ").includes("read:*") ||
|
application.data.scopes.split(" ").includes("read:*") ||
|
||||||
application.scopes.split(" ").includes("read");
|
application.data.scopes.split(" ").includes("read");
|
||||||
|
|
||||||
if (hasAllWriteScopes && hasAllReadScopes) {
|
if (hasAllWriteScopes && hasAllReadScopes) {
|
||||||
return true;
|
return true;
|
||||||
|
|
@ -50,6 +50,6 @@ export const checkIfOauthIsValid = (
|
||||||
|
|
||||||
// If there are scopes left, check if they match
|
// If there are scopes left, check if they match
|
||||||
return nonMatchedScopes.every((scope) =>
|
return nonMatchedScopes.every((scope) =>
|
||||||
application.scopes.split(" ").includes(scope),
|
application.data.scopes.split(" ").includes(scope),
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue