Skip to content

Fix repo images in authed instance case and add manifest json #332

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

Merged
merged 10 commits into from
Jun 6, 2025

Conversation

msukkari
Copy link
Contributor

@msukkari msukkari commented Jun 4, 2025

Summary by CodeRabbit

  • New Features

    • Added support for fetching and proxying repository images, including authentication for self-hosted code hosts.
    • Introduced a web app manifest for improved PWA support.
    • Added a utility to determine direct or proxied image URLs for repositories.
    • New API route for retrieving repository images.
  • Improvements

    • Repository tables and lists now use a more robust mechanism for displaying repository images.
    • Enhanced static file handling and middleware exclusions for manifest and logo assets.
  • Refactor

    • Delegated token retrieval logic to a shared utility, improving maintainability.
    • Updated TypeScript configuration for modern module and language support.
  • Chores

    • Updated dependencies in the crypto package for better integration with database and schema utilities.

@msukkari msukkari requested a review from brendan-kellam June 4, 2025 23:13
Copy link

coderabbitai bot commented Jun 4, 2025

Walkthrough

This update centralizes and refactors token retrieval logic by introducing a new getTokenFromConfig utility in the crypto package, updates the backend to use this function, and enhances error handling. It also adds a proxied repository image fetching mechanism for self-hosted code hosts, implements a PWA manifest, and updates static asset handling.

Changes

File(s) Change Summary
packages/backend/src/utils.ts Refactored getTokenFromConfig to delegate logic to @sourcebot/crypto's getTokenFromConfigBase, simplifying error handling and removing manual secret/token fetching.
packages/crypto/src/tokenUtils.ts, packages/crypto/src/index.ts Added and exported getTokenFromConfig utility for token retrieval from secrets or environment variables, supporting decryption and error handling.
packages/crypto/package.json, packages/crypto/tsconfig.json Added dependencies on @sourcebot/db and @sourcebot/schemas; updated TypeScript target and module settings for modern Node compatibility.
packages/web/src/actions.ts Added getRepoImage action to fetch/proxy repo images, supporting authentication for self-hosted code hosts. Imports updated for new token utility and connection config types.
packages/web/src/app/api/[domain]/repos/[repoId]/image/route.ts Introduced new API route to serve repository images, handling validation and error responses.
packages/web/src/lib/utils.ts Added getRepoImageSrc utility to determine whether to use direct or proxied image URLs based on host.
packages/web/src/app/[domain]/connections/[id]/components/repoListItem.tsx Updated to use getRepoImageSrc for image rendering, ensuring correct image source selection.
packages/web/src/app/[domain]/repos/columns.tsx, packages/web/src/app/[domain]/repos/repositoryTable.tsx Added repoId property to repository info and ensured it is set in all relevant places. Updated image cell to use getRepoImageSrc.
packages/web/public/manifest.json, packages/web/src/app/layout.tsx Added PWA manifest and linked it in the app layout's <head>.
packages/web/src/middleware.ts Updated middleware matcher to exclude new static assets (manifest.json, logo_192.png, logo_512.png).

Sequence Diagram(s)

sequenceDiagram
    participant WebClient
    participant WebAPI
    participant Actions
    participant Crypto
    participant DB

    WebClient->>WebAPI: GET /api/[domain]/repos/[repoId]/image
    WebAPI->>Actions: getRepoImage(repoId, domain)
    Actions->>DB: fetch repo by id/org
    Actions->>Crypto: getTokenFromConfig(token, orgId, db)
    Crypto->>DB: fetch secret (if needed)
    Crypto-->>Actions: token string
    Actions->>ExternalHost: fetch image with Authorization (if self-hosted)
    ExternalHost-->>Actions: image data
    Actions-->>WebAPI: image response
    WebAPI-->>WebClient: image data or redirect
Loading

Possibly related PRs

  • V4 #311: Introduces the new getTokenFromConfig function in the crypto package, which this PR uses to refactor token retrieval in the backend.

Suggested reviewers

  • brendan-kellam

Poem

In the warren, secrets hop,
Tokens now from one true shop.
Images fetched, both near and far,
Self-hosted or public star.
With manifest and icons bright,
Sourcebot’s code leaps into light.
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bd9beca and 555277f.

📒 Files selected for processing (1)
  • packages/web/src/actions.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/web/src/actions.ts
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build
  • GitHub Check: build
✨ 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: 2

🧹 Nitpick comments (6)
packages/web/public/manifest.json (1)

1-14: Consider enhancing the PWA manifest for better user experience.

While the current manifest is functional, consider adding these standard PWA properties for a more complete implementation:

 {
     "name": "Sourcebot",
     "short_name": "Sourcebot",
+    "description": "AI-powered code analysis and review platform",
     "display": "standalone",
     "start_url": "/",
+    "theme_color": "#000000",
+    "background_color": "#ffffff",
+    "orientation": "portrait-primary",
     "icons": [
+      {
+        "src": "/logo_192.png", 
+        "sizes": "192x192",
+        "type": "image/png"
+      },
       {
         "src": "/logo_512.png",
         "sizes": "512x512",
         "type": "image/png"
       }
     ]
   }
packages/web/src/app/api/[domain]/repos/[repoId]/image/route.ts (1)

5-23: Consider adding comprehensive error handling.

The implementation is solid but could benefit from additional error handling:

  1. The direct return of result assumes getRepoImage always returns a proper Response object
  2. No try-catch block to handle unexpected errors from the getRepoImage action
  3. Consider validating that repoIdNum is positive
 export async function GET(
     request: NextRequest,
     { params }: { params: { domain: string; repoId: string } }
 ) {
     const { domain, repoId } = params;
     const repoIdNum = parseInt(repoId);

-    if (isNaN(repoIdNum)) {
+    if (isNaN(repoIdNum) || repoIdNum <= 0) {
         return new Response("Invalid repo ID", { status: 400 });
     }

-    const result = await getRepoImage(repoIdNum, domain);
+    try {
+        const result = await getRepoImage(repoIdNum, domain);

-    if (isServiceError(result)) {
-        return new Response(result.message, { status: result.statusCode });
-    }
+        if (isServiceError(result)) {
+            return new Response(result.message, { status: result.statusCode });
+        }

-    return result;
+        return result;
+    } catch (error) {
+        console.error('Error fetching repo image:', error);
+        return new Response("Internal server error", { status: 500 });
+    }
 }
packages/crypto/src/tokenUtils.ts (1)

5-33: Consider adding defensive error handling.

The function is well-structured but could benefit from additional error handling:

  1. No validation that orgId is positive
  2. Database query errors aren't explicitly handled
  3. The decrypt function could throw errors that aren't caught
 export const getTokenFromConfig = async (token: Token, orgId: number, db: PrismaClient) => {
+    if (orgId <= 0) {
+        throw new Error('Invalid organization ID');
+    }
+
     if ('secret' in token) {
         const secretKey = token.secret;
-        const secret = await db.secret.findUnique({
-            where: {
-                orgId_key: {
-                    key: secretKey,
-                    orgId
+        try {
+            const secret = await db.secret.findUnique({
+                where: {
+                    orgId_key: {
+                        key: secretKey,
+                        orgId
+                    }
                 }
-            }
-        });
+            });
+        } catch (error) {
+            throw new Error(`Failed to query secret: ${error instanceof Error ? error.message : 'Unknown error'}`);
+        }

         if (!secret) {
             throw new Error(`Secret with key ${secretKey} not found for org ${orgId}`);
         }

-        const decryptedToken = decrypt(secret.iv, secret.encryptedValue);
+        try {
+            const decryptedToken = decrypt(secret.iv, secret.encryptedValue);
+        } catch (error) {
+            throw new Error(`Failed to decrypt token: ${error instanceof Error ? error.message : 'Unknown error'}`);
+        }
         return decryptedToken;
packages/web/src/lib/utils.ts (1)

413-440: Improve input validation and edge case handling.

The function logic is sound but could be more robust:

  1. Handle empty string imageUrl case
  2. Consider validating domain parameter
  3. The public hostnames list might need to include more GitLab/Gitea instances
 export const getRepoImageSrc = (imageUrl: string | undefined, repoId: number, domain: string): string | undefined => {
-    if (!imageUrl) return undefined;
+    if (!imageUrl || imageUrl.trim() === '') return undefined;
+    
+    if (!domain || domain.trim() === '') {
+        console.warn('Invalid domain provided to getRepoImageSrc');
+        return imageUrl;
+    }
     
     try {
         const url = new URL(imageUrl);
         
         // List of known public instances that don't require authentication
         const publicHostnames = [
             'github.com',
             'gitlab.com',
             'avatars.githubusercontent.com',
             'gitea.com',
             'bitbucket.org',
+            // Add more common public instances as needed
         ];
         
         const isPublicInstance = publicHostnames.includes(url.hostname);
         
         if (isPublicInstance) {
             return imageUrl;
         } else {
             // Use the proxied route for self-hosted instances
             return `/api/${domain}/repos/${repoId}/image`;
         }
     } catch {
         // If URL parsing fails, use the original URL
+        console.warn('Failed to parse image URL:', imageUrl);
         return imageUrl;
     }
 };

Consider making the public hostnames configurable.

The hardcoded list of public hostnames might need updates over time. Consider making this configurable or moving it to a constants file.

packages/web/src/actions.ts (2)

1756-1783: Consider refactoring the repetitive token retrieval logic.

The token retrieval logic for different connection types follows a similar pattern. Consider extracting this into a helper function to reduce duplication and improve maintainability.

+const getAuthHeadersForConnection = async (connection: any, orgId: number, prisma: PrismaClient): Promise<Record<string, string>> => {
+    const config = connection.config as any;
+    if (!config.token) return {};
+    
+    try {
+        const token = await getTokenFromConfig(config.token, orgId, prisma);
+        
+        switch (connection.connectionType) {
+            case 'github':
+            case 'gitea':
+                return { 'Authorization': `token ${token}` };
+            case 'gitlab':
+                return { 'Authorization': `Bearer ${token}` };
+            default:
+                return {};
+        }
+    } catch (error) {
+        logger.warn(`Failed to get token for connection ${connection.id}:`, error);
+        return {};
+    }
+};

 let authHeaders: Record<string, string> = {};
 for (const { connection } of repo.connections) {
-    try {
-        if (connection.connectionType === 'github') {
-            const config = connection.config as unknown as GithubConnectionConfig;
-            if (config.token) {
-                const token = await getTokenFromConfig(config.token, connection.orgId, prisma);
-                authHeaders['Authorization'] = `token ${token}`;
-                break;
-            }
-        } else if (connection.connectionType === 'gitlab') {
-            const config = connection.config as unknown as GitlabConnectionConfig;
-            if (config.token) {
-                const token = await getTokenFromConfig(config.token, connection.orgId, prisma);
-                authHeaders['Authorization'] = `Bearer ${token}`;
-                break;
-            }
-        } else if (connection.connectionType === 'gitea') {
-            const config = connection.config as unknown as GiteaConnectionConfig;
-            if (config.token) {
-                const token = await getTokenFromConfig(config.token, connection.orgId, prisma);
-                authHeaders['Authorization'] = `token ${token}`;
-                break;
-            }
-        }
-    } catch (error) {
-        logger.warn(`Failed to get token for connection ${connection.id}:`, error);
-    }
+    const headers = await getAuthHeadersForConnection(connection, connection.orgId, prisma);
+    if (Object.keys(headers).length > 0) {
+        authHeaders = headers;
+        break;
+    }
 }

1742-1748: Extract public hostnames to a constant.

Consider moving the public hostnames list to a constant for better maintainability and potential reuse.

+const PUBLIC_CODE_HOST_DOMAINS = [
+    'github.com',
+    'gitlab.com',
+    'avatars.githubusercontent.com',
+    'gitea.com',
+    'bitbucket.org',
+] as const;

 // Only proxy images from self-hosted instances that might require authentication
 const imageUrl = new URL(repo.imageUrl);

-const publicHostnames = [
-    'github.com',
-    'gitlab.com',
-    'avatars.githubusercontent.com',
-    'gitea.com',
-    'bitbucket.org',
-];
-const isPublicInstance = publicHostnames.includes(imageUrl.hostname);
+const isPublicInstance = PUBLIC_CODE_HOST_DOMAINS.includes(imageUrl.hostname);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 258b9cf and 89278fc.

⛔ Files ignored due to path filters (2)
  • packages/web/public/logo_512.png is excluded by !**/*.png
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (14)
  • packages/backend/src/utils.ts (2 hunks)
  • packages/crypto/package.json (1 hunks)
  • packages/crypto/src/index.ts (1 hunks)
  • packages/crypto/src/tokenUtils.ts (1 hunks)
  • packages/crypto/tsconfig.json (2 hunks)
  • packages/web/public/manifest.json (1 hunks)
  • packages/web/src/actions.ts (2 hunks)
  • packages/web/src/app/[domain]/connections/[id]/components/repoListItem.tsx (2 hunks)
  • packages/web/src/app/[domain]/repos/columns.tsx (2 hunks)
  • packages/web/src/app/[domain]/repos/repositoryTable.tsx (2 hunks)
  • packages/web/src/app/api/[domain]/repos/[repoId]/image/route.ts (1 hunks)
  • packages/web/src/app/layout.tsx (1 hunks)
  • packages/web/src/lib/utils.ts (1 hunks)
  • packages/web/src/middleware.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (13)
packages/web/src/middleware.ts (1)

32-32: LGTM! Proper static asset exclusion for PWA files.

The updated matcher correctly excludes the PWA manifest and icon files from middleware processing, ensuring they're served as static assets without interference.

packages/crypto/package.json (1)

11-12: LGTM! Appropriate dependencies for centralized token utilities.

Adding the db and schemas dependencies supports the new centralized token utility functions, improving code organization and maintainability across the monorepo.

packages/crypto/src/index.ts (1)

67-68:

✅ Verification successful

Verify the module path and ensure tokenUtils exists.

The export looks good for centralizing token retrieval logic. However, please confirm that:

  1. The tokenUtils.js file exists (or if this should reference tokenUtils.ts)
  2. The .js extension is correct for Node16 module resolution

🏁 Script executed:

#!/bin/bash
# Description: Verify tokenUtils file exists and the export is correct
# Expected: tokenUtils file should exist and export getTokenFromConfig

# Check if tokenUtils file exists
fd "tokenUtils" packages/crypto/src/

# Verify getTokenFromConfig is exported from tokenUtils
rg -A 5 "export.*getTokenFromConfig" packages/crypto/src/

Length of output: 684


tokenUtils export path and .js extension validated

Confirmed correct file and export; the .js extension aligns with Node16 ES module resolution and matches the compiled output.

packages/crypto/src/tokenUtils.ts exists and exports getTokenFromConfig
• Including .js in the import is required for ESM under Node16

No further changes required.

packages/crypto/tsconfig.json (1)

3-19: LGTM! TypeScript configuration modernization.

The updates to ES2022/ES2023 and Node16 module resolution are appropriate for supporting modern ES modules and align with the new token utilities export using .js extensions.

packages/web/src/app/[domain]/connections/[id]/components/repoListItem.tsx (2)

3-3: LGTM! Centralizing image URL logic.

Good refactoring to centralize repository image URL resolution logic.


56-58: LGTM! Consistent image rendering logic.

The conditional rendering and image source usage are correctly updated to use the centralized imageSrc.

packages/web/src/app/[domain]/repos/repositoryTable.tsx (2)

28-28: LGTM! Adding repoId for image proxying support.

Good addition of repoId to support the new centralized image handling functionality.


39-39:

✅ Verification successful

Verify repoId is always available in repo data.

The mapping looks correct. Please confirm that repo.repoId is always present and properly typed in the repository data structure.


🏁 Script executed:

#!/bin/bash
# Description: Verify repoId is properly defined in repository types
# Expected: repoId should be a required field in repository interfaces

# Check repository type definitions
rg -A 10 -B 5 "interface.*[Rr]epo" packages/web/src/
rg -A 10 -B 5 "type.*[Rr]epo" packages/web/src/

# Verify repoId field in database schemas
rg "repoId" packages/db/src/

Length of output: 14732


🏁 Script executed:

#!/bin/bash
# Verify that repoId is required in the repositoryQuerySchema
rg -A20 -B5 "repositoryQuerySchema" packages/web/src/lib/types.ts

Length of output: 753


🏁 Script executed:

#!/bin/bash
# Show the definition of repositoryQuerySchema and verify repoId field
rg -C5 "repositoryQuerySchema" packages/web/src/lib

Length of output: 1521


🏁 Script executed:

#!/bin/bash
# Locate repositoryTable.tsx and display its prop types and mapping context
file=$(rg -l "repositoryTable.tsx" packages/web/src)
echo "Found file: $file"
sed -n '1,200p' "$file"

Length of output: 151


🏁 Script executed:

#!/bin/bash
# Locate all repos directories under src/app and list their contents
find packages/web/src/app -type d -name repos | while read dir; do
  echo "==> Directory: $dir"
  ls -1 "$dir"
done

Length of output: 674


Confirmed: repoId is always present and correctly typed
repoId is defined as a required number in the Zod repositoryQuerySchema (packages/web/src/lib/schemas.ts) and flows through to every component prop type:

  • RetryRepoIndexButtonProps (repoId: number)
  • RepoListItemProps (repoId: number)
  • RepositoryColumnInfo (repoId: number)

No further changes needed.

packages/web/src/app/[domain]/repos/columns.tsx (3)

9-9: LGTM!

The import is correctly added for the new utility function.


15-15: LGTM!

The type extension correctly adds the required repoId field for the new image source utility.


116-116: LGTM!

The image source correctly uses the new utility function to handle both public and self-hosted repository images with appropriate fallback.

packages/backend/src/utils.ts (1)

5-5: Good refactoring to centralize token retrieval logic.

The delegation to getTokenFromConfigBase from the crypto package is a clean architectural improvement that promotes code reuse while maintaining backend-specific error handling.

Also applies to: 27-41

packages/web/src/actions.ts (1)

1718-1810: Well-implemented image proxy with proper authentication handling.

The implementation correctly handles both public and private repository images, includes appropriate error handling, sets proper cache headers, and respects security boundaries. The guest access allowance is appropriate for image viewing.

brendan-kellam
brendan-kellam previously approved these changes Jun 4, 2025
@msukkari msukkari merged commit 8dc41a2 into main Jun 6, 2025
5 of 6 checks passed
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.

2 participants