-
-
Notifications
You must be signed in to change notification settings - Fork 31
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix auth and cors #104
fix auth and cors #104
Conversation
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
WalkthroughThe pull request includes significant changes across several files, primarily focusing on enhancing API versioning, updating workflow configurations, and modifying components for improved functionality. Key updates involve the introduction of a new API version ( Changes
Possibly related PRs
Suggested labels
Poem
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 15
🧹 Outside diff range and nitpick comments (13)
apps/api/app/v1/[[...route]]/auth.ts (1)
1-3
: Remove duplicate auth importThe auth module is imported twice from @repo/auth.
- import { auth } from "@repo/auth"; - import { Hono } from "hono"; - import { auth as Auth } from "@repo/auth"; + import { Hono } from "hono"; + import { auth } from "@repo/auth"; + import type { Auth } from "@repo/auth";apps/www/lib/auth-client.ts (1)
Line range hint
9-11
: Add error handling for auth client initializationThe auth client should handle initialization failures gracefully.
+ try { export const authClient = createAuthClient({ - baseURL: BaseDomain, + baseURL: baseUrl, plugins: [multiSessionClient()], }); + } catch (error) { + console.error('Failed to initialize auth client:', error); + throw error; + }apps/api/middleware.ts (1)
Line range hint
8-8
: Review CORS configurationSetting
sec-fetch-mode
tono-cors
is very restrictive and may break cross-origin requests. Consider:
- Using proper CORS middleware with configured origins
- Setting appropriate CORS headers (Access-Control-Allow-Origin, etc.)
- Implementing proper preflight handling
- response.headers.set("sec-fetch-mode", "no-cors"); + // Use proper CORS middleware instead + response.headers.set('Access-Control-Allow-Origin', process.env.ALLOWED_ORIGINS); + response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); + response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');apps/app/middleware.ts (3)
Line range hint
12-20
: Enhance session validation and error handlingThe current session validation could be improved:
- No explicit error handling for fetch failures
- No session token validation
- Missing request timeout
const { data: session } = await betterFetch<Session>( `${baseDomain}/v1/auth/get-session`, { baseURL: request.nextUrl.origin, headers: { cookie: request.headers.get("cookie") || "", }, + timeout: 5000, // Add timeout + retry: 1, // Add retry }, -); +).catch(error => { + console.error('Session validation failed:', error); + return { data: null }; +}); +// Validate session token format if present +if (session?.token && !isValidSessionToken(session.token)) { + console.warn('Invalid session token format'); + return NextResponse.redirect(redirectUrl); +}
Line range hint
21-24
: Add security headers to auth redirectsWhen redirecting unauthenticated users, add security headers to prevent open redirects.
- return NextResponse.redirect(redirectUrl); + const response = NextResponse.redirect(redirectUrl); + response.headers.set('X-Frame-Options', 'DENY'); + response.headers.set('X-Content-Type-Options', 'nosniff'); + return response;
Line range hint
27-29
: Consider stricter path matching for auth routesThe current matcher
/:path*
is very broad. Consider restricting it to specific paths that require authentication.export const config = { - matcher: "/:path*", + matcher: [ + "/dashboard/:path*", + "/settings/:path*", + // Add other protected routes + ], };apps/api/app/v1/[[...route]]/route.ts (1)
Line range hint
38-45
: Document authentication requirementsWith the addition of PATCH and DELETE methods, please document:
- Which endpoints support these methods
- Authentication requirements
- Required request headers
- Expected response formats
Consider creating an OpenAPI/Swagger specification to document these endpoints.
.github/workflows/format-and-push.yml (2)
21-24
: Consider adding commit verificationWhile the checkout configuration is improved with
fetch-depth: 0
, additional security measures could be beneficial.Consider adding commit signature verification:
- name: Checkout repository uses: actions/checkout@v4 with: fetch-depth: 0 + verify-commits: true
47-49
: Enhance error handling in workflow scriptsThe script execution could benefit from better error handling and logging.
Consider adding error handling and verbose logging:
run: | + set -euo pipefail pnpm install pnpm i -g turbo
And for the git push:
- git push origin HEAD:${{ github.head_ref }} + if ! git push origin HEAD:${{ github.head_ref }}; then + echo "::error::Failed to push changes" + exit 1 + fiAlso applies to: 61-61
apps/status/app/page.tsx (2)
42-42
: Removeconsole.log
statement from production codeThe
console.log
statement on line 42 is likely used for debugging purposes and should be removed to avoid unnecessary logging in production.Apply this diff to remove the
console.log
statement:- console.log("todayStatus", todayStatus);
112-114
: Use appropriate locale for time formattingCurrently,
toLocaleTimeString
is called with the locale'en-IN'
. For a global application, it's better to use the user's locale or omit the locale parameter to default to the user's settings.Apply this diff to use the user's locale:
- ? `${new Date(webStatus[webStatus.length - 1].timestamp).toLocaleTimeString('en-IN', { hour: '2-digit', minute: '2-digit', second: '2-digit' })}` + ? `${new Date(webStatus[webStatus.length - 1].timestamp).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' })}`apps/status/components/custom/site/footer.tsx (1)
9-9
: Use consistent quotation marks in JSX attributesThe
className
andhref
attributes inside theLink
component are using inconsistent quotation marks. It's best practice to use double quotes for JSX attributes for consistency.Apply this diff to use double quotes:
- Powered by <Link href={"https://l.devwtf.in/plura-x"} className='hover:underline font-semibold text-primary cursor-pointer'>Plura Ai</Link> + Powered by <Link href="https://l.devwtf.in/plura-x" className="hover:underline font-semibold text-primary cursor-pointer">Plura Ai</Link>apps/status/components/custom/status.card.tsx (1)
15-15
: Add validation for the statusData propConsider adding validation or default value for the statusData prop to handle cases where it might be undefined or empty.
-export default function StatusCard({statusData}:{statusData: StatusData[]}) { +export default function StatusCard({statusData = []}:{statusData: StatusData[]}) {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (3)
apps/status/public/images/plura-logo.jpg
is excluded by!**/*.jpg
apps/status/public/images/plura-logo.png
is excluded by!**/*.png
pnpm-lock.yaml
is excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (25)
.github/workflows/format-and-push.yml
(3 hunks)apps/api/__tests__/life.test.ts
(1 hunks)apps/api/app/api/[[...route]]/auth.ts
(0 hunks)apps/api/app/layout.tsx
(0 hunks)apps/api/app/page.tsx
(0 hunks)apps/api/app/v1/[[...route]]/auth.ts
(1 hunks)apps/api/app/v1/[[...route]]/route.ts
(1 hunks)apps/api/middleware.ts
(1 hunks)apps/app/middleware.ts
(1 hunks)apps/status/app/page.tsx
(1 hunks)apps/status/components/custom/site/footer.tsx
(1 hunks)apps/status/components/custom/site/header.tsx
(1 hunks)apps/status/components/custom/status.card.tsx
(2 hunks)apps/status/components/custom/status.tracker.tsx
(1 hunks)apps/status/components/ui/tooltip.tsx
(1 hunks)apps/status/package.json
(1 hunks)apps/triggers/src/site.status.ts
(1 hunks)apps/www/app/(routes)/about/page.tsx
(1 hunks)apps/www/app/layout.tsx
(1 hunks)apps/www/lib/auth-client.ts
(1 hunks)apps/www/lib/server.ts
(1 hunks)packages/auth/src/auth.ts
(1 hunks)packages/crypt/package.json
(0 hunks)packages/database/package.json
(1 hunks)packages/database/prisma/schema.prisma
(1 hunks)
💤 Files with no reviewable changes (4)
- apps/api/app/page.tsx
- apps/api/app/api/[[...route]]/auth.ts
- packages/crypt/package.json
- apps/api/app/layout.tsx
🔇 Additional comments (11)
packages/database/package.json (1)
16-16
: Verify Prisma v6 migration impact on auth flows
The major version upgrade from Prisma 5.x to 6.x could have breaking changes that affect authentication and database operations. Please ensure:
- All database migrations are properly tested
- Authentication flows using Prisma models are validated
- Review Prisma v6 breaking changes documentation
Also applies to: 20-20
✅ Verification successful
Let me gather more information about the Prisma schema changes and usage.
Let me check one more thing to verify if there are any changes in the schema or query patterns between versions.
Prisma v6 upgrade appears safe for auth flows
The verification shows:
- Schema changes are minimal and don't affect auth-related models (User/Session/Account)
- Only non-breaking changes found: making timestamps required in Verification model
- Basic Prisma client usage patterns remain standard and compatible
- No complex auth-specific operations that could be affected by the major version change
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check for Prisma schema changes that might affect auth
fd -e prisma | xargs cat | grep -A 5 "model.*User\|model.*Session\|model.*Account"
Length of output: 595
Script:
#!/bin/bash
# Check for previous version of Prisma in package.json
git show HEAD~1:packages/database/package.json | grep "@prisma/client"
# Look for Prisma client usage in auth-related files
rg "PrismaClient|prisma\." -A 3 --type ts
Length of output: 1635
Script:
#!/bin/bash
# Check for any changes in Prisma schema
git diff HEAD~1 HEAD -- "*.prisma"
# Look for any auth-specific Prisma operations
rg "prisma\.(session|account)\." -A 3 --type ts
Length of output: 527
apps/www/app/layout.tsx (1)
19-19
: Verify the necessity of suppressContentEditableWarning
This change seems unrelated to the PR's objectives of fixing auth and CORS. Please clarify why this attribute is needed.
apps/api/app/v1/[[...route]]/route.ts (1)
16-16
: Verify API versioning impact
The change from /api
to /v1
base path is a breaking change. Ensure that:
- All clients are updated to use the new path
- A migration plan is in place
- Documentation is updated
packages/auth/src/auth.ts (3)
11-11
:
Security: Review localhost origin in production
Adding http://localhost:3004
to trustedOrigins
could pose a security risk if not properly handled in production environments.
Consider conditionally including localhost origins based on the environment:
- trustedOrigins: [
- "https://www.plura.pro",
- "http://localhost:3004",
- "https://app.plura.pro",
- "http://localhost:3003",
- ],
+ trustedOrigins: process.env.NODE_ENV === "production"
+ ? ["https://www.plura.pro", "https://app.plura.pro"]
+ : ["http://localhost:3004", "http://localhost:3003"],
16-16
: Verify API version change impact
The addition of /v1/auth
as basePath represents a breaking change that could affect existing clients.
Consider:
- Implementing API versioning gradually with fallback support
- Adding deprecation notices for old routes
- Documenting the migration path for clients
✅ Verification successful
API version change appears to be consistent with existing usage
The middleware.ts file already uses the /v1/auth
path format, indicating this isn't a breaking change but rather a formalization of an existing pattern. The basePath addition in the auth package aligns with the current implementation.
- Found in
apps/app/middleware.ts
:${baseDomain}/v1/auth/get-session
- No instances of unversioned
/auth
endpoints were found in the current codebase - The auth routes are consistently using the v1 prefix
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for auth endpoint usage across the codebase
rg -A 3 "\/auth\/" --type ts
Length of output: 105
Script:
#!/bin/bash
# Search for auth endpoint usage across the codebase with proper regex
rg -A 3 "/auth/" --type ts
# Also check for any configuration files that might define API paths
fd -e json -e yaml -e yml -X rg -l "auth"
# Look for router definitions or API route handlers
ast-grep --pattern 'router.$_("/auth", $_)'
Length of output: 612
Script:
#!/bin/bash
# Check the git history for any previous auth endpoint paths
git grep -l "/auth" $(git rev-parse HEAD^)
# Look for any OpenAPI/Swagger specifications that might document the API
fd -e yaml -e json -X rg -l "openapi|swagger"
# Check the middleware file more thoroughly as it contains auth endpoint usage
cat apps/app/middleware.ts
Length of output: 2220
Line range hint 38-45
: Review CORS configuration for production domains
The production CORS configuration with crossSubDomainCookies
needs to be verified against the updated trusted origins.
Ensure that:
- The domain in
crossSubDomainCookies
matches the domains intrustedOrigins
- All required subdomains are properly handled
- Cookie settings are consistent with the security requirements
✅ Verification successful
Let me verify the CORS and cookie domain configurations by checking the trusted origins setup.
Let me try a different approach to check the CORS and trusted origins configuration.
CORS and cookie domain configuration is correctly aligned ✅
The verification shows that:
- The
crossSubDomainCookies
domain "plura.pro" correctly matches the root domain of the trusted origins ("www.plura.pro" and "app.plura.pro") - The trusted origins list includes all the necessary production domains that need cross-subdomain cookie access
- The configuration is properly guarded with a production environment check
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check for potential CORS configuration mismatches
rg "plura\.pro" --type ts
Length of output: 1248
Script:
#!/bin/bash
# Check for trusted origins and CORS configuration in auth.ts
ast-grep --pattern 'const trustedOrigins = [$$$]'
Length of output: 51
Script:
#!/bin/bash
# Get the complete auth configuration
cat packages/auth/src/auth.ts
Length of output: 1414
apps/www/app/(routes)/about/page.tsx (1)
24-25
: 🛠️ Refactor suggestion
Verify CORS configuration for new API endpoint
The endpoint URL has been updated to use /v1/
versioning, but ensure:
- CORS is properly configured for both production and development URLs
- Error handling could be improved beyond just console.log
Consider enhancing error handling:
} catch (e) {
- console.log(e);
+ console.error('Failed to fetch contributors:', e);
+ setContributors([]);
+ // Consider adding error state handling
}
✅ Verification successful
CORS is properly configured for the new API endpoint
The verification shows that CORS is correctly configured in apps/api/app/v1/[[...route]]/route.ts
using the Hono middleware with:
- Proper origin validation through
allowedOrigins
- Required HTTP methods including GET for the contributors endpoint
- Appropriate headers configuration
- Reasonable max age setting
The error handling suggestion in the review comment remains valid and would improve the code quality.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for CORS configuration in API routes
rg -A 5 "cors"
Length of output: 3065
apps/status/app/page.tsx (1)
37-41
:
Ensure correct date filtering considering time zones
The code uses new Date().toISOString().split("T")[0]
to get today's date in UTC. If status.timestamp
is not in UTC, this could lead to incorrect filtering of status data. Ensure that both the current date and status.timestamp
are in the same time zone, or use a date library like date-fns
for accurate date comparisons.
Run the following script to check the time zones of status.timestamp
:
✅ Verification successful
Time zone handling is correctly implemented
The codebase consistently uses ISO strings for timestamps:
- In
apps/triggers/src/site.status.ts
, timestamps are generated usingnew Date().toISOString()
- In
apps/status/app/page.tsx
, these ISO timestamps are correctly parsed usingnew Date()
- The filtering logic using
startsWith(today)
is safe because both the filter date and stored timestamps are in ISO format (UTC)
The current implementation is correct and doesn't need modification.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify if status timestamps are in UTC format.
# Fetch sample timestamps from the API and display them
curl -s "${process.env.NEXT_PUBLIC_STATUS_API_URL}/v1/status/site" | jq '.siteStatus[].timestamp' | head -n 5
Length of output: 188
Script:
#!/bin/bash
# Let's examine the codebase to understand the timestamp format and API implementation
# First, check the API implementation to see how timestamps are generated
rg -g "!*.{lock,json}" "timestamp" -B2 -A2
# Also check for any date/time related utilities or configurations
rg -g "!*.{lock,json}" "new Date|toISOString|getTime" -B2 -A2
# Look for status-related type definitions that might show timestamp format
fd "types?.ts" --exec cat {}
Length of output: 7971
apps/status/package.json (1)
16-16
: Verify the dependency version and check for vulnerabilities
Ensure that @radix-ui/react-tooltip
version ^1.1.4
is the latest stable version and is free from known security vulnerabilities.
Run the following script to check the latest version and any security advisories:
✅ Verification successful
Version 1.1.4 of @radix-ui/react-tooltip is the latest stable version
Based on the npm registry check, version 1.1.4 is indeed the latest stable version of @radix-ui/react-tooltip. This version is being used consistently across multiple packages in the monorepo (plura-status and plura-www), indicating it's a well-established version. While we couldn't directly check for vulnerabilities due to missing lock files, Radix UI is a well-maintained, popular UI library with a strong security track record.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for the latest version and vulnerabilities of @radix-ui/react-tooltip.
# Get the latest version available on npm
npm view @radix-ui/react-tooltip version
# Check for any known vulnerabilities
npm audit --package=@radix-ui/react-tooltip
Length of output: 443
Script:
#!/bin/bash
# Let's check the package.json and package-lock.json files to get more context
fd -e json -E node_modules package.json -x cat {}
Length of output: 11789
apps/status/components/ui/tooltip.tsx (1)
1-32
: Component implementation looks good
The Tooltip
components are correctly implemented using the Radix UI library, and the usage of React.forwardRef
is appropriate for ref forwarding.
apps/status/components/custom/status.card.tsx (1)
Line range hint 1-107
: Verify relevance to auth and CORS fixes
The changes in this file appear to be focused on status monitoring functionality, but the PR title suggests it's meant to fix authentication and CORS issues. Could you clarify how these changes relate to the PR objectives?
const res = await fetch("http://localhost:3001/v1/session", { | ||
headers: await headers(), | ||
}); | ||
return res.json(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Apply same fixes to getSession function
The same issues exist in this function: hardcoded URL and missing error handling.
- const res = await fetch("http://localhost:3001/v1/session", {
+ const baseUrl = process.env.API_BASE_URL || "http://localhost:3001";
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 5000);
+ const res = await fetch(`${baseUrl}/v1/session`, {
headers: await headers(),
+ signal: controller.signal,
});
+ clearTimeout(timeoutId);
+ if (!res.ok) {
+ throw new Error(`Failed to fetch session: ${res.status}`);
+ }
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const res = await fetch("http://localhost:3001/v1/session", { | |
headers: await headers(), | |
}); | |
return res.json(); | |
const baseUrl = process.env.API_BASE_URL || "http://localhost:3001"; | |
const controller = new AbortController(); | |
const timeoutId = setTimeout(() => controller.abort(), 5000); | |
const res = await fetch(`${baseUrl}/v1/session`, { | |
headers: await headers(), | |
signal: controller.signal, | |
}); | |
clearTimeout(timeoutId); | |
if (!res.ok) { | |
throw new Error(`Failed to fetch session: ${res.status}`); | |
} | |
return res.json(); |
const res = await fetch("http://localhost:3001/v1/multi-sessions", { | ||
headers: await headers(), | ||
}); | ||
return res.json(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Replace hardcoded URL with environment variable
The hardcoded localhost URL will fail in production. Consider using an environment variable for the base URL.
- const res = await fetch("http://localhost:3001/v1/multi-sessions", {
+ const baseUrl = process.env.API_BASE_URL || "http://localhost:3001";
+ const res = await fetch(`${baseUrl}/v1/multi-sessions`, {
Additionally, consider adding error handling and timeout:
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 5000);
const res = await fetch(`${baseUrl}/v1/multi-sessions`, {
headers: await headers(),
+ signal: controller.signal,
});
+ clearTimeout(timeoutId);
+ if (!res.ok) {
+ throw new Error(`Failed to fetch sessions: ${res.status}`);
+ }
Committable suggestion skipped: line range outside the PR's diff.
app.get("/*", (c) => auth.handler(c.req.raw)); | ||
app.post("/*", (c) => auth.handler(c.req.raw)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Security: Restrict wildcard routes and add rate limiting
The current implementation using /*
wildcards could expose unintended endpoints. Consider:
- Explicitly defining allowed routes
- Adding rate limiting
- Adding request validation
- app.get("/*", (c) => auth.handler(c.req.raw));
- app.post("/*", (c) => auth.handler(c.req.raw));
+ import { RateLimiter } from '@hono/rate-limiter'
+
+ const limiter = new RateLimiter({
+ max: 100, // max requests
+ window: '1m' // per minute
+ });
+
+ // Define specific auth routes
+ const authRoutes = ['/login', '/logout', '/register', '/session'] as const;
+
+ authRoutes.forEach(route => {
+ app.use(route, limiter);
+ app.get(route, (c) => auth.handler(c.req.raw));
+ app.post(route, (c) => auth.handler(c.req.raw));
+ });
Committable suggestion skipped: line range outside the PR's diff.
const BaseDomain = | ||
process.env.NODE_ENV === "production" | ||
? "https://api.plura.pro" | ||
: "http://localhost:3001"; | ||
? "https://api.plura.pro/v1/auth" | ||
: "http://localhost:3001/v1/auth"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Use environment variables for API URLs
Hardcoding production URLs makes deployment to different environments difficult and poses a security risk if the URL needs to change.
const BaseDomain =
process.env.NODE_ENV === "production"
- ? "https://api.plura.pro/v1/auth"
- : "http://localhost:3001/v1/auth";
+ ? process.env.NEXT_PUBLIC_API_URL || throw new Error("NEXT_PUBLIC_API_URL is not defined")
+ : process.env.NEXT_PUBLIC_DEV_API_URL || "http://localhost:3001";
+ const authPath = "/v1/auth";
+ const baseUrl = `${BaseDomain}${authPath}`;
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const BaseDomain = | |
process.env.NODE_ENV === "production" | |
? "https://api.plura.pro" | |
: "http://localhost:3001"; | |
? "https://api.plura.pro/v1/auth" | |
: "http://localhost:3001/v1/auth"; | |
const BaseDomain = | |
process.env.NODE_ENV === "production" | |
? process.env.NEXT_PUBLIC_API_URL || throw new Error("NEXT_PUBLIC_API_URL is not defined") | |
: process.env.NEXT_PUBLIC_DEV_API_URL || "http://localhost:3001"; | |
const authPath = "/v1/auth"; | |
const baseUrl = `${BaseDomain}${authPath}`; |
@@ -15,5 +15,5 @@ export function middleware(request: NextRequest) { | |||
} | |||
|
|||
export const config = { | |||
matcher: ["/api/:path*", "/dashboard"], | |||
matcher: ["/v1/:path*", "/dashboard"], |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
API endpoints need to be updated from /api
to /v1
in test files
The verification reveals inconsistency in API endpoint usage where test files still use the old /api
path prefix while the rest of the codebase has migrated to /v1
.
Locations requiring updates:
apps/api/__tests__/life.test.ts
:- Line containing
/api/health
- Line containing
/api/mail/send
- Line containing
/api/mail/send-batch
- Line containing
🔗 Analysis chain
Verify API version migration completeness
The path matcher has been updated from /api
to /v1
.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check for any remaining /api references that need updating
rg -g '!*.md' -g '!package*.json' '/api/'
# Check for consistency in new /v1 endpoint usage
rg -g '!*.md' -g '!package*.json' '/v1/'
Length of output: 1609
origin: allowedOrigins, | ||
allowMethods: ["GET", "POST", "PATCH", "DELETE", "OPTIONS"], | ||
allowHeaders: ["Content-Type", "Authorization"], | ||
exposeHeaders: ["Content-Length"], | ||
maxAge: 600, | ||
credentials: true, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Security: Review CORS configuration
Several security concerns in the CORS configuration:
credentials: true
requires strict origin validationmaxAge: 600
is quite long for CORS preflight cache- New HTTP methods (PATCH, DELETE) need proper authentication
- Authorization header is exposed without documentation
Recommendations:
- Implement strict origin validation when credentials are enabled
- Reduce maxAge to 300 seconds (5 minutes) or less
- Document authentication requirements for new HTTP methods
- Add security headers:
cors({
origin: allowedOrigins,
allowMethods: ["GET", "POST", "PATCH", "DELETE", "OPTIONS"],
allowHeaders: ["Content-Type", "Authorization"],
exposeHeaders: ["Content-Length"],
- maxAge: 600,
+ maxAge: 300,
credentials: true,
+ // Add security headers
+ preflightContinue: false,
+ optionsSuccessStatus: 204,
}),
Committable suggestion skipped: line range outside the PR's diff.
@@ -1,4 +1,4 @@ | |||
import { GET } from "../app/api/[[...route]]/route"; | |||
import { GET } from "../app/v1/[[...route]]/route"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Update test endpoints to match new API version
The test endpoints still use the /api/
prefix while the import has been updated to use the new /v1/
versioned routes.
Update the test endpoints to match the new API version:
- const req = new Request("http://localhost:3000/api/health", {
+ const req = new Request("http://localhost:3000/v1/health", {
This change should be applied to all test cases in this file to maintain consistency with the new API versioning.
Also applies to: 15-19
createdAt DateTime | ||
updatedAt DateTime |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
Migration safety concerns identified for timestamp changes
The migration history reveals potential issues:
- The
verification
table had inconsistent timestamp handling across migrations - Initially,
createdAt
was made optional (DROP NOT NULL
), then required again updatedAt
was added as an optional field
This sequence of migrations suggests:
- The table may have existing records with NULL timestamps
- The current schema change could break existing data
- The inconsistent NOT NULL constraints indicate potential data integrity issues
Recommendation:
- Add default values for both timestamp fields in the migration
- Consider backfilling existing NULL values before enforcing NOT NULL constraints
🔗 Analysis chain
Verify migration safety for timestamp changes
Making createdAt
and updatedAt
required is good practice, but this change needs careful handling:
- Ensure no existing records have null timestamps
- Verify all auth flows properly set these timestamps
The previous attempt might have failed due to syntax specificity. Let's try a broader search to:
- Find files that mention "verification"
- Look for Prisma Verification model usage with context
- Check migration files to understand how this change is handled
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for Verification model usage in auth flows
ast-grep --pattern 'prisma.verification.create({ data: { $$$'
ast-grep --pattern 'prisma.verification.update({ where: { $$$'
Length of output: 128
Script:
#!/bin/bash
# Search for Verification model usage with broader patterns
rg -l "verification" --type ts
rg "prisma.*verification" -A 2 --type ts
# Check if there's a migration file for this change
fd "migration" packages/database/prisma/migrations -x cat {}
Length of output: 3911
<TooltipProvider> | ||
<div className="flex gap-0.5 h-8 items-end mt-2 rounded-2xl cursor-pointer"> | ||
{data.map((item, index) => ( | ||
<Tooltip key={index}> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Avoid using array index as key in list rendering
Using the index as a key in list rendering can cause issues when the list changes. It's better to use a unique identifier from the data, such as item.timestamp
.
Apply this diff to use item.timestamp
as the key:
- <Tooltip key={index}>
+ <Tooltip key={item.timestamp}>
Committable suggestion skipped: line range outside the PR's diff.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Outside diff range and nitpick comments (2)
apps/api/__tests__/life.test.ts (2)
Line range hint
4-13
: Consider enhancing the prisma mock setupWhile the current mock setup is functional, consider adding return values to the mock functions to make the tests more robust and predictable.
vi.mock("@repo/db", () => ({ prisma: { user: { - findMany: vi.fn(), - create: vi.fn(), - update: vi.fn(), - delete: vi.fn(), + findMany: vi.fn().mockResolvedValue([]), + create: vi.fn().mockResolvedValue({}), + update: vi.fn().mockResolvedValue({}), + delete: vi.fn().mockResolvedValue({}), }, }, }));
16-17
: Consider improving test description clarityWhile the endpoint has been correctly updated to v1, the test description could be more specific about the expected behavior.
- it("GET /v1/health should return health status", async () => { + it("GET /v1/health should return success status with 'i am alive' message", async () => {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (1)
pnpm-lock.yaml
is excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (1)
apps/api/__tests__/life.test.ts
(4 hunks)
🔇 Additional comments (3)
apps/api/__tests__/life.test.ts (3)
1-1
: LGTM! Import path correctly updated to v1
The import path has been properly updated to reflect the new API versioning structure.
Line range hint 1-61
: API versioning consistently updated throughout the file
All endpoints have been properly updated to use the new /v1/
prefix, maintaining consistency with the API versioning changes.
48-49
:
Fix inconsistent test description
The test description doesn't match the actual endpoint being tested.
- it("GET /v1/mail should return health status", async () => {
+ it("GET /v1/mail/send-batch should return health status", async () => {
it("GET /v1/mail should return health status", async () => { | ||
const req = new Request("http://localhost:3000/v1/mail/send", { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix inconsistent test description
The test description doesn't match the actual endpoint being tested.
- it("GET /v1/mail should return health status", async () => {
+ it("GET /v1/mail/send should return health status", async () => {
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
it("GET /v1/mail should return health status", async () => { | |
const req = new Request("http://localhost:3000/v1/mail/send", { | |
it("GET /v1/mail/send should return health status", async () => { | |
const req = new Request("http://localhost:3000/v1/mail/send", { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 12
🧹 Outside diff range and nitpick comments (8)
.github/workflows/format-and-push.yml (2)
21-24
: Consider optimizing the repository checkoutSetting
fetch-depth: 0
fetches the complete repository history, which is unnecessary for a formatting workflow and could slow down the process. Since only the latest changes need to be formatted, you can use a shallow clone.- name: Checkout repository uses: actions/checkout@v4 with: - fetch-depth: 0 + fetch-depth: 1
47-49
: Consider installing turbo as a dev dependencyInstead of installing turbo globally, it's better to add it as a dev dependency in your project. This ensures consistent versioning and avoids global installation requirements.
run: | pnpm install - pnpm i -g turbo
Then add turbo to your
package.json
:{ "devDependencies": { "turbo": "latest" } }apps/status/app/page.tsx (2)
37-89
: Consider refactoring for better maintainability and error handlingThe
fetchStatusData
function could be improved by:
- Breaking it down into smaller, focused functions
- Adding specific error handling for different failure scenarios
- Implementing retry logic for failed requests
Example refactor:
const getServiceStatus = (latency: number, originalStatus: string): "operational" | "warning" | "down" => { if (originalStatus === "DOWN" || latency >= 1000) return "down"; if (latency >= 700) return "warning"; return "operational"; }; const mapStatusData = (status: StatusT, service: keyof StatusT['latencies']) => ({ status: getServiceStatus(status.latencies[service], status.statuses[service]), timestamp: status.timestamp, }); const filterTodayStatus = (statusData: StatusT[]) => { const today = new Date().toISOString().split("T")[0]; return statusData.filter((status) => status.timestamp.startsWith(today)); }; const fetchWithRetry = async (url: string, retries = 3) => { for (let i = 0; i < retries; i++) { try { const response = await fetch(url); if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); return await response.json(); } catch (error) { if (i === retries - 1) throw error; await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, i))); } } }; const fetchStatusData = async () => { try { setIsFetching(true); const data = await fetchWithRetry(`${BASE_API}/v1/status/site`); if (!data.siteStatus?.length) { setWebStatus([]); setApiStatus([]); setAppStatus([]); return; } const todayStatus = filterTodayStatus(data.siteStatus); if (!todayStatus.length) { setWebStatus([]); setApiStatus([]); setAppStatus([]); return; } setWebStatus(todayStatus.map(status => mapStatusData(status, 'WEB'))); setApiStatus(todayStatus.map(status => mapStatusData(status, 'API'))); setAppStatus(todayStatus.map(status => mapStatusData(status, 'APP'))); } catch (error) { console.error("Error fetching status data:", error); // Consider showing user-friendly error message } finally { setIsFetching(false); } };
104-114
: Simplify conditional rendering logicThe current implementation could be simplified and made more robust:
-{isFetching - ? "All services are ..." - : webStatus.length > 0 && - apiStatus.length > 0 && - appStatus.length > 0 && - webStatus[webStatus.length - 1].status === "operational" && - apiStatus[apiStatus.length - 1].status === "operational" && - appStatus[appStatus.length - 1].status === "operational" - ? "All services are online" - : "Some services are experiencing issues"} +{(() => { + if (isFetching) return "All services are ..."; + if (!webStatus.length || !apiStatus.length || !appStatus.length) { + return "Status data unavailable"; + } + const allOperational = [webStatus, apiStatus, appStatus].every( + status => status[status.length - 1]?.status === "operational" + ); + return allOperational ? "All services are online" : "Some services are experiencing issues"; +})()}packages/rag-ai/types.d.ts (2)
3-5
: Enhance configuration property documentationConsider using proper JSDoc format for better IDE integration and documentation generation.
- model: string; // The name of the model to use - apiKey: string; // API key for authentication - baseUrl: string; // Base URL for the API + /** The name of the model to use */ + model: string; + /** API key for authentication */ + apiKey: string; + /** Base URL for the API */ + baseUrl: string;
8-11
: Consider adding constraints for namespace propertyThe
namespace
property might benefit from additional type constraints to ensure valid values.export interface RagAiContextT { type: "text" | "embedding" | "pdf" | "csv" | "text-file" | "html"; data: string; - namespace: string; + /** Namespace identifier for context separation */ + namespace: `${string}-${string}`; // Enforce format like "project-context" }packages/rag-ai/package.json (2)
2-13
: Complete package metadata for public packageSince this package is marked as
private: false
, it should include complete metadata for publication:
- Add meaningful description
- Add relevant keywords for discoverability
- Add author information
- Consider using a more permissive license for open-source
14-17
: Consider using version ranges for dependenciesUsing fixed versions can make updates difficult. Consider using caret ranges:
"dependencies": { - "@upstash/rag-chat": "^2.0.3", - "langchain": "^0.3.6" + "@upstash/rag-chat": "^2.0.0", + "langchain": "^0.3.0" }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (1)
pnpm-lock.yaml
is excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (17)
.github/workflows/deploy-triggers.yml
(0 hunks).github/workflows/format-and-push.yml
(2 hunks)apps/status/app/page.tsx
(1 hunks)apps/status/components/custom/status.card.tsx
(2 hunks)apps/triggers/package.json
(1 hunks)apps/triggers/src/site.status.ts
(2 hunks)packages/crypt/package.json
(0 hunks)packages/crypt/tsconfig.json
(1 hunks)packages/crypt/tsconfig.tsbuildinfo
(0 hunks)packages/database/package.json
(1 hunks)packages/rag-ai/package.json
(1 hunks)packages/rag-ai/src/config.ts
(1 hunks)packages/rag-ai/src/func/context.ts
(1 hunks)packages/rag-ai/src/init.ts
(1 hunks)packages/rag-ai/tsconfig.json
(1 hunks)packages/rag-ai/types.d.ts
(1 hunks)packages/rag-ai/utils/types-validator.ts
(1 hunks)
💤 Files with no reviewable changes (3)
- packages/crypt/package.json
- .github/workflows/deploy-triggers.yml
- packages/crypt/tsconfig.tsbuildinfo
✅ Files skipped from review due to trivial changes (2)
- apps/triggers/package.json
- packages/rag-ai/tsconfig.json
🚧 Files skipped from review as they are similar to previous changes (2)
- apps/triggers/src/site.status.ts
- packages/database/package.json
🧰 Additional context used
🪛 actionlint (1.7.4)
.github/workflows/format-and-push.yml
58-58: shellcheck reported issue in this script: SC2046:warning:6:24: Quote this to prevent word splitting
(shellcheck)
🪛 yamllint (1.35.1)
.github/workflows/format-and-push.yml
[error] 56-56: trailing spaces
(trailing-spaces)
🔇 Additional comments (11)
packages/crypt/tsconfig.json (1)
2-2
: Verify the base TypeScript configuration.
Let's ensure the base configuration file exists and is properly referenced.
✅ Verification successful
Base configuration is valid and properly referenced
The base configuration exists at packages/typescript-config/base.json
and provides comprehensive TypeScript compiler options. The removal of local compilerOptions
is justified as they are now properly inherited from the base config. Regarding the "dist" directory exclusion:
- The base config doesn't include "dist" in excludes
- Modern build tools typically handle output directories separately
- The current exclude pattern for "node_modules" is sufficient for development
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if the base configuration exists and examine its contents
fd -t f "base.json" -p "typescript-config" --exec cat {}
Length of output: 161
Script:
#!/bin/bash
# Let's first find the typescript config files in the repository
fd -t f "tsconfig" --full-path
# Then let's check the content of any base.json files
fd -t f "base.json" --full-path
Length of output: 384
Script:
#!/bin/bash
# Let's examine the content of the base configuration file
cat packages/typescript-config/base.json
# And let's also check the content of the crypt package's tsconfig.json for comparison
cat packages/crypt/tsconfig.json
Length of output: 736
.github/workflows/format-and-push.yml (2)
14-14
: LGTM: Appropriate permission scope
The contents: write
permission is correctly specified and necessary for pushing formatted code changes.
26-27
: LGTM: Proper YAML formatting
The PNPM setup step is correctly structured with proper ordering of directives.
apps/status/components/custom/status.card.tsx (3)
15-32
: Well-structured uptime calculation implementation!
The calculateUptime
function is well-implemented with:
- Clear type definitions
- Appropriate weights for different status types
- Edge case handling
- Proper floating-point precision
34-34
: LGTM! Proper TypeScript typing for the component props.
67-75
: Hardcoded URLs need centralized configuration
While security attributes and dynamic uptime calculation have been implemented, the URL is still hardcoded. Consider using environment variables for the website URL.
apps/status/app/page.tsx (1)
7-28
: Well-structured TypeScript interface and state management!
The StatusT interface and state initialization are well-defined with proper typing.
packages/rag-ai/src/config.ts (2)
4-8
: LGTM: Well-structured configuration
The configuration object is well-typed and uses clear environment variable names. The default model and base URL values provide good fallbacks.
10-10
: LGTM: Configuration validation
Good practice to validate the configuration immediately after definition.
packages/rag-ai/src/init.ts (1)
5-14
: Verify cache implementation compatibility
The Redis cache implementation looks good, but ensure it's compatible with RAGChat's expected interface.
packages/rag-ai/src/func/context.ts (1)
1-1
: Verify ragAi initialization
Need to ensure ragAi is properly initialized before use.
✅ Verification successful
ragAi is properly initialized with all required dependencies
The verification shows that ragAi is correctly initialized in init.ts
with:
- Proper imports from required packages (
@upstash/rag-chat
,@repo/cache
) - Complete initialization with all necessary configuration (model, cache, streaming, etc.)
- Correct export for use in other files
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if ragAi is properly initialized in init.ts
ast-grep --pattern 'export const ragAi = new RAGChat($$$)'
Length of output: 640
Script:
#!/bin/bash
# Check if RAGChat class is properly defined and imported
ast-grep --pattern 'import { RAGChat } from $$$'
# Check if ragAiConfig and cache are properly imported and initialized
ast-grep --pattern 'import { $$ as ragAiConfig } from $$$'
ast-grep --pattern 'import { $$ as cache } from $$$'
Length of output: 166
Script:
#!/bin/bash
# Let's try a different approach to check the imports and initialization
rg -A 3 "^import.*RAGChat" packages/rag-ai/src/
rg -A 3 "^import.*ragAiConfig" packages/rag-ai/src/
rg -A 3 "^import.*cache" packages/rag-ai/src/
rg -A 3 "^import.*custom" packages/rag-ai/src/
Length of output: 1133
"exclude": ["node_modules"] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Consider re-adding "dist" to exclude patterns.
The removal of "dist" from exclude patterns might cause TypeScript to process built files, which could lead to:
- Slower type checking
- Potential circular references
- Unnecessary processing of compiled code
Consider applying this change:
- "exclude": ["node_modules"]
+ "exclude": ["node_modules", "dist"]
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "tsup.config.ts"], | |
"exclude": ["node_modules"] | |
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "tsup.config.ts"], | |
"exclude": ["node_modules", "dist"] |
if: | | ||
github.event_name == 'push' && | ||
github.event.head_commit.message != 'format: make the code prettier' | ||
run: | | ||
if [ -n "$(git status --porcelain)" ]; then | ||
git config --global user.name "github-actions[bot]" | ||
git config --global user.email "github-actions[bot]@users.noreply.github.com" | ||
git add . | ||
git commit -m "format: make the code prettier" | ||
git push origin ${{ github.head_ref }} | ||
git push origin HEAD:$(git rev-parse --abbrev-ref HEAD) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Fix formatting and potential shell scripting issues
There are several issues in this section that should be addressed:
- Trailing spaces in the conditions
- Unquoted command substitution in the git push command
- Complex branch name resolution that could be simplified
if: |
- github.event_name == 'push' &&
- github.event.head_commit.message != 'format: make the code prettier'
+ github.event_name == 'push' &&
+ github.event.head_commit.message != 'format: make the code prettier'
run: |
if [ -n "$(git status --porcelain)" ]; then
git config --global user.name "github-actions[bot]"
git config --global user.email "github-actions[bot]@users.noreply.github.com"
git add .
git commit -m "format: make the code prettier"
- git push origin HEAD:$(git rev-parse --abbrev-ref HEAD)
+ git push origin "HEAD:$(git rev-parse --abbrev-ref HEAD)"
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
if: | | |
github.event_name == 'push' && | |
github.event.head_commit.message != 'format: make the code prettier' | |
run: | | |
if [ -n "$(git status --porcelain)" ]; then | |
git config --global user.name "github-actions[bot]" | |
git config --global user.email "github-actions[bot]@users.noreply.github.com" | |
git add . | |
git commit -m "format: make the code prettier" | |
git push origin ${{ github.head_ref }} | |
git push origin HEAD:$(git rev-parse --abbrev-ref HEAD) | |
if: | | |
github.event_name == 'push' && | |
github.event.head_commit.message != 'format: make the code prettier' | |
run: | | |
if [ -n "$(git status --porcelain)" ]; then | |
git config --global user.name "github-actions[bot]" | |
git config --global user.email "github-actions[bot]@users.noreply.github.com" | |
git add . | |
git commit -m "format: make the code prettier" | |
git push origin "HEAD:$(git rev-parse --abbrev-ref HEAD)" |
🧰 Tools
🪛 actionlint (1.7.4)
58-58: shellcheck reported issue in this script: SC2046:warning:6:24: Quote this to prevent word splitting
(shellcheck)
🪛 yamllint (1.35.1)
[error] 56-56: trailing spaces
(trailing-spaces)
const BASE_API = | ||
process.env.NODE_ENV === "production" | ||
? "https://api.plura.pro" | ||
: "http://localhost:3001"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Use environment variables for API URLs
Consider using environment variables for both production and development API URLs instead of hardcoding them.
-const BASE_API =
- process.env.NODE_ENV === "production"
- ? "https://api.plura.pro"
- : "http://localhost:3001";
+const BASE_API = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const BASE_API = | |
process.env.NODE_ENV === "production" | |
? "https://api.plura.pro" | |
: "http://localhost:3001"; | |
const BASE_API = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001"; |
apiKey: process.env.RAG_AI_API_KEY || "", | ||
baseUrl: process.env.RAG_API_BASE_URL || "https://api.together.xyz/v1", |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical: Prevent initialization with empty API key
The empty string fallback for RAG_AI_API_KEY
is a security risk as it might allow the system to initialize without proper authentication.
Consider this safer implementation:
- apiKey: process.env.RAG_AI_API_KEY || "",
+ apiKey: process.env.RAG_AI_API_KEY ?? (() => {
+ throw new Error('RAG_AI_API_KEY environment variable is required');
+ })(),
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
apiKey: process.env.RAG_AI_API_KEY || "", | |
baseUrl: process.env.RAG_API_BASE_URL || "https://api.together.xyz/v1", | |
apiKey: process.env.RAG_AI_API_KEY ?? (() => { | |
throw new Error('RAG_AI_API_KEY environment variable is required'); | |
})(), | |
baseUrl: process.env.RAG_API_BASE_URL || "https://api.together.xyz/v1", |
}), | ||
redis: cache, | ||
streaming: true, | ||
debug: true, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Consider environment-based debug mode
Hardcoding debug mode to true
might expose sensitive information in production environments.
- debug: true,
+ debug: process.env.NODE_ENV === 'development',
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
debug: true, | |
debug: process.env.NODE_ENV === 'development', |
@@ -0,0 +1,18 @@ | |||
import { RagAiConfigT } from "types"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fix import path for types
The import path should be relative to maintain proper module resolution:
- import { RagAiConfigT } from "types";
+ import { RagAiConfigT } from "../types";
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
import { RagAiConfigT } from "types"; | |
import { RagAiConfigT } from "../types"; |
export const validateConfig = (config: RagAiConfigT): void => { | ||
if (!config.model) { | ||
console.warn("Warning: Model name (RAG_MODEL) is not set. Using default value."); | ||
} | ||
|
||
if (!config.apiKey) { | ||
console.error("Error: RAG_AI_API_KEY is required but not set."); | ||
throw new Error("Missing required configuration: RAG_AI_API_KEY"); | ||
} | ||
|
||
if (!config.baseUrl) { | ||
console.warn( | ||
"Warning: Base URL (RAG_API_BASE_URL) is not set. Using default value." | ||
); | ||
} | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Improve configuration validation strategy
Several improvements needed for the validation function:
- Console logging in a library is not recommended
- Inconsistent error handling (throwing for apiKey but warnings for others)
- No indication of successful validation
Consider this refactor:
- export const validateConfig = (config: RagAiConfigT): void => {
+ export const validateConfig = (config: RagAiConfigT): RagAiConfigT => {
if (!config.model) {
- console.warn("Warning: Model name (RAG_MODEL) is not set. Using default value.");
+ throw new Error("Missing required configuration: RAG_MODEL");
}
if (!config.apiKey) {
- console.error("Error: RAG_AI_API_KEY is required but not set.");
throw new Error("Missing required configuration: RAG_AI_API_KEY");
}
if (!config.baseUrl) {
- console.warn(
- "Warning: Base URL (RAG_API_BASE_URL) is not set. Using default value."
- );
+ throw new Error("Missing required configuration: RAG_API_BASE_URL");
}
+ return config;
};
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
export const validateConfig = (config: RagAiConfigT): void => { | |
if (!config.model) { | |
console.warn("Warning: Model name (RAG_MODEL) is not set. Using default value."); | |
} | |
if (!config.apiKey) { | |
console.error("Error: RAG_AI_API_KEY is required but not set."); | |
throw new Error("Missing required configuration: RAG_AI_API_KEY"); | |
} | |
if (!config.baseUrl) { | |
console.warn( | |
"Warning: Base URL (RAG_API_BASE_URL) is not set. Using default value." | |
); | |
} | |
}; | |
export const validateConfig = (config: RagAiConfigT): RagAiConfigT => { | |
if (!config.model) { | |
throw new Error("Missing required configuration: RAG_MODEL"); | |
} | |
if (!config.apiKey) { | |
throw new Error("Missing required configuration: RAG_AI_API_KEY"); | |
} | |
if (!config.baseUrl) { | |
throw new Error("Missing required configuration: RAG_API_BASE_URL"); | |
} | |
return config; | |
}; |
async function ragAiRemoveContext(id:string, namespace: string) { | ||
await ragAi.context.delete({ id: id, namespace: namespace }); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add validation for context removal
The remove function needs input validation:
async function ragAiRemoveContext(id:string, namespace: string) {
+ if (!id?.trim()) {
+ throw new Error('Context ID is required');
+ }
+ if (!namespace?.trim()) {
+ throw new Error('Namespace is required');
+ }
+ try {
await ragAi.context.delete({ id: id, namespace: namespace });
+ } catch (error) {
+ throw new Error(`Failed to remove context: ${error.message}`);
+ }
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
async function ragAiRemoveContext(id:string, namespace: string) { | |
await ragAi.context.delete({ id: id, namespace: namespace }); | |
} | |
async function ragAiRemoveContext(id:string, namespace: string) { | |
if (!id?.trim()) { | |
throw new Error('Context ID is required'); | |
} | |
if (!namespace?.trim()) { | |
throw new Error('Namespace is required'); | |
} | |
try { | |
await ragAi.context.delete({ id: id, namespace: namespace }); | |
} catch (error) { | |
throw new Error(`Failed to remove context: ${error.message}`); | |
} | |
} |
async function ragAiAddWEBContext(link: string, namespace: string) { | ||
await ragAi.context.add({ | ||
type: "html", | ||
source: link, | ||
config: { chunkOverlap: 50, chunkSize: 200 }, | ||
options: { namespace: namespace }, | ||
}); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Extract chunk configuration and add validation for web context
The chunk configuration should be configurable and the function needs validation:
+ const DEFAULT_CHUNK_CONFIG = {
+ chunkOverlap: 50,
+ chunkSize: 200,
+ };
- async function ragAiAddWEBContext(link: string, namespace: string) {
+ async function ragAiAddWEBContext(
+ link: string,
+ namespace: string,
+ chunkConfig = DEFAULT_CHUNK_CONFIG
+ ) {
+ if (!link?.trim()) {
+ throw new Error('URL is required');
+ }
+ if (!namespace?.trim()) {
+ throw new Error('Namespace is required');
+ }
+ try {
await ragAi.context.add({
type: "html",
source: link,
- config: { chunkOverlap: 50, chunkSize: 200 },
+ config: chunkConfig,
options: { namespace: namespace },
});
+ } catch (error) {
+ throw new Error(`Failed to add web context: ${error.message}`);
+ }
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
async function ragAiAddWEBContext(link: string, namespace: string) { | |
await ragAi.context.add({ | |
type: "html", | |
source: link, | |
config: { chunkOverlap: 50, chunkSize: 200 }, | |
options: { namespace: namespace }, | |
}); | |
} | |
const DEFAULT_CHUNK_CONFIG = { | |
chunkOverlap: 50, | |
chunkSize: 200, | |
}; | |
async function ragAiAddWEBContext( | |
link: string, | |
namespace: string, | |
chunkConfig = DEFAULT_CHUNK_CONFIG | |
) { | |
if (!link?.trim()) { | |
throw new Error('URL is required'); | |
} | |
if (!namespace?.trim()) { | |
throw new Error('Namespace is required'); | |
} | |
try { | |
await ragAi.context.add({ | |
type: "html", | |
source: link, | |
config: chunkConfig, | |
options: { namespace: namespace }, | |
}); | |
} catch (error) { | |
throw new Error(`Failed to add web context: ${error.message}`); | |
} | |
} |
async function ragAiAddPDFContext(filePath: string, namespace: string) { | ||
await ragAi.context.add({ | ||
type: "pdf", | ||
fileSource: filePath, | ||
options: { namespace: namespace }, | ||
}); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add error handling and input validation for PDF context
The function needs proper error handling and input validation:
async function ragAiAddPDFContext(filePath: string, namespace: string) {
+ if (!filePath?.trim()) {
+ throw new Error('File path is required');
+ }
+ if (!namespace?.trim()) {
+ throw new Error('Namespace is required');
+ }
+ try {
await ragAi.context.add({
type: "pdf",
fileSource: filePath,
options: { namespace: namespace },
});
+ } catch (error) {
+ throw new Error(`Failed to add PDF context: ${error.message}`);
+ }
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
async function ragAiAddPDFContext(filePath: string, namespace: string) { | |
await ragAi.context.add({ | |
type: "pdf", | |
fileSource: filePath, | |
options: { namespace: namespace }, | |
}); | |
} | |
async function ragAiAddPDFContext(filePath: string, namespace: string) { | |
if (!filePath?.trim()) { | |
throw new Error('File path is required'); | |
} | |
if (!namespace?.trim()) { | |
throw new Error('Namespace is required'); | |
} | |
try { | |
await ragAi.context.add({ | |
type: "pdf", | |
fileSource: filePath, | |
options: { namespace: namespace }, | |
}); | |
} catch (error) { | |
throw new Error(`Failed to add PDF context: ${error.message}`); | |
} | |
} |
Summary by CodeRabbit
Release Notes
New Features
StatusTracker
component for visual representation of system statuses.Page
to replace the previousHome
function, enhancing status fetching and display logic.Changes
/v1/
) across various components and middleware.Style
Chores