chromatic/server/index.ts

118 lines
2.7 KiB
TypeScript
Raw Normal View History

2024-02-12 12:15:50 +00:00
import oauth2 from "@bogeychan/elysia-oauth2";
2024-02-12 13:49:13 +00:00
import { staticPlugin } from '@elysiajs/static';
2024-02-12 12:15:50 +00:00
import { Database } from "bun:sqlite";
import { randomBytes } from "crypto";
2024-02-12 13:49:13 +00:00
import { Elysia, t } from "elysia";
2024-02-12 12:15:50 +00:00
import { clientToServerEvents } from "../common/events";
2024-02-12 13:49:13 +00:00
import { migrateDatabase } from "./migrations";
2024-02-12 12:15:50 +00:00
const db = new Database("db.sqlite", { create: true });
migrateDatabase(db);
const states = new Set();
const auth = oauth2({
profiles: {
incsoc: {
provider: {
clientId: Bun.env.OAUTH_CLIENT_ID!,
clientSecret: Bun.env.OAUTH_CLIENT_SECRET!,
auth: {
url: 'https://auth.incremental.social/auth/v1',
params: {}
},
token: {
url: 'https://auth.incremental.social/oauth/v2/token',
params: {}
}
},
scope: ['email', 'profile']
}
},
state: {
check(ctx, id, state) {
if (states.has(state)) {
states.delete(state);
return true;
}
return false;
},
generate(ctx, id) {
const state = randomBytes(8).toString('hex');
states.add(state);
return state;
}
},
storage: {
get(ctx, id) {
console.log(`get token: ${id}`);
// const token = (
// db
// .query('SELECT token FROM storage WHERE uuid = ? AND id = ?')
// .get(uuid, id) as { token: string }
// )?.token;
// if (!token) {
// return;
// }
// return JSON.parse(token);
return undefined;
},
set(ctx, id, token) {
console.log(`new token: ${id}`);
// db.run(
// 'INSERT OR REPLACE INTO storage (id, token) VALUES (?, ?)',
// [id, JSON.stringify(token)]
// );
},
delete(ctx, id) {
// db.run('DELETE FROM storage WHERE id = ?', [id]);
}
}
});
const app = new Elysia()
.use(auth)
.ws('/ws', {
body: t.Object({
message: clientToServerEvents
}),
message(ws, { message }) {
console.log(message);
},
beforeHandle: async function({ set, authorized, tokenHeaders }) {
// Check auth
if (!(await authorized("incsoc"))) {
return (set.status = 'Unauthorized');
}
const user = await fetch('https://auth.incremental.social/oidc/v1/userinfo', {
headers: await tokenHeaders("incsoc")
});
console.log(JSON.stringify(user));
// Update avatar and display name from mbin, fallback to userinfo
}
2024-02-12 13:49:13 +00:00
});
if (Bun.env.NODE_ENV === "production") {
app.use(staticPlugin({
alwaysStatic: true,
prefix: ""
}));
}
app.listen(3000);
2024-02-12 12:15:50 +00:00
console.log(
`🦊 Chromatic Lattice server is running at ${app.server?.url.href}`
);