Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
8628be1
Investigate Convex Upstash warnings
leoisadev1 Feb 11, 2026
a626c43
Investigate Convex Upstash warnings
leoisadev1 Feb 11, 2026
88366b2
Merge remote-tracking branch 'origin/add-upstash-rate-limits-and' int…
leoisadev1 Feb 11, 2026
9162dc0
Apply Cubic AI review suggestions
leoisadev1 Feb 11, 2026
9393e14
Address Cubic follow-up findings
leoisadev1 Feb 11, 2026
7cb6edd
fix(security): harden workflow endpoints and rate-limit checks
leoisadev1 Feb 11, 2026
3b59d07
fix(security): address remaining review findings
leoisadev1 Feb 11, 2026
1ba1454
fix(security): address all remaining Cubic + Tembo review findings
leoisadev1 Feb 11, 2026
6b80816
fix(security): use HMAC+timingSafeEqual for cleanup token comparison
leoisadev1 Feb 11, 2026
ee54eec
fix(security): extract cleanup action to node runtime, fix auth bypas…
leoisadev1 Feb 11, 2026
8302416
fix(security): stop forwarding cookies to QStash, add rate limiting a…
leoisadev1 Feb 11, 2026
4f97319
fix(security): fix parser passthrough, remove hardcoded HMAC keys, ha…
leoisadev1 Feb 11, 2026
04de610
fix(security): add NaN guard to bounds validation, log fetch errors
leoisadev1 Feb 11, 2026
76c4e04
fix(security): remove workflow token persistence and harden cleanup/m…
leoisadev1 Feb 11, 2026
7c103dc
fix(security): consume workflow auth refs once and harden error/rate …
leoisadev1 Feb 11, 2026
8e696e5
fix(security): harden fail-closed limits and workflow retries
leoisadev1 Feb 11, 2026
537b548
Fix: Broken access control in chat stream init (#621)
tembo[bot] Feb 12, 2026
8034851
fix(security): close auth fallback and token replay gaps
leoisadev1 Feb 12, 2026
0f4e92f
fix(security): reduce workflow secret exposure and endpoint hazards
leoisadev1 Feb 12, 2026
ec3519e
fix(security): stabilize workflow auth and endpoint safeguards
leoisadev1 Feb 12, 2026
664efc2
fix(security): enforce signed workflow callbacks and safer parsing
leoisadev1 Feb 12, 2026
e535f6b
fix(security): harden stream limits and workflow error surfaces
leoisadev1 Feb 12, 2026
770d822
fix(web): restore generic proxy IP extraction path
leoisadev1 Feb 12, 2026
795001a
fix(security): fail closed when usage reserve is unavailable
leoisadev1 Feb 12, 2026
ebd3049
fix(security): reject empty workflow auth tokens
leoisadev1 Feb 12, 2026
059948e
fix(security): harden workflow mode selection and model headers
leoisadev1 Feb 12, 2026
d200d7c
fix(security): restrict cookie fallback and keep key off qstash
leoisadev1 Feb 12, 2026
48ca3c4
fix(security): tighten cleanup auth and usage safeguards
leoisadev1 Feb 12, 2026
7b5d722
fix(security): tighten workflow and error handling responses
leoisadev1 Feb 12, 2026
020fefa
fix(security): tighten workflow token and usage edge cases
leoisadev1 Feb 12, 2026
826a74b
fix(web): execute chat exports inline for reliable delivery
leoisadev1 Feb 12, 2026
76f7360
fix(web): tighten workflow validation and retry behavior
leoisadev1 Feb 12, 2026
37c88fb
fix(web): harden export workflow payload guards
leoisadev1 Feb 12, 2026
4575997
fix(security): harden workflow callback and auth safeguards
leoisadev1 Feb 12, 2026
ec1e22a
fix(web): clean up workflow validation and rate-limit UX
leoisadev1 Feb 12, 2026
c048027
fix(web): enforce models fallback limit and workflow callback host
leoisadev1 Feb 12, 2026
3500ca5
fix(web): harden model IP gating and workflow title sanitization
leoisadev1 Feb 12, 2026
bb0e999
fix(security): tighten workflow auth fallback and usage counters
leoisadev1 Feb 12, 2026
0a44f88
fix: resolve merge conflict — keep chat.ts deleted (moved to workflow)
leoisadev1 Feb 12, 2026
3871cbc
fix: resolve all Cubic review findings
leoisadev1 Feb 12, 2026
181af3f
Merge pull request #622 from opencoredev/add-upstash-rate-limits-and
leoisadev1 Feb 12, 2026
6722ceb
fix(server): retain deprecated jonMode/dynamicPrompt in schema for ex…
leoisadev1 Feb 12, 2026
621899b
fix(prompt-draft): migrate draft storage from localStorage to session…
tembo[bot] Feb 13, 2026
394083f
Merge main
leoisadev1 Feb 14, 2026
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
12 changes: 12 additions & 0 deletions apps/server/convex/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,12 +244,18 @@ export const getByExternalId = query({
profile?.encryptedOpenRouterKey ?? user.encryptedOpenRouterKey,
=======
<<<<<<< HEAD
||||||| 54e09ce
encryptedOpenRouterKey:
profile?.encryptedOpenRouterKey ?? user.encryptedOpenRouterKey,
=======
<<<<<<< HEAD
||||||| 54e09ce
encryptedOpenRouterKey:
profile?.encryptedOpenRouterKey ?? user.encryptedOpenRouterKey,
=======
hasOpenRouterKey: !!(profile?.encryptedOpenRouterKey ?? user.encryptedOpenRouterKey),
>>>>>>> main
>>>>>>> main
>>>>>>> main
fileUploadCount: profile?.fileUploadCount ?? user.fileUploadCount ?? 0,
aiUsageCents: user.aiUsageCents,
Expand Down Expand Up @@ -334,12 +340,18 @@ export const getByExternalIdInternal = internalQuery({
profile?.encryptedOpenRouterKey ?? user.encryptedOpenRouterKey,
=======
<<<<<<< HEAD
||||||| 54e09ce
encryptedOpenRouterKey:
profile?.encryptedOpenRouterKey ?? user.encryptedOpenRouterKey,
=======
<<<<<<< HEAD
||||||| 54e09ce
encryptedOpenRouterKey:
profile?.encryptedOpenRouterKey ?? user.encryptedOpenRouterKey,
=======
hasOpenRouterKey: !!(profile?.encryptedOpenRouterKey ?? user.encryptedOpenRouterKey),
>>>>>>> main
>>>>>>> main
>>>>>>> main
fileUploadCount: profile?.fileUploadCount ?? user.fileUploadCount ?? 0,
aiUsageCents: user.aiUsageCents,
Expand Down
6 changes: 3 additions & 3 deletions apps/web/src/hooks/use-prompt-draft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { useCallback, useEffect, useRef } from "react";
import { usePromptDraftStore } from "@/stores/prompt-draft";

/**
* Hook for syncing prompt input with localStorage-backed draft persistence.
* Hook for syncing prompt input with sessionStorage-backed draft persistence.
*
* Features:
* - Debounced saves (300ms) to avoid excessive localStorage writes
* - Debounced saves (300ms) to avoid excessive storage writes
* - Per-chat drafts (chatId can be null for new chat)
* - Auto-restores draft on mount
* - Auto-clears draft on unmount when text is empty
Expand Down Expand Up @@ -68,7 +68,7 @@ export function usePromptDraft({ chatId, textInputController }: UsePromptDraftOp
clearStoredDraft(chatId);
}, [chatId, clearStoredDraft]);

// Sync text changes to localStorage (debounced)
// Sync text changes to sessionStorage (debounced)
// Using chatId and setDraft directly to avoid re-running on saveDraft recreation
useEffect(() => {
// Only save after initial restoration
Expand Down
90 changes: 90 additions & 0 deletions apps/web/src/routes/api/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,95 @@ const OPENROUTER_MODELS_URL = "https://openrouter.ai/api/v1/models";
const OPENROUTER_FETCH_TIMEOUT_MS = 10_000;
const TRUST_PROXY_MODE = process.env.TRUST_PROXY?.trim().toLowerCase();

<<<<<<< HEAD
if (TRUST_PROXY_MODE === "true") {
console.warn("[Models API] TRUST_PROXY=true requires x-forwarded-for for rate limiting");
}

if (!TRUST_PROXY_MODE) {
console.warn("[Models API] TRUST_PROXY is unset; models endpoint will reject requests when IP is unavailable");
}

if (
TRUST_PROXY_MODE &&
TRUST_PROXY_MODE !== "cloudflare" &&
TRUST_PROXY_MODE !== "vercel" &&
TRUST_PROXY_MODE !== "true"
) {
console.warn("[Models API] Unrecognized TRUST_PROXY value; models endpoint will reject requests when IP is unavailable");
}

const modelsIpRatelimit = upstashRedis
? new Ratelimit({
redis: upstashRedis,
limiter: Ratelimit.slidingWindow(30, "60 s"),
prefix: "ratelimit:models:ip",
})
: null;

async function fetchModelsFromOpenRouter(): Promise<Response> {
try {
const response = await fetch(OPENROUTER_MODELS_URL, {
headers: {
Accept: "application/json",
},
signal: AbortSignal.timeout(OPENROUTER_FETCH_TIMEOUT_MS),
});

if (!response.ok) {
return json(
{ error: "Upstream service error" },
{ status: 502 },
);
}

const payload = await response.text();

if (upstashRedis) {
try {
await upstashRedis.set(MODELS_CACHE_KEY, payload, {
ex: MODELS_CACHE_TTL_SECONDS,
});
} catch (error) {
console.warn("[Models API] Failed to write cache:", error);
}
}

return new Response(payload, {
status: 200,
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-store",
},
});
} catch (error) {
console.warn("[Models API] OpenRouter fetch failed:", error);
return json({ error: "Upstream service unavailable" }, { status: 502 });
}
}

function getClientIp(request: Request): string | null {
if (!TRUST_PROXY_MODE) {
return null;
}

if (TRUST_PROXY_MODE === "cloudflare") {
const cfConnectingIp = request.headers.get("cf-connecting-ip")?.trim();
return cfConnectingIp || null;
}

if (TRUST_PROXY_MODE === "vercel") {
const vercelForwardedFor = request.headers.get("x-vercel-forwarded-for")?.trim();
if (vercelForwardedFor) {
const first = vercelForwardedFor.split(",")[0]?.trim();
if (first) return first;
}
return null;
}

if (TRUST_PROXY_MODE === "true") {
||||||| 54e09ce
=======
<<<<<<< HEAD
/**
* TRUSTED_PROXIES: comma-separated list of trusted proxy IPs.
Expand Down Expand Up @@ -218,6 +307,7 @@ function getClientIp(request: Request): string | null {
}

if (TRUST_PROXY_MODE === "true") {
>>>>>>> main
>>>>>>> main
const forwardedFor = request.headers.get("x-forwarded-for")?.trim();
if (forwardedFor) {
Expand Down
13 changes: 9 additions & 4 deletions apps/web/src/stores/prompt-draft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,20 @@ import { create } from "zustand";
import { createJSONStorage, devtools, persist } from "zustand/middleware";

/**
* Store for persisting prompt drafts across page reloads.
* Store for persisting prompt drafts within the current browser session.
*
* Security: Uses sessionStorage instead of localStorage to limit exposure
* of sensitive draft content. Drafts are automatically cleared when the
* browser tab is closed, reducing the risk of exfiltration via XSS or
* compromised browser profiles.
*
* Non-annoying approach:
* - Drafts are saved per-chat (or "global" for new chat input)
* - Drafts are automatically cleared when a message is sent
* - Old drafts are cleaned up after 7 days to prevent localStorage bloat
* - Old drafts are cleaned up after 24 hours as a defensive measure
*/

const DRAFT_EXPIRY_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
const DRAFT_EXPIRY_MS = 24 * 60 * 60 * 1000; // 24 hours (session-scoped, defensive expiry)
const GLOBAL_DRAFT_KEY = "__global__";

interface PromptDraft {
Expand Down Expand Up @@ -115,7 +120,7 @@ export const usePromptDraftStore = create<PromptDraftState>()(
}),
{
name: "openchat-prompt-drafts",
storage: createJSONStorage(() => localStorage),
storage: createJSONStorage(() => sessionStorage),

@cubic-dev-ai cubic-dev-ai Bot Feb 14, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Switching to sessionStorage doesn't remove previously stored drafts from localStorage. Existing sensitive draft data under the "openchat-prompt-drafts" key will persist indefinitely in localStorage, undermining the security improvement this PR intends to make. Add a one-time migration cleanup to remove the old localStorage entry.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/src/stores/prompt-draft.ts, line 123:

<comment>Switching to `sessionStorage` doesn't remove previously stored drafts from `localStorage`. Existing sensitive draft data under the `"openchat-prompt-drafts"` key will persist indefinitely in `localStorage`, undermining the security improvement this PR intends to make. Add a one-time migration cleanup to remove the old `localStorage` entry.</comment>

<file context>
@@ -115,7 +120,7 @@ export const usePromptDraftStore = create<PromptDraftState>()(
 			{
 				name: "openchat-prompt-drafts",
-				storage: createJSONStorage(() => localStorage),
+				storage: createJSONStorage(() => sessionStorage),
 			},
 		),
</file context>
Fix with Cubic

},
),
{ name: "prompt-draft-store" },
Expand Down
Loading