fix(auth): real client IP rate-limiting + remote default-password guard

- Add custom-server.js: inject unspoofable socket IP, strip client XFF
  (wired into Docker CMD + CLI spawn + build-cli copy)
- loginLimiter: key on trusted x-9r-real-ip, TRUST_PROXY opt-in, global fallback
- Force password change on first remote login while default is in use
- Add /api/auth/reset-password (local-only) so CLI reset writes live SQLite
- CLI settings: reset via API instead of stale db.json
- Fix OAuth modals opening duplicate browser tabs on add-connection
- Add cli:pack / cli:publish scripts

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
decolua
2026-06-08 12:10:02 +07:00
co-authored by Cursor
parent c572c68717
commit 7648c3412b
17 changed files with 185 additions and 44 deletions
+7 -1
View File
@@ -5,6 +5,7 @@ import { cookies } from "next/headers";
import { setDashboardAuthCookie } from "@/lib/auth/dashboardSession";
import { isOidcConfigured } from "@/lib/auth/oidc";
import { checkLock, recordFail, recordSuccess, getClientIp } from "@/lib/auth/loginLimiter";
import { isLocalRequest } from "@/dashboardGuard";
const RESET_HINT = "Forgot password? Reset to default via 9Router CLI → Settings → Reset Password to Default.";
@@ -55,7 +56,12 @@ export async function POST(request) {
const cookieStore = await cookies();
await setDashboardAuthCookie(cookieStore, request);
return NextResponse.json({ success: true });
// Default password still in use on a remote client → force a password
// change before the dashboard is exposed remotely (keeps local UX intact).
const mustChangePassword =
!storedHash && !process.env.INITIAL_PASSWORD && !isLocalRequest(request);
return NextResponse.json({ success: true, mustChangePassword });
}
const { remainingBeforeLock } = recordFail(ip);
+13
View File
@@ -0,0 +1,13 @@
import { NextResponse } from "next/server";
import { updateSettings } from "@/lib/localDb";
// Reset dashboard password to default by clearing the stored hash.
// Local-only (enforced by dashboardGuard). Never returns the default literal.
export async function POST() {
try {
await updateSettings({ password: null });
return NextResponse.json({ success: true });
} catch (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
+57 -2
View File
@@ -14,6 +14,8 @@ export default function LoginPage() {
const [authMode, setAuthMode] = useState("password");
const [oidcConfigured, setOidcConfigured] = useState(false);
const [oidcLoginLabel, setOidcLoginLabel] = useState("Sign in with OIDC");
const [mustChange, setMustChange] = useState(false);
const [newPassword, setNewPassword] = useState("");
const router = useRouter();
// Countdown for rate-limit
@@ -72,6 +74,11 @@ export default function LoginPage() {
});
if (res.ok) {
const data = await res.json();
if (data.mustChangePassword) {
setMustChange(true);
return;
}
router.push("/dashboard");
router.refresh();
} else {
@@ -87,6 +94,31 @@ export default function LoginPage() {
}
};
// Force a new password before entering the dashboard (default + remote).
const handleSetNewPassword = async (e) => {
e.preventDefault();
setLoading(true);
setError("");
try {
const res = await fetch("/api/settings", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ currentPassword: password, newPassword }),
});
if (res.ok) {
router.push("/dashboard");
router.refresh();
} else {
const data = await res.json();
setError(data.error || "Failed to set password");
}
} catch (err) {
setError("An error occurred. Please try again.");
} finally {
setLoading(false);
}
};
const handleOidcLogin = () => {
window.location.href = "/api/auth/oidc/start";
};
@@ -121,6 +153,28 @@ export default function LoginPage() {
</div>
<Card>
{mustChange ? (
<form onSubmit={handleSetNewPassword} className="flex flex-col gap-4">
<p className="text-sm text-amber-600 dark:text-amber-400 text-center">
Set a new password before accessing the dashboard remotely.
</p>
<div className="flex flex-col gap-2">
<label className="text-sm font-medium">New password</label>
<Input
type="password"
placeholder="Enter new password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
required
autoFocus
/>
{error && <p className="text-xs text-red-500">{error}</p>}
</div>
<Button type="submit" variant="primary" className="w-full" loading={loading} disabled={!newPassword}>
Set password
</Button>
</form>
) : (
<div className="flex flex-col gap-4">
{oidcAvailable && (
<Button type="button" variant="primary" className="w-full" onClick={handleOidcLogin}>
@@ -181,8 +235,8 @@ export default function LoginPage() {
Default password is <code className="bg-sidebar px-1 rounded">123456</code>
</p>
{hasPassword === false && (
<p className="text-xs text-center text-text-muted">
No custom password is set yet. The default password above will work until you change it.
<p className="text-xs text-center text-amber-600 dark:text-amber-400">
Security risk: no password set. You will be asked to set one when logging in remotely.
</p>
)}
</form>
@@ -190,6 +244,7 @@ export default function LoginPage() {
error && <p className="text-xs text-red-500">{error}</p>
)}
</div>
)}
</Card>
</div>
</div>
+2 -1
View File
@@ -78,6 +78,7 @@ const LOCAL_ONLY_PATHS = [
"/api/tunnel/disable",
"/api/oauth/cursor/auto-import",
"/api/oauth/kiro/auto-import",
"/api/auth/reset-password",
];
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
@@ -88,7 +89,7 @@ function isLoopbackHostname(h) {
return LOOPBACK_HOSTS.has(name);
}
function isLocalRequest(request) {
export function isLocalRequest(request) {
if (!isLoopbackHostname(request.headers.get("host"))) return false;
const origin = request.headers.get("origin");
if (origin) {
+11 -3
View File
@@ -46,7 +46,15 @@ export function recordSuccess(ip) {
}
export function getClientIp(request) {
const xff = request.headers.get("x-forwarded-for");
if (xff) return xff.split(",")[0].trim();
return request.headers.get("x-real-ip") || "unknown";
// Trusted: set from TCP socket by custom-server.js (client cannot spoof).
const realIp = request.headers.get("x-9r-real-ip");
if (realIp) return realIp;
// Behind a trusted reverse proxy that overwrites XFF with the real client IP.
if (process.env.TRUST_PROXY === "true") {
const xff = request.headers.get("x-forwarded-for");
if (xff) return xff.split(",")[0].trim();
}
// Direct exposure without custom-server: single bucket so spoofed XFF
// rotation cannot escape the limiter.
return "unknown";
}
+2
View File
@@ -31,6 +31,8 @@ export {
isTailscaleLoggedIn,
isTailscaleLoggedInStrict,
isSystemDaemonRunning,
isDaemonAlive,
startFunnel,
getTailscaleBin,
installTailscale,
startLogin,
+7 -1
View File
@@ -519,6 +519,11 @@ function isDaemonTunMode() {
} catch { return null; }
}
/** Daemon process alive (independent of funnel state) — mirrors cloudflared PID check semantic. */
export function isDaemonAlive() {
return isDaemonTunMode() !== null;
}
/**
* Start tailscaled.
* - With sudoPassword: TUN mode (root) → Funnel TLS works
@@ -550,8 +555,9 @@ export async function startDaemonWithPassword(sudoPassword) {
return;
}
const wantTun = !!sudoPassword;
const currentMode = isDaemonTunMode(); // true=TUN, false=userspace, null=not running
// No password but a healthy TUN daemon already runs → keep TUN, never downgrade-kill it.
const wantTun = sudoPassword ? true : currentMode === true;
// Daemon already running in correct mode → reuse
if (currentMode !== null && currentMode === wantTun) {
+12 -3
View File
@@ -1,6 +1,6 @@
"use client";
import { useState, useEffect } from "react";
import { useState, useEffect, useRef } from "react";
import PropTypes from "prop-types";
import { Modal, Button, Input } from "@/shared/components";
import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard";
@@ -16,6 +16,12 @@ export default function KiroSocialOAuthModal({ isOpen, provider, onSuccess, onCl
const [callbackUrl, setCallbackUrl] = useState("");
const [error, setError] = useState(null);
const { copied, copy } = useCopyToClipboard();
const openedRef = useRef(false);
// Reset auto-open guard when modal closes so it can re-open next session.
useEffect(() => {
if (!isOpen) openedRef.current = false;
}, [isOpen]);
// Initialize auth flow
useEffect(() => {
@@ -37,8 +43,11 @@ export default function KiroSocialOAuthModal({ isOpen, provider, onSuccess, onCl
setAuthUrl(data.authUrl);
setStep("input");
// Auto-open browser
window.open(data.authUrl, "_blank");
// Auto-open browser once per modal session.
if (!openedRef.current) {
openedRef.current = true;
window.open(data.authUrl, "_blank");
}
} catch (err) {
setError(err.message);
setStep("error");
+5
View File
@@ -20,6 +20,7 @@ export default function OAuthModal({ isOpen, provider, providerInfo, onSuccess,
const [polling, setPolling] = useState(false);
const popupRef = useRef(null);
const pollingAbortRef = useRef(false);
const openedRef = useRef(false);
const { copied, copy } = useCopyToClipboard();
// State for client-only values to avoid hydration mismatch
@@ -310,6 +311,9 @@ export default function OAuthModal({ isOpen, provider, providerInfo, onSuccess,
// Reset state and start OAuth when modal opens
useEffect(() => {
if (isOpen && provider) {
// Guard against StrictMode/effect re-runs auto-opening multiple tabs.
if (openedRef.current) return;
openedRef.current = true;
setAuthData(null);
setCallbackUrl("");
setError(null);
@@ -321,6 +325,7 @@ export default function OAuthModal({ isOpen, provider, providerInfo, onSuccess,
} else if (!isOpen) {
// Abort polling and cleanup proxy when modal closes
pollingAbortRef.current = true;
openedRef.current = false;
if (provider === "codex") {
fetch("/api/oauth/codex/stop-proxy").catch(() => {});
} else if (provider === "xai") {
+13 -1
View File
@@ -8,7 +8,7 @@ import {
isTunnelManuallyDisabled, isTunnelReconnecting, isTailscaleReconnecting,
getTunnelService, getTailscaleService, setTunnelUnexpectedExitCallback,
killCloudflared, isCloudflaredRunning, ensureCloudflared,
isTailscaleRunning, isTailscaleRunningStrict,
isTailscaleRunning, isTailscaleRunningStrict, isDaemonAlive, startFunnel,
checkInternet,
RESTART_COOLDOWN_MS, NETWORK_SETTLE_MS,
WATCHDOG_INTERVAL_MS, NETWORK_CHECK_INTERVAL_MS, VIRTUAL_IFACE_REGEX,
@@ -176,6 +176,18 @@ async function safeRestartTailscale(reason) {
const running = reason === "startup" ? await isTailscaleRunningStrict() : isTailscaleRunning();
if (running) return;
// Daemon alive but funnel dropped → recover funnel only; never full-restart (preserves login/daemon).
if (isDaemonAlive() && svc.activeLocalPort) {
try {
await startFunnel(svc.activeLocalPort);
svc.lastRestartAt = Date.now();
console.log("[Tailscale] funnel re-established (daemon alive)");
} catch (err) {
console.log("[Tailscale] funnel recovery failed:", err.message);
}
return;
}
const force = FORCE_RESTART_REASONS.test(reason);
if (!force && Date.now() - svc.lastRestartAt < RESTART_COOLDOWN_MS) {
console.log(`[Tailscale] degraded but cooldown active, skip (${reason})`);