Skip to content

Conversation

@vershwal
Copy link
Member

Ref https://linear.app/ghost/issue/PROD-1736

@coderabbitai
Copy link

coderabbitai bot commented May 13, 2025

Warning

Rate limit exceeded

@vershwal has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 0 minutes and 16 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between a1b0a56 and dcd6bb3.

📒 Files selected for processing (1)
  • src/lookup-helpers.ts (1 hunks)
## Walkthrough

A new asynchronous function, `lookupActorProfile`, was introduced in `src/lookup-helpers.ts` to perform a WebFinger lookup for a given handle and return the actor's profile URL as a `URL` object or `null`. The function normalizes the input handle, constructs a WebFinger resource string, and queries `lookupWebFinger`. It prioritizes returning a profile-page link, falling back to an ActivityPub self link if necessary, with appropriate logging and error handling. Corresponding unit tests were added in `src/lookup-helpers.unit.test.ts` to cover various scenarios, including successful lookups, missing links, and error cases.

## Possibly related PRs

- TryGhost/ActivityPub#520: Implements a custom WebFinger HTTP handler on the server side, which relates to this PR's client-side WebFinger lookup functionality, both addressing WebFinger protocol processing.

## Suggested reviewers

- mike182uk
✨ Finishing Touches
  • 📝 Generate Docstrings

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

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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: 0

🧹 Nitpick comments (2)
src/lookup-helpers.ts (1)

110-162: Nicely implemented WebFinger lookup for actor profiles

The function follows a logical workflow with proper error handling and fallback mechanisms. It first tries to find the profile-page link and falls back to the ActivityPub self link if needed.

A few suggestions for improvement:

Consider extracting the common WebFinger lookup logic from both lookupAPIdByHandle and lookupActorProfile to reduce code duplication. Both functions share similar handle normalization, WebFinger lookup, and error handling patterns.

+async function performWebFingerLookup(ctx, handle, options = {}) {
+    try {
+        // Remove leading @ if present
+        const cleanHandle = handle.startsWith('@') ? handle.slice(1) : handle;
+        const resource = `acct:${cleanHandle}`;
+
+        const webfingerData = await lookupWebFinger(resource, {
+            allowPrivateAddress:
+                process.env.ALLOW_PRIVATE_ADDRESS === 'true' &&
+                ['development', 'testing'].includes(process.env.NODE_ENV || ''),
+            ...options
+        });
+
+        if (!webfingerData?.links) {
+            ctx.data.logger.info(`No links found in WebFinger response for handle ${handle}`);
+            return null;
+        }
+
+        return { webfingerData, cleanHandle };
+    } catch (err) {
+        ctx.data.logger.error(`Error looking up WebFinger for handle ${handle} - ${err}`);
+        return null;
+    }
+}

Consider using the same string formatting approach consistently throughout the file. Other functions use the format 'Message with {placeholder}' with { placeholder: value } as the second argument, while this function uses template literals:

-            `No links found in WebFinger response for handle ${handle}`,
+            'No links found in WebFinger response for handle {handle}',
+            { handle },
src/lookup-helpers.unit.test.ts (1)

132-281: Comprehensive test suite for the new function

The test suite for lookupActorProfile is thorough and covers all critical scenarios:

  • Returning profile page URL when available
  • Falling back to self link when profile page is not available
  • Handling handles with leading '@'
  • Properly handling error cases and logging

Consider adding a test case for when the WebFinger response contains links but they're empty (vs. the response having no links property at all):

+    it('should return null when WebFinger response has empty links array', async () => {
+        const mockWebFingerResponse = {
+            links: []
+        };
+
+        (
+            lookupWebFinger as unknown as ReturnType<typeof vi.fn>
+        ).mockResolvedValue(mockWebFingerResponse);
+
+        const result = await lookupActorProfile(
+            mockCtx as unknown as Context<ContextData>,
+            'user@example.com',
+        );
+
+        expect(result).toBeNull();
+        expect(mockCtx.data.logger.info).toHaveBeenCalledWith(
+            'No ActivityPub profile found in WebFinger response for handle user@example.com',
+        );
+    });

This would validate behavior when the WebFinger response includes an empty links array, which is a distinct case from having no links property at all.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d6878e4 and cf2828a.

📒 Files selected for processing (2)
  • src/lookup-helpers.ts (1 hunks)
  • src/lookup-helpers.unit.test.ts (6 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/lookup-helpers.ts (1)
src/app.ts (1)
  • ContextData (186-190)
src/lookup-helpers.unit.test.ts (2)
src/app.ts (1)
  • ContextData (186-190)
src/lookup-helpers.ts (1)
  • lookupActorProfile (110-162)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build, Test and Push
🔇 Additional comments (2)
src/lookup-helpers.unit.test.ts (2)

1-4: Updated imports look good

The imports correctly include the new dependencies and the lookupActorProfile function.


40-40: Type casting updates ensure proper typing

Good updates to ensure consistent typing with Context<ContextData> across all test cases.

Also applies to: 60-60, 83-83, 96-96, 124-124

return null;
}

return new URL(selfLink.href);
Copy link
Contributor

Choose a reason for hiding this comment

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

selfLink.href should be an URL according to spec, but maybe safer to put that in a try/catch block, as we're fetching external data?

Copy link
Member Author

Choose a reason for hiding this comment

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

Thanks @sagzy

  • Added fall back to self link if profile link href is not a valid URL.
  • If self link is not valid then it will be handled by the main try/catch.
  • Added tests for both cases.

Commit here.

@vershwal vershwal merged commit beaef4b into main May 13, 2025
7 checks passed
@vershwal vershwal deleted the weblookup branch May 13, 2025 05:29
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.

3 participants