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
21 changes: 21 additions & 0 deletions next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,27 @@ const securityHeaders = [
key: "Permissions-Policy",
value: "camera=(), microphone=(), geolocation=(), payment=()",
},
{
key: "Cross-Origin-Opener-Policy",
value: "same-origin",
},
{
key: "Cross-Origin-Embedder-Policy",
value: "credentialless",
},
{
key: "Cross-Origin-Resource-Policy",
value: "same-origin",
},
// HSTS only in production so local HTTP development keeps working.
...(isDev
? []
: [
{
key: "Strict-Transport-Security",
value: "max-age=63072000; includeSubDomains; preload",
},
]),
];

const nextConfig = {
Expand Down
55 changes: 46 additions & 9 deletions src/components/shared/wallet-error-banner.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,51 @@
"use client";

import { useEffect, useState } from "react";
import { AlertTriangle, X, ExternalLink } from "lucide-react";
import type { WalletError } from "@/lib/hooks/use-auth";
import { getSelectedWalletId, type WalletProviderId } from "@/lib/stellar/wallet";

interface WalletErrorBannerProps {
error: WalletError;
onDismiss: () => void;
onRetry?: () => void;
}

const WALLET_INSTALL_LINKS: Record<
WalletProviderId,
{ name: string; url: string }
> = {
freighter: { name: "Freighter", url: "https://www.freighter.app/" },
lobstr: { name: "LOBSTR", url: "https://lobstr.co/" },
rabet: { name: "Rabet", url: "https://rabet.io/" },
};

const ALL_WALLETS = Object.values(WALLET_INSTALL_LINKS);

function resolveInstallLinks(
walletId: string | null
): Array<{ name: string; url: string }> {
if (walletId && walletId in WALLET_INSTALL_LINKS) {
return [
WALLET_INSTALL_LINKS[walletId as WalletProviderId],
];
}
return ALL_WALLETS;
}

export function WalletErrorBanner({
error,
onDismiss,
onRetry,
}: WalletErrorBannerProps) {
const [walletId, setWalletId] = useState<string | null>(null);

useEffect(() => {
setWalletId(getSelectedWalletId());
}, []);

const installLinks = resolveInstallLinks(walletId);

return (
<div
role="alert"
Expand All @@ -25,15 +57,20 @@ export function WalletErrorBanner({
<p className="text-sm font-medium text-red-800">{error.message}</p>
<p className="text-sm text-red-600 mt-1">{error.resolution}</p>
{error.type === "not_installed" && (
<a
href="https://www.freighter.app/"
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-sm text-red-700 underline mt-2 hover:text-red-900"
>
Get Freighter
<ExternalLink className="h-3 w-3" />
</a>
<div className="mt-2 flex flex-wrap gap-x-3 gap-y-1">
{installLinks.map((wallet) => (
<a
key={wallet.name}
href={wallet.url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-sm text-red-700 underline hover:text-red-900"
>
Get {wallet.name}
<ExternalLink className="h-3 w-3" />
</a>
))}
</div>
)}
{onRetry && (
<button
Expand Down
37 changes: 36 additions & 1 deletion src/lib/api/client.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { apiClient, isAbortError } from "./client";
import { apiClient, hashJwtForCacheKey, isAbortError } from "./client";
import { useErrorStore } from "@/store/error-store";

// zustand's persist middleware writes on every set(); jsdom's localStorage is
Expand Down Expand Up @@ -447,3 +447,38 @@ describe("apiClient cache behaviour (issue #312)", () => {
});
});

// ── Issue #542: JWT must not appear in cache keys ────────────────────────────

describe("apiClient cache keys (issue #542)", () => {
const sampleJwt =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyLTEif0.signature";

it("does not embed the raw JWT in the hashed cache key component", () => {
const hashed = hashJwtForCacheKey(sampleJwt);

expect(hashed).not.toContain(sampleJwt);
expect(hashed).not.toContain("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9");
expect(hashed).not.toContain("signature");
});

it("hashes deterministically so cache hit/miss behaviour is unchanged", () => {
expect(hashJwtForCacheKey(sampleJwt)).toBe(hashJwtForCacheKey(sampleJwt));
});

it("distinguishes different tokens", () => {
expect(hashJwtForCacheKey("token-a")).not.toBe(hashJwtForCacheKey("token-b"));
});

it("serves a cache hit for the same token and a miss for a different one", async () => {
fetchMock.mockResolvedValueOnce(jsonResponse({ data: "user-1" }));
await apiClient.get("/cache-jwt", "jwt-user-1");
await apiClient.get("/cache-jwt", "jwt-user-1");
expect(fetchMock).toHaveBeenCalledTimes(1);

fetchMock.mockResolvedValueOnce(jsonResponse({ data: "user-2" }));
const other = await apiClient.get("/cache-jwt", "jwt-user-2");
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(other).toEqual({ data: "user-2" });
});
});

19 changes: 18 additions & 1 deletion src/lib/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,23 @@ type CacheEntry = {
expiresAt: number;
};

/**
* Fast non-cryptographic digest of a JWT for cache keying (#542).
* Two independent FNV-1a streams yield a 64-bit hex digest so the raw
* token never appears in heap-dumpable cache key strings, while cache
* hit/miss behaviour stays deterministic per token.
*/
export function hashJwtForCacheKey(jwt: string): string {
let h1 = 0x811c9dc5;
let h2 = 0x01000193;
for (let i = 0; i < jwt.length; i++) {
const c = jwt.charCodeAt(i);
h1 = Math.imul(h1 ^ c, 0x01000193);
h2 = Math.imul(h2 ^ c, 0x85ebca6b);
}
return `${(h1 >>> 0).toString(16)}${(h2 >>> 0).toString(16)}`;
}

const responseCache = new Map<string, CacheEntry>();

/**
Expand Down Expand Up @@ -377,7 +394,7 @@ class ApiClient {
}

private cacheKey(url: string, jwt?: string): string {
return jwt ? `${url}|${jwt}` : url;
return jwt ? `${url}|${hashJwtForCacheKey(jwt)}` : url;
}

/**
Expand Down
53 changes: 53 additions & 0 deletions src/middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,59 @@ describe("auth routes", () => {
});
});

describe("open redirect protection (#541)", () => {
it("rejects an absolute https URL in the redirect parameter", () => {
const target = redirectTarget(
middleware(makeRequest("/connect", "jwt-abc", "?redirect=https://evil.com"))
);

expect(target?.pathname).toBe("/dashboard");
expect(target?.hostname).not.toBe("evil.com");
});

it("rejects an absolute http URL with a path", () => {
const target = redirectTarget(
middleware(
makeRequest("/connect", "jwt-abc", "?redirect=http://evil.com/phish")
)
);

expect(target?.pathname).toBe("/dashboard");
});

it("rejects a protocol-relative URL", () => {
const target = redirectTarget(
middleware(makeRequest("/connect", "jwt-abc", "?redirect=//evil.com"))
);

expect(target?.pathname).toBe("/dashboard");
});

it("rejects a backslash-based open redirect", () => {
const target = redirectTarget(
middleware(makeRequest("/connect", "jwt-abc", "?redirect=/%5Cevil.com"))
);

expect(target?.pathname).toBe("/dashboard");
});

it("still honours a safe relative path", () => {
const target = redirectTarget(
middleware(makeRequest("/connect", "jwt-abc", "?redirect=/courses/course-1/quiz"))
);

expect(target?.pathname).toBe("/courses/course-1/quiz");
});

it("falls back to /dashboard when redirect is empty", () => {
const target = redirectTarget(
middleware(makeRequest("/connect", "jwt-abc", "?redirect="))
);

expect(target?.pathname).toBe("/dashboard");
});
});

describe("matcher", () => {
it("covers every protected area and both auth routes", () => {
expect(config.matcher).toEqual(
Expand Down
22 changes: 21 additions & 1 deletion src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,26 @@ function isAuthRoute(pathname: string): boolean {
return AUTH_PREFIXES.some((prefix) => pathname.startsWith(prefix));
}

/**
* Reject open-redirect targets (#541). Only same-origin relative paths are
* allowed: must start with a single "/", must not be protocol-relative
* ("//evil.com"), and must not embed a scheme ("https://evil.com").
*/
function isSafeRedirectPath(redirect: string | null): redirect is string {
if (!redirect) return false;
if (!redirect.startsWith("/")) return false;
if (redirect.startsWith("//")) return false;
if (redirect.includes("://")) return false;
if (redirect.includes("\\")) return false;
return true;
}

/**
* Decode JWT payload and check expiry (#495).
* Uses atob() for base64 decoding — works in Edge runtime.
* Malformed tokens are treated as expired.
*/
function isJwtExpired(token: string): boolean {
/** Validate JWT structure and expiry; signature verification remains server-side. */
function isValidSessionToken(token: string): boolean {
try {
Expand Down Expand Up @@ -124,7 +144,7 @@ export function middleware(request: NextRequest) {
if (validSession) {
const redirect = request.nextUrl.searchParams.get("redirect");
const url = request.nextUrl.clone();
url.pathname = redirect || "/dashboard";
url.pathname = isSafeRedirectPath(redirect) ? redirect : "/dashboard";
url.searchParams.delete("redirect");
return NextResponse.redirect(url);
}
Expand Down
Loading