Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 0 additions & 8 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,4 @@ logs/
dist/
.direnv/

# Flutter
flutter_client/.dart_tool/
flutter_client/.flutter-plugins
flutter_client/.flutter-plugins-dependencies
flutter_client/build/
flutter_client/.packages
flutter_client/pubspec.lock
flutter_client/flutter_02.png
pair-link.txt
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ node_modules
dist
logs
pnpm-lock.yaml
flutter_client
99 changes: 95 additions & 4 deletions client/src/components/GitStatus.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@
branches: string[];
}

interface PrData {
url: string;
number: number;
title: string;
state: string;
}

// Git status code to color/label
function fileStatusColor(status: string): string {
if (status.includes("M")) return "text-yellow-300";
Expand Down Expand Up @@ -64,6 +71,27 @@
const [creating, setCreating] = useState(false);
const [createError, setCreateError] = useState<string | null>(null);
const [deleting, setDeleting] = useState(false);
const [pr, setPr] = useState<PrData | null>(null);

const fetchPr = useCallback(async () => {
if (!projectId) {
setPr(null);
return;
}
try {
const res = await apiFetch(
`/api/projects/${encodeURIComponent(projectId)}/pr`,
{ serverId, serverUrl },
);
if (!res.ok) {
setPr(null);
return;
}
setPr(await res.json());
} catch {
setPr(null);
}
}, [projectId, serverId, serverUrl]);

const fetchStatus = useCallback(async () => {
if (!projectId) {
Expand Down Expand Up @@ -95,19 +123,23 @@
} finally {
setLoading(false);
}
}, [projectId]);

Check warning on line 126 in client/src/components/GitStatus.tsx

View workflow job for this annotation

GitHub Actions / lint

React Hook useCallback has missing dependencies: 'serverId' and 'serverUrl'. Either include them or remove the dependency array

// Fetch on mount and when projectId changes
useEffect(() => {
fetchStatus();
}, [fetchStatus]);
fetchPr();
}, [fetchStatus, fetchPr]);

// Refresh periodically (every 30s)
useEffect(() => {
if (!projectId) return;
const interval = setInterval(fetchStatus, 30000);
const interval = setInterval(() => {
fetchStatus();
fetchPr();
}, 30000);
return () => clearInterval(interval);
}, [projectId, fetchStatus]);
}, [projectId, fetchStatus, fetchPr]);

// Reset worktree create state when dropdown closes
useEffect(() => {
Expand Down Expand Up @@ -195,7 +227,7 @@
}

return (
<div className="relative">
<div className="relative flex items-center gap-1">
<button
onClick={() => setExpanded(!expanded)}
className={`
Expand Down Expand Up @@ -241,6 +273,23 @@
</span>
)}
</button>
{pr && (
<a
href={pr.url}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium bg-[var(--color-bg-secondary)] text-[var(--color-accent)] hover:bg-[var(--color-bg-hover)] transition-colors"
title={`PR #${pr.number}: ${pr.title}`}
>
<svg className="w-3.5 h-3.5" viewBox="0 0 16 16" fill="currentColor">
<path
fillRule="evenodd"
d="M7.177 3.073L9.573.677A.25.25 0 0110 .854v4.792a.25.25 0 01-.427.177L7.177 3.427a.25.25 0 010-.354zM3.75 2.5a.75.75 0 100 1.5.75.75 0 000-1.5zm-2.25.75a2.25 2.25 0 113 2.122v5.256a2.251 2.251 0 11-1.5 0V5.372A2.25 2.25 0 011.5 3.25zM11 2.5h-1V4h1a1 1 0 011 1v5.628a2.251 2.251 0 101.5 0V5A2.5 2.5 0 0011 2.5zm1 10.25a.75.75 0 111.5 0 .75.75 0 01-1.5 0zM3.75 12a.75.75 0 100 1.5.75.75 0 000-1.5z"
/>
</svg>
#{pr.number}
</a>
)}

{/* Expanded details dropdown */}
{expanded && (
Expand Down Expand Up @@ -320,6 +369,47 @@
)}
</div>
)}

{/* PR link */}
{pr && (
<div className="flex items-center gap-2">
<svg
className="w-4 h-4 text-[var(--color-text-tertiary)]"
viewBox="0 0 16 16"
fill="currentColor"
>
<path
fillRule="evenodd"
d="M7.177 3.073L9.573.677A.25.25 0 0110 .854v4.792a.25.25 0 01-.427.177L7.177 3.427a.25.25 0 010-.354zM3.75 2.5a.75.75 0 100 1.5.75.75 0 000-1.5zm-2.25.75a2.25 2.25 0 113 2.122v5.256a2.251 2.251 0 11-1.5 0V5.372A2.25 2.25 0 011.5 3.25zM11 2.5h-1V4h1a1 1 0 011 1v5.628a2.251 2.251 0 101.5 0V5A2.5 2.5 0 0011 2.5zm1 10.25a.75.75 0 111.5 0 .75.75 0 01-1.5 0zM3.75 12a.75.75 0 100 1.5.75.75 0 000-1.5z"
/>
</svg>
<a
href={pr.url}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
className="inline-flex items-center gap-1 text-sm text-[var(--color-accent)] hover:text-[#d97a5a] underline decoration-[var(--color-accent-muted)] hover:decoration-[#d97a5a] underline-offset-2"
>
PR #{pr.number}
<svg
className="w-3 h-3 shrink-0"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fillRule="evenodd"
d="M4.25 5.5a.75.75 0 00-.75.75v8.5c0 .414.336.75.75.75h8.5a.75.75 0 00.75-.75v-4a.75.75 0 011.5 0v4A2.25 2.25 0 0112.75 17h-8.5A2.25 2.25 0 012 14.75v-8.5A2.25 2.25 0 014.25 4h5a.75.75 0 010 1.5h-5zm7.25-1.25a.75.75 0 01.75-.75h4.5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0V6.31l-5.72 5.72a.75.75 0 11-1.06-1.06l5.72-5.72h-2.69a.75.75 0 01-.75-.75z"
clipRule="evenodd"
/>
</svg>
</a>
{pr.state !== "OPEN" && (
<span className="text-[10px] px-1.5 py-0.5 rounded bg-purple-900/50 text-purple-300">
{pr.state.toLowerCase()}
</span>
)}
</div>
)}
</div>

{/* Changed files list */}
Expand Down Expand Up @@ -352,6 +442,7 @@
onClick={(e) => {
e.stopPropagation();
fetchStatus();
fetchPr();
}}
className="w-full flex items-center justify-center gap-2 px-3 py-1.5 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)] rounded transition-colors"
>
Expand Down
27 changes: 22 additions & 5 deletions client/src/pages/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
getServerPin,
setServerPin,
clearServerPin,
getServers,

Check warning on line 25 in client/src/pages/Chat.tsx

View workflow job for this annotation

GitHub Actions / lint

'getServers' is defined but never used. Allowed unused vars must match /^_/u
} from "../lib/servers";
import {
registerServiceWorker,
Expand Down Expand Up @@ -546,7 +546,7 @@
reconnectTimerRef.current = setTimeout(() => {
connectAndAuth();
}, delay);
}, []); // connectAndAuth referenced below via ref

Check warning on line 549 in client/src/pages/Chat.tsx

View workflow job for this annotation

GitHub Actions / lint

React Hook useCallback has a missing dependency: 'connectAndAuth'. Either include it or remove the dependency array

const scheduleReconnectRef = useRef(scheduleReconnect);
scheduleReconnectRef.current = scheduleReconnect;
Expand Down Expand Up @@ -727,19 +727,36 @@
}
} else if (msg.type === "auth_error") {
console.error("Auth failed:", msg.error);
cachedPinRef.current = null;
clearServerPin(serverConfig.id);
setIsReconnecting(false);
setReconnectAttempt(0);
reconnectAttemptRef.current = 0;

if (msg.error === "device_expired") {
cachedPinRef.current = null;
clearServerPin(serverConfig.id);
setIsReconnecting(false);
setReconnectAttempt(0);
reconnectAttemptRef.current = 0;
setError(
"Device authorization has expired. Please re-pair this device.",
);
// Redirect to server list after a short delay
setTimeout(() => onNavigate("servers"), 3000);
} else if (
msg.error?.includes("Too many attempts") ||
msg.error?.includes("rate limit")
) {
// Rate limited — don't clear PIN, just retry after a delay
console.log("[auth] Rate limited, will retry in 10s...");
setError("Rate limited — retrying...");
setTimeout(() => {
if (cachedPinRef.current) {
connectAndAuth();
}
}, 10_000);
} else {
cachedPinRef.current = null;
clearServerPin(serverConfig.id);
setIsReconnecting(false);
setReconnectAttempt(0);
reconnectAttemptRef.current = 0;
setError(
msg.error || "Authentication failed - please re-enter PIN",
);
Expand Down Expand Up @@ -959,7 +976,7 @@
reject(new Error("WebSocket connection failed"));
};
});
}, [

Check warning on line 979 in client/src/pages/Chat.tsx

View workflow job for this annotation

GitHub Actions / lint

React Hook useCallback has missing dependencies: 'connectAndAuth' and 'onNavigate'. Either include them or remove the dependency array. If 'onNavigate' changes too often, find the parent component that defines it and wrap that definition in useCallback
serverConfig,
updateProjectState,
projectsKey,
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"lint": "eslint .",
"format": "prettier --write .",
"format:check": "prettier --check .",
"test": "tsx --test src/lib/*.test.ts",
"knip": "knip",
"ci:fix": "pnpm lint --fix && pnpm format",
"logs:server": "tail -f logs/server.log",
Expand Down
5 changes: 2 additions & 3 deletions scripts/new-pair.sh
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
#!/bin/bash
# Generate a new pairing QR code / link
# Usage: ./scripts/new-pair.sh <PIN>
# Must be run on the server machine (localhost auth exempt)
# Usage: ./scripts/new-pair.sh

set -e

PIN="${1:?Usage: $0 <PIN>}"
SERVER="http://localhost:6767"
OUTFILE="pair-link.txt"

RESPONSE=$(curl -s -X POST "$SERVER/api/new-pair-token" \
-H "Authorization: Bearer $PIN" \
-H "Content-Type: application/json")

URL=$(echo "$RESPONSE" | jq -r '.pairingUrl // empty')
Expand Down
63 changes: 58 additions & 5 deletions server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,19 @@ function checkAuthRateLimit(ip: string): boolean {
const now = Date.now();
const entry = authAttempts.get(ip);
if (!entry || now >= entry.resetAt) {
authAttempts.set(ip, { count: 1, resetAt: now + AUTH_WINDOW_MS });
return true;
}
entry.count++;
return entry.count <= AUTH_MAX_ATTEMPTS;
return entry.count < AUTH_MAX_ATTEMPTS;
}

function recordAuthFailure(ip: string): void {
const now = Date.now();
const entry = authAttempts.get(ip);
if (!entry || now >= entry.resetAt) {
authAttempts.set(ip, { count: 1, resetAt: now + AUTH_WINDOW_MS });
} else {
entry.count++;
}
}

// Device token TTL: 6 months
Expand Down Expand Up @@ -387,6 +395,7 @@ function checkApiAuth(req: IncomingMessage, res: ServerResponse): boolean {

const auth = req.headers["authorization"];
if (!auth || !auth.startsWith("Bearer ")) {
recordAuthFailure(clientIp);
json(res, { error: "Unauthorized" }, 401);
return false;
}
Expand All @@ -410,6 +419,7 @@ function checkApiAuth(req: IncomingMessage, res: ServerResponse): boolean {
}

if (!matched) {
recordAuthFailure(clientIp);
json(res, { error: "Unauthorized" }, 401);
return false;
}
Expand Down Expand Up @@ -439,8 +449,17 @@ async function handleRequest(req: IncomingMessage, res: ServerResponse) {
return;
}

// Auth gate: all /api/ routes require PIN auth, except /api/status (limited info without auth)
if (pathname?.startsWith("/api/") && pathname !== "/api/status") {
// Auth gate: all /api/ routes require PIN auth, except:
// - /api/status (limited info without auth)
// - /api/new-pair-token from localhost (if you're on the machine, you're authorized)
const isLocalhost =
req.socket.remoteAddress === "127.0.0.1" ||
req.socket.remoteAddress === "::1" ||
req.socket.remoteAddress === "::ffff:127.0.0.1";
const authExempt =
pathname === "/api/status" ||
(pathname === "/api/new-pair-token" && isLocalhost);
if (pathname?.startsWith("/api/") && !authExempt) {
if (!checkApiAuth(req, res)) return;
}

Expand Down Expand Up @@ -775,6 +794,39 @@ async function handleRequest(req: IncomingMessage, res: ServerResponse) {
}
}

// API: Get PR info for a project's current branch
if (
pathname?.startsWith("/api/projects/") &&
pathname.endsWith("/pr") &&
method === "GET"
) {
const projectId = decodeURIComponent(
pathname.split("/api/projects/")[1].replace("/pr", ""),
);
if (!validateProjectId(projectId))
return json(res, { error: "Invalid project ID" }, 400);
const project = getProject(projectId);
if (!project) {
return json(res, { error: "Project not found" }, 404);
}

try {
const prJson = execSync("gh pr view --json url,number,title,state", {
cwd: project.path,
encoding: "utf-8",
timeout: 10000,
}).trim();
const pr = JSON.parse(prJson);
console.log(
`[api] PR info for ${projectId}: #${pr.number} (${pr.state})`,
);
return json(res, pr);
} catch {
console.log(`[api] No PR found for ${projectId}`);
return json(res, { error: "No PR found" }, 404);
}
}

// API: Worktree management
if (
pathname?.startsWith("/api/projects/") &&
Expand Down Expand Up @@ -1422,6 +1474,7 @@ async function main() {
}
} else {
console.log("Auth failed - invalid PIN");
recordAuthFailure(clientIp);
sendEncrypted({ type: "auth_error", error: "Invalid PIN" });
}
} else if (msg.type === "list_projects") {
Expand Down
Loading
Loading