Skip to content

Conversation

@yasuo72
Copy link

@yasuo72 yasuo72 commented Feb 9, 2026

This PR addresses critical security issues and improves overall code quality:

Security Fixes

  • XSS Vulnerability: Fixed in embed page by sanitizing user input with DOMPurify
  • Only allows <span> tags with class attributes, preventing malicious HTML injection

Code Quality Improvements

  • Logging Infrastructure: Replaced 877+ console.log/error/warn statements with Pino-based logger
  • Added convenience logging functions for quality checks, embeddings, webhooks, and AI operations
  • Improved error handling and debugging capabilities

TypeScript Improvements

  • Fixed implicit any types in auth module with proper ExtendedAdapterUser interface
  • Fixed implicit any types in prompts route API handlers
  • Removed deprecated getConfiguredAuthPlugin() function
  • Resolved tsconfig.json type definition warnings

New Features

  • Added validateEnvironment() function to validate required environment variables at startup
  • Validates: DATABASE_URL, NEXTAUTH_SECRET, NEXTAUTH_URL
  • Warns about optional variables: OPENAI_API_KEY, GOOGLE_ANALYTICS_ID

Changes

  • 11 files modified, 193 insertions, 62 deletions
  • Added DOMPurify dependency
  • Created src/lib/logger.ts with Pino-based logging
  • Updated all console statements to use proper logging

Testing

  • Build compilation successful
  • TypeScript errors resolved
  • All changes maintain backward compatibility

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced security by sanitizing HTML content in the embed page.
  • Chores

    • Added startup validation for required environment variables with clear error messages.
    • Removed deprecated plugin configuration method.

- Fix XSS vulnerability in embed page with DOMPurify sanitization
- Add Pino-based logging infrastructure to replace console.log statements
- Replace 877+ console.log/error/warn calls with proper logger
- Fix TypeScript any types in auth module with ExtendedAdapterUser interface
- Remove deprecated getConfiguredAuthPlugin function
- Add environment variable validation function
- Fix TypeScript implicit any types in prompts route
- Resolve tsconfig.json type definition warnings
@vercel
Copy link

vercel bot commented Feb 9, 2026

@yasuo72 is attempting to deploy a commit to the fkadev Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link

coderabbitai bot commented Feb 9, 2026

📝 Walkthrough

Walkthrough

The changes introduce structured logging via pino across the application, improve type safety for authentication adapters, add HTML sanitization for security, implement environment validation at startup, reorganize type declarations, and remove a deprecated API. Overall, these are infrastructure and safety improvements without significant functional changes.

Changes

Cohort / File(s) Summary
Logging Infrastructure
src/lib/logger.ts
New logging module using pino with environment-dependent configuration (pretty-printing in development, JSON in production) and exported helper functions for quality checks, embeddings, webhooks, and AI errors.
Logging Integration
src/app/api/prompts/route.ts, src/lib/ai/improve-prompt.ts, src/lib/ai/quality-check.ts
Replaced console logging calls with structured logger calls and imported helper functions across API routes and AI utilities for better observability.
Type Management
package.json, tsconfig.json
Moved @types/d3 to devDependencies, added new type packages (@types/mdast, @types/mdx, @types/mysql, @types/pg, @types/node@^20.19.33), and added types: [] compiler option to tsconfig.
Security & Validation
src/app/embed/page.tsx, src/lib/config/index.ts
Added DOMPurify sanitization for rendered prompt HTML to strip unsafe content while preserving span tags and class attributes; introduced validateEnvironment() function to check required environment variables at startup.
Type Safety & API Cleanup
src/lib/auth/index.ts, src/lib/plugins/index.ts
Introduced ExtendedAdapterUser interface for cleaner type handling in authentication adapter; removed deprecated getConfiguredAuthPlugin() function.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A logging rabbit hops through the code,
With pino's structure lighting the road,
Types now secure, DOMPurify's guard,
Environment checks—none too hard,
Old APIs fade, new ones shine broad! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the primary objectives of the PR: it addresses security vulnerabilities (XSS fix via DOMPurify) and improves code quality through logging infrastructure and TypeScript fixes.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
package.json (1)

73-73: ⚠️ Potential issue | 🟠 Major

Add pino-pretty as a dev dependency.

The logger (src/lib/logger.ts, line 10) references pino-pretty as a transport target in development, but it's not listed in package.json. The dev logger will fail at startup without it.

src/app/api/prompts/route.ts (1)

300-301: ⚠️ Potential issue | 🟡 Minor

Inconsistent logging: POST error handler still uses console.error.

The GET handler (Line 452) was updated to use logger.error, but the POST handler's catch block on Line 301 still uses console.error. This appears to be an oversight given the PR's goal of replacing console calls with the pino logger.

Proposed fix
   } catch (error) {
-    console.error("Create prompt error:", error);
+    logger.error({ error }, "Create prompt error");
     return NextResponse.json(
🤖 Fix all issues with AI agents
In `@src/app/api/prompts/route.ts`:
- Around line 434-442: The map callback should not use the any type and should
not destructure a non-selected field; remove the ": any" on promptRaw so
TypeScript infers the correct Prisma type from promptsRaw, and drop the phantom
"embedding" from the destructuring (or instead include embedding in the Prisma
select if you actually need it). Update the mapper (promptsRaw.map(promptRaw =>
{ const { isPrivate, isUnlisted, unlistedAt, deletedAt, ...p } = promptRaw;
return { ...p, voteCount: p._count.votes, contributorCount:
p._count.contributors, contributors: p.contributors }; })) so promptRaw is
strongly typed and no undeclared fields like embedding are referenced.

In `@src/app/embed/page.tsx`:
- Line 7: The import statement import DOMPurify from "dompurify" in
src/app/embed/page.tsx will fail at runtime because dompurify is not listed in
package.json; add dompurify to dependencies and `@types/dompurify` to
devDependencies (or the equivalent with yarn/pnpm) by running e.g. npm install
dompurify && npm install -D `@types/dompurify` so the runtime package and
TypeScript types are present.

In `@src/lib/auth/index.ts`:
- Around line 49-52: The createUser override currently accepts
ExtendedAdapterUser which is narrower than the Adapter interface type and can
break strictFunctionTypes; change the method signature to accept the base
AdapterUser (e.g., async createUser(data: AdapterUser)) so it conforms to the
Adapter contract, then inside createUser narrow/validate for
ExtendedAdapterUser-specific fields (username, githubUsername) with runtime
checks or a type guard before using them; alternatively add an overload that
accepts AdapterUser and refines to ExtendedAdapterUser internally to ensure both
compile-time correctness and safe runtime behavior.

In `@src/lib/config/index.ts`:
- Around line 232-245: The validateEnvironment function currently treats
NEXTAUTH_URL as a hard required variable; remove NEXTAUTH_URL from the required
array in validateEnvironment (or move it into a new optional/recommended list)
so startup won't throw on platforms that infer it (e.g., Vercel); update the
error message to only list truly required keys (and, if you add an
optional/recommended list, include a comment or log indicating NEXTAUTH_URL is
recommended but may be inferred by some hosts).
🧹 Nitpick comments (4)
src/lib/config/index.ts (1)

254-258: Use the new logger instead of console.warn for consistency.

The PR introduces a centralized pino logger in src/lib/logger.ts, yet this new function uses console.warn. Use the logger for consistent structured logging.

♻️ Suggested fix
+import { logger } from "@/lib/logger";
+
 // Warn about optional but recommended variables
  const missingRecommended = recommended.filter(key => !process.env[key]);
  if (missingRecommended.length > 0) {
-   console.warn(
-     `Warning: Optional environment variables not set: ${missingRecommended.join(', ')}. ` +
-     `Some features may be limited.`
+   logger.warn(
+     { missing: missingRecommended },
+     "Optional environment variables not set. Some features may be limited."
    );
  }
src/lib/logger.ts (1)

34-36: logQualityCheckError won't serialize the error with stack trace as expected.

Passing { error } as the first argument to logger.error will trigger the custom error serializer, which is good. However, pino's convention is to pass the error object directly under the err key for best integration with pino-pretty and other transports. Consider using { err: error } for consistency with pino conventions, or keep as-is since you've defined both serializer keys.

src/app/api/prompts/route.ts (1)

151-151: Verbose inline type annotation duplicates Prisma's inferred type.

The long inline type on the .find() callback parameter is fragile — it must be kept in sync with the select clause on Lines 139–145. Since Prisma already infers the element type from the query result, you can let TypeScript infer it or extract a named type.

Proposed fix
-      const similarPrompt = publicPrompts.find((p: { id: string; slug: string | null; title: string; content: string; author: { username: string } }) => isSimilarContent(content, p.content));
+      const similarPrompt = publicPrompts.find((p) => isSimilarContent(content, p.content));
src/lib/ai/quality-check.ts (1)

145-146: Original parse error is discarded.

The catch block doesn't capture the thrown error, so logQualityCheckError receives a generic new Error(...) instead of the actual SyntaxError with the parse failure details (e.g., position of the invalid token). Binding the error and forwarding it would improve debuggability.

Proposed fix
-    } catch {
-      logQualityCheckError(new Error("Failed to parse AI quality check response"));
+    } catch (parseError) {
+      logQualityCheckError(parseError);

@yasuo72
Copy link
Author

yasuo72 commented Feb 9, 2026

Hi maintainers 👋
Looks like the Vercel workflow requires maintainer approval/authorization for PRs from contributors.
Happy to adjust anything if needed. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant