앱 v1.2.0: exe 디스코드 로그인 · 유저 등록 · 관리자 페이지
- 사이트 서버: 앱 로그인(/auth/app/begin·start·poll, 기존 OAuth 콜백 재사용), 앱 토큰(/app/me, 해시 저장), 유저 등록 API(/app/admin/users, 등록·역할·해제는 최고 관리자만, 목록은 관리자도). 최고 관리자 2명 고정 - 앱: 등록된 계정으로 로그인해야 코어(봇·녹음·사이트 연결)를 띄운다. 미등록이면 "등록되지 않은 아이디" + 아이디 표시. 10분마다 재확인, 등록 해제 시 즉시 잠금. 서버 연결 실패 시 마지막 확인 후 3일 유예 - 겜녹이 봇 토큰을 exe 에 넣지 않고 로그인한 등록 유저에게 서버가 내려준다 (잠기면 삭제). win-ci 토큰 주입 제거 - 관리자 탭(유저 등록·목록·접속 기록), 관리자 전용 설정(봇 변경·TTS 안내·보관 기간·사이트·학습 데이터·파인튜닝)은 일반 유저에게 잠금 표시 + 메인 프로세스에서 차단 - 테스트: 서버 앱 로그인 2건, 앱↔서버 통합 3건, Electron 로그인 E2E 스크립트(scripts/login-e2e.mts) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
228
site/server/src/app-auth.ts
Normal file
228
site/server/src/app-auth.ts
Normal file
@@ -0,0 +1,228 @@
|
||||
// 앱(exe) 디스코드 로그인 · 유저 등록 · 관리자 API
|
||||
// 1) 앱: POST /auth/app/begin → {id, secret, url}. url 을 브라우저로 연다
|
||||
// 2) 브라우저: GET /auth/app/start/:id → 디스코드 OAuth → /auth/discord/callback (사이트 로그인과 같은 콜백, state 가 "app." 으로 시작)
|
||||
// 3) 콜백: 등록된 아이디면 앱 토큰 발급, 아니면 "등록되지 않은 아이디" 결과를 남긴다
|
||||
// 4) 앱: POST /auth/app/poll {id, secret} 로 결과를 받아 간다 (한 번만)
|
||||
// 5) 앱: GET /app/me (Bearer 토큰) 로 주기적으로 확인. 등록 해제되면 403 → 앱이 잠긴다. 겜녹이 봇 토큰은 여기서만 내려준다
|
||||
import crypto from 'node:crypto';
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
||||
import type { AppLoginPoll, AppMe, AppRole, AppUserInfo, AppUserRow } from '@gvr/shared';
|
||||
import type { Config } from './config.js';
|
||||
import { avatarUrl, fetchDiscordUser, type DiscordApi, type DiscordUser } from './discord.js';
|
||||
import type { ServerStore } from './store.js';
|
||||
|
||||
const LOGIN_TTL_MS = 10 * 60000;
|
||||
const MAX_PENDING = 200;
|
||||
const SNOWFLAKE = /^\d{17,20}$/;
|
||||
|
||||
interface Pending {
|
||||
secretHash: Buffer;
|
||||
nonce: string;
|
||||
expiresAt: number;
|
||||
result: AppLoginPoll | null;
|
||||
}
|
||||
|
||||
const sha = (s: string) => crypto.createHash('sha256').update(s).digest();
|
||||
|
||||
export function registerAppAuth(app: FastifyInstance, deps: { cfg: Config; store: ServerStore; discord: DiscordApi; secure: boolean }) {
|
||||
const { cfg, store, discord, secure } = deps;
|
||||
const pending = new Map<string, Pending>();
|
||||
|
||||
const roleOf = (id: string): AppRole | null => (cfg.superAdmins.includes(id) ? 'superadmin' : (store.appUser(id)?.role ?? null));
|
||||
const sweep = () => {
|
||||
const now = Date.now();
|
||||
for (const [k, p] of pending) if (p.expiresAt <= now) pending.delete(k);
|
||||
};
|
||||
const userInfo = (id: string): AppUserInfo => {
|
||||
const u = store.appUser(id);
|
||||
const seen = store.appSeen(id);
|
||||
return { id, name: u?.name || seen?.name || id, avatar: u?.avatar ?? seen?.avatar ?? null };
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ 로그인 시작 · 결과 받기 (앱)
|
||||
app.post('/auth/app/begin', async (_req, reply) => {
|
||||
sweep();
|
||||
if (pending.size >= MAX_PENDING) return reply.code(429).send({ error: 'busy', message: '로그인 요청이 너무 많습니다. 잠시 뒤 다시 시도해 주세요' });
|
||||
const id = crypto.randomBytes(16).toString('base64url');
|
||||
const secret = crypto.randomBytes(32).toString('base64url');
|
||||
const expiresAt = Date.now() + LOGIN_TTL_MS;
|
||||
pending.set(id, { secretHash: sha(secret), nonce: crypto.randomBytes(16).toString('base64url'), expiresAt, result: null });
|
||||
return { id, secret, url: `${cfg.publicUrl}/auth/app/start/${id}`, expiresAt };
|
||||
});
|
||||
|
||||
app.post<{ Body: { id?: string; secret?: string } }>('/auth/app/poll', async (req, reply) => {
|
||||
const id = String(req.body?.id ?? '');
|
||||
const p = pending.get(id);
|
||||
const ok = p && p.expiresAt > Date.now() && crypto.timingSafeEqual(p.secretHash, sha(String(req.body?.secret ?? '')));
|
||||
if (!ok) return reply.code(410).send({ state: 'error', error: '로그인 요청이 만료되었습니다. 다시 로그인해 주세요' } satisfies AppLoginPoll);
|
||||
if (!p.result) return { state: 'pending' } satisfies AppLoginPoll;
|
||||
pending.delete(id); // 결과는 한 번만 내준다
|
||||
return p.result;
|
||||
});
|
||||
|
||||
// 브라우저: 로그인 요청 확인 → 디스코드 로그인으로
|
||||
app.get<{ Params: { id: string } }>('/auth/app/start/:id', async (req, reply) => {
|
||||
const p = pending.get(req.params.id);
|
||||
if (!p || p.expiresAt <= Date.now() || p.result) return page(reply, 410, '로그인 요청이 만료되었습니다', '겜녹이 앱에서 로그인 버튼을 다시 눌러 주세요.');
|
||||
const state = `app.${req.params.id}.${p.nonce}`;
|
||||
reply.setCookie('gvr_state', state, { path: '/auth', httpOnly: true, secure, sameSite: 'lax', maxAge: 600, signed: true });
|
||||
return reply.redirect(discord.authorizeUrl(state));
|
||||
});
|
||||
|
||||
/** /auth/discord/callback 에서 state 가 "app." 이면 여기로 온다 (state 쿠키 확인은 콜백에서 끝남) */
|
||||
async function completeLogin(state: string, code: string | undefined, error: string | undefined, reply: FastifyReply, log: FastifyRequest['log']) {
|
||||
const [, id = '', nonce = ''] = state.split('.');
|
||||
const p = pending.get(id);
|
||||
if (!p || p.nonce !== nonce || p.expiresAt <= Date.now() || p.result) return page(reply, 410, '로그인 요청이 만료되었습니다', '겜녹이 앱에서 로그인 버튼을 다시 눌러 주세요.');
|
||||
if (error || !code) {
|
||||
p.result = { state: 'error', error: '디스코드 로그인을 취소했습니다' };
|
||||
return page(reply, 200, '로그인을 취소했습니다', '겜녹이 앱에서 다시 시도할 수 있습니다.');
|
||||
}
|
||||
let u: DiscordUser;
|
||||
try {
|
||||
u = await discord.me((await discord.exchange(code)).access_token);
|
||||
} catch (e) {
|
||||
log.error(e, '앱 로그인 OAuth 실패');
|
||||
p.result = { state: 'error', error: '디스코드 로그인에 실패했습니다. 다시 시도해 주세요' };
|
||||
return page(reply, 502, '디스코드 로그인 실패', '잠시 뒤 겜녹이 앱에서 다시 시도해 주세요.');
|
||||
}
|
||||
const user: AppUserInfo = { id: u.id, name: u.global_name || u.username, avatar: avatarUrl(u) };
|
||||
const role = roleOf(u.id);
|
||||
if (!role) {
|
||||
log.info({ user: u.id }, '앱 로그인 거절: 등록되지 않은 아이디');
|
||||
p.result = { state: 'not_registered', user };
|
||||
return page(reply, 403, '등록되지 않은 아이디입니다', `${esc(user.name)} (${u.id}) 계정은 겜녹이 사용자로 등록되어 있지 않습니다. 관리자에게 이 아이디 등록을 요청해 주세요.`);
|
||||
}
|
||||
// 이름 · 사진은 로그인할 때마다 최신으로
|
||||
const row = store.appUser(u.id);
|
||||
if (row) store.upsertAppUser({ ...row, name: user.name, avatar: user.avatar });
|
||||
store.touchAppUser(u.id, { version: null, name: user.name, avatar: user.avatar });
|
||||
p.result = { state: 'ok', token: store.createAppSession(u.id), user, role };
|
||||
log.info({ user: u.id, role }, '앱 로그인');
|
||||
return page(reply, 200, '로그인 완료', `${esc(user.name)} 님, 겜녹이 앱으로 돌아가세요. 이 창은 닫아도 됩니다.`);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 로그인 확인 (앱, Bearer 토큰)
|
||||
const bearer = (req: FastifyRequest) => /^Bearer\s+(\S+)$/i.exec(String(req.headers.authorization || ''))?.[1] ?? '';
|
||||
async function auth(req: FastifyRequest, reply: FastifyReply): Promise<{ id: string; role: AppRole } | null> {
|
||||
const token = bearer(req);
|
||||
const s = store.appSession(token);
|
||||
if (!s) {
|
||||
reply.code(401).send({ error: 'invalid_session', message: '다시 로그인해 주세요' });
|
||||
return null;
|
||||
}
|
||||
const role = roleOf(s.userId);
|
||||
if (!role) {
|
||||
store.deleteAppSession(token);
|
||||
reply.code(403).send({ error: 'not_registered', message: '등록되지 않은 아이디입니다', user: userInfo(s.userId) });
|
||||
return null;
|
||||
}
|
||||
return { id: s.userId, role };
|
||||
}
|
||||
|
||||
app.get('/app/me', async (req, reply) => {
|
||||
const a = await auth(req, reply);
|
||||
if (!a) return;
|
||||
const user = userInfo(a.id);
|
||||
const ver = String(req.headers['x-gvr-version'] || '').slice(0, 20) || null;
|
||||
store.touchAppUser(a.id, { version: ver, name: user.name, avatar: user.avatar });
|
||||
return { user, role: a.role, botToken: cfg.botToken || null, serverTime: Date.now() } satisfies AppMe;
|
||||
});
|
||||
|
||||
app.post('/auth/app/logout', async (req) => {
|
||||
const t = bearer(req);
|
||||
if (t) store.deleteAppSession(t);
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ 관리자: 유저 등록
|
||||
const rows = (): AppUserRow[] => {
|
||||
const fixed: AppUserRow[] = cfg.superAdmins.map((id) => {
|
||||
const seen = store.appSeen(id);
|
||||
return { id, name: seen?.name ?? id, avatar: seen?.avatar ?? null, role: 'superadmin', fixed: true, addedBy: null, addedAt: null, lastSeenAt: seen?.at ?? null, lastVersion: seen?.version ?? null };
|
||||
});
|
||||
const rest = store
|
||||
.appUsers()
|
||||
.filter((u) => !cfg.superAdmins.includes(u.id))
|
||||
.sort((a, b) => (a.role === b.role ? b.addedAt - a.addedAt : a.role === 'admin' ? -1 : 1))
|
||||
.map((u): AppUserRow => ({ id: u.id, name: u.name, avatar: u.avatar, role: u.role, fixed: false, addedBy: u.addedBy, addedAt: u.addedAt, lastSeenAt: u.lastSeenAt, lastVersion: u.lastVersion }));
|
||||
return [...fixed, ...rest];
|
||||
};
|
||||
const need = async (req: FastifyRequest, reply: FastifyReply, level: 'admin' | 'superadmin') => {
|
||||
const a = await auth(req, reply);
|
||||
if (!a) return null;
|
||||
const ok = level === 'superadmin' ? a.role === 'superadmin' : a.role !== 'user';
|
||||
if (!ok) {
|
||||
reply.code(403).send({ error: 'forbidden', message: level === 'superadmin' ? '유저 등록은 최고 관리자만 할 수 있습니다' : '관리자만 볼 수 있습니다' });
|
||||
return null;
|
||||
}
|
||||
return a;
|
||||
};
|
||||
const role = (v: unknown): 'admin' | 'user' | null => (v === 'admin' || v === 'user' ? v : null);
|
||||
|
||||
app.get('/app/admin/users', async (req, reply) => {
|
||||
if (!(await need(req, reply, 'admin'))) return;
|
||||
return { users: rows() };
|
||||
});
|
||||
|
||||
app.post<{ Body: { id?: string; role?: string } }>('/app/admin/users', async (req, reply) => {
|
||||
const a = await need(req, reply, 'superadmin');
|
||||
if (!a) return;
|
||||
const id = String(req.body?.id ?? '').trim();
|
||||
const r = role(req.body?.role ?? 'user');
|
||||
if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' });
|
||||
if (!r) return reply.code(400).send({ error: 'bad_role', message: '역할은 관리자 또는 유저입니다' });
|
||||
if (cfg.superAdmins.includes(id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 이미 등록되어 있습니다' });
|
||||
let du: DiscordUser | null;
|
||||
try {
|
||||
du = await fetchDiscordUser(cfg, id);
|
||||
} catch (e) {
|
||||
req.log.warn(e, '디스코드 계정 조회 실패');
|
||||
return reply.code(502).send({ error: 'discord_error', message: '디스코드에서 계정을 확인하지 못했습니다. 잠시 뒤 다시 시도해 주세요' });
|
||||
}
|
||||
if (!du) return reply.code(404).send({ error: 'unknown_user', message: '디스코드에 없는 아이디입니다' });
|
||||
if ((du as any).bot) return reply.code(400).send({ error: 'bot', message: '봇 계정은 등록할 수 없습니다' });
|
||||
store.upsertAppUser({ id, name: du.global_name || du.username, avatar: avatarUrl(du), role: r, addedBy: a.id });
|
||||
req.log.info({ by: a.id, user: id, role: r }, '앱 유저 등록');
|
||||
return { users: rows() };
|
||||
});
|
||||
|
||||
app.patch<{ Params: { id: string }; Body: { role?: string } }>('/app/admin/users/:id', async (req, reply) => {
|
||||
const a = await need(req, reply, 'superadmin');
|
||||
if (!a) return;
|
||||
const r = role(req.body?.role);
|
||||
if (!r) return reply.code(400).send({ error: 'bad_role', message: '역할은 관리자 또는 유저입니다' });
|
||||
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 바꿀 수 없습니다' });
|
||||
if (!store.setAppUserRole(req.params.id, r)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
|
||||
req.log.info({ by: a.id, user: req.params.id, role: r }, '앱 유저 역할 변경');
|
||||
return { users: rows() };
|
||||
});
|
||||
|
||||
app.delete<{ Params: { id: string } }>('/app/admin/users/:id', async (req, reply) => {
|
||||
const a = await need(req, reply, 'superadmin');
|
||||
if (!a) return;
|
||||
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 지울 수 없습니다' });
|
||||
if (!store.removeAppUser(req.params.id)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
|
||||
req.log.info({ by: a.id, user: req.params.id }, '앱 유저 등록 해제');
|
||||
return { users: rows() };
|
||||
});
|
||||
|
||||
return { completeLogin };
|
||||
}
|
||||
|
||||
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
||||
|
||||
/** 브라우저에 보여 줄 짧은 안내 페이지 */
|
||||
function page(reply: FastifyReply, status: number, title: string, body: string) {
|
||||
const ok = status === 200;
|
||||
return reply
|
||||
.code(status)
|
||||
.type('text/html; charset=utf-8')
|
||||
.send(
|
||||
`<!doctype html><html lang="ko"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>겜녹이 · ${esc(title)}</title>` +
|
||||
`<style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#0b141c;color:#e6edf3;font-family:system-ui,'Malgun Gothic',sans-serif}` +
|
||||
`.c{max-width:420px;padding:32px;border-radius:14px;background:#121e29;border:1px solid #22313f;text-align:center}` +
|
||||
`h1{font-size:20px;margin:12px 0;color:${ok ? '#14c1b7' : '#ff4655'}}p{color:#9fb0c0;line-height:1.6;margin:0}.i{font-size:40px}</style></head>` +
|
||||
`<body><div class="c"><div class="i">${ok ? '✅' : '⛔'}</div><h1>${esc(title)}</h1><p>${body}</p></div></body></html>`,
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { Config } from './config.js';
|
||||
import { registerAppAuth } from './app-auth.js';
|
||||
import { avatarUrl, DiscordApi } from './discord.js';
|
||||
import { RelayHub } from './relay.js';
|
||||
import { ServerStore, type Session } from './store.js';
|
||||
@@ -19,6 +20,7 @@ export async function buildServer(cfg: Config) {
|
||||
const discord = new DiscordApi(cfg);
|
||||
await app.register(cookie, { secret: cfg.sessionSecret });
|
||||
const secure = cfg.publicUrl.startsWith('https://');
|
||||
const appAuth = registerAppAuth(app, { cfg, store, discord, secure });
|
||||
|
||||
const allowedGuilds = (): string[] => {
|
||||
const g = new Set(cfg.allowedGuilds);
|
||||
@@ -70,6 +72,8 @@ export async function buildServer(cfg: Config) {
|
||||
app.get<{ Querystring: { code?: string; state?: string; error?: string } }>('/auth/discord/callback', async (req, reply) => {
|
||||
const st = req.cookies.gvr_state ? req.unsignCookie(req.cookies.gvr_state) : null;
|
||||
reply.clearCookie('gvr_state', { path: '/auth' });
|
||||
// 앱(exe) 로그인: 같은 콜백을 쓰고 state 가 "app." 으로 시작한다 (app-auth.ts)
|
||||
if (st?.valid && st.value && st.value === req.query.state && st.value.startsWith('app.')) return appAuth.completeLogin(st.value, req.query.code, req.query.error, reply, req.log);
|
||||
if (req.query.error) return reply.redirect('/?login=cancelled');
|
||||
if (!req.query.code || !st?.valid || st.value !== req.query.state) return reply.redirect('/?login=invalid');
|
||||
try {
|
||||
@@ -175,7 +179,7 @@ export async function buildServer(cfg: Config) {
|
||||
if (fs.existsSync(cfg.webDir)) {
|
||||
await app.register(fastifyStatic, { root: cfg.webDir, wildcard: false, index: ['index.html'] });
|
||||
app.setNotFoundHandler((req, reply) => {
|
||||
if (req.method === 'GET' && !req.url.startsWith('/api/') && !req.url.startsWith('/auth/') && !req.url.startsWith('/game-assets/'))
|
||||
if (req.method === 'GET' && !req.url.startsWith('/api/') && !req.url.startsWith('/auth/') && !req.url.startsWith('/app/') && !req.url.startsWith('/game-assets/'))
|
||||
return reply.type('text/html').send(fs.readFileSync(path.join(cfg.webDir, 'index.html')));
|
||||
return reply.code(404).send({ error: 'not_found' });
|
||||
});
|
||||
|
||||
@@ -9,7 +9,10 @@ export interface Config {
|
||||
botToken: string;
|
||||
/** 로그인 허용 디스코드 서버 (기본: M&L). 게임 PC 가 알려 준 서버도 함께 허용 */
|
||||
allowedGuilds: string[];
|
||||
/** 사이트 관리자 (게임 PC 등록 코드). 최고 관리자도 포함된다 */
|
||||
owners: string[];
|
||||
/** 앱 최고 관리자: 유저 등록·역할 변경. 지우거나 바꿀 수 없다 */
|
||||
superAdmins: string[];
|
||||
sessionSecret: string;
|
||||
dataDir: string;
|
||||
webDir: string;
|
||||
@@ -19,6 +22,11 @@ export interface Config {
|
||||
assetUpstream: Record<string, string>;
|
||||
}
|
||||
|
||||
/** 앱 최고 관리자 (사용자 지정, 고정). SUPER_ADMIN_IDS 환경변수로 더할 수 있다 */
|
||||
export const SUPER_ADMINS = ['293719842274541579', '1352267557213573160'];
|
||||
|
||||
const ids = (v: string | undefined) => (v || '').split(',').map((s) => s.trim()).filter(Boolean);
|
||||
|
||||
export function loadConfig(env = process.env): Config {
|
||||
const need = (k: string) => {
|
||||
const v = env[k];
|
||||
@@ -33,7 +41,8 @@ export function loadConfig(env = process.env): Config {
|
||||
clientSecret: need('DISCORD_CLIENT_SECRET'),
|
||||
botToken: need('DISCORD_BOT_TOKEN'),
|
||||
allowedGuilds: (env.ALLOWED_GUILD_IDS || '').split(',').map((s) => s.trim()).filter(Boolean),
|
||||
owners: (env.OWNER_DISCORD_IDS || '').split(',').map((s) => s.trim()).filter(Boolean),
|
||||
owners: [...new Set([...ids(env.OWNER_DISCORD_IDS), ...SUPER_ADMINS, ...ids(env.SUPER_ADMIN_IDS)])],
|
||||
superAdmins: [...new Set([...SUPER_ADMINS, ...ids(env.SUPER_ADMIN_IDS)])],
|
||||
sessionSecret: need('SESSION_SECRET'),
|
||||
dataDir: env.DATA_DIR || path.resolve('data'),
|
||||
webDir: env.WEB_DIR || path.resolve('../web/dist'),
|
||||
|
||||
@@ -54,6 +54,14 @@ export class DiscordApi {
|
||||
}
|
||||
}
|
||||
|
||||
/** 봇 토큰으로 디스코드 계정 조회 (유저 등록 때 이름 확인). 없는 아이디면 null */
|
||||
export async function fetchDiscordUser(cfg: Config, id: string): Promise<DiscordUser | null> {
|
||||
const r = await fetch(`${cfg.discordApi}/users/${id}`, { headers: { authorization: `Bot ${cfg.botToken}` } });
|
||||
if (r.status === 404 || r.status === 400) return null;
|
||||
if (!r.ok) throw new Error(`users/${id} ${r.status}`);
|
||||
return (await r.json()) as DiscordUser;
|
||||
}
|
||||
|
||||
export function avatarUrl(u: DiscordUser): string | null {
|
||||
return u.avatar ? `https://cdn.discordapp.com/avatars/${u.id}/${u.avatar}.png?size=128` : null;
|
||||
}
|
||||
|
||||
@@ -18,10 +18,32 @@ export interface Session {
|
||||
checkedAt: number;
|
||||
expiresAt: number;
|
||||
}
|
||||
/** 앱(exe)을 쓸 수 있게 등록된 디스코드 계정. 최고 관리자는 설정(config)에 고정이라 여기 없어도 된다 */
|
||||
export interface AppUser {
|
||||
id: string;
|
||||
name: string;
|
||||
avatar: string | null;
|
||||
role: 'admin' | 'user';
|
||||
addedBy: string;
|
||||
addedAt: number;
|
||||
lastSeenAt: number | null;
|
||||
lastVersion: string | null;
|
||||
}
|
||||
/** 앱 로그인 토큰 (서버는 해시만 저장) */
|
||||
export interface AppSession {
|
||||
tokenHash: string;
|
||||
userId: string;
|
||||
createdAt: number;
|
||||
expiresAt: number;
|
||||
}
|
||||
interface Data {
|
||||
devices: Device[];
|
||||
codes: { code: string; expiresAt: number; createdBy: string }[];
|
||||
sessions: Session[];
|
||||
appUsers: AppUser[];
|
||||
appSessions: AppSession[];
|
||||
/** 최고 관리자의 마지막 접속 (appUsers 에 없을 수 있어 따로 둔다) */
|
||||
appSeen: Record<string, { at: number; version: string | null; name: string; avatar: string | null }>;
|
||||
}
|
||||
// codes 는 server.json 에 두지 않는다 (codes.json)
|
||||
|
||||
@@ -44,10 +66,13 @@ export class ServerStore {
|
||||
try {
|
||||
this.d = JSON.parse(fs.readFileSync(this.file, 'utf8'));
|
||||
} catch {
|
||||
this.d = { devices: [], codes: [], sessions: [] };
|
||||
this.d = { devices: [], codes: [], sessions: [], appUsers: [], appSessions: [], appSeen: {} };
|
||||
}
|
||||
this.d.devices ||= [];
|
||||
this.d.sessions ||= [];
|
||||
this.d.appUsers ||= [];
|
||||
this.d.appSessions ||= [];
|
||||
this.d.appSeen ||= {};
|
||||
}
|
||||
|
||||
private save(now = false): void {
|
||||
@@ -149,4 +174,74 @@ export class ServerStore {
|
||||
this.d.sessions = this.d.sessions.filter((x) => x.id !== id);
|
||||
this.save();
|
||||
}
|
||||
|
||||
// ---- 앱 유저 등록 · 앱 로그인 토큰
|
||||
appUsers(): AppUser[] {
|
||||
return this.d.appUsers;
|
||||
}
|
||||
appUser(id: string): AppUser | null {
|
||||
return this.d.appUsers.find((u) => u.id === id) ?? null;
|
||||
}
|
||||
upsertAppUser(u: Pick<AppUser, 'id' | 'name' | 'avatar' | 'role' | 'addedBy'>): AppUser {
|
||||
const cur = this.appUser(u.id);
|
||||
if (cur) {
|
||||
Object.assign(cur, { name: u.name, avatar: u.avatar, role: u.role });
|
||||
this.save(true);
|
||||
return cur;
|
||||
}
|
||||
const row: AppUser = { ...u, addedAt: Date.now(), lastSeenAt: null, lastVersion: null };
|
||||
this.d.appUsers.push(row);
|
||||
this.save(true);
|
||||
return row;
|
||||
}
|
||||
setAppUserRole(id: string, role: AppUser['role']): AppUser | null {
|
||||
const u = this.appUser(id);
|
||||
if (!u) return null;
|
||||
u.role = role;
|
||||
this.save(true);
|
||||
return u;
|
||||
}
|
||||
/** 등록 해제. 그 유저의 앱 토큰은 다음 확인 때 403(등록되지 않은 아이디)을 받고 지워진다 */
|
||||
removeAppUser(id: string): boolean {
|
||||
const n = this.d.appUsers.length;
|
||||
this.d.appUsers = this.d.appUsers.filter((u) => u.id !== id);
|
||||
this.save(true);
|
||||
return this.d.appUsers.length !== n;
|
||||
}
|
||||
appSeen(id: string): Data['appSeen'][string] | null {
|
||||
return this.d.appSeen[id] ?? null;
|
||||
}
|
||||
touchAppUser(id: string, seen: { version: string | null; name: string; avatar: string | null }): void {
|
||||
const at = Date.now();
|
||||
this.d.appSeen[id] = { at, ...seen };
|
||||
const u = this.appUser(id);
|
||||
if (u) {
|
||||
u.lastSeenAt = at;
|
||||
u.lastVersion = seen.version;
|
||||
}
|
||||
this.save();
|
||||
}
|
||||
createAppSession(userId: string, ttlMs = 30 * 24 * 3600 * 1000): string {
|
||||
const token = crypto.randomBytes(32).toString('base64url');
|
||||
const now = Date.now();
|
||||
this.d.appSessions = this.d.appSessions.filter((x) => x.expiresAt > now);
|
||||
this.d.appSessions.push({ tokenHash: sha256(token), userId, createdAt: now, expiresAt: now + ttlMs });
|
||||
this.save(true);
|
||||
return token;
|
||||
}
|
||||
/** 토큰 확인. 쓸 때마다 만료를 30일 뒤로 민다 */
|
||||
appSession(token: string, ttlMs = 30 * 24 * 3600 * 1000): AppSession | null {
|
||||
if (!token) return null;
|
||||
const h = sha256(token);
|
||||
const s = this.d.appSessions.find((x) => x.tokenHash === h);
|
||||
if (!s || s.expiresAt <= Date.now()) return null;
|
||||
s.expiresAt = Date.now() + ttlMs;
|
||||
this.save();
|
||||
return s;
|
||||
}
|
||||
deleteAppSession(token: string): void {
|
||||
const h = sha256(token);
|
||||
this.d.appSessions = this.d.appSessions.filter((x) => x.tokenHash !== h);
|
||||
this.save(true);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user