Skip to content
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

Merged
merged 4 commits into from
Dec 7, 2024
Merged

fix auth and cors #104

merged 4 commits into from
Dec 7, 2024

Conversation

SkidGod4444
Copy link
Member

@SkidGod4444 SkidGod4444 commented Dec 5, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new StatusTracker component for visual representation of system statuses.
    • Added a new functional component Page to replace the previous Home function, enhancing status fetching and display logic.
  • Changes

    • Updated API endpoints to versioning structure (/v1/) across various components and middleware.
    • Enhanced CORS configuration to support additional HTTP methods and headers.
    • Improved clarity and functionality in workflow configurations.
  • Style

    • Redesigned header and footer components for improved aesthetics and usability.
  • Chores

    • Updated dependencies and package configurations for better performance and compatibility.
    • Adjusted authentication client base URL to align with versioning updates.

Copy link

vercel bot commented Dec 5, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
plura-api ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 6, 2024 2:14pm
plura-app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 6, 2024 2:14pm
plura-status ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 6, 2024 2:14pm
plura-web ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 6, 2024 2:14pm

Copy link

coderabbitai bot commented Dec 5, 2024

Walkthrough

The 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 (/v1), adjustments to middleware and authentication mechanisms, and the removal of outdated files. Additionally, new components have been added, and existing ones have been modified to improve user experience and data handling, particularly in the status monitoring features.

Changes

File Path Change Summary
.github/workflows/format-and-push.yml Renamed checkout step, updated fetch depth, reordered installation step, modified push command.
apps/api/__tests__/life.test.ts Updated import path for GET function to target versioned endpoint.
apps/api/app/api/[[...route]]/auth.ts Deleted file containing API authentication service.
apps/api/app/layout.tsx Deleted layout component and associated metadata.
apps/api/app/page.tsx Deleted Home component responsible for API data fetching.
apps/api/app/v1/[[...route]]/auth.ts Introduced new authentication service for the /v1 API.
apps/api/app/v1/[[...route]]/route.ts Updated routing to /v1, modified CORS settings, and simplified Hono instance initialization.
apps/api/middleware.ts Updated matcher configuration for middleware to /v1.
apps/app/middleware.ts Updated session data fetch URL to /v1/auth/get-session.
apps/status/app/page.tsx Introduced new Page component for displaying service statuses.
apps/status/components/custom/site/footer.tsx Updated footer content to include a link to "Powered by Plura Ai".
apps/status/components/custom/site/header.tsx Modified header layout and styling, added new button for updates.
apps/status/components/custom/status.card.tsx Updated to accept statusData prop and modified display logic.
apps/status/components/custom/status.tracker.tsx Introduced StatusTracker component for visualizing system statuses.
apps/status/components/ui/tooltip.tsx Added tooltip UI component using Radix UI library.
apps/status/package.json Added @radix-ui/react-tooltip dependency.
apps/triggers/src/site.status.ts Updated health check URL to /v1/health.
apps/www/app/(routes)/about/page.tsx Updated contributor data fetch URLs for production and development.
apps/www/lib/auth-client.ts Changed base URL for authentication client to /v1/auth.
apps/www/lib/server.ts Updated API call URLs from /api/ to /v1/.
packages/auth/src/auth.ts Updated trusted origins and added basePath for authentication.
packages/crypt/package.json Removed dev script from package.json.
packages/database/package.json Upgraded @prisma/client and prisma dependencies to version ^6.0.1.
packages/database/prisma/schema.prisma Changed createdAt and updatedAt fields in Verification model from optional to required.

Possibly related PRs

  • auth #34: The changes in the main PR regarding the workflow file may relate to the modifications in the route.ts file in this PR, as both involve updates to the API structure and handling, particularly in the context of the Hono framework.
  • fix workflows #68: This PR also involves updates to workflow files, which may share some context with the changes made in the main PR regarding the .github/workflows/format-and-push.yml file.
  • update auth to better-auth v1 #71: The updates in this PR regarding the authentication process may relate to the changes in the main PR, as both involve improvements in handling API requests and responses, particularly in the context of user sessions and authentication.
  • Feat: Feature Page #99: The introduction of a feature page in this PR may connect with the overall enhancements in the main PR, as both aim to improve user interaction and functionality within the application.

Suggested labels

enhancement

Poem

🐇 In the code where bunnies hop,
Changes made, we’ll never stop!
From /api to /v1,
Our features shine, the work is fun!
With status checks and tooltips bright,
Plura’s path is clear and right! 🌟


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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 15

🧹 Outside diff range and nitpick comments (13)
apps/api/app/v1/[[...route]]/auth.ts (1)

1-3: Remove duplicate auth import

The 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 initialization

The 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 configuration

Setting sec-fetch-mode to no-cors is very restrictive and may break cross-origin requests. Consider:

  1. Using proper CORS middleware with configured origins
  2. Setting appropriate CORS headers (Access-Control-Allow-Origin, etc.)
  3. 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 handling

The current session validation could be improved:

  1. No explicit error handling for fetch failures
  2. No session token validation
  3. 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 redirects

When 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 routes

The 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 requirements

With the addition of PATCH and DELETE methods, please document:

  1. Which endpoints support these methods
  2. Authentication requirements
  3. Required request headers
  4. 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 verification

While 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 scripts

The 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
+   fi

Also applies to: 61-61

apps/status/app/page.tsx (2)

42-42: Remove console.log statement from production code

The 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 formatting

Currently, 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 attributes

The className and href attributes inside the Link 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 prop

Consider 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

📥 Commits

Reviewing files that changed from the base of the PR and between d9181f3 and 6a63ebd.

⛔ 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:

  1. All database migrations are properly tested
  2. Authentication flows using Prisma models are validated
  3. 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:

  1. Schema changes are minimal and don't affect auth-related models (User/Session/Account)
  2. Only non-breaking changes found: making timestamps required in Verification model
  3. Basic Prisma client usage patterns remain standard and compatible
  4. 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:

  1. All clients are updated to use the new path
  2. A migration plan is in place
  3. Documentation is updated
packages/auth/src/auth.ts (3)

11-11: ⚠️ Potential issue

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:

  1. Implementing API versioning gradually with fallback support
  2. Adding deprecation notices for old routes
  3. 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:

  1. The domain in crossSubDomainCookies matches the domains in trustedOrigins
  2. All required subdomains are properly handled
  3. 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:

  1. The crossSubDomainCookies domain "plura.pro" correctly matches the root domain of the trusted origins ("www.plura.pro" and "app.plura.pro")
  2. The trusted origins list includes all the necessary production domains that need cross-subdomain cookie access
  3. 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:

  1. CORS is properly configured for both production and development URLs
  2. 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: ⚠️ Potential issue

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 using new Date().toISOString()
  • In apps/status/app/page.tsx, these ISO timestamps are correctly parsed using new 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?

Comment on lines +12 to 15
const res = await fetch("http://localhost:3001/v1/session", {
headers: await headers(),
});
return res.json();
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

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.

Suggested change
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();

Comment on lines +5 to 8
const res = await fetch("http://localhost:3001/v1/multi-sessions", {
headers: await headers(),
});
return res.json();
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

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.

Comment on lines +12 to +13
app.get("/*", (c) => auth.handler(c.req.raw));
app.post("/*", (c) => auth.handler(c.req.raw));
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security: Restrict wildcard routes and add rate limiting

The current implementation using /* wildcards could expose unintended endpoints. Consider:

  1. Explicitly defining allowed routes
  2. Adding rate limiting
  3. 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.

Comment on lines 4 to +7
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";
Copy link

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.

Suggested change
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"],
Copy link

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
🔗 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

Comment on lines +29 to +34
origin: allowedOrigins,
allowMethods: ["GET", "POST", "PATCH", "DELETE", "OPTIONS"],
allowHeaders: ["Content-Type", "Authorization"],
exposeHeaders: ["Content-Length"],
maxAge: 600,
credentials: true,
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security: Review CORS configuration

Several security concerns in the CORS configuration:

  1. credentials: true requires strict origin validation
  2. maxAge: 600 is quite long for CORS preflight cache
  3. New HTTP methods (PATCH, DELETE) need proper authentication
  4. Authorization header is exposed without documentation

Recommendations:

  1. Implement strict origin validation when credentials are enabled
  2. Reduce maxAge to 300 seconds (5 minutes) or less
  3. Document authentication requirements for new HTTP methods
  4. 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";
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

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

Comment on lines +66 to +67
createdAt DateTime
updatedAt DateTime
Copy link

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:

  1. The table may have existing records with NULL timestamps
  2. The current schema change could break existing data
  3. 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:

  1. Ensure no existing records have null timestamps
  2. 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:

  1. Find files that mention "verification"
  2. Look for Prisma Verification model usage with context
  3. 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}>
Copy link

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.

apps/status/components/custom/status.card.tsx Outdated Show resolved Hide resolved
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: 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 setup

While 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 clarity

While 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6a63ebd and 4d08e87.

⛔ 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: ⚠️ Potential issue

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 () => {

Comment on lines +32 to +33
it("GET /v1/mail should return health status", async () => {
const req = new Request("http://localhost:3000/v1/mail/send", {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

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.

Suggested change
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", {

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: 12

🧹 Outside diff range and nitpick comments (8)
.github/workflows/format-and-push.yml (2)

21-24: Consider optimizing the repository checkout

Setting 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 dependency

Instead 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 handling

The fetchStatusData function could be improved by:

  1. Breaking it down into smaller, focused functions
  2. Adding specific error handling for different failure scenarios
  3. 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 logic

The 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 documentation

Consider 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 property

The 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 package

Since 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 dependencies

Using 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4d08e87 and d775f63.

⛔ 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

Comment on lines +3 to +4
"exclude": ["node_modules"]
Copy link

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:

  1. Slower type checking
  2. Potential circular references
  3. 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.

Suggested change
"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"]

Comment on lines +55 to +64
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)
Copy link

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:

  1. Trailing spaces in the conditions
  2. Unquoted command substitution in the git push command
  3. 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.

Suggested change
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)

Comment on lines +32 to +35
const BASE_API =
process.env.NODE_ENV === "production"
? "https://api.plura.pro"
: "http://localhost:3001";
Copy link

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.

Suggested change
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";

Comment on lines +6 to +7
apiKey: process.env.RAG_AI_API_KEY || "",
baseUrl: process.env.RAG_API_BASE_URL || "https://api.together.xyz/v1",
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

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.

Suggested change
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,
Copy link

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.

Suggested change
debug: true,
debug: process.env.NODE_ENV === 'development',

@@ -0,0 +1,18 @@
import { RagAiConfigT } from "types";
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

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.

Suggested change
import { RagAiConfigT } from "types";
import { RagAiConfigT } from "../types";

Comment on lines +3 to +18
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."
);
}
};
Copy link

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:

  1. Console logging in a library is not recommended
  2. Inconsistent error handling (throwing for apiKey but warnings for others)
  3. 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.

Suggested change
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;
};

Comment on lines +28 to +30
async function ragAiRemoveContext(id:string, namespace: string) {
await ragAi.context.delete({ id: id, namespace: namespace });
}
Copy link

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.

Suggested change
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}`);
}
}

Comment on lines +19 to +26
async function ragAiAddWEBContext(link: string, namespace: string) {
await ragAi.context.add({
type: "html",
source: link,
config: { chunkOverlap: 50, chunkSize: 200 },
options: { namespace: namespace },
});
}
Copy link

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.

Suggested change
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}`);
}
}

Comment on lines +3 to +9
async function ragAiAddPDFContext(filePath: string, namespace: string) {
await ragAi.context.add({
type: "pdf",
fileSource: filePath,
options: { namespace: namespace },
});
}
Copy link

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.

Suggested change
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}`);
}
}

@SkidGod4444 SkidGod4444 removed a link to an issue Dec 7, 2024
@SkidGod4444 SkidGod4444 merged commit 9ebb338 into main Dec 7, 2024
15 checks passed
@SkidGod4444 SkidGod4444 deleted the feat/status-and-agents branch December 7, 2024 07:35
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.

Agents API route with dynamic db and SDK configuration
1 participant