feat: xavis ai_platform 기능 이전 및 ncue 환경 전환
xavis 소스·DB 스키마·활용사례/F-Scan/프롬프트 라이브러리 등 기능 반영. @xavis.co.kr → @ncue.net, 관리자 토큰 ncue-admin, 런타임 data/ Git 추적 제외. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
158
ops-auth.js
158
ops-auth.js
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* OPS_STATE=PROD(구 REAL) 일 때 이메일(@xavis.co.kr) 매직 링크 인증
|
||||
* OPS_STATE=PROD(구 REAL) 일 때 이메일(@ncue.net) 매직 링크 인증
|
||||
*/
|
||||
const crypto = require("crypto");
|
||||
const { isOpsProdMode } = require("./lib/ops-state");
|
||||
@@ -15,10 +15,16 @@ try {
|
||||
}
|
||||
|
||||
const OPS_AUTH_COOKIE = "ops_user_session";
|
||||
const ALLOWED_EMAIL_SUFFIX = "@xavis.co.kr";
|
||||
const ALLOWED_EMAIL_SUFFIX = "@ncue.net";
|
||||
/** 메일 안 인증 링크 유효 시간(토큰 만료) */
|
||||
const MAGIC_LINK_MAX_AGE_MS = 15 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* 만기 없음 모드일 때 Set-Cookie max-age 상한(브라우저·HTTP 한도; 서명 payload의 exp는 Number.MAX_SAFE_INTEGER)
|
||||
* 10년마다 쿠키가 사라지면 다시 이메일 인증(매직 링크)이 필요할 수 있음
|
||||
*/
|
||||
const OPS_SESSION_BROWSER_MAX_AGE_MS = 10 * 365 * 24 * 60 * 60 * 1000;
|
||||
|
||||
/** OPS_SESSION_TZ 기준 달력 날짜 키 (YYYY-MM-DD) */
|
||||
function calendarDateKeyInTz(tsMs, tz) {
|
||||
const parts = new Intl.DateTimeFormat("en-CA", {
|
||||
@@ -80,16 +86,33 @@ function getLastMsOfCalendarDayInTz(dateKey, tz) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 로그인 세션 만료: 로그인일(OPS_SESSION_TZ 달력) + OPS_SESSION_TTL_DAYS(기본 15)일의 마지막 순간
|
||||
* 로그인 세션 만료 시각(ms)
|
||||
* - OPS_SESSION_TTL_DAYS: 미설정·0·never·none → 만기 없음(서명 exp = Number.MAX_SAFE_INTEGER)
|
||||
* - 양의 정수 N → 로그인일(OPS_SESSION_TZ 달력) + N일의 마지막 순간
|
||||
*/
|
||||
function getOpsSessionExpiresAtMs(nowMs = Date.now()) {
|
||||
const tz = (process.env.OPS_SESSION_TZ || "Asia/Seoul").trim() || "Asia/Seoul";
|
||||
const raw = (process.env.OPS_SESSION_TTL_DAYS || "15").trim();
|
||||
const raw = String(process.env.OPS_SESSION_TTL_DAYS ?? "0").trim() || "0";
|
||||
const lower = raw.toLowerCase();
|
||||
if (lower === "never" || lower === "none" || raw === "0") {
|
||||
return Number.MAX_SAFE_INTEGER;
|
||||
}
|
||||
const parsed = parseInt(raw, 10);
|
||||
const ttlDays = Number.isFinite(parsed) && parsed >= 0 ? parsed : 15;
|
||||
const loginDayKey = calendarDateKeyInTz(nowMs, tz);
|
||||
const targetKey = addCalendarDaysToKey(loginDayKey, ttlDays);
|
||||
return getLastMsOfCalendarDayInTz(targetKey, tz);
|
||||
if (Number.isFinite(parsed) && parsed > 0) {
|
||||
const loginDayKey = calendarDateKeyInTz(nowMs, tz);
|
||||
const targetKey = addCalendarDaysToKey(loginDayKey, parsed);
|
||||
return getLastMsOfCalendarDayInTz(targetKey, tz);
|
||||
}
|
||||
return Number.MAX_SAFE_INTEGER;
|
||||
}
|
||||
|
||||
/** res.cookie maxAge(ms) — 만기 없음일 때 astronomically large 값 대신 브라우저에 맞는 상한 */
|
||||
function getOpsSessionCookieMaxAgeMs(sessionExpMs) {
|
||||
const remain = Math.max(0, sessionExpMs - Date.now());
|
||||
if (sessionExpMs === Number.MAX_SAFE_INTEGER) {
|
||||
return Math.min(remain, OPS_SESSION_BROWSER_MAX_AGE_MS);
|
||||
}
|
||||
return remain;
|
||||
}
|
||||
|
||||
function isOpsProd() {
|
||||
@@ -97,7 +120,7 @@ function isOpsProd() {
|
||||
}
|
||||
|
||||
function getAuthSecret() {
|
||||
return (process.env.AUTH_SECRET || process.env.ADMIN_TOKEN || "xavis-admin").trim();
|
||||
return (process.env.AUTH_SECRET || process.env.ADMIN_TOKEN || "ncue-admin").trim();
|
||||
}
|
||||
|
||||
function getBaseUrl() {
|
||||
@@ -119,9 +142,38 @@ function buildMagicVerifyUrl(baseUrl, token) {
|
||||
return new URL(path, `${base}/`).href;
|
||||
}
|
||||
|
||||
const RETURN_TO_DEFAULT = "/learning";
|
||||
|
||||
/**
|
||||
* 인증 후·로그인 returnTo — 상대 경로만 허용(오픈 리다이렉트·한글 조사 등 오염 차단)
|
||||
* @param {unknown} v
|
||||
* @returns {string}
|
||||
*/
|
||||
function sanitizeReturnTo(v) {
|
||||
const s = (v || "").toString().trim();
|
||||
if (!s.startsWith("/") || s.startsWith("//")) return "/learning";
|
||||
if (!s.startsWith("/") || s.startsWith("//")) return RETURN_TO_DEFAULT;
|
||||
if (s.includes("\\") || s.includes("..")) return RETURN_TO_DEFAULT;
|
||||
|
||||
const qIdx = s.indexOf("?");
|
||||
const hIdx = s.indexOf("#");
|
||||
let pathEnd = s.length;
|
||||
if (qIdx >= 0) pathEnd = Math.min(pathEnd, qIdx);
|
||||
if (hIdx >= 0) pathEnd = Math.min(pathEnd, hIdx);
|
||||
const pathPart = s.slice(0, pathEnd);
|
||||
const suffix = s.slice(pathEnd);
|
||||
|
||||
if (pathPart !== "/" && !/^\/[a-zA-Z0-9][a-zA-Z0-9/_\-.]*$/.test(pathPart)) {
|
||||
if (s !== RETURN_TO_DEFAULT) {
|
||||
console.warn("[OPS] invalid returnTo path rejected:", s.slice(0, 160));
|
||||
}
|
||||
return RETURN_TO_DEFAULT;
|
||||
}
|
||||
if (suffix && !/^[?#][a-zA-Z0-9_\-=&.%+]*$/.test(suffix)) {
|
||||
if (s !== RETURN_TO_DEFAULT) {
|
||||
console.warn("[OPS] invalid returnTo query rejected:", s.slice(0, 160));
|
||||
}
|
||||
return RETURN_TO_DEFAULT;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -138,11 +190,12 @@ function isAllowedXavisEmail(email) {
|
||||
return s.endsWith(ALLOWED_EMAIL_SUFFIX);
|
||||
}
|
||||
|
||||
function signSessionCookie(email, expMs) {
|
||||
function signSessionCookie(email, expMs, iatMs = Date.now()) {
|
||||
const exp = expMs;
|
||||
const payload = `${email}|${exp}`;
|
||||
const iat = iatMs;
|
||||
const payload = `${email}|${exp}|${iat}`;
|
||||
const sig = crypto.createHmac("sha256", getAuthSecret()).update(payload).digest("hex");
|
||||
return Buffer.from(JSON.stringify({ email, exp, sig })).toString("base64url");
|
||||
return Buffer.from(JSON.stringify({ email, exp, iat, sig })).toString("base64url");
|
||||
}
|
||||
|
||||
function parseSessionCookie(val) {
|
||||
@@ -151,17 +204,41 @@ function parseSessionCookie(val) {
|
||||
const j = JSON.parse(Buffer.from(val, "base64url").toString("utf8"));
|
||||
if (!j.email || typeof j.exp !== "number") return null;
|
||||
if (Date.now() > j.exp) return null;
|
||||
const payload = `${j.email}|${j.exp}`;
|
||||
const sig = crypto.createHmac("sha256", getAuthSecret()).update(payload).digest("hex");
|
||||
if (sig !== j.sig) return null;
|
||||
return String(j.email).toLowerCase();
|
||||
const email = String(j.email).toLowerCase();
|
||||
const exp = j.exp;
|
||||
const iat = typeof j.iat === "number" ? j.iat : 0;
|
||||
const payloadNew = `${email}|${exp}|${iat}`;
|
||||
const sigNew = crypto.createHmac("sha256", getAuthSecret()).update(payloadNew).digest("hex");
|
||||
if (sigNew === j.sig) {
|
||||
return { email, exp, iat };
|
||||
}
|
||||
const payloadLegacy = `${email}|${exp}`;
|
||||
const sigLegacy = crypto.createHmac("sha256", getAuthSecret()).update(payloadLegacy).digest("hex");
|
||||
if (sigLegacy === j.sig) {
|
||||
return { email, exp, iat: 0 };
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getOpsSessionEmail(req) {
|
||||
return parseSessionCookie(req.cookies?.[OPS_AUTH_COOKIE]);
|
||||
const session = parseSessionCookie(req.cookies?.[OPS_AUTH_COOKIE]);
|
||||
return session ? session.email : null;
|
||||
}
|
||||
|
||||
async function resolveOpsSessionEmail(req, hooks) {
|
||||
const session = parseSessionCookie(req.cookies?.[OPS_AUTH_COOKIE]);
|
||||
if (!session) return null;
|
||||
if (typeof hooks.isSessionRevoked === "function") {
|
||||
const revoked = await hooks.isSessionRevoked({
|
||||
email: session.email,
|
||||
iatMs: session.iat,
|
||||
});
|
||||
if (revoked) return null;
|
||||
}
|
||||
return session.email;
|
||||
}
|
||||
|
||||
function loadMagicLinks(MAGIC_LINK_PATH) {
|
||||
@@ -303,7 +380,7 @@ async function sendMagicLinkEmail(to, linkUrl) {
|
||||
console.warn("[OPS] Magic link for", to, "→", linkUrl);
|
||||
return;
|
||||
}
|
||||
const from = (process.env.SMTP_FROM || (process.env.SMTP_USER || "").trim() || "noreply@xavis.co.kr").trim();
|
||||
const from = (process.env.SMTP_FROM || (process.env.SMTP_USER || "").trim() || "noreply@ncue.net").trim();
|
||||
const transporter = createSmtpTransport();
|
||||
const linkMinutes = Math.max(1, Math.floor(MAGIC_LINK_MAX_AGE_MS / 60000));
|
||||
const textBody = [
|
||||
@@ -344,24 +421,34 @@ module.exports = function createOpsAuth(DATA_DIR, hooks = {}) {
|
||||
if (isOpsPublicPath(req)) {
|
||||
return next();
|
||||
}
|
||||
const email = getOpsSessionEmail(req);
|
||||
if (email) {
|
||||
res.locals.opsUserEmail = email;
|
||||
return next();
|
||||
}
|
||||
if (req.path.startsWith("/api/")) {
|
||||
return res.status(401).json({ error: "로그인이 필요합니다." });
|
||||
}
|
||||
const returnTo = req.originalUrl || "/learning";
|
||||
return res.redirect("/login?returnTo=" + encodeURIComponent(returnTo));
|
||||
resolveOpsSessionEmail(req, hooks)
|
||||
.then((email) => {
|
||||
if (email) {
|
||||
res.locals.opsUserEmail = email;
|
||||
return next();
|
||||
}
|
||||
if (req.path.startsWith("/api/")) {
|
||||
return res.status(401).json({ error: "로그인이 필요합니다." });
|
||||
}
|
||||
const returnTo = req.originalUrl || "/learning";
|
||||
return res.redirect("/login?returnTo=" + encodeURIComponent(returnTo));
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error("[OPS] session resolve failed:", err?.message || err);
|
||||
if (req.path.startsWith("/api/")) {
|
||||
return res.status(500).json({ error: "인증 확인에 실패했습니다." });
|
||||
}
|
||||
return res.redirect("/login");
|
||||
});
|
||||
}
|
||||
|
||||
function registerRoutes(app) {
|
||||
app.get("/login", (req, res) => {
|
||||
app.get("/login", async (req, res) => {
|
||||
if (!isOpsProd()) {
|
||||
return res.redirect("/learning");
|
||||
}
|
||||
if (getOpsSessionEmail(req)) {
|
||||
const email = await resolveOpsSessionEmail(req, hooks);
|
||||
if (email) {
|
||||
return res.redirect(sanitizeReturnTo(req.query.returnTo));
|
||||
}
|
||||
return res.render("login", {
|
||||
@@ -371,7 +458,7 @@ module.exports = function createOpsAuth(DATA_DIR, hooks = {}) {
|
||||
});
|
||||
|
||||
app.get("/logout", async (req, res) => {
|
||||
const sessionEmail = getOpsSessionEmail(req);
|
||||
const sessionEmail = await resolveOpsSessionEmail(req, hooks);
|
||||
if (typeof hooks.onLogout === "function" && sessionEmail) {
|
||||
try {
|
||||
await hooks.onLogout({ email: sessionEmail, req });
|
||||
@@ -464,16 +551,17 @@ module.exports = function createOpsAuth(DATA_DIR, hooks = {}) {
|
||||
}
|
||||
}
|
||||
const sessionExp = getOpsSessionExpiresAtMs();
|
||||
const cookieVal = signSessionCookie(row.email, sessionExp);
|
||||
const issuedAt = Date.now();
|
||||
const cookieVal = signSessionCookie(row.email, sessionExp, issuedAt);
|
||||
const secure = process.env.NODE_ENV === "production";
|
||||
res.cookie(OPS_AUTH_COOKIE, cookieVal, {
|
||||
httpOnly: true,
|
||||
maxAge: Math.max(0, sessionExp - Date.now()),
|
||||
maxAge: getOpsSessionCookieMaxAgeMs(sessionExp),
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
secure,
|
||||
});
|
||||
const dest = appendVerifiedParam(sanitizeReturnTo(row.returnTo || "/learning"));
|
||||
const dest = appendVerifiedParam(row.returnTo || RETURN_TO_DEFAULT);
|
||||
return res.redirect(dest);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user