109 lines
2.5 KiB
TypeScript
109 lines
2.5 KiB
TypeScript
import { Elysia, t } from "elysia";
|
|
import oauth2 from "@bogeychan/elysia-oauth2";
|
|
import { Database } from "bun:sqlite";
|
|
import { randomBytes } from "crypto";
|
|
|
|
|
|
import { migrateDatabase } from "./migrations";
|
|
import { clientToServerEvents } from "../common/events";
|
|
|
|
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
|
|
}
|
|
})
|
|
.listen(3000);
|
|
|
|
console.log(
|
|
`🦊 Chromatic Lattice server is running at ${app.server?.url.href}`
|
|
);
|