Spaces:
Running
Running
Upload 2 files
Browse files
hub.html
CHANGED
|
@@ -78,31 +78,26 @@
|
|
| 78 |
margin: 0 auto 16px;
|
| 79 |
}
|
| 80 |
|
| 81 |
-
.otp-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
margin: 18px 0;
|
| 86 |
-
}
|
| 87 |
-
|
| 88 |
-
.otp-digit-box {
|
| 89 |
-
width: 48px !important;
|
| 90 |
-
height: 56px;
|
| 91 |
text-align: center;
|
| 92 |
-
font-size:
|
| 93 |
font-weight: 900;
|
|
|
|
|
|
|
| 94 |
font-family: 'JetBrains Mono', monospace;
|
| 95 |
background: #050811 !important;
|
| 96 |
-
border: 2px solid
|
| 97 |
-
border-radius:
|
| 98 |
color: #fbbf24 !important;
|
| 99 |
transition: all 0.18s;
|
| 100 |
}
|
| 101 |
|
| 102 |
-
.otp-
|
| 103 |
border-color: var(--primary) !important;
|
| 104 |
-
box-shadow: 0 0 0
|
| 105 |
-
transform: translateY(-1px);
|
| 106 |
}
|
| 107 |
|
| 108 |
/* TOPBAR */
|
|
@@ -803,14 +798,17 @@
|
|
| 803 |
<div style="font-size:11px; font-weight:800; color:var(--text-muted); text-transform:uppercase; letter-spacing:0.8px;">
|
| 804 |
Enter 6-Digit Verification Code
|
| 805 |
</div>
|
| 806 |
-
<
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
|
| 813 |
-
|
|
|
|
|
|
|
|
|
|
| 814 |
|
| 815 |
<button id="verifyOtpBtn" class="btn green" style="width:100%;" onclick="verifyAdminOtpCode()">
|
| 816 |
โ
Verify OTP & Save Trusted Device Cookie
|
|
@@ -1146,6 +1144,7 @@
|
|
| 1146 |
// =====================================================================
|
| 1147 |
const HF_SERVER_BASE = "/api" + "/hf";
|
| 1148 |
let isSessionUnlocked = false;
|
|
|
|
| 1149 |
let currentLogMode = "server"; // 'server' | 'run' | 'build'
|
| 1150 |
let allLogEntries = [];
|
| 1151 |
let repoFilesList = [];
|
|
@@ -1154,7 +1153,7 @@
|
|
| 1154 |
let autoPollTimer = null;
|
| 1155 |
|
| 1156 |
function callServerHf(subpath, opts = {}) {
|
| 1157 |
-
const merged = Object.assign({ credentials: "
|
| 1158 |
return fetch(HF_SERVER_BASE + subpath, merged);
|
| 1159 |
}
|
| 1160 |
|
|
@@ -1162,10 +1161,23 @@
|
|
| 1162 |
try {
|
| 1163 |
const d = new Date();
|
| 1164 |
d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
|
| 1165 |
-
|
|
|
|
| 1166 |
} catch (e) {}
|
| 1167 |
}
|
| 1168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1169 |
function showToast(msg, type = "info") {
|
| 1170 |
const box = document.getElementById("toastContainer");
|
| 1171 |
if (!box) return;
|
|
@@ -1181,45 +1193,24 @@
|
|
| 1181 |
}
|
| 1182 |
|
| 1183 |
// =====================================================================
|
| 1184 |
-
// ๐ 6-DIGIT OTP GATE LOGIC (
|
| 1185 |
// =====================================================================
|
| 1186 |
-
function
|
| 1187 |
const inp = ev.target;
|
| 1188 |
-
const
|
| 1189 |
-
inp.value =
|
| 1190 |
-
if (inp.value && idx < 5) {
|
| 1191 |
-
const next = document.getElementById("otpDigit" + (idx + 1));
|
| 1192 |
-
if (next) next.focus();
|
| 1193 |
-
}
|
| 1194 |
}
|
| 1195 |
|
| 1196 |
-
function
|
| 1197 |
-
if (ev.key === "
|
| 1198 |
-
|
| 1199 |
-
if (prev) { prev.focus(); prev.value = ""; }
|
| 1200 |
-
} else if (ev.key === "Enter") {
|
| 1201 |
verifyAdminOtpCode();
|
| 1202 |
}
|
| 1203 |
}
|
| 1204 |
|
| 1205 |
-
function handleOtpPaste(ev) {
|
| 1206 |
-
const pasted = (ev.clipboardData || window.clipboardData).getData("text").replace(/\D/g, "").slice(0, 6);
|
| 1207 |
-
if (!pasted) return;
|
| 1208 |
-
ev.preventDefault();
|
| 1209 |
-
for (let i = 0; i < 6; i++) {
|
| 1210 |
-
const box = document.getElementById("otpDigit" + i);
|
| 1211 |
-
if (box) box.value = pasted[i] || "";
|
| 1212 |
-
}
|
| 1213 |
-
if (pasted.length === 6) verifyAdminOtpCode();
|
| 1214 |
-
}
|
| 1215 |
-
|
| 1216 |
function collectEnteredOtp() {
|
| 1217 |
-
|
| 1218 |
-
|
| 1219 |
-
const box = document.getElementById("otpDigit" + i);
|
| 1220 |
-
code += (box && box.value) ? box.value.trim() : "";
|
| 1221 |
-
}
|
| 1222 |
-
return code;
|
| 1223 |
}
|
| 1224 |
|
| 1225 |
async function requestAdminOtp() {
|
|
@@ -1238,10 +1229,16 @@
|
|
| 1238 |
});
|
| 1239 |
const data = await res.json();
|
| 1240 |
if (res.ok && data.ok) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1241 |
msgEl.style.color = "#10b981";
|
| 1242 |
-
msgEl.textContent = "โ
" + (data.message || "OTP sent
|
| 1243 |
showToast("6-digit OTP sent to registered admin device!", "success");
|
| 1244 |
-
document.getElementById("
|
|
|
|
| 1245 |
} else {
|
| 1246 |
msgEl.style.color = "#ef4444";
|
| 1247 |
msgEl.textContent = "โ " + (data.error || "Could not send OTP.");
|
|
@@ -1254,7 +1251,7 @@
|
|
| 1254 |
setTimeout(() => {
|
| 1255 |
btn.disabled = false;
|
| 1256 |
btn.textContent = "๐ฒ Resend 6-Digit Verification OTP";
|
| 1257 |
-
},
|
| 1258 |
}
|
| 1259 |
}
|
| 1260 |
|
|
@@ -1267,22 +1264,34 @@
|
|
| 1267 |
return;
|
| 1268 |
}
|
| 1269 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1270 |
const btn = document.getElementById("verifyOtpBtn");
|
| 1271 |
btn.disabled = true;
|
| 1272 |
btn.textContent = "โณ Verifying OTP...";
|
| 1273 |
|
| 1274 |
try {
|
|
|
|
|
|
|
|
|
|
| 1275 |
const res = await callServerHf("/auth/verify-otp", {
|
| 1276 |
method: "POST",
|
| 1277 |
-
headers
|
| 1278 |
-
body: JSON.stringify({
|
|
|
|
|
|
|
|
|
|
| 1279 |
});
|
| 1280 |
const data = await res.json();
|
| 1281 |
if (res.ok && data.ok && data.authenticated) {
|
| 1282 |
if (data.sessionToken) {
|
| 1283 |
-
setPersistentAuthCookie("
|
| 1284 |
try { localStorage.setItem("hf_cmd_session_hdr", data.sessionToken); } catch (e) {}
|
| 1285 |
}
|
|
|
|
| 1286 |
msgEl.style.color = "#10b981";
|
| 1287 |
msgEl.textContent = "โ
Verified! Saving cookie & unlocking Commander...";
|
| 1288 |
showToast("OTP Verified! Trusted device cookie saved.", "success");
|
|
@@ -1304,6 +1313,11 @@
|
|
| 1304 |
|
| 1305 |
async function checkExistingSessionOnBoot() {
|
| 1306 |
const msgEl = document.getElementById("otpStatusMsg");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1307 |
try {
|
| 1308 |
const res = await callServerHf("/auth/session", {
|
| 1309 |
method: "GET",
|
|
@@ -1353,17 +1367,15 @@
|
|
| 1353 |
});
|
| 1354 |
} catch (e) {}
|
| 1355 |
try { localStorage.removeItem("hf_cmd_session_hdr"); } catch (e) {}
|
| 1356 |
-
setPersistentAuthCookie("
|
| 1357 |
isSessionUnlocked = false;
|
| 1358 |
if (sseLogSource) { try { sseLogSource.close(); } catch (e) {} sseLogSource = null; }
|
| 1359 |
if (autoPollTimer) { clearInterval(autoPollTimer); autoPollTimer = null; }
|
| 1360 |
document.getElementById("commanderMainPage")?.classList.remove("unlocked");
|
| 1361 |
const gate = document.getElementById("otpGateScreen");
|
| 1362 |
if (gate) gate.style.display = "flex";
|
| 1363 |
-
|
| 1364 |
-
|
| 1365 |
-
if (b) b.value = "";
|
| 1366 |
-
}
|
| 1367 |
const msgEl = document.getElementById("otpStatusMsg");
|
| 1368 |
if (msgEl) {
|
| 1369 |
msgEl.style.color = "#f59e0b";
|
|
@@ -1405,10 +1417,8 @@
|
|
| 1405 |
|
| 1406 |
function buildAuthHeaders(extra = {}) {
|
| 1407 |
const h = Object.assign({ "Content-Type": "application/json" }, extra);
|
| 1408 |
-
|
| 1409 |
-
|
| 1410 |
-
if (savedHdr) h["x-hf-session"] = savedHdr;
|
| 1411 |
-
} catch (e) {}
|
| 1412 |
return h;
|
| 1413 |
}
|
| 1414 |
|
|
@@ -1499,7 +1509,9 @@
|
|
| 1499 |
sseLogSource = null;
|
| 1500 |
}
|
| 1501 |
try {
|
| 1502 |
-
const
|
|
|
|
|
|
|
| 1503 |
sseLogSource = es;
|
| 1504 |
es.onmessage = (ev) => {
|
| 1505 |
if (currentLogMode !== "server") return;
|
|
@@ -2073,7 +2085,6 @@
|
|
| 2073 |
// =====================================================================
|
| 2074 |
document.addEventListener("DOMContentLoaded", async () => {
|
| 2075 |
initUploadDropzone();
|
| 2076 |
-
document.getElementById("otpBoxesWrap")?.addEventListener("paste", handleOtpPaste);
|
| 2077 |
|
| 2078 |
const editorEl = document.getElementById("codeEditorTextarea");
|
| 2079 |
if (editorEl) {
|
|
|
|
| 78 |
margin: 0 auto 16px;
|
| 79 |
}
|
| 80 |
|
| 81 |
+
.otp-single-input {
|
| 82 |
+
width: 100% !important;
|
| 83 |
+
height: 60px;
|
| 84 |
+
margin: 14px 0 18px;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
text-align: center;
|
| 86 |
+
font-size: 28px !important;
|
| 87 |
font-weight: 900;
|
| 88 |
+
letter-spacing: 14px;
|
| 89 |
+
padding-left: 20px !important;
|
| 90 |
font-family: 'JetBrains Mono', monospace;
|
| 91 |
background: #050811 !important;
|
| 92 |
+
border: 2px solid rgba(245, 158, 11, 0.45) !important;
|
| 93 |
+
border-radius: 14px !important;
|
| 94 |
color: #fbbf24 !important;
|
| 95 |
transition: all 0.18s;
|
| 96 |
}
|
| 97 |
|
| 98 |
+
.otp-single-input:focus {
|
| 99 |
border-color: var(--primary) !important;
|
| 100 |
+
box-shadow: 0 0 0 4px rgba(245, 158, 11, 0.22);
|
|
|
|
| 101 |
}
|
| 102 |
|
| 103 |
/* TOPBAR */
|
|
|
|
| 798 |
<div style="font-size:11px; font-weight:800; color:var(--text-muted); text-transform:uppercase; letter-spacing:0.8px;">
|
| 799 |
Enter 6-Digit Verification Code
|
| 800 |
</div>
|
| 801 |
+
<input
|
| 802 |
+
type="text"
|
| 803 |
+
id="otpSingleInput"
|
| 804 |
+
class="otp-single-input"
|
| 805 |
+
maxlength="6"
|
| 806 |
+
inputmode="numeric"
|
| 807 |
+
autocomplete="one-time-code"
|
| 808 |
+
placeholder="โขโขโขโขโขโข"
|
| 809 |
+
oninput="onSingleOtpInput(event)"
|
| 810 |
+
onkeydown="onSingleOtpKeydown(event)"
|
| 811 |
+
>
|
| 812 |
|
| 813 |
<button id="verifyOtpBtn" class="btn green" style="width:100%;" onclick="verifyAdminOtpCode()">
|
| 814 |
โ
Verify OTP & Save Trusted Device Cookie
|
|
|
|
| 1144 |
// =====================================================================
|
| 1145 |
const HF_SERVER_BASE = "/api" + "/hf";
|
| 1146 |
let isSessionUnlocked = false;
|
| 1147 |
+
let latestOtpChallengeToken = "";
|
| 1148 |
let currentLogMode = "server"; // 'server' | 'run' | 'build'
|
| 1149 |
let allLogEntries = [];
|
| 1150 |
let repoFilesList = [];
|
|
|
|
| 1153 |
let autoPollTimer = null;
|
| 1154 |
|
| 1155 |
function callServerHf(subpath, opts = {}) {
|
| 1156 |
+
const merged = Object.assign({ credentials: "include" }, opts);
|
| 1157 |
return fetch(HF_SERVER_BASE + subpath, merged);
|
| 1158 |
}
|
| 1159 |
|
|
|
|
| 1161 |
try {
|
| 1162 |
const d = new Date();
|
| 1163 |
d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
|
| 1164 |
+
const sec = location.protocol === "https:" ? ";SameSite=None;Secure" : ";SameSite=Lax";
|
| 1165 |
+
document.cookie = `${name}=${encodeURIComponent(val)};expires=${d.toUTCString()};path=/${sec}`;
|
| 1166 |
} catch (e) {}
|
| 1167 |
}
|
| 1168 |
|
| 1169 |
+
function getSavedSessionToken() {
|
| 1170 |
+
try {
|
| 1171 |
+
const s = localStorage.getItem("hf_cmd_session_hdr");
|
| 1172 |
+
if (s) return s;
|
| 1173 |
+
} catch (e) {}
|
| 1174 |
+
try {
|
| 1175 |
+
const m = document.cookie.match(/(?:^|;\s*)hf_cmd_client_session=([^;]+)/);
|
| 1176 |
+
if (m) return decodeURIComponent(m[1]);
|
| 1177 |
+
} catch (e) {}
|
| 1178 |
+
return "";
|
| 1179 |
+
}
|
| 1180 |
+
|
| 1181 |
function showToast(msg, type = "info") {
|
| 1182 |
const box = document.getElementById("toastContainer");
|
| 1183 |
if (!box) return;
|
|
|
|
| 1193 |
}
|
| 1194 |
|
| 1195 |
// =====================================================================
|
| 1196 |
+
// ๐ 6-DIGIT OTP GATE LOGIC (SINGLE ROCK-SOLID INPUT + STATELESS TOKEN)
|
| 1197 |
// =====================================================================
|
| 1198 |
+
function onSingleOtpInput(ev) {
|
| 1199 |
const inp = ev.target;
|
| 1200 |
+
const cleaned = String(inp.value || "").replace(/\D/g, "").slice(0, 6);
|
| 1201 |
+
if (inp.value !== cleaned) inp.value = cleaned;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1202 |
}
|
| 1203 |
|
| 1204 |
+
function onSingleOtpKeydown(ev) {
|
| 1205 |
+
if (ev.key === "Enter") {
|
| 1206 |
+
ev.preventDefault();
|
|
|
|
|
|
|
| 1207 |
verifyAdminOtpCode();
|
| 1208 |
}
|
| 1209 |
}
|
| 1210 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1211 |
function collectEnteredOtp() {
|
| 1212 |
+
const inp = document.getElementById("otpSingleInput");
|
| 1213 |
+
return String(inp ? inp.value : "").replace(/\D/g, "").slice(0, 6);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1214 |
}
|
| 1215 |
|
| 1216 |
async function requestAdminOtp() {
|
|
|
|
| 1229 |
});
|
| 1230 |
const data = await res.json();
|
| 1231 |
if (res.ok && data.ok) {
|
| 1232 |
+
if (data.challengeToken) {
|
| 1233 |
+
latestOtpChallengeToken = data.challengeToken;
|
| 1234 |
+
try { localStorage.setItem("hf_otp_challenge_tok", data.challengeToken); } catch (e) {}
|
| 1235 |
+
setPersistentAuthCookie("hf_otp_challenge", data.challengeToken, 1);
|
| 1236 |
+
}
|
| 1237 |
msgEl.style.color = "#10b981";
|
| 1238 |
+
msgEl.textContent = "โ
" + (data.message || "OTP sent! Enter the 6-digit code above.");
|
| 1239 |
showToast("6-digit OTP sent to registered admin device!", "success");
|
| 1240 |
+
const otpInp = document.getElementById("otpSingleInput");
|
| 1241 |
+
if (otpInp) { otpInp.value = ""; otpInp.focus(); }
|
| 1242 |
} else {
|
| 1243 |
msgEl.style.color = "#ef4444";
|
| 1244 |
msgEl.textContent = "โ " + (data.error || "Could not send OTP.");
|
|
|
|
| 1251 |
setTimeout(() => {
|
| 1252 |
btn.disabled = false;
|
| 1253 |
btn.textContent = "๐ฒ Resend 6-Digit Verification OTP";
|
| 1254 |
+
}, 2500);
|
| 1255 |
}
|
| 1256 |
}
|
| 1257 |
|
|
|
|
| 1264 |
return;
|
| 1265 |
}
|
| 1266 |
|
| 1267 |
+
let challengeTok = latestOtpChallengeToken;
|
| 1268 |
+
if (!challengeTok) {
|
| 1269 |
+
try { challengeTok = localStorage.getItem("hf_otp_challenge_tok") || ""; } catch (e) {}
|
| 1270 |
+
}
|
| 1271 |
+
|
| 1272 |
const btn = document.getElementById("verifyOtpBtn");
|
| 1273 |
btn.disabled = true;
|
| 1274 |
btn.textContent = "โณ Verifying OTP...";
|
| 1275 |
|
| 1276 |
try {
|
| 1277 |
+
const headers = buildAuthHeaders();
|
| 1278 |
+
if (challengeTok) headers["x-hf-challenge"] = challengeTok;
|
| 1279 |
+
|
| 1280 |
const res = await callServerHf("/auth/verify-otp", {
|
| 1281 |
method: "POST",
|
| 1282 |
+
headers,
|
| 1283 |
+
body: JSON.stringify({
|
| 1284 |
+
otp,
|
| 1285 |
+
challengeToken: challengeTok || undefined
|
| 1286 |
+
})
|
| 1287 |
});
|
| 1288 |
const data = await res.json();
|
| 1289 |
if (res.ok && data.ok && data.authenticated) {
|
| 1290 |
if (data.sessionToken) {
|
| 1291 |
+
setPersistentAuthCookie("hf_cmd_client_session", data.sessionToken, 365);
|
| 1292 |
try { localStorage.setItem("hf_cmd_session_hdr", data.sessionToken); } catch (e) {}
|
| 1293 |
}
|
| 1294 |
+
try { localStorage.removeItem("hf_otp_challenge_tok"); } catch (e) {}
|
| 1295 |
msgEl.style.color = "#10b981";
|
| 1296 |
msgEl.textContent = "โ
Verified! Saving cookie & unlocking Commander...";
|
| 1297 |
showToast("OTP Verified! Trusted device cookie saved.", "success");
|
|
|
|
| 1313 |
|
| 1314 |
async function checkExistingSessionOnBoot() {
|
| 1315 |
const msgEl = document.getElementById("otpStatusMsg");
|
| 1316 |
+
try {
|
| 1317 |
+
const savedChallenge = localStorage.getItem("hf_otp_challenge_tok");
|
| 1318 |
+
if (savedChallenge) latestOtpChallengeToken = savedChallenge;
|
| 1319 |
+
} catch (e) {}
|
| 1320 |
+
|
| 1321 |
try {
|
| 1322 |
const res = await callServerHf("/auth/session", {
|
| 1323 |
method: "GET",
|
|
|
|
| 1367 |
});
|
| 1368 |
} catch (e) {}
|
| 1369 |
try { localStorage.removeItem("hf_cmd_session_hdr"); } catch (e) {}
|
| 1370 |
+
setPersistentAuthCookie("hf_cmd_client_session", "", -1);
|
| 1371 |
isSessionUnlocked = false;
|
| 1372 |
if (sseLogSource) { try { sseLogSource.close(); } catch (e) {} sseLogSource = null; }
|
| 1373 |
if (autoPollTimer) { clearInterval(autoPollTimer); autoPollTimer = null; }
|
| 1374 |
document.getElementById("commanderMainPage")?.classList.remove("unlocked");
|
| 1375 |
const gate = document.getElementById("otpGateScreen");
|
| 1376 |
if (gate) gate.style.display = "flex";
|
| 1377 |
+
const otpInp = document.getElementById("otpSingleInput");
|
| 1378 |
+
if (otpInp) otpInp.value = "";
|
|
|
|
|
|
|
| 1379 |
const msgEl = document.getElementById("otpStatusMsg");
|
| 1380 |
if (msgEl) {
|
| 1381 |
msgEl.style.color = "#f59e0b";
|
|
|
|
| 1417 |
|
| 1418 |
function buildAuthHeaders(extra = {}) {
|
| 1419 |
const h = Object.assign({ "Content-Type": "application/json" }, extra);
|
| 1420 |
+
const savedTok = getSavedSessionToken();
|
| 1421 |
+
if (savedTok) h["x-hf-session"] = savedTok;
|
|
|
|
|
|
|
| 1422 |
return h;
|
| 1423 |
}
|
| 1424 |
|
|
|
|
| 1509 |
sseLogSource = null;
|
| 1510 |
}
|
| 1511 |
try {
|
| 1512 |
+
const tok = getSavedSessionToken();
|
| 1513 |
+
const q = tok ? `?session=${encodeURIComponent(tok)}` : "";
|
| 1514 |
+
const es = new EventSource(HF_SERVER_BASE + "/logs/stream" + q);
|
| 1515 |
sseLogSource = es;
|
| 1516 |
es.onmessage = (ev) => {
|
| 1517 |
if (currentLogMode !== "server") return;
|
|
|
|
| 2085 |
// =====================================================================
|
| 2086 |
document.addEventListener("DOMContentLoaded", async () => {
|
| 2087 |
initUploadDropzone();
|
|
|
|
| 2088 |
|
| 2089 |
const editorEl = document.getElementById("codeEditorTextarea");
|
| 2090 |
if (editorEl) {
|
server.js
CHANGED
|
@@ -10589,19 +10589,14 @@ const server = http.createServer((req, res) => {
|
|
| 10589 |
|
| 10590 |
// ==============================================================================
|
| 10591 |
// ๐ HARDENED HUGGING FACE SPACE & SERVER COMMANDER (/api/hf/*)
|
| 10592 |
-
// -
|
| 10593 |
-
//
|
| 10594 |
-
//
|
| 10595 |
-
// -
|
| 10596 |
-
// registered device via Green API.
|
| 10597 |
-
// - Cookie Auth : HMAC-SHA256 signed + server-allowlisted persistent
|
| 10598 |
-
// HttpOnly cookie (`hf_cmd_session`, 365 days).
|
| 10599 |
-
// - Zero Bypass : Every /api/hf/* endpoint requires a valid
|
| 10600 |
-
// server-verified session cookie/token.
|
| 10601 |
// ==============================================================================
|
| 10602 |
const _DEFAULT_SPACE_B64 = "QWlj" + "aGF0Ym90MTIzMjEvVHJhbnNhbHRvcg==";
|
| 10603 |
const DEFAULT_HF_REPO_ID = process.env.SPACE_ID || Buffer.from(_DEFAULT_SPACE_B64, "base64").toString("utf-8");
|
| 10604 |
-
const _ADMIN_DEST_B64 = "OTE3OTkyNDEwNDEx";
|
| 10605 |
const ADMIN_OTP_DEST = String(process.env.ADMIN_OTP_PHONE || process.env.FEEDBACK_NUMBER || Buffer.from(_ADMIN_DEST_B64, "base64").toString("utf-8")).replace(/\D/g, "");
|
| 10606 |
|
| 10607 |
const SERVER_LOG_BUFFER = [];
|
|
@@ -10609,45 +10604,52 @@ const MAX_SERVER_LOGS = 800;
|
|
| 10609 |
const HF_LOG_SSE_CLIENTS = new Set();
|
| 10610 |
let SERVER_STANDBY_MODE = null; // null (running), "PAUSED", or "STOPPED"
|
| 10611 |
|
| 10612 |
-
|
| 10613 |
-
|
| 10614 |
-
|
| 10615 |
-
|
| 10616 |
-
|
| 10617 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10618 |
};
|
| 10619 |
|
| 10620 |
-
|
| 10621 |
try {
|
| 10622 |
-
if (fs.existsSync(
|
| 10623 |
-
const raw = JSON.parse(fs.readFileSync(
|
| 10624 |
if (raw && typeof raw === "object") {
|
| 10625 |
-
if (
|
| 10626 |
-
|
|
|
|
| 10627 |
}
|
| 10628 |
-
if (raw.
|
| 10629 |
-
|
| 10630 |
}
|
| 10631 |
}
|
| 10632 |
-
} else {
|
| 10633 |
-
HF_COMMANDER_AUTH_STATE.hmacSecret = crypto.randomBytes(32).toString("hex") + HF_COMMANDER_AUTH_STATE.hmacSecret;
|
| 10634 |
-
fs.writeFileSync(HF_COMMANDER_SECRET_FILE, JSON.stringify(HF_COMMANDER_AUTH_STATE), { mode: 0o600 });
|
| 10635 |
}
|
| 10636 |
} catch (e) {}
|
| 10637 |
-
}
|
|
|
|
| 10638 |
|
| 10639 |
-
function
|
| 10640 |
try {
|
| 10641 |
const now = Date.now();
|
| 10642 |
-
|
| 10643 |
-
|
| 10644 |
-
|
| 10645 |
-
fs.writeFileSync(
|
| 10646 |
} catch (e) {}
|
| 10647 |
}
|
| 10648 |
|
| 10649 |
-
|
| 10650 |
-
const OTP_IP_TRACKER = new Map(); // ip -> { lockedUntil, sendCount, windowStart, failCount }
|
| 10651 |
|
| 10652 |
function getClientIpAddress(req) {
|
| 10653 |
return String((req.headers["x-forwarded-for"] || req.socket?.remoteAddress || "127.0.0.1")).split(",")[0].trim();
|
|
@@ -10657,14 +10659,14 @@ function getIpSecurityRecord(ip) {
|
|
| 10657 |
const now = Date.now();
|
| 10658 |
let rec = OTP_IP_TRACKER.get(ip);
|
| 10659 |
if (!rec || (now - rec.windowStart > 15 * 60 * 1000 && rec.lockedUntil < now)) {
|
| 10660 |
-
rec = { lockedUntil: 0,
|
| 10661 |
OTP_IP_TRACKER.set(ip, rec);
|
| 10662 |
}
|
| 10663 |
return rec;
|
| 10664 |
}
|
| 10665 |
|
| 10666 |
function hashWithCommanderSecret(val) {
|
| 10667 |
-
return crypto.createHmac("sha256",
|
| 10668 |
}
|
| 10669 |
|
| 10670 |
function safeTimingEqualHex(hexA, hexB) {
|
|
@@ -10692,48 +10694,115 @@ function parseCookiesFromReq(req) {
|
|
| 10692 |
return out;
|
| 10693 |
}
|
| 10694 |
|
| 10695 |
-
function
|
| 10696 |
-
const
|
| 10697 |
-
const
|
| 10698 |
-
|
| 10699 |
-
|
| 10700 |
-
|
| 10701 |
-
|
| 10702 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10703 |
|
| 10704 |
-
|
| 10705 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10706 |
expiresAt,
|
| 10707 |
-
|
| 10708 |
-
|
| 10709 |
-
|
| 10710 |
-
|
|
|
|
|
|
|
| 10711 |
}
|
| 10712 |
|
| 10713 |
-
function
|
| 10714 |
-
const
|
| 10715 |
-
|
| 10716 |
-
|
| 10717 |
-
|
| 10718 |
-
|
| 10719 |
-
|
| 10720 |
-
|
| 10721 |
-
const
|
| 10722 |
-
|
| 10723 |
-
|
| 10724 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10725 |
}
|
| 10726 |
|
| 10727 |
-
|
| 10728 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10729 |
|
| 10730 |
-
|
| 10731 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10732 |
|
| 10733 |
-
|
| 10734 |
-
|
| 10735 |
|
| 10736 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10737 |
}
|
| 10738 |
|
| 10739 |
// Redacts ALL tokens, API keys, phone numbers, email addresses, and personal space identifiers
|
|
@@ -10794,7 +10863,7 @@ function pushServerLogEntry(level, argsArray) {
|
|
| 10794 |
console.log = (...args) => { pushServerLogEntry("INFO", args); origLog(...args); };
|
| 10795 |
console.warn = (...args) => { pushServerLogEntry("WARN", args); origWarn(...args); };
|
| 10796 |
console.error = (...args) => { pushServerLogEntry("ERROR", args); origErr(...args); };
|
| 10797 |
-
pushServerLogEntry("SYSTEM", ["HF Space Commander initialized (Personal Details & Token Hidden, OTP
|
| 10798 |
})();
|
| 10799 |
|
| 10800 |
function resolveHfCredentials(req, body = {}, parsedUrl = null) {
|
|
@@ -10850,7 +10919,7 @@ async function commitOperationsToHfSpace(repoId, token, commitMessage, operation
|
|
| 10850 |
headers: {
|
| 10851 |
"Authorization": `Bearer ${token}`,
|
| 10852 |
"Content-Type": "application/x-ndjson",
|
| 10853 |
-
"User-Agent": "HF-Space-Commander/
|
| 10854 |
},
|
| 10855 |
body: ndjsonBody,
|
| 10856 |
signal: AbortSignal.timeout(45000)
|
|
@@ -10869,7 +10938,7 @@ async function commitOperationsToHfSpace(repoId, token, commitMessage, operation
|
|
| 10869 |
|
| 10870 |
async function dispatchOtpToAdminPhone(otpCode) {
|
| 10871 |
if (!ID_INSTANCE || !API_TOKEN) {
|
| 10872 |
-
throw new Error("Server messaging gateway
|
| 10873 |
}
|
| 10874 |
let destNum = ADMIN_OTP_DEST;
|
| 10875 |
if (destNum.length === 10) destNum = "91" + destNum;
|
|
@@ -10877,7 +10946,7 @@ async function dispatchOtpToAdminPhone(otpCode) {
|
|
| 10877 |
const messageText =
|
| 10878 |
`๐ *HF COMMANDER SECURITY OTP*\n\n` +
|
| 10879 |
`Verification Code: *${otpCode}*\n` +
|
| 10880 |
-
`Valid for:
|
| 10881 |
`โ ๏ธ Do not share this code with anyone.`;
|
| 10882 |
|
| 10883 |
const response = await fetch(`${GREEN_API_BASE_URL}/sendMessage/${API_TOKEN}`, {
|
|
@@ -10902,15 +10971,14 @@ async function handleHfCommanderRoutes(req, res) {
|
|
| 10902 |
const clientIp = getClientIpAddress(req);
|
| 10903 |
|
| 10904 |
res.setHeader("X-Content-Type-Options", "nosniff");
|
| 10905 |
-
res.setHeader("X-Frame-Options", "SAMEORIGIN");
|
| 10906 |
res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, private");
|
| 10907 |
|
| 10908 |
try {
|
| 10909 |
// =====================================================================
|
| 10910 |
-
// PUBLIC AUTHENTICATION ENDPOINTS (/api/hf/auth/*)
|
| 10911 |
// =====================================================================
|
| 10912 |
if (req.method === "GET" && route === "auth/session") {
|
| 10913 |
-
const validSession = verifyCommanderAuth(req);
|
| 10914 |
return sendJson(res, 200, {
|
| 10915 |
ok: true,
|
| 10916 |
authenticated: Boolean(validSession)
|
|
@@ -10924,42 +10992,20 @@ async function handleHfCommanderRoutes(req, res) {
|
|
| 10924 |
const waitSec = Math.ceil((ipRec.lockedUntil - now) / 1000);
|
| 10925 |
return sendJson(res, 429, {
|
| 10926 |
ok: false,
|
| 10927 |
-
error: `Too many attempts. Security lockout active for ${waitSec}s.`
|
| 10928 |
-
});
|
| 10929 |
-
}
|
| 10930 |
-
if (ACTIVE_OTP_CHALLENGE && (now - ACTIVE_OTP_CHALLENGE.createdAt < 25000)) {
|
| 10931 |
-
const waitCooldown = Math.ceil((25000 - (now - ACTIVE_OTP_CHALLENGE.createdAt)) / 1000);
|
| 10932 |
-
return sendJson(res, 429, {
|
| 10933 |
-
ok: false,
|
| 10934 |
-
error: `Please wait ${waitCooldown}s before requesting another OTP.`
|
| 10935 |
-
});
|
| 10936 |
-
}
|
| 10937 |
-
if (ipRec.sendCount >= 6) {
|
| 10938 |
-
ipRec.lockedUntil = now + 15 * 60 * 1000;
|
| 10939 |
-
return sendJson(res, 429, {
|
| 10940 |
-
ok: false,
|
| 10941 |
-
error: "Maximum OTP requests reached. Locked for 15 minutes."
|
| 10942 |
});
|
| 10943 |
}
|
| 10944 |
|
| 10945 |
const otpPlain = String(crypto.randomInt(100000, 1000000));
|
| 10946 |
-
const
|
| 10947 |
-
const otpHash = hashWithCommanderSecret(`${otpSalt}:${otpPlain}`);
|
| 10948 |
|
| 10949 |
await dispatchOtpToAdminPhone(otpPlain);
|
| 10950 |
|
| 10951 |
-
|
| 10952 |
-
otpSalt,
|
| 10953 |
-
otpHash,
|
| 10954 |
-
createdAt: now,
|
| 10955 |
-
expiresAt: now + 5 * 60 * 1000,
|
| 10956 |
-
attempts: 0
|
| 10957 |
-
};
|
| 10958 |
-
ipRec.sendCount += 1;
|
| 10959 |
-
|
| 10960 |
return sendJson(res, 200, {
|
| 10961 |
ok: true,
|
| 10962 |
-
|
|
|
|
| 10963 |
});
|
| 10964 |
}
|
| 10965 |
|
|
@@ -10974,56 +11020,66 @@ async function handleHfCommanderRoutes(req, res) {
|
|
| 10974 |
});
|
| 10975 |
}
|
| 10976 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10977 |
const body = JSON.parse((await readRequestBody(req)) || "{}");
|
| 10978 |
const submittedOtp = String(body.otp || "").replace(/\D/g, "").trim();
|
| 10979 |
|
| 10980 |
if (!submittedOtp || submittedOtp.length !== 6) {
|
| 10981 |
-
return sendJson(res, 400, { ok: false, error: "Please enter
|
| 10982 |
}
|
| 10983 |
|
| 10984 |
-
|
| 10985 |
-
|
| 10986 |
-
|
| 10987 |
-
|
| 10988 |
-
|
| 10989 |
-
|
| 10990 |
-
}
|
| 10991 |
|
| 10992 |
-
|
| 10993 |
-
const candidateHash = hashWithCommanderSecret(`${ACTIVE_OTP_CHALLENGE.otpSalt}:${submittedOtp}`);
|
| 10994 |
-
const isMatch = safeTimingEqualHex(candidateHash, ACTIVE_OTP_CHALLENGE.otpHash);
|
| 10995 |
|
| 10996 |
-
if (!
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10997 |
ipRec.failCount += 1;
|
| 10998 |
-
const remaining = Math.max(0,
|
| 10999 |
-
if (
|
| 11000 |
-
ACTIVE_OTP_CHALLENGE = null;
|
| 11001 |
ipRec.lockedUntil = now + 15 * 60 * 1000;
|
| 11002 |
return sendJson(res, 403, {
|
| 11003 |
ok: false,
|
| 11004 |
-
error: "Too many wrong OTP attempts!
|
| 11005 |
});
|
| 11006 |
}
|
| 11007 |
return sendJson(res, 401, {
|
| 11008 |
ok: false,
|
| 11009 |
-
error: `
|
| 11010 |
});
|
| 11011 |
}
|
| 11012 |
|
| 11013 |
-
|
| 11014 |
ipRec.failCount = 0;
|
| 11015 |
-
|
| 11016 |
-
|
| 11017 |
-
|
| 11018 |
-
|
| 11019 |
-
|
| 11020 |
-
|
| 11021 |
-
|
| 11022 |
-
|
| 11023 |
-
|
| 11024 |
-
if (isHttps) cookieFlags.push("Secure");
|
| 11025 |
-
|
| 11026 |
-
res.setHeader("Set-Cookie", cookieFlags.join("; "));
|
| 11027 |
return sendJson(res, 200, {
|
| 11028 |
ok: true,
|
| 11029 |
authenticated: true,
|
|
@@ -11033,19 +11089,20 @@ async function handleHfCommanderRoutes(req, res) {
|
|
| 11033 |
}
|
| 11034 |
|
| 11035 |
if (req.method === "POST" && route === "auth/logout") {
|
| 11036 |
-
const validSession = verifyCommanderAuth(req);
|
| 11037 |
if (validSession && validSession.jti) {
|
| 11038 |
-
|
| 11039 |
-
|
|
|
|
| 11040 |
}
|
| 11041 |
-
res.setHeader("Set-Cookie", "hf_cmd_session
|
| 11042 |
return sendJson(res, 200, { ok: true, authenticated: false, message: "Session locked and cookie cleared." });
|
| 11043 |
}
|
| 11044 |
|
| 11045 |
// =====================================================================
|
| 11046 |
// ๐ STRICT SERVER-SIDE AUTH GATE FOR ALL COMMANDER ROUTES BELOW
|
| 11047 |
// =====================================================================
|
| 11048 |
-
const authSession = verifyCommanderAuth(req);
|
| 11049 |
if (!authSession) {
|
| 11050 |
return sendJson(res, 401, {
|
| 11051 |
ok: false,
|
|
|
|
| 10589 |
|
| 10590 |
// ==============================================================================
|
| 10591 |
// ๐ HARDENED HUGGING FACE SPACE & SERVER COMMANDER (/api/hf/*)
|
| 10592 |
+
// - Stateless + Stateful OTP Verification (never loses challenge across
|
| 10593 |
+
// restarts, multiple tabs, or Hugging Face iframe cookie restrictions)
|
| 10594 |
+
// - Zero Personal Details Exposed in UI, responses, or logs
|
| 10595 |
+
// - Persistent 365-Day HMAC-SHA256 Signed Cookie + Header Auth
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10596 |
// ==============================================================================
|
| 10597 |
const _DEFAULT_SPACE_B64 = "QWlj" + "aGF0Ym90MTIzMjEvVHJhbnNhbHRvcg==";
|
| 10598 |
const DEFAULT_HF_REPO_ID = process.env.SPACE_ID || Buffer.from(_DEFAULT_SPACE_B64, "base64").toString("utf-8");
|
| 10599 |
+
const _ADMIN_DEST_B64 = "OTE3OTkyNDEwNDEx";
|
| 10600 |
const ADMIN_OTP_DEST = String(process.env.ADMIN_OTP_PHONE || process.env.FEEDBACK_NUMBER || Buffer.from(_ADMIN_DEST_B64, "base64").toString("utf-8")).replace(/\D/g, "");
|
| 10601 |
|
| 10602 |
const SERVER_LOG_BUFFER = [];
|
|
|
|
| 10604 |
const HF_LOG_SSE_CLIENTS = new Set();
|
| 10605 |
let SERVER_STANDBY_MODE = null; // null (running), "PAUSED", or "STOPPED"
|
| 10606 |
|
| 10607 |
+
// Deterministic HMAC secret derived from server environment so it NEVER changes across container restarts or workers
|
| 10608 |
+
const HF_DETERMINISTIC_HMAC_SECRET = crypto.createHash("sha256")
|
| 10609 |
+
.update(
|
| 10610 |
+
"hf_commander_v4_secret::" +
|
| 10611 |
+
String(process.env.HF_ACCESS_TOKEN || "") + "::" +
|
| 10612 |
+
String(process.env.API_TOKEN || "") + "::" +
|
| 10613 |
+
String(process.env.ID_INSTANCE || "") + "::" +
|
| 10614 |
+
DEFAULT_HF_REPO_ID
|
| 10615 |
+
)
|
| 10616 |
+
.digest("hex");
|
| 10617 |
+
|
| 10618 |
+
const HF_COMMANDER_STATE_FILE = path.join(os.tmpdir(), ".hf_commander_state_v4.json");
|
| 10619 |
+
let HF_COMMANDER_STATE = {
|
| 10620 |
+
challenges: [], // [{ otpSalt, expiresAt, otpHash, createdAt }]
|
| 10621 |
+
revokedJtis: {} // jti -> revokedAt
|
| 10622 |
};
|
| 10623 |
|
| 10624 |
+
function loadCommanderStateFromDisk() {
|
| 10625 |
try {
|
| 10626 |
+
if (fs.existsSync(HF_COMMANDER_STATE_FILE)) {
|
| 10627 |
+
const raw = JSON.parse(fs.readFileSync(HF_COMMANDER_STATE_FILE, "utf-8"));
|
| 10628 |
if (raw && typeof raw === "object") {
|
| 10629 |
+
if (Array.isArray(raw.challenges)) {
|
| 10630 |
+
const now = Date.now();
|
| 10631 |
+
HF_COMMANDER_STATE.challenges = raw.challenges.filter(c => c && c.expiresAt > now);
|
| 10632 |
}
|
| 10633 |
+
if (raw.revokedJtis && typeof raw.revokedJtis === "object") {
|
| 10634 |
+
HF_COMMANDER_STATE.revokedJtis = raw.revokedJtis;
|
| 10635 |
}
|
| 10636 |
}
|
|
|
|
|
|
|
|
|
|
| 10637 |
}
|
| 10638 |
} catch (e) {}
|
| 10639 |
+
}
|
| 10640 |
+
loadCommanderStateFromDisk();
|
| 10641 |
|
| 10642 |
+
function saveCommanderStateToDisk() {
|
| 10643 |
try {
|
| 10644 |
const now = Date.now();
|
| 10645 |
+
HF_COMMANDER_STATE.challenges = (HF_COMMANDER_STATE.challenges || [])
|
| 10646 |
+
.filter(c => c && c.expiresAt > now)
|
| 10647 |
+
.slice(-15);
|
| 10648 |
+
fs.writeFileSync(HF_COMMANDER_STATE_FILE, JSON.stringify(HF_COMMANDER_STATE), { mode: 0o600 });
|
| 10649 |
} catch (e) {}
|
| 10650 |
}
|
| 10651 |
|
| 10652 |
+
const OTP_IP_TRACKER = new Map(); // ip -> { lockedUntil, failCount, windowStart }
|
|
|
|
| 10653 |
|
| 10654 |
function getClientIpAddress(req) {
|
| 10655 |
return String((req.headers["x-forwarded-for"] || req.socket?.remoteAddress || "127.0.0.1")).split(",")[0].trim();
|
|
|
|
| 10659 |
const now = Date.now();
|
| 10660 |
let rec = OTP_IP_TRACKER.get(ip);
|
| 10661 |
if (!rec || (now - rec.windowStart > 15 * 60 * 1000 && rec.lockedUntil < now)) {
|
| 10662 |
+
rec = { lockedUntil: 0, failCount: 0, windowStart: now };
|
| 10663 |
OTP_IP_TRACKER.set(ip, rec);
|
| 10664 |
}
|
| 10665 |
return rec;
|
| 10666 |
}
|
| 10667 |
|
| 10668 |
function hashWithCommanderSecret(val) {
|
| 10669 |
+
return crypto.createHmac("sha256", HF_DETERMINISTIC_HMAC_SECRET).update(String(val)).digest("hex");
|
| 10670 |
}
|
| 10671 |
|
| 10672 |
function safeTimingEqualHex(hexA, hexB) {
|
|
|
|
| 10694 |
return out;
|
| 10695 |
}
|
| 10696 |
|
| 10697 |
+
function buildCookieHeaderString(req, name, val, maxAgeSec) {
|
| 10698 |
+
const isHttps = (req.headers["x-forwarded-proto"] === "https") || Boolean(process.env.SPACE_ID);
|
| 10699 |
+
const flags = [
|
| 10700 |
+
`${name}=${encodeURIComponent(val)}`,
|
| 10701 |
+
`Path=/`,
|
| 10702 |
+
`Max-Age=${maxAgeSec}`,
|
| 10703 |
+
`HttpOnly`
|
| 10704 |
+
];
|
| 10705 |
+
// Use SameSite=None; Secure on HTTPS so cookies work inside Hugging Face Spaces iframe!
|
| 10706 |
+
if (isHttps) {
|
| 10707 |
+
flags.push("SameSite=None", "Secure");
|
| 10708 |
+
} else {
|
| 10709 |
+
flags.push("SameSite=Lax");
|
| 10710 |
+
}
|
| 10711 |
+
return flags.join("; ");
|
| 10712 |
+
}
|
| 10713 |
|
| 10714 |
+
function createOtpChallengeToken(otpPlain) {
|
| 10715 |
+
const cleanOtp = String(otpPlain || "").trim();
|
| 10716 |
+
const otpSalt = crypto.randomBytes(12).toString("hex");
|
| 10717 |
+
const expiresAt = Date.now() + 15 * 60 * 1000; // 15 minutes validity
|
| 10718 |
+
const otpHash = hashWithCommanderSecret(`otp_v4:${otpSalt}:${expiresAt}:${cleanOtp}`);
|
| 10719 |
+
const challengeToken = `${otpSalt}.${expiresAt}.${otpHash}`;
|
| 10720 |
+
|
| 10721 |
+
loadCommanderStateFromDisk();
|
| 10722 |
+
HF_COMMANDER_STATE.challenges.push({
|
| 10723 |
+
otpSalt,
|
| 10724 |
expiresAt,
|
| 10725 |
+
otpHash,
|
| 10726 |
+
createdAt: Date.now()
|
| 10727 |
+
});
|
| 10728 |
+
saveCommanderStateToDisk();
|
| 10729 |
+
|
| 10730 |
+
return { challengeToken, expiresAt };
|
| 10731 |
}
|
| 10732 |
|
| 10733 |
+
function verifyOtpAgainstChallenges(submittedOtp, providedChallengeTokens = []) {
|
| 10734 |
+
const cleanOtp = String(submittedOtp || "").replace(/\D/g, "").trim();
|
| 10735 |
+
if (cleanOtp.length !== 6) return { valid: false, reason: "format" };
|
| 10736 |
+
|
| 10737 |
+
const now = Date.now();
|
| 10738 |
+
loadCommanderStateFromDisk();
|
| 10739 |
+
|
| 10740 |
+
// 1. Check stateless signed challengeToken(s) from body / header / cookie first (works even across container restarts!)
|
| 10741 |
+
for (const rawTok of providedChallengeTokens) {
|
| 10742 |
+
if (!rawTok || typeof rawTok !== "string") continue;
|
| 10743 |
+
const parts = rawTok.trim().split(".");
|
| 10744 |
+
if (parts.length === 3) {
|
| 10745 |
+
const [salt, expStr, expectedHash] = parts;
|
| 10746 |
+
const exp = parseInt(expStr, 10);
|
| 10747 |
+
if (salt && exp && !isNaN(exp) && now <= exp) {
|
| 10748 |
+
const candidateHash = hashWithCommanderSecret(`otp_v4:${salt}:${exp}:${cleanOtp}`);
|
| 10749 |
+
if (safeTimingEqualHex(candidateHash, expectedHash)) {
|
| 10750 |
+
return { valid: true };
|
| 10751 |
+
}
|
| 10752 |
+
}
|
| 10753 |
+
}
|
| 10754 |
}
|
| 10755 |
|
| 10756 |
+
// 2. Check all active challenges stored in memory/disk from the last 15 minutes
|
| 10757 |
+
const activeList = (HF_COMMANDER_STATE.challenges || []).filter(c => c && c.expiresAt > now);
|
| 10758 |
+
for (let i = activeList.length - 1; i >= 0; i--) {
|
| 10759 |
+
const ch = activeList[i];
|
| 10760 |
+
const candidateHash = hashWithCommanderSecret(`otp_v4:${ch.otpSalt}:${ch.expiresAt}:${cleanOtp}`);
|
| 10761 |
+
if (safeTimingEqualHex(candidateHash, ch.otpHash)) {
|
| 10762 |
+
return { valid: true };
|
| 10763 |
+
}
|
| 10764 |
+
}
|
| 10765 |
|
| 10766 |
+
// Determine if there were any challenges at all
|
| 10767 |
+
const hadAnyActive = activeList.length > 0 || providedChallengeTokens.some(t => {
|
| 10768 |
+
if (!t || typeof t !== "string") return false;
|
| 10769 |
+
const p = t.split(".");
|
| 10770 |
+
return p.length === 3 && parseInt(p[1], 10) > now;
|
| 10771 |
+
});
|
| 10772 |
|
| 10773 |
+
return { valid: false, reason: hadAnyActive ? "mismatch" : "expired_or_missing" };
|
| 10774 |
+
}
|
| 10775 |
|
| 10776 |
+
function issueCommanderSessionToken() {
|
| 10777 |
+
const jti = crypto.randomBytes(20).toString("hex");
|
| 10778 |
+
const expiresAt = Date.now() + 365 * 24 * 60 * 60 * 1000; // 1 year persistent session
|
| 10779 |
+
const payloadStr = `${jti}.${expiresAt}`;
|
| 10780 |
+
const sig = hashWithCommanderSecret(`session_v4:${payloadStr}`);
|
| 10781 |
+
const fullToken = `${payloadStr}.${sig}`;
|
| 10782 |
+
return { fullToken, jti, expiresAt, maxAgeSec: 365 * 24 * 60 * 60 };
|
| 10783 |
+
}
|
| 10784 |
+
|
| 10785 |
+
function verifyCommanderAuth(req, parsedUrl = null) {
|
| 10786 |
+
const cookies = parseCookiesFromReq(req);
|
| 10787 |
+
const headerTok = String(req.headers["x-hf-session"] || "").trim();
|
| 10788 |
+
const queryTok = parsedUrl ? String(parsedUrl.searchParams.get("session") || "").trim() : "";
|
| 10789 |
+
const candidates = [headerTok, cookies["hf_cmd_session"], cookies["hf_cmd_client_session"], queryTok].filter(Boolean);
|
| 10790 |
+
|
| 10791 |
+
for (const rawToken of candidates) {
|
| 10792 |
+
const parts = String(rawToken).trim().split(".");
|
| 10793 |
+
if (parts.length !== 3) continue;
|
| 10794 |
+
const [jti, expStr, providedSig] = parts;
|
| 10795 |
+
const expiresAt = parseInt(expStr, 10);
|
| 10796 |
+
if (!jti || !expiresAt || isNaN(expiresAt) || Date.now() > expiresAt) continue;
|
| 10797 |
+
|
| 10798 |
+
if (HF_COMMANDER_STATE.revokedJtis && HF_COMMANDER_STATE.revokedJtis[jti]) continue;
|
| 10799 |
+
|
| 10800 |
+
const expectedSig = hashWithCommanderSecret(`session_v4:${jti}.${expStr}`);
|
| 10801 |
+
if (safeTimingEqualHex(providedSig, expectedSig)) {
|
| 10802 |
+
return { jti, expiresAt, token: rawToken };
|
| 10803 |
+
}
|
| 10804 |
+
}
|
| 10805 |
+
return false;
|
| 10806 |
}
|
| 10807 |
|
| 10808 |
// Redacts ALL tokens, API keys, phone numbers, email addresses, and personal space identifiers
|
|
|
|
| 10863 |
console.log = (...args) => { pushServerLogEntry("INFO", args); origLog(...args); };
|
| 10864 |
console.warn = (...args) => { pushServerLogEntry("WARN", args); origWarn(...args); };
|
| 10865 |
console.error = (...args) => { pushServerLogEntry("ERROR", args); origErr(...args); };
|
| 10866 |
+
pushServerLogEntry("SYSTEM", ["HF Space Commander initialized (Personal Details & Token Hidden, Stateless+Stateful OTP Active)"]);
|
| 10867 |
})();
|
| 10868 |
|
| 10869 |
function resolveHfCredentials(req, body = {}, parsedUrl = null) {
|
|
|
|
| 10919 |
headers: {
|
| 10920 |
"Authorization": `Bearer ${token}`,
|
| 10921 |
"Content-Type": "application/x-ndjson",
|
| 10922 |
+
"User-Agent": "HF-Space-Commander/4.0"
|
| 10923 |
},
|
| 10924 |
body: ndjsonBody,
|
| 10925 |
signal: AbortSignal.timeout(45000)
|
|
|
|
| 10938 |
|
| 10939 |
async function dispatchOtpToAdminPhone(otpCode) {
|
| 10940 |
if (!ID_INSTANCE || !API_TOKEN) {
|
| 10941 |
+
throw new Error("Server messaging gateway (ID_INSTANCE / API_TOKEN) is not configured.");
|
| 10942 |
}
|
| 10943 |
let destNum = ADMIN_OTP_DEST;
|
| 10944 |
if (destNum.length === 10) destNum = "91" + destNum;
|
|
|
|
| 10946 |
const messageText =
|
| 10947 |
`๐ *HF COMMANDER SECURITY OTP*\n\n` +
|
| 10948 |
`Verification Code: *${otpCode}*\n` +
|
| 10949 |
+
`Valid for: 15 minutes\n\n` +
|
| 10950 |
`โ ๏ธ Do not share this code with anyone.`;
|
| 10951 |
|
| 10952 |
const response = await fetch(`${GREEN_API_BASE_URL}/sendMessage/${API_TOKEN}`, {
|
|
|
|
| 10971 |
const clientIp = getClientIpAddress(req);
|
| 10972 |
|
| 10973 |
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
|
|
| 10974 |
res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, private");
|
| 10975 |
|
| 10976 |
try {
|
| 10977 |
// =====================================================================
|
| 10978 |
+
// PUBLIC AUTHENTICATION ENDPOINTS (/api/hf/auth/*)
|
| 10979 |
// =====================================================================
|
| 10980 |
if (req.method === "GET" && route === "auth/session") {
|
| 10981 |
+
const validSession = verifyCommanderAuth(req, parsedUrl);
|
| 10982 |
return sendJson(res, 200, {
|
| 10983 |
ok: true,
|
| 10984 |
authenticated: Boolean(validSession)
|
|
|
|
| 10992 |
const waitSec = Math.ceil((ipRec.lockedUntil - now) / 1000);
|
| 10993 |
return sendJson(res, 429, {
|
| 10994 |
ok: false,
|
| 10995 |
+
error: `Too many failed attempts. Security lockout active for ${waitSec}s.`
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10996 |
});
|
| 10997 |
}
|
| 10998 |
|
| 10999 |
const otpPlain = String(crypto.randomInt(100000, 1000000));
|
| 11000 |
+
const { challengeToken } = createOtpChallengeToken(otpPlain);
|
|
|
|
| 11001 |
|
| 11002 |
await dispatchOtpToAdminPhone(otpPlain);
|
| 11003 |
|
| 11004 |
+
res.setHeader("Set-Cookie", buildCookieHeaderString(req, "hf_otp_challenge", challengeToken, 900));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11005 |
return sendJson(res, 200, {
|
| 11006 |
ok: true,
|
| 11007 |
+
challengeToken,
|
| 11008 |
+
message: "6-digit verification OTP sent to your registered admin device. Valid for 15 minutes."
|
| 11009 |
});
|
| 11010 |
}
|
| 11011 |
|
|
|
|
| 11020 |
});
|
| 11021 |
}
|
| 11022 |
|
| 11023 |
+
// If already authenticated on this request (e.g. accidental double click on Verify), succeed immediately!
|
| 11024 |
+
const existingSession = verifyCommanderAuth(req, parsedUrl);
|
| 11025 |
+
if (existingSession) {
|
| 11026 |
+
return sendJson(res, 200, {
|
| 11027 |
+
ok: true,
|
| 11028 |
+
authenticated: true,
|
| 11029 |
+
sessionToken: existingSession.token,
|
| 11030 |
+
message: "OTP verified! Persistent security cookie saved."
|
| 11031 |
+
});
|
| 11032 |
+
}
|
| 11033 |
+
|
| 11034 |
const body = JSON.parse((await readRequestBody(req)) || "{}");
|
| 11035 |
const submittedOtp = String(body.otp || "").replace(/\D/g, "").trim();
|
| 11036 |
|
| 11037 |
if (!submittedOtp || submittedOtp.length !== 6) {
|
| 11038 |
+
return sendJson(res, 400, { ok: false, error: "Please enter all 6 digits of the OTP." });
|
| 11039 |
}
|
| 11040 |
|
| 11041 |
+
const cookies = parseCookiesFromReq(req);
|
| 11042 |
+
const challengeCandidates = [
|
| 11043 |
+
body.challengeToken,
|
| 11044 |
+
req.headers["x-hf-challenge"],
|
| 11045 |
+
cookies["hf_otp_challenge"]
|
| 11046 |
+
].filter(Boolean);
|
|
|
|
| 11047 |
|
| 11048 |
+
const checkResult = verifyOtpAgainstChallenges(submittedOtp, challengeCandidates);
|
|
|
|
|
|
|
| 11049 |
|
| 11050 |
+
if (!checkResult.valid) {
|
| 11051 |
+
if (checkResult.reason === "expired_or_missing") {
|
| 11052 |
+
return sendJson(res, 400, {
|
| 11053 |
+
ok: false,
|
| 11054 |
+
error: "OTP has expired (15 min limit) or was not sent yet. Click 'Send 6-Digit Verification OTP' first."
|
| 11055 |
+
});
|
| 11056 |
+
}
|
| 11057 |
ipRec.failCount += 1;
|
| 11058 |
+
const remaining = Math.max(0, 6 - ipRec.failCount);
|
| 11059 |
+
if (ipRec.failCount >= 6) {
|
|
|
|
| 11060 |
ipRec.lockedUntil = now + 15 * 60 * 1000;
|
| 11061 |
return sendJson(res, 403, {
|
| 11062 |
ok: false,
|
| 11063 |
+
error: "Too many wrong OTP attempts! Locked for 15 minutes."
|
| 11064 |
});
|
| 11065 |
}
|
| 11066 |
return sendJson(res, 401, {
|
| 11067 |
ok: false,
|
| 11068 |
+
error: `Incorrect 6-digit OTP code. ${remaining} attempt(s) remaining.`
|
| 11069 |
});
|
| 11070 |
}
|
| 11071 |
|
| 11072 |
+
// OTP Verified! Clear fail count & issue persistent 1-year session token + cookie
|
| 11073 |
ipRec.failCount = 0;
|
| 11074 |
+
HF_COMMANDER_STATE.challenges = [];
|
| 11075 |
+
saveCommanderStateToDisk();
|
| 11076 |
+
|
| 11077 |
+
const { fullToken, maxAgeSec } = issueCommanderSessionToken();
|
| 11078 |
+
res.setHeader("Set-Cookie", [
|
| 11079 |
+
buildCookieHeaderString(req, "hf_cmd_session", fullToken, maxAgeSec),
|
| 11080 |
+
buildCookieHeaderString(req, "hf_otp_challenge", "", 0)
|
| 11081 |
+
]);
|
| 11082 |
+
|
|
|
|
|
|
|
|
|
|
| 11083 |
return sendJson(res, 200, {
|
| 11084 |
ok: true,
|
| 11085 |
authenticated: true,
|
|
|
|
| 11089 |
}
|
| 11090 |
|
| 11091 |
if (req.method === "POST" && route === "auth/logout") {
|
| 11092 |
+
const validSession = verifyCommanderAuth(req, parsedUrl);
|
| 11093 |
if (validSession && validSession.jti) {
|
| 11094 |
+
loadCommanderStateFromDisk();
|
| 11095 |
+
HF_COMMANDER_STATE.revokedJtis[validSession.jti] = Date.now();
|
| 11096 |
+
saveCommanderStateToDisk();
|
| 11097 |
}
|
| 11098 |
+
res.setHeader("Set-Cookie", buildCookieHeaderString(req, "hf_cmd_session", "", 0));
|
| 11099 |
return sendJson(res, 200, { ok: true, authenticated: false, message: "Session locked and cookie cleared." });
|
| 11100 |
}
|
| 11101 |
|
| 11102 |
// =====================================================================
|
| 11103 |
// ๐ STRICT SERVER-SIDE AUTH GATE FOR ALL COMMANDER ROUTES BELOW
|
| 11104 |
// =====================================================================
|
| 11105 |
+
const authSession = verifyCommanderAuth(req, parsedUrl);
|
| 11106 |
if (!authSession) {
|
| 11107 |
return sendJson(res, 401, {
|
| 11108 |
ok: false,
|