117 lines
2.7 KiB
TypeScript
117 lines
2.7 KiB
TypeScript
import oauth2 from "@bogeychan/elysia-oauth2";
|
|
import { staticPlugin } from '@elysiajs/static';
|
|
import { Database } from "bun:sqlite";
|
|
import { randomBytes } from "crypto";
|
|
import { Elysia, t } from "elysia";
|
|
|
|
import { clientToServerEvents } from "../common/events";
|
|
import { migrateDatabase } from "./migrations";
|
|
|
|
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
|
|
}
|
|
});
|
|
|
|
if (Bun.env.NODE_ENV === "production") {
|
|
app.use(staticPlugin({
|
|
alwaysStatic: true,
|
|
prefix: ""
|
|
}));
|
|
}
|
|
|
|
app.listen(3000);
|
|
|
|
console.log(
|
|
`🦊 Chromatic Lattice server is running at ${app.server?.url.href}`
|
|
);
|