File size: 62,234 Bytes
88c4c60 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 | "use client";
import { useState, useEffect, useRef, useCallback } from "react";
import PropTypes from "prop-types";
import { Card, Button, Input, Modal, CardSkeleton, Toggle, ConfirmModal } from "@/shared/components";
import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard";
import { getCurrentLocale, onLocaleChange } from "@/i18n/runtime";
// Locales that unlock wenyan (classical Chinese) caveman levels
const WENYAN_LOCALES = ["zh-CN", "zh-TW"];
const TUNNEL_BENEFITS = [
{ icon: "public", title: "Access Anywhere", desc: "Use your API from any network" },
{ icon: "group", title: "Share Endpoint", desc: "Share URL with team members" },
{ icon: "code", title: "Use in Cursor/Cline", desc: "Connect AI tools remotely" },
{ icon: "lock", title: "Encrypted", desc: "End-to-end TLS via Cloudflare" },
];
const TUNNEL_PING_INTERVAL_MS = 2000;
const TUNNEL_PING_MAX_MS = 300000;
const STATUS_POLL_FAST_MS = 5000;
const STATUS_POLL_SLOW_MS = 30000;
const REACHABLE_MISS_THRESHOLD = 5;
const CLIENT_PING_FAST_MS = 10000;
const CLIENT_PING_SLOW_MS = 60000;
const CLIENT_PING_TIMEOUT_MS = 5000;
// Browser-side health probe: must reach origin (not just CF/TS edge).
// cors mode → res.ok=false for 5xx (e.g. Cloudflare 530 when origin dead).
// /api/health route sets Access-Control-Allow-Origin: * → CORS works through tunnel.
async function clientPingUrl(url) {
if (!url) return false;
try {
const res = await fetch(`${url}/api/health`, {
mode: "cors",
cache: "no-store",
signal: AbortSignal.timeout(CLIENT_PING_TIMEOUT_MS),
});
return res.ok;
} catch { return false; }
}
// Race multiple URLs: resolve true as soon as any one passes ping.
async function clientPingAny(...urls) {
const checks = urls.filter(Boolean).map(clientPingUrl);
if (!checks.length) return false;
return new Promise((resolve) => {
let pending = checks.length;
checks.forEach((p) => p.then((ok) => {
if (ok) resolve(true);
else if (--pending === 0) resolve(false);
}));
});
}
const CAVEMAN_LEVELS = [
{ id: "lite", label: "Lite", desc: "Drop filler, keep grammar" },
{ id: "full", label: "Full", desc: "Drop articles, fragments OK" },
{ id: "ultra", label: "Ultra", desc: "Telegraphic, max compression" },
{ id: "wenyan-lite", label: "文 Lite", desc: "Classical Chinese, light compression", wenyan: true },
{ id: "wenyan", label: "文 Full", desc: "Maximum 文言文, 80-90% reduction", wenyan: true },
{ id: "wenyan-ultra", label: "文 Ultra", desc: "Extreme classical compression", wenyan: true },
];
export default function APIPageClient({ machineId }) {
const [keys, setKeys] = useState([]);
const [loading, setLoading] = useState(true);
const [showAddModal, setShowAddModal] = useState(false);
const [newKeyName, setNewKeyName] = useState("");
const [createdKey, setCreatedKey] = useState(null);
const [confirmState, setConfirmState] = useState(null);
const [requireApiKey, setRequireApiKey] = useState(false);
const [requireLogin, setRequireLogin] = useState(true);
const [hasPassword, setHasPassword] = useState(true);
const [tunnelDashboardAccess, setTunnelDashboardAccess] = useState(false);
const [rtkEnabled, setRtkEnabledState] = useState(true);
const [cavemanEnabled, setCavemanEnabled] = useState(false);
const [cavemanLevel, setCavemanLevel] = useState("full");
const [locale, setLocale] = useState("en");
// Cloudflare Tunnel state
const [tunnelChecking, setTunnelChecking] = useState(true);
const [tunnelEnabled, setTunnelEnabled] = useState(false);
const [tunnelReachable, setTunnelReachable] = useState(false);
const [tunnelUrl, setTunnelUrl] = useState("");
const [tunnelPublicUrl, setTunnelPublicUrl] = useState("");
const [tunnelLoading, setTunnelLoading] = useState(false);
const [tunnelProgress, setTunnelProgress] = useState("");
const [tunnelStatus, setTunnelStatus] = useState(null);
const [showEnableTunnelModal, setShowEnableTunnelModal] = useState(false);
const [showDisableTunnelModal, setShowDisableTunnelModal] = useState(false);
// Tailscale state
const [tsEnabled, setTsEnabled] = useState(false);
const [tsReachable, setTsReachable] = useState(false);
const [tsUrl, setTsUrl] = useState("");
const [tsLoading, setTsLoading] = useState(false);
const [tsProgress, setTsProgress] = useState("");
const [tsStatus, setTsStatus] = useState(null);
const [tsAuthUrl, setTsAuthUrl] = useState("");
const [tsAuthLabel, setTsAuthLabel] = useState("");
const [tsInstalled, setTsInstalled] = useState(null); // null=checking, true/false
const [tsInstalling, setTsInstalling] = useState(false);
const [tsInstallLog, setTsInstallLog] = useState([]);
const [tsSudoPassword, setTsSudoPassword] = useState("");
const [tsConnecting, setTsConnecting] = useState(false);
const [showTsModal, setShowTsModal] = useState(false);
const [showDisableTsModal, setShowDisableTsModal] = useState(false);
const tsLogRef = useRef(null);
// Debounce reachable=false: server may briefly return false during background refresh.
// Only flip UI to "reconnecting" after N consecutive misses to avoid spinner flicker.
const tunnelMissRef = useRef(0);
const tsMissRef = useRef(0);
// Browser-side reachable cache (independent of backend DNS quirks)
const tunnelClientReachableRef = useRef(false);
const tsClientReachableRef = useRef(false);
// Track whether reachable=true was ever observed in this session.
// Distinguishes "Checking..." (initial cold cache) from "Reconnecting..." (lost connection).
const tunnelEverReachableRef = useRef(false);
const tsEverReachableRef = useRef(false);
const [tunnelEverReachable, setTunnelEverReachable] = useState(false);
const [tsEverReachable, setTsEverReachable] = useState(false);
// API key visibility toggle state
const [visibleKeys, setVisibleKeys] = useState(new Set());
// Client-side local/remote detection (UI hint only, not a security gate)
const [isRemoteHost, setIsRemoteHost] = useState(false);
useEffect(() => {
if (typeof window !== "undefined")
setIsRemoteHost(!["localhost", "127.0.0.1", "::1"].includes(window.location.hostname));
}, []);
// Track app UI locale to gate wenyan caveman levels
useEffect(() => {
setLocale(getCurrentLocale());
return onLocaleChange(() => setLocale(getCurrentLocale()));
}, []);
const isWenyanLocale = WENYAN_LOCALES.includes(locale);
const visibleCavemanLevels = isWenyanLocale
? CAVEMAN_LEVELS
: CAVEMAN_LEVELS.filter((lvl) => !lvl.wenyan);
// Reset wenyan level to "ultra" when leaving a Chinese locale
useEffect(() => {
const current = CAVEMAN_LEVELS.find((lvl) => lvl.id === cavemanLevel);
if (current?.wenyan && !isWenyanLocale) {
setCavemanLevel("ultra");
patchSetting({ cavemanLevel: "ultra" });
}
}, [isWenyanLocale, cavemanLevel]);
const { copied, copy } = useCopyToClipboard();
// Security gate: block remote exposure while dashboard uses default password or login is off.
const isLoginUnsafe = !requireLogin || !hasPassword;
const unsafeReason = !requireLogin
? "Enable \"Require login\" and set a custom password before activating the tunnel."
: "Change the default dashboard password before activating the tunnel.";
// Auto-scroll install log
useEffect(() => {
if (tsLogRef.current) tsLogRef.current.scrollTop = tsLogRef.current.scrollHeight;
}, [tsInstallLog]);
useEffect(() => {
fetchData();
loadSettings();
}, []);
// Status poll: only while degraded (not yet reachable). Stop once healthy to avoid spam.
// Visibility re-check: refresh once when tab becomes visible.
useEffect(() => {
const anyEnabled = tunnelEnabled || tsEnabled;
if (!anyEnabled) return;
const tunnelHealthy = !tunnelEnabled || tunnelReachable;
const tsHealthy = !tsEnabled || tsReachable;
const allHealthy = tunnelHealthy && tsHealthy;
const onVisible = () => { if (!document.hidden) syncTunnelStatus(); };
document.addEventListener("visibilitychange", onVisible);
if (allHealthy) return () => document.removeEventListener("visibilitychange", onVisible);
const timer = setInterval(() => { if (!document.hidden) syncTunnelStatus(); }, STATUS_POLL_FAST_MS);
return () => {
clearInterval(timer);
document.removeEventListener("visibilitychange", onVisible);
};
}, [tunnelEnabled, tsEnabled, tunnelReachable, tsReachable]);
// Browser-side periodic ping: probes tunnel/tailscale URLs directly so UI stays
// "reachable" even when backend DNS (1.1.1.1) hiccups on *.ts.net or *.trycloudflare.com.
// Adaptive: slow when healthy, fast when degraded; pause when tab hidden.
useEffect(() => {
const probeBoth = async () => {
if (document.hidden) return;
if (tunnelEnabled && (tunnelUrl || tunnelPublicUrl)) {
const ok = await clientPingAny(tunnelPublicUrl, tunnelUrl);
tunnelClientReachableRef.current = ok;
if (ok) { tunnelMissRef.current = 0; setTunnelReachable(true); if (!tunnelEverReachableRef.current) { tunnelEverReachableRef.current = true; setTunnelEverReachable(true); } }
else { tunnelMissRef.current += 1; if (tunnelMissRef.current >= REACHABLE_MISS_THRESHOLD) setTunnelReachable(false); }
} else {
tunnelClientReachableRef.current = false;
}
if (tsEnabled && tsUrl) {
const ok = await clientPingUrl(tsUrl);
tsClientReachableRef.current = ok;
if (ok) { tsMissRef.current = 0; setTsReachable(true); if (!tsEverReachableRef.current) { tsEverReachableRef.current = true; setTsEverReachable(true); } }
else { tsMissRef.current += 1; if (tsMissRef.current >= REACHABLE_MISS_THRESHOLD) setTsReachable(false); }
} else {
tsClientReachableRef.current = false;
}
};
const anyEnabled = (tunnelEnabled && (tunnelUrl || tunnelPublicUrl)) || (tsEnabled && tsUrl);
if (!anyEnabled) return;
probeBoth();
const tunnelHealthy = !tunnelEnabled || tunnelReachable;
const tsHealthy = !tsEnabled || tsReachable;
if (tunnelHealthy && tsHealthy) return;
const id = setInterval(probeBoth, CLIENT_PING_FAST_MS);
return () => clearInterval(id);
}, [tunnelEnabled, tunnelUrl, tunnelPublicUrl, tsEnabled, tsUrl, tunnelReachable, tsReachable]);
// Client-side reachable only (server no longer probes; watchdog handles backend health).
// Miss-debounce: only flip to false after N consecutive misses.
const updateReachable = useCallback((_unused, clientRef, missRef, setter, everRef, everSetter) => {
const reachable = clientRef.current;
if (reachable) {
missRef.current = 0;
setter(true);
if (!everRef.current) {
everRef.current = true;
everSetter(true);
}
} else {
missRef.current += 1;
if (missRef.current >= REACHABLE_MISS_THRESHOLD) setter(false);
}
}, []);
// Trust user intent (settingsEnabled): UI stays "enabled" while watchdog restarts process
const syncTunnelStatus = async () => {
try {
const statusRes = await fetch("/api/tunnel/status", { cache: "no-store" });
if (!statusRes.ok) return;
const data = await statusRes.json();
const tEnabled = data.tunnel?.settingsEnabled ?? data.tunnel?.enabled ?? false;
const tUrl = data.tunnel?.tunnelUrl || "";
setTunnelUrl(tUrl);
setTunnelPublicUrl(data.tunnel?.publicUrl || "");
setTunnelEnabled(tEnabled);
updateReachable(null, tunnelClientReachableRef, tunnelMissRef, setTunnelReachable, tunnelEverReachableRef, setTunnelEverReachable);
const tsEn = data.tailscale?.settingsEnabled ?? data.tailscale?.enabled ?? false;
const tsUrlVal = data.tailscale?.tunnelUrl || "";
setTsUrl(tsUrlVal);
setTsEnabled(tsEn);
updateReachable(null, tsClientReachableRef, tsMissRef, setTsReachable, tsEverReachableRef, setTsEverReachable);
} catch { /* ignore poll errors */ }
};
const loadSettings = async () => {
setTunnelChecking(true);
try {
const [settingsRes, statusRes] = await Promise.all([
fetch("/api/settings"),
fetch("/api/tunnel/status", { cache: "no-store" })
]);
if (settingsRes.ok) {
const data = await settingsRes.json();
setRequireApiKey(data.requireApiKey || false);
setRequireLogin(data.requireLogin !== false);
setHasPassword(data.hasPassword || false);
setTunnelDashboardAccess(data.tunnelDashboardAccess || false);
setRtkEnabledState(data.rtkEnabled !== false);
setCavemanEnabled(!!data.cavemanEnabled);
setCavemanLevel(data.cavemanLevel || "full");
}
if (statusRes.ok) {
const data = await statusRes.json();
const tEnabled = data.tunnel?.settingsEnabled ?? data.tunnel?.enabled ?? false;
const tUrl = data.tunnel?.tunnelUrl || "";
setTunnelUrl(tUrl);
setTunnelPublicUrl(data.tunnel?.publicUrl || "");
setTunnelEnabled(tEnabled);
updateReachable(null, tunnelClientReachableRef, tunnelMissRef, setTunnelReachable, tunnelEverReachableRef, setTunnelEverReachable);
const tsEn = data.tailscale?.settingsEnabled ?? data.tailscale?.enabled ?? false;
const tsUrlVal = data.tailscale?.tunnelUrl || "";
setTsUrl(tsUrlVal);
setTsEnabled(tsEn);
updateReachable(null, tsClientReachableRef, tsMissRef, setTsReachable, tsEverReachableRef, setTsEverReachable);
}
} catch (error) {
console.log("Error loading settings:", error);
} finally {
setTunnelChecking(false);
}
};
const handleTunnelDashboardAccess = async (value) => {
try {
const res = await fetch("/api/settings", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ tunnelDashboardAccess: value }),
});
if (res.ok) setTunnelDashboardAccess(value);
} catch (error) {
console.log("Error updating tunnelDashboardAccess:", error);
}
};
const handleRequireApiKey = async (value) => {
try {
const res = await fetch("/api/settings", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ requireApiKey: value }),
});
if (res.ok) setRequireApiKey(value);
} catch (error) {
console.log("Error updating requireApiKey:", error);
}
};
const handleRtkEnabled = async (value) => {
try {
const res = await fetch("/api/settings", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ rtkEnabled: value }),
});
if (res.ok) setRtkEnabledState(value);
} catch (error) {
console.log("Error updating rtkEnabled:", error);
}
};
const patchSetting = async (patch) => {
try {
await fetch("/api/settings", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(patch),
});
} catch (error) {
console.log("Error updating setting:", error);
}
};
const handleCavemanEnabled = (value) => {
setCavemanEnabled(value);
patchSetting({ cavemanEnabled: value });
};
const handleCavemanLevel = (level) => {
setCavemanLevel(level);
patchSetting({ cavemanLevel: level });
};
const fetchData = async () => {
try {
const keysRes = await fetch("/api/keys");
const keysData = await keysRes.json();
if (keysRes.ok) {
setKeys(keysData.keys || []);
}
} catch (error) {
console.log("Error fetching data:", error);
} finally {
setLoading(false);
}
};
// u2500u2500u2500 Cloudflare Tunnel handlers
// Ping tunnel health until reachable. Race multiple URLs (shortlink + direct) — 1 OK is enough.
const pingTunnelHealth = async (...urls) => {
setTunnelLoading(true);
setTunnelProgress("Waiting for tunnel ready...");
const targets = urls.filter(Boolean).map((u) => `${u}/api/health`);
const start = Date.now();
while (Date.now() - start < TUNNEL_PING_MAX_MS) {
await new Promise((r) => setTimeout(r, TUNNEL_PING_INTERVAL_MS));
const ok = await Promise.any(targets.map(async (h) => {
const p = await fetch(h, { mode: "cors", cache: "no-store" });
if (p.ok) return true;
throw new Error("not ready");
})).catch(() => false);
if (ok) {
setTunnelEnabled(true);
setTunnelLoading(false);
setTunnelProgress("");
return true;
}
// Every 5 pings (~10s), check if backend process still alive
if ((Date.now() - start) % 10000 < TUNNEL_PING_INTERVAL_MS) {
try {
const statusRes = await fetch("/api/tunnel/status");
if (statusRes.ok) {
const status = await statusRes.json();
if (!status.tunnel?.enabled) {
setTunnelStatus({ type: "error", message: "Tunnel process stopped unexpectedly." });
setTunnelLoading(false);
setTunnelProgress("");
return false;
}
}
} catch { /* ignore */ }
}
}
setTunnelStatus({ type: "error", message: "Tunnel created but not reachable. Please try again." });
setTunnelLoading(false);
setTunnelProgress("");
return false;
};
const handleEnableTunnel = async () => {
setShowEnableTunnelModal(false);
setTunnelLoading(true);
setTunnelStatus(null);
setTunnelProgress("Creating tunnel...");
// Poll download progress while enable request is pending
let polling = true;
const pollProgress = async () => {
while (polling) {
try {
const r = await fetch("/api/tunnel/status");
if (r.ok) {
const s = await r.json();
if (s.download?.downloading) {
setTunnelProgress(`Downloading cloudflared... ${s.download.progress}%`);
} else if (polling) {
setTunnelProgress("Creating tunnel...");
}
}
} catch { /* ignore */ }
await new Promise((r) => setTimeout(r, 1000));
}
};
pollProgress();
try {
const res = await fetch("/api/tunnel/enable", { method: "POST" });
polling = false;
const data = await res.json();
if (!res.ok) {
setTunnelStatus({ type: "error", message: data.error || "Failed to enable tunnel" });
return;
}
const url = data.tunnelUrl;
if (!url) {
setTunnelStatus({ type: "error", message: "No tunnel URL returned" });
return;
}
setTunnelUrl(url);
setTunnelPublicUrl(data.publicUrl || "");
await pingTunnelHealth(data.publicUrl, url);
} catch (error) {
setTunnelStatus({ type: "error", message: error.message });
} finally {
polling = false;
setTunnelLoading(false);
setTunnelProgress("");
}
};
const handleDisableTunnel = async () => {
setTunnelLoading(true);
setTunnelStatus(null);
try {
const res = await fetch("/api/tunnel/disable", { method: "POST" });
const data = await res.json();
if (res.ok) {
setTunnelEnabled(false);
setTunnelUrl("");
setShowDisableTunnelModal(false);
setTunnelStatus({ type: "success", message: "Tunnel disabled" });
} else {
setTunnelStatus({ type: "error", message: data.error || "Failed to disable tunnel" });
}
} catch (error) {
setTunnelStatus({ type: "error", message: error.message });
} finally {
setTunnelLoading(false);
}
};
// u2500u2500u2500 Tailscale handlers
const checkTailscaleInstalled = async () => {
setTsInstalled(null);
try {
const res = await fetch("/api/tunnel/tailscale-check");
if (res.ok) {
const data = await res.json();
setTsInstalled(data.installed);
return data;
}
} catch { /* ignore */ }
setTsInstalled(false);
return { installed: false };
};
const handleInstallTailscale = async () => {
setTsInstalling(true);
setTsStatus(null);
setTsInstallLog([]);
try {
const res = await fetch("/api/tunnel/tailscale-install", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sudoPassword: tsSudoPassword }),
});
setTsSudoPassword("");
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const parts = buffer.split("\n\n");
buffer = parts.pop() || "";
for (const part of parts) {
const lines = part.split("\n");
let event = "progress";
let data = null;
for (const line of lines) {
if (line.startsWith("event: ")) event = line.slice(7).trim();
if (line.startsWith("data: ")) {
try { data = JSON.parse(line.slice(6)); } catch { /* skip */ }
}
}
if (!data) continue;
if (event === "progress") {
setTsInstallLog((prev) => [...prev.slice(-50), data.message]);
} else if (event === "done") {
setTsInstalled(true);
setTsInstalling(false);
setShowTsModal(false);
handleConnectTailscale();
return;
} else if (event === "error") {
setTsStatus({ type: "error", message: data.error || "Install failed" });
}
}
}
} catch (e) {
setTsStatus({ type: "error", message: e.message });
} finally {
setTsInstalling(false);
}
};
// Ping Tailscale health until reachable
const pingTsHealth = async (url) => {
setTsProgress("Waiting for Tailscale ready...");
const healthUrl = `${url}/api/health`;
const start = Date.now();
while (Date.now() - start < TUNNEL_PING_MAX_MS) {
await new Promise((r) => setTimeout(r, TUNNEL_PING_INTERVAL_MS));
try {
const ping = await fetch(healthUrl, { mode: "no-cors", cache: "no-store" });
if (ping.ok || ping.type === "opaque") return true;
} catch { /* not ready yet */ }
}
return false;
};
// Show inline login button instead of auto-opening popup (browsers block popups
// opened after async work because the user gesture is lost).
const requestUserAuth = (url, label) => {
setTsAuthUrl(url);
setTsAuthLabel(label);
};
const clearUserAuth = () => {
setTsAuthUrl("");
setTsAuthLabel("");
};
const handleConnectTailscale = async () => {
setShowTsModal(false);
setTsConnecting(true);
setTsLoading(true);
setTsStatus(null);
setTsProgress("Connecting...");
clearUserAuth();
try {
const res = await fetch("/api/tunnel/tailscale-enable", { method: "POST" });
const data = await res.json();
if (res.ok && data.success) {
setTsUrl(data.tunnelUrl || "");
const reachable = await pingTsHealth(data.tunnelUrl);
setTsEnabled(true);
setTsStatus(reachable ? null : { type: "warning", message: "Connected but not reachable yet." });
return;
}
if (data.needsLogin && data.authUrl) {
requestUserAuth(data.authUrl, "Open Login Page");
setTsProgress("Login required — click \"Open Login Page\" to continue");
for (let i = 0; i < 40; i++) {
await new Promise((r) => setTimeout(r, 3000));
try {
const r2 = await fetch("/api/tunnel/tailscale-check");
if (r2.ok) {
const check = await r2.json();
if (check.loggedIn) {
clearUserAuth();
setTsProgress("Starting funnel...");
const res2 = await fetch("/api/tunnel/tailscale-enable", { method: "POST" });
const data2 = await res2.json();
if (res2.ok && data2.success) {
setTsUrl(data2.tunnelUrl || "");
const ok2 = await pingTsHealth(data2.tunnelUrl);
setTsEnabled(true);
setTsStatus(ok2 ? null : { type: "warning", message: "Connected but not reachable yet." });
} else if (data2.funnelNotEnabled && data2.enableUrl) {
await pollFunnelEnable(data2.enableUrl);
} else {
setTsStatus({ type: "error", message: data2.error || "Failed to start funnel" });
}
return;
}
}
} catch { /* retry */ }
}
clearUserAuth();
setTsStatus({ type: "error", message: "Login timed out. Please try again." });
return;
}
if (data.funnelNotEnabled && data.enableUrl) {
await pollFunnelEnable(data.enableUrl);
return;
}
setTsStatus({ type: "error", message: data.error || "Failed to connect" });
} catch (error) {
setTsStatus({ type: "error", message: error.message });
} finally {
setTsLoading(false);
setTsConnecting(false);
setTsProgress("");
clearUserAuth();
}
};
const pollFunnelEnable = async (enableUrl) => {
requestUserAuth(enableUrl, "Open Funnel Settings");
setTsProgress("Click \"Open Funnel Settings\" to enable Funnel...");
for (let i = 0; i < 40; i++) {
await new Promise((r) => setTimeout(r, 3000));
try {
const res = await fetch("/api/tunnel/tailscale-enable", { method: "POST" });
const data = await res.json();
if (res.ok && data.success) {
clearUserAuth();
setTsUrl(data.tunnelUrl || "");
const ok3 = await pingTsHealth(data.tunnelUrl);
setTsEnabled(true);
setTsStatus(ok3 ? null : { type: "warning", message: "Connected but not reachable yet." });
return;
}
if (data.funnelNotEnabled) continue;
if (data.error) {
clearUserAuth();
setTsStatus({ type: "error", message: data.error });
return;
}
} catch { /* retry */ }
}
clearUserAuth();
setTsStatus({ type: "error", message: "Timed out waiting for Funnel to be enabled." });
};
const handleDisableTailscale = async () => {
setTsLoading(true);
setTsStatus(null);
try {
const res = await fetch("/api/tunnel/tailscale-disable", { method: "POST" });
const data = await res.json();
if (res.ok) {
setTsEnabled(false);
setTsUrl("");
setShowDisableTsModal(false);
setTsStatus({ type: "success", message: "Tailscale disabled" });
} else {
setTsStatus({ type: "error", message: data.error || "Failed to disable Tailscale" });
}
} catch (e) {
setTsStatus({ type: "error", message: e.message });
} finally {
setTsLoading(false);
}
};
const handleOpenTsModal = async () => {
setTsStatus(null);
setTsInstallLog([]);
const data = await checkTailscaleInstalled();
if (data?.installed && data?.hasCachedPassword) {
handleConnectTailscale();
} else {
setShowTsModal(true);
}
};
const handleCreateKey = async () => {
if (!newKeyName.trim()) return;
try {
const res = await fetch("/api/keys", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: newKeyName }),
});
const data = await res.json();
if (res.ok) {
setCreatedKey(data.key);
await fetchData();
setNewKeyName("");
setShowAddModal(false);
}
} catch (error) {
console.log("Error creating key:", error);
}
};
const handleDeleteKey = async (id) => {
setConfirmState({
title: "Delete API Key",
message: "Delete this API key?",
onConfirm: async () => {
setConfirmState(null);
try {
const res = await fetch(`/api/keys/${id}`, { method: "DELETE" });
if (res.ok) {
setKeys(keys.filter((k) => k.id !== id));
setVisibleKeys(prev => {
const next = new Set(prev);
next.delete(id);
return next;
});
}
} catch (error) {
console.log("Error deleting key:", error);
}
}
});
};
const handleToggleKey = async (id, isActive) => {
try {
const res = await fetch(`/api/keys/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ isActive }),
});
if (res.ok) {
setKeys(prev => prev.map(k => k.id === id ? { ...k, isActive } : k));
}
} catch (error) {
console.log("Error toggling key:", error);
}
};
const maskKey = (fullKey) => {
if (!fullKey) return "";
return fullKey.length > 8 ? fullKey.slice(0, 8) + "..." : fullKey;
};
const toggleKeyVisibility = (keyId) => {
setVisibleKeys(prev => {
const next = new Set(prev);
if (next.has(keyId)) next.delete(keyId);
else next.add(keyId);
return next;
});
};
const [baseUrl, setBaseUrl] = useState("/v1");
// Hydration fix: Only access window on client side
useEffect(() => {
if (typeof window !== "undefined") {
setBaseUrl(`${window.location.origin}/v1`);
}
}, []);
if (loading) {
return (
<div className="flex flex-col gap-8">
<CardSkeleton />
<CardSkeleton />
</div>
);
}
const currentEndpoint = baseUrl;
return (
<div className="flex flex-col gap-8">
{/* Endpoint Card */}
<Card>
<h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
<span className="material-symbols-outlined text-primary">api</span>
API Endpoint
</h2>
{/* Endpoint rows */}
<div className="flex flex-col gap-2">
{/* Local */}
<EndpointRow
label="Local"
url={currentEndpoint}
copyId="local_url"
copied={copied}
onCopy={copy}
/>
{/* Cloudflare Tunnel */}
<div className="flex items-center gap-2">
<span className={`text-xs font-mono px-1.5 py-0.5 rounded shrink-0 min-w-[88px] text-center ${
tunnelEnabled ? "bg-primary/10 text-primary" : "bg-surface-2 text-text-muted"
}`}>Tunnel</span>
{tunnelEnabled && !tunnelLoading && tunnelReachable ? (
<>
<Input value={`${tunnelPublicUrl || tunnelUrl}/v1`} readOnly className="flex-1 font-mono text-sm" />
<button
onClick={() => copy(`${tunnelPublicUrl || tunnelUrl}/v1`, "tunnel_url")}
className="p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary transition-colors shrink-0"
>
<span className="material-symbols-outlined text-[18px]">{copied === "tunnel_url" ? "check" : "content_copy"}</span>
</button>
<button
onClick={() => setShowDisableTunnelModal(true)}
className="p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0"
title="Disable Tunnel"
>
<span className="material-symbols-outlined text-[18px]">power_settings_new</span>
</button>
</>
) : tunnelEnabled && !tunnelLoading && !tunnelReachable ? (
<>
<div className="flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-amber-300 dark:border-amber-800 bg-amber-500/5 text-sm text-amber-600 dark:text-amber-400">
<span className="material-symbols-outlined animate-spin text-sm">progress_activity</span>
{tunnelEverReachable ? "Tunnel reconnecting..." : "Tunnel checking..."}
</div>
<button
onClick={() => setShowDisableTunnelModal(true)}
className="p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0"
title="Disable Tunnel"
>
<span className="material-symbols-outlined text-[18px]">power_settings_new</span>
</button>
</>
) : tunnelLoading ? (
<>
<div className="flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-border bg-input text-sm text-text-muted">
<span className="material-symbols-outlined animate-spin text-sm">progress_activity</span>
{tunnelProgress || "Creating tunnel..."}
</div>
<button
onClick={() => { setTunnelLoading(false); setTunnelProgress(""); }}
className="p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0"
title="Stop"
>
<span className="material-symbols-outlined text-[18px]">power_settings_new</span>
</button>
</>
) : tunnelStatus?.type === "error" ? (
<>
<div className="flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-red-300 dark:border-red-800 bg-red-500/5 text-sm text-red-600 dark:text-red-400">
<span className="material-symbols-outlined text-sm">error</span>
{tunnelStatus.message}
</div>
<Button size="sm" icon="cloud_upload" onClick={() => setShowEnableTunnelModal(true)}>Enable</Button>
</>
) : tunnelChecking ? (
<>
<div className="flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-border bg-input text-sm text-text-muted">
<span className="material-symbols-outlined animate-spin text-sm">progress_activity</span>
Checking...
</div>
<button
onClick={() => setTunnelChecking(false)}
className="p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0"
title="Stop"
>
<span className="material-symbols-outlined text-[18px]">power_settings_new</span>
</button>
</>
) : (
<Button
size="sm"
icon="cloud_upload"
onClick={() => {
if (isLoginUnsafe) {
setTunnelStatus({ type: "error", message: `Security required: ${unsafeReason}` });
return;
}
if (!requireApiKey) {
setTunnelStatus({ type: "error", message: "Security required: Enable \"Require API key\" before activating the tunnel." });
return;
}
setShowEnableTunnelModal(true);
}}
>
Enable
</Button>
)}
</div>
{/* Tailscale */}
<div className="flex items-center gap-2">
<span className={`text-xs font-mono px-1.5 py-0.5 rounded shrink-0 min-w-[88px] text-center ${
tsEnabled ? "bg-primary/10 text-primary" : "bg-surface-2 text-text-muted"
}`}>Tailscale</span>
{tsEnabled && !tsLoading && tsReachable ? (
<>
<Input value={`${tsUrl}/v1`} readOnly className="flex-1 font-mono text-sm" />
<button
onClick={() => copy(`${tsUrl}/v1`, "ts_url")}
className="p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary transition-colors shrink-0"
>
<span className="material-symbols-outlined text-[18px]">{copied === "ts_url" ? "check" : "content_copy"}</span>
</button>
<button
onClick={() => setShowDisableTsModal(true)}
className="p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0"
title="Disable Tailscale"
>
<span className="material-symbols-outlined text-[18px]">power_settings_new</span>
</button>
</>
) : tsEnabled && !tsLoading && !tsReachable ? (
<>
<div className="flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-amber-300 dark:border-amber-800 bg-amber-500/5 text-sm text-amber-600 dark:text-amber-400">
<span className="material-symbols-outlined animate-spin text-sm">progress_activity</span>
{tsEverReachable ? "Tailscale reconnecting..." : "Tailscale checking..."}
</div>
<button
onClick={() => setShowDisableTsModal(true)}
className="p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0"
title="Disable Tailscale"
>
<span className="material-symbols-outlined text-[18px]">power_settings_new</span>
</button>
</>
) : (tsLoading || tsConnecting) ? (
<>
<div className="flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-border bg-input text-sm text-text-muted">
<span className="material-symbols-outlined animate-spin text-sm">progress_activity</span>
{tsProgress || "Connecting..."}
</div>
{tsAuthUrl && (
<Button
size="sm"
icon="open_in_new"
onClick={() => window.open(tsAuthUrl, "tailscale_auth", "width=600,height=700,noopener,noreferrer")}
>
{tsAuthLabel || "Open"}
</Button>
)}
<button
onClick={() => { setTsLoading(false); setTsConnecting(false); setTsProgress(""); clearUserAuth(); }}
className="p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0"
title="Stop"
>
<span className="material-symbols-outlined text-[18px]">power_settings_new</span>
</button>
</>
) : tsStatus?.type === "error" ? (
<>
<div className="flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-red-300 dark:border-red-800 bg-red-500/5 text-sm text-red-600 dark:text-red-400">
<span className="material-symbols-outlined text-sm">error</span>
{tsStatus.message}
</div>
<Button size="sm" icon="vpn_lock" onClick={handleOpenTsModal}>Enable</Button>
</>
) : (
<Button
size="sm"
icon="vpn_lock"
onClick={() => {
if (isLoginUnsafe) {
setTsStatus({ type: "error", message: `Security required: ${unsafeReason}` });
return;
}
handleOpenTsModal();
}}
className="bg-linear-to-r from-indigo-500 to-purple-500 hover:from-indigo-600 hover:to-purple-600 text-white!"
>
Enable
</Button>
)}
</div>
</div>
{/* Pre-enable security gate banner */}
{isLoginUnsafe && !tunnelEnabled && !tsEnabled && (
<div className="mt-4">
<SecurityWarning
message={unsafeReason}
action={{ label: "Open settings", href: "/dashboard/profile" }}
/>
</div>
)}
{/* Security warnings when tunnel or tailscale is active */}
{(tunnelEnabled || tsEnabled) && (
<div className="mt-4 flex flex-col gap-2">
{!requireApiKey && (
<SecurityWarning
message="Require API key is disabled — your endpoint is publicly accessible without authentication."
action={{ label: "Enable", href: "#require-api-key" }}
/>
)}
{(!requireLogin || !hasPassword) && (
<SecurityWarning
message={
!requireLogin
? "Require login is disabled — anyone can access your dashboard via tunnel."
: "Dashboard uses the default password — change it in Profile settings."
}
action={{
label: !requireLogin ? "Enable" : "Change password",
href: "/dashboard/profile",
}}
/>
)}
</div>
)}
{/* Tunnel dashboard access option */}
{(tunnelEnabled || tsEnabled) && (
<div className="mt-4 pt-4 border-t border-border flex items-center gap-3">
<Toggle
checked={tunnelDashboardAccess}
onChange={() => handleTunnelDashboardAccess(!tunnelDashboardAccess)}
/>
<div className="flex items-center gap-1.5">
<p className="font-medium text-sm">Allow dashboard access via tunnel</p>
<Tooltip text="When enabled, the dashboard can be accessed through your tunnel or Tailscale URL (login still required). When disabled, dashboard access via tunnel/Tailscale is completely blocked." />
</div>
</div>
)}
</Card>
{/* Token Saver (RTK + Caveman) */}
<Card id="rtk">
<div className="flex items-center justify-between mb-2">
<h2 className="text-lg font-semibold flex items-center gap-2">
<span className="material-symbols-outlined text-primary">bolt</span>
Token Saver
</h2>
</div>
<div className="flex items-center justify-between pt-2 pb-4 border-b border-border gap-4">
<div className="min-w-0 flex-1">
<p className="font-medium">
Compress tool output{" "}
<a
href="https://github.com/rtk-ai/rtk"
target="_blank"
rel="noreferrer"
className="text-xs font-normal text-primary underline hover:opacity-80"
>
(RTK)
</a>
</p>
<p className="text-sm text-text-muted">
git/grep/ls/tree/logs → 60-90% fewer input tokens
</p>
</div>
<Toggle
checked={rtkEnabled}
onChange={() => handleRtkEnabled(!rtkEnabled)}
/>
</div>
<div className="flex items-center justify-between pt-4 gap-4 flex-wrap">
<div className="min-w-0 flex-1">
<p className="font-medium">
Compress LLM output{" "}
<a
href="https://github.com/JuliusBrussee/caveman"
target="_blank"
rel="noreferrer"
className="text-xs font-normal text-primary underline hover:opacity-80"
>
(Caveman)
</a>
</p>
<p className="text-sm text-text-muted">
Terse-style system prompt → ~65% fewer output tokens (up to 87%)
</p>
</div>
<div className="flex items-center gap-3 shrink-0">
{cavemanEnabled && (
<div className="flex flex-col items-end gap-1">
<div className="flex items-center gap-1.5">
{visibleCavemanLevels.map((lvl) => (
<button
key={lvl.id}
onClick={() => handleCavemanLevel(lvl.id)}
className={`px-3 py-1.5 rounded text-xs font-medium border transition-colors ${
cavemanLevel === lvl.id
? "bg-primary text-white border-primary"
: "bg-transparent border-border text-text-muted hover:bg-surface-2"
}`}
title={lvl.desc}
>
{lvl.label}
</button>
))}
</div>
<p className="text-xs text-primary">
{CAVEMAN_LEVELS.find((lvl) => lvl.id === cavemanLevel)?.desc}
</p>
</div>
)}
<Toggle
checked={cavemanEnabled}
onChange={() => handleCavemanEnabled(!cavemanEnabled)}
/>
</div>
</div>
</Card>
{/* API Keys */}
<Card id="require-api-key">
<div className="flex items-center justify-between mb-4">
<h2 className="text-lg font-semibold flex items-center gap-2">
<span className="material-symbols-outlined text-primary">vpn_key</span>
API Keys
</h2>
<Button icon="add" onClick={() => setShowAddModal(true)}>
Create Key
</Button>
</div>
<div className="flex items-center justify-between pb-4 mb-4 border-b border-border">
<div>
<p className="font-medium">Require API key</p>
<p className="text-sm text-text-muted">
Requests without a valid key will be rejected
</p>
</div>
<Toggle
checked={requireApiKey}
onChange={() => handleRequireApiKey(!requireApiKey)}
/>
</div>
{isRemoteHost && !requireApiKey && (
<div className="mb-4 -mt-2">
<SecurityWarning message="Endpoint is exposed without an API key." />
</div>
)}
{keys.length === 0 ? (
<div className="text-center py-12">
<div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 text-primary mb-4">
<span className="material-symbols-outlined text-[32px]">vpn_key</span>
</div>
<p className="text-text-main font-medium mb-1">No API keys yet</p>
<p className="text-sm text-text-muted mb-4">Create your first API key to get started</p>
<Button icon="add" onClick={() => setShowAddModal(true)}>
Create Key
</Button>
</div>
) : (
<div className="flex flex-col">
{keys.map((key) => (
<div
key={key.id}
className={`group flex items-center justify-between py-3 border-b border-black/[0.03] dark:border-white/[0.03] last:border-b-0 ${key.isActive === false ? "opacity-60" : ""}`}
>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium">{key.name}</p>
<div className="flex items-center gap-2 mt-1">
<code className="text-xs text-text-muted font-mono">
{visibleKeys.has(key.id) ? key.key : maskKey(key.key)}
</code>
<button
onClick={() => toggleKeyVisibility(key.id)}
className="p-1 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-all"
title={visibleKeys.has(key.id) ? "Hide key" : "Show key"}
>
<span className="material-symbols-outlined text-[14px]">
{visibleKeys.has(key.id) ? "visibility_off" : "visibility"}
</span>
</button>
<button
onClick={() => copy(key.key, key.id)}
className="p-1 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-all"
>
<span className="material-symbols-outlined text-[14px]">
{copied === key.id ? "check" : "content_copy"}
</span>
</button>
</div>
<p className="text-xs text-text-muted mt-1">
Created {new Date(key.createdAt).toLocaleDateString()}
</p>
{key.isActive === false && (
<p className="text-xs text-orange-500 mt-1">Paused</p>
)}
</div>
<div className="flex items-center gap-2">
<Toggle
size="sm"
checked={key.isActive ?? true}
onChange={(checked) => {
if (key.isActive && !checked) {
setConfirmState({
title: "Pause API Key",
message: `Pause API key "${key.name}"?\n\nThis key will stop working immediately but can be resumed later.`,
onConfirm: async () => {
setConfirmState(null);
handleToggleKey(key.id, checked);
}
});
} else {
handleToggleKey(key.id, checked);
}
}}
title={key.isActive ? "Pause key" : "Resume key"}
/>
<button
onClick={() => handleDeleteKey(key.id)}
className="p-2 hover:bg-red-500/10 rounded text-red-500 opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-all"
>
<span className="material-symbols-outlined text-[18px]">delete</span>
</button>
</div>
</div>
))}
</div>
)}
</Card>
{/* Add Key Modal */}
<Modal
isOpen={showAddModal}
title="Create API Key"
onClose={() => {
setShowAddModal(false);
setNewKeyName("");
}}
>
<div className="flex flex-col gap-4">
<Input
label="Key Name"
value={newKeyName}
onChange={(e) => setNewKeyName(e.target.value)}
placeholder="Production Key"
/>
<div className="flex gap-2">
<Button onClick={handleCreateKey} fullWidth disabled={!newKeyName.trim()}>
Create
</Button>
<Button
onClick={() => {
setShowAddModal(false);
setNewKeyName("");
}}
variant="ghost"
fullWidth
>
Cancel
</Button>
</div>
</div>
</Modal>
{/* Created Key Modal */}
<Modal
isOpen={!!createdKey}
title="API Key Created"
onClose={() => setCreatedKey(null)}
>
<div className="flex flex-col gap-4">
<div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
<p className="text-sm text-yellow-800 dark:text-yellow-200 mb-2 font-medium">
Save this key now!
</p>
<p className="text-sm text-yellow-700 dark:text-yellow-300">
This is the only time you will see this key. Store it securely.
</p>
</div>
<div className="flex gap-2">
<Input
value={createdKey || ""}
readOnly
className="flex-1 font-mono text-sm"
/>
<Button
variant="secondary"
icon={copied === "created_key" ? "check" : "content_copy"}
onClick={() => copy(createdKey, "created_key")}
>
{copied === "created_key" ? "Copied!" : "Copy"}
</Button>
</div>
<Button onClick={() => setCreatedKey(null)} fullWidth>
Done
</Button>
</div>
</Modal>
{/* Enable Tunnel Modal */}
<Modal
isOpen={showEnableTunnelModal}
title="Enable Tunnel"
onClose={() => setShowEnableTunnelModal(false)}
>
<div className="flex flex-col gap-4">
<div className="bg-surface-2 border border-border-subtle rounded-lg p-4">
<div className="flex items-start gap-3">
<span className="material-symbols-outlined text-primary">cloud_upload</span>
<div>
<p className="text-sm text-text-main font-medium mb-1">
Cloudflare Tunnel
</p>
<p className="text-sm text-text-muted">
Expose your local 9Router to the internet. No port forwarding, no static IP needed. Share endpoint URL with your team or use it in Cursor, Cline, and other AI tools from anywhere.
</p>
</div>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
{TUNNEL_BENEFITS.map((benefit) => (
<div key={benefit.title} className="flex flex-col items-center text-center p-3 rounded-lg bg-sidebar/50">
<span className="material-symbols-outlined text-xl text-primary mb-1">{benefit.icon}</span>
<p className="text-xs font-semibold">{benefit.title}</p>
<p className="text-xs text-text-muted">{benefit.desc}</p>
</div>
))}
</div>
<p className="text-xs text-text-muted">
Requires outbound port 7844 (TCP/UDP). Connection may take 10-30s.
</p>
<div className="flex gap-2">
<Button onClick={handleEnableTunnel} fullWidth>
Start Tunnel
</Button>
<Button onClick={() => setShowEnableTunnelModal(false)} variant="ghost" fullWidth>Cancel</Button>
</div>
</div>
</Modal>
{/* Disable Cloudflare Tunnel Modal */}
<Modal
isOpen={showDisableTunnelModal}
title="Disable Tunnel"
onClose={() => !tunnelLoading && setShowDisableTunnelModal(false)}
>
<div className="flex flex-col gap-4">
<p className="text-sm text-text-muted">The Cloudflare tunnel will be disconnected. Remote access via tunnel URL will stop working.</p>
<div className="flex gap-2">
<Button onClick={handleDisableTunnel} fullWidth disabled={tunnelLoading} variant="danger">
{tunnelLoading ? "Disabling..." : "Disable"}
</Button>
<Button onClick={() => setShowDisableTunnelModal(false)} variant="ghost" fullWidth disabled={tunnelLoading}>Cancel</Button>
</div>
</div>
</Modal>
{/* Tailscale Modal */}
<Modal
isOpen={showTsModal}
title="Tailscale Funnel"
onClose={() => { if (!tsInstalling) { setShowTsModal(false); setTsSudoPassword(""); setTsStatus(null); } }}
>
<div className="flex flex-col gap-4">
{/* Checking state */}
{tsInstalled === null && (
<p className="text-sm text-text-muted flex items-center gap-2">
<span className="material-symbols-outlined animate-spin text-sm">progress_activity</span>
Checking...
</p>
)}
{/* Not installed */}
{tsInstalled === false && !tsInstalling && (
<div className="flex flex-col gap-3">
<p className="text-sm text-text-muted">Tailscale is not installed. Install it to enable Funnel.</p>
<div className="flex gap-2">
<Button onClick={handleInstallTailscale} fullWidth>
Install Tailscale
</Button>
<Button onClick={() => setShowTsModal(false)} variant="ghost" fullWidth>Cancel</Button>
</div>
</div>
)}
{/* Installing with progress log */}
{tsInstalling && (
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2 text-sm text-text-muted">
<span className="material-symbols-outlined animate-spin text-sm">progress_activity</span>
Installing Tailscale...
</div>
{tsInstallLog.length > 0 && (
<div ref={tsLogRef} className="bg-black/5 dark:bg-white/5 rounded p-2 max-h-40 overflow-y-auto font-mono text-xs text-text-muted">
{tsInstallLog.map((line, i) => (
<div key={i}>{line}</div>
))}
</div>
)}
</div>
)}
{/* Installed: show Connect button */}
{tsInstalled === true && !tsInstalling && (
<div className="flex flex-col gap-3">
<div className="flex items-center gap-2 text-sm text-green-600 dark:text-green-400">
<span className="material-symbols-outlined text-[16px]">check_circle</span>
Tailscale installed
</div>
<div className="flex gap-2">
<Button
onClick={() => handleConnectTailscale()}
fullWidth
>
Connect
</Button>
<Button onClick={() => setShowTsModal(false)} variant="ghost" fullWidth>Cancel</Button>
</div>
</div>
)}
{tsStatus && <StatusAlert status={tsStatus} />}
</div>
</Modal>
{/* Disable Tailscale Modal */}
<Modal
isOpen={showDisableTsModal}
title="Disable Tailscale"
onClose={() => !tsLoading && setShowDisableTsModal(false)}
>
<div className="flex flex-col gap-4">
<p className="text-sm text-text-muted">Tailscale Funnel will be stopped. Remote access via Tailscale URL will stop working.</p>
<div className="flex gap-2">
<Button onClick={handleDisableTailscale} fullWidth disabled={tsLoading} variant="danger">
{tsLoading ? "Disabling..." : "Disable"}
</Button>
<Button onClick={() => setShowDisableTsModal(false)} variant="ghost" fullWidth disabled={tsLoading}>Cancel</Button>
</div>
</div>
</Modal>
{/* Confirm Modal */}
<ConfirmModal
isOpen={!!confirmState}
onClose={() => setConfirmState(null)}
onConfirm={confirmState?.onConfirm}
title={confirmState?.title || "Confirm"}
message={confirmState?.message}
variant="danger"
/>
</div>
);
}
/** Reusable endpoint row component */
function EndpointRow({ label, url, copyId, copied, onCopy, badge, actions }) {
return (
<div className="flex items-center gap-2">
<span className={`text-xs font-mono px-1.5 py-0.5 rounded shrink-0 min-w-[88px] text-center ${
(badge === "CF" || badge === "TS") ? "bg-primary/10 text-primary" : "bg-surface-2 text-text-muted"
}`}>{label}</span>
<Input value={url} readOnly className="flex-1 font-mono text-sm" />
<button
onClick={() => onCopy(url, copyId)}
className="p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary transition-colors shrink-0"
>
<span className="material-symbols-outlined text-[18px]">{copied === copyId ? "check" : "content_copy"}</span>
</button>
{actions}
</div>
);
}
/** Reusable status alert */
function StatusAlert({ status, className = "" }) {
// Render URLs in message as clickable links
const renderMessage = (msg) => {
const parts = msg.split(/(https?:\/\/[^\s]+)/g);
return parts.map((part, i) =>
/^https?:\/\//.test(part)
? <a key={i} href={part} target="_blank" rel="noreferrer" className="underline font-medium">{part}</a>
: part
);
};
return (
<div className={`p-2 rounded text-sm ${className} ${status.type === "success" ? "bg-green-500/10 text-green-600 dark:text-green-400" :
status.type === "warning" ? "bg-yellow-500/10 text-yellow-600 dark:text-yellow-400" :
status.type === "info" ? "bg-blue-500/10 text-blue-600 dark:text-blue-400" :
"bg-red-500/10 text-red-600 dark:text-red-400"
}`}>
{renderMessage(status.message)}
</div>
);
}
/** Inline tooltip, Claude Code CLI style */
function Tooltip({ text }) {
return (
<span className="relative group inline-flex items-center">
<span className="material-symbols-outlined text-[14px] text-text-muted cursor-help">help</span>
<span className="pointer-events-none absolute left-5 top-1/2 -translate-y-1/2 z-50 w-64 rounded bg-gray-900 dark:bg-gray-800 text-white text-xs px-2.5 py-1.5 opacity-0 group-hover:opacity-100 transition-opacity shadow-lg">
{text}
</span>
</span>
);
}
/** Security warning banner with optional action link */
function SecurityWarning({ message, action }) {
return (
<div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/20 text-amber-700 dark:text-amber-400">
<span className="material-symbols-outlined text-[16px] shrink-0 mt-0.5">warning</span>
<p className="text-xs flex-1">{message}</p>
{action && (
<a
href={action.href}
className="text-xs font-medium underline shrink-0 hover:opacity-80"
onClick={action.href.startsWith("#") ? (e) => {
e.preventDefault();
document.getElementById(action.href.slice(1))?.scrollIntoView({ behavior: "smooth" });
} : undefined}
>
{action.label}
</a>
)}
</div>
);
}
APIPageClient.propTypes = {
machineId: PropTypes.string.isRequired,
};
|