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
d8c183a
fix(auth): require email verification to prevent account takeover dur…
tembo[bot] Feb 13, 2026
56b6812
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
16 changes: 15 additions & 1 deletion apps/server/convex/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,25 @@ export const createAuth = (
// Use Convex site URL as baseURL so OAuth callbacks work correctly
baseURL: convexSiteUrl,
database: authComponent.adapter(ctx),
// TODO: add email verification (requireEmailVerification + sendVerificationEmail)
emailAndPassword: {
enabled: true,
minPasswordLength: 8,
maxPasswordLength: 128,
// SECURITY: Require verified email to prevent account takeover via
// unverified email registration exploiting email-based migration linking (OSS-37)
requireEmailVerification: true,
sendResetPassword: async ({ user, url }: { user: { email: string }; url: string }) => {
// TODO: integrate with email provider (e.g., Resend, SendGrid)
console.log(`[Auth] Password reset requested for ${user.email}: ${url}`);

@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: Security: Password reset URL (containing a secret token) is logged to console/stdout. Anyone with access to server logs could use this URL to reset a user's password, which undermines the security fix this PR introduces. At minimum, avoid logging the full URL — or use a structured logger with appropriate log levels so this is suppressed in production.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/server/convex/auth.ts, line 97:

<comment>Security: Password reset URL (containing a secret token) is logged to console/stdout. Anyone with access to server logs could use this URL to reset a user's password, which undermines the security fix this PR introduces. At minimum, avoid logging the full URL — or use a structured logger with appropriate log levels so this is suppressed in production.</comment>

<file context>
@@ -85,11 +85,25 @@ export const createAuth = (
+			requireEmailVerification: true,
+			sendResetPassword: async ({ user, url }: { user: { email: string }; url: string }) => {
+				// TODO: integrate with email provider (e.g., Resend, SendGrid)
+				console.log(`[Auth] Password reset requested for ${user.email}: ${url}`);
+			},
+		},
</file context>
Fix with Cubic

},
},
emailVerification: {
sendOnSignUp: true,
sendVerificationEmail: async ({ user, url }: { user: { email: string }; url: string }) => {
// TODO: integrate with email provider (e.g., Resend, SendGrid)
// For now, log the verification URL for development/debugging
console.log(`[Auth] Verification email for ${user.email}: ${url}`);
},
},
socialProviders: {
// Only include GitHub OAuth if credentials are configured
Expand Down
26 changes: 25 additions & 1 deletion apps/server/convex/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,16 @@ export const ensure = mutation({

// MIGRATION: Link WorkOS users to Better Auth by email
// Uses .first() since duplicate emails may exist from prior migrations
<<<<<<< HEAD
// SECURITY: Only link if the caller's email is verified to prevent account takeover
// via unverified email registration (see OSS-37)
const isEmailVerified = identity.emailVerified ?? false;
if (!existing && args.email && isEmailVerified && Date.now() < EMAIL_LINK_MIGRATION_DEADLINE_MS) {
||||||| 54e09ce
if (!existing && args.email) {
=======
if (!existing && args.email && Date.now() < EMAIL_LINK_MIGRATION_DEADLINE_MS) {
>>>>>>> main
const existingByEmail = await ctx.db
.query("users")
.withIndex("by_email", (q) => q.eq("email", args.email))
Expand All @@ -107,8 +116,11 @@ export const ensure = mutation({
updatedAt: Date.now(),
});
existing = existingByEmail;
console.log(`[Auth Migration] Linked user ${args.email} from WorkOS to Better Auth`);
console.log(`[Auth Migration] Linked user ${args.email} from WorkOS to Better Auth (email verified)`);
}
} else if (!existing && args.email && !isEmailVerified && Date.now() < EMAIL_LINK_MIGRATION_DEADLINE_MS) {
// Log attempts to link with unverified email for security monitoring
console.warn(`[Auth Migration] Blocked linking for unverified email ${args.email} (potential account takeover attempt)`);
}

const now = Date.now();
Expand Down Expand Up @@ -264,6 +276,11 @@ export const getByExternalId = query({
profile?.encryptedOpenRouterKey ?? user.encryptedOpenRouterKey,
=======
<<<<<<< HEAD
||||||| 54e09ce
encryptedOpenRouterKey:
profile?.encryptedOpenRouterKey ?? user.encryptedOpenRouterKey,
=======
<<<<<<< HEAD
||||||| 54e09ce
encryptedOpenRouterKey:
profile?.encryptedOpenRouterKey ?? user.encryptedOpenRouterKey,
Expand All @@ -274,6 +291,7 @@ export const getByExternalId = query({
>>>>>>> main
>>>>>>> main
>>>>>>> main
>>>>>>> main
>>>>>>> main
fileUploadCount: profile?.fileUploadCount ?? user.fileUploadCount ?? 0,
aiUsageCents: user.aiUsageCents,
Expand Down Expand Up @@ -378,6 +396,11 @@ export const getByExternalIdInternal = internalQuery({
profile?.encryptedOpenRouterKey ?? user.encryptedOpenRouterKey,
=======
<<<<<<< HEAD
||||||| 54e09ce
encryptedOpenRouterKey:
profile?.encryptedOpenRouterKey ?? user.encryptedOpenRouterKey,
=======
<<<<<<< HEAD
||||||| 54e09ce
encryptedOpenRouterKey:
profile?.encryptedOpenRouterKey ?? user.encryptedOpenRouterKey,
Expand All @@ -388,6 +411,7 @@ export const getByExternalIdInternal = internalQuery({
>>>>>>> main
>>>>>>> main
>>>>>>> main
>>>>>>> main
>>>>>>> main
fileUploadCount: profile?.fileUploadCount ?? user.fileUploadCount ?? 0,
aiUsageCents: user.aiUsageCents,
Expand Down
94 changes: 94 additions & 0 deletions apps/web/src/routes/api/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,99 @@ async function fetchModelsFromOpenRouter(): Promise<Response> {
}
}

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") {
const forwardedFor = request.headers.get("x-forwarded-for")?.trim();
if (forwardedFor) {
const first = forwardedFor.split(",")[0]?.trim();
if (first) return first;
||||||| 54e09ce
=======
<<<<<<< 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;
Expand Down Expand Up @@ -617,6 +710,7 @@ function getClientIp(request: Request): string | null {
const first = forwardedFor.split(",")[0]?.trim();
if (first) return first;
>>>>>>> main
>>>>>>> main
>>>>>>> main
}
return null;
Expand Down
Loading