Compare commits

...
Author SHA1 Message Date
Antigravity AI e04d904eb7 fix(ui): stabilize bottom-panel resize drag on webkit
Guard the resize pointermove handler with an isDraggingRef flag instead of
hasPointerCapture(), which behaves inconsistently across webkit versions in
CI for repeated drag sequences. setPointerCapture still delivers move/up
events when the pointer leaves the handle bounds.

Salvaged from the retired feat/phase-2-auth-gate branch (orig d91cc429); the
setPointerCapture work it built on is already on main.
2026-06-04 18:36:44 +12:00
Silvertakana 8ca4bdd9fa fix(auth): harden globe login gate with revocable sessions and deny-by-default API (#232)
- User.sessionVersion + jwt-callback revalidation rejects deleted-user,
  cross-database, and stale-version tokens (fixes cross-worktree stay-logged-in)
- POST /api/auth/revoke ("sign out everywhere") bumps sessionVersion
- proxy: deny-by-default /api with public allowlist + CORS preflight passthrough;
  anchored static-asset allowlist closes the path.includes(".") bypass
- harden session cookie options (httpOnly/sameSite/secure) and cut maxAge to 7 days
- unify https/secure-context detection in isHttpsDeployment() so the cookie
  writer (auth) and edge reader (proxy) never disagree on the __Secure- prefix
- augment next-auth User/Session/JWT types

Verified: 1009/1009 tests, build exit 0, live HTTP reproduction of all gates.
2026-06-04 18:17:46 +12:00
9 changed files with 311 additions and 37 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "worldwideview",
"version": "2.48.13",
"version": "2.48.15",
"private": true,
"type": "module",
"packageManager": "[email protected]",
+4
View File
@@ -14,6 +14,10 @@ model User {
name String
hashedPassword String
role String @default("user")
// Bumping this invalidates all of the user's existing JWT sessions.
// The JWT embeds the value at sign-in; the auth jwt callback rejects any
// token whose value no longer matches the DB (logout-everywhere / revoke).
sessionVersion Int @default(0)
createdAt DateTime @default(now())
favorites Favorite[]
memberships WorkspaceMember[]
+34
View File
@@ -0,0 +1,34 @@
import { NextResponse } from "next/server";
import { auth, signOut } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { isCloud } from "@/core/edition";
/**
* POST /api/auth/revoke: "sign out everywhere".
*
* Increments the authenticated user's `sessionVersion`, which invalidates every
* existing JWT issued for that user: the auth `jwt` callback compares each
* token's embedded version against the DB on its next use and rejects stale
* ones. Also clears the caller's own session cookie.
*
* Requires an authenticated session. Same-origin only in practice: the session
* cookie is `sameSite=lax`, so a cross-site POST carries no credentials.
*/
export async function POST() {
const session = await auth();
const userId = session?.user?.id;
if (!userId) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// Cloud identities are managed by Supabase; there is no local users row to bump.
if (!isCloud) {
await prisma.user.update({
where: { id: userId },
data: { sessionVersion: { increment: 1 } },
});
}
await signOut({ redirect: false });
return NextResponse.json({ ok: true });
}
+8 -5
View File
@@ -24,6 +24,7 @@ export function BottomPanelManager() {
);
const isCoveredRef = useRef(false);
const isDraggingRef = useRef(false);
useEffect(() => {
if (activeBottomPanel) {
@@ -39,17 +40,18 @@ export function BottomPanelManager() {
}, [activeBottomPanel]);
// Pointer-capture drag handlers — attached directly to the resize handle element.
// Using setPointerCapture ensures pointermove/pointerup are delivered to the
// element even when the pointer leaves it, which is required for webkit
// (without capture, webkit drops synthetic pointermove events from Playwright
// and from fast real-user drags that leave the element bounds).
// setPointerCapture ensures pointermove/pointerup are delivered to the element even
// when the pointer leaves its bounds (required for fast real-user drags and Playwright).
// isDraggingRef guards the move handler instead of hasPointerCapture, which has
// inconsistent behaviour across webkit versions in CI for repeated drag sequences.
const handleResizePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
e.currentTarget.setPointerCapture(e.pointerId);
isDraggingRef.current = true;
document.body.classList.add("is-dragging-bottom-panel");
};
const handleResizePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
if (!e.currentTarget.hasPointerCapture(e.pointerId)) return;
if (!isDraggingRef.current) return;
const newHeight = window.innerHeight - e.clientY;
const clampedHeight = Math.max(120, Math.min(newHeight, window.innerHeight - 100));
setBottomPanelHeight(clampedHeight);
@@ -57,6 +59,7 @@ export function BottomPanelManager() {
const handleResizePointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
e.currentTarget.releasePointerCapture(e.pointerId);
isDraggingRef.current = false;
document.body.classList.remove("is-dragging-bottom-panel");
};
+18
View File
@@ -48,6 +48,24 @@ export const isCloud: boolean = edition === "cloud";
/** True when running as the public demo instance. */
export const isDemo: boolean = edition === "demo";
// ---------------------------------------------------------------------------
// Secure-context detection (https)
// ---------------------------------------------------------------------------
/**
* True when the deployment serves over https, derived from the configured auth
* URL or a production NODE_ENV. This is the request-independent half of the
* secure-context check: the NextAuth cookie WRITER (auth.ts) uses it to decide
* the secure flag / __Secure- cookie prefix, and the edge proxy READER (proxy.ts)
* ORs it with per-request X-Forwarded-Proto / protocol when reading the token.
* Centralised here so the writer and reader can never disagree on which cookie
* name is in play behind a TLS-terminating reverse proxy.
*/
export function isHttpsDeployment(): boolean {
const authUrl = process.env.AUTH_URL ?? process.env.NEXTAUTH_URL ?? "";
return authUrl.startsWith("https://") || process.env.NODE_ENV === "production";
}
// ---------------------------------------------------------------------------
// Demo admin secret (must be before feature flags so they can reference it)
// ---------------------------------------------------------------------------
+45 -1
View File
@@ -18,8 +18,9 @@ vi.unmock("@/lib/auth");
// vi.hoisted() runs before all vi.mock() factories, so the variable is
// defined before the hoisted factory closure captures it.
// ---------------------------------------------------------------------------
const { mockUpsert } = vi.hoisted(() => ({
const { mockUpsert, mockFindUnique } = vi.hoisted(() => ({
mockUpsert: vi.fn().mockResolvedValue(undefined),
mockFindUnique: vi.fn(),
}));
vi.mock("@/lib/db", () => ({
@@ -27,6 +28,7 @@ vi.mock("@/lib/db", () => ({
user: {
upsert: mockUpsert,
findFirst: vi.fn(),
findUnique: mockFindUnique,
},
},
}));
@@ -54,6 +56,7 @@ vi.mock("@/core/edition", () => ({
isDemo: false,
getDemoAdminSecret: vi.fn(() => undefined),
DEMO_ADMIN_ROLE: "demo-admin",
isHttpsDeployment: vi.fn(() => false),
}));
vi.mock("bcryptjs", () => ({ compareSync: vi.fn(() => false) }));
@@ -61,6 +64,7 @@ vi.mock("bcryptjs", () => ({ compareSync: vi.fn(() => false) }));
import {
persistDemoAdminIfNeeded,
ensureLocalUserPersisted,
revalidateSession,
DEMO_ADMIN_ID,
DEMO_ADMIN_EMAIL,
DEMO_ADMIN_NAME,
@@ -148,3 +152,43 @@ describe("persistDemoAdminIfNeeded -- jwt callback guard", () => {
expect(mockUpsert).not.toHaveBeenCalled();
});
});
// ---------------------------------------------------------------------------
// revalidateSession -- authoritative JWT revocation check
// ---------------------------------------------------------------------------
describe("revalidateSession -- jwt revocation check", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("returns null when the token carries no user id", async () => {
const result = await revalidateSession({});
expect(result).toBeNull();
expect(mockFindUnique).not.toHaveBeenCalled();
});
it("returns null when the user no longer exists in the DB (deleted / cross-database token)", async () => {
mockFindUnique.mockResolvedValue(null);
const result = await revalidateSession({ id: "missing-user", sessionVersion: 0 });
expect(result).toBeNull();
});
it("returns null when the token sessionVersion is stale (revoked / logout-everywhere)", async () => {
mockFindUnique.mockResolvedValue({ sessionVersion: 3, role: "user" });
const result = await revalidateSession({ id: "u1", sessionVersion: 2 });
expect(result).toBeNull();
});
it("returns the token with role refreshed when the version matches", async () => {
mockFindUnique.mockResolvedValue({ sessionVersion: 5, role: "admin" });
const result = await revalidateSession({ id: "u1", sessionVersion: 5, role: "user" });
expect(result).not.toBeNull();
expect((result as { role?: string }).role).toBe("admin");
});
it("treats a missing token sessionVersion as 0", async () => {
mockFindUnique.mockResolvedValue({ sessionVersion: 0, role: "user" });
const result = await revalidateSession({ id: "u1" });
expect(result).not.toBeNull();
});
});
+75 -5
View File
@@ -3,8 +3,9 @@ import Credentials from "next-auth/providers/credentials";
import { compareSync } from "bcryptjs";
import { timingSafeEqual } from "crypto";
import { prisma } from "@/lib/db";
import type { JWT } from "next-auth/jwt";
import {
isDemo, isCloud, getDemoAdminSecret, DEMO_ADMIN_ROLE
isDemo, isCloud, getDemoAdminSecret, DEMO_ADMIN_ROLE, isHttpsDeployment
} from "@/core/edition";
import { authConfig } from "@/lib/auth.config";
import { SupabaseAdapter } from "@auth/supabase-adapter";
@@ -91,6 +92,7 @@ const localCredentialsProvider = Credentials({
name: "Demo Admin",
email: "admin",
role: DEMO_ADMIN_ROLE,
sessionVersion: 0,
};
}
@@ -120,15 +122,72 @@ const localCredentialsProvider = Credentials({
name: user.name,
email: user.email,
role: user.role,
sessionVersion: user.sessionVersion,
};
},
});
// True when the deployment serves over https (session cookie gets the secure
// flag / __Secure- prefix). Shared with the edge proxy reader via
// isHttpsDeployment() so the cookie writer and reader never disagree on the
// __Secure- prefix behind a TLS-terminating reverse proxy.
const isSecureDeploy = isHttpsDeployment();
/**
* Authoritative session revocation check, run from the jwt callback on every
* non-sign-in request (local/demo editions). Returns the token unchanged when
* still valid, or `null` to invalidate the session when:
* - the user row no longer exists (deleted, or the token was minted against a
* different database, e.g. another worktree/instance even with a shared
* AUTH_SECRET), or
* - the user's sessionVersion was bumped (logout-everywhere / credential
* rotation), making the token's embedded version stale.
*/
export async function revalidateSession(token: JWT): Promise<JWT | null> {
const userId = token.id;
if (typeof userId !== "string" || !userId) return null;
const dbUser = await prisma.user.findUnique({
where: { id: userId },
select: { sessionVersion: true, role: true },
});
if (!dbUser) return null;
const tokenVersion = typeof token.sessionVersion === "number" ? token.sessionVersion : 0;
if (dbUser.sessionVersion !== tokenVersion) return null;
// Keep role fresh in case it changed server-side since the token was issued.
token.role = dbUser.role;
return token;
}
export const {
handlers, auth, signIn, signOut
} = NextAuth({
...authConfig,
session: { strategy: "jwt" },
session: {
strategy: "jwt",
// Bound the lifetime of the signature-only token. The edge proxy gate
// verifies the JWT signature but cannot reach the DB (no Prisma on the
// edge runtime), so a shorter maxAge limits how long a leaked-but-
// unexpired token can reach pages before the authoritative revocation
// check (revalidateSession) rejects it on any auth() call.
maxAge: 7 * 24 * 60 * 60, // 7 days
updateAge: 24 * 60 * 60, // sliding refresh, at most once per day
},
// Explicit, hardened cookie options. These pin NextAuth's secure defaults so
// they cannot silently regress: httpOnly blocks JS access (XSS token theft),
// sameSite=lax blocks cross-site sends (CSRF), secure requires https in prod.
cookies: {
sessionToken: {
options: {
httpOnly: true,
sameSite: "lax",
path: "/",
secure: isSecureDeploy,
},
},
},
adapter: isCloud ? SupabaseAdapter({
url: process.env.NEXT_PUBLIC_SUPABASE_URL || "http://dummy.supabase.co",
secret: process.env.SUPABASE_SERVICE_ROLE_KEY || "dummy",
@@ -137,21 +196,32 @@ export const {
callbacks: {
...authConfig.callbacks,
async jwt({ token, user }) {
// Initial sign-in: copy identity claims from the authorized user.
if (user) {
token.role = (user as { role?: string }).role ?? "user";
token.role = user.role ?? "user";
token.id = user.id;
// Embed the user's current sessionVersion so the token can be
// compared against the DB on later requests and revoked.
token.sessionVersion = user.sessionVersion ?? 0;
// Persist the demo-admin synthetic identity on first sign-in so
// that the `users` FK target exists for API key creation. Runs
// only when `user` is present (initial sign-in, not token refresh).
// All values inside come from server-controlled constants.
await persistDemoAdminIfNeeded(user.id!, isCloud);
return token;
}
return token;
// Every subsequent request re-validates the token against the DB so
// that deleted users, cross-database tokens, and bumped
// sessionVersions are rejected. Cloud identities live in Supabase
// (no local `users` row), so they skip the Prisma comparison.
if (isCloud) return token;
return revalidateSession(token);
},
async session({ session, token }) {
if (session.user) {
session.user.id = token.id as string;
(session.user as { role?: string }).role = token.role as string;
session.user.role = token.role as string | undefined;
}
return session;
},
+97 -25
View File
@@ -2,11 +2,62 @@
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";
import { isDemo } from "@/core/edition";
import { isDemo, isHttpsDeployment } from "@/core/edition";
const workspaceCache = new Map<string, { status: string; expiresAt: number }>();
const CACHE_TTL = 60_000; // 60 seconds
// Anchored static-asset allowlist. Only requests ending in a real asset
// extension bypass the auth gate. This replaces the former `path.includes(".")`
// check, which let ANY dotted path (e.g. `/secret.page`, `/globe.config`)
// skip authentication entirely.
const STATIC_ASSET_RE = /\.(?:js|mjs|cjs|css|map|json|txt|xml|webmanifest|ico|png|jpe?g|gif|svg|webp|avif|bmp|woff2?|ttf|otf|eot|wasm|mp4|webm|glb|gltf)$/i;
// API routes that must stay reachable WITHOUT a logged-in session cookie.
// Everything else under /api is deny-by-default (requires a valid session JWT).
// - auth/internal/health/billing-webhook: pre-login, server-to-server, infra, or external callers.
// - mcp/globe/v1-entities: dual-auth routes that self-guard via Bearer API key
// (programmatic clients send no session cookie, so the gate must not block them).
// - marketplace/*: every marketplace route self-guards. validateMarketplaceAuth
// accepts a cross-origin Bearer marketplace JWT (callers send no session cookie),
// auth() guards the same-origin routes, and sideload is NODE_ENV-gated to dev.
// Gating the prefix here would 401 those cross-origin Bearer/preflight requests
// before their own auth runs, breaking install/manage from the marketplace origin.
// - glitchtip-tunnel/build/dev: telemetry/diagnostics (dev/* is NODE_ENV-gated to 403 in prod).
const PUBLIC_API_PREFIXES = [
"/api/auth",
"/api/internal/workspace",
"/api/health",
"/api/billing/webhook",
"/api/mcp",
"/api/globe",
"/api/v1/entities",
"/api/marketplace",
"/api/glitchtip-tunnel",
"/api/build",
"/api/dev",
];
function isPublicApiPath(path: string): boolean {
return PUBLIC_API_PREFIXES.some((p) => path === p || path.startsWith(`${p}/`));
}
// Resolve the Auth.js session token, handling the __Secure- cookie prefix used
// behind a TLS-terminating reverse proxy (the public URL is https but the
// request reaching us may be plain http). Detect via X-Forwarded-Proto / AUTH_URL.
async function getSessionToken(req: NextRequest) {
// Request-aware OR the deploy-wide https signal (isHttpsDeployment), so the
// reader agrees with the cookie writer (auth.ts) on the __Secure- prefix.
const isSecure = req.headers.get("x-forwarded-proto") === "https"
|| isHttpsDeployment()
|| req.nextUrl.protocol === "https:";
return getToken({
req,
secret: process.env.AUTH_SECRET,
secureCookie: isSecure,
});
}
async function resolveWorkspace(subdomain: string) {
const cached = workspaceCache.get(subdomain);
if (cached && Date.now() < cached.expiresAt) return cached;
@@ -62,16 +113,49 @@ export default async function proxy(req: NextRequest) {
return res;
}
// Static assets, API routes, data files — always pass through.
// Strip any client-supplied x-tenant-subdomain on /api/* before forwarding,
// then re-inject only the server-resolved value (H2: tenant-header spoof prevention).
// A forged header must never reach the Prisma tenant extension.
// API routes: DENY BY DEFAULT. Evaluated BEFORE the static-asset allowlist so
// that no `/api/...` path ending in an asset-like extension (e.g. a catch-all
// segment such as `/api/x/y.json`) can match the static fast-path and skip the
// gate. Public/self-guarded routes pass through; every other /api route requires
// a valid session JWT (else 401 JSON). This closes the former blanket `/api`
// pass-through that left unauthenticated data proxies (places/*, camera/test,
// earthquake, iss*, weather*, ...) open and burning server-held upstream keys.
if (path.startsWith("/api")) {
const res = NextResponse.next();
// Always drop a client-supplied tenant header; only the server-resolved
// value may be forwarded (H2: tenant-header spoof prevention).
res.headers.delete("x-tenant-subdomain");
// CORS preflight is credential-less by design (no cookie, no Authorization
// header), so gating it would 401 the preflight and break every cross-origin
// API route before its real request is ever sent. Let OPTIONS through; the
// route's own OPTIONS/CORS handler answers it (no body, nothing to leak).
if (req.method === "OPTIONS") return res;
if (isPublicApiPath(path)) {
if (tenantSubdomain) res.headers.set("x-tenant-subdomain", tenantSubdomain);
return res;
}
const apiToken = await getSessionToken(req);
if (apiToken) {
if (tenantSubdomain) res.headers.set("x-tenant-subdomain", tenantSubdomain);
return res;
}
return NextResponse.json(
{ error: "Unauthorized" },
{ status: 401, headers: { "WWW-Authenticate": "Bearer" } },
);
}
// Static assets and internal data dirs always pass through (no auth).
// Static files match an explicit extension allowlist instead of the old,
// bypass-prone `path.includes(".")` (which let any dotted path skip the gate).
if (
path.startsWith("/_next")
|| path.startsWith("/api")
|| path.startsWith("/data")
|| path.startsWith("/cesium")
|| path.includes(".")
|| STATIC_ASSET_RE.test(path)
) {
const res = NextResponse.next();
res.headers.delete("x-tenant-subdomain");
@@ -91,7 +175,7 @@ export default async function proxy(req: NextRequest) {
}
}
// Auth pages — always accessible
// Auth pages: always accessible
if (path.startsWith("/setup") || path.startsWith("/login")) {
const res = NextResponse.next();
if (tenantSubdomain) res.headers.set("x-tenant-subdomain", tenantSubdomain);
@@ -106,30 +190,18 @@ export default async function proxy(req: NextRequest) {
}
}
// Check JWT session from Auth.js cookie.
// Behind a TLS-terminating reverse proxy, the cookie was set with the
// `__Secure-` prefix (because the public URL is https), but the request
// reaching us is plain http, so getToken's auto-detection looks for the
// unprefixed name and misses it. Detect via X-Forwarded-Proto / AUTH_URL.
const xfProto = req.headers.get("x-forwarded-proto");
const authUrl = process.env.AUTH_URL ?? process.env.NEXTAUTH_URL ?? "";
const isSecure = xfProto === "https"
|| authUrl.startsWith("https://")
|| req.nextUrl.protocol === "https:";
const token = await getToken({
req,
secret: process.env.AUTH_SECRET,
secureCookie: isSecure,
});
// Check the Auth.js session cookie for page requests (the helper handles the
// __Secure- cookie prefix used behind a TLS-terminating reverse proxy).
const token = await getSessionToken(req);
if (token) {
// User is logged in — allow through
// User is logged in, allow through
const res = NextResponse.next();
if (tenantSubdomain) res.headers.set("x-tenant-subdomain", tenantSubdomain);
return res;
}
// Not logged in — check if first-run (no users)
// Not logged in: check if first-run (no users)
try {
const appUrl = process.env.NEXT_PUBLIC_APP_URL || process.env.APP_URL || `http://127.0.0.1:${process.env.PORT || "3000"}`;
const url = new URL("/api/auth/setup-status", appUrl);
+29
View File
@@ -0,0 +1,29 @@
import type { DefaultSession } from "next-auth";
/**
* Module augmentation for NextAuth/Auth.js. The app carries a per-user `role`
* and a `sessionVersion` (used for session revocation) on the authorized user,
* the session, and the JWT. Declaring them here makes those fields first-class
* and removes the need for `as { role?: string }` casts throughout auth.ts.
*/
declare module "next-auth" {
interface User {
role?: string;
sessionVersion?: number;
}
interface Session {
user: {
id: string;
role?: string;
} & DefaultSession["user"];
}
}
declare module "next-auth/jwt" {
interface JWT {
id?: string;
role?: string;
sessionVersion?: number;
}
}