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:
@@ -29,6 +29,7 @@ ENV DATA_DIR=/app/data
|
|||||||
COPY --from=builder /app/public ./public
|
COPY --from=builder /app/public ./public
|
||||||
COPY --from=builder /app/.next/static ./.next/static
|
COPY --from=builder /app/.next/static ./.next/static
|
||||||
COPY --from=builder /app/.next/standalone ./
|
COPY --from=builder /app/.next/standalone ./
|
||||||
|
COPY --from=builder /app/custom-server.js ./custom-server.js
|
||||||
COPY --from=builder /app/open-sse ./open-sse
|
COPY --from=builder /app/open-sse ./open-sse
|
||||||
# Next file tracing can omit sibling files; MITM runs server.js as a separate process.
|
# Next file tracing can omit sibling files; MITM runs server.js as a separate process.
|
||||||
COPY --from=builder /app/src/mitm ./src/mitm
|
COPY --from=builder /app/src/mitm ./src/mitm
|
||||||
@@ -49,4 +50,4 @@ RUN apk --no-cache upgrade && apk --no-cache add su-exec && \
|
|||||||
EXPOSE 20128
|
EXPOSE 20128
|
||||||
|
|
||||||
ENTRYPOINT ["/entrypoint.sh"]
|
ENTRYPOINT ["/entrypoint.sh"]
|
||||||
CMD ["node", "server.js"]
|
CMD ["node", "custom-server.js"]
|
||||||
|
|||||||
@@ -470,9 +470,13 @@ function openBrowser(url) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find standalone server (bundled in bin/app for published package)
|
// Find standalone server (bundled in bin/app for published package).
|
||||||
|
// Prefer custom-server.js (injects real socket IP) when present.
|
||||||
const standaloneDir = path.join(__dirname, "app");
|
const standaloneDir = path.join(__dirname, "app");
|
||||||
const serverPath = path.join(standaloneDir, "server.js");
|
const customServerPath = path.join(standaloneDir, "custom-server.js");
|
||||||
|
const serverPath = fs.existsSync(customServerPath)
|
||||||
|
? customServerPath
|
||||||
|
: path.join(standaloneDir, "server.js");
|
||||||
|
|
||||||
if (!fs.existsSync(serverPath)) {
|
if (!fs.existsSync(serverPath)) {
|
||||||
console.error("Error: Standalone build not found.");
|
console.error("Error: Standalone build not found.");
|
||||||
|
|||||||
@@ -154,6 +154,15 @@ if (standaloneApp !== standaloneRootToUse && fs.existsSync(standaloneNodeModules
|
|||||||
}
|
}
|
||||||
console.log("✅ Copied standalone build\n");
|
console.log("✅ Copied standalone build\n");
|
||||||
|
|
||||||
|
// Step 3a: Copy custom server (injects real socket IP, strips spoofable XFF).
|
||||||
|
const customServerSrc = path.join(appDir, "custom-server.js");
|
||||||
|
if (fs.existsSync(customServerSrc)) {
|
||||||
|
fs.copyFileSync(customServerSrc, path.join(cliAppDir, "custom-server.js"));
|
||||||
|
console.log("✅ Copied custom-server.js\n");
|
||||||
|
} else {
|
||||||
|
console.warn("⚠️ custom-server.js not found — server will run without real-IP injection\n");
|
||||||
|
}
|
||||||
|
|
||||||
// Step 3b: Ensure sql.js (pure JS fallback) bundled in app/cli/app/node_modules.
|
// Step 3b: Ensure sql.js (pure JS fallback) bundled in app/cli/app/node_modules.
|
||||||
// Strip better-sqlite3 (native) — it lives in ~/.9router/runtime to avoid
|
// Strip better-sqlite3 (native) — it lives in ~/.9router/runtime to avoid
|
||||||
// Windows EBUSY during global CLI updates. node:sqlite (Node ≥22.5) is also
|
// Windows EBUSY during global CLI updates. node:sqlite (Node ≥22.5) is also
|
||||||
|
|||||||
@@ -410,6 +410,14 @@ async function updateSettings(data) {
|
|||||||
return makeRequest("PATCH", "/api/settings", data);
|
return makeRequest("PATCH", "/api/settings", data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reset dashboard password to default (clears stored hash server-side)
|
||||||
|
* @returns {Promise<Object>} { success }
|
||||||
|
*/
|
||||||
|
async function resetPassword() {
|
||||||
|
return makeRequest("POST", "/api/auth/reset-password");
|
||||||
|
}
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// MODELS API
|
// MODELS API
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
@@ -528,6 +536,7 @@ module.exports = {
|
|||||||
// Settings
|
// Settings
|
||||||
getSettings,
|
getSettings,
|
||||||
updateSettings,
|
updateSettings,
|
||||||
|
resetPassword,
|
||||||
|
|
||||||
// Tunnel
|
// Tunnel
|
||||||
getTunnelStatus,
|
getTunnelStatus,
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
const path = require("path");
|
|
||||||
const fs = require("fs");
|
|
||||||
const os = require("os");
|
|
||||||
const api = require("../api/client");
|
const api = require("../api/client");
|
||||||
const { confirm, pause } = require("../utils/input");
|
const { confirm, pause } = require("../utils/input");
|
||||||
const { showStatus } = require("../utils/display");
|
const { showStatus } = require("../utils/display");
|
||||||
@@ -18,13 +15,6 @@ const COLORS = {
|
|||||||
|
|
||||||
const DEFAULT_PASSWORD = "123456";
|
const DEFAULT_PASSWORD = "123456";
|
||||||
|
|
||||||
// Resolve db.json path (matches app/src/lib/dataDir.js convention)
|
|
||||||
function getDbPath() {
|
|
||||||
return process.platform === "win32"
|
|
||||||
? path.join(process.env.APPDATA || "", "9router", "db.json")
|
|
||||||
: path.join(os.homedir(), ".9router", "db.json");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Show settings menu (tunnel + RTK + reset password)
|
* Show settings menu (tunnel + RTK + reset password)
|
||||||
* @param {Array<string>} breadcrumb - Breadcrumb path
|
* @param {Array<string>} breadcrumb - Breadcrumb path
|
||||||
@@ -171,18 +161,10 @@ async function toggleRtk(currentlyOn) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reset dashboard password by clearing the hash in db.json (Phase B).
|
* Reset dashboard password to default via server API (writes the live SQLite DB).
|
||||||
* After reset, user can log in with the default password "123456".
|
* After reset, user can log in with the default password "123456".
|
||||||
*/
|
*/
|
||||||
async function resetPassword() {
|
async function resetPassword() {
|
||||||
const dbPath = getDbPath();
|
|
||||||
|
|
||||||
if (!fs.existsSync(dbPath)) {
|
|
||||||
showStatus(`db.json not found at ${dbPath}`, "error");
|
|
||||||
await pause();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ok = await confirm(`Reset dashboard password to default "${DEFAULT_PASSWORD}"?`);
|
const ok = await confirm(`Reset dashboard password to default "${DEFAULT_PASSWORD}"?`);
|
||||||
if (!ok) {
|
if (!ok) {
|
||||||
showStatus("Cancelled", "info");
|
showStatus("Cancelled", "info");
|
||||||
@@ -190,16 +172,11 @@ async function resetPassword() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
const result = await api.resetPassword();
|
||||||
const raw = fs.readFileSync(dbPath, "utf-8");
|
if (result.success) {
|
||||||
const db = JSON.parse(raw);
|
|
||||||
if (db.settings && Object.prototype.hasOwnProperty.call(db.settings, "password")) {
|
|
||||||
delete db.settings.password;
|
|
||||||
}
|
|
||||||
fs.writeFileSync(dbPath, JSON.stringify(db, null, 2));
|
|
||||||
showStatus(`Password reset. Default: ${DEFAULT_PASSWORD}`, "success");
|
showStatus(`Password reset. Default: ${DEFAULT_PASSWORD}`, "success");
|
||||||
} catch (err) {
|
} else {
|
||||||
showStatus(`Failed to reset password: ${err.message}`, "error");
|
showStatus(`Failed to reset password: ${result.error}`, "error");
|
||||||
}
|
}
|
||||||
await pause();
|
await pause();
|
||||||
}
|
}
|
||||||
|
|||||||
22
custom-server.js
Normal file
22
custom-server.js
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
const http = require("http");
|
||||||
|
|
||||||
|
const origCreate = http.createServer.bind(http);
|
||||||
|
|
||||||
|
// Wrap Next standalone HTTP server: derive client IP from the TCP socket
|
||||||
|
// (unspoofable) and strip client-supplied forwarding headers so downstream
|
||||||
|
// rate-limiting keys on the real peer address instead of attacker-controlled XFF.
|
||||||
|
http.createServer = (...args) => {
|
||||||
|
const handler = args.find((a) => typeof a === "function");
|
||||||
|
const rest = args.filter((a) => typeof a !== "function");
|
||||||
|
if (!handler) return origCreate(...args);
|
||||||
|
const wrapped = (req, res) => {
|
||||||
|
const ip = req.socket && req.socket.remoteAddress ? req.socket.remoteAddress : "";
|
||||||
|
delete req.headers["x-9r-real-ip"];
|
||||||
|
delete req.headers["x-forwarded-for"];
|
||||||
|
req.headers["x-9r-real-ip"] = ip;
|
||||||
|
return handler(req, res);
|
||||||
|
};
|
||||||
|
return origCreate(...rest, wrapped);
|
||||||
|
};
|
||||||
|
|
||||||
|
require("./server.js");
|
||||||
@@ -9,7 +9,9 @@
|
|||||||
"start": "next start",
|
"start": "next start",
|
||||||
"dev:bun": "bun --bun next dev --webpack --port 20128",
|
"dev:bun": "bun --bun next dev --webpack --port 20128",
|
||||||
"build:bun": "bun --bun next build --webpack",
|
"build:bun": "bun --bun next build --webpack",
|
||||||
"start:bun": "bun ./.next/standalone/server.js"
|
"start:bun": "bun ./.next/standalone/server.js",
|
||||||
|
"cli:pack": "npm --prefix cli run pack:cli",
|
||||||
|
"cli:publish": "npm --prefix cli run publish:cli"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@dnd-kit/core": "^6.3.1",
|
"@dnd-kit/core": "^6.3.1",
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { cookies } from "next/headers";
|
|||||||
import { setDashboardAuthCookie } from "@/lib/auth/dashboardSession";
|
import { setDashboardAuthCookie } from "@/lib/auth/dashboardSession";
|
||||||
import { isOidcConfigured } from "@/lib/auth/oidc";
|
import { isOidcConfigured } from "@/lib/auth/oidc";
|
||||||
import { checkLock, recordFail, recordSuccess, getClientIp } from "@/lib/auth/loginLimiter";
|
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.";
|
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();
|
const cookieStore = await cookies();
|
||||||
await setDashboardAuthCookie(cookieStore, request);
|
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);
|
const { remainingBeforeLock } = recordFail(ip);
|
||||||
|
|||||||
13
src/app/api/auth/reset-password/route.js
Normal file
13
src/app/api/auth/reset-password/route.js
Normal 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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,8 @@ export default function LoginPage() {
|
|||||||
const [authMode, setAuthMode] = useState("password");
|
const [authMode, setAuthMode] = useState("password");
|
||||||
const [oidcConfigured, setOidcConfigured] = useState(false);
|
const [oidcConfigured, setOidcConfigured] = useState(false);
|
||||||
const [oidcLoginLabel, setOidcLoginLabel] = useState("Sign in with OIDC");
|
const [oidcLoginLabel, setOidcLoginLabel] = useState("Sign in with OIDC");
|
||||||
|
const [mustChange, setMustChange] = useState(false);
|
||||||
|
const [newPassword, setNewPassword] = useState("");
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
// Countdown for rate-limit
|
// Countdown for rate-limit
|
||||||
@@ -72,6 +74,11 @@ export default function LoginPage() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
|
const data = await res.json();
|
||||||
|
if (data.mustChangePassword) {
|
||||||
|
setMustChange(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
router.push("/dashboard");
|
router.push("/dashboard");
|
||||||
router.refresh();
|
router.refresh();
|
||||||
} else {
|
} 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 = () => {
|
const handleOidcLogin = () => {
|
||||||
window.location.href = "/api/auth/oidc/start";
|
window.location.href = "/api/auth/oidc/start";
|
||||||
};
|
};
|
||||||
@@ -121,6 +153,28 @@ export default function LoginPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Card>
|
<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">
|
<div className="flex flex-col gap-4">
|
||||||
{oidcAvailable && (
|
{oidcAvailable && (
|
||||||
<Button type="button" variant="primary" className="w-full" onClick={handleOidcLogin}>
|
<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>
|
Default password is <code className="bg-sidebar px-1 rounded">123456</code>
|
||||||
</p>
|
</p>
|
||||||
{hasPassword === false && (
|
{hasPassword === false && (
|
||||||
<p className="text-xs text-center text-text-muted">
|
<p className="text-xs text-center text-amber-600 dark:text-amber-400">
|
||||||
No custom password is set yet. The default password above will work until you change it.
|
Security risk: no password set. You will be asked to set one when logging in remotely.
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</form>
|
</form>
|
||||||
@@ -190,6 +244,7 @@ export default function LoginPage() {
|
|||||||
error && <p className="text-xs text-red-500">{error}</p>
|
error && <p className="text-xs text-red-500">{error}</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -78,6 +78,7 @@ const LOCAL_ONLY_PATHS = [
|
|||||||
"/api/tunnel/disable",
|
"/api/tunnel/disable",
|
||||||
"/api/oauth/cursor/auto-import",
|
"/api/oauth/cursor/auto-import",
|
||||||
"/api/oauth/kiro/auto-import",
|
"/api/oauth/kiro/auto-import",
|
||||||
|
"/api/auth/reset-password",
|
||||||
];
|
];
|
||||||
|
|
||||||
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
|
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
|
||||||
@@ -88,7 +89,7 @@ function isLoopbackHostname(h) {
|
|||||||
return LOOPBACK_HOSTS.has(name);
|
return LOOPBACK_HOSTS.has(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
function isLocalRequest(request) {
|
export function isLocalRequest(request) {
|
||||||
if (!isLoopbackHostname(request.headers.get("host"))) return false;
|
if (!isLoopbackHostname(request.headers.get("host"))) return false;
|
||||||
const origin = request.headers.get("origin");
|
const origin = request.headers.get("origin");
|
||||||
if (origin) {
|
if (origin) {
|
||||||
|
|||||||
@@ -46,7 +46,15 @@ export function recordSuccess(ip) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function getClientIp(request) {
|
export function getClientIp(request) {
|
||||||
const xff = request.headers.get("x-forwarded-for");
|
// Trusted: set from TCP socket by custom-server.js (client cannot spoof).
|
||||||
if (xff) return xff.split(",")[0].trim();
|
const realIp = request.headers.get("x-9r-real-ip");
|
||||||
return request.headers.get("x-real-ip") || "unknown";
|
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";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ export {
|
|||||||
isTailscaleLoggedIn,
|
isTailscaleLoggedIn,
|
||||||
isTailscaleLoggedInStrict,
|
isTailscaleLoggedInStrict,
|
||||||
isSystemDaemonRunning,
|
isSystemDaemonRunning,
|
||||||
|
isDaemonAlive,
|
||||||
|
startFunnel,
|
||||||
getTailscaleBin,
|
getTailscaleBin,
|
||||||
installTailscale,
|
installTailscale,
|
||||||
startLogin,
|
startLogin,
|
||||||
|
|||||||
@@ -519,6 +519,11 @@ function isDaemonTunMode() {
|
|||||||
} catch { return null; }
|
} catch { return null; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Daemon process alive (independent of funnel state) — mirrors cloudflared PID check semantic. */
|
||||||
|
export function isDaemonAlive() {
|
||||||
|
return isDaemonTunMode() !== null;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Start tailscaled.
|
* Start tailscaled.
|
||||||
* - With sudoPassword: TUN mode (root) → Funnel TLS works
|
* - With sudoPassword: TUN mode (root) → Funnel TLS works
|
||||||
@@ -550,8 +555,9 @@ export async function startDaemonWithPassword(sudoPassword) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const wantTun = !!sudoPassword;
|
|
||||||
const currentMode = isDaemonTunMode(); // true=TUN, false=userspace, null=not running
|
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
|
// Daemon already running in correct mode → reuse
|
||||||
if (currentMode !== null && currentMode === wantTun) {
|
if (currentMode !== null && currentMode === wantTun) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect, useRef } from "react";
|
||||||
import PropTypes from "prop-types";
|
import PropTypes from "prop-types";
|
||||||
import { Modal, Button, Input } from "@/shared/components";
|
import { Modal, Button, Input } from "@/shared/components";
|
||||||
import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard";
|
import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard";
|
||||||
@@ -16,6 +16,12 @@ export default function KiroSocialOAuthModal({ isOpen, provider, onSuccess, onCl
|
|||||||
const [callbackUrl, setCallbackUrl] = useState("");
|
const [callbackUrl, setCallbackUrl] = useState("");
|
||||||
const [error, setError] = useState(null);
|
const [error, setError] = useState(null);
|
||||||
const { copied, copy } = useCopyToClipboard();
|
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
|
// Initialize auth flow
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -37,8 +43,11 @@ export default function KiroSocialOAuthModal({ isOpen, provider, onSuccess, onCl
|
|||||||
setAuthUrl(data.authUrl);
|
setAuthUrl(data.authUrl);
|
||||||
setStep("input");
|
setStep("input");
|
||||||
|
|
||||||
// Auto-open browser
|
// Auto-open browser once per modal session.
|
||||||
window.open(data.authUrl, "_blank");
|
if (!openedRef.current) {
|
||||||
|
openedRef.current = true;
|
||||||
|
window.open(data.authUrl, "_blank");
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message);
|
setError(err.message);
|
||||||
setStep("error");
|
setStep("error");
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ export default function OAuthModal({ isOpen, provider, providerInfo, onSuccess,
|
|||||||
const [polling, setPolling] = useState(false);
|
const [polling, setPolling] = useState(false);
|
||||||
const popupRef = useRef(null);
|
const popupRef = useRef(null);
|
||||||
const pollingAbortRef = useRef(false);
|
const pollingAbortRef = useRef(false);
|
||||||
|
const openedRef = useRef(false);
|
||||||
const { copied, copy } = useCopyToClipboard();
|
const { copied, copy } = useCopyToClipboard();
|
||||||
|
|
||||||
// State for client-only values to avoid hydration mismatch
|
// 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
|
// Reset state and start OAuth when modal opens
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isOpen && provider) {
|
if (isOpen && provider) {
|
||||||
|
// Guard against StrictMode/effect re-runs auto-opening multiple tabs.
|
||||||
|
if (openedRef.current) return;
|
||||||
|
openedRef.current = true;
|
||||||
setAuthData(null);
|
setAuthData(null);
|
||||||
setCallbackUrl("");
|
setCallbackUrl("");
|
||||||
setError(null);
|
setError(null);
|
||||||
@@ -321,6 +325,7 @@ export default function OAuthModal({ isOpen, provider, providerInfo, onSuccess,
|
|||||||
} else if (!isOpen) {
|
} else if (!isOpen) {
|
||||||
// Abort polling and cleanup proxy when modal closes
|
// Abort polling and cleanup proxy when modal closes
|
||||||
pollingAbortRef.current = true;
|
pollingAbortRef.current = true;
|
||||||
|
openedRef.current = false;
|
||||||
if (provider === "codex") {
|
if (provider === "codex") {
|
||||||
fetch("/api/oauth/codex/stop-proxy").catch(() => {});
|
fetch("/api/oauth/codex/stop-proxy").catch(() => {});
|
||||||
} else if (provider === "xai") {
|
} else if (provider === "xai") {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
isTunnelManuallyDisabled, isTunnelReconnecting, isTailscaleReconnecting,
|
isTunnelManuallyDisabled, isTunnelReconnecting, isTailscaleReconnecting,
|
||||||
getTunnelService, getTailscaleService, setTunnelUnexpectedExitCallback,
|
getTunnelService, getTailscaleService, setTunnelUnexpectedExitCallback,
|
||||||
killCloudflared, isCloudflaredRunning, ensureCloudflared,
|
killCloudflared, isCloudflaredRunning, ensureCloudflared,
|
||||||
isTailscaleRunning, isTailscaleRunningStrict,
|
isTailscaleRunning, isTailscaleRunningStrict, isDaemonAlive, startFunnel,
|
||||||
checkInternet,
|
checkInternet,
|
||||||
RESTART_COOLDOWN_MS, NETWORK_SETTLE_MS,
|
RESTART_COOLDOWN_MS, NETWORK_SETTLE_MS,
|
||||||
WATCHDOG_INTERVAL_MS, NETWORK_CHECK_INTERVAL_MS, VIRTUAL_IFACE_REGEX,
|
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();
|
const running = reason === "startup" ? await isTailscaleRunningStrict() : isTailscaleRunning();
|
||||||
if (running) return;
|
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);
|
const force = FORCE_RESTART_REASONS.test(reason);
|
||||||
if (!force && Date.now() - svc.lastRestartAt < RESTART_COOLDOWN_MS) {
|
if (!force && Date.now() - svc.lastRestartAt < RESTART_COOLDOWN_MS) {
|
||||||
console.log(`[Tailscale] degraded but cooldown active, skip (${reason})`);
|
console.log(`[Tailscale] degraded but cooldown active, skip (${reason})`);
|
||||||
|
|||||||
Reference in New Issue
Block a user