Skip to content

Conversation

@divyaswormakai
Copy link
Contributor

@divyaswormakai divyaswormakai commented Dec 7, 2024

What kind of change does this PR introduce?

Fixes #470
Fixes app crashing when invalid bluesky credentials are provided.

Why was this change needed?

Added try catch block for the code on frontend and backend to stop applications from crashing.

Other information:

Checklist:

Put a "X" in the boxes below to indicate you have followed the checklist;

  • I have read the CONTRIBUTING guide.
  • I checked that there were not similar issues or PRs already open for this.
  • This PR fixes just ONE issue (do not include multiple issues or types of change in the same PR) For example, don't try and fix a UI issue and include new dependencies in the same PR.

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced error handling for social integration processes, improving user feedback during failures.
    • Added optional placeholder text for input fields in the CustomVariables component, enhancing user experience.
    • Introduced comprehensive functions for validating and normalizing domain handles, ensuring compliance with specified standards.
  • Bug Fixes

    • Improved validation for the identifier field in the BlueskyProvider, ensuring correct formatting.

@vercel
Copy link

vercel bot commented Dec 7, 2024

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

Name Status Preview Comments Updated (UTC)
gitroom ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 11, 2024 5:54am
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
postiz ⬜️ Ignored (Inspect) Visit Preview Dec 11, 2024 5:54am

@vercel
Copy link

vercel bot commented Dec 7, 2024

@divyaswormakai is attempting to deploy a commit to the Listinai Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link

coderabbitai bot commented Dec 7, 2024

Walkthrough

The changes in this pull request enhance error handling and user experience across several components. In the page.tsx file, a try-catch block is added to manage errors during the social integration process, improving feedback for invalid credentials. The add.provider.component.tsx file introduces a new placeholder property to improve input handling in the CustomVariables component. The bluesky.provider.ts file updates the authenticate method to include error handling, ensuring that incorrect credentials do not crash the backend process.

Changes

File Path Change Summary
apps/frontend/src/app/(site)/integrations/social/[provider]/continue/page.tsx Added try-catch block for error handling, improved response handling for social integration, and added fallback UI for invalid responses.
apps/frontend/src/components/launches/add.provider.component.tsx Introduced placeholder prop in CustomVariables for input fields and updated getSocialLink to utilize this new property for better user input experience.
libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts Updated authenticate method for error handling, refined customFields validation regex, and made minor adjustments to type declarations.
libraries/helpers/src/integrations/bluesky.provider.ts Added functions for validating and normalizing domain handles, enhancing error handling and ensuring compliance with domain name standards.

Assessment against linked issues

Objective Addressed Explanation
Ensure incorrect Bluesky credentials do not crash the backend process.
Improve error handling during authentication in BlueskyProvider.
Provide user feedback for invalid credentials in the UI.

Possibly related PRs

  • feat: autofill name based on username or let it be random string #474: The changes in this PR involve error handling related to the connectSocialMedia method, which is conceptually similar to the enhanced error handling introduced in the Page function of the main PR. Both PRs focus on improving user feedback and handling errors more gracefully during social integration processes.

Poem

🐰 In the meadow where bunnies play,
New changes hop in, brightening the day.
With placeholders here and errors caught,
Our integration's smoother, just as we thought!
So let's leap forward, with joy and cheer,
For a better experience, we hold so dear! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d6b790a and 0f816ae.

📒 Files selected for processing (1)
  • libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts

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 generate docstrings to generate docstrings for this PR. (Experiment)
  • @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: 0

🧹 Outside diff range and nitpick comments (3)
apps/frontend/src/app/(site)/integrations/social/[provider]/continue/page.tsx (1)

34-37: Consider enhancing error message handling.

The error message is directly used in the URL without encoding, which could cause issues with special characters.

-      return redirect(`/launches?msg=${msg}`);
+      return redirect(`/launches?msg=${encodeURIComponent(msg)}`);
libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts (2)

72-110: Consider enhancing error response structure.

While the error handling is good, the empty response structure might not provide enough context to the frontend about what went wrong.

Consider adding an error field to the response:

       return {
         refreshToken: '',
         expiresIn: 0,
         accessToken: '',
         id: '',
         name: '',
         picture: '',
         username: '',
+        error: error.message || 'Authentication failed'
       };

198-200: Simplify URL construction.

The current implementation of splitting and popping could be simplified.

-      releaseURL: `https://bsky.app/profile/${id}/post/${cidUrl[index].url
-        .split('/')
-        .pop()}`,
+      releaseURL: `https://bsky.app/profile/${id}/post/${cidUrl[index].url.split('/').at(-1)}`,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b263299 and b4b130d.

📒 Files selected for processing (3)
  • apps/frontend/src/app/(site)/integrations/social/[provider]/continue/page.tsx (1 hunks)
  • apps/frontend/src/components/launches/add.provider.component.tsx (3 hunks)
  • libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts (5 hunks)
🔇 Additional comments (3)
apps/frontend/src/app/(site)/integrations/social/[provider]/continue/page.tsx (1)

79-92: LGTM! Comprehensive error handling implementation.

The try-catch block with fallback UI effectively prevents application crashes and provides a good user experience.

libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts (1)

33-34: LGTM! Improved input validation and user guidance.

The placeholder and validation regex improvements help users understand the expected format.

apps/frontend/src/components/launches/add.provider.component.tsx (1)

193-193: LGTM! Enhanced form input experience.

The addition of placeholder support improves user guidance across the component hierarchy.

Also applies to: 275-275, 319-319

Copy link
Contributor

@jamesread jamesread left a comment

Choose a reason for hiding this comment

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

Hey @divyaswormakai , thanks so much indeed for taking the time to do this, good idea, and generally good PR. I left a couple of comments for you to address, hope that's OK!

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 (5)
libraries/helpers/src/integrations/bluesky.provider.ts (5)

1-21: LGTM! Consider improving comment formatting.

The documentation is comprehensive and well-attributed. Consider converting this into JSDoc format for better IDE integration.

-// Handle constraints, in English:
-//  - must be a possible domain name
+/**
+ * Handle constraints, in English:
+ * - must be a possible domain name
+ * ...
+ */

22-54: Consider using custom error types for better error handling.

The implementation is thorough but could be improved by using custom error types to allow consumers to handle specific validation failures differently.

+export class HandleValidationError extends Error {
+  constructor(message: string) {
+    super(message);
+    this.name = 'HandleValidationError';
+  }
+}

 export const ensureValidHandle = (handle: string): void => {
   if (!/^[a-zA-Z0-9.-]*$/.test(handle)) {
-    throw new Error(
+    throw new HandleValidationError(
       'Disallowed characters in handle (ASCII letters, digits, dashes, periods only)'
     );
   }
   // ... similar changes for other error throws

56-68: Improve regex maintainability with documentation and named constants.

The regex pattern is complex and could be hard to maintain. Consider breaking it down into named constants and adding documentation.

+const HANDLE_SEGMENT = '[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?';
+const TLD_SEGMENT = '[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?';
+/**
+ * Validates handle format using regex:
+ * - Segments must start and end with alphanumeric
+ * - Middle can contain hyphens
+ * - TLD must start with a letter
+ */
 export const ensureValidHandleRegex = (handle: string): void => {
   if (
-    !/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/.test(
+    !new RegExp(`^(${HANDLE_SEGMENT}\\.)+${TLD_SEGMENT}$`).test(
       handle
     )
   ) {

74-78: Consider wrapping validation errors with context.

The function could provide more context when validation fails by including the original handle in the error message.

 export const normalizeAndEnsureValidHandle = (handle: string): string => {
   const normalized = normalizeHandle(handle);
-  ensureValidHandle(normalized);
+  try {
+    ensureValidHandle(normalized);
+  } catch (err) {
+    throw new Error(`Invalid handle "${handle}": ${err.message}`);
+  }
   return normalized;
 };

1-92: Implementation aligns well with PR objectives.

The handle validation implementation provides a robust foundation for preventing crashes from invalid Bluesky credentials. The multiple validation approaches (detailed and regex-based) offer flexibility while maintaining strict validation rules.

Consider the following architectural improvements:

  1. Add rate limiting to prevent DoS attacks through expensive regex operations
  2. Consider caching validated handles to improve performance
  3. Add metrics/monitoring for validation failures to track potential abuse
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b4b130d and f326bf0.

📒 Files selected for processing (3)
  • apps/frontend/src/app/(site)/integrations/social/[provider]/continue/page.tsx (2 hunks)
  • libraries/helpers/src/integrations/bluesky.provider.ts (1 hunks)
  • libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/frontend/src/app/(site)/integrations/social/[provider]/continue/page.tsx
  • libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts
🔇 Additional comments (1)
libraries/helpers/src/integrations/bluesky.provider.ts (1)

70-72: LGTM!

Simple and correct implementation of case normalization.

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)
libraries/helpers/src/integrations/bluesky.provider.ts (2)

1-21: Add JSDoc documentation for exported functions.

While the handle constraints are well documented, adding JSDoc comments with examples would improve the API documentation.

Add JSDoc comments like this:

+/**
+ * Validates a Bluesky handle against domain name constraints.
+ * @param handle - The handle to validate
+ * @throws {Error} If the handle is invalid
+ * @example
+ * // Valid handles
+ * ensureValidHandle('alice.bsky.social')
+ * ensureValidHandle('bob-123.test.com')
+ * 
+ * // Invalid handles
+ * ensureValidHandle('alice') // Throws: Handle domain needs at least two parts
+ * ensureValidHandle('-alice.com') // Throws: Handle parts can not start or end with hyphens
+ */
 export const ensureValidHandle = (handle: string): void => {

22-54: Extract magic numbers into named constants.

The function implementation is robust, but readability could be improved by extracting magic numbers into named constants.

Consider this refactoring:

+const HANDLE_CONSTRAINTS = {
+  MAX_TOTAL_LENGTH: 253,
+  MAX_LABEL_LENGTH: 63,
+  MIN_LABELS: 2,
+  VALID_CHARS_PATTERN: /^[a-zA-Z0-9.-]*$/,
+  TLD_START_PATTERN: /^[a-zA-Z]/
+} as const;
+
 export const ensureValidHandle = (handle: string): void => {
+  if (handle == null) {
+    throw new Error('Handle cannot be null or undefined');
+  }
+
   // check that all chars are boring ASCII
-  if (!/^[a-zA-Z0-9.-]*$/.test(handle)) {
+  if (!HANDLE_CONSTRAINTS.VALID_CHARS_PATTERN.test(handle)) {
     throw new Error(
       'Disallowed characters in handle (ASCII letters, digits, dashes, periods only)'
     );
   }

-  if (handle.length > 253) {
+  if (handle.length > HANDLE_CONSTRAINTS.MAX_TOTAL_LENGTH) {
     throw new Error('Handle is too long (253 chars max)');
   }
   const labels = handle.split('.');
-  if (labels.length < 2) {
+  if (labels.length < HANDLE_CONSTRAINTS.MIN_LABELS) {
     throw new Error('Handle domain needs at least two parts');
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f326bf0 and d6b790a.

📒 Files selected for processing (1)
  • libraries/helpers/src/integrations/bluesky.provider.ts (1 hunks)
🔇 Additional comments (3)
libraries/helpers/src/integrations/bluesky.provider.ts (3)

70-72: LGTM!

The function correctly implements case normalization as specified in the handle constraints.


74-78: LGTM!

The function follows a good pattern of normalizing before validation and correctly returns the normalized handle.


80-88: Improve error handling and logging.

The current implementation uses console.log which isn't suitable for production code.

As suggested in the previous review, consider using the NestJS Logger:

+import { Logger } from '@nestjs/common';
+
 export const isValidHandle = (handle: string): boolean => {
+  const logger = new Logger('BlueskyProvider');
   try {
     ensureValidHandle(handle);
     return true;
   } catch (err) {
-    console.log('Error in bluesky handle validation:', err);
+    logger.debug(`Handle validation failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
     return false;
   }
 };

@divyaswormakai
Copy link
Contributor Author

@jamesread updated the code likewise :)

@nevo-david
Copy link
Contributor

Thank you so much for this PR, but I feel it's a bit over-coded, I pushed a very simplistic implementation for this.

@nevo-david nevo-david closed this Dec 12, 2024
@divyaswormakai divyaswormakai deleted the fix-bluesky-crash branch December 12, 2024 18:00
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.

Adding Incorrect Bluesky credentials crashes front end node process.

3 participants